hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
ed28dec2bc2b3a7a8ffa1abd7dd99418bf13b36a | 1,382 | class Geoserver < Formula
desc "Java server to share and edit geospatial data"
homepage "https://geoserver.org/"
url "https://downloads.sourceforge.net/project/geoserver/GeoServer/2.20.4/geoserver-2.20.4-bin.zip"
sha256 "418ef109c051d997d75d86a6fe51ee5280b87fabdb73cd96d3210f2d43a79b64"
# GeoServer releases contain a large number of files for each version, so the
# SourceForge RSS feed may only contain the most recent version (which may
# have a different major/minor version than the latest stable). We check the
# "GeoServer" directory page instead, since this is reliable.
livecheck do
url "https://sourceforge.net/projects/geoserver/files/GeoServer/"
strategy :page_match
regex(%r{href=(?:["']|.*?GeoServer/)?v?(\d+(?:\.\d+)+)/?["' >]}i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "5309f664f62a28dd177bc1ab63c3e59f6ff47f9dc7242a277d4c9abd66d514b0"
end
def install
libexec.install Dir["*"]
(bin/"geoserver").write <<~EOS
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $ geoserver path/to/data/dir"
else
cd "#{libexec}" && java -DGEOSERVER_DATA_DIR=$1 -jar start.jar
fi
EOS
end
def caveats
<<~EOS
To start geoserver:
geoserver path/to/data/dir
EOS
end
test do
assert_match "geoserver path", shell_output("#{bin}/geoserver")
end
end
| 31.409091 | 112 | 0.686686 |
08dc9c47cc1b2d52fd2808bdbc0cc12aefa5fb7b | 6,052 | #!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
ONE_LOCATION = ENV['ONE_LOCATION']
if !ONE_LOCATION
RUBY_LIB_LOCATION = '/usr/lib/one/ruby'
VMDIR = '/var/lib/one'
CONFIG_FILE = '/var/lib/one/config'
else
RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby'
VMDIR = ONE_LOCATION + '/var'
CONFIG_FILE = ONE_LOCATION + '/var/config'
end
$LOAD_PATH << RUBY_LIB_LOCATION
require 'opennebula'
require 'vcenter_driver'
require 'base64'
require 'nsx_driver'
base64_temp = ARGV[1]
template = OpenNebula::XMLElement.new
template.initialize_xml(Base64.decode64(base64_temp), 'VNET')
managed = template['TEMPLATE/OPENNEBULA_MANAGED'] != 'NO'
imported = template['TEMPLATE/VCENTER_IMPORTED']
error = template['TEMPLATE/VCENTER_NET_STATE'] == 'ERROR'
begin
# Step 0. Only execute for vcenter network driver
if template['VN_MAD'] == 'vcenter' && managed && !error && imported.nil?
# Step 1. Extract vnet settings
host_id = template['TEMPLATE/VCENTER_ONE_HOST_ID']
raise 'Missing VCENTER_ONE_HOST_ID' unless host_id
pg_name = template['TEMPLATE/BRIDGE']
pg_type = template['TEMPLATE/VCENTER_PORTGROUP_TYPE']
sw_name = template['TEMPLATE/VCENTER_SWITCH_NAME']
# Step 2. Contact cluster and extract cluster's info
vi_client = VCenterDriver::VIClient.new_from_host(host_id)
one_client = OpenNebula::Client.new
one_host = OpenNebula::Host.new_with_id(host_id, one_client)
rc = one_host.info
raise rc.message if OpenNebula.is_error? rc
ccr_ref = one_host['TEMPLATE/VCENTER_CCR_REF']
cluster = VCenterDriver::ClusterComputeResource
.new_from_ref(ccr_ref, vi_client)
dc = cluster.get_dc
# NSX
# nsxmgr = one_host['TEMPLATE/NSX_MANAGER']
# nsx_user = one_host['TEMPLATE/NSX_USER']
# nsx_pass_enc = one_host['TEMPLATE/NSX_MANAGER']
ls_id = template['TEMPLATE/NSX_ID']
# NSX
# With DVS we have to work at datacenter level and then for each host
if pg_type == VCenterDriver::Network::NETWORK_TYPE_DPG
begin
dc.lock
# Explore network folder in search of dpg and dvs
net_folder = dc.network_folder
net_folder.fetch!
# Get distributed port group and dvs if they exists
dvs = dc.dvs_exists(sw_name, net_folder)
dpg = dc.dpg_exists(pg_name, net_folder)
dc.remove_dpg(dpg) if dpg
# Only remove switch if the port group being removed is
# the last and only port group in the switch
if dvs && dvs.item.summary.portgroupName.size == 1 &&
dvs.item.summary.portgroupName[0] == "#{sw_name}-uplink-pg"
dc.remove_dvs(dvs)
end
rescue StandardError => e
raise e
ensure
dc.unlock if dc
end
end
if pg_type == VCenterDriver::Network::NETWORK_TYPE_PG
cluster['host'].each do |host|
# Step 3. Loop through hosts in clusters
esx_host = VCenterDriver::ESXHost
.new_from_ref(host._ref, vi_client)
begin
esx_host.lock # Exclusive lock for ESX host operation
next unless esx_host.pg_exists(pg_name)
swname = esx_host.remove_pg(pg_name)
next if !swname || sw_name != swname
vswitch = esx_host.vss_exists(sw_name)
next unless vswitch
# Only remove switch if the port group being removed is
# the last and only port group in the switch
if vswitch.portgroup.empty?
esx_host.remove_vss(sw_name)
end
rescue StandardError => e
raise e
ensure
esx_host.unlock if esx_host # Remove host lock
end
end
end
if pg_type == VCenterDriver::Network::NETWORK_TYPE_NSXV
nsx_client = NSXDriver::NSXClient.new(host_id)
logical_switch = NSXDriver::VirtualWire
.new(nsx_client, ls_id, nil, nil)
logical_switch.delete_logical_switch
end
if pg_type == VCenterDriver::Network::NETWORK_TYPE_NSXT
nsx_client = NSXDriver::NSXClient.new(host_id)
logical_switch = NSXDriver::OpaqueNetwork
.new(nsx_client, ls_id, nil, nil)
logical_switch.delete_logical_switch
end
end
rescue StandardError => e
STDERR.puts("#{e.message}/#{e.backtrace}")
exit(-1)
ensure
vi_client.close_connection if vi_client
end
| 39.555556 | 78 | 0.553866 |
e2002818e3337380bf5ed889a259b58173808a88 | 209 | def open_user_file
print "File to open: "
filename = gets.chomp
begin
fh = File.open(filename)
rescue
puts "Couldn't open your file!"
return
end
yield fh
fh.close
end
open_user_file
| 13.933333 | 35 | 0.674641 |
bf768fa3d1485486b6a85151daf191c290238269 | 1,006 | require 'spec_helper'
describe 'keystone::db::postgresql' do
shared_examples 'keystone::db::postgresql' do
let :req_params do
{
:password => 'keystonepass',
}
end
let :pre_condition do
'include postgresql::server'
end
context 'with only required parameters' do
let :params do
req_params
end
it { is_expected.to contain_openstacklib__db__postgresql('keystone').with(
:user => 'keystone',
:password => 'keystonepass',
:dbname => 'keystone',
:encoding => nil,
:privileges => 'ALL',
)}
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge(OSDefaults.get_facts({
:os_workers_keystone => 8,
:concat_basedir => '/var/lib/puppet/concat'
}))
end
it_behaves_like 'keystone::db::postgresql'
end
end
end
| 21.869565 | 80 | 0.578529 |
b96d9b33b83fd02c0a35cdbed4e3b9539faf575f | 412 | # frozen_string_literal: true
$LOAD_PATH << File.expand_path('../lib', __dir__)
require 'mongoid'
require 'mongoid/rspec'
require 'mongoid/enum'
ENV['MONGOID_ENV'] = 'test'
RSpec.configure do |config|
config.include Mongoid::Matchers
config.before(:each) do
Mongoid.purge!
end
end
Mongoid.load!(File.expand_path('support/mongoid.yml', __dir__), :test)
Mongo::Logger.logger.level = ::Logger::INFO
| 19.619048 | 70 | 0.728155 |
38087996d52e10776e73ff763bf0ff55d7f78674 | 279 | require 'test_helper'
class NoteTest < ActiveSupport::TestCase
def test_for_person
assert_equal 4, Note.for_person(people(:mary)).size
assert_equal 4, Note.count_for_person(people(:mary))
assert_equal 2, Note.for_person(people(:mary), :limit => 2).size
end
end
| 25.363636 | 68 | 0.741935 |
e807be1dc4646d5d7fc6bbb7430fc5b7fdda0f4b | 2,101 | class Team < ApplicationRecord
has_many :players, dependent: :destroy
has_many :microposts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :events, dependent: :destroy
validates :name, presence: true, length: { maximum: 100 }, uniqueness: true
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# 渡された文字列のハッシュ値を返す
def Team.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# チームを検索する
def self.search(search)
if search
where(['name LIKE ?', "%#{search}%"])
else
Team.all
end
end
# ユーザーをフォローする
def follow(other_team, other_team_players)
following << other_team
Relationship.send_follow_email(other_team, self, other_team_players)
end
# ユーザーをフォロー解除する
def unfollow(other_team, other_team_players)
active_relationships.find_by(followed_id: other_team.id).destroy
Relationship.send_unfollow_email(other_team, self, other_team_players)
end
# 現在のユーザーがフォローしてたらtrueを返す
def following?(other_team)
following.include?(other_team)
end
def players_names
team = Team.find(params[:id])
@players = team.players
end
# フォローしたチームに所属しているプレイヤーの投稿を返す
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :team_id"
Micropost.including_replies_name(name)
.where("team_id IN (#{following_ids}) OR team_id = :team_id", team_id: id)
end
end | 33.887097 | 78 | 0.66397 |
ab4b06a33023c5b59e8791302aa61642db82b31b | 548 | Rails.application.routes.draw do
get "/", to: "application#homepage", as: "homepage"
get "/login", to: "sessions#login"
post "/login", to: "sessions#process_login"
get "/logout", to: "sessions#logout"
get "/about", to: "sessions#about", as: "about"
resources :states
resources :park_states
resources :parks
resources :trails do
resources :hikes, only: [:new, :create, :show, :destroy]
end
resources :users
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
| 28.842105 | 102 | 0.686131 |
bb282798ca43cc76fe3502fee11c4bec1d493ec4 | 372 | Puppet::Type.newtype(:rvm_alias) do
@doc = 'Manage RVM Aliases.'
ensurable
autorequire(:rvm_system_ruby) do
[self[:target_ruby]]
end
newparam(:name) do
desc 'The name of the alias to be managed.'
isnamevar
end
newparam(:target_ruby) do
desc "The ruby version that is the target of our alias.
For example: 'ruby-1.9.2-p290'"
end
end
| 18.6 | 59 | 0.674731 |
f868ac2685fa08167d08f38bc90127d46b1fb79f | 443 | # == Schema Information
#
# Table name: reviews
#
# id :integer not null, primary key
# idUsuario :integer
# idViaje :integer
# idAsiento :integer
# asunto :string(255)
# desc :text
# puntaje :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Review < ActiveRecord::Base
attr_accessible :asunto, :desc, :idAsiento, :idUsuario, :idViaje, :puntaje
end
| 23.315789 | 76 | 0.629797 |
ab5d545db15af011905bce70771b65f76adc797f | 2,602 | require File.expand_path(File.dirname(__FILE__) + '/neo')
class AboutSandwichCode < Neo::Koan
def count_lines(file_name)
file = open(file_name)
count = 0
while file.gets
count += 1
end
count
ensure
file.close if file
end
def test_counting_lines
assert_equal 4, count_lines("example_file.txt")
end
# ------------------------------------------------------------------
def find_line(file_name)
file = open(file_name)
while line = file.gets
return line if line.match(/e/)
end
ensure
file.close if file
end
def test_finding_lines
assert_equal"test\n", find_line("example_file.txt")
end
# ------------------------------------------------------------------
# THINK ABOUT IT:
#
# The count_lines and find_line are similar, and yet different.
# They both follow the pattern of "sandwich code".
#
# Sandwich code is code that comes in three parts: (1) the top slice
# of bread, (2) the meat, and (3) the bottom slice of bread. The
# bread part of the sandwich almost always goes together, but
# the meat part changes all the time.
#
# Because the changing part of the sandwich code is in the middle,
# abstracting the top and bottom bread slices to a library can be
# difficult in many languages.
#
# (Aside for C++ programmers: The idiom of capturing allocated
# pointers in a smart pointer constructor is an attempt to deal with
# the problem of sandwich code for resource allocation.)
#
# Consider the following code:
#
def file_sandwich(file_name)
file = open(file_name)
yield(file)
ensure
file.close if file
end
# Now we write:
def count_lines2(file_name)
file_sandwich(file_name) do |file|
count = 0
while file.gets
count += 1
end
count
end
end
def test_counting_lines2
assert_equal 4, count_lines2("example_file.txt")
end
# ------------------------------------------------------------------
def find_line2(file_name)
file_sandwich(file_name) do |file|
while line = file.gets
return line if line.match(/e/)
end
end
end
def test_finding_lines2
assert_equal "test\n", find_line2("example_file.txt")
end
# ------------------------------------------------------------------
def count_lines3(file_name)
open(file_name) do |file|
count = 0
while file.gets
count += 1
end
count
end
end
def test_open_handles_the_file_sandwich_when_given_a_block
assert_equal 4, count_lines3("example_file.txt")
end
end
| 23.441441 | 70 | 0.602229 |
7a4885edd32d2d011ba4e88918324f274e834e89 | 579 | class CreateAudioEvents < ActiveRecord::Migration
def change
create_table :audio_events do |t|
t.references :audio_recording, :null => false
t.decimal :start_time_seconds, :null => false, :scale => 6
t.decimal :end_time_seconds, :scale => 6
t.decimal :low_frequency_hertz, :null => false, :scale => 6
t.decimal :high_frequency_hertz, :scale => 6
t.boolean :is_reference, :null => false, :default => false
t.timestamps
t.userstamps include_deleted_by = true
end
add_index :audio_events, :audio_recording_id
end
end
| 34.058824 | 65 | 0.680484 |
08a4cbf8469429c125a9796e22a51b92b422809b | 64 | FactoryGirl.define do
factory :resident do
user
end
end | 10.666667 | 22 | 0.71875 |
33074c790c7d65bd78e8dee22bddd6ff5d433add | 241 | class Spree::Admin::PromeseSettingsController < Spree::Admin::ResourceController
def index
redirect_to edit_admin_promese_setting_path(model_class.instance.id)
end
def model_class
@model_class ||= ::PromeseSetting
end
end
| 20.083333 | 80 | 0.775934 |
1a76ccd8add327af3110c55ed2c5618c8c29ce68 | 754 | ENV["RAILS_ENV"] = "test"
require File.expand_path("../../../../config/environment")
require "spec"
require "spec/rails"
require "ruby-debug"
ActiveRecord::Base.configurations = {'test' => {:adapter => 'sqlite3', :database => ":memory:"}}
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["test"])
load('schema.rb')
Spec::Runner.configure do |config|
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = true
config.fixture_path = File.dirname(__FILE__) + '/fixtures/'
end
class Object
def self.unset_class(*args)
class_eval do
args.each do |klass|
eval(klass) rescue nil
remove_const(klass) if const_defined?(klass)
end
end
end
end
alias :doing :lambda | 25.133333 | 96 | 0.704244 |
79791e6db4f56d2b361cbe1f8ef6ec2cc5cabe3b | 6,921 | #!/usr/bin/env ruby
require_relative '../lib/typed_array'
# Base - base_class
# Dire - direct_class
# BD - base_class direct_class
# Limit - size
# Strict - index_strict
# ISL - size index_strict
class TypedBaseArray < TypedArray; end
class TypedDireArray < TypedArray; end
class TypedBDArray < TypedArray; end
class TypedMTArray < TypedArray; end
class TypedBaseLimitArray < TypedArray; end
class TypedDireLimitArray < TypedArray; end
class TypedBDLimitArray < TypedArray; end
class TypedBaseStrictArray < TypedArray; end
class TypedDireStrictArray < TypedArray; end
class TypedBDStrictArray < TypedArray; end
class TypedBaseILSArray < TypedArray; end
class TypedDireILSArray < TypedArray; end
class TypedBDILSArray < TypedArray; end
require 'minitest/autorun'
require 'minitest/spec'
EMPTY_OBJECT = Object.new
EMPTY_INTEGER = [1,2,3,4,5]
EMPTY_CHAR = ['a','b','c']
describe TypedArray do
before do
end
describe "simple typed array" do
it "have basic base class" do
TypedBaseArray.instance_exec do
build base_class: [Integer]
new.tap do |ta|
ta.must_be :empty?
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
rand(200..500).tap do |sz|
1.upto sz do |s| ta.push sz % s end
ta.size.must_be :==, sz
end
proc do
ta.push 'a'
end.must_raise TypeError
end
new(*EMPTY_INTEGER).tap do |ta|
ta.wont_be :empty?
ta.size.must_be :>, 0
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
end
proc do
new(*EMPTY_CHAR)
end.must_raise TypeError
end
end
it "have basic direct class" do
TypedDireArray.instance_exec do
build direct_class: [Fixnum]
new.tap do |ta|
ta.must_be :empty?
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
rand(200..500).tap do |sz|
1.upto sz do |s| ta.push sz % s end
ta.size.must_be :==, sz
end
proc do
ta.push 'a'
end.must_raise TypeError
end
new(*EMPTY_INTEGER).tap do |ta|
ta.wont_be :empty?
ta.size.must_be :>, 0
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
end
proc do new(*EMPTY_CHAR) end.must_raise TypeError
proc do new(2 << 80, 2 << 81) end.must_raise TypeError
end
end
it "have basic base-direct class" do
TypedBDArray.instance_exec do
build base_class: [Integer], direct_class: [Object]
new.tap do |ta|
ta.must_be :empty?
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
rand(200..500).tap do |sz|
1.upto sz do |s| ta.push sz % s end
ta.size.must_be :==, sz
end
proc do
ta.push 'a'
end.must_raise TypeError
end
new(*EMPTY_INTEGER).tap do |ta|
ta.wont_be :empty?
ta.size.must_be :>, 0
ta.must_be_kind_of TypedArray
ta.must_be_instance_of self
end
new(EMPTY_OBJECT).tap do |ta|
ta.wont_be :empty?
ta.must_be_kind_of TypedBDArray
ta.must_be_instance_of self
end
proc do new *EMPTY_CHAR end.must_raise TypeError
end
end
it "cannot have total untyped class" do
proc do
TypedMTArray.send :build
end.must_raise ArgumentError
end
end
describe "typed array with limits" do
it "have base class with upper limit" do
TypedBaseLimitArray.send :build, base_class: [Integer], size: 0..10
TypedBaseLimitArray.new.must_be :empty?
TypedBaseLimitArray.new(*(EMPTY_INTEGER)).must_be_kind_of TypedBaseLimitArray
proc do
TypedBaseLimitArray.new *(EMPTY_INTEGER * 3)
end.must_raise RangeError
end
it "have direct class with lower limit" do
TypedDireLimitArray.send :build, direct_class: [String], size: 2..Float::INFINITY
proc do
TypedDireLimitArray.new
end.must_raise RangeError
TypedDireLimitArray.new(*EMPTY_CHAR).must_be_kind_of TypedDireLimitArray
TypedDireLimitArray.new(*(EMPTY_CHAR * 1000)).must_be_kind_of TypedDireLimitArray
end
it "have base-direct class with bounded limit" do
TypedBDLimitArray.send :build, base_class: [Integer], direct_class: [Object], size: 3..5
proc do
TypedBDLimitArray.new
end.must_raise RangeError
TypedBDLimitArray.new(*EMPTY_INTEGER).must_be_kind_of TypedBDLimitArray
proc do
TypedBDLimitArray.new *([EMPTY_OBJECT]*5 + EMPTY_INTEGER)
end.must_raise RangeError
end
end
describe "typed array with indexed checks" do
it "have rotating base class checks" do
TypedBaseStrictArray.send :build, base_class: ([Integer] * 5 + [String] * 3), index_strict: true
TypedBaseStrictArray.new
proc do
TypedBaseStrictArray.new *EMPTY_CHAR
end.must_raise TypeError
TypedBaseStrictArray.new *(EMPTY_INTEGER + EMPTY_CHAR)
end
it "have rotating direct class checks" do
TypedDireStrictArray.send :build, direct_class: [Fixnum,String,Fixnum,Array], index_strict: true
TypedDireStrictArray.new
proc do
TypedDireStrictArray.new *EMPTY_INTEGER
end.must_raise TypeError
proc do
TypedDireStrictArray.new *EMPTY_CHAR
end.must_raise TypeError
proc do
TypedDireStrictArray.new EMPTY_OBJECT
end.must_raise TypeError
TypedDireStrictArray.new 1,'2',3,[4],5,'6',7,[8]
TypedDireStrictArray.new 1
proc do
TypedDireStrictArray.new (2<<80)
end.must_raise TypeError
end
it "have rotating base-direct class checks" do
TypedBDStrictArray.send :build, base_class: [Integer, String], direct_class: [Array, IO], index_strict: true
TypedBDStrictArray.new.must_be_kind_of TypedBDStrictArray
TypedBDStrictArray.new(1).must_be_kind_of TypedArray
proc do
TypedBDStrictArray.new '2'
end.must_raise TypeError
TypedBDStrictArray.new([3]).must_be_kind_of TypedBDStrictArray
proc do
TypedBDStrictArray.new $stdout
end.must_raise TypeError
TypedBDStrictArray.new(1, $stdout).must_be_kind_of TypedArray
TypedBDStrictArray.new([2], '3').must_be_kind_of TypedArray
end
end
describe "typed array with indexed checks and size bounded" do
it "have rotating base class with bounded size" do
TypedBaseILSArray.send :build, base_class: [Fixnum,Bignum,Float,Numeric], index_strict: true, size: 3..9
TypedBaseILSArray.new(1,2<<80,3.0).tap do |tbils|
tbils.must_be_kind_of TypedArray
tbils.must_be_kind_of TypedBaseILSArray
end
end
end
end
| 32.341121 | 114 | 0.655108 |
26bc9f3c1a32709c580abbf37a34bb0ab153ff02 | 1,014 | =begin
#Datadog API V1 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-SNAPSHOT
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for DatadogAPIClient::V1::CanceledDowntimesIds
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe DatadogAPIClient::V1::CanceledDowntimesIds do
let(:instance) { DatadogAPIClient::V1::CanceledDowntimesIds.new }
describe 'test an instance of CanceledDowntimesIds' do
it 'should create an instance of CanceledDowntimesIds' do
expect(instance).to be_instance_of(DatadogAPIClient::V1::CanceledDowntimesIds)
end
end
describe 'test attribute "cancelled_ids"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 28.971429 | 102 | 0.774162 |
267668a815e89c314b7248345c53b4b576b8e160 | 134 | class AddCirleToVolunteer < ActiveRecord::Migration
def change
add_column :volunteers, :circle_id, :integer, limit: 8
end
end
| 22.333333 | 58 | 0.761194 |
33c892f96c96b77a8e2a1fcd7d3097a5681d5dd5 | 735 | require "faraday"
require "faraday_middleware"
module Vismasign
class Client
BASE_URL = "https://vismasign.frakt.io/"
attr_reader :identifier, :api_key, :adapter
def initialize(identifier:, api_key:, adapter: Faraday.default_adapter)
@identifier = identifier
@api_key = api_key
@adapter = adapter
end
def document
DocumentResource.new(self)
end
def invitation
InvitationResource.new(self)
end
def connection
@connection ||= Faraday.new(BASE_URL) do |conn|
conn.request :json
conn.response :follow_redirects
conn.response :json, content_type: "application/json"
conn.adapter adapter
end
end
end
end
| 22.272727 | 75 | 0.653061 |
b97d41b358a392b48d4f83f8d275ce56e47a55bf | 1,512 | class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ''
t.string :encrypted_password, null: false, default: ''
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.string :current_sign_in_ip
# t.string :last_sign_in_ip
## Encryptable
# t.string :password_salt
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
# add_index :users, :authentication_token, unique: true
end
end
| 30.857143 | 91 | 0.648148 |
11594f4f25340ba5c4241199b31b0c7c0bfd0335 | 437 | require 'avalara'
module SpreeAvatax
class Config
class << self
[:username, :username=, :password, :password=, :endpoint, :endpoint=].each do |config|
delegate config, to: ::Avalara
end
attr_accessor :company_code
# the "use_production_account" config will replace the "endpoint" config soon
attr_accessor :use_production_account
end
self.use_production_account = false
end
end
| 21.85 | 92 | 0.686499 |
39a458b91cc9a99f09e889d58867a210335c7a86 | 350 | class AddMinLinesForConsensusToCollection < ActiveRecord::Migration[5.2]
def change
add_column :collections, :max_line_edits, :integer
add_column :collections, :min_lines_for_consensus, :integer
add_column :collections, :min_lines_for_consensus_no_edits, :integer
add_column :collections, :min_percent_consensus, :decimal
end
end
| 38.888889 | 72 | 0.8 |
acb86a7ffdb1edf9933bb6ea284886bbeab93eb6 | 2,024 | # NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
task :set_annotation_options do
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults('position_in_routes' => "after",
'position_in_class' => "before",
'position_in_test' => "after",
'position_in_fixture' => "after",
'position_in_factory' => "after",
'show_indexes' => "true",
'simple_indexes' => "false",
'model_dir' => "app/models",
'include_version' => "false",
'require' => "",
'exclude_tests' => "false",
'exclude_fixtures' => "true",
'exclude_factories' => "false",
'ignore_model_sub_dir' => "false",
'skip_on_db_migrate' => "false",
'format_bare' => "true",
'format_rdoc' => "false",
'format_markdown' => "false",
'sort' => "false",
'force' => "false",
'trace' => "false",)
end
Annotate.load_tasks
# Annotate models
task :annotate do
puts 'Annotating models...'
system 'bundle exec annotate'
end
# Run annotate task after db:migrate
# and db:rollback tasks
Rake::Task['db:migrate'].enhance do
Rake::Task['annotate'].invoke
end
Rake::Task['db:rollback'].enhance do
Rake::Task['annotate'].invoke
end
end
| 41.306122 | 79 | 0.460968 |
213b1b29abc6a2847aaa5c33b9beb08bb647f617 | 3,006 | module Plaid
module Client
module Logins
include Plaid::Client::Configurations
#connects to the plaid api.
#this can be used to retrieve information, get the access token, and initialize a user.
#sets the access token on the {Plaid::Client::Base}
#@return {PlaidResponse}
def connect
body = body_original
response = self.class.post('/connect', :query => body)
handle(response) do |r|
plaid = PlaidResponse.new(r, "Successful retrieved information from bank")
self.access_token = plaid.access_token
plaid
end
end
#The basic way to submit MFA information to Plaid.
#Simply appends the answer into the parameters for submission.
#@return {PlaidResponse} or {PlaidError}
def connect_step(mfa_response)
body = body_mfa(mfa_response)
response = self.class.post('/connect/step', :query => body)
handle(response) { PlaidResponse.new(response, "Successful MFA submission - retrieved information from bank") }
end
#Submits an MFA answer to Plaid.
#Adds a webhook return address as a parameter.
#@return {PlaidResponse} or {PlaidError}
def connect_step_webhook(mfa_response)
body = body_mfa_webhook(mfa_response)
response = self.class.post('/connect/step', :query => body)
handle(response) { PlaidResponse.new(response, "Successful MFA submission - Webhook will notify when retrieved information from bank") }
end
# Plaid's preferred way to initialize a user to their bank via the Plaid Proxy.
#
def connect_init_user
body = body_init_user
response = self.class.post('/connect', :query => body)
handle(response) { PlaidResponse.new(response, "Successfully added user; Wait on Webhook Response") }
end
def connect_filter_response
end
def connect_step_specify_mode(mode)
body = body_mfa_mode(mode)
response = self.class.post('/connect/step', :query => body)
handle(response) { PlaidResponse.new(response, "Successful MFA mode submission - You will now be asked to
input your code.") }
end
def connect_update_credentials
if self.access_token.present?
body = body_update_credentials
response = self.class.patch('/connect', :query => body)
handle(response) { PlaidResponse.new(response, "Successfully updated credentials")}
else
PlaidError.new(nil, "Need to initialize the client with an access token")
end
end
def connect_delete_user
if self.access_token.present?
body = body_delete_user
response = self.class.delete('/connect', :query => body)
handle(response) { PlaidResponse.new(response, "Deleted user")}
else
PlaidError.new(nil, "Need to initialize the client with an access token so user can be deleted")
end
end
end
end
end
| 34.159091 | 144 | 0.654691 |
ac570d6439db6bdcdba9b212cdce43a1012f5fcf | 102 | module ClinicsHelper
def clinic_params
params.require(:clinic).permit(:name, :addr)
end
end
| 12.75 | 48 | 0.72549 |
ff217f69d95170a541807ab3036ffd754d0f10e5 | 304 | class CreateTranslationPages < ActiveRecord::Migration[6.1]
def change
create_table :translation_pages do |t|
t.text :filename
t.references :translation, null: false, foreign_key: true
t.references :translation_chapter
t.integer :order
t.timestamps
end
end
end
| 23.384615 | 63 | 0.700658 |
d591291726de164f532ff037ebac70c7dc5f5447 | 2,098 | require "topological_inventory/providers/common/operations/topology_api_client"
require "topological_inventory/providers/common/operations/sources_api_client"
module TopologicalInventory
module Providers
module Common
module Operations
class EndpointClient
include TopologyApiClient
def initialize(source_id, task_id, identity = nil)
self.identity = identity
self.source_id = source_id
self.task_id = task_id
end
def order_service(service_offering, service_plan, order_params)
raise NotImplementedError, "#{__method__} must be implemented in a subclass"
end
def source_ref_of(endpoint_svc_instance)
raise NotImplementedError, "#{__method__} must be implemented in a subclass"
end
def wait_for_provision_complete(source_id, endpoint_svc_instance, context = {})
raise NotImplementedError, "#{__method__} must be implemented in a subclass"
end
def provisioned_successfully?(endpoint_svc_instance)
raise NotImplementedError, "#{__method__} must be implemented in a subclass"
end
# Endpoint for conversion of provisioned service's status to
# TopologicalInventory Task's status
def task_status_for(endpoint_svc_instance)
raise NotImplementedError, "#{__method__} must be implemented in a subclass"
end
private
attr_accessor :identity, :task_id, :source_id
def sources_api
@sources_api ||= SourcesApiClient.new(identity)
end
def default_endpoint
@default_endpoint ||= sources_api.fetch_default_endpoint(source_id)
end
def authentication
@authentication ||= sources_api.fetch_authentication(source_id, default_endpoint)
end
def verify_ssl_mode
default_endpoint.verify_ssl ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end
end
end
end
end
end
| 33.301587 | 95 | 0.659676 |
e82ebb488b069ace384a40dbda2eef52ee7540e6 | 250 | class DataCopySolutionProposalNewColumn < ActiveRecord::Migration[5.2]
def change
SolutionProposal.all.each do |solution_proposal|
solution_proposal.update!(
decision_was_made: solution_proposal.solution
)
end
end
end
| 25 | 70 | 0.744 |
6a9485855b4c16965d9b3ee215d06a505007ea8e | 224 | class Representation::ItemRepresenter
attr_reader :model_object
def initialize(model_object)
@model_object = model_object
end
def to_h
model_object.attributes
end
def to_json
to_h.to_json
end
end | 14.933333 | 37 | 0.75 |
1818008eee70992b9b67b071d28f8451d7309ac4 | 334 | module Queries
class Article < Queries::BaseQuery
type Types::ArticleType, null: false
argument :id, String, required: true
def resolve(**args)
_, data_id = SoulsApiSchema.from_global_id(args[:id])
::Article.find(data_id)
rescue StandardError => e
GraphQL::ExecutionError.new(e)
end
end
end
| 23.857143 | 59 | 0.676647 |
9116c25ed08ed6a3116389022d25fe009349388e | 3,839 | # Copyright © 2011 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# 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 HOLDER 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.
FactoryGirl.define do
factory :protocol do
next_ssr_id { Random.rand(10000) }
short_title { Faker::Lorem.word }
title { Faker::Lorem.sentence(3) }
sponsor_name { Faker::Lorem.sentence(3) }
brief_description { Faker::Lorem.paragraph(2) }
indirect_cost_rate { Random.rand(1000) }
study_phase { Faker::Lorem.word }
udak_project_number { Random.rand(1000).to_s }
funding_rfa { Faker::Lorem.word }
potential_funding_start_date { Time.now + 1.year }
funding_start_date { Time.now + 10.day }
federal_grant_serial_number { Random.rand(200000).to_s }
federal_grant_title { Faker::Lorem.sentence(2) }
federal_grant_code_id { Random.rand(1000).to_s }
federal_non_phs_sponsor { Faker::Lorem.word }
federal_phs_sponsor { Faker::Lorem.word }
requester_id 1
trait :funded do
funding_status "funded"
end
trait :pending do
funding_status "pending"
end
trait :federal do
funding_source "federal"
potential_funding_source "federal"
end
ignore do
project_role_count 1
pi nil
end
# TODO: get this to work!
# after(:build) do |protocol, evaluator|
# FactoryGirl.create_list(:project_role, evaluator.project_role_count,
# protocol: protocol, identity: evaluator.pi)
# end
after(:build) do |protocol|
protocol.build_ip_patents_info(FactoryGirl.attributes_for(:ip_patents_info)) if not protocol.ip_patents_info
protocol.build_human_subjects_info(FactoryGirl.attributes_for(:human_subjects_info)) if not protocol.human_subjects_info
protocol.build_investigational_products_info(FactoryGirl.attributes_for(:investigational_products_info)) if not protocol.investigational_products_info
protocol.build_research_types_info(FactoryGirl.attributes_for(:research_types_info)) if not protocol.research_types_info
protocol.build_vertebrate_animals_info(FactoryGirl.attributes_for(:vertebrate_animals_info)) if not protocol.vertebrate_animals_info
end
factory :study do
type { "Study" }
end
end
end
| 47.395062 | 156 | 0.719979 |
bf01aa7c84cdd4ad922f747c7b1a0914ad25740c | 18,918 | # -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
ONE_LOCATION = ENV['ONE_LOCATION']
if !ONE_LOCATION
SQLITE_PATH = '/var/lib/one/one.db'
else
SQLITE_PATH = ONE_LOCATION + '/var/one.db'
end
require 'onedb_backend'
# If set to true, extra verbose time log will be printed for each migrator
LOG_TIME = false
class OneDB
attr_accessor :backend
CONNECTION_PARAMETERS = %i[server port user password db_name]
def initialize(ops)
if ops[:backend].nil? && CONNECTION_PARAMETERS.all? {|s| ops[s].nil? }
ops = read_credentials(ops)
elsif ops[:backend].nil? && CONNECTION_PARAMETERS.any? {|s| !ops[s].nil? }
# Set MySQL backend as default if any connection option is provided and --type is not
ops[:backend] = :mysql
end
if ops[:backend] == :sqlite
ops[:sqlite] = SQLITE_PATH if ops[:sqlite].nil?
begin
require 'sqlite3'
rescue LoadError
STDERR.puts "Ruby gem sqlite3 is needed for this operation:"
STDERR.puts " $ sudo gem install sqlite3"
exit -1
end
@backend = BackEndSQLite.new(ops[:sqlite])
elsif ops[:backend] == :mysql
begin
require 'mysql2'
rescue LoadError
STDERR.puts "Ruby gem mysql2 is needed for this operation:"
STDERR.puts " $ sudo gem install mysql2"
exit -1
end
passwd = ops[:passwd]
passwd = ENV['ONE_DB_PASSWORD'] unless passwd
passwd = get_password unless passwd
@backend = BackEndMySQL.new(
:server => ops[:server],
:port => ops[:port],
:user => ops[:user],
:passwd => passwd,
:db_name => ops[:db_name],
:encoding=> ops[:encoding]
)
elsif ops[:backend] == :postgresql
begin
require 'pg'
rescue
STDERR.puts "Ruby gem pg is needed for this operation:"
STDERR.puts " $ sudo gem install pg"
exit -1
end
passwd = ops[:passwd]
passwd = ENV['ONE_DB_PASSWORD'] unless passwd
passwd = get_password("PostgreSQL Password: ") unless passwd
ops[:port] = 5432 if ops[:port] == 0
@backend = BackEndPostgreSQL.new(
:server => ops[:server],
:port => ops[:port],
:user => ops[:user],
:passwd => passwd,
:db_name => ops[:db_name],
:encoding=> ops[:encoding]
)
else
raise "You need to specify the SQLite, MySQL or PostgreSQL connection options."
end
end
def get_password(question="MySQL Password: ")
# Hide input characters
`stty -echo`
print question
passwd = STDIN.gets.strip
`stty echo`
puts ""
return passwd
end
def read_credentials(ops)
begin
# Suppress augeas require warning message
$VERBOSE = nil
gem 'augeas', '~> 0.6'
require 'augeas'
rescue Gem::LoadError
STDERR.puts(
'Augeas gem is not installed, run `gem install ' \
'augeas -v \'0.6\'` to install it'
)
exit(-1)
end
work_file_dir = File.dirname(ONED_CONF)
work_file_name = File.basename(ONED_CONF)
aug = Augeas.create(:no_modl_autoload => true,
:no_load => true,
:root => work_file_dir,
:loadpath => ONED_CONF)
aug.clear_transforms
aug.transform(:lens => 'Oned.lns', :incl => work_file_name)
aug.context = "/files/#{work_file_name}"
aug.load
ops[:backend] = aug.get('DB/BACKEND')
ops[:server] = aug.get('DB/SERVER')
ops[:port] = aug.get('DB/PORT')
ops[:user] = aug.get('DB/USER')
ops[:passwd] = aug.get('DB/PASSWD')
ops[:db_name] = aug.get('DB/DB_NAME')
ops.each do |k, v|
next unless v
ops[k] = v.chomp('"').reverse.chomp('"').reverse
end
ops.each {|_, v| v.gsub!("\\", '') if v }
ops[:backend] = ops[:backend].to_sym unless ops[:backend].nil?
ops[:port] = ops[:port].to_i
ops
rescue StandardError => e
STDERR.puts "Unable to parse oned.conf: #{e}"
exit(-1)
end
def backup(bck_file, ops, backend=@backend)
bck_file = backend.bck_file(ops[:federated]) if bck_file.nil?
if !ops[:force] && File.exists?(bck_file)
raise "File #{bck_file} exists, backup aborted. Use -f " <<
"to overwrite."
end
backend.backup(bck_file, ops[:federated])
return 0
end
def restore(bck_file, ops, backend=@backend)
if !File.exists?(bck_file)
raise "File #{bck_file} doesn't exist, backup restoration aborted."
end
one_not_running
backend.restore(bck_file, ops[:force], ops[:federated])
return 0
end
def version(ops)
ret = @backend.read_db_version
if(ops[:verbose])
puts "Shared tables version: #{ret[:version]}"
time = ret[:version] == "2.0" ? Time.now : Time.at(ret[:timestamp])
puts "Timestamp: #{time.strftime("%m/%d %H:%M:%S")}"
puts "Comment: #{ret[:comment]}"
if ret[:local_version]
puts
puts "Local tables version: #{ret[:local_version]}"
time = Time.at(ret[:local_timestamp])
puts "Timestamp: #{time.strftime("%m/%d %H:%M:%S")}"
puts "Comment: #{ret[:local_comment]}"
if ret[:is_slave]
puts
puts "This database is a federation slave"
end
end
else
puts "Shared: #{ret[:version]}"
puts "Local: #{ret[:local_version]}"
end
return 0
end
def history
@backend.history
return 0
end
# max_version is ignored for now, as this is the first onedb release.
# May be used in next releases
def upgrade(max_version, ops)
one_not_running()
db_version = @backend.read_db_version
if ops[:verbose]
pretty_print_db_version(db_version)
puts ""
end
ops[:backup] = @backend.bck_file if ops[:backup].nil?
backup(ops[:backup], ops)
begin
timea = Time.now
# Delete indexes
@backend.delete_idx db_version[:local_version]
# Upgrade shared (federation) tables, only for standalone and master
if !db_version[:is_slave]
puts
puts ">>> Running migrators for shared tables"
dir_prefix = "#{RUBY_LIB_LOCATION}/onedb/shared"
result = apply_migrators(dir_prefix, db_version[:version], ops)
# Modify db_versioning table
if result != nil
@backend.update_db_version(db_version[:version])
else
puts "Database already uses version #{db_version[:version]}"
end
end
db_version = @backend.read_db_version
# Upgrade local tables, for standalone, master, and slave
puts
puts ">>> Running migrators for local tables"
dir_prefix = "#{RUBY_LIB_LOCATION}/onedb/local"
result = apply_migrators(dir_prefix, db_version[:local_version], ops)
# Modify db_versioning table
if result != nil
@backend.update_local_db_version(db_version[:local_version])
else
puts "Database already uses version #{db_version[:local_version]}"
end
# Generate indexes
@backend.create_idx
timeb = Time.now
puts
puts "Total time: #{"%0.02f" % (timeb - timea).to_s}s" if ops[:verbose]
return 0
rescue Exception => e
puts
puts e.message
puts e.backtrace.join("\n")
puts
puts
puts "The database will be restored"
ops[:force] = true
restore(ops[:backup], ops)
return -1
end
end
def apply_migrators(prefix, db_version, ops)
result = nil
i = 0
matches = Dir.glob("#{prefix}/#{db_version}_to_*.rb")
while ( matches.size > 0 )
if ( matches.size > 1 )
raise "There are more than one file that match \
\"#{prefix}/#{db_version}_to_*.rb\""
end
file = matches[0]
puts " > Running migrator #{file}" if ops[:verbose]
time0 = Time.now
load(file)
@backend.extend Migrator
result = @backend.up
time1 = Time.now
if !result
raise "Error while upgrading from #{db_version} to " <<
" #{@backend.db_version}"
end
puts " > Done in #{"%0.02f" % (time1 - time0).to_s}s" if ops[:verbose]
puts "" if ops[:verbose]
matches = Dir.glob(
"#{prefix}/#{@backend.db_version}_to_*.rb")
end
return result
end
def fsck(ops)
ret = @backend.read_db_version
if ops[:verbose]
pretty_print_db_version(ret)
puts ""
end
file = "#{RUBY_LIB_LOCATION}/onedb/fsck.rb"
if File.exists? file
one_not_running()
load(file)
@backend.extend OneDBFsck
@backend.check_db_version()
ops[:backup] = @backend.bck_file if ops[:backup].nil?
# FSCK will be executed, make DB backup
backup(ops[:backup], ops)
begin
puts " > Running fsck" if ops[:verbose]
time0 = Time.now
result = @backend.fsck
if !result
raise "Error running fsck version #{ret[:version]}"
end
puts " > Done" if ops[:verbose]
puts "" if ops[:verbose]
time1 = Time.now
puts " > Total time: #{"%0.02f" % (time1 - time0).to_s}s" if ops[:verbose]
return 0
rescue Exception => e
puts
puts e.message
puts e.backtrace.join("\n")
puts
puts "Error running fsck version #{ret[:version]}"
puts "The database will be restored"
ops[:force] = true
restore(ops[:backup], ops)
return -1
end
else
raise "No fsck file found in #{RUBY_LIB_LOCATION}/onedb/fsck.rb"
end
end
def patch(file, ops)
ret = @backend.read_db_version
if ops[:verbose]
pretty_print_db_version(ret)
puts ""
end
if File.exists? file
load(file)
@backend.extend OneDBPatch
if ([email protected]_hot_patch(ops))
one_not_running()
end
@backend.check_db_version(ops)
ops[:backup] = @backend.bck_file if ops[:backup].nil?
if ([email protected]_hot_patch(ops))
backup(ops[:backup], ops)
end
begin
puts " > Running patch #{file}" if ops[:verbose]
time0 = Time.now
result = @backend.patch(ops)
if !result
raise "Error running patch #{file}"
end
puts " > Done" if ops[:verbose]
puts "" if ops[:verbose]
time1 = Time.now
puts " > Total time: #{"%0.02f" % (time1 - time0).to_s}s" if ops[:verbose]
return 0
rescue Exception => e
puts
puts e.message
puts e.backtrace.join("\n")
puts
puts "Error running patch #{file}"
if ([email protected]_hot_patch(ops))
puts "The database will be restored"
ops[:force] = true
restore(ops[:backup], ops)
end
return -1
end
else
raise "File was not found: #{file}"
end
end
def sqlite2mysql(options, sqlite)
one_not_running()
sqlite_v = sqlite.backend.read_db_version
mysql_v = @backend.read_db_version
match = true
match = false if sqlite_v[:version] != mysql_v[:version]
match = false if sqlite_v[:local_version] != mysql_v[:local_version]
if !match
err_msg = "SQLite version: #{sqlite_v[:version]}\n"
err_msg << "SQLite local version: #{sqlite_v[:local_version]}\n"
err_msg << "MySQL version: #{mysql_v[:version]}\n"
err_msg << "MySQL local version: #{mysql_v[:local_version]}\n"
err_msg << "The MySQL and SQLite versions do not match. Please run "
err_msg << "'onedb -i' in order to bootstrap a blank OpenNebula DB."
raise err_msg
end
backup(options[:backup], options)
file = "#{RUBY_LIB_LOCATION}/onedb/sqlite2mysql.rb"
load(file)
@backend.extend Sqlite2MySQL
@backend.convert(sqlite.backend.db)
return 0
end
def vcenter_one54(ops)
@backend.read_db_version
file = "#{RUBY_LIB_LOCATION}/onedb/vcenter_one54.rb"
if File.exists? file
load(file)
@backend.extend One54Vcenter
one_not_running()
ops[:backup] = @backend.bck_file if ops[:backup].nil?
# Migrator will be executed, make DB backup
backup(ops[:backup], ops)
begin
time0 = Time.now
puts " > Migrating templates" if ops[:verbose]
result = @backend.migrate_templates(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Migrating VMs" if ops[:verbose]
result = @backend.migrate_vms(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Migrating hosts" if ops[:verbose]
result = @backend.migrate_hosts(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Migrating datastores" if ops[:verbose]
result = @backend.migrate_datastores(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Migrating vnets" if ops[:verbose]
result = @backend.migrate_vnets(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Migrating images" if ops[:verbose]
result = @backend.migrate_images(ops[:verbose])
if !result
raise "The migrator script didn't succeed"
end
puts " > Done" if ops[:verbose]
puts "" if ops[:verbose]
time1 = Time.now
puts " > Total time: #{"%0.02f" % (time1 - time0).to_s}s" if ops[:verbose]
return 0
rescue Exception => e
puts
puts e.message
puts e.backtrace.join("\n")
puts
puts "Error running migrator to OpenNebula 5.4 for vcenter"
puts "The database will be restored"
ops[:force] = true
restore(ops[:backup], ops)
return -1
end
else
raise "No vcenter_one54 file found in #{RUBY_LIB_LOCATION}/onedb/vcenter_one54.rb"
end
end
# Create or recreate FTS index on vm_pool search_token column
#
# @param recreate [Boolean] True to delete the index and create it again
def fts_index(recreate = false)
if backend.is_a? BackEndSQLite
raise 'This is operation is not supported for sqlite backend'
end
backend.fts_index(recreate)
end
private
def one_not_running()
if File.exists?(LOCK_FILE)
raise "First stop OpenNebula. Lock file found: #{LOCK_FILE}"
end
client = OpenNebula::Client.new
rc = client.get_version
if !OpenNebula.is_error?(rc)
raise "OpenNebula found listening on '#{client.one_endpoint}'"
end
end
def pretty_print_db_version(db_version)
puts "Version read:"
puts "Shared tables #{db_version[:version]} : #{db_version[:comment]}"
if db_version[:local_version]
puts "Local tables #{db_version[:local_version]} : #{db_version[:local_comment]}"
end
if db_version[:is_slave]
puts
puts "This database is a federation slave"
end
end
end
| 29.28483 | 97 | 0.498731 |
ac0fcfc28b367617071fa01a8ce52285ede4e9db | 2,824 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/auxiliary/report'
class MetasploitModule < Msf::Post
include Msf::Post::Windows::Registry
include Msf::Auxiliary::Report
def initialize(info={})
super( update_info( info,
'Name' => 'Windows Gather Internet Download Manager (IDM) Password Extractor',
'Description' => %q{
This module recovers the saved premium download account passwords from
Internet Download Manager (IDM). These passwords are stored in an encoded
format in the registry. This module traverses through these registry entries
and decodes them. Thanks to the template code of theLightCosine's CoreFTP
password module.
},
'License' => MSF_LICENSE,
'Author' =>
[
'sil3ntdre4m <sil3ntdre4m[at]gmail.com>',
'Unknown', # SecurityXploded Team, www.SecurityXploded.com
],
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ]
))
end
def run
creds = Rex::Text::Table.new(
'Header' => 'Internet Downloader Manager Credentials',
'Indent' => 1,
'Columns' =>
[
'User',
'Password',
'Site'
]
)
registry_enumkeys('HKU').each do |k|
next unless k.include? "S-1-5-21"
next if k.include? "_Classes"
print_status("Looking at Key #{k}")
begin
subkeys = registry_enumkeys("HKU\\#{k}\\Software\\DownloadManager\\Passwords\\")
if subkeys.nil? or subkeys.empty?
print_status ("IDM not installed for this user.")
return
end
subkeys.each do |site|
user = registry_getvaldata("HKU\\#{k}\\Software\\DownloadManager\\Passwords\\#{site}", "User")
epass = registry_getvaldata("HKU\\#{k}\\Software\\DownloadManager\\Passwords\\#{site}", "EncPassword")
next if epass == nil or epass == ""
pass = xor(epass)
print_good("Site: #{site} (User=#{user}, Password=#{pass})")
creds << [user, pass, site]
end
print_status("Storing data...")
path = store_loot(
'idm.user.creds',
'text/csv',
session,
creds.to_csv,
'idm_user_creds.csv',
'Internet Download Manager User Credentials'
)
print_status("IDM user credentials saved in: #{path}")
rescue ::Exception => e
print_error("An error has occurred: #{e.to_s}")
end
end
end
def xor(ciphertext)
pass = ciphertext.unpack("C*")
key=15
for i in 0 .. pass.length-1 do
pass[i] ^= key
end
return pass.pack("C*")
end
end
| 29.113402 | 112 | 0.582861 |
21821a0637ff737508f13251b40cbed3a35301da | 946 | require 'test_helper'
class ShepherdMailerTest < ActionMailer::TestCase
test "account_activation" do
shepherd = shepherds(:michael)
shepherd.activation_token = Shepherd.new_token
mail = ShepherdMailer.account_activation(shepherd)
assert_equal "Account activation", mail.subject
assert_equal [shepherd.email], mail.to
assert_equal ["[email protected]"], mail.from
assert_match shepherd.name, mail.body.encoded
assert_match shepherd.activation_token, mail.body.encoded
assert_match CGI.escape(shepherd.email), mail.body.encoded
end
test "password_reset" do
shepherd = shepherds(:michael)
shepherd.reset_token = Shepherd.new_token
mail = ShepherdMailer.password_reset(shepherd)
assert_equal "Password reset", mail.subject
assert_equal [shepherd.email], mail.to
assert_match shepherd.reset_token, mail.body.encoded
assert_match CGI.escape(shepherd.email), mail.body.encoded
end
end
| 33.785714 | 62 | 0.773784 |
1c4f8988fcb305732a7c5892a028505398206b64 | 5,048 | # frozen_string_literal: true
# Copyright 2020 Matthew B. Gray
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ChargeDescription gives a description based on the state of the charge taking into account the time of the charge
# The goal is that you may build desciptions based on the history of charges against a reservation
# And to create a Charge#description with a hat tip to previous charge records
# And so that accountants get really nice text in reports
class ChargeDescription
include ActionView::Helpers::NumberHelper
include ApplicationHelper
attr_reader :charge
def initialize(charge)
@charge = charge
end
def for_users
[
maybe_charge_state,
formatted_amount,
upgrade_maybe,
instalment_or_paid,
"with",
payment_type,
"for",
membership_type,
].compact.join(" ")
end
def for_accounts
[
formatted_amount,
upgrade_maybe,
instalment_or_paid,
"for",
maybe_member_name,
"as",
membership_type,
].compact.join(" ")
end
def for_cart_transactions(for_account: false)
base_charge_description = {
"for_users" => [
maybe_charge_state,
formatted_amount,
"Fully Paid",
"with",
payment_type,
"for "
].compact.join(" "),
"for_accounts" => [
formatted_amount,
"Fully Paid",
"by",
maybe_chargee_email,
"for "
].compact.join(" ")
}
cart_charge_desc = for_account ? base_charge_description["for_accounts"] : base_charge_description["for_users"]
max_cart_description_length = ::ApplicationHelper::MYSQL_MAX_FIELD_LENGTH - cart_charge_desc.length
if max_cart_description_length > 0
cart_description = CartContentsDescription.new(
charged_cart,
max_characters: max_cart_description_length
).describe_cart_contents
full_cart_desc = cart_charge_desc.concat(cart_description)
else
full_cart_desc = cart_charge_desc.concat(" #{worldcon_public_name}")
end
if full_cart_desc.length > ::ApplicationHelper::MYSQL_MAX_FIELD_LENGTH
return full_cart_desc[0, ::ApplicationHelper::MYSQL_MAX_FIELD_LENGTH]
end
full_cart_desc
end
private
def maybe_charge_state
if !charge.successful?
charge.state.humanize
end
end
def payment_type
if charge.stripe?
"Credit Card"
else
charge.transfer.humanize
end
end
def instalment_or_paid
if !charge.successful?
"Payment"
elsif charges_so_far.sum(&:amount) + charge.amount < charged_membership.price
"Instalment"
else
"Fully Paid"
end
end
def maybe_member_name
raise TypeError, "expected a Reservation, got #{charge.buyable.class.name}" if !charge.buyable.kind_of?(Reservation)
rescue TypeError
return nil
else
claims = charge.buyable.claims
active_claim = claims.active_at(charge_active_at).first
active_claim.contact
end
def charged_cart
raise TypeError, "expected a Cart, got #{charge.buyable.class.name}" unless charge.buyable.kind_of?(Cart)
rescue TypeError
return nil
else
charge.buyable
end
def membership_type
raise TypeError, "expected a Reservation, got #{charge.buyable.class.name}" unless charge.buyable.kind_of?(Reservation)
rescue TypeError
return nil
else
"#{charged_membership} member #{charge.buyable.membership_number}"
end
def charged_membership
raise TypeError, "expected a Reservation, got #{charge.buyable.class.name}" unless charge.buyable.kind_of?(Reservation)
rescue TypeError
return nil
else
return @charged_membership if @charged_membership.present?
orders = charge.buyable.orders
@charged_membership = orders.active_at(charge_active_at).first.membership
end
def upgrade_maybe
if orders_so_far.count > 1
"Upgrade"
else
nil
end
end
def orders_so_far
charge.buyable.orders.where("created_at <= ?", charge_active_at)
end
def charges_so_far
successful = charge.buyable.charges.successful
successful.where.not(id: charge.id).where("created_at < ?", charge_active_at)
end
def formatted_amount
charge.amount.format(with_currency: true)
end
# This makes it pretty clear we'll be within the thresholds, avoids floating point errors
# that may rise from how Postgres stores dates
def charge_active_at
@charge_active_from ||= charge.created_at + 1.second
end
def maybe_chargee_email
charge.buyable.email
end
end
| 26.429319 | 123 | 0.71038 |
0353eed8e0d0044c29a9d8e8c0e2acd9c48180d6 | 249 | module AgaApiFactory
module Model
class Creative
attr_accessor :source_id,:title,:description1,:description2,:se_id,:se_status,:adgroup_se_id,:destination_url,:display_url,:status,:black_word,:trademark,:competing_word
end
end
end
| 31.125 | 175 | 0.783133 |
7998209b7b00e7a759eade60dfa2e42ed37e7990 | 3,719 | require 'spec_helper'
describe MembersHelper do
describe '#action_member_permission' do
let(:project_member) { build(:project_member) }
let(:group_member) { build(:group_member) }
it { expect(action_member_permission(:admin, project_member)).to eq :admin_project_member }
it { expect(action_member_permission(:admin, group_member)).to eq :admin_group_member }
end
describe '#remove_member_message' do
let(:requester) { build(:user) }
let(:project) { create(:project) }
let(:project_member) { build(:project_member, project: project) }
let(:project_member_invite) { build(:project_member, project: project).tap { |m| m.generate_invite_token! } }
let(:project_member_request) { project.request_access(requester) }
let(:group) { create(:group) }
let(:group_member) { build(:group_member, group: group) }
let(:group_member_invite) { build(:group_member, group: group).tap { |m| m.generate_invite_token! } }
let(:group_member_request) { group.request_access(requester) }
it { expect(remove_member_message(project_member)).to eq "Are you sure you want to remove #{project_member.user.name} from the #{project.name_with_namespace} project?" }
it { expect(remove_member_message(project_member_invite)).to eq "Are you sure you want to revoke the invitation for #{project_member_invite.invite_email} to join the #{project.name_with_namespace} project?" }
it { expect(remove_member_message(project_member_request)).to eq "Are you sure you want to deny #{requester.name}'s request to join the #{project.name_with_namespace} project?" }
it { expect(remove_member_message(project_member_request, user: requester)).to eq "Are you sure you want to withdraw your access request for the #{project.name_with_namespace} project?" }
it { expect(remove_member_message(group_member)).to eq "Are you sure you want to remove #{group_member.user.name} from the #{group.name} group?" }
it { expect(remove_member_message(group_member_invite)).to eq "Are you sure you want to revoke the invitation for #{group_member_invite.invite_email} to join the #{group.name} group?" }
it { expect(remove_member_message(group_member_request)).to eq "Are you sure you want to deny #{requester.name}'s request to join the #{group.name} group?" }
it { expect(remove_member_message(group_member_request, user: requester)).to eq "Are you sure you want to withdraw your access request for the #{group.name} group?" }
end
describe '#remove_member_title' do
let(:requester) { build(:user) }
let(:project) { create(:project) }
let(:project_member) { build(:project_member, project: project) }
let(:project_member_request) { project.request_access(requester) }
let(:group) { create(:group) }
let(:group_member) { build(:group_member, group: group) }
let(:group_member_request) { group.request_access(requester) }
it { expect(remove_member_title(project_member)).to eq 'Remove user from project' }
it { expect(remove_member_title(project_member_request)).to eq 'Deny access request from project' }
it { expect(remove_member_title(group_member)).to eq 'Remove user from group' }
it { expect(remove_member_title(group_member_request)).to eq 'Deny access request from group' }
end
describe '#leave_confirmation_message' do
let(:project) { build_stubbed(:project) }
let(:group) { build_stubbed(:group) }
let(:user) { build_stubbed(:user) }
it { expect(leave_confirmation_message(project)).to eq "Are you sure you want to leave the \"#{project.name_with_namespace}\" project?" }
it { expect(leave_confirmation_message(group)).to eq "Are you sure you want to leave the \"#{group.name}\" group?" }
end
end
| 65.245614 | 212 | 0.736488 |
5d53b4d6531287f4ed17a4b7227f8b831e0df6cd | 242 | module AccountsHelper
def calculate_balance(account)
if account.transactions != nil
account.balance -= account.credit_limit - account.transaction.amount
else
account.balance = account.credit_limit
end
end
end
| 20.166667 | 74 | 0.719008 |
1a5ef5e38be296f6e1a60f15d6262e3289251f39 | 634 | # frozen_string_literal: true
require 'spec_helper'
support :input_helpers,
:operation_shared_examples,
:quickbooks_online_helpers
RSpec.describe LedgerSync::Adaptors::QuickBooksOnline::Vendor::Operations::Update do
include InputHelpers
include QuickBooksOnlineHelpers
let(:resource) do
LedgerSync::Vendor.new(vendor_resource(ledger_id: '123'))
end
let(:adaptor) { quickbooks_online_adaptor }
it_behaves_like 'an operation'
it_behaves_like 'a successful operation',
stubs: %i[
stub_find_vendor
stub_update_vendor
]
end
| 25.36 | 84 | 0.684543 |
798e031b7f16d74566efecb03711ff27a6297567 | 274 | lib_dir = File.expand_path('../../lib', __FILE__)
$:.unshift lib_dir
require 'chef'
require 'chef/knife'
require 'chef/knife/reporter_base'
require 'chef/knife/reporter_helpers'
require 'chef/knife/reporter_nodes_cli_report'
require 'chef/knife/reporter_roles_cli_report'
| 24.909091 | 49 | 0.791971 |
ed5c8365968e8c692202ed8f27936321ea444131 | 433 | cask 'lightworks' do
version '14.5.0'
sha256 '8b7d5890f7c0f2ede05d4de16a7a09e5bfc5b322690e70cbd2e481e3638e738c'
url "https://downloads.lwks.com/v#{version.major_minor.dots_to_hyphens}-new/lightworks_v#{version}.dmg"
name 'Lightworks'
homepage 'https://www.lwks.com/'
depends_on macos: '>= :mountain_lion'
app 'Lightworks.app'
zap trash: '~/Library/Saved Application State/com.editshare.lightworks.savedState'
end
| 28.866667 | 105 | 0.766744 |
386307802a6fa8f187f7b204519087edd827e7c2 | 1,154 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170327100415) do
create_table "hickwalls", force: :cascade do |t|
t.string "last_squawk"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "wickwalls", force: :cascade do |t|
t.string "last_squawk"
t.string "last_tweet"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 39.793103 | 86 | 0.750433 |
5d3b791afc402ae9fe54431838a079636a765fec | 141 | require 'mxx_ru/cpp'
MxxRu::Cpp::exe_target {
required_prj 'so_5/prj.rb'
target 'sample.so_5.svc.exceptions'
cpp_source 'main.cpp'
}
| 11.75 | 36 | 0.716312 |
ff594d357d90b875bf0b1831242eda57fc728e08 | 77,478 | # encoding: utf-8
# vim:ts=4:sw=4:et:smartindent:nowrap
# Classes to manage various KML objects. See
# http://code.google.com/apis/kml/documentation/kmlreference.html for a
# description of KML
module Kamelopard
require 'singleton'
require 'kamelopard/pointlist'
require 'xml'
require 'yaml'
require 'erb'
require 'cgi'
@@sequence = 0
@@id_prefix = ''
@@logger = nil
LogLevels = {
:debug => 0,
:info => 1,
:notice => 2,
:warn => 3,
:error => 4,
:fatal => 5
}
@@log_level = LogLevels[:notice]
# Sets a logging callback function. This function should expect three
# arguments. The first will be a log level (:debug, :info, :notice, :warn,
# :error, or :fatal); the second will be a module, categorizing the log
# entries generally; and the third will be the message
def Kamelopard.set_logger(l)
@@logger = l
end
def Kamelopard.set_log_level(lev)
raise "Unknown log level #{lev}" unless LogLevels.has_key? lev
@@log_level = LogLevels[lev]
end
def Kamelopard.log(level, mod, msg)
raise "Unknown log level #{level} for error message #{msg}" unless LogLevels.has_key? level
@@logger.call(level, mod, msg) unless @@logger.nil? or @@log_level > LogLevels[level]
end
def Kamelopard.get_document
DocumentHolder.instance.current_document
end
def Kamelopard.get_next_id # :nodoc
@@sequence += 1
@@sequence
end
def Kamelopard.id_prefix=(a)
@@id_prefix = a
end
def Kamelopard.id_prefix
@@id_prefix
end
#--
# Intelligently adds elements to a KML object. Expects the KML object as the
# first argument, an array as the second. Each entry in the array is itself an
# array, containing first an Object, and second either a string or a Proc
# object. If the first Object is nil, nothing happens. If it's not nil, then:
# * if the second element is a string, add a new element to the KML. This
# string is the element name, and the stringified form of the first element
# is its text value
# * if the second element is a proc, call the proc, passing it the KML
# object, and let the Proc (presumably) add itself to the KML
#++
def Kamelopard.kml_array(e, m) # :nodoc
m.map do |a|
if ! a[0].nil? then
if a[1].kind_of? Proc then
a[1].call(e)
elsif a[0].kind_of? XML::Node then
d = XML::Node.new(a[1])
d << a[0]
e << d
else
t = XML::Node.new a[1]
t << a[0].to_s
e << t
end
end
end
end
#--
# Accepts XdX'X.X", XDXmX.XXs, XdXmX.XXs, or X.XXXX with either +/- or N/E/S/W
#++
def Kamelopard.convert_coord(a) # :nodoc
a = a.to_s.upcase.strip.gsub(/\s+/, '')
mult = 1
if a =~ /^-/ then
mult *= -1
end
a = a.sub /^\+|-/, ''
a = a.strip
if a =~ /[SW]$/ then
mult *= -1
end
a = a.sub /[NESW]$/, ''
a = a.strip
if a =~ /^\d+(\.\d+)?$/ then
# coord needs no transformation
1
elsif a =~ /^\d+D\d+M\d+(\.\d+)?S$/ then
# coord is in dms
p = a.split /[D"']/
a = p[0].to_f + (p[2].to_f / 60.0 + p[1].to_f) / 60.0
elsif a =~ /^\d+D\d+'\d+(\.\d+)?"$/ then
# coord is in d'"
p = a.split /[D"']/
a = p[0].to_f + (p[2].to_f / 60.0 + p[1].to_f) / 60.0
elsif m = (a =~ /^(\d+)°(\d+)'(\d+\.\d+)?"$/) then
# coord is in °'"
b = a
a = $1.to_f + ($3.to_f / 60.0 + $2.to_f) / 60.0
else
raise "Couldn't determine coordinate format for #{a}"
end
# check that it's within range
a = a.to_f * mult
raise "Coordinate #{a} out of range" if a > 180 or a < -180
return a
end
# Helper function for altitudeMode / gx:altitudeMode elements
def Kamelopard.add_altitudeMode(mode, e)
return if mode.nil?
if mode == :clampToGround or mode == :relativeToGround or mode == :absolute then
t = XML::Node.new 'altitudeMode'
else
t = XML::Node.new 'gx:altitudeMode'
end
t << mode.to_s
e << t
end
# Base class for all Kamelopard objects. Manages object ID and a single
# comment string associated with the object. Object IDs are stored in the
# kml_id attribute, and are prefixed with the value last passed to
# Kamelopard.id_prefix=, if anything. Note that assigning this prefix will
# *not* change the IDs of Kamelopard objects that are already
# initialized... just ones initialized thereafter.
class Object
attr_accessor :kml_id
attr_reader :comment
# The master_only attribute determines whether this Object should be
# included in slave mode KML files, or not. It defaults to false,
# indicating the Object should be included in KML files of all types.
# Set it to true to ensure it shows up only in slave mode.
attr_reader :master_only
# This constructor looks for values in the options hash that match
# class attributes, and sets those attributes to the values in the
# hash. So a class with an attribute called :when can be set via the
# constructor by including ":when => some-value" in the options
# argument to the constructor.
def initialize(options = {})
@kml_id = "#{Kamelopard.id_prefix}#{self.class.name.gsub('Kamelopard::', '')}_#{ Kamelopard.get_next_id }"
@master_only = false
options.each do |k, v|
method = "#{k}=".to_sym
if self.respond_to? method then
self.method(method).call(v)
else
raise "Warning: couldn't find attribute for options hash key #{k}"
end
end
end
# If this is a master-only object, this function gets called internally
# in place of the object's original to_kml method
def _alternate_to_kml(*a)
if @master_only and ! DocumentHolder.instance.current_document.master_mode
Kamelopard.log(:info, 'master/slave', "Because this object is master_only, and we're in slave mode, we're not including object #{self.inspect}")
return ''
end
# XXX There must be a better way to do this, but I don't know what
# it is. Running "@original_to_kml_method.call(a)" when the
# original method expects multiple arguments interprets the
# argument as an array, not as a list of arguments. This of course
# makes sense, but I don't know how to get around it.
case @original_to_kml_method.parameters.size
when 0
return @original_to_kml_method.call
when 1
# XXX This bothers me, and I'm unconvinced the calls to
# functions with more than one parameter actually work. Why
# should I have to pass a[0][0] here and just a[0], a[1], etc.
# for larger numbers of parameters, if this were all correct?
return @original_to_kml_method.call(a[0][0])
when 2
return @original_to_kml_method.call(a[0], a[1])
when 3
return @original_to_kml_method.call(a[0], a[1], a[2])
else
raise "Unsupported number of arguments (#{@original_to_kml_method.arity}) in to_kml function #{@original_to_kml_method}. This is a bug"
end
end
# Changes whether this object is available in master style documents
# only, or in slave documents as well.
#
# More specifically, this method replaces the object's to_kml method
# with something that checks whether this object should be included in
# the KML output, based on whether it's master-only or not, and whether
# the document is in master or slave mode.
def master_only=(a)
# If this object is a master_only object, and we're printing in
# slave mode, this object shouldn't be included at all (to_kml
# should return an empty string)
if a != @master_only
@master_only = a
if a then
@original_to_kml_method = public_method(:to_kml)
define_singleton_method :to_kml, lambda { |*a| self._alternate_to_kml(a) }
else
define_singleton_method :to_kml, @original_to_kml_method
end
end
end
# This just makes the Ruby-ism question mark suffix work
def master_only?
return @master_only
end
# Adds an XML comment to this node. Handles HTML escaping the comment
# if needed
def comment=(cmnt)
require 'cgi'
@comment = CGI.escapeHTML(cmnt)
end
# Returns XML::Node containing this object's KML. Objects should
# override this method
def to_kml(elem)
elem.attributes['id'] = @kml_id.to_s
if not @comment.nil? and @comment != '' then
c = XML::Node.new_comment " #{@comment} "
elem << c
return c
end
end
# Generates a <Change> element suitable for changing the given field of
# an object to the given value
def change(field, value)
c = XML::Node.new 'Change'
o = XML::Node.new self.class.name.sub!(/Kamelopard::/, '')
o.attributes['targetId'] = self.kml_id
e = XML::Node.new field
e.content = value.to_s
o << e
c << o
c
end
end
# Abstract base class for Point and several other classes
class Geometry < Object
end
# Represents a Point in KML.
class Point < Geometry
attr_reader :longitude, :latitude
attr_accessor :altitude, :altitudeMode, :extrude
def initialize(longitude = nil, latitude = nil, altitude = nil, options = {})
super options
@longitude = Kamelopard.convert_coord(longitude) unless longitude.nil?
@latitude = Kamelopard.convert_coord(latitude) unless latitude.nil?
@altitude = altitude unless altitude.nil?
end
def longitude=(long)
@longitude = Kamelopard.convert_coord(long)
end
def latitude=(lat)
@latitude = Kamelopard.convert_coord(lat)
end
def to_s
"Point (#{@longitude}, #{@latitude}, #{@altitude}, mode = #{@altitudeMode}, #{ @extrude ? 'extruded' : 'not extruded' })"
end
def to_kml(elem = nil, short = false)
e = XML::Node.new 'Point'
super(e)
e.attributes['id'] = @kml_id
c = XML::Node.new 'coordinates'
c << "#{ @longitude }, #{ @latitude }, #{ @altitude }"
e << c
if not short then
c = XML::Node.new 'extrude'
c << ( @extrude ? 1 : 0 ).to_s
e << c
Kamelopard.add_altitudeMode(@altitudeMode, e)
end
elem << e unless elem.nil?
e
end
end
# Helper class for KML objects which need to know about several points at once
module CoordinateList
attr_reader :coordinates
def coordinates=(a)
if a.nil? then
coordinates = []
else
add_element a
end
end
def coordinates_to_kml(elem = nil)
e = XML::Node.new 'coordinates'
t = ''
@coordinates.each do |a|
t << "#{ a[0] },#{ a[1] }"
t << ",#{ a[2] }" if a.size > 2
t << ' '
end
e << t.chomp(' ')
elem << e unless elem.nil?
e
end
# Alias for add_element
def <<(a)
add_element a
end
# Adds one or more elements to this CoordinateList. The argument can be in any of several formats:
# * An array of arrays of numeric objects, in the form [ longitude,
# latitude, altitude (optional) ]
# * A Point, or some other object that response to latitude, longitude, and altitude methods
# * An array of the above
# * Another CoordinateList, to append to this on
# Note that this will not accept a one-dimensional array of numbers to add
# a single point. Instead, create a Point with those numbers, and pass
# it to add_element
#--
# XXX The above stipulation is a weakness that needs fixing
#++
def add_element(a)
if a.kind_of? Enumerable then
# We've got some sort of array or list. It could be a list of
# floats, to become one coordinate, or it could be several
# coordinates
t = a.to_a.first
if t.kind_of? Enumerable then
# At this point we assume we've got an array of float-like
# objects. The second-level arrays need to have two or three
# entries -- long, lat, and (optionally) alt
a.each do |i|
if i.size < 2 then
raise "There aren't enough objects here to make a 2- or 3-element coordinate"
elsif i.size >= 3 then
@coordinates << [ i[0].to_f, i[1].to_f, i[2].to_f ]
else
@coordinates << [ i[0].to_f, i[1].to_f ]
end
end
elsif t.respond_to? 'longitude' and
t.respond_to? 'latitude' and
t.respond_to? 'altitude' then
# This object can cough up a set of coordinates
a.each do |i|
@coordinates << [i.longitude, i.latitude, i.altitude]
end
else
# I dunno what it is
raise "Kamelopard can't understand this object as a coordinate"
end
elsif a.kind_of? CoordinateList then
# Append this coordinate list
@coordinates << a.coordinates
else
# This is one element. It better know how to make latitude, longitude, etc.
if a.respond_to? 'longitude' and
a.respond_to? 'latitude' and
a.respond_to? 'altitude' then
@coordinates << [a.longitude, a.latitude, a.altitude]
else
raise "Kamelopard can't understand this object as a coordinate"
end
end
end
end
# Corresponds to the KML LineString object
class LineString < Geometry
include CoordinateList
attr_accessor :altitudeOffset, :extrude, :tessellate, :altitudeMode, :drawOrder, :longitude, :latitude, :altitude
def initialize(coordinates = [], options = {})
@coordinates = []
super options
self.coordinates=(coordinates) unless coordinates.nil?
end
def to_kml(elem = nil)
k = XML::Node.new 'LineString'
super(k)
Kamelopard.kml_array(k, [
[@altitudeOffset, 'gx:altitudeOffset'],
[@extrude, 'extrude'],
[@tessellate, 'tessellate'],
[@drawOrder, 'gx:drawOrder']
])
coordinates_to_kml(k) unless @coordinates.nil?
Kamelopard.add_altitudeMode @altitudeMode, k
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's LinearRing object
class LinearRing < Geometry
attr_accessor :altitudeOffset, :extrude, :tessellate, :altitudeMode
include CoordinateList
def initialize(coordinates = [], options = {})
@tessellate = 0
@extrude = 0
@altitudeMode = :clampToGround
@coordinates = []
super options
self.coordinates=(coordinates) unless coordinates.nil?
end
def to_kml(elem = nil)
k = XML::Node.new 'LinearRing'
super(k)
Kamelopard.kml_array(k, [
[ @altitudeOffset, 'gx:altitudeOffset' ],
[ @tessellate, 'tessellate' ],
[ @extrude, 'extrude' ]
])
Kamelopard.add_altitudeMode(@altitudeMode, k)
coordinates_to_kml(k) unless @coordinates.nil?
elem << k unless elem.nil?
k
end
end
# Abstract class corresponding to KML's AbstractView object
class AbstractView < Object
attr_accessor :timestamp, :timespan, :viewerOptions, :heading, :tilt, :roll, :range, :altitudeMode
attr_reader :className, :point
def initialize(className, point, options = {})
raise "className argument must not be nil" if className.nil?
@heading = 0
@tilt = 0
@roll = nil
@range = nil
@altitudeMode = :clampToGround
@viewerOptions = {}
super options
@className = className
self.point= point unless point.nil?
end
def point=(point)
if point.nil? then
@point = nil
else
if point.respond_to? :point then
a = point.point
else
a = point
end
@point = Point.new a.longitude, a.latitude, a.altitude, :altitudeMode => a.altitudeMode
end
end
def longitude
@point.nil? ? nil : @point.longitude
end
def latitude
@point.nil? ? nil : @point.latitude
end
def altitude
@point.nil? ? nil : @point.altitude
end
def longitude=(a)
if @point.nil? then
@point = Point.new(a, 0)
else
@point.longitude = a
end
end
def latitude=(a)
if @point.nil? then
@point = Point.new(0, a)
else
@point.latitude = a
end
end
def altitude=(a)
if @point.nil? then
@point = Point.new(0, 0, a)
else
@point.altitude = a
end
end
def to_kml(elem = nil)
t = XML::Node.new @className
super(t)
Kamelopard.kml_array(t, [
[ @point.nil? ? nil : @point.longitude, 'longitude' ],
[ @point.nil? ? nil : @point.latitude, 'latitude' ],
[ @point.nil? ? nil : @point.altitude, 'altitude' ],
[ @heading, 'heading' ],
[ @tilt, 'tilt' ],
[ @range, 'range' ],
[ @roll, 'roll' ]
])
Kamelopard.add_altitudeMode(@altitudeMode, t)
if @viewerOptions.keys.length > 0 then
vo = XML::Node.new 'gx:ViewerOptions'
@viewerOptions.each do |k, v|
o = XML::Node.new 'gx:option'
o.attributes['name'] = k.to_s
o.attributes['enabled'] = v ? 'true' : 'false'
vo << o
end
t << vo
end
if not @timestamp.nil? then
@timestamp.to_kml(t, 'gx')
elsif not @timespan.nil? then
@timespan.to_kml(t, 'gx')
end
elem << t unless elem.nil?
t
end
def [](a)
return @viewerOptions[a]
end
def []=(a, b)
if not b.kind_of? FalseClass and not b.kind_of? TrueClass then
raise 'Option value must be boolean'
end
if a != :streetview and a != :historicalimagery and a != :sunlight then
raise 'Option index must be :streetview, :historicalimagery, or :sunlight'
end
@viewerOptions[a] = b
end
end
# Corresponds to KML's Camera object
class Camera < AbstractView
def initialize(point = nil, options = {})
super('Camera', point, options)
end
def range
raise "The range element is part of LookAt objects, not Camera objects"
end
def range=
# The range element doesn't exist in Camera objects
end
end
# Corresponds to KML's LookAt object
class LookAt < AbstractView
def initialize(point = nil, options = {})
super('LookAt', point, options)
end
def roll
raise "The roll element is part of Camera objects, not LookAt objects"
end
def roll=
# The roll element doesn't exist in LookAt objects
end
end
# Abstract class corresponding to KML's TimePrimitive object
class TimePrimitive < Object
end
# Corresponds to KML's TimeStamp object. The @when attribute must be in a
# format KML understands. Refer to the KML documentation to see which
# formats are available.
class TimeStamp < TimePrimitive
attr_accessor :when
def initialize(ts_when = nil, options = {})
super options
@when = ts_when unless ts_when.nil?
end
def to_kml(elem = nil, ns = nil)
prefix = ''
prefix = ns + ':' unless ns.nil?
k = XML::Node.new "#{prefix}TimeStamp"
super(k)
w = XML::Node.new 'when'
w << @when
k << w
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's TimeSpan object. @begin and @end must be in a format KML
# understands.
class TimeSpan < TimePrimitive
# XXX Evidence suggests this doesn't support unbounded intervals. Fix that, if it's true.
attr_accessor :begin, :end
def initialize(ts_begin = nil, ts_end = nil, options = {})
super options
@begin = ts_begin unless ts_begin.nil?
@end = ts_end unless ts_end.nil?
end
def to_kml(elem = nil, ns = nil)
prefix = ''
prefix = ns + ':' unless ns.nil?
k = XML::Node.new "#{prefix}TimeSpan"
super(k)
if not @begin.nil? then
w = XML::Node.new 'begin'
w << @begin
k << w
end
if not @end.nil? then
w = XML::Node.new 'end'
w << @end
k << w
end
elem << k unless elem.nil?
k
end
end
# Support class for Feature object
module Snippet
attr_accessor :snippet_text, :maxLines
def snippet_to_kml(elem = nil)
e = XML::Node.new 'Snippet'
e.attributes['maxLines'] = @maxLines.to_s
e << @snippet_text
elem << e unless elem.nil?
e
end
end
# Corresponds to Data elements within ExtendedData
class Data
attr_accessor :name, :displayName, :value
def initialize(name, value, displayName = nil)
@name = name
@displayName = displayName
@value = value
end
def to_kml(elem = nil)
v = XML::Node.new 'Data'
v.attributes['name'] = @name
Kamelopard.kml_array(v, [
[@value, 'value'],
[@displayName, 'displayName']
])
elem << v unless elem.nil?
v
end
end
# Corresponds to KML's ExtendedData SchemaData objects
class SchemaData
attr_accessor :schemaUrl, :simpleData
def initialize(schemaUrl, simpleData = {})
@schemaUrl = schemaUrl
raise "SchemaData's simpleData attribute should behave like a hash" unless simpleData.respond_to? :keys
@simpleData = simpleData
end
def <<(a)
@simpleData.merge a
end
def to_kml(elem = nil)
s = XML::Node.new 'SchemaData'
s.attributes['schemaUrl'] = @schemaUrl
@simpleData.each do |k, v|
sd = XML::Node.new 'SimpleData', v
sd.attributes['name'] = k
s << sd
end
elem << v unless elem.nil?
v
end
end
# Abstract class corresponding to KML's Feature object.
#--
# XXX Make this support alternate namespaces
#++
class Feature < Object
attr_accessor :visibility, :open, :atom_author, :atom_link, :name,
:phoneNumber, :abstractView, :styles, :timeprimitive, :styleUrl,
:styleSelector, :region, :metadata
attr_reader :addressDetails, :snippet, :extendedData, :description
include Snippet
def initialize (name = nil, options = {})
@visibility = true
@open = false
@styles = []
super options
@name = name unless name.nil?
end
def description=(a)
b = CGI.escapeHTML(a)
if b != a then
@description = XML::Node.new_cdata a
else
@description = a
end
end
def extendedData=(a)
raise "extendedData attribute must respond to the 'each' method" unless a.respond_to? :each
@extendedData = a
end
def styles=(a)
if a.is_a? Array then
@styles = a
elsif @styles.nil? then
@styles = []
else
@styles = [a]
end
end
# Hides the object. Note that this governs only whether the object is
# initially visible or invisible; to show or hide the feature
# dynamically during a tour, use an AnimatedUpdate object
def hide
@visibility = false
end
# Shows the object. See note for hide() method
def show
@visibility = true
end
def timestamp
@timeprimitive
end
def timespan
@timeprimitive
end
def timestamp=(t)
@timeprimitive = t
end
def timespan=(t)
@timeprimitive = t
end
def addressDetails=(a)
if a.nil? or a == '' then
DocumentHolder.instance.current_document.uses_xal = false
else
DocumentHolder.instance.current_document.uses_xal = true
end
@addressDetails = a
end
# This function accepts either a StyleSelector object, or a string
# containing the desired StyleSelector's @kml_id
def styleUrl=(a)
if a.is_a? String then
@styleUrl = a
elsif a.respond_to? :kml_id then
@styleUrl = "##{ a.kml_id }"
else
@styleUrl = a.to_s
end
end
def self.add_author(o, a)
e = XML::Node.new 'atom:name'
e << a.to_s
f = XML::Node.new 'atom:author'
f << e
o << f
end
def to_kml(elem = nil)
elem = XML::Node.new 'Feature' if elem.nil?
super elem
Kamelopard.kml_array(elem, [
[@name, 'name'],
[(@visibility.nil? || @visibility) ? 1 : 0, 'visibility'],
[(! @open.nil? && @open) ? 1 : 0, 'open'],
[@atom_author, lambda { |o| Feature.add_author(o, @atom_author) }],
[@atom_link, 'atom:link'],
[@address, 'address'],
[@addressDetails, 'xal:AddressDetails'],
[@phoneNumber, 'phoneNumber'],
[@description, 'description'],
[@styleUrl, 'styleUrl'],
[@styleSelector, lambda { |o| @styleSelector.to_kml(o) }],
[@metadata, 'Metadata' ]
])
styles_to_kml(elem)
snippet_to_kml(elem) unless @snippet_text.nil?
extended_data_to_kml(elem) unless @extendedData.nil?
@abstractView.to_kml(elem) unless @abstractView.nil?
@timeprimitive.to_kml(elem) unless @timeprimitive.nil?
@region.to_kml(elem) unless @region.nil?
yield(elem) if block_given?
elem
end
def extended_data_to_kml(elem)
v = XML::Node.new 'ExtendedData'
@extendedData.each do |f|
v << f.to_kml
end
elem << v unless elem.nil?
v
end
def styles_to_kml(elem)
raise "done here" if elem.class == Array
@styles.each do |a|
a.to_kml(elem) unless a.attached?
end
end
end
# Abstract class corresponding to KML's Container object.
class Container < Feature
def initialize(name = nil, options = {})
@features = []
super
end
def features=(a)
if a.respond_to? :[] then
@features = a
else
@features = [a]
end
end
# Adds a new object to this container.
def <<(a)
@features << a
end
end
# Corresponds to KML's Folder object.
class Folder < Container
attr_accessor :styles, :folders, :parent_folder
def initialize(name = nil, options = {})
@styles = []
@folders = []
super
DocumentHolder.instance.current_document.folders << self
end
def styles=(a)
if a.respond_to? :[] then
@styles = a
else
@styles = [a]
end
end
def folders=(a)
if a.respond_to? :[] then
@folders = a
else
@folders = [a]
end
end
def to_kml(elem = nil)
h = XML::Node.new 'Folder'
super h
@features.each do |a|
a.to_kml(h)
end
@folders.each do |a|
a.to_kml(h)
end
elem << h unless elem.nil?
h
end
# Folders can have parent folders; returns true if this folder has one
def has_parent?
not @parent_folder.nil?
end
# Folders can have parent folders; sets this folder's parent
def parent_folder=(a)
@parent_folder = a
a.folders << self
end
end
def get_stack_trace # :nodoc
k = ''
caller.each do |a| k << "#{a}\n" end
k
end
# Represents KML's Document class.
class Document < Container
attr_accessor :flyto_mode, :folders, :tours, :uses_xal, :vsr_actions
# Is this KML destined for a master LG node, or a slave? True if this
# is a master node. This defaults to true, so tours that don't need
# this function, and tours for non-LG targets, work normally.
attr_accessor :master_mode
def initialize(options = {})
@tours = []
@folders = []
@vsr_actions = []
@master_mode = false
Kamelopard.log(:info, 'Document', "Adding myself to the document holder")
DocumentHolder.instance << self
super
end
# Returns viewsyncrelay actions as a hash
def get_actions
{
'actions' => @vsr_actions.collect { |a| a.to_hash }
}
end
def get_actions_yaml
get_actions.to_yaml
end
# Returns the current Tour object
def tour
Tour.new if @tours.length == 0
@tours.last
end
# Returns the current Folder object
def folder
if @folders.size == 0 then
Folder.new
end
@folders.last
end
# Makes a screenoverlay with a balloon containing links to the tours in this document
# The erb argument contains ERB to populate the description. It can be left nil
# The options hash is passed to the ScreenOverlay constructor
def make_tour_index(erb = nil, options = {})
options[:name] ||= 'Tour index'
options[:screenXY] ||= Kamelopard::XY.new(0.0, 1.0, :fraction, :fraction)
options[:overlayXY] ||= Kamelopard::XY.new(0.0, 1.0, :fraction, :fraction)
s = Kamelopard::ScreenOverlay.new options
t = ERB.new( erb || %{
<html>
<body>
<ul><% @tours.each do |t| %>
<li><a href="#<%= t.kml_id %>;flyto"><% if t.icon.nil? %><%= t.name %><% else %><img src="<%= t.icon %>" /><% end %></a></li>
<% end %></ul>
</body>
</html>
})
s.description = XML::Node.new_cdata t.result(binding)
s.balloonVisibility = 1
balloon_au = [0, 1].collect do |v|
au = Kamelopard::AnimatedUpdate.new [], :standalone => true
a = XML::Node.new 'Change'
b = XML::Node.new 'ScreenOverlay'
b.attributes['targetId'] = s.kml_id
c = XML::Node.new 'gx:balloonVisibility'
c << XML::Node.new_text(v.to_s)
b << c
a << b
au << a
au
end
# Handle hiding and displaying the index
@tours.each do |t|
q = Wait.new(0.1, :standalone => true)
t.playlist.unshift balloon_au[0]
t.playlist.unshift q
t.playlist << balloon_au[1]
t.playlist << q
end
s
end
def get_kml_document
k = XML::Document.new
# XXX fix this
#k << XML::XMLDecl.default
k.root = XML::Node.new('kml')
r = k.root
if @uses_xal then
r.attributes['xmlns:xal'] = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
end
# XXX Should this be add_namespace instead?
r.attributes['xmlns'] = 'http://www.opengis.net/kml/2.2'
r.attributes['xmlns:gx'] = 'http://www.google.com/kml/ext/2.2'
r.attributes['xmlns:kml'] = 'http://www.opengis.net/kml/2.2'
r.attributes['xmlns:atom'] = 'http://www.w3.org/2005/Atom'
r << self.to_kml
k
end
def to_kml
d = XML::Node.new 'Document'
super d
# Print styles first
#! These get printed out in the call to super, in Feature.to_kml()
#@styles.map do |a| d << a.to_kml unless a.attached? end
# then folders
@folders.map do |a|
a.to_kml(d) unless a.has_parent?
end
# then tours
@tours.map do |a| a.to_kml(d) end
d
end
end
# Holds a set of Document objects, so we can work with multiple KML files
# at once and keep track of them. It's important for Kamelopard's usability
# to have the concept of a "current" document, so we don't have to specify
# the document we're talking about each time we do something interesting.
# This class supports that idea.
class DocumentHolder
include Singleton
attr_accessor :document_index, :initialized
attr_reader :documents
def initialize(doc = nil)
Kamelopard.log :debug, 'DocumentHolder', "document holder constructor"
@documents = []
@document_index = -1
if ! doc.nil?
Kamelopard.log :info, 'DocumentHolder', "Constructor called with a doc. Adding it."
self.documents << doc
end
Kamelopard.log :debug, 'DocumentHolder', "document holder constructor finished"
end
def document_index
return @document_index
end
def document_index=(a)
@document_index = a
end
def current_document
# Automatically create a Document if we don't already have one
if @documents.size <= 0
Kamelopard.log :info, 'Document', "Doc doesn't exist... adding new one"
Document.new
@document_index = 0
end
return @documents[@document_index]
end
def <<(a)
raise "Cannot add a non-Document object to a DocumentHolder" unless a.kind_of? Document
@documents << a
@document_index += 1
end
def [](a)
return @documents[a]
end
def []=(i, v)
raise "Cannot include a non-Document object in a DocumentHolder" unless v.kind_of? Document
@documents[i] = v
end
def size
return @documents.size
end
end
# Corresponds to KML's ColorStyle object. Color is stored as an 8-character hex
# string, with two characters each of alpha, blue, green, and red values, in
# that order, matching the ordering the KML spec demands.
class ColorStyle < Object
attr_accessor :color
attr_reader :colorMode
def initialize(color = nil, options = {})
super options
@color = color unless color.nil?
end
def validate_colorMode(a)
raise "colorMode must be either \"normal\" or \"random\"" unless a == :normal or a == :random
end
def colorMode=(a)
validate_colorMode a
@colorMode = a
end
def alpha
@color[0,2]
end
def alpha=(a)
@color[0,2] = a
end
def blue
@color[2,2]
end
def blue=(a)
@color[2,2] = a
end
def green
@color[4,2]
end
def green=(a)
@color[4,2] = a
end
def red
@color[6,2]
end
def red=(a)
@color[6,2] = a
end
def to_kml(elem = nil)
k = elem.nil? ? XML::Node.new('ColorStyle') : elem
super k
e = XML::Node.new 'color'
e << @color
k << e
e = XML::Node.new 'colorMode'
e << @colorMode
k << e
k
end
end
# Corresponds to KML's BalloonStyle object. Color is stored as an 8-character hex
# string, with two characters each of alpha, blue, green, and red values, in
# that order, matching the ordering the KML spec demands.
class BalloonStyle < Object
attr_accessor :bgColor, :text, :textColor, :displayMode
# Note: color element order is aabbggrr
def initialize(text = nil, options = {})
#text = '', textColor = 'ff000000', bgColor = 'ffffffff', displayMode = :default)
@bgColor = 'ffffffff'
@textColor = 'ff000000'
@displayMode = :default
super options
@text = text unless text.nil?
end
def to_kml(elem = nil)
k = XML::Node.new 'BalloonStyle'
super k
Kamelopard.kml_array(k, [
[ @bgColor, 'bgColor' ],
[ @text, 'text' ],
[ @textColor, 'textColor' ],
[ @displayMode, 'displayMode' ]
])
elem << k unless elem.nil?
k
end
end
# Internal class used where KML requires X and Y values and units
class XY
attr_accessor :x, :y, :xunits, :yunits
def initialize(x = 0.5, y = 0.5, xunits = :fraction, yunits = :fraction)
@x = x
@y = y
@xunits = xunits
@yunits = yunits
end
def to_kml(name, elem = nil)
k = XML::Node.new name
k.attributes['x'] = @x.to_s
k.attributes['y'] = @y.to_s
k.attributes['xunits'] = @xunits.to_s
k.attributes['yunits'] = @yunits.to_s
elem << k unless elem.nil?
k
end
end
# Corresponds to the KML Icon object
module Icon
attr_accessor :href, :x, :y, :w, :h, :refreshMode, :refreshInterval, :viewRefreshMode, :viewRefreshTime, :viewBoundScale, :viewFormat, :httpQuery
def href=(h)
@icon_id = "#{Kamelopard.id_prefix}Icon_#{Kamelopard.get_next_id}" if @icon_id.nil?
@href = h
end
def icon_to_kml(elem = nil)
@icon_id = "#{Kamelopard.id_prefix}Icon_#{Kamelopard.get_next_id}" if @icon_id.nil?
k = XML::Node.new 'Icon'
k.attributes['id'] = @icon_id
Kamelopard.kml_array(k, [
[@href, 'href'],
[@x, 'gx:x'],
[@y, 'gx:y'],
[@w, 'gx:w'],
[@h, 'gx:h'],
[@refreshMode, 'refreshMode'],
[@refreshInterval, 'refreshInterval'],
[@viewRefreshMode, 'viewRefreshMode'],
[@viewRefreshTime, 'viewRefreshTime'],
[@viewBoundScale, 'viewBoundScale'],
[@viewFormat, 'viewFormat'],
[@httpQuery, 'httpQuery'],
])
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's IconStyle object.
class IconStyle < ColorStyle
attr_accessor :scale, :heading, :hotspot
include Icon
def initialize(href = nil, options = {})
@hotspot = XY.new(0.5, 0.5, :fraction, :fraction)
super nil, options
@href = href unless href.nil?
end
def hs_x=(a)
@hotspot.x = a
end
def hs_y=(a)
@hotspot.y = a
end
def hs_xunits=(a)
@hotspot.xunits = a
end
def hs_yunits=(a)
@hotspot.yunits = a
end
def to_kml(elem = nil)
k = XML::Node.new 'IconStyle'
super(k)
Kamelopard.kml_array( k, [
[ @scale, 'scale' ],
[ @heading, 'heading' ]
])
if not @hotspot.nil? then
h = XML::Node.new 'hotSpot'
h.attributes['x'] = @hotspot.x.to_s
h.attributes['y'] = @hotspot.y.to_s
h.attributes['xunits'] = @hotspot.xunits.to_s
h.attributes['yunits'] = @hotspot.yunits.to_s
k << h
end
icon_to_kml(k)
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's LabelStyle object
class LabelStyle < ColorStyle
attr_accessor :scale
def initialize(scale = 1, options = {})
@scale = scale
super nil, options
end
def to_kml(elem = nil)
k = XML::Node.new 'LabelStyle'
super k
s = XML::Node.new 'scale'
s << @scale.to_s
k << s
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's LineStyle object. Color is stored as an 8-character hex
# string, with two characters each of alpha, blue, green, and red values, in
# that order, matching the ordering the KML spec demands.
class LineStyle < ColorStyle
attr_accessor :outerColor, :outerWidth, :physicalWidth, :width, :labelVisibility
def initialize(options = {})
@outerColor = 'ffffffff'
@width = 1
@outerWidth = 0
@physicalWidth = 0
@labelVisibility = 0
super nil, options
end
def to_kml(elem = nil)
k = XML::Node.new 'LineStyle'
super k
Kamelopard.kml_array(k, [
[ @width, 'width' ],
[ @outerColor, 'gx:outerColor' ],
[ @outerWidth, 'gx:outerWidth' ],
[ @physicalWidth, 'gx:physicalWidth' ],
])
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's ListStyle object. Color is stored as an 8-character hex
# string, with two characters each of alpha, blue, green, and red values, in
# that order, matching the ordering the KML spec demands.
#--
# This doesn't descend from ColorStyle because I don't want the to_kml()
# call to super() adding color and colorMode elements to the KML -- Google
# Earth complains about 'em
#++
class ListStyle < Object
attr_accessor :listItemType, :bgColor, :state, :href
def initialize(options = {})
#bgcolor = nil, state = nil, href = nil, listitemtype = nil)
@state = :open
@bgColor = 'ffffffff'
super
end
def to_kml(elem = nil)
k = XML::Node.new 'ListStyle'
super k
Kamelopard.kml_array(k, [
[@listItemType, 'listItemType'],
[@bgColor, 'bgColor']
])
if (! @state.nil? or ! @href.nil?) then
i = XML::Node.new 'ItemIcon'
Kamelopard.kml_array(i, [
[ @state, 'state' ],
[ @href, 'href' ]
])
k << i
end
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's PolyStyle object. Color is stored as an 8-character hex
# string, with two characters each of alpha, blue, green, and red values, in
# that order, matching the ordering the KML spec demands.
class PolyStyle < ColorStyle
attr_accessor :fill, :outline
def initialize(options = {})
#fill = 1, outline = 1, color = 'ffffffff', colormode = :normal)
@fill = 1
@outline = 1
super nil, options
end
def to_kml(elem = nil)
k = XML::Node.new 'PolyStyle'
super k
Kamelopard.kml_array( k, [
[ @fill, 'fill' ],
[ @outline, 'outline' ]
])
elem << k unless elem.nil?
k
end
end
# Abstract class corresponding to KML's StyleSelector object.
class StyleSelector < Object
def initialize(options = {})
super
@attached = false
DocumentHolder.instance.current_document.styles << self
end
def attached?
@attached
end
def attach(obj)
@attached = true
obj.styles << self
end
def to_kml(elem = nil)
elem = XML::Node.new 'StyleSelector' if elem.nil?
super elem
elem
end
end
# Corresponds to KML's Style object. Attributes are expected to be IconStyle,
# LabelStyle, LineStyle, PolyStyle, BalloonStyle, and ListStyle objects.
class Style < StyleSelector
attr_accessor :icon, :label, :line, :poly, :balloon, :list
def to_kml(elem = nil)
k = XML::Node.new 'Style'
super k
@icon.to_kml(k) unless @icon.nil?
@label.to_kml(k) unless @label.nil?
@line.to_kml(k) unless @line.nil?
@poly.to_kml(k) unless @poly.nil?
@balloon.to_kml(k) unless @balloon.nil?
@list.to_kml(k) unless @list.nil?
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's StyleMap object.
class StyleMap < StyleSelector
# StyleMap manages pairs. The first entry in each pair is a string key, the
# second is either a Style or a styleUrl. It will be assumed to be the
# latter if its kind_of? method doesn't claim it's a Style object
def initialize(pairs = {}, options = {})
super options
@pairs = pairs
end
# Adds a new Style to the StyleMap.
def merge(a)
@pairs.merge!(a)
end
def to_kml(elem = nil)
t = XML::Node.new 'StyleMap'
super t
@pairs.each do |k, v|
p = XML::Node.new 'Pair'
key = XML::Node.new 'key'
key << k.to_s
p. << key
if v.kind_of? Style then
v.to_kml(p)
else
s = XML::Node.new 'styleUrl'
s << v.to_s
p << s
end
t << p
end
elem << t unless elem.nil?
t
end
end
# Corresponds to KML's Placemark objects. The geometry attribute requires a
# descendant of Geometry
class Placemark < Feature
attr_accessor :name, :geometry, :balloonVisibility
def initialize(name = nil, options = {})
super
@name = name unless name.nil?
end
def to_kml(elem = nil)
k = XML::Node.new 'Placemark'
super k
@geometry.to_kml(k) unless @geometry.nil?
if ! @balloonVisibility.nil? then
x = XML::Node.new 'gx:balloonVisibility'
x << ( @balloonVisibility ? 1 : 0 )
k << x
end
elem << k unless elem.nil?
k
end
def to_s
"Placemark id #{ @kml_id } named #{ @name }"
end
def longitude
@geometry.longitude
end
def latitude
@geometry.latitude
end
def altitude
@geometry.altitude
end
def altitudeMode
@geometry.altitudeMode
end
def point
if @geometry.kind_of? Point then
@geometry
elsif @geometry.respond_to? :point then
@geometry.point
else
raise "This placemark uses a non-point geometry, but the operation you're trying requires a point object"
end
end
end
# Abstract class corresponding to KML's gx:TourPrimitive object. Tours are made up
# of descendants of these.
# The :standalone option affects only initialization; there's no point in
# doing anything with it after initialization. It determines whether the
# TourPrimitive object is added to the current tour or not
class TourPrimitive < Object
attr_accessor :standalone
def initialize(options = {})
DocumentHolder.instance.current_document.tour << self unless options[:standalone]
super
end
end
# Cooresponds to KML's gx:FlyTo object. The @view parameter needs to look like an
# AbstractView object
class FlyTo < TourPrimitive
attr_accessor :duration, :mode, :view
def initialize(view = nil, options = {})
@duration = 0
@mode = :bounce
super options
self.view= view unless view.nil?
end
def view=(view)
if view.kind_of? AbstractView then
@view = view
elsif view.respond_to? :abstractView then
@view = view.abstractView
else
@view = LookAt.new view
end
end
def range=(range)
if view.respond_to? 'range' and not range.nil? then
@view.range = range
end
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:FlyTo'
super k
Kamelopard.kml_array(k, [
[ @duration, 'gx:duration' ],
[ @mode, 'gx:flyToMode' ]
])
@view.to_kml k unless @view.nil?
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's gx:AnimatedUpdate object. For now at least, this isn't very
# intelligent; you've got to manually craft the <Change> tag(s) within the
# object.
class AnimatedUpdate < TourPrimitive
# XXX For now, the user has to specify the change / create / delete elements in
# the <Update> manually, rather than creating objects.
attr_accessor :target, :delayedStart, :duration
attr_reader :updates
# The updates argument is an array of strings containing <Change> elements
def initialize(updates, options = {})
#duration = 0, target = '', delayedstart = nil)
@updates = []
super options
@updates = updates unless updates.nil? or updates.size == 0
end
def target=(target)
if target.kind_of? Object then
@target = target.kml_id
else
@target = target
end
end
def updates=(a)
updates.each do |u| self.<<(u) end
end
# Adds another update string, presumably containing a <Change> element
def <<(a)
@updates << a
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:AnimatedUpdate'
super(k)
d = XML::Node.new 'gx:duration'
d << @duration.to_s
k << d
if not @delayedStart.nil? then
d = XML::Node.new 'gx:delayedStart'
d << @delayedStart.to_s
k << d
end
d = XML::Node.new 'Update'
q = XML::Node.new 'targetHref'
q << @target.to_s
d << q
@updates.each do |i|
if i.is_a? XML::Node then
d << i
else
parser = reader = XML::Parser.string(i)
doc = parser.parse
node = doc.child
n = node.copy true
d << n
end
end
k << d
elem << k unless elem.nil?
k
end
end
# Corresponds to a KML gx:TourControl object
class TourControl < TourPrimitive
def to_kml(elem = nil)
k = XML::Node.new 'gx:TourControl'
super(k)
q = XML::Node.new 'gx:playMode'
q << 'pause'
k << q
elem << k unless elem.nil?
k
end
end
# Corresponds to a KML gx:Wait object
class Wait < TourPrimitive
attr_accessor :duration
def initialize(duration = 0, options = {})
super options
@duration = duration
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:Wait'
super k
d = XML::Node.new 'gx:duration'
d << @duration.to_s
k << d
elem << k unless elem.nil?
k
end
end
# Corresponds to a KML gx:SoundCue object
class SoundCue < TourPrimitive
attr_accessor :href, :delayedStart
def initialize(href, delayedStart = nil)
super()
@href = href
@delayedStart = delayedStart
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:SoundCue'
super k
d = XML::Node.new 'href'
d << @href.to_s
k << d
if not @delayedStart.nil? then
d = XML::Node.new 'gx:delayedStart'
d << @delayedStart.to_s
k << d
end
elem << k unless elem.nil?
k
end
end
# Corresponds to a KML gx:Tour object
class Tour < Object
attr_accessor :name, :description, :last_abs_view, :playlist, :icon
def initialize(name = nil, description = nil, no_wait = false)
super()
@name = name
@description = description
@playlist = []
DocumentHolder.instance.current_document.tours << self
Wait.new(0.1, :comment => "This wait is automatic, and helps prevent animation glitches") unless no_wait
end
# Add another element to this Tour
def <<(a)
@playlist << a
@last_abs_view = a.view if a.kind_of? FlyTo
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:Tour'
super k
Kamelopard.kml_array(k, [
[ @name, 'name' ],
[ @description, 'description' ],
])
p = XML::Node.new 'gx:Playlist'
@playlist.map do |a| a.to_kml p end
k << p
elem << k unless elem.nil?
k
end
end
# Abstract class corresponding to the KML Overlay object
class Overlay < Feature
attr_accessor :color, :drawOrder
include Icon
def initialize(options = {})
super nil, options
DocumentHolder.instance.current_document.folder << self
end
def to_kml(elem)
super
Kamelopard.kml_array(elem, [
[ @color, 'color' ],
[ @drawOrder, 'drawOrder' ],
])
icon_to_kml(elem)
elem
end
end
# Corresponds to KML's ScreenOverlay object
class ScreenOverlay < Overlay
attr_accessor :overlayXY, :screenXY, :rotationXY, :size, :rotation, :balloonVisibility
def to_kml(elem = nil)
k = XML::Node.new 'ScreenOverlay'
super k
@overlayXY.to_kml('overlayXY', k) unless @overlayXY.nil?
@screenXY.to_kml('screenXY', k) unless @screenXY.nil?
@rotationXY.to_kml('rotationXY', k) unless @rotationXY.nil?
@size.to_kml('size', k) unless @size.nil?
if ! @rotation.nil? then
d = XML::Node.new 'rotation'
d << @rotation.to_s
k << d
end
if ! @balloonVisibility.nil? then
x = XML::Node.new 'gx:balloonVisibility'
x << ( @balloonVisibility ? 1 : 0 )
k << x
end
elem << k unless elem.nil?
k
end
end
# Supporting module for the PhotoOverlay class
module ViewVolume
attr_accessor :leftFov, :rightFov, :bottomFov, :topFov, :near
def viewVolume_to_kml(elem = nil)
p = XML::Node.new 'ViewVolume'
{
:near => @near,
:leftFov => @leftFov,
:rightFov => @rightFov,
:topFov => @topFov,
:bottomFov => @bottomFov
}.each do |k, v|
d = XML::Node.new k.to_s
v = 0 if v.nil?
d << v.to_s
p << d
end
elem << p unless elem.nil?
p
end
end
# Supporting module for the PhotoOverlay class
module ImagePyramid
attr_accessor :tileSize, :maxWidth, :maxHeight, :gridOrigin
def imagePyramid_to_kml(elem = nil)
@tileSize = 256 if @tileSize.nil?
p = XML::Node.new 'ImagePyramid'
{
:tileSize => @tileSize,
:maxWidth => @maxWidth,
:maxHeight => @maxHeight,
:gridOrigin => @gridOrigin
}.each do |k, v|
d = XML::Node.new k.to_s
v = 0 if v.nil?
d << v.to_s
p << d
end
elem << p unless elem.nil?
p
end
end
# Corresponds to KML's PhotoOverlay class
class PhotoOverlay < Overlay
attr_accessor :rotation, :point, :shape
include ViewVolume
include ImagePyramid
def initialize(options = {})
super
end
def point=(point)
if point.respond_to?('point')
@point = point.point
else
@point = point
end
end
def to_kml(elem = nil)
p = XML::Node.new 'PhotoOverlay'
super p
viewVolume_to_kml p
imagePyramid_to_kml p
p << @point.to_kml(nil, true)
{
:rotation => @rotation,
:shape => @shape
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
p << d
end
elem << p unless elem.nil?
p
end
end
# Corresponds to KML's LatLonBox and LatLonAltBox
class LatLonBox
attr_reader :north, :south, :east, :west
attr_accessor :rotation, :minAltitude, :maxAltitude, :altitudeMode
def initialize(north, south, east, west, rotation = 0, minAltitude = nil, maxAltitude = nil, altitudeMode = :clampToGround)
@north = Kamelopard.convert_coord north
@south = Kamelopard.convert_coord south
@east = Kamelopard.convert_coord east
@west = Kamelopard.convert_coord west
@minAltitude = minAltitude
@maxAltitude = maxAltitude
@altitudeMode = altitudeMode
@rotation = rotation
end
def north=(a)
@north = Kamelopard.convert_coord a
end
def south=(a)
@south = Kamelopard.convert_coord a
end
def east=(a)
@east = Kamelopard.convert_coord a
end
def west=(a)
@west = Kamelopard.convert_coord a
end
def to_kml(elem = nil, alt = false)
name = alt ? 'LatLonAltBox' : 'LatLonBox'
k = XML::Node.new name
[
['north', @north],
['south', @south],
['east', @east],
['west', @west],
['minAltitude', @minAltitude],
['maxAltitude', @maxAltitude]
].each do |a|
if not a[1].nil? then
m = XML::Node.new a[0]
m << a[1].to_s
k << m
end
end
if (not @minAltitude.nil? or not @maxAltitude.nil?) then
Kamelopard.add_altitudeMode(@altitudeMode, k)
end
m = XML::Node.new 'rotation'
m << @rotation.to_s
k << m
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's gx:LatLonQuad object
class LatLonQuad
attr_accessor :lowerLeft, :lowerRight, :upperRight, :upperLeft
def initialize(lowerLeft, lowerRight, upperRight, upperLeft)
@lowerLeft = lowerLeft
@lowerRight = lowerRight
@upperRight = upperRight
@upperLeft = upperLeft
end
def to_kml(elem = nil)
k = XML::Node.new 'gx:LatLonQuad'
d = XML::Node.new 'coordinates'
d << "#{ @lowerLeft.longitude },#{ @lowerLeft.latitude } #{ @lowerRight.longitude },#{ @lowerRight.latitude } #{ @upperRight.longitude },#{ @upperRight.latitude } #{ @upperLeft.longitude },#{ @upperLeft.latitude }"
k << d
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's GroundOverlay object
class GroundOverlay < Overlay
attr_accessor :altitude, :altitudeMode, :latlonbox, :latlonquad
def initialize(icon, options = {})
@altitude = 0
@altitudeMode = :clampToGround
@href = icon
super options
end
def to_kml(elem = nil)
raise "Either latlonbox or latlonquad must be non-nil" if @latlonbox.nil? and @latlonquad.nil?
k = XML::Node.new 'GroundOverlay'
super k
d = XML::Node.new 'altitude'
d << @altitude.to_s
k << d
Kamelopard.add_altitudeMode(@altitudeMode, k)
@latlonbox.to_kml(k) unless @latlonbox.nil?
@latlonquad.to_kml(k) unless @latlonquad.nil?
elem << k unless elem.nil?
k
end
end
# Corresponds to the LOD (Level of Detail) object
class Lod
attr_accessor :minpixels, :maxpixels, :minfade, :maxfade
def initialize(minpixels, maxpixels, minfade, maxfade)
@minpixels = minpixels
@maxpixels = maxpixels
@minfade = minfade
@maxfade = maxfade
end
def to_kml(elem = nil)
k = XML::Node.new 'Lod'
m = XML::Node.new 'minLodPixels'
m << @minpixels.to_s
k << m
m = XML::Node.new 'maxLodPixels'
m << @maxpixels.to_s
k << m
m = XML::Node.new 'minFadeExtent'
m << @minfade.to_s
k << m
m = XML::Node.new 'maxFadeExtent'
m << @maxfade.to_s
k << m
elem << k unless elem.nil?
k
end
end
# Corresponds to the KML Region object
class Region < Object
attr_accessor :latlonaltbox, :lod
def initialize(options = {})
super
end
def to_kml(elem = nil)
k = XML::Node.new 'Region'
super k
@latlonaltbox.to_kml(k, true) unless @latlonaltbox.nil?
@lod.to_kml(k) unless @lod.nil?
elem << k unless elem.nil?
k
end
end
# Sub-object in the KML Model class
class Orientation
attr_accessor :heading, :tilt, :roll
def initialize(heading, tilt, roll)
@heading = heading
# Although the KML reference by Google is clear on these ranges, Google Earth
# supports values outside the ranges, and sometimes it's useful to use
# them. So I'm turning off this error checking
#raise "Heading should be between 0 and 360 inclusive; you gave #{ heading }" unless @heading <= 360 and @heading >= 0
@tilt = tilt
#raise "Tilt should be between 0 and 180 inclusive; you gave #{ tilt }" unless @tilt <= 180 and @tilt >= 0
@roll = roll
#raise "Roll should be between 0 and 180 inclusive; you gave #{ roll }" unless @roll <= 180 and @roll >= 0
end
def to_kml(elem = nil)
x = XML::Node.new 'Orientation'
{
:heading => @heading,
:tilt => @tilt,
:roll => @roll
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
x << d
end
elem << x unless elem.nil?
x
end
end
# Sub-object in the KML Model class
class Scale
attr_accessor :x, :y, :z
def initialize(x, y, z = 1)
@x = x
@y = y
@z = z
end
def to_kml(elem = nil)
x = XML::Node.new 'Scale'
{
:x => @x,
:y => @y,
:z => @z
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
x << d
end
elem << x unless elem.nil?
x
end
end
# Sub-object in the KML ResourceMap class
class Alias
attr_accessor :targetHref, :sourceHref
def initialize(targetHref = nil, sourceHref = nil)
@targetHref = targetHref
@sourceHref = sourceHref
end
def to_kml(elem = nil)
x = XML::Node.new 'Alias'
{
:targetHref => @targetHref,
:sourceHref => @sourceHref,
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
x << d
end
elem << x unless elem.nil?
x
end
end
# Sub-object in the KML Model class
class ResourceMap
attr_accessor :aliases
def initialize(aliases = [])
@aliases = []
if not aliases.nil? then
if aliases.kind_of? Enumerable then
@aliases += aliases
else
@aliases << aliases
end
end
end
def to_kml(elem = nil)
k = XML::Node.new 'ResourceMap'
@aliases.each do |a| k << a.to_kml(k) end
elem << k unless elem.nil?
k
end
end
# Corresponds to KML's Link object
class Link < Object
attr_accessor :href, :refreshMode, :refreshInterval, :viewRefreshMode, :viewBoundScale, :viewFormat, :httpQuery
def initialize(href = '', options = {})
super options
@href = href unless href == ''
end
def to_kml(elem = nil)
x = XML::Node.new 'Link'
super x
{
:href => @href,
:refreshMode => @refreshMode,
:viewRefreshMode => @viewRefreshMode,
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
x << d
end
Kamelopard.kml_array(x, [
[ @refreshInterval, 'refreshInterval' ],
[ @viewBoundScale, 'viewBoundScale' ],
[ @viewFormat, 'viewFormat' ],
[ @httpQuery, 'httpQuery' ]
])
elem << x unless elem.nil?
x
end
end
# Corresponds to the KML Model class
class Model < Geometry
attr_accessor :link, :location, :orientation, :scale, :resourceMap
# location should be a Point, or some object that can behave like one,
# including a Placemark. Model will get its Location and altitudeMode data
# from this attribute
def initialize(options = {})
#link, location, orientation, scale, resourceMap)
super
end
def to_kml(elem = nil)
x = XML::Node.new 'Model'
super x
loc = XML::Node.new 'Location'
{
:longitude => @location.longitude,
:latitude => @location.latitude,
:altitude => @location.altitude,
}.each do |k, v|
d = XML::Node.new k.to_s
d << v.to_s
loc << d
end
x << loc
Kamelopard.add_altitudeMode(@location.altitudeMode, x)
@link.to_kml x unless @link.nil?
@orientation.to_kml x unless @orientation.nil?
@scale.to_kml x unless @scale.nil?
@resourceMap.to_kml x unless @resourceMap.nil?
elem << x unless elem.nil?
x
end
end
# Corresponds to the KML Polygon class
class Polygon < Geometry
# NB! No support for tessellate, because Google Earth doesn't support it, it seems
attr_accessor :outer, :inner, :altitudeMode, :extrude
def initialize(outer, options = {})
#extrude = 0, altitudeMode = :clampToGround)
@extrude = 0
@altitudeMode = :clampToGround
@inner = []
@outer = outer
super options
end
def inner=(a)
if a.kind_of? Array then
@inner = a
else
@inner = [ a ]
end
end
def <<(a)
@inner << a
end
def to_kml(elem = nil)
k = XML::Node.new 'Polygon'
super k
e = XML::Node.new 'extrude'
e << @extrude.to_s
k << e
Kamelopard.add_altitudeMode @altitudeMode, k
e = XML::Node.new('outerBoundaryIs')
e << @outer.to_kml
k << e
@inner.each do |i|
e = XML::Node.new('innerBoundaryIs')
e << i.to_kml
k << e
end
elem << k unless elem.nil?
k
end
end
# Abstract class corresponding to KML's MultiGeometry object
class MultiGeometry < Geometry
attr_accessor :geometries
def initialize(a = nil, options = {})
@geometries = []
@geometries << a unless a.nil?
super options
end
def <<(a)
@geometries << a
end
def to_kml(elem = nil)
e = XML::Node.new 'MultiGeometry'
@geometries.each do |g|
g.to_kml e
end
elem << e unless elem.nil?
e
end
end
# Analogue of KML's NetworkLink class
class NetworkLink < Feature
attr_accessor :refreshVisibility, :flyToView, :link
def initialize(href = '', options = {})
super(( options[:name] || ''), options)
@refreshMode ||= :onChange
@viewRefreshMode ||= :never
@link = Link.new(href, :refreshMode => @refreshMode, :viewRefreshMode => @viewRefreshMode)
@refreshVisibility ||= 0
@flyToView ||= 0
end
def refreshMode
link.refreshMode
end
def viewRefreshMode
link.viewRefreshMode
end
def href
link.href
end
def refreshMode=(a)
link.refreshMode = a
end
def viewRefreshMode=(a)
link.viewRefreshMode = a
end
def href=(a)
link.href = a
end
def to_kml(elem = nil)
e = XML::Node.new 'NetworkLink'
super e
@link.to_kml e
Kamelopard.kml_array(e, [
[@flyToView, 'flyToView'],
[@refreshVisibility, 'refreshVisibility']
])
elem << e unless elem.nil?
e
end
end
# Corresponds to Google Earth's gx:Track extension to KML
class Track < Geometry
attr_accessor :altitudeMode, :when, :coord, :angles, :model
def initialize(options = {})
@when = []
@coord = []
@angles = []
super
end
def to_kml(elem = nil)
e = XML::Node.new 'gx:Track'
[
[ @coord, 'gx:coord' ],
[ @when, 'when' ],
[ @angles, 'gx:angles' ],
].each do |a|
a[0].each do |g|
w = XML::Node.new a[1], g.to_s
e << w
end
end
elem << e unless elem.nil?
e
end
end
# Viewsyncrelay action
class VSRAction < Object
attr_accessor :name, :tour_name, :verbose, :fail_count, :input,
:action, :exit_action, :repeat, :constraints, :reset_constraints,
:initially_disabled
# XXX Consider adding some constraints, so that things like @name and @action don't go nil
# XXX Also ensure constraints and reset_constraints are hashes,
# containing reasonable values, and reasonable keys ('latitude' vs.
# :latitude, for instance)
def initialize(name, options = {})
@name = name
@constraints = {}
@repeat = 'DEFAULT'
@input = 'ALL'
super(options)
DocumentHolder.instance.current_document.vsr_actions << self
end
def to_hash
a = {}
a['name'] = @name unless @name.nil?
a['id'] = @id unless @id.nil?
a['input'] = @input unless @input.nil?
a['tour_name'] = @tour_name unless @tour_name.nil?
a['verbose'] = @verbose unless @verbose.nil?
a['fail_count'] = @fail_count unless @fail_count.nil?
a['action'] = @action unless @action.nil?
a['exit_action'] = @exit_action unless @exit_action.nil?
a['repeat'] = @repeat unless @repeat.nil?
a['initially_disabled'] = @initially_disabled unless @initially_disabled.nil?
a['constraints'] = @constraints unless @constraints.nil?
a['reset_constraints'] = @reset_constraints unless @reset_constraints.nil?
a
end
end
end
# End of Kamelopard module
| 31.662444 | 226 | 0.502478 |
03588e6bb480484e2ea944c0f85f030f96feca57 | 1,006 | def town_names(num = "", optional = "")
starts = ['Bed', 'Brunn', 'Dun', 'Far', 'Glen', 'Tarn']
middles = ['ding', 'fing', 'ly', 'ston']
ends = ['borough', 'burg', 'ditch', 'hall', 'pool', 'ville', 'way', 'worth']
waternames = ['-on-sea', ' Falls']
output = 3
if num == 5
output = 5
end
output.times do
result = ""
result += starts[rand(starts.count)]
if optional != 'short_name'
result += middles[rand(middles.count)]
end
result += ends[rand(ends.count)]
if optional == 'near_water' && num == 3
result += waternames[rand(2)]
end
if optional == 'in_middle_earth'
result += ' Shire'
end
puts result
end
end
puts " "
puts "------only 3 times"
town_names
puts " "
puts "------only 5 times"
town_names(5)
puts " "
puts "------only 3 times with water"
town_names(3, 'near_water')
puts " "
puts "------only 3 times with shire"
town_names(3, 'in_middle_earth')
puts " "
puts "------only 3 times with short names"
town_names(3, 'short_name')
puts " " | 17.344828 | 77 | 0.592445 |
eda9d7c2d7ee0ea069490dba42934c082e918d50 | 12,190 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# EDITING INSTRUCTIONS
# This file was generated from the file
# https://github.com/googleapis/googleapis/blob/master/google/cloud/texttospeech/v1beta1/cloud_tts.proto,
# and updates to that file get reflected here through a refresh process.
# For the short term, the refresh process will only be runnable by Google
# engineers.
require "json"
require "pathname"
require "google/gax"
require "google/cloud/texttospeech/v1beta1/cloud_tts_pb"
require "google/cloud/text_to_speech/v1beta1/credentials"
module Google
module Cloud
module TextToSpeech
module V1beta1
# Service that implements Google Cloud Text-to-Speech API.
#
# @!attribute [r] text_to_speech_stub
# @return [Google::Cloud::Texttospeech::V1beta1::TextToSpeech::Stub]
class TextToSpeechClient
# @private
attr_reader :text_to_speech_stub
# The default address of the service.
SERVICE_ADDRESS = "texttospeech.googleapis.com".freeze
# The default port of the service.
DEFAULT_SERVICE_PORT = 443
# The default set of gRPC interceptors.
GRPC_INTERCEPTORS = []
DEFAULT_TIMEOUT = 30
# The scopes needed to make gRPC calls to all of the methods defined in
# this service.
ALL_SCOPES = [
"https://www.googleapis.com/auth/cloud-platform"
].freeze
# @param credentials [Google::Auth::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc]
# Provides the means for authenticating requests made by the client. This parameter can
# be many types.
# A `Google::Auth::Credentials` uses a the properties of its represented keyfile for
# authenticating requests made by this client.
# A `String` will be treated as the path to the keyfile to be used for the construction of
# credentials for this client.
# A `Hash` will be treated as the contents of a keyfile to be used for the construction of
# credentials for this client.
# A `GRPC::Core::Channel` will be used to make calls through.
# A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The channel credentials
# should already be composed with a `GRPC::Core::CallCredentials` object.
# A `Proc` will be used as an updater_proc for the Grpc channel. The proc transforms the
# metadata for requests, generally, to give OAuth credentials.
# @param scopes [Array<String>]
# The OAuth scopes for this service. This parameter is ignored if
# an updater_proc is supplied.
# @param client_config [Hash]
# A Hash for call options for each method. See
# Google::Gax#construct_settings for the structure of
# this data. Falls back to the default config if not specified
# or the specified config is missing data points.
# @param timeout [Numeric]
# The default timeout, in seconds, for calls made through this client.
# @param metadata [Hash]
# Default metadata to be sent with each request. This can be overridden on a per call basis.
# @param exception_transformer [Proc]
# An optional proc that intercepts any exceptions raised during an API call to inject
# custom error handling.
def initialize \
credentials: nil,
scopes: ALL_SCOPES,
client_config: {},
timeout: DEFAULT_TIMEOUT,
metadata: nil,
exception_transformer: nil,
lib_name: nil,
lib_version: ""
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "google/gax/grpc"
require "google/cloud/texttospeech/v1beta1/cloud_tts_services_pb"
credentials ||= Google::Cloud::TextToSpeech::V1beta1::Credentials.default
if credentials.is_a?(String) || credentials.is_a?(Hash)
updater_proc = Google::Cloud::TextToSpeech::V1beta1::Credentials.new(credentials).updater_proc
end
if credentials.is_a?(GRPC::Core::Channel)
channel = credentials
end
if credentials.is_a?(GRPC::Core::ChannelCredentials)
chan_creds = credentials
end
if credentials.is_a?(Proc)
updater_proc = credentials
end
if credentials.is_a?(Google::Auth::Credentials)
updater_proc = credentials.updater_proc
end
package_version = Gem.loaded_specs['google-cloud-text_to_speech'].version.version
google_api_client = "gl-ruby/#{RUBY_VERSION}"
google_api_client << " #{lib_name}/#{lib_version}" if lib_name
google_api_client << " gapic/#{package_version} gax/#{Google::Gax::VERSION}"
google_api_client << " grpc/#{GRPC::VERSION}"
google_api_client.freeze
headers = { :"x-goog-api-client" => google_api_client }
headers.merge!(metadata) unless metadata.nil?
client_config_file = Pathname.new(__dir__).join(
"text_to_speech_client_config.json"
)
defaults = client_config_file.open do |f|
Google::Gax.construct_settings(
"google.cloud.texttospeech.v1beta1.TextToSpeech",
JSON.parse(f.read),
client_config,
Google::Gax::Grpc::STATUS_CODE_NAMES,
timeout,
errors: Google::Gax::Grpc::API_ERRORS,
metadata: headers
)
end
# Allow overriding the service path/port in subclasses.
service_path = self.class::SERVICE_ADDRESS
port = self.class::DEFAULT_SERVICE_PORT
interceptors = self.class::GRPC_INTERCEPTORS
@text_to_speech_stub = Google::Gax::Grpc.create_stub(
service_path,
port,
chan_creds: chan_creds,
channel: channel,
updater_proc: updater_proc,
scopes: scopes,
interceptors: interceptors,
&Google::Cloud::Texttospeech::V1beta1::TextToSpeech::Stub.method(:new)
)
@list_voices = Google::Gax.create_api_call(
@text_to_speech_stub.method(:list_voices),
defaults["list_voices"],
exception_transformer: exception_transformer
)
@synthesize_speech = Google::Gax.create_api_call(
@text_to_speech_stub.method(:synthesize_speech),
defaults["synthesize_speech"],
exception_transformer: exception_transformer
)
end
# Service calls
# Returns a list of {Google::Cloud::Texttospeech::V1beta1::Voice Voice}
# supported for synthesis.
#
# @param language_code [String]
# Optional (but recommended)
# [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If
# specified, the ListVoices call will only return voices that can be used to
# synthesize this language_code. E.g. when specifying "en-NZ", you will get
# supported "en-*" voices; when specifying "no", you will get supported
# "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh"
# will also get supported "cmn-*" voices; specifying "zh-hk" will also get
# supported "yue-*" voices.
# @param options [Google::Gax::CallOptions]
# Overrides the default settings for this call, e.g, timeout,
# retries, etc.
# @yield [result, operation] Access the result along with the RPC operation
# @yieldparam result [Google::Cloud::Texttospeech::V1beta1::ListVoicesResponse]
# @yieldparam operation [GRPC::ActiveCall::Operation]
# @return [Google::Cloud::Texttospeech::V1beta1::ListVoicesResponse]
# @raise [Google::Gax::GaxError] if the RPC is aborted.
# @example
# require "google/cloud/text_to_speech"
#
# text_to_speech_client = Google::Cloud::TextToSpeech.new(version: :v1beta1)
# response = text_to_speech_client.list_voices
def list_voices \
language_code: nil,
options: nil,
&block
req = {
language_code: language_code
}.delete_if { |_, v| v.nil? }
req = Google::Gax::to_proto(req, Google::Cloud::Texttospeech::V1beta1::ListVoicesRequest)
@list_voices.call(req, options, &block)
end
# Synthesizes speech synchronously: receive results after all text input
# has been processed.
#
# @param input [Google::Cloud::Texttospeech::V1beta1::SynthesisInput | Hash]
# Required. The Synthesizer requires either plain text or SSML as input.
# A hash of the same form as `Google::Cloud::Texttospeech::V1beta1::SynthesisInput`
# can also be provided.
# @param voice [Google::Cloud::Texttospeech::V1beta1::VoiceSelectionParams | Hash]
# Required. The desired voice of the synthesized audio.
# A hash of the same form as `Google::Cloud::Texttospeech::V1beta1::VoiceSelectionParams`
# can also be provided.
# @param audio_config [Google::Cloud::Texttospeech::V1beta1::AudioConfig | Hash]
# Required. The configuration of the synthesized audio.
# A hash of the same form as `Google::Cloud::Texttospeech::V1beta1::AudioConfig`
# can also be provided.
# @param options [Google::Gax::CallOptions]
# Overrides the default settings for this call, e.g, timeout,
# retries, etc.
# @yield [result, operation] Access the result along with the RPC operation
# @yieldparam result [Google::Cloud::Texttospeech::V1beta1::SynthesizeSpeechResponse]
# @yieldparam operation [GRPC::ActiveCall::Operation]
# @return [Google::Cloud::Texttospeech::V1beta1::SynthesizeSpeechResponse]
# @raise [Google::Gax::GaxError] if the RPC is aborted.
# @example
# require "google/cloud/text_to_speech"
#
# text_to_speech_client = Google::Cloud::TextToSpeech.new(version: :v1beta1)
#
# # TODO: Initialize `input`:
# input = {}
#
# # TODO: Initialize `voice`:
# voice = {}
#
# # TODO: Initialize `audio_config`:
# audio_config = {}
# response = text_to_speech_client.synthesize_speech(input, voice, audio_config)
def synthesize_speech \
input,
voice,
audio_config,
options: nil,
&block
req = {
input: input,
voice: voice,
audio_config: audio_config
}.delete_if { |_, v| v.nil? }
req = Google::Gax::to_proto(req, Google::Cloud::Texttospeech::V1beta1::SynthesizeSpeechRequest)
@synthesize_speech.call(req, options, &block)
end
end
end
end
end
end
| 44.98155 | 131 | 0.609844 |
18e8ef4cefad50b4863faf29f371a20493036071 | 2,901 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
devise_for :admin_users
authenticate :admin_user do
match "/delayed_job" => DelayedJobWeb, anchor: false, via: %i(get post)
namespace :admin do
resources :snap_applications, only: %i[index show] do
get "pdf", on: :member
end
resources :medicaid_applications, only: %i[index show] do
get "pdf", on: :member
end
resources :common_applications, only: %i[index show] do
get "pdf", on: :member
end
resources :exports, only: %i[index show]
resources :members, only: %i[index show]
resources :employments, only: %i[index show]
resources :addresses, only: %i[index show]
resources :household_members, only: %i[index show]
root to: "snap_applications#index"
end
end
resources :messages
get "/start" => "static_pages#index"
root "static_pages#index"
get "/privacy" => "static_pages#privacy"
get "/terms" => "static_pages#terms"
if GateKeeper.feature_enabled? "FLOW_CLOSED"
get "/clio" => redirect("/")
get "/union" => redirect("/")
else
get "/clio" => "static_pages#clio"
get "/union" => "static_pages#union"
end
resource :confirmations, only: %i[show]
resources :documents, only: %i[index new create destroy]
if Rails.env.test? || Rails.env.development?
resource :file_preview, only: %i[show]
end
resources :numbers, module: :stats, only: %i[index]
resource :resource, only: %i[show]
resource :sessions, only: %i[new destroy] do
collection do
get :clear, to: "sessions#destroy"
end
end
resource :skip_send_application, only: [:create]
resources :steps, only: %i[index show] do
collection do
StepNavigation.steps_and_substeps.each do |controller_class|
{ get: :edit, put: :update }.each do |method, action|
match "/#{controller_class.to_param}",
action: action,
controller: controller_class.controller_path,
via: method
end
end
Medicaid::StepNavigation.steps_and_substeps.each do |controller_class|
{ get: :edit, put: :update }.each do |method, action|
match "/#{controller_class.to_param}",
action: action,
controller: controller_class.controller_path,
via: method
end
end
end
end
resources :sections, controller: :forms, only: %i[index show] do
collection do
FormNavigation.all.each do |controller_class|
{ get: :edit, put: :update }.each do |method, action|
match "/#{controller_class.to_param}",
action: action,
controller: controller_class.controller_path,
via: method
end
end
end
end
resource :feedback, only: %i[create]
end
| 29.602041 | 101 | 0.638056 |
bf043f3f0137189ed47b29292fe76c8684fead30 | 4,122 | # frozen_string_literal: true
require 'spec_helper'
describe GitlabRoutingHelper do
let(:project) { build_stubbed(:project) }
let(:group) { build_stubbed(:group) }
describe 'Project URL helpers' do
describe '#project_member_path' do
let(:project_member) { create(:project_member) }
it { expect(project_member_path(project_member)).to eq project_project_member_path(project_member.source, project_member) }
end
describe '#request_access_project_members_path' do
it { expect(request_access_project_members_path(project)).to eq request_access_project_project_members_path(project) }
end
describe '#leave_project_members_path' do
it { expect(leave_project_members_path(project)).to eq leave_project_project_members_path(project) }
end
describe '#approve_access_request_project_member_path' do
let(:project_member) { create(:project_member) }
it { expect(approve_access_request_project_member_path(project_member)).to eq approve_access_request_project_project_member_path(project_member.source, project_member) }
end
describe '#resend_invite_project_member_path' do
let(:project_member) { create(:project_member) }
it { expect(resend_invite_project_member_path(project_member)).to eq resend_invite_project_project_member_path(project_member.source, project_member) }
end
end
describe 'Group URL helpers' do
describe '#group_members_url' do
it { expect(group_members_url(group)).to eq group_group_members_url(group) }
end
describe '#group_member_path' do
let(:group_member) { create(:group_member) }
it { expect(group_member_path(group_member)).to eq group_group_member_path(group_member.source, group_member) }
end
describe '#request_access_group_members_path' do
it { expect(request_access_group_members_path(group)).to eq request_access_group_group_members_path(group) }
end
describe '#leave_group_members_path' do
it { expect(leave_group_members_path(group)).to eq leave_group_group_members_path(group) }
end
describe '#approve_access_request_group_member_path' do
let(:group_member) { create(:group_member) }
it { expect(approve_access_request_group_member_path(group_member)).to eq approve_access_request_group_group_member_path(group_member.source, group_member) }
end
describe '#resend_invite_group_member_path' do
let(:group_member) { create(:group_member) }
it { expect(resend_invite_group_member_path(group_member)).to eq resend_invite_group_group_member_path(group_member.source, group_member) }
end
end
describe '#preview_markdown_path' do
let(:project) { create(:project) }
it 'returns group preview markdown path for a group parent' do
group = create(:group)
expect(preview_markdown_path(group)).to eq("/groups/#{group.path}/preview_markdown")
end
it 'returns project preview markdown path for a project parent' do
expect(preview_markdown_path(project)).to eq("/#{project.full_path}/preview_markdown")
end
it 'returns snippet preview markdown path for a personal snippet' do
@snippet = create(:personal_snippet)
expect(preview_markdown_path(nil)).to eq("/snippets/preview_markdown")
end
it 'returns project preview markdown path for a project snippet' do
@snippet = create(:project_snippet, project: project)
expect(preview_markdown_path(project)).to eq("/#{project.full_path}/preview_markdown")
end
end
describe '#edit_milestone_path' do
it 'returns group milestone edit path when given entity parent is a Group' do
group = create(:group)
milestone = create(:milestone, group: group)
expect(edit_milestone_path(milestone)).to eq("/groups/#{group.path}/-/milestones/#{milestone.iid}/edit")
end
it 'returns project milestone edit path when given entity parent is not a Group' do
milestone = create(:milestone, group: nil)
expect(edit_milestone_path(milestone)).to eq("/#{milestone.project.full_path}/-/milestones/#{milestone.iid}/edit")
end
end
end
| 37.472727 | 175 | 0.747695 |
bba856e7dbab4030d8f254510f758e0ab61f6620 | 2,669 | require 'rails_helper'
describe 'Editor', js: true do
let(:exercise) { FactoryBot.create(:audio_video, description: Forgery(:lorem_ipsum).sentence) }
let(:user) { FactoryBot.create(:teacher) }
before(:each) do
visit(sign_in_path)
fill_in('email', with: user.email)
fill_in('password', with: FactoryBot.attributes_for(:teacher)[:password])
click_button(I18n.t('sessions.new.link'))
expect_any_instance_of(LtiHelper).to receive(:lti_outcome_service?).and_return(true)
visit(implement_exercise_path(exercise))
end
it 'displays the exercise title' do
expect(page).to have_content(exercise.title)
end
it 'displays the exercise description' do
expect(page).to have_content(exercise.description)
end
it 'displays all visible files in a file tree' do
within('#files') do
exercise.files.select(&:visible).each do |file|
expect(page).to have_content(file.name_with_extension)
end
end
end
it "displays the main file's code" do
expect(page).to have_css(".frame[data-filename='#{exercise.files.detect(&:main_file?).name_with_extension}']")
end
context 'when selecting a file' do
before(:each) do
within('#files') { click_link(file.name_with_extension) }
end
context 'when selecting a binary file' do
context 'when selecting an audio file' do
let(:file) { exercise.files.detect { |file| file.file_type.audio? } }
it 'contains an <audio> tag' do
expect(page).to have_css("audio[src='#{file.native_file.url}']")
end
end
context 'when selecting an image file' do
let(:file) { exercise.files.detect { |file| file.file_type.image? } }
it 'contains an <img> tag' do
expect(page).to have_css("img[src='#{file.native_file.url}']")
end
end
context 'when selecting a video file' do
let(:file) { exercise.files.detect { |file| file.file_type.video? } }
it 'contains a <video> tag' do
expect(page).to have_css("video[src='#{file.native_file.url}']")
end
end
end
context 'when selecting a non-binary file' do
let(:file) { exercise.files.detect { |file| !file.file_type.binary? && !file.hidden? } }
it "displays the file's code" do
expect(page).to have_css(".frame[data-filename='#{file.name_with_extension}']")
end
end
end
it 'does not contains a button for submitting the exercise' do
click_button(I18n.t('exercises.editor.score'))
click_button('toggle-sidebar-output-collapsed')
expect(page).not_to have_css('#submit_outdated')
expect(page).to have_css('#submit')
end
end
| 32.156627 | 114 | 0.665043 |
61df8fd8e1d53d6278428faa21589c94806149fb | 1,121 |
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'coincheck-api'
Gem::Specification.new do |spec|
spec.name = 'coincheck-api'
spec.version = Coincheck::API::VERSION
spec.authors = ['Masayuki Higashino']
spec.email = ["[email protected]"]
spec.summary = %q{A client for Coincheck API.}
spec.description = %q{A client for Coincheck API.}
spec.homepage = 'https://github.com/mh61503891/coincheck-api'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_dependency 'activesupport', '~> 5.1.4'
spec.add_development_dependency 'bundler', '~> 1.16'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'pry', '~> 0.11'
spec.add_development_dependency 'awesome_print', '~> 1.8'
end
| 36.16129 | 74 | 0.647636 |
036346dc6c643cbf7bc8bf9cbd504896b4425f72 | 809 | module BasecampNinja; module Classic; module Modules; module CalendarEntry
def get_calendar_entry(project_id, id)
object = Hash.from_xml(connection["/projects/#{project_id}/calendar_entries/#{id}.xml"].get)["calendar_entry"]
BasecampNinja::Classic::CalendarEntry.new.extend(BasecampNinja::Classic::Renderer::CalendarEntry).from_hash(object)
rescue Exception => e
puts "Error: #{e.message}"
nil
end
def get_calendar_entries(project_id)
collection = Hash.from_xml(connection["/projects/#{project_id}/calendar_entries.xml"].get)["calendar_entries"]
collection.map { |object| BasecampNinja::Classic::CalendarEntry.new.extend(BasecampNinja::Classic::Renderer::CalendarEntry).from_hash(object) }
rescue Exception => e
puts "Error: #{e.message}"
[]
end
end; end; end; end | 47.588235 | 147 | 0.746601 |
e273d0034dc07665216a1c24f2e0088fcfd869f8 | 1,443 | # encoding: utf-8
class CampusImageUploader < CarrierWave::Uploader::Base
# Include RMagick or ImageScience support:
include CarrierWave::RMagick
# include CarrierWave::ImageScience
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"images/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
"/assets/#{model.class.to_s.underscore}/fallback/" + [version_name, "default.jpg"].compact.join('_')
end
# Process files as they are uploaded:
process :resize_to_fill => [400, 400]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
version :medium do
process :resize_to_fill => [100, 100]
end
version :small do
process :resize_to_fill => [48, 48]
end
# Add a white list of extensions which are allowed to be uploaded.
# For assets you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
| 27.75 | 104 | 0.70894 |
6aa24e63553ca7c12d2d021ebba76795676c0b57 | 1,560 | # Cookbook Name:: oc-opsworks-recipes
# Recipe:: install-opencast-job-metrics
::Chef::Recipe.send(:include, MhOpsworksRecipes::RecipeHelpers)
include_recipe "oc-opsworks-recipes::update-python"
rest_auth_info = get_rest_auth_info
aws_instance_id = node[:opsworks][:instance][:aws_instance_id]
(private_admin_hostname, admin_attributes) = node[:opsworks][:layers][:admin][:instances].first
workers_layer_id = node[:opsworks][:layers][:workers][:id]
stack_id = node[:opsworks][:stack][:id]
stack_name = stack_shortname
execute 'install pyhorn' do
command '/usr/bin/python3 -m pip install pyhorn'
user 'root'
end
["queued_job_count.py",
"queued_job_count_metric.sh",
"workers_job_load.py",
"workers_job_load_metrics.sh"
].each do |filename|
cookbook_file filename do
path "/usr/local/bin/#{filename}"
owner "root"
group "root"
mode "755"
end
end
cron_d 'opencast_jobs_queued' do
user 'custom_metrics'
minute '*'
command %Q(/usr/local/bin/queued_job_count_metric.sh "#{aws_instance_id}" "http://#{private_admin_hostname}/" "#{rest_auth_info[:user]}" "#{rest_auth_info[:pass]}" 2>&1 | logger -t info)
path '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
end
cron_d 'workers_job_load_metrics' do
user 'root'
minute '*'
command %Q(/usr/local/bin/workers_job_load_metrics.sh "#{stack_name}" "#{stack_id}" "#{workers_layer_id}" "#{private_admin_hostname}" "#{rest_auth_info[:user]}" "#{rest_auth_info[:pass]}" 2>&1 | logger -t info)
path '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
end
| 34.666667 | 212 | 0.728205 |
e9e81f96d297513342057de768a70ab49e9fef8f | 1,430 | # frozen_string_literal: true
require 'vk/api/objects'
require 'vk/schema/namespace'
module Vk
module API
class Notifications < Vk::Schema::Namespace
# @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
class Notification < Vk::Schema::Object
# @return [String] Notification type
attribute :type, API::Types::Coercible::String.optional.default(nil)
# @return [Integer] Date when the event has been occured
attribute :date, API::Types::Coercible::Int.optional.default(nil)
# @return [API::Wall::WallpostToId, API::Photos::Photo, API::Board::Topic, API::Video::Video, API::Notifications::NotificationsComment] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
attribute :parent, Dry::Types[API::Wall::WallpostToId] | Dry::Types[API::Photos::Photo] | Dry::Types[API::Board::Topic] | Dry::Types[API::Video::Video] | Dry::Types[API::Notifications::NotificationsComment].optional.default(nil)
# @return [API::Notifications::Feedback] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
attribute :feedback, Dry::Types[API::Notifications::Feedback].optional.default(nil)
# @return [API::Notifications::Reply] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
attribute :reply, Dry::Types[API::Notifications::Reply].optional.default(nil)
end
end
end
end
| 59.583333 | 236 | 0.705594 |
5d5f06979f222e3a13e6f8537c1093b98e90ceb6 | 2,277 | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cloud_crowd/version'
Gem::Specification.new do |s|
s.name = 'cloud-crowd'
s.version = CloudCrowd::VERSION
s.date = CloudCrowd::VERSION_RELEASED
s.homepage = "http://wiki.github.com/documentcloud/cloud-crowd"
s.summary = "Parallel Processing for the Rest of Us"
s.description = <<-EOS
The crowd, suddenly there where there was nothing before, is a mysterious and
universal phenomenon. A few people may have been standing together -- five, ten
or twelve, nor more; nothing has been announced, nothing is expected. Suddenly
everywhere is black with people and more come streaming from all sides as though
streets had only one direction.
EOS
s.license = "MIT"
s.authors = ['Jeremy Ashkenas', 'Ted Han', 'Nathan Stitt']
s.email = '[email protected]'
s.rubyforge_project = 'cloud-crowd'
s.require_paths = ['lib']
s.executables = ['crowd']
s.extra_rdoc_files = ['README']
s.rdoc_options << '--title' << 'CloudCrowd | Parallel Processing for the Rest of Us' <<
'--exclude' << 'test' <<
'--main' << 'README' <<
'--all'
s.add_dependency 'activerecord', '>=3.0'
s.add_dependency 'sinatra'
s.add_dependency 'active_model_serializers'
s.add_dependency 'json', ['>= 1.1.7']
s.add_dependency 'rest-client', ['>= 1.4']
s.add_dependency 'thin', ['>= 1.2.4']
s.add_dependency 'rake'
if s.respond_to?(:add_development_dependency)
s.add_development_dependency 'faker', ['>= 0.3.1']
s.add_development_dependency 'shoulda'
s.add_development_dependency 'machinist', ['>= 1.0.3']
s.add_development_dependency 'rack-test', ['>= 0.4.1']
s.add_development_dependency 'mocha', ['>= 0.9.7']
end
s.files = Dir[
'actions/**/*.rb',
'cloud-crowd.gemspec',
'config/**/*.example.*',
'EPIGRAPHS',
'examples/**/*.rb',
'lib/**/*.rb',
'LICENSE',
'public/**/*.{js,css,ico,png,gif}',
'README',
'test/**/*.{rb,ru,yml}',
'views/**/*.erb'
]
end
| 33.485294 | 97 | 0.597716 |
7a57ca5b99667adf334a9b76527d446b73e17577 | 421 | module Pione
module Lang
# DocumentParser is a parser for PIONE document.
class DocumentParser < Parslet::Parser
include Util::ParsletParserExtension
include CommonParser
include LiteralParser
include ExprParser
include ContextParser
include ConditionalBranchParser
include DeclarationParser
#
# root
#
root(:package_context)
end
end
end
| 21.05 | 52 | 0.68171 |
d588623b9a2976815ff6d77fa29ca9b905e248e4 | 493 | module Resources::Discounts
class Actions::Create < ::Actions::Save
private
def model
@model ||= Model.new(model_params)
end
# Indirect mapping
def model_params
{
name: params['discount']['name'],
description: params['discount']['description'],
code: params['discount']['code'],
value: params['discount']['percentage'],
expires_on: params['discount']['expiration_date']
}
end
end
end
| 23.47619 | 58 | 0.574037 |
b9e5acb539077b870320746eb6a92e740cc7a7f8 | 8,873 | =begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.31.1
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
module Plaid
class Configuration
# Plaid Environment mapping
# production, development, sandbox
Environment = { "production" => 0, "development" => 1, "sandbox" => 2 }
# Defines url scheme
attr_accessor :scheme
# Defines url host
attr_accessor :host
# Defines url base path
attr_accessor :base_path
# Define server configuration index
attr_accessor :server_index
# Define server operation configuration index
attr_accessor :server_operation_index
# Default server variables
attr_accessor :server_variables
# Default server operation variables
attr_accessor :server_operation_variables
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines the access token (Bearer) used with OAuth2.
attr_accessor :access_token
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# The time limit for HTTP request in seconds.
# Default to 0 (never times out).
attr_accessor :timeout
# Set this to false to skip client side validation in the operation.
# Default to true.
# @return [true, false]
attr_accessor :client_side_validation
### TLS/SSL setting
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :ssl_verify
### TLS/SSL setting
# Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html)
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
attr_accessor :ssl_verify_mode
### TLS/SSL setting
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
attr_accessor :ssl_ca_file
### TLS/SSL setting
# Client certificate file (for client certificate)
attr_accessor :ssl_client_cert
### TLS/SSL setting
# Client private key file (for client certificate)
attr_accessor :ssl_client_key
# Set this to customize parameters encoding of array parameter with multi collectionFormat.
# Default to nil.
#
# @see The params_encoding option of Ethon. Related source code:
# https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
attr_accessor :params_encoding
attr_accessor :inject_format
attr_accessor :force_ending_format
def initialize
@scheme = 'https'
@host = 'production.plaid.com'
@base_path = ''
@server_index = 0
@server_operation_index = {}
@server_variables = {}
@server_operation_variables = {}
@api_key = {
'Plaid-Version' => '2020-09-14',
}
@api_key_prefix = {}
@timeout = 0
@client_side_validation = true
@ssl_verify = true
@ssl_verify_mode = nil
@ssl_ca_file = nil
@ssl_client_cert = nil
@ssl_client_key = nil
@debugging = false
@inject_format = false
@force_ending_format = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
yield(self) if block_given?
end
# The default Configuration object.
def self.default
@@default ||= Configuration.new
end
def configure
yield(self) if block_given?
end
def scheme=(scheme)
# remove :// from scheme
@scheme = scheme.sub(/:\/\//, '')
end
def host=(host)
# remove http(s):// and anything after a slash
@host = host.sub(/https?:\/\//, '').split('/').first
end
def base_path=(base_path)
# Add leading and trailing slashes to base_path
@base_path = "/#{base_path}".gsub(/\/+/, '/')
@base_path = '' if @base_path == '/'
end
# Returns base URL for specified operation based on server settings
def base_url(operation = nil)
index = server_operation_index.fetch(operation, server_index)
return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if index == nil
server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation])
end
# Gets API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def api_key_with_prefix(param_name)
if @api_key_prefix[param_name]
"#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
else
@api_key[param_name]
end
end
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
'clientId' =>
{
type: 'api_key',
in: 'header',
key: 'PLAID-CLIENT-ID',
value: api_key_with_prefix('PLAID-CLIENT-ID')
},
'plaidVersion' =>
{
type: 'api_key',
in: 'header',
key: 'Plaid-Version',
value: api_key_with_prefix('Plaid-Version')
},
'secret' =>
{
type: 'api_key',
in: 'header',
key: 'PLAID-SECRET',
value: api_key_with_prefix('PLAID-SECRET')
},
}
end
# Returns an array of Server setting
def server_settings
[
{
url: "https://production.plaid.com",
description: "Production",
},
{
url: "https://development.plaid.com",
description: "Development",
},
{
url: "https://sandbox.plaid.com",
description: "Sandbox",
}
]
end
def operation_server_settings
{
}
end
# Returns URL based on server settings
#
# @param index array index of the server settings
# @param variables hash of variable and the corresponding value
def server_url(index, variables = {}, servers = nil)
servers = server_settings if servers == nil
# check array index out of bound
if (index < 0 || index >= servers.size)
fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}"
end
server = servers[index]
url = server[:url]
return url unless server.key? :variables
# go through variable and assign a value
server[:variables].each do |name, variable|
if variables.key?(name)
if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name]))
url.gsub! "{" + name.to_s + "}", variables[name]
else
fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}."
end
else
# use default value
url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value]
end
end
url
end
end
end
| 29.576667 | 163 | 0.628987 |
7ae7e98dd8b989d9964486f6d4d9408bae584746 | 1,547 | module DotMailer
class CampaignSummary
%w(
numUniqueOpens
numUniqueTextOpens
numTotalUniqueOpens
numOpens
numTextOpens
numTotalOpens
numClicks
numTextClicks
numTotalClicks
numPageViews
numTotalPageViews
numTextPageViews
numForwards
numTextForwardsge
numEstimatedForwards
numTextEstimatedForwards
numTotalEstimatedForwards
numReplies
numTextReplies
numTotalReplies
numHardBounces
numTextHardBounces
numTotalHardBounces
numSoftBounces
numTextSoftBounces
numTotalSoftBounces
numUnsubscribes
numTextUnsubscribes
numTotalUnsubscribes
numIspComplaints
numTextIspComplaints
numTotalIspComplaints
numMailBlocks
numTextMailBlocks
numTotalMailBlocks
numSent
numTextSent
numTotalSent
numRecipientsClicked
numDelivered
numTextDelivered
numTotalDelivered
).each do |meth|
define_method(meth.underscore) do
@params[meth].to_i
end
end
%w(
percentageDelivered
percentageUniqueOpens
percentageOpens
percentageUnsubscribes
percentageReplies
percentageHardBounces
percentageSoftBounces
percentageUsersClicked
percentageClicksToOpens
).each do |meth|
define_method(meth.underscore) do
@params[meth].to_f
end
end
def date_sent
Time.parse(@params["dateSent"])
end
def initialize(account, id)
@params = account.client.get "/campaigns/#{id.to_s}/summary"
end
end
end
| 19.833333 | 66 | 0.714932 |
ac40c7ed62b07dd4a7b07fc4c0456ea13691e685 | 1,744 | class XcbProto < Formula
desc "X.Org: XML-XCB protocol descriptions for libxcb code generation"
homepage "https://www.x.org/"
url "https://xcb.freedesktop.org/dist/xcb-proto-1.14.tar.gz"
sha256 "1c3fa23d091fb5e4f1e9bf145a902161cec00d260fabf880a7a248b02ab27031"
license "MIT"
revision OS.mac? ? 2 : 6
bottle do
rebuild 2
sha256 cellar: :any_skip_relocation, arm64_big_sur: "3ab62d4a00b0901a5676a904d9d58e263a2c6220d6bb08ea8bcee72ccede7b7e"
sha256 cellar: :any_skip_relocation, big_sur: "4059bed377fd405eb7d2da7a550d2cc1fe33facfa2d2b0c1f3b4b8ebb40c70e2"
sha256 cellar: :any_skip_relocation, catalina: "2cb7d82e47a13c5e90f1fb8e90eccd596efa140f13d3c34bdf594f2eb07adff4"
sha256 cellar: :any_skip_relocation, mojave: "f1bb7552c78b5f0d5adb7085e509c7ecaa6da5afd3bfa865546778e0dcd9a5a8"
sha256 cellar: :any_skip_relocation, x86_64_linux: "08c0e6815d15b21eedb1c36e463a03e354e293fe17fbf4a38574afe007c0a2e3"
end
depends_on "pkg-config" => [:build, :test]
depends_on "[email protected]" => :build
# Fix for Python 3.9. Use math.gcd() for Python >= 3.5.
# fractions.gcd() has been deprecated since Python 3.5.
patch do
url "https://gitlab.freedesktop.org/xorg/proto/xcbproto/-/commit/426ae35bee1fa0fdb8b5120b1dcd20cee6e34512.diff"
sha256 "53593ed1b146baa47755da8e9c58f51b1451eec038b421b145d3f583055c55e0"
end
def install
args = %W[
--prefix=#{prefix}
--sysconfdir=#{etc}
--localstatedir=#{var}
--disable-silent-rules
PYTHON=python3
]
system "./configure", *args
system "make"
system "make", "install"
end
test do
assert_match "#{share}/xcb", shell_output("pkg-config --variable=xcbincludedir xcb-proto").chomp
end
end
| 37.913043 | 122 | 0.747133 |
38460a2512bd730b7c032ad84e68a93acf10a40d | 1,791 | class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:name, :title, :contents)
end
end
| 23.88 | 88 | 0.637633 |
9121babeeddca1402956421552cb143b72b618ef | 7,437 | #
# Author:: Steven Danna ([email protected])
# Copyright:: Copyright (c) 2012 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'chef/user'
require 'tempfile'
describe Chef::User do
before(:each) do
@user = Chef::User.new
end
describe "initialize" do
it "should be a Chef::User" do
@user.should be_a_kind_of(Chef::User)
end
end
describe "name" do
it "should let you set the name to a string" do
@user.name("ops_master").should == "ops_master"
end
it "should return the current name" do
@user.name "ops_master"
@user.name.should == "ops_master"
end
# It is not feasible to check all invalid characters. Here are a few
# that we probably care about.
it "should not accept invalid characters" do
# capital letters
lambda { @user.name "Bar" }.should raise_error(ArgumentError)
# slashes
lambda { @user.name "foo/bar" }.should raise_error(ArgumentError)
# ?
lambda { @user.name "foo?" }.should raise_error(ArgumentError)
# &
lambda { @user.name "foo&" }.should raise_error(ArgumentError)
end
it "should not accept spaces" do
lambda { @user.name "ops master" }.should raise_error(ArgumentError)
end
it "should throw an ArgumentError if you feed it anything but a string" do
lambda { @user.name Hash.new }.should raise_error(ArgumentError)
end
end
describe "admin" do
it "should let you set the admin bit" do
@user.admin(true).should == true
end
it "should return the current admin value" do
@user.admin true
@user.admin.should == true
end
it "should default to false" do
@user.admin.should == false
end
it "should throw an ArgumentError if you feed it anything but true or false" do
lambda { @user.name Hash.new }.should raise_error(ArgumentError)
end
end
describe "public_key" do
it "should let you set the public key" do
@user.public_key("super public").should == "super public"
end
it "should return the current public key" do
@user.public_key("super public")
@user.public_key.should == "super public"
end
it "should throw an ArgumentError if you feed it something lame" do
lambda { @user.public_key Hash.new }.should raise_error(ArgumentError)
end
end
describe "private_key" do
it "should let you set the private key" do
@user.private_key("super private").should == "super private"
end
it "should return the private key" do
@user.private_key("super private")
@user.private_key.should == "super private"
end
it "should throw an ArgumentError if you feed it something lame" do
lambda { @user.private_key Hash.new }.should raise_error(ArgumentError)
end
end
describe "when serializing to JSON" do
before(:each) do
@user.name("black")
@user.public_key("crowes")
@json = @user.to_json
end
it "serializes as a JSON object" do
@json.should match(/^\{.+\}$/)
end
it "includes the name value" do
@json.should include(%q{"name":"black"})
end
it "includes the public key value" do
@json.should include(%{"public_key":"crowes"})
end
it "includes the 'admin' flag" do
@json.should include(%q{"admin":false})
end
it "includes the private key when present" do
@user.private_key("monkeypants")
@user.to_json.should include(%q{"private_key":"monkeypants"})
end
it "does not include the private key if not present" do
@json.should_not include("private_key")
end
it "includes the password if present" do
@user.password "password"
@user.to_json.should include(%q{"password":"password"})
end
it "does not include the password if not present" do
@json.should_not include("password")
end
end
describe "when deserializing from JSON" do
before(:each) do
user = { "name" => "mr_spinks",
"public_key" => "turtles",
"private_key" => "pandas",
"password" => "password",
"admin" => true }
@user = Chef::User.from_json(user.to_json)
end
it "should deserialize to a Chef::User object" do
@user.should be_a_kind_of(Chef::User)
end
it "preserves the name" do
@user.name.should == "mr_spinks"
end
it "preserves the public key" do
@user.public_key.should == "turtles"
end
it "preserves the admin status" do
@user.admin.should be_true
end
it "includes the private key if present" do
@user.private_key.should == "pandas"
end
it "includes the password if present" do
@user.password.should == "password"
end
end
describe "API Interactions" do
before (:each) do
@user = Chef::User.new
@user.name "foobar"
@http_client = mock("Chef::REST mock")
Chef::REST.stub!(:new).and_return(@http_client)
end
describe "list" do
before(:each) do
Chef::Config[:chef_server_url] = "http://www.example.com"
@osc_response = { "admin" => "http://www.example.com/users/admin"}
@ohc_response = [ { "user" => { "username" => "admin" }} ]
end
it "lists all clients on an OSC server" do
@http_client.stub!(:get_rest).with("users").and_return(@osc_response)
Chef::User.list.should == @osc_response
end
it "lists all clients on an OHC/OPC server" do
@http_client.stub!(:get_rest).with("users").and_return(@ohc_response)
# We expect that Chef::User.list will give a consistent response
# so OHC API responses should be transformed to OSC-style output.
Chef::User.list.should == @osc_response
end
end
describe "create" do
it "creates a new user via the API" do
@user.password "password"
@http_client.should_receive(:post_rest).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({})
@user.create
end
end
describe "read" do
it "loads a named user from the API" do
@http_client.should_receive(:get_rest).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"})
user = Chef::User.load("foobar")
user.name.should == "foobar"
user.admin.should == true
user.public_key.should == "pubkey"
end
end
describe "update" do
it "updates an existing user on via the API" do
@http_client.should_receive(:put_rest).with("users/foobar", {:name => "foobar", :admin => false}).and_return({})
@user.update
end
end
describe "destroy" do
it "deletes the specified user via the API" do
@http_client.should_receive(:delete_rest).with("users/foobar")
@user.destroy
end
end
end
end
| 29.050781 | 143 | 0.641926 |
26e18bf75f03cd711c1a41633abb23db8cc24fb3 | 575 | require 'digest/md5'
require 'tempfile'
module Chuckle
module Util
module_function
def hash_to_query(hash)
q = hash.map do |key, value|
key = CGI.escape(key.to_s)
value = CGI.escape(value.to_s)
"#{key}=#{value}"
end
q.sort.join('&')
end
def md5(s)
Digest::MD5.hexdigest(s.to_s)
end
def rm_if_necessary(path)
File.unlink(path) if File.exist?(path)
end
def tmp_path
Tempfile.open('chuckle') do |f|
path = f.path
f.unlink
path
end
end
end
end
| 16.911765 | 44 | 0.563478 |
18512c69780ff8a042a0265f3e698db7ca7c17e7 | 1,220 | # == Schema Information
#
# Table name: activities
#
# id :bigint(8) not null, primary key
# description :text
# difficulty :integer
# name :string
# schedule :text
# created_at :datetime not null
# updated_at :datetime not null
# venue_id :bigint(8)
#
# Indexes
#
# index_activities_on_venue_id (venue_id)
#
# Foreign Keys
#
# fk_rails_... (venue_id => venues.id)
#
require 'test_helper'
class ActivityTest < ActiveSupport::TestCase
def setup
@activity = activities(:one)
end
test 'should validate presence of name' do
assert_must validate_presence_of(:name), @activity
end
test 'should validate uniquness of name' do
assert_must validate_uniqueness_of(:name), @activity
end
test 'should validate presence of description' do
assert_must validate_presence_of(:description), @activity
end
test 'should validate presence of schedule' do
assert_must validate_presence_of(:schedule), @activity
end
test 'by_name should order activities alphabetically' do
activities = Activity.by_name
assert_equal 'Clase de crossfit', activities.first.name
assert_equal 'Kundalini yoga', activities.last.name
end
end
| 23.461538 | 61 | 0.705738 |
d53abcdd1a9ce221903a61632136ae4d7e4fcb2a | 596 | Pod::Spec.new do |s|
s.name = 'CommonKeyboard'
s.version = '1.0.6'
s.license = { :type => "MIT", :file => "LICENSE.md" }
s.summary = 'An elegant Keyboard library for iOS.'
s.homepage = 'https://github.com/kaweerutk/CommonKeyboard'
s.author = { "Kaweerut Kanthawong" => "[email protected]" }
s.source = { :git => 'https://github.com/kaweerutk/CommonKeyboard.git', :tag => s.version }
s.source_files = 'Sources/*.swift'
s.pod_target_xcconfig = {
"SWIFT_VERSION" => "4.2",
}
s.swift_version = '4.2'
s.ios.deployment_target = '9.0'
s.requires_arc = true
end
| 25.913043 | 93 | 0.637584 |
334a00187c6de0a36fd493c75815f959cadbe77f | 663 | require 'spec_helper'
describe 'nrpe::service' do
on_supported_os(facterversion: '3.6').each do |os, facts|
context "on #{os}" do
let :facts do
facts
end
context 'by default' do
let(:pre_condition) { 'include nrpe' }
service_name = case facts[:osfamily]
when 'Debian'
'nagios-nrpe-server'
else
'nrpe'
end
it {
is_expected.to contain_service(service_name).with(
'ensure' => 'running',
'enable' => true
)
}
end
end
end
end
| 22.862069 | 60 | 0.46003 |
ab9585920d2496686b0edc51239359fccfbcaeb5 | 2,005 | # frozen_string_literal: true
require "json"
module BeyondApi
class Request
class << self
[:get, :delete].each do |method|
define_method(method) do |session, path, params = {}|
response = BeyondApi::Connection.default.send(method) do |request|
request.url(session.api_url + path)
request.headers['Authorization'] = "Bearer #{ session.access_token }" unless session.access_token.nil?
request.params = params.to_h.camelize_keys
end
[response.body.blank? ? nil : JSON.parse(response.body), response.status]
end
end
[:post, :put, :patch].each do |method|
define_method(method) do |session, path, body = {}, params = {}|
response = BeyondApi::Connection.default.send(method) do |request|
request.url(session.api_url + path)
request.headers['Authorization'] = "Bearer #{ session.access_token }" unless session.access_token.nil?
request.params = params.to_h.camelize_keys
request.body = body.camelize_keys.to_json
end
[response.body.blank? ? nil : JSON.parse(response.body), response.status]
end
end
end
def self.upload(session, path, file_binary, content_type, params)
response = BeyondApi::Connection.default.post do |request|
request.url(session.api_url + path)
request.headers['Authorization'] = "Bearer #{ session.access_token }" unless session.access_token.nil?
request.headers['Content-Type'] = content_type
request.params = params.to_h.camelize_keys
request.body = file_binary
end
[response.body.blank? ? nil : JSON.parse(response.body), response.status]
end
def self.token(url, params)
response = BeyondApi::Connection.token.post do |request|
request.url(url)
request.params = params
end
[response.body.blank? ? nil : JSON.parse(response.body), response.status]
end
end
end
| 35.803571 | 114 | 0.641397 |
acd988f1b901279db46f86eed1a86da9f41ff90c | 2,180 | require "addressable/uri"
require "socket"
require "openssl"
class CarrierPigeon
def initialize(options={})
[:host, :port, :nick, :channel].each do |option|
raise "You must provide an IRC #{option}" unless options.has_key?(option)
end
tcp_socket = TCPSocket.new(options[:host], options[:port])
if options[:ssl]
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync = true
@socket.sync_close = true
@socket.connect
else
@socket = tcp_socket
end
sendln "PASS #{options[:password]}" if options[:password]
sendln "NICK #{options[:nick]}"
sendln "USER #{options[:nick]} 0 * :#{options[:nick]}"
while line = @socket.gets
case line
when /00[1-4] #{Regexp.escape(options[:nick])}/
break
when /^PING :(.+)$/i
sendln "PONG :#{$1}"
end
end
sendln options[:nickserv_command] if options[:nickserv_command]
if options[:join]
join = "JOIN #{options[:channel]}"
join += " #{options[:channel_password]}" if options[:channel_password]
sendln join
end
end
def message(channel, message, notice = false)
command = notice ? "NOTICE" : "PRIVMSG"
sendln "#{command} #{channel} :#{message}"
end
def die
sendln "QUIT :quit"
@socket.gets until @socket.eof?
@socket.close
end
def self.send(options={})
raise "You must supply a valid IRC URI" unless options[:uri]
raise "You must supply a message" unless options[:message]
uri = Addressable::URI.parse(options[:uri])
options[:host] = uri.host
options[:port] = uri.port || 6667
options[:nick] = uri.user
options[:password] = uri.password
options[:channel] = "#" + uri.fragment
if options[:nickserv_password]
options[:nickserv_command] ||=
"PRIVMSG NICKSERV :IDENTIFY #{options[:nickserv_password]}"
end
pigeon = new(options)
pigeon.message(options[:channel], options[:message], options[:notice])
pigeon.die
end
private
def sendln(cmd)
@socket.puts(cmd)
end
end
| 28.311688 | 79 | 0.637156 |
1dfebe1e616a72433f54d742a9dc94e965da11e5 | 3,944 | require 'datadog/instrumentation/hook_point'
require 'datadog/instrumentation/hook_point_error'
require 'datadog/instrumentation/strategy/prepend'
require 'datadog/instrumentation/strategy/chain'
module Datadog
module Instrumentation
# Represents a target in which to inject a hook
class HookPoint
DEFAULT_STRATEGY = Module.respond_to?(:prepend) ? :prepend : :chain
class << self
def parse(hook_point)
klass_name, separator, method_name = hook_point.split(/(\#|\.)/, 2)
raise ArgumentError, hook_point if klass_name.nil? || separator.nil? || method_name.nil?
raise ArgumentError, hook_point unless ['.', '#'].include?(separator)
method_kind = separator == '.' ? :klass_method : :instance_method
[klass_name.to_sym, method_kind, method_name.to_sym]
end
def const_exist?(name)
resolve_const(name) && true
rescue NameError, ArgumentError
false
end
def resolve_const(name)
raise ArgumentError if name.nil? || name.empty?
name.to_s.split('::').inject(Object) { |a, e| a.const_get(e, false) }
end
def strategy_module(strategy)
case strategy
when :prepend then Strategy::Prepend
when :chain then Strategy::Chain
else
raise HookPointError, "unknown strategy: #{strategy.inspect}"
end
end
end
attr_reader :klass_name, :method_kind, :method_name
def initialize(hook_point, strategy = DEFAULT_STRATEGY)
@klass_name, @method_kind, @method_name = HookPoint.parse(hook_point)
@strategy = strategy
extend HookPoint.strategy_module(strategy)
end
def to_s
@to_s ||= "#{@klass_name}#{@method_kind == :instance_method ? '#' : '.'}#{@method_name}"
end
def exist?
return false unless HookPoint.const_exist?(@klass_name)
if klass_method?
(
klass.singleton_class.public_instance_methods(false) +
klass.singleton_class.protected_instance_methods(false) +
klass.singleton_class.private_instance_methods(false)
).include?(@method_name)
elsif instance_method?
(
klass.public_instance_methods(false) +
klass.protected_instance_methods(false) +
klass.private_instance_methods(false)
).include?(@method_name)
else
raise HookPointError, "#{self} unknown hook point kind"
end
end
def klass
HookPoint.resolve_const(@klass_name)
end
def klass_method?
@method_kind == :klass_method
end
def instance_method?
@method_kind == :instance_method
end
def private_method?
if klass_method?
klass.private_methods.include?(@method_name)
elsif instance_method?
klass.private_instance_methods.include?(@method_name)
else
raise HookPointError, "#{self} unknown hook point kind"
end
end
def protected_method?
if klass_method?
klass.protected_methods.include?(@method_name)
elsif instance_method?
klass.protected_instance_methods.include?(@method_name)
else
raise HookPointError, "#{self} unknown hook point kind"
end
end
# rubocop:disable Lint/UselessMethodDefinition
def installed?(key)
super
end
def install(key, &block)
return unless exist?
return if installed?(key)
super
end
def uninstall(key)
return unless exist?
return unless installed?(key)
super
end
def enable(key)
super
end
def disable(key)
super
end
def disabled?(key)
super
end
# rubocop:enable Lint/UselessMethodDefinition
end
end
end
| 27.2 | 98 | 0.617647 |
18db03a5e4fcc0ca26905a5e527c3bb210a02ecf | 208 | require 'faker'
FactoryGirl.define do
factory :rating do
logline_id { Faker::Number.between(1, 50) }
user_id { Faker::Number.between(1, 20) }
rating { Faker::Number.between(1, 100) }
end
end
| 20.8 | 47 | 0.668269 |
91192b0f93487ea6d616dd76320a44874cbf5fd3 | 4,165 | require 'spec_helper'
RSpec.describe NgrokAPI::Services::TCPEdgeBackendModuleClient do
let(:base_url) { 'https://api.ngrok.com' }
let(:path) { '/edges/tcp/%{id}/backend' }
let(:not_found) do
NgrokAPI::Errors::NotFoundError.new(response: endpoint_backend_result)
end
before(:each) do
@client = class_double("HttpClient")
@tcp_edge_backend_module_client = NgrokAPI::Services::TCPEdgeBackendModuleClient.new(client: @client)
end
describe "#replace" do
it "will make a put request and return an instance of NgrokAPI::Models::EndpointBackend" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: endpoint_backend_result["id"],
}
data = "New a_module"
expect(@client).to receive(:put).with(path % replacements, data: data).
and_return(endpoint_backend_result)
result = @tcp_edge_backend_module_client.replace(
id: endpoint_backend_result["id"],
a_module: "New a_module"
)
expect(result.class).to eq(NgrokAPI::Models::EndpointBackend)
end
end
describe "#replace!" do
it "will make a put request and return an instance of NgrokAPI::Models::EndpointBackend" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: endpoint_backend_result["id"],
}
data = "New a_module"
expect(@client).to receive(:put).with(path % replacements, data: data).
and_return(endpoint_backend_result)
result = @tcp_edge_backend_module_client.replace(
id: endpoint_backend_result["id"],
a_module: "New a_module"
)
expect(result.class).to eq(NgrokAPI::Models::EndpointBackend)
# expect(result.id).to eq(endpoint_backend_result["id"])
end
end
describe "#get" do
it "will make a get request and return an instance of NgrokAPI::Models::EndpointBackend" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: endpoint_backend_result["id"],
}
data = {}
expect(@client).to receive(:get).with(path % replacements, data: data).
and_return(endpoint_backend_result)
result = @tcp_edge_backend_module_client.get(
id: endpoint_backend_result["id"]
)
expect(result.class).to eq(NgrokAPI::Models::EndpointBackend)
end
end
describe "#get!" do
it "will make a get request and return an instance of NgrokAPI::Models::EndpointBackend" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: endpoint_backend_result["id"],
}
data = {}
expect(@client).to receive(:get).with(path % replacements, data: data).
and_return(endpoint_backend_result)
result = @tcp_edge_backend_module_client.get(
id: endpoint_backend_result["id"]
)
expect(result.class).to eq(NgrokAPI::Models::EndpointBackend)
# expect(result.id).to eq(endpoint_backend_result["id"])
end
end
describe "#delete" do
it "will make a delete request" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: api_key_result["id"],
}
expect(@client).to receive(:delete).with(path % replacements).and_return(nil)
@tcp_edge_backend_module_client.delete(
id: api_key_result["id"]
)
end
end
describe "#delete!" do
it "will make a delete request" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: api_key_result["id"],
}
expect(@client).to receive(:delete).with(path % replacements, danger: true).and_return(nil)
@tcp_edge_backend_module_client.delete!(
id: api_key_result["id"]
)
end
it "will make a delete request and return NotFoundError if 404" do
path = '/edges/tcp/%{id}/backend'
replacements = {
id: api_key_result["id"],
}
expect do
expect(@client).to receive(:delete).with(path % replacements, danger: true).
and_raise(NgrokAPI::Errors::NotFoundError)
result = @tcp_edge_backend_module_client.delete!(
id: api_key_result["id"]
)
expect(result).to be nil
end.to raise_error(NgrokAPI::Errors::NotFoundError)
end
end
end
| 33.58871 | 105 | 0.646579 |
5df9bc83bea089cb83720879cb66fd18f11f93ea | 1,623 | # Add GPO records
# cluster with existing Registry Records
# create new Registry Records if no match can be found
#
# run once. use this as lessons for weekly update
#
require 'registry_record'
require 'source_record'
require 'normalize'
require 'json'
require 'dotenv'
require 'pp'
begin
Mongoid.load!(File.expand_path("../config/mongoid.yml", __FILE__), :development)
ORGCODE = 'dgpo'
fin = ARGV.shift
if fin =~ /\.gz$/
updates = Zlib::GzipReader.open(fin)
else
updates = open(fin)
end
new_count = 0
update_count = 0
src_count = {}
rr_ids = []
count = 0
rrcount = 0
updates.each do | line |
count += 1
line.chomp!
marc = JSON.parse line
#records without 001 are junk
gpo_id = marc['fields'].find {|f| f['001'] }
if gpo_id.nil?
next
else
gpo_id = gpo_id['001'].to_i
end
enum_chrons = []
src = SourceRecord.new
src.source = line
src.org_code = ORGCODE
src.local_id = src.extract_local_id.to_i
enum_chrons = src.extract_enum_chrons
src.enum_chrons = enum_chrons.flatten.uniq
src.in_registry = true
src.save
new_count += 1
if src.enum_chrons == []
src.enum_chrons << ""
end
src.enum_chrons.each do |ec|
if regrec = RegistryRecord::cluster( src, ec)
regrec.add_source(src)
update_count += 1
else
regrec = RegistryRecord.new([src.source_id], ec, "GPO initial load")
rrcount += 1
end
regrec.save
rr_ids << regrec.registry_id
end
end
puts "gpo new regrec count: #{rrcount}"
puts "gpo new srcs: #{new_count}"
puts "gpo regrec updates: #{update_count}"
rescue Exception => e
PP.pp e
puts e.backtrace
end
| 19.094118 | 80 | 0.677757 |
ed633604696eca311171b76011c6c168abeb6eed | 17,196 | =begin
#NSX-T Manager API
#VMware NSX-T Manager REST API
OpenAPI spec version: 2.5.1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.7
=end
require 'date'
module NSXT
# Contains the summary of the results of an application discovery session
class AppDiscoverySessionResultSummary
# Link to this resource
attr_accessor :_self
# The server will populate this field when returing the resource. Ignored on PUT and POST.
attr_accessor :_links
# Schema for this resource
attr_accessor :_schema
# The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected.
attr_accessor :_revision
# Indicates system owned resource
attr_accessor :_system_owned
# Defaults to ID if not set
attr_accessor :display_name
# Description of this resource
attr_accessor :description
# Opaque identifiers meaningful to the API user
attr_accessor :tags
# ID of the user who created this resource
attr_accessor :_create_user
# Protection status is one of the following: PROTECTED - the client who retrieved the entity is not allowed to modify it. NOT_PROTECTED - the client who retrieved the entity is allowed to modify it REQUIRE_OVERRIDE - the client who retrieved the entity is a super user and can modify it, but only when providing the request header X-Allow-Overwrite=true. UNKNOWN - the _protection field could not be determined for this entity.
attr_accessor :_protection
# Timestamp of resource creation
attr_accessor :_create_time
# Timestamp of last modification
attr_accessor :_last_modified_time
# ID of the user who last modified this resource
attr_accessor :_last_modified_user
# Unique identifier of this resource
attr_accessor :id
# The type of this resource.
attr_accessor :resource_type
# The status of the session
attr_accessor :status
# End time of the session expressed in milliseconds since epoch
attr_accessor :end_timestamp
# Start time of the session expressed in milliseconds since epoch
attr_accessor :start_timestamp
# The reason for the session status failure.
attr_accessor :failed_reason
# Some App Profiles that were part of the discovery session could be modified or deleted | after the session has been completed. NOT_REQUIRED status denotes that there were no such modifications. | REQUIRED status denotes some App Profiles that were part of the session has been modified/deleted and some | and some applications might not have been classfifed correctly. Use /session/<session-id>/reclassify API to| re-classfy the applications discovered based on app profiles.
attr_accessor :reclassification
# List of App Profiles summary discovered in this session
attr_accessor :app_profile_summary_list
# List of NSGroups provided for discovery for this session
attr_accessor :ns_groups
# List of app profiles targeted to be classified for this session
attr_accessor :app_profiles
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'_self' => :'_self',
:'_links' => :'_links',
:'_schema' => :'_schema',
:'_revision' => :'_revision',
:'_system_owned' => :'_system_owned',
:'display_name' => :'display_name',
:'description' => :'description',
:'tags' => :'tags',
:'_create_user' => :'_create_user',
:'_protection' => :'_protection',
:'_create_time' => :'_create_time',
:'_last_modified_time' => :'_last_modified_time',
:'_last_modified_user' => :'_last_modified_user',
:'id' => :'id',
:'resource_type' => :'resource_type',
:'status' => :'status',
:'end_timestamp' => :'end_timestamp',
:'start_timestamp' => :'start_timestamp',
:'failed_reason' => :'failed_reason',
:'reclassification' => :'reclassification',
:'app_profile_summary_list' => :'app_profile_summary_list',
:'ns_groups' => :'ns_groups',
:'app_profiles' => :'app_profiles'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'_self' => :'SelfResourceLink',
:'_links' => :'Array<ResourceLink>',
:'_schema' => :'String',
:'_revision' => :'Integer',
:'_system_owned' => :'BOOLEAN',
:'display_name' => :'String',
:'description' => :'String',
:'tags' => :'Array<Tag>',
:'_create_user' => :'String',
:'_protection' => :'String',
:'_create_time' => :'Integer',
:'_last_modified_time' => :'Integer',
:'_last_modified_user' => :'String',
:'id' => :'String',
:'resource_type' => :'String',
:'status' => :'String',
:'end_timestamp' => :'Integer',
:'start_timestamp' => :'Integer',
:'failed_reason' => :'String',
:'reclassification' => :'String',
:'app_profile_summary_list' => :'Array<AppDiscoveryAppProfileResultSummary>',
:'ns_groups' => :'Array<NSGroupMetaInfo>',
:'app_profiles' => :'Array<AppProfileMetaInfo>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'_self')
self._self = attributes[:'_self']
end
if attributes.has_key?(:'_links')
if (value = attributes[:'_links']).is_a?(Array)
self._links = value
end
end
if attributes.has_key?(:'_schema')
self._schema = attributes[:'_schema']
end
if attributes.has_key?(:'_revision')
self._revision = attributes[:'_revision']
end
if attributes.has_key?(:'_system_owned')
self._system_owned = attributes[:'_system_owned']
end
if attributes.has_key?(:'display_name')
self.display_name = attributes[:'display_name']
end
if attributes.has_key?(:'description')
self.description = attributes[:'description']
end
if attributes.has_key?(:'tags')
if (value = attributes[:'tags']).is_a?(Array)
self.tags = value
end
end
if attributes.has_key?(:'_create_user')
self._create_user = attributes[:'_create_user']
end
if attributes.has_key?(:'_protection')
self._protection = attributes[:'_protection']
end
if attributes.has_key?(:'_create_time')
self._create_time = attributes[:'_create_time']
end
if attributes.has_key?(:'_last_modified_time')
self._last_modified_time = attributes[:'_last_modified_time']
end
if attributes.has_key?(:'_last_modified_user')
self._last_modified_user = attributes[:'_last_modified_user']
end
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'resource_type')
self.resource_type = attributes[:'resource_type']
end
if attributes.has_key?(:'status')
self.status = attributes[:'status']
end
if attributes.has_key?(:'end_timestamp')
self.end_timestamp = attributes[:'end_timestamp']
end
if attributes.has_key?(:'start_timestamp')
self.start_timestamp = attributes[:'start_timestamp']
end
if attributes.has_key?(:'failed_reason')
self.failed_reason = attributes[:'failed_reason']
end
if attributes.has_key?(:'reclassification')
self.reclassification = attributes[:'reclassification']
end
if attributes.has_key?(:'app_profile_summary_list')
if (value = attributes[:'app_profile_summary_list']).is_a?(Array)
self.app_profile_summary_list = value
end
end
if attributes.has_key?(:'ns_groups')
if (value = attributes[:'ns_groups']).is_a?(Array)
self.ns_groups = value
end
end
if attributes.has_key?(:'app_profiles')
if (value = attributes[:'app_profiles']).is_a?(Array)
self.app_profiles = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if !@display_name.nil? && @display_name.to_s.length > 255
invalid_properties.push('invalid value for "display_name", the character length must be smaller than or equal to 255.')
end
if [email protected]? && @description.to_s.length > 1024
invalid_properties.push('invalid value for "description", the character length must be smaller than or equal to 1024.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if !@display_name.nil? && @display_name.to_s.length > 255
return false if [email protected]? && @description.to_s.length > 1024
status_validator = EnumAttributeValidator.new('String', ['FAILED', 'RUNNING', 'FINISHED'])
return false unless status_validator.valid?(@status)
reclassification_validator = EnumAttributeValidator.new('String', ['NOT_REQUIRED', 'REQUIRED'])
return false unless reclassification_validator.valid?(@reclassification)
true
end
# Custom attribute writer method with validation
# @param [Object] display_name Value to be assigned
def display_name=(display_name)
if !display_name.nil? && display_name.to_s.length > 255
fail ArgumentError, 'invalid value for "display_name", the character length must be smaller than or equal to 255.'
end
@display_name = display_name
end
# Custom attribute writer method with validation
# @param [Object] description Value to be assigned
def description=(description)
if !description.nil? && description.to_s.length > 1024
fail ArgumentError, 'invalid value for "description", the character length must be smaller than or equal to 1024.'
end
@description = description
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] status Object to be assigned
def status=(status)
validator = EnumAttributeValidator.new('String', ['FAILED', 'RUNNING', 'FINISHED'])
unless validator.valid?(status)
fail ArgumentError, 'invalid value for "status", must be one of #{validator.allowable_values}.'
end
@status = status
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] reclassification Object to be assigned
def reclassification=(reclassification)
validator = EnumAttributeValidator.new('String', ['NOT_REQUIRED', 'REQUIRED'])
unless validator.valid?(reclassification)
fail ArgumentError, 'invalid value for "reclassification", must be one of #{validator.allowable_values}.'
end
@reclassification = reclassification
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
_self == o._self &&
_links == o._links &&
_schema == o._schema &&
_revision == o._revision &&
_system_owned == o._system_owned &&
display_name == o.display_name &&
description == o.description &&
tags == o.tags &&
_create_user == o._create_user &&
_protection == o._protection &&
_create_time == o._create_time &&
_last_modified_time == o._last_modified_time &&
_last_modified_user == o._last_modified_user &&
id == o.id &&
resource_type == o.resource_type &&
status == o.status &&
end_timestamp == o.end_timestamp &&
start_timestamp == o.start_timestamp &&
failed_reason == o.failed_reason &&
reclassification == o.reclassification &&
app_profile_summary_list == o.app_profile_summary_list &&
ns_groups == o.ns_groups &&
app_profiles == o.app_profiles
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[_self, _links, _schema, _revision, _system_owned, display_name, description, tags, _create_user, _protection, _create_time, _last_modified_time, _last_modified_user, id, resource_type, status, end_timestamp, start_timestamp, failed_reason, reclassification, app_profile_summary_list, ns_groups, app_profiles].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = NSXT.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 34.95122 | 508 | 0.642824 |
d5f107641e3ee36f3342152e15181171d26f68da | 855 | # generated by 'rake generate'
require 'cocoa/bindings/NSIndexSet'
module Cocoa
class NSMutableIndexSet < Cocoa::NSIndexSet
attach_method :addIndex, :args=>1, :names=>[], :types=>["Q"], :retval=>"v"
attach_method :addIndexes, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
attach_method :addIndexesInRange, :args=>1, :names=>[], :types=>["{_NSRange=QQ}"], :retval=>"v"
attach_method :removeAllIndexes, :args=>0, :names=>[], :types=>[], :retval=>"v"
attach_method :removeIndex, :args=>1, :names=>[], :types=>["Q"], :retval=>"v"
attach_method :removeIndexes, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
attach_method :removeIndexesInRange, :args=>1, :names=>[], :types=>["{_NSRange=QQ}"], :retval=>"v"
attach_method :shiftIndexesStartingAtIndex, :args=>2, :names=>[:by], :types=>["Q", "q"], :retval=>"v"
end
end
| 57 | 105 | 0.625731 |
e95883a02f714356e25611e7da8595e705d6d08a | 13,561 | =begin
#Ahello REST API documentation
#На данной странице вы можете выполнять запросы к API, для этого необходимо указать 'appId', который был передан вам сотрудниками тех. поддержки в поле api_key. Укажите также PartnerUserId (это CRM Id пользователя или его email ), partnerUserId передается в заголовке запроса. Важно!!! ApiKeys-аутентификация c указанием только ключа appId в ближайшее время будет работать только для данной страницы документации. Для реальных сценариев интеграции необходимо использовать HMAC-аутентификацию. В ближайшее время появится раздел помощи по основным вопросам работы с API
OpenAPI spec version: v1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.16
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for AktionClient::UserApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'UserApi' do
before do
# run before each test
@instance = AktionClient::UserApi.new
end
after do
# run after each test
end
describe 'test an instance of UserApi' do
it 'should create an instance of UserApi' do
expect(@instance).to be_instance_of(AktionClient::UserApi)
end
end
describe 'test attribute "count_sl"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "last_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "first_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "middle_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "full_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "email_crm"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "email"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "mobile_phone"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "work_phone"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "partner_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "partner_guid"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "partner_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "partner_type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
# validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["active", "notActive", "unknown"])
# validator.allowable_values.each do |value|
# expect { @instance.partner_type = value }.not_to raise_error
# end
end
end
describe 'test attribute "partner_web_site"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "is_external_partner"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "domain_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "password"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "site_registration_date"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "birth_date"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "position"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_position"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_direction"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_product_type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_category"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_category_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_direction_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_position_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "positions_product_type_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "parent_user"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "business_unit_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "business_unit_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "is_suspended"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "is_multi_partner"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "permissions"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "monitors_user"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "principal_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "full_name_formated"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "allowed_domain_urls"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "geo_location_data"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "country_letter_code"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
# validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["rU", "uA", "kZ"])
# validator.allowable_values.each do |value|
# expect { @instance.country_letter_code = value }.not_to raise_error
# end
end
end
describe 'test attribute "country_code"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "verification_on"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "manager_limit_sl"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "region"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "easy_sl"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "last_login_date"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "sip_account"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "has_sip_account"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "parent_user_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "avaya_extension"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "parent_user_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "role"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "filial_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "filial_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "work_nbo"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "school_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "ticket_for_manager"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "roles_erm"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "count_sl_percent"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "easy_sl_percent"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "block_sys_users_login"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 32.598558 | 568 | 0.710788 |
f7d3458ff51b897b4857e0daf9896d62aafcc5b3 | 181 | Deface::Override.new(
virtual_path: 'spree/shared/_footer',
name: 'pages_in_footer',
insert_bottom: '#footer-right',
partial: 'spree/static_content/static_content_footer'
)
| 25.857143 | 55 | 0.756906 |
bb32d690684531b38c29bcaf8596fad6f8f980a8 | 535 | require 'tzinfo/timezone_definition'
module TZInfo
module Definitions
module Africa
module Mogadishu
include TimezoneDefinition
timezone 'Africa/Mogadishu' do |tz|
tz.offset :o0, 10888, 0, :LMT
tz.offset :o1, 10800, 0, :EAT
tz.offset :o2, 9000, 0, :BEAT
tz.transition 1893, 10, :o1, 26057898439, 10800
tz.transition 1930, 12, :o2, 19410739, 8
tz.transition 1956, 12, :o1, 116920291, 48
end
end
end
end
end
| 24.318182 | 57 | 0.575701 |
b93382e56c11872a565f842a44b493258d05f0fe | 749 | require 'fintoc/errors'
RSpec.describe Fintoc::Errors do
let(:error) { {
message: 'Missing required param: link_token',
doc_url: 'https://fintoc.com/docs#invalid-request-error'
} }
it 'raises a Invalid Request Error' do
expect { raise Fintoc::Errors::InvalidRequestError.new(error[:message], error[:doc_url]) }
.to(raise_error(an_instance_of(Fintoc::Errors::InvalidRequestError))
.with_message(/Missing required param: link_token/))
end
it 'raises a Invalid Request Error with default url doc' do
expect { raise Fintoc::Errors::InvalidRequestError.new(error[:message]) }
.to(raise_error(an_instance_of(Fintoc::Errors::InvalidRequestError))
.with_message(%r{https://fintoc.com/docs}))
end
end
| 37.45 | 94 | 0.715621 |
4a8b70c6ae22ffda877dc8ef7be8376a79ee7dfb | 21 | module Exceptions
end | 10.5 | 17 | 0.904762 |
18f6dd31879ac7b549078c6c06b12b8f2117e736 | 23,608 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Chris Read <[email protected]>
# Copyright:: Copyright (c) 2008-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Ohai.plugin(:Network) do
provides "network", "network/interfaces"
provides "counters/network", "counters/network/interfaces"
provides "ipaddress", "ip6address", "macaddress"
def linux_encaps_lookup(encap)
return "Loopback" if encap.eql?("Local Loopback") || encap.eql?("loopback")
return "PPP" if encap.eql?("Point-to-Point Protocol")
return "SLIP" if encap.eql?("Serial Line IP")
return "VJSLIP" if encap.eql?("VJ Serial Line IP")
return "IPIP" if encap.eql?("IPIP Tunnel")
return "6to4" if encap.eql?("IPv6-in-IPv4")
return "Ethernet" if encap.eql?("ether")
encap
end
def ipv6_enabled?
File.exist? "/proc/net/if_inet6"
end
def iproute2_binary_available?
["/sbin/ip", "/usr/bin/ip", "/bin/ip"].any? { |path| File.exist?(path) }
end
def find_ethtool_binary
["/sbin/ethtool", "/usr/sbin/ethtool"].find { |path| File.exist?(path) }
end
def is_openvz?
::File.directory?("/proc/vz")
end
def is_openvz_host?
is_openvz? && ::File.directory?("/proc/bc")
end
def extract_neighbors(family, iface, neigh_attr)
so = shell_out("ip -f #{family[:name]} neigh show")
so.stdout.lines do |line|
if line =~ /^([a-f0-9\:\.]+)\s+dev\s+([^\s]+)\s+lladdr\s+([a-fA-F0-9\:]+)/
interface = iface[$2]
unless interface
Ohai::Log.warn("neighbor list has entries for unknown interface #{interface}")
next
end
interface[neigh_attr] = Mash.new unless interface[neigh_attr]
interface[neigh_attr][$1] = $3.downcase
end
end
iface
end
# checking the routing tables
# why ?
# 1) to set the default gateway and default interfaces attributes
# 2) on some occasions, the best way to select node[:ipaddress] is to look at
# the routing table source field.
# 3) and since we're at it, let's populate some :routes attributes
# (going to do that for both inet and inet6 addresses)
def check_routing_table(family, iface, default_route_table)
so = shell_out("ip -o -f #{family[:name]} route show table #{default_route_table}")
so.stdout.lines do |line|
line.strip!
Ohai::Log.debug("Parsing #{line}")
if line =~ /\\/
parts = line.split('\\')
route_dest = parts.shift.strip
route_endings = parts
elsif line =~ /^([^\s]+)\s(.*)$/
route_dest = $1
route_endings = [$2]
else
next
end
route_endings.each do |route_ending|
if route_ending =~ /\bdev\s+([^\s]+)\b/
route_int = $1
else
Ohai::Log.debug("Skipping route entry without a device: '#{line}'")
next
end
route_int = "venet0:0" if is_openvz? && !is_openvz_host? && route_int == "venet0" && iface["venet0:0"]
unless iface[route_int]
Ohai::Log.debug("Skipping previously unseen interface from 'ip route show': #{route_int}")
next
end
route_entry = Mash.new(:destination => route_dest,
:family => family[:name])
%w{via scope metric proto src}.each do |k|
route_entry[k] = $1 if route_ending =~ /\b#{k}\s+([^\s]+)\b/
end
# a sanity check, especially for Linux-VServer, OpenVZ and LXC:
# don't report the route entry if the src address isn't set on the node
# unless the interface has no addresses of this type at all
if route_entry[:src]
addr = iface[route_int][:addresses]
unless addr.nil? || addr.has_key?(route_entry[:src]) ||
addr.values.all? { |a| a["family"] != family[:name] }
Ohai::Log.debug("Skipping route entry whose src does not match the interface IP")
next
end
end
iface[route_int][:routes] = Array.new unless iface[route_int][:routes]
iface[route_int][:routes] << route_entry
end
end
iface
end
# now looking at the routes to set the default attributes
# for information, default routes can be of this form :
# - default via 10.0.2.4 dev br0
# - default dev br0 scope link
# - default dev eth0 scope link src 1.1.1.1
# - default via 10.0.3.1 dev eth1 src 10.0.3.2 metric 10
# - default via 10.0.4.1 dev eth2 src 10.0.4.2 metric 20
# using a temporary var to hold routes and their interface name
def parse_routes(family, iface)
iface.collect do |i, iv|
iv[:routes].collect do |r|
r.merge(:dev => i) if r[:family] == family[:name]
end.compact if iv[:routes]
end.compact.flatten
end
# determine layer 1 details for the interface using ethtool
def ethernet_layer_one(iface)
return iface unless ethtool_binary = find_ethtool_binary
keys = %w{ Speed Duplex Port Transceiver Auto-negotiation MDI-X }
iface.each_key do |tmp_int|
next unless iface[tmp_int][:encapsulation] == "Ethernet"
so = shell_out("#{ethtool_binary} #{tmp_int}")
so.stdout.lines do |line|
line.chomp!
Ohai::Log.debug("Parsing ethtool output: #{line}")
line.lstrip!
k, v = line.split(": ")
next unless keys.include? k
k.downcase!.tr!("-", "_")
if k == "speed"
k = "link_speed" # This is not necessarily the maximum speed the NIC supports
v = v[/\d+/].to_i
end
iface[tmp_int][k] = v
end
end
iface
end
# determine link stats, vlans, queue length, and state for an interface using ip
def link_statistics(iface, net_counters)
so = shell_out("ip -d -s link")
tmp_int = nil
on_rx = true
so.stdout.lines do |line|
if line =~ IPROUTE_INT_REGEX
tmp_int = $2
iface[tmp_int] = Mash.new unless iface[tmp_int]
net_counters[tmp_int] = Mash.new unless net_counters[tmp_int]
end
if line =~ /(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/
int = on_rx ? :rx : :tx
net_counters[tmp_int][int] = Mash.new unless net_counters[tmp_int][int]
net_counters[tmp_int][int][:bytes] = $1
net_counters[tmp_int][int][:packets] = $2
net_counters[tmp_int][int][:errors] = $3
net_counters[tmp_int][int][:drop] = $4
if int == :rx
net_counters[tmp_int][int][:overrun] = $5
else
net_counters[tmp_int][int][:carrier] = $5
net_counters[tmp_int][int][:collisions] = $6
end
on_rx = !on_rx
end
if line =~ /qlen (\d+)/
net_counters[tmp_int][:tx] = Mash.new unless net_counters[tmp_int][:tx]
net_counters[tmp_int][:tx][:queuelen] = $1
end
if line =~ /vlan id (\d+)/ || line =~ /vlan protocol ([\w\.]+) id (\d+)/
if $2
tmp_prot = $1
tmp_id = $2
else
tmp_id = $1
end
iface[tmp_int][:vlan] = Mash.new unless iface[tmp_int][:vlan]
iface[tmp_int][:vlan][:id] = tmp_id
iface[tmp_int][:vlan][:protocol] = tmp_prot if tmp_prot
vlan_flags = line.scan(/(REORDER_HDR|GVRP|LOOSE_BINDING)/)
if vlan_flags.length > 0
iface[tmp_int][:vlan][:flags] = vlan_flags.flatten.uniq
end
end
if line =~ /state (\w+)/
iface[tmp_int]["state"] = $1.downcase
end
end
iface
end
def match_iproute(iface, line, cint)
if line =~ IPROUTE_INT_REGEX
cint = $2
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
if line =~ /mtu (\d+)/
iface[cint][:mtu] = $1
end
flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|LOWER_UP|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)/)
if flags.length > 1
iface[cint][:flags] = flags.flatten.uniq
end
end
cint
end
def parse_ip_addr(iface)
so = shell_out("ip addr")
cint = nil
so.stdout.lines do |line|
cint = match_iproute(iface, line, cint)
parse_ip_addr_link_line(cint, iface, line)
cint = parse_ip_addr_inet_line(cint, iface, line)
parse_ip_addr_inet6_line(cint, iface, line)
end
end
def parse_ip_addr_link_line(cint, iface, line)
if line =~ /link\/(\w+) ([\da-f\:]+) /
iface[cint][:encapsulation] = linux_encaps_lookup($1)
unless $2 == "00:00:00:00:00:00"
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$2.upcase] = { "family" => "lladdr" }
end
end
end
def parse_ip_addr_inet_line(cint, iface, line)
if line =~ /inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?/
tmp_addr, tmp_prefix = $1, $3
tmp_prefix ||= "32"
original_int = nil
# Are we a formerly aliased interface?
if line =~ /#{cint}:(\d+)$/
sub_int = $1
alias_int = "#{cint}:#{sub_int}"
original_int = cint
cint = alias_int
end
iface[cint] = Mash.new unless iface[cint] # Create the fake alias interface if needed
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][tmp_addr] = { "family" => "inet", "prefixlen" => tmp_prefix }
iface[cint][:addresses][tmp_addr][:netmask] = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s
if line =~ /peer (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr][:peer] = $1
end
if line =~ /brd (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr][:broadcast] = $1
end
if line =~ /scope (\w+)/
iface[cint][:addresses][tmp_addr][:scope] = ($1.eql?("host") ? "Node" : $1.capitalize)
end
# If we found we were an alias interface, restore cint to its original value
cint = original_int unless original_int.nil?
end
cint
end
def parse_ip_addr_inet6_line(cint, iface, line)
if line =~ /inet6 ([a-f0-9\:]+)\/(\d+) scope (\w+)/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
tmp_addr = $1
iface[cint][:addresses][tmp_addr] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("host") ? "Node" : $3.capitalize) }
end
end
# returns the macaddress for interface from a hash of interfaces (iface elsewhere in this file)
def get_mac_for_interface(interfaces, interface)
interfaces[interface][:addresses].select { |k, v| v["family"] == "lladdr" }.first.first unless interfaces[interface][:addresses].nil? || interfaces[interface][:flags].include?("NOARP")
end
# returns the default route with the lowest metric (unspecified metric is 0)
def choose_default_route(routes)
routes.select do |r|
r[:destination] == "default"
end.sort do |x, y|
(x[:metric].nil? ? 0 : x[:metric].to_i) <=> (y[:metric].nil? ? 0 : y[:metric].to_i)
end.first
end
def interface_has_no_addresses_in_family?(iface, family)
return true if iface[:addresses].nil?
iface[:addresses].values.all? { |addr| addr["family"] != family }
end
def interface_have_address?(iface, address)
return false if iface[:addresses].nil?
iface[:addresses].key?(address)
end
def interface_address_not_link_level?(iface, address)
iface[:addresses][address][:scope].downcase != "link"
end
def interface_valid_for_route?(iface, address, family)
return true if interface_has_no_addresses_in_family?(iface, family)
interface_have_address?(iface, address) && interface_address_not_link_level?(iface, address)
end
def route_is_valid_default_route?(route, default_route)
# if the route destination is a default route, it's good
return true if route[:destination] == "default"
# the default route has a gateway and the route matches the gateway
!default_route[:via].nil? && IPAddress(route[:destination]).include?(IPAddress(default_route[:via]))
end
# ipv4/ipv6 routes are different enough that having a single algorithm to select the favored route for both creates unnecessary complexity
# this method attempts to deduce the route that is most important to the user, which is later used to deduce the favored values for {ip,mac,ip6}address
# we only consider routes that are default routes, or those routes that get us to the gateway for a default route
def favored_default_route(routes, iface, default_route, family)
routes.select do |r|
if family[:name] == "inet"
# the route must have a source address
next if r[:src].nil? || r[:src].empty?
# the interface specified in the route must exist
route_interface = iface[r[:dev]]
next if route_interface.nil? # the interface specified in the route must exist
# the interface must have no addresses, or if it has the source address, the address must not
# be a link-level address
next unless interface_valid_for_route?(route_interface, r[:src], "inet")
# the route must either be a default route, or it must have a gateway which is accessible via the route
next unless route_is_valid_default_route?(r, default_route)
true
elsif family[:name] == "inet6"
iface[r[:dev]] &&
iface[r[:dev]][:state] == "up" &&
route_is_valid_default_route?(r, default_route)
end
end.sort_by do |r|
# sorting the selected routes:
# - getting default routes first
# - then sort by metric
# - then by prefixlen
[
r[:destination] == "default" ? 0 : 1,
r[:metric].nil? ? 0 : r[:metric].to_i,
# for some reason IPAddress doesn't accept "::/0", it doesn't like prefix==0
# just a quick workaround: use 0 if IPAddress fails
begin
IPAddress( r[:destination] == "default" ? family[:default_route] : r[:destination] ).prefix
rescue
0
end,
]
end.first
end
# Both the network plugin and this plugin (linux/network) are run on linux. This plugin runs first.
# If the 'ip' binary is available, this plugin may set {ip,mac,ip6}address. The network plugin should not overwrite these.
# The older code section below that relies on the deprecated net-tools, e.g. netstat and ifconfig, provides less functionality.
collect_data(:linux) do
require "ipaddr"
iface = Mash.new
net_counters = Mash.new
network Mash.new unless network
network[:interfaces] = Mash.new unless network[:interfaces]
counters Mash.new unless counters
counters[:network] = Mash.new unless counters[:network]
# ohai.plugin[:network][:default_route_table] = 'default'
if configuration(:default_route_table).nil? || configuration(:default_route_table).empty?
default_route_table = "main"
else
default_route_table = configuration(:default_route_table)
end
Ohai::Log.debug("default route table is '#{default_route_table}'")
# Match the lead line for an interface from iproute2
# 3: eth0.11@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
# The '@eth0:' portion doesn't exist on primary interfaces and thus is optional in the regex
IPROUTE_INT_REGEX = /^(\d+): ([0-9a-zA-Z@:\.\-_]*?)(@[0-9a-zA-Z]+|):\s/ unless defined? IPROUTE_INT_REGEX
if iproute2_binary_available?
# families to get default routes from
families = [{
:name => "inet",
:default_route => "0.0.0.0/0",
:default_prefix => :default,
:neighbour_attribute => :arp,
}]
families << {
:name => "inet6",
:default_route => "::/0",
:default_prefix => :default_inet6,
:neighbour_attribute => :neighbour_inet6,
} if ipv6_enabled?
parse_ip_addr(iface)
iface = link_statistics(iface, net_counters)
families.each do |family|
neigh_attr = family[:neighbour_attribute]
default_prefix = family[:default_prefix]
iface = extract_neighbors(family, iface, neigh_attr)
iface = check_routing_table(family, iface, default_route_table)
routes = parse_routes(family, iface)
default_route = choose_default_route(routes)
if default_route.nil? || default_route.empty?
attribute_name = if family[:name] == "inet"
"default_interface"
else
"default_#{family[:name]}_interface"
end
Ohai::Log.debug("Unable to determine '#{attribute_name}' as no default routes were found for that interface family")
else
network["#{default_prefix}_interface"] = default_route[:dev]
Ohai::Log.debug("#{default_prefix}_interface set to #{default_route[:dev]}")
# setting gateway to 0.0.0.0 or :: if the default route is a link level one
network["#{default_prefix}_gateway"] = default_route[:via] ? default_route[:via] : family[:default_route].chomp("/0")
Ohai::Log.debug("#{default_prefix}_gateway set to #{network["#{default_prefix}_gateway"]}")
# deduce the default route the user most likely cares about to pick {ip,mac,ip6}address below
favored_route = favored_default_route(routes, iface, default_route, family)
# FIXME: This entire block should go away, and the network plugin should be the sole source of {ip,ip6,mac}address
# since we're at it, let's populate {ip,mac,ip6}address with the best values
# if we don't set these, the network plugin may set them afterwards
if favored_route && !favored_route.empty?
if family[:name] == "inet"
ipaddress favored_route[:src]
m = get_mac_for_interface(iface, favored_route[:dev])
Ohai::Log.debug("Overwriting macaddress #{macaddress} with #{m} from interface #{favored_route[:dev]}") if macaddress
macaddress m
elsif family[:name] == "inet6"
# this rarely does anything since we rarely have src for ipv6, so this usually falls back on the network plugin
ip6address favored_route[:src]
if macaddress
Ohai::Log.debug("Not setting macaddress from ipv6 interface #{favored_route[:dev]} because macaddress is already set")
else
macaddress get_mac_for_interface(iface, favored_route[:dev])
end
end
else
Ohai::Log.debug("the linux/network plugin was unable to deduce the favored default route for family '#{family[:name]}' despite finding a default route, and is not setting ipaddress/ip6address/macaddress. the network plugin may provide fallbacks.")
Ohai::Log.debug("this potential default route was excluded: #{default_route}")
end
end
end # end families.each
else # ip binary not available, falling back to net-tools, e.g. route, ifconfig
begin
so = shell_out("route -n")
route_result = so.stdout.split($/).grep( /^0.0.0.0/ )[0].split( /[ \t]+/ )
network[:default_gateway], network[:default_interface] = route_result.values_at(1, 7)
rescue Ohai::Exceptions::Exec
Ohai::Log.debug("Unable to determine default interface")
end
so = shell_out("ifconfig -a")
cint = nil
so.stdout.lines do |line|
tmp_addr = nil
# dev_valid_name in the kernel only excludes slashes, nulls, spaces
# http://git.kernel.org/?p=linux/kernel/git/stable/linux-stable.git;a=blob;f=net/core/dev.c#l851
if line =~ /^([0-9a-zA-Z@\.\:\-_]+)\s+/
cint = $1
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
end
if line =~ /Link encap:(Local Loopback)/ || line =~ /Link encap:(.+?)\s/
iface[cint][:encapsulation] = linux_encaps_lookup($1)
end
if line =~ /HWaddr (.+?)\s/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "lladdr" }
end
if line =~ /inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "inet" }
tmp_addr = $1
end
if line =~ /inet6 addr: ([a-f0-9\:]+)\/(\d+) Scope:(\w+)/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("Host") ? "Node" : $3) }
end
if line =~ /Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr]["broadcast"] = $1
end
if line =~ /Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr]["netmask"] = $1
end
flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)\s/)
if flags.length > 1
iface[cint][:flags] = flags.flatten
end
if line =~ /MTU:(\d+)/
iface[cint][:mtu] = $1
end
if line =~ /P-t-P:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:peer] = $1
end
if line =~ /RX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) frame:(\d+)/
net_counters[cint] = Mash.new unless net_counters[cint]
net_counters[cint][:rx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "frame" => $5 }
end
if line =~ /TX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) carrier:(\d+)/
net_counters[cint][:tx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "carrier" => $5 }
end
if line =~ /collisions:(\d+)/
net_counters[cint][:tx]["collisions"] = $1
end
if line =~ /txqueuelen:(\d+)/
net_counters[cint][:tx]["queuelen"] = $1
end
if line =~ /RX bytes:(\d+) \((\d+?\.\d+ .+?)\)/
net_counters[cint][:rx]["bytes"] = $1
end
if line =~ /TX bytes:(\d+) \((\d+?\.\d+ .+?)\)/
net_counters[cint][:tx]["bytes"] = $1
end
end
so = shell_out("arp -an")
so.stdout.lines do |line|
if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) \[(\w+)\] on ([0-9a-zA-Z\.\:\-]+)/
next unless iface[$4] # this should never happen
iface[$4][:arp] = Mash.new unless iface[$4][:arp]
iface[$4][:arp][$1] = $2.downcase
end
end
end # end "ip else net-tools" block
iface = ethernet_layer_one(iface)
counters[:network][:interfaces] = net_counters
network["interfaces"] = iface
end
end
| 39.346667 | 259 | 0.603143 |
611255214f47736f8b1c9f08c1e239aabf44ae2b | 1,663 | #
# Be sure to run `pod lib lint BlinkingLabel.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'BlinkingLabel'
s.version = '0.1.0'
s.summary = 'A subclass on UILabel that provides a blink'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'This CocoaPod provides the ability to use a UILabel that may be started and stopped blinking.'
s.homepage = 'https://github.com/iamlordvodemort/BlinkingLabel'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Iamlordvoldemort' => '[email protected]' }
s.source = { :git => 'https://github.com/iamlordvodemort/BlinkingLabel.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'BlinkingLabel/Classes/**/*'
# s.resource_bundles = {
# 'BlinkingLabel' => ['BlinkingLabel/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 40.560976 | 118 | 0.662658 |
6223446decdba9eb94707db20fadacd953562739 | 1,484 | module HisAdapter
module Soap
class Client
class ApiNotFoundError < StandardError; end
attr_accessor :client, :adapter
def initialize(adapter:, **options)
@adapter = adapter.to_s
@client = Savon.client(wsdl: wsdl, **options)
end
def request(api, params = nil, **options)
parameter = ::HisAdapter::Parameter.new(api,
params,
adapter: adapter)
request = ::HisAdapter::Soap::Request.new(api,
parameter,
adapter: adapter,
client: client,
**options)
raw_response = request.call
Soap::Response.new(request, raw_response)
end
# 构建请求,但实际上没有调用
def build_request(api, params, **options)
parameter = ::HisAdapter::Parameter.new(api, params, adapter: adapter)
::HisAdapter::Soap::Request.new(api,
parameter,
adapter: adapter,
client: client,
**options).build
end
def config
@config ||= ::HisAdapter.config[adapter]
end
def wsdl
config["wsdl"]
end
end
end
end
| 29.098039 | 78 | 0.433962 |
18c7cf22dbc085e1b3cd9713b34b805a9991a8c2 | 585 | cask 'remembear' do
version '0.4.2'
sha256 '6f07a01e4b9f22c0a6359c81ee5ad0fec8266ae8d99ba6ae326b79ff123d08fa'
# amazonaws.com/tunnelbear/downloads/mac/remembear was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/tunnelbear/downloads/mac/remembear/RememBear-#{version}.zip"
appcast 'https://tunnelbear.s3.amazonaws.com/downloads/mac/remembear/appcast-beta.xml',
checkpoint: 'd1aa1b758e2dea1903f245fa89307f478011cc5ee123262f9bef2aed23007a69'
name 'RememBear'
homepage 'https://www.remembear.com/'
app 'RememBear.app'
end
| 41.785714 | 111 | 0.791453 |
ffc91dda117fee4031bb3639b4c849966d19be92 | 5,829 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_11_09_162417) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.bigint "record_id", null: false
t.bigint "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "agreements", force: :cascade do |t|
t.string "title"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "carriers", force: :cascade do |t|
t.string "item_id"
t.string "name"
t.string "manufacturer"
t.string "model"
t.string "color"
t.string "size"
t.integer "default_loan_length_days", default: 30
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
t.bigint "home_location_id", null: false
t.bigint "current_location_id", null: false
t.integer "status", default: 0, null: false
t.string "safety_link"
t.index ["current_location_id"], name: "index_carriers_on_current_location_id"
t.index ["home_location_id"], name: "index_carriers_on_home_location_id"
end
create_table "categories", force: :cascade do |t|
t.string "name", null: false
t.string "description"
t.bigint "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["parent_id"], name: "index_categories_on_parent_id"
end
create_table "fee_types", force: :cascade do |t|
t.string "name", null: false
t.integer "amount"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "loans", force: :cascade do |t|
t.integer "carrier_id"
t.date "due_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "checkin_volunteer_id"
t.bigint "checkout_volunteer_id"
t.bigint "member_id", null: false
t.datetime "returned_at"
t.index ["checkin_volunteer_id"], name: "index_loans_on_checkin_volunteer_id"
t.index ["checkout_volunteer_id"], name: "index_loans_on_checkout_volunteer_id"
t.index ["member_id"], name: "index_loans_on_member_id"
end
create_table "locations", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "membership_types", force: :cascade do |t|
t.string "name"
t.integer "fee_cents"
t.integer "duration_days"
t.integer "number_of_items"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "signed_agreements", force: :cascade do |t|
t.bigint "user_id"
t.bigint "agreement_id"
t.string "signature"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["agreement_id"], name: "index_signed_agreements_on_agreement_id"
t.index ["user_id"], name: "index_signed_agreements_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "street_address", null: false
t.string "street_address_second"
t.string "city", null: false
t.string "state", null: false
t.string "postal_code", null: false
t.string "phone_number", null: false
t.datetime "deactivated_at"
t.string "first_name"
t.string "last_name"
t.integer "role", default: 2, null: false
t.index ["deactivated_at"], name: "index_users_on_deactivated_at"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "carriers", "locations", column: "current_location_id"
add_foreign_key "carriers", "locations", column: "home_location_id"
add_foreign_key "loans", "users", column: "checkin_volunteer_id"
add_foreign_key "loans", "users", column: "checkout_volunteer_id"
add_foreign_key "loans", "users", column: "member_id"
end
| 38.602649 | 126 | 0.715389 |
d55455475f232f1f19d19c1cb8dca3fd0cf163ea | 1,442 | require 'test_helper'
include Scrivito::ControllerHelper
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
login = LoginPage.instance
@login_path = "/#{login.slug + login.id}"
end
test "SSL login with invalid information" do
https!
get @login_path
assert_template 'login_page/index'
post session_path, params: { email: "", password: "" }
assert_redirected_to @login_path
assert_not flash.empty?
https! false
get @login_path
assert_response :success
assert flash.present?
end
test "login with valid information" do
get @login_path
post session_path, params: { email: ENV['SCRIVITO_EMAIL'],
password: ENV["SCRIVITO_PASSWORD"] }
assert_redirected_to scrivito_path(Obj.root)
assert_equal session[:user] , ENV['SCRIVITO_EMAIL']
follow_redirect!
assert_template "plain_page/index"
end
test "successful login followed by logout with friendly fowordings" do
test_url = "/kata"
get test_url
get @login_path
post session_path, params: { email: ENV['SCRIVITO_EMAIL'],
password: ENV["SCRIVITO_PASSWORD"] }
assert_redirected_to test_url
follow_redirect!
# assert_template "blog_post_page/index.html"
assert_equal test_url, path
get "/logout"
assert_redirected_to test_url
follow_redirect!
assert_equal test_url, path
end
end
| 27.730769 | 72 | 0.685853 |
1cbc7cb4a669b6eefa9efbe7cbed348f9447e13e | 4,944 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
class TestTable < Test::Unit::TestCase
include Helper::Buildable
sub_test_case(".new") do
def test_valid
fields = [
Arrow::Field.new("visible", Arrow::BooleanDataType.new),
Arrow::Field.new("valid", Arrow::BooleanDataType.new),
]
schema = Arrow::Schema.new(fields)
columns = [
build_boolean_array([true]),
build_boolean_array([false]),
]
record_batch = Arrow::RecordBatch.new(schema, 1, columns)
assert_equal(1, record_batch.n_rows)
end
def test_no_columns
fields = [
Arrow::Field.new("visible", Arrow::BooleanDataType.new),
]
schema = Arrow::Schema.new(fields)
message = "[record-batch][new]: " +
"Invalid: Number of columns did not match schema"
assert_raise(Arrow::Error::Invalid.new(message)) do
Arrow::RecordBatch.new(schema, 0, [])
end
end
end
sub_test_case("instance methods") do
def setup
@visible_field = Arrow::Field.new("visible", Arrow::BooleanDataType.new)
@visible_values = [true, false, true, false, true]
@valid_field = Arrow::Field.new("valid", Arrow::BooleanDataType.new)
@valid_values = [false, true, false, true, false]
fields = [
@visible_field,
@valid_field,
]
schema = Arrow::Schema.new(fields)
columns = [
build_boolean_array(@visible_values),
build_boolean_array(@valid_values),
]
@record_batch = Arrow::RecordBatch.new(schema,
@visible_values.size,
columns)
end
def test_equal
fields = [
Arrow::Field.new("visible", Arrow::BooleanDataType.new),
Arrow::Field.new("valid", Arrow::BooleanDataType.new),
]
schema = Arrow::Schema.new(fields)
columns = [
build_boolean_array([true, false, true, false, true]),
build_boolean_array([false, true, false, true, false]),
]
other_record_batch = Arrow::RecordBatch.new(schema, 5, columns)
assert_equal(@record_batch,
other_record_batch)
end
def test_schema
assert_equal(["visible", "valid"],
@record_batch.schema.fields.collect(&:name))
end
sub_test_case("#column") do
def test_positive
assert_equal(build_boolean_array(@valid_values),
@record_batch.get_column(1))
end
def test_negative
assert_equal(build_boolean_array(@visible_values),
@record_batch.get_column(-2))
end
def test_positive_out_of_index
assert_nil(@record_batch.get_column(2))
end
def test_negative_out_of_index
assert_nil(@record_batch.get_column(-3))
end
end
def test_columns
assert_equal([5, 5],
@record_batch.columns.collect(&:length))
end
def test_n_columns
assert_equal(2, @record_batch.n_columns)
end
def test_n_rows
assert_equal(5, @record_batch.n_rows)
end
def test_slice
sub_record_batch = @record_batch.slice(3, 2)
sub_visible_values = sub_record_batch.n_rows.times.collect do |i|
sub_record_batch.get_column(0).get_value(i)
end
assert_equal([false, true],
sub_visible_values)
end
def test_to_s
assert_equal(<<-PRETTY_PRINT, @record_batch.to_s)
visible: [
true,
false,
true,
false,
true
]
valid: [
false,
true,
false,
true,
false
]
PRETTY_PRINT
end
def test_add_column
field = Arrow::Field.new("added", Arrow::BooleanDataType.new)
column = build_boolean_array([false, false, true, true, true])
new_record_batch = @record_batch.add_column(1, field, column)
assert_equal(["visible", "added", "valid"],
new_record_batch.schema.fields.collect(&:name))
end
def test_remove_column
new_record_batch = @record_batch.remove_column(0)
assert_equal(["valid"],
new_record_batch.schema.fields.collect(&:name))
end
end
end
| 29.783133 | 78 | 0.632888 |
87e975a076f0efc5477dbf7cd3734a41b0e755e4 | 395 | LatoPages::Engine.routes.draw do
root 'back/pages#index'
resources :pages, module: 'back'
scope '/api/v1/' do
get 'fields', to: 'api/v1/fields#index'
get 'fields/:page', to: 'api/v1/fields#index'
get 'fields/:page/:lang', to: 'api/v1/fields#index'
get 'field/:name/:page', to: 'api/v1/fields#show'
get 'field/:name/:page/:lang', to: 'api/v1/fields#show'
end
end
| 23.235294 | 59 | 0.632911 |
6a1bf6735f071d71725782d385f2cdd842385eb3 | 288 | FactoryGirl.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_historical_report/factories'
end
| 41.142857 | 130 | 0.795139 |
21efdb4f9933418cb12c38f974092c5c5881ecf9 | 1,278 | # frozen_string_literal: true
module ElasticAPM
# @api private
module Spies
# @api private
class MongoSpy
def install
::Mongo::Monitoring::Global.subscribe(
::Mongo::Monitoring::COMMAND,
Subscriber.new
)
end
# @api private
class Subscriber
TYPE = 'db.mongodb.query'.freeze
def initialize
@events = {}
end
def started(event)
push_event(event)
end
def failed(event)
pop_event(event)
end
def succeeded(event)
pop_event(event)
end
private
def push_event(event)
return unless ElasticAPM.current_transaction
ctx = Span::Context.new(
instance: event.database_name,
statement: nil,
type: 'mongodb'.freeze,
user: nil
)
span = ElasticAPM.span(event.command_name, TYPE, context: ctx)
@events[event.operation_id] = span
end
def pop_event(event)
return unless ElasticAPM.current_transaction
span = @events.delete(event.operation_id)
span && span.done
end
end
end
register 'Mongo', 'mongo', MongoSpy.new
end
end
| 20.612903 | 72 | 0.550078 |
871934d96774cbf8302ee19aaec50608821a8e21 | 1,003 | require "language/node"
class GatsbyCli < Formula
desc "Gatsby command-line interface"
homepage "https://www.gatsbyjs.org/docs/gatsby-cli/"
url "https://registry.npmjs.org/gatsby-cli/-/gatsby-cli-2.11.1.tgz"
sha256 "9ed953e5195cfdcd7d7ce55c22dff2c10f02627abd95b7accdea8947dc40e824"
bottle do
cellar :any_skip_relocation
sha256 "a5b342a5194424d62ac5f0baaf523eae190b30393247a2c861c80e8fc6d59da1" => :catalina
sha256 "688183236bf8eda318fe2f48c68b9147606a3c1df03ca8e3443352b6355337d5" => :mojave
sha256 "28677bbf9226ba26a8c28807b2849ac6ba5fb27fd583f27af0d2fd51c0df2eb3" => :high_sierra
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system bin/"gatsby", "new", "hello-world", "https://github.com/gatsbyjs/gatsby-starter-hello-world"
assert_predicate testpath/"hello-world/package.json", :exist?, "package.json was not cloned"
end
end
| 35.821429 | 103 | 0.768694 |
ac3e386953fcea36a96d0792caaf3825caafb8b9 | 1,054 | module Blobsterix
module Jsonizer
def json_var(*var_names)
@json_vars = (@json_vars||[])+var_names.flatten
end
def json_vars
@json_vars||= []
end
module Methods
def render_json(obj=nil)
Http.OK (obj||self).to_json, "json"
end
def render_xml(obj=nil)
obj = Nokogiri::XML::Builder.new do |xml|
yield xml
end if block_given?
Http.OK (obj||self).to_xml, "xml"
end
def to_json
stuff = Hash.new
self.class.json_vars.each{|var_name|
stuff[var_name.to_sym]=send(var_name) if respond_to?(var_name)
}
stuff.to_json
end
def to_xml()
xml = Nokogiri::XML::Builder.new do |xml|
xml.BlobsterixStatus() {
self.class.json_vars.each{|var_name|
var = send(var_name)
var = var.to_xml if var.respond_to?(:to_xml)
xml.send(var_name, var) if respond_to?(var_name)
}
}
end
xml.to_xml
end
end
end
end | 23.422222 | 72 | 0.553131 |
bba06c3dd47c6f25e68c4938ed83ad8633fbc602 | 55 | module RadiantCommentsExtension
VERSION = '1.0.2'
end | 18.333333 | 31 | 0.781818 |
4ad233e4b68193e3832ce3f4a7333923eb7eecd4 | 1,124 |
default['dev-stack']['app']['root_dir'] = '/vagrant'
default['dev-stack']['app']['fqdn'] = 'rails.dev'
# This is used in the upstream in the nginx config. It assumes the default Rails port of 4000
default['dev-stack']['nginx']['rails_upstream'] = 'localhost:3000'
# If you are using unicorn, then you need to set it to something like
# You don't need to uncomment this. Set this in the Vagrantfile to override
# the default.
# default['dev-stack']['nginx']['rails_upstream'] = "unix:/vagrant/tmp/sockets/unicorn.sock"
default['dev-stack']['ruby']['version'] = '1.9.3-p547'
# For building or caching datasets
default['dev-stack']['cache_dir'] = '/vagrant/.vagrant/cache'
default['dev-stack']['rails']['postgresql']['development_name'] = 'dev-stack-development'
default['dev-stack']['rails']['postgresql']['test_name'] = 'dev-stack-test'
default['dev-stack']['rails']['postgresql']['username'] = 'vagrant'
default['dev-stack']['rails']['postgresql']['password'] = 'vagrant'
default['dev-stack']['rails']['postgresql']['template'] = 'template0'
default['dev-stack']['rails']['postgresql']['encoding'] = 'UTF8'
| 46.833333 | 93 | 0.685053 |
e28c9de56ce674e7c62bf33e4887fd925c95f005 | 4,485 | module ActsAsTaggableOn::Taggable
module Ownership
def self.included(base)
base.extend ActsAsTaggableOn::Taggable::Ownership::ClassMethods
base.class_eval do
after_save :save_owned_tags
end
base.initialize_acts_as_taggable_on_ownership
end
module ClassMethods
def acts_as_taggable_on(*args)
initialize_acts_as_taggable_on_ownership
super(*args)
end
def initialize_acts_as_taggable_on_ownership
tag_types.map(&:to_s).each do |tag_type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{tag_type}_from(owner)
owner_tag_list_on(owner, '#{tag_type}')
end
RUBY
end
end
end
def owner_tags_on(owner, context)
if owner.nil?
scope = base_tags.where([%(#{namespaced_class(:Tagging).table_name}.context = ?), context.to_s])
else
scope = base_tags.where([%(#{namespaced_class(:Tagging).table_name}.context = ? AND
#{namespaced_class(:Tagging).table_name}.tagger_id = ? AND
#{namespaced_class(:Tagging).table_name}.tagger_type = ?), context.to_s, owner.id, owner.class.base_class.to_s])
end
# when preserving tag order, return tags in created order
# if we added the order to the association this would always apply
if self.class.preserve_tag_order?
scope.order("#{namespaced_class(:Tagging).table_name}.id")
else
scope
end
end
def cached_owned_tag_list_on(context)
variable_name = "@owned_#{context}_list"
(instance_variable_defined?(variable_name) && instance_variable_get(variable_name)) || instance_variable_set(variable_name, {})
end
def owner_tag_list_on(owner, context)
add_custom_context(context)
cache = cached_owned_tag_list_on(context)
cache[owner] ||= ActsAsTaggableOn::TagList.new(*owner_tags_on(owner, context).map(&:name))
end
def set_owner_tag_list_on(owner, context, new_list)
add_custom_context(context)
cache = cached_owned_tag_list_on(context)
cache[owner] = ActsAsTaggableOn.default_parser.new(new_list).parse
end
def reload(*args)
self.class.tag_types.each do |context|
instance_variable_set("@owned_#{context}_list", nil)
end
super(*args)
end
def save_owned_tags
tagging_contexts.each do |context|
cached_owned_tag_list_on(context).each do |owner, tag_list|
# Find existing tags or create non-existing tags:
tags = find_or_create_tags_from_list_with_context(tag_list.uniq, context)
# Tag objects for owned tags
owned_tags = owner_tags_on(owner, context).to_a
# Tag maintenance based on whether preserving the created order of tags
if self.class.preserve_tag_order?
old_tags, new_tags = owned_tags - tags, tags - owned_tags
shared_tags = owned_tags & tags
if shared_tags.any? && tags[0...shared_tags.size] != shared_tags
index = shared_tags.each_with_index { |_, i| break i unless shared_tags[i] == tags[i] }
# Update arrays of tag objects
old_tags |= owned_tags.from(index)
new_tags |= owned_tags.from(index) & shared_tags
# Order the array of tag objects to match the tag list
new_tags = tags.map { |t| new_tags.find { |n| n.name.downcase == t.name.downcase } }.compact
end
else
# Delete discarded tags and create new tags
old_tags = owned_tags - tags
new_tags = tags - owned_tags
end
# Find all taggings that belong to the taggable (self), are owned by the owner,
# have the correct context, and are removed from the list.
namespaced_class(:Tagging).destroy_all(taggable_id: id, taggable_type: self.class.base_class.to_s,
tagger_type: owner.class.base_class.to_s, tagger_id: owner.id,
namespaced(:tag_id) => old_tags, context: context) if old_tags.present?
# Create new taggings:
new_tags.each do |tag|
taggings.create!(namespaced(:tag_id) => tag.id, context: context.to_s, tagger: owner, taggable: self)
end
end
end
true
end
end
end
| 35.595238 | 148 | 0.626979 |
4a5b914835dd441b2e8513e05697439fd85f0c3f | 238 | require 'fileutils'
# copies js file into public/javascripts folder
FileUtils.cp File.join(File.dirname(__FILE__), 'javascripts/js_mouse_keyboard_interaction.js'), File.join(File.dirname(__FILE__), '../../../../../../public/javascripts') | 79.333333 | 169 | 0.752101 |
6a9b02712ffce8efd465eb1f87fe48bd696b818c | 689 | #!/usr/bin/env ruby
require 'tempfile'
def build(input, out)
File.readlines(input).each do |line|
if relative_path = line[/^require_relative\s+(["'])(\S+)\1$/, 2]
path = File.join(File.dirname(input), relative_path)
path += ".rb"
build(path, out)
out.puts
else
out.print line
end
end
end
start = "src/main.rb"
output = "bin/check-codeowners"
Tempfile.open('build', File.dirname(output)) do |out|
out.print <<~INTRO
#!/usr/bin/env ruby
# This is a generated file; for the source, see 'src'.
# Build with "ruby ./script/build.rb"
INTRO
build(start, out)
out.chmod 0o755
out.flush
File.rename out.path, output
end
| 19.138889 | 68 | 0.629898 |
1117225759e088c90b40345ebaa37498c6ef264c | 7,144 | =begin
#Topological Inventory Ingress API
#Topological Inventory Ingress API
The version of the OpenAPI document: 0.0.2
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.1
=end
require 'date'
module TopologicalInventoryIngressApiClient
class TagReferenceReference
attr_accessor :name
attr_accessor :namespace
attr_accessor :value
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'name',
:'namespace' => :'namespace',
:'value' => :'value'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'name' => :'String',
:'namespace' => :'String',
:'value' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `TopologicalInventoryIngressApiClient::TagReferenceReference` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `TopologicalInventoryIngressApiClient::TagReferenceReference`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'namespace')
self.namespace = attributes[:'namespace']
end
if attributes.key?(:'value')
self.value = attributes[:'value']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @name.nil?
invalid_properties.push('invalid value for "name", name cannot be nil.')
end
if @namespace.nil?
invalid_properties.push('invalid value for "namespace", namespace cannot be nil.')
end
if @value.nil?
invalid_properties.push('invalid value for "value", value cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @name.nil?
return false if @namespace.nil?
return false if @value.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name &&
namespace == o.namespace &&
value == o.value
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[name, namespace, value].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
TopologicalInventoryIngressApiClient.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.766667 | 237 | 0.6229 |
62e4c19eb856766aec8b492f6065af14060e9fc2 | 244 | cask "desktoputility" do
version :latest
sha256 :no_check
url "https://sweetpproductions.com/products/desktoputility/DesktopUtility.dmg"
name "DesktopUtility"
homepage "https://sweetpproductions.com/"
app "DesktopUtility.app"
end
| 22.181818 | 80 | 0.770492 |
aceed2eacde7286c876edb5f3c0009688b89162f | 3,469 | module LandingPageVersion::Section
class Listings < Base
ATTRIBUTES = [
:id,
:kind,
:title,
:paragraph,
:button_color,
:button_color_hover,
:button_title,
:button_path,
:price_color,
:no_listing_image_background_color,
:no_listing_image_text,
:author_name_color_hover,
:listings
].freeze
PERMITTED_PARAMS = [
:kind,
:id,
:previous_id,
:title,
:paragraph,
:cta_enabled,
:button_title,
:button_path_string,
:listing_1_id,
:listing_2_id,
:listing_3_id
].freeze
DEFAULTS = {
kind: "listings",
title: nil,
paragraph: nil,
button_color: {type: "marketplace_data", id: "primary_color"},
button_color_hover: {type: "marketplace_data", id: "primary_color_darken"},
button_title: nil,
button_path: {type: "path", id: "search"},
price_color: {type: "marketplace_data", id: "primary_color"},
no_listing_image_background_color: {type: "marketplace_data", id: "primary_color"},
no_listing_image_text: {type: "translation", id: "no_listing_image"},
author_name_color_hover: {type: "marketplace_data", id: "primary_color"},
'listings' => [
{
'listing' => { 'type' => 'listing', 'id' => nil }
},
{
'listing' => { 'type' => 'listing', 'id' => nil }
},
{
'listing' => { 'type' => 'listing', 'id' => nil }
}
]
}.freeze
attr_accessor(*(ATTRIBUTES + HELPER_ATTRIBUTES))
validates_each :listing_1_id, :listing_2_id, :listing_3_id do |record, attr, value|
unless record.landing_page_version.community.listings.where(id: value).any?
record.errors.add attr, :listing_with_this_id_does_not_exist
end
end
before_save :check_extra_attributes
def initialize(attributes={})
self.listings = DEFAULTS['listings']
super(attributes)
DEFAULTS.each do |key, value|
unless self.send(key)
self.send("#{key}=", value)
end
end
end
def attributes
Hash[ATTRIBUTES.map {|x| [x.to_s, nil]}]
end
def cta_enabled
return @cta_enabled if defined?(@cta_enabled)
@cta_enabled = button_title.present?
end
def cta_enabled=(value)
@cta_enabled = value != '0'
end
def button_path_string=(value)
self.button_path = {'value' => value}
end
def button_path_string
button_path&.[]('value')
end
def check_extra_attributes
unless cta_enabled
self.button_title = nil
self.button_path = nil
end
end
def i18n_key
'listings'
end
def listing_1_id
listing_id(0)
end
def listing_2_id
listing_id(1)
end
def listing_3_id
listing_id(2)
end
def listing_1_id=(value)
set_listing_id(0, value)
end
def listing_2_id=(value)
set_listing_id(1, value)
end
def listing_3_id=(value)
set_listing_id(2, value)
end
def listing_id(index)
listings[index]['listing']['id']
end
def set_listing_id(index, value)
listings[index]['listing']['id'] = value
end
def removable?
true
end
class << self
def new_from_content(content_section)
new(content_section)
end
def permitted_params
PERMITTED_PARAMS
end
end
end
end
| 21.955696 | 89 | 0.595849 |
f7988a61893133774798ba847201e696c3109c4a | 1,633 | # frozen_string_literal: true
require 'sidekiq'
module VBADocuments
class UploadScanner
include Sidekiq::Worker
def perform
return unless Settings.vba_documents.s3.enabled
VBADocuments::UploadSubmission.where(status: 'pending').find_each do |upload|
processed = process(upload)
expire(upload) unless processed
end
rescue => e
Rails.logger.error("Error in upload scanner #{e.message}", e)
end
private
def process(upload)
Rails.logger.info("VBADocuments: Processing: #{upload.inspect}")
object = bucket.object(upload.guid)
return false unless object.exists?
upload.update(status: 'uploaded')
VBADocuments::UploadProcessor.perform_async(upload.guid, caller: self.class.name)
true
end
def expire(upload)
upload.update(status: 'expired') if upload.created_at < Time.zone.now - 20.minutes
end
def bucket
@bucket ||= begin
s3 = Aws::S3::Resource.new(region: Settings.vba_documents.s3.region,
access_key_id: Settings.vba_documents.s3.aws_access_key_id,
secret_access_key: Settings.vba_documents.s3.aws_secret_access_key)
s3.bucket(Settings.vba_documents.s3.bucket)
end
end
end
end
# def again
# load('./modules/vba_documents/app/workers/vba_documents/upload_processor.rb')
# load('./modules/vba_documents/app/workers/vba_documents/upload_scanner.rb')
# g = "0f35783e-4b33-4e22-b64f-9a50eb391b49"
#
# u = UploadSubmission.find_by_guid(@g)
# u.status = 'pending'
# u.save
# UploadScanner.new.perform
# end
| 29.160714 | 102 | 0.679731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.