text stringlengths 10 2.61M |
|---|
require 'rspec'
require_relative '../../lib/csv_import'
RSpec.describe CsvImport do
let(:agency_name) { "Some Agent" }
let!(:import) { described_class.new(filename, agency_name) }
describe "initializing" do
let(:filename) { "spec/fixtures/empty.csv" }
it "sets filename and agency name attribute" do
expect(import.filename).to eq(filename)
expect(import.agency_name).to eq(agency_name)
end
end
describe "file with a single record" do
let(:filename) { "spec/fixtures/single.csv" }
it "creates one transaction with property, client and agency" do
import.run
transaction = Transaction.last
expect(transaction).to_not be_nil
expect(transaction.property).to_not be_nil
expect(transaction.client).to_not be_nil
expect(transaction.agency.name).to eq agency_name
end
end
describe "file with a duplicate record" do
let(:filename) { "spec/fixtures/duplicate.csv" }
it "creates only one transaction, property, client and agency" do
import.run
expect(Property.count).to eq 1
expect(Client.count).to eq 1
expect(Agency.count).to eq 1
expect(Transaction.count).to eq 1
end
end
describe "import including multiple transactions" do
let(:filename) { "spec/fixtures/multiple.csv" }
it "creates only one property with multiple transactions" do
import.run
expect(Property.count).to eq 1
expect(Transaction.count).to eq 2
end
end
describe "when running the same import multiple times" do
let(:filename) { "spec/fixtures/single.csv" }
it "creates no transactions and returns meaningful message" do
import.run
expect { import.run }.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Name You are trying to run the same import a second time")
end
end
describe "missing file" do
let(:filename) { "spec/fixtures/missing.csv" }
it "raises an exception with meaningful message" do
expect { import.run }.to raise_error(ImportFile::LocationError, "File is missing")
end
end
describe "empty file" do
let(:filename) { "spec/fixtures/empty.csv" }
it "creates no transactions with empty import" do
import.run
expect(Property.count).to eq 0
end
end
describe "incorrectly formatted file" do
let(:filename) { "spec/fixtures/incorrect.csv" }
it "raises an exception with a meaningful message" do
expect { import.run }.to raise_error(ImportFile::FormatError, "File format is incorrect")
end
end
describe "file with some invalid records" do
let(:filename) { "spec/fixtures/some_invalid_records.csv" }
it "imports correct records and saves remaining records into corrections directory" do
import.run
expect(Transaction.count).to eq 1
expect(Property.count).to eq 1
expect(Client.count).to eq 1
expect(Agency.count).to eq 1
expect(CSV.read("./corrections/error.csv").count).to eq(2)
File.delete "./corrections/error.csv"
end
end
end
|
module ApplicationHelper
def sidebar_link_options(section)
if %w( about documentation reference book blog videos
external-links downloads guis logos community
).include?(@section) && @section == section
{class: "active"}
else
{}
end
end
def partial(part)
render part
end
def random_tagline
content_tag(:em, '-' * 2) + TAGLINES.sample
end
def latest_version
begin
@version ||= Version.latest_version
@version.name
rescue
""
end
end
def latest_release_date
begin
@version ||= Version.latest_version
'(' + @version.committed.strftime("%Y-%m-%d") + ')'
rescue
""
end
end
def latest_relnote_url
"https://raw.github.com/git/git/master/Documentation/RelNotes/#{self.latest_version}.txt"
end
# overriding this because we're not using asset pipeline for images,
# but jason is using image_tag
def image_tag(image, options = {})
out = "<img src='/images/" + image + "'"
out += " width='" + options[:width].to_s + "'" if options[:width]
out += " height='" + options[:height].to_s + "'" if options[:height]
out += " />"
raw out
end
end
|
Rails.application.routes.draw do
root to: "pages#root"
get "fancy", to: "pages#fancy"
get "tooltip", to: "pages#tooltip"
get "datepicker", to: "pages#datepicker"
end
|
class Target < ActiveRecord::Base
belongs_to :age_group
belongs_to :provider
validates :age_group, :provider, presence: true
validates :provider, uniqueness: { scope: :age_group}
end
|
require 'spec_helper'
describe ItemsController do
before do
@user = Factory(:user)
@store = Factory(:store)
end
def valid_attributes
{ store_id: @store.id, name: 'Stuff and things' }
end
def valid_session
{ user_id: @user.id }
end
describe "POST create" do
describe "with valid params" do
it "creates a new Item" do
expect {
post :create, {:store_id => @store.id, :item => valid_attributes}, valid_session
}.to change(Item, :count).by(1)
end
it "assigns a newly created item as @item" do
post :create, {:store_id => @store.id, :item => valid_attributes}, valid_session
assigns(:item).should be_a(Item)
assigns(:item).should be_persisted
end
it "redirects to the associated store" do
post :create, {:store_id => @store.id, :item => valid_attributes}, valid_session
response.should redirect_to(@store)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved item as @item" do
# Trigger the behavior that occurs when invalid params are submitted
Item.any_instance.stub(:save).and_return(false)
post :create, {:store_id => @store.id, :item => {}}, valid_session
assigns(:item).should be_a_new(Item)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
Item.any_instance.stub(:save).and_return(false)
post :create, {:store_id => @store.id, :item => {}}, valid_session
response.should render_template("new")
end
end
end
end
|
require 'mechanize'
require 'singleton'
module Ayaneru
class Niconico
include Singleton
URL = {
login: 'https://secure.nicovideo.jp/secure/login?site=niconico',
search: 'http://api.search.nicovideo.jp/api/',
reserve: 'http://live.nicovideo.jp/api/watchingreservation'
}
attr_reader :agent, :logined
def initialize
YAML.load_file(File.expand_path(File.dirname(__FILE__)) + '/niconico_account.yml').each do |sym, value|
instance_variable_set('@' + sym, value)
end
@logined = false
@agent = Mechanize.new
@agent.ssl_version = 'SSLv3'
end
def login
page = @agent.post(URL[:login], 'mail' => @mail, 'password' => @password)
raise LoginError, "Failed to login (x-niconico-authflag is 0)" if page.header["x-niconico-authflag"] == '0'
@logined = true
end
def logout
Ayaneru.niconico.agent.cookie_jar.clear!
@logined = false
end
end
class LoginError < StandardError; end
end
require_relative 'niconico/search'
require_relative 'niconico/reserve'
|
class AddColumnToAboutUs < ActiveRecord::Migration
def change
add_column :about_us, :url, :string
end
end
|
#
# Author:: Matheus Francisco Barra Mina (<mfbmina@gmail.com>)
# © Copyright IBM Corporation 2015.
#
# LICENSE: MIT (http://opensource.org/licenses/MIT)
#
require 'fog/softlayer/models/account/brand'
module Fog
module Softlayer
class Account
class Brands < Fog::Collection
model Fog::Softlayer::Account::Brand
def all
data = service.get_account_owned_brands
load(data)
end
def get(identifier)
return nil if identifier.nil? || identifier == ""
data = service.get_brand(identifier).body
new.merge_attributes(data)
rescue Excon::Errors::NotFound
nil
end
end
end
end
end
|
class LocationPictureSerializer < ActiveModel::Serializer
attributes :id, :title, :location, :tags, :avatar, :user
end
|
module V1
class RunsController < V1Controller
before_action :set_run, only: [:show, :update, :destroy]
# GET /runs
def index
@runs = @athelete.runs.order(created_at: :desc)
render json: @runs
end
# POST /runs
def create
run_params['distance_in_meters']
@run = Run.new({
athelete: @athelete,
distance_in_meters: run_params['distance_in_meters'],
time_in_seconds: run_params['time_in_seconds'],
})
if @run.save
@runs = @athelete.runs.order(created_at: :desc)
render json: @runs, status: :created
else
render json: @run.errors, status: :unprocessable_entity
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_run
@run = Run.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def run_params
params.fetch(:run, {}).permit(:distance_in_meters, :time_in_seconds)
end
end
end
|
# frozen_string_literal: true
module Decidim
module Opinions
class NotifyOpinionsMentionedJob < ApplicationJob
def perform(comment_id, linked_opinions)
comment = Decidim::Comments::Comment.find(comment_id)
linked_opinions.each do |opinion_id|
opinion = Opinion.find(opinion_id)
affected_users = opinion.notifiable_identities
Decidim::EventsManager.publish(
event: "decidim.events.opinions.opinion_mentioned",
event_class: Decidim::Opinions::OpinionMentionedEvent,
resource: comment.root_commentable,
affected_users: affected_users,
extra: {
comment_id: comment.id,
mentioned_opinion_id: opinion_id
}
)
end
end
end
end
end
|
# frozen_string_literal: true
class AddStabbingToCausesOfDeath < ActiveRecord::Migration[5.0]
disable_ddl_transaction!
def change
execute <<-SQL
ALTER TYPE cause_of_death ADD VALUE 'stabbing';
SQL
end
end
|
require 'metatron_ruby_client'
require 'forwardable'
module Talis
module Bibliography
# Represents an eBook which is a type of asset associated with
# works and their manifestations.
#
# In order to perform remote operations, the client must be configured
# with a valid OAuth client that is allowed to query nodes:
#
# Talis::Authentication.client_id = 'client_id'
# Talis::Authentication.client_secret = 'client_secret'
#
class EBook < Talis::Resource
extend Forwardable, Talis::OAuthService, Talis::Bibliography
base_uri Talis::METATRON_HOST
attr_accessor :id, :vbid, :title, :author, :format, :digital_list_price,
:publisher_list_price, :store_price, :edition
private_class_method :new
def initialize(asset_data)
attrs = asset_data.try(:attributes) || {}
@id = asset_data.id
extract_attrs(attrs)
price_list = attrs.fetch(:pricelist, {})
extract_prices(price_list)
end
def extract_attrs(attrs)
@vbid = attrs[:vbid]
@title = attrs[:title]
@author = attrs[:author]
@format = attrs[:'book-format']
@edition = attrs[:edition]
end
def extract_prices(price_list)
@digital_list_price = price_list[:'digital-list-price']
@publisher_list_price = price_list[:'publisher-list-price']
@store_price = price_list.fetch(:'store-price', {})[:value]
end
class << self
def find_by_manifestation_id(manifestation_id, request_id = new_req_id)
id = manifestation_id.gsub('nbd:', '')
begin
set = api_client(request_id).get_manifestation_assets(token, id)
rescue MetatronClient::ApiError => error
return [] if error.code == 404
handle_response(error)
end
set.data.select { |asset| asset.type == Talis::EBOOK_TYPE }
.map { |asset| new(asset) }
end
end
end
end
end
|
class RemoveStreetAddressColumnFromAdoptionRequests < ActiveRecord::Migration
def change
remove_column :adoption_requests, :street_address
end
end
|
module GHI
module Commands
class Status < Command
def options
OptionParser.new do |opts|
opts.banner = 'usage: ghi status'
end
end
def execute
begin
options.parse! args
@repo ||= ARGV[0] if ARGV.one?
rescue OptionParser::InvalidOption => e
fallback.parse! e.args
retry
end
require_repo
res = throb { api.get "/repos/#{repo}" }.body
if res['has_issues']
puts "Issues are enabled for this repo"
else
puts "Issues are not enabled for this repo"
end
end
end
end
end
|
class Shot < ActiveRecord::Base
validates_presence_of :tape_id, :shot_in, :shot_out, :location, :province, :country, :keywords
end
|
require 'csv'
# CSV出力
CSV.generate do |csv|
csv_column_names = %w(id reception_number reception_day customer_name address
phone_number mobile_phone_number machine_model category
condition note progress contacted delivery reminder repair_staff completed)
csv << csv_column_names
@repairs_all.each do |r|
csv_column_values = [
r.id,
r.reception_number,
r.reception_day,
r.customer_name,
r.address,
r.phone_number,
r.mobile_phone_number,
r.machine_model,
r.category,
r.condition,
r.note,
r.progress,
r.contacted,
r.delivery,
r.reminder,
r.repair_staff,
r.completed
]
csv << csv_column_values
end
end
|
class PartnersController < ApplicationController
def create
end
def show
@partner = Partner.find(params[:id])
if @partner.reviews.blank?
@average_review = 0
else
@average_review = @partner.reviews.average(:rating).round(2)
end
end
end
|
# frozen_string_literal: true
# Migrate db
namespace :db do
require 'sequel'
DB = Sequel.connect 'sqlite://db/mscanalysis.sqlite3'
desc 'Generate migration'
task :generate, [:name] do |_, args|
name = args[:name]
abort('Missing migration file name') if name.nil?
content = <<~STR
# frozen_string_literal: true
Sequel.migration do
change do
end
end
STR
timestamp = Time.now.strftime('%Y%m%d%H%M%S')
filename = File.join('db/migrations/', "#{timestamp}_#{name}.rb")
File.write(filename, content)
puts "Generated: #{filename}"
end
desc 'Run migrations'
task :migrate, [:version] do |_, args|
Sequel.extension :migration
if args[:version]
puts "Migrating to version #{args[:version]}"
Sequel::Migrator.apply(DB, 'db/migrations', target: args[:version].to_i)
else
puts 'Migrating to latest'
Sequel::Migrator.apply(DB, 'db/migrations')
end
end
desc 'Rollback migration'
task :rollback, [:step] do |_, args|
Sequel.extension :migration
step = args[:step] ? Integer(args[:step]) : 1
version = 0
target_migration =
DB[:schema_migrations].reverse_order(:filename)
.offset(step)
.first
if target_migration
version = Integer(target_migration[:filename].match(/([\d]+)/)[0])
end
Sequel.extension :migration
Sequel::Migrator.apply(DB, 'db/migrations', version)
end
end
|
module Larvata::Signing
class Flow < ApplicationRecord
has_many :resources, class_name: "Larvata::Signing::Resource",
foreign_key: "larvata_signing_flow_id"
has_many :flow_stages, class_name: "Larvata::Signing::FlowStage",
foreign_key: "larvata_signing_flow_id"
# 取得指定簽核流程資料結構,並放入簽核單內
def self.pull_flow(flow_id, current_user)
flow = Larvata::Signing::Flow.includes(flow_stages: :flow_members).find_by_id(flow_id)
doc = Larvata::Signing::Doc.new(flow.attributes.slice("remind_period").merge({"larvata_signing_flow_id" => flow_id}))
flow.flow_stages.each do |flow_stage|
stage = doc.stages.build(flow_stage.attributes.slice("typing", "seq"))
unless flow_stage.supervisor_sign?
flow_stage.flow_members.each do |flow_member|
stage.srecords.build(flow_member.attributes.slice("dept_id", "role").merge({"signer_id" => flow_member.user_id}))
end
else
# TBD 建立主管簽核資料
end
end
doc
end
end
end
|
class Message < BaseREST
cache_expires 1.minute
delegate :attributes, :display, :attribute_unit, to: :sensor
def data
return "Parser not implemented" unless sensor_class
begin
sensor.attributes.inspect
rescue EOFError => err
return {}
end
end
def sensor_class
"Sensors::#{device.model.downcase.capitalize}".safe_constantize || Sensors::Base
end
def sensor
@sensor ||= sensor_class.new(message: self)
end
def device
@device ||= Rails.cache.fetch("message/device/#{self.devEUI}", expires: 24.hour) do
Project.all.map { |p| p.devices }.flatten.select{ |d| d.devEUI == self.devEUI }.first
end
end
def created_at
DateTime.parse(self.createdAt).in_time_zone
end
end
|
class Student < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:rememberable, :trackable, :validatable
has_many :records, dependent: :destroy
has_many :courses, through: :records
accepts_nested_attributes_for :courses
scope :undeclared_major, -> { where(major: "Undeclared") }
scope :declared_major, -> { where.not(major: "Undeclared") }
def find_student_record(course)
records.find_by_course_id(course.id)
end
def show_gpa
semester_gpa = gpa.to_s
semester_gpa.present? ? semester_gpa : "pending"
end
def calculate_gpa
credits = courses.pluck(:credit).sum
score = 0.0
student_records = records.where("course_id IN (?)", course_ids)
student_records.pluck(:grade).each do |grade|
score += grade_to_number grade
end
gpa = score / credits
update(gpa: gpa)
end
private
def grade_to_number grade
score = 0.0
case grade
when "A"
score = 4.0
when "B"
score = 3.0
when "C"
score = 2.0
when "D"
score = 1.0
when "F"
score = 0.0
end
score
end
end
|
require 'rails_helper'
RSpec.describe "Brands", type: :request do
before(:each) do
request_login_admin
end
describe "GET /brands" do
it "responded successfully" do
get brands_path
expect(response).to have_http_status(200)
end
end
end
|
require File.dirname(__FILE__) + '/../../spec_helper'
describe 'EC2.detach_volume' do
before(:all) do
@ec2 = Fog::AWS::EC2.gen
@instance_id = @ec2.run_instances('ami-5ee70037', 1, 1, {'Placement.AvailabilityZone' => 'us-east-1a'}).body['instancesSet'].first['instanceId']
@volume_id = @ec2.create_volume('us-east-1a', 1).body['volumeId']
eventually(128) do
@ec2.attach_volume(@volume_id, @instance_id, '/dev/sdh')
end
end
after(:all) do
eventually do
@ec2.delete_volume(@volume_id)
@ec2.terminate_instances([@instance_id])
end
end
it "should return proper attributes" do
eventually do
actual = @ec2.detach_volume(@volume_id)
actual.body['attachTime'].should be_a(Time)
actual.body['device'].should be_a(String)
actual.body['instanceId'].should be_a(String)
actual.body['requestId'].should be_a(String)
actual.body['status'].should be_a(String)
actual.body['volumeId'].should be_a(String)
end
end
end |
class SearchController < ApplicationController
skip_authorization_check
def search
@results = params[:tag].present? ? Question.tagged_with(params[:tag]) : ThinkingSphinx.search(params[:q], classes: filters)
put_questions_at_top
end
private
def filters
search_in = []
search_in << Question if params[:search_questions] == '1'
search_in << Answer if params[:search_answers] == '1'
search_in << Comment if params[:search_comments] == '1'
search_in.concat [Question, Answer, Comment] if search_in.empty?
search_in
end
def put_questions_at_top
temp = @results.select { |element| element.is_a? Question }
@results = temp + (@results - temp)
end
end
|
class Picture < ActiveRecord::Base
belongs_to :user
belongs_to :album, :counter_cache => true
validates_presence_of :album_id,:message=>'请选择一个相册'
validates_presence_of :logo,:on=>:create,:message=>'请选择上传文件'
upload_column :logo,:process => '1024x1024',:versions => {:web => "600x600",:thumb=>"140x140"}
end
|
module ApplicationHelper
def phone_number_display(phone_number)
# format the passed phone number for display
return nil if phone_number.blank?
PhoneNumberParser.format_for_display(phone_number)
end
def message_inbound_or_outbound(message)
# return a string indicating whether the message is inbound or outbound
return Message::INBOUND if message.inbound
Message::OUTBOUND
end
def feature_flag_for(flag)
@flags ||= {}
@flags[flag] = FeatureFlag.enabled?(flag) if @flags[flag].nil?
@flags[flag]
end
def client_messages_status(rr)
if rr.has_message_error
Message::ERROR
elsif rr.has_unread_messages
Message::UNREAD
else
Message::READ
end
end
end
|
#!/usr/bin/env ruby
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'uri'
require 'date' # needed to make it run on my osx machine for some reason
require 'builder' # for constructing formats of output
require 'trollop' # parsing command line arguments
# TODO
# - list tweets out that you want to process
# - move into a class
# - CLI interface as per '10 things in ruby I wish I'd known'
# - config file for user, etc
# - use a filehandle for input/output
# - rspec for testing
# - pass in url for source
class TwitterXMLToHTML
# User configurable
Default_twitter_username = "thinkinginrails"
Default_input = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=#{Default_twitter_username}"
Default_url_prefix = "http://twitter.com/thinkinginrails/statuses/"
def initialize(username,input,output)
@twitteruser = username || Default_twitter_username
@input = input || Default_input
@output = output || STDOUT
@tweets = []
#puts "Debug: username = #{@twitteruser} - input: #{@input} - output: #{@output}"
@xml = load_xml(@input)
@tweets = parse_tweets
end
def output_html_all
@tweets.map { |t| output_html(t) }.join("\n")
end
def [](num)
output_html(@tweets[num])
end
private
def output_html(t)
"<li>#{t[:parsed_tweet]} <em><a href=\"#{Default_url_prefix}#{t[:ttweetid]}\">#</a></em></li>"
end
def get_tweet(num)
output_html(@tweet[num])
end
# parse the XML and load up the @tweets array
def parse_tweets
@xml.xpath('//status').each do |status|
id = status.xpath('.//id').first.content
datetext = status.xpath('.//created_at').first.content
tweet = status.xpath('.//text').first.content
date = Date.parse(datetext)
tweettext = parse_tweet(tweet)
# puts "<li>#{tweettext} <em><a href=\"#{Default_url_prefix}#{tweetid}\">#</a></em></li>\n"
this_tweet = { :id => id, :tweet => tweet, :date => date, :parsed_tweet => tweettext }
@tweets << this_tweet
end
@tweets
end
# grabbed from http://stackoverflow.com/questions/2034580/i-am-creating-a-twitter-clone-in-ruby-on-rails-how-do-i-code-it-so-that-the
def linkup_mentions_and_hashtags(text)
text.gsub!(/@([\w]+)(\W)?/, '<a href="http://twitter.com/\1">@\1</a>\2')
text.gsub!(/#([\w]+)(\W)?/, '<a href="http://twitter.com/search?q=%23\1">#\1</a>\2')
text
end
# deal with various tweet parsing code to link usernames, links, etc
def parse_tweet(t)
URI.extract(t, %w[ http https ftp ]).each do |url|
t.gsub!(url, "<a href=\"#{url}\">#{url}</a>")
end
# auto-link @usernames
t = linkup_mentions_and_hashtags(t)
end
def load_xml(path)
# catch if we can't parse the XML
doc = Nokogiri::XML(open(path))
end
end
# Command line parsing
opts = Trollop::options do
opt :config, "Use a YAML config file"
opt :username, "Use this twitter username", :default => "thinkinginrails"
opt :output, "Output file (default STDOUT)", :default => STDOUT
end
p opts
input = "twitter.xml"
twitter_username = "thinkinginrails"
t = TwitterXMLToHTML.new(twitter_username,input,STDOUT)
puts t.output_html_all |
class Store
attr_reader :name, :city, :distance, :type, :phone
def initialize(store)
@name = store[:longName]
@city = store[:city]
@distance = store[:distance]
@type = store[:storeType]
@phone = store[:phone]
end
end |
# encoding: utf-8
require "fileutils"
require "rb.rotate/state"
require "rb.rotate/mail"
module RbRotate
module StorageModule
##
# Represents an item of some entry in storage.
#
class Item
##
# Parent entry.
#
@entry
##
# Indentifier of the item.
#
@identifier
attr_writer :identifier
##
# Full path of the item.
#
@path
##
# Data of the item.
#
@data
##
# Constructor.
#
def initialize(entry, identifier = nil, path = nil)
@entry = entry
@identifier = identifier
@path = path
# Loads data
self.load_data!
end
##
# Returns data.
#
def load_data!
if @data.nil?
if not @path.nil?
@data = State::get.archive.file(@path)
end
# Default
if @path.nil? or @data.nil?
@data = {
:date => Time::now,
:compression => false
}
end
end
end
##
# Rotates itself.
#
def rotate!
if @entry.storage.numeric_identifier? and (self.identifier.kind_of? Numeric)
##
# Unregisters old filename, increases counter
# and register it again.
#
self.unregister!
if self.exists?
old_path = self.path
self.identifier += 1
self.rebuild_path!
self.prepare_directory!
FileUtils.move(old_path, self.path)
self.register!
end
end
return self
end
##
# Returns state object.
#
def state
@entry.file.state
end
##
# Indicates, item still exists in storage.
#
def exists?
::File.exists? self.path
end
##
# Registers itself.
#
def register!
State::archive.register_file(self.path, @data)
end
##
# Unregisters itself.
#
def unregister!
State::archive.unregister_file(self.path)
end
##
# Removes itself.
#
def remove!
self.unregister!
# Eventually mails it if required
if @entry.storage.directory.configuration[:recycle].to_sym == :mail
self.mail!
end
FileUtils.remove(self.path)
end
##
# Mails the file.
#
def mail!
to = @entry.storage.directory.configuration[:mail]
self.decompress!
require "etc"
require "socket"
Mail::send(
:from => Etc.getlogin.dup << "@" << Socket.gethostname,
:to => to,
:subject => Socket.gethostname << " : log : " << self.path,
:body => ::File.read(self.target_path)
)
self.compress!
end
##
# Returns identifier.
#
def identifier
if @identifier.nil?
if @entry.storage.numeric_identifier?
@identifier = 1
else
item_identifier = @entry.storage.item_identifier
if item_identifier.to_sym == :date
format = "%Y%m%d.%H%M"
else
format = item_identifier
end
@identifier = Time::now.strftime(format)
end
end
return @identifier
end
##
# Returns path.
#
def path
if @path.nil?
self.rebuild_path!
end
return @path
end
##
# Generates target (without compression extension) path
# from path.
#
def target_path
if self.compressed?
extension = self.compression[:extension]
result = self.path[0...-(extension.length + 1)]
else
result = self.path
end
return result
end
##
# Rebuilds path.
#
def rebuild_path!
directory = @entry.storage.directory
configuration = directory.configuration
@path = configuration[:storage].dup << "/"
# Adds archive subdirectories structure if necessary
recursive = configuration[:recursive]
if (recursive.kind_of? TrueClass) or (configuration[:recursive].to_sym != :flat)
relative_path = directory.relative_path
if relative_path != ?.
@path << relative_path << "/"
end
end
# Adds filename
@path << self.state.name.to_s << "." << self.identifier.to_s
# Adds extension if necessary
if not self.state.extension.nil?
@path << "." << self.state.extension
end
# Adds compression extension if necessary
if self.compressed?
@path << "." << self.compression[:extension]
end
end
##
# Prepares directory.
#
def prepare_directory!
directory = FileUtils.mkdir_p(::File.dirname(self.path)).first
State::archive.register_directory(directory)
end
##
# Allocates new record.
#
def allocate(method)
# Prepares directory
self.prepare_directory!
# Allocates by required action
case method
when :copy
FileUtils.copy(@entry.file.path, self.path)
when :move
FileUtils.move(@entry.file.path, self.path)
when :append
self.append!(:"no compress")
else
raise Exception::new("Invalid allocating method.")
end
self.compress!
self.register!
return self
end
##
# Appends to item.
#
def append!(compress = :compress)
self.decompress!
::File.open(self.path, "a") do |io|
io.write(::File.read(@entry.file.path))
end
if compress == :compress
self.compress!
end
end
##
# Indicates file is or file should be compressed.
#
def compressed?
result = @data[:compression]
if result.kind_of? Array
result = true
end
return result
end
##
# Compress the file.
#
def compress!
# Checking out configuration
configuration = @entry.storage.directory.configuration
command, extension = configuration[:compress]
decompress = configuration[:decompress]
if not command.kind_of? FalseClass
# Setting file settings according to current
# configuration parameters
if command.kind_of? TrueClass
command = "gzip --best"
extension = "gz"
end
if decompress.kind_of? TrueClass
decompress = "gunzip"
end
@data[:compression] = {
:decompress => decompress,
:extension => extension
}
# Compress
system(command.dup << " " << self.path)
self.rebuild_path!
end
end
##
# Decompress file.
#
def decompress!
if self.compressed? and self.exists?
command = self.compression[:decompress]
system(command.dup << " " << self.path << " 2> /dev/null")
FileUtils.move(self.target_path, self.path)
end
end
##
# Describes compression.
#
def compression
@data[:compression]
end
##
# Returns the creation date.
#
def created_at
@data[:date]
end
##
# Returns the expiration date.
#
def expiration_at
configuration = @entry.storage.directory.configuration
period = configuration[:period].to_seconds
multiplier = configuration[:rotate]
return self.created_at + (period * multiplier)
end
##
# Indicates, item is expired.
#
def expired?
recycle = @entry.storage.directory.configuration[:recycle]
if recycle.kind_of? FalseClass
result = false
else
recycle = recycle.to_sym
end
if recycle and (recycle == :remove) or (recycle == :mail)
result = self.expiration_at < Time::now
end
return result
end
end
end
end
|
class AboutsController < ApplicationController
before_action :set_about, only: [:show, :edit, :update, :destroy]
def index
@about = About.first
if @about
redirect_to @about
else
About.create(content:'about as')
@about = About.first
redirect_to @about
end
end
def show
end
def edit
end
def create
@about = About.new(about_params)
respond_to do |format|
if @about.save
format.html { redirect_to edit_about_path @about, notice: 'Test was successfully created.' }
format.json { render :show, status: :created, location: @test }
else
format.html { render :new }
format.json { render json: @test.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @about.update(about_params)
format.html { redirect_to edit_about_path(@about), notice: 'Test was successfully updated.' }
format.json { render :show, status: :ok, location: @test }
else
format.html { render :edit }
format.json { render json: @test.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_about
@about = About.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def about_params
params.require(:about).permit(:content)
end
end
|
class Org < ActiveRecord::Base
belongs_to :contact, class_name: 'User'
has_many :apps
has_many :comments, as: :commentable
has_many :coaches, class_name: 'User', foreign_key: :coaching_org_id
validates_presence_of :name, :contact_id
validates_uniqueness_of :name
default_scope { order :name => :asc }
enum comment_type: []
def address
[address_line_1, address_line_2, city_state_zip].compact.join(", ")
end
def self.for_user(contact_id)
Org.where(:contact_id => contact_id)
end
def self.import(file)
keys = ['name', 'description', 'url', 'contact_id', "address_line_1", "address_line_2", "city_state_zip", "phone"]
CSV.foreach(file.path, headers: true) do |row|
row = row.select { |key,_| keys.include? key }
if row.empty?
raise "No valid columns. Valid columns are: 'name', 'description', 'url', 'contact_id', 'address_line_1', 'address_line_2', 'city_state_zip', 'phone'"
else
Org.create(row.to_h)
end
end
end
end
|
class AddPathHashToDocuments < ActiveRecord::Migration
def change
add_column :documents, :path_hash, :string, :null => false, :default => '', :after => :path
add_index :documents, :path_hash
Document.all.each do |doc|
doc.path_hash = Document.generate_hash(doc.path)
doc.save
end
end
end
|
class AddColumnToInternalProjects < ActiveRecord::Migration
def change
add_column :internal_projects, :active, :boolean, :default => true
end
end
|
require 'spec_helper'
describe Mappable::Utils do
context 'classify_name' do
let(:name) { 'name-foo_bar_1!' }
subject { Mappable::Utils.classify_name(name) }
it 'converts the name to a class name' do
expect(subject).to eq('NameFooBar1')
end
end
end
|
require_relative '../../../spec_helper'
require_relative '../../../../robot_app/models/concerns/command_executor'
module RobotApp::Models
describe CommandExecutor do
class RobotTestClass < Robot
def initialize; end
end
let(:robot_test) { RobotTestClass.new }
describe :execute_command do
let(:parsed_command) { {command: :unsupported} }
subject { robot_test.send :execute_command, parsed_command }
it 'raises an exception when the command is not supported' do
expect {subject}.to raise_error
end
it 'executes the place command' do
parsed_command[:command] = :place
parsed_command[:params] = []
expect(robot_test).to receive(:execute_place).with parsed_command[:params]
subject
end
it 'raises an exception when the sub execution raises an exception' do
parsed_command[:command] = :place
allow(robot_test).to receive(:execute_place).and_raise 'Sub-execution error'
expect {subject}.to raise_error 'Sub-execution error'
end
end
describe :execute_place do
let(:extension) { [[1,3], [2,4]] }
let(:playground) {
instance_double Playground,
dimensions_count: extension.size,
max: extension.max { |a, b| a.last <=> b.last }.last,
min: extension.min { |a, b| a.first <=> b.first }.first
}
let(:x_coordinate) { extension.first.first }
let(:y_coordinate) { extension.last.first }
let(:command_data) { [x_coordinate.to_s, y_coordinate.to_s, 'NORTH'] }
before :each do
allow(robot_test).to receive(:playground).and_return playground
allow(Position).to receive :new
end
subject { robot_test.send :execute_place, command_data }
it 'raises exception when the coordinates cardinality does not match the playground' do
allow(playground).to receive(:dimensions_count).and_return extension.size + 1
expect {subject}.to raise_error
end
it 'raises exception when the X coordinate is greater than the max X of playground' do
allow(playground).to receive(:max).with(0).and_return x_coordinate - 1
expect {subject}.to raise_error
end
it 'raises exception when the X coordinate is smaller than the min X of playground' do
allow(playground).to receive(:min).with(0).and_return x_coordinate + 1
expect {subject}.to raise_error
end
it 'raises exception when the Y coordinate is greater than the max Y of playground' do
allow(playground).to receive(:max).with(1).and_return y_coordinate - 1
expect {subject}.to raise_error
end
it 'raises exception when the Y coordinate is smaller than the min Y of playground' do
allow(playground).to receive(:min).with(1).and_return y_coordinate + 1
expect {subject}.to raise_error
end
it 'creates a new position with the given placement coordinates' do
expect(Position).to receive(:new).with [x_coordinate, y_coordinate]
subject
end
it 'assigns a new position to the robot' do
new_pos = instance_double Position
allow(Position).to receive(:new).and_return new_pos
expect(robot_test).to receive(:position=).with new_pos
subject
end
{
'NORTH' => Robot::Orientation_north,
'SOUTH' => Robot::Orientation_south,
'EAST' => Robot::Orientation_east,
'WEST' => Robot::Orientation_west
}.each do |parsed_value, expected_value|
it "assigns a new orientation to the robot for #{parsed_value}" do
expect(robot_test).to receive(:direction=).with expected_value
command_data[command_data.size - 1] = parsed_value
subject
end
end
it "raises exception when parsed direction is not supported" do
command_data[command_data.size - 1] = 'Unsupported'
expect {subject}.to raise_error
end
end
describe :execute_move do
describe 'safe move' do
let(:extension) { [[0, 3], [0, 3]] }
let(:safe_coordinates) { [1, 1] }
let(:safe_position) { instance_double Position, coordinates: safe_coordinates }
let(:playground) {
instance_double Playground,
max: extension.max { |a, b| a.last <=> b.last }.last,
min: extension.min { |a, b| a.first <=> b.first }.first
}
before :each do
allow(robot_test).to receive(:playground).and_return playground
allow(robot_test).to receive(:position).and_return safe_position
end
it 'raises exception when the orientation is unsupported' do
allow(robot_test).to receive(:direction).and_return :unknown
expect {robot_test.send :execute_move, []}.to raise_error
end
[
{update: :decremented, dimension_idx: 0, orientation: :west},
{update: :incremented, dimension_idx: 0, orientation: :east},
{update: :incremented, dimension_idx: 1, orientation: :north},
{update: :decremented, dimension_idx: 1, orientation: :south}
].each do |move|
let(:new_position) { instance_double Position }
before :each do
allow(robot_test).to receive(:direction).and_return move[:orientation]
allow(Position).to receive(:new).and_return new_position
allow(robot_test).to receive(:position_within_playground?).and_return true
allow(robot_test).to receive :position=
end
it "creates #{move[:update]} dimension #{move[:dimension_idx]} because of orientation #{move[:orientation]}" do
delta = move[:update] == :incremented ? 1 : -1
new_coordinates = safe_coordinates.dup
new_coordinates[move[:dimension_idx]] += delta
allow(robot_test).to receive(:direction).and_return move[:orientation]
expect(Position).to receive(:new).with new_coordinates
robot_test.send :execute_move, []
end
it 'checks the newly created position against the playground' do
expect(robot_test).to receive(:position_within_playground?).with new_position
robot_test.send :execute_move, []
end
it 'updates the position within the robot' do
expect(robot_test).to receive(:position=).with new_position
robot_test.send :execute_move, []
end
end
end
end
describe :execute_left do
subject { robot_test.send :execute_left, [] }
[
{start: Robot::Orientation_north, stop: Robot::Orientation_west},
{start: Robot::Orientation_west, stop: Robot::Orientation_south},
{start: Robot::Orientation_south, stop: Robot::Orientation_east},
{start: Robot::Orientation_east, stop: Robot::Orientation_north}
].each do |data|
it "changes orientation from #{data[:start]} to #{data[:stop]}" do
allow(robot_test).to receive(:direction).and_return data[:start]
expect(robot_test).to receive(:direction=).with data[:stop]
subject
end
end
end
describe :execute_right do
subject { robot_test.send :execute_right, [] }
[
{start: Robot::Orientation_north, stop: Robot::Orientation_east},
{start: Robot::Orientation_west, stop: Robot::Orientation_north},
{start: Robot::Orientation_south, stop: Robot::Orientation_west},
{start: Robot::Orientation_east, stop: Robot::Orientation_south}
].each do |data|
it "changes orientation from #{data[:start]} to #{data[:stop]}" do
allow(robot_test).to receive(:direction).and_return data[:start]
expect(robot_test).to receive(:direction=).with data[:stop]
subject
end
end
end
describe :position_within_playground? do
let(:coordinates) { [3, 7] }
let(:position) { instance_double Position, coordinates: coordinates }
let(:playground) { instance_double Playground, dimensions_count: 2 }
before :each do
allow(robot_test).to receive(:playground).and_return playground
end
subject { robot_test.send :position_within_playground?, position }
it 'checks the position coordinates against the playground' do
expect(playground).to receive(:valid_value_for_dimension?).once.with(3, 0).and_return true
expect(playground).to receive(:valid_value_for_dimension?).once.with(7, 1)
subject
end
it 'returns true when all the coordinate are within the boundaries' do
allow(playground).to receive(:valid_value_for_dimension?).and_return true
expect(subject).to eql true
end
it 'returns false when when one ofhte values are outside the boundaries' do
allow(playground).to receive(:valid_value_for_dimension?).and_return false
expect(subject).to eql false
end
it 'returns false when the coordinates of the position are bigger than the playground' do
coordinates << 5
expect(subject).to eql false
end
end
end
end
|
=begin
Deaf grandma. Whatever you say to Grandma (whatever you type in), she should respond with this:
HUH? SPEAK UP, SONNY!
unless you shout it (type in all capitals). If you shout, she can hear you (or at least she think so) and yells back:
NO, NOT SINCE 1938!
To make program believable, have Grandma shout different year each time, maybe any year at random between 1930 and 1950.
You can't stop talking with Grandma until you shout BYE.
=end
puts 'WHAT\'S UP, SONNY?'
while true
response = gets.chomp
if response == 'BYE'
puts 'GOOD BYE, MY SON!'
break
elsif response == response.upcase
random_year = rand(20) + 1930
puts "NO, NOT SINCE #{random_year}!"
else
puts 'HUH? SPEAK UP, SONNY!'
end
end
=begin
Deaf grandma extended. What if Grandma doesn't want you to leave? When you shout 'BYE' she could pretend not to hear you.
Change your previous program so that you have to shout 'BYE' three times in a row. If you shout BYE three times, but not
in a row, you should still be talking with Grandma.
=end
puts 'WHAT\'S UP, SONNY?'
count = 0
while true
response = gets.chomp
if response == 'BYE'
count = count + 1
puts 'HUH?'
else
count = 0
if response == response.upcase
random_year = rand(20) + 1930
puts "NO, NOT SINCE #{random_year}!"
else
puts 'HUH? SPEAK UP, SONNY!'
end
end
if count >=3
puts 'GOOD BYE, MY SON!'
break
end
end
|
helpers do
def entry(title, created, article)
"<h3 class='upcase'><a href='#' class='toggle' style='text-transform: uppercase;'>[+] #{title}<h2 class='upcase' style='text-transform: uppercase;'>#{created}</h2></a></h3>
<div class='hide'>
<p>#{article}</p>
</div>"
end
def biography(title, article)
"<div id='biography'>
<h2>#{title}</h2>
<p>
#{article}
</p>
<a href='#top' class='top'>Back To Top</a>
</div>"
end
end |
class Admin < Ohm::Model
include Shield::Model
include Ohm::Timestamps
include Ohm::DataTypes
attribute :email
attribute :crypted_password
attribute :blocked, Type::Boolean
unique :email
index :email
def self.fetch(email)
find(email: email).first
end
def self.with_serial_number(serial_number)
find(serial_number: serial_number).first
end
def status
blocked ? 'Disabled' : 'Active'
end
end
|
class RemoveUniqueIndexOnCollectionTitle < ActiveRecord::Migration[5.2]
def change
remove_index :collections, :title # remove the unique index
add_index :collections, :title # add a new non-unique index
end
end
|
module Fog
module Compute
class DigitalOceanV2
class Real
def get_ssh_key(key_id)
request(
:expects => [200],
:method => 'GET',
:path => "/v2/account/keys/#{key_id}"
)
end
end
# noinspection RubyStringKeysInHashInspection
class Mock
def get_ssh_key(_)
response = Excon::Response.new
response.status = 200
response.body = {
'ssh_key' => {
'id' => 512190,
'fingerprint' => '3b:16:bf:e4:8b:00:8b:b8:59:8c:a9:d3:f0:19:45:fa',
'public_key' => 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDDHr/jh2Jy4yALcK4JyWbVkPRaWmhck3IgCoeOO3z1e2dBowLh64QAM+Qb72pxekALga2oi4GvT+TlWNhzPH4V example',
'name' => 'My SSH Public Key'
}
}
response
end
end
end
end
end
|
require 'caxlsx'
require 'caxlsx_rails'
require 'roo'
class FacilitiesManagement::DeliverableMatrixSpreadsheetCreator
include FacilitiesManagement::SummaryHelper
include ActionView::Helpers::SanitizeHelper
def initialize(contract_id)
@contract = FacilitiesManagement::ProcurementSupplier.find(contract_id)
@procurement = @contract.procurement
@report = FacilitiesManagement::SummaryReport.new(@procurement.id)
@active_procurement_buildings = @procurement.active_procurement_buildings.order_by_building_name
end
def buildings_data
@buildings_data ||= @active_procurement_buildings.map { |b| { building_id: b.building_id, service_codes: b.procurement_building_services.map(&:code) } }
end
# rubocop:disable Metrics/AbcSize
def services_data
uniq_buildings_service_codes ||= @active_procurement_buildings.map { |pb| pb.procurement_building_services.map(&:code) }.flatten.uniq
services ||= FacilitiesManagement::StaticData.work_packages.select { |wp| uniq_buildings_service_codes.include? wp['code'] }
@services_data ||= services.sort { |a, b| [a['code'].split('.')[0], a['code'].split('.')[1].to_i] <=> [b['code'].split('.')[0], b['code'].split('.')[1].to_i] }
end
# rubocop:enable Metrics/AbcSize
def units_of_measure_values
@units_of_measure_values ||= @active_procurement_buildings.map do |building|
@report.da_procurement_building_services(building).map do |procurement_building_service|
{
building_id: building.building_id,
service_code: procurement_building_service.code,
uom_value: procurement_building_service.uval,
service_standard: procurement_building_service.service_standard,
service_hours: procurement_building_service.service_hours
}
end
end
end
def to_xlsx
@package.to_stream.read
end
# rubocop:disable Metrics/AbcSize
def build
@package = Axlsx::Package.new do |p|
p.workbook.styles do |s|
first_column_style = s.add_style sz: 12, b: true, alignment: { horizontal: :left, vertical: :center }, border: { style: :thin, color: '00000000' }
standard_column_style = s.add_style sz: 12, alignment: { horizontal: :left, vertical: :center }, border: { style: :thin, color: '00000000' }
p.workbook.add_worksheet(name: 'Buildings information') do |sheet|
add_header_row(sheet, ['Buildings information'])
add_building_name_row(sheet, ['Building name'], :left)
add_buildings_information(sheet)
style_buildings_information_sheet(sheet, first_column_style)
end
p.workbook.add_worksheet(name: 'Service Matrix') do |sheet|
add_header_row(sheet, ['Service Reference', 'Service Name'])
add_building_name_row(sheet, ['', ''], :center)
add_service_matrix(sheet)
style_service_matrix_sheet(sheet, standard_column_style)
end
if volume_services_included?
p.workbook.add_worksheet(name: 'Volume') do |sheet|
add_header_row(sheet, ['Service Reference', 'Service Name', 'Metric per annum'])
add_building_name_row(sheet, ['', '', ''], :center)
number_volume_services = add_volumes_information_da(sheet)
style_volume_sheet(sheet, standard_column_style, number_volume_services)
end
end
add_service_periods_worksheet(p, standard_column_style, units_of_measure_values) if services_require_service_periods?
add_customer_and_contract_details(p) if @procurement
add_service_details_sheet(p)
end
end
end
# rubocop:enable Metrics/AbcSize
def list_of_allowed_volume_services
# FM-736 requirement
%w[C.5 E.4 G.1 G.3 G.5 H.4 H.5 I.1 I.2 I.3 I.4 J.1 J.2 J.3 J.4 J.5 J.6 K.1 K.2 K.3 K.4 K.5 K.6 K.7]
end
private
def add_service_periods_worksheet(package, standard_column_style, units)
package.workbook.add_worksheet(name: 'Service Periods') do |sheet|
add_header_row(sheet, ['Service Reference', 'Service Name', 'Specific Service Periods'])
add_building_name_row(sheet, ['', '', ''], :center)
rows_added = add_service_periods(sheet, units)
style_service_periods_matrix_sheet(sheet, standard_column_style, rows_added) if sheet.rows.size > 1
end
end
def add_customer_and_contract_details(package)
package.workbook.add_worksheet(name: 'Customer & Contract Details') do |sheet|
add_contract_number(sheet) if any_contracts_offered?
add_customer_details(sheet)
add_contract_requirements(sheet)
end
end
def any_contracts_offered?
@procurement.procurement_suppliers.any? { |contract| !contract.unsent? }
end
def add_service_details_sheet(package)
service_descriptions_sheet = Roo::Spreadsheet.open(Rails.root.join('app', 'assets', 'files', 'FMServiceDescriptions.xlsx'), extension: :xlsx)
service_descriptions = service_descriptions_sheet.sheet('Service Descriptions')
package.workbook.add_worksheet(name: 'Service Information') do |sheet|
(service_descriptions.first_row..service_descriptions.last_row).each do |row_number|
sanitized_row = service_descriptions.row(row_number).map { |cell| strip_tags(cell) }
sheet.add_row sanitized_row, widths: [nil, 20, 200]
end
apply_service_information_sheet_styling(sheet)
end
end
def standard_row_height
35
end
def add_header_row(sheet, initial_values)
header_row_style = sheet.styles.add_style sz: 12, b: true, alignment: { wrap_text: true, horizontal: :center, vertical: :center }, border: { style: :thin, color: '00000000' }
header_row = initial_values
(1..@active_procurement_buildings.count).each { |x| header_row << "Building #{x}" }
sheet.add_row header_row, style: header_row_style, height: standard_row_height
end
def add_building_name_row(sheet, initial_values, float)
standard_style = sheet.styles.add_style sz: 12, border: { style: :thin, color: '00000000' }, alignment: { wrap_text: true, vertical: :center, horizontal: float }
row = initial_values
@active_procurement_buildings.each { |building| row << sanitize_string_for_excel(building.building_name) }
sheet.add_row row, style: standard_style, height: standard_row_height
end
def style_buildings_information_sheet(sheet, style)
sheet['A1:A10'].each { |c| c.style = style }
sheet.column_widths(*([50] * sheet.column_info.count))
end
def style_service_matrix_sheet(sheet, style)
column_widths = [15, 100]
@active_procurement_buildings.count.times { column_widths << 50 }
sheet["A3:B#{services_data.count + 2}"].each { |c| c.style = style }
sheet.column_widths(*column_widths)
end
def style_service_periods_matrix_sheet(sheet, style, rows_added)
column_widths = [15, 100]
@active_procurement_buildings.count.times { column_widths << 50 }
sheet["A3:B#{rows_added + 2}"].each { |c| c.style = style }
sheet.column_widths(*column_widths)
end
def add_buildings_information(sheet)
standard_style = sheet.styles.add_style sz: 12, border: { style: :thin, color: '00000000' }, alignment: { wrap_text: true, vertical: :center, horizontal: :left }
[building_description, building_address_street, building_address_town, building_address_postcode, building_nuts_region, building_gia, building_type, building_security_clearance].each do |row_type|
sheet.add_row row_type, style: standard_style, height: standard_row_height
end
end
def building_name
row = ['Building Name']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.building_name)
end
row
end
def building_description
row = ['Building Description']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.description)
end
row
end
def building_address_street
row = ['Building Address - Street']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.address_line_1)
end
row
end
def building_address_town
row = ['Building Address - Town']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.address_town)
end
row
end
def building_address_postcode
row = ['Building Address - Postcode']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.address_postcode)
end
row
end
def building_nuts_region
row = ['Building Location (NUTS Region)']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.address_region)
end
row
end
def building_gia
row = ['Building Gross Internal Area (GIA) (sqm)']
@active_procurement_buildings.each do |building|
row << building.gia
end
row
end
def building_type
row = ['Building Type']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.building_type)
end
row
end
def building_security_clearance
row = ['Building Security Clearance']
@active_procurement_buildings.each do |building|
row << sanitize_string_for_excel(building.security_type)
end
row
end
def add_service_matrix(sheet)
standard_style = sheet.styles.add_style sz: 12, border: { style: :thin, color: '00000000' }, alignment: { wrap_text: true, vertical: :center, horizontal: :center }
services_data.each do |service|
row_values = [service['code'], service['name']]
@active_procurement_buildings.each do |building|
v = building.service_codes.include?(service['code']) ? 'Yes' : ''
row_values << v
end
sheet.add_row row_values, style: standard_style, height: standard_row_height
end
end
# rubocop:disable Metrics/AbcSize
def add_volumes_information_da(sheet)
number_column_style = sheet.styles.add_style sz: 12, border: { style: :thin, color: '00000000' }
added_rows = 0
allowed_volume_services = services_data.keep_if { |service| list_of_allowed_volume_services.include? service['code'] }
allowed_volume_services.each do |s|
next if CCS::FM::Service.gia_services.include? s['code']
new_row = [s['code'], s['name'], s['metric']]
@active_procurement_buildings.each do |b|
uvs = units_of_measure_values.flatten.select { |u| b.building_id == u[:building_id] }
suv = uvs.find { |u| s['code'] == u[:service_code] }
new_row << calculate_uom_value(suv) if suv
new_row << nil unless suv
end
added_rows += 1
sheet.add_row new_row, style: number_column_style
end
added_rows
end
# rubocop:enable Metrics/AbcSize
def style_volume_sheet(sheet, style, number_volume_services)
column_widths = [15, 100, 50, 50]
@active_procurement_buildings.count.times { column_widths << 20 }
last_column_name = ('A'..'ZZ').to_a[2 + buildings_data.count]
sheet["A2:#{last_column_name}#{number_volume_services + 2}"].each { |c| c.style = style } if number_volume_services.positive?
sheet.column_widths(*column_widths)
end
def add_service_periods(sheet, units)
rows_added = 0
standard_style = sheet.styles.add_style sz: 12, border: { style: :thin, color: '00000000' }, alignment: { wrap_text: true, vertical: :center, horizontal: :center }, fg_color: '6E6E6E'
hours_required_services.each do |service|
Date::DAYNAMES.rotate(1).each do |day|
row_values = [service['code'], service['name'], day]
buildings_data.each do |building|
service_measure = units.flatten.select { |measure| measure[:service_code] == service['code'] && measure[:building_id] == building[:building_id] }.first
row_values << add_service_measure_row_value(service_measure, day)
end
rows_added += 1
sheet.add_row row_values, style: standard_style, height: standard_row_height
end
end
rows_added
end
def hours_required_services
allowed_services = []
FacilitiesManagement::StaticData.work_packages.select { |work_package| allowed_services << work_package['code'] if work_package['metric'] == 'Number of hours required' }
services_data.select { |service| allowed_services.include? service['code'] }
end
def add_service_measure_row_value(service_measure, day)
return nil if service_measure.nil? || service_measure[:service_hours].nil?
day_symbol = day.downcase.to_sym
case service_measure[:service_hours][day_symbol]['service_choice']
when 'not_required'
'Not required'
when 'all_day'
'All day (24 hours)'
when 'hourly'
determine_start_hourly_text(service_measure, day_symbol) + ' to ' + determine_end_hourly_text(service_measure, day_symbol) + next_day(service_measure[:service_hours][day_symbol])
else
'unknown??' + service_measure[:uom_value][day_symbol]['service_choice']
end
end
def next_day(service_hour_choice)
service_hour_choice[:next_day] ? ' (next day)' : ''
end
def service_measure_invalid_type?(service_measure)
invalid = false
invalid = true if service_measure.nil? || service_measure[:uom_value].instance_of?(String) || service_measure[:uom_value].instance_of?(Integer)
invalid
end
def determine_start_hourly_text(service_measure, day_symbol)
start_hour = format('%01d', service_measure[:service_hours][day_symbol]['start_hour'])
start_minute = format('%02d', service_measure[:service_hours][day_symbol]['start_minute'])
start_ampm = service_measure[:service_hours][day_symbol]['start_ampm'].downcase
start_hour + ':' + start_minute + start_ampm
end
def determine_end_hourly_text(service_measure, day_symbol)
end_hour = format('%01d', service_measure[:service_hours][day_symbol]['end_hour'])
end_minute = format('%02d', service_measure[:service_hours][day_symbol]['end_minute'])
end_ampm = service_measure[:service_hours][day_symbol]['end_ampm'].downcase
end_hour + ':' + end_minute + end_ampm
end
def add_contract_number(sheet)
sheet.add_row ['Reference number & date/time production of this document', "#{@contract.contract_number} #{@contract.offer_sent_date&.in_time_zone('London')&.strftime '- %Y/%m/%d - %l:%M%P'}"]
sheet.add_row []
end
def calculate_contract_number
FacilitiesManagement::ContractNumberGenerator.new(procurement_state: :direct_award, used_numbers: []).new_number
end
def add_customer_details(sheet)
bold_style = sheet.styles.add_style b: true
sheet.add_row ['1. Customer details'], style: bold_style
add_sanitized_customer_details(sheet)
end
def add_sanitized_customer_details(sheet)
telephone_number_style = sheet.styles.add_style format_code: '0##########', alignment: { horizontal: :left }
buyer_detail = @procurement.user.buyer_detail
sheet.add_row ['Contract name', sanitize_string_for_excel(@procurement.contract_name)]
sheet.add_row ['Buyer Organisation Name', sanitize_string_for_excel(buyer_detail.organisation_name)]
sheet.add_row ['Buyer Organisation Sector', buyer_detail.central_government? ? 'Central Government' : 'Wider Public Sector']
sheet.add_row ['Buyer Contact Name', sanitize_string_for_excel(buyer_detail.full_name)]
sheet.add_row ['Buyer Contact Job Title', sanitize_string_for_excel(buyer_detail.job_title)]
sheet.add_row ['Buyer Contact Email Address', @procurement.user.email]
sheet.add_row ['Buyer Contact Telephone Number', buyer_detail.telephone_number], style: [nil, telephone_number_style]
end
def add_contract_requirements(sheet)
bold_style = sheet.styles.add_style b: true
sheet.add_row []
sheet.add_row ['2. Contract requirements'], style: bold_style
add_initial_call_off_period(sheet)
add_mobilisation_period(sheet)
sheet.add_row ['Date of First Indexation', (@procurement.initial_call_off_start_date + 1.year).strftime('%d/%m/%Y')]
add_extension_periods(sheet)
add_tupe(sheet)
end
def add_mobilisation_period(sheet)
sheet.add_row ['Mobilisation Period', ("#{@procurement.mobilisation_period} weeks" if @procurement.mobilisation_period_required)]
sheet.add_row ['Mobilisation Start Date', ((@procurement.initial_call_off_start_date - @procurement.mobilisation_period.weeks - 1.day).strftime('%d/%m/%Y') if @procurement.mobilisation_period_required)]
sheet.add_row ['Mobilisation End Date', ((@procurement.initial_call_off_start_date - 1.day).strftime('%d/%m/%Y') if @procurement.mobilisation_period_required)]
end
def add_initial_call_off_period(sheet)
sheet.add_row ['Initial Call-Off Period', "#{@procurement.initial_call_off_period} years"]
sheet.add_row ['Initial Call-Off Period Start Date', @procurement.initial_call_off_start_date.strftime('%d/%m/%Y')]
sheet.add_row ['Initial Call-Off Period End Date', (@procurement.initial_call_off_start_date + @procurement.initial_call_off_period.years - 1.day).strftime('%d/%m/%Y')]
end
def add_extension_periods(sheet)
(1..4).each do |period|
sheet.add_row ["Extension Period #{period}", extension_period(period)]
end
end
def extension_period(period)
return nil if !@procurement.extensions_required || @procurement.try("optional_call_off_extensions_#{period}").nil?
@procurement.try("extension_period_#{period}_start_date").strftime('%d/%m/%Y') + ' - ' + @procurement.try("extension_period_#{period}_end_date").strftime('%d/%m/%Y')
end
def add_tupe(sheet)
sheet.add_row []
sheet.add_row ['TUPE involved', @procurement.tupe? ? 'Yes' : 'No']
end
def apply_service_information_sheet_styling(sheet)
header_row_style = sheet.styles.add_style sz: 12, b: true, alignment: { wrap_text: true, horizontal: :center, vertical: :center }, border: { style: :thin, color: '00000000' }, bg_color: 'D2D9EF'
no_style = sheet.styles.add_style bg_color: 'FFFFFF', b: false, fg_color: 'FFFFFF'
standard_style = sheet.styles.add_style sz: 12, alignment: { wrap_text: true }, border: { style: :thin, color: 'F000000' }
sheet['A1:C2266'].each { |c| c.style = standard_style }
sheet['A1:C1'].each { |c| c.style = header_row_style }
bold_rows(sheet)
bold_red_rows(sheet)
grey_rows(sheet)
workpackage_header_rows(sheet)
sheet['A1:A2266'].each { |c| c.style = no_style }
sheet.column_info.first.hidden = true
end
def bold_rows(sheet)
bold_style = sheet.styles.add_style sz: 12, b: true, border: { style: :thin, color: 'F000000' }
bolded_rows.each do |row|
sheet["A#{row}:C#{row}"].each { |c| c.style = bold_style }
end
end
def bold_red_rows(sheet)
bold_red_style = sheet.styles.add_style sz: 12, b: true, fg_color: 'B00004', border: { style: :thin, color: 'F000000' }
bolded_red_rows.each do |row|
sheet["A#{row}:C#{row}"].each { |c| c.style = bold_red_style }
end
end
def grey_rows(sheet)
grey_style = sheet.styles.add_style bg_color: '807E7E'
greyed_rows.each do |row|
sheet["A#{row}:C#{row}"].each { |c| c.style = grey_style }
end
end
def workpackage_header_rows(sheet)
wp_header_style = sheet.styles.add_style sz: 12, b: true, bg_color: 'FFFFFF'
bolded_no_border_rows.each do |row|
sheet["A#{row}:C#{row}"].each { |c| c.style = wp_header_style }
end
end
def bolded_rows
[
4, 26, 42, 64, 96, 101, 112, 123, 128, 143,
162, 176, 179, 184, 187, 210, 215, 230, 236,
247, 260, 269, 295, 308, 312, 314, 333, 342,
350, 369, 383, 390, 396, 399, 402, 412, 415,
422, 424, 429, 432, 436, 442, 444, 455, 462,
477, 479, 492, 497, 511, 523, 548, 555,
563, 596, 613, 621, 631, 654, 670, 678,
728, 754, 767, 772, 783, 796, 810, 816, 824,
832, 838, 845, 850, 859, 874, 895, 898, 920,
951, 959, 966, 993, 1010, 1027, 1036,
1053, 1067, 1084, 1093, 1119, 1128, 1132, 1137,
1152, 1182, 1190, 1204, 1210, 1216, 1232,
1243, 1248, 1254, 1268, 1271, 1275, 1285, 1305,
1312, 1318, 1329, 1340, 1353, 1364, 1371, 1383,
1416, 1421, 1438, 1445, 1451, 1466, 1481,
1489, 1494, 1500, 1515, 1522, 1531, 1544, 1559,
1566, 1591, 1605, 1612, 1619, 1629, 1640,
1657, 1667, 1674, 1679, 1687, 1729, 1752,
1776, 1786, 1802, 1808, 1815, 1823, 1833, 1842,
1847, 1857, 1872, 1885, 1893, 1901, 1908, 1915,
1924, 1940, 1957, 1971, 1978, 1985, 1990,
1994, 1999, 2004, 2032, 2101, 2207, 2260, 2262
]
end
def bolded_red_rows
[
5, 27, 43, 65, 97, 102, 113, 124, 129, 144,
237, 248, 261, 270, 296, 309, 313, 463, 493
]
end
def greyed_rows
[
25, 41, 63, 95, 100, 111, 122, 127, 142, 235,
246, 259, 268, 294, 307, 311, 461, 595, 612, 620,
630, 653, 669, 677, 727, 753, 766, 771, 782, 795, 809,
815, 823, 831, 837, 844, 849, 858, 873, 950, 958, 965,
992, 1009, 1035, 1052, 1066, 1083, 1092, 1118,
1127, 1131, 1136, 1181, 1189, 1203, 1209, 1215,
1231, 1242, 1247, 1253, 1267, 1284, 1253, 1267, 1284,
1304, 1311, 1317, 1328, 1339, 1352, 1363, 1370,
1382, 1415, 1420, 1437, 1444, 1450, 1465, 1488,
1493, 1499, 1514, 1521, 1530, 1543, 1558, 1565, 1590,
1604, 1611, 1618, 1628, 1639, 1666, 1673, 1678,
1728, 1751, 1753, 1775, 1785, 1801, 1807, 1814, 1822,
1832, 1841, 1846, 1871, 1884, 1892, 1900, 1907, 1914,
1939, 1956, 1970, 1977, 1984, 1989, 1993, 1998,
2003, 2031
]
end
def bolded_no_border_rows
[
2, 3, 489, 490, 491, 560, 561, 562, 892, 893, 894,
1024, 1025, 1026, 1149, 1150, 1151, 1272, 1273, 1274,
1478, 1479, 1480, 1654, 1655, 1656, 1684, 1685, 1686,
1854, 1855, 1856, 1921, 1922, 1923, 1923, 2098, 2099,
2100, 2204, 2205, 2206, 2259, 2260, 2261
]
end
def services_require_service_periods?
return false if @services_data.empty?
(@services_data.map { |sd| sd['code'] }.uniq & services_with_service_hours).size.positive?
end
def volume_services_included?
return false if @services_data.empty?
(@services_data.map { |sd| sd['code'] }.uniq & list_of_allowed_volume_services).size.positive?
end
def services_with_service_hours
%w[H.4 H.5 I.1 I.2 I.3 I.4 J.1 J.2 J.3 J.4 J.5 J.6]
end
def sanitize_string_for_excel(string)
return "’#{string}" if string.match?(/\A(@|=|\+|\-)/)
string
end
end
|
class IssuesController < ApplicationController
before_filter :authorize
# GET /issues
# GET /issues.json
def index
@issues = Issue.all
respond_to do |format|
format.html #index.html.erb
format.json { render json: @issues }
end
end
# GET /issues/1
# GET /issues/1.json
def show
# raise params.inspect
@issue = Issue.find(params[:id])
@answerer = Answer.find(@issue.answer_id).user if @issue.answer_id
# @comment = Comment.new
@comments = @issue.comments
@answer = Answer.new
respond_to do |format|
format.html #show.html.erb
format.json { render json: @issue }
end
end
# GET /issues/new
# GET /issues/new.json
def new
@issue = Issue.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @issue }
end
end
# GET /issues/1/edit
def edit
@issue = Issue.find(params[:id])
# if is_owner?()
# @status = @issue.status
# end
end
# POST /issues
# POST /issues.json
def create
@issue = current_user.issues.build(params[:issue])
respond_to do |format|
if @issue.save
format.html { redirect_to issues_path, notice: 'Issue was successfully created.' }
format.json { render json: @issue, status: :created, location: @issue }
else
format.html { render action: "new" }
format.json { render json: @issue.errors, status: :unprocessable_entity }
end
end
end
# PUT /issues/1
# PUT /issues/1.json
def update
# raise params.inspect
@issue = Issue.find(params[:id])
respond_to do |format|
if @issue.update_attributes(params[:issue])
format.html { redirect_to issues_path, notice: 'Issue was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @issue.errors, status: :unprocessable_entity }
end
end
end
# DELETE /issues/1
# DELETE /issues/1.json
def destroy
@issue = Issue.find(params[:id])
@issue.destroy
respond_to do |format|
format.html { redirect_to issues_url }
format.json { head :no_content }
end
end
end
|
Pod::Spec.new do |s|
s.name = "DataEntryToolbar"
s.version = "0.2.3"
s.summary = "A subclass of UIToolbar used to navigate up and down a dynamic tableView's text fields'."
s.description = <<-DESC
DataEntryToolbar is a subclass of UIToolbar intended for use as the input accessory view of a keyboard or picker, providing Next, Previous, & Done buttons to navigate up and down a dynamic tableView.
To set up:
- Set a `DataEntryToolbar` instance as the inputAccessoryView of `UITextFields` you want to control
- Add textFields to `tableTextFields` in cellForRowAtIndexPath, using the textField's cell's indexPath as a key
- If you want to be notified when a user taps one of the navigation buttons, implement the necessary closures
- The look and feel of the toolbar and its buttons can be customized as you would with any toolbar (i.e. barStyle, barTintColor, or button tintColor properties)
DESC
s.homepage = "https://github.com/jday001/DataEntryToolbar"
s.license = 'MIT'
s.author = { "jeff" => "jday@jdayapps.com" }
s.source = { :git => "https://github.com/jday001/DataEntryToolbar.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/jday001'
s.ios.deployment_target = "7.0"
s.requires_arc = true
s.source_files = 'Source/*.swift'
s.resource_bundles = {
'DataEntryToolbar' => ['Pod/Assets/*.png']
}
end
|
module Fog
module Compute
class DigitalOceanV2
class SshKey < Fog::Model
identity :id
attribute :fingerprint
attribute :public_key
attribute :name
def save
requires :name, :public_key
merge_attributes(service.create_ssh_key(name, public_key).body['ssh_key'])
true
end
def destroy
requires :id
service.delete_ssh_key id
end
def update
requires :id, :name
data = service.update_server(id, name)
merge_attributes(data.body['ssh_key'])
true
end
end
end
end
end
|
require File.join(File.dirname(__FILE__), 'lib', 'bard_bot')
Gem::Specification.new do |gem|
gem.name = 'bard_bot'
gem.version = BardBot::VERSION
gem.date = Date.today.to_s
gem.author = 'R. Scott Reis'
gem.email = 'reis.robert.s@gmail.com'
gem.license = 'MIT'
gem.homepage = 'https://github.com/EvilScott/bard_bot'
gem.summary = 'Shakespearean markov sentence generation'
gem.description = 'BardBot can generate markov sentences for your from a number of Shakespearean character corpora'
gem.files = Dir['{data,lib,spec}/**/*', 'Rakefile', 'README*', 'LICENSE*']
gem.require_path = 'lib'
gem.add_development_dependency 'rspec', '~> 3.1'
end
|
require "test_helper"
class ContextTest < MiniTest::Spec
class ParentCell < Cell::ViewModel
def user
context[:user]
end
end
let (:model) { Object.new }
let (:user) { Object.new }
let (:controller) { Object.new }
it do
cell = ParentCell.(model, admin: true, context: { user: user, controller: controller })
# cell.extend(ParentController)
cell.model.must_equal model
cell.controller.must_equal controller
cell.user.must_equal user
# nested cell
child = cell.cell("context_test/parent", "")
child.model.must_equal ""
child.controller.must_equal controller
child.user.must_equal user
end
end
|
# Helper Method
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0,1,2], #top row win
[3,4,5], #middle row win
[6,7,8], #bottom row win
[0,4,8], #top left diagonal win
[2,4,6], #top right diagonal win
[0,3,6], #left column win
[1,4,7], #middle column win
[2,5,8] #right column win
]
def won?(board)
WIN_COMBINATIONS.each do |x|
win_index1 = x[0]
win_index2 = x[1]
win_index3 = x[2]
if position_taken?(board, win_index1) == true && board[win_index2] == board[win_index1] && board[win_index3] == board[win_index1]
return x
end
end
return false
end
def full?(board)
board.all? do |x| x == "X" || x == "O" end
end
def draw?(board)
if full?(board) == true && won?(board) == false
return true
else
return false
end
end
def over?(board)
if draw?(board) == true || won?(board) != false
return true
else return false
end
end
def winner(board)
if won?(board) != false
return board[won?(board)[0]]
else
return nil
end
end
|
class AlertsController < ApplicationController
before_action :authenticate_employee!
before_action :set_alert, only: [:show, :edit, :update, :destroy]
before_action :set_beacon, only: [:create, :destroy]
# GET /alerts
# GET /alerts.json
def index
org = Organization.find(current_employee.organization_id)
@alerts = org.alerts
render "index.json.jbuilder", status: :ok
end
# POST /alerts
# POST /alerts.json
def create
# from mac - state, duration, uuid, major, minor
# we have - current_employee.id , @beacon.id
@alert = Alert.new(beacon_id: @beacon.id,
duration: params[:duration],
state: params[:state],
employee_id: current_employee.id)
if @alert.save
render json: { success: "PREY ACQUIRED! TRACKING MODE ACTIVATED! SCREEEEEEEEE!" }, status: :ok
else
render json: { errors: @alert.errors.full_messages }, status: :unprocessable_entity
end
end
# DELETE /alerts/1
# DELETE /alerts/1.json
def destroy
@alert.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_beacon
@beacon = Beacon.find_by(organization_id: current_employee.organization_id, uuid: params[:uuid], major: params[:major], minor: params[:minor])
end
def set_alert
@alert = Alert.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
#def alert_params
#params.require(:alert).permit(:beacon_id, :state, :duration, :employee_id)
#end
end
|
require 'rails_helper'
RSpec.describe 'Destroy Item API' do
before :each do
@item = create(:item)
@invoice = create(:invoice)
@invoice_item = create(:invoice_item, item: @item, invoice: @invoice)
end
describe 'happy path' do
it "can destroy an item" do
expect{ delete "/api/v1/items/#{@item.id}" }.to change(Item, :count).by(-1)
expect(response).to be_successful
expect(response.status).to eq 204
expect{Item.find(@item.id)}.to raise_error(ActiveRecord::RecordNotFound)
end
it 'can destory an invoice and invoice item' do
expect{ delete "/api/v1/items/#{@item.id}" }.to change(Item, :count).by(-1)
expect(response.status).to eq 204
expect{Invoice.find(@invoice.id)}.to raise_error(ActiveRecord::RecordNotFound)
expect{InvoiceItem.find(@invoice_item.id)}.to raise_error(ActiveRecord::RecordNotFound)
end
end
describe 'sad path' do
it 'cannot destory an invoice because it is linked to another item' do
@item_2 = create(:item)
@invoice_item_2 = create(:invoice_item, item: @item_2, invoice: @invoice)
expect{ delete "/api/v1/items/#{@item.id}" }.to change(Item, :count).by(-1)
expect(response.status).to eq 204
expect(Invoice.find(@invoice.id)).to eq(@invoice)
expect(InvoiceItem.find(@invoice_item_2.id)).to eq(@invoice_item_2)
expect{InvoiceItem.find(@invoice_item.id)}.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
|
class Fund
# * Module to setup the configuration
module Configuration
attr_accessor :default_currency, :supported_currencies, :currency_symbols
attr_accessor :currency_rates, :round_limit
class << self
# List of configurable keys for {Fund::Client}
# @return [Array] of option keys
def keys
# Reject all setters to get keys of only attributes
# Also reject other utility methods for the class
@keys ||= Fund::Configuration.public_instance_methods.reject { |method| method =~ /^.*=$/ } -
[:setup, :load_default, :config, :add]
end
end
# Set configuration options using a block
#
# Fund.setup do |config|
# config.supported_currencies = [:usd, :eur]
# end
# Fund.setup do |config|
# config.add :bit, 'Bit', 113.40
# end
def setup
yield self
end
# Utility method to add a new language in configuration
#
# @param currency [Symbol] A symbol representing the currency e.g. :usd, :eur
# @param symbol [String] A string representation of the currency e.g. $
# @param rate [Float] A floating number showing the currency rate with respect to default currency. See [Configuration::Default] for more reference
#
def add(currency, symbol, rate)
@supported_currencies << currency
@currency_symbols[currency] = symbol
@currency_rates[currency] = rate
end
def load_default
Configuration.keys.each do |key|
instance_variable_set(:"@#{key}", Fund::Default.options[key])
end
self
end
def config
self
end
end
end
|
class RemoveSlackWebhookUrlFromShop < ActiveRecord::Migration
def change
remove_column :shops, :slack_webhook_url
end
end
|
class RenameBasePollsToGamePolls < ActiveRecord::Migration
def change
rename_table :base_polls, :game_polls
remove_column :game_polls, :type
remove_column :game_polls, :video_link
end
end
|
# == Schema Information
#
# Table name: games
#
# id :integer not null, primary key
# name :string(255)
# date :datetime
# legend :text
# author :string(255)
# area :string(255)
# equipment :text
# coments :text
# created_at :datetime not null
# updated_at :datetime not null
# current :bool
# finished_at :datetime
#
class Game < ActiveRecord::Base
attr_accessible :area, :author, :coments, :date, :equipment, :legend, :name, :current, :finished_at
has_many :tasks
has_many :tryes
has_many :teams
has_many :task_orders
has_many :rgames
validates :name, uniqueness: { message: "Такое название уже есть" }, presence: { message: "Вы не ввели название" }
validates :author, presence: { message: "Вы не ввели автора" }
validates :legend, presence: { message: "Как же без легенды-то?" }
validate :game_starts_in_the_future
scope :finished, :conditions => ['finished_at IS NOT NULL']
def started?
self.date.nil? ? false : Time.now > self.date
end
def finish_game!
self.finished_at = Time.now
self.current = 0
self.save!
end
def finished?
self.finished_at.nil? ? false : Time.now > self.finished_at
end
protected
def game_starts_in_the_future
if self.finished_at.nil? and self.date and self.date < Time.now
self.errors.add(:date, "Вы выбрали дату из прошлого. Так нельзя :-)")
end
end
end
|
require 'tmpdir'
require 'vimrunner'
module Support
def assert_correct_indenting(string)
whitespace = string.scan(/^\s*/).first
string = string.split("\n").map { |line| line.gsub /^#{whitespace}/, '' }.join("\n").strip
File.open 'test.rb', 'w' do |f|
f.write string
end
@vim.edit 'test.rb'
@vim.normal 'gg=G'
@vim.write
IO.read('test.rb').strip.should eq string
end
end
RSpec.configure do |config|
include Support
config.before(:suite) do
VIM = Vimrunner.start_gvim
VIM.prepend_runtimepath(File.expand_path('../..', __FILE__))
end
config.after(:suite) do
VIM.kill
end
config.around(:each) do |example|
@vim = VIM
# cd into a temporary directory for every example.
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
@vim.command("cd #{dir}")
example.call
end
end
end
end
|
#
# Cookbook Name:: chef-server
# Recipe:: install-server
#
# Greg Konradt. Intended for installing Chef server with kitchen or Chef local mode
bash 'set_hostname' do
user 'root'
cwd '/tmp'
code <<-EOH
echo chef-server > /etc/hostname
echo "#{node['ipaddress']} chef-server" >> /etc/hosts
hostname chef-server
EOH
end
remote_file '/usr/local/src/chef-server.deb' do
owner 'root'
group 'root'
mode '0755'
source 'https://packages.chef.io/files/stable/chef-server/12.11.1/ubuntu/16.04/chef-server-core_12.11.1-1_amd64.deb'
checksum 'f9937ae1f43d7b5b12a5f91814c61ce903329197cd342228f2a2640517c185a6'
end
dpkg_package 'chef' do
source '/usr/local/src/chef-server.deb'
end
bash 'configure_chef_step_1' do
user 'root'
cwd '/tmp'
code <<-EOH
chef-server-ctl reconfigure
EOH
end
bash 'install_chef_manage' do
user 'root'
cwd '/tmp'
code <<-EOH
chef-server-ctl install chef-manage
EOH
end
directory '/secrets' do
owner 'root'
group 'root'
mode '400'
action :create
end
node["chef-server"]["users"].each do |myUser|
bash 'create_users' do
user 'root'
cwd '/tmp'
ignore_failure true
code <<-EOH
chef-server-ctl user-create #{myUser['name']} #{myUser['fullName']} #{myUser['email']} '#{myUser['pass']}' --filename /secrets/#{myUser['name']}.pem
EOH
end
end
bash 'create_organisation' do
user 'root'
cwd '/tmp'
ignore_failure true
code <<-EOH
chef-server-ctl org-create #{node['chef-server']['orgName']} '#{node['chef-server']['orgFullName']}' --association_user #{node['chef-server']['firstAdmin']} --filename /secrets/#{node['chef-server']['orgName']}-validator.pem
EOH
end
bash 'install_chef_reporting' do
user 'root'
cwd '/tmp'
code <<-EOH
chef-server-ctl install opscode-reporting
chef-server-ctl reconfigure
opscode-reporting-ctl reconfigure --accept-license
EOH
end
bash 'configure_chef_step_2' do
user 'root'
cwd '/tmp'
code <<-EOH
chef-server-ctl reconfigure
chef-manage-ctl reconfigure --accept-license
EOH
end
|
require 'rails_helper'
feature 'OpenWeatherMap Request' do
it 'queries the API for weather data' do
uri = URI.parse('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139')
response = JSON.parse(Net::HTTP.get(uri))
expect(response['name']).to eq('Koh Tao')
end
end |
module DocumentGenerator
module Helpers
BASE_URI = 'http://data.rollvolet.be/%{resource}/%{id}'
def write_to_pdf(path, html, options = {})
default_options = {
margin: {
left: 0,
top: 14, # top margin on each page
bottom: 20, # height (mm) of the footer
right: 0
},
disable_smart_shrinking: true,
print_media_type: true,
page_size: 'A4',
orientation: 'Portrait',
header: { content: '' },
footer: { content: '' }
}
options = default_options.merge options
pdf = WickedPdf.new.pdf_from_string(html, options)
# Write HTML to a document for debugging purposes
html_path = path.sub '.pdf', '.html'
File.open(html_path, 'wb') { |file| file << html }
File.open(path, 'wb') { |file| file << pdf }
end
def hide_element(css_class)
display_element(css_class, 'none')
end
def display_element(css_class, display = 'block')
@inline_css += ".#{css_class} { display: #{display} } "
''
end
# Language is determined by the language of the contact (if there is one) or customer.
# Language of the building doesn't matter
def select_language(data)
language = 'NED'
if data['contact'] and data['contact']['language']
language = data['contact']['language']['code']
elsif data['customer'] and data['customer']['language']
language = data['customer']['language']['code']
end
language
end
def select_footer(data, language)
if language == 'FRA'
ENV['FOOTER_TEMPLATE_FR'] || '/templates/footer-fr.html'
else
ENV['FOOTER_TEMPLATE_NL'] || '/templates/footer-nl.html'
end
end
def get_resource_uri(resource, id)
BASE_URI % { :resource => resource, :id => id }
end
def generate_building(data)
building = data['building']
if building
hon_prefix = building['honorificPrefix']
name = ''
name += hon_prefix['name'] if hon_prefix and hon_prefix['name'] and building['printInFront']
name += " #{building['prefix']}" if building['prefix'] and building['printPrefix']
name += " #{building['name']}" if building['name']
name += " #{building['suffix']}" if building['suffix'] and building['printSuffix']
name += " #{hon_prefix['name']}" if hon_prefix and hon_prefix['name'] and not building['printInFront']
addresslines = "#{name}<br>"
addresslines += "#{building['address1']}<br>" if building['address1']
addresslines += "#{building['address2']}<br>" if building['address2']
addresslines += "#{building['address3']}<br>" if building['address3']
addresslines += "#{building['postalCode']} #{building['city']}" if building['postalCode'] or building['city']
addresslines
else
hide_element('building')
end
end
# Address is always the address of the customer, even if a contact is attached
def generate_addresslines(data)
customer = data['customer']
hon_prefix = customer['honorificPrefix']
name = ''
name += hon_prefix['name'] if hon_prefix and hon_prefix['name'] and customer['printInFront']
name += " #{customer['prefix']}" if customer['prefix'] and customer['printPrefix']
name += " #{customer['name']}" if customer['name']
name += " #{customer['suffix']}" if customer['suffix'] and customer['printSuffix']
name += " #{hon_prefix['name']}" if hon_prefix and hon_prefix['name'] and not customer['printInFront']
addresslines = if name then "#{name}<br>" else "" end
addresslines += "#{customer['address1']}<br>" if customer['address1']
addresslines += "#{customer['address2']}<br>" if customer['address2']
addresslines += "#{customer['address3']}<br>" if customer['address3']
addresslines += customer['postalCode'] if customer['postalCode']
addresslines += " #{customer['city']}" if customer['city']
addresslines
end
def generate_contactlines(data)
vat_number = data['customer']['vatNumber']
contactlines = if vat_number then "<div class='contactline contactline--vat-number'>#{format_vat_number(vat_number)}</div>" else '' end
contact = data['contact']
if contact
hon_prefix = contact['honorificPrefix']
name = 'Contact: '
name += hon_prefix['name'] if hon_prefix and hon_prefix['name'] and contact['printInFront']
name += " #{contact['prefix']}" if contact['prefix'] and contact['printPrefix']
name += " #{contact['name']}" if contact['name']
name += " #{contact['suffix']}" if contact['suffix'] and contact['printSuffix']
name += " #{hon_prefix['name']}" if hon_prefix and hon_prefix['name'] and not contact['printInFront']
end
if contact
telephones = fetch_telephones(contact['id'], 'contacts')
else
telephones = fetch_telephones(data['customer']['number'])
end
top_telephones = telephones.first(2)
contactlines += if name then "<div class='contactline contactline--name'>#{name}</div>" else '' end
contactlines += "<div class='contactline contactline--telephones'>"
top_telephones.each do |tel|
formatted_tel = format_telephone(tel[:prefix], tel[:value])
contactlines += "<span class='contactline contactline--telephone'>#{formatted_tel}</span>"
end
contactlines += "</div>"
contactlines
end
def generate_ext_reference(data)
if data['reference']
data['reference']
else
hide_element('references--ext_reference')
hide_element('row--ext-reference')
hide_element('row--ext-reference .row--key')
hide_element('row--ext-reference .row--value')
end
end
def generate_invoice_number(data)
number = data['number'].to_s || ''
if number.length > 4
i = number.length - 4
"#{number[0..i-1]}/#{number[i..-1]}"
else
number
end
end
def generate_request_number(data)
format_request_number(data['id'].to_s)
end
def generate_invoice_date(data)
if data['invoiceDate'] then format_date(data['invoiceDate']) else '' end
end
def generate_request_date(data)
if data['requestDate'] then format_date(data['requestDate']) else '' end
end
def generate_bank_reference_with_base(base, number)
ref = base + number
modulo_check = ref % 97
padded_modulo = "%02d" % modulo_check.to_s
padded_modulo = '97' if padded_modulo == '00'
reference = "%012d" % (ref.to_s + padded_modulo)
"+++#{reference[0..2]}/#{reference[3..6]}/#{reference[7..-1]}+++"
end
def format_request_number(number)
if number
number.to_s.reverse.chars.each_slice(3).map(&:join).join(".").reverse
else
number
end
end
def format_decimal(number)
if number then sprintf("%0.2f", number).gsub(/(\d)(?=\d{3}+\.)/, '\1 ').gsub(/\./, ',') else '' end
end
def format_vat_number(vat_number)
if vat_number and vat_number.length >= 2
country = vat_number[0..1]
number = vat_number[2..-1]
if country.upcase == "BE"
if number.length == 9
return "#{country} #{number[0,3]}.#{number[3,3]}.#{number[6..-1]}"
elsif number.length > 9
return "#{country} #{number[0,4]}.#{number[4,3]}.#{number[7..-1]}"
end
return "#{country} #{number}"
end
else
return vat_number
end
end
def format_vat_rate(rate)
if rate == 0 || rate/rate.to_i == 1
rate.to_i.to_s
else
format_decimal(rate)
end
end
def format_date(date)
DateTime.parse(date).strftime("%d/%m/%Y")
end
def format_date_object(date)
date.strftime("%d/%m/%Y")
end
def format_telephone(prefix, value)
formatted_prefix = prefix.dup
formatted_prefix[0..1] = '+' if prefix and prefix.start_with? '00'
if (value)
area = find_area(value);
if (area)
group_per_2_chars = /(?=(?:..)*$)/
number_groups = value[area.size..].split(group_per_2_chars)
if (number_groups.size > 1 and number_groups[0].size == 1)
# concatenate first 2 elements if first element only contains 1 character
number_groups[0..1] = "#{number_groups[0]}#{number_groups[1]}"
end
number = "#{area} #{number_groups.join(' ')}"
if (number.start_with? '0')
formatted_number = "(#{number[0]})#{number[1..]}"
else
formatted_number = number
end
else
formatted_number = value;
end
end
[formatted_prefix, formatted_number].find_all { |e| e }.join(' ');
end
def find_area(value)
area = AREA_NUMBERS.find { |area| value.start_with?(area) }
if (area == '04' && value.size > 2)
# In area '04' only numbers like '2xx xx xx' and '3xx xx xx' occur.
# That's how they can be distinguished from cell phone numbers
if (not ['2', '3'].include?(value[2]))
# we assume it's a cell phone number, hence area is 4 characters (eg. 0475)
area = value.slice(0, 4);
end
end
area
end
# all known area numbers in Belgium as found on
# https://nl.wikipedia.org/wiki/Lijst_van_Belgische_zonenummers
AREA_NUMBERS = [
'02',
'03',
'04',
'09',
'010',
'011',
'012',
'013',
'014',
'015',
'016',
'019',
'050',
'051',
'052',
'053',
'054',
'055',
'056',
'057',
'058',
'059',
'060',
'061',
'063',
'064',
'065',
'067',
'069',
'071',
'080',
'081',
'082',
'083',
'085',
'086',
'087',
'089',
];
end
end
|
require 'sumac'
# make sure it exists
describe Sumac::Messages::Component::Exception do
# should be a subclass of Base
example do
expect(Sumac::Messages::Component::Exception < Sumac::Messages::Base).to be(true)
end
# ::from_object, #properties
# no message
example do
object = TypeError.new
component = Sumac::Messages::Component::Exception.from_object(object)
expect(component).to be_a(Sumac::Messages::Component::Exception)
expect(component.properties).to eq({'object_type' => 'exception', 'class' => 'TypeError'})
end
# with a message
example do
object = TypeError.new('abc')
component = Sumac::Messages::Component::Exception.from_object(object)
expect(component).to be_a(Sumac::Messages::Component::Exception)
expect(component.properties).to eq({'object_type' => 'exception', 'class' => 'TypeError', 'message' => 'abc'})
end
# ::from_properties, #object
# missing 'class' property
# unexpected property
example do
properties = {'object_type' => 'exception', 'message' => 'abc'}
expect{ Sumac::Messages::Component::Exception.from_properties(properties) }.to raise_error(Sumac::ProtocolError)
end
# missing 'message' property is ok
example do
properties = {'object_type' => 'exception', 'class' => 'TypeError'}
component = Sumac::Messages::Component::Exception.from_properties(properties)
expect(component).to be_a(Sumac::Messages::Component::Exception)
error = component.object
expect(error).to be_a(Sumac::RemoteError)
expect(error.remote_type).to eq('TypeError')
expect(error.remote_message).to be_nil
end
# all properties present
example do
properties = {'object_type' => 'exception', 'class' => 'TypeError', 'message' => 'abc'}
component = Sumac::Messages::Component::Exception.from_properties(properties)
expect(component).to be_a(Sumac::Messages::Component::Exception)
error = component.object
expect(error).to be_a(Sumac::RemoteError)
expect(error.remote_type).to eq('TypeError')
expect(error.remote_message).to eq('abc')
end
end
|
module CDI
module V1
class EducationalInstitutionSerializer < SimpleEducationalInstitutionSerializer
attributes :city_id, :state_id, :relation_with_me, :can_edit, :address
def address
object.address.present? ? InstitutionAddressSerializer.new(object.address) : nil
end
end
end
end
|
require 'iconv'
module Susanoo::Filter
CONV_TABLE = {
"\342\204\226" => "No.",
"\342\204\241" => "TEL",
"\342\205\240" => "I",
"\342\205\241" => "II",
"\342\205\242" => "III",
"\342\205\243" => "IV",
"\342\205\244" => "V",
"\342\205\245" => "VI",
"\342\205\246" => "VII",
"\342\205\247" => "VIII",
"\342\205\250" => "IX",
"\342\205\251" => "X",
"\342\205\260" => "i",
"\342\205\261" => "ii",
"\342\205\262" => "iii",
"\342\205\263" => "iv",
"\342\205\264" => "v",
"\342\205\265" => "vi",
"\342\205\266" => "vii",
"\342\205\267" => "viii",
"\342\205\270" => "ix",
"\342\205\271" => "x",
"\343\210\261" => "(株)",
"\343\210\262" => "(有)",
"\343\210\271" => "(代)",
"\343\212\244" => "(上)",
"\343\212\245" => "(中)",
"\343\212\246" => "(下)",
"\343\212\247" => "(左)",
"\343\212\250" => "(右)",
"\343\214\203" => "アール",
"\343\214\215" => "カロリー",
"\343\214\224" => "キロ",
"\343\214\230" => "グラム",
"\343\214\242" => "センチ",
"\343\214\243" => "セント",
"\343\214\246" => "ドル",
"\343\214\247" => "トン",
"\343\214\253" => "パーセント",
"\343\214\266" => "ヘクタール",
"\343\214\273" => "ページ",
"\343\215\211" => "ミリ",
"\343\215\212" => "ミリバール",
"\343\215\215" => "メートル",
"\343\215\221" => "リットル",
"\343\215\227" => "ワット",
"\343\215\273" => "平成",
"\343\215\274" => "昭和",
"\343\215\275" => "大正",
"\343\215\276" => "明治",
"\343\216\216" => "mg",
"\343\216\217" => "kg",
"\343\216\234" => "mm",
"\343\216\235" => "cm",
"\343\216\236" => "km",
"\343\216\241" => "m2",
"\343\217\204" => "cc",
"\343\217\215" => "K.K.",
"\357\274\215" => "−",
"\357\275\236" => "〜",
}
#
#=== 機種依存文字を変換する
#
def convert_non_japanese_chars(str, conv = true, import_all_enable = false)
sjis_text = convert(str, 'utf-8', 'shift_jis'){|c|
if conv && CONV_TABLE[c]
convert(CONV_TABLE[c], 'utf-8', 'shift_jis')
else
if import_all_enable
''
else
'<span class="invalid">&#%d;</span>' %
Iconv.conv('ucs-2be', 'utf-8', c).unpack('n').first
end
end
}
sjis_text.encode("UTF-8", "Shift_JIS").gsub(/\342\200\276/, '~')
end
#
#=== 機種依存文字を除去する
#
def remove_non_japanese_chars(text)
sjis_text = convert(text, 'utf8', 'shift_jis')
sjis_text.encode("UTF-8", "Shift_JIS").gsub(/\342\200\276/, '~')
end
#
# 対象の文字列の文字列コードを変換する
#
def convert(text, from, to)
ret_text = ''
input = text
Iconv.open(to, from) do |cd|
until input.empty?
begin
ret_text << cd.iconv(input)
break
rescue Iconv::Failure => e
ret_text << e.success
invalid_char, input = e.failed.split("", 2)
if block_given?
ret_text << yield(invalid_char)
end
rescue NoMethodError
raise 'invalid encoding'
end
end
end
return ret_text
end
#
# 機種依存文字を抜き出す
#
def non_japanese_chars(text)
return if text.blank?
invalid_chars = ""
input = text.dup
Iconv.open('shift_jis', 'utf-8') do |cd|
until input.empty?
begin
cd.iconv(input)
break
rescue Iconv::Failure => e
invalid_char, input = e.failed.split("", 2)
invalid_chars << invalid_char
rescue NoMethodError
raise 'invalid encoding'
end
end
end
return invalid_chars.split("")
end
module_function :convert_non_japanese_chars
module_function :remove_non_japanese_chars
module_function :convert
module_function :non_japanese_chars
end
|
require 'test_helper'
class PostTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "Post must have title and body" do
p = Post.new
assert_not p.valid?
p.title = "title"
assert_not p.valid?
p.body = "body"
assert p.valid?
p.title = ""
assert_not p.valid?
end
end
|
class Movie < ActiveRecord::Base
validates_presence_of :title, :path
end
|
class UsersController < ApplicationController
def index
users = User.all
render json: users
end
def create
user = User.find_or_create_by(username: strong_params[:username])
render json: user
end
def show
user = User.find(params[:id])
bad_games = Game.where( time: "0:00:00" )
bad_games.each {|game| game.destroy}
users_open_games = user.games.select{|game| game.status == "open"}
users_closed_games = user.games.select{|game| game.status == "closed"}
users_games = {open: users_open_games, closed: users_closed_games }
render json: users_games
end
private
def strong_params
params.require(:user).permit(:username)
end
end
|
class Number < ActiveRecord::Base
attr_accessible :active_race, :number, :race_id
belongs_to :race
end
|
require 'cgi'
module HBase
module Request
class BasicRequest
attr_reader :path
def initialize(path)
@path = path
end
protected
def pack_params columns
if columns.is_a? String
columns = [columns]
elsif columns.is_a? Array
else
raise StandardError, "Only String or Array type allows for columns"
end
columns.collect { |column| "column=#{column}" }.join('&')
end
end
end
end
|
# Q: I measured a cylinder with a string, and it was 50 cm around.
# I want to drill holes for 8 equidistant wheels centered 2cm from the bottom.
# Where do I drill?
# This is one of those "I want to see how you think" interview questions,
# which many studies have shown do not predict job performance.
# In fact, if someone asks you a question like this, consider walking away from the interview.
# Why? First let's answer the problem:
# A: This isn't really a programming question, it's an analysis question.
# There are several (!) tricks to this question that I can see:
#
# 1) For the calculation, the fact that it is a circle is not especially relevant,
# except that the line formed by the holes is a cycle
# So, no PI is necessary! Just divide the circumference by 8.
# 2) The question doesn't mention if the wheels are on axles (a QA/architecture question).
# If so, the axles would all run into each other! So let's assume they have no axles.
# That's what inexperienced developers would do! Assume the best!
# 3) the other trick is: the string may be meant to be a hint.
# - 8 is a power of 2
# - so you can find the points to drill by folding the string in half 3 times,
# - then marking everywhere the string is folded
# - Wrap this around the cylinder and drill on the marks. But where??
# We discover this string is not going to make your job especially easier,
# because the way the question is phrased, someone must have a metric ruler
# somewhere at least 50cm long, and you have to measure 2cm up anyway!
# Now I have more questions. Did the interviewer mess up the question?
# Are you not allowed to use a ruler? Is this a poorly phrased metaphor for something?
# Is it an ill-remembered puzzle from Encyclopedia Brown?? What is the deal?
# Maybe we have to let it go.
# So now that we have an answer,
# why this question may be unintentionally revealing something about the asker:
# The whole thing is sort of stupid and reeks of an ego boost for the interviewer...
# and at that, an interviewer who doesn't ever actually build anything physical.
# The fabrication methodology is ridiculous and contrived,
# if it were really about putting wheels on a cylinder, which of course it is not.
#
# But worse, it may be an indicator of an anti-pattern of the team's engineers, rederiving
# basic libraries from scratch, when they could have just used a common implementation
# and then immediately started work on the product.
#
# Like "implement quicksort! Our thing is different!"
# No. Don't implement Quicksort. Everyone has done that already.
# The part of your thing that is different is not going to helped by rewriting Quicksort.
# Sooooo...
# Want to see some code?? Sure!
TOTAL_CIRCLE = 50.0
NUMBER_OF_SEGMENTS = 8
puts "\n\nDividing a circle of circumference #{TOTAL_CIRCLE} cm " \
"into #{NUMBER_OF_SEGMENTS} segments:"
segment_length = TOTAL_CIRCLE / NUMBER_OF_SEGMENTS
puts "\nThe length of each segment is #{segment_length} cm"
puts "\nSo the segment endpoints lie at measurements:\n\n"
NUMBER_OF_SEGMENTS.times { |i| puts "\tSegment #{i +1} begins at\t#{segment_length * i} cm" }
puts "\n\tSegment #{NUMBER_OF_SEGMENTS} ends at\t#{TOTAL_CIRCLE} cm,"
puts "\t which is the same point as 0 cm"
puts "\n\n"
=begin
sample output:
Dividing a circle of circumference 50.0 cm into 8 segments:
The length of each segment is 6.25 cm
So the segment endpoints lie at measurements:
Segment 1 begins at 0.0 cm
Segment 2 begins at 6.25 cm
Segment 3 begins at 12.5 cm
Segment 4 begins at 18.75 cm
Segment 5 begins at 25.0 cm
Segment 6 begins at 31.25 cm
Segment 7 begins at 37.5 cm
Segment 8 begins at 43.75 cm
Segment 8 ends at 50.0 cm,
which is the same point as 0 cm
=end
|
require_relative 'db_connection'
require_relative '01_sql_object'
module Searchable
def where(params)
where_section = ""
params.each do |col, val|
where_section += "#{col.to_s} = #{val.to_s} AND "
end
where_string = where_section[0..-5]
results = DBConnection.execute(<<-SQL)
SELECT *
FROM #{table_name}
WHERE #{where_string}
SQL
parse_all(results)
end
end
class SQLObject
extend Searchable
# Mixin Searchable here...
end
|
Pod::Spec.new do |s|
s.name = "SwiftUIPager"
s.version = ENV['LIB_VERSION'] # pod trunk me --verbose
s.summary = "Native pager for SwiftUI. Easily to use, easy to customize."
s.description = <<-DESC
This framework provides a pager build on top of SwiftUI native components. Views are recycled, so you do not have to worry about memory issues. It is very easy to use and lets you customize it. For example, you can change the page aspect ratio, the scroll orientation and/or direction, the spacing between pages... It comes with with two pagination effects to make it look even more beautiful.
DESC
s.homepage = "https://medium.com/@fmdr.ct"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "fermoya" => "fmdr.ct@gmail.com" }
s.platforms = { :ios => "13.0", :osx => "10.15", :watchos => "6.0", :tvos => "13.0" }
s.swift_version = "5.1"
s.source = { :git => "https://github.com/fermoya/SwiftUIPager.git", :tag => "#{s.version}" }
s.source_files = "Sources/SwiftUIPager/**/*.swift"
s.documentation_url = "https://github.com/fermoya/SwiftUIPager/blob/main/README.md"
end
|
module JavaClass
# The module Analyse is for separating namespaces. It contains various methods
# to analyse classes accross a whole code bases (Classpath). The functionality
# of all analysers is collected in Dsl::ClasspathAnalysers.
# Author:: Peter Kofler
module Analyse
# Analyser to get dependencies of a whole Classpath (to be mixed into Dsl::LoadingClasspath).
# For an example see
# {how to list all imported types}[link:/files/lib/generated/examples/find_all_imported_types_txt.html].
# Author:: Peter Kofler
module Dependencies
# Return all types in this classpath. An additional block is used as _filter_ on class names.
# Returns a list of JavaQualifiedName. Requires a method _names_ in the base class.
def types(&filter)
names(&filter).collect { |c| c.to_classname }.sort
end
# Determine all imported types from all classes in this classpath together with count of imports.
# An additional block is used as _filter_ on class names. Requires a method _values_ in the base class.
def used_types_map(&filter)
type_map = Hash.new(0) # class_name (JavaQualifiedName) => cnt
values(&filter).collect { |clazz| clazz.imported_3rd_party_types }.flatten.each do |type|
# hash keys need to be frozen to keep state
if !type_map.include?(type)
type = type.freeze
end
type_map[type] += 1
end
type_map
end
# Determine all imported types from all classes in this classpath.
# An additional block is used as _filter_ on class names.
def used_types(&filter)
used_types_map(&filter).keys.sort
end
# Determine all foreign imported types from all classes in this classpath.
# An additional block is used as _filter_ on class names.
def external_types(&filter)
used_types(&filter) - types(&filter)
end
end
end
end
|
class AddIngredientRecipeIndex < ActiveRecord::Migration
def change
add_index :ingredients_recipes, [:recipe_id, :ingredient_id], :unique => true
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.network "private_network", ip: "192.168.56.16"
# full version WS2016
config.vm.box = "gusztavvargadr/w16s"
# alternative:
# config.vm.box = "mwrock/Windows2016"
config.vm.network "public_network", bridge: "Intel(R) Dual Band Wireless-AC 3160"
# configuration for virtualbox
config.vm.provider "virtualbox" do |v|
v.name = "DockerForWinVM"
v.memory = 4096
v.cpus = 2
end
# configuration for hyperv
config.vm.provider "hyperv" do |v|
v.vmname = "DockerForWinVM"
v.memory = 4096
v.cpus = 2
end
config.windows.halt_timeout = 15
config.winrm.max_tries = 30
config.vm.boot_timeout = 420
config.vm.hostname = "DockerForWinVM"
config.vm.provision :shell, path: "Provisioning/Chocolatey.ps1"
config.vm.provision :shell, path: "Provisioning/Docker-P1.ps1"
# reload plugin for restart during provision
# download from aidanns/vagrant-reload with 'vagrant plugin install vagrant-reload'
config.vm.provision :reload
config.vm.provision :shell, path: "Provisioning/Docker-P2.ps1"
config.vm.provision :shell, path: "Provisioning/docker-compose.bat"
# Verschil in connectiestring = User ID != User
config.vm.provision "file", source: "../VoorbeeldProjectWindows", destination: "~/VoorbeeldProject"
# config.vm.provision "file", source: "D:/Documenten/School/HoGent/StageEnBachelorproef/bachelorproef/BachelorproefDocker/09solSportsStore-master", destination: "~/09solSportsStore-master"
config.vm.provision :shell, path: "Provisioning/images.ps1"
config.vm.provision :shell, path: "Provisioning/applicaties.ps1"
end
|
json.array!(@users) do |user|
json.extract! user, :name, :email, :hashed_password, :salt, :true_name, :student_number, :team_id, :portait_path, :type
json.url user_url(user, format: :json)
end
|
require 'spec_helper'
describe "Function form_migration_content:" do
before do
@add = ["add_index :report, :_id_test_plan"]
end
it "print migration skeleton with set name" do
migration = LolDba.form_migration_content("TestMigration", @add)
expect(migration).to match(/class TestMigration/i)
end
it "print migration with add_keys params" do
migration = LolDba.form_migration_content("TestMigration", @add)
expect(migration).to match(/add_index :report, :_id_test_plan/i)
end
end
describe "Function form_data_for_migration:" do
it "return data for migrations for non-indexed single key in table" do
relationship_indexes = {:users => [:user_id]}
allow(LolDba).to receive(:key_exists?).with(:users, :user_id).and_return(false)
add_indexes = LolDba.form_data_for_migration(relationship_indexes)
expect(add_indexes.first).to eq("add_index :users, :user_id")
end
it "return data for migrations for non-indexed composite key in table" do
relationship_indexes = {:friends => [[:user_id, :friend_id]]}
allow(LolDba).to receive(:key_exists?).with(:friends, [:user_id, :friend_id]).and_return(false)
add_indexes = LolDba.form_data_for_migration(relationship_indexes)
expect(add_indexes.first).to eq("add_index :friends, [:user_id, :friend_id]")
end
it "ignore empty or nil keys for table" do
relationship_indexes = {:table => [""], :table2 => [nil]}
add_indexes = LolDba.form_data_for_migration(relationship_indexes)
expect(add_indexes).to be_empty
end
end
describe "Function key_exists?:" do
it "return true if key is already indexed" do
expect(LolDba.key_exists?("companies", "country_id")).to be_truthy
end
it "return false if key is not indexed yet" do
expect(LolDba.key_exists?("addresses", "country_id")).to be_falsey
end
it "return true if key is primary key(default)" do
expect(LolDba.key_exists?("addresses", "id")).to be_truthy
end
it "return true if key is custom primary key" do
expect(LolDba.key_exists?("gifts", "custom_primary_key")).to be_truthy
end
end
describe "Function puts_migration_content:" do
before do
@relationship_indexes, warning_messages = LolDba.check_for_indexes
end
it "print migration code" do
expect($stdout).to receive(:puts).with("")
expect($stdout).to receive(:puts).with(/TIP/)
expect($stdout).to receive(:puts).with(/TestMigration/i)
LolDba.puts_migration_content("TestMigration", @relationship_indexes, "")
end
it "print warning messages if they exist" do
warning = "warning text here"
expect($stdout).to receive(:puts).at_least(:once).with(warning)
expect($stdout).to receive(:puts)
LolDba.puts_migration_content("TestMigration", {}, warning)
end
it "print nothing if no indexes and warning messages exist" do
expect($stdout).to receive(:puts).with("")
expect($stdout).to receive(:puts).with("Yey, no missing indexes found!")
LolDba.puts_migration_content("TestMigration",{}, "")
end
end |
class RenameTypeColumnToUserImages < ActiveRecord::Migration[5.0]
def change
rename_column :user_images, :type, :image_type
end
end
|
# The login functions allow users to log in (what enables them
# to mantain a list of saved theorems), new users to registrate
# and logged users to log out.
class LoginController < ApplicationController
before_filter :authorize, :except => [:login, :add_user]
# Add a new user to the database.
def add_user
if request.get?
@user = User.new
else
@user = User.new(params[:user])
if @user.save
flash[:notice] = "User #{@user.name} created"
redirect_to(:action => 'login')
else
flash[:notice] = "User alread exists!"
end
end
end
# Display the login form and wait for user to
# enter a name and password. Then it validates
# these, adding the user object to the session,
# if authorized.
def login
if request.get?
session[:user_id] = nil
@user = User.new
else
@user = User.new(params[:user])
logged_in_user = @user.try_to_login
if logged_in_user
session[:user_id] = logged_in_user.id
redirect_to :controller => "proof", :action => "new"
else
flash[:notice] = "Invalid user/password combination"
end
end
end
# Log out by clearing the user entry in the session.
def logout
session[:user_id] = nil
flash[:notice] = "Logged out"
redirect_to(:controller => "proof", :action => "new")
end
end
|
class Api::WeixinConfigsController < Api::BaseController
skip_before_action :authenticate_user!
def index
signature = Wechat.api.jsapi_ticket.signature params[:url] || request.referer
render json: {
appId: WxPay.appid, # 必填,公众号的唯一标识
timestamp: signature[:timestamp], # 必填,生成签名的时间戳
nonceStr: signature[:noncestr], # 必填,生成签名的随机串
signature: signature[:signature],# 必填,签名,见附录1
# jsApiList: ['chooseWXPay', 'onMenuShareTimeline'], # 必填,需要使用的JS接口列表,所有JS接口列表见附录2
expired_at: Wechat.api.jsapi_ticket.got_ticket_at + Wechat.api.jsapi_ticket.ticket_life_in_seconds
}
end
alias :signature :index
def card_ext
options = {}
options[:openid] = params[:openid] if params[:openid].present?
options[:code] = params[:code] if params[:code].present?
options[:card_id] = params[:card_id] if params[:card_id].present?
result = Wechat.api.card_api_ticket.card_ext(options)
render json: {card_ext: result}
end
end |
namespace :ghc do
VERSION = '7.10.1' #GHC_VERSION
PREFIX = "/opt/ghc#{VERSION}"
task :run, [:src] do |t, arg|
ENV['PORT'] = '9090'
sh "cabal exec runhaskell #{PROJ_DIR}/src/web/#{arg.src}"
end
desc "print ghc-package dependencies"
task :pkgs do
puts GHC_PACKAGE_PATH
end
task :packages => :pkgs
desc "install ghc-#{VERSION}"
task :install => 'make:install'
desc "info"
task :info do
puts VERSION
puts PREFIX
end
namespace :make do
VER = VERSION
GHC_URL = "http://www.haskell.org/ghc/dist/#{VER}/ghc-#{VER}-src.tar.bz2"
GHC_TAR = "/var/tmp/#{GHC_URL.split('/').last}"
GHC_DIR = "/var/tmp/#{GHC_URL.split('/').last.split('-src').first}"
task :install => :build do
sh "cd #{GHC_DIR} && sudo make install"
end
task :build => [:pkgs, GHC_DIR] do
sh "cd #{GHC_DIR} && ./configure --prefix=#{PREFIX} CFLAGS=-O2"
sh "cd #{GHC_DIR} && make -j 8"
end
task :pkgs do
sh "sudo apt-get install -y ncurses-dev"
end
directory GHC_DIR => GHC_TAR do |t|
sh "cd /var/tmp && tar xf #{GHC_TAR}"
sh "cd #{GHC_DIR} && ./configure --prefix=#{PREFIX} CFLAGS=-O2"
end
file GHC_TAR do |t|
sh "wget -c -O #{t.name} #{GHC_URL}"
end
task :clean do
[GHC_TAR,GHC_DIR].each do |d|
sh "rm -rf #{d}"
end
end
end
end
|
class TemplatesController < ApplicationController
before_filter :template, :only => [:edit, :show, :destroy, :compile]
before_filter do
@page_title = template.name if template
end
def index
@page_title = "Template Directory"
@templates = RailsTemplate.listed.recent.limit(30)
render :action => 'index', :layout => 'application'
end
def new
@toc = true
@template = RailsTemplate.new
end
def create
@template = RailsTemplate.new(params[:rails_template])
@template.user = current_user if signed_in?
if @template.save
redirect_to (params[:next_step] == 'Finish') ? show_path(@template) : edit_path(@template)
else
flash[:alert] = 'Unable to create a template. Something is wrong.'
redirect_to root_path
end
end
def edit
@toc = true
params[:step] ||= 'app_info'
@heading = params[:step].titleize
@page_title = "Editing '#{template.name}'"
end
def compile
t = RailsWizard::Template.new(template.recipes)
render :text => t.compile, :content_type => 'text/plain', :layout => false
end
def update
if template.update_attributes(params[:rails_template])
redirect_to next_state
else
flash.now[:alert] = 'Unable to update template.'
render :action => params[:step]
end
end
def show
@page_title = template && template.name?? "#{template.name}".html_safe : "Your Template"
@heading = 'Generate Your Application'
render :action => 'show', :layout => 'application'
end
protected
def next_state
case params[:commit]
when 'Next Step'
step_path(template, next_step)
when 'Previous Step'
step_path(template, previous_step)
when 'Finish'
show_path(template)
end
end
def template
@template ||= RailsTemplate.from_param(params[:id])
end
helper_method :template
def next_step
RailsTemplate::STEPS[RailsTemplate::STEPS.index(params[:step]) + 1]
end
def previous_step
RailsTemplate::STEPS[RailsTemplate::STEPS.index(params[:step]) - 1]
end
helper_method :next_step, :previous_step
end
|
class Cart < ActiveRecord::Base
has_many :line_items
has_many :items, through: :line_items
belongs_to :user
def add_item(item_id)
new_item = Item.find_by(id: item_id)
if items.include?(new_item)
current_line_item = line_items.find_by(item_id: new_item.id)
current_line_item.quantity += 1
current_line_item
else
new_line_item = new_item.line_items.build(quantity: 1)
new_line_item.cart = self
new_line_item
end
end
def total
total_price = 0
self.items.each do |item|
total_price += item.price
end
total_price
end
end
|
class TeamSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :division
attribute :coach do |object|
object.coach.proper_name
end
attribute :number_students do |object|
object.students.count
end
end
|
# coding: utf-8
$:.unshift('lib')
require 'natto/version'
Gem::Specification.new do |s|
s.name = 'natto'
s.version = Natto::VERSION
s.add_dependency('ffi', '>= 1.9.0')
s.license = 'BSD'
s.summary = 'A gem leveraging FFI (foreign function interface), natto combines the Ruby programming language with MeCab, the part-of-speech and morphological analyzer for the Japanese language.'
s.description = <<END_DESC
natto provides a naturally Ruby-esque interface to MeCab. It runs on both CRuby (mri/yarv) and JRuby (jvm). It works with MeCab installations on Windows, Unix/Linux, and OS X. No compiler is necessary, as natto is not a C extension.
END_DESC
s.author = 'Brooke M. Fujita'
s.email = 'buruzaemon@gmail.com'
s.homepage = 'https://github.com/buruzaemon/natto'
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 1.9'
s.require_path = 'lib'
s.requirements << 'MeCab 0.996'
s.requirements << 'FFI, 1.9.0 or greater'
s.files = [
'lib/natto.rb',
'lib/natto/binding.rb',
'lib/natto/natto.rb',
'lib/natto/option_parse.rb',
'lib/natto/struct.rb',
'lib/natto/version.rb',
'README.md',
'LICENSE',
'CHANGELOG',
'.yardopts'
]
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest'
end
# Copyright (c) 2020, Brooke M. Fujita.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
# -*- coding: utf-8 -*-
require 'mini_magick' # image manipulation
require 'rtesseract' # OCR
require 'hpricot' #html analyzer
require 'net/http'
class Frigga
attr_reader :cookie, :user, :status
:READY
:SUCCESS
:FAIL
:CAPTCHA_WRONG
:USER_INFO_WRONG
def initialize(doretry=true)
@cookie = ""
@captcha = ""
@user = {id:nil, pwd:nil}
@retry = doretry
@retrycounter = 8
@status = {stat: :READY, info:nil}
end
def login(id, pwd)
@user[:id] = id
@user[:pwd] = pwd
get_cookie
loop do
get_captha_text
uri = URI(LOGIN_URL)
http = Net::HTTP.start(uri.host, uri.port)
data = gen_form_data({
operation: FORM_operation,
usercode_text: id,
userpwd_text: pwd,
checkcode_text: @captcha,
submittype: FORM_submittype
})
headers = {'Cookie' => @cookie}
resp = http.post(uri.request_uri, data, headers)
body = Frigga::get_utf8_body(resp)
doc = Hpricot(body)
fail = doc.search('noframes').first.nil?
if fail
info = doc.search('li').first
if info.nil?
raise 'Unknown wrong.'
end
content = info.inner_html
if content.match(CONFIRM_captcha)
@status[:stat] = :FAIL
@status[:info] = :CAPTCHA_WRONG
break unless @retry && @retrycounter>0
@retrycounter-=1
puts 'ocr failed,retrying...'
sleep 2
redo
end
if content.match(CONFIRM_input)
@status[:stat] = :FAIL
@status[:info] = :USER_INFO_WRONG
break
end
raise 'Unknown wrong.'
end
@status[:stat] = :SUCCESS
@status[:info] = nil
break
end
return @status[:stat] == :SUCCESS
end
def to_s
org = super
org.chop<<"\n[user]#{@user};\n[cookie]#{@cookie}\n[status]#{@status}"<<'>'
end
protected
CAPTCHA_FILE = 'captcha.jpg'
URL = 'http://222.30.32.10/'
VC_URL = URL+'ValidateCode' # CAPTCHA_URL
LOGIN_URL = URL+'stdloginAction.do'
FORM_operation = 'no'
FORM_submittype = '%C8%B7+%C8%CF'
CONFIRM_captcha = "请输入正确的验证码!"
CONFIRM_input = "用户不存在或密码错误!"
def self.get_utf8_body(resp)
body = resp.body
doc = Hpricot(body)
encoding = doc.search("meta[@content]").first.attributes['content'].split('charset=')[1]
body.force_encoding(encoding).encode("UTF-8")
end
def gen_form_data(list)
data = ""
list.each do |key, val|
data<<"#{key}=#{val}"<<'&'
end
data.chop
end
def get_captha_text
uri = URI.parse(VC_URL)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.initialize_http_header({ "Cookie" => @cookie })
response = http.request(request)
img = File.open(CAPTCHA_FILE, 'w')
img.write(response.read_body)
img.close
img = MiniMagick::Image.new(CAPTCHA_FILE)
img.resize(300)
# img.monochrome
# img.sharpen -1
@captcha = RTesseract.new(img.path).to_s_without_spaces.gsub(/[^0-9]/,"")
end
def get_cookie
uri = URI.parse(URL)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
@cookie = response.get_fields('set-cookie')[0].split(';')[0]
end
end |
# == Schema Information
#
# Table name: classrooms
#
# id :integer not null, primary key
# user_id :integer
# name :string(255)
# created_at :datetime
# updated_at :datetime
# school_id :integer
# teacher_id :integer
# code :string(255)
#
class Classroom < ActiveRecord::Base
belongs_to :school
belongs_to :teacher, :class_name => "User"
has_and_belongs_to_many :users
has_many :pins
has_many :reflections
validates_presence_of :school
validates_presence_of :teacher
validates :code, :uniqueness => { :scope => :school_id }
end
|
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.provision "ansible_local" do |ansible|
ansible.inventory_path = "tests/inventory"
ansible.limit = "localhost"
ansible.playbook = "tests/test.yml"
ansible.raw_arguments = [
"--connection=local",
"--sudo",
]
ansible.verbose = "v"
end
end
|
require_relative '../test_helper'
class ConfigTest < Ojo::OjoTestCase
def test_locations
Ojo.configuration.location = File.expand_path('../../tmp')
assert_equal File.expand_path('../../tmp'), Ojo.configuration.location
end
end
|
class DeleteRawData < ActiveRecord::Migration
def change
drop_table :raw_data
end
end
|
# frozen_string_literal: true
require 'bolt_spec/conn'
require 'bolt_spec/files'
require 'bolt_spec/integration'
describe "when running a plan that manipulates an execution result", ssh: true do
include BoltSpec::Conn
include BoltSpec::Files
include BoltSpec::Integration
let(:modulepath) { File.join(__dir__, '../fixtures/modules') }
let(:uri) { conn_uri('ssh', include_password: true) }
let(:config_flags) { %W[--no-host-key-check --format json --modulepath #{modulepath}] }
after(:each) { Puppet.settings.send(:clear_everything_for_tests) }
def run_plan(plan, params)
run_cli(['plan', 'run', plan, "--params", params.to_json] + config_flags)
end
context 'when using CLI options' do
let(:config_flags) { %W[--no-host-key-check --format json --modulepath #{modulepath}] }
it 'returns true on success' do
params = { target: uri }.to_json
output = run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(output.strip).to eq('true')
end
it 'returns false on failure' do
params = { target: uri, fail: true }.to_json
output = run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(output.strip).to eq('false')
end
context 'filters result sets' do
it 'includes target when filter is true' do
safe_uri = conn_uri('ssh')
params = { target: uri }.to_json
run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(@log_output.readlines)
.to include("NOTICE Puppet : Filtered set: [#{safe_uri}]\n")
end
it 'excludes target when filter is false' do
params = { target: uri, fail: true }.to_json
run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(@log_output.readlines).to include("NOTICE Puppet : Filtered set: []\n")
end
end
context 'array indexes result sets' do
it 'with a single index' do
params = { target: uri }.to_json
run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(@log_output.readlines)
.to include("NOTICE Puppet : Single index: #{uri}\n")
end
it 'with a slice index' do
params = { target: uri, fail: true }.to_json
run_cli(['plan', 'run', 'results::test_methods', "--params", params] + config_flags)
expect(@log_output.readlines).to include("NOTICE Puppet : Slice index: [#{uri}]\n")
end
end
it 'exposes `status` method for result and renames `result` to `value`' do
params = { nodes: uri }.to_json
result = run_cli(['plan', 'run', 'results::test_result', "--params", params] + config_flags)
expect(@log_output.readlines)
.to include("NOTICE Puppet : Result status: success\n")
expect(JSON.parse(result).first).to include('value')
end
end
it 'exposes errrors for results' do
params = { target: uri }.to_json
output = run_cli(['plan', 'run', 'results::test_error', "--params", params] + config_flags)
expect(output.strip).to eq('"The task failed with exit code 1:\n"')
end
end
|
class QuestionsController < ApplicationController
before_action :require_user
before_action :require_admin
def new
@question = Question.new
@quiz = Quiz.find(params['quiz_id'])
#@answer = Answer.new
end
def create
@question = Question.new(question_params)
@quiz = Quiz.find(params[:quiz_id])
if @question.save
@join = QuizQuestion.new(quiz_id: @quiz.id, question_id: @question.id)
@join.save
flash[:success] = "Question was sucessfully created"
redirect_to edit_quiz_path(@quiz)
else
flash[:danger] = "That didnt work"
redirect_to quiz_path(@quiz)
end
end
def edit
@question = Question.find(params[:id])
@quiz = Quiz.find(params[:quiz_id])
# @hasanswers = QuestionAnswer.all
# @allanswers = Answer.all
# @answers = @question.answers.all
# @availablea = Answer.where.not(id: @answers)
end
def update
@question = Question.find(params[:id])
@quiz = Quiz.find(params[:quiz_id])
if @question.update(question_params)
flash[:success] = "Question was successfully updated"
redirect_to edit_quiz_path(@quiz)
else
render 'edit'
end
end
def destroy
@question = Question.find(params[:id])
@question.destroy
flash[:danger] = "The Quiz Question has been deleted"
redirect_back(fallback_location:"/")
end
private
def question_params
params.require(:question).permit(:question, quiz_ids: [])
end
def require_admin
if !logged_in? || (logged_in? && !current_user.admin?)
flash[:danger] = "Only Admins can perform that action"
redirect_to root_path
end
end
end |
# web elements and functions for page
class BrokenLinksPage
include Capybara::DSL
include RSpec::Matchers
include Capybara::RSpecMatchers
def initialize
@good_image = Element.new(:css, "[src='/images/Toolsqa.jpg']")
@broken_image = Element.new(:css, "[src='/images/Toolsqa_1.jpg']")
end
def visit
Capybara.visit('broken')
end
def test_image
page.should have_css(@broken_image.path)
img = page.first(:css, @broken_image.path)
Capybara.visit img[:src]
# html response code should be 200
# maybe different solution?
end
end
|
class ExposureSerializer < ActiveModel::Serializer
attributes :id,:cvss_severity, :summary, :cve_id, :published, :title, :access_vector, :access_complexity, :integrity_impact, :availablility_impact, :cvss_v2_base_score
has_many :references
end
|
# frozen_string_literal: true
class TreasureHuntController < ApplicationController
def index
render json: TreasureHunt.all, status: :ok
end
def create
th = TreasureHunt.new(treasure_hunt_params)
if th.save
render json: { status: 'ok', distance: th.distance }, status: :ok
else
render json: { status: 'error', distance: -1, error: th.errors.full_messages }, status: :bad_request
end
end
private
def treasure_hunt_params
params.permit(:email, [current_location: []])
end
end
|
# frozen_string_literal: true
require 'uri'
require 'net/http'
module PhoneValidation
class ValidationRequest
attr_accessor :phone_number, :token
BASE_URL = 'http://apilayer.net/api/validate'
RESPONSE_FIELDS = %w[
carrier
country_code
country_name
country_prefix
international_format
line_type
location
local_format
].freeze
def initialize(token:, phone_number:)
@phone_number = phone_number
@token = token
end
def call
response = http.request(new_request)
response.read_body
end
private
def url
@url ||= URI("#{BASE_URL}?#{url_params}")
end
def url_params
params_hash.map { |key, value| "#{key}=#{value}" }.join('&')
end
def params_hash
{
access_key: token,
number: phone_number
}
end
def new_request
request = Net::HTTP::Get.new(url)
request['Content-Type'] = 'application/json'
request
end
def http
Net::HTTP.new(url.host, url.port)
end
end
end
|
require 'spec_helper'
describe "raw_touch_data/show" do
before(:each) do
@raw_touch_datum = assign(:raw_touch_datum, stub_model(RawTouchDatum,
:phase => 1,
:radius => 1.5,
:timestamp => 1.5,
:x => 1.5,
:y => 1.5
))
end
it "renders attributes in <p>" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
rendered.should match(/1/)
rendered.should match(/1.5/)
rendered.should match(/1.5/)
rendered.should match(/1.5/)
rendered.should match(/1.5/)
end
end
|
# This method will return an array of arrays.
# Each subarray will have strings which are anagrams of each other
# Time Complexity: O(n)
# Space Complexity: O(n)
def grouped_anagrams(strings)
return [] if strings.empty?
anagram_hash = Hash.new()
strings.each do |string|
word_array = string.split("").sort
if anagram_hash.include?(word_array)
anagram_hash[word_array] << string
else
anagram_hash[word_array] = [string]
end
end
result = []
anagram_hash.each do |key, value|
result << value
end
return result
end
# This method will return the k most common elements
# in the case of a tie it will select the first occurring element.
# Time Complexity: O(n)
# Space Complexity: O(n)
def top_k_frequent_elements(list, k)
return [] if list.empty?
return list if list.length == 1
element_count = Hash.new()
list.each do |element|
if element_count[element]
element_count[element] += 1
else
element_count[element] = 1
end
end
result = []
k.times do |i|
count = 0
frequent_element = nil
element_count.each do |element, frequency|
if frequency > count
count = frequency
frequent_element = element
end
end
result << frequent_element
element_count[frequent_element] = 0 if frequent_element
end
return result
end
# This method will return the true if the table is still
# a valid sudoku table.
# Each element can either be a ".", or a digit 1-9
# The same digit cannot appear twice or more in the same
# row, column or 3x3 subgrid
# Time Complexity: I have no idea...O(n^2) since I have nested loops?
# Space Complexity: O(n)
def valid_sudoku(table)
return true if in_row?(table) && in_column?(table) && in_box?(table)
return false
end
def in_row?(table)
table.length.times do |row|
sudoku_hash = Hash.new()
table.length.times do |i|
if sudoku_hash[table[row][i]]
return false
end
if table[row][i] != '.'
sudoku_hash[table[row][i]] = 1
end
end
end
end
# Checks whether there is any
# duplicate in current column or not.
def in_column?(table)
table.length.times do |col|
column_hash = Hash.new()
table.length.times do |i|
if column_hash[table[i][col]]
return false
end
if table[i][col] != '.'
column_hash[table[i][col]] = 1
end
end
end
end
# Checks whether there is any duplicate
# in current 3×3 box or not.
def in_box?(table)
# formula from https://stackoverflow.com/questions/41020695/how-do-i-split-a-9x9-array-into-9-3x3-components
grids = table.each_slice(3).map{|strip| strip.transpose.each_slice(3).map{|chunk| chunk.transpose}}.flatten(1)
grids.each do |box|
box_hash = Hash.new()
3.times do |row|
3.times do |col|
current = box[row][col]
if box_hash[current]
return false
end
if current != '.'
box_hash[current] = 1
end
end
end
end
end
|
FactoryGirl.define do
factory :contract_responsible do
association :contract
name {Faker::Name.name}
office {Faker::Company.profession}
department {Faker::Company.name}
whatsapp {Faker::PhoneNumber.phone_number}
skype {Faker::Beer.name}
end
end
|
require 'mongoid/history'
module ActiveTriples
class MongoidStrategy
class Trackable < MongoidStrategy
##
# Overload initializer to enable tracking
def initialize(source)
super source
enable_tracking
end
##
# Roll back last change and update source graph
# @return [Boolean] return whether the rollback was successful
def undo!
return false if history_tracks.empty?
document.undo!
source.clear
reload
end
private
##
# Make the delegate class trackable
def enable_tracking
collection.send :include, Mongoid::History::Trackable
collection.track_history
class << self
delegate :history_tracks, to: :document
delegate :track_history?, to: :collection
end
end
##
# Mongoid model for tracking changes to persisted `Mongoid::Documents`.
class HistoryTracker
include Mongoid::History::Tracker
end
end
end
end |
require 'faraday'
require 'json'
module Overleap
class Report
attr_reader :propensity, :ranking
def initialize(url, data)
connection = Overleap::Report.make_connection(url)
response = Overleap::Report.get_response(connection, data)
@propensity = response["propensity"]
@ranking = response["ranking"]
end
def to_s
puts "Propensity: #{@propensity}\n Response: #{@ranking}"
end
def self.make_connection(url)
connection = Faraday.new(:url => url) do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
connection
end
def self.get_response(socket, data)
attributes = nil
check_faraday(socket)
check_data(data)
begin
response = socket.get "/customer_scoring",
{ :income => data[:income],
:zipcode => data[:zipcode],
:age => data[:age] }
rescue
raise $!, "The URL you entered was either invalid, or incorrect."
end
check_status_code(response.status)
attributes = JSON.parse(response.body)
check_response(attributes)
attributes
end
private
def self.check_faraday(source)
raise TypeError, "Connection not valid. Please use create_connection with a valid url to create a Faraday connection." unless source.is_a? Faraday::Connection
end
def self.check_data(data)
if data.is_a? Hash
raise RuntimeError, "The information you entered was either incomplete or incorrect. Please include income, zipcode, and age." unless data.has_key?(:income) && data.has_key?(:zipcode) && data.has_key?(:age)
else
raise TypeError, "Please include income, zipcode, and age in a Hash."
end
end
def self.check_response(response)
if response.is_a? Hash
raise RuntimeError, "The received response did not include correct data. Please check that your source leads to the correct API." unless response.has_key?("propensity") && response.has_key?("ranking")
else
raise TypeError, "The received response was not a JSON. Please check that your source leads to the correct API."
end
end
def self.check_status_code(code)
raise RuntimeError, "Error code #{code} received. Please confirm that you are connecting to the correct website." unless code == 200
end
end
end
|
class AddFiresToCamps < ActiveRecord::Migration
def change
add_column :camps, :fires, :string
end
end
|
class Post < ActiveRecord::Base
attr_accessible :content
validates :content, :presence => true
validates :content, :length => { :minimum => 6 }
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.