text stringlengths 10 2.61M |
|---|
require 'csv'
require 'sqlite3'
require 'date'
# Reading the CSV file
companies = CSV.read("../TechCrunchcontinentalUSA.csv")
# Selecting only the 'web' companies
web_companies = companies.select { |el| el[3] == 'web' }
# Making a Hash so we can find duplicates
names = Hash.new(0)
web_companies.each { |el| names[el[1]] += 1 }
dups = names.select { |_, v| v > 1 }
# Iterate over the duplicate names
dups.keys.each do |k|
# Select out the actual rows based on names that were duplicate
set = web_companies.select{ |el| el[1] == k }
# Make a set of dates from subset, find max, delete the rest
max_date = set.map { |el| Date.parse(el[6]) }.max
to_delete = set.select { |el| Date.parse(el[6]) != max_date }
remaining = set.reject { |el| Date.parse(el[6]) != max_date }
to_delete.each { |el| web_companies.delete(el) }
# If duplicates still remain, compare by amount
if remaining.length > 1
set_of_amts = remaining.map{ |el| el[7] }
max_amt = set_of_amts.max
to_delete_amt = remaining.select { |el| el[7] != max_amt }
remaining = remaining.reject { |el| el[7] != max_amt }
to_delete_amt.each { |el| web_companies.delete(el) }
end
# If there are STILL duplicates, just choose one
if remaining.length > 1
to_delete_dups = remaining.drop(1)
to_delete_indices = []
to_delete_dups.each { |el| to_delete_indices << web_companies.index(el) }
to_delete_indices.each { |idx| web_companies.delete_at(idx) }
end
end
# # Helper to print out remaining duplicates
#
# web_companies.each_with_index do |el, i|
# next if i == web_companies.length - 1
# if web_companies[i + 1][0] == el[0]
# p el
# p web_companies[i + 1]
# end
# end
#
# # Helper to verify number
#
# p web_companies.map { |el| el[0] }.count
# p web_companies.map { |el| el[0] }.uniq.count
## Alternate Solution 3
# companies = companies.select { |arr| arr[3] == 'web' }
#
# companies = companies.chunk { |rows| rows[1] }.to_a
# .map { |companies| companies[1] }
#
# companies_result = []
#
# companies.each do |company|
# current_round = []
#
# company.each do |funding_round|
# current_round = funding_round if current_round.empty?
#
# if (Date.parse(funding_round[6]) <=> Date.parse(current_round[6])) == -1
# current_round = funding_round
# elsif (Date.parse(funding_round[6]) <=> Date.parse(current_round[6])).zero?
# if funding_round[7].to_i > current_round[7].to_i
# current_round = funding_round
# end
# end
# end
#
# companies_result << current_round
# end
begin
db = SQLite3::Database.open "companies.db"
db.execute "DROP TABLE IF EXISTS Companies"
db.execute "CREATE TABLE IF NOT EXISTS Companies(Id INTEGER PRIMARY KEY,
Permalink TEXT, Company TEXT, NumEmps INT, Catergory TEXT, City TEXT, State TEXT, FundedDate TEXT,
RaisedAmt INT, RaisedCurrency TEXT, Round TEXT)"
# Start at index 1 so we can insert Primary Key by index, or similar
(1..web_companies.length).each do |i|
company = web_companies[i - 1]
# Control for nil values which will cause exceptions
company.map! { |el| el.nil? ? 0 : el }
# Control for stray single quotes which will cause an exception
company.each_with_index do |el, idx|
company[idx] = el.delete("\'") if el.is_a?(String) && el.include?("\'")
end
# Print to track progress and examine where errors arise
# p company
# Make sure that values are entered as strings or integers according to schema
db.execute "INSERT INTO Companies VALUES(#{i}, '#{company[0]}', '#{company[1]}', #{company[2]}, '#{company[3]}', '#{company[4]}', '#{company[5]}', '#{company[6]}', #{company[7].to_i}, '#{company[8]}', '#{company[9]}')"
end
# SELECT AVG(RaisedAmt), State, MAX(RaisedAmt), Company, MAX(RaisedAmt)-AVG(RaisedAmt) AS diff FROM Companies GROUP BY State ORDER BY diff DESC LIMIT 1;
p db.execute "SELECT Company, MAX(RaisedAmt)-AVG(RaisedAmt) AS diff FROM Companies GROUP BY State ORDER BY diff DESC LIMIT 1"
rescue SQLite3::Exception => e
puts "Exception occurred"
puts e
ensure
db.close if db
end
|
# frozen_string_literal: true
class VkDeleteFriendsJob < ApplicationJob
def perform
Vkontakte::FriendsService.new.delete_friends
rescue StandardError => e
create_logger(e)
end
end
|
$:.push File.expand_path("../../..", __FILE__)
require 'sinatra'
require 'bettybot'
require 'coffee-script'
get '/application.js' do
coffee :application
end
get '/' do
betty = Bettybot::Betty.new
@messages = betty.memories
erb :index
end
post '/' do
betty = Bettybot::Betty.new
betty.reply_to Bettybot::Message.new('You', Time.now, params[:message])
redirect '/#latest'
end
helpers do
include Rack::Utils
alias_method :h, :escape_html
def message_attributes(message, messages)
attributes = ''
attributes += ' id="latest"' if message == messages.last
attributes += ' class="message'
attributes += ' mirror' if message.author != 'Betty'
attributes += '"'
end
def author_avatar(message)
"<img src=\"/#{message.author == 'Betty' ? 'bot' : 'human'}.png\" width=\"48\" height=\"48\" alt=\"\" />"
end
def media_from(message)
unless message.data.nil?
if message.data.has_key? 'url'
if File.extname(message.data['url']).match /\.(jpg|gif|png|jpeg)/i
"<br /><img src=\"#{message.data['url']}\" alt=\"\" />"
end
end
end
end
end
|
class RemotePhotosAddCachedLocalPhoto < ActiveRecord::Migration
def self.up
add_column :remote_photos, :cached_local_photo_id, :integer
end
def self.down
remove_column :remote_photos, :cached_local_photo_id
end
end
|
require 'rails_helper'
RSpec.describe CampaignsController, type: :controller do
let(:user) { create(:user) }
let(:campaign) { create(:campaign, user: user) }
let(:campaign_1) { create(:campaign) }
describe "#new" do
context "with user logged in" do
before {
login(user)
get :new
}
it "assigns a new campaign instance variable" do
# assigns(:campaign) refers to @campaign
expect(assigns(:campaign)).to be_a_new(Campaign)
end
it "renders the new template" do
expect(response).to render_template(:new)
end
end
context "with user not logged in" do
it "redirects to login page" do
get :new
expect(response).to redirect_to(new_session_path)
end
end
end
describe "#create" do
context "with user logged in" do
before {
login(user)
}
context "valid request" do
def valid_request
post :create, {
campaign: {
title: "Heyy Durr",
description: "Loren ipsum heroku starbucks",
goal: 11,
due_date: "2019-11-11 10:33:20"
}
}
end
it "creates a new campaign record in the database for current user" do
expect { valid_request }.to change { user.campaigns.count }.by(1)
end
it "redirects to campaign show page" do
valid_request
expect(response).to redirect_to(campaign_path(Campaign.last))
end
it "sets flash message" do
valid_request
expect(flash[:notice]).to be
end
end
context "invalid request" do
def invalid_request
post :create, {
campaign: {
title: nil,
description: "Loren ipsum heroku starbucks",
goal: 5,
due_date: "2019-11-11 10:33:20"
}
}
end
it "doesn't create a record in the database" do
expect { invalid_request }.not_to change { Campaign.count }
end
it "sets a flash errors message" do
invalid_request
expect(flash[:notice]).to be
end
it "renders the new template" do
invalid_request
expect(response).to render_template(:new)
end
end
end
context "without user logged in" do
it "redirects to login page" do
post :create
expect(response).to redirect_to(new_session_path)
end
end
end
describe "#show" do
it "assigns a campaign instance with passed id" do
get :show, id: campaign.id
expect(assigns(:campaign)).to eq(campaign)
end
it "renders the show template" do
get :show, id: campaign.id
expect(response).to render_template(:show)
end
end
describe "#index" do
it "assigns campaigns instance variable to created campaigns" do
campaign
campaign_1
get :index
expect(assigns(:campaigns)).to eq([campaign, campaign_1])
end
it "renders the index template" do
get :index
expect(response).to render_template(:index)
end
end
describe "#edit" do
context "with user logged in" do
context "with owner logged in" do
before {
login(user)
get :edit, id: campaign.id
}
it "renders the edit template" do
expect(response).to render_template(:edit)
end
it "retrieves the campaign with passed id and stores it in an instance variable" do
expect(assigns(:campaign)).to eq(campaign)
end
end
context "with not owner logged in" do
it "redirects to root path" do
login(user)
expect { get :edit, id: campaign_1.id }.to raise_error
end
end
end
context "without user logged in" do
it "redirects to login page" do
get :edit, id: campaign.id
expect(response).to redirect_to(new_session_path)
end
end
end
describe "#update" do
context "with user logged in" do
context "with owner logged in" do
before {
login(user)
}
context "with valid request" do
before do
patch :update, { id: campaign.id,
campaign: {
title: "Heyy Durr",
description: "Loren ipsum heroku starbucks",
goal: 11,
due_date: "2019-11-11 10:33:20"
}
}
end
it "redirect to the campaign show page" do
expect(response).to redirect_to(campaign_path(campaign.id))
end
it "changes the title of the campaign if it's different" do
campaign.reload
expect(campaign.title).to eq("Heyy Durr")
end
end
context "with invalid params" do
before do
patch :update, { id: campaign.id,
campaign: {
title: "",
description: "Loren ipsum heroku starbucks",
goal: 5,
due_date: "2019-11-11 10:33:20"
}
}
end
it "renders the edit page" do
expect(response).to render_template(:edit)
end
it "doesn't change the database" do
expect(campaign.reload.goal).not_to eq(5)
# expect(assigns(:campaign)).to eq(campaign)
end
it "sets an alert flash message" do
expect(flash[:alert]).to be
end
end
end
context "with not owner logged in" do
it "throws an error" do
login(user)
expect { patch :update, id: campaign_1.id }.to raise_error
end
end
end
context "without user logged in" do
it "redirects to login page" do
patch :update, id: campaign.id
expect(response).to redirect_to(new_session_path)
end
end
end
describe "#destroy" do
let!(:campaign) { create(:campaign, user: user) }
def destroy_request
delete :destroy, id: campaign.id
end
context "with user logged in" do
before { login(user) }
context "deleting own campaign" do
it "deleted the entry from the database" do
expect{destroy_request}.to change { Campaign.count }.by(-1)
end
it "redirect to the home page" do
expect(destroy_request).to redirect_to(root_path)
end
it "sets a flash message" do
destroy_request
expect(flash[:notice]).to be
end
end
context "deleting non-owned campaign" do
it "throws an error" do
expect { delete :destroy, id: campaign_1.id }.to raise_error
end
end
end
context "with user not logged in" do
it "redirects to login page" do
destroy_request
expect(response).to redirect_to(new_session_path)
end
end
end
end
|
require 'kimono_helper'
module MusicMosh
module Scrapers
module US
module IL
class BottomLounge
def run
json_data = KimonoHelper.fetch('8pdmf368')
shows = KimonoHelper.parse(json_data)
venue_hash = self.venue
shows.each do |show|
split_multiple_artists(show, shows, venue_hash)
show[:venue] = venue_hash
end
end
def split_multiple_artists(show, shows, venue_hash)
multiple_artists = show[:artist_name].split(' ~ ')
if multiple_artists.length > 1
show[:artist_name] = multiple_artists[0].to_s.strip
for i in 1..multiple_artists.length
shows << {
artist_name: multiple_artists[i].to_s.strip,
url: show[:url],
venue: venue_hash,
date: show[:date]
}
end
end
end
def venue
venue = Hash.new
venue[:name] = 'Bottom Lounge'
venue[:city] = 'Chicago'
venue[:state] = 'IL'
venue[:country] = 'US'
venue[:latitude] = 41.885217
venue[:longitude] = -87.661728
return venue
end
end
end
end
end
end |
class Api::SessionsController < ApplicationController
def show
@user = current_user
if @user
render 'api/users/show.json.jbuilder'
else
render json: {}
end
end
def new
@user = User.find_by_credentials(session_params[:email], session_params[:password])
if !@user.nil?
session[:session_token] = @user.session_token
render 'api/users/show.json.jbuilder'
else
render json: ["Invalid email/password combination"], status: 422
end
end
def destroy
@user = current_user
session[:session_token] = nil
@user.session_token = SecureRandom::urlsafe_base64(16)
render json: {}
end
def session_params
params.require(:user).permit(:email, :password)
end
end
|
# module API
module Railsapp
module V1
class Instapi < Grape::API
include Railsapp::V1::Defaults
resource :instapi do
desc "Return all photos"
get "", root: :photos do
@Photos = Photos.where(publish_status: 'Published')
if @Photos.present?
error!({:success_message => "Record found",:result => @Photos ,:count => @Photos.count}, 300)
else
error!({:error_message => "Record Could not found"}, 422)
end
end
desc "Return a photo"
params do
requires :id, type: String, desc: "ID of the photo"
end
get ":id", root: "photo" do
# byebug
@Photos = Photos.where(id: permitted_params[:id]).first
if @Photos.present?
error!({:success_message => "Record found",:result => @Photos }, 300)
else
error!({:error_message => "Record Could not found"}, 422)
end
# Photos.where(:id => @id).update_all(publish_status: @status_value)
end
end
end
end
end
|
require "spec_helper"
require "./converter"
describe Converter do
it "convert a+b to ab+" do
converter = Converter.new
result = converter.convert("a+b")
result.should be == "ab+"
end
it "convert a*b to ab*" do
converter = Converter.new
result = converter.convert("a*b")
result.should be == "ab*"
end
it "convert a|b to ab|" do
converter = Converter.new
result = converter.convert("a|b")
result.should be == "ab|"
end
it "convert a?b to ab?" do
converter = Converter.new
result = converter.convert("a?b")
result.should be == "ab?"
end
it "convert a*b|c to ab*c|" do
converter = Converter.new
result = converter.convert("a*b|c")
result.should be == "ab*c|"
end
it "convert 2*b|c.d to 2b*cd.|" do
converter = Converter.new
result = converter.convert("2*b|c.d")
result.should be == "2b*cd.|"
end
it "check the importance of + versus *" do
converter = Converter.new
importance = converter.important('+', '*')
importance.should be = false
end
it "check the importance of - versus *" do
converter = Converter.new
importance = converter.important('-', '*')
importance.should be = false
end
it "check the importance of * versus *" do
converter = Converter.new
importance = converter.important('*', '*')
importance.should == -1
end
it "check the importance of / versus *" do
converter = Converter.new
importance = converter.important('/', '*')
importance.should == -1
end
it "check the importance of + versus /" do
converter = Converter.new
importance = converter.important('+', '/')
importance.should be = false
end
it "check the importance of - versus /" do
converter = Converter.new
importance = converter.important('-', '/')
importance.should be = false
end
it "check the importance of * versus /" do
converter = Converter.new
importance = converter.important('*', '/')
importance.should == -1
end
it "check the importance of / versus /" do
converter = Converter.new
importance = converter.important('/', '/')
importance.should == -1
end
it "check the importance of + versus +" do
converter = Converter.new
importance = converter.important('+', '+')
importance.should == -1
end
it "check the importance of - versus +" do
converter = Converter.new
importance = converter.important('-', '+')
importance.should == -1
end
it "check the importance of * versus +" do
converter = Converter.new
importance = converter.important('*', '+')
importance.should == true
end
it "check the importance of / versus +" do
converter = Converter.new
importance = converter.important('/', '+')
importance.should == true
end
it "check the importance of + versus -" do
converter = Converter.new
importance = converter.important('+', '-')
importance.should == -1
end
it "check the importance of - versus -" do
converter = Converter.new
importance = converter.important('-', '-')
importance.should == -1
end
it "check the importance of * versus -" do
converter = Converter.new
importance = converter.important('*', '-')
importance.should == true
end
it "check the importance of / versus -" do
converter = Converter.new
importance = converter.important('/', '-')
importance.should == true
end
it "chec the importance of * vs +" do
converter = Converter.new
importance = converter.important2('*', '+')
importance.should == -1
end
it "chec the importance of * vs ?" do
converter = Converter.new
importance = converter.important2('*', '?')
importance.should == -1
end
it "chec the importance of * vs *" do
converter = Converter.new
importance = converter.important2('*', '*')
importance.should == -1
end
it "chec the importance of * vs ." do
converter = Converter.new
importance = converter.important2('*', '.')
importance.should == true
end
it "chec the importance of * vs |" do
converter = Converter.new
importance = converter.important2('*', '|')
importance.should == true
end
it "chec the importance of + vs +" do
converter = Converter.new
importance = converter.important2('+', '+')
importance.should == -1
end
it "chec the importance of + vs ?" do
converter = Converter.new
importance = converter.important2('+', '?')
importance.should == -1
end
it "chec the importance of + vs *" do
converter = Converter.new
importance = converter.important2('+', '*')
importance.should == -1
end
it "chec the importance of + vs ." do
converter = Converter.new
importance = converter.important2('+', '.')
importance.should == true
end
it "chec the importance of + vs |" do
converter = Converter.new
importance = converter.important2('+', '|')
importance.should == true
end
it "chec the importance of ? vs +" do
converter = Converter.new
importance = converter.important2('?', '+')
importance.should == -1
end
it "chec the importance of ? vs ?" do
converter = Converter.new
importance = converter.important2('?', '?')
importance.should == -1
end
it "chec the importance of ? vs *" do
converter = Converter.new
importance = converter.important2('?', '*')
importance.should == -1
end
it "chec the importance of ? vs ." do
converter = Converter.new
importance = converter.important2('?', '.')
importance.should == true
end
it "chec the importance of ? vs |" do
converter = Converter.new
importance = converter.important2('?', '|')
importance.should == true
end
it "chec the importance of . vs +" do
converter = Converter.new
importance = converter.important2('.', '+')
importance.should == false
end
it "chec the importance of . vs ?" do
converter = Converter.new
importance = converter.important2('.', '?')
importance.should == false
end
it "chec the importance of . vs *" do
converter = Converter.new
importance = converter.important2('.', '*')
importance.should == false
end
it "chec the importance of . vs ." do
converter = Converter.new
importance = converter.important2('.', '.')
importance.should == -1
end
it "chec the importance of . vs |" do
converter = Converter.new
importance = converter.important2('.', '|')
importance.should == true
end
it "chec the importance of | vs +" do
converter = Converter.new
importance = converter.important2('|', '+')
importance.should == false
end
it "chec the importance of | vs ?" do
converter = Converter.new
importance = converter.important2('|', '?')
importance.should == false
end
it "chec the importance of | vs *" do
converter = Converter.new
importance = converter.important2('|', '*')
importance.should == false
end
it "chec the importance of | vs ." do
converter = Converter.new
importance = converter.important2('|', '.')
importance.should == false
end
it "chec the importance of | vs |" do
converter = Converter.new
importance = converter.important2('|', '|')
importance.should == -1
end
it "write on a the same file called input.csv with the result of the convertions" do
converter = Converter.new
converted = converter.readAndConvert("input.csv")
tmp = true
CSV.foreach("input.csv") do |row|
if row[2] == ''
tmb = false
end
end
tmp.should == true
end
it "if the file has been used or tested it has to return -1" do
converter = Converter.new
converted = converter.readAndConvert("input.csv")
converted.should == -1
end
it "if the file doesnt exist, should return false" do
converter = Converter.new
converted = converter.readAndConvert("lol.csv")
converted.should == false
end
it "has to convert ab to a.b" do
converter = Converter.new
result = converter.normalize("ab")
result.should be == "a.b"
end
it "has to convert a+b to a+.b" do
converter = Converter.new
result = converter.normalize("a+b")
result.should be == "a+.b"
end
it "has to convert a*b to a*.b" do
converter = Converter.new
result = converter.normalize("a*b")
result.should be == "a*.b"
end
it "has to convert a?b to a?.b" do
converter = Converter.new
result = converter.normalize("a?b")
result.should be == "a?.b"
end
it "has to convert a|b to a|b" do
converter = Converter.new
result = converter.normalize("a|b")
result.should be == "a|b"
end
it "has to convert d+a|c to d+.a|c" do
converter = Converter.new
result = converter.normalize("d+a|c")
result.should be == "d+.a|c"
end
it "has to check if * is binary operator" do
converter = Converter.new
importance = converter.binary('*')
importance.should == false
end
it "has to check if + is binary operator" do
converter = Converter.new
importance = converter.binary('+')
importance.should == false
end
it "has to check if . is binary operator" do
converter = Converter.new
importance = converter.binary('.')
importance.should == true
end
it "has to check if | is binary operator" do
converter = Converter.new
importance = converter.binary('|')
importance.should == true
end
it "has to check if ? is binary operator" do
converter = Converter.new
importance = converter.binary('?')
importance.should == false
end
it "has to convert a.b to .ab" do
converter = Converter.new
result = converter.treelizer("a.b")
result.should be == ".ab"
end
it "has to convert a|b to |ab" do
converter = Converter.new
result = converter.treelizer("a|b")
result.should be == "|ab"
end
it "has to convert a+ to +a" do
converter = Converter.new
result = converter.treelizer("a+")
result.should be == "+a"
end
it "has to convert a* to *a" do
converter = Converter.new
result = converter.treelizer("a*")
result.should be == "*a"
end
it "has to convert a? to ?a" do
converter = Converter.new
result = converter.treelizer("a?")
result.should be == "?a"
end
it "has to convert a|b*.c to |a.*bc" do
converter = Converter.new
result = converter.treelizer("a|b*.c")
result.should be == "|a.*bc"
end
it "has to convert a+.b* to .+a*b" do
converter = Converter.new
result = converter.treelizer("a+.b*")
result.should be == ".+a*b"
end
it "has to convert a.b|a+.c? to |.ab.+a?c" do
converter = Converter.new
result = converter.treelizer("a.b|a+.c?")
result.should be == "|.ab.+a?c"
end
it "has to convert b?.c to .?bc" do
converter = Converter.new
result = converter.treelizer("b?.c")
result.should be == ".?bc"
end
it "has to convert c+.a to .+ca" do
converter = Converter.new
result = converter.treelizer("c+.a")
result.should be == ".+ca"
end
it "has to convert b?.c|c+.a to |.?bc.+ca" do
converter = Converter.new
result = converter.treelizer("b?.c|c+.a")
result.should be == "|.?bc.+ca"
end
end |
class ETMasterUnsubRetrieve < ExactTargetMessage
def initialize(params=nil)
super
self.system_name = 'tracking'
self.action = 'retrieve'
end
def validate
if self.properties[:start_date] && self.properties[:end_date].nil?
errors.add :end_date, "must be present since you specified a start date"
end
if self.properties[:end_date] && self.properties[:start_date].nil?
errors.add :start_date, "must be present since you specified an end date"
end
if self.properties[:start_date] && self.properties[:end_date] && self.properties[:start_date] > self.properties[:end_date]
errors.add :start_date, "cannot be after end date #{self.properties[:start_date]} #{self.properties[:end_date]}"
end
end
protected
def generate_request_specific_xml(xm)
xm.sub_action 'masterunsub'
xm.search_type nil
xm.search_value nil
xm.daterange {
xm.startdate self.properties[:start_date].to_s(:exact_target_date) if self.properties[:start_date]
xm.enddate self.properties[:end_date].to_s(:exact_target_date) if self.properties[:end_date]
}
end
def after_find
return unless self.properties.blank?
return if self.request.blank?
doc = REXML::Document.new request
self.properties[:start_date] = date_from_xml doc.root, './system/daterange/startdate'
self.properties[:end_date] = date_from_xml doc.root, './system/daterange/enddate'
end
def after_execute
return false unless self.status == :et_success
doc = REXML::Document.new self.response
REXML::XPath.each doc.root, '//subscriber' do |node|
reason = REXML::XPath.first(node, 'reason')
email_node = REXML::XPath.first(node, 'email_address')
next if email_node.blank? || email_node.text.blank?
email = email_node.text.to_s
if reason && reason.text && /API call/ =~ reason.text.to_s
logger.info "skipping api unsub for '#{email}'"
else
u = User.find_by_auth_email email
logger.warn "unable to find '#{email}' for master unsubscribe" and next unless u
if u.email_opt_in
u.email_opt_in = false
if u.save
logger.info "unsubscribed '#{email}'"
else
logger.warn "unable to save user #{u.id} while updating from master unsub retrieve:\n#{u.errors.full_messages.join("\n")}"
end
else
logger.info "skipping '#{email}': already master unsubscribed"
end
end
end
return true
end
private
def date_from_xml(root, xpath)
node = REXML::XPath.first root, xpath
return nil unless node
Date.parse node.text
end
end
|
class AddFileToJuristicDocument < ActiveRecord::Migration[5.0]
def self.up
change_table :juristic_documents do |t|
t.attachment :eugrl
end
end
end
|
class CreateCsvmngrs < ActiveRecord::Migration
def change
create_table :csvmngrs do |t|
t.string :instructor
t.string :email
t.integer :courseid
t.string :filename
t.timestamps
end
end
end
|
#!/usr/bin/env ruby
require 's3-wrapper'
command = ARGV.shift
if command == "config-default"
params = Hash[ ARGV.join(' ').scan(/([^=\s]+)(?:=(\S+))?/) ]
profile = S3Wrapper::Profile.config_default(params)
if profile
puts "configured default"
else
puts "failed to configure default"
end
else
profile_name = ARGV.shift
profile = S3Wrapper::Profile.get(profile_name)
case command
when "create-profile"
params = Hash[ ARGV.join(' ').scan(/([^=\s]+)(?:=(\S+))?/) ]
profile = S3Wrapper::Profile.create(profile_name, params)
puts "created #{profile.name}" if profile
when "get-profile"
if profile
puts "name: #{profile.name}"
puts "aws_access_key: #{profile.aws_access_key}"
puts "aws_secret_key: #{profile.aws_secret_key}"
puts "bucket_name: #{profile.bucket_name}"
puts "host_name: #{profile.host_name}"
end
when "delete-profile"
S3Wrapper::Profile.delete(profile.name)
when "upload"
if profile
S3Wrapper.upload_files(profile, ARGV)
puts "done"
end
end
end
|
require 'puppet'
Puppet::Type.newtype(:purge) do
attr_reader :purged_resources
@doc=(<<-EOT)
This is a metatype to purge resources from the agent. When run without
parameters the purge type takes a resource type as a title. The
resource type must be one that has a provider that supports the instances
method (eg: package, user, yumrepo). Any instances of the resource found
on the agent that are *not* in the catalog will be purged.
You can also add filter conditions to control the behaviour of purge
using the if and unless parameters.
Eg:
To remove *all* users found on the system that are not present in the
catalog (caution!):
purge { 'user': }
To remove all users found on the system but not in the catalog, unless
the user has a UID below 500:
purge { 'user':
unless => [ 'uid', '<=', '500' ],
}
EOT
# The ensurable block is mostly to make sure that this resource type
# will enter a changed state when there are resources that have been
# purged, that signals to puppet that any refresh events associated
# with this resource, like notify, should be triggered.
#
ensurable do
defaultto(:purged)
newvalue(:purgable)
newvalue(:purged) do
true
end
def retrieve
if @resource.purged?
:purgable
else
:purged
end
end
end
# By setting @isomorphic to false Puppet will allow duplicate namevars
# (not duplicate titles). This allows for multiple purge resource types
# to be declared purging the same resource type with different criteria
#
@isomorphic = false
newparam(:resource_type) do
isnamevar
desc "Name of the resource type to be purged"
validate do |name|
raise ArgumentError, "Unknown resource type #{name}" unless Puppet::Type.type(name)
end
end
newparam(:manage_property) do
desc <<-EOT
The manage property parameter defined which property to manage on the resource.
The property defined here will be set with the value of `state` and then
the `sync` method is called on the resources property.
`manage_property` defaults to "ensure"
EOT
defaultto :ensure
end
newparam(:state) do
desc <<-EOT
Define the desired state of the purged resources. This sets the value of the
property defined in `manage_property` before `sync` is called on the property.
`state` defaults to "absent"
EOT
defaultto :absent
end
[ :unless, :if ]. each do |param_name|
newparam(param_name, :array_matching => :all) do
desc(<<-EOT)
Purge resources #{param_name.to_s} they meet the criteria.
Criteria is defined as an array of "parameter", "operator", and "value".
Eg:
#{param_name.to_s} => [ 'name', '==', 'root' ]
Operators can support "!=","==","=~",">","<","<=",">=" as an argument
Value can be a string, integer or regex (without the enclosing slashes)
Multiple criterias can be nested in an array, eg:
#{param_name.to_s} => [
[ 'name', '==', 'root' ], [ 'name', '=~', 'admin.*' ]
]
EOT
validate do |cond|
raise ArgumentError, "must be an array" unless cond.is_a?(Array)
end
munge do |cond|
if cond[0].is_a?(Array)
cond
else
[ cond ]
end
end
validate do |cond_param|
case cond_param[0]
when String
cond = [ cond_param ]
when Array
cond = cond_param
end
cond.each do |param, operator, value|
unless ["!=","==","=~",">","<","<=",">="].include?(operator)
raise ArgumentError, "invalid operator #{operator}"
end
unless param && operator && value
raise ArgumentError, "not enough parameters given for filter"
end
end
end
end
end
def manage_property
self[:manage_property].to_sym
end
def state
self[:state]
end
def generate
klass = Puppet::Type.type(self[:name])
unless klass.validproperty?(manage_property)
err "Purge of resource type #{self[:name]} failed, #{manage_property} is not a valid property"
end
resource_instances = klass.instances
metaparams = @parameters.select { |n, p| p.metaparam? }
@purged_resources = []
## Don't try and purge things that are in the catalog
resource_instances.reject!{ |r| catalog.resource_refs.include? r.ref }
## Don't purge things that have been filtered with if/unless
resource_instances = resource_instances.select { |r| purge?(r) }
## Don't purge things that are already in sync
resource_instances = resource_instances.reject { |r|
is = begin
r.property(manage_property).retrieve
rescue NoMethodError
r.retrieve[manage_property]
end
should = is.is_a?(Symbol) ? state.to_sym : state
is == should
}
if resource_instances.length > 0
resource_instances.each do |res|
res.property(manage_property).should=(state)
# Whatever metaparameters we have assigned we allocate to the
# purged resource, this sets the same relationships on the resource
# we are purging that we have in this resource.
@parameters.each do |name, param|
res[name] = param.value if param.metaparam?
end
Puppet.debug("Purging resource #{res.ref} with #{manage_property} => #{state}")
@purged_resources << res
end
end
@purged_resources
end
# This method is called from the ensure block after generate() has
# identified resources to purge. If it returns true then it indiciates
# that resources have been purged and therefore puts the purge resource
# in a changed state so it can be used in refresh event relationships
# (notify, subscribe...etc) in Puppet.
#
def purged?
purged_resources.length > 0
end
# purge will evaluate the conditions given in if/unless
def purge?(res_type)
res = res_type.to_resource.to_hash
if self[:unless]
return false unless evaluate_resource(res, self[:unless])
end
if self[:if]
return false if evaluate_resource(res, self[:if])
end
return true
end
# evaluate_resources loops through the array of param, operator, value
# and returns true if any of the criteria match
#
def evaluate_resource(res,condition)
condition.select { |param, operator, value_attr|
Array(value_attr).select { |value|
Array(res[param.to_sym]).select { |p|
case operator
when "!=", "=="
p.to_s.send(operator, value)
when "=~"
p =~ Regexp.new(value)
when ">=", "<=", ">", "<"
p.to_i.send(operator, value.to_i)
end
}.length > 0
}.length > 0
}.length == 0
end
end
|
def palindrome?(text)
if text == ""
return true
end
text.downcase!.gsub!(/\W/, '')
text == text.reverse
end
print "Palindrome?:\n"
print "A man, a plan, a canal -- Panama", "\t=>\t", palindrome?("A man, a plan, a canal -- Panama"), "\n"
print "Madam, I'm Adam!", "\t=>\t", palindrome?("Madam, I'm Adam!"), "\n"
print "Abracadabra", "\t=>\t", palindrome?("Abracadabra"), "\n"
print "", "\t=>\t", palindrome?(""), "\n\n"
def count_words(text)
if text == ""
return {}
end
text.downcase!.gsub!(/\W/, ' ')
cnt = {}
for word in text.split(' ')
if cnt.key?(word)
cnt[word] += 1
else
cnt[word] = 1
end
end
cnt
end
print "Count_words:\n"
print "A man, a plan, a canal -- Panama", "\t=>\t", count_words("A man, a plan, a canal -- Panama"), "\n"
print "Madam, I'm Adam!", "\t=>\t", count_words("Madam, I'm Adam!"), "\n"
print "Abracadabra", "\t=>\t", count_words("Abracadabra"), "\n"
print "AAa aaA aAa" , "\t=>\t", count_words("AAa aaA aAa"), "\n"
print "", "\t=>\t", count_words(""), "\n\n"
def same23?(arr)
if arr.length != 5
return false
end
cnt = {'a'=>0, 'b'=>0, 'c'=>0}
for el in arr
cnt[el] += 1
end
c = cnt.values.sort
c[1] == 2 and c[2] == 3
end
print "Same23?:\n"
print ["a", "a", "a", "b", "b"], "\t=>\t", same23?(["a", "a", "a", "b", "b"]), "\n"
print ["a", "b", "c", "b", "c"], "\t=>\t", same23?(["a", "b", "c", "b", "c"]), "\n"
print ["a", "a", "a", "a", "a"], "\t=>\t", same23?(["a", "a", "a", "a", "a"]), "\n"
|
class CreateSlices < ActiveRecord::Migration
def change
create_table :slices do |t|
t.integer :use_case_id
t.integer :priority
t.string :workflow_state
t.string :estimate
t.integer :release_id
t.integer :order_priority
t.timestamps
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2014-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
# Client-side representation of an iterator over a query result set on
# the server.
#
# +Cursor+ objects are not directly exposed to application code. Rather,
# +Collection::View+ exposes the +Enumerable+ interface to the applications,
# and the enumerator is backed by a +Cursor+ instance.
#
# @example Get an array of 5 users named Emily.
# users.find({:name => 'Emily'}).limit(5).to_a
#
# @example Call a block on each user doc.
# users.find.each { |doc| puts doc }
#
# @api private
class Cursor
extend Forwardable
include Enumerable
include Retryable
def_delegators :@view, :collection
def_delegators :collection, :client, :database
def_delegators :@server, :cluster
# @return [ Collection::View ] view The collection view.
attr_reader :view
# The resume token tracked by the cursor for change stream resuming
#
# @return [ BSON::Document | nil ] The cursor resume token.
# @api private
attr_reader :resume_token
# Creates a +Cursor+ object.
#
# @example Instantiate the cursor.
# Mongo::Cursor.new(view, response, server)
#
# @param [ CollectionView ] view The +CollectionView+ defining the query.
# @param [ Operation::Result ] result The result of the first execution.
# @param [ Server ] server The server this cursor is locked to.
# @param [ Hash ] options The cursor options.
#
# @option options [ true, false ] :disable_retry Whether to disable
# retrying on error when sending getMore operations (deprecated, getMore
# operations are no longer retried)
# @option options [ true, false ] :retry_reads Retry reads (following
# the modern mechanism), default is true
#
# @since 2.0.0
def initialize(view, result, server, options = {})
unless result.is_a?(Operation::Result)
raise ArgumentError, "Second argument must be a Mongo::Operation::Result: #{result.inspect}"
end
@view = view
@server = server
@initial_result = result
@namespace = result.namespace
@remaining = limit if limited?
set_cursor_id(result)
if @cursor_id.nil?
raise ArgumentError, 'Cursor id must be present in the result'
end
@connection_global_id = result.connection_global_id
@options = options
@session = @options[:session]
@explicitly_closed = false
@lock = Mutex.new
unless closed?
register
ObjectSpace.define_finalizer(self, self.class.finalize(kill_spec(@connection_global_id),
cluster))
end
end
# @api private
attr_reader :server
# @api private
attr_reader :initial_result
# Finalize the cursor for garbage collection. Schedules this cursor to be included
# in a killCursors operation executed by the Cluster's CursorReaper.
#
# @param [ Cursor::KillSpec ] kill_spec The KillCursor operation specification.
# @param [ Mongo::Cluster ] cluster The cluster associated with this cursor and its server.
#
# @return [ Proc ] The Finalizer.
#
# @api private
def self.finalize(kill_spec, cluster)
unless KillSpec === kill_spec
raise ArgumentError, "First argument must be a KillSpec: #{kill_spec.inspect}"
end
proc do
cluster.schedule_kill_cursor(kill_spec)
end
end
# Get a human-readable string representation of +Cursor+.
#
# @example Inspect the cursor.
# cursor.inspect
#
# @return [ String ] A string representation of a +Cursor+ instance.
#
# @since 2.0.0
def inspect
"#<Mongo::Cursor:0x#{object_id} @view=#{@view.inspect}>"
end
# Iterate through documents returned from the query.
#
# A cursor may be iterated at most once. Incomplete iteration is also
# allowed. Attempting to iterate the cursor more than once raises
# InvalidCursorOperation.
#
# @example Iterate over the documents in the cursor.
# cursor.each do |doc|
# ...
# end
#
# @return [ Enumerator ] The enumerator.
#
# @since 2.0.0
def each
# If we already iterated past the first batch (i.e., called get_more
# at least once), the cursor on the server side has advanced past
# the first batch and restarting iteration from the beginning by
# returning initial result would miss documents in the second batch
# and subsequent batches up to wherever the cursor is. Detect this
# condition and abort the iteration.
#
# In a future driver version, each would either continue from the
# end of previous iteration or would always restart from the
# beginning.
if @get_more_called
raise Error::InvalidCursorOperation, 'Cannot restart iteration of a cursor which issued a getMore'
end
# To maintain compatibility with pre-2.10 driver versions, reset
# the documents array each time a new iteration is started.
@documents = nil
if block_given?
# StopIteration raised by try_next ends this loop.
loop do
document = try_next
if explicitly_closed?
raise Error::InvalidCursorOperation, 'Cursor was explicitly closed'
end
yield document if document
end
self
else
documents = []
# StopIteration raised by try_next ends this loop.
loop do
document = try_next
if explicitly_closed?
raise Error::InvalidCursorOperation, 'Cursor was explicitly closed'
end
documents << document if document
end
documents
end
end
# Return one document from the query, if one is available.
#
# This method will wait up to max_await_time_ms milliseconds
# for changes from the server, and if no changes are received
# it will return nil. If there are no more documents to return
# from the server, or if we have exhausted the cursor, it will
# raise a StopIteration exception.
#
# @note This method is experimental and subject to change.
#
# @return [ BSON::Document | nil ] A document.
#
# @raise [ StopIteration ] Raised on the calls after the cursor had been
# completely iterated.
#
# @api private
def try_next
if @documents.nil?
# Since published versions of Mongoid have a copy of old driver cursor
# code, our dup call in #process isn't invoked when Mongoid query
# cache is active. Work around that by also calling dup here on
# the result of #process which might come out of Mongoid's code.
@documents = process(@initial_result).dup
# the documents here can be an empty array, hence
# we may end up issuing a getMore in the first try_next call
end
if @documents.empty?
# On empty batches, we cache the batch resume token
cache_batch_resume_token
unless closed?
if exhausted?
close
@fully_iterated = true
raise StopIteration
end
@documents = get_more
else
@fully_iterated = true
raise StopIteration
end
else
# cursor is closed here
# keep documents as an empty array
end
# If there is at least one document, cache its _id
if @documents[0]
cache_resume_token(@documents[0])
end
# Cache the batch resume token if we are iterating
# over the last document, or if the batch is empty
if @documents.size <= 1
cache_batch_resume_token
if closed?
@fully_iterated = true
end
end
return @documents.shift
end
# Get the batch size.
#
# @example Get the batch size.
# cursor.batch_size
#
# @return [ Integer ] The batch size.
#
# @since 2.2.0
def batch_size
value = @view.batch_size && @view.batch_size > 0 ? @view.batch_size : limit
if value == 0
nil
else
value
end
end
# Is the cursor closed?
#
# @example Is the cursor closed?
# cursor.closed?
#
# @return [ true, false ] If the cursor is closed.
#
# @since 2.2.0
def closed?
# @cursor_id should in principle never be nil
@cursor_id.nil? || @cursor_id == 0
end
# Closes this cursor, freeing any associated resources on the client and
# the server.
#
# @return [ nil ] Always nil.
def close
return if closed?
unregister
read_with_one_retry do
spec = {
coll_name: collection_name,
db_name: database.name,
cursor_ids: [id],
}
op = Operation::KillCursors.new(spec)
execute_operation(op)
end
nil
rescue Error::OperationFailure, Error::SocketError, Error::SocketTimeoutError, Error::ServerNotUsable
# Errors are swallowed since there is noting can be done by handling them.
ensure
end_session
@cursor_id = 0
@lock.synchronize do
@explicitly_closed = true
end
end
# Get the parsed collection name.
#
# @example Get the parsed collection name.
# cursor.coll_name
#
# @return [ String ] The collection name.
#
# @since 2.2.0
def collection_name
# In most cases, this will be equivalent to the name of the collection
# object in the driver. However, in some cases (e.g. when connected
# to an Atlas Data Lake), the namespace returned by the find command
# may be different, which is why we want to use the collection name based
# on the namespace in the command result.
if @namespace
# Often, the namespace will be in the format "database.collection".
# However, sometimes the collection name will contain periods, which
# is why this method joins all the namespace components after the first.
ns_components = @namespace.split('.')
ns_components[1...ns_components.length].join('.')
else
collection.name
end
end
# Get the cursor id.
#
# @example Get the cursor id.
# cursor.id
#
# @note A cursor id of 0 means the cursor was closed on the server.
#
# @return [ Integer ] The cursor id.
#
# @since 2.2.0
def id
@cursor_id
end
# Get the number of documents to return. Used on 3.0 and lower server
# versions.
#
# @example Get the number to return.
# cursor.to_return
#
# @return [ Integer ] The number of documents to return.
#
# @since 2.2.0
def to_return
use_limit? ? @remaining : (batch_size || 0)
end
# Execute a getMore command and return the batch of documents
# obtained from the server.
#
# @return [ Array<BSON::Document> ] The batch of documents
#
# @api private
def get_more
@get_more_called = true
# Modern retryable reads specification prohibits retrying getMores.
# Legacy retryable read logic used to retry getMores, but since
# doing so may result in silent data loss, the driver no longer retries
# getMore operations in any circumstance.
# https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#qa
process(execute_operation(get_more_operation))
end
# @api private
def kill_spec(connection_global_id)
KillSpec.new(
cursor_id: id,
coll_name: collection_name,
db_name: database.name,
connection_global_id: connection_global_id,
server_address: server.address,
session: @session,
)
end
# @api private
def fully_iterated?
!!@fully_iterated
end
private
def explicitly_closed?
@lock.synchronize do
@explicitly_closed
end
end
def batch_size_for_get_more
if batch_size && use_limit?
[batch_size, @remaining].min
else
batch_size
end
end
def exhausted?
limited? ? @remaining <= 0 : false
end
def cache_resume_token(doc)
if doc[:_id] && doc[:_id].is_a?(Hash)
@resume_token = doc[:_id] && doc[:_id].dup.freeze
end
end
def cache_batch_resume_token
@resume_token = @post_batch_resume_token if @post_batch_resume_token
end
def get_more_operation
spec = {
session: @session,
db_name: database.name,
coll_name: collection_name,
cursor_id: id,
# 3.2+ servers use batch_size, 3.0- servers use to_return.
# TODO should to_return be calculated in the operation layer?
batch_size: batch_size_for_get_more,
to_return: to_return,
max_time_ms: if view.respond_to?(:max_await_time_ms) &&
view.max_await_time_ms &&
view.options[:await_data]
then
view.max_await_time_ms
else
nil
end,
}
if view.respond_to?(:options) && view.options.is_a?(Hash)
spec[:comment] = view.options[:comment] unless view.options[:comment].nil?
end
Operation::GetMore.new(spec)
end
def end_session
@session.end_session if @session && @session.implicit?
end
def limited?
limit ? limit > 0 : false
end
def process(result)
@remaining -= result.returned_count if limited?
# #process is called for the first batch of results. In this case
# the @cursor_id may be zero (all results fit in the first batch).
# Thus we need to check both @cursor_id and the cursor_id of the result
# prior to calling unregister here.
unregister if !closed? && result.cursor_id == 0
@cursor_id = set_cursor_id(result)
if result.respond_to?(:post_batch_resume_token)
@post_batch_resume_token = result.post_batch_resume_token
end
end_session if closed?
# Since our iteration code mutates the documents array by calling #shift
# on it, duplicate the documents here to permit restarting iteration
# from the beginning of the cursor as long as get_more was not called
result.documents.dup
end
def use_limit?
limited? && batch_size >= @remaining
end
def limit
@view.send(:limit)
end
def register
cluster.register_cursor(@cursor_id)
end
def unregister
cluster.unregister_cursor(@cursor_id)
end
def execute_operation(op)
context = Operation::Context.new(
client: client,
session: @session,
connection_global_id: @connection_global_id,
)
op.execute(@server, context: context)
end
# Sets @cursor_id from the operation result.
#
# In the operation result cursor id can be represented either as Integer
# value or as BSON::Int64. This method ensures that the instance variable
# is always of type Integer.
#
# @param [ Operation::Result ] result The result of the operation.
#
# @api private
def set_cursor_id(result)
@cursor_id = if result.cursor_id.is_a?(BSON::Int64)
result.cursor_id.value
else
result.cursor_id
end
end
end
end
require 'mongo/cursor/kill_spec'
|
require 'minitest_helper'
describe JsonStructure::Object_ do
describe 'not specifying object structure' do
it do
js = build { object }
assert js === {'abc' => 'xyz'}
refute js === ['a', 12]
end
end
describe 'specifying object structure' do
it do
js = build {
object(
foo: string,
bar: number,
)
}
assert js === {
'foo' => 'abc',
'bar' => 12221,
}
refute js === {
'foo' => [1, 2, 3],
'bar' => 122,
}
end
end
end
|
class InvoicesController < ApplicationController
before_action :authenticate_vendor!
def index
@invoices = current_vendor.invoices
end
def new
@invoice = current_vendor.invoices.build
end
def create
@invoice = current_vendor.invoices.build(invoice_params)
response = create_stripe_plan(current_vendor, @invoice)
@invoice.id_for_plan = response.id
respond_to do |format|
if @invoice.save
format.html { redirect_to invoices_path, notice: 'Invoice successfully created!' }
else
format.html { render :new }
format.json { render json: @invoice.errors, status: :unprocessable_entity }
end
end
end
private
def invoice_params
params.require(:invoice).permit(:name, :description, :amount)
end
def create_stripe_plan(vendor, invoice)
Stripe::Plan.create(
{
amount: invoice.amount * 100,
interval: 'month',
name: invoice.name,
currency: 'usd',
id: invoice.name + Invoice.maximum(:id).to_i.next.to_s
},
stripe_account: vendor.stripe_uid
)
end
end
|
FactoryBot.define do
factory :piggy_bank, class: PiggyBank do
name 'PS4 Games'
currency 'CAD'
description 'My PS4 Games'
balance 200.0
total_credit 0.0
total_debit 0.0
association :user, factory: [:user, :random_email]
end
end
|
require 'pad'
module DiceOfDebt
# Define empty Game to allow Virtus attribute to reference it
# TODO: try using Virtus finalization
class Game
end
# The Iteration class is responsible for keeping track of the value, debt and overall score for each iteration.
class Iteration
include Pad.entity
attr_reader :value, :debt
attribute :game, Game
attribute :value, Integer, default: 0
attribute :debt, Integer, default: 0
attribute :status, Symbol, default: :started
def roll_dice(fixed_rolls = {})
dice.roll(fixed_rolls).tap do
self.value = dice[:value].score
self.debt = dice[:debt].score
end
end
def score
value - debt
end
def end
self.status = :complete
end
def complete?
status == :complete
end
def dice
game.dice
end
end
end
|
class ChangeColumnInAttendences < ActiveRecord::Migration[5.2]
def change
change_column :attendences, :date, :date, default: Time.now.strftime('%Y/%m/%d')
end
end
|
require "becoming/version"
module Becoming
def becoming(mod)
@becoming = mod
end
def method_missing(m, *args, &blk)
if @becoming && @becoming.public_method_defined?(m)
@becoming.instance_method(m).bind(self).call(*args, &blk)
else
super
end
end
def respond_to_missing?(m, include_all=false)
if @becoming && @becoming.public_method_defined?(m)
true
else
super
end
end
end
module Becoming
module NullObject
def self.public_method_defined?(m)
true
end
def self.instance_method(m)
ByPass.instance_method(:bypass)
end
module ByPass
def bypass(*args, &blk); end
end
end
end
|
# frozen_string_literal: true
class PeopleController < ApplicationController
before_action :set_person, only: %i[show detail edit update destroy]
# GET /people
def index
@q = Person.includes(:house)
.order(last: :asc, first: :asc, middle: :asc)
.ransack(params[:q])
@pagy, @people = pagy(@q.result)
end
# GET /people/1
def show; end
# GET /people/1/detail
def detail; end
# GET /people/new
def new
@person = Person.new
@disable_house_select = false
end
# GET /people/occupant/<house_id>
def new_occupant
redirect_to houses_path and return unless house_id
@person = Person.new(house_id: house_id)
@disable_house_select = true
end
# GET /people/1/edit
def edit
@disable_house_select = false
end
# POST /people
def create
@person = Person.create(person_params)
if @person.save
redirect_to @person, notice: 'Person was successfully created.'
else
render :new
end
end
# PATCH/PUT /people/1
def update
if @person.update(person_params)
redirect_to @person, notice: 'Person was successfully updated.'
else
render :edit
end
end
# DELETE /people/1
def destroy
@person.destroy
redirect_to people_url, notice: 'Person was successfully destroyed.'
end
private
def set_person
@person = Person.find(params[:id])
end
def person_params
params.require(:person).permit(:nickname, :first, :middle, :last, :suffix, :honorific,
:note, :house_id, :role, :status)
end
def house_id
@house_id ||= existing_house_id
end
def existing_house_id
House.find(house_id_as_UUID_from_params).id
rescue ActiveRecord::RecordNotFound
nil
end
def house_id_as_UUID_from_params
params[:house_id].match(SharedRegexp::UUID_FORMAT)[0]
end
end
|
class CreateChanges < ActiveRecord::Migration
def change
create_table :changes do |t|
t.string :action
t.string :pid
t.datetime :time
t.string :board_pid
t.string :sprint_pid
t.string :location
t.string :status
t.string :associated_story_pid
t.string :associated_subtask_pid
t.string :new_value
t.string :current_story_value
t.integer :board_id
t.integer :sprint_id
t.integer :sprint_story_id
t.integer :subtask_id
t.boolean :is_done
t.timestamps
end
end
end
|
require 'spec_helper'
describe Contentr::Admin::PagesController do
describe '#show' do
it 'displays the page\'s areas' do
contentpage_two = create(:contentpage, name: 'bar', slug: 'bar')
visit contentr.admin_page_path(id: contentpage_two)
contentpage_two.areas.each do |area|
expect(page.all('.panel-title')).to have_content(area)
end
end
it 'is able to add paragraphs to areas', js: true do
contentr_page = create(:contentpage, name: 'bar', slug: 'bar')
visit contentr.admin_page_path(id: contentr_page)
within('#area-left_column .new-paragraph-buttons') do
click_link 'HTML'
end
within('.existing-paragraphs form') do
fill_in 'Body', with: 'hello world!'
click_button 'Save Paragraph'
end
expect(page.find(".paragraph")).to have_content('hello world!')
end
it "resets the publish button if i click on it", js: true do
contentpage = create(:contentpage_with_paragraphs)
@para = contentpage.paragraphs.first
@para.body = "hell yeah"
@para.save!
visit(contentr.admin_page_path(contentpage))
expect(page).to_not have_content('No Unpublished Changes')
within("#paragraph_#{@para.id}") do
click_link("Publish!")
end
expect(page).to have_content("No Unpublished Changes")
end
it "shows the paragraphs of the page" do
contentpage = create(:contentpage_with_paragraphs)
visit(contentr.admin_page_path(contentpage))
expect(page.all(:css, '.existing-paragraphs').count).to be(4)
end
it "deletes a paragraph when i click on delete" do
contentpage = create(:contentpage_with_paragraphs)
expect(contentpage.paragraphs.count).to be 2
visit(contentr.admin_page_path(contentpage))
within("#paragraph_1") do
page.find("a.remove-paragraph-btn").click
end
expect(contentpage.paragraphs.count).to be 1
end
it "shows the unpublished version of a paragraph if there is one" do
contentpage = create(:contentpage_with_paragraphs)
para = contentpage.paragraphs.first
para.body = "hell yeah!"
para.save!
visit(contentr.admin_page_path(contentpage))
expect(page).to have_content("hell yeah!")
end
it 'lets the user add content blocks', js: true do
create(:site)
contentpage = create(:contentpage_with_paragraphs)
article = create(:article, title: 'My new article')
content_block = create(:content_block, name: 'Artikel anzeigen',
partial: '_article')
visit(contentr.admin_page_path(contentpage))
expect(page.all('.existing-paragraphs')).not_to have_content('Artikel anzeigen')
within('#area-center_column .new-paragraph-buttons') do
click_link 'Content Block'
end
within('.existing-paragraphs form') do
select 'Artikel anzeigen', from: 'Content block to display'
click_button 'Save Paragraph'
end
expect(page.find('.existing-paragraphs[data-area="area-center_column"]')).to have_content(article.title)
end
it 'loads existing content blocks' do
create(:site)
article = create(:article)
contentpage = create(:contentpage_with_content_block_paragraph)
visit(contentr.admin_page_path(contentpage))
expect(page.find('.existing-paragraphs[data-area="area-center_column"]')).to have_content(article.title)
end
end
end
|
FactoryBot.define do
factory :question do
content 'How many vowels are there in English Alphabet?'
answer 5
published true
# association :teacher, factory: :teacher
end
factory :another_question, class: Question do
content 'How many vowels are there in Filipino Alphabet?'
answer 'five'
published true
end
factory :invalid_question, class: Question do
content ''
answer ''
published ''
teacher_id ''
end
end
|
class AddDisplayFormatToSections < ActiveRecord::Migration[5.0]
def change
add_column :sections, :display_format, :json
end
end
|
# frozen_string_literal: true
require "abstract_unit"
require "active_model"
require "controller/fake_models"
class ApplicationController < ActionController::Base
self.view_paths = File.join(FIXTURE_LOAD_PATH, "actionpack")
end
module Quiz
# Models
Question = Struct.new(:name, :id) do
extend ActiveModel::Naming
include ActiveModel::Conversion
def persisted?
id.present?
end
end
# Controller
class QuestionsController < ApplicationController
def new
render partial: Quiz::Question.new("Namespaced Partial")
end
end
end
module Fun
class GamesController < ApplicationController
def hello_world; end
def nested_partial_with_form_builder
render partial: ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {})
end
end
end
class TestController < ApplicationController
protect_from_forgery
before_action :set_variable_for_layout
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
end
layout :determine_layout
def name
nil
end
private :name
helper_method :name
def hello_world
end
def hello_world_file
render file: File.expand_path("../../fixtures/actionpack/hello", __dir__), formats: [:html]
end
# :ported:
def render_hello_world
render "test/hello_world"
end
def render_hello_world_with_last_modified_set
response.last_modified = Date.new(2008, 10, 10).to_time
render "test/hello_world"
end
# :ported: compatibility
def render_hello_world_with_forward_slash
render "/test/hello_world"
end
# :ported:
def render_template_in_top_directory
render template: "shared"
end
# :deprecated:
def render_template_in_top_directory_with_slash
render "/shared"
end
# :ported:
def render_hello_world_from_variable
@person = "david"
render plain: "hello #{@person}"
end
# :ported:
def render_action_hello_world
render action: "hello_world"
end
def render_action_upcased_hello_world
render action: "Hello_world"
end
def render_action_hello_world_as_string
render "hello_world"
end
def render_action_hello_world_with_symbol
render action: :hello_world
end
# :ported:
def render_text_hello_world
render plain: "hello world"
end
# :ported:
def render_text_hello_world_with_layout
@variable_for_layout = ", I am here!"
render plain: "hello world", layout: true
end
def hello_world_with_layout_false
render layout: false
end
# :ported:
def render_file_with_instance_variables
@secret = "in the sauce"
path = File.expand_path("../../fixtures/test/render_file_with_ivar", __dir__)
render file: path
end
# :ported:
def render_file_not_using_full_path
@secret = "in the sauce"
render file: "test/render_file_with_ivar"
end
def render_file_not_using_full_path_with_dot_in_path
@secret = "in the sauce"
render file: "test/dot.directory/render_file_with_ivar"
end
def render_file_using_pathname
@secret = "in the sauce"
render file: Pathname.new(__dir__).join("..", "..", "fixtures", "test", "dot.directory", "render_file_with_ivar")
end
def render_file_from_template
@secret = "in the sauce"
@path = File.expand_path("../../fixtures/test/render_file_with_ivar", __dir__)
end
def render_file_with_locals
path = File.expand_path("../../fixtures/test/render_file_with_locals", __dir__)
render file: path, locals: { secret: "in the sauce" }
end
def render_file_as_string_with_locals
path = File.expand_path("../../fixtures/test/render_file_with_locals", __dir__)
render file: path, locals: { secret: "in the sauce" }
end
def accessing_request_in_template
render inline: "Hello: <%= request.host %>"
end
def accessing_logger_in_template
render inline: "<%= logger.class %>"
end
def accessing_action_name_in_template
render inline: "<%= action_name %>"
end
def accessing_controller_name_in_template
render inline: "<%= controller_name %>"
end
# :ported:
def render_custom_code
render plain: "hello world", status: 404
end
# :ported:
def render_text_with_nil
render plain: nil
end
# :ported:
def render_text_with_false
render plain: false
end
def render_text_with_resource
render plain: Customer.new("David")
end
# :ported:
def render_nothing_with_appendix
render plain: "appended"
end
# This test is testing 3 things:
# render :file in AV :ported:
# render :template in AC :ported:
# setting content type
def render_xml_hello
@name = "David"
render template: "test/hello"
end
def render_xml_hello_as_string_template
@name = "David"
render "test/hello"
end
def render_line_offset
render inline: "<% raise %>", locals: { foo: "bar" }
end
def heading
head :ok
end
def greeting
# let's just rely on the template
end
# :ported:
def blank_response
render plain: " "
end
# :ported:
def layout_test
render action: "hello_world"
end
# :ported:
def builder_layout_test
@name = nil
render action: "hello", layout: "layouts/builder"
end
# :move: test this in Action View
def builder_partial_test
render action: "hello_world_container"
end
# :ported:
def partials_list
@test_unchanged = "hello"
@customers = [ Customer.new("david"), Customer.new("mary") ]
render action: "list"
end
def partial_only
render partial: true
end
def hello_in_a_string
@customers = [ Customer.new("david"), Customer.new("mary") ]
render plain: "How's there? " + render_to_string(template: "test/list")
end
def accessing_params_in_template
render inline: "Hello: <%= params[:name] %>"
end
def accessing_local_assigns_in_inline_template
name = params[:local_name]
render inline: "<%= 'Goodbye, ' + local_name %>",
locals: { local_name: name }
end
def render_implicit_html_template_from_xhr_request
end
def render_implicit_js_template_without_layout
end
def formatted_html_erb
end
def formatted_xml_erb
end
def render_to_string_test
@foo = render_to_string inline: "this is a test"
end
def default_render
@alternate_default_render ||= nil
if @alternate_default_render
@alternate_default_render.call
else
super
end
end
def render_action_hello_world_as_symbol
render action: :hello_world
end
def layout_test_with_different_layout
render action: "hello_world", layout: "standard"
end
def layout_test_with_different_layout_and_string_action
render "hello_world", layout: "standard"
end
def layout_test_with_different_layout_and_symbol_action
render :hello_world, layout: "standard"
end
def rendering_without_layout
render action: "hello_world", layout: false
end
def layout_overriding_layout
render action: "hello_world", layout: "standard"
end
def rendering_nothing_on_layout
head :ok
end
def render_to_string_with_assigns
@before = "i'm before the render"
render_to_string plain: "foo"
@after = "i'm after the render"
render template: "test/hello_world"
end
def render_to_string_with_exception
render_to_string file: "exception that will not be caught - this will certainly not work"
end
def render_to_string_with_caught_exception
@before = "i'm before the render"
begin
render_to_string file: "exception that will be caught- hope my future instance vars still work!"
rescue
end
@after = "i'm after the render"
render template: "test/hello_world"
end
def accessing_params_in_template_with_layout
render layout: true, inline: "Hello: <%= params[:name] %>"
end
# :ported:
def render_with_explicit_template
render template: "test/hello_world"
end
def render_with_explicit_unescaped_template
render template: "test/h*llo_world"
end
def render_with_explicit_escaped_template
render template: "test/hello,world"
end
def render_with_explicit_string_template
render "test/hello_world"
end
# :ported:
def render_with_explicit_template_with_locals
render template: "test/render_file_with_locals", locals: { secret: "area51" }
end
# :ported:
def double_render
render plain: "hello"
render plain: "world"
end
def double_redirect
redirect_to action: "double_render"
redirect_to action: "double_render"
end
def render_and_redirect
render plain: "hello"
redirect_to action: "double_render"
end
def render_to_string_and_render
@stuff = render_to_string plain: "here is some cached stuff"
render plain: "Hi web users! #{@stuff}"
end
def render_to_string_with_inline_and_render
render_to_string inline: "<%= 'dlrow olleh'.reverse %>"
render template: "test/hello_world"
end
def rendering_with_conflicting_local_vars
@name = "David"
render action: "potential_conflicts"
end
def hello_world_from_rxml_using_action
render action: "hello_world_from_rxml", handlers: [:builder]
end
# :deprecated:
def hello_world_from_rxml_using_template
render template: "test/hello_world_from_rxml", handlers: [:builder]
end
def action_talk_to_layout
# Action template sets variable that's picked up by layout
end
# :addressed:
def render_text_with_assigns
@hello = "world"
render plain: "foo"
end
def render_with_assigns_option
render inline: "<%= @hello %>", assigns: { hello: "world" }
end
def yield_content_for
render action: "content_for", layout: "yield"
end
def render_content_type_from_body
response.content_type = Mime[:rss]
render body: "hello world!"
end
def render_using_layout_around_block
render action: "using_layout_around_block"
end
def render_using_layout_around_block_in_main_layout_and_within_content_for_layout
render action: "using_layout_around_block", layout: "layouts/block_with_layout"
end
def partial_formats_html
render partial: "partial", formats: [:html]
end
def partial
render partial: "partial"
end
def partial_html_erb
render partial: "partial_html_erb"
end
def render_to_string_with_partial
@partial_only = render_to_string partial: "partial_only"
@partial_with_locals = render_to_string partial: "customer", locals: { customer: Customer.new("david") }
render template: "test/hello_world"
end
def render_to_string_with_template_and_html_partial
@text = render_to_string template: "test/with_partial", formats: [:text]
@html = render_to_string template: "test/with_partial", formats: [:html]
render template: "test/with_html_partial"
end
def render_to_string_and_render_with_different_formats
@html = render_to_string template: "test/with_partial", formats: [:html]
render template: "test/with_partial", formats: [:text]
end
def render_template_within_a_template_with_other_format
render template: "test/with_xml_template",
formats: [:html],
layout: "with_html_partial"
end
def partial_with_counter
render partial: "counter", locals: { counter_counter: 5 }
end
def partial_with_locals
render partial: "customer", locals: { customer: Customer.new("david") }
end
def partial_with_form_builder
render partial: ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {})
end
def partial_with_form_builder_subclass
render partial: LabellingFormBuilder.new(:post, nil, view_context, {})
end
def partial_collection
render partial: "customer", collection: [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_as
render partial: "customer_with_var", collection: [ Customer.new("david"), Customer.new("mary") ], as: :customer
end
def partial_collection_with_iteration
render partial: "customer_iteration", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new("christine") ]
end
def partial_collection_with_as_and_iteration
render partial: "customer_iteration_with_as", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new("christine") ], as: :client
end
def partial_collection_with_counter
render partial: "customer_counter", collection: [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_as_and_counter
render partial: "customer_counter_with_as", collection: [ Customer.new("david"), Customer.new("mary") ], as: :client
end
def partial_collection_with_locals
render partial: "customer_greeting", collection: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" }
end
def partial_collection_with_spacer
render partial: "customer", spacer_template: "partial_only", collection: [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_spacer_which_uses_render
render partial: "customer", spacer_template: "partial_with_partial", collection: [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_shorthand_with_locals
render partial: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" }
end
def partial_collection_shorthand_with_different_types_of_records
render partial: [
BadCustomer.new("mark"),
GoodCustomer.new("craig"),
BadCustomer.new("john"),
GoodCustomer.new("zach"),
GoodCustomer.new("brandon"),
BadCustomer.new("dan") ],
locals: { greeting: "Bonjour" }
end
def empty_partial_collection
render partial: "customer", collection: []
end
def partial_collection_shorthand_with_different_types_of_records_with_counter
partial_collection_shorthand_with_different_types_of_records
end
def missing_partial
render partial: "thisFileIsntHere"
end
def partial_with_hash_object
render partial: "hash_object", object: { first_name: "Sam" }
end
def partial_with_nested_object
render partial: "quiz/questions/question", object: Quiz::Question.new("first")
end
def partial_with_nested_object_shorthand
render Quiz::Question.new("first")
end
def partial_hash_collection
render partial: "hash_object", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ]
end
def partial_hash_collection_with_locals
render partial: "hash_greeting", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ], locals: { greeting: "Hola" }
end
def partial_with_implicit_local_assignment
@customer = Customer.new("Marcel")
render partial: "customer"
end
def render_call_to_partial_with_layout
render action: "calling_partial_with_layout"
end
def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
render action: "calling_partial_with_layout", layout: "layouts/partial_with_layout"
end
before_action only: :render_with_filters do
request.format = :xml
end
# Ensure that the before filter is executed *before* self.formats is set.
def render_with_filters
render action: :formatted_xml_erb
end
private
def set_variable_for_layout
@variable_for_layout = nil
end
def determine_layout
case action_name
when "hello_world", "layout_test", "rendering_without_layout",
"rendering_nothing_on_layout", "render_text_hello_world",
"render_text_hello_world_with_layout",
"hello_world_with_layout_false",
"partial_only", "accessing_params_in_template",
"accessing_params_in_template_with_layout",
"render_with_explicit_template",
"render_with_explicit_string_template",
"update_page", "update_page_with_instance_variables"
"layouts/standard"
when "action_talk_to_layout", "layout_overriding_layout"
"layouts/talk_from_action"
when "render_implicit_html_template_from_xhr_request"
(request.xhr? ? "layouts/xhr" : "layouts/standard")
end
end
end
class RenderTest < ActionController::TestCase
tests TestController
def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
super
@controller.logger = ActiveSupport::Logger.new(nil)
ActionView::Base.logger = ActiveSupport::Logger.new(nil)
@request.host = "www.nextangle.com"
end
def teardown
ActionView::Base.logger = nil
end
# :ported:
def test_simple_show
get :hello_world
assert_response 200
assert_response :success
assert_equal "<html>Hello world!</html>", @response.body
end
# :ported:
def test_renders_default_template_for_missing_action
get :'hyphen-ated'
assert_equal "hyphen-ated.erb", @response.body
end
# :ported:
def test_render
get :render_hello_world
assert_equal "Hello world!", @response.body
end
def test_line_offset
exc = assert_raises ActionView::Template::Error do
get :render_line_offset
end
line = exc.backtrace.first
assert(line =~ %r{:(\d+):})
assert_equal "1", $1,
"The line offset is wrong, perhaps the wrong exception has been raised, exception was: #{exc.inspect}"
end
# :ported: compatibility
def test_render_with_forward_slash
get :render_hello_world_with_forward_slash
assert_equal "Hello world!", @response.body
end
# :ported:
def test_render_in_top_directory
get :render_template_in_top_directory
assert_equal "Elastica", @response.body
end
# :ported:
def test_render_in_top_directory_with_slash
get :render_template_in_top_directory_with_slash
assert_equal "Elastica", @response.body
end
# :ported:
def test_render_from_variable
get :render_hello_world_from_variable
assert_equal "hello david", @response.body
end
# :ported:
def test_render_action
get :render_action_hello_world
assert_equal "Hello world!", @response.body
end
def test_render_action_upcased
assert_raise ActionView::MissingTemplate do
get :render_action_upcased_hello_world
end
end
# :ported:
def test_render_action_hello_world_as_string
get :render_action_hello_world_as_string
assert_equal "Hello world!", @response.body
end
# :ported:
def test_render_action_with_symbol
get :render_action_hello_world_with_symbol
assert_equal "Hello world!", @response.body
end
# :ported:
def test_render_text
get :render_text_hello_world
assert_equal "hello world", @response.body
end
# :ported:
def test_do_with_render_text_and_layout
get :render_text_hello_world_with_layout
assert_equal "{{hello world, I am here!}}\n", @response.body
end
# :ported:
def test_do_with_render_action_and_layout_false
get :hello_world_with_layout_false
assert_equal "Hello world!", @response.body
end
# :ported:
def test_render_file_with_instance_variables
get :render_file_with_instance_variables
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file
get :hello_world_file
assert_equal "Hello world!", @response.body
end
# :ported:
def test_render_file_not_using_full_path
get :render_file_not_using_full_path
assert_equal "The secret is in the sauce\n", @response.body
end
# :ported:
def test_render_file_not_using_full_path_with_dot_in_path
get :render_file_not_using_full_path_with_dot_in_path
assert_equal "The secret is in the sauce\n", @response.body
end
# :ported:
def test_render_file_using_pathname
get :render_file_using_pathname
assert_equal "The secret is in the sauce\n", @response.body
end
# :ported:
def test_render_file_with_locals
get :render_file_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
# :ported:
def test_render_file_as_string_with_locals
get :render_file_as_string_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
# :assessed:
def test_render_file_from_template
get :render_file_from_template
assert_equal "The secret is in the sauce\n", @response.body
end
# :ported:
def test_render_custom_code
get :render_custom_code
assert_response 404
assert_response :missing
assert_equal "hello world", @response.body
end
# :ported:
def test_render_text_with_nil
get :render_text_with_nil
assert_response 200
assert_equal "", @response.body
end
# :ported:
def test_render_text_with_false
get :render_text_with_false
assert_equal "false", @response.body
end
# :ported:
def test_render_nothing_with_appendix
get :render_nothing_with_appendix
assert_response 200
assert_equal "appended", @response.body
end
def test_render_text_with_resource
get :render_text_with_resource
assert_equal 'name: "David"', @response.body
end
# :ported:
def test_attempt_to_access_object_method
assert_raise(AbstractController::ActionNotFound) { get :clone }
end
# :ported:
def test_private_methods
assert_raise(AbstractController::ActionNotFound) { get :determine_layout }
end
# :ported:
def test_access_to_request_in_view
get :accessing_request_in_template
assert_equal "Hello: www.nextangle.com", @response.body
end
def test_access_to_logger_in_view
get :accessing_logger_in_template
assert_equal "ActiveSupport::Logger", @response.body
end
# :ported:
def test_access_to_action_name_in_view
get :accessing_action_name_in_template
assert_equal "accessing_action_name_in_template", @response.body
end
# :ported:
def test_access_to_controller_name_in_view
get :accessing_controller_name_in_template
assert_equal "test", @response.body # name is explicitly set in the controller.
end
# :ported:
def test_render_xml
get :render_xml_hello
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
assert_equal "application/xml", @response.content_type
end
# :ported:
def test_render_xml_as_string_template
get :render_xml_hello_as_string_template
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
assert_equal "application/xml", @response.content_type
end
# :ported:
def test_render_xml_with_default
get :greeting
assert_equal "<p>This is grand!</p>\n", @response.body
end
# :move: test in AV
def test_render_xml_with_partial
get :builder_partial_test
assert_equal "<test>\n <hello/>\n</test>\n", @response.body
end
# :ported:
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
end
def test_render_xml_with_layouts
get :builder_layout_test
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
end
def test_partials_list
get :partials_list
assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_render_to_string
get :hello_in_a_string
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_render_to_string_resets_assigns
get :render_to_string_test
assert_equal "The value of foo is: ::this is a test::\n", @response.body
end
def test_render_to_string_inline
get :render_to_string_with_inline_and_render
assert_equal "Hello world!", @response.body
end
# :ported:
def test_nested_rendering
@controller = Fun::GamesController.new
get :hello_world
assert_equal "Living in a nested world", @response.body
end
def test_accessing_params_in_template
get :accessing_params_in_template, params: { name: "David" }
assert_equal "Hello: David", @response.body
end
def test_accessing_local_assigns_in_inline_template
get :accessing_local_assigns_in_inline_template, params: { local_name: "Local David" }
assert_equal "Goodbye, Local David", @response.body
assert_equal "text/html", @response.content_type
end
def test_should_implicitly_render_html_template_from_xhr_request
get :render_implicit_html_template_from_xhr_request, xhr: true
assert_equal "XHR!\nHello HTML!", @response.body
end
def test_should_implicitly_render_js_template_without_layout
get :render_implicit_js_template_without_layout, format: :js, xhr: true
assert_no_match %r{<html>}, @response.body
end
def test_should_render_formatted_template
get :formatted_html_erb
assert_equal "formatted html erb", @response.body
end
def test_should_render_formatted_html_erb_template
get :formatted_xml_erb
assert_equal "<test>passed formatted html erb</test>", @response.body
end
def test_should_render_formatted_html_erb_template_with_bad_accepts_header
@request.env["HTTP_ACCEPT"] = "; a=dsf"
get :formatted_xml_erb
assert_equal "<test>passed formatted html erb</test>", @response.body
end
def test_should_render_formatted_html_erb_template_with_faulty_accepts_header
@request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*"
get :formatted_xml_erb
assert_equal "<test>passed formatted html erb</test>", @response.body
end
def test_layout_test_with_different_layout
get :layout_test_with_different_layout
assert_equal "<html>Hello world!</html>", @response.body
end
def test_layout_test_with_different_layout_and_string_action
get :layout_test_with_different_layout_and_string_action
assert_equal "<html>Hello world!</html>", @response.body
end
def test_layout_test_with_different_layout_and_symbol_action
get :layout_test_with_different_layout_and_symbol_action
assert_equal "<html>Hello world!</html>", @response.body
end
def test_rendering_without_layout
get :rendering_without_layout
assert_equal "Hello world!", @response.body
end
def test_layout_overriding_layout
get :layout_overriding_layout
assert_no_match %r{<title>}, @response.body
end
def test_rendering_nothing_on_layout
get :rendering_nothing_on_layout
assert_equal "", @response.body
end
def test_render_to_string_doesnt_break_assigns
get :render_to_string_with_assigns
assert_equal "i'm before the render", @controller.instance_variable_get(:@before)
assert_equal "i'm after the render", @controller.instance_variable_get(:@after)
end
def test_bad_render_to_string_still_throws_exception
assert_raise(ActionView::MissingTemplate) { get :render_to_string_with_exception }
end
def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns
assert_nothing_raised { get :render_to_string_with_caught_exception }
assert_equal "i'm before the render", @controller.instance_variable_get(:@before)
assert_equal "i'm after the render", @controller.instance_variable_get(:@after)
end
def test_accessing_params_in_template_with_layout
get :accessing_params_in_template_with_layout, params: { name: "David" }
assert_equal "<html>Hello: David</html>", @response.body
end
def test_render_with_explicit_template
get :render_with_explicit_template
assert_response :success
end
def test_render_with_explicit_unescaped_template
assert_raise(ActionView::MissingTemplate) { get :render_with_explicit_unescaped_template }
get :render_with_explicit_escaped_template
assert_equal "Hello w*rld!", @response.body
end
def test_render_with_explicit_string_template
get :render_with_explicit_string_template
assert_equal "<html>Hello world!</html>", @response.body
end
def test_render_with_filters
get :render_with_filters
assert_equal "<test>passed formatted xml erb</test>", @response.body
end
# :ported:
def test_double_render
assert_raise(AbstractController::DoubleRenderError) { get :double_render }
end
def test_double_redirect
assert_raise(AbstractController::DoubleRenderError) { get :double_redirect }
end
def test_render_and_redirect
assert_raise(AbstractController::DoubleRenderError) { get :render_and_redirect }
end
# specify the one exception to double render rule - render_to_string followed by render
def test_render_to_string_and_render
get :render_to_string_and_render
assert_equal("Hi web users! here is some cached stuff", @response.body)
end
def test_rendering_with_conflicting_local_vars
get :rendering_with_conflicting_local_vars
assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body)
end
def test_action_talk_to_layout
get :action_talk_to_layout
assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body
end
# :addressed:
def test_render_text_with_assigns
get :render_text_with_assigns
assert_equal "world", @controller.instance_variable_get(:@hello)
end
def test_render_text_with_assigns_option
get :render_with_assigns_option
assert_equal "world", response.body
end
# :ported:
def test_template_with_locals
get :render_with_explicit_template_with_locals
assert_equal "The secret is area51\n", @response.body
end
def test_yield_content_for
get :yield_content_for
assert_equal "<title>Putting stuff in the title!</title>\nGreat stuff!\n", @response.body
end
def test_overwriting_rendering_relative_file_with_extension
get :hello_world_from_rxml_using_template
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
get :hello_world_from_rxml_using_action
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
end
def test_using_layout_around_block
get :render_using_layout_around_block
assert_equal "Before (David)\nInside from block\nAfter", @response.body
end
def test_using_layout_around_block_in_main_layout_and_within_content_for_layout
get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout
assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body
end
def test_partial_only
get :partial_only
assert_equal "only partial", @response.body
assert_equal "text/html", @response.content_type
end
def test_should_render_html_formatted_partial
get :partial
assert_equal "partial html", @response.body
assert_equal "text/html", @response.content_type
end
def test_render_html_formatted_partial_even_with_other_mime_time_in_accept
@request.accept = "text/javascript, text/html"
get :partial_html_erb
assert_equal "partial.html.erb", @response.body.strip
assert_equal "text/html", @response.content_type
end
def test_should_render_html_partial_with_formats
get :partial_formats_html
assert_equal "partial html", @response.body
assert_equal "text/html", @response.content_type
end
def test_render_to_string_partial
get :render_to_string_with_partial
assert_equal "only partial", @controller.instance_variable_get(:@partial_only)
assert_equal "Hello: david", @controller.instance_variable_get(:@partial_with_locals)
assert_equal "text/html", @response.content_type
end
def test_render_to_string_with_template_and_html_partial
get :render_to_string_with_template_and_html_partial
assert_equal "**only partial**\n", @controller.instance_variable_get(:@text)
assert_equal "<strong>only partial</strong>\n", @controller.instance_variable_get(:@html)
assert_equal "<strong>only html partial</strong>\n", @response.body
assert_equal "text/html", @response.content_type
end
def test_render_to_string_and_render_with_different_formats
get :render_to_string_and_render_with_different_formats
assert_equal "<strong>only partial</strong>\n", @controller.instance_variable_get(:@html)
assert_equal "**only partial**\n", @response.body
assert_equal "text/plain", @response.content_type
end
def test_render_template_within_a_template_with_other_format
get :render_template_within_a_template_with_other_format
expected = "only html partial<p>This is grand!</p>"
assert_equal expected, @response.body.strip
assert_equal "text/html", @response.content_type
end
def test_partial_with_counter
get :partial_with_counter
assert_equal "5", @response.body
end
def test_partial_with_locals
get :partial_with_locals
assert_equal "Hello: david", @response.body
end
def test_partial_with_form_builder
get :partial_with_form_builder
assert_equal "<label for=\"post_title\">Title</label>\n", @response.body
end
def test_partial_with_form_builder_subclass
get :partial_with_form_builder_subclass
assert_equal "<label for=\"post_title\">Title</label>\n", @response.body
end
def test_nested_partial_with_form_builder
@controller = Fun::GamesController.new
get :nested_partial_with_form_builder
assert_equal "<label for=\"post_title\">Title</label>\n", @response.body
end
def test_namespaced_object_partial
@controller = Quiz::QuestionsController.new
get :new
assert_equal "Namespaced Partial", @response.body
end
def test_partial_collection
get :partial_collection
assert_equal "Hello: davidHello: mary", @response.body
end
def test_partial_collection_with_as
get :partial_collection_with_as
assert_equal "david david davidmary mary mary", @response.body
end
def test_partial_collection_with_iteration
get :partial_collection_with_iteration
assert_equal "3-0: david-first3-1: mary3-2: christine-last", @response.body
end
def test_partial_collection_with_as_and_iteration
get :partial_collection_with_as_and_iteration
assert_equal "3-0: david-first3-1: mary3-2: christine-last", @response.body
end
def test_partial_collection_with_counter
get :partial_collection_with_counter
assert_equal "david0mary1", @response.body
end
def test_partial_collection_with_as_and_counter
get :partial_collection_with_as_and_counter
assert_equal "david0mary1", @response.body
end
def test_partial_collection_with_locals
get :partial_collection_with_locals
assert_equal "Bonjour: davidBonjour: mary", @response.body
end
def test_partial_collection_with_spacer
get :partial_collection_with_spacer
assert_equal "Hello: davidonly partialHello: mary", @response.body
end
def test_partial_collection_with_spacer_which_uses_render
get :partial_collection_with_spacer_which_uses_render
assert_equal "Hello: davidpartial html\npartial with partial\nHello: mary", @response.body
end
def test_partial_collection_shorthand_with_locals
get :partial_collection_shorthand_with_locals
assert_equal "Bonjour: davidBonjour: mary", @response.body
end
def test_partial_collection_shorthand_with_different_types_of_records
get :partial_collection_shorthand_with_different_types_of_records
assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body
end
def test_empty_partial_collection
get :empty_partial_collection
assert_equal " ", @response.body
end
def test_partial_with_hash_object
get :partial_with_hash_object
assert_equal "Sam\nmaS\n", @response.body
end
def test_partial_with_nested_object
get :partial_with_nested_object
assert_equal "first", @response.body
end
def test_partial_with_nested_object_shorthand
get :partial_with_nested_object_shorthand
assert_equal "first", @response.body
end
def test_hash_partial_collection
get :partial_hash_collection
assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body
end
def test_partial_hash_collection_with_locals
get :partial_hash_collection_with_locals
assert_equal "Hola: PratikHola: Amy", @response.body
end
def test_render_missing_partial_template
assert_raise(ActionView::MissingTemplate) do
get :missing_partial
end
end
def test_render_call_to_partial_with_layout
get :render_call_to_partial_with_layout
assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body
end
def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body
end
end
|
module WastebitsClient
class RegistrationConfirmation < Base
attr_accessor :confirmation_token
def save
if self.valid?
return self.class.put(@confirmation_token, '/users/confirmations',
:body => { :token => @confirmation_token },
:headers => { 'Authorization' => WastebitsClient::Base.client_authorization(WastebitsClient::Base.api_key, WastebitsClient::Base.api_secret) })
end
end
end
end
|
Rails.application.routes.draw do
root to: "static_pages#root"
get '/favorites' => "static_pages#favorites"
namespace :api, defaults: {format: :json} do
resources :rubygems do
collection do
get 'search'
end
end
resources :favorites, only: [:index, :create, :destroy]
end
end
|
class DeleteExpiredAuditsService < BaseServicer
def execute!
Audit.includes(:audit_structure).to_destroy.each do |audit|
AuditDestroyer.execute!(audit: audit)
end
end
end
|
require 'wsdl_mapper/svc_generation/proxy_generator'
module WsdlMapper
module SvcGeneration
class DocumentedProxyGenerator < ProxyGenerator
def generate_operation(f, op)
yard = WsdlMapper::Generation::YardDocFormatter.new f
f.blank_line
yard.text op.type.name.name
yard.blank_line
yard.tag :xml_name, op.type.name.name
yard.tag :xml_namespace, op.type.name.ns
yard.param :body, '::Hash', 'Keyword arguments for the InputBody constructor'
get_body_parts(op.type.input).each do |part|
type = @generator.get_ruby_type_name part.type
yard.option :body, type, part.property_name.attr_name
end
yard.blank_line
super
end
def generate_async_operation(f, op)
yard = WsdlMapper::Generation::YardDocFormatter.new f
f.blank_line
yard.text op.type.name.name
yard.blank_line
yard.tag :xml_name, op.type.name.name
yard.tag :xml_namespace, op.type.name.ns
yard.param :body_promise, 'Concurrent::Promise', 'Promise delivering keyword arguments (Hash) for the InputBody constructor'
yard.blank_line
super
end
end
end
end
|
require 'rails_helper'
RSpec.describe Api::V1::ToolsController,
:apidoc, type: :controller,
resource_group: 'API V1',
resource: 'Ferramentas [/api/v1/tools]' do
# [GET /api/v1/tools]
describe '#index',
action: 'listar todas as ferramentas cadastradas [GET]',
action_description: "Este endpoint permite listar todas as ferramentas cadastradas" do
let!(:tagging) { create(:tagging) }
context "without tag filter" do
it "returns all tools" do
get :index, format: :json
expect(JSON.parse(response.body).length).to eql 1
expect(response).to have_http_status(:ok)
end
end
context "with a tag filter" do
it "returns filtered tools from tag" do
get :index, :params => { :tag => tagging.tag.name }, format: :json
expect(JSON.parse(response.body).length).to eql 1
expect(response).to have_http_status(:ok)
end
end
end
# [GET /api/v1/tools/1]
describe '#show',
resource: 'Ferramentas [/api/v1/tools/:id]',
action: 'Exibe uma ferramenta [GET]',
action_description: "Permite exibir uma ferramenta" do
let!(:tool) { create(:tool) }
let(:retrieve_tools) { get :show, params: { id: tool.id.to_s }, format: :json }
it "retorna todas as ferramentas" do
retrieve_tools
expect(JSON.parse(response.body)).to match({
'id' => tool.id,
'title' => tool.title,
'link' => tool.link,
'description' => tool.description,
'tags' => tool.tag_list
})
expect(response).to have_http_status(:ok)
end
end
# [POST /api/v1/tools]
describe '#create',
resource: 'Ferramentas [/api/v1/tools]',
action: 'Cadastra uma ferramenta [POST]',
action_description: "Permite cadastrar uma ferramenta" do
let(:create_tool) { post :create, params: { 'title' => 'Test', 'link' => 'http://test.com', 'description' => 'Example', 'tags' => ['test'] }, format: :json }
let(:create_empty_tool) { post :create, format: :json }
context 'fails to create a tool' do
it 'fails to create a tool' do
expect{ create_empty_tool }.not_to change { Tool.count }
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'succeeds in creating a tool' do
it 'succeeds in creating a tool' do
expect { create_tool }.to change { Tool.count }
expect(response).to have_http_status(:created)
end
end
end
# [DELETE /api/v1/tools/1]
describe '#destroy',
resource: 'Ferramentas [/api/v1/tools/:id]',
action: 'Remove uma ferramenta [DELETE]',
action_description: "Permite remover uma ferramenta" do
let!(:tool) { create(:tool) }
let(:retrieve_tools) { get :destroy, params: { id: tool.id.to_s }, format: :json }
it "removes a tool" do
retrieve_tools
expect(Tool.count).to eql(0)
expect(response).to have_http_status(:no_content)
end
end
end
|
class BadgePrintoutsController < ApplicationController
include BadgePrintoutsHelper
def new
end
def create
inputs = params.require(:badges).select { |b| b[:first].present? }
if inputs.empty?
return redirect_back fallback_location: new_badge_printout_path, alert: 'Must enter at least one name'
end
@badges = inputs.map do |input|
role_class = input.require(:role)
role = available_roles.find { |r| r.classname == role_class }
Badge.new(input.require(:first), input[:last], input.require(:pronouns), role)
end
render layout: false
end
end
|
require 'test_helper'
class BudgetsShowTest < ActionDispatch::IntegrationTest
include ApplicationHelper
def setup
@user = users(:jane)
@budget = budgets(:one)
end
test "redirect show as logged-out user" do
get budget_path(@budget)
assert_redirected_to login_path
follow_redirect!
assert_not flash.empty?
get users_path
assert_template 'users/index'
end
test "show as logged-in user" do
log_in_as(@user)
get budget_path(@budget)
assert_template 'budgets/show'
assert_select 'title', full_title("Budget " + @budget.id.to_s)
assert_select 'h1', text: "Budget " + @budget.id.to_s
# Edit budget button
assert_select 'a[href=?]', edit_budget_path(@budget), text: 'Edit'
# Delete budget button
assert_select 'a[href=?]', budget_path(@budget), text: 'Delete', method: :delete
assert_difference 'Budget.count', -1 do
delete budget_path(@budget)
end
end
end |
class TaxAdvanceFinalName < PayrollName
def initialize
super(PayTagGateway::REF_TAX_ADVANCE_FINAL,
'Tax advance after relief', 'Tax advance after relief',
PayNameGateway::VPAYGRP_TAX_RESULT, PayNameGateway::HPAYGRP_UNKNOWN)
end
end |
# frozen_string_literal: true
require 'apartment/adapters/abstract_adapter'
module Apartment
module Adapters
# JDBC Abstract adapter
class AbstractJDBCAdapter < AbstractAdapter
private
def multi_tenantify_with_tenant_db_name(config, tenant)
config[:url] = "#{config[:url].gsub(%r{(\S+)/.+$}, '\1')}/#{environmentify(tenant)}"
end
def rescue_from
ActiveRecord::JDBCError
end
end
end
end
|
class AddColumnToReservationStatus < ActiveRecord::Migration[5.0]
def change
add_column :reservation_statuses, :bag_status, :string
end
end
|
require 'pry'
class CashRegister
attr_accessor :discount, :total, :item, :last_trans
def initialize(discount=nil)
@last_trans = self
@total = 0
@discount = discount
@items = []
end
def total
return @total
end
def add_item(item, price, quantity=nil)
@item = item
if quantity == nil
self.total += price
@items << item
else
self.total += (price * quantity)
quantity.times do
@items << item
end
end
end
def apply_discount
if @discount == nil
"There is no discount to apply."
else
@discount = @discount * 0.01
@total = @total - (@discount * @total)
@total = @total.floor
"After the discount, the total comes to $#{@total}."
end
end
def items
@items
end
def void_last_transaction
@total = @total - @last_trans.total
end
end
|
# An Account on DocumentCloud can be used to access the workspace and upload
# documents. Accounts have full priviledges for the entire organization, at the
# moment.
class Account < ActiveRecord::Base
include DC::Access
DISABLED = 0
ADMINISTRATOR = 1
CONTRIBUTOR = 2
REVIEWER = 3
FREELANCER = 4
ROLES = [ADMINISTRATOR, CONTRIBUTOR, REVIEWER, FREELANCER, DISABLED]
# Associations:
belongs_to :organization
has_many :projects, :dependent => :destroy
has_many :annotations
has_many :collaborations, :dependent => :destroy
has_many :processing_jobs, :dependent => :destroy
has_one :security_key, :dependent => :destroy, :as => :securable
has_many :shared_projects, :through => :collaborations, :source => :project
# Validations:
validates_presence_of :first_name, :last_name, :email
validates_format_of :email, :with => DC::Validators::EMAIL
validates_uniqueness_of :email, :case_sensitive => false
validates_inclusion_of :role, :in => ROLES
# Sanitizations:
text_attr :first_name, :last_name, :email
# Delegations:
delegate :name, :to => :organization, :prefix => true, :allow_nil => true
# Scopes:
named_scope :admin, {:conditions => {:role => ADMINISTRATOR}}
named_scope :active, {:conditions => ["role != ?", DISABLED]}
named_scope :real, {:conditions => ["role in (?)", [ADMINISTRATOR, CONTRIBUTOR, FREELANCER, DISABLED]]}
named_scope :reviewer, {:conditions => {:role => REVIEWER}}
# Attempt to log in with an email address and password.
def self.log_in(email, password, session=nil, cookies=nil)
account = Account.lookup(email)
return false unless account && account.password == password
account.authenticate(session, cookies) if session && cookies
account
end
def self.login_reviewer(key, session=nil, cookies=nil)
security_key = SecurityKey.find_by_key(key)
return nil unless security_key
account = security_key.securable
account.authenticate(session, cookies) if session && cookies
account
end
# Retrieve the names of the contributors for the result set of documents.
def self.names_for_documents(docs)
ids = docs.map {|doc| doc.account_id }.uniq
self.all(:conditions => {:id => ids}, :select => 'id, first_name, last_name').inject({}) do |hash, acc|
hash[acc.id] = acc.full_name; hash
end
end
def self.lookup(email)
Account.first(:conditions => ['lower(email) = ?', email.downcase])
end
# Save this account as the current account in the session. Logs a visitor in.
def authenticate(session, cookies)
session['account_id'] = id
session['organization_id'] = organization_id
refresh_credentials(cookies)
self
end
# Reset the logged-in cookie.
def refresh_credentials(cookies)
cookies['dc_logged_in'] = {:value => 'true', :expires => 1.month.from_now, :httponly => true}
end
def slug
first = first_name && first_name.downcase.gsub(/\W/, '')
last = last_name && last_name.downcase.gsub(/\W/, '')
@slug ||= "#{id}-#{first}-#{last}"
end
def admin?
role == ADMINISTRATOR
end
def contributor?
role == CONTRIBUTOR
end
def reviewer?
role == REVIEWER
end
def freelancer?
role == FREELANCER
end
def real?
admin? || contributor?
end
def active?
role != DISABLED
end
# An account owns a resource if it's tagged with the account_id.
def owns?(resource)
resource.account_id == id
end
def collaborates?(resource)
(admin? || contributor?) &&
resource.organization_id == organization_id &&
[ORGANIZATION, EXCLUSIVE, PUBLIC, PENDING, ERROR].include?(resource.access)
end
# Heavy-duty SQL.
# A document is shared with you if it's in any project of yours, and that
# project is in collaboration with an owner or and administrator of the document.
# Note that shared? is not the same as reviews?, as it ignores hidden projects.
def shared?(resource)
collaborators = Account.find_by_sql(<<-EOS
select distinct on (a.id)
a.id as id, a.organization_id as organization_id, a.role as role
from accounts as a
inner join collaborations as c1
on c1.account_id = a.id
inner join collaborations as c2
on c2.account_id = #{id} and c2.project_id = c1.project_id
inner join projects as p
on p.id = c1.project_id and p.hidden = false
inner join project_memberships as pm
on pm.project_id = c1.project_id and pm.document_id = #{resource.document_id}
where a.id != #{id}
EOS
)
collaborators.any? {|account| account.owns_or_collaborates?(resource) }
end
def owns_or_collaborates?(resource)
owns?(resource) || collaborates?(resource)
end
# Effectively the same as Account#shares?, but for hidden projects used for reviewers.
def reviews?(resource)
project = resource.projects.hidden.first
project && project.collaborators.exists?(id)
end
def allowed_to_edit?(resource)
owns_or_collaborates?(resource) || shared?(resource)
end
def allowed_to_edit_account?(account)
(self.id == account.id) ||
((self.organization_id == account.organization_id) && (self.admin? || account.reviewer?))
end
def shared_document_ids
return @shared_document_ids if @shared_document_ids
@shared_document_ids ||= accessible_project_ids.empty? ? [] :
ProjectMembership.connection.select_values(
"select distinct document_id from project_memberships where project_id in (#{accessible_project_ids.join(',')})"
).map {|id| id.to_i }
end
# The list of all of the projects that have been shared with this account
# through collaboration.
def accessible_project_ids
@accessible_project_ids ||=
Collaboration.owned_by(self).all(:select => [:project_id]).map {|c| c.project_id }
end
# When an account is created by a third party, send an email with a secure
# key to set the password.
def send_login_instructions(admin=nil)
create_security_key if security_key.nil?
LifecycleMailer.deliver_login_instructions(self, admin)
end
def send_reviewer_instructions(documents, inviter_account, message=nil)
key = nil
if self.role == Account::REVIEWER
create_security_key if self.security_key.nil?
key = '?key=' + self.security_key.key
end
LifecycleMailer.deliver_reviewer_instructions(documents, inviter_account, self, message, key)
end
# Upgrading a reviewer account to a newsroom account also moves their
# notes over to the (potentially different) organization.
def upgrade_reviewer_to_real(organization, role)
update_attributes :organization => organization, :role => role
Annotation.update_all("organization_id = #{organization.id}", "account_id = #{id}")
end
# When a password reset request is made, send an email with a secure key to
# reset the password.
def send_reset_request
create_security_key if security_key.nil?
LifecycleMailer.deliver_reset_request(self)
end
# No middle names, for now.
def full_name
"#{first_name} #{last_name}"
end
# The ISO 8601-formatted email address.
def rfc_email
"\"#{full_name}\" <#{email}>"
end
# MD5 hash of processed email address, for use in Gravatar URLs.
def hashed_email
@hashed_email ||= Digest::MD5.hexdigest(email.downcase.gsub(/\s/, ''))
end
# Has this account been assigned, but never logged into, with no password set?
def pending?
!hashed_password && !reviewer?
end
# It's slo-o-o-w to compare passwords. Which is a mixed bag, but mostly good.
def password
return false if hashed_password.nil?
@password ||= BCrypt::Password.new(hashed_password)
end
# BCrypt'd passwords helpfully have the salt built-in.
def password=(new_password)
@password = BCrypt::Password.create(new_password, :cost => 8)
self.hashed_password = @password
end
def canonical(options={})
attrs = {
'id' => id,
'slug' => slug,
'email' => email,
'first_name' => first_name,
'last_name' => last_name,
'organization_id' => organization_id,
'role' => role,
'hashed_email' => hashed_email,
'pending' => pending?
}
attrs['organization_name'] = organization_name if options[:include_organization]
if options[:include_document_counts]
attrs['public_documents'] = Document.unrestricted.count(:conditions => {:account_id => id})
attrs['private_documents'] = Document.restricted.count(:conditions => {:account_id => id})
end
attrs
end
# The JSON representation of an account avoids sending down the password,
# among other things, and includes extra attributes.
def to_json(options={})
canonical(options).to_json
end
end
|
require 'pry'
def consolidate_cart(cart)
cart.group_by(&:itself).map do |key, entries|
key.map do |item, vals|
vals.update(count: entries.length)
end
end
consolidated = {}
cart.map { |item| consolidated.update(item)}
return consolidated
end
def apply_coupons(cart, coupons)
coupons.each do |coupon|
coupon_name = coupon[:item]
temp = {
:price => coupon[:cost],
:clearance => true,
:count => coupon[:num]
}
if cart.key?(coupon_name)
temp[:clearance] = cart[coupon_name][:clearance]
leftover = cart[coupon_name][:count] - temp[:count]
if leftover >= 0
temp[:count] = (cart[coupon_name][:count]/temp[:count]).floor
cart[coupon_name][:count] = (cart[coupon_name][:count]%coupon[:num])
cart[coupon_name + " W/COUPON"] = temp
end #if leftover
end #if cart.key?
end #coupons.each
return cart
end #method
def apply_clearance(cart)
cart.map do |cart_item, details|
if details[:clearance] == true
details[:price] -= (details[:price]/5)
end #if details[:clearance]
end #cart.map
return cart
end #method
def checkout(cart, coupons)
cart = consolidate_cart(cart)
cart = apply_coupons(cart, coupons)
cart = apply_clearance(cart)
total = 0.0
cart.each do |cart_item, details|
# binding.pry
total += (details[:price] * details[:count])
end #cart.each do
if total > 100
total -= (total/10)
end
return total
end #method
|
require 'formula'
class Sqlitebrowser < Formula
homepage 'http://sqlitebrowser.org'
url 'https://github.com/sqlitebrowser/sqlitebrowser/archive/v3.5.1.tar.gz'
sha1 '2c915ccb1e869e98c9e4133ecef1ba003a304d87'
head 'https://github.com/sqlitebrowser/sqlitebrowser.git'
bottle do
cellar :any
sha1 "34109839c79ae06a811db806782433c193ba99f6" => :yosemite
sha1 "82ae0afbb0fac9c67e25b6d8d55007dc7371bdf1" => :mavericks
sha1 "c4af5c9aa9fd484beabc8726eeab13ae1dd15f72" => :mountain_lion
end
depends_on 'qt'
depends_on 'cmake' => :build
depends_on 'sqlite' => 'with-functions'
def install
system "cmake", ".", *std_cmake_args
system 'make install'
end
end
|
require "spec_helper"
RSpec.describe "cross site scripting", type: :system do
fixtures :projects, :users,
:email_addresses,
:roles, :members,
:member_roles,
:trackers,
:projects_trackers,
:enabled_modules,
:wikis,
:wiki_pages,
:wiki_contents
before do
Attachment.storage_path = "#{Rails.root}/plugins/redmine_drawio/spec/files"
log_user('admin', 'admin')
end
describe "drawio_attach" do
it "does not execute javascript from uploaded SVG (XSS proof)" do
Attachment.create!(
container_id: 1,
container_type: "WikiPage",
filename: "xss.svg",
disk_filename: "xss.svg",
filesize: 1,
content_type: "image/svg+xml",
digest: "c1993a380fa0031d269ce96de5cb30eca04d3bfbc1bedbb5ea5834d0e17b66f4",
downloads: 0,
author_id: 1,
description: "",
disk_directory: ""
)
WikiContent.first.update!(text: "{{drawio_attach(xss.svg)}}")
# expect no javascript alert is rendered
expect do
accept_alert wait: 2 do
visit "/projects/ecookbook/wiki"
end
end.to raise_error(Capybara::ModalNotFound)
end
end
end
|
namespace :videos do
desc "Videos with nil positions are replaced with valid positions"
task :update_positions do
Video.not_positioned.each { |video| video.update_placement }
end
end
|
require 'spec_helper'
describe UsersController do
let(:valid_session) { {} }
let(:params) do
{ "phone" => "1234567890" }
end
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = create(:tutor)
@user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
sign_in @user
end
describe 'GET #show' do
it "assigns the requested user to @user" do
get :show, id: @user.slug
expect(assigns(:user)).to eq @user
end
it "renders the :show template" do
get :show, id: @user.slug
expect(response).to render_template :show
end
end
describe 'GET #panel' do
it "should render panel template if profile completness = 100" do
create(:education, user: @user)
User.logger.debug "QS COUNTS #{@user.questions.count}"
@user.questions.update_all(answer: 'Some text placeholder to pretend it as answer,Some text placeholder to pretend it as answer.')
create(:course, user: @user)
get :panel
expect(response).to render_template :panel
end
end
describe 'GET #edit_profile' do
it "should open edit_profile page if logged in" do
get :edit_profile
expect(response).to render_template :edit_profile
assigns(:user).should eq(@user)
end
end
describe "PUT update_tags" do
describe "with valid params" do
it "updates the requested user tags" do
tag1 = create(:tag)
tag2 = create(:tag)
put :update_tags, {tag_ids: "#{tag1.id},#{tag2.id}"}
expect(response).to redirect_to my_board_url
end
end
describe "with invalid params" do
it "updates the requested user tags" do
put :update_tags, {tag_ids: ""}
expect(response).to redirect_to academy_board_url
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested user" do
# article = Article.create! valid_attributes
# # Assuming there are no other articles in the database, this
# # specifies that the Article created on the previous line
# # receives the :update_attributes message with whatever params are
# # submitted in the request.
User.any_instance.should_receive(:update).with(params)
put :update, {:id => @user.to_param, :user => params}, valid_session
end
# it "assigns the requested article as @article" do
# article = Article.create! valid_attributes
# put :update, {:id => article.to_param, :article => valid_attributes}, valid_session
# assigns(:article).should eq(article)
# end
# it "redirects to the article" do
# article = Article.create! valid_attributes
# put :update, {:id => article.to_param, :article => valid_attributes}, valid_session
# response.should redirect_to(article)
# end
end
# describe "with invalid params" do
# it "assigns the article as @article" do
# article = Article.create! valid_attributes
# # Trigger the behavior that occurs when invalid params are submitted
# Article.any_instance.stub(:save).and_return(false)
# put :update, {:id => article.to_param, :article => { "link" => "invalid value" }}, valid_session
# assigns(:article).should eq(article)
# end
# it "re-renders the 'edit' template" do
# article = Article.create! valid_attributes
# # Trigger the behavior that occurs when invalid params are submitted
# Article.any_instance.stub(:save).and_return(false)
# put :update, {:id => article.to_param, :article => { "link" => "invalid value" }}, valid_session
# response.should render_template("edit")
# end
# end
end
end
|
# encoding: UTF-8
require 'spec_helper'
describe XmlFeedHandler do
before :each do
@shop = Shop.create({:name => "alza.sk", :url => "http://www.alza.sk"})
end
def valid_attributes
{
:shop => @shop,
:feed_path => "#{RAILS_ROOT}/spec/tmp/feed.xml"
}
end
it "should be valid" do
handler = XmlFeedHandler.create(valid_attributes)
handler.valid?.should == true
end
it "should enqueue after create" do
handler = XmlFeedHandler.create(valid_attributes)
handler.status.should == "enqueued"
end
it "should run after perform called" do
handler = XmlFeedHandler.create(valid_attributes)
handler.perform
handler.status.should == "finished"
handler.result.should == "alza.sk -4712-01-01 00:00:00 UTC\n Total number of products: 4\n0 of products skipped (without required attributes)"
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
describe Mongo::Auth::Aws::CredentialsRetriever do
describe '#credentials' do
context 'when credentials should be obtained from endpoints' do
let(:cache) do
Mongo::Auth::Aws::CredentialsCache.new
end
let(:subject) do
described_class.new(credentials_cache: cache).tap do |retriever|
allow(retriever).to receive(:credentials_from_environment).and_return(nil)
end
end
context 'when cached credentials are not expired' do
let(:credentials) do
double('credentials', expired?: false)
end
before(:each) do
cache.credentials = credentials
end
it 'returns the cached credentials' do
expect(subject.credentials).to eq(credentials)
end
it 'does not obtain credentials from endpoints' do
expect(subject).not_to receive(:obtain_credentials_from_endpoints)
described_class.new(credentials_cache: cache).credentials
end
end
shared_examples_for 'obtains credentials from endpoints' do
context 'when obtained credentials are not expired' do
let(:credentials) do
double('credentials', expired?: false)
end
before(:each) do
expect(subject)
.to receive(:obtain_credentials_from_endpoints)
.and_return(credentials)
end
it 'returns the obtained credentials' do
expect(subject.credentials).not_to be_expired
end
it 'caches the obtained credentials' do
subject.credentials
expect(cache.credentials).to eq(credentials)
end
end
context 'when cannot obtain credentials from endpoints' do
before(:each) do
expect(subject)
.to receive(:obtain_credentials_from_endpoints)
.and_return(nil)
end
it 'raises an error' do
expect { subject.credentials }.to raise_error(Mongo::Auth::Aws::CredentialsNotFound)
end
end
end
context 'when cached credentials expired' do
before(:each) do
cache.credentials = double('credentials', expired?: true)
end
it_behaves_like 'obtains credentials from endpoints'
end
context 'when no credentials cached' do
before(:each) do
cache.clear
end
it_behaves_like 'obtains credentials from endpoints'
end
end
end
end
|
module DasParseCsv
def generate_lambdum( name_part, rmethod, params, desired_code_id, value )
if name_part =~ /^(.+)\.csv$/
name_part = $1
else
return super
end
return [value, name_part] if value.is_a?(Proc) # протокол - бежать куда подальше ежели оно так
value = value.split("\n").map { |line|
line.split(/[\s,]+/).map{ |e| prepare_param_value(e) }
=begin
{ |t|
if t =~ /\A(0|[1-9][0-9]*)\z/
return t.to_i
end
if t =~ /\A(([1-9]*)|(([1-9]*)\.([0-9]*)))\z/
return t.to_f
end
t
}
=end
}
if params[:flatten]
value = value.flatten
STDERR.puts "csv data flattened: #{value.inspect}"
end
lambdum = lambda { |ctx|
ctx.send( rmethod || "r=",value )
}
return [lambdum, name_part]
end
end
LetterParser.prepend DasParseCsv |
class AddRankToUserCareer < ActiveRecord::Migration
def change
add_column :user_careers, :rank, :integer
add_column :user_careers, :total_weight, :float
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :user do
nickname { 'アえ間' }
email { Faker::Internet.free_email }
password { Faker::Internet.password(min_length: 7) }
password_confirmation { password }
end
end
|
Rails.application.routes.draw do
resources :sessions, only: [:new, :create, :destroy]
get 'signup', to: 'students#new', as: 'signup'
get 'login', to: 'sessions#new', as: 'login'
get 'logout', to: 'sessions#destroy', as: 'logout'
resources :students
resources :quizzes do
resources :questions, shallow: true
end
resources :questions do
resources :answers, shallow: true
end
resources :answers
get '/' => 'static#welcome'
get 'about' => 'static#about'
get 'quizzes/:id/summary', to: 'quizzes#summary', as: :summary
post 'quizzes/:id/summary', to: 'quizzes#email', as: :email
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
get 'profile' => 'students#show'
post 'questions/:id' => 'questions#student_answer'
# namespace :admin do
# resources :answers, :questions, :quizzes
# get 'admin/quizzes' => 'admin/quizzes#index'
# get 'admin/quizzes/new' => 'admin/quizzes#new'
# post 'admin/quizzes' => 'admin/quizzes#create'
# get 'admin/quizzes/:id' => 'admin/quizzes#show'
# get 'admin/quizzes/:id/edit' => 'admin/quizzes#edit'
# put 'admin/quizzes/:id' => 'admin/quizzes#update'
# delete 'admin/quizzes/:id' => 'admin/quizzes#destroy'
# end
# get 'quizzes/:quiz_id/questions' => 'questions#index'
# get 'quizzes/:quiz_id/questions/new' => 'questions#new'
# post 'quizzes/:quiz_id/questions' => 'questions#create'
# get 'quizzes/:quiz_id/questions:id' => 'questions#show'
# get 'quizzes/:quiz_id/questions/:id/edit' => 'questions#edit'
# put 'quizzes/:quiz_id/questions/:id' => 'questions#update'
# delete 'quizzes/:quiz_id/questions/:id' => 'questions#destroy'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
class RoomsController < ApplicationController
before_action :set_room, only: [:show, :edit, :update, :destroy]
def search
if params.has_key?('search')
@rooms = Room.search(params['search'])
else
@rooms = []
end
params['search'] ||= {}
@old_roomtype = params.has_key?('search') ? params[:search][:room_roomtype] : ""
end
# GET /rooms
# GET /rooms.json
def index
@rooms = Room.all
end
# GET /rooms/1
# GET /rooms/1.json
def show
end
# GET /rooms/new
def new
@room = Room.new
end
# GET /rooms/1/edit
def edit
end
# POST /rooms
# POST /rooms.json
def create
@room = Room.new(room_params)
respond_to do |format|
if @room.save
format.html { redirect_to @room, notice: t('flash.room.create') }
format.json { render :show, status: :created, location: @room }
else
format.html { render :new }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /rooms/1
# PATCH/PUT /rooms/1.json
def update
respond_to do |format|
if @room.update(room_params)
format.html { redirect_to @room, notice: t('flash.room.upadate') }
format.json { render :show, status: :ok, location: @room }
else
format.html { render :edit }
format.json { render json: @room.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rooms/1
# DELETE /rooms/1.json
def destroy
@room.destroy
respond_to do |format|
format.html { redirect_to @room.floor, notice: t('flash.room.delete') }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_room
@room = Room.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def room_params
params.require(:room).permit(:name, :description, :floor_id, :capacity,
:computers, :roomtype_id)
end
end
|
class Goal < ActiveRecord::Base
include PublicActivity::Common
attr_accessible :complete, :name, :user_id
belongs_to :user
validates :name, presence: true, length: { maximum: 100 }
end
|
# frozen_string_literal: true
# Application controller from which all Karafka controllers should inherit
# You can rename it if it would conflict with your current code base (in case you're integrating
# Karafka with other frameworks)
class ApplicationController < Karafka::BaseController
end
|
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
# GET returns an index of all users
def index
@users = User.where(activated: true).paginate(page: params[:page])
end
# GET show details of a user
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
redirect_to root_url and return unless @user.activated
end
# GET new user form
def new
@user = User.new
end
# POST save new user in database and temporarily log them in using session storage
def create
@user = User.new(user_params)
if @user.save # if model validation is successful
@user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else # if model validation unsuccessful
render 'new' # re-render the new user form with errors
end
end
# GET edit user form
def edit
@user = User.find(params[:id])
end
# PATCH update existing user in database
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
# DELETE delete user from database
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_url
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.following.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
# in new versions of Rails, passing the actual params object into new or update will raise an exception, because it's a security liability
# so we whitelist which params CAN be updated using permit
# and we enforce which params MUST be updated using require
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
##################
# Before filters #
##################
# Confirms the correct user.
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
|
require 'feature_helper'
feature 'Admin Routes', js: true do
context 'Resque' do
given(:user) { create :user, email: Settings.admin.email }
background do
login_as user
end
Steps 'Can access Resque' do
When 'I try to visit the resque page' do
visit '/resque'
end
Then 'I do see the resque page' do
should_see 'Workers Working'
end
end
end
end
|
class MasterflowersController < ApplicationController
before_action :require_user
def index
@masterflowers = Masterflower.all
options_for_sort = { "newest" => "created_at DESC", "oldest" => "created_at ASC", "a-z" => "masterflower_name ASC", "z-a" => "masterflower_name DESC", "highest price" => "masterflower_price DESC", "lowest price" => "masterflower_price ASC" }
if params[:r] && params[:t]
# name search = params[:r]
# sort = params[:t]
@masterflowers = Masterflower.search(params[:r]).order(options_for_sort[params[:t]])
if @masterflowers.blank?
flash.now[:alert] = "Sorry, no flowers match your search"
@masterflowers = Masterflower.all
end
end
end
def show
@masterflower = Masterflower.find(params[:id])
end
def new
@masterflower = Masterflower.new
end
def edit
@masterflower = Masterflower.find(params[:id])
end
def create
@masterflower = Masterflower.new(masterflower_params)
@masterflower.save
if @masterflower.errors.any?
flash[:danger] = "The name '" + @masterflower.masterflower_name.capitalize + "' has been taken or the price was empty."
redirect_to masterflowers_path
else
redirect_to masterflowers_path
end
end
def update
@masterflower = Masterflower.find(params[:id])
@masterflower.update(masterflower_params)
if @masterflower.errors.any?
flash[:danger] = "The price of '" + @masterflower.masterflower_name.capitalize + "' cannot be empty."
redirect_to masterflowers_path
else
redirect_to masterflowers_path
end
end
def destroy
@masterflower = Masterflower.find(params[:id])
@masterflower.destroy
redirect_to masterflowers_path
end
private
def masterflower_params
params.require(:masterflower).permit(:masterflower_name, :masterflower_price, :vendor)
end
end
|
class ForumPolicy < ApplicationPolicy
attr_reader :user, :forum
class Scope < Scope
def resolve
if user.admin?
scope.all
else
scope.where(privilege: 0)
end
end
end
def initialize(user, forum)
@user = user
@forum = forum
end
def new?
user.admin?
end
def create?
user.admin?
end
def edit?
user.admin?
end
def update?
user.admin?
end
end
|
require 'rails_helper'
RSpec.describe "cards/index", type: :view do
before(:each) do
assign(:cards, [
FactoryBot.create(:card),
FactoryBot.create(:card)
])
end
it "renders a list of cards" do
render
end
end
|
source 'http://rubygems.org'
source 'http://gemcutter.org'
gemspec
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '>= 3.2.0'
gem 'coffee-rails', '>= 3.2.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtime
# gem 'therubyracer'
gem 'uglifier', '>= 1.0.3'
end
gem "jquery-rails"
gem 'bson_ext'
gem 'yajl-ruby'
gem 'will_paginate'
gem 'rack-ssl'
gem "bcrypt-ruby", :require => "bcrypt"
gem 'validate_url'
gem 'email_validator'
gem 'chronic'
gem 'jquery-rails'
gem 'orm_adapter', :git => 'git://github.com/timgaleckas/orm_adapter.git'
group :development, :test do
gem 'debugger'
gem 'rspec-rails'
gem 'authlogic'
gem 'pg'
end
group :test do
gem 'steak'
gem 'capybara'
gem 'selenium-client'
gem 'selenium-webdriver'
gem 'launchy'
gem 'shoulda'
gem 'factory_girl_rails'
gem 'webrat'
gem 'autotest'
gem 'autotest-growl'
gem 'database_cleaner'
gem 'fuubar'
gem 'watchr'
gem 'delorean'
gem 'rspec-set'
end
|
# Draws a debug view of a collision shape
class DebugCollisionShape
Z_ORDER = 11
CIRCLE_STEPS = 12
DEGREES_PER_STEP = 360.0 / CIRCLE_STEPS
attr_reader :collision_shape
def initialize(collision_shape)
@collision_shape = collision_shape
end
def draw
if collision_shape.is_a?(CP::Shape::Poly)
draw_polygon
elsif collision_shape.is_a?(CP::Shape::Circle)
draw_circle
elsif collision_shape.is_a?(CP::Shape::Segment)
draw_segment
else
puts "I don't know how to draw #{collision_shape.class}"
end
end
private
def color
if rigid_body.static?
Gosu::Color::GREEN
else
Gosu::Color::CYAN
end
end
def rigid_body
collision_shape.body
end
def direction_vector
CP::Vec2.for_angle(rigid_body.a)
end
def draw_polygon
collision_shape.num_verts.times do |index|
start = polygon_side_edge(index)
finish = polygon_side_edge(index + 1)
Gosu.draw_line(
start.x, start.y, color,
finish.x, finish.y, color,
Z_ORDER
)
end
end
def polygon_side_edge(index)
index = 0 if index >= collision_shape.num_verts
rigid_body.pos + collision_shape.vert(index).rotate(direction_vector)
end
def draw_segment
Gosu.draw_line(
segment_start.x, segment_start.y, color,
segment_finish.x, segment_finish.y, color,
Z_ORDER
)
end
def segment_start
rigid_body.pos + collision_shape.a.rotate(direction_vector)
end
def segment_finish
rigid_body.pos + collision_shape.b.rotate(direction_vector)
end
def draw_circle
radius = collision_shape.radius
CIRCLE_STEPS.times do |side_number|
start = circle_side_edge(radius, side_number)
finish = circle_side_edge(radius, side_number + 1)
Gosu.draw_line(
start.x, start.y, color,
finish.x, finish.y, color,
Z_ORDER
)
end
end
def circle_side_edge(radius, side_number)
angle = (DEGREES_PER_STEP * side_number).gosu_to_radians
edge_offset = CP::Vec2.new(radius, 0).rotate(CP::Vec2.for_angle(angle))
rigid_body.pos + edge_offset
end
end
|
class Route
attr_reader :pattern, :http_method, :controller_class, :action_name
# A Router keeps track of multiple Routes. Each Route should store the following information:
# The URL pattern it is meant to match (/users, /users/new, /users/(\d+), /users/(\d+)/edit, etc.).
# The HTTP method (GET, POST, PUT, DELETE).
# The controller class the route maps to.
# The action name that should be invoked.
def initialize(pattern, http_method, controller_class, action_name)
@pattern = pattern
@http_method = http_method
@controller_class = controller_class
@action_name = action_name
end
# checks if pattern matches path and method matches request method
def matches?(req)
(@pattern =~ req.path) &&
(@http_method == req.request_method.downcase.to_sym)
# Also write a method, Route#matches?(req), which will test whether
# a Route matches a request. Remember that a route is a match only
# if the pattern matches the request path and if its http_method
# is the same as the request method (you can use
# req.request_method). Note that pattern will be a Regexp, so you
# should use the match operator =~, not ==.
# NB: Rack::Request#request_method returns an uppercase string,
# http_method is set as a lowercase symbol. Adjust accordingly!
end
# use pattern to pull out route params (save for later?)
# instantiate controller and call controller action
def run(req, res)
end
end
class Router
attr_reader :routes
def initialize
@routes = []
end
# simply adds a new route to the list of routes
def add_route(pattern, method, controller_class, action_name)
@routes << Route.new(pattern, method, controller_class, action_name)
end
# evaluate the proc in the context of the instance
# for syntactic sugar :)
def draw(&proc)
end
# make each of these methods that
# when called add route
[:get, :post, :put, :delete].each do |http_method|
add_route(req.pattern, http_method, controller_class, action_name)
end
# should return the route that matches this request
def match(req)
@routes.each do |route|
return route if route.matches?(req)
end
end
# either throw 404 or call run on a matched route
def run(req, res)
end
end
|
require 'spec_helper'
describe ForumController do
describe "route should routing " do
it "index" do
{:get => "/"}.should route_to(:controller => "forum", :action => "index")
end
it "new" do
{:get => "/nova-discussao"}.should route_to(:controller => "forum", :action => "new")
end
it "show" do
{:get => "/this-is-my-question"}.should route_to(:controller => "forum", :action => "show", :id => "this-is-my-question")
end
it "create" do
{:post => "/"}.should route_to(:controller => "forum", :action => "create")
end
it "update" do
{:put => "/this-is-my-question"}.should route_to(:controller => "forum", :action => "update", :id => "this-is-my-question")
end
it "new reply" do
{:get => "/this-is-my-question/resposta"}.should route_to(:controller => "forum", :action => "reply", :id => "this-is-my-question")
end
end
describe "named routes" do
it "should be questions path" do
questions_path.should == "/"
end
it "should be question path" do
question_path(42).should == "/42"
end
it "should be new question path" do
new_question_path.should == "/nova-discussao"
end
it "should be new reply path" do
reply_path(42).should == "/42/resposta"
end
end
end
|
require 'test_helper'
class ComplicationsControllerTest < ActionController::TestCase
setup do
@complication = complications(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:complications)
end
test "should get new" do
get :new
assert_response :success
end
test "should create complication" do
assert_difference('Complication.count') do
post :create, complication: { anesthesia_related: @complication.anesthesia_related, death: @complication.death, death_preventable: @complication.death_preventable, description: @complication.description, error_grade: @complication.error_grade, error_type: @complication.error_type, operation_record_id: @complication.operation_record_id, preventable: @complication.preventable, wound_infection: @complication.wound_infection }
end
assert_redirected_to complication_path(assigns(:complication))
end
test "should show complication" do
get :show, id: @complication
assert_response :success
end
test "should get edit" do
get :edit, id: @complication
assert_response :success
end
test "should update complication" do
patch :update, id: @complication, complication: { anesthesia_related: @complication.anesthesia_related, death: @complication.death, death_preventable: @complication.death_preventable, description: @complication.description, error_grade: @complication.error_grade, error_type: @complication.error_type, operation_record_id: @complication.operation_record_id, preventable: @complication.preventable, wound_infection: @complication.wound_infection }
assert_redirected_to complication_path(assigns(:complication))
end
test "should destroy complication" do
assert_difference('Complication.count', -1) do
delete :destroy, id: @complication
end
assert_redirected_to complications_path
end
end
|
class User
attr_reader :id, :name
def initialize(params)
@params = params
@id = params["id"]
@name = params["name"]
end
def to_h
@params
end
end
|
#
# Uses the AWS Config or CloudWatch service to monitor for events.
#
# AWS Config or CloudWatch events are collected in an SNS Topic. Each appliance uses a unique
# SQS queue subscribed to the AWS Config topic. If the appliance-specific queue
# doesn't exist, this event monitor will create the queue and subscribe the
# queue to the AWS Config topic.
#
class ManageIQ::Providers::Amazon::CloudManager::EventCatcher::Stream
class ProviderUnreachable < ManageIQ::Providers::BaseManager::EventCatcher::Runner::TemporaryFailure
end
#
# Creates an event monitor
#
# @param [ManageIQ::Providers::Amazon::CloudManager] ems
# @param [String] sns_aws_config_topic_name
AWS_CONFIG_TOPIC = "AWSConfig_topic".freeze
def initialize(ems, sns_aws_config_topic_name = AWS_CONFIG_TOPIC)
@ems = ems
@topic_name = sns_aws_config_topic_name
@stop_polling = false
@before_poll = nil
end
#
# Stop capturing events
#
def stop
@stop_polling = true
end
def before_poll(&block)
@before_poll = block
end
#
# Collect events off the appliance-specific queue and return the events as a
# batch to the caller.
#
# :yield: array of Amazon events as hashes
#
def poll
@ems.with_provider_connection(:service => :SQS) do |sqs|
queue_poller = Aws::SQS::QueuePoller.new(
find_or_create_queue,
:client => sqs.client,
:wait_time_seconds => 20,
:before_request => @before_poll
)
begin
queue_poller.poll do |sqs_message|
$aws_log.debug("#{log_header} received message #{sqs_message}")
throw :stop_polling if @stop_polling
event = parse_event(sqs_message)
yield event if event
end
rescue Aws::SQS::Errors::ServiceError => exception
raise ProviderUnreachable, exception.message
end
end
end
private
# @return [String] is a queue_url
def find_or_create_queue
queue_url = sqs_get_queue_url(queue_name)
subscribe_topic_to_queue(sns_topic, queue_url) unless queue_subscribed_to_topic?(queue_url, sns_topic)
add_policy_to_queue(queue_url, sns_topic.arn) unless queue_has_policy?(queue_url, sns_topic.arn)
queue_url
rescue Aws::SQS::Errors::NonExistentQueue
$aws_log.info("#{log_header} Amazon SQS Queue #{queue_name} does not exist; creating queue")
queue_url = sqs_create_queue(queue_name)
subscribe_topic_to_queue(sns_topic, queue_url)
add_policy_to_queue(queue_url, sns_topic.arn)
$aws_log.info("#{log_header} Created Amazon SQS Queue #{queue_name} and subscribed to AWSConfig_topic")
queue_url
rescue Aws::SQS::Errors::ServiceError => exception
raise ProviderUnreachable, exception.message
end
def queue_has_policy?(queue_url, topic_arn)
policy_attribute = 'Policy'
policy = @ems.with_provider_connection(:service => :SQS) do |sqs|
sqs.client.get_queue_attributes(
:queue_url => queue_url,
:attribute_names => [policy_attribute]
).attributes[policy_attribute]
end
policy == queue_policy(queue_url_to_arn(queue_url), topic_arn)
end
def queue_subscribed_to_topic?(queue_url, topic)
queue_arn = queue_url_to_arn(queue_url)
topic.subscriptions.any? { |subscription| subscription.attributes['Endpoint'] == queue_arn }
end
def sqs_create_queue(queue_name)
@ems.with_provider_connection(:service => :SQS) do |sqs|
sqs.client.create_queue(:queue_name => queue_name).queue_url
end
end
def sqs_get_queue_url(queue_name)
$aws_log.debug("#{log_header} Looking for Amazon SQS Queue #{queue_name} ...")
@ems.with_provider_connection(:service => :SQS) do |sqs|
sqs.client.get_queue_url(:queue_name => queue_name).queue_url
end
end
# @return [Aws::SNS::Topic] the found topic
# @raise [ProviderUnreachable] in case the topic is not found
def sns_topic
@ems.with_provider_connection(:service => :SNS) do |sns|
get_topic(sns) || create_topic(sns)
end
end
def get_topic(sns)
sns.topics.detect { |t| t.arn.split(/:/)[-1] == @topic_name }
end
def create_topic(sns)
topic = sns.create_topic(:name => @topic_name)
$aws_log.info("Created SNS topic #{@topic_name}")
topic
rescue Aws::SNS::Errors::ServiceError => err
raise ProviderUnreachable, "Cannot create SNS topic #{@topic_name}, #{err.class.name}, Message=#{err.message}"
end
# @param [Aws::SNS::Topic] topic
def subscribe_topic_to_queue(topic, queue_url)
queue_arn = queue_url_to_arn(queue_url)
$aws_log.info("#{log_header} Subscribing Queue #{queue_url} to #{topic.arn}")
subscription = topic.subscribe(:protocol => 'sqs', :endpoint => queue_arn)
raise ProviderUnreachable, "Can't subscribe to #{queue_arn}" unless subscription.arn.present?
end
def add_policy_to_queue(queue_url, topic_arn)
queue_arn = queue_url_to_arn(queue_url)
policy = queue_policy(queue_arn, topic_arn)
@ems.with_provider_connection(:service => :SQS) do |sqs|
sqs.client.set_queue_attributes(
:queue_url => queue_url,
:attributes => {'Policy' => policy}
)
end
end
def queue_url_to_arn(queue_url)
@queue_url_to_arn ||= {}
@queue_url_to_arn[queue_url] ||= begin
arn_attribute = "QueueArn"
@ems.with_provider_connection(:service => :SQS) do |sqs|
sqs.client.get_queue_attributes(
:queue_url => queue_url,
:attribute_names => [arn_attribute]
).attributes[arn_attribute]
end
end
end
# @param [Aws::SQS::Types::Message] message
def parse_event(message)
event = JSON.parse(JSON.parse(message.body)['Message'])
if event["messageType"] == "ConfigurationItemChangeNotification"
# Aws Config Events
event["eventType"] = parse_event_type(event)
event["event_source"] = :config
elsif event.fetch_path("detail", "eventType") == "AwsApiCall"
# CloudWatch with CloudTrail for API requests Events
event["eventType"] = "AWS_API_CALL_" + event.fetch_path("detail", "eventName")
event["event_source"] = :cloud_watch_api
elsif event["detail-type"] == "EC2 Instance State-change Notification"
# CloudWatch EC2 Events
state = "_#{event.fetch_path("detail", "state")}" if event.fetch_path("detail", "state")
event["eventType"] = "#{event["detail-type"].tr(" ", "_").tr("-", "_")}#{state}"
event["event_source"] = :cloud_watch_ec2
elsif event['detail-type'] == 'EBS Snapshot Notification'
event['eventType'] = event['detail-type'].gsub(/[\s-]/, '_')
event['event_source'] = :cloud_watch_ec2_ebs_snapshot
elsif event["AlarmName"]
# CloudWatch Alarm
event["eventType"] = "AWS_ALARM_#{event["AlarmName"]}"
event["event_source"] = :cloud_watch_alarm
else
# Not recognized event, ignoring...
$log.debug("#{log_header} Parsed event from SNS Message not recognized #{event}")
return
end
$log.info("#{log_header} Found SNS Message with message type #{event["eventType"]} coming from #{event[:event_source]}")
event["messageId"] = message.message_id
$log.info("#{log_header} Parsed event from SNS Message #{event["eventType"]} coming from #{event[:event_source]}")
event
rescue JSON::ParserError => err
$log.error("#{log_header} JSON::ParserError parsing '#{message.body}' - #{err.message}")
nil
end
def parse_event_type(event)
event_type_prefix = event.fetch_path("configurationItem", "resourceType")
change_type = event.fetch_path("configurationItemDiff", "changeType")
if event_type_prefix.end_with?("::Instance")
suffix = change_type if change_type == "CREATE"
suffix ||= parse_instance_state_change(event)
else
suffix = change_type
end
# e.g., AWS_EC2_Instance_STARTED
"#{event_type_prefix}_#{suffix}".gsub("::", "_")
end
def parse_instance_state_change(event)
change_type = event["configurationItemDiff"]["changeType"]
return change_type if change_type == "CREATE"
state_changed = event.fetch_path("configurationItemDiff", "changedProperties", "Configuration.State.Name")
state_changed ? state_changed["updatedValue"] : change_type
end
def log_header
@log_header ||= "MIQ(#{self.class.name}#)"
end
def queue_name
@queue_name ||= "manageiq-awsconfig-queue-#{@ems.guid}"
end
def queue_policy(queue_arn, topic_arn)
<<EOT
{
"Version": "2012-10-17",
"Id": "#{queue_arn}/SQSDefaultPolicy",
"Statement": [
{
"Sid": "#{Digest::MD5.hexdigest(queue_arn)}",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "SQS:SendMessage",
"Resource": "#{queue_arn}",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "#{topic_arn}"
}
}
}
]
}
EOT
end
end
|
require 'spec_helper'
describe Dennis do
it 'has a version number' do
expect(Dennis::VERSION).to be
end
describe '.define' do
it 'accepts a block as parameter' do
# allow(Dennis).to receive(:define).and_yield(true)
end
end
end
|
require 'spec_helper'
describe "UserPages" do
subject { page }
describe "sign up" do
before { visit signup_path }
describe "as a logged in user" do
let(:user) { FactoryGirl.create(:user) }
before do
visit signin_path
sign_in(user)
end
describe "page" do
before { visit signup_path }
it { should_not have_selector('h1', text: 'Sign up') }
it { should have_selector('title', text: user.name) }
end
describe "submiting to the create action" do
before { post users_path }
specify { response.should redirect_to(user) }
end
end
describe "page" do
it { should have_selector('h1', text: 'Sign up') }
it { should have_selector('title', text: full_title('Sign up')) }
end
let(:submit) { "Create my account" }
describe "with invalid information" do
it "should not create a user" do
expect { click_button submit }.not_to change(User, :count)
end
describe "after submission" do
before { click_button submit }
it { should have_selector('h1', text: 'Sign up') }
it { should have_selector('title', text: full_title('Sign up')) }
it { should have_content('error')}
it { should have_content('be blank')}
it { should have_content('invalid')}
it { should have_content('too short')}
end
end
describe "with valid information" do
before { fill_user_info_form("Piotr Planeta", "example@com.pl", "example") }
it "should create a user" do
expect { click_button submit }.to change(User, :count).by(1)
end
describe "after saving the user" do
before { click_button submit }
let(:user) { User.find_by_email('example@com.pl') }
it { should have_selector('h1', text: user.name) }
it { should have_selector('div.alert.alert-success', text: 'Welcome') }
it { should have_link('Sign out') }
end
end
end
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
end
describe "edit" do
let(:user) { FactoryGirl.create(:user) }
before do
sign_in(user)
visit edit_user_path(user)
end
describe "page" do
it { should have_selector('h1', text: "Update your profile") }
it { should have_selector('title', text: full_title('Edit user')) }
end
describe "with invalid information" do
before { click_button "Save changes" }
it { should have_content('error') }
end
describe "with valid information" do
let(:new_name) { "New Name" }
let(:new_email) { "new@example.com" }
before do
fill_user_info_form(new_name, new_email, user.password)
click_button "Save changes"
end
it { should have_selector('title', text: new_name) }
it { should have_selector('div.alert.alert-success') }
it { should have_link('Sign out', href: signout_path) }
specify { user.reload.name.should == new_name }
specify { user.reload.email.should == new_email }
end
end
end |
require 'spec_helper'
describe Api::QuestpagesController do
render_views
before :each do
setup_questpages
setup_categories
setup_videos
end
describe 'index' do
it 'does not show trash' do
trash = FactoryGirl.create :questpage, :is_trash => true, :title => 'trash questpage'
Questpage.count.should >= 2
get :index, :format => :json
results = JSON.parse response.body
results = results.map{ |r| r['title'] }
results.include?( 'trash questpage' ).should eql false
end
end
end
|
require "rails_helper"
RSpec.describe Movie do
let(:title) {"The Title"}
let(:release_date) {Date.parse("2016-01-01")}
let(:description) {"The Description"}
def create_movie(attributes = {})
Movie.create!({title: title, release_date: release_date, description: description}.merge(attributes))
end
it "has a title, release date and description" do
movie = create_movie
expect(movie.title).to eq(title)
expect(movie.release_date).to eq(release_date)
expect(movie.description).to eq(description)
end
it "needs a title" do
expect { create_movie(title: nil) }.to raise_error(ActiveRecord::RecordInvalid)
end
it "needs a release date" do
expect { create_movie(release_date: nil) }.to raise_error(ActiveRecord::RecordInvalid)
end
it "needs a release date younger than the world's first motion picture" do
too_old_release_date = Date.parse("1700-01-01")
expect { create_movie(release_date: too_old_release_date) }.to raise_error(ActiveRecord::RecordInvalid)
end
end
|
class User < ActiveRecord::Base
acts_as_authentic
belongs_to :site
def self.get_list
# TODO: Elaborate this model & return a limited set of interesting fields.
find(:all, :select => "id, login", :order => "login")
end
def self.get_roles
%w(Implementer/SDM Programmer/User Investigator Funder)
end
def name
if self.last_name && self.last_name.length > 0 then
"#{first_name} #{last_name}"
else
self.login
end
end
def full_name
"#{self.name}, #{self.degrees}"
end
end
|
class Transfer
attr_accessor :sender, :receiver, :status, :amount
@@all = []
def initialize(sender, receiver, amount, status = 'pending')
@status = status
@amount = amount
@receiver = receiver
@sender = sender
@@all << self
end
def valid?
sender.valid? && receiver.valid?
end
def execute_transaction
if sender.balance > amount && self.status == 'pending' && valid?
sender.withdrawal(self.amount)
receiver.deposit(self.amount)
self.status = 'complete'
else
self.status = 'rejected'
"Transaction rejected. Please check your account balance."
end
end
def reverse_transfer
if receiver.balance > amount && self.status == 'complete' && valid?
sender.deposit(self.amount)
receiver.withdrawal(self.amount)
self.status = 'reversed'
else
self.status = 'rejected'
"Reversal rejected! Buzz off, 'customer'! "
end
end
end
|
class PostsFetcher
@queue = :fetcher_queue
class << self
def perform(id)
begin
@author = Author.find(id)
rescue ActiveRecord::RecordNotFound
logger.info "Author #{id} not found"
return
end
fetch_and_save_author_posts
end
private
def fetch_and_save_author_posts
@author.posts = (@author.posts + new_posts).uniq(&:post_id)
end
def new_posts
fetch_posts.reject {|post| post["message"].blank?}.map do |raw_post_data|
initialize_new_post(raw_post_data)
end
end
def initialize_new_post(data)
Post.new(post_id: data['id'],
message: data['message'],
updated_time: data['updated_time'],
picture: data['picture'])
end
def fetch_posts
fb_api.get_connections("#{@author.profile}", 'posts')
end
def fb_api
@fb_api ||= Koala::Facebook::API.new(oauth.get_app_access_token)
end
def oath
@oauth ||= Koala::Facebook::OAuth.new(ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'])
end
end
end
|
class Hdl < ApplicationRecord
belongs_to :profile
after_initialize :set_defaults
validates :value, presence: { message: "The value must be provided" },
numericality: {
greater_than: 0
}
validates :date, presence: { message: "A date must be informed" }
def set_defaults
self.date = Time.now unless self.date
end
end
|
require 'csv'
class Todo
def initialize(file_name)
@file_name = file_name
# You will need to read from your CSV here and assign them to the @todos variable. make sure headers are set to true
@todos = CSV.read(@file_name, headers: true)
end
def start
loop do
system('clear')
puts "---- TODO.rb ----"
view_todos
puts
puts "What would you like to do?"
puts "1) Exit 2) Add Todo 3) Mark Todo As Complete 4) Edit a Todo 5) Delete a Todo"
print " > "
action = gets.chomp.to_i
case action
when 1 then exit
when 2 then add_todo
when 3 then mark_todo
when 4 then edit_todo
when 5 then delete_todo
else
puts "\a"
puts "Not a valid choice"
end
end
end
def todos
@todos
end
def view_todos
puts "Unfinished"
unfinished.each{ |row| puts row}
puts "Completed"
completed.each{ |row| puts row}
end
def unfinished
unfinished_todos = @todos.select { |row| row["completed"] == "no"}
unfinished_todos.each_with_index.map { |row, index| "#{index + 1}) #{row[0]}" }
end
def completed
completed_todos = @todos.select { |row| row["completed"] == "yes"}
completed_todos.each_with_index.map { |row, index| "#{index + 1}) #{row[0]}" }
end
def add_todo
puts "Name of Todo > "
new_todo = get_input
@todos << [new_todo, "no"]
save!
end
def mark_todo
puts "Which todo have you finished?"
todo_index = get_input.to_i
unfinished_index = 0
@todos.each_with_index do |row, index|
if row["completed"] == "no"
unfinished_index += 1
if unfinished_index == todo_index
@todos[index]["completed"] = "yes"
end
end
end
save!
end
def edit_todo
puts "Is the todo you want to edit finished (y/n)?"
is_completed = get_input.downcase
if is_completed == "y"
completed_value = "yes"
puts "Which completed todo would you like to edit?"
todo_index = get_input.to_i
elsif is_completed == "n"
completed_value = "no"
puts "Which unfinished todo would you like to edit?"
todo_index = get_input.to_i
else
return
end
puts "new name for todo: "
new_todo = get_input
edited_index = 0
@todos.each_with_index do |row, index|
if row["completed"] == completed_value
edited_index += 1
if edited_index == todo_index
@todos[index]["name"] = new_todo
end
end
end
save!
end
def delete_todo
puts "Is the todo you want to delete finished (y/n)?"
is_completed = get_input.downcase
if is_completed == "y"
completed_value = "yes"
puts "Which completed todo would you like to delete?"
todo_index = get_input.to_i
elsif is_completed == "n"
completed_value = "no"
puts "Which unfinished todo would you like to delete?"
todo_index = get_input.to_i
else
return
end
deleted_index = 0
@todos.each_with_index do |row, index|
if row["completed"] == completed_value
deleted_index += 1
if deleted_index == todo_index
@todos.delete(index)
end
end
end
save!
end
private
def get_input
gets.chomp
end
def save!
File.write(@file_name, @todos.to_csv)
end
end
# Todo.new('../spec/test_todos.csv').start
|
require 'date'
class Randgen
DATE_TIME_EPOCH = ::DateTime.new(2015, 1, 1, 0, 0, 0)
def self.date
return DATE_TIME_EPOCH - rand(800)
end
def self.time
return date.to_time
end
end |
module ApplicationHelper
# Returns the full title on a per-page basis.
# If a page_title is supplied as an argument in calls to this function,
# it is appended to the base_title
def full_title(page_title = '')
base_title = "Hacker Academy"
if page_title.empty?
base_title
else
base_title + " | " + page_title
end
end
end
|
class User < ActiveRecord::Base
devise :omniauthable, :omniauth_providers => [:facebook, :google_oauth2]
has_many :arguments
has_many :theorems
has_many :notifications
#validates :handle, :uniqueness => true, format: {with: /\A[a-zA-Z0-9]+\z/ , message: "may only contain numbers and letters"}
validate do
self.errors.add(:handle, "cannot use that handle") if self.handle == 'theorems'
unless self.handle.nil?
other_user = User.where(handle: self.handle).first
self.errors.add(:handle, "handle already taken") if other_user
self.errors.add(:handle, "handle may only use a-z A-Z and 0-9") unless self.handle =~ /\A[a-zA-Z0-9]+\z/
end
end
def self.from_omniauth(auth)
user = where(provider: auth.provider, uid: auth.uid).first_or_create
user.name = auth.info.name
user.email = auth.info.email
user.save
user
end
def as_json(options={})
super(only: [:id, :name, :handle])
end
end
|
require "isodoc"
require_relative "gbconvert"
require_relative "gbcleanup"
require "gb_agencies"
require_relative "metadata"
require_relative "gbwordrender"
require "fileutils"
module IsoDoc
module Gb
# A {Converter} implementation that generates GB output, and a document
# schema encapsulation of the document for validation
class WordConvert < IsoDoc::WordConvert
def initialize(options)
@common = IsoDoc::Gb::Common.new(options)
@standardclassimg = options[:standardclassimg]
@libdir = File.dirname(__FILE__)
super
@lang = "zh"
@script = "Hans"
end
def default_fonts(options)
script = options[:script] || "Hans"
scope = options[:scope] || "national"
{
bodyfont: (script == "Hans" ? '"SimSun",serif' : '"Cambria",serif'),
headerfont: (script == "Hans" ? '"SimHei",sans-serif' : '"Calibri",sans-serif'),
monospacefont: '"Courier New",monospace',
titlefont: (scope == "national" ? (script != "Hans" ? '"Cambria",serif' : '"SimSun",serif' ) :
(script == "Hans" ? '"SimHei",sans-serif' : '"Calibri",sans-serif' ))
}
end
def default_file_locations(options)
{
wordstylesheet: html_doc_path("wordstyle.scss"),
standardstylesheet: html_doc_path("gb.scss"),
header: html_doc_path("header.html"),
wordcoverpage: html_doc_path("word_gb_titlepage.html"),
wordintropage: html_doc_path("word_gb_intro.html"),
ulstyle: "l7",
olstyle: "l10",
}
end
def extract_fonts(options)
b = options[:bodyfont] || "Arial"
h = options[:headerfont] || "Arial"
m = options[:monospacefont] || "Courier"
t = options[:titlefont] || "Arial"
"$bodyfont: #{b};\n$headerfont: #{h};\n$monospacefont: #{m};\n$titlefont: #{t};\n"
end
def metadata_init(lang, script, labels)
unless ["en", "zh"].include? lang
lang = "zh"
script = "Hans"
end
@meta = Metadata.new(lang, script, labels)
@meta.set(:standardclassimg, @standardclassimg)
@common.meta = @meta
end
def cleanup(docxml)
@cleanup = Cleanup.new(@script, @deprecated_lbl)
super
@cleanup.cleanup(docxml)
docxml
end
def example_cleanup(docxml)
super
@cleanup.example_cleanup(docxml)
end
def i18n_init(lang, script)
super
y = if lang == "en"
YAML.load_file(File.join(File.dirname(__FILE__), "i18n-en.yaml"))
elsif lang == "zh" && script == "Hans"
YAML.load_file(File.join(File.dirname(__FILE__),
"i18n-zh-Hans.yaml"))
else
YAML.load_file(File.join(File.dirname(__FILE__), "i18n-zh-Hans.yaml"))
end
@labels = @labels.merge(y)
end
ENDLINE = <<~END.freeze
<v:line id="_x0000_s1026"
alt="" style='position:absolute;left:0;text-align:left;z-index:251662848;
mso-wrap-edited:f;mso-width-percent:0;mso-height-percent:0;
mso-width-percent:0;mso-height-percent:0'
from="6.375cm,20.95pt" to="10.625cm,20.95pt"
strokeweight="1.5pt"/>
END
def end_line(_isoxml, out)
out.parent.add_child(ENDLINE)
end
def generate_header(filename, dir)
return unless @header
template = Liquid::Template.parse(File.read(@header, encoding: "UTF-8"))
meta = @meta.get
meta[:filename] = filename
params = meta.map { |k, v| [k.to_s, v] }.to_h
File.open("header.html", "w:utf-8") { |f| f.write(template.render(params)) }
FileUtils.cp @common.fileloc(File.join('html', 'blank.png')), "blank.png"
@files_to_delete << "blank.png"
@files_to_delete << "header.html"
"header.html"
end
def header_strip(h)
h = h.to_s.gsub(%r{<br/>}, " ").sub(/<\/?h[12][^>]*>/, "")
h1 = to_xhtml_fragment(h.dup)
h1.traverse do |x|
x.replace(" ") if x.name == "span" &&
/mso-tab-count/.match?(x["style"])
x.remove if x.name == "span" && x["class"] == "MsoCommentReference"
x.remove if x.name == "a" && x["epub:type"] == "footnote"
x.replace(x.children) if x.name == "a"
end
from_xhtml(h1)
end
def word_cleanup(docxml)
word_preface(docxml)
word_annex_cleanup(docxml)
@cleanup.title_cleanup(docxml.at('//div[@class="WordSection2"]'))
docxml
end
def omit_docid_prefix(prefix)
super || prefix == "Chinese Standard"
end
end
end
end
|
require 'time'
module JADOF #:nodoc:
# Represents a blog post. Has the same functionality as {Page}
# but with a {#date} added (which makes {#to_param}) include
# a date, in the conventional way: `2010/01/31/name-of-post`
class Post < Page
# @return [Time] the date that this post was created.
# If a [String] is passed in, it will be parsed as a time.
attr_accessor :date
def date= value
@date = Time.parse value.to_s
end
# @return [String] The conventional way to display blog
# post urls, eg. `2010/01/31/name-of-post`
def to_param
date ? "#{ date.strftime('%Y/%m/%d') }/#{ full_name }" : super
end
end
end
|
Chef::Log.info('Running deploy/before_symlink.rb...')
rails_env = new_resource.environment['RAILS_ENV']
current_release = release_path
Chef::Log.info("Precompiling assets for #{rails_env}...")
execute 'rake assets:precompile' do
cwd current_release
command 'bundle exec rake assets:precompile'
environment new_resource.environment
end
Chef::Log.info("Seeding database for #{rails_env}...")
execute 'rake db:seed' do
cwd current_release
command 'bundle exec rake db:seed'
environment new_resource.environment
end
|
class User
class Notification < ApplicationRecord
belongs_to :user
validates :read, inclusion: { in: [true, false] }
validates :message, presence: true
validates :link, presence: true
end
end
|
require 'json'
require 'cuba'
require_relative 'fizz_buzz'
require_relative 'fizz_buzz_presenter'
GET_DISPLAY_MESSAGE = 'Welcome to Mario\'s FizzBuzz. The API endpoint is a POST
to /fizz_buzz.json. Thanks for visiting. I hope you enjoyed this demonstration.'
Cuba.define do
on post do
on /fizz_buzz\.json\z/ do
# NOTE: Cuba doesn't allow empty strings to be passed as default params.
# We work around this by passing a proc to `on`. See this issue for more
# details: https://github.com/soveran/cuba/issues/76
fizz_buzz_response_handler = Proc.new{|number=''|
fizz_buzz = FizzBuzz.new(number: number)
response = FizzBuzzPresenter.new(fizz_buzz: fizz_buzz).as_json
res.status = 422 if !fizz_buzz.valid?
res.write(response)
}
on param('number'), &fizz_buzz_response_handler
on true, &fizz_buzz_response_handler
end
end
on get do
on root do
res.write GET_DISPLAY_MESSAGE
end
on /.+/ do
res.redirect '/'
end
end
end
|
require 'spec_helper'
require 'puppet_x/puppetlabs/deep_symbolize_keys'
describe 'deep_symbolize_keys' do
describe Hash do
it 'should have been monkey patched with deep_symbolize_keys' do
expect(subject.respond_to?(:deep_symbolize_keys))
end
it 'should have symbols for keys after deep_symbolize_keys is called' do
expect({ 'a' => 1 }.deep_symbolize_keys).to eq(a: 1)
end
end
describe Array do
it 'should have been monkey patched with deep_symbolize_keys' do
expect(subject.respond_to?(:deep_symbolize_keys))
end
it 'should have symbols for keys after deep_symbolize_keys is called' do
expect([{ 'a' => 1 }].deep_symbolize_keys).to eq([{ a: 1 }])
end
end
end
|
class ArtistCitiesController < ApplicationController
before_action :set_artist_city, only: [:show, :update, :destroy]
def destroy
@artist_city.destroy()
head :no_content
end
def update
@artist_city.is_primary = artist_city_params[:is_primary]
@artist_city.save()
head :no_content
#json_response(@member_contact.to_json(:include => :contact), :ok)
end
def create
@artist_city = ArtistCity.create!(artist_city_params)
json_response({
artist_city: @artist_city
})
end
def artist_city_params
params.require(:artist_city).permit(:artist_id, :city_id, :is_primary, :sequence)
end
def set_artist_city
@artist_city = ArtistCity.find(params[:id]) if params[:id]
end
end
|
class BadCollecteFolder < StandardError ; end
class Collecte
class << self
# {Collecte} La collecte courante, pour qu'elle soit
# accessible de partout avec `Collecte.current`
attr_accessor :current
# Lors de l'appel par la commande `collecte`, cette
# méthode vérifie qu'un dossier de collecte soit bien
# accessible. Ce dossier peut être précisé soit parce
# que c'est le dossier courant, soit parce qu'il a
# été donné dans la commande (en dernier argument).
#
# Si on a bien un dossier de collecte, on renvoie true,
# sinon on renvoie false ce qui lève une exception.
#
def check_collecte_folder
@command_folder ||= CURRENT_FOLDER
# Le dossier doit exister
File.exist?(@command_folder) || raise(BadCollecteFolder, "Le dossier de collecte `#{@command_folder}` est introuvable…")
# Le dossier doit contenir des fichiers typiques d'une
# collecte et notamment, surtout, le fichier scènes
fscenes = File.join(@command_folder, 'scenes.collecte')
File.exist?(fscenes) || raise(BadCollecteFolder, "Le dossier courant (`#{@command_folder}`) n’est pas un dossier de collecte.")
return true
rescue BadCollecteFolder => e
puts "### ERREUR : #{e.message}"
return false
end
end #/<< self
end #/Collecte
|
require 'spec_helper'
require_relative '../../lib/paths'
using StringExtension
module Jabverwock
RSpec.describe 'jwCssJs test' do
subject(:jwjs){JW_CSS_JS.new}
it "alias of js.doc" do
# jdoc == js.doc
jwjs.jdoc.write("a")
expect(jwjs.js.doc.orders[0]).to eq "document.write('a');"
end
it "document write case 1" do
jwjs.js.doc.write("a")
expect(jwjs.js.doc.orders[0]).to eq "document.write('a');"
end
it "document write case 2" do
jwjs.js.doc.write("a")
expect(jwjs.js.orders[0]).to eq "document.write('a');"
end
it "document write case 2-2" do
a = jwjs.js.doc.write("a")
expect(jwjs.js.orders[0]).to eq "document.write('a');"
end
it "document write case 2-3).to eq alias" do
a = jwjs.jdoc.write("a")
expect(jwjs.js.orders[0]).to eq "document.write('a');"
end
it "document write case 3" do
a = jwjs.js.doc.write("a")
expect(jwjs.orders[0]).to eq "document.write('a');"
end
it "document write case 4" do
jwjs.js.doc.updateSelector :id__sample
a = jwjs.js.doc.write("a")
jwjs.js.doc.byID.innerHTML("aa".dQuo)
expect(jwjs.orders[1]).to eq "document.getElementById('sample').innerHTML = \"aa\";"
end
it "when set jwjs class id, js id set at the same time" do
jwjs.attr :id__sample
jwjs.js.doc.byID
expect(jwjs.orders[0]).to eq "document.getElementById('sample');"
end
# #### add member ####
it "add jsArray to js.units case 1" do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
expect(parent.jsArray.count).to eq 0
end
it "add jsArray to js.units case 2" do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
# this is expression for test of assembleJS
# this mean self.js.units convert to self.jsArray
# parent.jsArray.append parent.js.units
parent.self_JsOrders_add_to_self_jsArray
expect(parent.jsArray.count).to eq 1
end
it "add member " do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
child = JW_CSS_JS.new.attr(:id__test)
child.js.doc.write("child")
parent.addMember child
expect(parent.jsArray).to eq child.orders
end
it "add member case 2 " do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
child = JW_CSS_JS.new.attr(:id__test)
child.js.doc.write("child")
child.js.doc.write("child again")
parent.addMember child
expect(parent.jsArray.count).to eq 2 # child and child again
end
it "add member case 3 " do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
child = JW_CSS_JS.new.attr(:id__test)
child.js.doc.write("child")
child.js.doc.write("child again")
parent.addMember child
parent.self_JsOrders_add_to_self_jsArray
expect(parent.jsArray.count).to eq 3 # parent, child and child again
end
it "assembleJS, show JS Result" do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
child = JW_CSS_JS.new.attr(:id__test)
child.js.doc.write("child")
child.js.doc.write("child again")
parent.addMember child
parent.assembleJS
# p parent.showJsResult
# p parent.applyJS
end
it "assembleHTML test" do
parent = JW_CSS_JS.new.attr(:id__sample)
parent.js.doc.write("parent")
child = JW_CSS_JS.new.attr(:id__test)
child.js.doc.write("child")
child.js.doc.write("child again")
parent.addMember child
parent.assemble
end
# ## file read ####
# it "file read" do
# jwCssJs = JW_CSS_JS.new
# jwCssJs.jsRead "./sample.js"
# expect(jwCssJs.orders[0]).to eq "var myCollection = document.getElementsByTagName(\"p\");"
# expect(jwCssJs.orders.last).to eq "}"
# end
end
end
|
class AnnotatorType < BaseObject
description "Information about an annotator"
implements GraphQL::Types::Relay::Node
field :name, GraphQL::Types::String, null: true
field :profile_image, GraphQL::Types::String, null: true
field :user, UserType, null: true
def user
User.where(id: object.id).last if object.is_a?(User)
end
end
|
class Yj < FPM::Cookery::Recipe
description 'CLI - Convert YAML <=> TOML <=> JSON <=> HCL'
name 'yj'
version '4.0.0'
revision '1'
homepage 'https://github.com/sclevine/yj'
source "https://github.com/sclevine/yj/releases/download/v#{version}/yj-linux"
sha256 '0019875f3f0aa1ea14a0969ce8557789e95fe0307fa1d25ef29ed70ad9874438'
def build
end
def install
chmod 0555, 'yj-linux'
bin.install 'yj-linux', 'yj'
end
end
|
#!/bin/env ruby
# move to directory of this file, so that icons can load correctly.
Dir.chdir(File.dirname(File.expand_path(__FILE__)))
# Load FXRuby: try gem, then Fox 1.6 directly
begin
# try fxruby gem
require 'rubygems'
gem 'fxruby', '= 1.6'
require 'fox16'
require 'fox16/colors'
FOXVERSION="1.6"
include Fox
rescue LoadError
# no gem? try fox16 direct.
begin
require 'fox16'
require 'fox16/colors'
FOXVERSION="1.6"
include Fox
rescue
# Workaround for Windows OCI: Use fox12
begin
gem 'fxruby'
require 'fox12'
require 'fox12/colors'
FOXVERSION="1.2"
include Fox
rescue
# no gem, no fox16/12? -> die
STDERR << "ERROR: You need FXRuby >= 1.2!"
exit
end
end
end
require 'thread'
require 'lib/RiManager'
require 'lib/Recursive_Open_Struct'
require 'lib/Globals'
require 'lib/Packet_List'
require 'lib/Packet_Item'
require 'lib/Empty_Text_Field_Handler'
require 'lib/Icon_Loader'
require 'lib/Search_Engine'
require 'lib/FoxDisplayer'
require 'lib/FoxTextFormatter'
require 'lib/fxirb'
=begin
# Parse any options passed to fxri and store them in $options
$options = OpenStruct.new
$options.search_paths = []
opts = OptionParser.new { |opts|
opts.banner = "fxri - A graphical interface to the Ruby documentation.\nUsage: fxri [options]"
opts.separator ""
opts.separator "Specific options:"
opts.on( "-I", "--search-path [PATH]",
"Specify additional search paths to look for ri documentation",
"(may be used multiple times)") { |path|
$options.search_paths << path if File.directory? path
}
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
}
opts.parse!( ARGV )
=end
# Responsible for application initialization
class FXri < FXHorizontalFrame
# Initializes the XDCC-application.
def initialize(p, opts=0, x=0 ,y=0 ,w=0 ,h=0 , pl=DEFAULT_SPACING, pr=DEFAULT_SPACING, pt=DEFAULT_SPACING, pb=DEFAULT_SPACING, hs=DEFAULT_SPACING, vs=DEFAULT_SPACING)
super(p, opts, x ,y ,w ,h , pl, pr, pt, pb, hs, vs)
@isLoaded = false
set_default_font
# load icons
icon_loader = Icon_Loader.new(FXApp::instance)
icon_loader.cfg_to_icons($cfg.icons)
@gui = Recursive_Open_Struct.new
@gui.main = self
@data = Recursive_Open_Struct.new
@data.gui_mutex = Mutex.new
build(self)
FXToolTip.new(FXApp::instance, TOOLTIP_NORMAL)
@gui.close
create_data
@data.close
@search_engine = Search_Engine.new(@gui, @data)
# show init message
@data.displayer.display_information($cfg.text.help)
end
# Automatically called when the Fox application is created
def create
super
show
# load items
Thread.new do
# delayed loading, this speeds up freeride's startup.
sleep 1 if $cfg.delayed_loading
@gui.search_field.enabled = false
load_items
@isLoaded = true
@gui.search_field.enabled = true
@gui.search_field.text = ""
end
end
def create_data
@data.displayer = FoxDisplayer.new(@gui.text)
@data.ri_manager = RiManager.new(@data.displayer)
@data.items = Array.new
@desc = nil
end
# Set the default font to the first font of $cfg.app.font.name that is available on this system.
def set_default_font
@font = load_font($cfg.app.font.name)
FXApp::instance.normalFont = @font if @font
end
# Returns the first font of the given array of font names that can be loaded, or nil.
def load_font(font_array)
# load default font
font = nil
font_array.detect do |name|
next if FXFont.listFonts(name).empty?
font = FXFont.new(FXApp::instance, name, $cfg.app.font.size)
end
font
end
# build gui
def build(parent)
FXSplitter.new(parent, SPLITTER_TRACKING|LAYOUT_FILL_X|LAYOUT_FILL_Y) do |base|
FXVerticalFrame.new(base, LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,$cfg.packet_list_width,0, 0,0,0,0,0,0) do |search_frame|
@gui.search_field = FXTextField.new(search_frame, 1, nil, 0, TEXTFIELD_NORMAL|LAYOUT_FILL_X|FRAME_SUNKEN)
@gui.search_field.connect(SEL_CHANGED) do |*args|
on_search
end
FXVerticalFrame.new(search_frame, FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0,0,0) do |list_frame|
@gui.packet_list = Packet_List.new(@data, list_frame, nil, 0,
ICONLIST_DETAILED|
ICONLIST_COLUMNS|
#ICONLIST_MINI_ICONS|
HSCROLLER_NEVER|
VSCROLLER_ALWAYS|
ICONLIST_BROWSESELECT|
LAYOUT_FILL_X|
LAYOUT_FILL_Y) do |packet_list|
packet_list.add_header($cfg.text.method_name, $cfg.packet_list_width) { |x| make_sortable(x) }
end
@gui.packet_list.setHeaderSize(0, 1000)
end
@gui.search_label = FXLabel.new(search_frame, "", nil, LAYOUT_FILL_X|LABEL_NORMAL|JUSTIFY_RIGHT, 0,0,0,0, 0,0,0,0)
@gui.packet_list.connect(SEL_SELECTED) do |sender, sel, data|
item = sender.getItem(data).packet_item
show_info(item.data)
end
end
split = FXSplitter.new(base, SPLITTER_TRACKING|LAYOUT_FILL_X|LAYOUT_FILL_Y|SPLITTER_VERTICAL) if $cfg.launch_irb
right = FXHorizontalFrame.new(($cfg.launch_irb ? split : base), FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0,0,0)
@gui.text = FXText.new(right, nil, 0, TEXT_READONLY|TEXT_WORDWRAP|LAYOUT_FILL_X|LAYOUT_FILL_Y)
if $cfg.launch_irb
irb_frame = FXHorizontalFrame.new(split, FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0,0,0)
@irb_frame = irb_frame
@gui.irb = FXIrb.init(irb_frame, nil, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y|TEXT_WORDWRAP|TEXT_SHOWACTIVE)
@gui.irb.setFont(@font) if @font
split.setSplit(0, $cfg.irb_height)
end
font = load_font($cfg.ri_font)
@gui.text.font = font if font
font.create
@gui.text_width = font.fontWidth
@gui.text.connect(SEL_CONFIGURE) do
on_show if @desc
end
# construct hilite styles
@gui.text.styled = true
@gui.text.hiliteStyles = create_styles
end
end
def create_empty_style
hs = FXHiliteStyle.new
hs.activeBackColor = FXColor::White
hs.hiliteBackColor = FXColor::DarkBlue
hs.normalBackColor = FXColor::White
hs.normalForeColor = FXColor::Black
hs.selectBackColor = FXColor::DarkBlue
hs.selectForeColor = FXColor::White
hs.style = 0
hs
end
def create_styles
styles = Array.new
#normal
styles.push create_empty_style
# bold
hs = create_empty_style
hs.style = FXText::STYLE_BOLD
styles.push hs
# H1
hs = create_empty_style
hs.style = FXText::STYLE_UNDERLINE|FXText::STYLE_BOLD
hs.normalForeColor = FXColor::ForestGreen
styles.push hs
# H2
hs = create_empty_style
hs.style = FXText::STYLE_UNDERLINE
hs.normalForeColor = FXColor::ForestGreen
styles.push hs
# H3
hs = create_empty_style
hs.normalForeColor = FXColor::ForestGreen
styles.push hs
# teletype
hs = create_empty_style
hs.normalForeColor = FXColor::DarkCyan
styles.push hs
# code
hs = create_empty_style
hs.activeBackColor = FXColor::LightGrey
hs.normalForeColor = FXColor::DarkGreen
hs.style = FXText::STYLE_UNDERLINE|FXText::STYLE_BOLD
styles.push hs
# emphasis
hs = create_empty_style
hs.normalForeColor = FXColor::DarkCyan
styles.push hs
# class
hs = create_empty_style
hs.style = FXText::STYLE_BOLD
hs.normalForeColor = FXColor::Blue
styles.push hs
styles
end
# loads all ri items
def load_items
@gui.search_field.text = "loading..."
@data.ri_manager.all_names.each do |name|
icon = case name.type
when NameDescriptor::CLASS
$cfg.icons.klass
when NameDescriptor::INSTANCE_METHOD
$cfg.icons.instance_method
when NameDescriptor::CLASS_METHOD
$cfg.icons.class_method
end
item = Packet_Item.new(@gui.packet_list, icon, name.to_s)
@search_engine.update_search_status_text
item.data = name
@data.items.push item
end
@gui.search_field.text = "sorting..."
@gui.packet_list.on_cmd_header(0)
@gui.packet_list.update_header_width
recalc
end
def go_search(string)
@gui.search_field.text = string
on_search
end
def on_search
# do nothing if not fully loaded
return if !@isLoaded
@search_engine.on_search
end
def on_show
begin
w = @gui.text.width / @gui.text_width - 3
w = [w, $cfg.minimum_letters_per_line].max
@data.ri_manager.show(@desc, w)
rescue RiError => e
#puts desc
end
end
def show_info(desc)
@desc = desc
on_show
end
# x beeing the name of the ri doc, like "Set#delete"
# This creates a sortable representation. First class, then class methods, then instance.
def make_sortable(x)
[ x.downcase.gsub("::", " 1 ").gsub("#", " 2 "),
x.downcase,
x]
end
end
Thread.abort_on_exception= true
application = FXApp.new($cfg.app.name, $cfg.app.name)
application.threadsEnabled = true
#application.init(ARGV)
window = FXMainWindow.new(application, $cfg.app.name, nil, nil, DECOR_ALL, 0, 0, $cfg.app.width, $cfg.app.height)
FXri.new(window,FRAME_NONE|LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0,0,0,0,0,0,0)
application.create
window.show(PLACEMENT_SCREEN)
application.run
|
require 'test/unit'
require 'noofakku/instruction/output'
require 'shoulda'
require 'ostruct'
module Noofakku
class OutputTest < Test::Unit::TestCase
context "Execution" do
setup do
@instance = Output.new
end
should "throw on nil processor" do
assert_raise (RuntimeError) { @instance.perform(nil, Object.new, Object.new, Object.new, Object.new) }
end
should "throw on nil memory" do
assert_raise (RuntimeError) { @instance.perform(Object.new, nil, Object.new, Object.new, Object.new) }
end
should "throw on nil output" do
assert_raise (RuntimeError) { @instance.perform(Object.new, Object.new, Object.new, Object.new, nil) }
end
should "yield the value of the memory cell addressed by the data pointer" do
spy_processor = OpenStruct.new(data_pointer: 0)
output = ->value { assert_equal 42, value }
@instance.perform(spy_processor, [42], nil, nil, output)
end
end
end
end |
# frozen_string_literal: true
class UpdateGroupSummariesToVersion2 < ActiveRecord::Migration[6.1]
def change
update_view :group_summaries, version: 2, revert_to_version: 1
end
end
|
# frozen_string_literal: true
# TODO: add tests
module Ringu
module Container
def self.included(base)
base.extend(ClassMethods)
const_set "Inject", Ringu::Injector.create(base.deps)
const_set "Resolve", Ringu::Resolver.create(base.deps)
end
module ClassMethods
def deps
@deps ||= Ringu::Deps.new
end
def register(name, value)
deps.register(name, value)
end
def resolve(name)
deps.resolve(name)
end
end
end
end
|
module Types
class MutationType < Types::BaseObject
field :create_article, mutation: Mutations::Articles::Create
field :update_article, mutation: Mutations::Articles::Update
field :destroy_article, mutation: Mutations::Articles::Destroy
field :article_toggle_favorite, mutation: Mutations::Articles::ToggleFavorite
field :create_comment, mutation: Mutations::Comments::Create
field :update_comment, mutation: Mutations::Comments::Update
field :destroy_comment, mutation: Mutations::Comments::Destroy
field :create_account, mutation: Mutations::Account::Create
field :update_profile, mutation: Mutations::Profile::Update
field :user_toggle_follow, mutation: Mutations::Users::ToggleFollow
end
end
|
# frozen_string_literal: true
# audit logging.
class Payment < ActiveRecord::Base
belongs_to :user
belongs_to :payer, class_name: 'User'
validates :user, :payer, :balance_cents, presence: true
validates :balance_cents, numericality: {greater_than: 0}
register_currency :pln
monetize :balance_cents
scope :newest_first, -> { order(created_at: :desc) }
end
|
def merchant_with_items(items_count: 3)
FactoryBot.create(:merchant) do |merchant|
FactoryBot.create_list(:item, items_count, merchant: merchant)
end
end |
require 'sinatra'
before do
content_type :txt
end
get '/attachment' do
attachment 'test.txt'
"Here's what will be sent downstream, in an attachment called 'test.txt'."
end
# Attachment should be shown in a 'Content-Disposition' header.
# It is downloaded when browsed. |
require 'simplernlg'
nlg = SimplerNLG::NLG
# the republicans
# won the white house
# in every year that bears killed more than 10 people
phrase = nlg.phrase({
:s => 'the Republicans', # nlg.factory.create_noun_phrase('the', 'Republican'),
:number => :plural,
:v => 'win',
:perfect => true,
:tense => :present,
:o => nlg.factory.create_noun_phrase('the', 'White House')
})
bears = nlg.factory.create_noun_phrase('bear')
bears.set_feature SimplerNLG::NLG::Feature::NUMBER, SimplerNLG::NLG::NumberAgreement::PLURAL
comp = nlg.phrase({
:s => bears,
:v => 'kill',
:tense => :past,
:o => 'more than 10 people'
})
pp = nlg.factory.create_preposition_phrase('in', nlg.factory.create_noun_phrase('every', 'year'))
pp.add_post_modifier(comp)
modifiers = [:add_post_modifier, :add_pre_modifier, :add_front_modifier]
# phrase.add_post_modifier pp
# The Republicans have won the White House in every year bears killed more than 10 people.
# phrase.add_pre_modifier pp
# The Republicans have in every year bears killed more than 10 people won the White House.
phrase.send(modifiers.sample, pp)
# In every year bears killed more than 10 people the Republicans have won the White House.
sent = nlg.realizer.realise_sentence(phrase)
puts sent
# comp = nlg.factory.create_clause();
# comp.set_subject('bears');
# comp.set_verb_phrase('kill');
# comp.set_object(this.man);
|
#
# Cookbook Name:: bootstrap_linux
# Recipe:: ohmyzsh
#
# Copyright (C) 2015 YOUR_NAME
#
# All rights reserved - Do Not Redistribute
#
if node['ohmyzsh']['install']
package 'zsh'
execute 'ohmyzsh' do
command "curl -S https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sudo -u #{node['user']} bash"
cwd node['home']
action :run
only_if { File.exists?('/bin/zsh') }
end
template "#{node['home']}/.zshrc" do
source 'zshrc.erb'
user node['user']
owner node['user']
mode 00744
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.