text
stringlengths
10
2.61M
#!/usr/local/opt/ruby/bin/ruby # encoding: UTF-8 # frozen_string_literal: true =begin Script qui permet de "builder" un fichier Markdown, c'est-à-dire de produire le fichier HTML ou le fichier PDF avec la commande CMD-B TODO * Tester tous les cas : avec fichier .css, avec fichier .sass, avec template .erb. =end require 'kramdown' require 'sass' FILE_PATH = ARGV[0] FORMAT_PDF = ARGV[1] == '-pdf' FOLDER = File.dirname(FILE_PATH) AFFIXE = File.basename(FILE_PATH, File.extname(FILE_PATH)) # # Retourne le chemin d'accès au fichier de même affixe avec # l'extension +ext+ # def file_with_ext(ext) File.join(FOLDER,"#{AFFIXE}.#{ext}") end KRAMDOWN_METHOD = FORMAT_PDF ? :to_pdf : :to_html # # Fichier HTML de destination # (même pour le format PDF) # HTML_DEST_PATH = file_with_ext('html') puts "\n*** Production du fichier #{FORMAT_PDF ? 'PDF' : 'HTML'} ***" # # Un rappel de la syntaxe markdown étendue par kramdown # puts "\nRappel de syntaxe Kramdown" puts "--------------------------" puts "On place une ligne '{: .class #id key=\"value\"}' SOUS une ligne pour\najouter ces attributs." puts "On place \n- TOC\n{:toc}\n… pour obtenir une table des matières " puts "(utiliser '1. TOC' pour qu'elle soit numérotée" # # Existe-t-il un fichier ERB de même nom ? Si oui, on le prend comme # fichier template # puts "\nTemplate (modèle)" puts "-----------------" TEMPLATE_PATH = if File.exists?(file_with_ext('erb')) puts "Utilisation du template '#{AFFIXE}.erb'." file_with_ext('erb') else puts "On peut créer un modèle HTML avec un fichier #{AFFIXE}.erb contenant '<%= @body %>'." puts "Pour le titre, voir le template de ce dossier (ci-dessous)" puts "Puisqu'il n'est pas défini, je prends 'template.erb' dans mon dossier (#{__dir__})." File.join(__dir__,'template.erb') end # # Existe-t-il du code CSS pour styler le document # puts "\nCode CSS (aspect)" puts "-----------------" CSS_CODE = if File.exists?(file_with_ext('css')) File.read(file_with_ext('css')).force_encoding('utf-8') elsif File.exists?(file_with_ext('sass')) sass_code = File.readfile_with_ext('sass') data_compilation = { line_comments: false, style: :compressed, syntax: :sass } Sass.compile(sass_code, data_compilation) else puts "On peut créer un fichier #{AFFIXE}.css ou #{AFFIXE}.sass pour définir les styles du document final." puts "Si un fichier template #{AFFIXE}.erb est utilisé, ajouter dedans __CSS__ à l'endroit où le code css doit être mis (il possèdera sa balise <style>)." File.read(File.join(__dir__,'github.css')).force_encoding('utf-8') end # # Le template pour obtenir un document complet # template_code = File.read(TEMPLATE_PATH).force_encoding('utf-8') template_code = template_code.sub(/__CSS__/, CSS_CODE) # # Options kramdown # KRAMDOWN_OPTIONS = { header_offset: 0, # pour que '#' fasse un chapter template: "string://#{template_code}", # pour avoir un document entier } str = File.read(FILE_PATH).force_encoding('utf-8') code = Kramdown::Document.new(str, KRAMDOWN_OPTIONS).to_html File.open(HTML_DEST_PATH,'wb'){|f|f.write(code)} if FORMAT_PDF PDF_DEST_PATH = file_with_ext('pdf') res = `/usr/local/bin/wkhtmltopdf "file://#{HTML_DEST_PATH}" "#{PDF_DEST_PATH}" 2>&1` File.delete(HTML_DEST_PATH) end
class ButtonLabel < Draco::Component attribute :text attribute :size, default: 0 attribute :padding, default: 12 end
class CommentsController < ApplicationController before_action :set_comment, only: [:show, :edit, :update, :destroy] # GET /comments # GET /comments.json def index @comments = Comment.page params[:page] end # GET /comments/1 # GET /comments/1.json def show end private # Use callbacks to share common setup or constraints between actions. def set_comment @comment = Comment.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def comment_params params.require(:comment).permit(:id, :post_id, :message, :from, :reactions, :comments) end end
class BuildingsController < ApplicationController before_action :authenticate_user! before_action :set_company before_action :set_building, only: [:show, :edit, :update, :destroy] def index @buildings = @company.buildings.all end def show @meeting_rooms = @building.meeting_rooms end def new @building = @company.buildings.build end def edit @building = @company.buildings.find(params[:id]) end def create @building = @company.buildings.new(building_params) respond_to do |format| if @building.save format.html { redirect_to company_path(@company), notice: 'Building and Meeting Rooms were successfully created.' } else format.html { render :new } end end end def update respond_to do |format| if @building.update(building_params) format.html { redirect_to company_path(@company), notice: 'Building and Meeting Rooms were successfully updated.' } else format.html { render :edit } end end end def destroy @building.destroy respond_to do |format| format.html { redirect_to company_path(@company), notice: 'Building was successfully destroyed.' } end end private def set_company @company = current_user.companies.find(params[:company_id]) end def set_building @building = @company.buildings.find(params[:id]) end def building_params params.require(:building).permit( :name, meeting_rooms_attributes: [:id, :name, :capacity, :_destroy, equipment_attributes: [:id, :_destroy, :name], equipment_meeting_rooms_attributes: [:id, :name, :_destroy, :equipment_id, equipment_attributes: [:id, :_destroy, :name]]] ) end end
class CreateRestaurants < ActiveRecord::Migration[5.1] def change create_table :restaurants do |t| t.string :name t.integer :cuisine_id t.integer :rating t.boolean :accept_10_bis t.float :lat t.float :lon t.string :max_delivery_time t.timestamps end end end
## Generated from bartender.proto for spotify.bartender.proto require "beefcake" module SpotifyWeb module Schema module Bartender module FallbackArtistType TYPE_UNKNOWN_FALLBACK = 0 TYPE_FOLLOWED_ARTIST = 1 TYPE_LOCAL_TRACK_ARTIST = 2 end module RecentArtistType TYPE_UNKNOWN_RECENT_ARTIST = 3 TYPE_LISTENED = 4 TYPE_FOLLOWED = 5 TYPE_LOCAL = 6 end module StoryType TYPE_UNKNOWN_STORY = 0 TYPE_RECOMMENDATION = 1 TYPE_NEW_RELEASE = 2 TYPE_SHARED_ITEM = 3 TYPE_CREATED_ITEM = 4 TYPE_SUBSCRIBED_TO_ITEM = 5 TYPE_FOLLOWED_PROFILE = 6 TYPE_SOCIAL_LISTEN = 7 TYPE_RECENT_STREAM = 8 TYPE_REPRISE = 9 TYPE_CURRENT_FAVORITES = 10 TYPE_RECENT_ARTIST = 11 TYPE_BLAST_FROM_THE_PAST = 12 TYPE_SOCIAL_LISTEN_LOW = 13 end module ReasonType TYPE_UNKNOWN_REASON = 0 TYPE_LISTENED_TO = 1 TYPE_LISTENED_TO2 = 2 TYPE_FOLLOW_USER = 3 TYPE_FOLLOW_ARTIST = 4 TYPE_POPULAR = 5 TYPE_BFTP = 6 TYPE_LOCAL_ARTIST = 7 TYPE_ALGO = 8 end module MetadataType TYPE_UNKNOWN_METADATA = 0 TYPE_SPOTIFY_DATA = 1 TYPE_REVIEW = 2 TYPE_NEWS = 3 TYPE_CONCERT = 4 TYPE_PLAYLIST = 5 end module ScoreType TYPE_UNKNOWN_SCORE = 0 TYPE_FOLLOWER_COUNT = 1 TYPE_STAR_RATING = 2 end module RecLevel REC_LOW = 0 REC_MID = 1 REC_HIGH = 2 end class StoryRequest include Beefcake::Message end class StoryList include Beefcake::Message end class Story include Beefcake::Message end class RichText include Beefcake::Message end class RichTextField include Beefcake::Message end class Reason include Beefcake::Message end class SpotifyLink include Beefcake::Message end class SpotifyAudioPreview include Beefcake::Message end class SpotifyImage include Beefcake::Message end class Metadata include Beefcake::Message end class ConcertData include Beefcake::Message end class Location include Beefcake::Message end class DiscoveredPlaylist include Beefcake::Message end class DiscoverNux include Beefcake::Message end class StoryWithReason include Beefcake::Message end class StoriesWithReasons include Beefcake::Message end class SocialReaction include Beefcake::Message end class UserList include Beefcake::Message end class StoryRequest optional :country, :string, 1 optional :language, :string, 2 optional :device, :string, 3 optional :version, :int32, 4 repeated :fallback_artist, :string, 5 repeated :fallback_artist_type, FallbackArtistType, 6 repeated :recent_artist, :string, 7 repeated :recent_artist_type, RecentArtistType, 8 end class StoryList repeated :stories, Story, 1 optional :has_fallback, :bool, 12 optional :is_last_page, :bool, 2 optional :is_employee, :bool, 3 end class Story optional :version, :int32, 1 optional :story_id, :string, 2 optional :type, StoryType, 3 optional :reason, Reason, 4 optional :recommended_item, SpotifyLink, 5 optional :recommended_item_parent, SpotifyLink, 6 repeated :hero_image, SpotifyImage, 8 optional :metadata, Metadata, 9 optional :reason_text, RichText, 10 repeated :auxiliary_image, SpotifyImage, 11 optional :reason_text_number, :int32, 12 end class RichText optional :text, :string, 1 repeated :fields, RichTextField, 2 end class RichTextField optional :text, :string, 1 optional :uri, :string, 2 optional :url, :string, 3 optional :bold, :bool, 4 optional :italic, :bool, 5 optional :underline, :bool, 6 end class Reason optional :type, ReasonType, 1 repeated :sample_criteria, SpotifyLink, 2 optional :criteria_count, :int32, 3 repeated :reason_type, ReasonType, 4 repeated :date, :int32, 5 end class SpotifyLink optional :uri, :string, 1 optional :display_name, :string, 2 optional :parent, SpotifyLink, 3 repeated :preview, SpotifyAudioPreview, 6 end class SpotifyAudioPreview optional :uri, :string, 1 optional :file_id, :string, 2 end class SpotifyImage optional :uri, :string, 1 optional :file_id, :string, 2 optional :width, :int32, 3 optional :height, :int32, 4 end class Metadata optional :id, :string, 1 optional :app, :string, 2 optional :type, MetadataType, 3 optional :title, :string, 4 optional :summary, :string, 5 optional :favicon_url, :string, 6 optional :external_url, :string, 7 optional :internal_uri, :string, 8 optional :dtpublished, :int32, 9 optional :dtexpiry, :int32, 10 optional :author, SpotifyLink, 11 repeated :score, :int32, 12 repeated :score_type, ScoreType, 13 optional :concert_data, ConcertData, 14 repeated :item_uri, :string, 15 repeated :image, SpotifyImage, 16 optional :bouncer_id, :string, 17 repeated :related_uri, :string, 18 optional :story_uuid, :string, 19 optional :reactions, SocialReaction, 20 end class ConcertData optional :dtstart, :int32, 1 optional :dtend, :int32, 2 optional :location, Location, 3 end class Location optional :name, :string, 1 optional :city, :string, 2 optional :lat, :double, 3 optional :lng, :double, 4 end class DiscoveredPlaylist optional :uri, :string, 1 end class DiscoverNux optional :seen, :int32, 1 end class StoryWithReason optional :story, Story, 1 optional :reason, Reason, 2 repeated :track_uris, :string, 3 optional :level, RecLevel, 4 end class StoriesWithReasons repeated :stories, StoryWithReason, 1 end class SocialReaction optional :id, :string, 1 optional :likes, UserList, 2 optional :streams, UserList, 3 optional :reshares, UserList, 4 end class UserList repeated :usernames, :string, 1 optional :count, :int64, 2 optional :include_requesting_user, :bool, 3 end end end end
DB.create_table? :movements do primary_key :id foreign_key :room_name, :rooms, type: String String :north String :south String :east String :west String :up String :down end #The Movement class, specifies the valid movements in the room class Movement < Sequel::Model def room Room[self.room_name] end end Movement.unrestrict_primary_key
class SendEmailUserRequestWorker include Sidekiq::Worker def perform id @request = Request.find_by id: id @request.send_email_to_user_request if @request.nil? end end
require 'uuidtools' require 'rails/mongoid' class Note include Mongoid::Document include Mongoid::Timestamps::Created store_in collection: "notes", database: "NotesWSD2021" field :_id, type: String, default: ->{ SecureRandom.uuid.to_s} field :title, type: String field :text, type: String field :image, type: String, default: ->{ "" } validates_presence_of :_id, :title, :text validates_uniqueness_of :_id has_many :userNotes end
RSpec.shared_examples "interest acknowledgement worker" do context "with an invalid id" do it "returns :record_not_found when performed" do expect(subject.perform(nil)).to eq :record_not_found end end context "with a valid id" do let :element do described_class.to_s.gsub(/AcknowledgementWorker/,"").underscore end let! :interest do FactoryGirl.create(element) end it "sends the email" do expect{subject.perform(interest.id)}.to change{ActionMailer::Base.deliveries.count}.by(1) end end end
require 'net/https' module Kender # This module abstracts access to GitHub. It's current, sole purpose is to # allow commit statuses to be created. # # See: https://github.com/blog/1227-commit-status-api # module GitHub extend self # Update the commit status for the current HEAD commit. Assumes the working # directory is a git repo and the "origin" remote points to a GitHub repo. # The +state+ variable must be one of :pending, :success or :failure. The # +config+ object must respond to +build_number+, +build_url+ and # +github_auth_token+. # def update_commit_status(state, config) # TODO: Refactor the following code to use gems like git/grit/rugged and # octokit. ~asmith unless config.github_auth_token puts "Skipping setting the status on Github to #{state} because the access token is not configured" return end body = %Q({ "state": "#{state.to_s}", "target_url": "#{config.build_url}", "description": "Continuous integration run #{config.build_number}" }) commit = `git log -1 --format=format:%H` remotes = `git remote --verbose` remote_name = ENV['GITHUB_REMOTE'] || 'origin' unless repo = /^#{remote_name}\s+git@(\w+\.)?github.com:([\w-]+\/[\w-]+)\b/.match(remotes).to_a.last puts "Could not establish GitHub repo name from '#{remote_name}' remote" return end uri = URI("https://api.github.com/repos/#{repo}/statuses/#{commit}?access_token=#{config.github_auth_token}") puts "Setting #{repo} commit #{commit} status to '#{state}' on GitHub" ensure_real_connection do Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http| response = http.post(uri.request_uri, body) unless response.is_a?(Net::HTTPCreated) puts "Setting commit status FAILED", response end end end end def ensure_real_connection if !defined?(WebMock) return yield end if !WebMock.net_connect_allowed? WebMock.allow_net_connect! yield WebMock.disable_net_connect! else yield end end end end
class Route attr_reader :stations def initialize(first_station, last_station) @stations =[first_station, last_station] end def add_station(station) @stations.insert(-2, station) end def remove_station(station) @stations.delete(station) end def print_route puts @stations end end
source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5' # Use postgresql as the database for Active Record gem 'mysql2', '~> 0.3.18' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0' gem "js-routes" #For error viewing gem 'dynamic_form' gem 'protected_attributes' #Gem for rendering images gem "paperclip", "~> 4.2" #Gem for pagination of books gem 'will_paginate', '~> 3.0.6' #Gem for using Ajax js lib script.aculo.us gem 'prototype-rails', github: 'rails/prototype-rails', branch: '4.2' gem 'coffee-script-source', '1.8.0' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' #instead of WEBrick using thin gem 'thin' gem 'pry-rails' end
class Race < ActiveRecord::Base include Coded serialize :body_options def support_class "Race::#{code.titleize.gsub(/\s/,"")}".constantize end def quadruped? code == "centaur" end def description support_class.description end def demonic? group == "demon" end # Gets the skin type (skin, fur, or scale) off of the body options, used in # descriptions def skin return "fur" if body_options[:frame][:fur_colors].present? return "scale" if body_options[:frame][:scale_colors].present? "skin" end # === Random Selection === # Choose a race a random, given the race distribution, with options to # restrict some groups and races. Some races, (demons, dark elves, high # elves, and elf lords) will never be selected at random. # # Available options: # no_furry:true > A furry race will never be chosen # fae_only:true > Only fae and elves will be chosen # from_group:'group' > Only races from the specified group will be chosen # forbidden:['code'] > Never select a race with this code # # You can use the forbidden option in combination with the other options, but # it doesn't make sense to combine the other options. This will enter an # infinite loop if you search in the goblin group, but forbid all goblins. def self.random options = {} searching = true # --- Determine search range given options --- min = 1 max = 100 min = 31 if options[:no_furry] min = 41 if options[:fae_only] if options[:from_group] == "furry" min = 1 max = 30 end if options[:from_group] == "goblin" min = 31 max = 40 end if options[:from_group] == "fae" min = 41 max = 70 end if options[:from_group] == "elf" min = 71 max = 100 end # --- Search within range for non-forbidden race --- while(searching) code = case Roll.random(min, max) # Furry 30% when (1..2) then "rat" # 2% when (3..7) then "lupin" # 5% when (8..12) then "vulpine" # 5% when (13..17) then "selkie" # 5% when (18..22) then "equian" # 5% when (23..26) then "minotaur" # 4% when (27..28) then "centaur" # 2% when (29) then "naga" # 1% when (30) then "dragon" # 1% # Greenskin 10% when (31..38) then "goblin" # 8% when (39..40) then "ogre" # 2% # Lesser fae 30% when (41..47) then "nymph" # 7% when (48..54) then "dryad" # 7% when (55..60) then "gnome" # 6% when (61..66) then "sylph" # 6% when (67..70) then "pixie" # 4% # Humaniod 30% when (71..75) then "neko" # 5% when (76..83) then "wood_elf" # 8% when (84..100) then "elf" # 17% end unless options[:forbidden] && options[:forbidden].member?(code) searching = false end end Race.lookup(code) end # === Race Aspects === def random_aspects { physical: random_aspect(physical), personal: random_aspect(personal), mental: random_aspect(mental), magical: random_aspect(magical) } end # Adds +/-9 to the base value, ensuring it's not below 0 def random_aspect base aspect = base + Roll.random(1,19)-10 (aspect < 0) ? 0 : aspect end # === Race Seed === def self.manufacture_each data data.flatten.each do |datum| Race.manufacture datum end end def self.manufacture data Race.create data end end
module Eventable extend ActiveSupport::Concern included do has_many :events, as: :source after_create :touch_created_event before_destroy :touch_destroyed_event after_save :touch_finished_event after_save :touch_assign_user_event after_save :touch_change_user_event after_save :touch_changed_expiry_on_event end module ClassMethods end private def touch_created_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_destroyed_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_finished_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_changed_expiry_on_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_assign_user_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_change_user_event raise NotImplementedError, 'Must be implemented by subtypes.' end def touch_event(user_id, action, **options) event_parameters = default_parameters(user_id, action).merge(options) events.create(event_parameters) end def default_parameters(user_id, action) { user_id: user_id, action: action } end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "hashicorp/precise64" config.vm.define :nginxCodeTest config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.provider "virtualbox" do |vb| vb.gui = false vb.memory = "1024" end config.vm.synced_folder "salt/roots/", "/srv/salt/" config.vm.provision :salt do |salt| # see: https://github.com/mitchellh/vagrant/issues/5973#issuecomment-137276605 salt.bootstrap_options = "-F -c /tmp/ -P" salt.minion_config = "salt/minion" salt.run_highstate = true salt.verbose = true end end
require 'rails_helper' describe Users::NotificationService do let(:user) { create(:user) } before { ActionMailer::Base.deliveries.clear } it 'notifies a user' do subject.call(user, message: 'msg', link: 'link') expect(user.notifications.size).to eq(1) notification = user.notifications.first expect(notification.user).to eq(user) expect(notification.message).to eq('msg') expect(notification.link).to eq('link') end it 'sends an email for confirmed user emails' do user.update!(email: 'foo@bar.com', confirmed_at: Time.current) subject.call(user, message: 'msg', link: 'link') expect(ActionMailer::Base.deliveries.size).to eq(1) mail = ActionMailer::Base.deliveries.first expect(mail.to).to eq([user.email]) end it "doesn't send an email for unconfirmed user emails" do user.update!(email: 'foo@bar.com') subject.call(user, message: 'msg', link: 'link') expect(ActionMailer::Base.deliveries).to be_empty end end
require 'spec_helper' module Anticipate describe Anticipate do include Anticipate let :anticipator do mock("anticipator") end before do anticipator.stub!(:anticipate).and_yield end describe "trying_every(n).seconds" do it "yields" do called = false trying_every(1).seconds { called = true } called.should be_true end it "overrides the interval" do anticipator.should_receive(:anticipate).with(55, anything) trying_every(55).seconds {} end it "uses the default timeout" do anticipator.should_receive(:anticipate).with(anything, default_tries) trying_every(66).seconds {} end end describe "sleeping(n).seconds.between_tries" do it "yields" do called = false sleeping(1).seconds.between_tries { called = true } called.should be_true end it "overrides the interval" do anticipator.should_receive(:anticipate).with(77, anything) trying_every(77).seconds {} end it "uses the default timeout" do anticipator.should_receive(:anticipate).with(anything, default_tries) trying_every(88).seconds {} end end describe "failing_after(n).tries" do it "yields" do called = false failing_after(1).tries { called = true } called.should be_true end it "overrides the timeout" do anticipator.should_receive(:anticipate).with(anything, 77) failing_after(77).tries {} end it "uses the default interval" do anticipator.should_receive(:anticipate).with(default_interval, anything) failing_after(88).tries {} end end describe "failing_after(x).tries.trying_every(y).seconds" do it "yields" do called = false failing_after(2).tries.trying_every(1).seconds { called = true } called.should be_true end it "overrides the timeout" do anticipator.should_receive(:anticipate).with(anything, 1) failing_after(anything).tries.trying_every(1).seconds {} end it "overrides the interval" do anticipator.should_receive(:anticipate).with(2, anything) failing_after(anything).tries.trying_every(2).seconds {} end end describe "trying_every(x).seconds.failing_after(y).tries" do it "yields" do called = false trying_every(1).seconds.failing_after(2).tries { called = true } called.should be_true end it "overrides the timeout" do anticipator.should_receive(:anticipate).with(anything, 3) trying_every(anything).seconds.failing_after(3).tries {} end it "overrides the interval" do anticipator.should_receive(:anticipate).with(4, anything) trying_every(4).seconds.failing_after(anything).tries {} end end describe "sleeping(x).seconds.between_tries.failing_after(y).tries" do it "yields" do called = false sleeping(1).seconds.between_tries.failing_after(2).tries { called = true } called.should be_true end it "overrides the timeout" do anticipator.should_receive(:anticipate).with(anything, 5) sleeping(anything).seconds.between_tries.failing_after(5).tries {} end it "overrides the interval" do anticipator.should_receive(:anticipate).with(6, anything) trying_every(6).seconds.failing_after(anything).tries {} end end end end
class AddDefaultValueToUserLevelsCompleted < ActiveRecord::Migration def up change_column :user_levels, :completed, :boolean, :default => false end def down change_column :user_levels, :completed, :boolean, nil end end
require_relative 'feature_spec_helper' describe "A user who is not logged in" do it "cannot access the checkout page" do order = create :order item = create :item order.items << item visit order_path(order) expect(page).to_not have_content('Proceed to Checkout') end end describe 'A user who is logged in' do include AdminHelper before do @user = create(:user, email: "t@example.com") @host = create(:user, email: "h@example.com") @order = create(:order, user_id: @user.id) @item = create(:item, user_id: @host.id) @user.orders << @order @order_item = OrderItem.create(order_id: @order.id, item_id: @item.id) @availability = Availability.create(date: Time.now.to_date, order_item_id: @order_item.id) allow_any_instance_of(ApplicationController) .to receive(:order) { @order } log_me_in! visit order_path(@order) end it 'can access the checkout page' do click_on('Enter Payment Info') expect(page).to have_content("Enter Payment Info & Submit Booking Requests") end it 'can get to confirmation screen' do click_on('Enter Payment Info') click_on('Everything good? Submit requests.') expect(page).to have_content('requested') end end
require "rails_helper" RSpec.describe SendParticipantToVoicemail do describe "#call" do it "creates a new call with the existing participant" do user = create(:user) participant = build_stubbed(:participant) stub_const("ConnectCallToVoicemail", spy(call: Result.success)) result = described_class.new( participant: participant, user: user ).call expect(result.success?).to be(true) new_call = Call.find_by(user: user) expect(new_call.in_state?(:no_answer)).to be(true) expect(new_call.participants.first.sid).to eq(participant.sid) end it "creates a new call with an existing contact" do user = create(:user) existing_contact = create(:contact, user: user) incoming_contact = create(:contact, phone_number: existing_contact.phone_number) participant = build_stubbed(:participant, contact: incoming_contact) stub_const("ConnectCallToVoicemail", spy(call: Result.success)) result = described_class.new( participant: participant, user: user ).call expect(result.success?).to be(true) new_call = Call.find_by(user: user) new_participant = new_call.participants.first expect(new_participant.contact).to eq(existing_contact) expect(Contact.for_user(user).count).to eq(1) end it "still creates a no_answer call even if voicemail cannot be connected" do user = create(:user) existing_contact = create(:contact, user: user) incoming_contact = create(:contact, phone_number: existing_contact.phone_number) participant = build_stubbed(:participant, contact: incoming_contact) stub_const("ConnectCallToVoicemail", spy(call: Result.failure("No voicemail"))) result = described_class.new( participant: participant, user: user ).call expect(result.success?).to be(false) new_call = Call.find_by(user: user) expect(new_call.in_state?(:no_answer)).to be(true) end end end
class Objective < ActiveRecord::Base belongs_to :user validates :description, presence:true validates :due, presence:true end
# frozen_string_literal: true desc "Add pokemon from the Johto region" task populate_johto_pokemon: :environment do start_time = Time.now PopulatePokemon::Service.new(152, 251, "Johto").populate time_diff = Time.at(Time.now - start_time).utc.strftime("%T") puts "\nProcess finished in #{time_diff}." end
=begin Base class for all of our profile controllers. This class takes care of setting up @profile_mode (my_home/aboutme), setting up @user (the user who's information we are interested in). This class also handles protecting access to private data (my_home) by insuring appropriate authentication and session ownership. =end class ProfileBaseController < ApplicationController before_filter :setup_at_profile_mode before_filter :require_my_home_mode before_filter :require_my_home_authentication before_filter :setup_at_user before_filter :require_canonical_screen_name before_filter :setup_motto before_filter :profile_web_analytics def setup_at_profile_mode @profile_mode = params[:profile_mode].to_sym end # this filter should be skipped for pages with dual mode (public view and private/edit view) def require_my_home_mode @single_mode_page = true return handle_permission_denied unless my_home? end # my_home pages require the user to be authenticated def require_my_home_authentication my_home? ? require_authentication : true end # find the @user for the page...if my_home use session_user, otherwise find from db def setup_at_user if my_home? @user = session_user else return handle_resource_not_found if params[:screen_name].blank? @user = User.find_by_auth_screen_name_and_account_status params[:screen_name].downcase, :active if @user.blank? @user = User.find_by_auth_screen_name_and_account_status params[:screen_name].downcase, :deactivated if @user render :template => 'common/deactivated_user', :layout => 'application' return end end return handle_resource_not_found("We were unable to find a profile for '#{params[:screen_name]}'") if @user.blank? || @user.proxy_user? end end # ensure that the screen_name in the url matches the screen_name of the @user...if not redirect the url to the canonical version def require_canonical_screen_name return true if params[:screen_name].blank? || params[:screen_name] == @user.screen_name permanent_redirect_to params.merge({:screen_name => @user.screen_name}) return false end def setup_motto a = Answer.first :joins => :question, :conditions => ["answers.user_id = ? AND questions.question_type = 'motto'", @user.id] @motto = a ? a.cleanse_text : nil end helper_method :aboutme? def aboutme? @profile_mode == :aboutme end helper_method :my_home? def my_home? @profile_mode == :my_home end helper_method :dual_mode_page? def dual_mode_page? @single_mode_page != true end helper_method :show_todo_banner? def show_todo_banner? my_home? && user_todo_list.detect { |ut| ut.weight >= 30 } && Time.now < (@user.created_at + 30.days) end # OK, the way this works is that this runs as a before filter; if you need to pass # extra_stack info, skip_before_filter and call this method yourself passing your extra # info as an array of strings. The default stack looks like: # # 'Profile' # 'Self' (if this is a private/editable page) # @user.screen_name # titleized controller name ('Public Profile', 'Editable Profile', 'My Home', 'Friends & Fans', etc) # titleized action name (unless it's index) # extra_stack # "#{params[:per_page]} Per Page" if :per_page is present # "Page #{params[:page]}" if :page is present # def profile_web_analytics(extra_stack=nil) page_stack = ['Profile'] page_stack << 'Self' if my_home? page_stack << @user.screen_name page_stack << profile_controller_name page_stack << params[:action].titleize unless params[:action] == 'index' page_stack << extra_stack page_stack << "#{params[:per_page]} Per Page" unless params[:per_page].blank? page_stack << "Page #{params[:page]}" unless params[:page].blank? page_stack = page_stack.flatten.reject { |s| s.blank? } @web_analytics.page_stack = page_stack @web_analytics.page_name = my_home? ? "Profile: Self: #{@user.screen_name}" : "Profile: #{@user.screen_name}" @web_analytics.page_type = 'Profile Page' # vp hidden pixel tracking for stats @web_analytics.vp_viewed_profile = @user unless my_home? end def profile_controller_name cntlr = params['controller'].gsub(/^profile_(.*)$/) { |s| $1.titleize } cntlr = (aboutme? ? 'Public Profile' : 'Edit Profile') if cntlr == 'Home' cntlr end # only cache the page is it is an aboutme page, has no query string and has no flash def cache_aboutme_page cache_page if aboutme? && request.query_string.blank? && flash.blank? end end
class Utilisateur attr_accessor :nom def initialize(nom) @nom = nom end end victor = Utilisateur.new("Victor Poiraud") puts victor.nom
# frozen_string_literal: true # == Schema Information # # Table name: skills # # id :integer not null, primary key # deleted_at :datetime # skill_description :text # skill_name :string not null # created_at :datetime not null # updated_at :datetime not null # organization_id :integer not null # # Indexes # # index_skills_on_organization_id (organization_id) # # Foreign Keys # # skills_organization_id_fk (organization_id => organizations.id) # class Skill < ApplicationRecord include PgSearch::Model pg_search_scope :search, against: [:skill_name], using: { tsearch: { prefix: true } } validates :skill_name, presence: true validate :grade_descriptors_must_have_unique_marks belongs_to :organization has_many :grade_descriptors, dependent: :destroy, inverse_of: :skill has_many :assignments, dependent: :destroy has_many :subjects, through: :assignments, dependent: :restrict_with_error, inverse_of: :skills scope :by_organization, ->(organization_id) { where organization_id: organization_id } scope :by_subject, ->(subject_id) { joins(:assignments).where(assignments: { subject_id: subject_id }) } accepts_nested_attributes_for :grade_descriptors, update_only: true def grade_descriptors_must_have_unique_marks return if grade_descriptors.empty? return unless duplicates? grade_descriptors.map(&:mark) errors.add :grade_descriptors, 'Grade Descriptors cannot have duplicate marks.' end def can_delete? subjects.count.zero? && Grade.where(skill: self, deleted_at: nil).count.zero? end private def duplicates?(arr) arr.uniq.length != arr.length end end
# GSPlan - Team commitment planning # # Copyright (C) 2008 Jan Schrage <jan@jschrage.de> # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU # General Public License as published by the Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program. # If not, see <http://www.gnu.org/licenses/>. require 'test_helper' class ProjectTest < ActiveSupport::TestCase fixtures :projects, :reviews, :projecttracks def test_validation_empty prj = Project.new( :id => 3 ) assert !prj.valid? assert prj.errors.invalid?(:name) assert prj.errors.invalid?(:planbeg) assert prj.errors.invalid?(:planend) assert prj.errors.invalid?(:planeffort) assert prj.errors.invalid?(:worktype_id) assert prj.errors.invalid?(:country_id) assert prj.errors.invalid?(:employee_id) end def test_validation_name_plan prj = Project.new( :id => 3, :name => "TestProject-1", :planbeg => Date::strptime("2008-08-31"), :planend => Date::strptime("2008-08-01"), :planeffort => "-5", :worktype_id => "1", :country_id => "1", :employee_id => "1") assert !prj.valid? assert prj.errors.invalid?(:name) assert prj.errors.invalid?(:planend) assert prj.errors.invalid?(:planeffort) end def test_valid_project prj = Project.new( :id => 3, :name => "TestProject-3", :planbeg => Date::strptime("2008-08-31"), :planend => Date::strptime("2008-09-30"), :planeffort => "5", :worktype_id => "1", :country_id => "1", :employee_id => "1") assert prj.valid? end def test_update prj = Project.find_by_id(1) prj.planend = Date::strptime("2008-09-30"); assert prj.save! end def test_update_no_reviews_nok prj = Project.find_by_id(2) prj.planend = Date::strptime("2008-09-30"); assert !prj.save end def test_days_committed prj4 = Project.find_by_id(4) assert_equal 12,prj4.days_committed('2008-08-10'.to_date) assert_equal 12,prj4.days_committed prj1 = Project.find_by_id(1) assert_equal 1,prj1.days_committed('2008-08-10'.to_date) assert_equal 1,prj1.days_committed('2008-10-10'.to_date) assert_equal 2,prj1.days_committed end def test_days_booked prj4 = Project.find_by_id(4) assert_equal 9,prj4.days_booked('2008-09-10'.to_date) prj2 = Project.find_by_id(2) assert_equal 5,prj2.days_booked('2008-09-10'.to_date) end end
class CreateAccountCredentials < ActiveRecord::Migration def change create_table :account_credentials do |t| t.string :uid t.string :token t.string :token_secret t.string :account_type t.references :user t.timestamps end end end
# frozen_string_literal: true class CreateScores < ActiveRecord::Migration[5.2] def change create_table :scores do |t| t.date :wakeup_on, null: false t.integer :score, null: false t.string :reason, limit: 50, null: false t.string :cause, limit: 50 t.timestamps end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe ProductController, type: :controller do render_views describe 'GET #show' do let(:product) { create :product } subject { get :show, params: { id: product.id } } context 'show product' do it 'it render show view' do is_expected.to render_template :show end end end end
class PoorPokemon::Pokemon attr_accessor :name, :type1, :type2, :hp, :att, :def, :spAtt, :spDef, :spd, :moves def initialize(arr, flag=false) #flag is for enemy to have perfect stats @name, @type1, @type2, @hp, @att, @def, @spAtt, @spDef, @spd = arr #Determines proper stats #https://www.dragonflycave.com/mechanics/stats #Individual stats (0-15) atkIV = flag ? 15: rand(15) @att += atkIV @att = @att*2+68 defIV = flag ? 15:rand(15) @def += defIV @def = @def*2+68 spdIV = flag ? 15:rand(15) @spd += spdIV @spd = @spd*2+68 spIV = flag ? 15:rand(15) @spAtt += spIV @spAtt = @spAtt*2+68 @spDef += spIV @spDef = @spDef*2+68 #how HP and IV are connected if atkIV%2==1 @hp += 8 end if defIV%2==1 @hp += 4 end if spdIV%2==1 @hp += 2 end if spIV%2==1 @hp += 1 end @hp = @hp*2+110 @moves = [] end def alive? @hp > 0 end def attacks(oppPokemon, move) #dmg calculations attackStat = ["normal", "fighting", "flying", "poison", "ground", "rock", "bug", "ghost"].include?(move.type) ? @att : @spAtt attackPower = move.dmg defenseStat = ["normal", "fighting", "flying", "poison", "ground", "rock", "bug", "ghost"].include?(move.type) ? oppPokemon.def : oppPokemon.spDef randNum = rand(255-217)+217 stab = move.type == @type1 || move.type == @type2 ? 1.5 : 1 weakResist = calcWeakResist(oppPokemon,move) #dmg equation damageTotal = (((((42 * attackStat.to_f * (attackPower.to_f/defenseStat.to_f))/50)+2)*stab.to_f*weakResist.to_f)*randNum.to_f/255).floor #applying dmg move.pp -= 1 oppPokemon.hp -= damageTotal if oppPokemon.hp < 0 oppPokemon.hp = 0 #just in case HP checked end [damageTotal,weakResist] end def calcWeakResist(oppPokemon,move, typeInput=nil) #returns multiplier for attack effectiveness #0.25, 0.5, 1, 2, or 4 # http://unrealitymag.com/wp-content/uploads/2014/11/rby-rules.jpg type = (typeInput || oppPokemon.type1).downcase output = 1; #number returned as modifier case move.type.downcase when 'normal' if ['ghost'].include?(type) output *= 0 end when 'bug' if ['fire','flying',"rock"].include?(type) output*=0.5 elsif ['grass','poison',"psychic"].include?(type) output*=2 end when 'dragon' #No effectiveness when 'ice' if ['ice','water'].include?(type) output*=0.5 elsif ['dragon','flying','grass','ground'].include?(type) output*=2 end when 'fighting' if ['flying','psychic'].include?(type) output*=0.5 elsif ['ice','normal','rock'].include?(type) output*=2 elsif ['ghost'].include?(type) output*=0 end when 'fire' if ['rock','water'].include?(type) output*=0.5 elsif ['bug','grass','ice'].include?(type) output*=2 end when 'flying' if ['electric','rock'].include?(type) output*=0.5 elsif ['bug','fighting',"grass"].include?(type) output*=2 end when 'grass' if ['bug','fire','flying','grass','poison'].include?(type) output*=0.5 elsif ['ground','rock','water'].include?(type) output*=2 end when 'ghost' if ['normal','psychic'].include?(type) output*=0 end when 'ground' if ['grass'].include?(type) output*=0.5 elsif ['electric','fire','poison','rock'].include?(type) output*=2 elsif ['flying'].include?(type) output*=0 end when 'electric' if ['electric','grass'].include?(type) output*=0.5 elsif ['flying','water'].include?(type) output*=2 elsif ['ground'].include?(type) output*=0 end when 'poison' if ['ground','poison','rock'].include?(type) output*=0.5 elsif ['bug','grass'].include?(type) output*=2 end when 'psychic' if ['psychic'].include?(type) output*=0.5 elsif ['fighting','poison'].include?(type) output*=2 end when 'rock' if ['fighting','rock'].include?(type) elsif ['bug','fire','flying','ice'].include?(type) end when 'water' if ['grass','ice'].include?(type) output*=0.5 elsif ['fire','ground','rock'].include?(type) output*=2 end else puts "SOMETHING WENT WRONG WITH TYPE DMG" puts "MoveType: #{move.type.downcase} Type: #{type.downcase}" end if(typeInput.nil? && oppPokemon.type2 !="") output *= calcWeakResist(oppPokemon,move, oppPokemon.type2) end output end def canAttack? #returns true if pokemon has enough PP to attack @moves.any?{|move| move.usable?} end def usableMoves #returns array of usable moves @moves.select{|move| move.usable?} end end
class Anagram attr_accessor :word def initialize(word) @word = word end def match(collection) output = [] collection.each_with_index do |el, idx| if el.split("").sort.join == word.split("").sort.join output << collection[idx] end end output end end
class AddParentToSpreeProperties < ActiveRecord::Migration def change add_reference :spree_properties, :parent, index: true add_column :spree_properties, :position, :integer, default: 0 add_column :spree_properties, :lft, :integer, default: 0 add_column :spree_properties, :rgt, :integer, default: 0 add_index :spree_properties, [:parent_id], :name => 'index_properties_on_parent_id' end end
class Station < ActiveRecord::Base has_many(:gas) end
require "formula" class Rsnapshot < Formula homepage "http://rsnapshot.org" stable do url "http://rsnapshot.org/downloads/rsnapshot-1.3.1.tar.gz" sha1 "a3aa3560dc389e1b00155a5869558522c4a29e05" # Fix pod2man error; docs in HEAD do not have this problem patch :DATA end head "https://github.com/DrHyde/rsnapshot.git" def install system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end end __END__ diff --git a/rsnapshot-program.pl b/rsnapshot-program.pl index dfd7ef6..72de4af 100755 --- a/rsnapshot-program.pl +++ b/rsnapshot-program.pl @@ -6666,6 +6666,8 @@ additional disk space will be taken up. =back +=back + Remember that tabs must separate all elements, and that there must be a trailing slash on the end of every directory.
require 'rails_helper' RSpec.describe Playlist, type: :model do it{ should belong_to :user } it{ should have_many :videos } it{ should validate_presence_of(:name)} end
class CreateArtistBalances < ActiveRecord::Migration[6.1] def change create_table :artist_balances do |t| t.references :artist, null: false, foreign_key: true t.float :balance, null: false t.timestamps end end end
require 'spec_helper' require 'lib/brewery_db/webhooks/shared_examples/events' require 'lib/brewery_db/webhooks/shared_examples/social_accounts' require 'brewery_db/webhooks/brewery' describe BreweryDB::Webhooks::Brewery do let(:model_id) { 'g0jHqt' } let(:response) do yaml = YAML.load_file("spec/support/vcr_cassettes/#{cassette}.yml") JSON.parse(yaml['http_interactions'].first['response']['body']['string'])['data'] end it_behaves_like 'a webhook that updates events' it_behaves_like 'a webhook that updates social accounts' context '#insert' do let(:cassette) { 'brewery_with_associations' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'insert') } context 'before we have guilds' do it 'raises an OrderingError' do VCR.use_cassette(cassette) do expect { webhook.process }.to raise_error(BreweryDB::Webhooks::OrderingError) end end end context 'when we have guilds' do let(:brewery) { Brewery.find_by(brewerydb_id: model_id) } before do response['guilds'].map { |g| Factory(:guild, brewerydb_id: g['id']) } VCR.use_cassette(cassette) { webhook.process } end it 'creates a brewery' do expect(brewery).not_to be_nil end it 'assigns attributes correctly' do expect_equal_attributes(brewery, response) end it 'assigns guilds' do expect(brewery.guilds.count).to eq(response['guilds'].count) end it 'creates social media accounts' do expect(brewery.social_media_accounts.count).to eq(response['socialAccounts'].count) end it 'parses and assigns alternate names' do expect(brewery.alternate_names.presence).to eq(response['alternateNames'].presence) end end end context 'with an existing brewery' do let!(:brewery) { Factory(:brewery, brewerydb_id: model_id) } context '#edit' do let(:cassette) { 'brewery_with_associations' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit') } before do response['guilds'].map { |g| Factory(:guild, brewerydb_id: g['id']) } VCR.use_cassette(cassette) { webhook.process } end it 'reassigns attributes correctly' do expect_equal_attributes(brewery.reload, response) end end context '#guild_insert' do let(:cassette) { 'brewery_guilds' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'guild_insert') } it 'raises an OrderingError if we do not have the guilds yet' do VCR.use_cassette(cassette) do expect { webhook.process }.to raise_error(BreweryDB::Webhooks::OrderingError) end end it 'assigns guilds if we have them' do response.each { |g| Factory(:guild, brewerydb_id: g['id']) } VCR.use_cassette(cassette) { webhook.process } expect(brewery.guilds.count).to eq(response.count) end end context '#guild_delete' do let(:cassette) { 'brewery_guilds' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'guild_delete') } it 'removes guilds from an association' do guild = Factory(:guild) guilds = response.map { |g| Factory(:guild, brewerydb_id: g['id']) } guilds << guild brewery.guilds = guilds VCR.use_cassette(cassette) { webhook.process } brewery.reload expect(brewery.guilds.count).to eq(response.count) expect(brewery.guilds).not_to include(guild) end end context '#guild_edit' do let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'guild_edit') } it 'acts as a noop, returning true' do expect(webhook.process).to be_true end end context '#beer_insert' do let(:cassette) { 'brewery_beers' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'beer_insert') } it 'raises an OrderingError if we do not have the beers yet' do VCR.use_cassette(cassette) do expect { webhook.process }.to raise_error(BreweryDB::Webhooks::OrderingError) end end it 'assigns beers if we have them' do response.each { |b| Factory(:beer, brewerydb_id: b['id']) } VCR.use_cassette(cassette) { webhook.process } expect(brewery.beers.count).to eq(response.count) end end context '#beer_delete' do let(:cassette) { 'brewery_beers' } let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'beer_delete') } it 'removes beers from an association' do beer = Factory(:beer) beers = response.map { |b| Factory(:beer, brewerydb_id: b['id']) } beers << beer brewery.beers = beers VCR.use_cassette(cassette) { webhook.process } brewery.reload expect(brewery.beers.count).to eq(response.count) expect(brewery.beers).not_to include(beer) end end context '#beer_edit' do let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: 'beer_edit') } it 'acts as a noop, returning true' do expect(webhook.process).to be_true end end %w[insert delete edit].each do |action| let(:webhook) { BreweryDB::Webhooks::Brewery.new(id: model_id, action: 'edit', sub_action: "location_#{action}") } context "#location_#{action}" do it 'should be a noop, returning true' do expect(webhook.process).to be_true end end end end def expect_equal_attributes(brewery, attrs) expect(brewery.name).to eq(attrs['name']) expect(brewery.website).to eq(attrs['website']) expect(brewery.description).to eq(attrs['description']) expect(brewery.established).to eq(attrs['established'].to_i) expect(brewery).not_to be_organic expect(brewery.created_at).to eq(Time.zone.parse(attrs['createDate'])) expect(brewery.updated_at).to eq(Time.zone.parse(attrs['updateDate'])) expect(brewery.image_id).to eq(attrs['images']['icon'].match(/upload_(\w+)-icon/)[1]) end end
class StaffAdmin::ChoferesController < StaffAdminController include Geokit::Geocoders add_breadcrumb "index", :staff_admin_choferes_path, :title => "Back to the Index" rescue_from CanCan::AccessDenied do |exception| redirect_to staff_admin_choferes_path, :alert => exception.message end def index @page = "choferes_index" @model = Chofer.new() end def list authorize! :administrate, Chofer choferes = @current_empresa.choferes render json: { model_array: serialize_collection(choferes, ChoferSerializer) } end def new raise params.inspect end def create authorize! :administrate, Chofer m = Chofer.new(chofer_params) m.empresa = @current_empresa if m.valid? m.save end render json: {status: :ok} end def edit @model = Chofer.find_by_id(params[:id]) authorize! :administrate, @model to_render = "edit" respond_to do |format| format.js{ render to_render } end end def update @model = Chofer.find_by_id(params[:id]) authorize! :administrate, @model @model.update_attributes(chofer_params) render json: {status: :ok} end def destroy model = Chofer.find_by_id(params[:id]) authorize! :administrate, model model.destroy redirect_to staff_admin_choferes_path() end private def chofer_params params.require(:chofer).permit! end end
class CreateInvitationsAndGuests < ActiveRecord::Migration[5.1] def change create_table :invitations do |t| t.string :rsvp_code, null: false t.string :addressee, null: false t.string :address_line_1, null: false t.string :address_line_2 t.string :city, null: false t.string :state t.string :country t.string :zip, null: false t.timestamp :sent_at t.timestamp :rsvped_at t.string :rsvp_comment, limit: 1024 t.timestamps end create_table :guests do |t| t.belongs_to :invitation, index: true t.string :name t.string :category, null: false t.timestamp :accepted_at t.timestamp :declined_at t.string :entree_selection t.timestamps end end end
require_relative "Move.rb" class Knight attr_accessor :position def initialize(position=[0, 0]) @position = Move.new(position, -1) end def knight_moves(starting_pos=@position, ending_pos=@position) move_list = [] move_list.push(starting_pos) i = 0 while(move_list[i].position != ending_pos) next_moves = calc_moves(move_list[i].position) next_moves.map! { |position| Move.new(position, i) } next_moves.each do |move| move_list.push(move) if move.position == ending_pos return path_string(move_list, move, i) end end i += 1 end end def calc_moves(starting_pos=[0, 0]) possible_moves = [] changes = [[1,2], [-1,-2], [-1,2], [1,-2], [2,1], [-2,-1], [-2,1], [2,-1]] changes.each do |change| new_position = [] new_position.push(starting_pos[0] + change[0]) new_position.push(starting_pos[1] + change[1]) if (new_position[0] >= 0 && new_position[1] >= 0) && new_position[0] <= 8 && new_position[1] <= 8 possible_moves.push(new_position) end end possible_moves end def path_string(moves, move, counter) j = counter number_of_moves = 0 path = "" while j >= 0 path = "\n#{move.position.inspect}" + path j = move.parent move = moves[j] number_of_moves += 1 end path = "You made it in #{number_of_moves-1} moves! Here's you path:" + path return path end end
module SubstAttr module Substitute module NullObject extend self def build(interface=nil) if interface return strict(interface) end weak end def strict(interface) Mimic.(interface, record: false) end def weak Weak.new end Weak = Mimic::Build.(Object, record: false) do def method_missing(*) end end end end end
require "rails_helper" RSpec.describe Publisher, type: :model do describe ".publish" do let(:compute_engine) { class_double(ComputeEngine).as_stubbed_const } let(:project) { create(:project, id: "13371337-1337-1337-1337-133713371337") } before { allow(compute_engine).to receive(:insert_instance) } subject { described_class.publish(project) } it "calls ComputeEngine.insert_instance" do expect(compute_engine).to( receive(:insert_instance).with( "compositor-13371337-1337-1337-1337-133713371337", "my-compositor-template" ) ) subject end it "creates a new deployment" do expect { subject }.to change { project.deployments.count }.by(1) end end end
FactoryGirl.define do factory :restaurant, :class => Restaurant do |f| f.user_id 0 f.menu_uid 0 f.slug "#{Faker::Name.name}#{Time.now.to_i}" f.name {Faker::Name.name} f.address {Faker::Address.street_address} f.description 'Description' f.phone Faker::Number.number(10) f.email { Faker::Internet.email } f.deliverable true f.shisha_allow true f.disabled false f.created_at Time.now f.updated_at Time.now f.lat 10.7717395 f.lng 106.669815 f.district Faker::Address.street_address f.city {Faker::Address.city} f.postcode {Faker::Address.postcode} f.country {Faker::Address.country} f.direction 'abc' f.service_avg 0 f.quality_avg 0 f.value_avg 0 f.rating_avg 0 f.price Faker::Commerce.price f.menu_name 'Menu name' f.is_owner true f.contact_note 'Contact note' f.suggester_name 'Suggester name' f.website "google.com" f.halal_status "Normal" f.short_address {Faker::Address.street_address} f.special_deal "Special deal" f.facebook_link "facebook.com" f.twitter_link "twitter.com" f.pinterest_link "pinterest_link" f.waiting_for_approve_change true f.suggester_email "abc#{Time.now.to_i}@gmail.com" f.suggester_phone {Faker::PhoneNumber.cell_phone} f.request_approve_photo true f.instagram_link "instagram.com" end end
class ForoMigration < ActiveRecord::Migration def self.up create_table :follows, :force => true do |t| t.references :followable, :null => false t.references :follower, :null => false t.boolean :blocked, :default => false, :null => false t.timestamps end add_index :follows, :follower_id, :name => "fk_follows" add_index :follows, :followable_id, :name => "fk_followables" end def self.down drop_table :follows end end
class RemoveIntroFacFromFaculities < ActiveRecord::Migration[5.1] def change remove_column :faculities, :intro_fac, :text end end
# モンスターの情報を管理するモデル class Monster < ApplicationRecord belongs_to :skill with_options class_name: 'Attribute' do belongs_to :element, foreign_key: :element_id belongs_to :sub_element, foreign_key: :sub_element_id end has_many :monster_species has_many :species, through: :monster_species end
class Post < ApplicationRecord belongs_to :user, optional: true validates :title, presence: true validates :body, presence: true validates :title, uniqueness: { message: "You can't have two posts with the same title." } def content_html Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(body) end end
class Order < ApplicationRecord belongs_to :user belongs_to :item has_one :address_info extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :shipping_area end
class StepsTaken < ActiveRecord::Base validates :steps_taken, presence: {message: 'You must enter the number of steps taken'} validates :date_walked, presence: {message: 'You must enter a date for when you walked'} end
DB = Sequel.connect(ENV['DATABASE_URL']) class MP < Sequel::Model BASE_URL = 'http://www.parliament.nz' def self.parse(name, link, electorate_details, image) last_name, first_name = name.split(',').map(&:strip) electorate, party, list_mp = parse_electorate(electorate_details) new(details_url: link, first_name: first_name, last_name: last_name, party: party, electorate: electorate, list_mp: list_mp, details_url: BASE_URL + link, image_url: image ? BASE_URL + image : nil ) end def self.parse_electorate(electorate_details) party, electorate = electorate_details.split(',').map(&:strip) if electorate == 'List' [nil, party, true] else [electorate, party, false] end end def as_json { id: id, first_name: first_name, last_name: last_name, party: party, electorate: electorate, list_mp: list_mp, details_url: details_url, image_url: image_url } end private def image_from_src(src) BASE_URL + src end end
require 'spec_helper' describe Guard::Notifier::GNTP do let(:fake_gntp) do Class.new do def self.notify(options) end end end before do subject.stub(:require) stub_const 'GNTP', fake_gntp end describe '.available?' do context 'without the silent option' do it 'shows an error message when not available on the host OS' do ::Guard::UI.should_receive(:error).with 'The :gntp notifier runs only on Mac OS X, Linux, FreeBSD, OpenBSD, Solaris and Windows.' RbConfig::CONFIG.should_receive(:[]).with('host_os').and_return 'os2' subject.available? end it 'shows an error message when the gem cannot be loaded' do RbConfig::CONFIG.should_receive(:[]).with('host_os').and_return 'darwin' ::Guard::UI.should_receive(:error).with "Please add \"gem 'ruby_gntp'\" to your Gemfile and run Guard with \"bundle exec\"." subject.should_receive(:require).with('ruby_gntp').and_raise LoadError subject.available? end end context 'with the silent option' do it 'does not show an error message when not available on the host OS' do ::Guard::UI.should_not_receive(:error).with 'The :gntp notifier runs only on Mac OS X, Linux, FreeBSD, OpenBSD, Solaris and Windows.' RbConfig::CONFIG.should_receive(:[]).with('host_os').and_return 'os2' subject.available?(true) end it 'does not show an error message when the gem cannot be loaded' do RbConfig::CONFIG.should_receive(:[]).with('host_os').and_return 'darwin' ::Guard::UI.should_not_receive(:error).with "Please add \"gem 'ruby_gntp'\" to your Gemfile and run Guard with \"bundle exec\"." subject.should_receive(:require).with('ruby_gntp').and_raise LoadError subject.available?(true) end end end describe '.nofify' do let(:gntp) { double('GNTP').as_null_object } before do ::GNTP.stub(:new).and_return gntp end it 'requires the library again' do subject.should_receive(:require).with('ruby_gntp').and_return true subject.notify('success', 'Welcome', 'Welcome to Guard', '/tmp/welcome.png', { }) end it 'opens GNTP as Guard application' do ::GNTP.should_receive(:new).with('Guard', '127.0.0.1', '', 23053) subject.notify('success', 'Welcome', 'Welcome to Guard', '/tmp/welcome.png', { }) end context 'when not registered' do before { Guard::Notifier::GNTP.instance_variable_set :@registered, false } it 'registers the Guard notification types' do gntp.should_receive(:register) subject.notify('success', 'Welcome', 'Welcome to Guard', '/tmp/welcome.png', { }) end end context 'when already registered' do before { Guard::Notifier::GNTP.instance_variable_set :@registered, true } it 'registers the Guard notification types' do gntp.should_not_receive(:register) subject.notify('success', 'Welcome', 'Welcome to Guard', '/tmp/welcome.png', { }) end end context 'without additional options' do it 'shows the notification with the default options' do gntp.should_receive(:notify).with({ :sticky => false, :name => 'success', :title => 'Welcome', :text => 'Welcome to Guard', :icon => '/tmp/welcome.png' }) subject.notify('success', 'Welcome', 'Welcome to Guard', '/tmp/welcome.png', { }) end end context 'with additional options' do it 'can override the default options' do gntp.should_receive(:notify).with({ :sticky => true, :name => 'pending', :title => 'Waiting', :text => 'Waiting for something', :icon => '/tmp/wait.png' }) subject.notify('pending', 'Waiting', 'Waiting for something', '/tmp/wait.png', { :sticky => true, }) end it 'cannot override the core options' do gntp.should_receive(:notify).with({ :sticky => false, :name => 'failed', :title => 'Failed', :text => 'Something failed', :icon => '/tmp/fail.png' }) subject.notify('failed', 'Failed', 'Something failed', '/tmp/fail.png', { :name => 'custom', :title => 'Duplicate title', :text => 'Duplicate text', :icon => 'Duplicate icon' }) end end end end
class MealAvailabilityLocation < ApplicationRecord belongs_to :meal_availability belongs_to :city end
class AddSelectColorSchemaAtIssueToEasySettings < ActiveRecord::Migration def change EasySetting.create(:name => 'issue_color_scheme_for', :value => 'issue_priority') end end
module Api module V1 class CartsController < ApplicationController include ActionController::HttpAuthentication::Token::ControllerMethods before_action :authenticate def add_product result = Cart.add_product(current_user.id, params[:product_id], params[:quantity]) if result[:error].present? render json: {error: result[:error]} else render json: {cart_items: current_user.cart.cart_items } end end def show render json: current_user.cart.cart_items end private def authenticate authenticate_or_request_with_http_token do |token, _options| User.find_by(token: token) end end def current_user @current_user ||= authenticate end end end end
class Image attr_accessor :arr def initialize(arr) @arr = arr end def output_image(arr=@arr) arr.each do |x| x.each do |y| print y end puts end end def inside_matrix?(x, y) x >= 0 && x <= @arr.size && y >= 0 && y <= @arr.first.size - 1 end def manhattan(x1,y1,x2,y2) (x1 - x2).abs + (y1 - y2).abs end def blur(num) new_array = Array.new @arr.each{|i|new_array<<i.dup} @arr.each_with_index do |row, rowIndex| row.each_with_index do |col, colIndex| if (@arr[rowIndex][colIndex] > 0) (0..num).each do |n| (0..num).each do |m| puts "n #{n} m #{m}" if inside_matrix?(rowIndex + n, colIndex + m) && manhattan(rowIndex, colIndex, rowIndex + n, colIndex + m) <= num new_array[rowIndex + n][colIndex + m] = 1 end if inside_matrix?(rowIndex - n, colIndex - m) && manhattan(rowIndex, colIndex, rowIndex - n, colIndex - m) <= num new_array[rowIndex - n][colIndex - m] = 1 end if inside_matrix?(rowIndex + n, colIndex - m) && manhattan(rowIndex, colIndex, rowIndex + n, colIndex - m) <= num new_array[rowIndex + n][colIndex - m] = 1 end if inside_matrix?(rowIndex - n, colIndex + m) && manhattan(rowIndex, colIndex, rowIndex - n, colIndex + m) <= num new_array[rowIndex - n][colIndex + m] = 1 end # if inside_matrix?(rowIndex, colIndex + n) && manhattan(rowIndex, colIndex, rowIndex, colIndex + n) <= num # new_array[rowIndex][colIndex + n] = 1 # end # if inside_matrix?(rowIndex, colIndex - n) && manhattan(rowIndex, colIndex, rowIndex, colIndex - n) <= num # new_array[rowIndex][colIndex - n] = 1 # end # if inside_matrix?(rowIndex - n, colIndex) && manhattan(rowIndex, colIndex, rowIndex - n, colIndex) <= num # new_array[rowIndex - n][colIndex] = 1 # end # if inside_matrix?(rowIndex + n, colIndex) && manhattan(rowIndex, colIndex, rowIndex + n, colIndex) <= num # new_array[rowIndex + n][colIndex] = 1 # end end end end end end @arr = new_array end end image = Image.new([ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ]) image.blur(3) image.output_image
class Interview < ActiveRecord::Base include DateAndTimeMethods belongs_to :user belongs_to :application_record delegate :department, :position, to: :application_record validates :completed, :hired, inclusion: { in: [true, false], message: 'must be true or false' } validates :application_record, :location, :scheduled, :user, presence: true after_create :send_confirmation after_update :resend_confirmation default_scope { order :scheduled } scope :pending, -> { where completed: false } def calendar_title "Interview with #{user.full_name}" end def information(options = {}) info = "#{format_date_time scheduled} at #{location}" info += ": #{user.proper_name}" if options.key? :include_name info end def pending? !completed end private def resend_confirmation if location_changed? || scheduled_changed? JobappsMailer.interview_reschedule self end end def send_confirmation JobappsMailer.interview_confirmation self end end
class StandardsController < InheritedResources::Base def index @standards = Standard.all render component: 'Standards', props: { standards: @standards } end def create @standard = Standard.new(standard_params) if @standard.save render :json => @standard end end def update @standard = Standard.find(params[:id]) if @standard.update(standard_params) render :json => @standard end end def destroy Standard.find(params[:id]).destroy respond_to do |format| format.json { render :json => {}, :status => :no_content } end end private def standard_params params.require(:standard).permit(:name, :id) end end
require 'spec_helper' describe Circuit::Rack::Behavioral do include Rack::Test::Methods include SpecHelpers::MultiSiteHelper class RenderMyMiddlewareBehavior include ::Circuit::Behavior use(Class.new do def initialize(app) @app = app end def call(env) [200, {"Content-Type" => "test/html"}, ["RenderMyMiddlewareBehavior"]] end end) end def app stub_app_with_circuit_site setup_site!(root.site, RenderMyMiddlewareBehavior) end context 'GET /' do get "/" context "status" do subject { last_response.body } it { should include("RenderMyMiddlewareBehavior") } end end context 'GET /foo/bar which does not exist' do get "/foo/bar" subject { last_response } its(:status) { should == 404 } its(:body) { should == "Not Found" } end context 'GET / for site with no root' do def app stub_app_with_circuit_site dup_site_1 end it "should return 404 Not Found" do get "/" last_response.status.should == 404 last_response.body.should == "Not Found" end end context "GET / without site" do def no_site_middleware (Class.new do def initialize(app, site=nil) @app = app; end def call(env) @app.call(env); end end) end def app stub_app_with_circuit_site nil, no_site_middleware end it "should raise a missing site error" do expect { get "/" }.to raise_error(Circuit::Rack::MissingSiteError, "Rack variable rack.circuit.site is missing") end end end
class CreateUoms < ActiveRecord::Migration def self.up create_table :uoms do |t| t.string :uom, :null => false t.string :note t.integer :updated_id # users t.integer :created_id # users t.timestamps end end def self.down drop_table :uoms end end
class CreateAllowedMethods < ActiveRecord::Migration def change create_table :allowed_methods do |t| t.integer :challenge_id, :null => false t.string :method, :null => false t.timestamps end end end
class ProductQuestionsWidenLabel < ActiveRecord::Migration def self.up change_column :product_questions, :label, :string, :limit => 128 end def self.down end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # username :string not null # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime not null # class User < ActiveRecord::Base has_many :leagues has_many :games, through: :leagues, source: :games attr_reader :password validates :username, :password_digest, :session_token, presence: true validates :username, uniqueness: true validates :password, length: {minimum: 6}, allow_nil: :true after_initialize :ensure_session_token before_validation :ensure_session_token_uniqueness def password= (password) self.password_digest = BCrypt::Password.create(password) @password = password end def self.find_by_credentials (username, password) user = User.find_by(username: username) return nil unless user user.password_is?(password) ? user : nil end def password_is? (password) BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_session_token! self.session_token = new_session_token ensure_session_token_uniqueness self.save self.session_token end private def ensure_session_token self.session_token ||= new_session_token end def new_session_token SecureRandom.base64 end def ensure_session_token_uniqueness while User.find_by(session_token: self.session_token) self.session_token = new_session_token end end end
require 'openstudio' require 'json' class OSModel < OpenStudio::Model::Model def add_geometry(coords, gridSize, floors, floorHeight, wwr, name) winH = floorHeight * wwr wallH = (floorHeight - winH) / 2 bldgH = floors * floorHeight wwrSub = (((winH - 0.05)* (gridSize - 0.05)) / (winH * gridSize)) - 0.01 num_surfaces = 0 previous_num_surfaces = 0 # Loop through Floors for floor in (0..floors -1) z0 = floor * floorHeight z1 = z0 + wallH z2 = z1 + winH heights = [z0, z1, z2] heights.each do |z| # Surfaces Count (excludes subsurfaces) before this height is added surface_count = self.getSurfaces.length # puts "surface Count: #{surface_count}" # Height Adjustment if z == z0 || z == z2 height = wallH else height = winH end osPoints = Array.new # Create a new story within the building story = OpenStudio::Model::BuildingStory.new(self) story.setNominalFloortoFloorHeight(height) story.setName("#{name}:Story #{floor+1}") # Loop Trough Sides # loop through 3 iterations of sides for i in (1..coords.length-1) points = createWallGrid(coords[i -1], coords[i], gridSize) points.pop points.each do |point| osPoints.push(OpenStudio::Point3d.new(point[0], point[1], z)) end end points = createWallGrid(coords[coords.length-1], coords[0], gridSize) points.pop points.each do |point| osPoints.push(OpenStudio::Point3d.new(point[0], point[1], z)) end # Identity matrix for setting space origins m = OpenStudio::Matrix.new(4,4,0) m[0,0] = 1 m[1,1] = 1 m[2,2] = 1 m[3,3] = 1 # Minimal zones core_polygon = OpenStudio::Point3dVector.new osPoints.each do |point| core_polygon << point end core_space = OpenStudio::Model::Space::fromFloorPrint(core_polygon, height, self) core_space = core_space.get m[0,3] = osPoints[0].x m[1,3] = osPoints[0].y m[2,3] = osPoints[0].z core_space.changeTransformation(OpenStudio::Transformation.new(m)) core_space.setBuildingStory(story) core_space.setName("#{floor} Core Space") #Set vertical story position story.setNominalZCoordinate(z) #Add Windows to z1 level to surfaces above the surface count if z == z1 self.getSurfaces.each do |s| next if not s.name.to_s.index('SUB') == nil #Ignore Subsurfaces next if not s.name.to_s.split(" ")[1].to_i >= surface_count #Ignore surfaces before this current height new_window = s.setWindowToWallRatio(wwrSub, 0.025, true) end end =begin self.getSurfaces.each do |s| puts s.name next if not s.name.to_s.split(" ")[1].to_i >= surface_count #Ignore surfaces before this current height number = s.name.to_s.split(" ")[1].to_i s.setName("#{name}:material:#{floor}:#{z}: #{number}") puts s.name.to_s.split(" ")[1].to_i end =end end # End of heights Loop end #End of Floors Loop #Put all of the spaces in the model into a vector spaces = OpenStudio::Model::SpaceVector.new self.getSpaces.each { |space| spaces << space } #Match surfaces for each space in the vector OpenStudio::Model.matchSurfaces(spaces) # Match surfaces and sub-surfaces within spaces #Apply a thermal zone to each space in the model if that space has no thermal zone already self.getSpaces.each do |space| if space.thermalZone.empty? new_thermal_zone = OpenStudio::Model::ThermalZone.new(self) space.setThermalZone(new_thermal_zone) end end # end space loop end # end add_geometry method def add_grid_roof(roofCoords, gridSize, height, shape) #Switch Case for Different Shapes case shape when "rect" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0], roofCoords[1], roofCoords[2], gridSize,height, self) when "l" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0][0], roofCoords[0][1], roofCoords[0][2], gridSize,height, self) #Surface count before addition surfaces1 = self.getSurfaces.length construct_grid_roof(roofCoords[1][0], roofCoords[1][1], roofCoords[1][2], gridSize,height, self) when "t" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0][0], roofCoords[0][1], roofCoords[0][2], gridSize,height, self) #Surface count before addition surfaces1 = self.getSurfaces.length construct_grid_roof(roofCoords[1][0], roofCoords[1][1], roofCoords[1][2], gridSize,height, self) when "u" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0][0], roofCoords[0][1], roofCoords[0][2], gridSize,height, self) #Surface count before addition surfaces1 = self.getSurfaces.length construct_grid_roof(roofCoords[1][0], roofCoords[1][1], roofCoords[1][2], gridSize,height, self) #Surface count before addition surfaces2 = self.getSurfaces.length construct_grid_roof(roofCoords[2][0], roofCoords[2][1], roofCoords[2][2], gridSize,height, self) when "h" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0][0], roofCoords[0][1], roofCoords[0][2], gridSize,height, self) #Surface count before addition surfaces1 = self.getSurfaces.length construct_grid_roof(roofCoords[1][0], roofCoords[1][1], roofCoords[1][2], gridSize,height, self) #Surface count before addition surfaces2 = self.getSurfaces.length construct_grid_roof(roofCoords[2][0], roofCoords[2][1], roofCoords[2][2], gridSize,height, self) when "cross" #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(roofCoords[0][0], roofCoords[0][1], roofCoords[0][2], gridSize,height, self) #Surface count before addition surfaces1 = self.getSurfaces.length construct_grid_roof(roofCoords[1][0], roofCoords[1][1], roofCoords[1][2], gridSize,height, self) #Surface count before addition surfaces2 = self.getSurfaces.length construct_grid_roof(roofCoords[2][0], roofCoords[2][1], roofCoords[2][2], gridSize,height, self) else return false end #Put all of the spaces in the model into a vector spaces = OpenStudio::Model::SpaceVector.new self.getSpaces.each { |space| spaces << space } #Match surfaces for each space in the vector OpenStudio::Model.matchSurfaces(spaces) # Match surfaces and sub-surfaces within spaces #Apply a thermal zone to each space in the model if that space has no thermal zone already self.getSpaces.each do |space| if space.thermalZone.empty? new_thermal_zone = OpenStudio::Model::ThermalZone.new(self) space.setThermalZone(new_thermal_zone) end end # end space loop end def add_ground(bounds, gridSize) #Surface count before addition surfaces = self.getSurfaces.length construct_grid_roof(bounds[0], bounds[1], bounds[3], gridSize,0.0, self) #Put all of the spaces in the model into a vector spaces = OpenStudio::Model::SpaceVector.new self.getSpaces.each { |space| spaces << space } #Match surfaces for each space in the vector OpenStudio::Model.matchSurfaces(spaces) # Match surfaces and sub-surfaces within spaces #Apply a thermal zone to each space in the model if that space has no thermal zone already self.getSpaces.each do |space| if space.thermalZone.empty? new_thermal_zone = OpenStudio::Model::ThermalZone.new(self) space.setThermalZone(new_thermal_zone) end end # end space loop end def remove_building_extras(startSurface, endSurface) self.getSurfaces.each do |s| next if not s.surfaceType == "Floor" || s.surfaceType == "RoofCeiling" next if not s.name.to_s.split(" ")[1].to_i.between?(startSurface, endSurface) s.remove end end def remove_grid_roof_interor(startSurface, endSurface) #remove new surfaces but the roof surfaces self.getSurfaces.each do |s| next if s.surfaceType == "RoofCeiling" next if not s.name.to_s.split(" ")[1].to_i.between?(startSurface, endSurface) s.remove end end def remove_ground_extra(startSurface, endSurface) #remove new surfaces but the roof surfaces self.getSurfaces.each do |s| next if s.surfaceType == "Floor" next if not s.name.to_s.split(" ")[1].to_i.between?(startSurface, endSurface) s.remove end end def rename(startSurface, endSurface) self.getSurfaces.each do |s| next if s.surfaceType == "Floor" next if not s.name.to_s.split(" ")[1].to_i.between?(startSurface, endSurface) numb = s.name.to_s.split(" ")[1].to_i s.setName("Building 1 Surface : #{numb}") end end def add_constructions(construction_library_path, degree_to_north) #input error checking if not construction_library_path return false end #make sure the file exists on the filesystem; if it does, open it construction_library_path = OpenStudio::Path.new(construction_library_path) if OpenStudio::exists(construction_library_path) construction_library = OpenStudio::IdfFile::load(construction_library_path, "OpenStudio".to_IddFileType).get else puts "#{construction_library_path} couldn't be found" end #add the objects in the construction library to the model self.addObjects(construction_library.objects) #apply the newly-added construction set to the model building = self.getBuilding default_construction_set = OpenStudio::Model::getDefaultConstructionSets(self)[0] building.setDefaultConstructionSet(default_construction_set) building.setNorthAxis(degree_to_north) # OpenStudio::model::RoofVegetation::RoofVegetation(self ,"Smooth") end #end Constructions def num_surfaces() return self.getSurfaces.length end def set_runperiod(day, month) #From https://github.com/buildsci/openstudio_scripts/blob/master/newMethods/newMethods.rb runPeriod = self.getRunPeriod runPeriod.setEndDayOfMonth(day) runPeriod.setEndMonth(month) end def save_openstudio_osm(dir, name) save_path = OpenStudio::Path.new("#{dir}/#{name}") self.save(save_path,true) end def translate_to_energyplus_and_save_idf(dir,name) #make a forward translator and convert openstudio model to energyplus forward_translator = OpenStudio::EnergyPlus::ForwardTranslator.new() workspace = forward_translator.translateModel(self) idf_save_path = OpenStudio::Path.new("#{dir}/#{name}") workspace.save(idf_save_path,true) end def add_temperature_variable(dir, name) # Open a file and read from it\nOutput:Variable,*,Surface Outside Face Convection Heat Gain Rate,hourly; !- Zone Average [W]\nOutput:Variable,*,Surface Outside Face Convection Heat Gain Rate per Area,hourly; !- Zone Average [W/m2]\nOutput:Variable,*,Surface Outside Face Solar Radiation Heat Gain Rate,hourly; !- Zone Average [W]\nOutput:Variable,*,Surface Outside Face Solar Radiation Heat Gain Rate per Area,hourly; !- Zone Average [W/m2]\nOutput:Variable,*,Surface Outside Face Conduction Heat Loss Rate,hourly; !- Zone Average [W]\nOutput:Variable,*,Surface Outside Face Conduction Heat Transfer Rate per Area,hourly; !- Zone Average [W/m2] File.open("#{dir}#{name}.idf", 'a') {|f| f.write("Output:Variable,*,Surface Outside Face Temperature,hourly; !- Zone Average [C]") } end def set_solarDist() simControl = self.getSimulationControl simControl.setSolarDistribution("FullExteriorWithReflections") end def get_surface_numbers(startSurface, endSurface, type) surfaceArray = [] self.getSurfaces.each do |s| next if not s.surfaceType == type next if not s.name.to_s.split(" ")[1].to_i.between?(startSurface, endSurface) surfaceArray.push(s.name.to_s.split(" ")[1].to_i) end return surfaceArray end end def count_surfaces(model) count = 0 puts "surfaces Length #{model.getSurfaces.length}" model.getSurfaces.each do |s| next if not s.name.to_s.index('SUB') == nil count += 1 end puts "count : #{count}" return count end def distanceFormula(x1,y1,x2,y2) return Math.sqrt(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1))) end def findRotation(pt1, pt2) deltaX = pt2[0] - pt1[0] deltaY = pt2[1] - pt1[1] theta = Math.atan2(deltaY, deltaX) return theta end #Do Grid for One Length def get_num_patches(coords, gridSize) numb_patches = 0 orgGridSize = gridSize for pt in (1..coords.length-1) gridSize = orgGridSize sideLength = distanceFormula(coords[pt-1][0],coords[pt-1][1],coords[pt][0],coords[pt][1]) gridLength = ((sideLength % gridSize) / ((sideLength / gridSize).to_i)) + gridSize #Number of Grid Checks if (gridSize * 2) > sideLength gridLength = sideLength / 2 gridSize = gridLength end iterator = (sideLength / gridSize).to_i numb_patches += iterator end gridSize = orgGridSize sideLength = distanceFormula(coords[coords.length-1][0],coords[coords.length-1][1],coords[0][0],coords[0][1]) #Number of Grid Checks if (gridSize * 2) > sideLength gridLength = sideLength / 2 gridSize = gridLength end iterator = (sideLength / gridSize).to_i numb_patches +=iterator return numb_patches end def createWallGrid(point1, point2, gridSize) sideLength = distanceFormula(point1[0],point1[1],point2[0],point2[1]) gridLength = ((sideLength % gridSize) / ((sideLength / gridSize).to_i)) + gridSize #Number of Grid Checks if (gridSize * 2) > sideLength gridLength = sideLength / 2 gridSize = gridLength end #Deltas and Iterators deltaX = point2[0] - point1[0] deltaY = point2[1] - point1[1] xIt = deltaX / (sideLength / gridSize).to_i yIt = deltaY / (sideLength / gridSize).to_i iterator = (sideLength / gridSize).to_i #Infinity Check #Zero Check points = Array.new #Loop Wall for i in (0..iterator) points[i] = [point1[0] + (xIt * i), point1[1] + (yIt * i)] end return points end def all_the_grids(pt0, pt1, pt3, gridSize) all_grids = Array.new() #Side 1 l0 = distanceFormula(pt0[0], pt0[1], pt1[0], pt1[1]); gridLength0 = ((l0 % gridSize) / ((l0 / gridSize).to_i)) + gridSize #Make sure of a min of 2 patches gridSize0 = gridSize if (gridSize * 2) > l0 gridLength0 = l0/2 gridSize0 = gridLength0 end deltaX0 = pt1[0] - pt0[0] deltaY0 = pt1[1] - pt0[1] xIt0 = deltaX0 / (l0/gridSize0).to_i yIt0 = deltaY0 / (l0/gridSize0).to_i iterator0 = (l0/gridSize0).to_i #Side 4 l3 = distanceFormula(pt0[0], pt0[1], pt3[0], pt3[1]); gridLength3 = ((l3 % gridSize) / ((l3 / gridSize).to_i)) + gridSize #Make sure of a min of 2 patches gridSize3 = gridSize if (gridSize * 2) > l3 gridLength3 = l3/2 gridSize3 = gridLength3 end deltaX3 = pt0[0] - pt3[0] deltaY3 = pt0[1] - pt3[1] xIt3 = deltaX0 / (l3/gridSize3).to_i yIt3 = deltaY0 / (l3/gridSize3).to_i iterator3 = (l3/gridSize3).to_i #Rotations theta0 = findRotation(pt0, pt1) theta3 = findRotation(pt0, pt3) for j in (0..iterator3-1) point0 = [pt0[0] + (gridLength3 * j * Math.cos(theta3)), pt0[1] + (gridLength3 * j * Math.sin(theta3))]; point3 = [pt0[0] + (gridLength3 * (j + 1) * Math.cos(theta3)), pt0[1] + (gridLength3 * (j + 1) * Math.sin(theta3))]; for i in(0..iterator0-1) point0_1 = [point0[0] + (gridLength0 * i * Math.cos(theta0)), point0[1] + (gridLength0 * i * Math.sin(theta0))]; point1 = [point0[0] + (gridLength0 * (i + 1) * Math.cos(theta0)), point0[1] + (gridLength0 * (i + 1) * Math.sin(theta0))]; point2 = [point3[0] + (gridLength0 * (i + 1) * Math.cos(theta0)), point3[1] + (gridLength0 * (i + 1) * Math.sin(theta0))]; point3_1 = [point3[0] + (gridLength0 * i * Math.cos(theta0)), point3[1] + (gridLength0 * i * Math.sin(theta0))]; all_grids.push([point0_1, point1, point2,point3_1]) end end return all_grids end def construct_grid_roof(pt1, pt2, pt3, gridSize, height, model) grid_points = all_the_grids(pt1, pt2, pt3, gridSize) #all_the_grids(coords[0], coords[1], coords[3], gridSize) #loop through grid points grid_points.each do |square| os_points = Array.new #Loop through square to make footprint square.each do |sq| os_points.push(OpenStudio::Point3d.new(sq[0], sq[1], height-0.1)) end # Identity matrix for setting space origins m = OpenStudio::Matrix.new(4,4,0) m[0,0] = 1 m[1,1] = 1 m[2,2] = 1 m[3,3] = 1 # Minimal zones core_polygon = OpenStudio::Point3dVector.new os_points.each do |point| core_polygon << point end core_space = OpenStudio::Model::Space::fromFloorPrint(core_polygon, 0.1, model) core_space = core_space.get m[0,3] = os_points[0].x m[1,3] = os_points[0].y m[2,3] = os_points[0].z core_space.changeTransformation(OpenStudio::Transformation.new(m)) core_space.setName("Roof") end end file = File.read("osmObj.json") buildings = JSON.parse(file) startSurface = [] roofSurface = [] endSurface = [] #initialize and make OSModel model = OSModel.new #Loop through Buildings buildings['buildings'].each do |building| startSurface.push(model.num_surfaces) model.add_geometry(building['coords'], building['gridSize'], building['floors'], building['floorHeight'], building['wwr'], building['name']) roofSurface.push(model.num_surfaces) model.add_grid_roof(building['roofCoords'],building['gridSize'], building['height'],building['shape']) endSurface.push(model.num_surfaces) end puts "start Surf: #{startSurface}" puts "roof Surf: #{roofSurface}" puts "end Surf: #{endSurface}" startGround = [] endGround = [] # Add Ground startGround.push(model.num_surfaces) model.add_ground(buildings['ground']['bounds']['inner'], buildings['ground']['innerGridSize']) endGround.push(model.num_surfaces) startGround.push(model.num_surfaces) model.add_ground(buildings['ground']['bounds']['top'], buildings['ground']['gridSize']) endGround.push(model.num_surfaces) startGround.push(model.num_surfaces) model.add_ground(buildings['ground']['bounds']['left'], buildings['ground']['gridSize']) endGround.push(model.num_surfaces) startGround.push(model.num_surfaces) model.add_ground(buildings['ground']['bounds']['right'], buildings['ground']['gridSize']) endGround.push(model.num_surfaces) startGround.push(model.num_surfaces) model.add_ground(buildings['ground']['bounds']['bottom'], buildings['ground']['gridSize']) endGround.push(model.num_surfaces) puts "start Ground Array : #{startGround}" puts "End Ground Array : #{endGround}" #Name Primary Surfaces in Model #Walls =begin wallsFloor0Z0 = model.get_surface_numbers(0, 26, "Wall") wallsFloor0Z1 = model.get_surface_numbers(26, 52, "Wall") wallsFloor0Z2 = model.get_surface_numbers(52, 78, "Wall") wallsFloor1Z0 = model.get_surface_numbers(78, 104, "Wall") wallsFloor1Z1 = model.get_surface_numbers(104, 130, "Wall") wallsFloor1Z2 = model.get_surface_numbers(130, 156, "Wall") wallsFloor2Z0 = model.get_surface_numbers(156, 182, "Wall") wallsFloor2Z1 = model.get_surface_numbers(182, 208, "Wall") wallsFloor2Z2 = model.get_surface_numbers(208, 234, "Wall") #Roof roofSegment1 = model.get_surface_numbers(234 + 1, 444, "RoofCeiling") #Ground innerGround = model.get_surface_numbers(444+ 1, 828, "RoofCeiling") topGround = model.get_surface_numbers(828+ 1, 876, "RoofCeiling") leftGround = model.get_surface_numbers(876+ 1, 936, "RoofCeiling") rightGround = model.get_surface_numbers(936+ 1, 996, "RoofCeiling") bottomGround = model.get_surface_numbers(996+ 1, 1080, "RoofCeiling") puts "wallsFloor0Z0:#{wallsFloor0Z0}" puts "wallsFloor0Z1:#{wallsFloor0Z1}" puts "wallsFloor0Z2:#{wallsFloor0Z2}" puts "wallsFloor1Z0:#{wallsFloor1Z0}" puts "wallsFloor1Z1:#{wallsFloor1Z1}" puts "wallsFloor1Z2:#{wallsFloor1Z2}" puts "wallsFloor2Z0:#{wallsFloor2Z0}" puts "wallsFloor2Z1:#{wallsFloor2Z1}" puts "wallsFloor2Z2:#{wallsFloor2Z2}" puts "roofSegment1:#{roofSegment1}" puts "innerGround:#{innerGround}" puts "topGround:#{topGround}" puts "leftGround:#{leftGround}" puts "rightGround:#{rightGround}" puts "bottomGround:#{bottomGround}" =end #Remove Interiors, Extras, etc #model.remove_building_extras(startSurface[0], roofSurface[0]-1) #model.remove_grid_roof_interor(roofSurface[0], endSurface[0]) #model.remove_building_extras(startSurface[1], roofSurface[1]-1) #model.remove_grid_roof_interor(roof Surface[1], endSurface[1]) =begin model.remove_ground_extra(startGround[0], endGround[0]) model.remove_ground_extra(startGround[1], endGround[1]) model.remove_ground_extra(startGround[2], endGround[2]) model.remove_ground_extra(startGround[3], endGround[3]) model.remove_ground_extra(startGround[4], endGround[4]) =end #Rename #model.rename(startSurface[0], roofSurface[0]-1, "Building 1") #Set Simulation Aspects model.add_constructions(buildings['construction'], buildings['orientation']) model.set_runperiod(buildings['runPeriod']['day'], buildings['runPeriod']['month']); model.set_solarDist(); #Save and Translate and Adjust model.save_openstudio_osm('./', buildings['fileName']) model.translate_to_energyplus_and_save_idf('./', buildings['fileName']) model.add_temperature_variable('./', buildings['fileName'])
class Box < ApplicationRecord # has_many :collections # has_many :recipes, through: :collections has_many :recipes end
#!/usr/bin/ruby # On Red Hat /etc/localtime is a copy of the relevant timezone file from # /usr/share/zoneinfo. If Red Hat releases updated timezone data (via a # new tzdata RPM) the files in /usr/share/zoneinfo get updated, but # /etc/localtime does not. So we have etch manage /etc/localtime, this # script feeding the /u/s/z file to etch. # FIXME: This is reading /u/s/z on the server, which kinda defeats the purpose if @groups.include?('uspacific') @contents << IO.read('/usr/share/zoneinfo/US/Pacific') else @contents << IO.read('/usr/share/zoneinfo/UTC') end
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do describe '#treat_empty_as_nil?', active_record: true do context 'with a nullable field' do subject do RailsAdmin.config('Team').fields.detect do |f| f.name == :name end.with(object: Team.new) end it 'is true' do expect(subject.treat_empty_as_nil?).to be true end end context 'with a non-nullable field' do subject do RailsAdmin.config('Team').fields.detect do |f| f.name == :manager end.with(object: Team.new) end it 'is false' do expect(subject.treat_empty_as_nil?).to be false end end end describe '#parse_input' do subject do RailsAdmin.config('FieldTest').fields.detect do |f| f.name == :string_field end.with(object: FieldTest.new) end context 'with treat_empty_as_nil being true' do before do RailsAdmin.config FieldTest do field :string_field do treat_empty_as_nil true end end end context 'when value is empty' do let(:params) { {string_field: ''} } it 'makes the value nil' do subject.parse_input(params) expect(params.key?(:string_field)).to be true expect(params[:string_field]).to be nil end end context 'when value does not exist in params' do let(:params) { {} } it 'does not touch params' do subject.parse_input(params) expect(params.key?(:string_field)).to be false end end end context 'with treat_empty_as_nil being false' do before do RailsAdmin.config FieldTest do field :string_field do treat_empty_as_nil false end end end let(:params) { {string_field: ''} } it 'keeps the value untouched' do subject.parse_input(params) expect(params.key?(:string_field)).to be true expect(params[:string_field]).to eq '' end end end end
require 'vanagon/engine/base' require 'vanagon/logger' require 'yaml' ### Note this class is deprecated in favor of using the ABS Engine. The pooler has changed it's API with regards to # getting VMs for ondemand provisioning and would need to be updated here. # See DIO-1066 class Vanagon class Engine class Pooler < Base attr_reader :token # The vmpooler_template is required to use the pooler engine def initialize(platform, target = nil, **opts) super @available_poolers = %w[ https://vmpooler-prod.k8s.infracore.puppet.net https://nspooler-prod.k8s.infracore.puppet.net ] @token = load_token @required_attributes << "vmpooler_template" end # Get the engine name def name 'pooler' end # Return the vmpooler template name to build on def build_host_name if @build_host_template_name.nil? validate_platform @build_host_template_name = @platform.vmpooler_template end @build_host_template_name end # Retrieve the pooler token from an environment variable # ("VMPOOLER_TOKEN") or from a number of potential configuration # files (~/.vanagon-token or ~/.vmfloaty.yml). # @return [String, nil] token for use with the vmpooler def load_token ENV['VMPOOLER_TOKEN'] || token_from_file end # a wrapper method around retrieving a vmpooler token, # with an explicitly ordered preference for a Vanagon-specific # token file or a preexisting vmfoaty yaml file. # # @return [String, nil] token for use with the vmpooler def token_from_file read_vanagon_token || read_vmfloaty_token end private :token_from_file # Read a vmpooler token from the plaintext vanagon-token file, # as outlined in the project README. # # @return [String, nil] the vanagon vmpooler token value def read_vanagon_token(path = "~/.vanagon-token") absolute_path = File.expand_path(path) return nil unless File.exist?(absolute_path) VanagonLogger.info "Reading vmpooler token from: #{path}" File.read(absolute_path).chomp end private :read_vanagon_token # Read a vmpooler token from the yaml formatted vmfloaty config, # as outlined by the vmfloaty project: # https://github.com/puppetlabs/vmfloaty # # @return [String, nil] the vmfloaty vmpooler token value def read_vmfloaty_token(path = "~/.vmfloaty.yml") absolute_path = File.expand_path(path) return nil unless File.exist?(absolute_path) VanagonLogger.info "Reading vmpooler token from: #{path}" YAML.load_file(absolute_path)['token'] end private :read_vmfloaty_token # This method is used to obtain a vm to build upon using Puppet's internal # vmpooler (https://github.com/puppetlabs/vmpooler) or other pooler technologies # leveraging the same API # @raise [Vanagon::Error] if a target cannot be obtained def select_target @available_poolers.each do |current_pooler| @pooler = select_target_from(current_pooler) break unless @pooler.empty? end raise Vanagon::Error, "Something went wrong getting a target vm to build on, maybe the pool for #{build_host_name} is empty?" if @pooler.empty? end # Attempt to provision a host from a specific pooler. # def select_target_from(pooler) response = Vanagon::Utilities.http_request( "#{pooler}/vm", 'POST', "{\"#{build_host_name}\":\"1\"}", { 'X-AUTH-TOKEN' => @token } ) if response["ok"] @target = response[build_host_name]['hostname'] # The nspooler does not use 'domain' in the response: 'hostname' just returns the fqdn. # in the future we should make the two APIs the same in this sense, but for now, just check # if 'domain' is a thing and use it if so. if response['domain'] @target += ".#{response['domain']}" end Vanagon::Driver.logger.info "Reserving #{@target} (#{build_host_name}) [#{@token ? 'token used' : 'no token used'}]" add_tags_to_target(pooler, response[build_host_name]['hostname']) else pooler = '' end pooler end # Add tags to a provisioned target using the pooler API # def add_tags_to_target(pooler, hostname) tags = { 'tags' => { 'jenkins_build_url' => ENV['BUILD_URL'], 'project' => ENV['JOB_NAME'] || 'vanagon', 'created_by' => ENV['USER'] || ENV['USERNAME'] || 'unknown' } } Vanagon::Utilities.http_request( "#{pooler}/vm/#{hostname}", 'PUT', tags.to_json, { 'X-AUTH-TOKEN' => @token } ) end # This method is used to tell the vmpooler to delete the instance of the # vm that was being used so the pool can be replenished. def teardown response = Vanagon::Utilities.http_request( "#{@pooler}/vm/#{@target}", "DELETE", nil, { 'X-AUTH-TOKEN' => @token } ) if response and response["ok"] Vanagon::Driver.logger.info "#{@target} has been destroyed" VanagonLogger.info "#{@target} has been destroyed" else Vanagon::Driver.logger.info "#{@target} could not be destroyed" VanagonLogger.info "#{@target} could not be destroyed" end rescue Vanagon::Error => e Vanagon::Driver.logger.info "#{@target} could not be destroyed (#{e.message})" VanagonLogger.error "#{@target} could not be destroyed (#{e.message})" end end end end
class CreatePermissions < ActiveRecord::Migration def change create_table :permissions do |t| t.string :subject_class, limit: 60, default: "" t.string :action, null: false, limit: 50, default:"" t.string :name, null: false, limit: 50, default:"" t.timestamps end create_table :permissions_roles, :id => false do |t| t.references :role, :permission end add_index :permissions_roles, [:permission_id, :role_id] end end
class PostPolicy < ApplicationPolicy def index? true end def destroy? user.present? && (record.user == user || user.admin? || user.moderator? ) end class Scope attr_reader :user, :scope def initialize(user, scope) @user = user @scope = scope end def resolve if @user.nil? raise Pundit::NotAuthorizedError, "Must be logged in." elsif @user.admin? || @user.moderator? @posts = Post.all else @user && (@record.user == @user) @posts = @user.posts end end end end
# Copyright (C) 2011-2014 Tanaka Akira <akr@fsij.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Tb::Cmd.subcommands << 'newfield' Tb::Cmd.default_option[:opt_newfield_ruby] = nil def (Tb::Cmd).op_newfield op = OptionParser.new op.banner = "Usage: tb newfield [OPTS] FIELD VALUE [TABLE]\n" + "Add a field." define_common_option(op, "ho", "--no-pager") op.def_option('--ruby RUBY-EXP', 'ruby expression to generate values. A hash is given as _. no VALUE argument.') {|ruby_exp| Tb::Cmd.opt_newfield_ruby = ruby_exp } op end Tb::Cmd.def_vhelp('newfield', <<'End') Example: % cat tst.csv a,b,c 0,1,2 4,5,6 % tb newfield foo bar tst.csv foo,a,b,c bar,0,1,2 bar,4,5,6 % tb newfield foo --ruby '_["b"] + _["c"]' tst.csv foo,a,b,c 12,0,1,2 56,4,5,6 End def (Tb::Cmd).main_newfield(argv) op_newfield.parse!(argv) exit_if_help('newfield') err('no new field name given.') if argv.empty? field = argv.shift if Tb::Cmd.opt_newfield_ruby rubyexp = Tb::Cmd.opt_newfield_ruby pr = eval("lambda {|_| #{rubyexp} }") else err('no value given.') if argv.empty? value = argv.shift pr = lambda {|_| value } end argv = ['-'] if argv.empty? creader = Tb::CatReader.open(argv, Tb::Cmd.opt_N) er = creader.newfield(field) {|pairs| pr.call(pairs) } output_tbenum(er) end
class MixTask < Task def initialize super('Mix that batter up!') end def time_required 3 # Mix for 3 minutes end end
require 'spec_helper' require 'animal_quiz/property' require 'animal_quiz/question' require 'animal_quiz/question_list' require 'support/animal_properties_context' require 'support/animal_questions_context' describe AnimalQuiz::QuestionList do include_context 'Animal Properties' include_context 'Animal Questions' include_context 'Animals' let (:questions) { [question1, question3] } let (:animals) { [elephant, mouse, mammoth] } subject { described_class.new questions } it 'has questions' do expect(subject.questions).to eq(questions) end it 'returns the most likely question for the possible animals' do expect(subject.get_question(animals)).to eq(question3) end it 'adds a question' do subject.add(question2) expect(subject.questions).to include(question1, question2, question3) end it 'marks questions as used when they are retrieved' do subject.get_question(animals) expect(subject.used_questions).to include(question3) end it 'resets questions to the original state with none being used' do expect(subject.questions).to include(question3) subject.get_question(animals) expect(subject.used_questions).to include(question3) expect(subject.questions).not_to include(question3) subject.reset expect(subject.used_questions).to eq([]) expect(subject.questions).to include(question3) end end
# Modelo MotivoConsulta # Tabla motivos_consulta # Campos id:integer # motivo:string # created_at:datetime # updated_at:datetime class MotivoConsulta < ActiveRecord::Base has_many :motivos_episodio_consulta, inverse_of: :motivo, dependent: :destroy validates :motivo, presence: true, uniqueness: true end
require 'http_parser.rb' require 'websocket_parser' require 'base64' require 'digest/sha1' require 'securerandom' module Microprocess use "http/5" def ws_server(ip, port) server(ip, port, WS::Server) end def ws_connect(ip, port) connect(ip, port, WS::Client::Socket) end module WS PROTOCOL_VERSION = 13 # RFC 6455 GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" module Client class Socket < Stream def initialize(io) super(io) @httpparser = Http::Parser.new @httpparser.header_value_type = :strings @httpparser.on_headers_complete = proc do if @httpparser.status_code == 101 mode_wsparser! emit(:upgrade) else emit(:error) end end @wsparser = WebSocket::Parser.new @wsparser.on_message do |message| emit(:message, message) end @wsparser.on_error do |message| emit(:error, message) close end @wsparser.on_close do |status, message| write_close WebSocket::Message.close.to_data end @wsparser.on_ping do |payload| emit(:ping, payload) write WebSocket::Message.pong(payload).to_data end mode_httpparser! end def mode_httpparser! events.delete(:chunk) on(:chunk) do |chunk| begin @httpparser << chunk rescue => e p e.to_s emit(:error, e.to_s) close end end end def mode_wsparser! events.delete(:chunk) on(:chunk) do |chunk| @wsparser << chunk.dup end end def generate_key Base64.strict_encode64(SecureRandom.random_bytes(16)) end def upgrate(path, &block) write "GET #{path} HTTP/1.1\r\n" write "Host: server.example.com\r\n" write "Upgrade: websocket\r\n" write "Connection: upgrade\r\n" write "Sec-WebSocket-Key: #{generate_key}\r\n" write "Sec-WebSocket-Version: #{PROTOCOL_VERSION}\r\n" write "Origin: http://example.com\r\n" write "\r\n" end def message(str) write WebSocket::Message.new(str).to_data end end end class Server < HTTP::Server def read_nonblock sock, addrinfo = @io.accept_nonblock sock = Server::Socket.new(sock) emit(:accept, sock) 0 rescue IO::WaitReadable nil end end class Server::Socket < Stream def initialize(io) super(io) @httpparser = Http::Parser.new @httpparser.header_value_type = :strings @httpparser.on_headers_complete = proc do req = Request.new(@httpparser.headers) req.version = @httpparser.http_version.join('.') req.method = @httpparser.http_method req.request_url = @httpparser.request_url if req.upgrade = @httpparser.upgrade? req.upgrade_data = @httpparser.upgrade_data end req.parse_request_url res = WS::Response.new res.on(:done) do write res.read if res.status == 101 mode_wsparser! emit(:upgrade, req) end end emit(:request, req, res) end @wsparser = WebSocket::Parser.new @wsparser.on_message do |message| emit(:message, message) end @wsparser.on_error do |message| emit(:error, message) close end @wsparser.on_close do |status, message| write_close WebSocket::Message.close.to_data end @wsparser.on_ping do |payload| emit(:ping, payload) write WebSocket::Message.pong(payload).to_data end mode_httpparser! end def mode_httpparser! events.delete(:chunk) on(:chunk) do |chunk| begin @httpparser << chunk rescue => e p e.to_s emit(:error, e.to_s) close end end end def mode_wsparser! events.delete(:chunk) on(:chunk) do |chunk| @wsparser << chunk.dup end end def message(str) write WebSocket::Message.new(str).to_data end end class Request include Events def initialize(headers) @headers = {} headers.each do |k,v| @headers[k.downcase] = v end end attr_reader :headers attr_accessor :request_url attr_accessor :method attr_accessor :version attr_accessor :keep_alive attr_accessor :upgrade attr_accessor :upgrade_data def parse_request_url uri = URI.parse(@request_url) @path = uri.path @query = uri.query end attr_accessor :path attr_accessor :query def upgrade? if @headers['upgrade'].downcase != 'websocket' @error = 'connection upgrade is not for websocket' return false end if @headers['sec-websocket-version'].to_i != PROTOCOL_VERSION @error = "protocol version not supported" return false end true end attr_reader :error end class Response include Events def initialize @headers = {} @version = '1.1' @done = false end attr_accessor :status attr_accessor :headers attr_accessor :version def done?; @done; end def done(status) @status = status @done = true emit(:done) end def http_headers "HTTP/#{version} #{status} #{HTTP::HTTP_STATUS_CODES[status]}\r\n".tap do |str| @headers.each do |k,v| str << "#{k}: #{v}\r\n" end end end def accept_token_for(websocket_key) Base64.strict_encode64(Digest::SHA1.digest(websocket_key + GUID)) end def upgrade!(req) headers["Upgrade"] = 'websocket' headers["Connection"] = 'Upgrade' headers["Sec-WebSocket-Accept"] = accept_token_for(req.headers['sec-websocket-key']) done(101) end def read http_headers << "\r\n" end end end end
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} head # @param {Integer} x # @return {ListNode} def partition(head, x) return head if head == nil less_than_list = ListNode.new() greater_than_list = ListNode.new() pointer_less_than = less_than_list dummy_less_than_list = less_than_list pointer_greater_than = greater_than_list dummy_greater_than_list = greater_than_list while(head != nil) new_node = ListNode.new(head.val) if(head.val < x) pointer_less_than.next = new_node pointer_less_than = pointer_less_than.next less_than_list = less_than_list.next else pointer_greater_than.next = new_node pointer_greater_than = pointer_greater_than.next greater_than_list = greater_than_list.next end head = head.next end less_than_list.next = dummy_greater_than_list.next return dummy_less_than_list.next end
class Motion; class ImageEditorView < UIView def initWithFrame(frame) super.tap do |view| view.opaque = false view.layer.opacity = 0.7 view.backgroundColor = UIColor.clearColor view.addSubview(image_view) view.setup_constraints end end def setup_constraints addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( 'H:|[image]|', options: 0, metrics: nil, views: { 'image' => image_view })) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( 'V:|[image]|', options: 0, metrics: nil, views: { 'image' => image_view })) end def crop_rect @crop_rect ||= CGRectZero end def crop_rect=(rect) @crop_rect = CGRectOffset(rect, frame.origin.x, frame.origin.y) setNeedsDisplay end def drawRect(rect) super UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) context = UIGraphicsGetCurrentContext() UIColor.blackColor.setFill UIRectFill(bounds) UIColor.clearColor.setFill UIRectFill(CGRectInset(crop_rect, 1, 1)) image_view.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() end def image_view @image_view ||= UIImageView.alloc.init.tap do |image_view| image_view.translatesAutoresizingMaskIntoConstraints = false end end end; end
require 'tb' require 'test/unit' class TestTbNDJSON < Test::Unit::TestCase def parse_ndjson(ndjson) Tb::NDJSONReader.new(StringIO.new(ndjson)).to_a end def generate_ndjson(ary) writer = Tb::NDJSONWriter.new(out = '') ary.each {|h| writer.put_hash h } writer.finish out end def test_reader ndjson = <<-'End' {"A":"a","B":"b","C":"c"} {"A":"d","B":"e","C":"f"} End reader = Tb::NDJSONReader.new(StringIO.new(ndjson)) assert_equal({"A"=>"a", "B"=>"b", "C"=>"c"}, reader.get_hash) assert_equal({"A"=>"d", "B"=>"e", "C"=>"f"}, reader.get_hash) assert_equal(nil, reader.get_hash) assert_equal(nil, reader.get_hash) end def test_reader_header ndjson = <<-'End' {"A":"a"} {"A":"d","B":"e","C":"f"} End reader = Tb::NDJSONReader.new(StringIO.new(ndjson)) assert_equal(%w[A B C], reader.get_named_header) assert_equal({"A"=>"a"}, reader.get_hash) assert_equal({"A"=>"d", "B"=>"e", "C"=>"f"}, reader.get_hash) assert_equal(nil, reader.get_hash) assert_equal(nil, reader.get_hash) end def test_writer arys = [] writer = Tb::NDJSONWriter.new(arys) writer.header_generator = lambda { flunk } assert_equal([], arys) writer.put_hash({"A"=>"a", "B"=>"b", "C"=>"c"}) assert_equal(['{"A":"a","B":"b","C":"c"}'+"\n"], arys) writer.put_hash({"A"=>"d", "B"=>"e", "C"=>"f"}) assert_equal(['{"A":"a","B":"b","C":"c"}'+"\n", '{"A":"d","B":"e","C":"f"}'+"\n"], arys) writer.finish assert_equal(['{"A":"a","B":"b","C":"c"}'+"\n", '{"A":"d","B":"e","C":"f"}'+"\n"], arys) end def test_newline_in_string assert_equal('{"r":"\r","n":"\n"}'+"\n", generate_ndjson([{"r"=>"\r", "n"=>"\n"}])) end def test_empty_line assert_equal([{"a"=>"1"}, {"a"=>"2"}], parse_ndjson('{"a":"1"}'+"\n\n" + '{"a":"2"}'+"\n")) end end
#!/usr/bin/env ruby #tf_idf, tf_sub, fo, len, kp_freq def getFeatures(str) hash = Hash.new tmpArray = str.split(/,/) for tmp in tmpArray do subArray = tmp.split(/=/) key = subArray[0].strip value = subArray[1].strip hash["#{key}"] = value end return hash end path = ARGV[0] arffFile = ARGV[1] g = File.open(arffFile,"w") g.write("\n") g.write("@RELATION kp\n") g.write("@ATTRIBUTE tf_idf NUMERIC\n") g.write("@ATTRIBUTE fo NUMERIC\n") g.write("@ATTRIBUTE tf_sub NUMERIC\n") g.write("@ATTRIBUTE len NUMERIC\n") g.write("@ATTRIBUTE kp_freq NUMERIC\n") g.write("@ATTRIBUTE class {yes, no}\n") g.write("@DATA\n") featFiles = Array.new if File.directory?(path) currDir = Dir.getwd Dir.chdir(path) featFiles = Dir.glob("*.feat") Dir.chdir(currDir) path = path + "/" else featFiles << path path = "" end for feat in featFiles do f = File.open("#{path}#{feat}") while !f.eof do l = f.gets.chomp.strip featHash = getFeatures(l) tf_idf = featHash["tf_idf"] fo = featHash["fo"] tf_sub = featHash["tf_sub"] len = featHash["len"] kp_freq = featHash["kp_freq"] classname = featHash["classname"] g.write("#{tf_idf},#{fo},#{tf_sub},#{len},#{kp_freq},#{classname}\n") end f.close end g.close
module Spree class PurchaseOrderPayments < PaymentMethod def payment_source_class PurchaseOrderCheckout end def authorize(amount, source, gateway_options) order_number = gateway_options[:order_id][/(\w+)-/,1] order = Order.find_by_number(order_number) if order && order.user && order.user.can_order_with_po order.po_number = source.po_number order.save return OpenStruct.new({:success? => true}) else return OpenStruct.new({:success? => false}) end end def auto_capture false end def payment_profiles_supported? true end end end
# frozen_string_literal: true require "rake" require "rumrunner/manifest" module Rum ## # Defines the DSL methods for Rum Runner. module DSL private ## # Rum base task block. # # Example # rum :amancevice/rumrunner do # tag %x(git describe --tags --always) # # ... # end # def rum(*args, &block) name, _, deps = Rake.application.resolve_args(args) path, home = deps Manifest.new(name: name, path: path, home: home).install(&block) end end end self.extend Rum::DSL
describe Nanoc::Int::Item do it_behaves_like 'a document' describe '#freeze' do let(:item) { described_class.new('Hallo', { foo: { bar: 'asdf' } }, '/foo.md') } before do item.freeze end it 'prevents changes to children' do expect { item.children << :lol }.to raise_frozen_error end end end
require 'pathname' module Logging class LogDirectoryError < RuntimeError end class NullLogger def unknown(*); end def debug(*); end def info(*); end def warn(*); end def error(*); end def fatal(*); end end class << self def logger=(new_logger) @logger = new_logger end def logger @logger ||= NullLogger.new end def check_dir(dir) raise LogDirectoryError, "logging directory #{dir} does not exist" unless Dir.exist?(dir) raise LogDirectoryError, "cannot write to logging dir #{dir}" unless can_write_to_dir?(dir) end private def can_write_to_dir?(dir_name) return false unless Dir.exist?(dir_name) test_file_path = Pathname.new(dir_name) + Time.new.strftime("%Y%m%d%H%m%S.test") begin test_file_path.open("w") {} true rescue Errno::EACCES false ensure test_file_path.delete if test_file_path.exist? end end end def logger Logging.logger end end
require 'test_helper' class Fluent::PapertrailTest < Test::Unit::TestCase class TestSocket attr_reader :packets def initialize() @packets = [] end def puts(message) @packets << message end end def setup Fluent::Test.setup @driver = Fluent::Test::BufferedOutputTestDriver.new(Fluent::Papertrail, 'test') @mock_host = 'test.host' @mock_port = 123 @driver.configure(" papertrail_host #{@mock_host} papertrail_port #{@mock_port} ") @driver.instance.socket = TestSocket.new @default_record = { 'hostname' => 'some.host.name', 'facility' => 'local0', 'severity' => 'warn', 'program' => 'someprogram', 'message' => 'some_message' } end def test_create_socket_defaults_to_ssl_socket # override the test configuration from above to # create a live SSLSocket with papertrailapp.com @driver.configure(' papertrail_host logs3.papertrailapp.com papertrail_port 12345 ') assert @driver.instance.socket.is_a? OpenSSL::SSL::SSLSocket end def test_configure_empty_configuration begin @driver.configure('') rescue => e assert e.is_a? Fluent::ConfigError end end def test_configure_uses_papertrail_config assert @driver.instance.papertrail_host.eql? @mock_host assert @driver.instance.papertrail_port.eql? @mock_port end def test_create_packet_without_timestamp packet = @driver.instance.create_packet(nil, nil, @default_record) assert packet.hostname.to_s.eql? @default_record['hostname'] assert packet.facility.to_s.eql? '16' assert packet.severity.to_s.eql? '4' assert packet.tag.to_s.eql? @default_record['program'] assert packet.content.to_s.eql? @default_record['message'] end def test_create_packet_with_timestamp epoch_time = 550_611_383 converted_date = '1987-06-13' packet = @driver.instance.create_packet(nil, epoch_time, @default_record) assert packet.time.to_s.include? converted_date end def test_send_to_papertrail_with_test_socket snt_packet = @driver.instance.create_packet(nil, nil, @default_record) @driver.instance.send_to_papertrail(snt_packet) rcv_packet = @driver.instance.socket.packets.last assert rcv_packet.eql? snt_packet.assemble end end
require 'rss' require 'open-uri' class RSSFeed def initialize puts "Enter RSS URL:" puts url = gets.chomp read(url) end def read(url) open(url) do |rss| feed = RSS::Parser.parse(rss) puts "Title: #{feed.channel.title}" feed.items.each do |item| puts "Item: #{item.title}" puts item.description end end end end RSSFeed.new
#! /usr/bin/env ruby require 'kramdown' require 'erb' require 'stringio' require 'base64' require 'optparse' require 'listen' require 'rubydown' def get_context binding end class EvalDoc < Kramdown::Document attr_accessor :context, :stdout attr_reader :javascripts def initialize(text, *opts) super(text, *opts) @javascripts = {} self.context = get_context self.root = scan_el(self.root) @exception_raised = false end REQUIREJS_SCRIPT_TAG = '<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>' MATHJAX_SCRIPT_TAG = "<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>" private def scan_el(el) @javascripts[:mathjax] ||= MATHJAX_SCRIPT_TAG if el.type == :math new_children = [] el.children.each do |child_el| if (child_el.type == :codeblock || child_el.type == :codespan) && child_el.options[:lang] == 'ruby' new_children << scan_el(child_el) code = child_el.value.gsub(/^ *ruby *\n/, '') new_children << eval_and_elementize(code) unless @exception_raised @javascripts[:requirejs] ||= REQUIREJS_SCRIPT_TAG else new_children << scan_el(child_el) end end el.children = new_children return el end def eval_and_elementize(code) stdout = StringIO.new $stdout = stdout eval_result = begin self.context.eval(code) rescue Exception => e @exception_raised = true <<~HERE #{e} #{e.backtrace.join("\n")} HERE end $stdout = STDOUT stdout_string = stdout.string.empty? ? '' : stdout.string + "\n" case when eval_result.is_a?(Exception) text_result_el(eval_result.inspect) when eval_result.respond_to?(:to_html) Kramdown::Document.new(eval_result.to_html, input: :html).root when eval_result.instance_of?(File) && File.extname(eval_result.path) == ".png" img_b64 = Base64.encode64(File.binread(eval_result.path)) Kramdown::Document.new("<img src='data:image/png;base64,#{img_b64}' />", input: :html).root else text_result_el(stdout_string + "=> #{eval_result}") end end def text_result_el(text) text_el = Kramdown::Document.new("<pre><code class='language-plaintext'>#{text}</code></pre>", input: :html).root p_el = Kramdown::Element.new(:p) p_el.children << text_el p_el end end def main # to separate binding options = {} options[:erb] = File.expand_path('../../templates/template.html.erb', __FILE__) option_parser = OptionParser.new do |opts| opts.on("-i INPUT", "Input form the file") do |input| options[:input] = input end opts.on("--watch", "Watch file") do options[:watch] = true end opts.on("-e ERB", "Specify template file") do |erb| options[:erb] = erb end opts.on("-o OUTPUT", "Output html to OUTPUT") do |output| options[:output] = output end opts.on("-h", "--help", "Prints this help") do puts opts exit end opts.on_tail("--version", "Show version") do puts Rubydown::VERSION exit end end option_parser.parse! # puts options.inspect # puts options[:input] # puts options[:erb] # puts options[:output] case options[:input] when /\.md\z/i options[:output] ||= options[:input].sub(/\.md\z/i, '.html') when /./ abort("Input file must be markdown (*.md)") else abort(option_parser.help) end if options[:watch] doc = EvalDoc.new(File.read(options[:input], encoding: 'utf-8')) # using in ERB File.write(options[:output], ERB.new(File.read(options[:erb])).result(binding)) listener = Listen.to(File.dirname(options[:input])) do |modifieds, _, _| if modifieds.any? { |modified| modified == File.absolute_path(options[:input]) } doc = EvalDoc.new(File.read(options[:input], encoding: 'utf-8')) # using in ERB File.write(options[:output], ERB.new(File.read(options[:erb])).result(binding)) end end listener.start sleep else doc = EvalDoc.new(File.read(options[:input], encoding: 'utf-8')) # using in ERB File.write(options[:output], ERB.new(File.read(options[:erb])).result(binding)) end # puts ERB.new(File.read(options[:erb])).result(binding) end main
module Support module Paypal module AdaptivePayments module Pay module Stub def stub_paypal_pay! allow_any_instance_of(::PayPal::SDK::AdaptivePayments::API).to receive(:pay). and_return Pay.successful_response end def stub_paypal_pay_failure! allow_any_instance_of(::PayPal::SDK::AdaptivePayments::API).to receive(:pay). and_return Pay.unsuccessful_response end end def self.successful_response(email=nil, amount=nil) email ||= 'foo@bar.com' amount = 10 if amount.nil? ::PayPal::SDK::AdaptivePayments::DataTypes::PayResponse.new responseEnvelope: { timestamp: 10.seconds.ago, ack: "Success", correlationId: SecureRandom.hex(3), }, payKey: SecureRandom.hex(3), success?: true, paymentExecStatus: "COMPLETED", paymentInfoList: { paymentInfo: [ { pendingRefund: false, receiver: { accountId: SecureRandom.hex(3), amount: amount, email: email, primary: false }, senderTransactionId: SecureRandom.hex(3), senderTransactionStatus: "COMPLETED", transactionId: SecureRandom.hex(3), transactionStatus: "COMPLETED" } ] }, sender: { accountId: SecureRandom.hex(3) } end def self.unsuccessful_response() ::PayPal::SDK::AdaptivePayments::DataTypes::PayResponse.new responseEnvelope: { timestamp: 10.seconds.ago, ack: "Failure", correlationId: SecureRandom.hex(3), }, error: [{ errorId: 580001, domain: "PLATFORM", subdomain: "Application", severity: "Error", category: "Application", message: "Invalid request: More than one field cannot be used to specify a sender" }] end end end end end RSpec.configure do |config| config.include Support::Paypal::AdaptivePayments::Pay::Stub, type: :controller config.include Support::Paypal::AdaptivePayments::Pay::Stub, type: :request end
class AddDataSheetToDataTables < ActiveRecord::Migration[5.0] def self.up add_attachment :data_tables, :data_sheet end def self.down remove_attachment :data_tables, :data_sheet end end
# This migration comes from refinery_elephants (originally 1) class CreateElephantsElephants < ActiveRecord::Migration def up create_table :refinery_elephants do |t| t.string :headline t.string :link t.integer :photo_id t.string :author t.integer :position t.timestamps end end def down if defined?(::Refinery::UserPlugin) ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-elephants"}) end if defined?(::Refinery::Page) ::Refinery::Page.delete_all({:link_url => "/elephants/elephants"}) end drop_table :refinery_elephants end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'tzinfo/timezone_definition' module TZInfo module Definitions module Asia module Colombo include TimezoneDefinition timezone 'Asia/Colombo' do |tz| tz.offset :o0, 19164, 0, :LMT tz.offset :o1, 19172, 0, :MMT tz.offset :o2, 19800, 0, :IST tz.offset :o3, 19800, 1800, :IHST tz.offset :o4, 19800, 3600, :IST tz.offset :o5, 23400, 0, :LKT tz.offset :o6, 21600, 0, :LKT tz.transition 1879, 12, :o1, 17335550003, 7200 tz.transition 1905, 12, :o2, 52211763607, 21600 tz.transition 1942, 1, :o3, 116657485, 48 tz.transition 1942, 8, :o4, 9722413, 4 tz.transition 1945, 10, :o2, 38907909, 16 tz.transition 1996, 5, :o5, 832962600 tz.transition 1996, 10, :o6, 846266400 tz.transition 2006, 4, :o2, 1145039400 end end end end end
class RenameBusinessLogoToAvatarInUsers < ActiveRecord::Migration def change rename_column :users, :business_logo, :avatar end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :username, presence: true, uniqueness: true has_many :tips has_many :questions has_many :reports has_many :votes has_many :cities, class_name: 'UserCity' has_many :ignored_questions def city_names cities.pluck(:city) end def questions_to_answer ignored = ignored_questions.pluck(:id) Question.where(city: city_names).where.not(user: self).where.not(id: ignored) end end
namespace :demo do desc "Reset Database" task database: :environment do Rake::Task['db:drop'].execute Rake::Task['db:create'].execute Rake::Task['db:migrate'].execute Rake::Task['db:seed'].execute end end
# == Schema Information # # Table name: conversations # # id :bigint not null, primary key # sender_id :bigint # recipient_id :bigint # identifier :string # created_at :datetime not null # updated_at :datetime not null # class Conversation < ApplicationRecord belongs_to :sender, :foreign_key => "sender_id", :class_name => "User" belongs_to :recipient, :foreign_key => "recipient_id", :class_name => "User" has_many :messages, dependent: :destroy private def self.get_conversation(user_id) where("recipient_id = ? ",user_id) end def self.current_user_conversations(user_id) where("recipient_id = ? OR sender_id = ? ",user_id, user_id) end def self.own_conversations(user_id) where("recipient_id = ? OR sender_id = ? ",user_id, user_id) end def self.foreign_conversations(user_id) where("recipient_id <> ? OR sender_id <> ? ",user_id, user_id) end # Scope to check reciproque connectivity scope :between, -> (sender_id,recipient_id) do where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id) end end
module Base62 # http://refactormycode.com/codes/125-base-62-encoding BASE62_CHARS = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a BASE62_MAP = {} BASE62_CHARS.zip((0..61).to_a){|ch,num| BASE62_MAP[ch]=num } def self.i_to_s i return '0' if i == 0 s = '' while i > 0 s << BASE62_CHARS[i.modulo(62)] i /= 62 end s.reverse end def self.s_to_i str i_out = 0 str.reverse.chars.each_with_index do |c, i| i_out += BASE62_MAP[c] * (62 ** i) end i_out end end module ShorturlSequence def self.encode_integer i, radix case radix.to_s when '36' then i.to_s(36) when '62' then Base62.i_to_s(i) else raise "Can't encode into base #{radix}" end end def self.decode_str s, radix s = s.gsub(%r{\W+$},'') case radix.to_s when '36' then s.to_i(36) when '62' then Base62.s_to_i(i) else raise "Can't encode into base #{radix}" end end end class Shorturl attr_accessor :base_url attr_accessor :token def initialize token self.token = token end end class Shorturl62 def to_i Base62.s_to_i token end def to_s url end def url "#{base_url}/#{token}" end end class IsgdShorturl < Shorturl62 def base_url 'http://is.gd' end end class Monkeyshines::Store::SequentialUrlStream DEFAULT_MAX_URLSTR = '1zzzzz'.to_i(36) DEFAULT_RADIX = { 'http://tinyurl.com/' => 36, 'http://bit.ly/' => 62, 'http://is.gd/' => 62, } attr_accessor :base_url, :min_limit, :span, :encoding_radix def initialize base_url, min_limit=0, max_limit=nil, encoding_radix=nil self.base_url = self.class.fix_url(base_url) self.min_limit = min_limit.to_i max_limit ||= DEFAULT_MAX_URLSTR self.span = max_limit.to_i - self.min_limit self.encoding_radix = (encoding_radix || DEFAULT_RADIX[self.base_url]).to_i raise "Please specify either encoding_radix of 36 or 62" unless [36, 62].include?(self.encoding_radix) end def self.fix_url url url = 'http://' + url unless (url[0..6]=='http://') url = url + '/' unless (url[-1..-1]=='/') url end # An infinite stream of urls in range def each *args, &block (min_limit..max_limit).each(&block) end def self.new_from_command_line cmdline_opts, default_opts={} options = default_opts.merge(cmdline_opts) Trollop::die :base_url if options[:base_url].blank? self.new *options.values_of(:base_url, :min_limit, :max_limit, :encoding_radix) end end class Monkeyshines::Store::RandomUrlStream < Monkeyshines::Store::SequentialUrlStream # An infinite stream of urls in range def each *args, &block loop do yield url_in_range end end def url_in_range idx = rand(span) + min_limit base_url + ShorturlSequence.encode_integer(idx, encoding_radix) end end
class FriendsController < ApplicationController before_action :set_friend, only: [:destroy] def index end def friend_request user_friend = User.find(params[:user]) #Criando a solicitação de amizade do usuário on-line friend = Friend.new friend.user_id = current_user.id friend.friend_id = user_friend.id friend.status = 'request' friend.save flash[:success] = 'Sua solicitação foi realizada!' #Criando a solicitação de amizade que fica pendente da #aprovação do outro usuário friend2 = Friend.new friend2.user_id = user_friend.id friend2.friend_id = current_user.id friend2.status = 'pending' friend2.save #friend2.create_activity(:friend_request, :owner => User.find(friend2.user_id)) redirect_to users_path end def accept_request friend = Friend.find(params[:friend]) friend.status = 'accept' friendship = Friend.where(user_id: friend.friend_id, friend_id: current_user.id, status: 'request').first friendship.status = 'accept' friendship.save friend.save redirect_to root_path end def refuse_request friend = Friend.find(params[:friend]) friend1 = Friend.where(user_id: friend.friend_id, friend_id: friend.user_id, status: 'request').first friend1.delete friend.delete redirect_to root_path end def cancel_request friend = Friend.find(params[:friend]) if friend.status == "accept" friendship = Friend.where(user_id: friend.friend_id, friend_id: friend.user_id, status: 'accept').first else friendship = Friend.where(user_id: friend.friend_id, friend_id: friend.user_id, status: 'pending').first end friendship.delete friend.delete redirect_to root_path end def destroy @friend.destroy respond_to do |format| format.html { redirect_to root_path, notice: 'Armizade desfeita com sucesso.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_friend @friend = Friend.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def friend_params params.require(:friend).permit(:requester_id, :destiny_id, :status) end end
class Ability < ActiveRecord::Base include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :admin can :manage, :all else can :read, :all if user.role?(:seller) can :create, Product can :update, Product do |product| product.try(:user) == user end end if user.role?(:supplier) can :create, Product can :update, Product do |product| product.try(:user) == user end end if user.role?(:buyer) can :read, Product can :read, Cart can :update, Cart end end end end
require 'rails_helper' describe User do describe '#create' do # 入力されている場合のテスト ▼ it "全ての項目の入力が存在すれば登録できること" do # テストしたいことの内容 user = build(:user) # 変数userにbuildメソッドを使用して、factory_botのダミーデータを代入 expect(user).to be_valid # 変数userの情報で登録がされるかどうかのテストを実行 end it "nameがない場合は登録できないこと" do # テストしたいことの内容 user = build(:user, name: nil) # 変数userにbuildメソッドを使用して、factory_botのダミーデータを代入(今回の場合は意図的にnicknameの値をからに設定) user.valid? #バリデーションメソッドを使用して「バリデーションにより保存ができない状態であるか」をテスト expect(user.errors[:name]).to include("入力してください。") # errorsメソッドを使用して、「バリデーションにより保存ができない状態である場合なぜできないのか」を確認し、.to include("を入力してください")でエラー文を記述(今回のRailsを日本語化しているのでエラー文も日本語) end it "emailがない場合は登録できないこと" do user = build(:user, email: nil) user.valid? expect(user.errors[:email]).to include("入力してください。") end it "passwordがない場合は登録できないこと" do user = build(:user, password: nil) user.valid? expect(user.errors[:password]).to include("入力してください。") end it "encrypted_passwordがない場合は登録できないこと" do user = build(:user, encrypted_password: nil) user.valid? expect(user.errors[:encrypted_password]).to include("入力してください。") end it "重複したemailが存在する場合登録できないこと" do user = create(:user) # createメソッドを使用して変数userとデータベースにfactory_botのダミーデータを保存 another_user = build(:user, email: user.email) # 2人目のanother_userを変数として作成し、buildメソッドを使用して、意図的にemailの内容を重複させる another_user.valid? # another_userの「バリデーションにより保存ができない状態であるか」をテスト expect(another_user.errors[:email]).to include("既に登録済みです。") end it "passwordが存在してもencrypted_passwordがない場合は登録できないこと" do user = build(:user, password: "password", encrypted_password: nil) # 意図的に確認用パスワードに値を空にする user.valid? expect(user.errors[:encrypted_password]).to include("入力してください。") end it "passwordが6文字以上であれば登録できること" do user = build(:user, password: "123456", encrypted_password: "123456") # buildメソッドを使用して6文字のパスワードを設定 expect(user).to be_valid end it "passwordが6文字以下であれば登録できないこと" do user = build(:user, password: "12345", encrypted_password: "12345") # 意図的に5文字のパスワードを設定してエラーが出るかをテスト user.valid? expect(user.errors[:password]).to include("6文字以上で登録してください。") end it "名前が20文字より多ければ登録できないこと" do user = build(:user, name: "123456789123456789101") user.valid? expect(user.errors[:name]).to include("20文字以内で入力してください。") end it "名前が20文字以上であれば登録できること" do user = build(:user, name: "123456") expect(user).to be_valid end it "自己紹介が100文字以上であれば登録できないこと" do user = build(:user, introduction: "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") user.valid? expect(user.errors[:introduction]).to include("100文字以上で入力してください") end it "自己紹介が100文字以下であれば登録できること" do user = build(:user, introduction: "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") expect(user).to be_valid end it "フォローするとfollower(フォローしている人)が生成される" do user1 = create(:user) user2 = create(:user, email: "user2@example.com") user2.follow(user1.id) expect(user2.follower.count).to eq 1 end it "フォロー解除するとfollower(フォローしている人)が削除される" do user1 = create(:user) user2 = create(:user, email: "user2@example.com") user2.follow(user1.id) user2.unfollow(user1.id) expect(user2.follower.count).to eq 0 end it "すでにフォローしているか確認する" do user1 = create(:user) user2 = create(:user, email: "user2@example.com") user2.follow(user1.id) expect(user2.following?(user1)).to be_truthy end it "フォローしたとき相手に通知を作成する" do visiter = create(:user) visited = create(:user, email: "user2@example.com") visiter.follow(visited.id) expect(visiter.create_notification_follow!(visiter)).to be_truthy end end end
class Acme::RegistrationsController < Devise::RegistrationsController before_filter :configure_account_update_params, only: [:update] def configure_account_update_params devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:image_uid, :image_name, :mobile_number, :prenom, :email, :password, :current_password)} end protected def after_update_path_for(current_user) edit_user_registration_path end end
# Preview all emails at http://localhost:3000/rails/mailers/enquiry_mailer class EnquiryMailerPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/enquiry_mailer/created def created EnquiryMailer.created end end