text
stringlengths
10
2.61M
#!/usr/bin/env ruby # @param {String} str # @return {Integer} def my_atoi(str) ret = str.to_i if ret > 2147483647 ret = 2147483647 end if ret < -2147483648 ret = -2147483648 end ret end
module Antelope module Generator class CHeader < Base register_as "c-header", "c_header" has_directive "union", Array[String, String] has_directive "api.prefix", String has_directive "api.push-pull", String has_directive "api.value.type", String has_directive "api.token.prefi...
class RecipesController < ApplicationController impressionist :actions=> [:show] def index @recipes = Recipe.all.order(created_at: "DESC").limit(8) @tsukurepos = Tsukurepo.all.order(created_at: "DESC").limit(8) end def new @recipe = Recipe.new @recipe.flows.build @recipe.ingredients.build...
require 'yaml' require 'fileutils' require 'sprawl/service_definition' module Sprawl class MultiGitLoader def self.load(options) puts 'Using Multi Git Loader' if options[:verbose] begin # Make temp directory Dir.mkdir('.sprawl') pull_repos(options[:group]) service_d...
# added in release 1.7.0 module GroupDocs class Document::TemplateEditorFields < Api::Entity # @attr [Integer] page attr_accessor :page # @attr [String] name attr_accessor :name # @attr [String] type attr_accessor :type # @attr [GroupDocs::Document::Rectangle] rect attr_acc...
require 'rails_helper' describe 'token middleware', :type => :request do let(:token) { FactoryGirl.create(:token) } context 'with a valid key' do let(:key) { token.key } context 'with a reference' do let!(:reference) { FactoryGirl.create(:reference) } it 'shows contact information' do ...
class MovieRetriever def initialize movie_db @movie_db = movie_db end def posters @movie_db.posters.compact end end describe "Movie database" do before :each do @movie_db = double("MovieDB") @retriever = MovieRetriever.new @movie_db end it "retrieves one poster if there is one" do ...
require 'spec_helper' describe Rack::DevMark::Utils do subject { Class.new{ include Rack::DevMark::Utils }.new } describe "#camelize" do it "camelizes" do expect(subject.camelize("test_test_test")).to eq("TestTestTest") end end end
class Item < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :prefecture belongs_to_active_hash :condition belongs_to_active_hash :delivery_fee belongs_to_active_hash :days_until_shipping belongs_to :category, optional: true belongs_to :buyer, class_name:...
Rails.application.configure do config.webpack.dev_server.host = 'client' if Rails.env.test? config.webpack.dev_server.manifest_host = 'client' config.webpack.dev_server.manifest_port = 3808 config.webpack.dev_server.enabled = !Rails.env.production? && ENV['CI'].blank? end
#!/usr/bin/env ruby # frozen_string_literal: true $:.unshift(File.expand_path('../lib', __dir__)) require 'rblint' def run_tests(constant, contents) contents.each do |content| parser = RbLint::Parser.new(content) parser.singleton_class.prepend(RbLint::Rules.const_get(constant)) parser.parse if par...
require 'bacon' require 'tilt' describe Tilt::StringTemplate do it "is registered for '.str' files" do Tilt['test.str'].should.equal Tilt::StringTemplate end it "compiles and evaluates the template on #render" do template = Tilt::StringTemplate.new { |t| "Hello World!" } template.render.should.equal...
class MaterialCategoryPolicy < Struct.new(:user, :m_c) def show? m_c.course.users.include? user end def create? m_c.course.admins.include? user end def update? create? end def destroy? create? end def new? create? end end
class CreateClocks < ActiveRecord::Migration def change create_table :clocks do |t| t.string :department t.integer :name t.integer :number t.datetime :time t.integer :machine_number t.integer :code t.string :way t.integer :card_number t.timestamps null: false...
require_relative 'bike' class DockingStation attr_reader :bike # def initialize #(@bike) # end #@bike def release_bike raise "No bikes available" unless @bike @bike end def dock_bike(bike) #need to return bike which is being docked #use instance var to store the bike...
class Api::V1::MerchantsController < Api::V1::BaseController def object_type Merchant end def items respond_with Item.where(merchant_id: params[:id]).order(:id) end def invoices respond_with Invoice.where(merchant_id: params[:id]).order(:id) end def most_revenue respond_with Merchant.m...
class AddShopTierToUsers < ActiveRecord::Migration def change add_column :users, :shopTier, :integer, default:1 end end
require 'spec_helper' describe EnumerableObserver do let(:array) { Array.new } let(:caller) { Object.new } describe 'items added' do it 'should observe items added' do items_to_add = [1, 2, 3] expect(caller).to receive(:items_added).with(items_to_add) EnumerableObserver.observe(array).adde...
class Geoipupdate < Formula desc "Automatic updates of GeoIP2 and GeoIP Legacy databases" homepage "https://github.com/maxmind/geoipupdate" url "https://github.com/maxmind/geoipupdate/releases/download/v2.4.0/geoipupdate-2.4.0.tar.gz" sha256 "8b4e88ce8d84e9c75bc681704d19ec5c63c54f01e945f7669f97fb0df7e13952" r...
Dynamic.class_eval do # How a field should be RENDERED ON A SEARCH FORM of a given team def self.field_search_json_schema_type_language(team = nil) languages = team.get_languages || [] keys = languages.flatten.uniq include_other = true if keys.empty? include_other = false joins = "INN...
class ChangeMsgColumnName < ActiveRecord::Migration def change rename_column :user_messages, :recipient_id, :user_id end end
class DocsController < ApplicationController before_action :_check_admin_rights, only: [:new, :edit, :create, :update, :destroy] before_action :require_user, only: [:download] before_action :_set_doc, only: [:show, :edit, :update, :destroy] helper_method :download, :layout layout :layout #TO...
class AddIdentifiableIdToStudentUsers < ActiveRecord::Migration def change add_column :student_users, :identifiable_id, :integer end end
module ProductCustomizations # given params[:customizations], return a non-persisted array of ProductCustomization objects def product_customizations customizations = [] # do we have any customizations? params[:product_customizations].to_unsafe_h.each do |customization_type_id, customization_pair_value|...
namespace :rpush_app do desc 'create rpush app' task create: :environment do app = Rpush::Gcm::App.new app.name = "android_app" app.auth_key = Rails.application.credentials.FIREBASE_SERVER_KEY app.connections = 1 app.save! end end
require './Lib/Airport' describe Airport do let(:plane) { double :plane, land: nil, take_off: nil } let(:gate) { double :gate } let(:available_gate) { double :gate, available?: true } let(:unavailable_gate) { double :gate, available?: false} let(:two_gate_airport) { Airport.new [available_gate, unavailable_ga...
require 'spec_helper' describe NoPerc do before(:each) do @attr = { :composer_name => "Example Composer", :work_name => "Example Work name" } end it "should require a composer name" do no_name_composer_name = NoPerc.new(@attr.merge(:composer_name => "")) no_name_composer_name.should_not be_va...
class Move < ActiveRecord::Base attr_accessible :game_id, :square, :player_number, :current_user belongs_to :game validates :game_id, :square, :player_number, presence: true validate :right_player validate :square_free validate :game_active validate :player_allowed def right_player unless self.rig...
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :reviews, dependent: :destroy validates :first_name, :last_name, presence: true end
# # Be sure to run `pod lib lint CardIOSDKBridge.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'Car...
class Patient::RatingsController < ApplicationController layout 'patient_layout' skip_before_action :verify_authenticity_token before_filter :require_patient_signin def create puts "Rating params" puts params @consult = Consult.find(params[:consult_id]) @rating = Rating.create(rating_params) ...
require 'spec_helper' describe GnipInstanceImportsController do let(:user) { users(:owner) } let(:gnip_csv_result_mock) { GnipCsvResult.new("a,b,c\n1,2,3") } let(:gnip_instance) { gnip_instances(:default) } let(:workspace) { workspaces(:public) } let(:gnip_instance_import_params) { { :gnip_instance_i...
require 'test_helper' class MessagesControllerTest < ActionDispatch::IntegrationTest setup do @message = messages(:one) end test "should get list posted and public" do get messages_url, as: :json assert_response :success body = JSON.parse(@response.body) assert_equal 1, body.length end ...
# Ignoring Case # Using the following code, compare the value of name with the string 'RoGeR' while ignoring # the case of both strings. Print true if the values are the same; print false if they aren't. # Then, perform the same case-insensitive comparison, except compare the value of name with the # string 'DAVE...
module TeamStats def team_info(team_id) info = {} info["team_id"] = @teams[team_id].team_id info["franchiseId"] = @teams[team_id].franchiseId info["teamName"] = @teams[team_id].teamName info["abbreviation"] = @teams[team_id].abbreviation info["link"] = @teams[team_id].link info end d...
class Level < ApplicationRecord has_many :courses validates :name, :presence => true end
# == Schema Information # # Table name: posts # # id :integer not null, primary key # title :string(255) # content :string(255) # user_id :integer # created_at :datetime not null # updated_at :datetime not null # class Post < ActiveRecord::Base # solo content e title...
class CreateResearchSequence < ActiveRecord::Migration[5.2] def up execute <<-SQL CREATE SEQUENCE research_seq; SQL end def down execute <<-SQL DROP SEQUENCE research_seq; SQL end end
namespace :dev do namespace :composer do desc "Runs composer install on the VM." task :install do run "vagrant ssh -- -t 'cd #{REMOTE_APP_FOLDER}; composer install'" end desc "Runs composer update on the VM." task :update do run "vagrant ssh -- -t 'cd #{REMOTE_APP_FOLDER}; composer up...
class Like < ActiveRecord::Base belongs_to :video belongs_to :liked_by, class_name: "User" end
class VendorsController < ApplicationController before_filter :authenticate_vendor!, :only=> [:usersearch,:addmember, :createmember, :memberlist, :addmywwmember,:edit, :update] ####################### Vendor Search ####################################### def search if !params[:searchtype].nil? if...
class User < ActiveRecord::Base belongs_to :credit_company has_many :credit_companies, foreign_key: "executive_id" # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :remember...
require 'rubygems' require 'json' require 'httparty' require 'pp' class Issues < Linkbot::Plugin @@config = Linkbot::Config["plugins"]["activecollab"] if @@config include HTTParty base_uri @@config["url"] debug_output $stderr Linkbot::Plugin.register('issues', self, { :message => {:regex =...
bp_require 'json/json' bp_require 'machsend' bp_require 'machsend/utils' bp_require 'machsend/logging' bp_require 'machsend/observable' bp_require 'machsend/base' bp_require 'machsend/asset' bp_require 'machsend/client' bp_require 'machsend/rpc' bp_require 'machsend/rpc/message' bp_require 'machsend/rpc/client_to_clie...
class Post < ApplicationRecord belongs_to :user validates :text, length: { maximum: 200 } end
# encoding: utf-8 class DocumentUploader < CarrierWave::Uploader::Base storage :file def store_dir "#{Rails.root}/private/documents/#{model.id}" end end
module Api module V1 class BookSuggestionController < ApiController def create render json: BookSuggestion.create!(book_suggestion_params), status: :created end def book_suggestion_params params.require(:book_suggestion).permit(:author, :title, :link, ...
requirements = [ { name: "add the paper to the page", spec: "$frame.find('svg').length > 0", position: 1, success: "You just made an HTML canvas to draw on.", step: 1, kit: "whackamole" }, { name: "set the background color", spec: ' colored_rects = 0 _.each($frame.find("svg rect"),...
require 'vizier/arguments/base' module Vizier #Input must match the regular expression passed to create this Argument class RegexpArgument < Argument register "regexp", Regexp register "regex" def complete(terms, prefix, subject) return [prefix] end def validate(term, subject) retu...
# This is a working file until I split these up require 'spec_helper' describe MSFLVisitors::Parsers::MSFLParser do let(:expected_node) { ->(wrapped_node) { MSFLVisitors::Nodes::Filter.new [ wrapped_node ] } } let(:left) { MSFLVisitors::Nodes::Field.new :value } let(:right) { MSFLVisitors::Nodes::Number.new o...
module Gloat class Slide VALID_EXTENSIONS = %w{ slide textile md haml erb html } attr_reader :template_name def initialize content, extension, template_name='default' @extension = extension @template_name = template_name parse_slide(content) end def self.slide_file_valid? fi...
TeamType = GraphqlCrudOperations.define_default_type do name 'Team' description 'Team type' interfaces [NodeIdentification.interface] field :archived, types.Boolean field :private, types.Boolean field :avatar, types.String field :name, !types.String field :slug, !types.String field :description, typ...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html devise_for :customers root to: 'homes#top' get 'about' => 'homes#about' get 'customers/unsubscribe' => "customers#unsubscribe" patch 'customers/status' => "customers#status"...
class Collection < ApplicationRecord belongs_to :box belongs_to :recipe end
class User::TopController < User::Base include SmartYoyakuApi::User before_action :set_categories before_action :not_found, only: :details def index end def shop if params[:category_id].present? @category = Category.find(params[:category_id]) @all_store = Store.categorized(params[:category...
module Acronym # @param [String] # @return [String] def self.abbreviate(string) # letter after word boundary string.scan(/\b[a-zA-Z]/).join.upcase end end
require 'test_helper' class MovieReactionsControllerTest < ActionDispatch::IntegrationTest setup do @movie_reaction = movie_reactions(:one) end test "should get index" do get movie_reactions_url assert_response :success end test "should get new" do get new_movie_reaction_url assert_resp...
# # Binary Secret Handshake # > There are 10 types of people in the world: Those who understand binary, and those who don't. # You and your fellow flatirons are of those in the "know" when it comes to binary decide to come up with a secret "handshake". # ``` # 1 = wink # 10 = double blink # 100 = close your eyes # 1...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure('2') do |config| config.vm.box = "precise32" config.vm.box_url = "http://files.vagrantup.com/precise32.box" config.vm.hostname = 'stm32-dev-box' config.vm.synced_folder ".", "/home/vagrant/files" config.vm.provider :virtualbox do |vb| ...
module AdminArea class RecommendationRequestsController < AdminController def index # accounts with unresolved recs: accounts = Account\ .joins(:unresolved_recommendation_requests)\ .includes( :unresolved_recommendation_requests, ...
# pic-mover.rb $LOAD_PATH << File.dirname(__FILE__) require 'logger' require 'settings' require 'remote' require 'fileutils' class Server def initialize @conf = Settings.new log_path = File.join(@conf['local_root'], 'log', @conf['local_log_file']) @log = Logger.new(log_path) @log.level = Logger.cons...
class CreateClientOrganizations < ActiveRecord::Migration[5.2] def change create_table :client_organizations do |t| t.bigint :client_id t.bigint :organization_id end add_index :client_organizations, [:client_id, :organization_id], unique: true end end
class DocumentationLink < ActiveRecord::Base belongs_to :documentation validates_presence_of :path end
class Users::UsersController < ApplicationController before_action :authenticate_user! load_and_authorize_resource end
class SessionsController < ApplicationController skip_before_action :require_user, only: [:new, :create] # login page def new @login_form = LoginForm.new end # login form POST def create @login_form = LoginForm.new(login_params) user = @login_form.authenticate if @login_form.valid? && logi...
require 'spec_helper' require 'simplecov' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../config/environment', __dir__) abort('The Rails environment is running in production mode!') if Rails.env.production? require 'rails/all' require 'rspec/rails' require 'devise' # include Rack::Test::Methods begin ActiveR...
class Restaurant < ActiveRecord::Base has_many :reviews, dependent: :destroy validates :name, presence: true, uniqueness: true def average_rating return 'N/A' if reviews.none? reviews.inject(0) do |sum, review| @total = sum+review.rating end @total/reviews.count end end
class ApplicationController < ActionController::API private # mongodb saves everything, remove any non-class defined attributes def private_params(_class) params.permit(_class.column_names) end end
# модель товара # по большему счету тут все наглядно: # - картинки, зависимости, валидации и переводы # - алиас для категорий # - расчет минимальной цены из вариантов # - проверка наличия вариантов с картинкой материала class Good < ActiveRecord::Base include ActionView::Helpers::NumberHelper include ActionView::He...
require 'rails_helper' describe "find an item with params" do context "search using valid params" do before :each do @item = create(:item) end it "can find an item with id params" do get '/api/v1/items/find', params: {id: @item.id} end it "can find an item with name params" do g...
#GET request get '/sample-41-how-to-set-callback-for-annotation-and-manage-user-rights' do haml :sample41 end #POST request post '/sample41/callback' do begin #Get callback request data = JSON.parse(request.body.read) serialized_data = JSON.parse(data['SerializedData']) raise 'Empty pa...
class Bullhorn module Plugin class << self attr_accessor :options attr :ignored_exceptions end def self.ignored_exceptions [].tap do |ex| ex << ActiveRecord::RecordNotFound if defined? ActiveRecord if defined? ActionController ex << ActionController::UnknownCo...
class Project < ActiveRecord::Base validates :title, :presence => true, :uniqueness => true has_many :project_weeks has_many :weeks, :through => :project_weeks, :uniq => true def num_weeks_scheduled weeks num = 0 weeks.each do |week| if self.weeks.include?(week) num += 1 end end...
class RemoveManuallyEnteredForeignKeys < ActiveRecord::Migration def change remove_column :answers, :question_id remove_column :questions, :quiz_id end end
class UpdateMatches < ActiveRecord::Migration[5.2] def change remove_column :matches, :forfeit, :integer remove_column :matches, :league_play, :boolean remove_column :matches, :teams_id, :integer add_reference :matches, :division end end
class AddDatetimeStatusesToConsultant < ActiveRecord::Migration def change add_column :consultants, :date_on_hold, :datetime add_column :consultants, :date_pending_approval, :datetime add_column :consultants, :date_approved, :datetime add_column :consultants, :date_rejected, :datetime end def dat...
class Proc def to_route(opts = {}) based_on = opts[:based_on] if opts[:unwrap] or based_on and based_on.extensions and based_on.graph source = proc { self.call.map { |e| e.element } } else source = self end if based_on Pacer::RouteBuilder.current.chain(source, :element_type => :m...
class Api::V1::InvitationsController < Devise::InvitationsController skip_before_action :resource_from_invitation_token, :only => [:edit] def edit invitation_token = params[:invitation_token] slug = params[:slug] resource = User.accept_team_invitation(invitation_token, slug) path = if resource.erro...
#! /usr/bin/env ruby -S rspec require 'spec_helper' describe 'the dns_aaaa function' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it 'should exist' do expect(Puppet::Parser::Functions.function('dns_aaaa')).to eq('function_dns_aaaa') end it 'should raise a ArgumentError if there is less than ...
class Hand attr_reader :held_cards def initialize @held_cards = [] end def size held_cards.count end def new_card!(deck_to_draw) held_cards << deck_to_draw.draw! end def view if size == 0 "No cards!" else cards_info = [] held_cards.each do |card| cards_in...
class Dragon def initialize name @name = name @asleep = false @stuff_in_belly = 10 # He's full. @stuff_in_intestine = 0 # He doesn't need to go. puts "#{@name} just hatched from the mystical egg." end def feed puts "You feed #{@name} the bodies of your enemies." @stuff_in_belly = 10 ...
class CreateBookmarks < ActiveRecord::Migration[5.0] def change create_table :bookmarks do |t| t.string :title t.string :url t.text :description t.text :image t.boolean :favorite t.belongs_to :user t.timestamps end end end
User.class_eval do after_commit -> { PipelineService::V2.publish self } # Submissions must be excused upfront else once the first requirement check happens # the all_met condition will fail on submissions not being excused yet # # content_tag - where we want to place them # context_module - module of the p...
# encoding: utf-8 Gem::Specification.new do |s| s.name = 'hibot' s.version = '0.0.4' s.date = '2015-07-28' s.summary = "IRC bot supporting multiple services." s.description = "IRC bot supporting multiple services like spotify, giphy and so on." s.authors = ["Nicolas Collard"] s....
class AddLocalToGames < ActiveRecord::Migration def change add_column :games, :local, :integer, :default => 0 add_column :games, :local_miss, :integer, :default => 0 end end
class SkillsController < ApplicationController before_filter :authenticate_admin! def new @skill = Skill.new @post = Post.find(params[:post_id]) render :partial => 'form', :locals => {:skill => @skill, :post => @post} end def create @post = Post.find(params[:post_id]) @skill = @post.skills.build(para...
require 'edge' describe Edge do context '#initialize' do edge = Edge.new('A','B', 5) it 'has a start node' do expect(edge.start).to eq 'A' end it 'has an end node' do expect(edge.finish). to eq 'B' end it 'has a weight' do expect(edge.weight). to eq 5 end end end
module UserHelper def classes(contribution) return case contribution.contribution_type when :image, :video, :suggestion "#{contribution.contribution_type.to_s} dnld" when 'attached_file' "document dnld" when 'link' "#{contribution.contribution_type} dnld" else ...
class Preferences < ActiveRecord::Base belongs_to :user def self.create_for_user user user.create_preferences if user.preferences.nil? end end
require "rails_helper" describe Subscription do it "belongs to user" do Subscription.reflect_on_association(:user).macro.should eq(:belongs_to) end it "belongs to plan" do Subscription.reflect_on_association(:plan).macro.should eq(:belongs_to) end it "has many to transactions" do Subscri...
# listpkg.rb - This script will extract the package information # from a Conary database and list the installed packages and their # version numbers on the console. # # Author: Steven Oliphant # Stonecap Enterprises # # This software is copyrighted 2007 All rights reserved # ManageIQ # 1 Internation...
# encoding: utf-8 require "spec_helper" describe Refinery do describe "LandingPages" do describe "Admin" do describe "landing_pages" do refinery_login_with :refinery_user describe "landing_pages list" do before do FactoryGirl.create(:landing_page, :Homepage_Headline =...
# Public: Uses the meal cost and tip amount to calculate the cost per person of a meal shared. class CheckSplitter attr_reader :tip_amount # Public: Initializes a new Checksplitter. def initialize(meal_cost:, group:, tip_percentage: 0.18) @meal_cost = meal_cost.to_f @group = group.to_f self.get_tip_...
FactoryGirl.define do factory :history do symbol "MyString" date "2016-03-04" open "9.99" high "9.99" low "9.99" close "9.99" volume 1 adj_close "9.99" end end
class CitiesController < ApplicationController def index @cities = City.all end def show @city = City.find(params[:id]) @neighborhoods = Neighborhoods.all end private def set_city @city = City.find(params[:id]) end end
# frozen_string_literal: true # # Author:: Chef Partner Engineering (<partnereng@chef.io>) # Copyright:: Copyright (c) 2022 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_user end private def find_verified_user token = request.params[:token] payload = JWT.decode(token, ENV['JWT_SECRET_KEY'], tru...
class UsersController < ApplicationController def index @users = User.joins(:professions).where(professions: { id: params[:profession]}) @profession = Profession.find(params[:profession]) @enquiry = Enquiry.new() end def new User.new() end def show @user = User.find(params[:id]) end ...
class AddEmailAndPasswordToUser < ActiveRecord::Migration def self.up add_column :users, :email, :string add_column :users, :password, :string add_column :users, :status, :string,:default=>User::STATUS[:reg_step_1] add_column :users,:last_position_x,:double,:default=>0 add_column :users,:last_posi...
class State < ActiveRecord::Base has_many :petitions has_many :state_word_counts validates :name, presence: true, uniqueness:true def to_param name end end