text
stringlengths
10
2.61M
class CaptionsController < ApplicationController before_action :authenticate_user! # board_pin_captions GET /boards/:board_id/pins/:pin_id/captions(.:format) captions#index # POST /boards/:board_id/pins/:pin_id/captions(.:format) captions#create # new_board_pin_caption GE...
require 'javaclass/classfile/attributes/attributes' module JavaClass module ClassFile # Container of the fields - skips the fields for now. # Author:: Peter Kofler class Fields # :nodoc: # Size of the whole fields structure in bytes. attr_reader :size # Parse the field ...
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'pcp-client/version' Gem::Specification.new do |s| s.name = 'pcp-client' s.version = PCPClient::VERSION s.licenses = ['ASL 2.0'] s.summary = "Client library for PCP" s.description = "S...
require_relative "oystercard" class Journey PENALTY_FARE = 6 NORMAL_FARE = 1 attr_reader :entry_station def initialize(entry_station:) @entry_station = entry_station @completed_journey = false end def complete? if @completed_journey == true return true else return false end...
#To delete module Api::V1 class UsersController < Api::V1::BaseController private def user_params params.require(:user).permit(:name, :lastname, :email, :address, :phone, :authentication_token, :district) end def query_params params.permit(:name, :lastname, :email, :district_id, :token) ...
class Api::V1::LinksController < Api::ApiController respond_to :json def index user = current_user respond_with user.links.order('id') end def show user = User.find(params[:id]) respond_with user.links.find(params[:link][:id]) end def create user = current_user link = user.links.c...
module NetAppSdk class NFS < Filer def self.on nfs_on = @@filer.invoke("nfs-enable") raise nfs_on.results_reason \ if nfs_on.results_status == 'failed' return true end def self.off nfs_off = @@filer.invoke("nfs-disable") raise nfs_off.results_reason \ ...
ENV["RAILS_ENV"] ||= 'test' require 'simplecov' SimpleCov.start 'rails' require 'rubygems' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'thinking_sphinx/test' require 'database_cleaner' require 'webmock/rspec' require 'capybara/rspec' Dir[Rails....
module Tournament def self.begin *fighters puts "A tournament amoung #{fighters}".yellow round = 1 while fighters.count > 1 puts "ROUND #{round}".yellow pairs = fighters.each_slice(2).to_a pairs.each do |fighter_a, fighter_b| next if fighter_b.nil? winning_fighter = Match...
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) @item.image = fixture_file_upload('public/images/test_image.png') end describe '商品出品登録' do it 'すべての値が正しく入力されていれば、登録できる' do expect(@item).to be_valid end it '画像がない場合、登録できない' do @i...
class CreateRecipeIngredientsUnits < ActiveRecord::Migration def change create_table :recipe_ingredients_units do |t| t.string :ingredient_unit_name t.timestamps null: false end end end
class RemoveColumnsFromChurches < ActiveRecord::Migration def change remove_column :churches, :incumbent_name remove_column :churches, :incumbent_age add_column :people, :age, :integer add_column :people, :age_approx, :boolean end end
class Triangle # write code here attr_accessor :side_a, :side_b, :side_c def initialize(s_a, s_b, s_c) @side_a = s_a @side_b = s_b @side_c = s_c end def kind if (@side_a <= 0) || (@side_b <= 0) || (@side_c <= 0) raise TriangleError elsif (@side_a + @side_b <= @side_c) || (@side_a +...
# Copyright:: Copyright (c) 2014 eGlobalTech, Inc., all rights reserved # # Licensed under the BSD-3 license (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the root of the project or at # # http://egt-labs.com/mu/LICENSE.html # # Unless ...
require_relative '../models/book' require_relative '../views/books_view' require_relative '../controllers/users_controller' require 'erb' class BooksController class << self attr_accessor :isbn, :option def find BooksView.ask_for_isbn book = Book.find_by_isbn @isbn BooksView.display_book(b...
# frozen_string_literal: true ActiveAdmin.register Category do menu parent: 'Configuration' permit_params :name end
class TextMessage < ApplicationRecord belongs_to :account belongs_to :user, optional: true belongs_to :to_contact, class_name: "Contact", foreign_key: "to_contact_id" belongs_to :from_contact, class_name: "Contact", foreign_key: "from_contact_id" scope :within_this_month, -> { where(created_at: DateTime.now....
require 'spec_helper' describe 'LayoutLinks' do it 'should have the right title' do visit root_path page.should have_title('Splash') end it 'should have a root link' do visit root_path page.should have_link('TF Home', root_path) end describe 'when not signed in' do it 'should have an A...
require 'spec_helper' describe User do let(:admin){Factory(:admin)} describe 'Validations' do context 'User is valid' do it 'with all the attributes' do admin.should be_valid end end context 'User is invalid' do it 'without a password' do pending end it ...
# frozen_string_literal: true require 'evss/base_service' module EVSS class CommonService < BaseService API_VERSION = Settings.evss.versions.common BASE_URL = "#{Settings.evss.url}/wss-common-services-web-#{API_VERSION}/rest/" def create_user_account post 'persistentPropertiesService/11.0/createU...
class AsylumController < ApplicationController def index @villains = Villain.all @cart = current_cart end end
require 'diffy' require 'term/ansicolor' module Cli class Stackscript < Thor include Formattable include Term::ANSIColor include Api::Utils desc "ls", "List stackscripts (from Linode)" option :raw, type: :boolean, default: false def ls puts Api::Stackscript.list(format) end de...
module Disable extend ActiveSupport::Concern included do scope :disabled, -> { where.not(disabled_at: nil) } scope :enabled, -> { where(disabled_at: nil).order(updated_at: :desc) } belongs_to :owner, class_name: 'User', foreign_key: 'created_user_id', optional: true belongs_to :modifier, class_nam...
class HomeController < ApplicationController before_filter :set_locale def set_locale I18n.locale=params[:locale] end def index @festivals = Festival.all @artists = Artist.all end end
require 'nokogiri' class MetadataController < ApplicationController def new @doi = params[:doi] end def create endpoint = ENV['ENDPOINT'] + '/metadata' username = ENV['USERNAME'] password = ENV['PASSWORD'] pem = File.read(ENV['PEM']) @xml = build_xml @doi = params[:doi] response...
class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(params[:contact]) if @contact.save flash[:notice] = 'Contact was successfully created!' respond_to do |format| format.html { redirect_to :action => 'index...
class ApplicationController < ActionController::Base protect_from_forgery before_filter :check_uri def check_uri redirect_to request.protocol + request.host_with_port[4..-1] + request.request_uri if /^www/.match(request.host) end end
class Api::V1::ForecastsController < ApplicationController def index render json: ForecastSerializer.new(ForecastFacade.new(params[:location])) # converts forecastfacade to json end end
class Picture < ActiveRecord::Base belongs_to :user mount_uploader :image, ImageUploader validates :title, presence: true validates :content, presence: true validates :image, presence: true end
# Count the number of subsets of {1, 2, ..., n} with reciprical sum strictly # less than 1. # A305442 require_relative '../helpers/subset_logic' require_relative "../helpers/sums_and_differences" def a(n) (1..n).to_a.count_subsets do |subset| subset.map { |i| 1.to_r/i }.reduce(0, :+) < 1 end end p (0..15).map...
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'test_helper' require 'polynomial' require 'rational' if RUBY_VERSION < '1.9' class TestPolynomial < Test::Unit::TestCase def setup @p = Polynomial.new([1,2,3]) @h = Polynomial.new({0 => 1, 1 => 2, 2 => 3}) end def test_initialization assert_equal(...
module Bundler module Whatsup # Iterator for set of Change objects class Changes nil end end end
class RemoveCommentFromPicks < ActiveRecord::Migration def change remove_column :picks, :comment, :text remove_column :picks, :name, :text end end
names = ["Henrietta", "Bubba", "Touralou", nil, "Feliks"] names.each do |name| begin puts "#{name} has #{name.length} letters. Did ya know?" rescue puts puts "Oh my God! Ohmygod! OH MY GOD!!!!" puts "Something awfully dejected just happened." puts "This is SO terrible. Call daddy." puts e...
require 'spec_helper' require 'rails_helper' describe Card do before do @card = Card.new end describe "number" do it "should be invalid" do ["", " ", "1", "829612982", "1234567A"].each do |number| @card.number = number expect(@card).not_to be_valid end end it "shoul...
class PeopleController < ApplicationController def index # Access cached data or save it for the first time fetch_people # Without caching we would normally do this: # @people = People.all end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] before_action :logged_in? def index @students = User.where(course_name: session[:course_name]) && User.where(role: "student") @assignments = Assignment.all if session[:user_role] == "admin" ...
class RemoveDeliveryStatusI18nFromBuyInfomations < ActiveRecord::Migration[5.2] def change remove_column :buy_infomations, :delivery_status_i18n, :integer end end
class ChangeUserAndLesson < ActiveRecord::Migration[5.0] def change add_reference :subscribeds, :lesson add_reference :subscribeds, :user end end
# frozen_string_literal: true require 'weese/bus/stop' require 'weese/bus/route' module Weese # MetroBus related structures. Most important: {MetroBus} module Bus # MetroBus client. Used for accessing MetroBus-related WMATA APIs. class MetroBus include Requests::Requester include Bus::Requires...
class CreateTransactions < ActiveRecord::Migration def change create_table :transactions do |t| t.integer :student_id t.string :message t.integer :loggable_id t.string :loggable_type t.timestamps end add_index(:transactions, :student_id) add_index(:transactions, :loggable_id)...
class Tag < ActiveRecord::Base has_many :taggings, :dependent => :destroy def to_param name end def to_s name end end
require 'rails_helper' RSpec.feature 'Account Update', type: :feature do given!(:user) { create(:user) } background do Capybara.current_driver = :selenium_chrome_headless sign_in_with_factory user end scenario 'normal update' do email_before = user.email account_update('afterupload', '', 'new...
module PositionHelper def position_kinds Position.kinds.keys.map { |c| [position_kind(c), c] } end def position_kind(k) t("model.position.kinds.#{k}") end end
describe App do describe '#run' do context 'when dealer wins' do context 'and player busts' do let(:cards) do [ Card.new(:spade, 'K'), Card.new(:diamond, 'J'), Card.new(:diamond, '3'), Card.new(:diamond, '4'), Card.new(:heart, 'Q'...
require 'spec_helper' describe 'elasticsearch', :type => 'class' do let :params do { :config => { 'node' => { 'name' => 'test' } } } end context "On Debian OS" do let :facts do { :operatingsystem => 'Debian' } end # init.pp it { should contain_class('elasticsearch::package') } ...
class User < ActiveRecord::Base has_many :project validates_uniqueness_of :name end
#encoding:utf-8 require 'spec_helper' describe ApplicationHelper do describe 'render_close_icon' do subject { helper.render_close_icon } it { should have_selector('a.close') } end describe 'flash_class' do subject { helper.flash_class(flash_key) } context 'when flash key is :notice' do le...
class RemoveRecipientFromQuotationComment < ActiveRecord::Migration[5.0] def change remove_column :quotation_comments, :recipient_id end end
class Stream < ActiveRecord::Base has_many :posts, :conditions => 'is_deleted IS FALSE', :order => 'published_at DESC' has_many :articles, :include => [:service], :conditions => "is_deleted IS FALSE AND is_draft IS FALSE AND services.identifier = 'articles'", :order => 'published_at DESC', :clas...
module Motion class LaunchImages def self.screenshot_path NSBundle.mainBundle.objectForInfoDictionaryKey('screenshot_path') end def self.taking? screenshot_path != nil end def self.take!(orientation = :portrait) return unless taking? Dispatch::Queue.main.async do ...
require File.expand_path(File.join(File.dirname(__FILE__), 'meta')) module WebInspector class Inspector def initialize(page) @page = page @meta = WebInspector::Meta.new(page).meta end def title @page.css('title').inner_text.strip rescue nil end def description @meta['de...
module ApplicationHelper def human_readable_box_type package_type box_type_hum = {"JAR"=>'Jar', "DB" => 'Dress Box', "SLB" => 'Slide Lid Box', "SBN" => 'Semi Boîte Nature', "CB" => 'Cardboard Pack', "BLBN" => 'Black Lacquered Boîte Nature', "VBN" => 'Varnished Boîte Nature', "VSBN" => 'Varnished Semi Boîte Nat...
# frozen_string_literal: true require "securerandom" require "pathname" module Haikunate require "haikunate/version" class << self attr_accessor :default_range, :default_variant end self.default_range = 1000..9999 self.default_variant = -> { rand(default_range) } def self.data_dir @data_dir ||=...
require 'scooter' include Scooter::LDAP # Should never get here unless an "openldap" host is specified in the # beaker host/config file def ldap_dispatcher # Scooter doesn't support custom settings yet. #@ldap_dispatcher ||= LDAPDispatcher.new(openldap, { :encryption => nil, :port => 389, # ...
FactoryGirl.define do factory :event do name "Test Event Name" description "Test Event Description" date_time DateTime.new(2018, 11, 10, 9, 8) image File.new("#{Rails.root}/app/assets/images/seed_assets/events_images/event_image.jpg") address [street_address: "1234 Test Street", city: "Test City",...
# "size" in this case refers to "2T", "5T", etc. class AddSizeToCanonicalItem < ActiveRecord::Migration[5.2] def change add_column :canonical_items, :size, :string end end
# frozen_string_literal: true # == Schema Information # # Table name: memberships # # id :integer not null, primary key # account_id :integer # user_id :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_memberships_on_account_id (ac...
class Alpaga < Formula desc "Alpaga FTW!" homepage "https://github.com/tonyo/alpaga/" url "https://github.com/tonyo/alpaga/releases/download/0.1.1/alpaga.sh" version "0.1.1" sha256 "ca1c183f75890baab9a0289c996c9e0d322bf2887dd8e6d5a6782f2c92267783" def install bin.install "alpaga.sh" end test do ...
class ArticleSerializer < ActiveModel::Serializer attributes :id, :title, :author, :description, :section, :image_url, :url, :publication_date has_many :clippings has_many :collections, through: :clippings end
require 'fwiki' require 'rack/test' require 'base64' configure do DataMapper::Logger.new(STDOUT, :debug) DataMapper.setup :default, 'sqlite3::memory:' end describe Page do it 'should create a body when contents are specified' do p = Page.new(:name => 'foo', :contents => 'bar') p.contents.should == 'bar'...
class MediaBrowse class NoUser; end attr_reader :user def initialize(options) @user = options.fetch(:user, NoUser) || NoUser end def items MediaRepository.visible_for(user) end end
# Incorporate logic to send some messages from the admin web interface class MessageSender def component_message(component, provider, provider_account) if provider == 'facebook' user_id = provider_account.user.id if component.component_type == 'crawler' facebook_id = provider_account.facebook_...
module Crawler module Db class WebPageResult < Sequel::Model(connection[:web_page_results]) SPACE_MATCHER = Regexp.compile('\s+') # @param [String] url # @return [Boolean] def self.crawled?(url) !!send(:[], url) end # @param [Crawler::Http::Response] response # ...
require 'rails_helper' RSpec.describe Price, type: :model do before do @price = FactoryBot.build(:price) end describe 'シュミレーション情報の登録' do context '登録がうまくいくとき' do it '正しく情報を入力すれば登録できる' do expect(@price).to be_valid end end context '登録がうまくいくいかないとき' do it '運営業態を選択していないと登録できな...
require 'bulutfon_sdk/rest/base_request' module BulutfonSDK module REST class OutgoingFax < BaseRequest include BulutfonSDK::Util def initialize(*args) super(*args) @resource = 'outgoing-faxes' end def all( params = {} ) prepare_request( 'get', @resource, params...
# Given this data structure write some code to return an array containing the colors of the fruits and the sizes of the vegetables. The sizes should be uppercase and the colors should be capitalized. hsh = { 'grape' => {type: 'fruit', colors: ['red', 'green'], size: 'small'}, 'carrot' => {type: 'vegetable', colors...
# frozen_string_literal: true module GraphQL module StaticValidation module InputObjectNamesAreUnique def on_input_object(node, parent) validate_input_fields(node) super end private def validate_input_fields(node) input_field_defns = node.arguments input_f...
class TasksController < ApplicationController before_action :authenticate_user! before_action :set_task, only: [:show, :edit, :update, :destroy] before_action :is_own_task?, only: [:edit, :update, :destroy] before_action :is_project_member?, only: [:show] def index @project = :all @tasks = current_us...
class AddLightningDataTable < ActiveRecord::Migration def change create_table :lightningdata do |t| t.integer :user_id t.integer :lightning_id t.timestamps end end end
class AddResolutionrtoIssues < ActiveRecord::Migration def change add_column :issues, :resolution, :text end end
class CreateCards < ActiveRecord::Migration def change create_table :cards do |t| t.text :japanese t.text :reading t.text :meaning t.timestamps end end end
#def oxford_comma(array) # array = [] # if array.size == 1 # return array[0] # elsif array.size == 2 # return array.join(" and ") # else #return array[0..-2].join(", ") + ", and " + array[-1] #end #end def oxford_comma(array) case array.length when 1 "#{array[0]}" when 2 array[0..1].join(" ...
require_relative 'album_details_section' require_relative 'album_player_section' require './app/helpers/tweets_helper' class TweetReviewSection < SitePrism::Section include TweetsHelper element :user_name, '.user-name' element :twitter_user_name, '.twitter-username a' element :reviewed_on, '.reviewed-on' el...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class StaticPagesController < ApplicationController def index if user_signed_in? if current_user.profile #have prof, go to newsfeed redirect_to tweets_path else #no prof, create one flash[:success] = "Create a profile below" redirect_to new_profile_path end end end end
require 'rcleaner' def cd(cwd) old_cwd = Dir.getwd Dir.chdir cwd begin yield if block_given? ensure Dir.chdir old_cwd end end
class FavoriteClass < ActiveRecord::Base belongs_to :dance_class belongs_to :user validates :dance_class_id, :user_id, :presence => true end
class AccessTokensController < ApplicationController def create authenticator = UserAuthenticator.new(params[:code]) authenticator.perform end end
# encoding: utf-8 require "logstash/codecs/base" # # Log.io Codec Plugin for Logstash (http://logstash.net) # Author: Luke Chavers <github.com/vmadman> # Created: 11/22/2013 # Current Logstash: 1.2.2 # # To the extent possible under law, Luke Chavers has waived all copyright and related # or neighboring rights to this...
class Shelter < ActiveRecord::Base has_many :pets has_many :shelter_users has_many :users, through: :shelter_users validates :name, uniqueness: true end
FactoryBot.define do factory :type do name 'Angel' end end
FactoryGirl.define do factory :user do name "Thomas A. Anderson" email "thomas.a.anderson@metacortex.com" password "ilovetrinity" end factory :board do title "Project: Exit Matrix" description "Follow the white rabbit" user_id 1 end factory :list do title "Done" board_id 1 ...
# == Schema Information # # Table name: projects # # id :integer not null, primary key # name :string(255) # email :string(255) # key :string(255) # hub_id :integer # created_at :datetime not null # updated_at :datetime not null # logo :string(255) # mi...
class AddUserToStudents < ActiveRecord::Migration[5.2] def change add_reference :students, :user_id, index: true, foreign_key: { to_table: :users } end end
class ReviewsController < ApplicationController def new @review = Review.new # @booking = Booking.find(params[:booking_id]) # authorize@review end def create @review = Review.new(review_params) @booking = Booking.find(params[:booking_id]) @user = booking.user @review.booking = @bookin...
module PolicyfileDeliveryTruck module Helpers module_function # Returns the filename relative to the repo root def repo_path(node, filename) File.join(node['delivery']['workspace']['repo'], filename) end # Return whether there is a policyfile present in the repo def repo_has_policyfile...
# encoding: utf-8 require "logstash/inputs/base" require "logstash/namespace" require "stud/interval" require "koala" # Generate a repeating message. # # This plugin is intented only as an example. class LogStash::Inputs::Facebook < LogStash::Inputs::Base config_name "facebook" # If undefined, Logstash will comp...
require 'forwardable' require 'skype/api' require 'skype/chat' require 'skype/chatmessage' require 'skype/events' module Skype class << self extend Forwardable def_delegator Skype::Api, :instance, :instance def_delegator Skype::Api, :attach def_delegator Skype::Chat, :new, :chat def_del...
class CreateBillentries < ActiveRecord::Migration[5.0] def change create_table :billentries do |t| t.string :truck_no t.string :company_name t.string :address t.datetime :time_arrive t.datetime :time_departure t.date :current_date t.decimal :supply_rate t.decimal :w...
# -*- encoding : utf-8 -*- require 'rails_helper' describe 'people module' do it 'is forbidden to view index without authentication' do people.navigate_to_index expect: :forbidden end it 'is forbidden to view index without an associated church' do home.login :user people.navigate_to_index expect: ...
require 'set' input = File.read("/Users/hhh/JungleGym/advent_of_code/2020/inputs/day09.in").split("\n").map { |x| x.to_i } def sum_in? n, window set = Set.new(window) set.any? do |x| complement = n-x set.include? complement end end def part1 input x, y = 0, 25 window = input[x,y] queue = input[y...
require "json" class WatsonService include IBMWatson def initialize(text) @text = text end def analyse authenticator = Authenticators::IamAuthenticator.new( apikey: ENV["WATSON_API_KEY"] ) natural_language_understanding = NaturalLanguageUnderstandingV1.new( version: "2021-03-25", ...
module Util module StringHelper def pluralize(word) if word.to_s.end_with?("s") word else word << "s" end word end end end
class Expense < ActiveRecord::Base belongs_to :category belongs_to :purse validates_presence_of :amount, :date, :category, :purse def self.search_query(params) expenses = Expense.arel_table categories = Category.arel_table q = expenses .project('expenses.*', cate...
class AddLocationNameToRestaurants < ActiveRecord::Migration def change add_column :restaurants, :location_name, :string end end
class Model < ApplicationRecord include Ownable include Fieldable include Categorizable include Documentable multisearchable( against: [:name, :model_number], additional_attributes: ->(record) { { label: record.name } }, ) pg_search_scope( :search, against: [:name, :model_number], associ...
module SubmissionsHelper def fields_for_item(item, &block) prefix = item.new_record? ? 'new' : 'existing' fields_for("submission[#{prefix}_item_attributes][]", item, &block) end def add_item_link(name) link_to_function name do |page| page.insert_html :bottom, :items, :partial => 'item', :obje...
require 'spec_helper' describe 'Service Options', reset: false do downloadable_collection_id = 'C90762182-LAADS' downloadable_collection_title = 'MODIS/Aqua Calibrated Radiances 5-Min L1B Swath 250m V005' collection_with_intermittent_timeline_id = 'C179003030-ORNL_DAAC' before :all do load_page :search, ...
class SharedIdentityCookie def self.public_key @public_key ||= begin uri = ServiceDescriptor.discover(:kernel, "SharedIdentityCookieRsaPublicKey") response = Datapathy.adapters[:ssbe].http.resource(uri).get(:accept => 'application/x-pem-file') resp...