text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe "movie_suggestions/show", type: :view do before(:each) do @movie_suggestion = assign(:movie_suggestion, MovieSuggestion.create!( :user => nil, :name => "Name", :details => "Details", :status => false, :is_deleted => false )) end it "ren...
class Comment < ActiveRecord::Base belongs_to :project belongs_to :user attr_accessible :comment, :lock_version validates :comment, presence: true end
class EmosController < ApplicationController before_action :set_emo, only: [:show, :edit, :update, :destroy] # GET /emos # GET /emos.json def index @emos = Emo.all @emo = Emo.new end # GET /emos/1 # GET /emos/1.json def show @mecab = Natto::MeCab.new("-Ochasen") end # GET /emos/new ...
class AepluginsController < ApplicationController before_action :only_admin before_action :set_aeplugin, only: [:edit, :update, :delete_aeplugin] layout "account" def new @aeplugin = Aeplugin.new @aeplugins = Aeplugin.all.order('created_at desc') end def create @aeplugin = Aeplugin.new(para...
require "./lib/Lesson 12 Euclidean Algorithm/CommonPrimeDivisors/common_prime_divisors" describe 'CommonPrimeDivisors' do describe 'Example Tests' do it 'Example: ([15,10,3], [75,30,5]) to 1' do expect(common_prime_divisors([15,10,3], [75,30,5])).to eq 1 end end describe 'Correctness Tests' do ...
# == Schema Information # # Table name: auctions # # id :bigint not null, primary key # auction_ends :datetime # auction_open_status :boolean # image_path :string # item_description :string # item_name :string # start_price :decimal(, ) # win_price...
class InputError < StandardError attr_accessor :error_message def initialize(message) self.error_message = message end end
# Cookbook Name:: oracle-instantclient # Provider:: AlienConvert # Author:: David Kinzer <dtkinzer@gmail.com> # # Copyright (C) 2014 David Kinzer # # 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 ...
require 'rack' module NexmoHelpers # NEXMO CREATE MESSAGE ------------------------------------------------------- def stub_nexmo_create_message(request_body, response_body) stub_request(:post, 'https://rest.nexmo.com/sms/json') .with(body: request_body) .to_return( status: 200, bo...
module BrewSparkling module Handler class Base class << self def command(*names) names.each do |name| ::BrewSparkling::Handler.register name, self end end end attr_reader :args def initialize(args) @args = args end end en...
feature "Bid Newspaper - Create" do context 'Visitor' do scenario "Access invalid" do visit new_bid_newspaper_path expect(current_path).to eq new_session_path end end context 'Admin' do let(:user) { create :user} background do login user...
#!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' $:.unshift(File.dirname(__FILE__)) require 'TestSetup' require 'RandomThings' class PgLineSegmentTest < Test include SqlPostgres include RandomThings def test_ctor_defaults assertEquals(PgLineSegment.new, PgLineSegment.new(PgPoint.new, PgPoi...
class GamesController < ApplicationController def new @game = Game.new end def show @game = Game.find(params[:id]) end def create g = Game.create #g.world.graph redirect_to game_path(g) return false end def game @game = Game.find(params[:id]) @game_player = @game.curre...
require 'rubygems' require 'nokogiri' #pour le scraping require 'open-uri' #sert à ouvrir le http, mais la gem est contenue dans nokogiri donc à ne pas installer require 'csv' #pour enregistrement csv class ScrapEsiee puts "attention scrapping Esiee, go go go!" # méthode qui lance le programme def initialize # on ...
fish_arr = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] def sluggish_octopus(arr) longest_fish = "" arr.each_index do |i1| arr.each_index do |i2| if arr[i1].length > arr[i2].length && arr[i1].length > longest_fish.length longest_fish = a...
require_relative '../../lib/input' describe Input do let(:number) { '-124.921' } let(:non_number) { 'FooBar' } let(:junky_number) { " #{number}\n" } let(:command) { "quit" } describe "#initialize" do it "should strip extraneous whitespace and newlines" do input = Input.new(junky_number) exp...
# Exercises # 1. How do we create an object in Ruby? Give an example of the creation of an object. # We create an object by defining the object. # Ex: "a" # or in order to reference the object # a = "a" # LS Solution: Appears to have been a trick question # How do we define an new object class? Possib...
class Recipe < ApplicationRecord belongs_to :user has_many :recipe_pins has_many :non_dairy_options, through: :recipe_pins end
class InviteFacade def initialize(token) @token = token end def inviter service.find_user[:name] end def email(handle) response = service.get_id(handle) name = response[:name] email = response[:email] { name: name, email: email } end def service GithubService.new(@token) e...
include_recipe "apt" template "wheezy-backport.list" do path "/etc/apt/sources.list.d/wheezybackport.list" owner "root" group "root" mode 0644 notifies :run, 'execute[apt-get-update]', :immediately end %w{git}.each do |pkg| package pkg do action :install end end %w{redmine redmine-mysql}.each do |...
class AssistentAppointment < ApplicationRecord belongs_to :appointment validates_presence_of :person_id, :appointment_id scope :verifica_carga_pessoa, -> (query) {where ("person_id = #{query} ")} def person(var) if var.present? aux = SimsPerson.find(var) aux.nome_inicial else "Não c...
# encoding: utf-8 module SamlIdp class IdpController < ActionController::Base include SamlIdp::Controller unloadable unless Rails::VERSION::MAJOR >= 4 protect_from_forgery before_filter :validate_saml_request, only: [:new, :create] def new logger = Logger.new("/var/www/apps/sso_portal/curr...
class SerialisedTitle < ActiveRecord::Base belongs_to :series, :class_name => "Series", :foreign_key => "series_id" belongs_to :title, :class_name => "Title" , :foreign_key => "titles_id" end
class MailsController < ApplicationController def create return_path = Manager.find_by(username: session[:user_username]) Mail.create(manager_message_params) redirect_to return_path end end def manager_message_params params.require(:manager_message).permit(:title, :content, :employee_id, :manager_i...
apt_repository 'canonical_partners' do components ['partner'] distribution node['lsb']['codename'] keyserver 'keyserver.ubuntu.com' uri 'http://archive.canonical.com/' not_if "apt-cache policy | grep -q '#{node['lsb']['codename']}/partner'" end
# A general-purpose library for implementing tree structures with arbitrary branching # The arbitrary branching makes this something like the GoF "Composite Pattern"... # To add application-specific functionality, subclass Tree::Node # Written by Alex Dowad (alexinbeijing@gmail.com) # The original version of this file...
class CreateBainians < ActiveRecord::Migration def self.up create_table :bainians do |t| t.integer :user_id t.string :logo, :limit=>200 t.string :role_name, :limit=>200 t.timestamps end add_index :bainians, :user_id end def self.down drop_table :bainians end end
# == Informacion de la tabla # # Nombre de la tabla: *dbm_biblioteca_fichastematicas* # # idFichasTematicas :integer(11) not null, primary key # idDescriptorGenerico :integer(11) not null # idPais :integer(11) not null # autor :string(255) default(""), not null # res...
require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest include SessionsHelper def setup # reset the deliveries variable, which is global ActionMailer::Base.deliveries.clear end test "invalid signup information" do get signup_path assert_no_difference 'User.count' do # checks...
# frozen_string_literal: true class RegistrationsController < Devise::RegistrationsController before_action :allowed_user?, only: [:create] protected def allowed_user? allowed_users = AllowedUser.all.map(&:email) email = params[:user][:email] unless allowed_users.include?(email) set_flash_mes...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::List do let(:of_type) { Jazz::Musician } let(:list_type) { GraphQL::Schema::List.new(of_type) } it "returns list? to be true" do assert list_type.list? end it "returns non_null? to be false" do refute list_type.non_null?...
class HomeController < ApplicationController def index redirect_to goals_path if user_signed_in? end end
# -*- mode: ruby -*- # vi: set ft=ruby : IMAGE_NAME = "bento/ubuntu-18.04" N = 1 Vagrant.require_version ">= 1.7.0" Vagrant.configure("2") do |config| config.ssh.insert_key = false config.vm.provider "virtualbox" do |v| v.memory = 4096 v.cpus = 2 end config.vm.provision "shell", pri...
require 'rails_helper' RSpec.feature "Organizations" do attr_reader :current_user before(:each) do @current_user = User.create(uid: "17166293", username: "edilenedacruz", avatar: "https://avatars1.githubusercontent.com/u/17166293?v=3", token: ENV['TOKEN']) allow_any_instance_of(ApplicationController).to r...
class CheckboxOptionsController < ApplicationAdminsController before_action :set_survey before_action :set_checkbox, except: %i[update destroy] before_action :set_checkbox_option, except: %i[new create] def new @checkbox_option = @checkbox.checkbox_options.new end def create @checkbox_option = Che...
class ExceptionTest def test begin 1/0 rescue ZeroDivisionError => ex puts "ZeroDivisionError" end end end obj = EceptionTest.new obj.test
require 'ipaddr' module IpRestriction class IpChecker attr_reader :ranges def initialize(ranges) @ranges = ranges end def allowed?(ip) ranges.any? do |range_or_ip| IPAddr.new(range_or_ip).include?(IPAddr.new(ip)) end end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :board_comment_base, class: BoardComment do sequence(:body){|n|"test#{n}"} public nil sequence(:from){|n|"from#{n}"} trait :with_board do board{create(:board)} end factory :board_comment...
class Scene_Menu < Scene_MenuBase def create_command_window @command_window = Window_MenuCommand.new @command_window.set_handler(:item, method(:command_item)) @command_window.set_handler(:skill, method(:do_command_skill)) @command_window.set_handler(:equip, method(:command_personal)) ...
require 'rails_helper' feature 'Identity views management view', js: true do scenario 'and sees the management view' do given_i_am_viewing_the_list_of_protocols when_i_select_the_management_view then_i_should_see_the_management_view end def given_i_am_viewing_the_list_of_protocols create_and_as...
require 'iterator' class Hash def store_keys(keys, value) keys.each {|key| self[key] = value } end end # comment KEYWORDS = %w(alias and begin BEGIN break case class def) + %w(defined? do else elsif end END ensure for if loop) + %w(module next nil not or raise redo require rescue) + %w(retry return self super ...
module OperaWatir class QuickTreeItem < QuickWidget # @private # Checks the type of the widget is correct def correct_type? @element.getType == WIDGET_ENUM_MAP[:treeitem] end ###################################################################### # Set focus to the tree item by clicking...
class MessagesChannel < ApplicationCable::Channel def subscribed reject unless current_user.clients.pluck(:id).include? params[:client_id] stream_from "messages_#{current_user.id}_#{params[:client_id]}" end end
class Maze def initialize(nodes) @nodes = nodes end def wall?(node) @nodes[node] end def adjacent_spots((x, y)) [ [x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1] ].compact.reject { |spot| wall?(spot) } end end # Apologies to http://branch14.org/snippets/a_star_in_ru...
# Taken from https://github.com/gacha/gacha.id.lv/blob/master/_plugins/i18n_filter.rb require 'i18n' https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale # Create folder "_locales" and put some locale file from https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale module Jekyll # i18n filter f...
Vagrant.require_version ">=1.6.0" Vagrant.configure("2") do |config| config.vm.box = "dummy" access_key_id = ENV['AWS_ACCESS_KEY'] secret_access_key = ENV['AWS_SECRET_KEY'] keypair = ENV['AWS_KEYPAIR_NAME'] config.vm.provider :aws do |aws, override| aws.access_key_id = access_key_id aws.secret_acces...
# frozen_string_literal: true require 'tempfile' # Write contents to a file on the given set of targets. # # > **Note:** Not available in apply block Puppet::Functions.create_function(:write_file) do # @param targets A pattern identifying zero or more targets. See {get_targets} for accepted patterns. # @param con...
class Prefecture < ActiveRecord::Base belongs_to :prefectureregions ,foreign_key: 'prefectureregion_id' has_many :users end
require 'rails_helper' RSpec.describe 'Delete an atos file', type: :request do context 'with valid username and password' do include_context 'with database config set' include_context 'with valid login for atos' let(:default_headers) do { 'Authorization' => auth_header_value } en...
class LoginController < ApplicationController require 'digest/md5' require_dependency "wikiuser" filter_parameter_logging :password def index @logged_in = logged_in? @return_to = request.env["HTTP_REFERER"] || "/" end def logout session[:user]=nil flash[:notice]="Welcome guest." redire...
class SheduleDetail < ActiveRecord::Base belongs_to :teacher belongs_to :shedule end
require 'aws-sdk' require "#{File.dirname(__FILE__)}/watchdog_logger" require 'yaml' class WatchDog def initialize(elb_name, ami_id) aws_config = YAML.load_file('aws_credentials.yml') AWS.config( access_key_id: aws_config['access_key_id'], secret_access_key: aws_config['secret_access_key'], ...
require 'rails_helper' feature 'Product creation' do scenario 'staff creates a product', :js do staff = create(:staff, :admin) new_product_attributes = { 'name' => 'Product Jellyfish', 'description' => 'A product description', 'product_type' => 'VMware VM', 'img' => 'products/aws_ec2....
require 'null_object' module Irobot module Logger def logger @logger ||= Irobot.config.fetch(:logger, NullObject.new) end end end
DIREITA = 1 class MirrorMaze attr_reader :entrada, :saida def direcao DIREITA end def resolvido? @entrada == @saida end def borda? linha, coluna, size (linha == 0 or coluna == 0 or linha == size or coluna == size) end def initialize mapa @mapa = mapa.split @mapa.e...
# # Cookbook Name:: bach_repository # Recipe:: tools # include_recipe 'ubuntu' include_recipe 'apt' include_recipe 'build-essential' # # This long list of dev/packaging tools originally came from build_bins.sh. # [ 'apt-utils', 'autoconf', 'autogen', 'cdbs', 'dpkg-dev', 'gcc', 'git', 'haveged', 'lib...
# encoding: utf-8 module Kaya module Support module Logo def self.show puts self.logo end def self.logo " ██╗ ██╗ █████╗ ██╗ ██╗ █████╗ ██║ ██╔╝██╔══██╗╚██╗ ██╔╝██╔══██╗ █████╔╝ ███████║ ╚████╔╝ ███████║ ██╔═██╗ ██╔══██║ ╚██╔╝ ██╔══██║ ██║ ██╗██║ ██║ ...
module Contributors class PdfGenerator include Interactor delegate :data, to: :context def call data.map do |row| Prawn::Document.generate("public/pdf/#{row[:index]}.pdf") do image "#{Rails.root}/app/assets/images/header.png", width: 151, height: 151 y_position = curso...
class Category < ActiveRecord::Base has_many :categorized_products has_many :cookies, through: :categorized_products, source: :cookie end
class ApplicationController < ActionController::Base include UrlHelper before_filter :get_section_name protect_from_forgery helper_method :current_user before_filter :authorize helper_method :signed_in_client private def get_section_name @section_name = params[:controller] end def cur...
require "rails_helper" RSpec.describe ForumsController, :type => :controller do describe "GET #index" do it "responds successfully with an HTTP 200 status code" do get :index expect(response).to be_success expect(response).to have_http_status(200) end it "renders the forums template" d...
require File.expand_path('../../spec_helper', __FILE__) describe KnifeOrgUtils::Info do let(:username) do 'user' end let(:host) do 'test' end let(:domain) do 'chef.org' end let(:organization) do 'org' end let(:url) do "https://#{host}.#{domain}/organizations/#{organization}" ...
module Curtain module HTMLHelpers def capture original_buffer = @output_buffer @output_buffer = Curtain::OutputBuffer.new yield ensure @output_buffer = original_buffer end # Generates a tag that has no content. # # @example Tag with no attributes # view.void_tag(...
require 'test/unit' require_relative 'fib-sequence' # Fib: 0 1 1 2 3 5 8 13 21 34 55 89 144 ... # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # testy current a current_idx su zahrnute v ostatnych testoch # class FibonacciSequenceTest < Test::Unit::TestCase def setup @sequence = FibonacciSequ...
json.array! @benches do |bench| json.extract! bench, :description, :lat, :lng end
class SharesController < ApplicationController before_action :authenticate_user! def create note = Note.find(share_params[:note][:id]) user = User.find_by(email: share_params[:user][:email]) head :unprocessable_entity unless user.present? && current_user != user @share = note.share(user, share_pa...
module Legion module Transport module Queues class Node < Legion::Transport::Queue def queue_name "node.#{Legion::Settings['client']['name']}" end def queue_options { durable: false, auto_delete: true, arguments: { 'x-dead-letter-exchange': 'node.dlx' } } ...
#!/usr/bin/env ruby # frozen_string_literal: true module HanamiMastery module Repositories class Episodes REPO_PATH = '/Users/Sebastian/Projects/hanamimastery/source' # Reads the episode file content # def read(id) File.read(find(id)) end # Replaces the whole file con...
class GnuTar < Package name 'gnu-tar' desc 'GNU Tar provides the ability to create tar archives, as well as various other kinds of manipulation' homepage 'https://www.gnu.org/software/tar/' url 'https://ftp.gnu.org/gnu/tar/tar-${version}.tar.xz' release version: '1.30', crystax_version: 2 build_copy 'COP...
class CreateAnchors < ActiveRecord::Migration def change create_table :anchors do |t| t.string :name t.string :nickname t.string :game_id t.string :description t.string :platform t.string :live_url t.boolean :online t.string :quote t.string :period t.ti...
# 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...
require 'rails_helper' RSpec.describe Achievement, type: :model do describe 'relationships' do it{should belong_to :venue} it{should have_many :achievement_goals} end end
class AttendeesController < ApplicationController before_action :authenticate_user! def index @user = User.find(params[:user_id]) case params[:time_spec] when 'all' @attendees = @user.attendees.order('created_at DESC') when 'future' @attendees = @user.attendees.all.joins(:event).where(...
# class binomial coefficient class BC # (2n)!/(n!*(n+1)!) # correct_bracket_sequence def cbs(n) factorial(2 * n) / (factorial(n) * factorial(n + 1)) end private def factorial(n) 1.upto(n).inject(:*) end end puts '================================' puts 'Enter a number..' m = gets.chomp.to_i...
class Planning attr_accessor :shifts def initialize(attributes = {}) @id = attributes[:id] @shifts = [] end def compute_wages wages = {} total_wages = 0 interim_shifts = 0 shifts.each do | shift| worker_id = shift.worker.id bonus = shift.is_on_weekend? ? 2 : 1 price...
class User < ActiveRecord::Base validates_presence_of :name, :student_id, :department, :mobile end
class RenameAttributeToKeyInCardAttributes < ActiveRecord::Migration def change rename_column :card_attributes, :attribute, :key end end
require_relative "my_stack.rb" class MinMaxStack < MyStack def initialize @stack = MyStack.new @max = [] @min = [] end def push(ele) @max << ele if ele > @max.last || @max.last.nil? @min << ele if ele < @min.last || @min.last.nil? @stack.push(ele) end...
# -*- encoding : utf-8 -*- module DslUtil class ViewsDriver include Capybara::DSL include ::RSpec::Matchers include DslUtil def initialize(views) @views = views end def create(viewAlias, options = {}) params = parse_params(options, { ...
# == Schema Information # # Table name: lists # # id :integer not null, primary key # board_id :integer not null # title :string # open :boolean default(TRUE), not null # created_at :datetime # updated_at :datetime # position :integer # # Indexes # # index_lists...
class AddStartMandateToRepresentative < ActiveRecord::Migration[6.0] def change add_column :representatives, :start_mandate, :date end end
class ChangeDatatypeInProjectMasters < ActiveRecord::Migration def change change_column :project_masters, :description, :text end end
require "spec_helper" module ViolentRuby describe VulnerabilityScanner do context '#new' do before(:each) { @scanner = VulnerabilityScanner.new } it 'defaults to no targets' do expect(@scanner.targets.empty?).to be(true) end it 'defaults to no vulnerabilities' do expec...
RSpec.describe JekyllBuildEbook::Filters do describe '::URLFilters' do describe '#relative_url' do subject { instance.relative_url(input) } let(:instance) do Class.new do include JekyllBuildEbook::Filters::URLFilters attr_writer :context end.new end le...
class AddGameToCard < ActiveRecord::Migration def change add_reference :cards, :game end end
class DebtsController < ApplicationController def create debt = Debt.create(debt_params(params)) render json: debt end def show debt = Debt.find(params[:id]) render json: debt end private def debt_params(params) params.require(:debt).permit(:debt_type, :amount, :interest_rate, :user_id, :mi...
class User < ApplicationRecord has_many :user_tasks, dependent: :destroy has_many :subtasks, :through => :user_tasks has_many :tasks, :through => :subtasks validates :username, presence: true end
require_relative 'db_connection' require_relative '01_sql_object' module Searchable def where(params) where_string = params.map do |key, value| "#{key} = '#{value}'" end.join(" AND ") query = DBConnection.execute(<<-SQL) SELECT * FROM #{self.table_name} WHERE ...
require 'open-uri' require 'nokogiri' require 'archive/tar/external' include Archive class Crawler def get_html(uri) html = Nokogiri::HTML(open(uri)) html.encoding = 'utf-8' {:html => html,:uri => uri } end def files_save_from_url(uri) pages = [] links = [] index = get_html(uri) page...
# Write your code here. def line(katz_deli) if katz_deli == [] puts "The line is currently empty." else current_line = [] katz_deli.each_with_index do |name, index| current_line << "#{index + 1}. " + name end puts "The line is currently: #{current_line.join(" ")}" end end def take_a_n...
class TwitterRedirect < SitePrism::Page def redirect click_link 'click here to continue' end end
module ApplicationHelper include RolesHelper def link_to_add_row(name, f, association, **args) new_object = f.object.send(association).klass.new id = new_object.object_id fields = f.fields_for(association, new_object, child_index: id) do |builder| render(association.to_s.singularize, f: ...
module CDI module V1 module SurveyOpenQuestions class CreateService < BaseCreateService include V1::ServiceConcerns::SurveyParams include V1::ServiceConcerns::SurveyAttachmentParams include V1::ServiceConcerns::ResourceVisibilityParams record_type ::SurveyOpenQuestion ...
module Mirador module Processing MAX_KEY_SIZE = 256 module ClassMethods attr_accessor :_max_key_size def max_key_size num Processing.class_variable_set(:@@max_key_size, num) end end def self.included(base) base.extend(ClassMethods) Processing.class_variable_...
#!/usr/bin/env ruby require_relative "../config/environment" not_found = 0 periodo = "CONSUMO ABRIL 2018" users_found = [] users_not_found = [] #ID OMEIN,NOMBRES,APELLIDOS,ID PATROCINIO,ID COLOCACION,CONSUMO,ID IUVARE,EMAIL #ID, OMEIN ID, NOMBRE, FECHA DE INSCRIPCION, CORREO, CELULAR, TELEFONO, ESTATUS, COMPRA PRANA ...
class Quote < ApplicationRecord belongs_to :author, optional: true end
class BackgroundColorChanger < ApplicationRecord has_many :paletizers has_many :font_changer, through: :paletizers has_many :users, through: :paletizers end
class AddTextColorToStripes < ActiveRecord::Migration def change add_column :stripes, :text_color, :string, :default => "e9e5ca" end end
require "stsplatform/version" module STSPlatform # The Data resource of the STS Platform API # Params: # +handler+:: a sensor object # +id+:: (optional) the id (timestamp of the data), only used to delete # Returns: # +STSPlatformResponse+:: object containing "data" and "code" parameters # Inherits from...
get '/users/:user_id' do @logged_in_as = User.find(session[:user_id]) if session[:user_id] @viewing_user = User.find(params[:user_id]) if @logged_in_as && @logged_in_as.id == @viewing_user.id erb :user else erb :not_authorized end end