text stringlengths 10 2.61M |
|---|
# encoding: utf-8
class ConversationsController < ApplicationController
before_filter :authenticate_user!
# before_filter :get_mailbox, :get_box, :get_actor
before_filter :get_mailbox, :get_box
before_filter :check_current_subject_in_conversation, :only => [:show, :update, :destroy,:reply]
before_filter :mark_read, :only => :show
before_filter :get_unread_count, :only => [:show, :index]
def index
@title = "我的私信"
@conversations = @mailbox.conversations.order("created_at DESC").page(params[:page]).per(9)
# mask all items as read
# if @box.eql? "inbox"
# @conversations = @mailbox.inbox.page(params[:page]).per(9)
# elsif @box.eql? "sentbox"
# @conversations = @mailbox.sentbox.page(params[:page]).per(9)
# else
# @conversations = @mailbox.trash.page(params[:page]).per(9)
# end
end
def show
@title = "对话"
unless @conversation.is_participant?(current_user)
notice_stickie t("notice.no_ability")
return redirect_to root_path
end
@message = Message.new conversation_id: @conversation.id
#
#
# if @box.eql? 'trash'
# @receipts = @mailbox.receipts_for(@conversation).trash
# else
# @receipts = @mailbox.receipts_for(@conversation).not_trash
# end
# render :action => :show
# @receipts.mark_as_read
end
def new
end
def edit
end
def create
end
def update
if params[:untrash].present?
@conversation.untrash(@actor)
end
if params[:reply_all].present?
last_receipt = @mailbox.receipts_for(@conversation).last
@receipt = @actor.reply_to_all(last_receipt, params[:body])
end
if @box.eql? 'trash'
@receipts = @mailbox.receipts_for(@conversation).trash
else
@receipts = @mailbox.receipts_for(@conversation).not_trash
end
redirect_to :action => :show
@receipts.mark_as_read
end
def destroy
@conversation.move_to_trash(@actor)
respond_to do |format|
format.html {
if params[:location].present? and params[:location] == 'conversation'
redirect_to conversations_path(:box => :trash)
else
redirect_to conversations_path(:box => @box,:page => params[:page])
end
}
format.js {
if params[:location].present? and params[:location] == 'conversation'
render :js => "window.location = '#{conversations_path(:box => @box,:page => params[:page])}';"
else
render 'conversations/destroy'
end
}
end
end
def search
@message = Message.new
#搜索私信内容
@conversations = current_user.mailbox.conversations.
joins([:messages, :receipts]).
where("notifications.body like ? ", "%#{params[:search]}%")
#搜索私信用户
if user = User.find_by_username(params[:search])
conversation = current_user.has_conversation_with?(user)
@conversations << conversation if conversation
end
#TODO: 加分页
# page = params[:page] || 1
# if !(@conversations.nil?)
# unless @conversations.kind_of?(Array)
# @conversations = @conversations.page(page).per(8)
# else
# @conversations = Kaminari.paginate_array(@conversations).page(page).per(10)
# end
# end
end
private
def get_mailbox
@mailbox = current_user.mailbox
end
# def get_actor
# @actor = Actor.normalize(current_subject)
# end
def get_box
if params[:box].blank? or !["inbox","sentbox","trash"].include?params[:box]
@box = "inbox"
return
end
@box = params[:box]
end
def check_current_subject_in_conversation
@conversation = Conversation.find_by_id(params[:id])
if @conversation.nil? or !@conversation.is_participant?(current_user)
# if @conversation.nil?
redirect_to conversations_path(:box => @box)
return
end
end
def mark_read
@conversation = Conversation.find_by_id(params[:id])
current_user.read(@conversation)
end
end
|
require 'rails_helper'
RSpec.describe "announcements/show", type: :view do
before(:each) do
@announcement = assign(:announcement, Announcement.create!(
:name => "Name",
:kind => "Kind",
:title => "Title",
:subtitle => "Subtitle",
:column => 2,
:lines => 3,
:page => 4,
:color => "Color",
:script => "MyText",
:publication => nil
))
end
it "renders attributes in <p>" do
render
expect(rendered).to match(/Name/)
expect(rendered).to match(/Kind/)
expect(rendered).to match(/Title/)
expect(rendered).to match(/Subtitle/)
expect(rendered).to match(/2/)
expect(rendered).to match(/3/)
expect(rendered).to match(/4/)
expect(rendered).to match(/Color/)
expect(rendered).to match(/MyText/)
expect(rendered).to match(//)
end
end
|
class TagExperience < ApplicationRecord
belongs_to :tag
belongs_to :experience
end
|
module Spree
class ReportGenerationService
REPORTS = {
finance_analysis: [
:payment_method_transactions, :payment_method_transactions_conversion_rate,
:sales_performance, :shipping_cost, :sales_tax
],
product_analysis: [
:cart_additions, :cart_removals, :cart_updations,
:product_views, :product_views_to_cart_additions,
:product_views_to_purchases, :unique_purchases,
:best_selling_products, :returned_products
],
promotion_analysis: [:promotional_cost, :annual_promotional_cost],
trending_search_analysis: [:trending_search],
user_analysis: [:user_pool, :users_not_converted, :users_who_recently_purchased]
}
def self.generate_report(report_name, options)
klass = Spree.const_get((report_name.to_s + '_report').classify)
resource = klass.new(options)
dataset = resource.generate
total_records = resource.select_columns(dataset).count
if resource.no_pagination?
result_set = dataset
else
result_set = resource.select_columns(dataset.limit(options['records_per_page'], options['offset'])).all
end
options['no_pagination'] = resource.no_pagination?.to_s unless options['no_pagination'] == 'true'
[headers(klass, resource, report_name), result_set, total_pages(total_records, options['records_per_page'], options['no_pagination']), search_attributes(klass), resource.chart_json, resource]
end
def self.download(options = {}, headers, stats)
::CSV.generate(options) do |csv|
csv << headers.map { |head| head[:name] }
stats.each do |record|
csv << headers.map { |head| record[head[:value]] }
end
end
end
def self.search_attributes(klass)
search_attributes = {}
klass::SEARCH_ATTRIBUTES.each do |key, value|
search_attributes[key] = value.to_s.humanize
end
search_attributes
end
def self.total_pages(total_records, records_per_page, no_pagination)
if no_pagination != 'true'
total_pages = total_records / records_per_page
if total_records % records_per_page == 0
total_pages -= 1
end
total_pages
end
end
def self.headers(klass, resource, report_name)
klass::HEADERS.keys.map do |header|
{
name: Spree.t(header.to_sym, scope: [:insight, report_name]),
value: header,
sorted: resource.try(:header_sorted?, header) ? resource.sortable_type.to_s : nil,
type: klass::HEADERS[header],
sortable: header.in?(klass::SORTABLE_ATTRIBUTES)
}
end
end
end
end
|
class Rect
def initialize(x, y, w, h)
@x1 = x
@y1 = y
@x2 = x + w
@y2 = y + h
end
def x1
@x1
end
def y1
@y1
end
def x2
@x2
end
def y2
@y2
end
def center
center_x = (@x1 + @x2) / 2
center_y = (@y1 + @y2) / 2
[center_x.to_i, center_y.to_i]
end
def intersects_with rect
(@x1 <= rect.x2) && (@x2 >= rect.x1) && (@y1 <= rect.y2) && (@y2 >= rect.y1)
end
end
|
#Fedena
#Copyright 2011 Foradian Technologies Private Limited
#
#This product includes software developed at
#Project Fedena - http://www.projectfedena.org/
#
#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.
class FinanceDonation < ActiveRecord::Base
belongs_to :transaction, :class_name => 'FinanceTransaction'
validates_presence_of :donor, :amount
validates_numericality_of :amount, :greater_than => 0, :message =>:should_be_non_zero, :unless => "amount.nil?"
after_create :create_finance_transaction
# after_create :create_finance_transaction
before_save :verify_precision
has_many :donation_additional_details, :dependent => :destroy
accepts_nested_attributes_for :donation_additional_details, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
before_create :set_financial_year
def set_financial_year
self.financial_year_id = FinancialYear.current_financial_year_id
end
def verify_precision
self.amount = FedenaPrecision.set_and_modify_precision self.amount
end
def create_finance_transaction
transaction = FinanceTransaction.create(
:title => "#{t('donation_from')}" + donor,
:description => description,
:amount => amount,
:transaction_date => transaction_date,
:finance_type => "FinanceDonation",
:finance_id => self.id,
:category => FinanceTransactionCategory.find_by_name('Donation')
)
self.transaction_id = transaction.id
self.send(:update_without_callbacks)
end
def self.donors_list(params)
conditions = []
conds = "(ftrr.fee_account_id IS NULL OR fa.is_deleted = false) "
if params.present?
conditions << "#{conds} AND finance_donations.transaction_date BETWEEN ? AND ?"
conditions << params[:from].to_date.beginning_of_day
conditions << params[:to].to_date.end_of_day
else
conditions << conds
end
@donations = FinanceDonation.all(:include => {:transaction => :transaction_receipt}, :conditions => conditions,
:joins => "INNER JOIN finance_transactions ft ON ft.finance_type = 'FinanceDonation' AND ft.finance_id = finance_donations.id
INNER JOIN finance_transaction_receipt_records ftrr ON ftrr.finance_transaction_id = ft.id
LEFT JOIN fee_accounts fa ON fa.id = ftrr.fee_account_id", :order => "created_at ASC")
data = []
@addional_field_titles = DonationAdditionalField.all( :select => :name, :conditions => "status = true",
:order => :priority)
col_heads = ["#{t('donor')}", "#{t('description')}", "#{t('amount')}", "#{t('receipt_no')}",
"#{t('transaction_date')}"]
col_heads += @addional_field_titles.collect(&:name)
data << col_heads
@donations.each_with_index do |c,i|
@additional_details = c.donation_additional_details.find(:all, :include => [:donation_additional_field],
:order => "donation_additional_fields.priority ASC")
col = []
col << "#{c.donor}"
col << "#{c.description}"
col << "#{FedenaPrecision.set_and_modify_precision(c.amount)}"
col << "#{c.transaction.receipt_number}"
col << "#{format_date(c.transaction_date)}"
col += @additional_details.collect(&:additional_info)
col = col.flatten
data << col
end
return data
end
def fetch_other_details_for_cancelled_transaction
{:payee_name=>donor}
end
end
|
class Car < ApplicationRecord
validates :name, :color, presence: true
validates :name, :space_uuid, uniqueness: { allow_blank: true }
scope :unparked, -> { where space_uuid: nil }
def can_park?
# TODO: check if there is an available space
end
def park!
# TODO: get an available space, claim it, and store its UUID
end
def self.clear_out!
# TODO: clear all used parking spaces
end
end
|
require_dependency "kanban_board_ui/application_controller"
module KanbanBoardUi
class AssignmentsController < ApplicationController
before_filter :authenticate_user!
def update
@assignment = KanbanBoard::Assignment.find(params[:id])
authorize! :update, @assignment
@project = @assignment.project
respond_to do |format|
if @assignment.update(assignment_params)
format.html { redirect_to project_path(@project), notice: 'Task was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
private
def assignment_params
params.require(:assignment).permit(:status)
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant::Config.run do |config|
config.vm.define :web do |web_config|
web_config.vm.box = "precise32"
web_config.vm.box_url = "http://files.vagrantup.com/precise32.box"
web_config.vm.host_name = "lies-i-told-my-kids-playground"
web_config.vm.customize ["modifyvm", :id, "--memory", 768]
web_config.vm.network :hostonly, "172.22.22.22"
web_config.vm.share_folder "v-root", "/vagrant", "./" #, :nfs => true
web_config.vm.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"]
web_config.vm.forward_port 80, 8080 #apache2
web_config.vm.forward_port 5432, 8032 #postgresql
web_config.vm.forward_port 3306, 8006 #mysql
web_config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = ["cookbooks", "custom_cookbooks"]
chef.add_recipe "apt"
chef.add_recipe "openssl"
chef.add_recipe "apache2"
#chef.add_recipe "postgresql::client"
#chef.add_recipe "postgresql::server"
chef.add_recipe "mysql::client"
chef.add_recipe "mysql::server"
chef.add_recipe "git"
chef.add_recipe "subversion"
chef.add_recipe "php"
chef.add_recipe "php_modules"
chef.add_recipe "apache2::mod_php5"
chef.add_recipe "apache2::mod_rewrite"
chef.add_recipe "apache2::mod_deflate"
chef.add_recipe "apache2::mod_headers"
chef.add_recipe "apache2_vhosts"
#chef.add_recipe "composer"
chef.json = {
:mysql => {
:server_root_password => "passw0rd",
:server_repl_password => "passw0rd",
:server_debian_password => "passw0rd"
},
:apache2 => {
:keepaliverequests => 100,
:keepalivetimeout => 5,
:listen_ports => ["80", "443"]
},
:php => {
:version => "5.3.10"
}
#,
#:postgresql => {
# :version => "9.1",
# :hba => [
# { :method => "trust", :address => "0.0.0.0/0" },
# { :method => "trust", :address => "::1/0" },
# ],
# :password => {
# :postgres => "passw0rd"
# }
#}
}
end
end
end
|
class TourDataController < ApplicationController
before_filter :set_page
before_filter :set_tour_data
protected
def set_page
@page = Page.where(:handle => 'tour-data').first
end
def set_tour_data
@tour_data = TourDatum.last(10)
end
end
|
shared_examples 'an event decorator' do
it 'has a header' do
decorator.header.should be
end
it 'has an enumerable body' do
expect(decorator.body).to respond_to(:each)
end
end
|
class User < ActiveRecord::Base
has_many :meetupsearches
has_many :receipients, :through => :meetupsearches
has_many :inverse_meetupsearches, :class_name => "meetup_searches", :friend_key => "receipient_id"
has_many :inverse_receivers, :through => :inverse_meetupsearches, :source => :user
has_many :meetings
has_many :receivers, :through => :meetings
has_many :inverse_meetings, :class_name => "Meeting", :foreign_key => "receiver_id"
has_many :inverse_receivers, :through => :inverse_meetings, :source => :user
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_attached_file :image, :styles => { small: "64x64", med: "100x100", large: "200x200" }, :default_url=>"robot.png"
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:facebook, :google_oauth2]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.firstname = auth.info.first_name
user.lastname = auth.info.last_name
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.image = auth.info.image
end
end
end
|
require "spec_helper"
module SftpListen
describe Configuration do
let(:config) { SftpListen::Configuration.new }
describe "#initialize" do
it "sets the default user_name" do
expect(config.user_name).to eql("")
end
it "sets the default password" do
expect(config.password).to eql("")
end
it "sets the default port" do
expect(config.port).to eql(22)
end
it "sets the default directories" do
expect(config.directories).to eql(["inbound", "outbound"])
end
it "sets the default handler klass" do
expect(config.handler_klass).to eql(nil)
end
end
end
end
|
require 'pry'
class Api::SectionsController < ApplicationController
def index
@sections = Section.all
render json: @sections
end
def create
# binding.pry
@section = Section.new(section_params)
if @section.save
render json: @section
else
render json: { errors: @section.errors, status: :unprocessable_entity }
end
end
def update
@section = Section.find(params[:id])
# section.update(name: params[:name], color: params[:color])
if @section.update(section_params)
render json: @section
else
render json: { errors: @section.errors, status: :unprocessable_entity }
end
end
def destroy
# binding.pry
Section.find(params[:id]).destroy
render json: { message: 'Section deleted' }
end
private
def section_params
# binding.pry
params.require(:section).permit(:title, :color, :collapse, :kind)
end
end
|
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.3'
gem 'bootsnap', '>= 1.1.0', require: false
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0.7'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 4.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails', '>= 4.0.4'
gem 'active_model_serializers', '~> 0.10.9'
# Utilize the bootstrap frontend framework
gem 'bootstrap-sass'
gem 'bootstrap-sass-extras'
gem 'autoprefixer-rails'
gem 'bootswatch-rails'
# Markdown editor and rendering
gem 'rails-bootstrap-markdown'
gem 'redcarpet', '>= 3.2.3'
# Utilize font-awesome iconogrphy set
gem 'font-awesome-sass', '~> 5.9.0'
# Devise for user authentication
gem 'devise', '~> 4.6.2'
gem 'doorkeeper', '~> 5.1.0'
gem 'rack-cors', :require => 'rack/cors'
gem 'pundit'
# Exporting resumes to PDF
gem 'wicked_pdf', '~> 1.4'
# because sometimes you need a NULL
gem 'nilify_blanks'
# nice slugged URLs
gem 'friendly_id', '~> 5.2.5'
# Multi-tenancy
gem 'acts_as_tenant'
# Carrierwave for handling uploads to S3
gem 'carrierwave'
gem 'carrierwave_backgrounder'
gem 'mini_magick'
# queues are cool
gem 'hiredis'
gem 'redis-namespace'
gem 'sidekiq', '< 6'
gem 'sidekiq-failures'
gem 'sinatra', '~> 2.0.4', :require => nil # for sidekiq web UI
# pagination
gem 'kaminari'
gem 'pager_api', '~> 0.3.2'
gem 'unicorn'
gem 'thor'
group :development do
gem 'binding_of_caller'
gem 'better_errors'
gem 'listen', '~> 3.1.5'
end
group :production do
gem 'fog-aws', '~> 3.5'
end
group :development, :test do
gem 'rspec-rails', '~> 3.8'
gem 'capybara'
gem 'selenium-webdriver'
gem 'database_cleaner'
gem 'factory_bot_rails'
gem 'faker'
gem 'fuubar'
gem 'pry-rails'
gem 'pry-byebug'
gem 'pundit-matchers', '~> 1.6.0'
end
|
require_relative 'regular_movie'
module VideoStore
class ChildrensMovie < RegularMovie
def charge(days_rented)
return 1.5 if days_rented <= 3
1.5 + (days_rented - 3) * 1.5
end
end
end
|
describe Rallio do
describe '.application_id=' do
it 'sets @application_id' do
Rallio.application_id = 'foobar'
expect(Rallio.instance_variable_get(:@application_id)).to eq 'foobar'
end
end
describe '.application_id' do
it 'returns the value set via .application_id=' do
Rallio.application_id = 'foobar'
expect(Rallio.application_id).to eq 'foobar'
end
end
describe '.application_secret=' do
it 'sets @application_secret' do
Rallio.application_secret = 'foobar'
expect(Rallio.instance_variable_get(:@application_secret)).to eq 'foobar'
end
end
describe '.application_secret' do
it 'returns the value set via .application_secret=' do
Rallio.application_secret= 'foobar'
expect(Rallio.application_secret).to eq 'foobar'
end
end
end
|
require_relative 'p05_hash_map'
def can_string_be_palindrome?(string)
hsh = HashMap.new
arr = string.chars
arr.each do |el|
if hsh[el]
hsh[el] += 1
else
hsh[el] = 0
end
end
count = 0
hsh.each do |k, v|
if v % 2 == 0
count += 1
end
end
if count == hsh.count
return true
else
return false
end
end
|
require 'spec_helper'
describe 'Authentication for App API' do
it 'disallows connection attempts when no SSL_CLIENT_VERIFY env var is set' do
get '/api/app/ping', {}, {}
response.status.should eq(401)
end
it 'disallows connection attempts when the client SSL cert was not verified' do
get '/api/app/ping', {}, { 'SSL_CLIENT_VERIFY' => 'NONE' }
response.status.should eq(401)
end
it 'authenticates when a client SSL cert was verified succesfully' do
get '/api/app/ping', {}, { 'SSL_CLIENT_VERIFY' => 'SUCCESS' }
response.status.should eq(200)
end
end
|
class SchedulerGame
class States
class Game < CyberarmEngine::GuiState
KONAMI_CODE = [
Gosu::KB_UP,
Gosu::KB_UP,
Gosu::KB_DOWN,
Gosu::KB_DOWN,
Gosu::KB_LEFT,
Gosu::KB_RIGHT,
Gosu::KB_LEFT,
Gosu::KB_RIGHT,
Gosu::KB_B,
Gosu::KB_A,
]
attr_reader :game_time
def setup
window.show_cursor = true
@map = Map.new(file: "#{GAME_ROOT_PATH}/media/maps/1.dat")
@key_history = Array.new(KONAMI_CODE.size, 0)
@key_history_index = 0
@font = Gosu::Font.new(26)
@clock_font = Gosu::Font.new(48)
@game_time = 0.0
@game_clock = 3.0 * 60.0
@game_started = false
s = get_song("#{GAME_ROOT_PATH}/media/music/oga_cynicmusic_awake10_megaWall.mp3")
s.play(true)
end
def draw
fill(0x88_444444)
@map.draw
@map.paths.each(&:draw)
@clock_font.draw_text(format_clock, @map.width + 32, 32, 0)
@font.draw_text("#{remaining_travellers} of #{@map.travellers.size} Travellers remaining", @map.width + 32, 80, 0)
end
def update
@map.update
add_to_path if @building_path
check_for_win
check_for_lose
@game_time += window.dt if @game_started
end
def button_down(id)
super
@game_started = true
# TODO: Track mouse move while button down to create path to NEED #
construct_path if id == Gosu::MS_LEFT
@key_history[@key_history_index] = id
push_state(States::Pause) if id == Gosu::KB_ESCAPE
if @key_history == KONAMI_CODE
window.close
puts "You cheated! [TODO: Maybe do something fun?]"
end
@key_history_index += 1
if @key_history_index > @key_history.size - 1
@key_history_index = 0
@key_history = Array.new(@key_history.size, 0)
end
end
def button_up(id)
super
finish_path if id == Gosu::MS_LEFT
end
def construct_path
node = @map.mouse_over(window.mouse_x, window.mouse_y)
return unless node_neighbor_is_zone?(node)
@building_path = true
@map.paths << Path.new(map: @map, color_index: Path.next_color)
end
def add_to_path
node = @map.mouse_over(window.mouse_x, window.mouse_y)
@map.paths.last.nodes << node if node != @map.paths.last&.nodes&.detect { |n| n == node } &&
node_is_straight?(node, @map.paths.last&.nodes&.last) &&
node_is_neighbor?(node, @map.paths.last&.nodes&.last) &&
node.type == :floor
@map.paths.last.externally_valid = path_valid?(@map.paths.last)
end
def finish_path
@building_path = false
unless @map.paths.last&.valid? &&
node_neighbor_is_zone?(@map.paths.last&.nodes&.last) &&
node_neighbor_is_zone?(@map.paths.last&.nodes&.first) != node_neighbor_is_zone?(@map.paths.last&.nodes&.last)
@map.paths.delete(@map.paths.last)
else
@map.paths.last.building = false
assign_path(@map.paths.last)
end
end
def path_valid?(path_a)
@map.paths.reject { |o| o == path_a }.each do |path_b|
return false if path_a.nodes.any? { |n| path_b.nodes.include?(n) }
end
true
end
def assign_path(path)
zone = node_neighbor_is_zone?(path.nodes.first)
goal = node_neighbor_is_zone?(path.nodes.last)
travellers = @map.travellers.select { |t| t.path.nil? && t.zone == zone && t.goal == goal }
if travellers.size.positive?
travellers.each { |t| t.path = path }
else
@map.paths.delete(path)
end
end
def node_is_straight?(a, b)
return true if b.nil?
norm = (a.position - b.position).normalized
# Round to 1 decimal place to correct for floating point error
norm.x.round(1).abs == 1.0 && norm.y.round(1).abs == 0.0 ||
norm.x.round(1).abs == 0.0 && norm.y.round(1).abs == 1.0
end
def node_is_neighbor?(a, b)
return true if b.nil?
a.position.distance(b.position) <= 1.0
end
def node_neighbor_is_zone?(node)
return false unless node
# UP
up = @map.get_zone(node.position.x, node.position.y - 1)
return up if up
# DOWN
down = @map.get_zone(node.position.x, node.position.y + 1)
return down if down
# LEFT
left = @map.get_zone(node.position.x - 1, node.position.y)
return left if left
# RIGHT
right = @map.get_zone(node.position.x + 1, node.position.y)
return right if right
false
end
def remaining_travellers
@map.travellers.size - (@map.travellers.size - @map.zones.detect { |z| z.type == :entry_door }.occupancy)
end
def format_clock
time = (@game_clock - @game_time).clamp(0.0, @game_clock)
minutes = (time / 60.0) % 60.0
seconds = time % 60.0
"#{minutes.floor.to_s.rjust(2, '0')}:#{seconds.floor.to_s.rjust(2, '0')}"
end
def check_for_win
if @map.zones.detect { |z| z.type == :entry_door }.occupancy.zero? &&
@map.paths.size.zero? &&
@game_time <= @game_clock
push_state(States::GameWon, game_time: @game_time, map: @map)
end
end
def check_for_lose
if @game_time > @game_clock
push_state(States::GameLost, game_time: @game_time, map: @map)
end
end
end
end
end
|
#NOTE these records are present in the central database
#and are used for translating the domain names
class Domain
include Mongoid::Document
field :_id, type: String #domain for lookup
field :subdomain
end
|
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require 'fileutils'
require 'yaml'
include HP::Cloud
describe "AuthCaches default directory" do
it "should assemble properly" do
AuthCache.new.directory.should eq(ENV['HOME'] + '/.hpcloud/accounts/.cache/')
end
end
describe "AuthCaches getting credentials" do
before(:all) do
AuthCacheHelper.use_tmp()
end
context "when nothing exists" do
it "should provide have nothing" do
authcaches = AuthCache.new()
authcaches.read({}).should be_nil
end
end
context "when something exists" do
it "should provide credentials" do
something = { :hp_access_key => 'a', :hp_tenant_id => 'b' }
somethingelse = { :hp_access_key => 'c', :hp_tenant_id => 'd' }
authcaches = AuthCache.new()
creds = { :a => 'a', :b => 'b' }
authcaches.write(something, creds)
authcaches.write(somethingelse, nil)
authcaches.read(somethingelse).should be_nil
authcaches.read(something).should eq(creds)
authcaches = AuthCache.new()
authcaches.read(something).should eq(creds)
authcaches.read(somethingelse).should be_nil
end
end
context "when something else" do
it "should provide credentials" do
something = { :hp_access_key => 'a', :hp_tenant_id => 'b' }
authcaches = AuthCache.new()
authcaches.write(something, {:a => 'block'})
authcaches.read(something)[:a].should eq('block')
end
end
context "when removing" do
it "should remove credentials" do
something = { :hp_access_key => 'a', :hp_tenant_id => 'b' }
another = { :hp_access_key => 'c', :hp_tenant_id => 'd' }
onemore = { :hp_access_key => 'e', :hp_tenant_id => 'f' }
yetanother = { :hp_access_key => 'g', :hp_tenant_id => 'h' }
authcaches = AuthCache.new()
authcaches.write(something, {:a => 'block'})
authcaches.write(another, {:a => 'cdn'})
authcaches.write(onemore, {:a => 'compute'})
authcaches.write(yetanother, {:a => 'storage'})
authcaches = AuthCache.new()
authcaches.read(something)[:a].should eq('block')
authcaches.read(another)[:a].should eq('cdn')
authcaches.read(onemore)[:a].should eq('compute')
authcaches.read(yetanother)[:a].should eq('storage')
authcaches.remove(yetanother)
authcaches = AuthCache.new()
authcaches.read(something)[:a].should eq('block')
authcaches.read(another)[:a].should eq('cdn')
authcaches.read(onemore)[:a].should eq('compute')
authcaches.read(yetanother).should be_nil
authcaches.remove
authcaches = AuthCache.new()
authcaches.read(something).should be_nil
authcaches.read(another).should be_nil
authcaches.read(onemore).should be_nil
authcaches.read(yetanother).should be_nil
end
end
context "when something else" do
it "should provide credentials" do
something = { :hp_access_key => 'a', :hp_tenant_id => 'b' }
bogus = { :hp_access_key => 'c', :hp_tenant_id => 'd' }
authcaches = AuthCache.new()
authcaches.write(something, {:service_catalog => {:DNS =>
{:"region-a.geo-1" => "https://region-a.geo-1.dns.hpcloudsvc.com/v1/",
:"region-b.geo-1" => "https://region-b.geo-1.dns.hpcloudsvc.com/v1/"}}})
authcaches.default_zone(something, 'DNS').should eq('region-a.geo-1')
authcaches.default_zone(bogus, 'DNS').should be_nil
authcaches.default_zone(something, 'bogus').should be_nil
end
end
context "create file name" do
it "should make name" do
opts = { :hp_access_key => 'a', :hp_tenant_id => 'b' }
authcaches = AuthCache.new()
authcaches.get_name(opts).should eq("a:b")
end
end
after(:all) {reset_all()}
end
|
class Brewery < ApplicationRecord
# dependent destroy should destroy logs on brewery distroy
has_many :logs , dependent: :destroy
has_many :users, through: :logs
end
|
class UserController
attr_reader :type
def initialize(special_meanings, privileges, user_type_inheritance_inherit_previous)
@pipe, @user, @special_meanings = Pipe.new, Main::Users.new, special_meanings
identify_from_session
@allowed_actions_by_data_object_name_and_condition = {}
user_type_inheritance_inherit_previous.each do |user_type|
privileges[user_type].each do |data_object_name, actions_by_condition|
@allowed_actions_by_data_object_name_and_condition[data_object_name] ||= {}
@allowed_actions_by_data_object_name_and_condition[data_object_name].
merge! actions_by_condition
end
break if user_type == @type
end
end
def get_filters_if_access(action, data_object_name)
general_action = get_general_action action
return false unless chance_to_access? general_action, data_object_name
conditions_by_condition_name = {}
@allowed_actions_by_data_object_name_and_condition[data_object_name]
.each do |condition_name, general_actions|
if general_actions.include? general_action
conditions_by_condition_name[condition_name] = case condition_name
when :all
{}
when :buyer_own
{buyer_id: @id}
when :seller_own
{seller_id: @id}
when :buyer_own_while_ordering
{buyer_id: @id, status: :ordering}
when :own
if data_object_name == :user
{id: @id}
else
{user_id: @id}
end
when :published
{published: true}
else
false
end
end
end
if conditions_by_condition_name.include? :all
conditions_by_condition_name[:all]
elsif conditions_by_condition_name.one? { |name, condition| condition }
conditions_by_condition_name.each_value { |condition| return condition if condition }
elsif conditions_by_condition_name.none? { |name, condition| condition }
false
else
or_conditions = []
conditions_by_condition_name.each_value do |condition|
or_conditions << condition if condition
end
or_conditions
end
end
def login
username_and_password = @pipe.get :params, names: [:username, :password]
array_of_one_user_hash = @pipe.get :runtime_table_hashes, {
data_obj_name: @user.data_obj_name,
attributes: @user.attributes_of(:for_login),
username: username_and_password[:username],
password: username_and_password[:password],
limit: 1,
}
user_hash = array_of_one_user_hash.first
unless user_hash.empty?
save_in_user user_hash
@pipe.put :successful_authentication_in_session, {
id: @id,
type: @type,
}
true
else
false
end
end
private
def identify_from_session
user_hash = @pipe.get :successful_authentication_in_session
if user_hash
save_in_user user_hash
true
else
@type = :visitor
false
end
end
def save_in_user(user_hash)
@user.set user_hash
@type = @user.type
@id = @user.id
end
def chance_to_access?(general_action, data_object_name)
unless @allowed_actions_by_data_object_name_and_condition.include? data_object_name
return false
end
@allowed_actions_by_data_object_name_and_condition[data_object_name]
.any? { |condition, general_actions| general_actions.include? general_action }
end
def get_general_action(action)
@special_meanings.each do |general_action, actions|
return general_action if actions.include? action
end
action
end
end
|
class Lesson < ActiveRecord::Base
belongs_to :learning_day
belongs_to :course
has_one :home_task, :dependent => :destroy
default_scope :order=>"strftime('%H:%M', start_time)"
def hometask
if self.home_task
content = self.home_task.content.gsub("\n","<br/>")
else
nil
end
end
def starttime
self.start_time.strftime("%H:%M")
end
def endtime
self.end_time.strftime("%H:%M")
end
end
|
require_relative '../../../games/8puzzle/board'
require 'test/unit'
require 'set'
class TestBoard < Test::Unit::TestCase
UNSOLVABLE_BOARD = {
T1: 1, T2: 2, T3: 3,
T4: 4, T5: 5, T6: 6,
T7: 8, T8: 7, T9: 0
}
EASY_GRID = {
T1: 1, T2: 2, T3: 3,
T4: 0, T5: 4, T6: 6,
T7: 7, T8: 5, T9: 8
}
def setup
@easy_board = EightPuzzle::Board.new(EASY_GRID)
end
def test_hash
board1 = EightPuzzle::Board.generate_random
board2 = EightPuzzle::Board.generate_random
assert_not_equal(board1.hash, board2.hash)
board3 = EightPuzzle::Board.new(EASY_GRID)
board4 = EightPuzzle::Board.new(EASY_GRID)
assert_equal(board3.hash, board4.hash)
end
def test_eql
random_board = EightPuzzle::Board.generate_random
assert_equal(false, random_board.eql?(@easy_board))
assert_equal(false, @easy_board.eql?(random_board))
assert_equal(false, random_board == @easy_board)
assert_equal(false, @easy_board == random_board)
assert_equal(true, random_board.eql?(random_board))
assert_equal(true, random_board == random_board)
end
def test_in_set
set = Set.new
board1 = EightPuzzle::Board.generate_random
set.add(board1)
set.add(board1)
assert_equal(1, set.size)
assert_equal(true, set.include?(board1))
set.add(@easy_board)
assert_equal(2, set.size)
end
def test_finished?
finished_board = EightPuzzle::Board.new(EightPuzzle::Board::WINNING_GRID)
assert_equal(false, @easy_board.finished?)
assert_equal(true, finished_board.finished?)
end
def test_unsolvable
unsolvable_board = EightPuzzle::Board.new(UNSOLVABLE_BOARD)
assert_raise { unsolvable_board.solve }
end
def test_solve
solved_board = @easy_board.solve
assert_equal(true, solved_board.finished?)
end
end
|
require "test_helper"
class UseVanityControllerTest < ActionController::TestCase
tests UseVanityController
def setup
super
metric :sugar_high
new_ab_test :pie_or_cake do
metrics :sugar_high
alternatives :pie, :cake
default :pie
end
# Class eval this instead of including in the controller to delay
# execution until the request exists in the context of the test
UseVanityController.class_eval do
use_vanity :current_user
end
# Rails 3 configuration for cookies
::Rails.application.config.session_options[:domain] = '.foo.bar' if ::Rails.respond_to?(:application)
end
def teardown
super
end
def test_render_js_for_tests
Vanity.playground.use_js!
get :js
assert_match(/script.*v=pie_or_cake=.*script/m, @response.body)
end
def test_view_helper_ab_test_js_for_tests
Vanity.playground.use_js!
get :view_helper_ab_test_js
assert_match(/script.*v=pie_or_cake=.*script/m, @response.body)
end
def test_global_ab_test_js_for_tests
Vanity.playground.use_js!
get :global_ab_test_js
assert_match(/script.*v=pie_or_cake=.*script/m, @response.body)
end
def test_render_model_js_for_tests
Vanity.playground.use_js!
get :model_js
assert_match(/script.*v=pie_or_cake=.*script/m, @response.body)
end
def test_chooses_sets_alternatives_for_rails_tests
experiment(:pie_or_cake).chooses(:pie)
get :index
assert_equal 'pie', @response.body
experiment(:pie_or_cake).chooses(:cake)
get :index
assert_equal 'cake', @response.body
end
def test_adds_participant_to_experiment
get :index
assert_equal 1, experiment(:pie_or_cake).alternatives.map(&:participants).sum
end
def test_does_not_add_invalid_participant_to_experiment
Vanity.playground.use_js!
@request.user_agent = "Googlebot/2.1 ( http://www.google.com/bot.html)"
get :index
assert_equal 0, experiment(:pie_or_cake).alternatives.map(&:participants).sum
end
def test_vanity_cookie_is_persistent
get :index
cookie = @response["Set-Cookie"].to_s
assert_match(/vanity_id=[a-f0-9]{32};/, cookie)
expires = cookie[/expires=(.*)(;|$)/, 1]
assert expires
assert_in_delta Time.parse(expires), Time.now + (20 * 365 * 24 * 60 * 60), 1.day
end
def test_vanity_cookie_default_id
get :index
assert cookies["vanity_id"] =~ /^[a-f0-9]{32}$/
end
def test_vanity_cookie_retains_id
@request.cookies["vanity_id"] = "from_last_time"
get :index
assert_equal "from_last_time", cookies["vanity_id"]
end
def test_vanity_cookie_uses_configuration
Vanity.configuration.cookie_name = "new_id"
get :index
assert cookies["new_id"] =~ /^[a-f0-9]{32}$/
end
def test_vanity_identity_set_from_cookie
@request.cookies["vanity_id"] = "from_last_time"
get :index
assert_equal "from_last_time", @controller.send(:vanity_identity)
end
def test_vanity_identity_set_from_user
@controller.current_user = stub("user", id: "user_id")
get :index
assert_equal "user_id", @controller.send(:vanity_identity)
end
def test_vanity_identity_with_null_user_falls_back_to_cookie
@controller.current_user = stub("user", id: nil)
get :index
assert cookies["vanity_id"] =~ /^[a-f0-9]{32}$/
end
def test_vanity_identity_with_no_user_model
UseVanityController.class_eval do
use_vanity nil
end
@controller.current_user = Object.new
get :index
assert cookies["vanity_id"] =~ /^[a-f0-9]{32}$/
end
def test_vanity_identity_set_with_block
UseVanityController.class_eval do
attr_accessor :project_id
use_vanity { |controller| controller.project_id }
end
@controller.project_id = "576"
get :index
assert_equal "576", @controller.send(:vanity_identity)
end
def test_vanity_identity_set_with_identity_paramater
params = { _identity: "id_from_params" }
get :index, params
assert_equal "id_from_params", @controller.send(:vanity_identity)
end
def test_vanity_identity_prefers_block_over_symbol
UseVanityController.class_eval do
attr_accessor :project_id # rubocop:todo Lint/DuplicateMethods
use_vanity(:current_user) { |controller| controller.project_id }
end
@controller.project_id = "576"
@controller.current_user = stub(id: "user_id")
get :index
assert_equal "576", @controller.send(:vanity_identity)
end
def test_vanity_identity_prefers_parameter_over_cookie
@request.cookies['vanity_id'] = "old_id"
params = { _identity: "id_from_params" }
get :index, params
assert_equal "id_from_params", @controller.send(:vanity_identity)
assert cookies['vanity_id'], "id_from_params"
end
def test_vanity_identity_prefers_cookie_over_object
@request.cookies['vanity_id'] = "from_last_time"
@controller.current_user = stub(id: "user_id")
get :index
assert_equal "from_last_time", @controller.send(:vanity_identity)
end
# query parameter filter
def test_redirects_and_loses_vanity_query_parameter
params = { foo: "bar", _vanity: "567" }
get :index, params
assert_redirected_to "/use_vanity?foo=bar"
end
def test_sets_choices_from_vanity_query_parameter
first = experiment(:pie_or_cake).alternatives.first
fingerprint = experiment(:pie_or_cake).fingerprint(first)
10.times do
@controller = nil
setup_controller_request_and_response
params = { _vanity: fingerprint }
get :index, params
assert_equal experiment(:pie_or_cake).choose, experiment(:pie_or_cake).alternatives.first
assert experiment(:pie_or_cake).showing?(first)
end
end
def test_does_nothing_with_vanity_query_parameter_for_posts
experiment(:pie_or_cake).chooses(experiment(:pie_or_cake).alternatives.last.value)
first = experiment(:pie_or_cake).alternatives.first
fingerprint = experiment(:pie_or_cake).fingerprint(first)
params = { foo: "bar", _vanity: fingerprint }
post :index, params
assert_response :success
assert !experiment(:pie_or_cake).showing?(first)
end
def test_track_param_tracks_a_metric
params = { _identity: "123", _track: "sugar_high" }
get :index, params
assert_equal experiment(:pie_or_cake).alternatives[0].converted, 1
end
def test_cookie_domain_from_rails_configuration
get :index
assert_match(/domain=.foo.bar/, @response["Set-Cookie"]) if ::Rails.respond_to?(:application)
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :validatable
has_many :tweets, dependent: :destroy
has_many :videos, dependent: :destroy
has_many :tracks, dependent: :destroy
has_many :matches, dependent: :destroy
after_create do
validate_twitter_username
validate_youtube_username
validate_soundcloud_username
end
def validate_twitter_username
begin
TWITTER.user(twitter_username)
rescue
self.update(twitter_username: nil)
puts "INVALID TWITTER USERNAME"
false
else
puts "TWITTER USERNAME VALIDATED"
true
end
end
def validate_youtube_username
begin
YOUTUBE.activity(youtube_username)
rescue
self.update(youtube_username: nil)
puts "INVALID YOUTUBE USERNAME"
false
else
puts "YOUTUBE USERNAME VALIDATED"
true
end
end
def validate_soundcloud_username
begin
SOUNDCLOUD.get("/users/#{soundcloud_username}")
rescue
self.update(soundcloud_username: nil)
puts "INVALID SOUNDCLOUD USERNAME"
false
else
puts "SOUNDCLOUD USERNAME VALIDATED"
true
end
end
def load_profile_img
case
when twitter_username != "" then self.update(image_url: TWITTER.user(twitter_username).attrs[:profile_image_url_https])
when youtube_username != "" then self.update(image_url: YOUTUBE.profile(youtube_username).avatar)
when soundcloud_username != "" then self.update(image_url: SOUNDCLOUD.get("/users/#{soundcloud_username}"))
else self.update(image_url: "https://pbs.twimg.com/profile_images/3253620646/8031eb423b8d91cca462af4825cdfdb2.jpeg")
end
puts "PROFILE IMAGE UPLOADED"
end
def load_tweets
tweets.destroy_all
unless twitter_username.nil? || twitter_username.empty?
tweet_data = TWITTER.user_timeline(twitter_username, :count => 5)
tweet_data.each do |tweet_object|
tweet = tweets.create(content: tweet_object.text)
tweet_object.hashtags.each do |hashtag_object|
if hashtag_object.text
tweet.hashtags.create(text: hashtag_object.text)
end
end
end
end
end
def load_videos
videos.destroy_all
unless youtube_username.nil? || youtube_username.empty?
activity = YOUTUBE.activity(youtube_username)
video_ids = activity.first(5).map { |action| action.video_id }
video_data = video_ids.map { |video_id| YOUTUBE.video_by(video_id) }
video_data.each do |video_object|
url = video_object.player_url
title = video_object.title
description = video_object.description
label = video_object.categories.map { |category| category.label }.first
author = video_object.author.name
video = videos.create(url: url, title: title, description: description, label: label, author: author)
end
end
end
def load_tracks
tracks.destroy_all
unless soundcloud_username.nil? || soundcloud_username.empty?
track_data = SOUNDCLOUD.get("/users/#{soundcloud_username}/favorites", :limit => 5)
track_data.each do |track_object|
image_url = track_object.artwork_url
description = track_object.description
genre = track_object.genre
title = track_object.title
track_url = track_object.permalink_url
author = track_object.user.username
tag_string = track_object.tag_list
strings = tag_string.scan(/["][^"]+["]/)
strings.each do |string|
tag_string.gsub!(string,"")
string.gsub!("\"","")
end
words = tag_string.split(" ")
tag_array = words.concat(strings)
track = tracks.create(image_url: image_url, description: description, genre: genre, track_url: track_url, title: title, author: author)
tag_array.first(5).each do |tag|
track.tags.create(name: tag)
end
end
end
end
def load_match_data(raw_match_data)
matches.destroy_all
raw_match_data.each do |match|
matches.create(match_user_id: match["user_id"], twitter_percent: match["twitter_percent"], youtube_percent: match["youtube_percent"], soundcloud_percent: match["soundcloud_percent"], overall_percent: match["overall_percent"])
end
end
def match_data_formatted
matches.order(overall_percent: :desc).map do |match|
match.formatted
end
end
def personal_info
{user_id: id, name: name, blurb: blurb, image_url: image_url, tweets: tweets.first(5), videos: videos.first(5), tracks: tracks.first(5)}
end
def self.data(current_user)
current_user_tweet_data = current_user.tweets.map do |tweet|
hashtags = tweet.hashtags.map do |hashtag|
hashtag.text
end
{"content" => tweet.content, "hashtags" => hashtags}
end
current_user_video_data = current_user.videos.map do |video|
{"title" => video.title, "description" => video.description, "label" => video.label, "author" => video.author}
end
current_user_track_data = current_user.tracks.map do |track|
tags = track.tags.map do |tag|
tag.name
end
{"title" => track.title, "author" => track.author, "description" => track.description, "genre" => track.genre, "track_url" => track.track_url, "image_url" => track.image_url, "tags" => tags}
end
current_user_data = {"user_id" => current_user.id, "tweets" => current_user_tweet_data, "videos" => current_user_video_data, "tracks" => current_user_track_data}
match_data = User.where.not(id: current_user.id).map do |user|
user_tweet_data = user.tweets.map do |tweet|
hashtags = tweet.hashtags.map do |hashtag|
hashtag.text
end
{"content" => tweet.content, "hashtags" => hashtags}
end
user_video_data = user.videos.map do |video|
{"title" => video.title, "description" => video.description, "label" => video.label, "author" => video.author}
end
user_track_data = user.tracks.map do |track|
tags = track.tags.map do |tag|
tag.name
end
{"title" => track.title, "author" => track.author, "description" => track.description, "genre" => track.genre, "track_url" => track.track_url, "image_url" => track.image_url, "tags" => tags}
end
{"user_id" => user.id, "tweets" => user_tweet_data, "videos" => user_video_data, "tracks" => user_track_data}
end
{"user" => current_user_data, "matches" => match_data}
end
def self.drunk_tye_matcher(current_user)
User.where.not(id: current_user.id).map do |user|
twitter_percent = rand(0.0..1.0)
youtube_percent = rand(0.0..1.0)
soundcloud_percent = rand(0.0..1.0)
overall_percent = (twitter_percent + youtube_percent + soundcloud_percent) / 3.0
{"user_id" => user.id, "twitter_percent" => twitter_percent, "youtube_percent" => youtube_percent, "soundcloud_percent" => soundcloud_percent, "overall_percent" => overall_percent}
end
end
def self.drunk_tye_processor(raw_match_data)
raw_match_data.map do |match|
user_id = match["user_id"]
twitter_percent = "#{(match["twitter_percent"]*100).to_i}%"
youtube_percent = "#{(match["youtube_percent"]*100).to_i}%"
soundcloud_percent = "#{(match["soundcloud_percent"]*100).to_i}%"
overall_percent = "#{(match["overall_percent"]*100).to_i}%"
user = User.find(user_id)
{"id" => user.id, "name" => user.name, "blurb" => user.blurb, "image_url" => user.image_url, "twitter_percent" => twitter_percent, "youtube_percent" => youtube_percent, "soundcloud_percent" => soundcloud_percent, "overall_percent" => overall_percent }
end
end
end
|
class Person < ActiveRecord::Base
scope :teenagers, where('age < 20 AND age > 12')
scope :by_name, order(:name)
end
|
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network "public_network"
config.vm.provision "shell", inline: <<-SHELL
sudo apt-get update
sudo apt-get install -y libffi-dev libssl-dev gconf-service libgconf-2-4 libgtk2.0-0 fonts-liberation libappindicator1 xdg-utils libpango1.0-0 python3-pip libxml2-dev python3-lxml libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk unzip xvfb libnss3-dev
sudo apt-get -f install
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb >/dev/null 2>&1
sudo dpkg -i google-chrome-stable_current_amd64.deb
sudo pip3 install python-docx selenium Pillow nwdiag
sudo pip3 install paramiko --upgrade
sudo pip3 install requests --upgrade
wget "http://chromedriver.storage.googleapis.com/$(curl -s "http://chromedriver.storage.googleapis.com/LATEST_RELEASE")/chromedriver_linux64.zip" >/dev/null 2>&1
unzip chromedriver_linux64.zip
sudo cp chromedriver /usr/local/bin/
sudo cp /vagrant/xvfb /etc/init.d/
sudo chmod +x /etc/init.d/xvfb
sudo update-rc.d xvfb defaults
sudo service xvfb start
echo "export DISPLAY=:1" >> /home/vagrant/.bashrc
SHELL
end
|
class FontInconsolataGForPowerline < Formula
head "https://github.com/powerline/fonts.git", branch: "master", only_path: "Inconsolata-g"
desc "Inconsolata-g for Powerline"
homepage "https://github.com/powerline/fonts/tree/master/Inconsolata-g"
def install
(share/"fonts").install "Inconsolata-g for Powerline.otf"
end
test do
end
end
|
class AddCompanyIdToFinding < ActiveRecord::Migration[5.0]
def change
add_reference :findings, :company, foreign_key: true
end
end
|
# == Schema Information
#
# Table name: countries
#
# id :integer not null, primary key
# name :string(255) default(""), not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Country < ActiveRecord::Base
has_many :brigades, dependent: :destroy
attr_accessible :name
validates :name, presence: true,
uniqueness: true,
length: (3..100)
end
|
require 'rails_helper'
RSpec.describe Book, :category, :type => :model do
subject(:category) { create :category }
context 'association' do
it { should have_many :books }
end
context 'validation' do
it { should validate_presence_of(:name) }
it { should validate_length_of(:name).is_at_most(50) }
end
end |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :first_name, presence: true, uniqueness: { scope: :last_name }
validates :user_name, uniqueness: true
has_one :dashboard
has_many :item_listings, dependent: :destroy
has_many :stores, dependent: :destroy
has_many :funds, dependent: :destroy
end
|
Given(/^I am not logged in$/) do
visit logout_path
end
# ERROR MESSAGE
Then /^creation should fail with "(.*)"$/ do |msg|
steps %Q{
Then I should see "#{msg}"
}
end
Given(/^I am logged in on the "([^"]*) page$/) do |arg|
visit "/org"
click_link "Log in with GitHub"
visit "/org"
end
Then /^the field "(.*)" should be empty$/ do |field|
expect(find_field("#{field}").value).to be_empty
end
Then /^I should be on the "([^"]*) page$/ do |arg|
expect(visit arg)
end
Given /^the form is "blank"$/ do
visit creation_path
end
Given /^an app exists with the parameters: "(.*)"$/ do |parameters|
Params = parameters.split(“, “)
#Pending
#create the model with params
end |
#
# Cookbook:: sturdy_ssm_agent
# Recipe:: install
#
# Copyright:: 2017, Sturdy Networks
# Copyright:: 2017, Jonathan Serafini
#
# 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.
# Download the installer
# @since 0.1.0
remote_file 'amazon-ssm-agent' do
path node['ssm_agent']['package']['path']
source node['ssm_agent']['package']['url']
checksum node['ssm_agent']['package']['checksum']
mode 0644
end
# Install the package
# @since 0.1.0
package 'amazon-ssm-agent' do # ~FC109
source node['ssm_agent']['package']['path']
provider value_for_platform_family(
'rhel' => Chef::Provider::Package::Yum,
'suse' => Chef::Provider::Package::Zypper,
'amazon' => Chef::Provider::Package::Yum,
'debian' => Chef::Provider::Package::Dpkg,
'windows' => Chef::Provider::Package::Windows
)
end
# Ensure service state
# @since 0.1.0
service node['ssm_agent']['service']['name'] do
provider Chef::Provider::Service::Upstart if node['platform'].include? 'amazon'
action node['ssm_agent']['service']['actions']
end
|
class CreateTutorialWidget < ::RailsConnector::Migration
def up
create_obj_class(
name: 'TutorialWidget',
type: 'publication',
title: 'Tutorial widget',
attributes: [
{name: 'headline', type: 'string', title: 'Headline'},
{name: 'content', type: 'html', title: 'Content'},
{name: 'border', type: 'enum', title: 'Border', values: ['Yes', 'No']},
{name: 'partnerlinks', type: 'linklist', title: 'Partnerlinks'},
{name: 'datum', type: 'date', title: 'datum'},
],
preset_attributes: {},
mandatory_attributes: []
)
end
end
|
class Imovel < ApplicationRecord
belongs_to :proprietario
belongs_to :finalidade
has_many :categorias
end
|
class AddHotitemToSearch < ActiveRecord::Migration
def self.up
add_column :searches, :hotitem_id, :string
end
def self.down
remove_column :searches, :hotitem_id
end
end
|
module Kata
module Algorithms
def self.find_non_existing_smallest_integer_number(array)
return 1 if array.empty?
# expected worst-case time complexity is O(N);
# expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
existing = []
array.each do |element|
existing[element] = 1 unless element < 0
end
return 1 if existing.empty?
first_nil = existing[1..-1].find_index { |i| i.nil? }
if first_nil.nil?
existing.size
else
first_nil + 1
end
end
end
end
|
# Handles creating new sessions (loging in) and destroying sessions (logging out)
class SessionsController < ApplicationController
def create
user = User.authenticate(params[:email], params[:password]);
if user
session[:user_id] = user.id
redirect_to dashboard_path
else
flash.now[:alert] = 'Could not log you in. Please check your username and/or password.'
redirect_to root_url
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => 'Logged out!'
end
end |
class AddUrgencyToGsa18fProcurement < ActiveRecord::Migration
def change
add_column :gsa18f_procurements, :urgency, :string
end
end
|
require 'rails_helper'
RSpec.describe RoleCheck do
context "Verify App Modules & Permission Constants" do
it "Constants Permission should exists" do
expect(CAN_READ).to eq 1
expect(CAN_UPDATE).to eq 2
expect(CAN_CREATE).to eq 4
expect(CAN_DELETE).to eq 8
end
it "Constatns AppModules should exists" do
expect(Constants::APP_MODULES[0][:name]).to eq "Finance"
expect(Constants::APP_MODULES[1][:name]).to eq "Inventory"
expect(Constants::APP_MODULES[2][:name]).to eq "Cultivation"
expect(Constants::APP_MODULES[3][:name]).to eq "Issues"
end
end
context "Invalid Call Exceptions" do
it "should return exception Missing current user" do
expect { RoleCheck.call(nil, nil, nil) }.to raise_error(ArgumentError, 'Missing "current_user"')
end
it "should return exception Missing feature" do
expect { RoleCheck.call({ id: "1"}, nil, nil) }.to raise_error(ArgumentError, 'Missing "feature"')
end
it "should return exception Missing permissions" do
expect { RoleCheck.call({ id: "1" }, 1000, nil) }.to raise_error(ArgumentError, 'Missing "permissions"')
end
end
context "RoleCheck core logic" do
let!(:role) { create(:role, :with_permission_1010) }
let!(:current_user) {
res = create(:user)
res.roles = [role.id]
res
}
it "user can read feature 1010" do
cmd = RoleCheck.call(current_user, 1010, CAN_READ)
expect(cmd.result).to eq true
end
it "user can read feature 1020" do
cmd = RoleCheck.call(current_user, 1020, CAN_READ)
expect(cmd.result).to eq true
end
it "user can update feature 1020" do
cmd = RoleCheck.call(current_user, 1020, CAN_UPDATE)
expect(cmd.result).to eq true
end
it "user can create feature 1020" do
cmd = RoleCheck.call(current_user, 1020, CAN_CREATE)
expect(cmd.result).to eq true
end
it "user cannot delete feature 1020" do
cmd = RoleCheck.call(current_user, 1020, CAN_DELETE)
expect(cmd.result).to eq false
end
it "user cannot read feature 2000" do
cmd = RoleCheck.call(current_user, 2000, CAN_READ)
expect(cmd.result).to eq false
end
end
context "Super Admin" do
let!(:role) { create(:role, :super_admin) }
let!(:current_user) {
res = create(:user)
res.roles = [role.id]
res
}
it "can read feature 1010" do
cmd = RoleCheck.call(current_user, 1010, CAN_READ)
expect(cmd.result).to eq true
end
it "cannot delete feature 1020" do
cmd = RoleCheck.call(current_user, 1020, CAN_DELETE)
expect(cmd.result).to eq true
end
it "can create feature 2000" do
cmd = RoleCheck.call(current_user, 2000, CAN_READ)
expect(cmd.result).to eq true
end
end
end
|
class TokenSerializer < ApplicationSerializer
delegate :token, to: :object
set_id :token
end
|
require 'rubygems'
require 'bundler'
Bundler.setup
$:.unshift(File.join(File.dirname(__FILE__), '../../lib/client/lib'))
$:.unshift(File.dirname(__FILE__))
require 'mysql_helper'
require 'json/pure'
require 'singleton'
require 'spec'
require 'vmc_base'
require 'curb'
require 'pp'
# The integration test automation based on Cucumber uses the AppCloudHelper as a driver that takes care of
# of all interactions with AppCloud through the VCAP::BaseClient intermediary.
#
# Author:: A.B.Srinivasan
# Copyright:: Copyright (c) 2010 VMware Inc.
TEST_AUTOMATION_USER_ID = "tester@vcap.example.com"
TEST_AUTOMATION_PASSWORD = "tester"
SIMPLE_APP = "simple_app"
REDIS_LB_APP = "redis_lb_app"
ENV_TEST_APP = "env_test_app"
TINY_JAVA_APP = "tiny_java_app"
SIMPLE_DB_APP = "simple_db_app"
BROKEN_APP = "broken_app"
RAILS3_APP = "rails3_app"
JPA_APP = "jpa_app"
HIBERNATE_APP = "hibernate_app"
DBRAILS_APP = "dbrails_app"
DBRAILS_BROKEN_APP = "dbrails_broken_app"
GRAILS_APP = "grails_app"
ROO_APP = "roo_app"
SIMPLE_ERLANG_APP = "mochiweb_test"
SERVICE_TEST_APP = "service_test_app"
After do
# This used to delete the entire user, but that now require admin privs
# so it was removed.
AppCloudHelper.instance.cleanup
end
After("@creates_simple_app") do
AppCloudHelper.instance.delete_app_internal SIMPLE_APP
end
After("@creates_tiny_java_app") do
AppCloudHelper.instance.delete_app_internal TINY_JAVA_APP
end
After("@creates_simple_db_app") do
AppCloudHelper.instance.delete_app_internal SIMPLE_DB_APP
end
After("@creates_service_test_app") do
AppCloudHelper.instance.delete_app_internal SERVICE_TEST_APP
end
After("@creates_redis_lb_app") do
AppCloudHelper.instance.delete_app_internal REDIS_LB_APP
end
After("@creates_env_test_app") do
AppCloudHelper.instance.delete_app_internal ENV_TEST_APP
end
After("@creates_broken_app") do
AppCloudHelper.instance.delete_app_internal BROKEN_APP
end
After("@creates_rails3_app") do
AppCloudHelper.instance.delete_app_internal RAILS3_APP
end
After("@creates_jpa_app") do
AppCloudHelper.instance.delete_app_internal JPA_APP
end
After("@creates_hibernate_app") do
AppCloudHelper.instance.delete_app_internal HIBERNATE_APP
end
After("@creates_dbrails_app") do
AppCloudHelper.instance.delete_app_internal DBRAILS_APP
end
After("@creates_dbrails_broken_app") do
AppCloudHelper.instance.delete_app_internal DBRAILS_BROKEN_APP
end
After("@creates_grails_app") do
AppCloudHelper.instance.delete_app_internal GRAILS_APP
end
After("@creates_roo_app") do
AppCloudHelper.instance.delete_app_internal ROO_APP
end
After("@creates_mochiweb_app") do
AppCloudHelper.instance.delete_app_internal SIMPLE_ERLANG_APP
end
After("@provisions_service") do
AppCloudHelper.instance.unprovision_service
end
at_exit do
AppCloudHelper.instance.cleanup
end
['TERM', 'INT'].each { |s| trap(s) { AppCloudHelper.instance.cleanup; Process.exit! } }
class AppCloudHelper
include Singleton, MysqlServiceHelper
def initialize
@last_registered_user, @last_login_token = nil
# Go through router endpoint for CloudController
@target = ENV['VCAP_BVT_TARGET'] || 'vcap.me'
@registered_user = ENV['VCAP_BVT_USER']
@registered_user_passwd = ENV['VCAP_BVT_USER_PASSWD']
@base_uri = "http://api.#{@target}"
@droplets_uri = "#{@base_uri}/apps"
@resources_uri = "#{@base_uri}/resources"
@services_uri = "#{@base_uri}/services"
@configuration_uri = "#{@base_uri}/services/v1/configurations"
@binding_uri = "#{@base_uri}/services/v1/bindings"
@suggest_url = @target
puts "\n** VCAP_BVT_TARGET = '#{@target}' (set environment variable to override) **"
puts "** Running as user: '#{test_user}' (set environment variables VCAP_BVT_USER / VCAP_BVT_USER_PASSWD to override) **"
puts "** VCAP CloudController = '#{@base_uri}' **\n\n"
# Namespacing allows multiple tests to run in parallel.
# Deprecated, along with the load-test tasks.
# puts "** To run multiple tests in parallel, set environment variable VCAP_BVT_NS **"
@namespace = ENV['VCAP_BVT_NS'] || ''
puts "** Using namespace: '#{@namespace}' **\n\n" unless @namespace.empty?
config_file = File.join(File.dirname(__FILE__), 'testconfig.yml')
begin
@config = File.open(config_file) do |f|
YAML.load(f)
end
rescue => e
puts "Could not read configuration file: #{e}"
exit
end
load_mysql_config()
@testapps_dir = File.join(File.dirname(__FILE__), '../../apps')
@client = VMC::BaseClient.new()
# Make sure we cleanup if we had a failed run..
# Fake out the login and registration piece..
begin
login
@last_registered_user = test_user
rescue
end
cleanup
end
def cleanup
delete_app_internal(SIMPLE_APP)
delete_app_internal(TINY_JAVA_APP)
delete_app_internal(REDIS_LB_APP)
delete_app_internal(ENV_TEST_APP)
delete_app_internal(SIMPLE_DB_APP)
delete_app_internal(BROKEN_APP)
delete_app_internal(RAILS3_APP)
delete_app_internal(JPA_APP)
delete_app_internal(HIBERNATE_APP)
delete_app_internal(DBRAILS_APP)
delete_app_internal(DBRAILS_BROKEN_APP)
delete_app_internal(GRAILS_APP)
delete_app_internal(ROO_APP)
delete_app_internal(SERVICE_TEST_APP)
# This used to delete the entire user, but that now require admin privs
# so it was removed, as we the delete_user method. See the git
# history if it needs to be revived.
end
def create_uri name
"#{name}.#{@suggest_url}"
end
def create_user
@registered_user || "#{@namespace}#{TEST_AUTOMATION_USER_ID}"
end
def create_passwd
@registered_user_passwd || TEST_AUTOMATION_PASSWORD
end
alias :test_user :create_user
alias :test_passwd :create_passwd
def get_registered_user
@last_registered_user
end
def register
unless @registered_user
@client.register_internal(@base_uri, test_user, test_passwd)
end
@last_registered_user = test_user
end
def login
token = @client.login_internal(@base_uri, test_user, test_passwd)
# TBD - ABS: This is a hack around the 1 sec granularity of our token time stamp
sleep(1)
@last_login_token = token
end
def get_login_token
@last_login_token
end
def list_apps token
@client.get_apps_internal(@droplets_uri, auth_hdr(token))
end
def get_app_info app_list, app
if app_list.empty?
return
end
appname = get_app_name app
app_list.each { |d|
if d['name'] == appname
return d
end
}
end
def create_app app, token, instances=1
appname = get_app_name app
delete_app app, token
@app = app
url = create_uri appname
manifest = {
:name => "#{appname}",
:staging => {
:model => @config[app]['framework'],
:stack => @config[app]['startup']
},
:resources=> {
:memory => @config[app]['memory'] || 64
},
:uris => [url],
:instances => "#{instances}",
}
response = @client.create_app_internal @droplets_uri, manifest, auth_json_hdr(token)
response.should_not == nil
if response.status == 200
return parse_json(response.content)
else
puts "Creation of app #{appname} failed. Http status #{response.status}. Content: #{response.content}"
return
end
end
def get_app_name app
# It seems _ is not welcomed in hostname
"#{@namespace}my_test_app_#{app}".gsub("_", "-")
end
def upload_app app, token, subdir = nil
Dir.chdir("#{@testapps_dir}/#{app}" + (if subdir then "/#{subdir}" else "" end))
opt_war_file = nil
if Dir.glob('*.war').first
opt_war_file = Dir.glob('*.war').first
end
appname = get_app_name app
@client.upload_app_bits @resources_uri, @droplets_uri, appname, auth_hdr(token), opt_war_file
end
def get_app_status app, token
appname = get_app_name app
response = @client.get_app_internal(@droplets_uri, appname, auth_hdr(token))
if (response.status == 200)
JSON.parse(response.content)
end
end
def delete_app_internal app
token = get_login_token
if app != nil && token != nil
delete_app app, token
end
end
def delete_app app, token
appname = get_app_name app
response = @client.delete_app_internal(@droplets_uri, appname, [], auth_hdr(token))
@app = nil
response
end
def start_app app, token
appname = get_app_name app
app_manifest = get_app_status app, token
if app_manifest == nil
raise "Application #{appname} does not exist, app needs to be created."
end
if (app_manifest['state'] == 'STARTED')
return
end
app_manifest['state'] = 'STARTED'
response = @client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
raise "Problem starting application #{appname}." if response.status != 200
end
def poll_until_done app, expected_health, token
secs_til_timeout = @config['timeout_secs']
health = nil
sleep_time = 0.5
while secs_til_timeout > 0 && health != expected_health
sleep sleep_time
secs_til_timeout = secs_til_timeout - sleep_time
status = get_app_status app, token
runningInstances = status['runningInstances'] || 0
health = runningInstances/status['instances'].to_f
# to mark? Not sure why this change, but breaks simple stop tests
#health = runningInstances == 0 ? status['instances'].to_f : runningInstances.to_f
end
health
end
def stop_app app, token
appname = get_app_name app
app_manifest = get_app_status app, token
if app_manifest == nil
raise "Application #{appname} does not exist."
end
if (app_manifest['state'] == 'STOPPED')
return
end
app_manifest['state'] = 'STOPPED'
@client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
end
def get_app_files app, instance, path, token
appname = get_app_name app
@client.get_app_files_internal @droplets_uri, appname, instance, path, auth_hdr(token)
end
def get_instances_info app, token
appname = get_app_name app
instances_info = @client.get_app_instances_internal @droplets_uri, appname, auth_hdr(token)
instances_info
end
def set_app_instances app, new_instance_count, token
appname = get_app_name app
app_manifest = get_app_status app, token
if app_manifest == nil
raise "App #{appname} needs to be deployed on AppCloud before being able to increment its instance count"
end
instances = app_manifest['instances']
health = app_manifest['health']
if (instances == new_instance_count)
return
end
app_manifest['instances'] = new_instance_count
response = @client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
raise "Problem setting instance count for application #{appname}." if response.status != 200
expected_health = 1.0
poll_until_done app, expected_health, token
new_instance_count
end
def get_app_crashes app, token
appname = get_app_name app
response = @client.get_app_crashes_internal @droplets_uri, appname, auth_hdr(token)
crash_info = JSON.parse(response.content) if (response.status == 200)
end
def get_app_stats app, token
appname = get_app_name app
response = @client.get_app_stats_internal(@droplets_uri, appname, auth_hdr(token))
if (response.status == 200)
JSON.parse(response.content)
end
end
def add_app_uri app, uri, token
appname = get_app_name app
app_manifest = get_app_status app, token
if app_manifest == nil
raise "Application #{appname} does not exist, app needs to be created."
end
app_manifest['uris'] << uri
response = @client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
raise "Problem adding uri #{uri} to application #{appname}." if response.status != 200
expected_health = 1.0
poll_until_done app, expected_health, token
end
def remove_app_uri app, uri, token
appname = get_app_name app
app_manifest = get_app_status app, token
if app_manifest == nil
raise "Application #{appname} does not exist, app needs to be created."
end
if app_manifest['uris'].delete(uri) == nil
raise "Application #{appname} is not associated with #{uri} to be removed"
end
response = @client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
raise "Problem removing uri #{uri} from application #{appname}." if response.status != 200
expected_health = 1.0
poll_until_done app, expected_health, token
end
def modify_and_upload_app app,token
Dir.chdir("#{@testapps_dir}/modified_#{app}")
appname = get_app_name app
@client.upload_app_bits @resources_uri, @droplets_uri, appname, auth_hdr(token), nil
end
def modify_and_upload_bad_app app,token
appname = get_app_name app
Dir.chdir("#{@testapps_dir}/#{BROKEN_APP}")
@client.upload_app_bits @resources_uri, @droplets_uri, appname, auth_hdr(token), nil
end
def poll_until_update_app_done app, token
appname = get_app_name app
@client.update_app_internal @droplets_uri, appname, auth_hdr(token)
update_state = nil
secs_til_timeout = @config['timeout_secs']
while secs_til_timeout > 0 && update_state != 'SUCCEEDED' && update_state != 'CANARY_FAILED'
sleep 1
secs_til_timeout = secs_til_timeout - 1
response = @client.get_update_app_status @droplets_uri, appname, auth_hdr(token)
update_info = JSON.parse(response.content)
update_state = update_info['state']
end
update_state
end
def get_services token
response = HTTPClient.get "#{@base_uri}/info/services", nil, auth_hdr(token)
services = JSON.parse(response.content)
services
end
def get_frameworks token
response = HTTPClient.get "#{@base_uri}/info", nil, auth_hdr(token)
frameworks = JSON.parse(response.content)
frameworks['frameworks']
end
def provision_db_service token
name = "#{@namespace}#{@app || 'simple_db_app'}"
service_manifest = {
:type=>"database",
:vendor=>"mysql",
:tier=>"free",
:version=>"5.1.45",
:name=>name,
:options=>{"size"=>"256MiB"}}
@client.add_service_internal @services_uri, service_manifest, auth_hdr(token)
#puts "Provisioned service #{service_manifest}"
service_manifest
end
def provision_redis_service token
service_manifest = {
:type=>"key-value",
:vendor=>"redis",
:tier=>"free",
:version=>"5.1.45",
:name=>"#{@namespace}redis_lb_app-service",
}
@client.add_service_internal @services_uri, service_manifest, auth_hdr(token)
#puts "Provisioned service #{service_manifest}"
service_manifest
end
def provision_redis_service_named token, name
service_manifest = {
:type=>"key-value",
:vendor=>"redis",
:tier=>"free",
:version=>"5.1.45",
:name=>redis_name(name),
}
@client.add_service_internal @services_uri, service_manifest, auth_hdr(token)
#puts "Provisioned service #{service_manifest}"
service_manifest
end
def redis_name name
"#{@namespace}redis_#{name}"
end
def aurora_name name
"#{@namespace}aurora_#{name}"
end
def mozyatmos_name name
"#{@namespace}mozyatmos_#{name}"
end
def provision_aurora_service_named token, name
service_manifest = {
:type=>"database",
:vendor=>"aurora",
:tier=>"std",
:name=>aurora_name(name),
}
@client.add_service_internal @services_uri, service_manifest, auth_hdr(token)
#puts "Provisioned service #{service_manifest}"
service_manifest
end
def provision_mozyatmos_service_named token, name
service_manifest = {
:type=>"blob",
:vendor=>"mozyatmos",
:tier=>"std",
:name=>mozyatmos_name(name),
}
@client.add_service_internal @services_uri, service_manifest, auth_hdr(token)
#puts "Provisioned service #{service_manifest}"
service_manifest
end
def attach_provisioned_service app, service_manifest, token
appname = get_app_name app
app_manifest = get_app_status app, token
provisioned_service = app_manifest['services']
provisioned_service = [] unless provisioned_service
svc_name = service_manifest[:name]
provisioned_service << svc_name
app_manifest['services'] = provisioned_service
response = @client.update_app_state_internal @droplets_uri, appname, app_manifest, auth_hdr(token)
raise "Problem attaching service #{svc_name} to application #{appname}." if response.status != 200
end
def delete_services services, token
#puts "Deleting services #{services}"
response = @client.delete_services_internal(@services_uri, services, auth_hdr(token))
response
end
def get_uri app, relative_path=nil
appname = get_app_name app
uri = "#{appname}.#{@suggest_url}"
if relative_path != nil
uri << "/#{relative_path}"
end
uri
end
def get_app_contents app, relative_path=nil
uri = get_uri app, relative_path
get_uri_contents uri
end
def get_uri_contents uri
easy = Curl::Easy.new
easy.url = uri
easy.http_get
easy
end
def post_record uri, data_hash
easy = Curl::Easy.new
easy.url = uri
easy.http_post(data_hash.to_json)
easy.close
end
def put_record uri, data_hash
easy = Curl::Easy.new
easy.url = uri
easy.http_put(data_hash.to_json)
easy.close
end
def delete_record uri
easy = Curl::Easy.new
easy.url = uri
easy.http_delete
easy.close
end
def parse_json payload
JSON.parse(payload)
end
def auth_hdr token
{
'AUTHORIZATION' => "#{token}",
}
end
def auth_json_hdr token
{
'AUTHORIZATION' => "#{token}",
'content-type' => "application/json",
}
end
def bind_service_to_app(app, service, token)
app_name = app["name"]
service_name = service["service_id"]
app["services"] ||= []
app["services"] << @service_alias
res = @client.update_app_state_internal(@droplets_uri, app_name, app, auth_json_hdr(token))
debug "binding result: #{res.content}"
res.status.should == 200
res.content
end
def unprovision_service(service = nil)
service = @service_detail if service.nil?
return if service.nil?
res = @client.unprovision_service_internal(@configuration_uri, service['service_id'], auth_json_hdr(@token))
res.status.should == 200
@service_detail = nil
end
def valid_services
%w(mysql mongodb redis rabbitmq)
end
def shutdown_service_node(service)
pid = service_node_pid(service)
%x[kill -9 #{pid}]
end
def service_node_pid(service)
node_process = service + "_node"
pid = %x[ps -ef|grep ruby|grep #{node_process}|grep -v grep|awk '{print $2}']
return pid
end
def start_service_node(service)
service_node_pid(service).should == ""
start_script = File.expand_path("../../../../#{service}/bin/#{service}_node", __FILE__)
gem_file = File.expand_path("../../../../#{service}/Gemfile", __FILE__)
debug "start script for #{service}:#{start_script}"
# FIXME Bundler.with_clean_env issue
Bundler.with_clean_env do
pid = spawn({"BUNDLE_GEMFILE"=>gem_file}, "#{start_script} >/tmp/vcap-run/#{service}_node.log 2>&1")
Process.detach(pid)
end
# check
service_node_pid(service).should_not == nil
end
def debug(msg)
if ENV['SERVICE_TEST']
puts "D: " + msg
end
end
# Parse the port of given service gateway. Only works if service gw running on the same host with test code.
def service_gateway_port(service)
gw_name = "#{service}_gateway"
pid = %x[ps -ef|grep 'ruby'|grep -v grep|grep '#{gw_name}'|awk '{ print $2}']
pid.strip!
output = %x[netstat -apn 2>/dev/null|grep -v grep|grep #{pid}| grep -v ESTABLISHED| awk '{print $4}']
ip_ports = output.split("\n")
debug "all ports: #{ip_ports}"
ip_ports.each do |i|
# GW return 400 for a request not using json as content-type
res= %x[curl -i #{i} 2>/dev/null|head -n 1|grep 400]
debug "Result of curl: #{res}"
if not res.empty?
return i
end
end
end
end
|
class Timelog < ApplicationRecord
belongs_to :day, optional: true
belongs_to :user
has_many :tag_taggables, as: :taggable, dependent: :destroy
has_many :tags, through: :tag_taggables
before_save :ensure_day
after_save :save_main_tag
scope :in_range, ->(from, to) {
where('(start > :from AND start < :to) OR (finish > :from AND finish < :to)', from: from, to: to)
}
def duration(as: :seconds)
(finish - start).send(as)
end
def main_tag
tag_taggables.find_by("meta->>'main' = ?", true.to_json)&.tag
end
def main_tag_id
main_tag&.id
end
def main_tag=(main_tag_params)
@main_tag = if main_tag_params.nil? || main_tag_params.is_a?(Tag)
main_tag_params
else
Tag.find(main_tag_params[:id])
end
end
def save_main_tag
return unless @main_tag && @main_tag.id != main_tag&.id
tag_taggables.destroy_all
TagTaggable.create(taggable: self, tag_id: @main_tag.id, meta: { main: true })
end
def ensure_day
self.day ||= Day.ensure(user, date: start)
end
def reeval_day!
self.day = Day.ensure(user, date: start)
save!
end
end
|
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "finn-the-human-#{n}@land-of-ooo.ooo" }
password 'boomboom'
end
end
|
class User < ActiveRecord::Base
has_secure_password
validates :email, presence: true, uniqueness: true
validates :name, length: { minimum: 3, maximum: 30 }
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
has_many :comments
has_many :ratings
end
|
# Cookbook:: fivem
# Attributes:: mariadb_server
#
# 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.
#
package 'gnupg'
mariadb_server_install 'FiveM MariaDB Server' do
action [:install, :create]
setup_repo true
version node['fivem']['mariadb']['version']
password node['fivem']['mariadb']['server']['password']
end
mariadb_server_configuration 'FiveM MariaDB Server Configuration' do
version node['fivem']['mariadb']['version']
mysqld_bind_address node['fivem']['mariadb']['server']['host']
mysqld_port node['fivem']['mariadb']['server']['port']
end
|
class User < ActiveRecord::Base
belongs_to :referrer, :class_name => "User", :foreign_key => "referrer_id"
has_many :referrals, :class_name => "User", :foreign_key => "referrer_id"
attr_accessible :email
validates :email, :uniqueness => true, :format => { :with => /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i, :message => "Invalid email format." }
validates :referral_code, :uniqueness => true
before_create :create_referral_code
after_create :send_welcome_email
after_create :send_referral_confirmation_email
# REFERRAL_STEPS = [
# {
# 'count' => 10,
# "title" => "A mug, badge reel, and pens!",
# "description" => "<h4>Refer 10 friends to NurseGrid and we'll send you:</h4><ul><li>NurseGrid t-shirt</li><li>BPA-free coffee travel mug</li><li>A nurse badge reel</li><li>A set of NurseGrid pens</li></ul>",
# "class" => "prize-one",
# "image" => ActionController::Base.helpers.asset_path("nursegrid_prize_one.jpg")
# },
# {
# 'count' => 20,
# 'remaining'=> 30,
# "title" => "$50 in Scrubs!",
# "description" => "<p>The first 30 nurses to get 20 of their friends to join NurseGrid will receive a $50 gift card to NWScrubs! Happy Shopping</p>",
# "class" => "prize-two",
# "image" => ActionController::Base.helpers.asset_path("nursegrid_prize_two.jpg")
# },
# {
# 'count' => 100,
# 'title' => '$750 JetBlue',
# 'description' => "for every nurse you refer to NurseGrid, we will enter you into the grand prize drawing for a chance to win a <span>$750 Jetblue travel gift card!</span>.",
# 'class' => 'prize-grand',
# 'image' => ActionController::Base.helpers.asset_path("nursegrid_prize_grand.jpg")
# }
# ]
GRAND_PRIZE_STEPS = [
{
'step' => 1,
'referrals' => 1,
'tickets' => 1
},
{
'step' => 2,
'referrals' => 16,
'tickets' => 4
},
{
'step' => 3,
'referrals' => 21,
'tickets' => 6
},
{
'step' => 4,
'referrals' => 26,
'tickets' => 8
},
{
'step' => 5,
'referrals' => 31,
'tickets' => 10
},
{
'step' => 6,
'referrals' => 36,
'tickets' => 12
},
{
'step' => 7,
'referrals' => 41,
'tickets' => 14
},
{
'step' => 8,
'referrals' => 51,
'tickets' => 16
}
]
def referral_count
self.referrals.count
end
def adjusted_referral_count
self.referral_count + 1
end
def grand_prize_progress
count = self.referrals.count
if count <= 15
return count
elsif count > 15 && count <= 20
return count + (3*(count - 15))
elsif count < 20 && count <= 25
return count + (5*(count - 17))
elsif count > 25 && count <= 30
return 73 + (8*(count-26))
elsif count > 30 && count <= 35
return 115 + (10*(count-31))
elsif count > 35 && count <= 40
return 167 + (12*(count-36))
elsif count > 40 && count <= 50
return 229 + (14*(count-41))
elsif count > 50
return 371 + (16*(count-51))
end
end
def check_prize_level
prize_two = Prize.find_by_prize_count(20)
if prize_two.remaining > 0
if self.referrals.count == 29
self.prize_two_winner = true
self.save
prize_two.remaining -=1
prize_two.save
end
end
end
def send_referral_confirmation_email
if self.referrer
UserMailer.referral_confirmation(referrer).deliver
end
end
handle_asynchronously :send_referral_confirmation_email
private
def create_referral_code
referral_code = SecureRandom.hex(5)
@collision = User.find_by_referral_code(referral_code)
while !@collision.nil?
referral_code = SecureRandom.hex(5)
@collision = User.find_by_referral_code(referral_code)
end
self.referral_code = referral_code
end
def send_welcome_email
UserMailer.signup_email(self).deliver
end
handle_asynchronously :send_welcome_email
end
|
module Boilerpipe::Extractors
class DefaultExtractor
def self.text(contents)
doc = ::Boilerpipe::SAX::BoilerpipeHTMLParser.parse(contents)
::Boilerpipe::Extractors::DefaultExtractor.process doc
doc.content
end
def self.process(doc)
filters = ::Boilerpipe::Filters
# merge adjacent blocks with equal text_density
filters::SimpleBlockFusionProcessor.process doc
# merge text blocks next to each other
filters::BlockProximityFusion::MAX_DISTANCE_1.process doc
# marks text blocks as content / non-content using boilerpipe alg
filters::DensityRulesClassifier.process doc
doc
end
end
end
|
module Elevate
class Callback
def initialize(controller, block)
@controller = controller
@block = block
end
def call(*args)
if NSThread.isMainThread
invoke(*args)
else
Dispatch::Queue.main.sync { invoke(*args) }
end
end
private
def invoke(*args)
@controller.instance_exec(*args, &@block)
end
end
end
|
FactoryGirl.define do
factory :attachment do
file_file_name "example.png"
file_content_type "image/png"
file_file_size 1000
user
proposal
end
end
|
module QueryModelPatch
# Get all descendants projects for given ids.
def get_descendant_projects(value, all = [])
if all.empty?
all = value
end
projects = Project.where(parent_id: value)
new_ids = []
projects.each do |project|
new_ids.push(project.id)
all.push(project.id)
end
# If no more new items, return all collected ids, otherwise keep looking.
unless new_ids.empty?
get_descendant_projects(new_ids, all)
else
all
end
end
def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
if field == 'project_id' && operator == '=*'
ids = get_descendant_projects(value)
value_str = ids.join(",")
sql = "#{db_table}.#{db_field} IN (SELECT id FROM projects where id IN (#{value_str}))"
elsif field == 'spent_on' && operator == 'tlm'
prevDate = User.current.today.prev_month
currentDate = User.current.today
sql = date_clause(db_table, db_field,
prevDate.beginning_of_month, currentDate.end_of_month,
is_custom_filter)
else
super
end
end
def add_filter_error(field, message)
unless message == :blank && field == 'spent_on'
super
end
end
end
# Add module to Query Model
Query.prepend QueryModelPatch
|
require 'rails_helper'
RSpec.describe ServiceRequest, type: :model do
it { is_expected.to belong_to(:protocol) }
it { is_expected.to have_many(:sub_service_requests) }
end
|
class ChangeTypeToDataType < ActiveRecord::Migration[5.1]
def change
rename_column :data, :type, :data_type
end
end
|
class ApplicationController < ActionController::API
rescue_from Exceptions::AuthorizationError, with: :unauthorized_error
rescue_from Exceptions::InvalidHeaderError, Exceptions::EmptyObjectError, Exceptions::WrongHeaderError, with: :invalid_exceptions
rescue_from Exceptions::AuthenticationError, with: :authenticated_exception
after_action :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = '*'
end
protected
# user authentication for actions
def authenticate_user
if current_user
true
else
raise Exceptions::AuthorizationError.new('invalid user authorization')
end
end
def current_user
if request.headers['Authorization'].present?
# decode access_token
payload = TokenHelper.jwt_decode(request.headers['Authorization'])
# checks for payload
unless payload && !payload['refresh']
raise Exceptions::InvalidHeaderError.new("Authorization")
end
@user = User.find(payload['user_id']) unless @user
# return user if it is present
if @user
@user
else
raise Exceptions::EmptyObjectError.new("user cannot be found")
end
end
end
# catches AuthenticationError
def authenticated_exception(exception)
logger.error "IAuthentication failed - #{request.headers['Authorization']}"
render json: {error: exception}, status: 307, scope: nil
end
# catches InvalidHeaderError, EmptyObjectError, WrongHeaderError
def invalid_exceptions(exception)
render json: {error: exception}, status: 401, scope: nil
end
def unauthorized_error(exception)
logger.error "Invalid authorization - #{request.headers['Authorization']}"
render json: {error: exception}, status: 403, scope: nil
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
User.create(full_name: "Admin", email: "admin@forumhub.com", password: "password", role: :admin)
User.create(full_name: "Sample User", email: "user@forumhub.com", password: "password", role: :user)
["Science", "Technolgy", "Software Development", "IT", "Ruby", "Rails", "Javascript"].each do |category|
Category.create(title: category)
end
Question.create(title: "How to install Ruby/Rails?", body: "How to install ruby on rails", user_id: User.last.id, category_id: Category.last.id)
|
#! /usr/bin/env ruby
#
require 'bundler/setup'
require 'json'
require 'net/http'
require 'openssl'
require 'pp'
require 'socket'
require 'thread'
require 'etcd'
MARATHON = ENV.fetch 'MARATHON_URL'
USER, _, PASS = ENV.fetch('MARATHON_AUTH').partition ':'
ips = Hash.new do |this, host|
this[host] = Socket::getaddrinfo(host, nil, nil, :STREAM, nil, nil, false)
end
old = {}
etcd_uris = ENV.fetch('ETCDCTL_PEERS').split(',').map{|u| URI.parse(u)}
crt = OpenSSL::X509::Certificate.new File.read ENV.fetch 'ETCDCTL_CERT_FILE'
key = OpenSSL::PKey.read File.read ENV.fetch 'ETCDCTL_KEY_FILE'
etcd = Etcd.client host: etcd_uris[0].host,
port: etcd_uris[0].port || 80,
use_ssl: etcd_uris[0].scheme.end_with?('s'),
ca_file: ENV.fetch('ETCDCTL_CA_FILE'),
ssl_cert: crt,
ssl_key: key
def connect
http = Net::HTTP.new MARATHON, 443
http.use_ssl = true
http
end
def get path
req = Net::HTTP::Get.new "https://#{MARATHON}#{path}"
req.basic_auth USER, PASS
req
end
def to_json data
data = data.keys.sort.map {|k| [k, data[k]]}
JSON.dump Hash[data]
end
mutex = Mutex.new
cond = ConditionVariable.new
Thread.abort_on_exception = true
Thread.new do
http = connect
loop do
res = http.request get "/v2/apps?embed=apps.tasks"
data = JSON.load res.body
new = {}
data["apps"].each do |app|
records = app['labels'].each.select{|k, v| k.start_with? 'kevincox-dns'}
next if records.empty?
records.map! do |k, v|
j = JSON.load v
{
type: j['type'] || 'A',
name: j.fetch('name'),
priority: j['priority'] || 10,
weight: j['weight'] || 100,
port: j['port'] || 0,
cdn: j.fetch('cdn'),
ttl: j.fetch('ttl'),
}
end
id = app.fetch 'id'
new_keys = {}
old_keys = old.fetch id, {}
healthchecks = app['healthChecks'].length
app['tasks'].each do |task|
records.each do |rec|
case type = rec.fetch(:type)
when 'A'
hcs = task.fetch 'healthCheckResults', [].freeze
next unless hcs && hcs.count{|hc| hc['alive'] } == healthchecks
ips[task['host']].each do |addrinfo|
type = case addrinfo[0]
when 'AF_INET'
'A'
when 'AF_INET6'
'AAAA'
else
next
end
ip = addrinfo[3]
name = rec[:name]
ttl = rec[:ttl]
cdn = rec[:cdn]
key = "/services/A-#{name}/#{ip}"
value = to_json type: type,
name: name,
value: ip,
ttl: ttl,
cdn: cdn
etcd.set key, value: value, ttl: 60
new_keys[key] = true
old_keys.delete key
end
when 'SRV'
name = rec.fetch :name
proto = name.partition('.')[0][1, -1]
port = task.fetch('ports')[rec.fetch(:port)]
host = task.fetch 'host'
value = "#{rec[:priority]} #{rec[:weight]} #{port} #{host}"
key = "/services/SRV-#{name}/#{host}:#{port}"
value = to_json type: type,
name: name,
value: value,
ttl: rec[:ttl],
cdn: false
etcd.set key, value: value, ttl: 60
new_keys[key] = true
old_keys.delete key
else
$stderr.puts "WRN: Unknown record type #{type.inspect}"
$stderr.puts "in #{rec.inspect}"
end
end
end
old_keys.each do |k, v|
etcd.delete k
end
new[id] = new_keys
end
old = new
mutex.synchronize { cond.wait mutex, 30 }
end
end
stream = connect
stream.read_timeout = 24 * 60 * 60
req = get "/v2/events"
req['Accept'] = 'text/event-stream'
stream.request req do |res|
res.read_body do |chunk|
mutex.synchronize { cond.signal }
end
end
|
require_relative 'convert'
def greet(name)
puts "Hi #{name}! Welcome to Dudley's Pig Emporkium"
end
test_cases = [
{
number: 4,
base: 2,
expected: '100'
},
{
number: 322,
base: 16,
expected: '142'
},
{
number: 187,
base: 2,
expected: '10111011'
},
{
number: 748,
base: 20,
expected: '1h8'
},
{
number: 166,
base: 22,
expected: '7c'
},
{
number: 883,
base: 16,
expected: '373'
},
{
number: 217,
base: 32,
expected: '6p'
},
{
number: 447,
base: 24,
expected: 'if'
},
{
number: 507,
base: 13,
expected: '300'
},
{
number: 800,
base: 20,
expected: '200'
},
{
number: 188,
base: 20,
expected: '98'
},
{
number: 665,
base: 10,
expected: '665'
},
{
number: 861,
base: 34,
expected: 'pb'
},
{
number: 425,
base: 30,
expected: 'e5'
},
{
number: 868,
base: 29,
expected: '10r'
},
{
number: 930,
base: 14,
expected: '4a6'
},
{
number: 979,
base: 21,
expected: '24d'
},
{
number: 806,
base: 3,
expected: '1002212'
},
{
number: 755,
base: 21,
expected: '1ek'
},
{
number: 12,
base: 10,
expected: '12'
},
{
number: 586,
base: 17,
expected: '208'
},
{
number: 663,
base: 36,
expected: 'if'
},
{
number: 964,
base: 34,
expected: 'sc'
},
{
number: 750,
base: 36,
expected: 'ku'
},
{
number: 731,
base: 8,
expected: '1333'
},
{
number: 874,
base: 9,
expected: '1171'
},
{
number: 613,
base: 28,
expected: 'lp'
},
{
number: 487,
base: 36,
expected: 'dj'
},
{
number: 998,
base: 14,
expected: '514'
},
{
number: 9,
base: 12,
expected: '9'
},
{
number: 181,
base: 10,
expected: '181'
},
{
number: 523,
base: 34,
expected: 'fd'
},
{
number: 960,
base: 22,
expected: '1le'
},
{
number: 31,
base: 29,
expected: '12'
},
{
number: 746,
base: 36,
expected: 'kq'
},
{
number: 903,
base: 36,
expected: 'p3'
},
{
number: 486,
base: 15,
expected: '226'
},
{
number: 906,
base: 7,
expected: '2433'
},
{
number: 992,
base: 30,
expected: '132'
},
{
number: 588,
base: 33,
expected: 'hr'
},
{
number: 341,
base: 29,
expected: 'bm'
},
{
number: 760,
base: 19,
expected: '220'
},
{
number: 878,
base: 7,
expected: '2363'
},
{
number: 85,
base: 7,
expected: '151'
},
{
number: 10,
base: 5,
expected: '20'
},
{
number: 544,
base: 36,
expected: 'f4'
},
{
number: 4,
base: 27,
expected: '4'
},
{
number: 401,
base: 19,
expected: '122'
},
{
number: 766,
base: 24,
expected: '17m'
},
{
number: 622,
base: 19,
expected: '1de'
},
{
number: 349,
base: 32,
expected: 'at'
},
{
number: 989,
base: 34,
expected: 't3'
},
{
number: 540,
base: 12,
expected: '390'
},
{
number: 102,
base: 8,
expected: '146'
},
{
number: 876,
base: 4,
expected: '31230'
},
{
number: 677,
base: 26,
expected: '101'
},
{
number: 705,
base: 10,
expected: '705'
},
{
number: 773,
base: 17,
expected: '2b8'
},
{
number: 513,
base: 15,
expected: '243'
},
{
number: 946,
base: 22,
expected: '1l0'
},
{
number: 991,
base: 16,
expected: '3df'
},
{
number: 754,
base: 32,
expected: 'ni'
},
{
number: 647,
base: 24,
expected: '12n'
},
{
number: 757,
base: 18,
expected: '261'
},
{
number: 27,
base: 25,
expected: '12'
},
{
number: 106,
base: 29,
expected: '3j'
},
{
number: 760,
base: 33,
expected: 'n1'
},
{
number: 50,
base: 22,
expected: '26'
},
{
number: 689,
base: 26,
expected: '10d'
},
{
number: 996,
base: 17,
expected: '37a'
},
{
number: 768,
base: 36,
expected: 'lc'
},
{
number: 408,
base: 18,
expected: '14c'
},
{
number: 744,
base: 14,
expected: '3b2'
},
{
number: 389,
base: 16,
expected: '185'
},
{
number: 827,
base: 17,
expected: '2eb'
},
{
number: 968,
base: 28,
expected: '16g'
},
{
number: 995,
base: 23,
expected: '1k6'
},
{
number: 2,
base: 16,
expected: '2'
},
{
number: 404,
base: 17,
expected: '16d'
},
{
number: 651,
base: 5,
expected: '10101'
},
{
number: 521,
base: 14,
expected: '293'
},
{
number: 107,
base: 10,
expected: '107'
},
{
number: 384,
base: 3,
expected: '112020'
},
{
number: 270,
base: 34,
expected: '7w'
},
{
number: 868,
base: 20,
expected: '238'
},
{
number: 655,
base: 31,
expected: 'l4'
},
{
number: 334,
base: 9,
expected: '411'
},
{
number: 99,
base: 10,
expected: '99'
},
{
number: 115,
base: 18,
expected: '67'
},
{
number: 181,
base: 27,
expected: '6j'
},
{
number: 790,
base: 18,
expected: '27g'
},
{
number: 495,
base: 30,
expected: 'gf'
},
{
number: 756,
base: 20,
expected: '1hg'
},
{
number: 949,
base: 18,
expected: '2gd'
},
{
number: 91,
base: 18,
expected: '51'
},
{
number: 566,
base: 25,
expected: 'mg'
},
{
number: 801,
base: 35,
expected: 'mv'
},
{
number: 813,
base: 11,
expected: '67a'
},
{
number: 762,
base: 33,
expected: 'n3'
},
{
number: 43,
base: 26,
expected: '1h'
}
]
puts "Running #{test_cases.count} tests"
test_cases.each do |test|
output = Converter.new(test[:number]).to_base(test[:base])
# output = test[:number].to_base test[:base]
unless output == test[:expected]
puts "Failed to convert #{test[:number]} to base #{test[:base]} (got #{output}, #{test[:expected]} expected)"
end
end
puts 'Tests complete'
# str = "test_cases = [\n"
# 100.times do
# base = (2..36).to_a.sample
# number = (1..1000).to_a.sample
# str << "{\nnumber: #{number},\nbase: #{base},\nexpected: '#{number.to_s base}'\n},\n"
# end
# str << "\n]"
# puts str
|
class Numeric
def restrict(var = {})
min = var[:min] || 0
max = var[:max] || 255
self < min ? min : (self > max ? max : self)
end
def to_hex
to_s(base=16).rjust(2, '0')
end
end |
class StreamFavoritesController < FavoritesController
def create
if @favable.is_a?(Stream) and not @favable.is_public?
redirect_to @redirect_location and return false
end
super
end
protected
def get_favable
@favable = Stream.find(params[:id])
end
def get_favorite
@favorite = current_profile.favorites.streams.find_by_favable_id(@favable.id)
end
def set_redirect_location
@redirect_location = profile_stream_path(@favable.profile, @favable)
end
end
|
require 'spec_helper'
describe "account_types/show" do
before do
assign(:account_type, Factory(:assets))
end
it "should show the name of the account type" do
render
rendered.should have_content("Name: Assets")
end
it "should show the code of the account type" do
render
rendered.should have_content("Code: assets")
end
it "should show the name of the account type" do
render
rendered.should have_content("Note: Asset Desc")
end
end
|
class RemoveColumnBillTotalAmountInBillentries < ActiveRecord::Migration[5.0]
def change
remove_column :billentries, :bill_total_amount
end
end
|
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_host
def set_host
Rails.application.routes.default_url_options[:host] = request.host_with_port
end
protected
#サインイン後の遷移先指定
def after_sign_in_path_for(resource)
home_path
end
#サインアップ後の遷移先指定
def after_sign_up_path_for(resource)
home_path
end
#ログアウト後の遷移先指定
def after_sign_out_path_for(resource)
home_path
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
end
end
|
class ConfigureTimeStampItems < ActiveRecord::Migration[5.2]
def change
remove_column :users, :created_at
remove_column :users, :updated_at
remove_column :photos, :created_at
remove_column :photos, :updated_at
remove_column :follows, :created_at
remove_column :follows, :updated_at
remove_column :likes, :created_at
remove_column :likes, :updated_at
remove_column :comments, :created_at
remove_column :comments, :updated_at
end
end
|
class FeeCollectionBatch < ActiveRecord::Base
belongs_to :batch
belongs_to :finance_fee_collection
has_many :collection_particulars,
:finder_sql=>'select cp.* from collection_particulars cp inner join finance_fee_particulars ffp on ffp.id=cp.finance_fee_particular_id where cp.finance_fee_collection_id=#{finance_fee_collection_id} and ffp.batch_id=#{batch_id}',
:dependent=>:destroy
has_many :collection_discounts,
:finder_sql=>'select cd.* from collection_discounts cd inner join fee_discounts fd on fd.id=cd.fee_discount_id where cd.finance_fee_collection_id=#{finance_fee_collection_id} and fd.batch_id=#{batch_id}',
:dependent=>:destroy
before_destroy :delete_finance_fees
after_create :create_associates
attr_accessor :tax_mode
validates_uniqueness_of :finance_fee_collection_id,:scope=>:batch_id
named_scope :current_active_financial_year, lambda {|x|
{:joins => {:finance_fee_collection => :fee_category},
:conditions => ["finance_fee_categories.financial_year_id
#{FinancialYear.current_financial_year_id.present? ? '=' : 'IS'} ?",
FinancialYear.current_financial_year_id] }}
private
def create_associates
tax_config = tax_mode || 0
discounts=FeeDiscount.find_all_by_finance_fee_category_id_and_batch_id(finance_fee_collection.fee_category_id,
batch_id,:conditions=>"is_deleted=0 and is_instant=false")
discounts.each do |discount|
CollectionDiscount.create(:fee_discount_id=>discount.id,:finance_fee_collection_id=>finance_fee_collection_id)
end
include_associations = tax_config ? [] : [:tax_slabs]
particlulars = FinanceFeeParticular.find_all_by_finance_fee_category_id_and_batch_id(
finance_fee_collection.fee_category_id,batch_id, :conditions=>"is_deleted=0",
:include => include_associations)
particlulars.each do |particular|
CollectionParticular.create(:finance_fee_particular_id=>particular.id,:finance_fee_collection_id=>finance_fee_collection_id)
#particular wise tax recording while collection is created or modified
particular.collectible_tax_slabs.create({ :tax_slab_id => particular.tax_slabs.try(:last).try(:id),
:collection_id => finance_fee_collection_id, :collection_type => 'FinanceFeeCollection'
}) if tax_config && particular.tax_slabs.present?
end
end
def load_tax_config
Configuration.get_config_value('EnableFinanceTax').to_i
end
def delete_finance_fees
FinanceFee.find(:all,:conditions=>"finance_fees.batch_id=#{batch_id} and finance_fees.fee_collection_id=#{finance_fee_collection_id}").each{|fee| fee.destroy}
end
end
|
# == Schema Information
#
# Table name: ad_boxes
#
# id :integer not null, primary key
# grid_x :integer
# grid_y :integer
# column :integer
# row :integer
# order :integer
# ad_type :string
# advertiser :string
# inactive :boolean
# ad_image :string
# page_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# color :boolean
# path :string
# date :date
# page_heading_margin_in_lines :integer
# page_number :integer
# grid_width :float
# grid_height :float
# gutter :float
#
# Indexes
#
# index_ad_boxes_on_page_id (page_id)
#
require 'test_helper'
class AdBoxTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
class Matricula < ActiveRecord::Base
self.table_name = 'matriculas'
self.inheritance_column = 'ruby_type'
self.primary_key = 'id'
if ActiveRecord::VERSION::STRING < '4.0.0' || defined?(ProtectedAttributes)
attr_accessible :codigo, :empresa_id
end
belongs_to :empresa, :foreign_key => 'empresa_id', :class_name => 'Empresa'
has_many :matriculas_log, :foreign_key => 'matricula_id', :class_name => 'MatriculasLog'
has_many :empresas, :through => :matriculas_log, :foreign_key => 'empresa_id', :class_name => 'Empresa'
has_many :vehiculos, :through => :matriculas_log, :foreign_key => 'vehiculo_id', :class_name => 'Vehiculo'
def get_nombre_empresa
begin
empresa = Empresa.find(self.empresa_id)
return empresa.razon_social
rescue Exception => e
return ""
end
end
def get_vehiculo
operaciones = MatriculaLog.where("matricula_id = ?", self.id).order('fecha DESC').limit(1)
vehiculo = Vehiculo.find(operaciones[0].vehiculo_id)
#return Vehiculo.find(80)
end
def self.search1(search)
where("codigo = ?", search)
end
def as_json(options = {})
super(options.merge(include: :empresa))
end
end
|
class RenameTreatsToTreatments < ActiveRecord::Migration
def change
rename_table :treats, :treatments
end
end
|
class ChangeDatatypeFrameTypeOfBikes < ActiveRecord::Migration[5.0]
def change
change_column :bikes, :frame_type, :integer
end
end
|
#
# Author:: Mukta Aphale (<mukta.aphale@clogeny.com>)
# Copyright:: Copyright (c) 2013 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
#
require 'spec_helper'
if Chef::Platform.windows?
require 'chef/application/windows_service'
end
describe "Chef::Application::WindowsService", :windows_only do
let (:instance) {Chef::Application::WindowsService.new}
let (:shell_out_result) {Object.new}
let (:tempfile) {Tempfile.new "log_file"}
before do
instance.stub(:parse_options)
shell_out_result.stub(:stdout)
shell_out_result.stub(:stderr)
end
it "runs chef-client in new process" do
instance.should_receive(:configure_chef).twice
instance.service_init
instance.should_receive(:run_chef_client).and_call_original
instance.should_receive(:shell_out).and_return(shell_out_result)
instance.stub(:running?).and_return(true, false)
instance.instance_variable_get(:@service_signal).stub(:wait)
instance.stub(:state).and_return(4)
instance.service_main
end
it "passes config params to new process" do
Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info})
instance.should_receive(:configure_chef).twice
instance.service_init
instance.stub(:running?).and_return(true, false)
instance.instance_variable_get(:@service_signal).stub(:wait)
instance.stub(:state).and_return(4)
instance.should_receive(:run_chef_client).and_call_original
instance.should_receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}").and_return(shell_out_result)
instance.service_main
tempfile.unlink
end
end
|
require 'spec_helper'
describe ActionView::Helpers::FormBuilder do
class Post
def user_id
1
end
end
let(:template) do
ActionView::Base.new
end
describe "#autocomplete_select" do
let(:post) { Post.new }
let(:builder) { ActionView::Helpers::FormBuilder.new(:item, post, template, {}) }
context "with options" do
subject { builder.autocomplete_select(:user_id, '/search', :minLength => 3, :source => '/overwrite') }
it { should eq "<input data-autocomplete-select=\"{"minLength":3,"source":"/search"}\" type=\"text\" value=\"1\" name=\"item[user_id]\" id=\"item_user_id\" />" }
end
context "without options" do
subject { builder.autocomplete_select(:user_id, '/search') }
it { should eq "<input data-autocomplete-select=\"{"source":"/search"}\" type=\"text\" value=\"1\" name=\"item[user_id]\" id=\"item_user_id\" />" }
end
end
end
|
require 'test_helper'
class ImportFileTest < ActiveSupport::TestCase
test "invalid won't import" do
imp = ImportFile.new
assert !imp.import
end
test "import valid file" do
file = Rack::Test::UploadedFile.new('test/samples/example_input.tab', 'text/plain')
imp = ImportFile.new(file: file)
assert imp.valid?
assert_equal 'example_input.tab', imp.filename
assert_difference(['Customer.count', 'Merchant.count', 'Item.count'], 3) do
assert_difference('Purchase.count', 4) do
assert imp.import
end
end
# assert that duplicates were rejected
assert_equal 1, Customer.where(name: "Snake Plissken").count
assert_equal 1, Item.where(description: "$20 Sneakers for $5").count
assert_equal 1, Merchant.where(name: "Sneaker Store Emporium").count
expected_results(imp.results, processed_rows: 4, revenue: 95.0, successful_rows: 4, error_rows: [])
end
test "import invalid file" do
file = Rack::Test::UploadedFile.new('test/samples/bad_input.tab', 'text/plain')
imp = ImportFile.new(file: file)
assert imp.valid?
assert_equal 'bad_input.tab', imp.filename
assert_difference(['Customer.count', 'Merchant.count', 'Item.count', 'Purchase.count'], 0) do
assert imp.import
end
results = imp.results
expected_results(results, processed_rows: 6, revenue: 0, successful_rows: 0)
assert_equal 6, results[:error_rows].size
end
def expected_results(results, expected)
expected.keys.each do |k|
assert_equal expected[k], results[k]
end
end
end
|
=begin
Tests du model Article
=end
require 'spec_helper'
require_model 'article'
describe Article do
# -------------------------------------------------------------------
# La classe
# -------------------------------------------------------------------
describe "Classe" do
it "doit répondre à :article_courant" do
Article.should respond_to :article_courant
end
it ":article_courant doit retourner le contenu de l'article courant" do
res = Article::article_courant
res.should =~ /div id="current_article"/
# @note: le reste du contenu est vérifié par l'instance (:to_html)
end
end # / describle classe
# -------------------------------------------------------------------
# Instance
# -------------------------------------------------------------------
describe "Instance" do
before(:each) do
@art = Article::new "xxxx"
end
it "doit répondre à :id" do
@art.should respond_to :id
end
it ":id doit retourner la bonne valeur" do
@art.id.should == "xxxx"
end
it "doit répondre à :path_article" do
@art.should respond_to :path_article
end
it ":path_article doit retourner la bonne valeur" do
@art.path_article.should ==
File.join(BASE_SITE, 'data', 'article', 'xarchive', 'xxxx.yml')
end
it "doit répondre à :data" do
@art.should respond_to :data
end
it ":data doit retourner les données" do
res = @art.data
res.should have_key :titre
res.should have_key :date
res.should have_key :contenu
res.should have_key :cate
res[:type].should == "article"
end
it "doit répondre à :to_html" do
@art.should respond_to :to_html
end
it ":to_html doit retourner le code HTML" do
res = @art.to_html
sens1 = res =~ /div id="article-xxxx" class="article"/
sens2 = res =~ /div class="article" id="article-xxxx"/
(sens1 || sens2).should be_true
res.should =~ /div class="article_titre"/
res.should =~ /div class="article_date"/
res.should =~ /div class="article_contenu"/
end
# :titre_linked
it "doit répondre à :titre_linked" do
@art.should respond_to :titre_linked
end
it ":titre_linked doit retourner la bonne valeur" do
res = @art.titre_linked
id = iv_get(@art, :id).to_s
res.should =~ /<div class="article_titre">/
res.should =~ /Titre pour article test/
href = Regexp::escape(File.join(Site::base_url_simple, 'article', 'xxxx', 'show'))
res.should =~ /<a href="#{href}">/
src = Regexp::escape(File.join(Site::base_url_simple, 'img', 'file.png'))
res.should =~ /<img src="#{src}" \/>/
end
end # /describe Instance
end |
# A method named `binary_to_decimal` that receives as input an array of size 8.
# The array is randomly filled with 0’s and 1’s.
# The most significant bit is at index 0.
# The least significant bit is at index 7.
# Calculate and return the decimal value for this binary number using
# # the algorithm you devised in class.
def binary_to_decimal(binary_array)
raise ArgumentErrot if binary_array == nil
decimal = 0
index = 0
while index < binary_array.length
decimal += binary_array[index] * 2 ** (binary_array.length - 1 - index)
index += 1
end
return decimal
end
dec = binary_to_decimal([1, 0, 0, 1, 1, 0, 1, 0])
print dec
def binary_to_decimal(binary_array)
raise ArgumentErrot if binary_array == nil
decimal = 0
binary_array.each_with_index do |digit, index|
decimal += digit * 2 ** (binary_array.length - 1 - index)
end
return decimal
end
dec = binary_to_decimal([1, 0, 0, 1, 1, 0, 1, 0])
print dec |
Rails.application.routes.draw do
resources :produces
root 'welcome#index'
resources :users do
resources :favorites
end
# custom route, get by username
get 'users(/username/:username)', to: 'users#display'
resources :markets, only: [:index]
end
|
require_relative 'bike'
class DockingStation
def release_bike
Bike.new
end
def dock(bike)
# use an instance variable to store the Bike
# in the 'state' of this instance
@bike = bike
end
attr_reader :bike
#longer way
#def bike
#(we need to return the bike we dock)
#@bike
#end
end
|
class Ledger < ApplicationRecord
belongs_to :group
belongs_to :character
belongs_to :spec
end
|
class Requisicao < ActiveRecord::Base
has_many :itens, :dependent => :destroy
has_many :eventos
belongs_to :unidade
belongs_to :usuario
belongs_to :empresa
belongs_to :departamento
ESTADOS = {
:pendente => 'Pendente',
:confirmado => 'Confirmado',
:enviado => 'Enviado',
:recebido => 'Recebido'
}
# valores são criados em before_create(), apos a validação,
# por isso essa validação deve ocorrer apenas no update
validates_presence_of :pedido, :data, :estado, :on => :update
# valor boolean
validates_inclusion_of :emergencial, :transporte, :in => [ true, false ]
# quando definido transporte a unidade deve ser definida
validates_presence_of :unidade_id, :if => :transporte?
validates_presence_of :usuario_id, :empresa_id
symbolize :estado
validates_inclusion_of :estado, :in => ESTADOS.keys, :on => :update
validates_uniqueness_of :pedido
# validates_format_of
def validate_on_update
if estado != :pendente && itens.empty?
errors.add 'itens', 'não foram adicionados'
end
end
def before_create
self.data = Time.now
self.pedido = data.strftime('%d%m%Y%H%M%S') \
+ empresa.codigo + usuario.codigo
self.estado = :pendente
eventos.build(:tipo => :criacao, :data => data,
:usuario => usuario)
end
def pendente?
estado == :pendente
end
def confirmar(usuario)
if pendente?
Requisicao.transaction do
self.estado = :confirmado
e = eventos.build(:tipo => :confirmacao, :data => Time.now,
:usuario => usuario)
e.save && save
end
else
confirmado?
end
end
def confirmado?
estado == :confirmado
end
def resumo_qtd
itens.group_by { |item| item.material }.collect do |material, item_array|
[ material, item_array.sum { |item| item.qtd } ]
end.sort_by { |pair| pair.first.id } #ordena pelo material_id
end
def method_missing(name, *params, &block)
eventos.find_by_tipo(name) || super
end
end
|
namespace :edu do
task :default => :docker
EDU_DOCKER_DIR = "#{DOCKER_DIR}/edu"
task :docker => [:clean,:install] do
task('docker:mk').reenable
task('docker:mk').invoke(EDU_DOCKER_DIR.split('/').last)
end
task :install do
Dir.chdir PROJ_DIR do
['dev:clean', 'dev:all', "dev:install[#{EDU_DOCKER_DIR}]"].each do |t|
sh "bundle exec rake #{t}"
sh "cp #{ETC_DIR}/edu.yml #{EDU_DOCKER_DIR}"
end
end
end
task :clean => 'dev:clean' do
Dir.chdir EDU_DOCKER_DIR do
sh "rm -f edu edu.yml"
end
end
end
|
module Rails
module Rack
module Log
class Level
class RuleSet
attr_reader :rules
def initialize(options = {})#:nodoc:
@rules = []
end
protected
def add_rule(condition, options = {}) #:nodoc:
@rules << Rule.new(condition, options)
end
end
end
end
end
end
|
require "rails_helper"
RSpec.feature "用户可以将商品添加到购物车" do
# given(:product) { FactoryGirl.create(:product, name: "电水壶", price: 50) }
given(:user) { FactoryGirl.create(:user) }
scenario "如果正确填写商品数量" do
FactoryGirl.create(:product, name: "电水壶", price: 50)
login_as(user)
visit "/"
click_link "电水壶"
fill_in "Goods amount", with: "5"
click_button "Add to cart"
expect(page).to have_content "商品已经成功加入购物车"
end
# scenario "when providing invalid attributes" do
# click_button "Create Project"
# expect(page).to have_content "Project has not been created."
# expect(page).to have_content "Name can't be blank"
# end
end
|
#!/bin/env ruby
require 'yaml'
def parse_body(body, &blk)
@body_sep = "%"
lines = []
body.split(@body_sep).each do |b|
hash = YAML::load(b)
next unless hash
if block_given? then
yield hash
else
lines << b
end
end
lines
end
if __FILE__ == $0 then
#srand(99)
File.open("log.txt", "a") do |log|
parse_body(ARGF.read) do |specifics|
#specifics.keys.sort_by{rand}.each do |k|
specifics.each do |k,v|
v = specifics[k]
opcnt = rand 1000
puts "#{k}|#{opcnt}|#{v}"
log.puts "#{k}|#{opcnt}|#{v}"
end
puts "%"
end
end
end
|
# spec/requests/todos_spec.rb
require 'rails_helper'
RSpec.describe 'Pages API', type: :request do
# initialize test data
let!(:pages) { create_list(:page, 10) }
let(:page_id) { pages.first.id }
# Test suite for GET /pages
describe 'GET /pages' do
# make HTTP get request before each example
before { get '/pages' }
it 'returns pages' do
# Note `json` is a custom helper to parse JSON responses
expect(json).not_to be_empty
expect(json.size).to eq(10)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for GET /pages/:id
describe 'GET /pages/:id' do
before { get "/pages/#{page_id}" }
context 'when the record exists' do
it 'returns the page' do
expect(json).not_to be_empty
expect(json['id']).to eq(page_id)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when the record does not exist' do
let(:page_id) { 100 }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns a not found message' do
expect(response.body).to match(/Couldn't find Page/)
end
end
end
# Test suite for POST /pages
describe 'POST /pages' do
# valid payload
let(:valid_attributes) { { url: 'https://www.google.com' } }
context 'when the request is valid' do
before { post '/pages', params: valid_attributes }
it 'creates a page' do
expect(json['url']).to eq('https://www.google.com')
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/pages', params: { url: 'Foobar' } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
expect(response.body)
.to match(/Validation failed: Url is not valid/)
end
end
end
# Test suite for DELETE /todos/:id
describe 'DELETE /pages/:id' do
before { delete "/pages/#{page_id}" }
it 'returns status code 204' do
expect(response).to have_http_status(204)
end
end
end |
module Authenticable
def current_user
# if there is a current user return the user
return @current_user if @current_user
# check the request header to get the token
# from Authorization
header = request.headers['Authorization']
header = header.split(' ').last if header
begin
# token decode
@decoded = JsonWebToken.decode(header)
# get user id from token
@current_user = User.find(@decoded[:user_id])
# if record not found return error
rescue ActiveRecord::RecordNotFound => e
render json: { errors: e.message, msg: 'record not found' }, status: :unauthorized
# if record found and error with token return error
rescue JWT::DecodeError => e
render json: { errors: e.message, msg: 'Token Error: Check token' }, status: :unauthorized
end
end
def check_login
#make current_user global
head :forbidden unless self.current_user
end
end |
class CreateDefaultSectionsForExistingIssues < ActiveRecord::Migration
class Issue < ActiveRecord::Base
has_many :sections
end
class Section < ActiveRecord::Base
belongs_to :issue
end
def up
Issue.find_each do |issue|
section = issue.sections.create(default: true)
connection.update(<<-SQL)
UPDATE articles SET section_id = #{section.id} WHERE issue_id = #{issue.id}
SQL
end
end
def down
Section.include(:issue).find_each do |section|
issue = section.issue
connection.update(<<-SQL)
UPDATE articles SET issue_id = #{issue.id} WHERE section_id = #{section.id}
SQL
end
end
end
|
class Manager < ActiveRecord::Base
has_many :custom_requests, class_name: "TaskMaster::CustomRequest", as: :requestor
end
|
require 'cloudformation_mapper/resource'
class CloudformationMapper::Resource::AwsResourceCloudtrailTrail < CloudformationMapper::Resource
register_type 'AWS::CloudTrail::Trail'
type 'Template'
parameter do
type 'Template'
name :Properties
parameter do
type 'Boolean'
name :IncludeGlobalServiceEvents
end
parameter do
type 'Boolean'
name :IsLogging
end
parameter do
type 'String'
name :S3BucketName
end
parameter do
type 'String'
name :S3KeyPrefix
end
parameter do
type 'String'
name :SnsTopicName
end
end
parameter do
type 'Template'
name :Outputs
end
end
|
module FeatureMacros
def register_with(email, password)
visit "/users/sign_up"
fill_in "user_email", :with => email
fill_in "user_password", :with => password
fill_in "user_password_confirmation", :with => password
click_button "Sign up"
expect(page).to have_text("A message with a confirmation link has been sent to your email address.")
expect(page).to have_text("Please follow the link to activate your account.")
end
def confirm_email(email)
mails = ActionMailer::Base.deliveries
mail = mails.last
expect(mail.to).to eq([email])
expect(mail.subject).to eq('Confirmation instructions')
body = mail.body.to_s
matchh = body.match(/.*(http:\/\/.*)".*/)
confirmation_url = matchh[1]
visit confirmation_url
expect(page).to have_text("Your email address has been successfully confirmed.")
end
def sign_in_with(email, password, options = {})
fill_in "user_email", :with => email
fill_in "user_password", :with => password
click_button "Log in"
user = User.where(email: email).first
welcome_message = options[:welcome_message] || (user.user_profile.present? ? "Welcome back #{user.user_profile.first_name}." : "Welcome #{user.email}")
expect(page).to have_text(welcome_message)
end
def fill_in_family_form_and_create_family
fill_in 'family_address', :with => '123 Main St'
fill_in 'family_city', :with => 'Chicago'
select 'Illinois', :from => 'family_state'
fill_in 'family_zip', :with => '60606'
click_button 'Create family'
end
def create_profile_with(params)
fill_profile_form_with(params)
click_button "Create my profile"
expect(page).to have_text("User profile created.")
end
def add_family_member(params)
fill_profile_form_with(params)
click_button "Add new member"
expect(page).to have_text("User profile created.")
end
def fill_profile_form_with(params)
fill_in "user_profile_first_name", :with => params[:first_name]
fill_in "user_profile_last_name", :with => params[:last_name]
fill_in "user_profile_date_of_birth", :with => params[:date_of_birth]
end
def finish_paypal_payment
paypal_window = window_opened_by do
within_frame(page.find("#braintree-dropin-frame")) do
find("#braintree-paypal-button").click
end
end
within_window paypal_window do
click_link "Proceed with Sandbox Purchase"
end
sleep(1)
click_button "Pay now"
end
end
|
class AddInChatToUsers < ActiveRecord::Migration
def change
add_column :users, :in_chat, :boolean
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
groceries = Grocery.create([
{title: "Carrots", description: "Green giant."},
{title: "Celery", description: "Ore-Ida."},
{title: "Wine", description: "Silverado Vineyards"},
{title: "Toothpaste", description: "Colgate"},
{title: "Cheese", description: "Parmesan."}
]) |
require 'spec_helper'
require 'app/models/config/base'
require 'app/models/config/eslint'
describe Config::Eslint do
it_behaves_like 'a service based linter' do
let(:raw_config) do
<<-EOS.strip_heredoc
rules:
quotes: [2, "double"]
EOS
end
let(:hound_config_content) do
{
'eslint' => {
'enabled' => true,
'config_file' => 'config/.eslintrc'
}
}
end
end
end
|
require 'rockpaperscissors'
describe Rockpaperscissors do
describe 'returns winner' do
it 'rock is beaten by paper' do
expect(subject.winner('Bob', :rock, 'Alice', :paper)).to eq("Alice")
end
it 'rock is beaten by spock' do
expect(subject.winner('Bob', :rock, 'Alice', :spock)).to eq("Alice")
end
it 'scissors is beaten by rock' do
expect(subject.winner('Bob', :rock, 'Alice', :scissors)).to eq("Bob")
end
it 'scissors is beaten by spock' do
expect(subject.winner('Bob', :spock, 'Alice', :scissors)).to eq("Bob")
end
it 'paper is beaten by scissors' do
expect(subject.winner('Bob', :paper, 'Alice', :scissors)).to eq("Alice")
end
it 'paper is beaten by lizard' do
expect(subject.winner('Bob', :paper, 'Alice', :lizard)).to eq("Alice")
end
it 'lizard is beaten by scissors' do
expect(subject.winner('Bob', :scissors, 'Alice', :lizard)).to eq("Bob")
end
it 'lizard is beaten by rock' do
expect(subject.winner('Bob', :rock, 'Alice', :lizard)).to eq("Bob")
end
it 'spock is beaten by lizard' do
expect(subject.winner('Bob', :spock, 'Alice', :lizard)).to eq("Alice")
end
it 'spock is beaten by paper' do
expect(subject.winner('Bob', :spock, 'Alice', :paper)).to eq("Alice")
end
end
describe 'returns draw' do
it 'returns :draw if players choose same' do
expect(subject.winner('Bob', :rock, 'Alice', :rock)).to eq(:draw)
end
end
end
|
require "open3"
require_relative "vars"
# Scenario: Install dependencies
When(/^I install dependencies$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'setup'"
output, error, @status = Open3.capture3 "#{cmd}"
end
Then(/^it should be successful$/) do
expect(@status.success?).to eq(true)
end
# Scenario: Configure automysqlbackup
When(/^I configure automysqlbackup$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'automysqlbackup_config'"
output, error, @status = Open3.capture3 "#{cmd}"
end
# Scenario: Create S3 Bucket
When(/^I create S3 Bucket$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'create_s3'"
output, error, @status = Open3.capture3 "#{cmd}"
end
And(/^the bucket should exists on AWS$/) do
cmd = "aws s3 ls | grep #{BUCKETNAME}"
output, error, status = Open3.capture3 "#{cmd}"
expect(status.success?).to eq(true)
expect(output).to match("#{BUCKETNAME}")
end
# Scenario: Encrypt the S3 bucket with a bucket policy
When(/^I encrypt the S3 bucket with a bucket policy$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'encrypt_s3'"
output, error, @status = Open3.capture3 "#{cmd}"
end
# Scenario: Copy backup bash script to remote server
When(/^I copy backup bash script to remote server$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'copy_bash'"
output, error, @status = Open3.capture3 "#{cmd}"
end
And(/^the script should exists on the remote server$/) do
cmd = "ssh -i '#{PATHTOKEY}' #{PUBDNS} 'sudo ls | grep bash.sh'"
output, error, status = Open3.capture3 "#{cmd}"
expect(status.success?).to eq(true)
expect(output).to match("bash.sh")
end
# Scenario: Run cron job to set up recurring local and remote backups
When(/^I run cron job to set up recurring local and remote backups$/) do
cmd = "ansible-playbook playbook.backup.yml -i host.ini --private-key=#{PATHTOKEY} --tags 'cron_job'"
output, error, @status = Open3.capture3 "#{cmd}"
end
|
class User < ApplicationRecord
has_secure_password
mount_uploader :avatar, AvatarUploader
end
|
class BidItem < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
belongs_to :organizer
# 全文检索
mapping do
indexes :id, :index => :not_analyzed
indexes :title, :analyzer => 'ik'
indexes :organizer_id, :index => :not_analyzed
indexes :auction_id, :index => :not_analyzed
indexes :lot
indexes :description, :analyzer => 'ik'
indexes :condition
indexes :start_at, :type => 'date'
indexes :end_at, :type => 'date'
indexes :status
indexes :est_price_low
indexes :est_price_high
indexes :realized_price
indexes :winner
indexes :loser
indexes :is_online
indexes :small_img
indexes :medium_img
indexes :big_img
indexes :source_url
indexes :topic_name
indexes :organizer_name
indexes :created_at, :type => 'date'
indexes :updated_at, :type => 'date'
indexes :organizer do
indexes :short_name, :index => :not_analyzed
end
end
def to_indexed_json
self.to_json({:include => {:organizer => {:only => :short_name}}})
end
def self.index_search(keyword, per_page, page, short_name = nil)
BidItem.search(:per_page => per_page, :page => page) do
query do
string keyword, :default_field => "title"
end
if short_name.present?
filter :term, 'organizer.short_name' => short_name
end
highlight :title, :options => {:tag => "<label class='keywords'>"}
facet 'organizer' do
terms 'organizer.short_name'
end
#sort { by :start_at ,'desc'}
end
end
end
|
# Set correct `contributor` for all patreon users
module Users
class SetPatreonContributorsService
def initialize(patron_ids)
@patron_ids = patron_ids
end
def perform
User.where(provider: 'patreon').each do |user|
user.update(contributor: @patron_ids.include?(user.uid))
end
end
end
end
|
require_relative "piece"
require_relative "board"
class Bishop < Piece
attr_accessor :pos, :board, :color
include Slideable
def initialize(symbol,board,pos)
@color = symbol
@board = board
@pos = pos
end
def move_dirs
dirs = self.diagonal_dirs
possible_move = []
i = 0
until i > 7
dirs.each do |dir|
row, col = dir
possible_move << self.pos.grow_unblocked_moves_in_dir(row,col)
end
i += 1
end
possible_move.select { |coor| @board.valid_pos?(coor) }
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.