text stringlengths 10 2.61M |
|---|
class CaptionsController < ApplicationController
before_action :authenticate_user!
# board_pin_captions GET /boards/:board_id/pins/:pin_id/captions(.:format) captions#index
# POST /boards/:board_id/pins/:pin_id/captions(.:format) captions#create
# new_board_pin_caption GET /boards/:board_id/pins/:pin_id/captions/new(.:format) captions#new
# edit_board_pin_caption GET /boards/:board_id/pins/:pin_id/captions/:id/edit(.:format) captions#edit
# board_pin_caption GET /boards/:board_id/pins/:pin_id/captions/:id(.:format) captions#show
# PATCH /boards/:board_id/pins/:pin_id/captions/:id(.:format) captions#update
# PUT /boards/:board_id/pins/:pin_id/captions/:id(.:format) captions#update
# DELETE /boards/:board_id/pins/:pin_id/captions/:id(.:format) captions#destroy
def index
@board = Board.find(params[:board_id])
redirect_to board_path(@board)
end
def create
@board = Board.find(params[:board_id])
@pin = @board.pins.find(params[:pin_id])
@caption = Caption.find_or_create_by(caption_params)
existing_tag = Tag.find_by(pin: @pin, user:current_user.id, caption:@caption)
unless existing_tag
Tag.create(pin:@pin,user:current_user,caption:@caption)
end
redirect_to board_path(@board)
end
def new
@board = Board.find(params[:board_id])
@pin = @board.pins.find(params[:pin_id])
@board = Board.find(params[:board_id])
@caption = Caption.new
end
private
def caption_params
params.require(:caption).permit(:body)
end
end
|
require 'javaclass/classfile/attributes/attributes'
module JavaClass
module ClassFile
# Container of the fields - skips the fields for now.
# Author:: Peter Kofler
class Fields # :nodoc:
# Size of the whole fields structure in bytes.
attr_reader :size
# Parse the field structure from the bytes _data_ beginning at position _start_.
def initialize(data, start, constant_pool)
count = data.u2(start)
@size = 2
(1..count).each do |i|
# TODO Implement parsing of fields into Field class
# access_flags = data.u2(start + @size) # later ... FieldAccessFlag.new(data, start + @size)
# @size += 2
# name_index = data.u2(start + @size) # later ... get from ConstantPool
# @size += 2
# descriptor_index = data.u2(start + @size) # later ... get from ConstantPool
# @size += 2
@size += 6
attributes = Attributes::Attributes.new(data, start + @size, constant_pool)
@size += attributes.size
end
end
end
end
end
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'pcp-client/version'
Gem::Specification.new do |s|
s.name = 'pcp-client'
s.version = PCPClient::VERSION
s.licenses = ['ASL 2.0']
s.summary = "Client library for PCP"
s.description = "See https://github.com/puppetlabs/pcp-specifications"
s.homepage = 'https://github.com/puppetlabs/ruby-pcp-client'
s.authors = ["Puppet Labs"]
s.email = "puppet@puppetlabs.com"
s.executables = ["pcp-ping"]
s.files = Dir["lib/**/*.rb"]
s.add_runtime_dependency 'eventmachine', '~> 1.2'
s.add_runtime_dependency 'faye-websocket', '~> 0.11.0'
s.add_runtime_dependency 'rschema', '~> 1.3'
end
|
require_relative "oystercard"
class Journey
PENALTY_FARE = 6
NORMAL_FARE = 1
attr_reader :entry_station
def initialize(entry_station:)
@entry_station = entry_station
@completed_journey = false
end
def complete?
if @completed_journey == true
return true
else
return false
end
end
def fare
if @completed_journey == true
@completed_journey = false
return NORMAL_FARE
else
return PENALTY_FARE
end
end
def finish(station)
@completed_journey = true
self
end
end
|
#To delete
module Api::V1
class UsersController < Api::V1::BaseController
private
def user_params
params.require(:user).permit(:name, :lastname, :email, :address, :phone, :authentication_token, :district)
end
def query_params
params.permit(:name, :lastname, :email, :district_id, :token)
end
end
end
|
class Api::V1::LinksController < Api::ApiController
respond_to :json
def index
user = current_user
respond_with user.links.order('id')
end
def show
user = User.find(params[:id])
respond_with user.links.find(params[:link][:id])
end
def create
user = current_user
link = user.links.create(link_params)
if link.save
respond_with link
end
end
def destroy
user = User.find(params[:id])
respond_with status: 204 if user.links.delete(params[:id])
end
def update
link = Link.find(params[:link][:id])
respond_with link.update(link_params)
end
private
def link_params
params.require(:link).permit(:id, :title, :url, :read, :user_id)
end
end
|
module NetAppSdk
class NFS < Filer
def self.on
nfs_on = @@filer.invoke("nfs-enable")
raise nfs_on.results_reason \
if nfs_on.results_status == 'failed'
return true
end
def self.off
nfs_off = @@filer.invoke("nfs-disable")
raise nfs_off.results_reason \
if nfs_off.results_status == 'failed'
return true
end
def self.add_export(pathname, type, anon=false, nosuid=false, allhosts=false, exports)
#
# - type = read-only || read-write || root
# - exports = string (hostname, IP, subnet [CIDR])
raise "unkown argument in type" unless type == "read-only" or \
type == "read-write" or \
type == "root"
raise "empty pathname" if pathname.empty?
nfs_exports_rule_info = NaElement.new("exports-rule-info")
nfs_exports_rule_info.child_add_string("anon", anon) if anon
nfs_exports_rule_info.child_add_string("nosuid", nosuid) if nosuid
nfs_exports_rule_info.child_add_string("pathname", pathname)
nfs_exports = NaElement.new(type)
nfs_exports_host = NaElement.new("exports-hostname-info")
nfs_exports_host.child_add_string("all-hosts", true) if allhosts == true
nfs_exports_host.child_add_string("name", exports) if exports
nfs_exports.child_add(nfs_exports_host)
nfs_exports_rule_info.child_add(nfs_exports)
nfs_rules = NaElement.new("rules")
nfs_rules.child_add(nfs_exports_rule_info)
nfs_exports_invoke = NaElement.new("nfs-exportfs-append-rules")
nfs_exports_invoke.child_add(nfs_rules)
nfs_exports_invoke.child_add_string("verbose", true)
nfs_add_export = @@filer.invoke_elem(nfs_exports_invoke)
raise nfs_add_export.results_reason \
if nfs_add_export.results_status == 'failed'
return true
end
def self.del_export(pathname)
nfs_exports_path_del = NaElement.new("pathname-info")
nfs_exports_path_del.child_add_string("name", pathname)
nfs_pathnames = NaElement.new("pathnames")
nfs_pathnames.child_add(nfs_exports_path_del)
nfs_exports_invoke = NaElement.new("nfs-exportfs-delete-rules")
nfs_exports_invoke.child_add(nfs_pathnames)
nfs_exports_invoke.child_add_string("verbose", true)
nfs_del_export = @@filer.invoke_elem(nfs_exports_invoke)
raise nfs_del_export.results_reason \
if nfs_del_export.results_status == 'failed'
return true
end
def self.status
nfs_status = @@filer.invoke("nfs-status")
raise nfs_status.results_reason \
if nfs_status.results_status == 'failed'
return result = {
isdrained: nfs_status.child_get_string("is-drained"),
isenabled: nfs_status.child_get_string("is-enabled")
}
end
end
end
|
ENV["RAILS_ENV"] ||= 'test'
require 'simplecov'
SimpleCov.start 'rails'
require 'rubygems'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'thinking_sphinx/test'
require 'database_cleaner'
require 'webmock/rspec'
require 'capybara/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Dir[Rails.root.join("spec/fixtures/db/*.rb")].each { |f| require f }
Dir[Rails.root.join("spec/fixtures/models/*.rb")].each { |f| require f }
WebMock.disable_net_connect!
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = true
config.filter_run focus: true
config.run_all_when_everything_filtered = true
config.order = 'random'
config.include ActionView::TestCase::Behavior, example_group: { file_path: %r{spec/presenters} }
config.include FactoryGirl::Syntax::Methods
config.include ThinkingSphinxHelpers
config.include RemoteStubs
config.include PresenterHelper
config.include DatePathHelper
config.include StubPublishingCallbacks
config.include AudioCleanup
config.include FormFillers, type: :feature
config.include AuthenticationHelper, type: :feature
config.before :suite do
DatabaseCleaner.clean_with :truncation
load "#{Rails.root}/db/seeds.rb"
DatabaseCleaner.strategy = :transaction
migration = -> { FixtureMigration.new.up }
silence_stream STDOUT, &migration
FileUtils.rm_rf Rails.application.config.scpr.media_root.join("audio/upload")
ThinkingSphinx::Test.init
ThinkingSphinx::Test.start_with_autostop
end
config.before type: :feature do
DatabaseCleaner.strategy = :truncation, { except: STATIC_TABLES }
end
config.before :all do
DeferredGarbageCollection.start
end
config.before :each do
WebMock.reset!
stub_request(:get, %r|a\.scpr\.org\/api\/outputs|).to_return({
:body => load_fixture("api/assethost/outputs.json"),
:content_type => "application/json"
})
stub_request(:get, %r|a\.scpr\.org\/api\/assets|).to_return({
:body => load_fixture("api/assethost/asset.json"),
:content_type => "application/json"
})
stub_request(:post, %r|a\.scpr\.org\/api\/assets|).to_return({
:body => load_fixture("api/assethost/asset.json"),
:content_type => "application/json"
})
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
Rails.cache.clear
end
config.after :all do
DeferredGarbageCollection.reconsider
end
config.after :suite do
DatabaseCleaner.clean_with :truncation
end
end
|
module Tournament
def self.begin *fighters
puts "A tournament amoung #{fighters}".yellow
round = 1
while fighters.count > 1
puts "ROUND #{round}".yellow
pairs = fighters.each_slice(2).to_a
pairs.each do |fighter_a, fighter_b|
next if fighter_b.nil?
winning_fighter = Match.new(fighter_a, fighter_b, 0.25).fight
fighters.delete ([fighter_a, fighter_b] - [winning_fighter]).first
puts ""
puts "#{winning_fighter} advances to the next round!".yellow
puts ""
end
round += 1
end
puts "The winner of the tournament is #{fighters.first}".yellow.blink
end
end |
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
@item.image = fixture_file_upload('public/images/test_image.png')
end
describe '商品出品登録' do
it 'すべての値が正しく入力されていれば、登録できる' do
expect(@item).to be_valid
end
it '画像がない場合、登録できない' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
it '商品名の記載がない場合、登録できない' do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it '商品の説明の記載がない場合、登録できない' do
@item.description = ''
@item.valid?
expect(@item.errors.full_messages).to include("Description can't be blank")
end
it 'カテゴリーが選択されていない場合、登録できない' do
@item.category_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include('Category is invalid')
end
it '商品の状態が選択されていない場合、登録できない' do
@item.condition_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include('Condition is invalid')
end
it '配送料の負担が選択されていない場合、登録できない' do
@item.shipping_payer_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include('Shipping payer is invalid')
end
it '発送元の地域が選択されていない場合、登録できない' do
@item.shipping_from_area_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include('Shipping from area is invalid')
end
it '発送までの日数が選択されていない場合、登録できない' do
@item.shipping_duration_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include('Shipping duration is invalid')
end
it '価格の記載がない場合、登録できない' do
@item.price = ''
@item.valid?
expect(@item.errors.full_messages).to include("Price can't be blank")
end
it '価格が¥300未満の場合、登録できない' do
@item.price = '299'
@item.valid?
expect(@item.errors.full_messages).to include('Price must be greater than 299')
end
it '価格が¥10000000以上の場合、登録できない' do
@item.price = '10000000'
@item.valid?
expect(@item.errors.full_messages).to include('Price must be less than 10000000')
end
it '価格が半角数字以外の場合、登録できない' do
@item.price = '1000'
@item.valid?
expect(@item.errors.full_messages).to include('Price is not a number')
end
end
end
|
class CreateRecipeIngredientsUnits < ActiveRecord::Migration
def change
create_table :recipe_ingredients_units do |t|
t.string :ingredient_unit_name
t.timestamps null: false
end
end
end
|
class RemoveColumnsFromChurches < ActiveRecord::Migration
def change
remove_column :churches, :incumbent_name
remove_column :churches, :incumbent_age
add_column :people, :age, :integer
add_column :people, :age_approx, :boolean
end
end
|
class Triangle
# write code here
attr_accessor :side_a, :side_b, :side_c
def initialize(s_a, s_b, s_c)
@side_a = s_a
@side_b = s_b
@side_c = s_c
end
def kind
if (@side_a <= 0) || (@side_b <= 0) || (@side_c <= 0)
raise TriangleError
elsif (@side_a + @side_b <= @side_c) || (@side_a + @side_c <= @side_b) || (@side_b + @side_c <= @side_a)
raise TriangleError
else
if((@side_a == @side_b) && (@side_b == @side_c))
:equilateral
elsif((@side_a == @side_b) || (@side_b == @side_c) || (@side_c == @side_a))
:isosceles
else
:scalene
end
end
end
class TriangleError < StandardError
def message
"illegal traingle"
end
end
end
|
# Copyright:: Copyright (c) 2014 eGlobalTech, Inc., all rights reserved
#
# Licensed under the BSD-3 license (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the root of the project or at
#
# http://egt-labs.com/mu/LICENSE.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module MU
class Cloud
class AWS
# Support for AWS SNS
class Notifier < MU::Cloud::Notifier
# Initialize this cloud resource object. Calling +super+ will invoke the initializer defined under {MU::Cloud}, which should set the attribtues listed in {MU::Cloud::PUBLIC_ATTRS} as well as applicable dependency shortcuts, like +@vpc+, for us.
# @param args [Hash]: Hash of named arguments passed via Ruby's double-splat
def initialize(**args)
super
@mu_name ||= @deploy.getResourceName(@config["name"])
end
# Called automatically by {MU::Deploy#createResources}
def create
MU::Cloud::AWS.sns(region: @config['region'], credentials: @config['credentials']).create_topic(name: @mu_name)
@cloud_id = @mu_name
MU.log "Created SNS topic #{@mu_name}"
end
# Called automatically by {MU::Deploy#createResources}
def groom
if @config['subscriptions']
@config['subscriptions'].each { |sub|
MU::Cloud::AWS::Notifier.subscribe(
arn: arn,
endpoint: sub['endpoint'],
region: @config['region'],
credentials: @config['credentials'],
protocol: sub['type']
)
}
end
end
# Does this resource type exist as a global (cloud-wide) artifact, or
# is it localized to a region/zone?
# @return [Boolean]
def self.isGlobal?
false
end
# Denote whether this resource implementation is experiment, ready for
# testing, or ready for production use.
def self.quality
MU::Cloud::BETA
end
# Remove all notifiers associated with the currently loaded deployment.
# @param noop [Boolean]: If true, will only print what would be done
# @param ignoremaster [Boolean]: If true, will remove resources not flagged as originating from this Mu server
# @param region [String]: The cloud provider region
# @return [void]
def self.cleanup(noop: false, ignoremaster: false, region: MU.curRegion, credentials: nil, flags: {})
MU.log "AWS::Notifier.cleanup: need to support flags['known']", MU::DEBUG, details: flags
MU.log "Placeholder: AWS Notifier artifacts do not support tags, so ignoremaster cleanup flag has no effect", MU::DEBUG, details: ignoremaster
MU::Cloud::AWS.sns(region: region, credentials: credentials).list_topics.topics.each { |topic|
if topic.topic_arn.match(MU.deploy_id)
# We don't have a way to tag our SNS topics, so we will delete any topic that has the MU-ID in its ARN.
# This may fail to find notifier groups in some cases (eg. cache_cluster) so we might want to delete from each API as well.
MU.log "Deleting SNS topic: #{topic.topic_arn}"
if !noop
MU::Cloud::AWS.sns(region: region, credentials: credentials).delete_topic(topic_arn: topic.topic_arn)
end
end
}
end
# Canonical Amazon Resource Number for this resource
# @return [String]
def arn
@cloud_id ||= @mu_name
"arn:"+(MU::Cloud::AWS.isGovCloud?(@config["region"]) ? "aws-us-gov" : "aws")+":sns:"+@config['region']+":"+MU::Cloud::AWS.credToAcct(@config['credentials'])+":"+@cloud_id
end
# Return the metadata for this user cofiguration
# @return [Hash]
def notify
desc = MU::Cloud::AWS.sns(region: @config["region"], credentials: @config["credentials"]).get_topic_attributes(topic_arn: arn).attributes
MU.structToHash(desc)
end
# Locate an existing notifier.
# @return [Hash<String,OpenStruct>]: The cloud provider's complete descriptions of matching notifier.
def self.find(**args)
found = {}
if args[:cloud_id]
arn = "arn:"+(MU::Cloud::AWS.isGovCloud?(args[:region]) ? "aws-us-gov" : "aws")+":sns:"+args[:region]+":"+MU::Cloud::AWS.credToAcct(args[:credentials])+":"+args[:cloud_id]
desc = MU::Cloud::AWS.sns(region: args[:region], credentials: args[:credentials]).get_topic_attributes(topic_arn: arn).attributes
found[args[:cloud_id]] = desc if desc
else
next_token = nil
begin
resp = MU::Cloud::AWS.sns(region: args[:region], credentials: args[:credentials]).list_topics(next_token: next_token)
if resp and resp.topics
resp.topics.each { |t|
found[t.topic_arn.sub(/.*?:([^:]+)$/, '\1')] = MU::Cloud::AWS.sns(region: args[:region], credentials: args[:credentials]).get_topic_attributes(topic_arn: t.topic_arn).attributes
}
end
next_token = resp.next_token
end while next_token
end
found
end
# Cloud-specific configuration properties.
# @param _config [MU::Config]: The calling MU::Config object
# @return [Array<Array,Hash>]: List of required fields, and json-schema Hash of cloud-specific configuration parameters for this resource
def self.schema(_config)
toplevel_required = []
schema = {
"subscriptions" => {
"type" => "array",
"items" => {
"type" => "object",
"required" => ["endpoint"],
"properties" => {
"type" => {
"type" => "string",
"description" => "",
"enum" => ["http", "https", "email", "email-json", "sms", "sqs", "application", "lambda"]
}
}
}
}
}
[toplevel_required, schema]
end
# Cloud-specific pre-processing of {MU::Config::BasketofKittens::notifier}, bare and unvalidated.
# @param notifier [Hash]: The resource to process and validate
# @param _configurator [MU::Config]: The overall deployment configurator of which this resource is a member
# @return [Boolean]: True if validation succeeded, False otherwise
def self.validateConfig(notifier, _configurator)
ok = true
if notifier['subscriptions']
notifier['subscriptions'].each { |sub|
if !sub["type"]
if sub["endpoint"].match(/^http:/i)
sub["type"] = "http"
elsif sub["endpoint"].match(/^https:/i)
sub["type"] = "https"
elsif sub["endpoint"].match(/^sqs:/i)
sub["type"] = "sqs"
elsif sub["endpoint"].match(/^\+?[\d\-]+$/)
sub["type"] = "sms"
elsif sub["endpoint"].match(/\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
sub["type"] = "email"
else
MU.log "Notifier #{notifier['name']} subscription #{sub['endpoint']} did not specify a type, and I'm unable to guess one", MU::ERR
ok = false
end
end
}
end
ok
end
# Subscribe to a notifier group. This can either be an email address, SQS queue, application endpoint, etc...
# Will create the subscription only if it doesn't already exist.
# @param arn [String]: The cloud provider's identifier of the notifier group.
# @param protocol [String]: The type of the subscription (eg. email,https, etc..).
# @param endpoint [String]: The endpoint of the subscription. This will depend on the 'protocol' (as an example if protocol is email, endpoint will be the email address) ..
# @param region [String]: The cloud provider region.
def self.subscribe(arn: nil, protocol: nil, endpoint: nil, region: MU.curRegion, credentials: nil)
retries = 0
begin
resp = MU::Cloud::AWS.sns(region: region, credentials: credentials).list_subscriptions_by_topic(topic_arn: arn).subscriptions
rescue Aws::SNS::Errors::NotFound
if retries < 5
MU.log "Couldn't find topic #{arn}, retrying several times in case of a lagging resource"
retries += 1
sleep 30
retry
else
raise MuError, "Couldn't find topic #{arn}, giving up"
end
end
already_subscribed = false
if resp && !resp.empty?
resp.each { |subscription|
already_subscribed = true if subscription.protocol == protocol && subscription.endpoint == endpoint
}
end
unless already_subscribed
MU::Cloud::AWS.sns(region: region, credentials: credentials).subscribe(topic_arn: arn, protocol: protocol, endpoint: endpoint)
MU.log "Subscribed #{endpoint} to SNS topic #{arn}"
end
end
# Test if a notifier group exists
# Create a new notifier group. Will check if the group exists before creating it.
# @param topic_name [String]: The cloud provider's name for the notifier group.
# @param region [String]: The cloud provider region.
# @param account_number [String]: The cloud provider account number.
# @return [string]: The cloud provider's identifier.
def self.topicExist(topic_name, region: MU.curRegion, account_number: MU.account_number, credentials: nil)
arn = "arn:#{MU::Cloud::AWS.isGovCloud?(region) ? "aws-us-gov" : "aws"}:sns:#{region}:#{account_number}:#{topic_name}"
match = nil
MU::Cloud::AWS.sns(region: region, credentials: credentials).list_topics.topics.each { |topic|
if topic.topic_arn == arn
match = topic.topic_arn
break
end
}
return match
end
end
end
end
end
|
require_relative '../models/book'
require_relative '../views/books_view'
require_relative '../controllers/users_controller'
require 'erb'
class BooksController
class << self
attr_accessor :isbn, :option
def find
BooksView.ask_for_isbn
book = Book.find_by_isbn @isbn
BooksView.display_book(book)
end
def sort
BooksView.ask_for_option
if(option == "1")
Book.order(year: :desc)
else
Book.order(rating: :desc)
end
end
def all_books
books = Book.all
BooksView.display_books(books)
end
def all_books_web(argument)
case argument
when 'books'
@books = Book.all
erb = ERB.new(File.open("#{__dir__}/../views/index.html.erb").read, 0, '>')
erb.result binding
when 'sort_by_year'
@books = Book.order(year: :desc)
erb = ERB.new(File.open("#{__dir__}/../views/index.html.erb").read, 0, '>')
erb.result binding
when 'sort_by_rating'
@books = Book.order(rating: :desc)
erb = ERB.new(File.open("#{__dir__}/../views/index.html.erb").read, 0, '>')
erb.result binding
end
end
def find_book_web(isbn)
@book = Book.find_by_isbn isbn
if @book
erb = ERB.new(File.open("#{__dir__}/../views/show.html.erb").read, 0, '>')
erb.result binding
else
erb = ERB.new(File.open("#{__dir__}/../views/404.html.erb").read, 0, '>')
erb.result binding
end
end
def not_found
erb = ERB.new(File.open("#{__dir__}/../views/404.html.erb").read, 0, '>')
erb.result binding
end
end
end |
# frozen_string_literal: true
ActiveAdmin.register Category do
menu parent: 'Configuration'
permit_params :name
end
|
class TextMessage < ApplicationRecord
belongs_to :account
belongs_to :user, optional: true
belongs_to :to_contact, class_name: "Contact", foreign_key: "to_contact_id"
belongs_to :from_contact, class_name: "Contact", foreign_key: "from_contact_id"
scope :within_this_month, -> { where(created_at: DateTime.now.beginning_of_month..DateTime.now.end_of_month) }
def self.for_to_or_from_contact(contact)
where(from_contact: contact).or(where(to_contact: contact))
end
def self.latest_threads(account)
sql = <<SQL
SELECT m1.*
FROM
text_messages m1
LEFT JOIN text_messages m2
ON (m1.to_contact_id = m2.to_contact_id
AND m1.created_at < m2.created_at)
WHERE m2.id IS NULL
AND m1.account_id = :account_id
ORDER BY m1.created_at DESC
SQL
find_by_sql [sql, account_id: account.id]
end
end |
require 'spec_helper'
describe 'LayoutLinks' do
it 'should have the right title' do
visit root_path
page.should have_title('Splash')
end
it 'should have a root link' do
visit root_path
page.should have_link('TF Home', root_path)
end
describe 'when not signed in' do
it 'should have an About link' do
visit root_path
page.should have_link('About', page_path('about'))
end
it 'should have an About page at /about' do
visit('/about')
page.should have_content 'About'
end
it 'should not have a sign out link' do
visit root_path
expect(page).to_not have_link("Sign-out", destroy_user_session_path)
end
it 'should have a User Register link' do
visit root_path
page.should have_link('User Sign Up', new_user_registration_path)
end
it 'should have a Vendor Register link' do
visit root_path
page.should have_link('Vendor Sign Up', new_vendor_registration_path)
end
it 'should have a Sign-in link' do
visit root_path
page.should have_link('User Log in', new_user_session_path)
end
it 'should have a Sign-in link' do
visit root_path
page.should have_link('Vendor Log in', new_vendor_session_path)
end
it 'should have the right links in the layout' do
visit root_path
click_link 'About'
page.should have_content 'About'
end
it 'should have an User sign-in page at /user_login', focus: true do
visit root_path
click_link 'User Log in'
page.should have_content 'User Log in'
page.should have_field 'Email'
page.should have_field 'Password'
page.should have_link 'Forgot password?'
page.should have_unchecked_field 'user[remember_me]'
page.should have_button('Log in', new_user_session_path)
end
it 'should have an Vendor sign-in page at /vendor_login' do
visit root_path
click_link 'Vendor Log in'
page.should have_content 'Vendor Log in'
page.should have_field 'Email'
page.should have_field 'Password'
page.should have_link 'Forgot password?'
page.should have_unchecked_field 'vendor[remember_me]'
page.should have_button('Log in', new_vendor_session_path)
end
it 'should have an User sign-up page at /user_register', focus: true do
visit root_path
click_link 'User Sign Up'
page.should have_content 'User Log in'
page.should have_field 'Email'
page.should have_field 'Password'
page.should have_button('User Sign Up', new_user_registration_path)
page.should have_link('Sign in', new_user_session_path)
page.should have_link "Didn't receive confirmation instructions?"
page.should have_link "Didn't receive unlock instructions?"
end
it 'should have an Vendor sign-up page at /vendor_register' do
visit root_path
click_link 'Vendor Sign Up'
page.should have_field 'Email'
page.should have_field 'Password'
page.should have_button('Vendor Sign Up', new_vendor_registration_path)
page.should have_link('Sign in', new_vendor_session_path)
page.should have_link "Didn't receive confirmation instructions?"
page.should have_link "Didn't receive unlock instructions?"
end
end
describe 'when signed in' do
let(:user) { create(:admin) }
before(:each) do
visit root_path
click_link "SIGN-IN"
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button('Sign in')
end
it 'should redirect to a User profile page' do
expect(page).to have_content("#{user.fullname}")
end
it 'should have the right title on the profile page' do
expect(page).to have_title("Infinitory | People: #{user.fullname}")
end
it 'should have a link to edit the current user' do
expect(page).to have_link("Edit", edit_user_registration_path(user))
end
it 'should not have a link to edit users other than the current user' do
member = create(:user, lab: user.lab, institute: user.institute)
visit user_path(member)
expect(page).to_not have_link("Edit")
end
it 'should have a brand link pointing to their profile page' do
expect(page).to have_link("INFINITORY", user_path(user))
click_link("INFINITORY")
expect(page).to have_title("Infinitory | People: #{user.fullname}")
end
it 'should have a new root path redirecting to the User profile page' do
visit root_path
expect(page).to have_content("#{user.fullname}")
end
it 'should have a Feedback link on the current User profile page' do
get '/'
expect(page).to have_link("Feedback", new_message_path)
end
# it 'should not have a Feedback link on other Users profile pages' do
# get '/'
# expect(page).to have_link("Feedback", new_message_path)
# end
it 'should have a Feedback page at /messages/new' do
get '/messages/new'
expect(page).to have_content('Send feedback')
end
it 'should have an Invitation page at /invitation/new' do
visit new_user_invitation_path
expect(page).to have_content('Invite another scientist or lab member')
end
it 'should have a sign out link' do
visit new_messages_path
expect(page).to have_link("Sign-out", destroy_user_session_path)
end
it 'should not have sign-in or sign-up links at the root path' do
visit root_path
expect(page).to_not have_link('SIGN-IN', new_user_session_path)
expect(page).to_not have_link('Sign up', new_user_registration_path)
end
end
end
|
require 'spec_helper'
describe User do
let(:admin){Factory(:admin)}
describe 'Validations' do
context 'User is valid' do
it 'with all the attributes' do
admin.should be_valid
end
end
context 'User is invalid' do
it 'without a password' do
pending
end
it 'withoud an email' do
admin.email = nil
admin.should_not be_valid
end
it "without a type" do
admin.type = nil
admin.should_not be_valid
end
end
end
end
|
# frozen_string_literal: true
require 'evss/base_service'
module EVSS
class CommonService < BaseService
API_VERSION = Settings.evss.versions.common
BASE_URL = "#{Settings.evss.url}/wss-common-services-web-#{API_VERSION}/rest/"
def create_user_account
post 'persistentPropertiesService/11.0/createUserAccount'
end
def self.breakers_service
BaseService.create_breakers_service(name: 'EVSS/Common', url: BASE_URL)
end
end
end
|
class AsylumController < ApplicationController
def index
@villains = Villain.all
@cart = current_cart
end
end
|
require 'diffy'
require 'term/ansicolor'
module Cli
class Stackscript < Thor
include Formattable
include Term::ANSIColor
include Api::Utils
desc "ls", "List stackscripts (from Linode)"
option :raw, type: :boolean, default: false
def ls
puts Api::Stackscript.list(format)
end
desc "create LABEL", "create a new stackscript"
option :distribution, default: "Ubuntu 16.04 LTS"
option :description, default: "Initial setup (as per http://goo.gl/0GLSrd)"
option :comment, default: "Initial revision"
def create(label)
Api::Stackscript.create(label, options).tap do |response|
puts "Created StackScript \"#{label}\" (ID #{response.stackscriptid})"
end
end
desc "update LABEL", "Push local stackscript changes up to Linode"
option :distribution, default: "Ubuntu 16.04 LTS"
option :description, default: "Initial setup (as per http://goo.gl/0GLSrd)"
option :comment, default: "Revised and uploaded"
def update(label)
Api::Stackscript.update(label, options).tap do |response|
puts "Updated StackScript \"#{label}\" (ID #{response.stackscriptid})"
end
end
desc "rm LABEL", "Delete a stackscript"
def rm(label)
Api::Stackscript.delete(label).tap do |response|
puts "Deleted StackScript \"#{label}\" (ID #{response.stackscriptid})"
end
end
desc "show LABEL", "Display the upstream source code for a stackscript"
def show(label)
puts Api::Stackscript.source_from(label)
end
desc "diff LABEL", "Check status and diff of local vs published versions of a stackscript"
def diff(label)
remote = Api::Stackscript.source_from(label)
local = read_local label
diff = Diffy::Diff.new(remote, local, context: 1).map do |line|
case line
when /^\+/ then green{line}
when /^-/ then red{line}
end
end.join
puts diff.to_s.size == 0 ? "Stackscript #{label} is up to date." : diff
end
end
end
|
module Disable
extend ActiveSupport::Concern
included do
scope :disabled, -> { where.not(disabled_at: nil) }
scope :enabled, -> { where(disabled_at: nil).order(updated_at: :desc) }
belongs_to :owner, class_name: 'User', foreign_key: 'created_user_id', optional: true
belongs_to :modifier, class_name: 'User', foreign_key: 'updated_user_id', optional: true
def enabled?
disabled_at.blank?
end
def disabled?
disabled_at.present?
end
def disabled!
raise RecordAlreadyDisabled, '已删除, 不能再次删除' unless enabled?
ActiveRecord::Base.transaction do
before_disabled
update!(disabled_at: Time.current)
end
end
def enabled!
update!(disabled_at: nil)
end
def before_disabled; end
before_create do
self.created_user_id = PaperTrail.request.whodunnit
end
before_update do
self.updated_user_id = PaperTrail.request.whodunnit
end
before_destroy do
self.updated_user_id = PaperTrail.request.whodunnit
end
end
end
|
class HomeController < ApplicationController
before_filter :set_locale
def set_locale
I18n.locale=params[:locale]
end
def index
@festivals = Festival.all
@artists = Artist.all
end
end |
require 'nokogiri'
class MetadataController < ApplicationController
def new
@doi = params[:doi]
end
def create
endpoint = ENV['ENDPOINT'] + '/metadata'
username = ENV['USERNAME']
password = ENV['PASSWORD']
pem = File.read(ENV['PEM'])
@xml = build_xml
@doi = params[:doi]
response_code = update_remote_metadata(endpoint, build_xml, username, password, pem)
@status = response_status_message(response_code)
end
private
def response_status_message(code)
statuses = {
'201' => 'Created - operation successful',
'400' => 'Bad Request - invalid XML, wrong prefix',
'401' => 'Unauthorized - no login',
'403' => 'Forbidden - login problem, quota exceeded',
'500' => 'Internal Server Error - server internal error, try later'
}
statuses[code]
end
def build_xml
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.resource( 'xmlns' => 'http://datacite.org/schema/kernel-3',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd'
) {
xml.identifier params[:doi], :identifierType => 'DOI'
xml.creators {
params[:creatorName].each do |creatorName|
xml.creator {
xml.creatorName_ creatorName
}
end
}
xml.titles {
xml.title params[:title]
}
xml.publisher params[:publisher]
xml.publicationYear params[:publicationYear]
}
end
builder.to_xml
# xml = ''
# xml += declaration
# xml += root_open
# xml += identifier_open
# xml += params[:doi]
# xml += identifier_close
# xml += root_close
# <creators>
# <creator>
# <creatorName>Khokhar, Masud</creatorName>
# </creator>
# <creator>
# <creatorName>Hartland, Andy</creatorName>
# </creator>
# </creators>
# <titles>
# <title>Library staff page of Masud Khokhar</title>
# </titles>
# <publisher>Lancaster University Library</publisher>
# <publicationYear>2014</publicationYear>
# <subjects>
# <subject>Library</subject>
# <subject>Staff</subject>
# </subjects>
# <language>eng</language>
# <resourceType resourceTypeGeneral="Dataset">Dataset</resourceType>
# <version>1</version>
# <descriptions>
# <description descriptionType="Abstract">Masud is brilliant</description>
# </descriptions>
end
def update_remote_metadata(endpoint, xml, username, password, pem)
uri = URI.parse(endpoint)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
req = Net::HTTP::Post.new(uri)
req.initialize_http_header({'Accept' => 'application/xml;charset=UTF-8'})
req.content_type = 'application/xml;charset=UTF-8'
req.basic_auth username, password
req.body = xml
response = http.request(req)
# @response = response
@debug = true
if @debug
@response_class = response.class
@headers = {}
@headers[:request] = headers(req)
@headers[:response] = headers(response)
end
response.code
if response.code != '201'
redirect_to :back, :flash => { :error => response.code + ' ' + response.body }
return
end
redirect_to :back, :flash => { :notice => params[:doi] + ' metadata successfully updated' }
now = DateTime.now
record = Record.find(BLA)
record.metadata_updated_at = now
record.metadata_updated_by = set_user
record.save
end
def headers(r)
headers_hash = {}
# headers_arr = []
r.each_header do |header_name, header_value|
# headers_arr << "HEADER #{header_name} : #{header_value}"
headers_hash[header_name] = header_value
end
# headers_str = headers_arr.join(' ')
headers_hash
end
def set_user
# not available via WEBrick
request.remote_user
end
end |
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
if @contact.save
flash[:notice] = 'Contact was successfully created!'
respond_to do |format|
format.html { redirect_to :action => 'index' and return }
format.json { render :text => '', :status => :ok and return}
end
else
flash[:error] = 'That contact could not be created. Please try again.'
respond_to do |format|
format.html { render :action => 'new' }
format.json { render :json => @contact.errors.to_json, :status => :unprocessable_entity }
end
end
end
def index
if @search = params[:search]
@contacts = Contact.by_name @search
else
@contacts = Contact.all
end
respond_to do |format|
format.html
format.json { render :json => @contacts.to_json }
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :check_uri
def check_uri
redirect_to request.protocol + request.host_with_port[4..-1] + request.request_uri if /^www/.match(request.host)
end
end |
class Api::V1::ForecastsController < ApplicationController
def index
render json: ForecastSerializer.new(ForecastFacade.new(params[:location]))
# converts forecastfacade to json
end
end
|
class Picture < ActiveRecord::Base
belongs_to :user
mount_uploader :image, ImageUploader
validates :title, presence: true
validates :content, presence: true
validates :image, presence: true
end
|
# Count the number of subsets of {1, 2, ..., n} with reciprical sum strictly
# less than 1.
# A305442
require_relative '../helpers/subset_logic'
require_relative "../helpers/sums_and_differences"
def a(n)
(1..n).to_a.count_subsets do |subset|
subset.map { |i| 1.to_r/i }.reduce(0, :+) < 1
end
end
p (0..15).map { |i| a(i) }.first_differences
|
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'test_helper'
require 'polynomial'
require 'rational' if RUBY_VERSION < '1.9'
class TestPolynomial < Test::Unit::TestCase
def setup
@p = Polynomial.new([1,2,3])
@h = Polynomial.new({0 => 1, 1 => 2, 2 => 3})
end
def test_initialization
assert_equal(@p.coefficients, @h.coefficients)
assert_equal({}, Polynomial.new.coefficients)
assert_equal(0, @p.coefficients[42])
assert_equal(0, @h.coefficients[42])
assert_raise TypeError do
Polynomial.new(:foo)
end
assert_raise TypeError do
Polynomial.new([1,2, :foo])
end
end
def test_assign_value
p = Polynomial.new
p[1] = 1
assert_equal({1 => 1}, p.coefficients)
end
def test_assign_with_zero
p = Polynomial.new
p[1] = 0
assert_equal({}, p.coefficients)
end
def test_equality_of_different_types
assert_equal({0 => 1, 1 => 2, 2 => 3}, @p.coefficients)
assert_equal({0 => 1.0, 1 => 2.0, 2 => 3.0}, @p.coefficients)
assert_equal({0 => Rational(1, 1), 1 => Rational(2, 1), 2 => Rational(3, 1)}, @p.coefficients)
end
def test_remove_zeros
assert_equal({}, Polynomial.new.coefficients)
assert_equal({}, Polynomial.new([0]).coefficients)
assert_equal({}, Polynomial.new([0,0,0]).coefficients)
assert_equal({1 => 2}, Polynomial.new([0, 2, 0]).coefficients)
end
def test_degree
assert_equal(2, @p.degree)
assert_equal(4, Polynomial.new([1,0,0,0,1]).degree)
assert_equal(-Math::INFINITY, Polynomial.new([0]).degree)
assert_equal(-Math::INFINITY, Polynomial.new([0,0,0,0,0]).degree)
assert_equal(0, Polynomial.new([2]).degree)
end
def test_negate
assert_equal({}, Polynomial.new.negate!.coefficients)
assert_equal({0 => -1, 1 => -2, 2 => -3}, @p.negate!.coefficients)
assert_equal({0 => -2}, Polynomial.new([4.0/2.0]).negate!.coefficients)
assert_equal({0 => -1, 1 => -2}, (-Polynomial.new([1,2])).coefficients)
end
def test_get_coefficient
assert_equal(2, @p[1])
end
def test_addition
p1 = Polynomial.new([1,3])
p2 = Polynomial.new([2,4])
assert_equal({0 => 3, 1 => 7}, (p1 + p2).coefficients)
assert_equal({0 => 1, 1 => 3}, p1.coefficients)
assert_equal({0 => 2, 1 => 4}, p2.coefficients)
assert_not_equal(p1, p1 + Polynomial.new)
assert_not_equal(p1, Polynomial.new + p1)
end
def test_subtraction
p1 = Polynomial.new([1,3])
p2 = Polynomial.new([2,4])
assert_equal({0 => -1, 1 => -1}, (p1 - p2).coefficients)
assert_equal({0 => 1, 1 => 3}, p1.coefficients)
assert_equal({0 => 2, 1 => 4}, p2.coefficients)
assert_not_equal(p1, p1 - Polynomial.new)
end
def test_multiplication
# (3x + 1)*(4x - 2) = 12x^2 - 2x - 2
p1 = Polynomial.new([1,3])
p2 = Polynomial.new([-2,4])
assert_equal({0 => -2, 1 => -2, 2 => 12}, (p1 * p2).coefficients)
assert_equal({0 => 1, 1 => 3}, p1.coefficients)
assert_equal({0 => -2, 1 => 4}, p2.coefficients)
assert_equal({}, (p1*Polynomial.new).coefficients)
assert_equal({}, (Polynomial.new*p2).coefficients)
assert_not_equal(p1, (p1*Polynomial.new([1])))
assert_not_equal(p1, (Polynomial.new([1])*p1))
end
def test_polynomial_classes_by_degree
assert(Polynomial.new.zero_polynomial?)
assert(Polynomial.new([1]).constant?)
assert(Polynomial.new([1,2]).linear?)
assert(Polynomial.new([1,2,3]).quadratic?)
assert(Polynomial.new([1,2,3,4]).cubic?)
assert(Polynomial.new([1,2,3,4,5]).quartic?)
assert(Polynomial.new([1,2,3,4,5]).biquadratic?)
assert(Polynomial.new([1,2,3,4,5,6]).quintic?)
assert(Polynomial.new([1,2,3,4,5,6,7]).sextic?)
assert(Polynomial.new([1,2,3,4,5,6,7]).hexic?)
assert(Polynomial.new([1,2,3,4,5,6,7,8]).septic?)
assert(Polynomial.new([1,2,3,4,5,6,7,8]).heptic?)
assert(Polynomial.new([1,2,3,4,5,6,7,8,9]).octic?)
assert(Polynomial.new([1,2,3,4,5,6,7,8,9,10]).nonic?)
assert(Polynomial.new([1,2,3,4,5,6,7,8,9,10,11]).decic?)
end
def test_leading_coefficient
assert_equal(0, Polynomial.new.leading_coefficient)
assert_equal(2, Polynomial.new([1,2,3,4,5,2]).leading_coefficient)
assert(Polynomial.new([1,2,3,1]).monic?)
end
end
|
module Bundler
module Whatsup
# Iterator for set of Change objects
class Changes
nil
end
end
end |
class RemoveCommentFromPicks < ActiveRecord::Migration
def change
remove_column :picks, :comment, :text
remove_column :picks, :name, :text
end
end
|
names = ["Henrietta", "Bubba", "Touralou", nil, "Feliks"]
names.each do |name|
begin
puts "#{name} has #{name.length} letters. Did ya know?"
rescue
puts
puts "Oh my God! Ohmygod! OH MY GOD!!!!"
puts "Something awfully dejected just happened."
puts "This is SO terrible. Call daddy."
puts
end
end
|
require 'spec_helper'
require 'rails_helper'
describe Card do
before do
@card = Card.new
end
describe "number" do
it "should be invalid" do
["", " ", "1", "829612982", "1234567A"].each do |number|
@card.number = number
expect(@card).not_to be_valid
end
end
it "should be valid" do
["12345678", "01010101"].each do |number|
@card.number = number
expect(@card).to be_valid
end
end
end
end
|
class PeopleController < ApplicationController
def index
# Access cached data or save it for the first time
fetch_people
# Without caching we would normally do this:
# @people = People.all
end
end
|
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :logged_in?
def index
@students = User.where(course_name: session[:course_name]) && User.where(role: "student")
@assignments = Assignment.all
if session[:user_role] == "admin"
render 'admin_index'
else
render 'index'
end
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to users_path
end
def change_avatar
@user = User.find(params[:id])
end
def import
User.import(params[:file])
redirect_to users_path, notice: "IMPORT SUCCESSFUL"
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, :password, :role, :course_name, :avatar, assignment_ids: [])
end
end
|
class RemoveDeliveryStatusI18nFromBuyInfomations < ActiveRecord::Migration[5.2]
def change
remove_column :buy_infomations, :delivery_status_i18n, :integer
end
end
|
class ChangeUserAndLesson < ActiveRecord::Migration[5.0]
def change
add_reference :subscribeds, :lesson
add_reference :subscribeds, :user
end
end
|
# frozen_string_literal: true
require 'weese/bus/stop'
require 'weese/bus/route'
module Weese
# MetroBus related structures. Most important: {MetroBus}
module Bus
# MetroBus client. Used for accessing MetroBus-related WMATA APIs.
class MetroBus
include Requests::Requester
include Bus::RequiresStop
include Bus::RequiresRoute
# @return [String] WMATA API key
attr_accessor :api_key
#
# MetroBus client. Used for accessing MetroBus related endpoints
#
# @param [String] api_key WMATA API key, get one at {http://developer.wmata.com}
#
def initialize(api_key)
@api_key = api_key
end
#
# List of all bus route variants.
# {https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d6a WMATA Documentation}
#
# @raise [WeeseError] If request or JSON parse fails
#
# @return [Hash] JSON Response
#
def routes
fetch(
Requests::Request.new(
@api_key,
Bus::Urls::ROUTES,
{}
)
)
end
#
# Nearby bus stops based on latitude, longitude, and radius.
# {https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d6d WMATA Documentation}
#
# @param [RadiusAtCoordinates] radius_at_coordinates A radius in meters around a lat/long
#
# @raise [WeeseError] If request or JSON parse fails
#
# @return [Hash] JSON Response
#
def stops(radius_at_coordinates = nil)
query = radius_at_coordinates ? radius_at_coordinates.to_h : {}
fetch(
Requests::Request.new(
@api_key,
Bus::Urls::STOPS,
query
)
)
end
end
end
end
|
class CreateTransactions < ActiveRecord::Migration
def change
create_table :transactions do |t|
t.integer :student_id
t.string :message
t.integer :loggable_id
t.string :loggable_type
t.timestamps
end
add_index(:transactions, :student_id)
add_index(:transactions, :loggable_id)
end
end
|
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
def to_param
name
end
def to_s
name
end
end
|
require 'rails_helper'
RSpec.feature 'Account Update', type: :feature do
given!(:user) { create(:user) }
background do
Capybara.current_driver = :selenium_chrome_headless
sign_in_with_factory user
end
scenario 'normal update' do
email_before = user.email
account_update('afterupload', '', 'newpass', 'newpass', user.password)
user.reload
expect(user.name).to eq('afterupload')
expect(user.email).to eq(email_before)
end
scenario 'informat email' do
account_update('afterupload', '@gmail.com', 'newpass', 'newpass', user.password)
expect(page).to have_content '無効な形式です'
end
scenario 'wrong password' do
account_update('afterupload', '', 'newpass', 'newpass', 'spcspec')
expect(page).to have_content 'Current password is invalid'
end
scenario 'unmatched password' do
account_update('afterupload', '', 'newpass', 'nepass', user.password)
expect(page).to have_content 'Password confirmation doesn\'t match Password'
end
end
|
module PositionHelper
def position_kinds
Position.kinds.keys.map { |c| [position_kind(c), c] }
end
def position_kind(k)
t("model.position.kinds.#{k}")
end
end |
describe App do
describe '#run' do
context 'when dealer wins' do
context 'and player busts' do
let(:cards) do
[
Card.new(:spade, 'K'),
Card.new(:diamond, 'J'),
Card.new(:diamond, '3'),
Card.new(:diamond, '4'),
Card.new(:heart, 'Q'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはスペードのKです。
あなたの引いたカードはダイヤのJです。
ディーラーの引いたカードはダイヤの3です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は20です。
カードを引きますか?
y/n: y/n:
あなたの引いたカードはハートのQです。
30点でバストしました。
press return:
あなたの負けです。
対戦成績: 0勝1敗0分
勝率: 0.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
# input 'x' to retry y/n
allow(app).to receive(:gets).and_return('x', 'y', 'n')
expect { app.run }.to output(expected).to_stdout
end
end
context 'and dealer is greater than player' do
let(:cards) do
[
Card.new(:club, '7'),
Card.new(:spade, 'K'),
Card.new(:spade, '8'),
Card.new(:heart, 'J'),
Card.new(:diamond, '8'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはクラブの7です。
あなたの引いたカードはスペードのKです。
ディーラーの引いたカードはスペードの8です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は17です。
カードを引きますか?
y/n:
ディーラーの2枚目のカードはハートのJでした。
ディーラーの得点は18です。
press return:
あなたの得点は17です。
ディーラーの得点は18です。
あなたの負けです。
対戦成績: 0勝1敗0分
勝率: 0.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
allow(app).to receive(:gets).and_return('n', '', 'n')
expect { app.run }.to output(expected).to_stdout
end
end
end
context 'when player wins' do
context 'and dealer busts' do
let(:cards) do
[
Card.new(:club, 'J'),
Card.new(:club, '8'),
Card.new(:diamond, '7'),
Card.new(:club, '7'),
Card.new(:diamond, '8'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはクラブのJです。
あなたの引いたカードはクラブの8です。
ディーラーの引いたカードはダイヤの7です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は18です。
カードを引きますか?
y/n:
ディーラーの2枚目のカードはクラブの7でした。
ディーラーの現在の得点は14です。
press return:
ディーラーの引いたカードはダイヤの8です。
ディーラーは22点でバストしました。
press return:
あなたの勝ちです!
対戦成績: 1勝0敗0分
勝率: 100.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
allow(app).to receive(:gets).and_return('n', '', 'n')
expect { app.run }.to output(expected).to_stdout
end
end
context 'and player is greater than dealer' do
let(:cards) do
[
Card.new(:club, '7'),
Card.new(:spade, 'K'),
Card.new(:spade, '8'),
Card.new(:heart, '3'),
Card.new(:spade, '3'),
Card.new(:diamond, '8'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはクラブの7です。
あなたの引いたカードはスペードのKです。
ディーラーの引いたカードはスペードの8です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は17です。
カードを引きますか?
y/n:
あなたの引いたカードはスペードの3です。
あなたの現在の得点は20です。
カードを引きますか?
y/n:
ディーラーの2枚目のカードはハートの3でした。
ディーラーの現在の得点は11です。
press return:
ディーラーの引いたカードはダイヤの8です。
ディーラーの得点は19です。
press return:
あなたの得点は20です。
ディーラーの得点は19です。
あなたの勝ちです!
対戦成績: 1勝0敗0分
勝率: 100.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
allow(app).to receive(:gets).and_return('y', 'n', '', '', 'n')
expect { app.run }.to output(expected).to_stdout
end
end
end
context 'when draws' do
let(:cards) do
[
Card.new(:club, '7'),
Card.new(:spade, 'K'),
Card.new(:spade, '8'),
Card.new(:heart, '3'),
Card.new(:diamond, '6'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはクラブの7です。
あなたの引いたカードはスペードのKです。
ディーラーの引いたカードはスペードの8です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は17です。
カードを引きますか?
y/n:
ディーラーの2枚目のカードはハートの3でした。
ディーラーの現在の得点は11です。
press return:
ディーラーの引いたカードはダイヤの6です。
ディーラーの得点は17です。
press return:
あなたの得点は17です。
ディーラーの得点は17です。
引き分けです。
対戦成績: 0勝0敗1分
勝率: 0.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
allow(app).to receive(:gets).and_return('n', '', '', 'n')
expect { app.run }.to output(expected).to_stdout
end
end
context 'when repeat game' do
let(:cards) do
[
Card.new(:heart, 'K'),
Card.new(:diamond, 'A'),
Card.new(:diamond, '5'),
Card.new(:heart, '3'),
Card.new(:heart, 'A'),
Card.new(:diamond, '10'),
Card.new(:diamond, 'A'),
Card.new(:diamond, '10'),
Card.new(:spade, '8'),
Card.new(:diamond, '2'),
Card.new(:club, 'K'),
Card.new(:diamond, '9'),
Card.new(:spade, 'A'),
Card.new(:spade, '10'),
Card.new(:club, '3'),
Card.new(:diamond, '10'),
Card.new(:diamond, '4'),
]
end
let(:expected) do
<<~TEXT
ブラックジャックへようこそ!
【第1回戦】
ゲームを開始します。
あなたの引いたカードはハートのKです。
あなたの引いたカードはダイヤのAです。
ディーラーの引いたカードはダイヤの5です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は11です。
カードを引きますか?
y/n:
あなたの引いたカードはハートのAです。
あなたの現在の得点は12です。
カードを引きますか?
y/n:
あなたの引いたカードはダイヤの10です。
22点でバストしました。
press return:
あなたの負けです。
対戦成績: 0勝1敗0分
勝率: 0.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
【第2回戦】
ゲームを開始します。
あなたの引いたカードはダイヤのAです。
あなたの引いたカードはダイヤの10です。
ディーラーの引いたカードはスペードの8です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は11です。
カードを引きますか?
y/n:
あなたの引いたカードはクラブのKです。
あなたの得点は21です。
press return:
ディーラーの2枚目のカードはダイヤの2でした。
ディーラーの現在の得点は10です。
press return:
ディーラーの引いたカードはダイヤの9です。
ディーラーの得点は19です。
press return:
あなたの得点は21です。
ディーラーの得点は19です。
あなたの勝ちです!
対戦成績: 1勝1敗0分
勝率: 50.0%
ブラックジャック終了!もう一度遊びますか?
y/n:
【第3回戦】
ゲームを開始します。
あなたの引いたカードはスペードのAです。
あなたの引いたカードはスペードの10です。
ディーラーの引いたカードはクラブの3です。
ディーラーの2枚目のカードは分かりません。
あなたの現在の得点は11です。
カードを引きますか?
y/n:
ディーラーの2枚目のカードはダイヤの10でした。
ディーラーの現在の得点は13です。
press return:
ディーラーの引いたカードはダイヤの4です。
ディーラーの得点は17です。
press return:
あなたの得点は11です。
ディーラーの得点は17です。
あなたの負けです。
対戦成績: 1勝2敗0分
勝率: 33.3%
ブラックジャック終了!もう一度遊びますか?
y/n:
さようなら。また遊んでね★
TEXT
end
example do
app = App.new
allow(app).to receive(:generate_cards).and_return(cards)
allow(app).to receive(:gets).and_return(
'y', 'y', '', 'y',
'y', '', '', '', 'y',
'n', '', '', 'n',
)
expect { app.run }.to output(expected).to_stdout
end
end
end
end |
require 'spec_helper'
describe 'elasticsearch', :type => 'class' do
let :params do {
:config => { 'node' => { 'name' => 'test' } }
} end
context "On Debian OS" do
let :facts do {
:operatingsystem => 'Debian'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On Ubuntu OS" do
let :facts do {
:operatingsystem => 'Ubuntu'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On CentOS OS" do
let :facts do {
:operatingsystem => 'CentOS'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On RedHat OS" do
let :facts do {
:operatingsystem => 'Redhat'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On Fedora OS" do
let :facts do {
:operatingsystem => 'Fedora'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On Scientific OS" do
let :facts do {
:operatingsystem => 'Scientific'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On Amazon OS" do
let :facts do {
:operatingsystem => 'Amazon'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On OracleLinux OS" do
let :facts do {
:operatingsystem => 'OracleLinux'
} end
# init.pp
it { should contain_class('elasticsearch::package') }
it { should contain_class('elasticsearch::config') }
it { should contain_class('elasticsearch::service') }
# package.pp
it { should contain_package('elasticsearch') }
# service.pp
it { should contain_service('elasticsearch') }
# config.pp
end
context "On an unknown OS" do
let :facts do {
:operatingsystem => 'Darwin'
} end
it { expect { should raise_error(Puppet::Error) } }
end
context "install using an alternative package source" do
context "with a debian package" do
let :facts do {
:operatingsystem => 'Debian'
} end
let :params do {
:pkg_source => 'puppet:///path/to/package.deb',
:config => { 'node' => { 'name' => 'test' } }
} end
it { should contain_file('/tmp/package.deb').with(:source => 'puppet:///path/to/package.deb') }
it { should contain_package('elasticsearch').with(:source => '/tmp/package.deb', :provider => 'dpkg') }
end
context "with a redhat package" do
let :facts do {
:operatingsystem => 'CentOS'
} end
let :params do {
:pkg_source => 'puppet:///path/to/package.rpm',
:config => { 'node' => { 'name' => 'test' } }
} end
it { should contain_file('/tmp/package.rpm').with(:source => 'puppet:///path/to/package.rpm') }
it { should contain_package('elasticsearch').with(:source => '/tmp/package.rpm', :provider => 'rpm') }
end
context "with an unsupported package" do
let :facts do {
:operatingsystem => 'CentOS'
} end
let :params do {
:pkg_source => 'puppet:///path/to/package.yaml',
:config => { 'node' => { 'name' => 'test' } }
} end
it { expect { should raise_error(Puppet::Error) } }
end
end
context "install java" do
let :params do {
:java_install => true,
:config => { 'node' => { 'name' => 'test' } }
} end
context "On a Debian OS" do
let :facts do {
:operatingsystem => 'Debian'
} end
it { should contain_package('openjdk-6-jre-headless') }
end
context "On an Ubuntu OS" do
let :facts do {
:operatingsystem => 'Ubuntu'
} end
it { should contain_package('openjdk-6-jre-headless') }
end
context "On a CentOS OS " do
let :facts do {
:operatingsystem => 'CentOS'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On a RedHat OS " do
let :facts do {
:operatingsystem => 'Redhat'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On a Fedora OS " do
let :facts do {
:operatingsystem => 'Fedora'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On a Scientific OS " do
let :facts do {
:operatingsystem => 'Scientific'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On a Amazon OS " do
let :facts do {
:operatingsystem => 'Amazon'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On a OracleLinux OS " do
let :facts do {
:operatingsystem => 'OracleLinux'
} end
it { should contain_package('java-1.6.0-openjdk') }
end
context "On an unknown OS" do
let :facts do {
:operatingsystem => 'Darwin'
} end
it { expect { should raise_error(Puppet::Error) } }
end
context "Custom java package" do
let :facts do {
:operatingsystem => 'CentOS'
} end
let :params do {
:java_install => true,
:java_package => 'java-1.7.0-openjdk',
:config => { 'node' => { 'name' => 'test' } }
} end
it { should contain_package('java-1.7.0-openjdk') }
end
end
context "test restarts on configuration change" do
let :facts do {
:operatingsystem => 'CentOS'
} end
context "does not restart when restart_on_change is false" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:restart_on_change => false,
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').without_notify }
end
context "restarts when restart_on_change is true" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:restart_on_change => true,
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:notify => "Class[Elasticsearch::Service]") }
end
end
context "test content of default service file" do
context "On a CentOS OS" do
let :facts do {
:operatingsystem => 'CentOS'
} end
context "set a value" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:service_settings => { 'ES_USER' => 'elasticsearch', 'ES_GROUP' => 'elasticsearch' }
} end
it { should contain_file('/etc/sysconfig/elasticsearch').with(:content => "### MANAGED BY PUPPET ###\n\nES_GROUP=elasticsearch\nES_USER=elasticsearch\n") }
end
end
context "On a Debian OS" do
let :facts do {
:operatingsystem => 'Debian'
} end
context "set a value" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:service_settings => { 'ES_USER' => 'elasticsearch', 'ES_GROUP' => 'elasticsearch' }
} end
it { should contain_file('/etc/default/elasticsearch').with(:content => "### MANAGED BY PUPPET ###\n\nES_GROUP=elasticsearch\nES_USER=elasticsearch\n") }
end
end
end
context "test content of config file" do
let :facts do {
:operatingsystem => 'CentOS'
} end
context "with nothing set" do
let :params do {
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n") }
end
context "set a value" do
let :params do {
:config => { 'node' => { 'name' => 'test' } }
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n---\nnode: \n name: test\n") }
end
context "set a value to true" do
let :params do {
:config => { 'node' => { 'master' => true } }
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n---\nnode: \n master: true\n") }
end
context "set a value to false" do
let :params do {
:config => { 'node' => { 'data' => false } }
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n---\nnode: \n data: false\n") }
end
context "deeper hash and multiple keys" do
let :params do {
:config => { 'index' => { 'routing' => { 'allocation' => { 'include' => 'tag1', 'exclude' => [ 'tag2', 'tag3' ] } } }, 'node' => { 'name' => 'somename' } }
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n---\nindex: \n routing: \n allocation: \n exclude: \n - tag2\n - tag3\n include: tag1\nnode: \n name: somename\n") }
end
context "Combination of full hash and shorted write up keys" do
let :params do {
:config => { 'node' => { 'name' => 'NodeName', 'rack' => 46 }, 'boostrap.mlockall' => true, 'cluster' => { 'name' => 'ClusterName', 'routing.allocation.awareness.attributes' => 'rack' }, 'discovery.zen' => { 'ping.unicast.hosts'=> [ "host1", "host2" ], 'minimum_master_nodes' => 3, 'ping.multicast.enabled' => false }, 'gateway' => { 'expected_nodes' => 4, 'recover_after_nodes' => 3 }, 'network.host' => '123.123.123.123' }
} end
it { should contain_file('/etc/elasticsearch/elasticsearch.yml').with(:content => "### MANAGED BY PUPPET ###\n---\nboostrap: \n mlockall: true\ncluster: \n name: ClusterName\n routing: \n allocation: \n awareness: \n attributes: rack\ndiscovery: \n zen: \n minimum_master_nodes: 3\n ping: \n multicast: \n enabled: false\n unicast: \n hosts: \n - host1\n - host2\ngateway: \n expected_nodes: 4\n recover_after_nodes: 3\nnetwork: \n host: 123.123.123.123\nnode: \n name: NodeName\n rack: 46\n") }
end
end
context "try with different configdir" do
let :facts do {
:operatingsystem => 'CentOS'
} end
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:confdir => '/opt/elasticsearch/etc'
} end
it { should contain_file('/opt/elasticsearch/etc/elasticsearch.yml') }
end
context "install init script" do
let :facts do {
:operatingsystem => 'CentOS'
} end
context "default" do
let :params do {
:config => { 'node' => { 'name' => 'test' } }
} end
it { should_not contain_file('/etc/init.d/elasticsearch') }
end
context "when unmanaged" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:status => 'unmanaged',
:initfile => 'puppet:///data/elasticsearch/elasticsearch.init'
} end
it { should_not contain_file('/etc/init.d/elasticsearch') }
end
context "when not unmanaged" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:initfile => 'puppet:///data/elasticsearch/elasticsearch.init'
} end
it { should contain_file('/etc/init.d/elasticsearch').with(:source => 'puppet:///data/elasticsearch/elasticsearch.init') }
end
end
context "package options" do
let :facts do {
:operatingsystem => 'CentOS'
} end
context "default" do
let :params do {
:config => { 'node' => { 'name' => 'test' } }
} end
it { should contain_package('elasticsearch').with(:ensure => 'present') }
end
context "when autoupgrade is true" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:autoupgrade => true
} end
it { should contain_package('elasticsearch').with(:ensure => 'latest') }
end
context "when version is set" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:version => '0.20.5'
} end
it { should contain_package('elasticsearch').with(:ensure => '0.20.5') }
end
context "when absent" do
let :params do {
:config => { 'node' => { 'name' => 'test' } },
:ensure => 'absent'
} end
it { should contain_package('elasticsearch').with(:ensure => 'purged') }
end
end
end
|
class User < ActiveRecord::Base
has_many :project
validates_uniqueness_of :name
end
|
#encoding:utf-8
require 'spec_helper'
describe ApplicationHelper do
describe 'render_close_icon' do
subject { helper.render_close_icon }
it { should have_selector('a.close') }
end
describe 'flash_class' do
subject { helper.flash_class(flash_key) }
context 'when flash key is :notice' do
let(:flash_key) { :notice }
it { should == 'alert-success' }
end
context 'when flash key is :error' do
let(:flash_key) { :error }
it { should == 'alert-error' }
end
end
describe 'render_user_bar' do
def render
helper.render_user_bar
end
context 'when user has signed in' do
before do
helper.should_receive(:user_signed_in?).with().and_return(true)
end
it 'renders signed_in_user_bar' do
helper.should_receive(:render).with('signed_in_user_bar').once
render
end
end
context 'when user has not yet signed in' do
before do
helper.should_receive(:user_signed_in?).with().and_return(false)
end
it 'renders signed_out_user_bar' do
helper.should_receive(:render).with('signed_out_user_bar').once
render
end
end
end
describe 'render_flashes' do
context 'when it is called twice' do
it 'only renders flashes once' do
helper.should_receive(:render).with('common/flashes').once
helper.render_flashes
helper.render_flashes
end
end
end
describe 'format_tags' do
subject { helper.format_tags(tags) }
let(:tags) { ["python", "code"] }
it { should eq "<span class=\"tag\"><i class=\"icon-tag\"></i><a href=\"/tags/python\">python</a></span><span class=\"tag\"><i class=\"icon-tag\"></i><a href=\"/tags/code\">code</a></span>" }
end
describe 'format_labels' do
let(:labels) { ["a", "b"] }
context "only labels" do
subject { helper.format_labels(labels) }
it 'with empty color and type' do
should == "<span class=\"label\"><a href=\"/tags/a\">a</a></span><span class=\"label\"><a href=\"/tags/b\">b</a></span>"
end
end
context "with labels and color" do
subject { helper.format_labels(labels, color) }
let(:color) { "info" }
it 'with color of info and empty type' do
should == "<span class=\"label label-info\"><a href=\"/tags/a\">a</a></span><span class=\"label label-info\"><a href=\"/tags/b\">b</a></span>"
end
end
context "with labels, color and type" do
subject { helper.format_labels(labels, color, type) }
let(:color) { "info" }
context "tag" do
let(:type) { "tag" }
it 'with type' do
should == "<span class=\"label label-info\"><a href=\"/tags/a\">a</a></span><span class=\"label label-info\"><a href=\"/tags/b\">b</a></span>"
end
end
context "author" do
let(:type) { "author" }
it 'with type' do
should == "<span class=\"label label-info\"><a href=\"/authors/a\">a</a></span><span class=\"label label-info\"><a href=\"/authors/b\">b</a></span>"
end
end
context "translator" do
let(:type) { "translator" }
it 'with type' do
should == "<span class=\"label label-info\"><a href=\"/translators/a\">a</a></span><span class=\"label label-info\"><a href=\"/translators/b\">b</a></span>"
end
end
end
end
describe "book_follow_info" do
before { helper.stub :current_user, nil }
let(:book) { create :book }
subject { helper.book_follow_info(book) }
it { should eql [0, { false: '收藏' , true: '已收藏' }, false].to_json }
end
end
|
class RemoveRecipientFromQuotationComment < ActiveRecord::Migration[5.0]
def change
remove_column :quotation_comments, :recipient_id
end
end
|
class Stream < ActiveRecord::Base
has_many :posts, :conditions => 'is_deleted IS FALSE', :order => 'published_at DESC'
has_many :articles,
:include => [:service],
:conditions => "is_deleted IS FALSE AND is_draft IS FALSE AND services.identifier = 'articles'",
:order => 'published_at DESC',
:class_name => 'Post'
has_many :drafts,
:include => [:service],
:conditions => "is_deleted IS FALSE AND is_draft IS TRUE AND services.identifier = 'articles'",
:order => 'posts.created_at DESC',
:class_name => 'Post'
has_many :media_posts,
:include => [:medias, :service],
:conditions => "is_deleted IS FALSE AND medias.id IS NOT NULL AND services.identifier != 'wakoopa'",
:order => 'posts.published_at DESC',
:class_name => 'Post',
:limit => 4
has_many :services do
def public(options = {})
find(:all, options.merge(:conditions => "is_enabled IS TRUE AND identifier != 'blog'"))
end
end
has_many :upcoming_trips,
:conditions => "travel_starts_at > NOW()",
:class_name => 'Trip',
:limit => 8
def authenticate(password)
if self.password == password
true
else
self.errors.add(:password, 'Invalid password mate!')
false
end
end
def self.current
self.find_or_create_by_id(1)
end
def activity_overview_graph
require 'google_chart'
# Main Activity Chart
GoogleChart::BarChart.new('900x300', "Daily Activity", :vertical, false) do |bc|
data = {}
services = []
self.posts.find(:all,
:select => 'COUNT(posts.id) AS num_posts, service_id, published_at',
:conditions => ['posts.published_at > ?', 2.weeks.ago],
:group => "service_id,DATE_FORMAT(posts.published_at, '%Y-%m-%d')").each do |post|
xlabel = post.published_at.beginning_of_day
data[xlabel] = {} unless data[xlabel]
data[xlabel][post.service_id.to_i] = post.num_posts.to_i
services << post.service_id.to_i unless services.include?(post.service_id.to_i)
end
xlabels = []
data_by_service = {}
all_values = []
data = data.to_a
data.sort! { |a,b| a.first.to_i <=> b.first.to_i }
data.each do |date,posts_by_service|
xlabels << date.strftime("%b-%d")
total_today = 0
services.each do |service_id|
data_by_service[service_id] ||= []
data_by_service[service_id] << (posts_by_service[service_id] || 0)
total_today += posts_by_service[service_id].to_i
end
all_values << total_today
end
color_i = 0
services.sort!
services.reverse!
services.each do |service_id|
bc.data(Service.find(service_id).identifier, data_by_service[service_id], graph_colors[(color_i % 4)])
color_i += 1
end
ylabels = []
0.upto(all_values.max) { |i| ylabels << i }
#1.upto(10) { |i| ylabels << i }
bc.axis(:y, :labels => ylabels)
bc.axis(:x, :labels => xlabels)
bc.width_spacing_options(:bar_width => 50)
bc.stacked = true
return bc
end
end
def used_services_graph
require 'google_chart'
# Services Diagram
services = {}
self.posts.find(:all,
:select => 'COUNT(posts.id) AS num_posts,service_id',
:conditions => ['posts.published_at > ?', 2.weeks.ago],
:group => 'service_id').each do |post|
services[post.service_id.to_i] = post.num_posts.to_i
end
GoogleChart::PieChart.new('320x200', "Services used", false) do |pc|
color_i = 0
services = services.to_a.sort! { |b,a| a.first <=> b.first }
services.each do |service_id,num_posts|
pc.data(Service.find(service_id).identifier, num_posts, graph_colors[(color_i % 4)])
color_i += 1
end
return pc
end
end
def common_activity_hours_graph_url
require 'google_chart'
hourly_activity = {}
time_zone = nil
self.posts.find(:all,
:select => 'COUNT(posts.id) AS num_posts,published_at',
:conditions => ['posts.published_at > ?', 2.weeks.ago],
:group => "DATE_FORMAT(posts.published_at, '%H')").each do |post|
hourly_activity[post.published_at.strftime("%H").to_i] = post.num_posts.to_i
end
puts hourly_activity.inspect
xlabels = (0..23).collect { |h| "#{h+1}:00" }
hourly_activity = (0..23).collect { |h| hourly_activity[h] || 0 }
hourly_activity = hourly_activity.collect { |p| ((p/hourly_activity.max.to_f)*100).ceil }
"http://chart.apis.google.com/chart?cht=r&chs=200x200&chd=t:#{hourly_activity.join(',')}0&chco=#{graph_colors.first}&chls=2.0,4.0,0.0&chxt=x&chxl=0:|#{(0..23).collect { |i| i.to_s }.join('|')}&chxr=0,0.0,23.0&chm=B,#{graph_colors.last},0,1.0,4.0&chtt=Hourly+Activity+#{time_zone}"
end
def activity_summary_sparkline_url
data = {}
self.posts.find(:all,
:select => 'COUNT(posts.id) AS num_posts, published_at',
:conditions => ['posts.published_at > ?', 2.weeks.ago],
:group => "DATE_FORMAT(posts.published_at, '%Y-%m-%d')").each do |post|
data[post.published_at.beginning_of_day] = post.num_posts.to_i
end
data = data.to_a
data.sort! { |a,b| a.first <=> b.first }
data = data.collect { |d| d.last }
peak = data.max
data = data.collect { |p| ((p/peak.to_f)*100).ceil }
"http://chart.apis.google.com/chart?chs=200x80&chd=t:#{data.join(',')}&cht=ls"
end
protected
def graph_colors
['2a2a2a', '666666', '999999', 'cccccc']
end
end
|
module Motion
class LaunchImages
def self.screenshot_path
NSBundle.mainBundle.objectForInfoDictionaryKey('screenshot_path')
end
def self.taking?
screenshot_path != nil
end
def self.take!(orientation = :portrait)
return unless taking?
Dispatch::Queue.main.async do
if needs_rotation?(orientation)
rotate(orientation)
sleep 1.0
end
Dispatch::Queue.main.async { capture! }
end
end
def self.capture!
screen = UIScreen.mainScreen
height = screen.bounds.size.height
scale = begin
if !screen.respondsToSelector('displayLinkWithTarget:selector:')
''
elsif screen.scale == 1.0
''
elsif screen.scale == 2.0
'@2x'
elsif screen.scale == 3.0
'@3x'
else
puts 'Error: Unable to determine screen scale'
exit
end
end
filename = generate_filename(height, scale)
if scale != ''
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, screen.scale)
else
UIGraphicsBeginImageContext(window.bounds.size)
end
window.layer.renderInContext(UIGraphicsGetCurrentContext())
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
data = UIImagePNGRepresentation(image)
data.writeToFile(filename, atomically:true)
puts "Wrote to #{filename}"
if should_rotate_and_take_again?(height)
take!(:landscape)
else
exit
end
end
def self.generate_filename(height, scale)
filename = screenshot_path + 'Default'
case height
when 480 # iPhone 4s
when 568 # iPhone 5s
filename << '-568h'
when 667 # iPhone 6
filename << '-667h'
when 736 # iPhone 6 Plus
filename << '-736h'
when 768 # iPad (Landscape)
filename << '-Landscape'
when 1024 # iPad (Portrait)
filename << '-Portrait'
else
puts "Error: Invalid screen height #{height}"
exit
end
filename << scale << '.png'
end
# ported from BubbleWrap to reduce dependencies
def self.window
normal_windows = UIApplication.sharedApplication.windows.select { |w|
w.windowLevel == UIWindowLevelNormal
}
key_window = normal_windows.select { |w|
w == UIApplication.sharedApplication.keyWindow
}.first
key_window || normal_windows.first
end
def self.should_rotate_and_take_again?(height)
height == 1024 # iPad (Portrait)
end
def self.rotate(to)
if to == :portrait
value = NSNumber.numberWithInt(UIInterfaceOrientationPortrait)
else
value = NSNumber.numberWithInt(UIInterfaceOrientationLandscapeLeft)
end
UIDevice.currentDevice.setValue(value, forKey:'orientation')
end
def self.needs_rotation?(orientation)
status = UIApplication.sharedApplication.statusBarOrientation
if orientation == :portrait && status == UIInterfaceOrientationPortrait
false
elsif orientation == :landscape && (status == UIInterfaceOrientationLandscapeLeft ||
status == UIInterfaceOrientationLandscapeRight)
false
else
true
end
end
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), 'meta'))
module WebInspector
class Inspector
def initialize(page)
@page = page
@meta = WebInspector::Meta.new(page).meta
end
def title
@page.css('title').inner_text.strip rescue nil
end
def description
@meta['description'] || snippet
end
def body
@page.css('body').to_html
end
def meta
@meta
end
def links
links = []
@page.css("a").each do |a|
links.push((a[:href].to_s.start_with? @url.to_s) ? a[:href] : URI.join(@url, a[:href]).to_s) if (a and a[:href])
end
return links
end
def images
images = []
@page.css("img").each do |img|
images.push((img[:src].to_s.start_with? @url.to_s) ? img[:src] : URI.join(url, img[:src]).to_s) if (img and img[:src])
end
return images
end
private
def snippet
first_long_paragraph = @page.search('//p[string-length() >= 120]').first
first_long_paragraph ? first_long_paragraph.text : ''
end
end
end |
module ApplicationHelper
def human_readable_box_type package_type
box_type_hum = {"JAR"=>'Jar', "DB" => 'Dress Box', "SLB" => 'Slide Lid Box', "SBN" => 'Semi Boîte Nature', "CB" => 'Cardboard Pack', "BLBN" => 'Black Lacquered Boîte Nature', "VBN" => 'Varnished Boîte Nature', "VSBN" => 'Varnished Semi Boîte Nature', "VSLB" => 'Varnished Slid Lid Box', "NVBN" => 'Numbered Varnished Boîte Nature', "NSLB" => 'Numbered Slide Lid Box', "NSBN" => 'Numbered Semi Boîte Nature', "V898" => 'Varnished 8-9-8', "CBB" => 'Cardboard Box', "NDB" => 'Numbered Dress Box', "TH" => 'Travel Humidor', "SB" => 'Seleccion Box', "MT" => 'Metal Tin', "MP" => 'Metal Tin', "TP3IT" => '3 cigars in humidified tubes', "RCBB"=> 'Rigid Cardboard Box', "RBB" => 'Rigid Cardboard Box'}
box_type_hum[package_type]||package_type
end
def human_readable_box_type_2 package_type
case package_type
when "DB"
'Dress Box'
when "SLB"
'Slide Lid Box'
when "SBN"
'Semi Boîte Nature'
when "CB"
'Cardboard Pack'
when "BLBN"
'Black Lacquered Boîte Nature'
when "VBN"
'Varnished Boîte Nature'
when "VSBN"
'Varnished Semi Boîte Nature'
when "VSLB"
'Varnished Slid Lid Box'
when "NVBN"
'Numbered Varnished Boîte Nature'
when "NSLB"
'Numbered Slide Lid Box'
when "NSBN"
'Numbered Semi Boîte Nature'
when "V898"
'Varnished 8-9-8'
when "CBB"
'Cardboard Box'
when "NDB"
'Numbered Dress Box'
when "TH"
'Travel Humidor'
when "SB"
'Seleccion Box'
when "MT", "MP"
'Metal Tin'
when "TP3IT"
'3 cigars in humidified tubes'
when "RBB"
'Rigid Cardboard Box'
else
package_type
end
end
end |
# frozen_string_literal: true
require "securerandom"
require "pathname"
module Haikunate
require "haikunate/version"
class << self
attr_accessor :default_range, :default_variant
end
self.default_range = 1000..9999
self.default_variant = -> { rand(default_range) }
def self.data_dir
@data_dir ||= Pathname.new(File.expand_path("#{__dir__}/../data"))
end
def self.nouns
@nouns ||= data_dir.join("nouns.txt").read.lines.map(&:chomp)
end
def self.nouns=(nouns)
@nouns = nouns.map(&:chomp)
end
def self.adjectives
@adjectives ||= data_dir.join("adjectives.txt").read.lines.map(&:chomp)
end
def self.adjectives=(adjectives)
@adjectives = adjectives.map(&:chomp)
end
def self.call(joiner: "-", variant: default_variant)
[adjectives.sample, nouns.sample, variant.call].join(joiner)
end
def self.next(joiner: "-", variant: default_variant)
options = {joiner: joiner, variant: variant}
name = call(**options) while !name || yield(name)
name
end
end
Haiku = Haikunate
|
require 'scooter'
include Scooter::LDAP
# Should never get here unless an "openldap" host is specified in the
# beaker host/config file
def ldap_dispatcher
# Scooter doesn't support custom settings yet.
#@ldap_dispatcher ||= LDAPDispatcher.new(openldap, { :encryption => nil, :port => 389,
# :auth => { :method => :simple, :username => "cn=admin,dc=example,dc=com", :password => "puppetlabs" } })
@ldap_dispatcher ||= LDAPDispatcher.new(openldap, { :encryption => nil, :port => 389 })
end
|
FactoryGirl.define do
factory :event do
name "Test Event Name"
description "Test Event Description"
date_time DateTime.new(2018, 11, 10, 9, 8)
image File.new("#{Rails.root}/app/assets/images/seed_assets/events_images/event_image.jpg")
address [street_address: "1234 Test Street", city: "Test City", state: "Madeup", zip: "54321"]
branch {rand(1..2)}
end
end
|
# "size" in this case refers to "2T", "5T", etc.
class AddSizeToCanonicalItem < ActiveRecord::Migration[5.2]
def change
add_column :canonical_items, :size, :string
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: memberships
#
# id :integer not null, primary key
# account_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_memberships_on_account_id (account_id)
# index_memberships_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (account_id => accounts.id)
# fk_rails_... (user_id => users.id)
#
require 'rails_helper'
RSpec.describe Membership, type: :model do
it 'has a valid factory' do
expect(build(:membership)).to be_valid
end
# Lazily loaded to ensure it's only used when it's needed
# RSpec tip: Try to avoid @instance_variables if possible. They're slow.
let(:membership) { build(:membership) }
describe 'ActiveModel validations' do
it { expect(membership).to validate_presence_of(:account) }
it { expect(membership).to validate_presence_of(:user) }
end
describe 'Associations' do
it { expect(membership).to belong_to(:account) }
it { expect(membership).to belong_to(:user) }
end
describe 'Database columns' do
it { expect(membership).to have_db_index(:account_id) }
it { expect(membership).to have_db_index(:user_id) }
end
end
|
class Alpaga < Formula
desc "Alpaga FTW!"
homepage "https://github.com/tonyo/alpaga/"
url "https://github.com/tonyo/alpaga/releases/download/0.1.1/alpaga.sh"
version "0.1.1"
sha256 "ca1c183f75890baab9a0289c996c9e0d322bf2887dd8e6d5a6782f2c92267783"
def install
bin.install "alpaga.sh"
end
test do
assert_match 'Alpaga!', shell_output("#{bin}/alpaga.sh").chomp
end
end
|
class ArticleSerializer < ActiveModel::Serializer
attributes :id, :title, :author, :description, :section, :image_url, :url, :publication_date
has_many :clippings
has_many :collections, through: :clippings
end
|
require 'fwiki'
require 'rack/test'
require 'base64'
configure do
DataMapper::Logger.new(STDOUT, :debug)
DataMapper.setup :default, 'sqlite3::memory:'
end
describe Page do
it 'should create a body when contents are specified' do
p = Page.new(:name => 'foo', :contents => 'bar')
p.contents.should == 'bar'
end
it 'should search the body and title' do
p = Page.new(:name => 'foo page', :contents => 'now is the time for all good foo to come to the aid of their bar')
p.scan(%r(the)).length.should == 3
end
end
def authorized_get(path)
get path, {}, {'HTTP_AUTHORIZATION' => encode_credentials(USERNAME, PASSWORD)}
end
def encode_credentials(username, password)
'Basic ' + Base64.encode64(username + ':' + password)
end
describe "fwiki" do
include Rack::Test::Methods
def app
@app ||= Sinatra::Application
end
it 'should require authorization' do
get '/'
last_response.status.should == 401
end
it 'should not allow bad authorization' do
get '/', {}, {'HTTP_AUTHORIZATION' => encode_credentials('foo', 'asdf')}
last_response.status.should == 401
end
it 'should respond to /' do
page = mock('page object')
page.should_receive(:name).twice
Page.should_receive(:all).and_return [page]
authorized_get '/'
last_response.should be_ok
end
it 'should get a page' do
page = mock('page object')
page.should_receive(:name).exactly(3).times.and_return 'foo'
page.should_receive(:contents).and_return 'bar'
Page.should_receive(:get).with('home').and_return page
authorized_get '/home'
last_response.should be_ok
last_response.body.should include('foo')
last_response.body.should include('bar')
end
it "should show a page's edit form" do
page = mock('page object')
page.stub!(:name)
page.stub!(:contents)
Page.should_receive(:get).with('foo').and_return page
authorized_get '/foo?edit=1'
last_response.should be_ok
end
it 'should 404 on a bad page' do
page = nil
Page.should_receive(:get).with('foo<bar').and_return nil
authorized_get '/foo%3cbar'
last_response.status.should == 404
last_response.body.should include('you can create')
last_response.body.should include('foo<bar')
end
end
describe 'fwiki searching' do
include Rack::Test::Methods
def app
@app ||= Sinatra::Application
end
def mock_page_result(name, search_result)
p = mock('page')
p.stub!(:name).and_return name
p.stub!(:scan).and_return search_result
p
end
it 'should search pages' do
page1 = mock_page_result('foo page', ['foo is foo', 'foo foo foo'])
page2 = mock_page_result('bar page', [])
Page.stub!(:all).and_return [page1, page2]
authorized_get '/search?term=foo'
last_response.should be_ok
last_response.body.should include('foo page')
last_response.body.should include('foo is foo')
last_response.body.should include('foo foo foo')
last_response.body.should_not include('bar page')
end
it 'should say when there are no results' do
page = mock_page_result('bar page', [])
Page.stub!(:all).and_return [page]
authorized_get '/search/baz'
last_response.should be_ok
last_response.body.should include('no baz :(')
end
end
|
class MediaBrowse
class NoUser; end
attr_reader :user
def initialize(options)
@user = options.fetch(:user, NoUser) || NoUser
end
def items
MediaRepository.visible_for(user)
end
end
|
# Incorporate logic to send some messages from the admin web interface
class MessageSender
def component_message(component, provider, provider_account)
if provider == 'facebook'
user_id = provider_account.user.id
if component.component_type == 'crawler'
facebook_id = provider_account.facebook_id
auth_token = provider_account.auth_token
crawler_message = Sm::Messages::CrawlerMessage.new(user_id, provider, facebook_id, auth_token)
Sm.message_dispatcher.send_and_receive_confirm(crawler_message)
return "Send message to crawler=#{component.name} for user id=#{user_id}"
elsif component.component_type == 'graph'
graph_names = []
graphs = GraphMeta.all
graph_messages = []
graphs.each do |graph|
graph_name = graph.name
graph_names << graph_name
graph_messages << Sm::Messages::GraphMessage.new(user_id, graph_name, provider)
end
Sm.message_dispatcher.one_time_dispatcher_message(graph_messages)
return "Sent messages to graphs=[#{graph_names.join(", ")}] for user id=#{user_id}"
elsif component.component_type == 'analyzer'
models = FieldTrigger.where(component_id: component.id).includes(:source_field).all.map{|t| t.source_field.model.name}.uniq
analyzer_messages = get_analyzer_messages(user_id, provider, models, component.name)
analyzer_messages.each do |analyzer_message|
Rails.logger.info "Sending analyzer message = #{analyzer_message.inspect}"
Sm.message_dispatcher.one_time_dispatcher_message(analyzer_message)
end
else
return "Unsupported component type=#{component.component_type}"
end
else
return "Unknown provider #{provider}"
end
end
private
def get_analyzer_messages(user_id, provider, models, component_name)
result = []
models.each do |model|
result << Sm::Messages::AnalyzerMessage.new(user_id, provider, model, component_name)
end
result
end
end |
module Crawler
module Db
class WebPageResult < Sequel::Model(connection[:web_page_results])
SPACE_MATCHER = Regexp.compile('\s+')
# @param [String] url
# @return [Boolean]
def self.crawled?(url)
!!send(:[], url)
end
# @param [Crawler::Http::Response] response
# @param [Crawler::WebPage, nil] webpage
def self.save_result(response, webpage)
new do |wpr|
wpr.url = response.request_uri.to_s
wpr.hostname = response.request_uri.host
wpr.title = (webpage ? webpage.title.to_s : nil)
wpr.server_header = response.headers[:server].to_s
wpr.status_code = response.code.to_i
wpr.robots_meta = (webpage ? webpage.robots_meta.join(',') : nil)
end.save
end
def before_create
super
self.created_at = Time.now
end
def before_validation
super
self.url = url.strip
self.hostname = hostname.strip
self.title = nil if title && title.length == 0
self.server_header = nil if server_header && server_header.length == 0
self.status_code = 0 unless status_code
self.robots_meta = nil if robots_meta && robots_meta.length == 0
if server_header
self.server_header = server_header.strip.gsub(SPACE_MATCHER, ' ').downcase
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Price, type: :model do
before do
@price = FactoryBot.build(:price)
end
describe 'シュミレーション情報の登録' do
context '登録がうまくいくとき' do
it '正しく情報を入力すれば登録できる' do
expect(@price).to be_valid
end
end
context '登録がうまくいくいかないとき' do
it '運営業態を選択していないと登録できない' do
@price.category_id = nil
@price.valid?
expect(@price.errors.full_messages).to include('運営業態を入力してください')
end
it '年齢を選択していないと登録できない' do
@price.age_id = nil
@price.valid?
expect(@price.errors.full_messages).to include('年齢を入力してください')
end
it '無償化対象金額を入力していないと登録できない' do
@price.free_price = nil
@price.valid?
expect(@price.errors.full_messages).to include('保育料を入力してください')
end
it '無償化対象外金額を入力していないと登録できない' do
@price.not_free_price = nil
@price.valid?
expect(@price.errors.full_messages).to include('保育料以外の金額を入力してください')
end
end
end
end
|
require 'bulutfon_sdk/rest/base_request'
module BulutfonSDK
module REST
class OutgoingFax < BaseRequest
include BulutfonSDK::Util
def initialize(*args)
super(*args)
@resource = 'outgoing-faxes'
end
def all( params = {} )
prepare_request( 'get', @resource, params)
end
def get( id )
prepare_request( 'get', "#{@resource}/#{id}")
end
def create(params)
prepare_atachment(params)
prepare_request( 'post', @resource, params)
end
private
def prepare_atachment(params)
file = params[:attachment]
basename = File.basename file
type = file_content_type file
content = File.read(file)
base_64_data = Base64.strict_encode64(content)
params[:attachment] = "data:#{type};name:#{basename};base64:#{base_64_data}"
end
end
end
end
|
# Given this data structure write some code to return an array containing the colors of the fruits and the sizes of the vegetables. The sizes should be uppercase and the colors should be capitalized.
hsh = {
'grape' => {type: 'fruit', colors: ['red', 'green'], size: 'small'},
'carrot' => {type: 'vegetable', colors: ['orange'], size: 'medium'},
'apple' => {type: 'fruit', colors: ['red', 'green'], size: 'medium'},
'apricot' => {type: 'fruit', colors: ['orange'], size: 'medium'},
'marrow' => {type: 'vegetable', colors: ['green'], size: 'large'},
}
# The return value should look like this:
[["Red", "Green"], "MEDIUM", ["Red", "Green"], ["Orange"], "LARGE"]
arr = []
# hsh.each do |k, v|
# color = v[:colors] if v[:type] == 'fruit'
# size = v[:size] if v[:type] == 'vegetable'
# arr << color.map { | e | e.capitalize } unless !color
# arr << size.upcase unless !size
# end
hsh.each do |_, v|
if v[:type] == 'fruit'
arr << v[:colors].map { | e | e.capitalize }
elsif v[:type] == 'vegetable'
arr << v[:size].upcase
end
end
p arr
# LS solution:
hsh.map do |_, value|
if value[:type] == 'fruit'
value[:colors].map do |color|
color.capitalize
end
elsif value[:type] == 'vegetable'
value[:size].upcase
end
end
# => [["Red", "Green"], "MEDIUM", ["Red", "Green"], ["Orange"], "LARGE"] |
# frozen_string_literal: true
module GraphQL
module StaticValidation
module InputObjectNamesAreUnique
def on_input_object(node, parent)
validate_input_fields(node)
super
end
private
def validate_input_fields(node)
input_field_defns = node.arguments
input_fields_by_name = Hash.new { |h, k| h[k] = [] }
input_field_defns.each { |a| input_fields_by_name[a.name] << a }
input_fields_by_name.each do |name, defns|
if defns.size > 1
error = GraphQL::StaticValidation::InputObjectNamesAreUniqueError.new(
"There can be only one input field named \"#{name}\"",
nodes: defns,
name: name
)
add_error(error)
end
end
end
end
end
end
|
class TasksController < ApplicationController
before_action :authenticate_user!
before_action :set_task, only: [:show, :edit, :update, :destroy]
before_action :is_own_task?, only: [:edit, :update, :destroy]
before_action :is_project_member?, only: [:show]
def index
@project = :all
@tasks = current_user.all_tasks
end
def index_by_project
@project = current_user.projects.find(params[:project_id])
@tasks = @project.tasks
render :index
end
def index_wo_project
@project = :empty
@tasks = current_user.tasks.without_project
render :index
end
def show
@comments = @task.comments
end
def new
@task = current_user.tasks.new(project_id: params[:project_id])
end
def edit
end
def create
@task = current_user.tasks.new(task_params)
if @task.save
redirect_to tasks_path, notice: 'Задача успешно добавлена.'
else
render action: 'new'
end
end
def update
if @task.update(task_params)
redirect_to tasks_url, notice: 'Задача успешно обновлена.'
else
render action: 'edit'
end
end
def destroy
@task.destroy
redirect_to tasks_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
@task = Task.find(params[:id])
end
def is_own_task?
redirect_to(tasks_path, alert: 'Нет доступа!') unless @task.is_owner?(current_user)
end
def is_project_member?
if @task.project and not @task.project.users.include?(current_user)
redirect_to tasks_path, alert: 'Нет доступа!'
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def task_params
params.require(:task).permit(:title, :description, :project_id, :state)
end
end
|
class AddLightningDataTable < ActiveRecord::Migration
def change
create_table :lightningdata do |t|
t.integer :user_id
t.integer :lightning_id
t.timestamps
end
end
end
|
class AddResolutionrtoIssues < ActiveRecord::Migration
def change
add_column :issues, :resolution, :text
end
end
|
class CreateCards < ActiveRecord::Migration
def change
create_table :cards do |t|
t.text :japanese
t.text :reading
t.text :meaning
t.timestamps
end
end
end
|
#def oxford_comma(array)
# array = []
# if array.size == 1
# return array[0]
# elsif array.size == 2
# return array.join(" and ")
# else
#return array[0..-2].join(", ") + ", and " + array[-1]
#end
#end
def oxford_comma(array)
case array.length
when 1
"#{array[0]}"
when 2
array[0..1].join(" and ")
else
array[0...-1].join(", ") << ", and #{array[-1]}"
end
end
|
require_relative 'album_details_section'
require_relative 'album_player_section'
require './app/helpers/tweets_helper'
class TweetReviewSection < SitePrism::Section
include TweetsHelper
element :user_name, '.user-name'
element :twitter_user_name, '.twitter-username a'
element :reviewed_on, '.reviewed-on'
element :rating, '.review-rating'
element :review_text, '.tweet-text'
element :reply_text, '.tweet-reply'
element :aotm_badge, '.album-of-the-month'
element :recommender, '.recommender'
section :album_details, AlbumDetailsSection, '.genre'
section :album_player, AlbumPlayerSection, '.listen-embed'
def reviewed_on?(datetime)
reviewed_on.has_content? datetime.to_date.to_formatted_s(:long_ordinal)
end
def has_profile_link_to?(user)
twitter_user_name[:href].end_with?("/reviewers/#{user.twitter_screen_name}/feed") ||
twitter_user_name[:href].end_with?("/reviewers/#{user.id}/feed")
end
def has_review_text?(tweet_review)
review_text.has_content? remove_hashtag_and_rating(tweet_review.tweet.text)
end
def has_reply_text?(tweet_review)
reply_text.has_content? remove_hashtag_and_rating(tweet_review.tweet.reply.text)
end
def has_user?(user)
user_name.has_content? user.name
end
def edit_review
click_link 'Edit review details'
EditReview.new
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)
Team.create(name: "喵喵咪")
User.create(name: "呆喵", team_id: 1)
User.create(name: "笨喵", team_id: 1)
Project.create(name: "打老鼠", team_id: 1)
Project.create(name: "吃老鼠", team_id: 1)
Access.create(user_id: 1, project_id: 1)
Access.create(user_id: 2 , project_id: 1)
Access.create(user_id: 1, project_id: 2)
Access.create(user_id: 2 , project_id: 2)
todo_event_content = {
title: "打老鼠",
content: "打老鼠打老鼠",
due: Date.today,
worker_id: 3,
worker_name: "笨喵",
status: 0
}
comment_event_content = {
content: "喵老鼠",
commentable_id: 1,
commentable_type: "todos",
commentable_title: "打晕老鼠"
}
todo_add_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "add",
project_id: 1, content: todo_event_content.to_json)
todo_add_event = Event.create(creator_id: 2, creator_name: "笨喵",
resource_type: "todos", action_type: "add",
project_id: 1, content: todo_event_content.to_json)
todo_assign_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "assign",
project_id: 1, content: todo_event_content.to_json)
todo_change_due_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "change_due",
project_id: 1, content: todo_event_content.to_json)
todo_change_worker_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "change_worker",
project_id: 2, content: todo_event_content.to_json)
todo_complete_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "complete",
project_id: 1, content: todo_event_content.to_json)
todo_delete_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "todos", action_type: "assign",
project_id: 1, content: todo_event_content.to_json)
comment_add_event = Event.create(creator_id: 1, creator_name: "呆喵",
resource_type: "comments", action_type: "add",
project_id: 1, content: comment_event_content.to_json) |
class StaticPagesController < ApplicationController
def index
if user_signed_in?
if current_user.profile #have prof, go to newsfeed
redirect_to tweets_path
else #no prof, create one
flash[:success] = "Create a profile below"
redirect_to new_profile_path
end
end
end
end
|
require 'rcleaner'
def cd(cwd)
old_cwd = Dir.getwd
Dir.chdir cwd
begin
yield if block_given?
ensure
Dir.chdir old_cwd
end
end
|
class FavoriteClass < ActiveRecord::Base
belongs_to :dance_class
belongs_to :user
validates :dance_class_id, :user_id, :presence => true
end
|
class AccessTokensController < ApplicationController
def create
authenticator = UserAuthenticator.new(params[:code])
authenticator.perform
end
end
|
# encoding: utf-8
require "logstash/codecs/base"
#
# Log.io Codec Plugin for Logstash (http://logstash.net)
# Author: Luke Chavers <github.com/vmadman>
# Created: 11/22/2013
# Current Logstash: 1.2.2
#
# To the extent possible under law, Luke Chavers has waived all copyright and related
# or neighboring rights to this work. You are free to distribute, modify, and use
# this work without permission of any kind. Attribution is appreciated, but is not required.
#
# This codec formats events for output to Log.io, a log stream viewer
# built on Node.JS (http://logio.org/). Log.io is Copyright 2011-2013 Narrative Science Inc.
# and is released under the Apache 2.0 license. (http://www.apache.org/licenses/LICENSE-2.0.html)
#
# output {
# tcp {
# codec => logio {
# debug_output => "true"
# }
# host => "127.0.0.1"
# port => 28777
# }
# }
#
# Important Note: This codec is only useful when applied to OUTPUTs
#
class LogStash::Codecs::LogIO < LogStash::Codecs::Base
config_name "logio"
milestone 1
# Applies to ALL output. Set the TIME output format (Ruby). Date directives
# are allowed but are not included in the default because log.io does not persist
# events, making them rather pointless.
#
# The default will yield: '09:45:15 AM UTC'
#
# See: http://www.ruby-doc.org/core-2.0.0/Time.html#method-i-strftime
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^
config :timestamp_format, :validate => :string, :default => "%I:%M:%S %p %Z"
# Only applies to STANDARD output. Set the message you which to emit for
# each event. This supports sprintf strings.
#
# myapp something >> 09:45:15 AM UTC : An event happened
# ^
config :standard_message_format, :validate => :string, :default => "%{message}"
# Only applies to STANDARD output. This specifies the string to
# use for the 'log level' that is passed to log.io. This supports sprintf strings.
# This setting affects the RAW output to log.io and, as far as I can tell, it does
# not affect what log.io displays in any way.
#
# +log|myapp|something|DEBUG|A message here...
# ^
config :standard_log_level_format, :validate => :string, :default => "DEBUG"
# Only applies to DEBUG output. This specifies the string to
# use for the 'stream' that is passed to log.io. This supports sprintf strings.
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^
config :standard_stream_format, :validate => :string, :default => "%{type}"
# Only applies to DEBUG output. This specifies the string to
# use for the 'node' that is passed to log.io. This supports sprintf strings.
#
# myapp something >> 09:45:15 AM UTC : An event happened
# ^
config :standard_node_format, :validate => :string, :default => "%{source}"
# When TRUE additional debug information will be sent that shows
# the full contents of the event as they were when they arrived
# at this output. This is very handy for debugging logstash configs.
# The example below is shortened for so that it would fit this document:
#
# debug myapp >> 09:45:15 AM UTC :
# debug myapp >> 09:45:15 AM UTC : -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# debug myapp >> 09:45:15 AM UTC :
# debug myapp >> 09:45:15 AM UTC : ..... "message" => "app started",
# debug myapp >> 09:45:15 AM UTC : .. "@timestamp" => "2000-12-21T01:00:00.123Z",
# debug myapp >> 09:45:15 AM UTC : .... "@version" => "1",
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
#
# Note: Since Log.io allows you to filter by stream, the debug output is sent
# along with the standard output. (they're not mutually exclusive)
#
# The conversion and tranmission of events into debug format is likely relatively
# expensive and is not advised for use in production environments.
config :debug_output, :validate => :boolean, :default => false
# Only applies to DEBUG output. This specifies the string to
# use for the 'stream' that is passed to log.io. This supports sprintf strings.
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^
config :debug_stream_format, :validate => :string, :default => "debug"
# Only applies to DEBUG output. This specifies the string to
# use for the 'node' that is passed to log.io. This supports sprintf strings.
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^
config :debug_node_format, :validate => :string, :default => "%{type}"
# Only applies to DEBUG output. This specifies the string to
# use for the 'log level' that is passed to log.io. This supports sprintf strings.
# This setting affects the RAW output to log.io and, as far as I can tell, it does
# not affect what log.io displays in any way.
#
# +log|debug|myapp|DEBUG|A message here...
# ^
config :debug_log_level_format, :validate => :string, :default => "DEBUG"
# Only applies to DEBUG output. To help ensure that all '=>' arrows line
# up in debug output, even across multiple events, we'll use this number
# to enforce a rough min length for the padding and hash key of each field.
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^ ^ = 14
config :debug_eq_left_length, :validate => :number, :default => 35
# Only applies to DEBUG output. To help ensure that all event timestamps
# line up in debug output, even across multiple events, we'll use this number
# to enforce a rough min length for the stream and node fields in the output.
#
# debug myapp >> 09:45:15 AM UTC : ....... "type" => "myapp",
# ^ ^ = 13
config :debug_stream_node_length, :validate => :number, :default => 20
# The constructor (of sorts)
public
def register
# We need this for awesome_inspect
require "ap"
end
# Decode: Convert incoming
# This is not supported by this codec as it would not serve a purpose.
public
def decode(data)
raise "The Log.io Codec cannot be used to decode messages (i.e. on an input)."
end
public
# Encode: Encode the data for transport
def encode(data)
# Find date/time string
field_time = data['@timestamp'].strftime(@timestamp_format)
# Handle the debug transmission, if desired
if @debug_output == true
# This code IS a bit sloppy. This is due to my lack of
# Ruby knowledge/skill. Since this won't be used in production (hopefully),
# it should not matter very much.
# Resolve a few strings
debug_field_stream = data.sprintf(@debug_stream_format)
debug_field_node = data.sprintf(@debug_node_format)
debug_field_level = data.sprintf(@debug_log_level_format)
# Create the event divider line:
#
# debug myapp >> 09:45:15 AM UTC :
# debug myapp >> 09:45:15 AM UTC : -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# debug myapp >> 09:45:15 AM UTC :
#
div = "\n" + ("-=" * 100) + "-\n"
# Create the initial string
str = div + "\n" + data.to_hash.awesome_inspect
# Log.io will eliminate extra whitespace so
# we have to use dots to indent.
#
# debug myapp >> 09:45:15 AM UTC : ..... "message" => "app started",
# ^
str = str.gsub(/ /,'..')
# This code ensures there is a space after the dots but before
# the hash key of the event.
#
# debug myapp >> 09:45:15 AM UTC : ..... "message" => "app started",
# ^
str = str.gsub(/\.\.\."/,'.. "')
# These dots will be added to array elements because
# .awesome_inspect does not properly indent arrays.
#
# debug myapp >> 09:45:15 AM UTC : .... "tags" => [
# debug myapp >> 09:45:15 AM UTC : .................. [0] "example",
# ^
array_element_indent = "......................."
# Ensures that there is a space between the dots and [ start of array elements
#
# debug myapp >> 09:45:15 AM UTC : .................. [0] "example",
# ^
str = str.gsub(/\.\.\.\[/,array_element_indent + '.. [')
# Ensures that there is a space between the dots and ] end of arrays
#
# debug myapp >> 09:45:15 AM UTC : ............... ]
# ^
str = str.gsub(/\.\.\.\]/,array_element_indent + '.. ]')
# Split our multi-line string into an array
arr = str.split(/\n/)
# --------------------------------------------------------------------
# Note:
# awesome_inspect() right aligns keys to make => assignments line up.
# However, since it calculates the alignment point based on the lengths
# of the keys in the current event (only) we will enforce a minimum
# indentention so that ALL events line up properly by padding messages
# to a minimum dot indention.
# --------------------------------------------------------------------
# We'll base the padding on the index (location) of the '=' equal sign
# in the 4th line of our array. The fourth line is actually the first
# hash key (usually 'message') because of our div and blank lines that surround it.
pad_length_check_index = 4
equal_sign_index = arr[pad_length_check_index].index('=')
# This shouldn't happen, but just in case there is not an '=' sign
# in our checked string we'll report an error.
if equal_sign_index.nil?
ident_consistency_padding = ""
@on_event.call("+log|debug|logio_codec|WARNING|Parse Error 001: The message did not contain an equal sign where expected.\r\n")
else
# We force the hash key length + padding to
# be at least @debug_eq_left_length characters/bytes.
consistency_padding_amount = @debug_eq_left_length - equal_sign_index
# Just in case it's too long. This will result in weird
# output but shouldn't break anything.
if( consistency_padding_amount > 0 )
ident_consistency_padding = "." * consistency_padding_amount
else
ident_consistency_padding = ""
@on_event.call("+log|debug|logio_codec|WARNING|Parse Error 002: Long field name found, consider increasing codec param: debug_eq_left_length\r\n")
end
end
# Because log.io prepends messages with the node and stream names,
# we will padd our messages using '>' to make them line up in the buffer.
# The 'stream' is actually fixed, so we only have to pad based on the 'node'.
stream_concat = debug_field_stream + " " + debug_field_node
stream_length = stream_concat.length
if( stream_length < @debug_stream_node_length )
neg_stream_length = @debug_stream_node_length - stream_length
else
neg_stream_length = 0
@on_event.call("+log|debug|logio_codec|WARNING|Parse Error 003: Long node and stream found, consider increasing codec param: debug_stream_node_length\r\n")
end
stream_padding = ">" * neg_stream_length
# Output each line of our array
arr.each_with_index do |line,index|
if( index < 4 )
real_field_indent_string = ''
else
real_field_indent_string = ident_consistency_padding
end
# We will not show the { and } lines as they just waste space
if (line != "{" && line != "}")
# Output!
@on_event.call("+log|" + debug_field_stream + "|" + debug_field_node + "|" + debug_field_level + "|" + stream_padding + " " + field_time + " : " + real_field_indent_string + line + "\r\n")
end
end
end
# Perform standard output
# e.g. +log|debug|myapp|INFO|A log message\r\n
# Resolve a few strings
standard_field_stream = data.sprintf(@standard_stream_format)
standard_field_node = data.sprintf(@standard_node_format)
standard_field_level = data.sprintf(@standard_log_level_format)
if data.is_a? LogStash::Event and @standard_message_format
standard_field_message = data.sprintf(@standard_message_format)
@on_event.call("+log|" + standard_field_stream + "|" + standard_field_node + "|" + standard_field_level + "|" + field_time + " : " + standard_field_message + "\r\n")
else
@on_event.call("+log|" + standard_field_stream + "|" + standard_field_node + "|" + standard_field_level + "|" + field_time + " : Raw Output (parse failure): " + data.to_s + "\r\n")
@on_event.call("+log|standard|logio_codec|WARNING|Parse Error 004: Unable to process event or missing standard_message_format.\r\n")
end
end
end |
class Shelter < ActiveRecord::Base
has_many :pets
has_many :shelter_users
has_many :users, through: :shelter_users
validates :name, uniqueness: true
end
|
FactoryBot.define do
factory :type do
name 'Angel'
end
end
|
FactoryGirl.define do
factory :user do
name "Thomas A. Anderson"
email "thomas.a.anderson@metacortex.com"
password "ilovetrinity"
end
factory :board do
title "Project: Exit Matrix"
description "Follow the white rabbit"
user_id 1
end
factory :list do
title "Done"
board_id 1
end
end
|
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# key :string(255)
# hub_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# logo :string(255)
# misc_image :string(255)
#
class Project < ActiveRecord::Base
attr_accessible :name, :email, :logo, :misc_image, :hub_id, :hub, :approved
belongs_to :hub
has_many :pages, dependent: :destroy
before_save :create_key
validates :name, presence: true, length: { maximum: 100 }
validates :email, presence: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
validates :hub_id, presence: true
default_scope order: 'name'
private
def create_key
self.key = SecureRandom.urlsafe_base64(6) unless self.key
end
end
|
class AddUserToStudents < ActiveRecord::Migration[5.2]
def change
add_reference :students, :user_id, index: true, foreign_key: { to_table: :users }
end
end
|
class ReviewsController < ApplicationController
def new
@review = Review.new
# @booking = Booking.find(params[:booking_id])
# authorize@review
end
def create
@review = Review.new(review_params)
@booking = Booking.find(params[:booking_id])
@user = booking.user
@review.booking = @booking
@review.user = @user
@review.save
if @review.save
redirect_to 'chef_path'
else
render :new
end
end
def edit
@review = Review.find(params[:id])
end
def update
@review = Review.find(params[:id])
@review.update(review_params)
redirect_to chef_path(@review.booking.chef)
end
private
def review_params
params.require(:review).permit(:content, :rating, :user_id, :booking_id)
end
end
|
module PolicyfileDeliveryTruck
module Helpers
module_function
# Returns the filename relative to the repo root
def repo_path(node, filename)
File.join(node['delivery']['workspace']['repo'], filename)
end
# Return whether there is a policyfile present in the repo
def repo_has_policyfile?(node)
File.exist?(repo_path(node, 'Policyfile.rb'))
end
def policy_changed?(node, _chef_server_url)
# Work out if the policy we have in the repo is different than the
# policy used to build the AMI
return unless repo_has_policyfile?(node)
chef_server = DeliverySugar::ChefServer.new
chef_server.with_server_config do
build_policy = Chef::ServerAPI.new.get('policy_groups')['build']['policies'][policy_name(node)]
return true if build_policy.nil?
return build_policy['revision_id'] != policy_revision(node)
end
end
def policy_group(node)
curr_stage = node['delivery']['change']['stage']
delivery_config = node['delivery']['config']['policyfile-delivery-truck']
# Return the current policy group
if curr_stage != 'delivered'
curr_stage
else
delivery_config['delivered_policy_group']
end
end
# Return the policy name in the policyfile, if any
def policy_name(node)
return unless repo_has_policyfile?(node)
policy = nil
File.foreach(repo_path(node, 'Policyfile.rb')) do |l|
m = /^\s*name ['"]([a-zA-Z0-9_-]+)["']/.match(l)
if m
policy = m[1]
break
end
end
policy
end
def policy_revision(node)
return unless repo_has_policyfile?(node)
policy = JSON.parse(File.read(repo_path(node, 'Policyfile.lock.json')))
policy['revision_id']
end
end
module DSL
# methods that are included directly in the DSL where you have access to
# things like the chef node. Things are split out like this to assist with
# testing.
def repo_path(filename)
PolicyfileDeliveryTruck::Helpers.repo_path(node, filename)
end
def repo_has_policyfile?
PolicyfileDeliveryTruck::Helpers.repo_has_policyfile?(node)
end
def policy_changed?
PolicyfileDeliveryTruck::Helpers.policy_changed?(node, _chef_server_url)
end
def policy_group
PolicyfileDeliveryTruck::Helpers.policy_group(node)
end
def policy_name
PolicyfileDeliveryTruck::Helpers.policy_name(node)
end
def policy_revision
PolicyfileDeliveryTruck::Helpers.policy_revision(node)
end
def chef_server_url
begin
delivery_config = node['delivery']['config']['policyfile-delivery-truck']
rescue NoMethodError
delivery_config = {}
end
url = delivery_config['chef-server']
# Allow an empty value or a value of 'delivery' to signal that the
# delivery chef server should be used.
if url.empty? || url == 'delivery'
delivery_chef_server[:chef_server_url]
else
url
end
end
end
end
# And these mix the DSL methods into the Chef infrastructure
Chef::Resource.include PolicyfileDeliveryTruck::DSL
Chef::DSL::Recipe.include PolicyfileDeliveryTruck::DSL
|
# encoding: utf-8
require "logstash/inputs/base"
require "logstash/namespace"
require "stud/interval"
require "koala"
# Generate a repeating message.
#
# This plugin is intented only as an example.
class LogStash::Inputs::Facebook < LogStash::Inputs::Base
config_name "facebook"
# If undefined, Logstash will complain, even if codec is unused.
default :codec, "plain"
# OAuth token to access the facebook API with
config :oauth_token, :validate => :string, :required => true
# How often to monitor the feed for new data
config :interval, :validate => :number, :default => 300
# Facebook ID of the feed to monitor
config :facebook_id, :validate => :number
public
def register
@api = Koala::Facebook::API.new(@oauth_token)
end
def run(queue)
# we can abort the loop if stop? becomes true
while !stop?
feed = @api.get_connections(@facebook_id, "feed")
feed.each do |p|
event = LogStash::Event.new(p)
decorate(event)
queue << event
end
# because the sleep interval can be big, when shutdown happens
# we want to be able to abort the sleep
# Stud.stoppable_sleep will frequently evaluate the given block
# and abort the sleep(@interval) if the return value is true
Stud.stoppable_sleep(@interval) { stop? }
end # loop
end # def run
def stop
# nothing to do in this case so it is not necessary to define stop
# examples of common "stop" tasks:
# * close sockets (unblocking blocking reads/accepts)
# * cleanup temporary files
# * terminate spawned threads
end
end # class LogStash::Inputs::Example
|
require 'forwardable'
require 'skype/api'
require 'skype/chat'
require 'skype/chatmessage'
require 'skype/events'
module Skype
class << self
extend Forwardable
def_delegator Skype::Api, :instance, :instance
def_delegator Skype::Api, :attach
def_delegator Skype::Chat, :new, :chat
def_delegator Skype::Chat, :all, :chats
def_delegator Skype::Events, :on
Skype::Events.initialize_listeners
end
end
|
class CreateBillentries < ActiveRecord::Migration[5.0]
def change
create_table :billentries do |t|
t.string :truck_no
t.string :company_name
t.string :address
t.datetime :time_arrive
t.datetime :time_departure
t.date :current_date
t.decimal :supply_rate
t.decimal :weight
t.decimal :previous_amount
t.decimal :current_total_amount
t.decimal :recieved_amount
t.decimal :net_balance
t.decimal :total_amount
t.timestamps
end
end
end
|
# -*- encoding : utf-8 -*-
require 'rails_helper'
describe 'people module' do
it 'is forbidden to view index without authentication' do
people.navigate_to_index expect: :forbidden
end
it 'is forbidden to view index without an associated church' do
home.login :user
people.navigate_to_index expect: :forbidden
end
describe 'with a valid church' do
before :each do
setup.login_with_church :user, :church
end
it 'allows adding a person' do
people.add :person
people.has_people :person
end
it 'allows editing a person' do
people.add :person
people.edit :person, first_name: 'Roger', last_name: 'Banks'
people.has_people :person
end
it 'should not list people from other churches' do
people.add :person
people.has_people :person
home.logout
setup.login_with_church :user2, :church2
people.has_people #none
end
end
end
|
require 'set'
input = File.read("/Users/hhh/JungleGym/advent_of_code/2020/inputs/day09.in").split("\n").map { |x| x.to_i }
def sum_in? n, window
set = Set.new(window)
set.any? do |x|
complement = n-x
set.include? complement
end
end
def part1 input
x, y = 0, 25
window = input[x,y]
queue = input[y, input.size]
while !queue.empty?
curr = queue.shift
if !sum_in? curr, window
return curr
end
window.shift
window << curr
end
end
target = part1 input
p "part 1: #{target}"
x = 0
y = x + 2
while y < input.size
window = input[x..y]
sum = window.reduce(:+)
if sum == target
p "part 2: #{window.min + window.max}"
break
end
if sum < target
y += 1
end
if sum > target
x += 1
y = x + 1
end
end
|
require "json"
class WatsonService
include IBMWatson
def initialize(text)
@text = text
end
def analyse
authenticator = Authenticators::IamAuthenticator.new(
apikey: ENV["WATSON_API_KEY"]
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2021-03-25",
authenticator: authenticator
)
natural_language_understanding.service_url = "https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/12ed5a68-6868-461b-9fb8-a3208f37d7fc"
response = natural_language_understanding.analyze(
text: @text,
features: {
emotion: {},
sentiment: {},
keywords: {sentiment: true, emotion: true, limit:3}
}
)
JSON.parse(JSON.pretty_generate(response.result))
end
end
|
module Util
module StringHelper
def pluralize(word)
if word.to_s.end_with?("s")
word
else
word << "s"
end
word
end
end
end |
class Expense < ActiveRecord::Base
belongs_to :category
belongs_to :purse
validates_presence_of :amount, :date, :category, :purse
def self.search_query(params)
expenses = Expense.arel_table
categories = Category.arel_table
q = expenses
.project('expenses.*',
categories[:id].as('category_id'),
categories[:title].as('category_title'),
categories[:color].as('category_color'))
.join(categories).on(expenses[:category_id].eq(categories[:id]))
.group(expenses[:id], categories[:id], categories[:title], categories[:color])
if %w(amount date comment).include?(params[:sort_column]) && %w(asc desc).include?(params[:sort_type])
q.order(expenses[params[:sort_column]].send(params[:sort_type] == 'asc' ? :asc : :desc))
elsif (params[:sort_column] == 'category') && %w(asc desc).include?(params[:sort_type])
q.order(categories[:title].send(params[:sort_type] == 'asc' ? :asc : :desc))
else
q.order(expenses[:id].desc)
end
q.where(expenses[:id].eq(params[:id])) if params[:id].present?
q.where(expenses[:comment].matches("%#{params[:comment]}%")) if params[:comment].present?
q.where(expenses[:date].gteq(Date.parse(params[:from_date]).beginning_of_day)) if params[:from_date].present?
q.where(expenses[:date].lteq(Date.parse(params[:to_date]).end_of_day)) if params[:to_date].present?
q.where(expenses[:date].in(Date.parse(params[:date]).beginning_of_day..Date.parse(params[:date]).end_of_day)) if params[:date].present?
q.where(expenses[:created_at].in(Date.parse(params[:created_at]).beginning_of_day..Date.parse(params[:created_at]).end_of_day)) if params[:created_at].present?
q.where(expenses[:updated_at].in(Date.parse(params[:updated_at]).beginning_of_day..Date.parse(params[:updated_at]).end_of_day)) if params[:updated_at].present?
q.where(categories[:title].matches("%#{params[:category]}%")) if params[:category].present?
q
end
private
end
|
class AddLocationNameToRestaurants < ActiveRecord::Migration
def change
add_column :restaurants, :location_name, :string
end
end
|
class Model < ApplicationRecord
include Ownable
include Fieldable
include Categorizable
include Documentable
multisearchable(
against: [:name, :model_number],
additional_attributes: ->(record) { { label: record.name } },
)
pg_search_scope(
:search,
against: [:name, :model_number], associated_against: {
category: [:name],
manufacturer: [:name]
}, using: {
tsearch: { prefix: true },
trigram: {}
},
ignoring: :accents,
)
slug :name
tracked
resourcify
belongs_to :manufacturer
has_many :items, -> { includes_associated }
has_many :accessories, -> { includes_associated }
has_many :consumables, -> { includes_associated }
has_many :components, -> { includes_associated }
validates_presence_of :name
validates :name, uniqueness: { scope: :model_number, message: "Model already exists" }
scope :includes_associated, -> { includes([:manufacturer, :category, :items, :accessories, :consumables, :components, :documentations]) }
def types
self.category.type.where(model: self)
end
end
|
module SubmissionsHelper
def fields_for_item(item, &block)
prefix = item.new_record? ? 'new' : 'existing'
fields_for("submission[#{prefix}_item_attributes][]", item, &block)
end
def add_item_link(name)
link_to_function name do |page|
page.insert_html :bottom, :items, :partial => 'item', :object => Item.new
end
end
end |
require 'spec_helper'
describe 'Service Options', reset: false do
downloadable_collection_id = 'C90762182-LAADS'
downloadable_collection_title = 'MODIS/Aqua Calibrated Radiances 5-Min L1B Swath 250m V005'
collection_with_intermittent_timeline_id = 'C179003030-ORNL_DAAC'
before :all do
load_page :search, overlay: false
login
end
context 'for collections with granule results' do
before :all do
load_page :search, project: [downloadable_collection_id], view: :project
wait_for_xhr
click_link "Retrieve project data"
wait_for_xhr
end
context "when setting options for a collection with order options" do
after :all do
reset_access_page
end
context 'choosing to set an order option' do
before :all do
choose 'FtpPushPull'
end
it 'shows the form for the associated order option' do
expect(page).to have_text('Distribution Options')
end
it 'hides and shows portions of the form based on form selections' do
expect(page).to have_no_text('Ftp Push Information')
select 'FtpPush', from: 'Distribution Options'
expect(page).to have_text('Ftp Push Information')
end
end
end
end
context 'for collections without granule results' do
before :all do
load_page :search, project: [collection_with_intermittent_timeline_id], view: :project, temporal: ['2014-07-10T00:00:00Z', '2014-07-10T03:59:59Z']
wait_for_xhr
click_link "Retrieve project data"
wait_for_xhr
end
it 'displays no service options' do
expect(page).to have_no_field('FtpPushPull')
end
it 'displays a message indicating that there are no matching granules' do
expect(page).to have_text('There are no matching granules to access for this collection')
end
end
context "for collections with bounding box prepopulation options" do
context "when the project's query has a spatial filter" do
before :all do
load_page 'data/configure', {project: ['C1000000560-NSIDC_ECS'],
granule_id: 'G1001048061-NSIDC_ECS',
bounding_box: [1, 2, 3, 4]}
end
it "prepopulates the options form with the filter's MBR" do
choose 'AE_SI12.3 ESI Service'
check 'Enter bounding box'
expect(page).to have_field('North', with: "3")
expect(page).to have_field('South', with: "1")
expect(page).to have_field('East', with: "4")
expect(page).to have_field('West', with: "2")
end
end
context "when the project's query has no spatial filter" do
before :all do
load_page 'data/configure', {project: ['C1000000560-NSIDC_ECS'],
granule_id: 'G1001048061-NSIDC_ECS'}
end
it "does not prepopulate the form" do
choose 'AE_SI12.3 ESI Service'
check 'Enter bounding box'
expect(page).to have_field('North', with: "90")
expect(page).to have_field('South', with: "-90")
expect(page).to have_field('East', with: "180")
expect(page).to have_field('West', with: "-180")
end
end
end
end
|
class SharedIdentityCookie
def self.public_key
@public_key ||= begin
uri = ServiceDescriptor.discover(:kernel, "SharedIdentityCookieRsaPublicKey")
response = Datapathy.adapters[:ssbe].http.resource(uri).get(:accept => 'application/x-pem-file')
response.body
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.