text stringlengths 10 2.61M |
|---|
class Game < ActiveRecord::Base
belongs_to :home_team, class_name: 'Team'
belongs_to :away_team, class_name: 'Team'
belongs_to :venue
attr_accessible :ends_at, :starts_at, :home_team_id, :away_team_id, :venue_id
validates :venue, presence: true
has_event_calendar :start_at_field => 'starts_at', :end_at_f... |
module SessionsHelper
$id
def sign_in(user)
remember_token = User.new_remember_token # create a new token
# .permanent - set the expiration to 20.years.from_now
cookies.permanent[:remember_token] = remember_token # place the raw token in the browser cookies
user.update_attribute(:remember_token,... |
# Encoding: UTF-8
require File.expand_path('lib/refinery/caststone/version', __dir__)
version = Refinery::Caststone::Version
rails_version = '>=6.1.7'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'refinerycms-caststone'
s.version = version
s.description = 'Ruby on Rails Caststone ext... |
# Write a method that takes a String as an argument, and returns a new String that contains the original value using a staggered capitalization scheme in which every other character is capitalized, and the remaining characters are lowercase. Characters that are not letters should not be changed, but count as characters... |
class Admins::PhotographiesController < ApplicationController
before_filter :authenticate_admin!
layout "admins"
def index
@photographies = Photography.all
respond_to do |format|
format.html
end
end
def new
@photography = Photography.new
@photography.photos.build
respond_to do |format|
form... |
# Color クラスのソースファイル
# Author:: maki-tetsu
# Date:: 2011/03/11
# Copyright:: Copyright (c) 2011 maki-tetsu
module PREP # nodoc
module Core # nodoc
class Color
attr_reader :red, :green, :blue
def initialize(red, green, blue)
self.red = red
self.green = green
self.blue = blue
... |
require "spec_helper"
RSpec.describe "Day 5: Binary Boarding" do
let(:runner) { Runner.new("2020/05") }
describe "Part One" do
it "calculates proper Seat IDs" do
expect(runner.execute!("FBFBBFFRLR", part: 1)).to eq(357)
expect(runner.execute!("BFFFBBFRRR", part: 1)).to eq(567)
expect(runner.... |
class Admin::LocationsController < Admin::AdminController
before_action :set_location, only: [:edit, :update]
before_action :set_districts, except: [:index]
def index
@locations = Location.includes(:district).paginate(:page => page_number, :per_page => 25)
end
def new
@location = Location.new
end
... |
#!/usr/bin/env ruby
require 'spec_helper'
describe 'scarlett linux user pi' do
it 'creates pi user with following properties' do
expect(user('pi')).to exist
expect(user('pi')).to have_uid(1000)
expect(user('pi')).to have_home_directory('/home/pi')
expect(user('pi')).to have_login_shell('/bin/bash')
... |
require File.dirname(__FILE__) + '/../spec_helper.rb'
describe "JiakSchema" do
before do
@allowed_fields = [:foo,:bar,:baz]
@required_fields = [:foo]
@read_mask = [:foo,:bar]
@write_mask = [:baz]
@hash = {
:allowed_fields => @allowed_fields,
:required_fields => @required_fields,
... |
require 'rails_helper'
RSpec.describe Member, type: :model do
let(:house) { create(:house) }
subject(:member) { create(:member, house_id: house.id) }
let(:task) { create(:task, member_id: member.id, house_id: house.id) }
it 'has a valid factory' do
expect(member).to be_valid
end
context 'associations... |
Rails.application.routes.draw do
get 'welcome/home'
get 'pages/summary'
get 'pages/installation'
get 'pages/tutorial'
get 'pages/demo'
get 'pages/conclusion'
get 'pages/credits'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'welcome#home'
end
|
require 'rails_helper'
describe :Routing, type: :routing do
subject { route }
describe 'POST /treasure_hunt' do
let(:route) { { post: 'treasure_hunt' } }
it { is_expected.to route_to('check_ins#create') }
end
describe 'others' do
let(:route) { { get: 'other_route' } }
it { is_expected.to rout... |
# -*- encoding : utf-8 -*-
require 'test_helper'
class ApprobationDissertationsControllerTest < ActionController::TestCase
setup do
@approbation_dissertation = approbation_dissertations(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:ap... |
ENV['APP_ENV'] = 'test'
require './counter'
require 'rspec'
require 'rack/test'
RSpec.describe 'The Counter App' do
include Rack::Test::Methods
after(:all) { User.destroy_all}
let(:user_params) { generate_user_params }
def app
Counter
end
it "registers a user" do
post '/register', user_params
... |
BRIDGE_NET="192.168.1."
INTERNAL_NET="192.168.15."
DOMAIN="test.net"
servers=[
{
:hostname => "minio-host1." + DOMAIN,
:ip => BRIDGE_NET + "154",
:ip_int => INTERNAL_NET + "2",
:ram => 512,
:hdd_name => "hdd.vdi",
:hdd_size => "10000"
},
{
:hostname => "minio-host2." + DOM... |
class Region < ActiveRecord::Base
acts_as_nested_set
has_one :status, as: :stateable, dependent: :destroy
delegate :state, to: :status, allow_nil: true
def categories(industry)
Category.joins(:industries, :regions)
end
end
|
module Roglew
module WGL
UNIQUE_ID_NV ||= 0x20CE
NUM_VIDEO_CAPTURE_SLOTS_NV ||= 0x20CF
end
end
module WGL_NV_video_capture
module RenderHandle
include Roglew::RenderHandleExtension
functions [
[:wglBindVideoCaptureDeviceNV, [ :uint, :pointer ], :bool ],
[:wglEnumerateVi... |
class ClothsInventories < ActiveRecord::Base
attr_accessible :amount
belongs_to :inventory
belongs_to :cloth
end
|
FactoryBot.define do
factory :user do
name 'pj'
password 'password'
email 'pj@email.com'
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
require 'workflow/business_calendar'
include Workflow
describe BusinessCalendar do
context "calculate_expiration: hours" do
it "allows well-formed durations: hours" do
# %w(0h 6h 24h 999h).each do |duration|
%w(24h 48h).each do ... |
module UnreadIssues
module UserPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
has_many :issue_reads, dependent: :delete_all
has_many :assigned_issues, class_name: 'Issue' , foreign_key: 'assigned_to_id'
end
end
module InstanceMetho... |
describe "Rool::Iterate" do
before :each do
@data = {
foo: [2, 3, 4, 5, 6, 7, 10],
fizz: ['Yes', 'We', 'Keneng'],
cool_number: 262,
bar: [10, 10, 10, 10, 10]
}
end
describe '#process' do
it 'will be an instance of Rool::All' do
@iterate_test = Rool::Iterate.new(:foo, ... |
class Assessment < ApplicationRecord
belongs_to :user
belongs_to :act
validates_presence_of :user_id, :act_id, :posee_gravamen, :tipo_gravamen, :genera_gravamen, :tipo_genera_gravamen, :fecha_constitucion, :fecha_cancelacion
end
|
class Subdomain
HOME_IP = ENV.fetch('HOME_IP', '1.1.1.1').freeze
def self.matches?(request)
return 'depilate' if Rails.env.development?
name = request.subdomain
name = request.domain || HOME_IP if name.blank? || name == 'www'
name = name.gsub(/^www\./, '').split('.').first
case name
when 'o... |
class PlayerCardRanker
attr_reader :position, :style, :game_version
def initialize(player_cards: , position: , style:)
@player_cards = player_cards
@position = position
@style = style
end
# TODO: support per-position tie-breakers
def sorted_collection
@player_cards.sort_by(&:score... |
require File.join(File.dirname(__FILE__), "../helper")
# with_steps_for :rsd do
# run File.expand_path(__FILE__).gsub(".rb",""), :type => Merb::Test::RspecStory
# end
Story "Providing RSD (http://en.wikipedia.org/wiki/Really_Simple_Discovery)", %{
As a RSD-enabled client
I want to be able to know about the avai... |
class Locations::EditSerializer < ApplicationSerializer
object_as :location
identifier :slug
attributes(
:id,
:slug,
:name,
:parent_id,
:currency,
)
belongs_to :parent, serializer: Locations::OptionsSerializer
end
|
# A frequent practice is to place the standard CRUD actions in each
# controller in the following order: index, show, new, edit, create, update
# and destroy.
class FeaturesController < ApplicationController
def index
@features = Feature.all
end
def show
@feature = Feature.find(params[:id])
end
def... |
# -*- coding: utf-8 -*-
class Similarity
class << self
def similarity(lhs, rhs)
max = [lhs.size, rhs.size].max
max > 0 ? 1.0 - levenshtein_distance(lhs, rhs).to_f / max : 1.0
end
def levenshtein_distance(lhs, rhs)
width = lhs.size + 1
height = rhs.size + 1
d = Array.new(w... |
# frozen_string_literal: true
module Decidim
module Opinions
# Contains the meta data of the document, like title and description.
#
class ParticipatoryText < Opinions::ApplicationRecord
include Decidim::HasComponent
include Decidim::Traceable
include Decidim::Loggable
end
end
end... |
class Server < ActiveRecord::Base
include Searchable
belongs_to :company
has_many :server_users, dependent: :destroy
validates :name,
presence: true
validates :ip_address,
presence: true,
uniqueness: true
validates :company,
presence: true
delegate :name, to: :company, prefix: true
en... |
################################################################################
#
# Author: Zachary Patten <zachary@jovelabs.com>
# Copyright: Copyright (c) 2012-2013 Jove Labs
# License: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
########################################################
# Defines the main methods that are necessary to read input
########################################################
class PluginReadInputBb < Plugin
#Returns an array with the errors due to parameters are missing
def check_params
#Priority, base ram
co... |
# frozen_string_literal: true
class CollaboratorsFinder
ERROR_MESSAGE = "Is not valid"
attr_reader :collaborator, :collab_info
def initialize(collaborator, collab_info)
@collaborator = collaborator
@collab_info = collab_info
end
def self.call!(collaborator:, collab_info:)
new(collaborator, col... |
class CountryFlag
def self.all
[
{title: "Portugal", code: "portugal"},
{title: "Republic of the Congo", code: "republicofthe_congo"},
{title: "Aruba", code: "aruba"},
{title: "Macedonia", code: "macedonia"},
{title: "Gibraltar", code: "gibraltar"},
{title: "Croatia... |
require 'rails_helper'
RSpec.describe 'Friendships', type: :request do
before(:all) do
post '/tokens'
data = JSON.parse(response.body)
@token = data['token']
@id = data['id']
@user = create(:user, username: 'Javier 6', email: 'jav6@gmail.com')
@receiver = create(:user, username: 'Ana 6', emai... |
module Roglew
module WGL
TYPE_RGBA_FLOAT_ATI ||= 0x21A0
end
module GL
RGBA_FLOAT_MODE_ATI ||= 0x8820
COLOR_CLEAR_UNCLAMPED_VALUE_ATI ||= 0x8835
end
end |
# app/models/organisation.rb
class Organisation < ApplicationRecord
has_many :users, foreign_key: :organisation_id
has_many :scenarios, through: :users
# validations
validates_presence_of :name
def admins
users.admins
end
def unapproved_users
users.unapproved
end
end
|
class InfosController < ApplicationController
PER = 30
def index
#isPublic(公開)にチェックが入っている、公開日以降、のレコードのみ表示
@infos = Info.where('isPublic = ? and infoDate <= ?', true, Date.today).page(params[:page]).per(PER)
end
def show
set_info
#isPublicがtrueでない、または公開日以前のお知らせの場合(アドレスバーに直接入力された場合)、ホーム画面を... |
module ConceptsHelper
def select_from_statuses
defaults = ["Clarification Needed", "Pending Approval", "In Progress","Completed"]
select_tag('concept[status]', options_for_select(defaults))
end
def select_from_verticals
defaults = ["Homes", "Food", "4Car","Programmes","Blogs","E4","X-Platform","... |
require 'fileutils'
require 'colorize'
class Func
attr_accessor :classname, :state
@state = 0
def Func.incr_state
@state =+ 1
end
def Func.get_state
return @state
end
def Func.set_classname=(name)
@classname = name
end
def Func.get_classname()
... |
#
# Class Question < Thing
#
require 'thing'
class Question < Thing
# => Retourne un lien de type "new", donc pour ajouter une nouvelle question
#
# @param data Hash qui doit contenir au minimum :
# :ce_parent Le nom du parent, humain, précédé de "ce"
# ... |
require 'mechanize'
require 'highline/import'
require 'nokogiri'
require 'terminal-table'
require 'colorize'
class Caltime
TIMESTAMP_URL = "https://caltimeprod.berkeley.edu/wfc/applications/wtk/html/ess/timestamp-record.jsp"
BASE_URL = "https://caltimeprod.berkeley.edu/"
SSO_URL = "https://caltimeprod.berkeley.... |
=begin
-Prompt the user for all the infomation
-convert any user input to the appropriate date type
-print hash back out to the screen
-give user a chance to update infomation
=end
system "clear"
client_info = {}
#Client's info
puts "***************"
puts "Client's' Info"
puts "***************"
puts "Client's name:... |
require 'lib/eventable'
require 'lib/action_chooser'
class Player
include Eventable
include ActionChooser
attr_reader :warrior
def play_turn(warrior)
@warrior ||= warrior
trigger :turn_start
warrior.public_send *best_action
trigger :turn_finish
end
end
|
# Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'walrat'
module Walrat
# A SymbolParslet allows for evaluation of a parslet to be deferred until
# runtime (or parse time, to be more precise).
class SymbolParslet < Parslet
attr_reader :... |
RSpec.describe Xencoder do
it { expect(described_class.new('01')).to be_a Xencoder::Encoder }
it { expect(described_class.new('0123456789abcdef', length: 4, seed: 200)).to be_a Xencoder::Encoder }
context 'default encoder' do
subject(:encoder) { described_class.encoder }
it { expect(subject.seed).to eq 1... |
class FilterPhotos
attr_reader :title, :photos, :filter
def initialize(params = nil)
@params = params || Hash.new
end
def call
@title, @photos, @filter = [
by_contestant,
by_tag,
by_category,
by_popularity,
by_default
].find { |el| el }
self
end
private
de... |
# frozen_string_literal: true
module Boring
module Ci
module Travisci
class InstallGenerator < Rails::Generators::Base
desc "Adds Github Action to the application"
source_root File.expand_path("templates", __dir__)
DEFAULT_RUBY_VERSION = "2.7.1"
class_option :ruby_version,... |
module SessionHelper
def current_user
@current_user ||= OpenStruct.new(session[:current_user]) if session[:current_user]
end
def signed_in?
current_user.present?
end
def refresh_token(credentials)
oauth_strategy = OmniAuth::Strategies::MicrosoftGraph.new(
nil, ENV['AZURE_APP_ID'], ENV['AZU... |
require_relative '../product/order'
require_relative '../infra/topic'
require_relative '../infra/pub_sub'
require_relative './invoice.rb'
class Customer
attr_accessor :first_name, :vouchers, :payment_method
def initialize(first_name)
@vouchers = Array.new
@first_name = first_name
end
def set_payment_... |
class AddKindRefToBookmark < ActiveRecord::Migration[6.1]
def change
add_reference :bookmarks, :kind, foreign_key: true
end
end
|
class Student < ActiveRecord::Base
validates :No, :presence => true, :uniqueness => true
belongs_to :classbj
has_many :events
after_create do |s|
self.classbj.num += 1
self.classbj.save
end
def score
self.events.all.sum { |x| x.regulation.score }
end
def week_score
self.events.where("... |
class AddKitsuIdToAnime < ActiveRecord::Migration[6.0]
def change
add_column :animes, :kitsu_id, :integer
add_column :animes, :episode_count, :integer
add_column :animes, :episode_length, :integer
add_column :animes, :alternative_titles, :text, array: true, default: []
change_column :animes, :aire... |
require 'rails_helper'
describe SlackServices::GroupMessagesImporter do
describe '#import' do
let(:group) { Group.create(external_id: 'G06JV4K5L', name: 'Some group') }
it 'imports Slack Group messages' do
VCR.use_cassette 'groups/messages' do
expect { described_class.new(group).import }
... |
#user 和 role 变为多对多。使用次方法得到所有agent_role中的权限集合
def user_role_permissions # 错误的写法,如果有多个权限,后面的权限会覆盖前面的相同key的权限的值,使得最后的值不正确
roles = self.agent_roles
return {} unless agent_roles
h = roles.each.inject({}) do |sum, agent_role|
sum.merge!(agent_role.permission).merge!(agent_role.permissions)
end
end
def user_role_... |
require 'test/unit'
require 'match_mixins'
# purpose:
# exercise Ruby's native regex support
#
# hopefully one day I will be able to
# overload Ruby's regex routines with
# my own, and make all these tests pass OK.
#
# todo:
# rubicon/language/regexp.test contains also many
# interesting patterns.
class TestRubyRegex ... |
feature "maintenance mode" do
include EnvVarSpecHelper
context "showing maintenance page" do
scenario "on home page" do
with_env_var("MAINTENANCE_MODE", "true") do
visit root_path
expect(page).to have_content("This site is currently down")
end
end
scenario "on internal page... |
require 'spec_helper'
powershell = 'powershell.exe -ExecutionPolicy RemoteSigned'
describe 'iis::manage_virtual_application', :type => :define do
describe 'when I create a virtual application in IIS' do
let(:title) { 'reviews' }
let(:params) {{
:site_name => 'myWebSite',
:site_path => 'C:\in... |
class RecordBatchAssignment < ActiveRecord::Base
belongs_to :batch
belongs_to :record_group
belongs_to :record_assignment
has_many :student_records,:primary_key=>'batch_id',:foreign_key=>"batch_id"
end
|
class A263135Builder
# . | | o o .
# . | o o | o o o o .
# . o o | o o o | o o o o .
# . o o | o o o | o o o o .
# . o o | o o | o o o o .
# . | | o o o o .
# . | ... |
{
:ssh => {
:keys => ["id_rsa_acceptance", "#{ENV['HOME']}/.ssh/id_rsa-acceptance"],
},
:helper => [
'setup/helpers/classification_helper.rb',
'setup/helpers/ldap_helper.rb',
'setup/helpers/gatling_config_helper.rb',
],
:xml ... |
class Backstage::StorefrontRouter
def initialize(storefront)
@storefront = storefront
end
def matches?(request)
(request.params[:storefront] || request.subdomain) == @storefront.to_s
end
end
|
class NoticeMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.notice_mailer.sendmail_insta.subject
#
def sendmail_insta
@photo = photo
mail to: "to@example.org"
subject:'投稿されました'
end
end
|
#!/usr/bin/env ruby
# encoding: utf-8
# Inline
rep :link do |data|
%{<a href="#{data[:target]}">#{data[:title]}</a>}
end
rep :anchor do |data|
%{<a id="#{data[:id]}">#{data[:title]}</a>}
end
rep :fmi do |data|
%{<span class="fmi">for more information on #{data[:topic]}, see #{data[:link]}</span>}
end
rep :draft... |
class DailyLogController < ApplicationController
layout :choose_layout
def choose_layout
if current_user.nutrition_only
"nutrition"
else
"application"
end
end
def index
@gym = current_user.gym
@daily_logs = current_user.daily_logs.order(created_at: :desc)
@today_log = curre... |
class CreateShows < ActiveRecord::Migration
def self.up
create_table :shows do |t|
t.datetime :scheduled_for
t.string :venue_name
t.string :venue_address_1
t.string :venue_address_2
t.string :venue_city
t.string :venue_state
t.string :venue_postal_code
t.float :pric... |
# 08.13.2020
# Now that we know about hashes, we will refactor your original
# account generator code to utilize arrays with hashes.
# Since each student has three pieces of data, we will utilize
# a hash to store these three pieces of data, related to one another.
# This is a better solution because this will keep ea... |
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe "/city_global_locations/edit.html.erb" do
include CityGlobalLocationsHelper
before(:each) do
assigns[:city_global_location] = @city_global_location = stub_model(CityGlobalLocation,
:new_record? => false,
:country =>... |
class BookContributor < ActiveRecord::Base
belongs_to :book
belongs_to :book_role
belongs_to :contributor
scope :authors, -> { where(book_role: BookRole.author) }
validates :book_id, presence: true
validates :book_role_id, presence: true
validates :contributor_id, presence: true
end
|
class CreateCharacters < ActiveRecord::Migration[5.0]
def change
create_table :characters do |t|
t.string :name
t.references :house, foreign_key: true
t.text :description
t.text :biography
t.string :personality
t.string :titles
t.string :status
t.string :death
... |
class CreateArtistInformations < ActiveRecord::Migration[5.2]
def change
create_table :artist_informations do |t|
t.integer :artist_id
t.boolean :books_open
t.timestamps
end
end
end
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Milestoner::Errors::DuplicateTag do
it_behaves_like "a base error" do
let(:error) { described_class.new }
end
end
|
#Copyright 2010 Foradian Technologies Private Limited
#This product includes software developed at
#Project Fedena - http://www.projectfedena.org/
#
#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... |
class Api::CommentsController < ApplicationController
def create
@comment = Comment.new params.require(:comment).permit(:post_id, :author, :content)
if @comment.save
@post = @comment.post
render "api/posts/show", status: 201
else
render @comment.errors, status: 422
end
end
d... |
class Notifier < ActionMailer::Base
default from: "admin@gatewaygamer.com"
def send_new_event_notification(event)
@event = event
mail(
:to => "admin@gatewaygamer.com",
:subject => 'New Event Created'
)
end
def send_contact(email, subject, contents)
mail(
:to => "admin@gatewaygamer.com",
:sub... |
class AddAmountToAlbumDiscountCodes < ActiveRecord::Migration
def self.up
add_column :album_discount_codes, :amount, :integer, :default=>5, :null=>false
end
def self.down
end
end
|
class CreateSpreeCategory < ActiveRecord::Migration
def change
create_table "spree_categories" do |t|
t.string "name", null: false
t.string "permalink", null: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
... |
class AddRoundNumberToRounds < ActiveRecord::Migration[5.1]
def change
add_column :rounds, :round_number, :integer, null: false
end
end
|
class XmlSidebar < Sidebar
display_name _("XML Syndication")
description "RSS and Atom feeds"
setting :articles, true, :input_type => :checkbox
setting :comments, true, :input_type => :checkbox
setting :trackbacks, false, :input_type => :checkbox
setting :format, 'atom10', :input_type => :radio,
... |
class ChangeTimeToBeTimeInRuns < ActiveRecord::Migration
def change
change_column :runs, :time, :time
end
end
|
# frozen_string_literal: true
When /^I visit the (?:root|home) page$/ do
visit('/')
end
Then /^I should see "([^"]*)"$/ do |text|
expect(page).to have_content(text)
end
|
require 'spec_helper'
describe User do
before :each do
@user = User.create :name => "Fabs"
@friend = User.create name: "Joao"
@user.friends << @friend
@user.save
@friend.save
end
it 'should have friends' do
@user.friends.should == [@friend]
end
it 'should save friends' do
fa... |
require 'spec_helper'
RSpec.describe Paperclip::Watermark do
let(:image_file_jpeg) do
fixture_file_upload(Rails.root.join('../fixtures/images/sample_image.jpg'), 'image/jpeg', :binary)
end
let(:image_file_gif) do
fixture_file_upload(Rails.root.join('../fixtures/images/sample_gif_image.gif'), 'image/gif',... |
# encoding: utf-8
ActiveAdmin::Dashboards.build do
section "Iesniegumu informācija:", :priority => 5 do
h2 "Kopā iesniegti #{Submission.all.count} rēķinu pieteikumi"
h3 "No tiem apstrādāti ir #{Submission.processed.count} un savu kārtu gaida #{Submission.unprocessed.count}."
end
section "Adrešu informāc... |
class Bot
attr_accessor :x, :y
def initialize(r, c)
@x = r
@y = c
end
def coords
[@x, @y]
end
end
class Grid
attr_reader :size, :grid
def initialize(size, grid)
raise ArgumentError, "Please enter an integer less than 100" unless size < 100
@size = size
@grid = grid
end
de... |
module QamehaBackupsHandler
class << self
#####################################################################################################
# MAIN FEATURES
#####################################################################################################
def backup_for_user(user, docfiles=nil... |
class Goalevent < ApplicationRecord
belongs_to :goal
belongs_to :player
belongs_to :eventtype
end
|
require_relative '../configurations/list_configuration'
class UseWeakCryptoAlgorithmsRule < Rule
@name = "Use of weak crypto algorithm"
@poor_crypto = /^(sha1|md5)/
@poor_crypto_conf = RegexConfiguration.new("Regular expression of weak Crypto Algorithms", @poor_crypto, "Regular expression for names of known we... |
class ChangeTypeToFeedback < ActiveRecord::Migration[5.0]
def change
rename_column :feedbacks, :type, :feedback_type
end
end
|
module KTorrent
class Manager
attr_accessor :torrents
def load_torrent_from_file(path)
return nil unless File.readable?(path)
contents = File.open(path, 'rb') { |file| file.read }
metadata = ::KTorrent::BEncoding.decode(contents)
::KTorrent::Torrent.new(manager: self, metadata: metad... |
# frozen_string_literal: true
class Post < ApplicationRecord
include Friendlyable
include Postable
self.primary_key = 'hash_id'
has_many :saved_posts
has_many :voters, through: :saved_posts, source: :voters
scope :texts, -> { where(type: 'Text') }
scope :links, -> { where(type: 'Link') }
end
|
# Problem 252: Convex Holes
# http://projecteuler.net/problem=252
#
# Given a set of points on a plane, we define a convex hole to be a convex polygon having as vertices any of the given points and not containing any of the given points in its interior (in addition to the vertices, other given points may lie on the p... |
class SchoolsController < ApplicationController
def index
@schools = School.pluck :name
respond_to do |format|
format.json { render json: @schools }
end
end
end
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "should create user" do
user = User.new
user.email = "create@example.com"
user.password = "c0ntr0!!3r"
user.name = "Create User"
user.address_1 = "1234 Douglas St"
user.address_2 = "line 2"
user.apt_number = "409"
us... |
class Board < ApplicationRecord
def setup
index = 0
9.times do
self[index] = index
index += 1
end
end
def spaces_array #array of spaces
spaces_array = []
index = 0
9.times do
spaces_array << self[index]
index += 1
end
return spaces_array
end
def avail... |
class AddShortUrlToCampaigns < ActiveRecord::Migration
def change
add_column :campaigns, :short_url, :text
end
end
|
# frozen_string_literal: true
module Rogare
class << self
extend Memoist
@@boot = Time.now
def boot
@@boot
end
@@threads = []
def spinoff(_thing, &block)
@@threads << Thread.new(&block)
end
def spinall!
require 'thwait'
ThreadsWait.all_waits(*@@threads)
... |
require "net/http"
class Downloader
DEFAULT_USER_AGENT = "Devtest v1.0"
def initialize(url)
@url = url
end
def body
response.body
end
private
attr_reader :url, :response
def response
@response ||= download
end
def download
uri = URI(url)
request = Net::HTTP::Get.new(uri)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.