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
|
---|---|---|---|---|---|
b9fa2f6908d8a8e0184241063cd5d9b77975e73f | 789 | require_relative "../../lib/commands/rotate"
require_relative "../../lib/tt_robot"
require_relative "../../lib/tt_robot/robot"
require_relative "../../lib/tt_robot/output"
RSpec.describe Rotate do
let(:output) { Output.new }
let(:robot) { Robot.new(output) }
let(:rotate) { described_class.new(robot) }
context "initialization" do
it "should be an instance of Rotate" do
expect(rotate).to be_a Rotate
end
it "should store a robot" do
expect(rotate.robot).to eq(robot)
end
end
describe ".set_direction" do
it "should set robot direction" do
command_hash = { position: { x: 3, y: 3 }, direction: "NORTH" }
robot.place(command_hash)
rotate.run({ command: "LEFT" })
expect(robot.direction).to eq("EAST")
end
end
end
| 27.206897 | 69 | 0.656527 |
e9b1f97ad61bf07df464b0b2867b3515f344d157 | 384 | # encoding: UTF-8
require "rubygems"
require "bundler"
Bundler.require(:default)
Bundler.require(Sinatra::Base.environment)
require 'load_path'
LoadPath.configure do
add sibling_directory('lib')
add sibling_directory('config')
end
require 'logging.cfg'
require 'db'
require 'controllers/redirects_controller'
require 'controllers/redirects_api_controller' | 21.333333 | 46 | 0.757813 |
abd3742816540d42f7d0111fecb3c099160fb0a9 | 257 | spec('2.0.0') do
configuration('my-configuration') do
override 'OVERRIDE', '1'
type 'debug'
end
target('my-target') do
type :application
source_dir 'support_files/abc'
configuration do end
end
variant('$base') do
target(123) do end
end
end | 18.357143 | 37 | 0.696498 |
2150adc45e4051eb285b4b025dc77d170992ef7a | 599 | require 'spec_helper'
describe "time_chunks/new" do
before(:each) do
assign(:time_chunk, stub_model(TimeChunk,
:source_id => "MyString",
:date_time => ""
).as_new_record)
end
it "renders new time_chunk form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => time_chunks_path, :method => "post" do
assert_select "input#time_chunk_source_id", :name => "time_chunk[source_id]"
assert_select "input#time_chunk_date_time", :name => "time_chunk[date_time]"
end
end
end
| 28.52381 | 87 | 0.687813 |
6292cc62b73614f807cf9efe35ce952840536272 | 1,170 | class UsersController < ApplicationController
get '/signup' do
if !session[:user_id]
erb :'users/create_user'
else
redirect to ('/trackers')
end
end
post '/signup' do
@user = User.new(params)
if [email protected]
# binding.pry
@errors = @user.errors.full_messages
erb :'users/create_user'
else
session[:user_id] = @user.id
redirect to ('/trackers')
end
end
get '/signin' do
if !session[:user_id]
erb :'users/signin'
else
redirect to '/trackers' #index
end
end
post '/signin' do
@user = User.find_by(email: params[:email])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect to '/trackers'
else
@errors = "Invalid email or password"
erb :'users/signin'
end
end
get '/signout' do
if logged_in?
session.clear
redirect to '/signin'
else
redirect to '/'
end
end
end | 22.5 | 57 | 0.493162 |
21f9445ac31ba97071a11a60f7bae0ca7890b395 | 1,168 | require 'puppet_labs/trello/trello_issue_job'
require 'puppet_labs/github/controller'
module PuppetLabs
module Github
class IssueController < Controller
attr_reader :issue
def initialize(options = {})
super(options)
if issue = options[:issue]
@issue = issue
end
end
##
# run processes the issue and queues up an issue job.
#
# @return [Array] containing the Sinatra route style [status, headers_hsh, body_hsh]
def run
case issue.action
when "opened"
job = PuppetLabs::Trello::TrelloIssueJob.new
job.issue = issue
delayed_job = job.queue
logger.info "Successfully queued up opened issue #{issue.repo_name}/#{issue.number} as job #{delayed_job.id}"
body = {
'job_id' => delayed_job.id,
'queue' => delayed_job.queue,
'priority' => delayed_job.priority,
'created_at' => delayed_job.created_at,
}
return [ACCEPTED, {}, body]
else
logger.info "Ignoring issue #{issue.repo_name}/#{issue.number} because the action is #{issue.action}."
body = { 'message' => 'Action has been ignored.' }
return [OK, {}, body]
end
end
end
end
end
| 27.162791 | 115 | 0.65411 |
62b5b6f70787bf87511b95bf59ac5cd6c84ec90e | 100 | json.extract! @hydroponic, :id, :fecha, :descripcion, :costo, :materiales, :created_at, :updated_at
| 50 | 99 | 0.74 |
1ce53ff57a200da8d8a39a06f94435ad9108ed9b | 135 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_src_session'
| 33.75 | 73 | 0.8 |
e8e9ba49f20557daaa98612ef05d775530b229d8 | 1,133 | describe :net_httpheader_set_form_data, :shared => true do
before(:each) do
@headers = NetHTTPHeaderSpecs::Example.new
end
describe "when passed params" do
it "automatically set the 'Content-Type' to 'application/x-www-form-urlencoded'" do
@headers.send(@method, "cmd" => "search", "q" => "ruby", "max" => "50")
@headers["Content-Type"].should == "application/x-www-form-urlencoded"
end
it "sets self's body based on the passed form parameters" do
@headers.send(@method, "cmd" => "search", "q" => "ruby", "max" => "50")
@headers.body.split("&").should == ["max=50", "cmd=search", "q=ruby"]
end
end
describe "when passed params, separator" do
it "sets self's body based on the passed form parameters and the passed separator" do
@headers.send(@method, {"cmd" => "search", "q" => "ruby", "max" => "50"}, "&")
@headers.body.split("&").should == ["max=50", "cmd=search", "q=ruby"]
@headers.send(@method, {"cmd" => "search", "q" => "ruby", "max" => "50"}, ";")
@headers.body.split(";").should == ["max=50", "cmd=search", "q=ruby"]
end
end
end | 41.962963 | 89 | 0.597529 |
e2bb378f663c3adf71a6dfb0dffbeab5d3c34d37 | 2,795 | require 'spec_helper'
describe Gitlab::Ci::Status::Build::Play do
let(:user) { create(:user) }
let(:project) { create(:project, :stubbed_repository) }
let(:build) { create(:ci_build, :manual, project: project) }
let(:status) { Gitlab::Ci::Status::Core.new(build, user) }
subject { described_class.new(status) }
describe '#label' do
it 'has a label that says it is a manual action' do
expect(subject.label).to eq 'manual play action'
end
end
describe '#status_tooltip' do
it 'does not override status status_tooltip' do
expect(status).to receive(:status_tooltip)
subject.status_tooltip
end
end
describe '#badge_tooltip' do
it 'does not override status badge_tooltip' do
expect(status).to receive(:badge_tooltip)
subject.badge_tooltip
end
end
describe '#has_action?' do
context 'when user is allowed to update build' do
context 'when user is allowed to trigger protected action' do
before do
project.add_developer(user)
create(:protected_branch, :developers_can_merge,
name: build.ref, project: project)
end
it { is_expected.to have_action }
end
context 'when user can not push to the branch' do
before do
build.project.add_developer(user)
create(:protected_branch, :masters_can_push,
name: build.ref, project: project)
end
it { is_expected.not_to have_action }
end
end
context 'when user is not allowed to update build' do
it { is_expected.not_to have_action }
end
end
describe '#action_path' do
it { expect(subject.action_path).to include "#{build.id}/play" }
end
describe '#action_icon' do
it { expect(subject.action_icon).to eq 'play' }
end
describe '#action_title' do
it { expect(subject.action_title).to eq 'Play' }
end
describe '#action_button_title' do
it { expect(subject.action_button_title).to eq 'Trigger this manual action' }
end
describe '.matches?' do
subject { described_class.matches?(build, user) }
context 'when build is playable' do
context 'when build stops an environment' do
let(:build) do
create(:ci_build, :playable, :teardown_environment)
end
it 'does not match' do
expect(subject).to be false
end
end
context 'when build does not stop an environment' do
let(:build) { create(:ci_build, :playable) }
it 'is a correct match' do
expect(subject).to be true
end
end
end
context 'when build is not playable' do
let(:build) { create(:ci_build) }
it 'does not match' do
expect(subject).to be false
end
end
end
end
| 25.409091 | 81 | 0.638283 |
d5289bf5c39b77468d148abc4a33332b61160bbb | 358 | class CreateRelationships < ActiveRecord::Migration[5.1]
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
end
end
| 25.571429 | 70 | 0.731844 |
ac0ced0775d2cf1b6d2b2520f3a25ab18786bd9e | 682 | require 'chefspec'
describe 'gem_package::upgrade' do
platform 'ubuntu'
describe 'upgrades a gem_package with an explicit action' do
it { is_expected.to upgrade_gem_package('explicit_action') }
it { is_expected.to_not upgrade_gem_package('not_explicit_action') }
end
describe 'upgrades a gem_package with attributes' do
it { is_expected.to upgrade_gem_package('with_attributes').with(version: '1.0.0') }
it { is_expected.to_not upgrade_gem_package('with_attributes').with(version: '1.2.3') }
end
describe 'upgrades a gem_package when specifying the identity attribute' do
it { is_expected.to upgrade_gem_package('identity_attribute') }
end
end
| 34.1 | 91 | 0.755132 |
9102763041b13e4c1ade81f1e0fbb0ab1fd8d3db | 1,066 | require "language/node"
class Eslint < Formula
desc "AST-based pattern checker for JavaScript"
homepage "https://eslint.org"
url "https://registry.npmjs.org/eslint/-/eslint-5.9.0.tgz"
sha256 "5efa81dfad297759368bb859b87682bc9655414d62da39fba92816ae60b03c33"
bottle do
cellar :any_skip_relocation
sha256 "ed8c5cb7f54caa36e9a69b3d069bb2f6bb8e75b64073ca138e95f4852e740dfd" => :mojave
sha256 "abcbb8e3c444132c56bd9285e40342136faed8e953ee41094822fe63e5d86cf9" => :high_sierra
sha256 "1c6cdd0dde0190e4531e8010196b4a173dbacdb446c6d3e853ca6f1f0724ecc5" => :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
(testpath/".eslintrc.json").write("{}") # minimal config
(testpath/"syntax-error.js").write("{}}")
# https://eslint.org/docs/user-guide/command-line-interface#exit-codes
output = shell_output("#{bin}/eslint syntax-error.js", 1)
assert_match "Unexpected token }", output
end
end
| 34.387097 | 93 | 0.748593 |
6a3c293eeaf393cfeb9cd30dfb5031462c207a62 | 1,057 | cask "telegram" do
version "7.2.1,207127"
sha256 "c24b7754e6273eec85b495f42433d902fea7f5782ed29c04ecc2082d9001a78f"
url "https://osx.telegram.org/updates/Telegram-#{version.before_comma}.#{version.after_comma}.app.zip"
appcast "https://osx.telegram.org/updates/versions.xml"
name "Telegram for macOS"
desc "Messaging app with a focus on speed and security"
homepage "https://macos.telegram.org/"
auto_updates true
depends_on macos: ">= :el_capitan"
app "Telegram.app"
zap trash: [
"~/Library/Application Scripts/ru.keepcoder.Telegram",
"~/Library/Application Scripts/ru.keepcoder.Telegram.TelegramShare",
"~/Library/Caches/ru.keepcoder.Telegram",
"~/Library/Containers/ru.keepcoder.Telegram",
"~/Library/Containers/ru.keepcoder.Telegram.TelegramShare",
"~/Library/Cookies/ru.keepcoder.Telegram.binarycookies",
"~/Library/Group Containers/*.ru.keepcoder.Telegram",
"~/Library/Preferences/ru.keepcoder.Telegram.plist",
"~/Library/Saved Application State/ru.keepcoder.Telegram.savedState",
]
end
| 37.75 | 104 | 0.74456 |
f8962a1c043f0073b28f9709534595cd3cda1020 | 1,672 | #
# Be sure to run `pod lib lint PerformanceLibWynk.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 https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'PerformanceLibWynk'
s.version = '0.1.0'
s.summary = 'A short description of PerformanceLibWynk.'
# 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 = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/karishmawynk/PerformanceLibWynk'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'karishmawynk' => '[email protected]' }
s.source = { :git => 'https://github.com/karishmawynk/PerformanceLibWynk.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'PerformanceLibWynk/Classes/**/*'
# s.resource_bundles = {
# 'PerformanceLibWynk' => ['PerformanceLibWynk/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 38.883721 | 115 | 0.653708 |
2197efb0750803475cc3f9b0b169ed8e9691fd39 | 6,719 | module GatewayOptionsStubs
def successful_gateway_options_response
StubResponse.succeeded <<-XML
<gateways>
<gateway>
<gateway_type>paypal</gateway_type>
<name>PayPal</name>
<auth_modes>
<auth_mode>
<auth_mode_type>signature</auth_mode_type>
<name>Signature</name>
<credentials>
<credential>
<name>login</name>
<label>Login</label>
<safe type="boolean">true</safe>
</credential>
<credential>
<name>password</name>
<label>Password</label>
<safe type="boolean">false</safe>
</credential>
<credential>
<name>signature</name>
<label>Signature</label>
<safe type="boolean">false</safe>
</credential>
</credentials>
</auth_mode>
<auth_mode>
<auth_mode_type>certificate</auth_mode_type>
<name>Certificate</name>
<credentials>
<credential>
<name>login</name>
<label>Login</label>
<safe type="boolean">true</safe>
</credential>
<credential>
<name>password</name>
<label>Password</label>
<safe type="boolean">false</safe>
</credential>
<credential>
<name>pem</name>
<label>PEM Certificate</label>
<safe type="boolean">false</safe>
<large type="boolean">true</large>
</credential>
</credentials>
</auth_mode>
<auth_mode>
<auth_mode_type>delegate</auth_mode_type>
<name>Delegate</name>
<credentials>
<credential>
<name>email</name>
<label>PayPal Email</label>
<safe type="boolean">true</safe>
</credential>
</credentials>
</auth_mode>
</auth_modes>
<characteristics>
<supports_purchase type="boolean">true</supports_purchase>
<supports_authorize type="boolean">true</supports_authorize>
<supports_capture type="boolean">true</supports_capture>
<supports_credit type="boolean">true</supports_credit>
<supports_general_credit type="boolean">true</supports_general_credit>
<supports_void type="boolean">true</supports_void>
<supports_verify type="boolean">true</supports_verify>
<supports_reference_purchase type="boolean">true</supports_reference_purchase>
<supports_purchase_via_preauthorization type="boolean">true</supports_purchase_via_preauthorization>
<supports_offsite_purchase type="boolean">true</supports_offsite_purchase>
<supports_offsite_authorize type="boolean">true</supports_offsite_authorize>
<supports_3dsecure_purchase type="boolean">true</supports_3dsecure_purchase>
<supports_3dsecure_authorize type="boolean">true</supports_3dsecure_authorize>
<supports_store type="boolean">true</supports_store>
<supports_remove type="boolean">false</supports_remove>
<supports_fraud_review type="boolean">true</supports_fraud_review>
</characteristics>
<payment_methods>
<payment_method>credit_card</payment_method>
<payment_method>paypal</payment_method>
</payment_methods>
<gateway_specific_fields>
<gateway_specific_field>recurring</gateway_specific_field>
</gateway_specific_fields>
<supported_countries>US, GB, CA</supported_countries>
<regions>europe, north_america</regions>
<homepage>http://paypal.com/</homepage>
<company_name>Paypal Inc.</company_name>
</gateway>
<gateway>
<gateway_type>worldpay</gateway_type>
<name>WorldPay</name>
<auth_modes>
<auth_mode>
<auth_mode_type>default</auth_mode_type>
<name>Default</name>
<credentials>
<credential>
<name>login</name>
<label>Login</label>
<safe type="boolean">true</safe>
</credential>
<credential>
<name>password</name>
<label>Password</label>
<safe type="boolean">false</safe>
</credential>
</credentials>
</auth_mode>
</auth_modes>
<characteristics>
<supports_purchase type="boolean">true</supports_purchase>
<supports_authorize type="boolean">true</supports_authorize>
<supports_capture type="boolean">true</supports_capture>
<supports_credit type="boolean">true</supports_credit>
<supports_general_credit type="boolean">true</supports_general_credit>
<supports_void type="boolean">true</supports_void>
<supports_verify type="boolean">true</supports_verify>
<supports_reference_purchase type="boolean">true</supports_reference_purchase>
<supports_purchase_via_preauthorization type="boolean">false</supports_purchase_via_preauthorization>
<supports_offsite_purchase type="boolean">false</supports_offsite_purchase>
<supports_offsite_authorize type="boolean">false</supports_offsite_authorize>
<supports_3dsecure_purchase type="boolean">false</supports_3dsecure_purchase>
<supports_3dsecure_authorize type="boolean">false</supports_3dsecure_authorize>
<supports_store type="boolean">false</supports_store>
<supports_remove type="boolean">false</supports_remove>
<supports_fraud_review type="boolean">false</supports_fraud_review>
</characteristics>
<payment_methods>
<payment_method>credit_card</payment_method>
</payment_methods>
<gateway_specific_fields/>
<supported_countries>HK, US, GB, AU, AD, BE, CH, CY, CZ, DE, DK, ES, FI, FR, GI, GR, HU, IE, IL, IT, LI, LU, MC, MT, NL, NO, NZ, PL, PT, SE, SG, SI, SM, TR, UM, VA</supported_countries>
<regions>latin_america</regions>
<homepage>http://worldpay.com</homepage>
<company_name>Worldpay</company_name>
</gateway>
</gateways>
XML
end
end
| 45.398649 | 195 | 0.577467 |
91d3611131bb4c4534faa073480ef79b4e25be9e | 628 | class LikesController < ApplicationController
before_action :find_likeable
before_action :authenticate_user!
respond_to :js
def create
@likeable.liked_by current_user
@likeable.create_activity(:like, owner: current_user)
end
def destroy
@likeable.disliked_by current_user
activity = PublicActivity::Activity.find_by_trackable_id_and_key(@likeable.id, "#{@likeable_type.downcase}.like")
activity.destroy if activity.present?
end
private
def find_likeable
@likeable_type = params[:likeable_type].classify
@likeable = @likeable_type.constantize.find(params[:likeable_id])
end
end
| 27.304348 | 117 | 0.770701 |
1c8bed2036f0844917d51d2705a6e0fd06820531 | 3,404 | require 'mittsu'
module Mittsu
class PerspectiveCamera < Camera
attr_accessor :zoom, :fov, :aspect, :near, :far
def initialize(fov = 50.0, aspect = 1.0, near = 0.1, far = 2000.0)
super()
@type = 'PerspectiveCamera'
@zoom = 1.0
@fov = fov.to_f
@aspect = aspect.to_f
@near = near.to_f
@far = far.to_f
update_projection_matrix
end
# Uses Focal Length (in mm) to estimate and set FOV
# 35mm (fullframe) camera is used if frame size is not specified;
# Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
def set_lens(focal_length, frame_height = 24.0)
@fov = 2.0 * Math.rad_to_deg(Math.atan(frame_height / (focal_length * 2.0)))
update_projection_matrix
end
# Sets an offset in a larger frustum. This is useful for multi-window or
# multi-monitor/multi-machine setups.
#
# For example, if you have 3x2 monitors and each monitor is 1920x1080 and
# the monitors are in grid like this
#
# +---+---+---+
# | A | B | C |
# +---+---+---+
# | D | E | F |
# +---+---+---+
#
# then for each monitor you would call it like this
#
# var w = 1920;
# var h = 1080;
# var fullWidth = w * 3;
# var fullHeight = h * 2;
#
# --A--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
# --B--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
# --C--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
# --D--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
# --E--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
# --F--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
#
# Note there is no reason monitors have to be the same size or in a grid.
def set_view_offset(full_width, full_height, x, y, width, height)
@full_width = full_width
@full_height = full_height
@x = x
@y = y
@width = width
@height = height
update_projection_matrix
end
def update_projection_matrix
new_fov = Math.rad_to_deg(2.0 * Math.atan(Math.tan(Math.deg_to_rad(@fov) * 0.5) / @zoom))
if @full_width
aspect = @full_width / @full_height
top = Math.tan(Math.deg_to_rad(new_fov * 0.5)) * @near
bottom = -top
left = aspect * bottom
right = aspect * top
width = (right - left).abs
height = (top - bottom).abs
projection_matrix.make_frustum(
left + @x * width / @full_width,
left + (@x + @width) * width / @full_width,
top - (@y + @height) * height / @full_height,
top - @y * height / @full_height,
@near,
@far
)
else
projection_matrix.make_perspective(new_fov, @aspect, @near, @far)
end
end
def clone
camera = Mittsu::PerspectiveCamera.new
super(camera)
camera.zoom = zoom
camera.fov = fov
camera.aspect = aspect
camera.near = near
camera.far = far
camera.projection_matrix.copy(projection_matrix)
camera
end
protected
def jsonify
data = super
data[:fov] = self.fov
data[:aspect] = self.aspect
data[:near] = self.near
data[:far] = self.far
data
end
end
end
| 26.80315 | 95 | 0.56698 |
bb9af19157183338d82f63f78a84ae435ca71568 | 521 | Pod::Spec.new do |s|
s.name = 'hhxNewProperty'
s.version = '0.1.0'
s.summary = 'hhxNewProperty is a library for personal use.'
s.homepage = 'https://github.com/13760770758/hhxNewProperty'
s.license = 'MIT'
s.author = { 'hhx' => '[email protected]' }
s.platform = :ios,"9.0"
s.source = { :git => 'https://github.com/13760770758/hhxNewProperty.git', :tag => s.version.to_s}
s.vendored_frameworks = 'myFrameWork/*.framework'
s.requires_arc = true
end
| 37.214286 | 107 | 0.600768 |
e9c18be0b33bc627720e48f01ee7bbeec93a8e7a | 1,492 | class GitFixup < Formula
desc "Alias for git commit --fixup <ref>"
homepage "https://github.com/keis/git-fixup"
url "https://github.com/keis/git-fixup/archive/v1.1.1.tar.gz"
sha256 "1843caf40fb54bfd746f966fc04fac68613fe8ec2f18b2af99f9d32a40ea0809"
head "https://github.com/keis/git-fixup.git", :branch => "master"
bottle do
cellar :any_skip_relocation
sha256 "ea6a6ead131ad504711f0905aa3899c60412f8a287ee1308aeb2824a10f17ba3" => :high_sierra
sha256 "478f6c76e15aa1fe183711e609fdc492bb9be5970a555b2b6a1ccfbbd3b96be0" => :sierra
sha256 "0145c568d255c20a0f728d14152aad8a83a0ceb25e9f833d016efc57d19191c8" => :el_capitan
sha256 "077bcf80be63e6da3bdd7699f6b82549d99014210ff8e015e5319234d8a9e75a" => :yosemite
sha256 "f0c6934dbd1317abae4ef8c0e1440d624dbc7025f06eb1006d654c0c2925cc5b" => :mavericks
sha256 "4c4db90452fa1858bf990c08b6f047eb1a0549d655142be2e15d3f1c150e12cc" => :x86_64_linux # glibc 2.19
end
def install
system "make", "PREFIX=#{prefix}", "install"
zsh_completion.install "completion.zsh" => "_git-fixup"
end
test do
(testpath/".gitconfig").write <<~EOS
[user]
name = Real Person
email = [email protected]
EOS
system "git", "init"
(testpath/"test").write "foo"
system "git", "add", "test"
system "git", "commit", "--message", "Initial commit"
(testpath/"test").delete
(testpath/"test").write "bar"
system "git", "add", "test"
system "git", "fixup"
end
end
| 36.390244 | 107 | 0.723861 |
28feb10d5b5713d1feed1e7cda4e463536face30 | 677 | Pod::Spec.new do |spec|
spec.name = "LBRichTextView"
spec.version = "0.0.3"
spec.summary = "支持各种自定义类型输入的强大RichTextView"
spec.description = "一个可以支持图片输入,视频输入,语音输入,类似于iOS系统自带的备忘录,可以定义View输入的强大富文本RichTextView。"
spec.homepage = "https://github.com/A1129434577/LBRichTextView"
spec.license = { :type => "MIT", :file => "LICENSE" }
spec.author = { "刘彬" => "[email protected]" }
spec.platform = :ios
spec.ios.deployment_target = '8.0'
spec.source = { :git => 'https://github.com/A1129434577/LBRichTextView.git', :tag => spec.version.to_s }
spec.source_files = "LBRichTextView/**/*.{h,m}"
spec.requires_arc = true
end
| 45.133333 | 112 | 0.649926 |
28eb4c11746df936ec9084775315d6f942c20bf5 | 2,466 | # frozen_string_literal: true
module Enums
module Ci
module Pipeline
# Returns the `Hash` to use for creating the `failure_reason` enum for
# `Ci::Pipeline`.
def self.failure_reasons
{
unknown_failure: 0,
config_error: 1,
external_validation_failure: 2,
deployments_limit_exceeded: 23
}
end
# Returns the `Hash` to use for creating the `sources` enum for
# `Ci::Pipeline`.
def self.sources
{
unknown: nil,
push: 1,
web: 2,
trigger: 3,
schedule: 4,
api: 5,
external: 6,
# TODO: Rename `pipeline` to `cross_project_pipeline` in 13.0
# https://gitlab.com/gitlab-org/gitlab/issues/195991
pipeline: 7,
chat: 8,
webide: 9,
merge_request_event: 10,
external_pull_request_event: 11,
parent_pipeline: 12,
ondemand_dast_scan: 13
}
end
# Dangling sources are those events that generate pipelines for which
# we don't want to directly affect the ref CI status.
# - when a webide pipeline fails it does not change the ref CI status to failed
# - when a child pipeline (from parent_pipeline source) fails it affects its
# parent pipeline. It's up to the parent to affect the ref CI status
# - when an ondemand_dast_scan pipeline runs it is for testing purpose and should
# not affect the ref CI status.
def self.dangling_sources
sources.slice(:webide, :parent_pipeline, :ondemand_dast_scan)
end
# CI sources are those pipeline events that affect the CI status of the ref
# they run for. By definition it excludes dangling pipelines.
def self.ci_sources
sources.except(*dangling_sources.keys)
end
def self.ci_and_parent_sources
ci_sources.merge(sources.slice(:parent_pipeline))
end
# Returns the `Hash` to use for creating the `config_sources` enum for
# `Ci::Pipeline`.
def self.config_sources
{
unknown_source: nil,
repository_source: 1,
auto_devops_source: 2,
webide_source: 3,
remote_source: 4,
external_project_source: 5,
bridge_source: 6,
parameter_source: 7
}
end
end
end
end
Enums::Ci::Pipeline.prepend_if_ee('EE::Enums::Ci::Pipeline')
| 30.825 | 87 | 0.609084 |
8798e989e9214ad18223b0e86177e08192a38af9 | 41 | module HerokuSan
VERSION = "4.4.0"
end
| 10.25 | 19 | 0.682927 |
011bc936f9c7ce8b1e32c674af49b550e3f54cf0 | 3,068 | #!/usr/bin/env ruby
#
# check-stale-results.rb
#
# Author: Matteo Cerutti <[email protected]>
#
require 'net/http'
require 'json'
require 'sensu-plugin/utils'
require 'sensu-plugin/check/cli'
require 'chronic_duration'
class CheckStaleResults < Sensu::Plugin::Check::CLI
include Sensu::Plugin::Utils
option :stale,
:description => "Elapsed time to consider a check result result (default: 1d)",
:short => "-s <TIME>",
:long => "--stale <TIME>",
:proc => proc { |s| ChronicDuration.parse(s) },
:default => ChronicDuration.parse('1d')
option :verbose,
:description => "Be verbose",
:short => "-v",
:long => "--verbose",
:boolean => true,
:default => false
option :warn,
:description => "Warn if number of stale check results exceeds COUNT (default: 1)",
:short => "-w <COUNT>",
:long => "--warn <COUNT>",
:proc => proc(&:to_i),
:default => 1
option :crit,
:description => "Critical if number of stale check results exceeds COUNT",
:short => "-c <COUNT>",
:long => "--crit <COUNT>",
:proc => proc(&:to_i),
:default => nil
def initialize()
super
raise "Critical threshold must be higher than the warning threshold" if (config[:crit] and config[:warn] >= config[:crit])
# get list of sensu results
@results = get_results()
end
def humanize(secs)
[[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map { |count, name|
if secs > 0
secs, n = secs.divmod(count)
"#{n.to_i} #{name}"
end
}.compact.reverse.join(' ')
end
def api_request(method, path, &blk)
if not settings.has_key?('api')
raise "api.json settings not found."
end
http = Net::HTTP.new(settings['api']['host'], settings['api']['port'])
req = net_http_req_class(method).new(path)
if settings['api']['user'] && settings['api']['password']
req.basic_auth(settings['api']['user'], settings['api']['password'])
end
yield(req) if block_given?
http.request(req)
end
def get_results()
results = []
if req = api_request(:GET, "/results")
results = JSON.parse(req.body) if req.code == '200'
end
results
end
def run()
stale = 0
footer = "\n\n"
@results.each do |result|
if (diff = Time.now.to_i - result['check']['issued']) > config[:stale]
stale += 1
footer += " - check result #{result['client']}/#{result['check']['name']} is stale (#{humanize(diff)})\n"
end
end
footer += "\n"
if (config[:crit] and stale >= config[:crit])
msg = "Found #{stale} stale check results (>= #{config[:crit]})"
msg += footer if config[:verbose]
critical(msg)
end
if stale >= config[:warn]
msg = "Found #{stale} stale check results (>= #{config[:warn]})"
msg += footer if config[:verbose]
warning(msg)
end
ok("No stale check results found (>= #{config[:warn]})")
end
end
| 27.392857 | 126 | 0.571056 |
91a80b32afb6a63d5cc8483e87fdd0436dc6a9bc | 418 |
action :test do
ruby_block "interior-ruby-block-1" do
block do
# doesn't need to do anything
end
notifies :run, "ruby_block[interior-ruby-block-2]", :immediately
end
ruby_block "interior-ruby-block-2" do
block do
$interior_ruby_block_2 = "executed"
end
action :nothing
end
end
action :no_updates do
ruby_block "no-action" do
block {}
action :nothing
end
end
| 16.72 | 68 | 0.662679 |
212e42273b2b92e62d2242ce7e0e2d5eb6710398 | 1,210 | # frozen_string_literal: true
module View
module Game
class Bank < Snabberb::Component
include Lib::Color
needs :game
needs :layout, default: nil
def render
if @layout == :card
render_card
else
props = {
style: {
'margin-bottom': '1rem',
},
}
h(:div, props, "Bank Cash: #{@game.format_currency(@game.bank.cash)}")
end
end
def render_card
title_props = {
style: {
padding: '0.4rem',
backgroundColor: color_for(:bg2),
color: color_for(:font2),
},
}
body_props = {
style: {
margin: '0.3rem 0.5rem 0.4rem',
display: 'grid',
grid: 'auto / 1fr',
gap: '0.5rem',
justifyItems: 'center',
},
}
h('div.bank.card', [
h('div.title.nowrap', title_props, [h(:em, 'The Bank')]),
h(:div, body_props, [
h(:div, @game.format_currency(@game.bank.cash)),
h(GameInfo, game: @game, layout: 'discarded_trains'),
]),
])
end
end
end
end
| 22.830189 | 80 | 0.456198 |
1dc0a8f65e8ac131a844d945eed7069db5701fec | 457 | class Producto < ActiveRecord::Base
belongs_to :solicitud
belongs_to :proveedor
belongs_to :compra
before_save :precio_total, :total
def precio_total
if self.cantidad && self.precio
self.total = self.cantidad * self.precio
end
end
def total
if self.aprobar && self.compra_id
self.total_compra = self.cantidad_compra * self.precio_compra
end
end
end
| 20.772727 | 73 | 0.617068 |
d5a26ca17be41917ceece396e3549b80bbe5abe2 | 295 | # frozen_string_literal: true
module Drivers
module Appserver
class Null < Drivers::Appserver::Base
adapter :null
allowed_engines :null
output filter: []
def configure; end
alias after_deploy configure
alias after_undeploy configure
end
end
end
| 18.4375 | 41 | 0.684746 |
f83172e5eddeafcf7f37e08d8083aaa82935990c | 1,538 | # frozen_string_literal: true
require 'ckeditor'
# Use this hook to configure ckeditor
Ckeditor.setup do |_config|
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default), :mongo_mapper and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'ckeditor/orm/active_record'
# Allowed image file types for upload.
# Set to nil or [] (empty array) for all file types
# By default: %w(jpg jpeg png gif tiff)
# config.image_file_types = ["jpg", "jpeg", "png", "gif", "tiff"]
# Allowed attachment file types for upload.
# Set to nil or [] (empty array) for all file types
# By default: %w(doc docx xls odt ods pdf rar zip tar tar.gz swf)
# config.attachment_file_types = ["doc", "docx", "xls", "odt", "ods", "pdf", "rar", "zip", "tar", "swf"]
# Setup authorization to be run as a before filter
# By default: there is no authorization.
# config.authorize_with :cancan
# Asset model classes
# config.picture_model { Ckeditor::Picture }
# config.attachment_file_model { Ckeditor::AttachmentFile }
# Paginate assets
# By default: 24
# config.default_per_page = 24
# Customize ckeditor assets path
# By default: nil
# config.asset_path = "http://www.example.com/assets/ckeditor/"
# To reduce the asset precompilation time, you can limit plugins and/or languages to those you need:
# By default: nil (no limit)
# config.assets_languages = ['en', 'uk']
# config.assets_plugins = ['image', 'smiley']
end
| 35.767442 | 106 | 0.698309 |
ff8949d32673368c4202c0ac95d9d4212877f046 | 770 | module Exchanger
# SOAP Client for Exhange Web Services
class Client
delegate :endpoint, :timeout, :username, :password, :debug, :insecure_ssl, :ssl_version, :to => "Exchanger.config"
def initialize
@client = HTTPClient.new
@client.debug_dev = STDERR if debug
@client.set_auth nil, username, password if username
@client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE if insecure_ssl
@client.ssl_config.ssl_version = ssl_version if ssl_version
end
# Does the actual HTTP level interaction.
def request(post_body, headers)
response = @client.post(endpoint, post_body, headers)
return { :status => response.status, :body => response.content, :content_type => response.contenttype }
end
end
end
| 36.666667 | 118 | 0.709091 |
26b98afa52588bbc015e7284b25e0777b6d63b6a | 8,524 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Tim Hinderliter (<[email protected]>)
# Author:: Christopher Walters (<[email protected]>)
# Author:: Daniel DeLeo (<[email protected]>)
# Copyright:: Copyright 2008-2014 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.
#
require 'chef/log'
require 'chef/rest'
require 'chef/run_context'
require 'chef/config'
require 'chef/node'
require 'chef/chef_class'
class Chef
module PolicyBuilder
# ExpandNodeObject is the "classic" policy builder implementation. It
# expands the run_list on a node object and then queries the chef-server
# to find the correct set of cookbooks, given version constraints of the
# node's environment.
class ExpandNodeObject
attr_reader :events
attr_reader :node
attr_reader :node_name
attr_reader :ohai_data
attr_reader :json_attribs
attr_reader :override_runlist
attr_reader :run_context
attr_reader :run_list_expansion
def initialize(node_name, ohai_data, json_attribs, override_runlist, events)
@node_name = node_name
@ohai_data = ohai_data
@json_attribs = json_attribs
@override_runlist = override_runlist
@events = events
@node = nil
@run_list_expansion = nil
end
# This method injects the run_context and into the Chef class.
#
# NOTE: This is duplicated with the Policyfile implementation. If
# it gets any more complicated, it needs to be moved elsewhere.
#
# @param run_context [Chef::RunContext] the run_context to inject
def setup_chef_class(run_context)
Chef.set_run_context(run_context)
end
def setup_run_context(specific_recipes=nil)
if Chef::Config[:solo]
Chef::Cookbook::FileVendor.fetch_from_disk(Chef::Config[:cookbook_path])
cl = Chef::CookbookLoader.new(Chef::Config[:cookbook_path])
cl.load_cookbooks
cookbook_collection = Chef::CookbookCollection.new(cl)
run_context = Chef::RunContext.new(node, cookbook_collection, @events)
else
Chef::Cookbook::FileVendor.fetch_from_remote(api_service)
cookbook_hash = sync_cookbooks
cookbook_collection = Chef::CookbookCollection.new(cookbook_hash)
run_context = Chef::RunContext.new(node, cookbook_collection, @events)
end
# TODO: this is really obviously not the place for this
# FIXME: need same edits
setup_chef_class(run_context)
# TODO: this is not the place for this. It should be in Runner or
# CookbookCompiler or something.
run_context.load(@run_list_expansion)
if specific_recipes
specific_recipes.each do |recipe_file|
run_context.load_recipe_file(recipe_file)
end
end
run_context
end
def finish_load_node(node)
@node = node
end
# Applies environment, external JSON attributes, and override run list to
# the node, Then expands the run_list.
#
# === Returns
# node<Chef::Node>:: The modified node object. node is modified in place.
def build_node
# Allow user to override the environment of a node by specifying
# a config parameter.
if Chef::Config[:environment] && !Chef::Config[:environment].chomp.empty?
node.chef_environment(Chef::Config[:environment])
end
# consume_external_attrs may add items to the run_list. Save the
# expanded run_list, which we will pass to the server later to
# determine which versions of cookbooks to use.
node.reset_defaults_and_overrides
node.consume_external_attrs(ohai_data, @json_attribs)
setup_run_list_override
expand_run_list
Chef::Log.info("Run List is [#{node.run_list}]")
Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]")
events.node_load_completed(node, @expanded_run_list_with_versions, Chef::Config)
node
end
# Expands the node's run list. Stores the run_list_expansion object for later use.
def expand_run_list
@run_list_expansion = if Chef::Config[:solo]
node.expand!('disk')
else
node.expand!('server')
end
# @run_list_expansion is a RunListExpansion.
#
# Convert @expanded_run_list, which is an
# Array of Hashes of the form
# {:name => NAME, :version_constraint => Chef::VersionConstraint },
# into @expanded_run_list_with_versions, an
# Array of Strings of the form
# "#{NAME}@#{VERSION}"
@expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings
@run_list_expansion
rescue Exception => e
# TODO: wrap/munge exception with useful error output.
events.run_list_expand_failed(node, e)
raise
end
# Sync_cookbooks eagerly loads all files except files and
# templates. It returns the cookbook_hash -- the return result
# from /environments/#{node.chef_environment}/cookbook_versions,
# which we will use for our run_context.
#
# === Returns
# Hash:: The hash of cookbooks with download URLs as given by the server
def sync_cookbooks
Chef::Log.debug("Synchronizing cookbooks")
begin
events.cookbook_resolution_start(@expanded_run_list_with_versions)
cookbook_hash = api_service.post("environments/#{node.chef_environment}/cookbook_versions",
{:run_list => @expanded_run_list_with_versions})
rescue Exception => e
# TODO: wrap/munge exception to provide helpful error output
events.cookbook_resolution_failed(@expanded_run_list_with_versions, e)
raise
else
events.cookbook_resolution_complete(cookbook_hash)
end
synchronizer = Chef::CookbookSynchronizer.new(cookbook_hash, events)
if temporary_policy?
synchronizer.remove_obsoleted_files = false
end
synchronizer.sync_cookbooks
# register the file cache path in the cookbook path so that CookbookLoader actually picks up the synced cookbooks
Chef::Config[:cookbook_path] = File.join(Chef::Config[:file_cache_path], "cookbooks")
cookbook_hash
end
# Indicates whether the policy is temporary, which means an
# override_runlist was provided. Chef::Client uses this to decide whether
# to do the final node save at the end of the run or not.
def temporary_policy?
!node.override_runlist.empty?
end
########################################
# Internal public API
########################################
def setup_run_list_override
runlist_override_sanity_check!
unless(override_runlist.empty?)
node.override_runlist(*override_runlist)
Chef::Log.warn "Run List override has been provided."
Chef::Log.warn "Original Run List: [#{node.primary_runlist}]"
Chef::Log.warn "Overridden Run List: [#{node.run_list}]"
end
end
# Ensures runlist override contains RunListItem instances
def runlist_override_sanity_check!
# Convert to array and remove whitespace
if override_runlist.is_a?(String)
@override_runlist = override_runlist.split(',').map { |e| e.strip }
end
@override_runlist = [override_runlist].flatten.compact
override_runlist.map! do |item|
if(item.is_a?(Chef::RunList::RunListItem))
item
else
Chef::RunList::RunListItem.new(item)
end
end
end
def api_service
@api_service ||= Chef::REST.new(config[:chef_server_url])
end
def config
Chef::Config
end
end
end
end
| 35.966245 | 121 | 0.65955 |
e9cbde5873bbd9fabb1ba21d48ac05f3ea1b8934 | 648 | module VagrantPlugins
module SyncedFolderNFSGuest
module ProviderVMwareFusion
module Cap
def self.read_host_ip
# In practice, we need the host's IP on the vmnet device this VM uses.
# It seems a bit tricky to get the right one, so let's allow all.
return `for N in $(ifconfig | awk -F: '/vmnet/ { print $1; }'); do ifconfig $N | awk '/inet / { print $2; }'; done`.split("\n")
end
def self.nfs_settings(machine)
host_ip = self.read_host_ip
machine_ip = machine.provider.driver.read_ip
return host_ip, machine_ip
end
end
end
end
end
| 32.4 | 137 | 0.611111 |
7a47eeeb4ee22fe36117f47268ec18474a84ab3b | 6,665 | require 'spec_helper'
module Spree
describe StockLocation do
subject { create(:stock_location_with_items, backorderable_default: true) }
let(:stock_item) { subject.stock_items.order(:id).first }
let(:variant) { stock_item.variant }
it 'creates stock_items for all variants' do
subject.stock_items.count.should eq Variant.count
end
context "handling stock items" do
let!(:variant) { create(:variant) }
context "given a variant" do
subject { StockLocation.create(name: "testing", propagate_all_variants: false) }
context "set up" do
it "creates stock item" do
subject.should_receive(:propagate_variant)
subject.set_up_stock_item(variant)
end
context "stock item exists" do
let!(:stock_item) { subject.propagate_variant(variant) }
it "returns existing stock item" do
subject.set_up_stock_item(variant).should == stock_item
end
end
end
context "propagate variants" do
let(:stock_item) { subject.propagate_variant(variant) }
it "creates a new stock item" do
expect {
subject.propagate_variant(variant)
}.to change{ StockItem.count }.by(1)
end
context "passes backorderable default config" do
context "true" do
before { subject.backorderable_default = true }
it { stock_item.backorderable.should be_true }
end
context "false" do
before { subject.backorderable_default = false }
it { stock_item.backorderable.should be_false }
end
end
end
context "propagate all variants" do
subject { StockLocation.new(name: "testing") }
context "true" do
before { subject.propagate_all_variants = true }
specify do
subject.should_receive(:propagate_variant).at_least(:once)
subject.save!
end
end
context "false" do
before { subject.propagate_all_variants = false }
specify do
subject.should_not_receive(:propagate_variant)
subject.save!
end
end
end
end
end
it 'finds a stock_item for a variant' do
stock_item = subject.stock_item(variant)
stock_item.count_on_hand.should eq 10
end
it 'finds a stock_item for a variant by id' do
stock_item = subject.stock_item(variant.id)
stock_item.variant.should eq variant
end
it 'returns nil when stock_item is not found for variant' do
stock_item = subject.stock_item(100)
stock_item.should be_nil
end
it 'creates a stock_item if not found for a variant' do
variant = create(:variant)
variant.stock_items.destroy_all
variant.save
stock_item = subject.stock_item_or_create(variant)
stock_item.variant.should eq variant
end
it 'finds a count_on_hand for a variant' do
subject.count_on_hand(variant).should eq 10
end
it 'finds determines if you a variant is backorderable' do
subject.backorderable?(variant).should be_true
end
it 'restocks a variant with a positive stock movement' do
originator = double
subject.should_receive(:move).with(variant, 5, originator)
subject.restock(variant, 5, originator)
end
it 'unstocks a variant with a negative stock movement' do
originator = double
subject.should_receive(:move).with(variant, -5, originator)
subject.unstock(variant, 5, originator)
end
it 'it creates a stock_movement' do
expect {
subject.move variant, 5
}.to change { subject.stock_movements.where(stock_item_id: stock_item).count }.by(1)
end
it 'can be deactivated' do
create(:stock_location, :active => true)
create(:stock_location, :active => false)
Spree::StockLocation.active.count.should eq 1
end
it 'ensures only one stock location is default at a time' do
first = create(:stock_location, :active => true, :default => true)
second = create(:stock_location, :active => true, :default => true)
first.reload.default.should eq false
second.reload.default.should eq true
first.default = true
first.save!
first.reload.default.should eq true
second.reload.default.should eq false
end
context 'fill_status' do
it 'all on_hand with no backordered' do
on_hand, backordered = subject.fill_status(variant, 5)
on_hand.should eq 5
backordered.should eq 0
end
it 'some on_hand with some backordered' do
on_hand, backordered = subject.fill_status(variant, 20)
on_hand.should eq 10
backordered.should eq 10
end
it 'zero on_hand with all backordered' do
zero_stock_item = mock_model(StockItem,
count_on_hand: 0,
backorderable?: true)
subject.should_receive(:stock_item).with(variant).and_return(zero_stock_item)
on_hand, backordered = subject.fill_status(variant, 20)
on_hand.should eq 0
backordered.should eq 20
end
context 'when backordering is not allowed' do
before do
@stock_item = mock_model(StockItem, backorderable?: false)
subject.should_receive(:stock_item).with(variant).and_return(@stock_item)
end
it 'all on_hand' do
@stock_item.stub(count_on_hand: 10)
on_hand, backordered = subject.fill_status(variant, 5)
on_hand.should eq 5
backordered.should eq 0
end
it 'some on_hand' do
@stock_item.stub(count_on_hand: 10)
on_hand, backordered = subject.fill_status(variant, 20)
on_hand.should eq 10
backordered.should eq 0
end
it 'zero on_hand' do
@stock_item.stub(count_on_hand: 0)
on_hand, backordered = subject.fill_status(variant, 20)
on_hand.should eq 0
backordered.should eq 0
end
end
context 'without stock_items' do
subject { create(:stock_location) }
let(:variant) { create(:base_variant) }
it 'zero on_hand and backordered', focus: true do
subject
variant.stock_items.destroy_all
on_hand, backordered = subject.fill_status(variant, 1)
on_hand.should eq 0
backordered.should eq 0
end
end
end
end
end
| 30.295455 | 90 | 0.623106 |
6a45c69d44483c78aa0c437a789960323b9c22bc | 10,066 | require_relative '../../config/environment'
require 'rack-flash'
class BooksController < ApplicationController
use Rack::Flash
get '/books' do
if Helpers.is_logged_in?(session)
@books = Book.all
erb :'books/index'
else
erb :'sessions/authentication_error', :layout => false
end
end
get '/books/new' do
if Helpers.is_logged_in?(session)
@books = Book.all
@authors = Author.all
@publishers = Publisher.all
@genres = Genre.all
erb :'books/new'
else
erb :'sessions/authentication_error', :layout => false
end
end
post '/books' do
if Helpers.is_logged_in?(session)
#INPUT VALIDATION!!!
has_error = false
if !params[:book][:name] || params[:book][:name].empty?
flash[:message] ||= []
flash[:message] << "*Please specify a book name*"
has_error = true
end
if (!params[:book][:author] || params[:book][:author].empty?) && (!params[:author][:name] || params[:author][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please specify an author or create a new author*"
has_error = true
end
if !params[:book][:author].empty? && !params[:author][:name].empty?
flash[:message] ||= []
flash[:message] << "*Only one author per book. Please either the new author field or the author dropdown.*"
has_error = true
end
if (!params[:book][:publisher] || params[:book][:publisher].empty?) && (!params[:publisher][:name] || params[:publisher][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please specify an author or create a new publisher*"
has_error = true
end
if !params[:book][:publisher].empty? && !params[:publisher][:name].empty?
flash[:message] ||= []
flash[:message] << "*Only one publisher per book. Please either the new publisher field or the publisher dropdown*"
has_error = true
end
if !params[:book][:year_published] || params[:book][:year_published].empty?
flash[:message] ||= []
flash[:message] << "*Please enter a publication year*"
has_error = true
end
if (!params[:book][:genre_ids] || params[:book][:genre_ids].empty?) && (!params[:genre][:name] || params[:genre][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please select or create at least one genre*"
has_error = true
end
redirect to '/books/new' if has_error == true
#ACTUAL OBJECT CREATION
@books = Book.all
if !Book.all.detect{ |b| b.name == params[:book][:name] }
@book = Book.create(name: params[:book][:name], has_been_read: params[:book][:has_been_read])
else
@book = Book.find_by(:name => params[:book][:name])
#set alternate flash message here LATER
redirect to "/books/#{@book.slug}"
end
#associating book with author
if !params[:author][:name].empty?
@book.author = Author.find_or_create_by(:name => params[:author][:name])
else
@book.author = Author.find_by(:name => params[:book][:author])
end
@book.save
#associating book with existing publisher
if !params[:publisher][:name].empty?
@book.publisher = Publisher.find_or_create_by(:name => params[:publisher][:name])
else
@book.publisher = Publisher.find_by(:name => params[:book][:publisher])
end
#associating a book with existing genres
if params[:book][:genre_ids]
params[:book][:genre_ids].each do |g|
@book.genres << Genre.find(g)
end
end
#associating book with a new genre
if !params[:genre][:name].empty?
if !Genre.all.detect {|g| g.name == params[:genre][:name]}
@book.genres << Genre.create(:name => params[:genre][:name])
else
@book.genres << Genre.find_by(name: params[:genre][:name])
end
end
@book.user = Helpers.current_user(session)
#editing book's publication year
#
@book.year_published = params[:book][:year_published]
# saving book
@book.save
redirect to "/books/#{@book.slug}"
end
end
get '/books/:slug' do
if Helpers.is_logged_in?(session)
@books = Book.all
@book = Book.find_by_slug(params[:slug])
erb :'books/show'
else
erb :'sessions/authentication_error', :layout => false
end
end
get '/books/:slug/edit' do
if Helpers.is_logged_in?(session)
@book = Book.find_by_slug(params[:slug])
@books = Book.all
@authors = Author.all
@publishers = Publisher.all
@genres = Genre.all
if Helpers.current_user(session) == @book.user
erb :'books/edit'
else
erb :'sessions/wrong_user_error'
end
else
erb :'sessions/authentication_error', :layout => false
end
end
patch '/books/:slug' do
if Helpers.is_logged_in?(session)
#INPUT VALIDATION!!!
has_error = false
if !params[:book][:name] || params[:book][:name].empty?
flash[:message] ||= []
flash[:message] << "*Please specify a book name*"
has_error = true
end
if (!params[:book][:author] || params[:book][:author].empty?) && (!params[:author][:name] || params[:author][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please specify an author or create a new author*"
has_error = true
end
if !params[:book][:author].empty? && !params[:author][:name].empty?
flash[:message] ||= []
flash[:message] << "*Only one author per book. Please either the new author field or the author dropdown.*"
has_error = true
end
if (!params[:book][:publisher] || params[:book][:publisher].empty?) && (!params[:publisher][:name] || params[:publisher][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please specify an author or create a new publisher*"
has_error = true
end
if !params[:book][:publisher].empty? && !params[:publisher][:name].empty?
flash[:message] ||= []
flash[:message] << "*Only one publisher per book. Please either the new publisher field or the publisher dropdown*"
has_error = true
end
if !params[:book][:year_published] || params[:book][:year_published].empty?
flash[:message] ||= []
flash[:message] << "*Please enter a publication year*"
has_error = true
end
if (!params[:book][:genre_ids] || params[:book][:genre_ids].empty?) && (!params[:genre][:name] || params[:genre][:name].empty?)
flash[:message] ||= []
flash[:message] << "*Please select or create at least one genre*"
has_error = true
end
redirect to "/books/#{params[:slug]}/edit" if has_error == true
@book = Book.find_by_slug(params[:slug])
if Helpers.current_user(session) == @book.user
@books = Book.all
@book.name = params[:book][:name]
#associating book with author
if !params[:author][:name].empty?
@book.author = Author.find_or_create_by(:name => params[:author][:name])
else
@book.author = Author.find_by(:name => params[:book][:author])
end
#associating book with existing publisher
if !params[:publisher][:name].empty?
@book.publisher = Publisher.find_or_create_by(:name => params[:publisher][:name])
else
@book.publisher = Publisher.find_by(:name => params[:book][:publisher])
end
#associating a book with existing genres
#edited from original new.erb so that duplicates are not added
@book.genres = params[:book][:genre_ids].collect { |g| Genre.find(g)}
#associating book with a new genre
if !params[:genre][:name].empty?
if !Genre.all.detect {|g| g.name == params[:genre][:name]}
@book.genres << Genre.create(:name => params[:genre][:name])
elsif [email protected]{|g| g.name == params[:genre][:name]}
#the above was edited so that duplicates would not be added to the genre through the new genre field
@book.genres << Genre.find_by(name: params[:genre][:name])
end
#if the genre is already detected in the book's genres array, this whole statement just does nothing.
end
# editing book's publication year
@book.year_published = params[:book][:year_published]
@book.has_been_read = params[:book][:has_been_read]
#saving book
@book.save
#DELETING EMPTY ITEMS THAT WERE DISASSOCIATED DURING EDIT
Author.all.each do |author|
if author.books.count == 0
author.delete
end
end
Publisher.all.each do |publisher|
if publisher.books.count == 0
publisher.delete
end
end
Genre.all.each do |genre|
if genre.books.count == 0
genre.delete
end
end
flash[:message] = "Book Successfully Edited"
redirect to "/books/#{@book.slug}"
else
erb :'sessions/wrong_user_error'
end
else
erb :'sessions/authentication_error'
end
end
delete '/books/:slug/delete' do
if Helpers.is_logged_in?(session)
@book = Book.find_by_slug(params[:slug])
if Helpers.current_user(session) == @book.user
@book.delete
@book.author.delete if @book.author.books.count == 0
@book.publisher.delete if @book.publisher.books.count == 0
@book.genres.each do |g|
g.delete if g.books.count == 0
end
flash[:message] = "Book Successfully Deleted"
redirect to "/books"
else
erb :'sessions/wrong_user_error'
end
else
erb :'sessions/authentication_error'
end
end
#later add functionality that says if the author has no books, the author instance is deleted
end
| 32.262821 | 141 | 0.591993 |
0316d5699bfed264a7e5019e3174ee436ece5243 | 357 | require 'cinch'
class Messenger
include Cinch::Plugin
match /msg (.+?) (.+)/
def execute(m, receiver, message)
User(receiver).send(message)
end
end
bot = Cinch::Bot.new do
configure do |c|
c.server = "irc.freenode.org"
c.nick = "CinchBot"
c.channels = ["#cinch-bots"]
c.plugins.plugins = [Messenger]
end
end
bot.start
| 15.521739 | 35 | 0.630252 |
6a3add543cbc23e216ee8d32f706ab424fa4b422 | 2,577 | # frozen_string_literal: true
module Fireblocks
class API
class Transactions
class << self
EXTERNAL_WALLET = 'EXTERNAL_WALLET'
VAULT_ACCOUNT = 'VAULT_ACCOUNT'
VALID_TRANSACTION_KEYS = %i[
amount
assetId
source
destination
destinations
fee
feeLevel
gasPrice
note
autoStaking
networkStaking
cpuStaking
].freeze
def create(options)
body = options.slice(*VALID_TRANSACTION_KEYS)
Fireblocks::Request.post(body: body, path: '/v1/transactions')
end
def from_vault_to_external(
amount:,
asset_id:,
source_id:,
destination: nil,
destinations: nil,
destination_id: nil,
one_time_address: nil,
tag: nil,
options: {}
)
destination_params = destination_payload(
destination_type: EXTERNAL_WALLET,
destination: destination,
destinations: destinations,
destination_id: destination_id,
one_time_address: one_time_address,
tag: tag
)
body = {
amount: amount,
assetId: asset_id,
source: {
type: VAULT_ACCOUNT,
id: source_id
}
}.merge(options, destination_params).compact
create(body)
end
def from_vault_to_vault(
amount:,
asset_id:,
source_id:,
destination_id:,
options: {}
)
body = {
amount: amount,
assetId: asset_id,
source: {
type: VAULT_ACCOUNT,
id: source_id
},
destination: {
type: VAULT_ACCOUNT,
id: destination_id
}
}.merge(options).compact
create(body)
end
def destination_payload(**kwargs)
return { destinations: kwargs[:destinations] } if kwargs[:destinations].is_a?(Array)
return { destination: kwargs[:destination] } if kwargs[:destination].is_a?(Hash)
{
destination: {
type: kwargs[:destination_type],
id: kwargs[:destination_id],
oneTimeAddress: {
address: kwargs[:one_time_address],
tag: kwargs[:tag]
}.compact
}.compact
}
end
end
end
end
end
| 24.542857 | 94 | 0.500194 |
333751637ba5b9e874fbee895ef8fae6fd1fa535 | 353 | class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.string :zip_code
t.string :type_address
t.string :address
t.string :number
t.string :complement
t.string :neighborhood
t.string :city
t.string :state
t.text :note
t.timestamps
end
end
end
| 19.611111 | 47 | 0.631728 |
1c7b544c5bd6732acdd5a00246511cbdce59d01e | 544 | # frozen_string_literal: true
require_relative "graphql/cop"
require_relative "graphql/argument_description"
require_relative "graphql/argument_name"
require_relative "graphql/extract_input_type"
require_relative "graphql/extract_type"
require_relative "graphql/field_definitions"
require_relative "graphql/field_description"
require_relative "graphql/field_hash_key"
require_relative "graphql/field_method"
require_relative "graphql/field_name"
require_relative "graphql/resolver_method_length"
require_relative "graphql/object_description"
| 34 | 49 | 0.876838 |
bbfca84b0397c9b4d0b2515ea75d5724ebcffe86 | 774 | class ParseDGSResponse < Faraday::Response::Middleware
def on_complete(env)
if env[:body]
reencode_body(env)
handle_errors(env)
end
end
private
def reencode_body(env)
env[:body].encode('UTF-8', invalid: :replace, undef: :replace)
end
def handle_errors(env)
if had_login_errors?(env)
env[:status] = 401
raise DGS::NotLoggedInException, env[:body]
else
handle_other_errors(env)
end
end
def had_login_errors?(env)
login_errors = %w(not_logged_in wrong_userid wrong_password cookies_disabled login_denied no_uid unknown_user)
env[:body].match("Error: (#{login_errors.join('|')})")
end
def handle_other_errors(env)
raise DGS::Exception, env[:body] if env[:body].match(/Error:/)
end
end
| 23.454545 | 114 | 0.686047 |
e9cf2ed9d2711fb828c9f9498ddbd6809d775011 | 1,171 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint geolocator.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'geolocator_apple'
s.version = '1.2.0'
s.summary = 'Geolocation iOS plugin for Flutter.'
s.description = <<-DESC
Geolocation iOS plugin for Flutter. This plugin provides the Apple implementation for the geolocator plugin.
DESC
s.homepage = 'http://github.com/baseflow/flutter-geolocator'
s.license = { :type => 'MIT', :file => '../LICENSE' }
s.author = { 'Baseflow' => '[email protected]' }
s.source = { :http => 'https://github.com/baseflow/flutter-geolocator/tree/master/' }
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/GeolocatorPlugin.modulemap'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
end
| 46.84 | 110 | 0.64304 |
1a0e39a2372ae48ef530ba75002361306c1df643 | 3,842 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataMigration::Mgmt::V2018_07_15_preview
module Models
#
# Model object.
#
#
class MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputMigrationLevel < MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutput
include MsRestAzure
def initialize
@resultType = "MigrationLevelOutput"
end
attr_accessor :resultType
# @return [DateTime] Migration start time
attr_accessor :started_on
# @return [DateTime] Migration end time
attr_accessor :ended_on
# @return [String] Source server version
attr_accessor :source_server_version
# @return [String] Source server name
attr_accessor :source_server
# @return [String] Target server version
attr_accessor :target_server_version
# @return [String] Target server name
attr_accessor :target_server
#
# Mapper for
# MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputMigrationLevel class
# as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'MigrationLevelOutput',
type: {
name: 'Composite',
class_name: 'MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputMigrationLevel',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
resultType: {
client_side_validation: true,
required: true,
serialized_name: 'resultType',
type: {
name: 'String'
}
},
started_on: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'startedOn',
type: {
name: 'DateTime'
}
},
ended_on: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'endedOn',
type: {
name: 'DateTime'
}
},
source_server_version: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'sourceServerVersion',
type: {
name: 'String'
}
},
source_server: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'sourceServer',
type: {
name: 'String'
}
},
target_server_version: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'targetServerVersion',
type: {
name: 'String'
}
},
target_server: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'targetServer',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.671642 | 129 | 0.495055 |
5d9d5a86374834659bdca9c57b4aeb92a8138aea | 3,615 | require 'rails_helper'
RSpec.describe SmsNotificationService do
let!(:facility_name) { 'Simple Facility' }
let!(:appointment_scheduled_date) { Date.new(2018, 1, 1) }
let!(:appointment) do
create(:appointment,
facility: create(:facility, name: facility_name),
scheduled_date: appointment_scheduled_date)
end
context '#send_reminder_sms' do
let(:twilio_client) { double('TwilioClientDouble') }
let(:sender_phone_number) { ENV['TWILIO_PHONE_NUMBER'] }
let(:recipient_phone_number) { '8585858585' }
let(:expected_sms_recipient_phone_number) { '+918585858585' }
context 'follow_up_reminder' do
it 'should have the SMS body in the default locale' do
sms = SmsNotificationService.new(recipient_phone_number, sender_phone_number, twilio_client)
expected_msg_default = 'We missed you for your scheduled BP check-up at Simple Facility on 1 January, 2018.'\
' Please come between 9.30 AM and 2 PM.'
expect(twilio_client).to receive_message_chain('messages.create').with(from: '+15005550006',
to: expected_sms_recipient_phone_number,
status_callback: '',
body: expected_msg_default)
sms.send_reminder_sms('missed_visit_sms_reminder', appointment, '')
end
it 'should have the SMS body in Marathi' do
sms = SmsNotificationService.new(recipient_phone_number, sender_phone_number, twilio_client)
expected_msg_marathi = 'दि. 1 जानेवारी, 2018 रोजी या दवाखान्यात Simple Facility ठरल्यानुसार बी. पी. चेक अप करून एक महिन्याचे औषध'\
' नेल्याचे दिसत नाही. कृपया सकाळी 9 ते दुपारी 12 या वेळेत येऊन बी. पी. चे औषध घेऊन जावे.'
expect(twilio_client).to receive_message_chain('messages.create').with(from: '+15005550006',
to: expected_sms_recipient_phone_number,
status_callback: '',
body: expected_msg_marathi)
sms.send_reminder_sms('missed_visit_sms_reminder', appointment, '', 'mr-IN')
end
it 'should have the SMS body in Punjabi' do
sms = SmsNotificationService.new(recipient_phone_number, sender_phone_number, twilio_client)
expected_msg_punjabi = 'ਸਰਕਾਰੀ ਹਸਪਤਾਲ Simple Facility ਵਿੱਚ 1 ਜਨਵਰੀ, 2018 ਨੂੰ ਤੁਹਾਡੇ ਬੀ.ਪੀ ਦੀ ਜਾਂਚ ਹੋਣੀ ਸੀ। ਕਿਰਪਾ ਕਰਕੇ'\
' 9:30 ਤੋਂ 2 ਵਜੇ ਦੇ ਵਿੱਚ ਆਉ।'
expect(twilio_client).to receive_message_chain('messages.create').with(from: '+15005550006',
to: expected_sms_recipient_phone_number,
status_callback: '',
body: expected_msg_punjabi)
sms.send_reminder_sms('missed_visit_sms_reminder', appointment, '', 'pa-Guru-IN')
end
it 'should raise an error if the locale for the SMS body is unsupported' do
sms = SmsNotificationService.new(recipient_phone_number, sender_phone_number, twilio_client)
expect {
sms.send_reminder_sms('missed_visit_sms_reminder', appointment, ' ', 'gu-IN')
}.to raise_error(StandardError)
end
end
end
end
| 52.391304 | 138 | 0.559613 |
7ae845f508dff8beecc820674720a4c50908cde8 | 352 | describe file('/opt/chef/embedded/etc/gemrc') do
it { should exist }
its('type') { should eq :file }
its('owner') { should eq 'root' }
its('group') { should eq 'root' }
its('mode') { should eq 420 }
its('content') { should match(%r{":sources":\n- http://rubygems.org/}) }
its('content') { should match(%r{gem: "--no-ri --no-rdoc"}) }
end
| 35.2 | 74 | 0.596591 |
e21738c6c1486261e0fa066a49ec5b0a9e1c7565 | 445 | class Bob
def hey(msg)
capital_l, lower_l = msg.scan(/[A-Z]/), msg.scan(/[a-z]/)
numbers, last_sym = msg.scan(/[0-9]/), msg.gsub(/\n/, '').scan(/[\?!\.]$/)
if (capital_l + lower_l + numbers + last_sym).empty?
'Fine. Be that way!'
elsif lower_l.empty? && capital_l.empty? == false
'Whoa, chill out!'
elsif last_sym.include?('?') && (lower_l || numbers)
'Sure.'
else
'Whatever.'
end
end
end
| 27.8125 | 78 | 0.550562 |
39d120cac331a3270dbb100e34c9f1e9dc1ff895 | 163 | Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'trellos#index'
end
| 32.6 | 102 | 0.779141 |
0125238e7ae8446ecb48a31312a71aae1b72b7ec | 8,331 | =begin
#NSX-T Data Center Policy API
#VMware NSX-T Data Center Policy REST API
OpenAPI spec version: 3.1.0.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.19
=end
require 'date'
module NSXTPolicy
# BGP neighbor learned/advertised route details.
class BgpNeighborRouteDetailsCsvRecord
# BGP Multi Exit Discriminator attribute.
attr_accessor :med
# CIDR network address.
attr_accessor :network
# BGP Weight attribute.
attr_accessor :weight
# Transport node id
attr_accessor :transport_node_id
# BGP AS path attribute.
attr_accessor :as_path
# Next hop IP address.
attr_accessor :next_hop
# Logical router id
attr_accessor :logical_router_id
# BGP Local Preference attribute.
attr_accessor :local_pref
# BGP neighbor source address.
attr_accessor :source_address
# BGP neighbor id
attr_accessor :neighbor_id
# BGP neighbor peer IP address.
attr_accessor :neighbor_address
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'med' => :'med',
:'network' => :'network',
:'weight' => :'weight',
:'transport_node_id' => :'transport_node_id',
:'as_path' => :'as_path',
:'next_hop' => :'next_hop',
:'logical_router_id' => :'logical_router_id',
:'local_pref' => :'local_pref',
:'source_address' => :'source_address',
:'neighbor_id' => :'neighbor_id',
:'neighbor_address' => :'neighbor_address'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'med' => :'Integer',
:'network' => :'String',
:'weight' => :'Integer',
:'transport_node_id' => :'String',
:'as_path' => :'String',
:'next_hop' => :'String',
:'logical_router_id' => :'String',
:'local_pref' => :'Integer',
:'source_address' => :'String',
:'neighbor_id' => :'String',
:'neighbor_address' => :'String'
}
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?(:'med')
self.med = attributes[:'med']
end
if attributes.has_key?(:'network')
self.network = attributes[:'network']
end
if attributes.has_key?(:'weight')
self.weight = attributes[:'weight']
end
if attributes.has_key?(:'transport_node_id')
self.transport_node_id = attributes[:'transport_node_id']
end
if attributes.has_key?(:'as_path')
self.as_path = attributes[:'as_path']
end
if attributes.has_key?(:'next_hop')
self.next_hop = attributes[:'next_hop']
end
if attributes.has_key?(:'logical_router_id')
self.logical_router_id = attributes[:'logical_router_id']
end
if attributes.has_key?(:'local_pref')
self.local_pref = attributes[:'local_pref']
end
if attributes.has_key?(:'source_address')
self.source_address = attributes[:'source_address']
end
if attributes.has_key?(:'neighbor_id')
self.neighbor_id = attributes[:'neighbor_id']
end
if attributes.has_key?(:'neighbor_address')
self.neighbor_address = attributes[:'neighbor_address']
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
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?
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 &&
med == o.med &&
network == o.network &&
weight == o.weight &&
transport_node_id == o.transport_node_id &&
as_path == o.as_path &&
next_hop == o.next_hop &&
logical_router_id == o.logical_router_id &&
local_pref == o.local_pref &&
source_address == o.source_address &&
neighbor_id == o.neighbor_id &&
neighbor_address == o.neighbor_address
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
[med, network, weight, transport_node_id, as_path, next_hop, logical_router_id, local_pref, source_address, neighbor_id, neighbor_address].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 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 = NSXTPolicy.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
| 29.027875 | 149 | 0.614212 |
618c0ab28756296f5c27ce9492db2ebee0a331e5 | 426 | module Swift
module Gist
end
end
require "swift/gist/cli"
require "swift/gist/file_watcher"
require "swift/gist/format_swift_module"
require "swift/gist/generate_project"
require "swift/gist/generate_project_art"
require "swift/gist/runner"
require "swift/gist/spm_package_creator"
require "swift/gist/spm_project_creator"
require "swift/gist/stdin_watcher"
require "swift/gist/swift_module"
require "swift/gist/version"
| 25.058824 | 41 | 0.819249 |
5dac53c1792c65d05c06d7201234c99f093a1a3c | 2,554 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'metasploit/framework/hashes/identify'
class MetasploitModule < Msf::Post
include Msf::Post::File
include Msf::Post::Linux::Priv
include Msf::Auxiliary::Report
def initialize(info = {})
super( update_info( info,
'Name' => 'BSD Dump Password Hashes',
'Description' => %q{ Post module to dump the password hashes for all users on a BSD system. },
'License' => MSF_LICENSE,
'Author' => ['bcoles'],
'Platform' => ['bsd'],
'SessionTypes' => ['shell', 'meterpreter']
))
end
def run
unless is_root?
fail_with Failure::NoAccess, 'You must run this module as root!'
end
passwd = read_file('/etc/passwd').to_s
unless passwd.blank?
p = store_loot('passwd', 'text/plain', session, passwd, 'passwd', 'BSD passwd file')
vprint_good("passwd saved in: #{p}")
end
master_passwd = read_file('/etc/master.passwd').to_s
unless master_passwd.blank?
p = store_loot('master.passwd', 'text/plain', session, master_passwd, 'master.passwd', 'BSD master.passwd file')
vprint_good("master.passwd saved in: #{p}")
end
# Unshadow passswords
john_file = unshadow(passwd, master_passwd)
return if john_file == ''
john_file.each_line do |l|
hash_parts = l.split(':')
jtr_format = identify_hash hash_parts[1]
if jtr_format.empty? # overide the default
jtr_format = 'des,bsdi,sha512,crypt'
end
credential_data = {
jtr_format: jtr_format,
origin_type: :session,
post_reference_name: self.refname,
private_type: :nonreplayable_hash,
private_data: hash_parts[1],
session_id: session_db_id,
username: hash_parts[0],
workspace_id: myworkspace_id
}
create_credential(credential_data)
print_good(l.chomp)
end
p = store_loot('bsd.hashes', 'text/plain', session, john_file, 'unshadowed.passwd', 'BSD Unshadowed Password File')
print_good("Unshadowed Password File: #{p}")
end
def unshadow(pf, sf)
unshadowed = ''
sf.each_line do |sl|
pass = sl.scan(/^\w*:([^:]*)/).join
next if pass == '*'
next if pass == '!'
user = sl.scan(/(^\w*):/).join
pf.each_line do |pl|
next unless pl.match(/^#{user}:/)
unshadowed << pl.gsub(/:\*:/,":#{pass}:")
end
end
unshadowed
end
end
| 28.065934 | 119 | 0.618246 |
5d75a95e31a59769d669a8237ff93c250a4bf71f | 254 | RSpec.describe Supabase do
it 'has a version number' do
expect(Supabase::VERSION).not_to be nil
end
end
RSpec.describe Supabase::Error do
it "descends StandardError" do
expect(Supabase::Error.ancestors).to include(StandardError)
end
end
| 21.166667 | 63 | 0.751969 |
6af6b32208989b2946d3bbc5bc099fba24d0fa60 | 18,411 | #!/usr/bin/env ruby
# encoding: utf-8
require 'test/unit'
require File.join(File.dirname(__FILE__), 'setup_variant')
require 'stringio'
require 'tempfile'
require 'ostruct'
unless Array.method_defined?(:permutation)
begin
require 'enumerator'
require 'permutation'
class Array
def permutation
Permutation.for(self).to_enum.map { |x| x.project }
end
end
rescue LoadError
warn "Skipping permutation tests."
end
end
class TestJSON < Test::Unit::TestCase
include JSON
def setup
@ary = [1, "foo", 3.14, 4711.0, 2.718, nil, [1,-2,3], false, true].map do
|x| [x]
end
@ary_to_parse = ["1", '"foo"', "3.14", "4711.0", "2.718", "null",
"[1,-2,3]", "false", "true"].map do
|x| "[#{x}]"
end
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
'"g":"\\"\\u0000\\u001f","h":1.0E3,"i":1.0E-3}'
end
def test_construction
parser = JSON::Parser.new('test')
assert_equal 'test', parser.source
end
def assert_equal_float(expected, is)
assert_in_delta(expected.first, is.first, 1e-2)
end
def test_parse_simple_arrays
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([nil], parse('[null]'))
assert_equal([false], parse('[false]'))
assert_equal([true], parse('[true]'))
assert_equal([-23], parse('[-23]'))
assert_equal([23], parse('[23]'))
assert_equal([0.23], parse('[0.23]'))
assert_equal([0.0], parse('[0e0]'))
assert_raises(JSON::ParserError) { parse('[+23.2]') }
assert_raises(JSON::ParserError) { parse('[+23]') }
assert_raises(JSON::ParserError) { parse('[.23]') }
assert_raises(JSON::ParserError) { parse('[023]') }
assert_equal_float [3.141], parse('[3.141]')
assert_equal_float [-3.141], parse('[-3.141]')
assert_equal_float [3.141], parse('[3141e-3]')
assert_equal_float [3.141], parse('[3141.1e-3]')
assert_equal_float [3.141], parse('[3141E-3]')
assert_equal_float [3.141], parse('[3141.0E-3]')
assert_equal_float [-3.141], parse('[-3141.0e-3]')
assert_equal_float [-3.141], parse('[-3141e-3]')
assert_raises(ParserError) { parse('[NaN]') }
assert parse('[NaN]', :allow_nan => true).first.nan?
assert_raises(ParserError) { parse('[Infinity]') }
assert_equal [1.0/0], parse('[Infinity]', :allow_nan => true)
assert_raises(ParserError) { parse('[-Infinity]') }
assert_equal [-1.0/0], parse('[-Infinity]', :allow_nan => true)
assert_equal([""], parse('[""]'))
assert_equal(["foobar"], parse('["foobar"]'))
assert_equal([{}], parse('[{}]'))
end
def test_parse_simple_objects
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({ "a" => nil }, parse('{ "a" : null}'))
assert_equal({ "a" => nil }, parse('{"a":null}'))
assert_equal({ "a" => false }, parse('{ "a" : false } '))
assert_equal({ "a" => false }, parse('{"a":false}'))
assert_raises(JSON::ParserError) { parse('{false}') }
assert_equal({ "a" => true }, parse('{"a":true}'))
assert_equal({ "a" => true }, parse(' { "a" : true } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => 23 }, parse('{"a":23 } '))
assert_equal({ "a" => 23 }, parse(' { "a" : 23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
end
def test_parse_json_primitive_values
assert_raise(JSON::ParserError) { JSON.parse('') }
assert_raise(JSON::ParserError) { JSON.parse('', :quirks_mode => true) }
assert_raise(TypeError) { JSON::Parser.new(nil).parse }
assert_raise(TypeError) { JSON::Parser.new(nil, :quirks_mode => true).parse }
assert_raise(TypeError) { JSON.parse(nil) }
assert_raise(TypeError) { JSON.parse(nil, :quirks_mode => true) }
assert_raise(JSON::ParserError) { JSON.parse(' /* foo */ ') }
assert_raise(JSON::ParserError) { JSON.parse(' /* foo */ ', :quirks_mode => true) }
parser = JSON::Parser.new('null')
assert_equal false, parser.quirks_mode?
assert_raise(JSON::ParserError) { parser.parse }
assert_raise(JSON::ParserError) { JSON.parse('null') }
assert_equal nil, JSON.parse('null', :quirks_mode => true)
parser = JSON::Parser.new('null', :quirks_mode => true)
assert_equal true, parser.quirks_mode?
assert_equal nil, parser.parse
assert_raise(JSON::ParserError) { JSON.parse('false') }
assert_equal false, JSON.parse('false', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('true') }
assert_equal true, JSON.parse('true', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('23') }
assert_equal 23, JSON.parse('23', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('1') }
assert_equal 1, JSON.parse('1', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('3.141') }
assert_in_delta 3.141, JSON.parse('3.141', :quirks_mode => true), 1E-3
assert_raise(JSON::ParserError) { JSON.parse('18446744073709551616') }
assert_equal 2 ** 64, JSON.parse('18446744073709551616', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('"foo"') }
assert_equal 'foo', JSON.parse('"foo"', :quirks_mode => true)
assert_raise(JSON::ParserError) { JSON.parse('NaN', :allow_nan => true) }
assert JSON.parse('NaN', :quirks_mode => true, :allow_nan => true).nan?
assert_raise(JSON::ParserError) { JSON.parse('Infinity', :allow_nan => true) }
assert JSON.parse('Infinity', :quirks_mode => true, :allow_nan => true).infinite?
assert_raise(JSON::ParserError) { JSON.parse('-Infinity', :allow_nan => true) }
assert JSON.parse('-Infinity', :quirks_mode => true, :allow_nan => true).infinite?
assert_raise(JSON::ParserError) { JSON.parse('[ 1, ]', :quirks_mode => true) }
end
if Array.method_defined?(:permutation)
def test_parse_more_complex_arrays
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
json = pretty_generate(perm)
assert_equal perm, parse(json)
end
end
def test_parse_complex_objects
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
s = "a"
orig_obj = perm.inject({}) { |h, x| h[s.dup] = x; s = s.succ; h }
json = pretty_generate(orig_obj)
assert_equal orig_obj, parse(json)
end
end
end
def test_parse_arrays
assert_equal([1,2,3], parse('[1,2,3]'))
assert_equal([1.2,2,3], parse('[1.2,2,3]'))
assert_equal([[],[[],[]]], parse('[[],[[],[]]]'))
end
def test_parse_values
assert_equal([""], parse('[""]'))
assert_equal(["\\"], parse('["\\\\"]'))
assert_equal(['"'], parse('["\""]'))
assert_equal(['\\"\\'], parse('["\\\\\\"\\\\"]'))
assert_equal(["\"\b\n\r\t\0\037"],
parse('["\"\b\n\r\t\u0000\u001f"]'))
for i in 0 ... @ary.size
assert_equal(@ary[i], parse(@ary_to_parse[i]))
end
end
def test_parse_array
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([1], parse('[1]'))
assert_equal([1], parse(' [ 1 ] '))
assert_equal(@ary,
parse('[[1],["foo"],[3.14],[47.11e+2],[2718.0E-3],[null],[[1,-2,3]]'\
',[false],[true]]'))
assert_equal(@ary, parse(%Q{ [ [1] , ["foo"] , [3.14] \t , [47.11e+2]\s
, [2718.0E-3 ],\r[ null] , [[1, -2, 3 ]], [false ],[ true]\n ] }))
end
class SubArray < Array
def <<(v)
@shifted = true
super
end
def shifted?
@shifted
end
end
class SubArray2 < Array
def to_json(*a)
{
JSON.create_id => self.class.name,
'ary' => to_a,
}.to_json(*a)
end
def self.json_create(o)
o.delete JSON.create_id
o['ary']
end
end
class SubArrayWrapper
def initialize
@data = []
end
attr_reader :data
def [](index)
@data[index]
end
def <<(value)
@data << value
@shifted = true
end
def shifted?
@shifted
end
end
def test_parse_array_custom_array_derived_class
res = parse('[1,2]', :array_class => SubArray)
assert_equal([1,2], res)
assert_equal(SubArray, res.class)
assert res.shifted?
end
def test_parse_array_custom_non_array_derived_class
res = parse('[1,2]', :array_class => SubArrayWrapper)
assert_equal([1,2], res.data)
assert_equal(SubArrayWrapper, res.class)
assert res.shifted?
end
def test_parse_object
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({'foo'=>'bar'}, parse('{"foo":"bar"}'))
assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } '))
end
class SubHash < Hash
def []=(k, v)
@item_set = true
super
end
def item_set?
@item_set
end
end
class SubHash2 < Hash
def to_json(*a)
{
JSON.create_id => self.class.name,
}.merge(self).to_json(*a)
end
def self.json_create(o)
o.delete JSON.create_id
self[o]
end
end
class SubOpenStruct < OpenStruct
def [](k)
__send__(k)
end
def []=(k, v)
@item_set = true
__send__("#{k}=", v)
end
def item_set?
@item_set
end
end
def test_parse_object_custom_hash_derived_class
res = parse('{"foo":"bar"}', :object_class => SubHash)
assert_equal({"foo" => "bar"}, res)
assert_equal(SubHash, res.class)
assert res.item_set?
end
def test_parse_object_custom_non_hash_derived_class
res = parse('{"foo":"bar"}', :object_class => SubOpenStruct)
assert_equal "bar", res.foo
assert_equal(SubOpenStruct, res.class)
assert res.item_set?
end
def test_parse_generic_object
res = parse('{"foo":"bar", "baz":{}}', :object_class => JSON::GenericObject)
assert_equal(JSON::GenericObject, res.class)
assert_equal "bar", res.foo
assert_equal "bar", res["foo"]
assert_equal "bar", res[:foo]
assert_equal "bar", res.to_hash[:foo]
assert_equal(JSON::GenericObject, res.baz.class)
end
def test_generate_core_subclasses_with_new_to_json
obj = SubHash2["foo" => SubHash2["bar" => true]]
obj_json = JSON(obj)
obj_again = JSON.parse(obj_json, :create_additions => true)
assert_kind_of SubHash2, obj_again
assert_kind_of SubHash2, obj_again['foo']
assert obj_again['foo']['bar']
assert_equal obj, obj_again
assert_equal ["foo"], JSON(JSON(SubArray2["foo"]), :create_additions => true)
end
def test_generate_core_subclasses_with_default_to_json
assert_equal '{"foo":"bar"}', JSON(SubHash["foo" => "bar"])
assert_equal '["foo"]', JSON(SubArray["foo"])
end
def test_generate_of_core_subclasses
obj = SubHash["foo" => SubHash["bar" => true]]
obj_json = JSON(obj)
obj_again = JSON(obj_json)
assert_kind_of Hash, obj_again
assert_kind_of Hash, obj_again['foo']
assert obj_again['foo']['bar']
assert_equal obj, obj_again
end
def test_parser_reset
parser = Parser.new(@json)
assert_equal(@hash, parser.parse)
assert_equal(@hash, parser.parse)
end
def test_comments
json = <<EOT
{
"key1":"value1", // eol comment
"key2":"value2" /* multi line
* comment */,
"key3":"value3" /* multi line
// nested eol comment
* comment */
}
EOT
assert_equal(
{ "key1" => "value1", "key2" => "value2", "key3" => "value3" },
parse(json))
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
/* illegal nested multi line comment */
* comment */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
closed multi comment */
and again, throw an Error */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /*/*/
}
EOT
assert_equal({ "key1" => "value1" }, parse(json))
end
def test_backslash
data = [ '\\.(?i:gif|jpe?g|png)$' ]
json = '["\\\\.(?i:gif|jpe?g|png)$"]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
data = [ '\\"' ]
json = '["\\\\\""]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
json = '["/"]'
data = JSON.parse(json)
assert_equal ['/'], data
assert_equal json, JSON.generate(data)
#
json = '["\""]'
data = JSON.parse(json)
assert_equal ['"'], data
assert_equal json, JSON.generate(data)
json = '["\\\'"]'
data = JSON.parse(json)
assert_equal ["'"], data
assert_equal '["\'"]', JSON.generate(data)
end
def test_wrong_inputs
assert_raises(ParserError) { JSON.parse('"foo"') }
assert_raises(ParserError) { JSON.parse('123') }
assert_raises(ParserError) { JSON.parse('[] bla') }
assert_raises(ParserError) { JSON.parse('[] 1') }
assert_raises(ParserError) { JSON.parse('[] []') }
assert_raises(ParserError) { JSON.parse('[] {}') }
assert_raises(ParserError) { JSON.parse('{} []') }
assert_raises(ParserError) { JSON.parse('{} {}') }
assert_raises(ParserError) { JSON.parse('[NULL]') }
assert_raises(ParserError) { JSON.parse('[FALSE]') }
assert_raises(ParserError) { JSON.parse('[TRUE]') }
assert_raises(ParserError) { JSON.parse('[07] ') }
assert_raises(ParserError) { JSON.parse('[0a]') }
assert_raises(ParserError) { JSON.parse('[1.]') }
assert_raises(ParserError) { JSON.parse(' ') }
end
def test_nesting
assert_raises(JSON::NestingError) { JSON.parse '[[]]', :max_nesting => 1 }
assert_raises(JSON::NestingError) { JSON.parser.new('[[]]', :max_nesting => 1).parse }
assert_equal [[]], JSON.parse('[[]]', :max_nesting => 2)
too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
too_deep_ary = eval too_deep
assert_raises(JSON::NestingError) { JSON.parse too_deep }
assert_raises(JSON::NestingError) { JSON.parser.new(too_deep).parse }
assert_raises(JSON::NestingError) { JSON.parse too_deep, :max_nesting => 100 }
ok = JSON.parse too_deep, :max_nesting => 101
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => nil
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => false
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => 0
assert_equal too_deep_ary, ok
assert_raises(JSON::NestingError) { JSON.generate [[]], :max_nesting => 1 }
assert_equal '[[]]', JSON.generate([[]], :max_nesting => 2)
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary }
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary, :max_nesting => 100 }
ok = JSON.generate too_deep_ary, :max_nesting => 101
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => nil
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => false
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => 0
assert_equal too_deep, ok
end
def test_symbolize_names
assert_equal({ "foo" => "bar", "baz" => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}'))
assert_equal({ :foo => "bar", :baz => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true))
end
def test_load
assert_equal @hash, JSON.load(@json)
tempfile = Tempfile.open('json')
tempfile.write @json
tempfile.rewind
assert_equal @hash, JSON.load(tempfile)
stringio = StringIO.new(@json)
stringio.rewind
assert_equal @hash, JSON.load(stringio)
assert_equal nil, JSON.load(nil)
assert_equal nil, JSON.load('')
end
def test_load_with_options
small_hash = JSON("foo" => 'bar')
symbol_hash = { :foo => 'bar' }
assert_equal symbol_hash, JSON.load(small_hash, nil, :symbolize_names => true)
end
def test_dump
too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
assert_equal too_deep, JSON.dump(eval(too_deep))
assert_kind_of String, Marshal.dump(eval(too_deep))
assert_raises(ArgumentError) { JSON.dump(eval(too_deep), 100) }
assert_raises(ArgumentError) { Marshal.dump(eval(too_deep), 100) }
assert_equal too_deep, JSON.dump(eval(too_deep), 101)
assert_kind_of String, Marshal.dump(eval(too_deep), 101)
output = StringIO.new
JSON.dump(eval(too_deep), output)
assert_equal too_deep, output.string
output = StringIO.new
JSON.dump(eval(too_deep), output, 101)
assert_equal too_deep, output.string
end
def test_big_integers
json1 = JSON([orig = (1 << 31) - 1])
assert_equal orig, JSON[json1][0]
json2 = JSON([orig = 1 << 31])
assert_equal orig, JSON[json2][0]
json3 = JSON([orig = (1 << 62) - 1])
assert_equal orig, JSON[json3][0]
json4 = JSON([orig = 1 << 62])
assert_equal orig, JSON[json4][0]
json5 = JSON([orig = 1 << 64])
assert_equal orig, JSON[json5][0]
end
if defined?(JSON::Ext::Parser)
def test_allocate
parser = JSON::Ext::Parser.new("{}")
assert_raise(TypeError, '[ruby-core:35079]') {parser.__send__(:initialize, "{}")}
parser = JSON::Ext::Parser.allocate
assert_raise(TypeError, '[ruby-core:35079]') {parser.source}
end
end
def test_argument_encoding
source = "{}".force_encoding("ascii-8bit")
JSON::Parser.new(source)
assert_equal Encoding::ASCII_8BIT, source.encoding
end if defined?(Encoding::ASCII_8BIT)
end
| 33.71978 | 229 | 0.588616 |
1ccdb264c31df43ff238a9b8f67d5dc010ef922b | 4,892 | describe "Time Spiral block" do
include_context "db", "tsp", "tsb", "plc", "fut"
it "is:future" do
assert_search_include "is:future", "Dryad Arbor"
assert_search_exclude "is:new", "Dryad Arbor"
assert_search_exclude "is:old", "Dryad Arbor"
assert_search_results "is:future is:vanilla",
"Blade of the Sixth Pride",
"Blind Phantasm",
"Fomori Nomad",
"Mass of Ghouls",
"Nessian Courser",
"Dryad Arbor" # not sure if it ought to be so
end
it "is:new" do
assert_search_exclude "is:future", "Amrou Scout"
assert_search_include "is:new", "Amrou Scout"
assert_search_exclude "is:old", "Amrou Scout"
end
it "is:old" do
assert_search_exclude "is:future", "Squire"
assert_search_exclude "is:new", "Squire"
assert_search_include "is:old", "Squire"
end
it "is:*-bordered" do
"is:black-bordered" .should include_cards "Dryad Arbor"
"is:white-bordered" .should return_no_cards "Dryad Arbor"
"is:silver-bordered".should return_no_cards "Dryad Arbor"
end
it "Dryad Arbor" do
assert_search_include "c:g", "Dryad Arbor"
assert_search_exclude "c:l", "Dryad Arbor"
assert_search_exclude "c:c", "Dryad Arbor"
assert_search_include "is:permanent", "Dryad Arbor"
assert_search_exclude "is:spell", "Dryad Arbor"
assert_search_results "t:land t:creature", "Dryad Arbor"
end
it "Ghostfire" do
assert_search_exclude "c:r", "Ghostfire"
assert_search_include "ci:r", "Ghostfire"
assert_search_include "c:c", "Ghostfire"
end
it "Non-ASCII" do
assert_search_results "Dralnu", "Dralnu, Lich Lord"
assert_search_results "Dralnu Lich Lord", "Dralnu, Lich Lord"
assert_search_results "Dralnu, Lich Lord", "Dralnu, Lich Lord"
assert_search_results "Dralnu , Lich Lord", "Dralnu, Lich Lord"
assert_search_results "Dandân", "Dandân"
assert_search_results "Dandan", "Dandân"
assert_search_results "Cutthroat il-Dal", "Cutthroat il-Dal"
assert_search_results "Cutthroat il Dal", "Cutthroat il-Dal"
assert_search_results "Cutthroat ildal", "Cutthroat il-Dal" # Thanks to spelling corrections
assert_search_results "Lim-Dûl the Necromancer", "Lim-Dûl the Necromancer"
assert_search_results "Lim-Dul the Necromancer", "Lim-Dûl the Necromancer"
assert_search_results "Lim Dul the Necromancer", "Lim-Dûl the Necromancer"
assert_search_results "Limdul the Necromancer", "Lim-Dûl the Necromancer"
assert_search_results "limdul necromancer", "Lim-Dûl the Necromancer"
assert_search_results "lim dul necromancer", "Lim-Dûl the Necromancer"
assert_search_results "lim dul necromancer", "Lim-Dûl the Necromancer"
assert_search_results "Sarpadian Empires, Vol. VII", "Sarpadian Empires, Vol. VII"
assert_search_results "sarpadian empires vol vii", "Sarpadian Empires, Vol. VII"
assert_search_results "sarpadian empires", "Sarpadian Empires, Vol. VII"
end
it "is: opposes not:" do
assert_search_equal "not:future", "-is:future"
assert_search_equal "not:new", "-is:new"
assert_search_equal "not:old", "-is:old"
end
it "is:timeshifted" do
assert_count_printings "is:timeshifted", 45
end
it "manaless suspend cards" do
assert_search_results "cmc=0 o:suspend", "Ancestral Vision", "Hypergenesis", "Living End", "Lotus Bloom", "Restore Balance", "Wheel of Fate"
assert_search_results "cmc=0 o:suspend ci:c", "Lotus Bloom"
assert_search_results "cmc=0 o:suspend ci:u", "Lotus Bloom", "Ancestral Vision"
assert_search_results "cmc=0 o:suspend c:c", "Lotus Bloom"
assert_search_results "cmc=0 o:suspend c:u", "Ancestral Vision"
assert_search_results "cmc=0 o:suspend mana=0"
end
# This goes against magiccards.info logic which treats * as 0
# I'm not sure yet if it makes any sense or not
it "lhurgoyfs" do
assert_search_results "t:lhurgoyf", "Tarmogoyf", "Detritivore"
assert_search_results "t:lhurgoyf pow=0"
assert_search_results "t:lhurgoyf tou=0"
assert_search_results "t:lhurgoyf tou=1"
assert_search_results "t:lhurgoyf pow>=0"
assert_search_results "t:lhurgoyf tou>=0"
assert_search_results "t:lhurgoyf pow<tou", "Tarmogoyf"
assert_search_results "t:lhurgoyf pow<=tou", "Tarmogoyf", "Detritivore"
assert_search_results "t:lhurgoyf pow>=tou", "Detritivore"
assert_search_results "t:lhurgoyf pow=tou", "Detritivore"
assert_search_results "t:lhurgoyf pow>tou"
end
it "negative" do
assert_search_results "pow=-1", "Char-Rumbler"
assert_search_results "pow<0", "Char-Rumbler"
assert_search_include "pow>=-1", "Char-Rumbler"
assert_search_include "pow>=-2", "Char-Rumbler"
assert_search_exclude "pow>-1", "Char-Rumbler"
end
it "oracle unicode" do
assert_search_results %Q[ft:"Lim-Dûl"], "Drudge Reavers"
assert_search_results %Q[ft:"Lim-Dul"], "Drudge Reavers"
end
end
| 40.766667 | 144 | 0.717089 |
ffa0eed91f5a145183935ace9cc0bd483dc1b28a | 1,403 | =begin
#TextMagic API
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.8
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for TextMagic::MuteChatInputObject
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'MuteChatInputObject' do
before do
# run before each test
@instance = TextMagic::MuteChatInputObject.new
end
after do
# run after each test
end
describe 'test an instance of MuteChatInputObject' do
it 'should create an instance of MuteChatInputObject' do
expect(@instance).to be_instance_of(TextMagic::MuteChatInputObject)
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 "mute"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "_for"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 25.981481 | 102 | 0.735567 |
1ac62ac09efaf60fafedde677ce209cda6426467 | 176 | class DomainTerm < ActiveRecord::Base
# TODO we should add an index on this join table and remove the uniq query
has_and_belongs_to_many :local_authorities, -> {uniq}
end
| 29.333333 | 76 | 0.772727 |
e90eeee2b15d0959dd354cc1ec802e50127badda | 146 | require 'test_helper'
module Annex
class BlockTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
end
| 14.6 | 43 | 0.664384 |
6ae8a2cea33cd648c37dbe3a5eb53a12d0a2da58 | 552 | require "pathname"
require "json"
require "ri_cal"
require "addressable/uri"
require "faraday"
require "faraday_middleware"
require "active_support/cache"
require "almanack/base"
require "almanack/version"
require "almanack/configuration"
require "almanack/calendar"
require "almanack/serialized_transformation"
require "almanack/representation/ical_feed"
require "almanack/representation/json_feed"
require "almanack/event"
require "almanack/event_source/static"
require "almanack/event_source/meetup_group"
require "almanack/event_source/ical_feed"
| 27.6 | 44 | 0.835145 |
e9f9c558414c676d90031623bcf63bfb32ba8593 | 2,113 | class EquipamentosController < ApplicationController
before_action :set_equipamento, only: [:show, :edit, :update, :destroy]
# GET /equipamentos
# GET /equipamentos.json
def index
@equipamentos = Equipamento.all
end
# GET /equipamentos/1
# GET /equipamentos/1.json
def show
end
# GET /equipamentos/new
def new
@equipamento = Equipamento.new
end
# GET /equipamentos/1/edit
def edit
end
# POST /equipamentos
# POST /equipamentos.json
def create
@equipamento = Equipamento.new(equipamento_params)
respond_to do |format|
if @equipamento.save
format.html { redirect_to @equipamento, notice: 'Equipamento was successfully created.' }
format.json { render :show, status: :created, location: @equipamento }
else
format.html { render :new }
format.json { render json: @equipamento.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /equipamentos/1
# PATCH/PUT /equipamentos/1.json
def update
respond_to do |format|
if @equipamento.update(equipamento_params)
format.html { redirect_to @equipamento, notice: 'Equipamento was successfully updated.' }
format.json { render :show, status: :ok, location: @equipamento }
else
format.html { render :edit }
format.json { render json: @equipamento.errors, status: :unprocessable_entity }
end
end
end
# DELETE /equipamentos/1
# DELETE /equipamentos/1.json
def destroy
@equipamento.destroy
respond_to do |format|
format.html { redirect_to equipamentos_url, notice: 'Equipamento was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_equipamento
@equipamento = Equipamento.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def equipamento_params
params.require(:equipamento).permit(:nome, :ip, :status, :descricao, :protocolo_id, :sala_id, :tipo_id)
end
end
| 28.173333 | 109 | 0.687175 |
26d561b99a5fadacab041bb1b31eb6f22264b379 | 417 | module EPlusOut
module Relations
class CoolingPeakConditions < Relation
def initialize(gateway, mapper = Mappers::PeakConditionMapper.new)
super(gateway, mapper)
end
def name_field
:report_for_string
end
def clauses
{
table_name: "Cooling Peak Conditions"
}
end
def order_by
[:row_name]
end
end
end
end | 18.130435 | 72 | 0.592326 |
33e754e55a7739e03937c909c05fced5826308b3 | 1,070 | #
# Cookbook:: my_cookbook
# Spec:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
require 'spec_helper'
describe 'my_cookbook::pandbprod01' do
context 'When all attributes are default, on Ubuntu 16.04' do
let(:chef_run) do
# for a complete list of available platforms and versions see:
# https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'When all attributes are default, on CentOS 7.4.1708' do
let(:chef_run) do
# for a complete list of available platforms and versions see:
# https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708')
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
end
| 29.722222 | 82 | 0.7 |
abe53a2f59bec2174f46408d37f7a90c2141c4f8 | 84 | module Furigana
module Util
module Lists
extend self
end
end
end
| 9.333333 | 17 | 0.642857 |
62164164d590d2405415957ec8cf849f3533c02c | 528 | class Project < ApplicationRecord
belongs_to :user
include PgSearch::Model
has_many :volunteers, dependent: :destroy
has_many :volunteered_users, through: :volunteers, source: :user, dependent: :destroy
acts_as_taggable_on :skills
acts_as_taggable_on :project_types
pg_search_scope :search, against: %i(name description participants looking_for location highlight)
def to_param
[id, name.parameterize].join("-")
end
def volunteer_emails
self.volunteered_users.collect { |u| u.email }
end
end
| 24 | 100 | 0.761364 |
1d2b870e2789afd09f7269d0ff87bd3cfa986dc1 | 2,166 | class FdkAacEncoder < Formula
desc "Command-line encoder frontend for libfdk-aac"
homepage "https://github.com/nu774/fdkaac"
url "https://github.com/nu774/fdkaac/archive/v1.0.1.tar.gz"
sha256 "ce9459111cee48c84b2e5e7154fa5a182c8ec1132da880656de3c1bc3bf2cc79"
license "Zlib"
bottle do
sha256 cellar: :any, arm64_big_sur: "cb07e4fec67df342a3a6d9cae8d40e9a2d8436618c4b11f1183145d1eb01faa4"
sha256 cellar: :any, big_sur: "2bb1d960c47fca61a9b677314b64dc2ab1311111c7b36818a46e47aa13bcc675"
sha256 cellar: :any, catalina: "ce0c1d5ff1bc3cc3483d2602fdbb1f3f0e6b8124c821f13f7d22c931bdd64303"
sha256 cellar: :any, mojave: "251c3f283f5bf30c69b05b69fb80e3ef497d17d0f3290e1d11021d51950910ce"
sha256 cellar: :any, high_sierra: "6bd9626cca01c6d07b55143acd321676a573f68ba2ec7734922b936332fab567"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "fdk-aac"
def install
system "autoreconf", "-i"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--mandir=#{man}"
system "make", "install"
end
test do
# generate test tone pcm file
sample_rate = 44100
two_pi = 2 * Math::PI
num_samples = sample_rate
frequency = 440.0
max_amplitude = 0.2
position_in_period = 0.0
position_in_period_delta = frequency / sample_rate
samples = [].fill(0.0, 0, num_samples)
num_samples.times do |i|
samples[i] = Math.sin(position_in_period * two_pi) * max_amplitude
position_in_period += position_in_period_delta
position_in_period -= 1.0 if position_in_period >= 1.0
end
samples.map! do |sample|
(sample * 32767.0).round
end
File.open("#{testpath}/tone.pcm", "wb") do |f|
f.syswrite(samples.flatten.pack("s*"))
end
system "#{bin}/fdkaac", "-R", "--raw-channels", "1", "-m",
"1", "#{testpath}/tone.pcm", "--title", "Test Tone"
end
end
| 32.818182 | 106 | 0.663897 |
384152463c63a6e6214192bb281ad07521ef0669 | 1,548 | require "spec_helper"
describe MaropostApi::Journeys do
before do
@client = MaropostApi::Client.new(auth_token: TOKEN, account_number: ACCOUNT_ID)
end
describe "#start", vcr: true do
context "with correct params" do
it "sends start request with provided params" do
journey_id = "12429"
contact_id = "742520380"
response = @client.journeys.start(journey_id: journey_id, contact_id: contact_id)
expect(response.message).to include("Success")
end
end
end
describe "#stop", vcr: true do
context "with correct params" do
it "sends stop request with provided params" do
journey_id = "12429"
contact_id = "742520380"
response = @client.journeys.stop(journey_id: journey_id, contact_id: contact_id)
expect(response.message).to include("Success")
end
end
end
describe "#reset", vcr: true do
context "with correct params" do
it "sends reset request with provided params" do
journey_id = "12429"
contact_id = "742520380"
response = @client.journeys.reset(journey_id: journey_id, contact_id: contact_id)
expect(response.message).to include("successfully")
end
end
end
describe "#stop_all_journeys", vcr: true do
context "with correct params" do
it "stops all the journeys for the provided email" do
response = @client.journeys.stop_all_journeys(email: "[email protected]")
expect(response.message).to include("Success")
end
end
end
end
| 29.207547 | 89 | 0.669897 |
79f8097afcf18ed883c82ac987cb1140883b85c8 | 6,844 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::Glacier
class Account
extend Aws::Deprecations
# @overload def initialize(id, options = {})
# @param [String] id
# @option options [Client] :client
# @overload def initialize(options = {})
# @option options [required, String] :id
# @option options [Client] :client
def initialize(*args)
options = Hash === args.last ? args.pop.dup : {}
@id = extract_id(args, options)
@data = Aws::EmptyStructure.new
@client = options.delete(:client) || Client.new(options)
@waiter_block_warned = false
end
# @!group Read-Only Attributes
# @return [String]
def id
@id
end
# @!endgroup
# @return [Client]
def client
@client
end
# @raise [NotImplementedError]
# @api private
def load
msg = "#load is not implemented, data only available via enumeration"
raise NotImplementedError, msg
end
alias :reload :load
# @api private
# @return [EmptyStructure]
def data
@data
end
# @return [Boolean]
# Returns `true` if this resource is loaded. Accessing attributes or
# {#data} on an unloaded resource will trigger a call to {#load}.
def data_loaded?
!!@data
end
# @deprecated Use [Aws::Glacier::Client] #wait_until instead
#
# Waiter polls an API operation until a resource enters a desired
# state.
#
# @note The waiting operation is performed on a copy. The original resource
# remains unchanged.
#
# ## Basic Usage
#
# Waiter will polls until it is successful, it fails by
# entering a terminal state, or until a maximum number of attempts
# are made.
#
# # polls in a loop until condition is true
# resource.wait_until(options) {|resource| condition}
#
# ## Example
#
# instance.wait_until(max_attempts:10, delay:5) do |instance|
# instance.state.name == 'running'
# end
#
# ## Configuration
#
# You can configure the maximum number of polling attempts, and the
# delay (in seconds) between each polling attempt. The waiting condition is
# set by passing a block to {#wait_until}:
#
# # poll for ~25 seconds
# resource.wait_until(max_attempts:5,delay:5) {|resource|...}
#
# ## Callbacks
#
# You can be notified before each polling attempt and before each
# delay. If you throw `:success` or `:failure` from these callbacks,
# it will terminate the waiter.
#
# started_at = Time.now
# # poll for 1 hour, instead of a number of attempts
# proc = Proc.new do |attempts, response|
# throw :failure if Time.now - started_at > 3600
# end
#
# # disable max attempts
# instance.wait_until(before_wait:proc, max_attempts:nil) {...}
#
# ## Handling Errors
#
# When a waiter is successful, it returns the Resource. When a waiter
# fails, it raises an error.
#
# begin
# resource.wait_until(...)
# rescue Aws::Waiters::Errors::WaiterFailed
# # resource did not enter the desired state in time
# end
#
# @yieldparam [Resource] resource to be used in the waiting condition.
#
# @raise [Aws::Waiters::Errors::FailureStateError] Raised when the waiter
# terminates because the waiter has entered a state that it will not
# transition out of, preventing success.
#
# yet successful.
#
# @raise [Aws::Waiters::Errors::UnexpectedError] Raised when an error is
# encountered while polling for a resource that is not expected.
#
# @raise [NotImplementedError] Raised when the resource does not
#
# @option options [Integer] :max_attempts (10) Maximum number of
# attempts
# @option options [Integer] :delay (10) Delay between each
# attempt in seconds
# @option options [Proc] :before_attempt (nil) Callback
# invoked before each attempt
# @option options [Proc] :before_wait (nil) Callback
# invoked before each wait
# @return [Resource] if the waiter was successful
def wait_until(options = {}, &block)
self_copy = self.dup
attempts = 0
options[:max_attempts] = 10 unless options.key?(:max_attempts)
options[:delay] ||= 10
options[:poller] = Proc.new do
attempts += 1
if block.call(self_copy)
[:success, self_copy]
else
self_copy.reload unless attempts == options[:max_attempts]
:retry
end
end
Aws::Waiters::Waiter.new(options).wait({})
end
# @!group Actions
# @example Request syntax with placeholder values
#
# vault = account.create_vault({
# vault_name: "string", # required
# })
# @param [Hash] options ({})
# @option options [required, String] :vault_name
# The name of the vault.
# @return [Vault]
def create_vault(options = {})
options = options.merge(account_id: @id)
@client.create_vault(options)
Vault.new(
account_id: @id,
name: options[:vault_name],
client: @client
)
end
# @!group Associations
# @param [String] name
# @return [Vault]
def vault(name)
Vault.new(
account_id: @id,
name: name,
client: @client
)
end
# @example Request syntax with placeholder values
#
# account.vaults()
# @param [Hash] options ({})
# @return [Vault::Collection]
def vaults(options = {})
batches = Enumerator.new do |y|
options = options.merge(account_id: @id)
resp = @client.list_vaults(options)
resp.each_page do |page|
batch = []
page.data.vault_list.each do |v|
batch << Vault.new(
account_id: @id,
name: v.vault_name,
data: v,
client: @client
)
end
y.yield(batch)
end
end
Vault::Collection.new(batches)
end
# @deprecated
# @api private
def identifiers
{ id: @id }
end
deprecated(:identifiers)
private
def extract_id(args, options)
value = args[0] || options.delete(:id)
case value
when String then value
when nil then raise ArgumentError, "missing required option :id"
else
msg = "expected :id to be a String, got #{value.class}"
raise ArgumentError, msg
end
end
class Collection < Aws::Resources::Collection; end
end
end
| 28.164609 | 79 | 0.602425 |
0896cd5992dc8d5e8f9faf4ed1a3fa7489295193 | 1,546 | # -*- encoding: utf-8 -*-
# stub: addressable 2.7.0 ruby lib
Gem::Specification.new do |s|
s.name = "addressable".freeze
s.version = "2.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Bob Aman".freeze]
s.date = "2019-08-31"
s.description = "Addressable is an alternative implementation to the URI implementation that is\npart of Ruby's standard library. It is flexible, offers heuristic parsing, and\nadditionally provides extensive support for IRIs and URI templates.\n".freeze
s.email = "[email protected]".freeze
s.extra_rdoc_files = ["README.md".freeze]
s.files = ["README.md".freeze]
s.homepage = "https://github.com/sporkmonger/addressable".freeze
s.licenses = ["Apache-2.0".freeze]
s.rdoc_options = ["--main".freeze, "README.md".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze)
s.rubygems_version = "3.1.3".freeze
s.summary = "URI Implementation".freeze
s.installed_by_version = "3.1.3" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<public_suffix>.freeze, [">= 2.0.2", "< 5.0"])
s.add_development_dependency(%q<bundler>.freeze, [">= 1.0", "< 3.0"])
else
s.add_dependency(%q<public_suffix>.freeze, [">= 2.0.2", "< 5.0"])
s.add_dependency(%q<bundler>.freeze, [">= 1.0", "< 3.0"])
end
end
| 41.783784 | 256 | 0.697283 |
7ac1bd58edee2a829b09e0ec105a45f40b55dee5 | 1,816 | # frozen_string_literal: true
module SystemCheck
# Used by gitlab:sidekiq:check rake task
class SidekiqCheck < BaseCheck
set_name 'Sidekiq:'
def multi_check
check_sidekiq_running
only_one_sidekiq_running
end
private
def check_sidekiq_running
$stdout.print "Running? ... "
if sidekiq_worker_process_count > 0
$stdout.puts "yes".color(:green)
else
$stdout.puts "no".color(:red)
try_fixing_it(
sudo_gitlab("RAILS_ENV=production bin/background_jobs start")
)
for_more_information(
see_installation_guide_section("Install Init Script"),
"see log/sidekiq.log for possible errors"
)
fix_and_rerun
end
end
def only_one_sidekiq_running
worker_count = sidekiq_worker_process_count
cluster_count = sidekiq_cluster_process_count
return if worker_count == 0
$stdout.print 'Number of Sidekiq processes (cluster/worker) ... '
if (cluster_count == 1 && worker_count > 0) || (cluster_count == 0 && worker_count == 1)
$stdout.puts "#{cluster_count}/#{worker_count}".color(:green)
else
$stdout.puts "#{cluster_count}/#{worker_count}".color(:red)
try_fixing_it(
'sudo service gitlab stop',
"sudo pkill -u #{gitlab_user} -f sidekiq",
"sleep 10 && sudo pkill -9 -u #{gitlab_user} -f sidekiq",
'sudo service gitlab start'
)
fix_and_rerun
end
end
def sidekiq_worker_process_count
ps_ux, _ = Gitlab::Popen.popen(%w(ps uxww))
ps_ux.lines.grep(/sidekiq \d+\.\d+\.\d+/).count
end
def sidekiq_cluster_process_count
ps_ux, _ = Gitlab::Popen.popen(%w(ps uxww))
ps_ux.lines.grep(/sidekiq-cluster/).count
end
end
end
| 27.938462 | 94 | 0.633811 |
6a19b0b218cdeb26dbb8a804c5247020a899b945 | 133,619 | # encoding: US-ASCII
$TESTING = true
# :stopdoc:
require "minitest/test"
require "sexp_processor" # for deep_clone
# key:
# wwtt = what were they thinking?
class Examples
attr_reader :reader
attr_writer :writer
def a_method x; x+1; end
alias an_alias a_method
define_method(:bmethod_noargs) do
x + 1
end
define_method(:unsplatted) do |x|
x + 1
end
define_method :splatted do |*args|
y = args.first
y + 42
end
define_method :dmethod_added, instance_method(:a_method) if
RUBY_VERSION < "1.9"
end
class ParseTreeTestCase < Minitest::Test
attr_accessor :processor # to be defined by subclass
def setup
super
@processor = nil
end
def after_process_hook klass, node, data, input_name, output_name
end
def before_process_hook klass, node, data, input_name, output_name
end
def self.add_test name, data, klass = self.name[4..-1]
name = name.to_s
klass = klass.to_s
if testcases.has_key? name then
if testcases[name].has_key? klass then
warn "testcase #{klass}##{name} already has data"
else
testcases[name][klass] = data
end
else
warn "testcase #{name} does not exist"
end
end
def self.add_tests name, hash
name = name.to_s
hash.each do |klass, data|
warn "testcase #{klass}##{name} already has data" if
testcases[name].has_key? klass
testcases[name][klass] = data
end
end
def self.add_18tests name, hash
add_tests "#{name}__18", hash
end
def self.add_19tests name, hash
add_tests "#{name}__19_20_21_22_23_24", hash # HACK?
end
def self.add_19edgecases ruby, sexp, cases
cases.each do |name, code|
add_19tests name, "Ruby" => code, "ParseTree" => sexp, "Ruby2Ruby" => ruby
end
end
def self.clone_same
@@testcases.each do |node, data|
data.each do |key, val|
if val == :same then
prev_key = self.previous(key)
data[key] = data[prev_key].deep_clone
end
end
end
end
def self.copy_test_case nonverbose, klass
verbose = nonverbose + "_mri_verbose_flag"
testcases[verbose][klass] = testcases[nonverbose][klass]
end
VER_RE = "(1[89]|2[01234])"
def self.generate_test klass, node, data, input_name, output_name
klass.send :define_method, "test_#{node}" do
flunk "Processor is nil" if processor.nil?
tversions = node[/(?:_#{VER_RE})+$/]
if tversions then
cversion = self.class.name[/#{VER_RE}/]
assert true # shut up prove_it!
# can't push this up because it may be generating into an
# abstract test class and the actual subclass is versioned.
return "version specific test" unless tversions.include? cversion if cversion
end
assert data.has_key?(input_name), "Unknown input data"
assert data.has_key?(output_name), "Missing test data"
$missing[node] << output_name unless data.has_key? output_name
input = data[input_name].deep_clone
expected = data[output_name].deep_clone
case expected
when :unsupported then
assert_raises(UnsupportedNodeError) do
processor.process(input)
end
else
extra_expected = []
extra_input = []
_, expected, extra_expected = *expected if
Array === expected and expected.sexp_type == :defx
_, input, extra_input = *input if
Array === input and input.sexp_type == :defx
# OMG... I can't believe I have to do this this way. these
# hooks are here instead of refactoring this define_method
# body into an assertion. It'll allow subclasses to hook in
# and add behavior before or after the processor does it's
# thing. If you go the body refactor route, some of the
# RawParseTree test cases fail for completely bogus reasons.
before_process_hook klass, node, data, input_name, output_name
refute_nil data[input_name], "testcase does not exist?"
@result = processor.process input
assert_equal(expected, @result,
"failed on input: #{data[input_name].inspect}")
after_process_hook klass, node, data, input_name, output_name
extra_input.each do |extra|
processor.process(extra)
end
extra = processor.extra_methods rescue []
assert_equal extra_expected, extra
end
end
end
def self.generate_tests klass
install_missing_reporter
clone_same
output_name = klass.name.to_s.sub(/^Test/, "")
input_name = self.previous(output_name)
@@testcases.each do |node, data|
next if [:skip, :unsupported].include? data[input_name]
next if data[output_name] == :skip
generate_test klass, node, data, input_name, output_name
end
end
def self.inherited klass
super
generate_tests klass unless klass.name =~ /TestCase/
end
def self.install_missing_reporter
unless defined? $missing then
$missing = Hash.new { |h,k| h[k] = [] }
at_exit {
at_exit {
warn ""
$missing.sort.each do |name, klasses|
warn "add_tests(#{name.inspect},"
klasses.map! { |klass| " #{klass.inspect} => :same" }
warn klasses.join("\n") + ")"
end
warn ""
}
}
end
end
def self.previous key, extra=0 # FIX: remove R2C code
idx = @@testcase_order.index(key)
raise "Unknown class #{key} in @@testcase_order" if idx.nil?
case key
when "RubyToRubyC" then
idx -= 1
end
@@testcase_order[idx - 1 - extra]
end
def self.testcase_order; @@testcase_order; end
def self.testcases; @@testcases; end
def self.unsupported_tests *tests
tests.flatten.each do |name|
add_test name, :unsupported
end
end
############################################################
# Shared TestCases:
@@testcase_order = %w(Ruby ParseTree)
@@testcases = Hash.new { |h,k| h[k] = {} }
###
# 1.8 specific tests
add_18tests("call_arglist_norm_hash_splat",
"Ruby" => "o.m(42, :a => 1, :b => 2, *c)",
"ParseTree" => s(:call,
s(:call, nil, :o), :m,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)),
s(:splat, s(:call, nil, :c))))
add_18tests("call_arglist_space",
"Ruby" => "a (1,2,3)",
"ParseTree" => s(:call, nil, :a,
s(:lit, 1), s(:lit, 2), s(:lit, 3)),
"Ruby2Ruby" => "a(1, 2, 3)")
add_18tests("fcall_arglist_norm_hash_splat",
"Ruby" => "m(42, :a => 1, :b => 2, *c)",
"ParseTree" => s(:call, nil, :m,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)),
s(:splat, s(:call, nil, :c))))
add_18tests("if_args_no_space_symbol",
"Ruby" => "x if y:z",
"ParseTree" => s(:if,
s(:call, nil, :y, s(:lit, :z)),
s(:call, nil, :x),
nil),
"Ruby2Ruby" => "x if y(:z)")
add_18tests("if_post_not",
"Ruby" => "a if not b",
"ParseTree" => s(:if, s(:call, nil, :b), nil,
s(:call, nil, :a)),
"Ruby2Ruby" => "a unless b")
add_18tests("if_pre_not",
"Ruby" => "if not b then a end",
"ParseTree" => s(:if, s(:call, nil, :b), nil,
s(:call, nil, :a)),
"Ruby2Ruby" => "a unless b")
add_18tests("iter_args_ivar",
"Ruby" => "a { |@a| 42 }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :@a),
s(:lit, 42)))
add_18tests("iter_masgn_args_ivar",
"Ruby" => "a { |a, @b| 42 }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :a, :@b),
s(:lit, 42)))
add_18tests("not",
"Ruby" => "(not true)",
"ParseTree" => s(:not, s(:true)))
add_18tests("str_question_control",
"Ruby" => '?\M-\C-a',
"ParseTree" => s(:lit, 129),
"Ruby2Ruby" => "129")
add_18tests("str_question_escape",
"Ruby" => '?\n',
"ParseTree" => s(:lit, 10),
"Ruby2Ruby" => "10")
add_18tests("str_question_literal",
"Ruby" => "?a",
"ParseTree" => s(:lit, 97),
"Ruby2Ruby" => "97")
add_18tests("unless_post_not",
"Ruby" => "a unless not b",
"ParseTree" => s(:if, s(:call, nil, :b),
s(:call, nil, :a), nil),
"Ruby2Ruby" => "a if b")
add_18tests("unless_pre_not",
"Ruby" => "unless not b then a end",
"ParseTree" => s(:if, s(:call, nil, :b),
s(:call, nil, :a), nil),
"Ruby2Ruby" => "a if b")
add_18tests("until_post_not",
"Ruby" => "begin\n (1 + 1)\nend until not true",
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend while true")
add_18tests("until_pre_not",
"Ruby" => "until not true do\n (1 + 1)\nend",
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_18tests("until_pre_not_mod",
"Ruby" => "(1 + 1) until not true",
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_18tests("while_post_not",
"Ruby" => "begin\n (1 + 1)\nend while not true",
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend until true")
add_18tests("while_pre_not",
"Ruby" => "while not true do\n (1 + 1)\nend",
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend")
add_18tests("while_pre_not_mod",
"Ruby" => "(1 + 1) while not true",
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend") # FIX
###
# 1.9 specific tests
add_19edgecases("lambda { || (x + 1) }",
s(:iter,
s(:call, nil, :lambda),
s(:args),
s(:call, s(:call, nil, :x), :+, s(:lit, 1))),
"stabby_args" => "->() { (x + 1) }",
"stabby_args_doend" => "->() do (x + 1) end")
add_19edgecases("lambda { (x + 1) }",
s(:iter,
s(:call, nil, :lambda),
0,
s(:call, s(:call, nil, :x), :+, s(:lit, 1))),
"stabby_args_0_no_parens" => "-> { (x + 1) }",
"stabby_args_0_no_parens_doend" => "-> do (x + 1) end",
"stabby_args_0_spacebar_broken" => "->{x+1}") # I hate you
add_19edgecases("lambda { |x, y| (x + y) }",
s(:iter,
s(:call, nil, :lambda),
s(:args, :x, :y),
s(:call, s(:lvar, :x), :+, s(:lvar, :y))),
"stabby_args_2" => "->(x, y) { (x + y) }",
"stabby_args_2_doend" => "->(x, y) do (x + y) end",
"stabby_args_2_no_parens" => "-> x, y { (x + y) }",
"stabby_args_2_no_parens_doend" => "-> x, y do (x + y) end")
add_19edgecases("lambda { |x| (x + 1) }",
s(:iter,
s(:call, nil, :lambda),
s(:args, :x),
s(:call, s(:lvar, :x), :+, s(:lit, 1))),
"stabby_args_1" => "->(x) { (x + 1) }",
"stabby_args_1_doend" => "->(x) do (x + 1) end",
"stabby_args_1_no_parens" => "-> x { (x + 1) }",
"stabby_args_1_no_parens_doend" => "-> x do (x + 1) end")
add_19tests("array_bare_hash",
"Ruby" => "[:a, :b => :c]",
"ParseTree" => s(:array,
s(:lit, :a),
s(:hash,
s(:lit, :b),
s(:lit, :c))),
"Ruby2Ruby" => "[:a, { :b => :c }]")
add_19tests("array_bare_hash_labels",
"Ruby" => "[:a, b: :c]",
"ParseTree" => s(:array,
s(:lit, :a),
s(:hash,
s(:lit, :b),
s(:lit, :c))),
"Ruby2Ruby" => "[:a, { :b => :c }]")
add_19tests("call_arglist_norm_hash_colons",
"Ruby" => "o.m(42, a: 1, b: 2)",
"ParseTree" => s(:call,
s(:call, nil, :o),
:m,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
"Ruby2Ruby" => "o.m(42, :a => 1, :b => 2)")
add_19tests("call_arglist_trailing_comma",
"Ruby" => "a(1,2,3,)",
"ParseTree" => s(:call,
nil,
:a,
s(:lit, 1), s(:lit, 2), s(:lit, 3)),
"Ruby2Ruby" => "a(1, 2, 3)")
add_19tests("call_bang",
"Ruby" => "!a",
"ParseTree" => s(:call,
s(:call, nil, :a),
:"!"))
add_19tests("call_bang_empty",
"Ruby" => "! ()",
"ParseTree" => s(:call, s(:nil), :"!"))
add_19tests("call_fonz",
"Ruby" => "a.()",
"ParseTree" => s(:call, s(:call, nil, :a), :call),
"Ruby2Ruby" => "a.call")
add_19tests("call_fonz_cm",
"Ruby" => "a::()",
"ParseTree" => s(:call, s(:call, nil, :a), :call),
"Ruby2Ruby" => "a.call")
add_19tests("call_not",
"Ruby" => "not (42)",
"ParseTree" => s(:call, s(:lit, 42), :"!"))
# add_19tests("call_not_empty",
# "Ruby" => "not ()",
# "ParseTree" => s(:call, s(:lit, 42), :"!"))
add_19tests("call_not_equal",
"Ruby" => "a != b",
"ParseTree" => s(:call,
s(:call, nil, :a),
:"!=",
s(:call, nil, :b)))
add_19tests("call_splat_mid",
"Ruby" => "def f(a = nil, *b, c)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :a, s(:nil)), :"*b", :c),
s(:nil)))
add_19tests("defn_args_mand_opt_mand",
"Ruby" => "def f(mand1, opt = 42, mand2)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand1, s(:lasgn, :opt, s(:lit, 42)), :mand2),
s(:nil)))
add_19tests("defn_args_mand_opt_splat_mand",
"Ruby" => "def f(mand1, opt = 42, *rest, mand2)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand1, s(:lasgn, :opt, s(:lit, 42)), :"*rest", :mand2),
s(:nil)))
add_19tests("defn_args_opt_mand",
"Ruby" => "def f(opt = 42, mand)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :opt, s(:lit, 42)), :mand),
s(:nil)))
add_19tests("defn_args_opt_splat_mand",
"Ruby" => "def f(opt = 42, *rest, mand)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :opt, s(:lit, 42)), :"*rest", :mand),
s(:nil)))
add_19tests("defn_args_splat_mand",
"Ruby" => "def f(*rest, mand)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :"*rest", :mand),
s(:nil)))
add_19tests("defn_args_splat_middle",
"Ruby" => "def f(first, *middle, last)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :first, :"*middle", :last),
s(:nil)))
add_19tests("fcall_arglist_hash_colons",
"Ruby" => "m(a: 1, b: 2)",
"ParseTree" => s(:call, nil, :m,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
"Ruby2Ruby" => "m(:a => 1, :b => 2)")
add_19tests("hash_new",
"Ruby" => "{ a: 1, b: 2 }",
"ParseTree" => s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)),
"Ruby2Ruby" => "{ :a => 1, :b => 2 }")
add_19tests("hash_new_no_space",
"Ruby" => "{a:1,b:2}",
"ParseTree" => s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)),
"Ruby2Ruby" => "{ :a => 1, :b => 2 }")
add_19tests("hash_new_with_keyword",
"Ruby" => "{ true: 1, b: 2 }",
"ParseTree" => s(:hash,
s(:lit, :true), s(:lit, 1),
s(:lit, :b), s(:lit, 2)),
"Ruby2Ruby" => "{ :true => 1, :b => 2 }")
add_19tests("if_post_not",
"Ruby" => "a if not b",
"ParseTree" => s(:if, s(:call, s(:call, nil, :b), :"!"),
s(:call, nil, :a),
nil),
"Ruby2Ruby" => "a unless b")
add_19tests("if_pre_not",
"Ruby" => "if not b then a end",
"ParseTree" => s(:if, s(:call, s(:call, nil, :b), :"!"),
s(:call, nil, :a),
nil),
"Ruby2Ruby" => "a unless b")
add_19tests("label_in_bare_hash_in_array_in_ternary",
"Ruby" => "1 ? [:a, b: 2] : 1",
"ParseTree" => s(:if, s(:lit, 1),
s(:array,
s(:lit, :a),
s(:hash, s(:lit, :b), s(:lit, 2))),
s(:lit, 1)),
"Ruby2Ruby" => "1 ? ([:a, { :b => 2 }]) : (1)")
add_19tests("label_in_callargs_in_ternary",
"Ruby" => "1 ? m(a: 2) : 1",
"ParseTree" => s(:if, s(:lit, 1),
s(:call, nil, :m,
s(:hash, s(:lit, :a), s(:lit, 2))),
s(:lit, 1)),
"Ruby2Ruby" => "1 ? (m(:a => 2)) : (1)")
add_19tests("not",
"Ruby" => "(not true)",
"ParseTree" => s(:call, s(:true), :"!"))
add_19tests("splat_fcall_middle",
"Ruby" => "meth(1, *[2], 3)",
"ParseTree" => s(:call,
nil,
:meth,
s(:lit, 1),
s(:splat, s(:array, s(:lit, 2))),
s(:lit, 3)))
add_19tests("str_question_control",
"Ruby" => '?\M-\C-a',
"ParseTree" => s(:str, "\x81"))
add_19tests("str_question_escape",
"Ruby" => '?\n',
"ParseTree" => s(:str, "\n"))
add_19tests("str_question_literal",
"Ruby" => "?a",
"ParseTree" => s(:str, "a"))
add_19tests("unless_post_not",
"Ruby" => "a unless not b",
"ParseTree" => s(:if, s(:call, s(:call, nil, :b), :"!"),
nil,
s(:call, nil, :a)),
"Ruby2Ruby" => "a if b")
add_19tests("unless_pre_not",
"Ruby" => "unless not b then a end",
"ParseTree" => s(:if, s(:call, s(:call, nil, :b), :"!"),
nil,
s(:call, nil, :a)),
"Ruby2Ruby" => "a if b")
add_19tests("until_post_not",
"Ruby" => "begin\n (1 + 1)\nend until not true",
"ParseTree" => s(:until, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend while true")
add_19tests("until_pre_not",
"Ruby" => "until not true do\n (1 + 1)\nend",
"ParseTree" => s(:until, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_19tests("until_pre_not_mod",
"Ruby" => "(1 + 1) until not true",
"ParseTree" => s(:until, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_19tests("while_post_not",
"Ruby" => "begin\n (1 + 1)\nend while not true",
"ParseTree" => s(:while, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend until true")
add_19tests("while_pre_not",
"Ruby" => "while not true do\n (1 + 1)\nend",
"ParseTree" => s(:while, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend")
add_19tests("while_pre_not_mod",
"Ruby" => "(1 + 1) while not true",
"ParseTree" => s(:while, s(:call, s(:true), :"!"),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend") # FIX
###
# Shared tests:
add_tests("alias",
"Ruby" => "class X\n alias :y :x\nend",
"ParseTree" => s(:class, :X, nil,
s(:alias, s(:lit, :y), s(:lit, :x))))
add_tests("alias_ugh",
"Ruby" => "class X\n alias y x\nend",
"ParseTree" => s(:class, :X, nil,
s(:alias, s(:lit, :y), s(:lit, :x))),
"Ruby2Ruby" => "class X\n alias :y :x\nend")
add_tests("and",
"Ruby" => "a and b",
"ParseTree" => s(:and,
s(:call, nil, :a),
s(:call, nil, :b)))
add_tests("argscat_inside",
"Ruby" => "a = [b, *c]",
"ParseTree" => s(:lasgn, :a,
s(:array,
s(:call, nil, :b),
s(:splat, s(:call, nil, :c)))))
add_tests("argscat_svalue",
"Ruby" => "a = b, c, *d",
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:array,
s(:call, nil, :b),
s(:call, nil, :c),
s(:splat,
s(:call, nil, :d))))))
add_tests("argspush",
"Ruby" => "a[*b] = c",
"ParseTree" => s(:attrasgn,
s(:call, nil, :a),
:[]=,
s(:splat,
s(:call, nil, :b)),
s(:call, nil, :c)))
add_tests("array",
"Ruby" => "[1, :b, \"c\"]",
"ParseTree" => s(:array, s(:lit, 1), s(:lit, :b), s(:str, "c")))
add_tests("array_pct_W",
"Ruby" => "%W[a b c]",
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_W_dstr",
"Ruby" => "%W[a #\{@b} c]",
"ParseTree" => s(:array,
s(:str, "a"),
s(:dstr, "", s(:evstr, s(:ivar, :@b))),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"#\{@b}\", \"c\"]")
add_tests("array_pct_w",
"Ruby" => "%w[a b c]",
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_w_dstr",
"Ruby" => "%w[a #\{@b} c]",
"ParseTree" => s(:array,
s(:str, "a"),
s(:str, "#\{@b}"),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"\\\#{@b}\", \"c\"]") # TODO: huh?
add_tests("attrasgn",
"Ruby" => "y = 0\n42.method = y\n",
"ParseTree" => s(:block,
s(:lasgn, :y, s(:lit, 0)),
s(:attrasgn,
s(:lit, 42), :method=, s(:lvar, :y))))
add_tests("attrasgn_index_equals",
"Ruby" => "a[42] = 24",
"ParseTree" => s(:attrasgn,
s(:call, nil, :a),
:[]=,
s(:lit, 42), s(:lit, 24)))
add_tests("attrasgn_index_equals_space",
"Ruby" => "a = []; a [42] = 24",
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:attrasgn, s(:lvar, :a), :[]=,
s(:lit, 42), s(:lit, 24))),
"Ruby2Ruby" => "a = []\na[42] = 24\n")
add_tests("back_ref",
"Ruby" => "[$&, $`, $', $+]",
"ParseTree" => s(:array,
s(:back_ref, :&),
s(:back_ref, :"`"),
s(:back_ref, :"'"),
s(:back_ref, :+)))
add_tests("begin",
"Ruby" => "begin\n (1 + 1)\nend",
"ParseTree" => s(:call, s(:lit, 1), :+, s(:lit, 1)),
"Ruby2Ruby" => "(1 + 1)")
add_tests("begin_def",
"Ruby" => "def m\n begin\n\n end\nend",
"ParseTree" => s(:defn, :m, s(:args), s(:nil)),
"Ruby2Ruby" => "def m\n # do nothing\nend")
add_tests("begin_rescue_ensure",
"Ruby" => "begin\n a\nrescue\n # do nothing\nensure\n # do nothing\nend",
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, nil, :a),
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_ensure_all_empty",
"Ruby" => "begin\n # do nothing\nrescue\n # do nothing\nensure\n # do nothing\nend",
"ParseTree" => s(:ensure,
s(:rescue,
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_twice",
"Ruby" => "begin\n a\nrescue => mes\n # do nothing\nend\nbegin\n b\nrescue => mes\n # do nothing\nend\n",
"ParseTree" => s(:block,
s(:rescue,
s(:call, nil, :a),
s(:resbody,
s(:array, s(:lasgn, :mes, s(:gvar, :$!))),
nil)),
s(:rescue,
s(:call, nil, :b),
s(:resbody,
s(:array,
s(:lasgn, :mes, s(:gvar, :$!))),
nil))))
copy_test_case "begin_rescue_twice", "Ruby"
copy_test_case "begin_rescue_twice", "ParseTree"
add_tests("block_attrasgn",
"Ruby" => "def self.setup(ctx)\n bind = allocate\n bind.context = ctx\n return bind\nend",
"ParseTree" => s(:defs, s(:self), :setup,
s(:args, :ctx),
s(:lasgn, :bind, s(:call, nil, :allocate)),
s(:attrasgn,
s(:lvar, :bind), :context=, s(:lvar, :ctx)),
s(:return, s(:lvar, :bind))))
add_tests("block_lasgn",
"Ruby" => "x = (y = 1\n(y + 2))",
"ParseTree" => s(:lasgn, :x,
s(:block,
s(:lasgn, :y, s(:lit, 1)),
s(:call, s(:lvar, :y), :+, s(:lit, 2)))))
add_tests("block_mystery_block",
"Ruby" => "a(b) do\n if b then\n true\n else\n c = false\n d { |x| c = true }\n c\n end\nend",
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:call, nil, :b)),
0,
s(:if,
s(:call, nil, :b),
s(:true),
s(:block,
s(:lasgn, :c, s(:false)),
s(:iter,
s(:call, nil, :d),
s(:args, :x),
s(:lasgn, :c, s(:true))),
s(:lvar, :c)))))
add_tests("block_pass_args_and_splat",
"Ruby" => "def blah(*args, &block)\n other(42, *args, &block)\nend",
"ParseTree" => s(:defn, :blah, s(:args, :"*args", :"&block"),
s(:call, nil, :other,
s(:lit, 42),
s(:splat, s(:lvar, :args)),
s(:block_pass, s(:lvar, :block)))))
add_tests("block_pass_call_0",
"Ruby" => "a.b(&c)",
"ParseTree" => s(:call,
s(:call, nil, :a),
:b,
s(:block_pass, s(:call, nil, :c))))
add_tests("block_pass_call_1",
"Ruby" => "a.b(4, &c)",
"ParseTree" => s(:call,
s(:call, nil, :a),
:b,
s(:lit, 4),
s(:block_pass, s(:call, nil, :c))))
add_tests("block_pass_call_n",
"Ruby" => "a.b(1, 2, 3, &c)",
"ParseTree" => s(:call,
s(:call, nil, :a),
:b,
s(:lit, 1), s(:lit, 2), s(:lit, 3),
s(:block_pass, s(:call, nil, :c))))
add_tests("block_pass_fcall_0",
"Ruby" => "a(&b)",
"ParseTree" => s(:call, nil, :a,
s(:block_pass, s(:call, nil, :b))))
add_tests("block_pass_fcall_1",
"Ruby" => "a(4, &b)",
"ParseTree" => s(:call, nil, :a,
s(:lit, 4),
s(:block_pass, s(:call, nil, :b))))
add_tests("block_pass_fcall_n",
"Ruby" => "a(1, 2, 3, &b)",
"ParseTree" => s(:call, nil, :a,
s(:lit, 1), s(:lit, 2), s(:lit, 3),
s(:block_pass, s(:call, nil, :b))))
add_tests("block_pass_omgwtf",
"Ruby" => "define_attr_method(:x, :sequence_name, &Proc.new { |*args| nil })",
"ParseTree" => s(:call, nil, :define_attr_method,
s(:lit, :x),
s(:lit, :sequence_name),
s(:block_pass,
s(:iter,
s(:call, s(:const, :Proc), :new),
s(:args, :"*args"),
s(:nil)))))
add_tests("block_pass_splat",
"Ruby" => "def blah(*args, &block)\n other(*args, &block)\nend",
"ParseTree" => s(:defn, :blah,
s(:args, :"*args", :"&block"),
s(:call, nil, :other,
s(:splat, s(:lvar, :args)),
s(:block_pass, s(:lvar, :block)))))
add_tests("block_pass_thingy",
"Ruby" => "r.read_body(dest, &block)",
"ParseTree" => s(:call,
s(:call, nil, :r),
:read_body,
s(:call, nil, :dest),
s(:block_pass, s(:call, nil, :block))))
add_tests("block_stmt_after",
"Ruby" => "def f\n begin\n b\n rescue\n c\n end\n\n d\nend",
"ParseTree" => s(:defn, :f, s(:args),
s(:rescue,
s(:call, nil, :b),
s(:resbody,
s(:array),
s(:call, nil, :c))),
s(:call, nil, :d)),
"Ruby2Ruby" => "def f\n b rescue c\n d\nend")
copy_test_case "block_stmt_after", "Ruby"
copy_test_case "block_stmt_after", "ParseTree"
copy_test_case "block_stmt_after", "Ruby2Ruby"
add_tests("block_stmt_before",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\nend",
"ParseTree" => s(:defn, :f, s(:args),
s(:call, nil, :a),
s(:rescue, s(:call, nil, :b),
s(:resbody,
s(:array),
s(:call, nil, :c)))),
"Ruby2Ruby" => "def f\n a\n b rescue c\nend")
# oddly... this one doesn't HAVE any differences when verbose... new?
copy_test_case "block_stmt_before", "Ruby"
copy_test_case "block_stmt_before", "ParseTree"
copy_test_case "block_stmt_before", "Ruby2Ruby"
add_tests("block_stmt_both",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\n d\nend",
"ParseTree" => s(:defn, :f, s(:args),
s(:call, nil, :a),
s(:rescue,
s(:call, nil, :b),
s(:resbody,
s(:array),
s(:call, nil, :c))),
s(:call, nil, :d)),
"Ruby2Ruby" => "def f\n a\n b rescue c\n d\nend")
copy_test_case "block_stmt_both", "Ruby"
copy_test_case "block_stmt_both", "ParseTree"
copy_test_case "block_stmt_both", "Ruby2Ruby"
add_tests("bmethod",
"Ruby" => [Examples, :unsplatted],
"ParseTree" => s(:defn, :unsplatted, s(:args, :x),
s(:call, s(:lvar, :x), :+, s(:lit, 1))),
"Ruby2Ruby" => "def unsplatted(x)\n (x + 1)\nend")
add_tests("bmethod_noargs",
"Ruby" => [Examples, :bmethod_noargs],
"ParseTree" => s(:defn, :bmethod_noargs, s(:args),
s(:call,
s(:call, nil, :x),
:"+",
s(:lit, 1))),
"Ruby2Ruby" => "def bmethod_noargs\n (x + 1)\nend")
add_tests("bmethod_splat",
"Ruby" => [Examples, :splatted],
"ParseTree" => s(:defn, :splatted, s(:args, :"*args"),
s(:lasgn, :y,
s(:call, s(:lvar, :args), :first)),
s(:call, s(:lvar, :y), :+, s(:lit, 42))),
"Ruby2Ruby" => "def splatted(*args)\n y = args.first\n (y + 42)\nend")
add_tests("break",
"Ruby" => "loop { break if true }",
"ParseTree" => s(:iter,
s(:call, nil, :loop),
0,
s(:if, s(:true), s(:break), nil)))
add_tests("break_arg",
"Ruby" => "loop { break 42 if true }",
"ParseTree" => s(:iter,
s(:call, nil, :loop),
0,
s(:if, s(:true), s(:break, s(:lit, 42)), nil)))
add_tests("call",
"Ruby" => "self.method",
"ParseTree" => s(:call, s(:self), :method))
add_tests("call_arglist",
"Ruby" => "o.puts(42)",
"ParseTree" => s(:call, s(:call, nil, :o), :puts, s(:lit, 42)))
add_tests("call_arglist_hash",
"Ruby" => "o.m(:a => 1, :b => 2)",
"ParseTree" => s(:call,
s(:call, nil, :o), :m,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))))
add_tests("call_arglist_norm_hash",
"Ruby" => "o.m(42, :a => 1, :b => 2)",
"ParseTree" => s(:call,
s(:call, nil, :o), :m,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))))
add_tests("call_command",
"Ruby" => "1.b(c)",
"ParseTree" => s(:call,
s(:lit, 1),
:b,
s(:call, nil, :c)))
add_tests("call_expr",
"Ruby" => "(v = (1 + 1)).zero?",
"ParseTree" => s(:call,
s(:lasgn, :v,
s(:call, s(:lit, 1), :+, s(:lit, 1))),
:zero?))
add_tests("call_index",
"Ruby" => "a = []\na[42]\n",
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[], s(:lit, 42))))
add_tests("call_index_no_args",
"Ruby" => "a[]",
"ParseTree" => s(:call, s(:call, nil, :a),
:[]))
add_tests("call_index_space",
"Ruby" => "a = []\na [42]\n",
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[], s(:lit, 42))),
"Ruby2Ruby" => "a = []\na[42]\n")
add_tests("call_no_space_symbol",
"Ruby" => "foo:bar",
"ParseTree" => s(:call, nil, :foo, s(:lit, :bar)),
"Ruby2Ruby" => "foo(:bar)")
add_tests("call_unary_neg",
"Ruby" => "-2**31",
"ParseTree" => s(:call,
s(:call, s(:lit, 2), :**, s(:lit, 31)),
:-@),
"Ruby2Ruby" => "-(2 ** 31)")
add_tests("case",
"Ruby" => "var = 2\nresult = \"\"\ncase var\nwhen 1 then\n puts(\"something\")\n result = \"red\"\nwhen 2, 3 then\n result = \"yellow\"\nwhen 4 then\n # do nothing\nelse\n result = \"green\"\nend\ncase result\nwhen \"red\" then\n var = 1\nwhen \"yellow\" then\n var = 2\nwhen \"green\" then\n var = 3\nelse\n # do nothing\nend\n",
"ParseTree" => s(:block,
s(:lasgn, :var, s(:lit, 2)),
s(:lasgn, :result, s(:str, "")),
s(:case,
s(:lvar, :var),
s(:when,
s(:array, s(:lit, 1)),
s(:call, nil, :puts, s(:str, "something")),
s(:lasgn, :result, s(:str, "red"))),
s(:when,
s(:array, s(:lit, 2), s(:lit, 3)),
s(:lasgn, :result, s(:str, "yellow"))),
s(:when, s(:array, s(:lit, 4)), nil),
s(:lasgn, :result, s(:str, "green"))),
s(:case,
s(:lvar, :result),
s(:when, s(:array, s(:str, "red")),
s(:lasgn, :var, s(:lit, 1))),
s(:when, s(:array, s(:str, "yellow")),
s(:lasgn, :var, s(:lit, 2))),
s(:when, s(:array, s(:str, "green")),
s(:lasgn, :var, s(:lit, 3))),
nil)))
add_tests("case_nested",
"Ruby" => "var1 = 1\nvar2 = 2\nresult = nil\ncase var1\nwhen 1 then\n case var2\n when 1 then\n result = 1\n when 2 then\n result = 2\n else\n result = 3\n end\nwhen 2 then\n case var2\n when 1 then\n result = 4\n when 2 then\n result = 5\n else\n result = 6\n end\nelse\n result = 7\nend\n",
"ParseTree" => s(:block,
s(:lasgn, :var1, s(:lit, 1)),
s(:lasgn, :var2, s(:lit, 2)),
s(:lasgn, :result, s(:nil)),
s(:case,
s(:lvar, :var1),
s(:when, s(:array, s(:lit, 1)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 1))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 2))),
s(:lasgn, :result, s(:lit, 3)))),
s(:when, s(:array, s(:lit, 2)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 4))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 5))),
s(:lasgn, :result, s(:lit, 6)))),
s(:lasgn, :result, s(:lit, 7)))))
add_tests("case_nested_inner_no_expr",
"Ruby" => "case a\nwhen b then\n case\n when (d and e) then\n f\n else\n # do nothing\n end\nelse\n # do nothing\nend",
"ParseTree" => s(:case, s(:call, nil, :a),
s(:when,
s(:array, s(:call, nil, :b)),
s(:case, nil,
s(:when,
s(:array,
s(:and,
s(:call, nil, :d),
s(:call, nil, :e))),
s(:call, nil, :f)),
nil)),
nil))
add_tests("case_no_expr",
"Ruby" => "case\nwhen (a == 1) then\n :a\nwhen (a == 2) then\n :b\nelse\n :c\nend",
"ParseTree" => s(:case, nil,
s(:when,
s(:array,
s(:call,
s(:call, nil, :a),
:==,
s(:lit, 1))),
s(:lit, :a)),
s(:when,
s(:array,
s(:call,
s(:call, nil, :a),
:==,
s(:lit, 2))),
s(:lit, :b)),
s(:lit, :c)))
add_tests("case_splat",
"Ruby" => "case a\nwhen :b, *c then\n d\nelse\n e\nend",
"ParseTree" => s(:case, s(:call, nil, :a),
s(:when,
s(:array,
s(:lit, :b),
s(:splat, s(:call, nil, :c))),
s(:call, nil, :d)),
s(:call, nil, :e)))
add_tests("cdecl",
"Ruby" => "X = 42",
"ParseTree" => s(:cdecl, :X, s(:lit, 42)))
add_tests("class_plain",
"Ruby" => "class X\n puts((1 + 1))\n \n def blah\n puts(\"hello\")\n end\nend",
"ParseTree" => s(:class, :X, nil,
s(:call, nil, :puts,
s(:call, s(:lit, 1), :+, s(:lit, 1))),
s(:defn, :blah, s(:args),
s(:call, nil, :puts, s(:str, "hello")))))
add_tests("class_scoped",
"Ruby" => "class X::Y\n c\nend",
"ParseTree" => s(:class, s(:colon2, s(:const, :X), :Y), nil,
s(:call, nil, :c)))
add_tests("class_scoped3",
"Ruby" => "class ::Y\n c\nend",
"ParseTree" => s(:class, s(:colon3, :Y), nil,
s(:call, nil, :c)))
add_tests("class_super_array",
"Ruby" => "class X < Array\nend",
"ParseTree" => s(:class, :X, s(:const, :Array)))
add_tests("class_super_expr",
"Ruby" => "class X < expr\nend",
"ParseTree" => s(:class, :X, s(:call, nil, :expr)))
add_tests("class_super_object",
"Ruby" => "class X < Object\nend",
"ParseTree" => s(:class, :X, s(:const, :Object)))
add_tests("colon2",
"Ruby" => "X::Y",
"ParseTree" => s(:colon2, s(:const, :X), :Y))
add_tests("colon3",
"Ruby" => "::X",
"ParseTree" => s(:colon3, :X))
add_tests("const",
"Ruby" => "X",
"ParseTree" => s(:const, :X))
add_tests("constX",
"Ruby" => "X = 1",
"ParseTree" => s(:cdecl, :X, s(:lit, 1)))
add_tests("constY",
"Ruby" => "::X = 1",
"ParseTree" => s(:cdecl, s(:colon3, :X), s(:lit, 1)))
add_tests("constZ",
"Ruby" => "X::Y = 1",
"ParseTree" => s(:cdecl,
s(:colon2, s(:const, :X), :Y),
s(:lit, 1)))
add_tests("cvar",
"Ruby" => "@@x",
"ParseTree" => s(:cvar, :@@x))
add_tests("cvasgn",
"Ruby" => "def x\n @@blah = 1\nend",
"ParseTree" => s(:defn, :x, s(:args),
s(:cvasgn, :@@blah, s(:lit, 1))))
add_tests("cvasgn_cls_method",
"Ruby" => "def self.quiet_mode=(boolean)\n @@quiet_mode = boolean\nend",
"ParseTree" => s(:defs, s(:self), :quiet_mode=,
s(:args, :boolean),
s(:cvasgn, :@@quiet_mode,
s(:lvar, :boolean))))
add_tests("cvdecl",
"Ruby" => "class X\n @@blah = 1\nend",
"ParseTree" => s(:class, :X, nil,
s(:cvdecl, :@@blah, s(:lit, 1))))
add_tests("dasgn_0",
"Ruby" => "a.each { |x| b.each { |y| x = (x + 1) } if true }",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a), :each),
s(:args, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b), :each),
s(:args, :y),
s(:lasgn, :x,
s(:call, s(:lvar, :x), :+, s(:lit, 1)))),
nil)))
add_tests("dasgn_1",
"Ruby" => "a.each { |x| b.each { |y| c = (c + 1) } if true }",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a), :each),
s(:args, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b), :each),
s(:args, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+, s(:lit, 1)))),
nil)))
add_tests("dasgn_2",
"Ruby" => "a.each do |x|\n if true then\n c = 0\n b.each { |y| c = (c + 1) }\n end\nend",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a), :each),
s(:args, :x),
s(:if, s(:true),
s(:block,
s(:lasgn, :c, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :b), :each),
s(:args, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+,
s(:lit, 1))))),
nil)))
add_tests("dasgn_curr",
"Ruby" => "data.each do |x, y|\n a = 1\n b = a\n b = a = x\nend",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :data), :each),
s(:args, :x, :y),
s(:block,
s(:lasgn, :a, s(:lit, 1)),
s(:lasgn, :b, s(:lvar, :a)),
s(:lasgn, :b, s(:lasgn, :a, s(:lvar, :x))))))
add_tests("dasgn_icky",
"Ruby" => "a do\n v = nil\n assert_block(full_message) do\n begin\n yield\n rescue Exception => v\n break\n end\n end\nend",
"ParseTree" => s(:iter,
s(:call, nil, :a),
0,
s(:block,
s(:lasgn, :v, s(:nil)),
s(:iter,
s(:call, nil, :assert_block,
s(:call, nil, :full_message)),
0,
s(:rescue,
s(:yield),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :v, s(:gvar, :$!))),
s(:break)))))))
add_tests("dasgn_mixed",
"Ruby" => "t = 0\nns.each { |n| t += n }\n",
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :ns), :each),
s(:args, :n),
s(:lasgn, :t,
s(:call, s(:lvar, :t), :+, s(:lvar, :n))))),
"Ruby2Ruby" => "t = 0\nns.each { |n| t = (t + n) }\n")
add_tests("defined",
"Ruby" => "defined? $x",
"ParseTree" => s(:defined, s(:gvar, :$x)))
add_tests("defn_args_block", # TODO: make all the defn_args* p their arglist
"Ruby" => "def f(&block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f, s(:args, :"&block"),
s(:nil)))
add_tests("defn_args_mand",
"Ruby" => "def f(mand)\n # do nothing\nend",
"ParseTree" => s(:defn, :f, s(:args, :mand),
s(:nil)))
add_tests("defn_args_mand_block",
"Ruby" => "def f(mand, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f, s(:args, :mand, :"&block"),
s(:nil)))
add_tests("defn_args_mand_opt",
"Ruby" => "def f(mand, opt = 42)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, s(:lasgn, :opt, s(:lit, 42))),
s(:nil)))
add_tests("defn_args_mand_opt_block",
"Ruby" => "def f(mand, opt = 42, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, s(:lasgn, :opt, s(:lit, 42)), :"&block"),
s(:nil)))
add_tests("defn_args_mand_opt_splat",
"Ruby" => "def f(mand, opt = 42, *rest)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, s(:lasgn, :opt, s(:lit, 42)), :"*rest"),
s(:nil)))
add_tests("defn_args_mand_opt_splat_block",
"Ruby" => "def f(mand, opt = 42, *rest, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, s(:lasgn, :opt, s(:lit, 42)), :"*rest", :"&block"),
s(:nil)))
add_tests("defn_args_mand_opt_splat_no_name",
"Ruby" => "def x(a, b = 42, *)\n # do nothing\nend",
"ParseTree" => s(:defn, :x,
s(:args, :a, s(:lasgn, :b, s(:lit, 42)), :"*"),
s(:nil)))
add_tests("defn_args_mand_splat",
"Ruby" => "def f(mand, *rest)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest"),
s(:nil)))
add_tests("defn_args_mand_splat_block",
"Ruby" => "def f(mand, *rest, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest", :"&block"),
s(:nil)))
add_tests("defn_args_mand_splat_no_name",
"Ruby" => "def x(a, *args)\n p(a, args)\nend",
"ParseTree" => s(:defn, :x, s(:args, :a, :"*args"),
s(:call, nil, :p,
s(:lvar, :a), s(:lvar, :args))))
add_tests("defn_args_none",
"Ruby" => "def empty\n # do nothing\nend",
"ParseTree" => s(:defn, :empty, s(:args),
s(:nil)))
add_tests("defn_args_opt",
"Ruby" => "def f(opt = 42)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :opt, s(:lit, 42))),
s(:nil)))
add_tests("defn_args_opt_block",
"Ruby" => "def f(opt = 42, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :opt, s(:lit, 42)), :"&block"),
s(:nil)))
add_tests("defn_args_opt_splat",
"Ruby" => "def f(opt = 42, *rest)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args, s(:lasgn, :opt, s(:lit, 42)), :"*rest"),
s(:nil)))
add_tests("defn_args_opt_splat_block",
"Ruby" => "def f(opt = 42, *rest, &block)\n # do nothing\nend",
"ParseTree" => s(:defn, :f,
s(:args,
s(:lasgn, :opt, s(:lit, 42)),
:"*rest", :"&block"),
s(:nil)))
add_tests("defn_args_opt_splat_no_name",
"Ruby" => "def x(b = 42, *)\n # do nothing\nend",
"ParseTree" => s(:defn, :x,
s(:args, s(:lasgn, :b, s(:lit, 42)), :"*"),
s(:nil)))
add_tests("defn_args_splat",
"Ruby" => "def f(*rest)\n # do nothing\nend",
"ParseTree" => s(:defn, :f, s(:args, :"*rest"),
s(:nil)))
add_tests("defn_args_splat_no_name",
"Ruby" => "def x(*)\n # do nothing\nend",
"ParseTree" => s(:defn, :x, s(:args, :"*"),
s(:nil)))
add_tests("defn_or",
"Ruby" => "def |(o)\n # do nothing\nend",
"ParseTree" => s(:defn, :|, s(:args, :o),
s(:nil)))
add_tests("defn_rescue",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:rescue,
s(:call,
s(:call, s(:self), :uuid),
:==,
s(:call, s(:lvar, :resource), :uuid)),
s(:resbody, s(:array), s(:false)))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_rescue_mri_verbose_flag",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:rescue,
s(:call,
s(:call, s(:self), :uuid),
:==,
s(:call, s(:lvar, :resource), :uuid)),
s(:resbody, s(:array), s(:false)))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_something_eh",
"Ruby" => "def something?\n # do nothing\nend",
"ParseTree" => s(:defn, :something?,
s(:args),
s(:nil)))
add_tests("defn_splat_no_name",
"Ruby" => "def x(a, *)\n p(a)\nend",
"ParseTree" => s(:defn, :x,
s(:args, :a, :"*"),
s(:call, nil, :p, s(:lvar, :a))))
add_tests("defn_zarray",
"Ruby" => "def zarray\n a = []\n return a\nend",
"ParseTree" => s(:defn, :zarray,
s(:args),
s(:lasgn, :a, s(:array)),
s(:return, s(:lvar, :a))))
add_tests("defs",
"Ruby" => "def self.x(y)\n (y + 1)\nend",
"ParseTree" => s(:defs, s(:self), :x,
s(:args, :y),
s(:call, s(:lvar, :y), :+, s(:lit, 1))))
add_tests("defs_empty",
"Ruby" => "def self.empty\n # do nothing\nend",
"ParseTree" => s(:defs, s(:self), :empty, s(:args), s(:nil)))
add_tests("defs_empty_args",
"Ruby" => "def self.empty(*)\n # do nothing\nend",
"ParseTree" => s(:defs, s(:self), :empty,
s(:args, :*),
s(:nil)))
add_tests("defs_expr_wtf",
"Ruby" => "def (a.b).empty(*)\n # do nothing\nend",
"ParseTree" => s(:defs,
s(:call, s(:call, nil, :a), :b),
:empty,
s(:args, :*),
s(:nil)))
add_tests("dmethod",
"Ruby" => [Examples, :dmethod_added],
"ParseTree" => s(:defn, :dmethod_added,
s(:args, :x),
s(:call, s(:lvar, :x), :+, s(:lit, 1))),
"Ruby2Ruby" => "def dmethod_added(x)\n (x + 1)\nend")
add_tests("dot2",
"Ruby" => "(a..b)",
"ParseTree" => s(:dot2,
s(:call, nil, :a),
s(:call, nil, :b)))
add_tests("dot3",
"Ruby" => "(a...b)",
"ParseTree" => s(:dot3,
s(:call, nil, :a),
s(:call, nil, :b)))
add_tests("dregx",
"Ruby" => "/x#\{(1 + 1)}y/",
"ParseTree" => s(:dregx, "x",
s(:evstr,
s(:call, s(:lit, 1), :+, s(:lit, 1))),
s(:str, "y")))
add_tests("dregx_interp",
"Ruby" => "/#\{@rakefile}/",
"ParseTree" => s(:dregx, "", s(:evstr, s(:ivar, :@rakefile))))
add_tests("dregx_interp_empty",
"Ruby" => "/a#\{}b/",
"ParseTree" => s(:dregx, "a", s(:evstr), s(:str, "b")))
add_tests("dregx_n",
"Ruby" => '/#{1}/n',
"ParseTree" => s(:dregx, "",
s(:evstr, s(:lit, 1)), /x/n.options))
add_tests("dregx_once",
"Ruby" => "/x#\{(1 + 1)}y/o",
"ParseTree" => s(:dregx_once, "x",
s(:evstr,
s(:call, s(:lit, 1), :+, s(:lit, 1))),
s(:str, "y")))
add_tests("dregx_once_n_interp",
"Ruby" => "/#\{IAC}#\{SB}/no",
"ParseTree" => s(:dregx_once, "",
s(:evstr, s(:const, :IAC)),
s(:evstr, s(:const, :SB)), /x/n.options))
add_tests("dstr",
"Ruby" => "argl = 1\n\"x#\{argl}y\"\n",
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x", s(:evstr, s(:lvar, :argl)),
s(:str, "y"))))
add_tests("dstr_2",
"Ruby" => "argl = 1\n\"x#\{(\"%.2f\" % 3.14159)}y\"\n",
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr,
"x",
s(:evstr,
s(:call, s(:str, "%.2f"), :%,
s(:lit, 3.14159))),
s(:str, "y"))))
add_tests("dstr_3",
"Ruby" => "max = 2\nargl = 1\n\"x#\{(\"%.#\{max}f\" % 3.14159)}y\"\n",
"ParseTree" => s(:block,
s(:lasgn, :max, s(:lit, 2)),
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x",
s(:evstr,
s(:call,
s(:dstr, "%.",
s(:evstr, s(:lvar, :max)),
s(:str, "f")),
:%,
s(:lit, 3.14159))),
s(:str, "y"))))
add_tests("dstr_concat",
"Ruby" => '"#{22}aa" "cd#{44}" "55" "#{66}"',
"ParseTree" => s(:dstr,
"",
s(:evstr, s(:lit, 22)),
s(:str, "aa"),
s(:str, "cd"),
s(:evstr, s(:lit, 44)),
s(:str, "55"),
s(:evstr, s(:lit, 66))),
"Ruby2Ruby" => '"#{22}aacd#{44}55#{66}"')
add_tests("dstr_gross",
"Ruby" => '"a #$global b #@ivar c #@@cvar d"',
"ParseTree" => s(:dstr, "a ",
s(:evstr, s(:gvar, :$global)),
s(:str, " b "),
s(:evstr, s(:ivar, :@ivar)),
s(:str, " c "),
s(:evstr, s(:cvar, :@@cvar)),
s(:str, " d")),
"Ruby2Ruby" => '"a #{$global} b #{@ivar} c #{@@cvar} d"')
add_tests("dstr_heredoc_expand",
"Ruby" => "<<EOM\n blah\n#\{1 + 1}blah\nEOM\n",
"ParseTree" => s(:dstr, " blah\n",
s(:evstr, s(:call, s(:lit, 1), :+, s(:lit, 1))),
s(:str, "blah\n")),
"Ruby2Ruby" => "\" blah\\n#\{(1 + 1)}blah\\n\"")
add_tests("dstr_heredoc_windoze_sucks",
"Ruby" => "<<-EOF\r\ndef test_#\{action}_valid_feed\r\n EOF\r\n",
"ParseTree" => s(:dstr,
"def test_",
s(:evstr, s(:call, nil, :action)),
s(:str, "_valid_feed\n")),
"Ruby2Ruby" => "\"def test_#\{action}_valid_feed\\n\"")
add_tests("dstr_heredoc_yet_again",
"Ruby" => "<<-EOF\ns1 '#\{RUBY_PLATFORM}' s2\n#\{__FILE__}\n EOF\n",
"ParseTree" => s(:dstr, "s1 '",
s(:evstr, s(:const, :RUBY_PLATFORM)),
s(:str, "' s2\n"),
s(:str, "(string)"),
s(:str, "\n")),
"Ruby2Ruby" => "\"s1 '#\{RUBY_PLATFORM}' s2\\n(string)\\n\"")
add_tests("dstr_nest",
"Ruby" => "%Q[before [#\{nest}] after]",
"ParseTree" => s(:dstr, "before [",
s(:evstr, s(:call, nil, :nest)),
s(:str, "] after")),
"Ruby2Ruby" => "\"before [#\{nest}] after\"")
add_tests("dstr_str_lit_start",
"Ruby" => '"#{"blah"}#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})"',
"ParseTree" => s(:dstr,
"blah(string):",
s(:evstr, s(:lit, 1)),
s(:str, ": warning: "),
s(:evstr, s(:call, s(:gvar, :$!), :message)),
s(:str, " ("),
s(:evstr, s(:call, s(:gvar, :$!), :class)),
s(:str, ")")),
"Ruby2Ruby" => '"blah(string):#{1}: warning: #{$!.message} (#{$!.class})"')
add_tests("dstr_the_revenge",
"Ruby" => '"before #{from} middle #{to} (#{__FILE__}:#{__LINE__})"',
"ParseTree" => s(:dstr,
"before ",
s(:evstr, s(:call, nil, :from)),
s(:str, " middle "),
s(:evstr, s(:call, nil, :to)),
s(:str, " ("),
s(:str, "(string)"),
s(:str, ":"),
s(:evstr, s(:lit, 1)),
s(:str, ")")),
"Ruby2Ruby" => '"before #{from} middle #{to} ((string):#{1})"')
add_tests("dsym",
"Ruby" => ":\"x#\{(1 + 1)}y\"",
"ParseTree" => s(:dsym, "x",
s(:evstr, s(:call, s(:lit, 1), :+, s(:lit, 1))),
s(:str, "y")))
add_tests("dxstr",
"Ruby" => "t = 5\n`touch #\{t}`\n",
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 5)),
s(:dxstr, "touch ", s(:evstr, s(:lvar, :t)))))
add_tests("ensure",
"Ruby" => "begin\n (1 + 1)\nrescue SyntaxError => e1\n 2\nrescue Exception => e2\n 3\nelse\n 4\nensure\n 5\nend",
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, s(:lit, 1), :+, s(:lit, 1)),
s(:resbody,
s(:array,
s(:const, :SyntaxError),
s(:lasgn, :e1, s(:gvar, :$!))),
s(:lit, 2)),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :e2, s(:gvar, :$!))),
s(:lit, 3)),
s(:lit, 4)),
s(:lit, 5)))
add_tests("false",
"Ruby" => "false",
"ParseTree" => s(:false))
add_tests("fbody",
"Ruby" => [Examples, :an_alias],
"ParseTree" => s(:defn, :an_alias, s(:args, :x),
s(:call, s(:lvar, :x), :+, s(:lit, 1))),
"Ruby2Ruby" => "def an_alias(x)\n (x + 1)\nend")
add_tests("fcall_arglist",
"Ruby" => "m(42)",
"ParseTree" => s(:call, nil, :m, s(:lit, 42)))
add_tests("fcall_arglist_hash",
"Ruby" => "m(:a => 1, :b => 2)",
"ParseTree" => s(:call, nil, :m,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))))
add_tests("fcall_arglist_norm_hash",
"Ruby" => "m(42, :a => 1, :b => 2)",
"ParseTree" => s(:call, nil, :m,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))))
add_tests("fcall_block",
"Ruby" => "a(:b) { :c }",
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:lit, :b)),
0,
s(:lit, :c)))
add_tests("fcall_index_space",
"Ruby" => "a [42]",
"ParseTree" => s(:call, nil, :a, s(:array, s(:lit, 42))),
"Ruby2Ruby" => "a([42])")
add_tests("fcall_inside_parens",
"Ruby" => "( a (b), c)",
"ParseTree" => s(:call, nil, :a,
s(:call, nil, :b), s(:call, nil, :c)),
"Ruby2Ruby" => "a(b, c)")
add_tests("fcall_keyword",
"Ruby" => "42 if block_given?",
"ParseTree" => s(:if,
s(:call, nil, :block_given?),
s(:lit, 42), nil))
add_tests("flip2",
"Ruby" => "x = if ((i % 4) == 0)..((i % 3) == 0) then\n i\nelse\n nil\nend",
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip2,
s(:call,
s(:call, s(:call, nil, :i),
:%,
s(:lit, 4)),
:==,
s(:lit, 0)),
s(:call,
s(:call, s(:call, nil, :i),
:%,
s(:lit, 3)),
:==,
s(:lit, 0))),
s(:call, nil, :i),
s(:nil))))
add_tests("flip2_method",
"Ruby" => "if 1..2.a?(b) then\n nil\nend",
"ParseTree" => s(:if,
s(:flip2,
s(:lit, 1),
s(:call, s(:lit, 2), :a?, s(:call, nil, :b))),
s(:nil),
nil))
add_tests("flip3",
"Ruby" => "x = if ((i % 4) == 0)...((i % 3) == 0) then\n i\nelse\n nil\nend",
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip3,
s(:call,
s(:call, s(:call, nil, :i),
:%,
s(:lit, 4)),
:==,
s(:lit, 0)),
s(:call,
s(:call, s(:call, nil, :i),
:%,
s(:lit, 3)),
:==,
s(:lit, 0))),
s(:call, nil, :i),
s(:nil))))
add_tests("for",
"Ruby" => "for o in ary do\n puts(o)\nend",
"ParseTree" => s(:for,
s(:call, nil, :ary),
s(:lasgn, :o),
s(:call, nil, :puts, s(:lvar, :o))))
add_tests("for_no_body",
"Ruby" => "for i in (0..max) do\n # do nothing\nend",
"ParseTree" => s(:for,
s(:dot2,
s(:lit, 0),
s(:call, nil, :max)),
s(:lasgn, :i)))
add_tests("gasgn",
"Ruby" => "$x = 42",
"ParseTree" => s(:gasgn, :$x, s(:lit, 42)))
add_tests("global",
"Ruby" => "$stderr",
"ParseTree" => s(:gvar, :$stderr))
add_tests("gvar",
"Ruby" => "$x",
"ParseTree" => s(:gvar, :$x))
add_tests("gvar_underscore",
"Ruby" => "$_",
"ParseTree" => s(:gvar, :$_))
add_tests("gvar_underscore_blah",
"Ruby" => "$__blah",
"ParseTree" => s(:gvar, :$__blah))
add_tests("hash",
"Ruby" => "{ 1 => 2, 3 => 4 }",
"ParseTree" => s(:hash,
s(:lit, 1), s(:lit, 2),
s(:lit, 3), s(:lit, 4)))
add_tests("hash_rescue",
"Ruby" => "{ 1 => (2 rescue 3) }",
"ParseTree" => s(:hash,
s(:lit, 1),
s(:rescue,
s(:lit, 2),
s(:resbody, s(:array), s(:lit, 3)))))
add_tests("iasgn",
"Ruby" => "@a = 4",
"ParseTree" => s(:iasgn, :@a, s(:lit, 4)))
add_tests("if_block_condition",
"Ruby" => "if (x = 5\n(x + 1)) then\n nil\nend",
"ParseTree" => s(:if,
s(:block,
s(:lasgn, :x, s(:lit, 5)),
s(:call, s(:lvar, :x), :+, s(:lit, 1))),
s(:nil),
nil))
add_tests("if_lasgn_short",
"Ruby" => "if x = obj.x then\n x.do_it\nend",
"ParseTree" => s(:if,
s(:lasgn, :x,
s(:call,
s(:call, nil, :obj),
:x)),
s(:call, s(:lvar, :x), :do_it),
nil))
add_tests("if_nested",
"Ruby" => "return if false unless true",
"ParseTree" => s(:if, s(:true), nil,
s(:if, s(:false), s(:return), nil)))
add_tests("if_post",
"Ruby" => "a if b",
"ParseTree" => s(:if, s(:call, nil, :b),
s(:call, nil, :a), nil))
add_tests("if_pre",
"Ruby" => "if b then a end",
"ParseTree" => s(:if, s(:call, nil, :b),
s(:call, nil, :a), nil),
"Ruby2Ruby" => "a if b")
add_tests("iter_call_arglist_space",
"Ruby" => "a (1) {|c|d}",
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:lit, 1)),
s(:args, :c),
s(:call, nil, :d)),
"Ruby2Ruby" => "a(1) { |c| d }")
add_tests("iter_dasgn_curr_dasgn_madness",
"Ruby" => "as.each { |a|\n b += a.b(false) }",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :as), :each),
s(:args, :a),
s(:lasgn, :b,
s(:call,
s(:lvar, :b),
:+,
s(:call, s(:lvar, :a), :b, s(:false))))),
"Ruby2Ruby" => "as.each { |a| b = (b + a.b(false)) }")
add_tests("iter_downto",
"Ruby" => "3.downto(1) { |n| puts(n.to_s) }",
"ParseTree" => s(:iter,
s(:call, s(:lit, 3), :downto, s(:lit, 1)),
s(:args, :n),
s(:call, nil, :puts,
s(:call, s(:lvar, :n), :to_s))))
add_tests("iter_each_lvar",
"Ruby" => "array = [1, 2, 3]\narray.each { |x| puts(x.to_s) }\n",
"ParseTree" => s(:block,
s(:lasgn, :array,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:iter,
s(:call, s(:lvar, :array), :each),
s(:args, :x),
s(:call, nil, :puts,
s(:call, s(:lvar, :x), :to_s)))))
add_tests("iter_each_nested",
"Ruby" => "array1 = [1, 2, 3]\narray2 = [4, 5, 6, 7]\narray1.each do |x|\n array2.each do |y|\n puts(x.to_s)\n puts(y.to_s)\n end\nend\n",
"ParseTree" => s(:block,
s(:lasgn, :array1,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:lasgn, :array2,
s(:array,
s(:lit, 4), s(:lit, 5),
s(:lit, 6), s(:lit, 7))),
s(:iter,
s(:call, s(:lvar, :array1), :each),
s(:args, :x),
s(:iter,
s(:call, s(:lvar, :array2), :each),
s(:args, :y),
s(:block,
s(:call, nil, :puts,
s(:call, s(:lvar, :x), :to_s)),
s(:call, nil, :puts,
s(:call, s(:lvar, :y), :to_s)))))))
add_tests("iter_loop_empty",
"Ruby" => "loop { }",
"ParseTree" => s(:iter, s(:call, nil, :loop), 0))
add_tests("iter_masgn_2",
"Ruby" => "a { |b, c| p(c) }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :b, :c),
s(:call, nil, :p, s(:lvar, :c))))
add_tests("iter_masgn_args_splat",
"Ruby" => "a { |b, c, *d| p(c) }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :b, :c, :"*d"),
s(:call, nil, :p, s(:lvar, :c))))
add_tests("iter_masgn_args_splat_no_name",
"Ruby" => "a { |b, c, *| p(c) }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :b, :c, :*),
s(:call, nil, :p, s(:lvar, :c))))
add_tests("iter_masgn_splat",
"Ruby" => "a { |*c| p(c) }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :"*c"),
s(:call, nil, :p, s(:lvar, :c))))
add_tests("iter_masgn_splat_no_name",
"Ruby" => "a { |*| p(c) }",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :*),
s(:call, nil, :p, s(:call, nil, :c))))
add_tests("iter_shadowed_var",
"Ruby" => "a do |x|\n b do |x|\n puts x\n end\nend",
"ParseTree" => s(:iter,
s(:call, nil, :a),
s(:args, :x),
s(:iter,
s(:call, nil, :b),
s(:args, :x),
s(:call, nil, :puts, s(:lvar, :x)))),
"Ruby2Ruby" => "a { |x| b { |x| puts(x) } }")
add_tests("iter_upto",
"Ruby" => "1.upto(3) { |n| puts(n.to_s) }",
"ParseTree" => s(:iter,
s(:call, s(:lit, 1), :upto, s(:lit, 3)),
s(:args, :n),
s(:call, nil, :puts,
s(:call, s(:lvar, :n), :to_s))))
add_tests("iter_while",
"Ruby" => "argl = 10\nwhile (argl >= 1) do\n puts(\"hello\")\n argl = (argl - 1)\nend\n",
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 10)),
s(:while,
s(:call, s(:lvar, :argl), :">=", s(:lit, 1)),
s(:block,
s(:call, nil, :puts, s(:str, "hello")),
s(:lasgn,
:argl,
s(:call, s(:lvar, :argl), :"-",
s(:lit, 1)))),
true)))
add_tests("ivar",
"Ruby" => [Examples, :reader],
"ParseTree" => s(:defn, :reader, s(:args),
s(:ivar, :@reader)),
"Ruby2Ruby" => "attr_reader :reader")
add_tests("lambda_args_anon_star",
"Ruby" => "lambda { |*| nil }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :*),
s(:nil)))
add_tests("lambda_args_anon_star_block",
"Ruby" => "lambda { |*, &block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :*, :"&block"),
s(:lvar, :block)))
add_tests("lambda_args_block",
"Ruby" => "lambda { |&block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :"&block"),
s(:lvar, :block)))
add_tests("lambda_args_norm_anon_star",
"Ruby" => "lambda { |a, *| a }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :*),
s(:lvar, :a)))
add_tests("lambda_args_norm_anon_star_block",
"Ruby" => "lambda { |a, *, &block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :*, :"&block"),
s(:lvar, :block)))
add_tests("lambda_args_norm_block",
"Ruby" => "lambda { |a, &block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :"&block"),
s(:lvar, :block)))
add_tests("lambda_args_norm_comma",
"Ruby" => "lambda { |a,| a }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a),
s(:lvar, :a)),
"Ruby2Ruby" => "lambda { |a| a }")
add_tests("lambda_args_norm_comma2",
"Ruby" => "lambda { |a,b,| a }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :b),
s(:lvar, :a)),
"Ruby2Ruby" => "lambda { |a, b| a }")
add_tests("lambda_args_norm_star",
"Ruby" => "lambda { |a, *star| star }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :"*star"),
s(:lvar, :star)))
add_tests("lambda_args_norm_star_block",
"Ruby" => "lambda { |a, *star, &block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :a, :"*star", :"&block"),
s(:lvar, :block)))
add_tests("lambda_args_star",
"Ruby" => "lambda { |*star| star }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :"*star"),
s(:lvar, :star)))
add_tests("lambda_args_star_block",
"Ruby" => "lambda { |*star, &block| block }",
"ParseTree" => s(:iter,
s(:call, nil, :lambda),
s(:args, :"*star", :"&block"),
s(:lvar, :block)))
add_tests("lasgn_array",
"Ruby" => "var = [\"foo\", \"bar\"]",
"ParseTree" => s(:lasgn, :var,
s(:array,
s(:str, "foo"),
s(:str, "bar"))))
add_tests("lasgn_call",
"Ruby" => "c = (2 + 3)",
"ParseTree" => s(:lasgn, :c,
s(:call, s(:lit, 2), :+, s(:lit, 3))))
add_tests("lit_bool_false",
"Ruby" => "false",
"ParseTree" => s(:false))
add_tests("lit_bool_true",
"Ruby" => "true",
"ParseTree" => s(:true))
add_tests("lit_float",
"Ruby" => "1.1",
"ParseTree" => s(:lit, 1.1))
add_tests("lit_long",
"Ruby" => "1",
"ParseTree" => s(:lit, 1))
add_tests("lit_long_negative",
"Ruby" => "-1",
"ParseTree" => s(:lit, -1))
add_tests("lit_range2",
"Ruby" => "(1..10)",
"ParseTree" => s(:lit, 1..10))
add_tests("lit_range3",
"Ruby" => "(1...10)",
"ParseTree" => s(:lit, 1...10))
add_tests("lit_regexp",
"Ruby" => "/x/",
"ParseTree" => s(:lit, /x/))
add_tests("lit_regexp_i_wwtt",
"Ruby" => "str.split(//i)",
"ParseTree" => s(:call,
s(:call, nil, :str),
:split,
s(:lit, //i)))
add_tests("lit_regexp_n",
"Ruby" => "/x/n", # HACK differs on 1.9 - this is easiest
"ParseTree" => s(:lit, /x/n),
"Ruby2Ruby" => /x/n.inspect)
add_tests("lit_regexp_once",
"Ruby" => "/x/o",
"ParseTree" => s(:lit, /x/),
"Ruby2Ruby" => "/x/")
add_tests("lit_sym",
"Ruby" => ":x",
"ParseTree" => s(:lit, :x))
add_tests("lit_sym_splat",
"Ruby" => ":\"*args\"",
"ParseTree" => s(:lit, :"*args"))
add_tests("lvar_def_boundary",
"Ruby" => "b = 42\ndef a\n c do\n begin\n do_stuff\n rescue RuntimeError => b\n puts(b)\n end\n end\nend\n",
"ParseTree" => s(:block,
s(:lasgn, :b, s(:lit, 42)),
s(:defn, :a, s(:args),
s(:iter,
s(:call, nil, :c),
0,
s(:rescue,
s(:call, nil, :do_stuff),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :b, s(:gvar, :$!))),
s(:call, nil, :puts,
s(:lvar, :b))))))))
add_tests("masgn",
"Ruby" => "a, b = c, d",
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:array, s(:call, nil, :c),
s(:call, nil, :d))))
add_tests("masgn_argscat",
"Ruby" => "a, b, *c = 1, 2, *[3, 4]",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b),
s(:splat, s(:lasgn, :c))),
s(:array,
s(:lit, 1), s(:lit, 2),
s(:splat,
s(:array, s(:lit, 3), s(:lit, 4))))))
add_tests("masgn_attrasgn",
"Ruby" => "a, b.c = d, e",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:attrasgn,
s(:call, nil, :b),
:c=)),
s(:array,
s(:call, nil, :d),
s(:call, nil, :e))))
add_tests("masgn_attrasgn_array_rhs",
"Ruby" => "a.b, a.c, _ = q",
"ParseTree" => s(:masgn,
s(:array,
s(:attrasgn,
s(:call, nil, :a),
:b=),
s(:attrasgn,
s(:call, nil, :a),
:c=),
s(:lasgn, :_)),
s(:to_ary,
s(:call, nil, :q))))
add_tests("masgn_attrasgn_idx",
"Ruby" => "a, i, j = [], 1, 2\na[i], a[j] = a[j], a[i]\n",
"ParseTree" => s(:block,
s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :i), s(:lasgn, :j)),
s(:array, s(:array), s(:lit, 1), s(:lit, 2))),
s(:masgn,
s(:array,
s(:attrasgn,
s(:lvar, :a), :[]=, s(:lvar, :i)),
s(:attrasgn,
s(:lvar, :a), :[]=, s(:lvar, :j))),
s(:array,
s(:call,
s(:lvar, :a), :[], s(:lvar, :j)),
s(:call,
s(:lvar, :a), :[], s(:lvar, :i))))))
add_tests("masgn_cdecl",
"Ruby" => "A, B, C = 1, 2, 3",
"ParseTree" => s(:masgn,
s(:array, s(:cdecl, :A), s(:cdecl, :B),
s(:cdecl, :C)),
s(:array, s(:lit, 1), s(:lit, 2), s(:lit, 3))))
add_tests("masgn_iasgn",
"Ruby" => "a, @b = c, d",
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:iasgn, :"@b")),
s(:array,
s(:call, nil, :c),
s(:call, nil, :d))))
add_tests("masgn_masgn",
"Ruby" => "a, (b, c) = [1, [2, 3]]",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:masgn,
s(:array,
s(:lasgn, :b),
s(:lasgn, :c)))),
s(:to_ary,
s(:array,
s(:lit, 1),
s(:array,
s(:lit, 2),
s(:lit, 3))))))
add_tests("masgn_splat_lhs",
"Ruby" => "a, b, *c = d, e, f, g",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b),
s(:splat, s(:lasgn, :c))),
s(:array,
s(:call, nil, :d),
s(:call, nil, :e),
s(:call, nil, :f),
s(:call, nil, :g))))
add_tests("masgn_splat_no_name_to_ary",
"Ruby" => "a, b, * = c",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b),
s(:splat)),
s(:to_ary, s(:call, nil, :c))))
add_tests("masgn_splat_no_name_trailing",
"Ruby" => "a, b, = c",
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c))),
"Ruby2Ruby" => "a, b = c") # TODO: check this is right
add_tests("masgn_splat_rhs_1",
"Ruby" => "a, b = *c",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b)),
s(:splat, s(:call, nil, :c))))
add_tests("masgn_splat_rhs_n",
"Ruby" => "a, b = c, d, *e",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b)),
s(:array,
s(:call, nil, :c),
s(:call, nil, :d),
s(:splat, s(:call, nil, :e)))))
add_tests("masgn_splat_to_ary",
"Ruby" => "a, b, *c = d",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b),
s(:splat, s(:lasgn, :c))),
s(:to_ary, s(:call, nil, :d))))
add_tests("masgn_splat_to_ary2",
"Ruby" => "a, b, *c = d.e(\"f\")",
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :b),
s(:splat, s(:lasgn, :c))),
s(:to_ary,
s(:call,
s(:call, nil, :d),
:e,
s(:str, "f")))))
add_tests("match",
"Ruby" => "1 if /x/",
"ParseTree" => s(:if, s(:match, s(:lit, /x/)), s(:lit, 1), nil))
add_tests("match2",
"Ruby" => "/x/ =~ \"blah\"",
"ParseTree" => s(:match2, s(:lit, /x/), s(:str, "blah")))
add_tests("match3",
"Ruby" => "\"blah\" =~ /x/",
"ParseTree" => s(:match3, s(:lit, /x/), s(:str, "blah")))
add_tests("module",
"Ruby" => "module X\n def y\n # do nothing\n end\nend",
"ParseTree" => s(:module, :X,
s(:defn, :y, s(:args), s(:nil))))
add_tests("module2",
"Ruby" => "module X\n def y\n # do nothing\n end\n \n def z\n # do nothing\n end\nend",
"ParseTree" => s(:module, :X,
s(:defn, :y, s(:args), s(:nil)),
s(:defn, :z, s(:args), s(:nil))))
add_tests("module_scoped",
"Ruby" => "module X::Y\n c\nend",
"ParseTree" => s(:module, s(:colon2, s(:const, :X), :Y),
s(:call, nil, :c)))
add_tests("module_scoped3",
"Ruby" => "module ::Y\n c\nend",
"ParseTree" => s(:module, s(:colon3, :Y),
s(:call, nil, :c)))
add_tests("next",
"Ruby" => "loop { next if false }",
"ParseTree" => s(:iter,
s(:call, nil, :loop),
0,
s(:if, s(:false), s(:next), nil)))
add_tests("next_arg",
"Ruby" => "loop { next 42 if false }",
"ParseTree" => s(:iter,
s(:call, nil, :loop),
0,
s(:if, s(:false), s(:next, s(:lit, 42)), nil)))
add_tests("nth_ref",
"Ruby" => "$1",
"ParseTree" => s(:nth_ref, 1))
add_tests("op_asgn1",
"Ruby" => "b = []\nb[1] ||= 10\nb[2] &&= 11\nb[3] += 12\n",
"ParseTree" => s(:block,
s(:lasgn, :b, s(:array)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn1_ivar",
"Ruby" => "@b = []\n@b[1] ||= 10\n@b[2] &&= 11\n@b[3] += 12\n",
"ParseTree" => s(:block,
s(:iasgn, :@b, s(:array)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn2",
"Ruby" => "s = Struct.new(:var)\nc = s.new(nil)\nc.var ||= 20\nc.var &&= 21\nc.var += 22\nc.d.e.f ||= 42\n",
"ParseTree" => s(:block,
s(:lasgn, :s,
s(:call,
s(:const, :Struct),
:new,
s(:lit, :var))),
s(:lasgn, :c,
s(:call, s(:lvar, :s), :new, s(:nil))),
s(:op_asgn2, s(:lvar, :c),
:var=, :"||", s(:lit, 20)),
s(:op_asgn2, s(:lvar, :c),
:var=, :"&&", s(:lit, 21)),
s(:op_asgn2, s(:lvar, :c),
:var=, :+, s(:lit, 22)),
s(:op_asgn2,
s(:call,
s(:call, s(:lvar, :c), :d),
:e),
:f=, :"||", s(:lit, 42))))
add_tests("op_asgn2_self",
"Ruby" => "self.Bag ||= Bag.new",
"ParseTree" => s(:op_asgn2, s(:self), :"Bag=", :"||",
s(:call, s(:const, :Bag), :new)))
add_tests("op_asgn_and",
"Ruby" => "a = 0\na &&= 2\n",
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_and,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 2)))))
add_tests("op_asgn_and_ivar2",
"Ruby" => "@fetcher &&= new(Gem.configuration[:http_proxy])",
"ParseTree" => s(:op_asgn_and,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil,
:new,
s(:call,
s(:call, s(:const, :Gem), :configuration),
:[],
s(:lit, :http_proxy))))))
add_tests("op_asgn_or",
"Ruby" => "a = 0\na ||= 1\n",
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_or,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 1)))))
add_tests("op_asgn_or_block",
"Ruby" => "a ||= begin\n b\n rescue\n c\n end",
"ParseTree" => s(:op_asgn_or,
s(:lvar, :a),
s(:lasgn, :a,
s(:rescue,
s(:call, nil, :b),
s(:resbody, s(:array),
s(:call, nil, :c))))),
"Ruby2Ruby" => "a ||= b rescue c")
add_tests("op_asgn_or_ivar",
"Ruby" => "@v ||= {}",
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@v),
s(:iasgn, :@v, s(:hash))))
add_tests("op_asgn_or_ivar2",
"Ruby" => "@fetcher ||= new(Gem.configuration[:http_proxy])",
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil, :new,
s(:call,
s(:call, s(:const, :Gem), :configuration),
:[],
s(:lit, :http_proxy))))))
add_tests("or",
"Ruby" => "(a or b)",
"ParseTree" => s(:or,
s(:call, nil, :a),
s(:call, nil, :b)))
add_tests("or_big",
"Ruby" => "((a or b) or (c and d))",
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a),
s(:call, nil, :b)),
s(:and,
s(:call, nil, :c),
s(:call, nil, :d))))
add_tests("or_big2",
"Ruby" => "((a || b) || (c && d))",
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a),
s(:call, nil, :b)),
s(:and,
s(:call, nil, :c),
s(:call, nil, :d))),
"Ruby2Ruby" => "((a or b) or (c and d))")
add_tests("parse_floats_as_args",
"Ruby" => "def x(a=0.0,b=0.0)\n a+b\nend",
"ParseTree" => s(:defn, :x,
s(:args,
s(:lasgn, :a, s(:lit, 0.0)),
s(:lasgn, :b, s(:lit, 0.0))),
s(:call, s(:lvar, :a), :+, s(:lvar, :b))),
"Ruby2Ruby" => "def x(a = 0.0, b = 0.0)\n (a + b)\nend")
add_tests("postexe",
"Ruby" => "END { 1 }",
"ParseTree" => s(:iter, s(:postexe), 0, s(:lit, 1)))
add_tests("proc_args_0",
"Ruby" => "proc { || (x + 1) }",
"ParseTree" => s(:iter,
s(:call, nil, :proc),
s(:args),
s(:call, s(:call, nil, :x), :+, s(:lit, 1))))
add_tests("proc_args_1",
"Ruby" => "proc { |x| (x + 1) }",
"ParseTree" => s(:iter,
s(:call, nil, :proc),
s(:args, :x),
s(:call, s(:lvar, :x), :+, s(:lit, 1))))
add_tests("proc_args_2",
"Ruby" => "proc { |x, y| (x + y) }",
"ParseTree" => s(:iter,
s(:call, nil, :proc),
s(:args, :x, :y),
s(:call, s(:lvar, :x), :+, s(:lvar, :y))))
add_tests("proc_args_no",
"Ruby" => "proc { (x + 1) }",
"ParseTree" => s(:iter,
s(:call, nil, :proc),
0,
s(:call, s(:call, nil, :x), :+, s(:lit, 1))))
add_tests("redo",
"Ruby" => "loop { redo if false }",
"ParseTree" => s(:iter,
s(:call, nil, :loop),
0,
s(:if, s(:false), s(:redo), nil)))
add_tests("rescue", # TODO: need a resbody w/ multiple classes and a splat
"Ruby" => "blah rescue nil",
"ParseTree" => s(:rescue,
s(:call, nil, :blah),
s(:resbody, s(:array), s(:nil))))
add_tests("rescue_block_body",
"Ruby" => "begin\n a\nrescue => e\n c\n d\nend",
"ParseTree" => s(:rescue,
s(:call, nil, :a),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:call, nil, :c),
s(:call, nil, :d))))
add_tests("rescue_block_body_3",
"Ruby" => "begin\n a\nrescue A\n b\nrescue B\n c\nrescue C\n d\nend",
"ParseTree" => s(:rescue,
s(:call, nil, :a),
s(:resbody, s(:array, s(:const, :A)),
s(:call, nil, :b)),
s(:resbody, s(:array, s(:const, :B)),
s(:call, nil, :c)),
s(:resbody, s(:array, s(:const, :C)),
s(:call, nil, :d))))
add_tests("rescue_block_body_ivar",
"Ruby" => "begin\n a\nrescue => @e\n c\n d\nend",
"ParseTree" => s(:rescue,
s(:call, nil, :a),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
s(:call, nil, :c),
s(:call, nil, :d))))
add_tests("rescue_block_nada",
"Ruby" => "begin\n blah\nrescue\n # do nothing\nend",
"ParseTree" => s(:rescue,
s(:call, nil, :blah),
s(:resbody, s(:array), nil)))
add_tests("rescue_exceptions",
"Ruby" => "begin\n blah\nrescue RuntimeError => r\n # do nothing\nend",
"ParseTree" => s(:rescue,
s(:call, nil, :blah),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :r, s(:gvar, :$!))),
nil)))
add_tests("rescue_iasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => @e\n # do nothing\nend",
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
nil)))
add_tests("rescue_lasgn",
"Ruby" => "begin\n 1\nrescue\n var = 2\nend",
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array),
s(:lasgn, :var, s(:lit, 2)))),
"Ruby2Ruby" => "1 rescue var = 2")
add_tests("rescue_lasgn_var",
"Ruby" => "begin\n 1\nrescue => e\n var = 2\nend",
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:lasgn, :var, s(:lit, 2)))))
add_tests("rescue_lasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => e\n # do nothing\nend",
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
nil)))
add_tests("retry",
"Ruby" => "retry",
"ParseTree" => s(:retry))
add_tests("return_0",
"Ruby" => "return",
"ParseTree" => s(:return))
add_tests("return_1",
"Ruby" => "return 1",
"ParseTree" => s(:return, s(:lit, 1)))
add_tests("return_1_splatted",
"Ruby" => "return *1",
"ParseTree" => s(:return, s(:svalue, s(:splat, s(:lit, 1)))))
add_tests("return_n",
"Ruby" => "return 1, 2, 3",
"ParseTree" => s(:return, s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
"Ruby2Ruby" => "return [1, 2, 3]")
add_tests("sclass",
"Ruby" => "class << self\n 42\nend",
"ParseTree" => s(:sclass, s(:self), s(:lit, 42)))
add_tests("sclass_multiple",
"Ruby" => "class << self\n x\n y\nend",
"ParseTree" => s(:sclass, s(:self),
s(:call, nil, :x), s(:call, nil, :y)))
add_tests("sclass_trailing_class",
"Ruby" => "class A\n class << self\n a\n end\n \n class B\n end\nend",
"ParseTree" => s(:class, :A, nil,
s(:sclass, s(:self),
s(:call, nil, :a)),
s(:class, :B, nil)))
add_tests("splat",
"Ruby" => "def x(*b)\n a(*b)\nend",
"ParseTree" => s(:defn, :x,
s(:args, :"*b"),
s(:call, nil, :a, s(:splat, s(:lvar, :b)))))
add_tests("splat_array",
"Ruby" => "[*[1]]",
"ParseTree" => s(:array, s(:splat, s(:array, s(:lit, 1)))))
add_tests("splat_break",
"Ruby" => "break *[1]",
"ParseTree" => s(:break, s(:svalue, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_break_array",
"Ruby" => "break [*[1]]",
"ParseTree" => s(:break, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_fcall",
"Ruby" => "meth(*[1])",
"ParseTree" => s(:call,
nil,
:meth,
s(:splat, s(:array, s(:lit, 1)))))
add_tests("splat_fcall_array",
"Ruby" => "meth([*[1]])",
"ParseTree" => s(:call, nil, :meth,
s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_lasgn",
"Ruby" => "x = *[1]",
"ParseTree" => s(:lasgn, :x, s(:svalue, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_lasgn_array",
"Ruby" => "x = [*[1]]",
"ParseTree" => s(:lasgn, :x, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_lit_1",
"Ruby" => "[*1]",
# UGH - damn MRI
"ParseTree" => s(:array, s(:splat, s(:lit, 1))))
add_tests("splat_lit_n",
"Ruby" => "[1, *2]",
"ParseTree" => s(:array, s(:lit, 1), s(:splat, s(:lit, 2))))
add_tests("splat_next",
"Ruby" => "next *[1]",
"ParseTree" => s(:next, s(:svalue, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_next_array",
"Ruby" => "next [*[1]]",
"ParseTree" => s(:next, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_return",
"Ruby" => "return *[1]",
"ParseTree" => s(:return, s(:svalue, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_return_array",
"Ruby" => "return [*[1]]",
"ParseTree" => s(:return, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_super",
"Ruby" => "super(*[1])",
"ParseTree" => s(:super, s(:splat, s(:array, s(:lit, 1)))))
add_tests("splat_super_array",
"Ruby" => "super([*[1]])",
"ParseTree" => s(:super, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("splat_yield",
"Ruby" => "yield(*[1])",
"ParseTree" => s(:yield, s(:splat, s(:array, s(:lit, 1)))))
add_tests("splat_yield_array",
"Ruby" => "yield([*[1]])",
"ParseTree" => s(:yield, s(:array, s(:splat, s(:array, s(:lit, 1))))))
add_tests("str",
"Ruby" => '"x"',
"ParseTree" => s(:str, "x"))
add_tests("str_concat_newline", # FIX? make prettier? possible?
"Ruby" => '"before" \\
" after"',
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_concat_space",
"Ruby" => '"before" " after"',
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_heredoc",
"Ruby" => "<<'EOM'\n blah\nblah\nEOM",
"ParseTree" => s(:str, " blah\nblah\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\"")
add_tests("str_heredoc_call",
"Ruby" => "<<'EOM'.strip\n blah\nblah\nEOM",
"ParseTree" => s(:call, s(:str, " blah\nblah\n"),
:strip),
"Ruby2Ruby" => "\" blah\\nblah\\n\".strip")
add_tests("str_heredoc_double",
"Ruby" => "a += <<-H1 + b + <<-H2\n first\nH1\n second\nH2",
"ParseTree" => s(:lasgn, :a,
s(:call,
s(:lvar, :a),
:+,
s(:call,
s(:call,
s(:str, " first\n"),
:+,
s(:call, nil, :b)),
:+,
s(:str, " second\n")))),
"Ruby2Ruby" => "a = (a + ((\" first\\n\" + b) + \" second\\n\"))")
add_tests("str_heredoc_empty", # yes... tarded
"Ruby" => "<<'EOM'\nEOM",
"ParseTree" => s(:str, ""),
"Ruby2Ruby" => '""')
add_tests("str_heredoc_indent",
"Ruby" => "<<-EOM\n blah\nblah\n\n EOM",
"ParseTree" => s(:str, " blah\nblah\n\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\\n\"")
add_tests("str_interp_file",
"Ruby" => '"file = #{__FILE__}\n"',
"ParseTree" => s(:str, "file = (string)\n"),
"Ruby2Ruby" => '"file = (string)\\n"')
add_tests("structure_extra_block_for_dvar_scoping",
"Ruby" => "a.b do |c, d|\n unless e.f(c) then\n g = false\n d.h { |x, i| g = true }\n end\nend",
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a), :b),
s(:args, :c, :d),
s(:if,
s(:call, s(:call, nil, :e), :f, s(:lvar, :c)),
nil,
s(:block,
s(:lasgn, :g, s(:false)),
s(:iter,
s(:call, s(:lvar, :d), :h),
s(:args, :x, :i),
s(:lasgn, :g, s(:true)))))))
add_tests("structure_remove_begin_1",
"Ruby" => "a << begin\n b\n rescue\n c\n end",
"ParseTree" => s(:call, s(:call, nil, :a), :<<,
s(:rescue,
s(:call, nil, :b),
s(:resbody, s(:array),
s(:call, nil, :c)))),
"Ruby2Ruby" => "(a << (b rescue c))")
add_tests("structure_remove_begin_2",
"Ruby" => "a = if c\n begin\n b\n rescue\n nil\n end\n end\na",
"ParseTree" => s(:block,
s(:lasgn,
:a,
s(:if, s(:call, nil, :c),
s(:rescue, s(:call, nil, :b),
s(:resbody,
s(:array), s(:nil))),
nil)),
s(:lvar, :a)),
"Ruby2Ruby" => "a = b rescue nil if c\na\n") # OMG that's awesome
add_tests("super_0",
"Ruby" => "def x\n super()\nend",
"ParseTree" => s(:defn, :x, s(:args), s(:super)))
add_tests("super_1",
"Ruby" => "def x\n super(4)\nend",
"ParseTree" => s(:defn, :x, s(:args),
s(:super, s(:lit, 4))))
add_tests("super_1_array",
"Ruby" => "def x\n super([24, 42])\nend",
"ParseTree" => s(:defn, :x, s(:args),
s(:super, s(:array, s(:lit, 24), s(:lit, 42)))))
add_tests("super_block_pass",
"Ruby" => "super(a, &b)",
"ParseTree" => s(:super,
s(:call, nil, :a),
s(:block_pass,
s(:call, nil, :b))))
add_tests("super_block_splat",
"Ruby" => "super(a, *b)",
"ParseTree" => s(:super,
s(:call, nil, :a),
s(:splat, s(:call, nil, :b))))
add_tests("super_n",
"Ruby" => "def x\n super(24, 42)\nend",
"ParseTree" => s(:defn, :x, s(:args),
s(:super, s(:lit, 24), s(:lit, 42))))
add_tests("svalue",
"Ruby" => "a = *b",
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:splat, s(:call, nil, :b)))))
add_tests("ternary_nil_no_space",
"Ruby" => "1 ? nil: 1",
"ParseTree" => s(:if, s(:lit, 1), s(:nil), s(:lit, 1)),
"Ruby2Ruby" => "1 ? (nil) : (1)")
add_tests("ternary_symbol_no_spaces",
"Ruby" => "1?:x:1",
"ParseTree" => s(:if, s(:lit, 1), s(:lit, :x), s(:lit, 1)),
"Ruby2Ruby" => "1 ? (:x) : (1)")
add_tests("to_ary",
"Ruby" => "a, b = c",
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c))))
add_tests("true",
"Ruby" => "true",
"ParseTree" => s(:true))
add_tests("undef",
"Ruby" => "undef :x",
"ParseTree" => s(:undef, s(:lit, :x)))
add_tests("undef_2",
"Ruby" => "undef :x, :y",
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y))),
"Ruby2Ruby" => "undef :x\nundef :y\n")
add_tests("undef_3",
"Ruby" => "undef :x, :y, :z",
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\n")
add_tests("undef_block_1",
"Ruby" => "f1\nundef :x\n", # TODO: don't like the extra return
"ParseTree" => s(:block,
s(:call, nil, :f1),
s(:undef, s(:lit, :x))))
add_tests("undef_block_2",
"Ruby" => "f1\nundef :x, :y",
"ParseTree" => s(:block,
s(:call, nil, :f1),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y)\n")
add_tests("undef_block_3",
"Ruby" => "f1\nundef :x, :y, :z",
"ParseTree" => s(:block,
s(:call, nil, :f1),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\n")
add_tests("undef_block_3_post",
"Ruby" => "undef :x, :y, :z\nf2",
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)),
s(:call, nil, :f2)),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\nf2\n")
add_tests("undef_block_wtf",
"Ruby" => "f1\nundef :x, :y, :z\nf2",
"ParseTree" => s(:block,
s(:call, nil, :f1),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
s(:call, nil, :f2)),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\nf2\n")
add_tests("unless_post",
"Ruby" => "a unless b",
"ParseTree" => s(:if, s(:call, nil, :b), nil,
s(:call, nil, :a)))
add_tests("unless_pre",
"Ruby" => "unless b then a end",
"ParseTree" => s(:if, s(:call, nil, :b), nil,
s(:call, nil, :a)),
"Ruby2Ruby" => "a unless b")
add_tests("until_post",
"Ruby" => "begin\n (1 + 1)\nend until false",
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false))
add_tests("until_pre",
"Ruby" => "until false do\n (1 + 1)\nend",
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true))
add_tests("until_pre_mod",
"Ruby" => "(1 + 1) until false",
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "until false do\n (1 + 1)\nend")
add_tests("valias",
"Ruby" => "alias $y $x",
"ParseTree" => s(:valias, :$y, :$x))
add_tests("vcall",
"Ruby" => "method",
"ParseTree" => s(:call, nil, :method))
add_tests("while_post",
"Ruby" => "begin\n (1 + 1)\nend while false",
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), false))
add_tests("while_post2",
"Ruby" => "begin\n (1 + 2)\n (3 + 4)\nend while false",
"ParseTree" => s(:while, s(:false),
s(:block,
s(:call, s(:lit, 1), :+, s(:lit, 2)),
s(:call, s(:lit, 3), :+, s(:lit, 4))),
false))
add_tests("while_pre",
"Ruby" => "while false do\n (1 + 1)\nend",
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true))
add_tests("while_pre_mod",
"Ruby" => "(1 + 1) while false",
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+, s(:lit, 1)), true),
"Ruby2Ruby" => "while false do\n (1 + 1)\nend") # FIX can be one liner
add_tests("while_pre_nil",
"Ruby" => "while false do\nend",
"ParseTree" => s(:while, s(:false), nil, true))
add_tests("xstr",
"Ruby" => "`touch 5`",
"ParseTree" => s(:xstr, "touch 5"))
add_tests("yield_0",
"Ruby" => "yield",
"ParseTree" => s(:yield))
add_tests("yield_1",
"Ruby" => "yield(42)",
"ParseTree" => s(:yield, s(:lit, 42)))
add_tests("yield_array_0",
"Ruby" => "yield([])",
"ParseTree" => s(:yield, s(:array)))
add_tests("yield_array_1",
"Ruby" => "yield([42])",
"ParseTree" => s(:yield, s(:array, s(:lit, 42))))
add_tests("yield_array_n",
"Ruby" => "yield([42, 24])",
"ParseTree" => s(:yield, s(:array, s(:lit, 42), s(:lit, 24))))
add_tests("yield_n",
"Ruby" => "yield(42, 24)",
"ParseTree" => s(:yield, s(:lit, 42), s(:lit, 24)))
add_tests("zarray",
"Ruby" => "a = []",
"ParseTree" => s(:lasgn, :a, s(:array)))
add_tests("zsuper",
"Ruby" => "def x\n super\nend",
"ParseTree" => s(:defn, :x, s(:args), s(:zsuper)))
# TODO: discuss and decide which lit we like
# it "converts a regexp to an sexp" do
# "/blah/".to_sexp.should == s(:regex, "blah", 0)
# "/blah/i".to_sexp.should == s(:regex, "blah", 1)
# "/blah/u".to_sexp.should == s(:regex, "blah", 64)
# end
end
# :startdoc:
| 42.771767 | 359 | 0.323726 |
6137fb49043cdb65aa56de6b1950cec37df33714 | 296 | def get_grade(g1, g2, g3)
grade = (g1 + g2 + g3) / 3.0
case grade
when 90..100 then "A"
when 80..90 then "B"
when 70..80 then "C"
when 60..70 then "D"
when 0..60 then "F"
end
end
puts get_grade(90, 90, 89.99999999999999999999)# == "A"
puts get_grade(50, 50, 95) #== "D" | 21.142857 | 55 | 0.577703 |
4a167ed78e85fdd78092dbb919153bf79e0e31c5 | 401 | class UpdateBotsDescription < ActiveRecord::Migration[4.2]
def change
b = BotUser.smooch_user
unless b.nil?
b.set_description = 'Connect Check with Facebook Messenger, WhatsApp and Twitter to create tiplines.'
b.save!
end
b = BotUser.keep_user
unless b.nil?
b.set_description = 'Archive links to third-party archiving services.'
b.save!
end
end
end
| 26.733333 | 107 | 0.688279 |
33fe625c90f4feb229d8b4b6a83f303d371acc69 | 621 | class ApplicationHelper::Toolbar::TimelineCenter < ApplicationHelper::Toolbar::Basic
button_group('timeline_downloading', [
button(
:timeline_txt,
'fa fa-file-text-o fa-lg',
N_('Download this Timeline data in text format'),
nil,
:url => "/render_txt"),
button(
:timeline_csv,
'fa fa-file-text-o fa-lg',
N_('Download this Timeline data in CSV format'),
nil,
:url => "/render_csv"),
button(
:timeline_pdf,
'fa fa-file-pdf-o fa-lg',
N_('Download this Timeline data in PDF format'),
nil,
:url => "/render_pdf"),
])
end
| 27 | 84 | 0.597424 |
3846eb0a69ba60bfe619eeb2c505078a3b5d139a | 9,570 | # frozen_string_literal: true
require "acceptance_helper"
describe "Logidze meta", :db do
include_context "cleanup migrations"
before(:all) do
Dir.chdir("#{File.dirname(__FILE__)}/../dummy") do
successfully "rails generate logidze:install"
successfully "rails generate logidze:model user --only-trigger --limit=5"
successfully "rake db:migrate"
# Close active connections to handle db variables
ActiveRecord::Base.connection_pool.disconnect!
end
end
let(:meta) { { 'some_key' => 'some_val' } }
let(:meta_alt) { { 'some_key' => 'some_val2' } }
let(:meta2) { { 'other_key' => 'other_val' } }
describe ".with_meta" do
subject { User.create!(name: 'test', age: 10, active: false) }
context "insert" do
it "doesn't set meta if it's not provided" do
expect(subject.reload.meta).to be_nil
end
it "loads meta when meta is provided" do
Logidze.with_meta(meta) do
expect(subject.reload.meta).to eq meta
end
end
it "loads meta with stringified keys when hash with symbolized keys is provided" do
Logidze.with_meta(meta.transform_keys(&:to_sym)) do
expect(subject.reload.meta).to eq meta
end
end
it "handles failed transaction" do
ignore_exceptions do
Logidze.with_meta(meta) do
CustomUser.create!
end
end
expect(subject.reload.meta).to be_nil
end
it "handles block" do
block = -> { subject }
Logidze.with_meta(meta, &block)
expect(subject.reload.meta).to eq(meta)
end
it "handles nil" do
block = -> { subject }
Logidze.with_meta(nil, &block)
expect(subject.reload.meta).to be_nil
expect(subject.log_data.current_version.data.keys).not_to include(Logidze::History::Version::META)
end
it "handles nested blocks" do
Logidze.with_meta(meta) do
expect(Thread.current[:meta]).to eq([meta])
Logidze.with_meta(meta2) do
expect(Thread.current[:meta]).to eq([meta, meta2])
expect(subject.reload.meta).to eq(meta.merge(meta2))
end
expect(Thread.current[:meta]).to eq([meta])
end
end
it "overrides keys in nested blocks" do
Logidze.with_meta(meta) do
expect(Thread.current[:meta]).to eq([meta])
Logidze.with_meta(meta_alt) do
expect(Thread.current[:meta]).to eq([meta, meta_alt])
expect(subject.reload.meta).to eq(meta_alt)
end
expect(Thread.current[:meta]).to eq([meta])
end
end
it "cleans up meta storage after the exception" do
expect do
Logidze.with_meta(meta) do
expect(Thread.current[:meta]).to eq([meta])
expect do
begin
Logidze.with_meta(meta2) do
expect(Thread.current[:meta]).to eq([meta, meta2])
raise "error inside the nested block"
end
ensure
expect(Thread.current[:meta]).to eq([meta])
end
end.to raise_error /error inside the nested block/
raise "error inside the block"
end
end.to raise_error /error inside the block/
expect(Thread.current[:meta]).to eq([])
end
end
context "update" do
it "sets meta" do
Logidze.with_meta(meta) do
subject.update!(age: 12)
end
expect(subject.reload.meta).to eq(meta)
end
it "supports nested blocks" do
Logidze.with_meta(meta) do
subject.update!(age: 11)
expect(subject.reload.meta).to eq(meta)
Logidze.with_meta(meta2) do
subject.update!(age: 12)
expect(subject.reload.meta).to eq(meta.merge(meta2))
end
subject.update!(age: 13)
expect(subject.reload.meta).to eq(meta)
end
end
it "properly overrides keys inside nested blocks" do
Logidze.with_meta(meta) do
subject.update!(age: 11)
expect(subject.reload.meta).to eq(meta)
Logidze.with_meta(meta_alt) do
subject.update!(age: 12)
expect(subject.reload.meta).to eq(meta_alt)
end
subject.update!(age: 13)
expect(subject.reload.meta).to eq(meta)
end
end
it "works with undo/redo" do
Logidze.with_meta(meta) do
subject.update!(age: 12)
end
subject.update!(active: true)
Logidze.with_meta(meta2) do
subject.update!(name: 'updated')
end
expect(subject.reload.meta).to eq meta2
subject.undo!
expect(subject.reload.meta).to be_nil
subject.redo!
expect(subject.reload.meta).to eq meta2
subject.switch_to!(2)
expect(subject.reload.meta).to eq meta
end
it "handles history compaction" do
# 2 vesions (insert + update)
Logidze.with_meta(meta) do
subject.update!(age: 12)
end
expect(subject.reload.log_size).to eq 2
Logidze.with_meta(meta2) do
# version 3
subject.update!(active: true)
# version 4
subject.update!(name: 'updated')
# version 5
subject.update!(age: 100)
end
subject.update!(name: 'compacted')
expect(subject.reload.log_size).to eq 5
# now the second version is the earliest
expect(subject.at_version(1)).to be_nil
expect(subject.at_version(2).meta).to eq meta
subject.update!(age: 27)
expect(subject.reload.log_size).to eq 5
# now the third version is the earliest
expect(subject.at_version(2)).to be_nil
expect(subject.at_version(3).meta).to eq meta2
end
end
end
describe ".with_responsible" do
let(:responsible) { User.create!(name: 'owner') }
subject { User.create!(name: 'test', age: 10, active: false) }
context "insert" do
it "doesn't set responsible user if it's not provided" do
expect(subject.reload.whodunnit).to be_nil
end
it "loads responsible when id is provided" do
Logidze.with_responsible(responsible.id) do
expect(subject.reload.whodunnit).to eq responsible
end
end
it "loads responsible when id is string" do
Logidze.with_responsible(responsible.name) do
expect(subject.reload.becomes(CustomUser).whodunnit).to eq responsible
end
end
it "handles failed transaction" do
ignore_exceptions do
Logidze.with_responsible(responsible.id) do
CustomUser.create!
end
end
expect(subject.reload.whodunnit).to be_nil
end
it "handles block" do
block = -> { subject }
Logidze.with_responsible(responsible.id, &block)
expect(subject.reload.whodunnit).to eq responsible
end
it "handles nil" do
block = -> { subject }
Logidze.with_responsible(nil, &block)
expect(subject.reload.whodunnit).to be_nil
expect(subject.log_data.current_version.data.keys).not_to include(Logidze::History::Version::META)
end
it "handles nested blocks with responsible" do
Logidze.with_responsible(responsible.id) do
Logidze.with_meta(meta) do
expect(subject.reload.meta).to eq meta.merge(
Logidze::History::Version::META_RESPONSIBLE => responsible.id
)
end
end
end
end
context "update" do
let(:responsible2) { User.create!(name: 'tester') }
it "sets responsible" do
Logidze.with_responsible(responsible.id) do
subject.update!(age: 12)
end
expect(subject.reload.whodunnit).to eq responsible
end
it "works with undo/redo" do
Logidze.with_responsible(responsible.id) do
subject.update!(age: 12)
end
subject.update!(active: true)
Logidze.with_responsible(responsible2.id) do
subject.update!(name: 'updated')
end
expect(subject.reload.whodunnit).to eq responsible2
subject.undo!
expect(subject.reload.whodunnit).to be_nil
subject.redo!
expect(subject.reload.whodunnit).to eq responsible2
subject.switch_to!(2)
expect(subject.reload.whodunnit).to eq responsible
end
it "handles history compaction" do
# 2 vesions (insert + update)
Logidze.with_responsible(responsible.id) do
subject.update!(age: 12)
end
expect(subject.reload.log_size).to eq 2
Logidze.with_responsible(responsible2.id) do
# version 3
subject.update!(active: true)
# version 4
subject.update!(name: 'updated')
# version 5
subject.update!(age: 100)
end
subject.update!(name: 'compacted')
expect(subject.reload.log_size).to eq 5
# now the second version is the earliest
expect(subject.at_version(1)).to be_nil
expect(subject.at_version(2).whodunnit).to eq responsible
subject.update!(age: 27)
expect(subject.reload.log_size).to eq 5
# now the third version is the earliest
expect(subject.at_version(2)).to be_nil
expect(subject.at_version(3).whodunnit).to eq responsible2
end
end
end
end
| 27.579251 | 106 | 0.598642 |
d5d84c7f5f3adb92fcbdca9d0cdfc03784c149cd | 380 | module VagrantPlugins
module Proxmox
module Action
# set env[:result] to :is_created
class IsCreated < ProxmoxAction
def initialize app, env
@app = app
end
def call env
env[:result] = env[:machine].state.id != :not_created
# env[:result] = $machine_state[env[:machine].name] = :not_created
next_action env
end
end
end
end
end
| 18.095238 | 71 | 0.65 |
01a6ddd6e064f491709b3bfdc4731bb05ec45db4 | 468 | require "spec_helper"
require "fog/brightbox/models/compute/account"
describe Fog::Brightbox::Compute::Account do
include ModelSetup
subject { service.accounts.new }
describe "when asked for collection name" do
it "responds 'accounts'" do
assert_equal "accounts", subject.collection_name
end
end
describe "when asked for resource name" do
it "responds 'account'" do
assert_equal "account", subject.resource_name
end
end
end
| 22.285714 | 54 | 0.726496 |
08fc31d76771c4a939f36dc0d95ec78958be1dfa | 1,811 | module Megam
class TextFormatter
attr_reader :data
attr_reader :ui
def initialize(data, ui)
@ui = ui
@data = if data.respond_to?(:display_hash)
data.display_hash
elsif data.kind_of?(Array)
data
elsif data.respond_to?(:to_hash)
data.to_hash
else
data
end
end
def formatted_data
@formatted_data ||= text_format(data)
end
def text_format(data)
buffer = ''
if data.respond_to?(:keys)
justify_width = data.keys.map {|k| k.to_s.size }.max.to_i + 1
data.sort.each do |key, value|
# key: ['value'] should be printed as key: value
if value.kind_of?(Array) && value.size == 1 && is_singleton(value[0])
value = value[0]
end
if is_singleton(value)
# Strings are printed as key: value.
justified_key = ui.color("#{key}:".ljust(justify_width), :cyan)
buffer << "#{justified_key} #{value}\n"
else
# Arrays and hashes get indented on their own lines.
buffer << ui.color("#{key}:\n", :cyan)
lines = text_format(value).split("\n")
lines.each { |line| buffer << " #{line}\n" }
end
end
elsif data.kind_of?(Array)
data.each_index do |index|
item = data[index]
buffer << text_format(data[index])
# Separate items with newlines if it's an array of hashes or an
# array of arrays
buffer << "\n" if !is_singleton(data[index]) && index != data.size-1
end
else
buffer << "#{data}\n"
end
buffer
end
def is_singleton(value)
!(value.kind_of?(Array) || value.respond_to?(:keys))
end
end
end
| 28.296875 | 79 | 0.538929 |
1c60c88804b1acc9cf456d3f7aaf36fd956be8ac | 3,642 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CDN::Mgmt::V2020_09_01
module Models
#
# Defines the parameters for QueryString match conditions
#
class QueryStringMatchConditionParameters
include MsRestAzure
# @return [String] . Default value:
# '#Microsoft.Azure.Cdn.Models.DeliveryRuleQueryStringConditionParameters'
# .
attr_accessor :odatatype
# @return [QueryStringOperator] Describes operator to be matched.
# Possible values include: 'Any', 'Equal', 'Contains', 'BeginsWith',
# 'EndsWith', 'LessThan', 'LessThanOrEqual', 'GreaterThan',
# 'GreaterThanOrEqual', 'RegEx'
attr_accessor :operator
# @return [Boolean] Describes if this is negate condition or not
attr_accessor :negate_condition
# @return [Array<String>] The match value for the condition of the
# delivery rule
attr_accessor :match_values
# @return [Array<Transform>] List of transforms
attr_accessor :transforms
#
# Mapper for QueryStringMatchConditionParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'QueryStringMatchConditionParameters',
type: {
name: 'Composite',
class_name: 'QueryStringMatchConditionParameters',
model_properties: {
odatatype: {
client_side_validation: true,
required: true,
is_constant: true,
serialized_name: '@odata\\.type',
default_value: '#Microsoft.Azure.Cdn.Models.DeliveryRuleQueryStringConditionParameters',
type: {
name: 'String'
}
},
operator: {
client_side_validation: true,
required: true,
serialized_name: 'operator',
type: {
name: 'String'
}
},
negate_condition: {
client_side_validation: true,
required: false,
serialized_name: 'negateCondition',
type: {
name: 'Boolean'
}
},
match_values: {
client_side_validation: true,
required: false,
serialized_name: 'matchValues',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
transforms: {
client_side_validation: true,
required: false,
serialized_name: 'transforms',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'TransformElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| 31.669565 | 104 | 0.500275 |
2164443563237f7d3f86eaf7e073b89bd6f7d50a | 2,578 | module Erp::Products
class Comment < ApplicationRecord
belongs_to :product, class_name: 'Erp::Products::Product'
belongs_to :parent, class_name: "Erp::Products::Comment", optional: true
belongs_to :user, class_name: "Erp::User"
has_many :children, class_name: "Erp::Products::Comment", foreign_key: "parent_id", dependent: :destroy
validates :message, :presence => true
# Filters
def self.filter(query, params)
params = params.to_unsafe_hash
and_conds = []
# show archived items condition - default: false
show_archived = false
#filters
if params["filters"].present?
params["filters"].each do |ft|
or_conds = []
ft[1].each do |cond|
# in case filter is show archived
if cond[1]["name"] == 'show_archived'
# show archived items
show_archived = true
else
or_conds << "#{cond[1]["name"]} = '#{cond[1]["value"]}'"
end
end
and_conds << '('+or_conds.join(' OR ')+')' if !or_conds.empty?
end
end
#keywords
if params["keywords"].present?
params["keywords"].each do |kw|
or_conds = []
kw[1].each do |cond|
or_conds << "LOWER(#{cond[1]["name"]}) LIKE '%#{cond[1]["value"].downcase.strip}%'"
end
and_conds << '('+or_conds.join(' OR ')+')'
end
end
# join with products table for search product
query = query.joins(:product)
# showing archived items if show_archived is not true
query = query.where(archived: false) if show_archived == false
query = query.where(and_conds.join(' AND ')) if !and_conds.empty?
return query
end
def self.search(params)
query = self.where(parent_id: nil)
query = self.filter(query, params)
# order
if params[:sort_by].present?
order = params[:sort_by]
order += " #{params[:sort_direction]}" if params[:sort_direction].present?
query = query.order(order)
end
return query
end
def archive
update_columns(archived: true)
end
def unarchive
update_columns(archived: false)
end
def self.archive_all
update_all(archived: true)
end
def self.unarchive_all
update_all(archived: false)
end
def product_name
product.present? ? product.name : ''
end
# display user name
def user_name
user.present? ? user.name : ''
end
def user_email
user.present? ? user.email : ''
end
end
end
| 25.524752 | 107 | 0.59038 |
e294c6296019b2cb04160e87ff9b897b5979918c | 1,587 | #--
# Copyright (c) 1998-2003 Minero Aoki <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
# with permission of Minero Aoki.
#++
#:stopdoc:
module TMail
module Base64
module_function
def folding_encode( str, eol = "\n", limit = 60 )
[str].pack('m')
end
def encode( str )
[str].pack('m').tr( "\r\n", '' )
end
def decode( str, strict = false )
str.unpack('m').first
end
end
end
#:startdoc:
| 33.765957 | 74 | 0.706994 |
e2021bc946db222626994a8083b5e49e5a6607f8 | 1,267 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/pubsub_v1/service.rb'
require 'google/apis/pubsub_v1/classes.rb'
require 'google/apis/pubsub_v1/representations.rb'
module Google
module Apis
# Cloud Pub/Sub API
#
# Provides reliable, many-to-many, asynchronous messaging between applications.
#
# @see https://cloud.google.com/pubsub/docs
module PubsubV1
VERSION = 'V1'
REVISION = '20190304'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
# View and manage Pub/Sub topics and subscriptions
AUTH_PUBSUB = 'https://www.googleapis.com/auth/pubsub'
end
end
end
| 33.342105 | 83 | 0.73165 |
211a56baf6c5bb20cad657ba3c75713f99d0df08 | 2,972 | require 'spec_helper'
# for this spec to work, you need to have postgres and mysql installed (in
# addition to the gems), and you should make sure that you have set up
# appropriate users and permissions. see database.yml for more info
describe "adapter" do
include_context "hairtrigger utils"
describe ".triggers" do
before do
reset_tmp(:migration_glob => "*initial_tables*")
initialize_db
migrate_db
end
shared_examples_for "mysql" do
# have to stub SHOW TRIGGERS to get back a '%' host, since GRANTs
# and such get a little dicey for testing (local vs travis, etc.)
it "matches the generated trigger with a '%' grant" do
conn.instance_variable_get(:@config)[:host] = "somehost" # wheeeee!
implicit_definer = "'root'@'somehost'"
show_triggers_definer = "root@%"
builder = trigger.on(:users).before(:insert){ "UPDATE foos SET bar = 1" }
triggers = builder.generate.select{|t|t !~ /\ADROP/}
expect(conn).to receive(:implicit_mysql_definer).and_return(implicit_definer)
expect(conn).to receive(:select_rows).with("SHOW TRIGGERS").and_return([
['users_before_insert_row_tr', 'INSERT', 'users', "BEGIN\n UPDATE foos SET bar = 1;\nEND", 'BEFORE', 'NULL', 'STRICT_ALL_TABLES', show_triggers_definer]
])
expect(db_triggers).to eq(triggers)
end
it "quotes table names" do
conn.execute <<-SQL
CREATE TRIGGER foos_tr AFTER DELETE ON users
FOR EACH ROW
BEGIN
UPDATE groups SET bob_count = bob_count - 1;
END
SQL
expect(conn.triggers["foos_tr"]).to match(/CREATE TRIGGER foos_tr AFTER DELETE ON `users`/)
end
end
context "mysql" do
let(:adapter) { :mysql }
it_behaves_like "mysql"
end if ADAPTERS.include? :mysql
context "mysql2" do
let(:adapter) { :mysql2 }
it_behaves_like "mysql"
end if ADAPTERS.include? :mysql2
context "postgresql" do
let(:adapter) { :postgresql }
it "quotes table names" do
conn.execute <<-SQL
CREATE FUNCTION foos_tr()
RETURNS TRIGGER AS $$
BEGIN
UPDATE groups SET bob_count = bob_count - 1;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER foos_tr AFTER DELETE ON users
FOR EACH ROW EXECUTE PROCEDURE foos_tr();
SQL
expect(conn.triggers["foos_tr"]).to match(/CREATE TRIGGER foos_tr AFTER DELETE ON "users"/)
end
end
context "sqlite3" do
let(:adapter) { :sqlite3 }
it "quotes table names" do
conn.execute <<-SQL
CREATE TRIGGER foos_tr AFTER DELETE ON users
FOR EACH ROW
BEGIN
UPDATE groups SET bob_count = bob_count - 1;
END;
SQL
expect(conn.triggers["foos_tr"]).to match(/CREATE TRIGGER foos_tr AFTER DELETE ON "users"/)
end
end
end
end
| 30.958333 | 165 | 0.622476 |
d53e1dfecd2606786b7019246278dd763691771b | 3,764 | require "rails_helper"
describe "Heading", type: :view do
def component_name
"heading"
end
it "fails to render a heading when no title is given" do
assert_raises do
render_component({})
end
end
it "renders a heading correctly" do
render_component(text: "Download documents")
assert_select "h2.gem-c-heading", text: "Download documents"
end
it "renders a different heading level" do
render_component(text: "Original consultation", heading_level: 3)
assert_select "h3.gem-c-heading", text: "Original consultation"
end
it "adds xl font size" do
render_component(text: "Extra large", font_size: "xl")
assert_select ".gem-c-heading.govuk-heading-xl"
end
it "adds l font size" do
render_component(text: "Large", font_size: "l")
assert_select ".gem-c-heading.govuk-heading-l"
end
it "adds m font size" do
render_component(text: "Medium", font_size: "m")
assert_select ".gem-c-heading.govuk-heading-m"
end
it "supports legacy font size option of 24" do
render_component(text: "Medium", font_size: 24)
assert_select ".gem-c-heading.govuk-heading-m"
end
it "adds s font size" do
render_component(text: "Small", font_size: "s")
assert_select ".gem-c-heading.govuk-heading-s"
end
it "supports legacy font size option of 19" do
render_component(text: "Small", font_size: 19)
assert_select ".gem-c-heading.govuk-heading-s"
end
it "adds default font size if given no or an invalid value" do
render_component(text: "font size not specified")
assert_select ".gem-c-heading.gem-c-heading--font-size-27"
render_component(text: "font size 199", font_size: 199)
assert_select ".gem-c-heading.gem-c-heading--font-size-27"
end
it "has a specified id attribute" do
render_component(text: "Consultation description", id: "custom-id")
assert_select ".gem-c-heading[id='custom-id']", text: "Consultation description"
end
it "adds the correct class for publications and consultations page" do
render_component(text: "Consistency is nice", mobile_top_margin: true)
assert_select ".gem-c-heading.gem-c-heading--mobile-top-margin"
end
it "adds padding" do
render_component(text: "Padddddding", padding: true)
assert_select ".gem-c-heading.gem-c-heading--padding"
end
it "adds margin" do
render_component(text: "Margin 7", margin_bottom: 7)
assert_select '.gem-c-heading.govuk-\!-margin-bottom-7'
end
it "defaults to no bottom margin if an incorrect value is passed" do
render_component(text: "Margin wat", margin_bottom: 20)
assert_select "[class='^=govuk-\!-margin-bottom-']", false
end
it "has no margin class added by default" do
render_component(text: "No margin")
assert_select "[class='^=govuk-\!-margin-bottom-']", false
end
it "adds border 1" do
render_component(text: "Border 1", border_top: 1)
assert_select ".gem-c-heading.gem-c-heading--border-top-1"
end
it "adds border 2" do
render_component(text: "Border 2", border_top: 2)
assert_select ".gem-c-heading.gem-c-heading--border-top-2"
end
it "adds border 5" do
render_component(text: "Border 5", border_top: 5)
assert_select ".gem-c-heading.gem-c-heading--border-top-5"
end
it "adds branding" do
render_component(text: "Branded", brand: "attorney-generals-office")
assert_select ".gem-c-heading.brand--attorney-generals-office.brand__border-color"
end
it "adds a lang attribute if passed" do
render_component(text: "Branded", lang: "cy")
assert_select ".gem-c-heading[lang=cy]"
end
it "inverts the heading" do
render_component(text: "Inverted", inverse: true)
assert_select ".gem-c-heading.gem-c-heading--inverse"
end
end
| 30.852459 | 86 | 0.702179 |
ab54e3ce38bd8e09d5460df2f8aba82137dd0a4b | 16,109 | class Openstackclient < Formula
include Language::Python::Virtualenv
desc "Command-line client for OpenStack"
homepage "https://openstack.org"
url "https://files.pythonhosted.org/packages/f9/d8/474a7371757b553e61ae5d4fe14c4443e84a20cc4c84db91565e79d3d45d/python-openstackclient-5.8.0.tar.gz"
sha256 "334852df8897b95f0581ec12ee287de8c7a9289a208a18f0a8b38777019fd986"
license "Apache-2.0"
bottle do
sha256 cellar: :any, arm64_monterey: "7cc84fe8e987840c52b5ab7bcd42c2e1f1024cb79b8824aa2e0b034ce637f186"
sha256 cellar: :any, arm64_big_sur: "eae672452360b4952e7b8f2eab491ec9b2f1a8c1191a6fecc43fb8254ef00482"
sha256 cellar: :any, monterey: "9aa85587f045bbcdd590f578a70fb4291d1020ca8bac075ad59e2f440501cb17"
sha256 cellar: :any, big_sur: "22b405402f7168890fbe73b600015409afec64dd4d4b00ab5ded04357a5e0592"
sha256 cellar: :any, catalina: "a564c5682c02624762f69bfa0e3ec18bb7997c770ca66d5bb9e8c9eb92b8b75b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ff86b46c6da5ec999060b4eae4234fb2f5047adc1513591992ae71855ff47065"
end
depends_on "rust" => :build
depends_on "[email protected]"
depends_on "six"
resource "appdirs" do
url "https://files.pythonhosted.org/packages/d7/d8/05696357e0311f5b5c316d7b95f46c669dd9c15aaeecbb48c7d0aeb88c40/appdirs-1.4.4.tar.gz"
sha256 "7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41"
end
resource "attrs" do
url "https://files.pythonhosted.org/packages/d7/77/ebb15fc26d0f815839ecd897b919ed6d85c050feeb83e100e020df9153d2/attrs-21.4.0.tar.gz"
sha256 "626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd"
end
resource "autopage" do
url "https://files.pythonhosted.org/packages/d1/1c/aaaf5bcb9f37e3d17e040a83de5a35c6cb29fc9ce45412cc8224a570fe30/autopage-0.5.0.tar.gz"
sha256 "5305b43cc0798170d7124e5a2feecf969e45f4a0baf75cb351138114eaf76b83"
end
resource "Babel" do
url "https://files.pythonhosted.org/packages/17/e6/ec9aa6ac3d00c383a5731cc97ed7c619d3996232c977bb8326bcbb6c687e/Babel-2.9.1.tar.gz"
sha256 "bc0c176f9f6a994582230df350aa6e05ba2ebe4b3ac317eab29d9be5d2768da0"
end
resource "certifi" do
url "https://files.pythonhosted.org/packages/6c/ae/d26450834f0acc9e3d1f74508da6df1551ceab6c2ce0766a593362d6d57f/certifi-2021.10.8.tar.gz"
sha256 "78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"
end
resource "cffi" do
url "https://files.pythonhosted.org/packages/00/9e/92de7e1217ccc3d5f352ba21e52398372525765b2e0c4530e6eb2ba9282a/cffi-1.15.0.tar.gz"
sha256 "920f0d66a896c2d99f0adbb391f990a84091179542c205fa53ce5787aff87954"
end
resource "charset-normalizer" do
url "https://files.pythonhosted.org/packages/56/31/7bcaf657fafb3c6db8c787a865434290b726653c912085fbd371e9b92e1c/charset-normalizer-2.0.12.tar.gz"
sha256 "2857e29ff0d34db842cd7ca3230549d1a697f96ee6d3fb071cfa6c7393832597"
end
resource "cliff" do
url "https://files.pythonhosted.org/packages/71/33/0115d1f56dce6bc9f4f4b394347c52a7182109026d2c25d8837047e3edee/cliff-3.10.1.tar.gz"
sha256 "045aee3f3c64471965d7ad507ce8474a4e2f20815fbb5405a770f8596a2a00a0"
end
resource "cmd2" do
url "https://files.pythonhosted.org/packages/7b/d9/87486a680f7961105ca5f49d0701187447ec6620538f512bc3942e976e6f/cmd2-2.4.0.tar.gz"
sha256 "090909ab6c8ecee40813cec759e61dd6e70c8227a1a8e96082f5f2b0d394bc77"
end
resource "cryptography" do
url "https://files.pythonhosted.org/packages/f9/4b/1cf8e281f7ae4046a59e5e39dd7471d46db9f61bb564fddbff9084c4334f/cryptography-36.0.1.tar.gz"
sha256 "53e5c1dc3d7a953de055d77bef2ff607ceef7a2aac0353b5d630ab67f7423638"
end
resource "debtcollector" do
url "https://files.pythonhosted.org/packages/76/0d/60e6c88b5b139f11b4fff730a3f32962f415edc61cc0aa76db81060cd32b/debtcollector-2.4.0.tar.gz"
sha256 "1bc03e2d9017de480c41cf3e5a0d8cc95f1b0c8f1339281b4eca8a22acf76a23"
end
resource "decorator" do
url "https://files.pythonhosted.org/packages/66/0c/8d907af351aa16b42caae42f9d6aa37b900c67308052d10fdce809f8d952/decorator-5.1.1.tar.gz"
sha256 "637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330"
end
resource "dogpile.cache" do
url "https://files.pythonhosted.org/packages/0e/94/73c2d93c9e3293115e5b831da50d6dcb20959a424309e2ddcc485238e0ce/dogpile.cache-1.1.5.tar.gz"
sha256 "0f01bdc329329a8289af9705ff40fadb1f82a28c336f3174e12142b70d31c756"
end
resource "idna" do
url "https://files.pythonhosted.org/packages/62/08/e3fc7c8161090f742f504f40b1bccbfc544d4a4e09eb774bf40aafce5436/idna-3.3.tar.gz"
sha256 "9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d"
end
resource "iso8601" do
url "https://files.pythonhosted.org/packages/28/97/d2d3d96952c77e7593e0f4a634656fb384f7282327f7fef74b726b3b4c1c/iso8601-1.0.2.tar.gz"
sha256 "27f503220e6845d9db954fb212b95b0362d8b7e6c1b2326a87061c3de93594b1"
end
resource "jmespath" do
url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz"
sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9"
end
resource "jsonpatch" do
url "https://files.pythonhosted.org/packages/21/67/83452af2a6db7c4596d1e2ecaa841b9a900980103013b867f2865e5e1cf0/jsonpatch-1.32.tar.gz"
sha256 "b6ddfe6c3db30d81a96aaeceb6baf916094ffa23d7dd5fa2c13e13f8b6e600c2"
end
resource "jsonpointer" do
url "https://files.pythonhosted.org/packages/29/7f/e6b5930e6dd1f461ad412dfc40bc94e5235011f6bbf73cafa8074617c203/jsonpointer-2.2.tar.gz"
sha256 "f09f8deecaaa5aea65b5eb4f67ca4e54e1a61f7a11c75085e360fe6feb6a48bf"
end
resource "keystoneauth1" do
url "https://files.pythonhosted.org/packages/18/4d/e6f986e9c12c1c817abcc1080bf7db56faf5ac86a7607a11a3c9cf722fa3/keystoneauth1-4.5.0.tar.gz"
sha256 "49b3488966a43eeb0200ea511b997e6403c25d563a984c6330e82a0ebfc4540c"
end
resource "msgpack" do
url "https://files.pythonhosted.org/packages/61/3c/2206f39880d38ca7ad8ac1b28d2d5ca81632d163b2d68ef90e46409ca057/msgpack-1.0.3.tar.gz"
sha256 "51fdc7fb93615286428ee7758cecc2f374d5ff363bdd884c7ea622a7a327a81e"
end
resource "munch" do
url "https://files.pythonhosted.org/packages/43/a1/ec48010724eedfe2add68eb7592a0d238590e14e08b95a4ffb3c7b2f0808/munch-2.5.0.tar.gz"
sha256 "2d735f6f24d4dba3417fa448cae40c6e896ec1fdab6cdb5e6510999758a4dbd2"
end
resource "netaddr" do
url "https://files.pythonhosted.org/packages/c3/3b/fe5bda7a3e927d9008c897cf1a0858a9ba9924a6b4750ec1824c9e617587/netaddr-0.8.0.tar.gz"
sha256 "d6cc57c7a07b1d9d2e917aa8b36ae8ce61c35ba3fcd1b83ca31c5a0ee2b5a243"
end
resource "netifaces" do
url "https://files.pythonhosted.org/packages/a6/91/86a6eac449ddfae239e93ffc1918cf33fd9bab35c04d1e963b311e347a73/netifaces-0.11.0.tar.gz"
sha256 "043a79146eb2907edf439899f262b3dfe41717d34124298ed281139a8b93ca32"
end
resource "openstacksdk" do
url "https://files.pythonhosted.org/packages/88/48/06ff537795ca78dd51c15d0dbfba6b2fd538f02b9b2715ba264e09d7d4e6/openstacksdk-0.61.0.tar.gz"
sha256 "3eed308871230f0c53a8f58b6c5a358b184080c6b2c6bc69ab088eea057aa127"
end
resource "os-client-config" do
url "https://files.pythonhosted.org/packages/58/be/ba2e4d71dd57653c8fefe8577ade06bf5f87826e835b3c7d5bb513225227/os-client-config-2.1.0.tar.gz"
sha256 "abc38a351f8c006d34f7ee5f3f648de5e3ecf6455cc5d76cfd889d291cdf3f4e"
end
resource "os-service-types" do
url "https://files.pythonhosted.org/packages/58/3f/09e93eb484b69d2a0d31361962fb667591a850630c8ce47bb177324910ec/os-service-types-1.7.0.tar.gz"
sha256 "31800299a82239363995b91f1ebf9106ac7758542a1e4ef6dc737a5932878c6c"
end
resource "osc-lib" do
url "https://files.pythonhosted.org/packages/68/17/03e208f95d40f88e2fda8d60c62698eeb1ac54b19c9cafcd921d806c669a/osc-lib-2.5.0.tar.gz"
sha256 "d8f8a450fab2a1294e0aef8cdc9a255a1bcc5b58e1b2f6098e35e6db1e13e9d1"
end
resource "oslo.config" do
url "https://files.pythonhosted.org/packages/52/c0/e7e93ba68b601cf14dacac5a8ae33fe225a9ef2b9f53c284e51b4eb608bb/oslo.config-8.8.0.tar.gz"
sha256 "96933d3011dae15608a11616bfb00d947e22da3cb09b6ff37ddd7576abd4764c"
end
resource "oslo.context" do
url "https://files.pythonhosted.org/packages/da/0c/04ebb9679c3c198073081c0406b85bde525671329218c7efa929f447f258/oslo.context-4.1.0.tar.gz"
sha256 "75a9a722a552fba8a89e8a01028fa82a6190ab317a9591bb83303a2210a79144"
end
resource "oslo.i18n" do
url "https://files.pythonhosted.org/packages/7c/d8/a56cdadc3eb21f399327c45662e96479cb73beee0d602769b7847e857e7d/oslo.i18n-5.1.0.tar.gz"
sha256 "6bf111a6357d5449640852de4640eae4159b5562bbba4c90febb0034abc095d0"
end
resource "oslo.log" do
url "https://files.pythonhosted.org/packages/d1/70/d714ee27781b6f54f9db6b6831748f567160f10f92f7cec0e2f12b2e6794/oslo.log-4.6.1.tar.gz"
sha256 "c609614fbe8352054c6e45e6a94baae8b6dccf0fdea5b0dd83fcd61499ec9636"
end
resource "oslo.serialization" do
url "https://files.pythonhosted.org/packages/e8/3d/142b294299ace8a470ad47a90fe152fc21ab8b4e7f9c88dfcb9679d53ff6/oslo.serialization-4.3.0.tar.gz"
sha256 "3aa472f434aee8bbcc0725312b7f409aa1fa54bbc134904124cf49b0e86b9115"
end
resource "oslo.utils" do
url "https://files.pythonhosted.org/packages/95/ba/25f7e518be08d92a12dd1c6de56a5606860f17f15c1b2e20e6d390b65052/oslo.utils-4.12.2.tar.gz"
sha256 "41fd2c4ff6d2e8da38aadb5a5bf24258a8650e0e0a698a6b239d48b8e4177c3b"
end
resource "packaging" do
url "https://files.pythonhosted.org/packages/df/9e/d1a7217f69310c1db8fdf8ab396229f55a699ce34a203691794c5d1cad0c/packaging-21.3.tar.gz"
sha256 "dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"
end
resource "pbr" do
url "https://files.pythonhosted.org/packages/51/da/eb358ed53257a864bf9deafba25bc3d6b8d41b0db46da4e7317500b1c9a5/pbr-5.8.1.tar.gz"
sha256 "66bc5a34912f408bb3925bf21231cb6f59206267b7f63f3503ef865c1a292e25"
end
resource "prettytable" do
url "https://files.pythonhosted.org/packages/cb/7d/7e6bc4bd4abc49e9f4f5c4773bb43d1615e4b476d108d1b527318b9c6521/prettytable-3.2.0.tar.gz"
sha256 "ae7d96c64100543dc61662b40a28f3b03c0f94a503ed121c6fca2782c5816f81"
end
resource "pycparser" do
url "https://files.pythonhosted.org/packages/5e/0b/95d387f5f4433cb0f53ff7ad859bd2c6051051cebbb564f139a999ab46de/pycparser-2.21.tar.gz"
sha256 "e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"
end
resource "pyparsing" do
url "https://files.pythonhosted.org/packages/d6/60/9bed18f43275b34198eb9720d4c1238c68b3755620d20df0afd89424d32b/pyparsing-3.0.7.tar.gz"
sha256 "18ee9022775d270c55187733956460083db60b37d0d0fb357445f3094eed3eea"
end
resource "pyperclip" do
url "https://files.pythonhosted.org/packages/a7/2c/4c64579f847bd5d539803c8b909e54ba087a79d01bb3aba433a95879a6c5/pyperclip-1.8.2.tar.gz"
sha256 "105254a8b04934f0bc84e9c24eb360a591aaf6535c9def5f29d92af107a9bf57"
end
resource "python-cinderclient" do
url "https://files.pythonhosted.org/packages/54/05/2ae3d26e8e29cb041c557dc38111687120b47053b31d51af2c1a2bfea23a/python-cinderclient-8.3.0.tar.gz"
sha256 "e00103875029dc85cbb59131d00ccc8534f692956acde32b5a3cc5af4c24580b"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/4c/c4/13b4776ea2d76c115c1d1b84579f3764ee6d57204f6be27119f13a61d0a9/python-dateutil-2.8.2.tar.gz"
sha256 "0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"
end
resource "python-heatclient" do
url "https://files.pythonhosted.org/packages/5c/d0/cea722a2e3c7f6f2ef7d3af6e1b043a8ce39f8f1ced21583af0e84a07a59/python-heatclient-2.5.1.tar.gz"
sha256 "de5ed7cb12a6d7c0403350e136c0a6470719476db8fbc9bf8d0d581ebc0b1c2b"
end
resource "python-keystoneclient" do
url "https://files.pythonhosted.org/packages/ee/a7/4f371e8f4fd063799ad5cef8789360e5a3b94f197e956ef46a4b9fb6e988/python-keystoneclient-4.4.0.tar.gz"
sha256 "fc17ca9a1aa493104b496ba347f12507f271b5b6e819f4de4aef6574918aa071"
end
resource "python-neutronclient" do
url "https://files.pythonhosted.org/packages/43/50/f9aa3ce530b1ba59f442042c9d57b5395853b9d336fffcb8d89fd25065de/python-neutronclient-7.8.0.tar.gz"
sha256 "9bc66b2952912c2ba298d4c8492db897a5eafcb0ecf757e37baa691b70b47b4e"
end
resource "python-novaclient" do
url "https://files.pythonhosted.org/packages/ca/26/581411d8acc539e59ffff1dc7d59e512e374340aae1bdf9c491ae8a853e1/python-novaclient-17.7.0.tar.gz"
sha256 "4ebc27f4ce06c155b8e991a44463b9358596e6856cf171c9af8dc7568d868bed"
end
resource "python-octaviaclient" do
url "https://files.pythonhosted.org/packages/cb/db/2b36b092d5d5c9fa9da338464787f914a0983321b0ef4f93a6493f493975/python-octaviaclient-2.5.0.tar.gz"
sha256 "4b871ddb39cafc9c25ca0196404ea60f9d70c348249494ed49600616b0117aa4"
end
resource "python-swiftclient" do
url "https://files.pythonhosted.org/packages/b4/d2/46d10a8735ce210d905f6a541125d3b77baca4cf455d6b25de70224678b7/python-swiftclient-3.13.1.tar.gz"
sha256 "2d26c90b6392f6befa7fbb16fcda7be44aa26e2ae8a5bee2705d1d1c813833f0"
end
resource "pytz" do
url "https://files.pythonhosted.org/packages/e3/8e/1cde9d002f48a940b9d9d38820aaf444b229450c0854bdf15305ce4a3d1a/pytz-2021.3.tar.gz"
sha256 "acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326"
end
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/36/2b/61d51a2c4f25ef062ae3f74576b01638bebad5e045f747ff12643df63844/PyYAML-6.0.tar.gz"
sha256 "68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"
end
resource "requests" do
url "https://files.pythonhosted.org/packages/60/f3/26ff3767f099b73e0efa138a9998da67890793bfa475d8278f84a30fec77/requests-2.27.1.tar.gz"
sha256 "68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61"
end
resource "requestsexceptions" do
url "https://files.pythonhosted.org/packages/82/ed/61b9652d3256503c99b0b8f145d9c8aa24c514caff6efc229989505937c1/requestsexceptions-1.4.0.tar.gz"
sha256 "b095cbc77618f066d459a02b137b020c37da9f46d9b057704019c9f77dba3065"
end
resource "rfc3986" do
url "https://files.pythonhosted.org/packages/85/40/1520d68bfa07ab5a6f065a186815fb6610c86fe957bc065754e47f7b0840/rfc3986-2.0.0.tar.gz"
sha256 "97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c"
end
resource "simplejson" do
url "https://files.pythonhosted.org/packages/7a/47/c7cc3d4ed15f09917838a2fb4e1759eafb6d2f37ebf7043af984d8b36cf7/simplejson-3.17.6.tar.gz"
sha256 "cf98038d2abf63a1ada5730e91e84c642ba6c225b0198c3684151b1f80c5f8a6"
end
resource "stevedore" do
url "https://files.pythonhosted.org/packages/67/73/cd693fde78c3b2397d49ad2c6cdb082eb0b6a606188876d61f53bae16293/stevedore-3.5.0.tar.gz"
sha256 "f40253887d8712eaa2bb0ea3830374416736dc8ec0e22f5a65092c1174c44335"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/b0/b1/7bbf5181f8e3258efae31702f5eab87d8a74a72a0aa78bc8c08c1466e243/urllib3-1.26.8.tar.gz"
sha256 "0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c"
end
resource "wcwidth" do
url "https://files.pythonhosted.org/packages/89/38/459b727c381504f361832b9e5ace19966de1a235d73cdbdea91c771a1155/wcwidth-0.2.5.tar.gz"
sha256 "c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83"
end
resource "wrapt" do
url "https://files.pythonhosted.org/packages/eb/f6/d81ccf43ac2a3c80ddb6647653ac8b53ce2d65796029369923be06b815b8/wrapt-1.13.3.tar.gz"
sha256 "1fea9cd438686e6682271d36f3481a9f3636195578bab9ca3382e2f5f01fc185"
end
def install
virtualenv_install_with_resources
end
test do
system bin/"openstack", "-h"
openstack_subcommands = [
"server list",
"stack list",
"loadbalancer list",
]
openstack_subcommands.each do |subcommand|
output = shell_output("#{bin}/openstack #{subcommand} 2>&1", 1)
assert_match "Missing value auth-url required", output
end
end
end
| 49.566154 | 151 | 0.822025 |
e2b3f4170299997e86b0a4f9719f8beac955a1a1 | 394 | class CreateCompetes < ActiveRecord::Migration[5.0]
def change
create_table :competes do |t|
t.references :group, null: false
t.references :event, null: false
t.string :award
t.timestamps
end
add_foreign_key :competes, :groups, on_delete: :cascade, on_update: :cascade
add_foreign_key :competes, :events, on_delete: :cascade, on_update: :cascade
end
end
| 21.888889 | 80 | 0.705584 |
21b51e91537e0d0015f49e9f17cce0b7a2d85ec9 | 4,602 | cask "firefox" do
version "84.0"
language "cs" do
sha256 "9fe199fdb21191cbca9ecbfd11c0771e9fdaab0add164a2b899d1bfa933bd2c8"
"cs"
end
language "de" do
sha256 "297d87391b2fe18067e6bcb1ceeb94fb1e556108673447f361bad75f06b81e84"
"de"
end
language "en-CA" do
sha256 "1785253cc8425d439a91b2a056a79b70de5ab6477247ea3b0c80d8b2a9a67b7e"
"en-CA"
end
language "en-GB" do
sha256 "b8fd2d16cf4fe201af6164077543c6428a91ff2641b95c0aaf7e45efe163a703"
"en-GB"
end
language "en", default: true do
sha256 "4c7bca050eb228f4f6f93a9895af0a87473e03c67401d1d2f1ba907faf87fefd"
"en-US"
end
language "eo" do
sha256 "a93e0ca6fe7f3d1344edbbaba2b9a7639a340825bd7f29bc9f9dd35cb4a32a58"
"eo"
end
language "es-AR" do
sha256 "6a906d6fedfb5f85ac5c82e96edfc1c99d6e166996d68b90a0c7cb6cdbc94a24"
"es-AR"
end
language "es-CL" do
sha256 "da57cb6b7135e4327bbc57570668419de7472c87e9f944dde0c7038a4b473b0d"
"es-CL"
end
language "es-ES" do
sha256 "59d40b7e3c0be9ec0bd0f74efd78a3f74ffa3180b252e7b8de134e5693aaf59e"
"es-ES"
end
language "fi" do
sha256 "b51b50bb2988b1894b832dd594ab57d2767ab5107c0d5f8adee4b53651e6f89d"
"fi"
end
language "fr" do
sha256 "d7dcf8cab1c6359619f9fe7bc72e5d97eb5d95ed9d9f9ac85c4f38089c76fd6c"
"fr"
end
language "gl" do
sha256 "7561ed0e6f1f2c940fa0fa5efb7c09e5384051ef15a8584377d6c52db890da09"
"gl"
end
language "in" do
sha256 "f707775322a882ee7b2cc57d92bba562c6f952fc207b341ae903ef20970d59c2"
"hi-IN"
end
language "it" do
sha256 "f39fdf0369a8c34efb180179c56a27f7a14e89c51641b8fdaba2f73ad6716314"
"it"
end
language "ja" do
sha256 "c148bb5c6a70e12dd2e49679510005f73417e14152f5c6746359a89c05b251d0"
"ja-JP-mac"
end
language "ko" do
sha256 "99d82a9fa4fd4f1684612ee8e628b4f3968e4de627c45e63cf834cc47eda2bbe"
"ko"
end
language "nl" do
sha256 "0fd9f0d16de70819e23fb4454cf37712eb55018d1f5e9d84de8101f8c68f8f6c"
"nl"
end
language "pl" do
sha256 "9d38faf772e0806971f0612343fb14bee161274edf77cbec538b7915a4ee30ca"
"pl"
end
language "pt-BR" do
sha256 "4a65933749b89d2e52a9ff98867a82e5801c1d27bf2e223612b34b002ae9beef"
"pt-BR"
end
language "pt" do
sha256 "fd9b8adec337a07ce4a518b15432622a0b64d2ed2396d9390ca9fce651d2d9ef"
"pt-PT"
end
language "ru" do
sha256 "ac212b2d1a2eab0ca913eb45b97d8b582dabfa691bfce9436c0b44b90702ffe9"
"ru"
end
language "sv" do
sha256 "9acb1fa4d1b628545f91067534c51c65eb0e23a9be8f2cab3c06faa7bc680798"
"sv-SE"
end
language "tr" do
sha256 "5910d49f56dd1f836a2fe775c85402624c988c1413f0c890764cc75cf507a582"
"tr"
end
language "uk" do
sha256 "91bcdc4402ac7b064f8d415ceacba0823c1eca17217d5a1fa013921aeb885891"
"uk"
end
language "zh-TW" do
sha256 "8c9177f31e9da274ed46d18358d68515815f0c5e42a4edb91901b27c67568d33"
"zh-TW"
end
language "zh" do
sha256 "c41b2868c96a3d97e09e28911d459e24804bf5c44ec29193b4b7b8c784732a33"
"zh-CN"
end
url "https://download-installer.cdn.mozilla.net/pub/firefox/releases/#{version}/mac/#{language}/Firefox%20#{version}.dmg",
verified: "download-installer.cdn.mozilla.net/pub/firefox/releases/"
appcast "https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://download.mozilla.org/%3Fproduct=firefox-latest-ssl%26os=osx"
name "Mozilla Firefox"
desc "Web browser"
homepage "https://www.mozilla.org/firefox/"
auto_updates true
conflicts_with cask: [
"firefox-beta",
"firefox-esr",
]
depends_on macos: ">= :sierra"
app "Firefox.app"
zap trash: [
"/Library/Logs/DiagnosticReports/firefox_*",
"~/Library/Application Support/Firefox",
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.firefox.sfl*",
"~/Library/Application Support/CrashReporter/firefox_*",
"~/Library/Caches/Firefox",
"~/Library/Caches/Mozilla/updates/Applications/Firefox",
"~/Library/Caches/org.mozilla.firefox",
"~/Library/Caches/org.mozilla.crashreporter",
"~/Library/Preferences/org.mozilla.firefox.plist",
"~/Library/Preferences/org.mozilla.crashreporter.plist",
"~/Library/Saved Application State/org.mozilla.firefox.savedState",
"~/Library/WebKit/org.mozilla.firefox",
],
rmdir: [
"~/Library/Application Support/Mozilla", # May also contain non-Firefox data
"~/Library/Caches/Mozilla/updates/Applications",
"~/Library/Caches/Mozilla/updates",
"~/Library/Caches/Mozilla",
]
end
| 31.520548 | 152 | 0.752064 |
2144f20b284549ffd070e0345c19ff86b9674e0f | 202 | module BowlingSolitaire
class Move
def before
@round.preview
end
def after
apply.preview
end
def preview
before
puts "-->"
after
end
end
end
| 10.631579 | 23 | 0.554455 |
2883e13a2ce24953b0e8bb7b998362b8425ce52c | 387 | class ConditionIsHolofoil < ConditionSimple
def match?(card)
return false unless card.frame == "m15"
return true if card.set_code == "ust" and card.rarity == "basic"
return false unless %W[rare mythic special].include?(card.rarity)
return false if card.back?
return false if card.types.include?("contraption")
true
end
def to_s
"is:holofoil"
end
end
| 25.8 | 69 | 0.692506 |
183f2ba0881cc5f7401e35c3c337565f7f26493e | 4,473 | # Copyright 2017 OpenCensus Authors
#
# 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 "rails/railtie"
require "opencensus/trace/integrations/rack_middleware"
require "opencensus/trace/integrations/active_support"
module OpenCensus
module Trace
module Integrations
##
# # Rails Integration
#
# This Railtie automatically sets up OpenCensus for a Rails server:
#
# * It wraps all requests in spans, using the `RackMiddleware`
# integration.
# * It wraps common events (ActiveRecord database calls, ActionView
# renders, etc) in subspans.
#
# ## Configuration
#
# This Railtie exposes the OpenCensus configuration on the `opencensus`
# key of the Rails configuration. So you can, for example, set:
#
# config.opencensus.trace.default_max_attributes = 64
#
# ### Configuring ActiveSupport Notifications
#
# See OpenCensus::Trace::Integrations::ActiveSupport for information on
# ActiveSupport notifications
#
# ### Configuring Middleware Placement
#
# By default, the Railtie places the OpenCensus middleware at the end of
# the middleware stack. This means it will measure your application code
# but not the effect of other middleware, including middlware that is
# part of the Rails stack or any custom middleware you have installed.
# If you would rather place the middleware at the beginning of the stack
# where it surrounds all other middleware, set this configuration:
#
# OpenCensus::Trace.config do |config|
# config.middleware_placement = :begin
# end
#
# Or, using Rails:
#
# config.opencensus.trace.middleware_placement = :begin
#
# This effectively causes the Railtie to use `unshift` rather than `use`
# to add the OpenCensus middleware to the middleware stack.
# You may also set this configuration to an existing middleware class to
# cause the OpenCensus middleware to be inserted before that middleware
# in the stack. For example:
#
# OpenCensus::Trace.config do |config|
# config.middleware_placement = ::Rails::Rack::Logger
# end
#
# Or, using Rails:
#
# config.opencensus.trace.middleware_placement = ::Rails::Rack::Logger
#
# You can also set the following configuration options:
# * `path_sanitize_proc` defaults to return the path that is passed to it.
# You can use this to manipulate the path provided to the span, which
# might be useful if it contains IDs, thereby creating distinct spans
# for the same application endpoint.
# For example this will remove all numbers from your path:
# configuration.path_sanitize_proc = ->(path) { path.gsub(/\d+/, "*")}
# (The full path will be added as an attribute named 'http.path')
class Rails < ::Rails::Railtie
OpenCensus::Trace.configure do |c|
c.add_option! :middleware_placement, :end,
match: [:begin, :end, Class]
c.add_option! :path_sanitize_proc, ->(path) { path }
end
unless config.respond_to? :opencensus
config.opencensus = OpenCensus.configure
end
initializer "opencensus.trace" do |app|
setup_middleware app.middleware
end
##
# Insert middleware into the middleware stack
# @private
#
def setup_middleware middleware_stack
where = OpenCensus::Trace.configure.middleware_placement
case where
when Class
middleware_stack.insert_before where, RackMiddleware
when :begin
middleware_stack.unshift RackMiddleware
else
middleware_stack.use RackMiddleware
end
end
end
end
end
end
| 37.90678 | 80 | 0.653029 |
08f02732400c5427745ae49b31f843428280c0d9 | 140,376 | survey 'IQ',
:full_title => 'Iraq',
:default_mandatory => 'false',
:status => 'alpha',
:description => '<p><strong>This has been generated based on a default and needs to be localised for Iraq. Please help us! Contact <a href="mailto:[email protected]">[email protected]</a></strong></p><p>This self-assessment questionnaire generates an open data certificate and badge you can publish to tell people all about this open data. We also use your answers to learn how organisations publish open data.</p><p>When you answer these questions it demonstrates your efforts to comply with relevant legislation. You should also check which other laws and policies apply to your sector.</p><p><strong>You do not need to answer all the questions to get a certificate.</strong> Just answer those you can.</p>' do
translations :en => :default
section_general 'General Information',
:description => '',
:display_header => false do
q_dataTitle 'What\'s this data called?',
:discussion_topic => :dataTitle,
:help_text => 'People see the name of your open data in a list of similar ones so make this as unambiguous and descriptive as you can in this tiny box so they quickly identify what\'s unique about it.',
:required => :required
a_1 'Data Title',
:string,
:placeholder => 'Data Title',
:required => :required
q_documentationUrl 'Where is it described?',
:discussion_topic => :documentationUrl,
:display_on_certificate => true,
:text_as_statement => 'This data is described at',
:help_text => 'Give a URL for people to read about the contents of your open data and find more detail. It can be a page within a bigger catalog like data.gov.uk.'
a_1 'Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Documentation URL',
:requirement => ['pilot_1', 'basic_1']
label_pilot_1 'You should have a <strong>web page that offers documentation</strong> about the open data you publish so that people can understand its context, content and utility.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_1'
dependency :rule => 'A and B'
condition_A :q_releaseType, '!=', :a_collection
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
label_basic_1 'You must have a <strong>web page that gives documentation</strong> and access to the open data you publish so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_1'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_collection
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_publisher 'Who publishes this data?',
:discussion_topic => :publisher,
:display_on_certificate => true,
:text_as_statement => 'This data is published by',
:help_text => 'Give the name of the organisation who publishes this data. It’s probably who you work for unless you’re doing this on behalf of someone else.',
:required => :required
a_1 'Data Publisher',
:string,
:placeholder => 'Data Publisher',
:required => :required
q_publisherUrl 'What website is the data published on?',
:discussion_topic => :publisherUrl,
:display_on_certificate => true,
:text_as_statement => 'The data is published on',
:help_text => 'Give a URL to a website, this helps us to group data from the same organisation even if people give different names.'
a_1 'Publisher URL',
:string,
:input_type => :url,
:placeholder => 'Publisher URL'
q_releaseType 'What kind of release is this?',
:discussion_topic => :releaseType,
:pick => :one,
:required => :required
a_oneoff 'a one-off release of a single dataset',
:help_text => 'This is a single file and you don’t currently plan to publish similar files in the future.'
a_collection 'a one-off release of a set of related datasets',
:help_text => 'This is a collection of related files about the same data and you don’t currently plan to publish similar collections in the future.'
a_series 'ongoing release of a series of related datasets',
:help_text => 'This is a sequence of datasets with planned periodic updates in the future.'
a_service 'a service or API for accessing open data',
:help_text => 'This is a live web service that exposes your data to programmers through an interface they can query.'
end
section_legal 'Legal Information',
:description => 'Rights, licensing and privacy' do
label_group_2 'Rights',
:help_text => 'your right to share this data with people',
:customer_renderer => '/partials/fieldset'
q_publisherRights 'Do you have the rights to publish this data as open data?',
:discussion_topic => :iq_publisherRights,
:help_text => 'If your organisation didn\'t originally create or gather this data then you might not have the right to publish it. If you’re not sure, check with the data owner because you will need their permission to publish it.',
:requirement => ['basic_2'],
:pick => :one,
:required => :required
a_yes 'yes, you have the rights to publish this data as open data',
:requirement => ['standard_1']
a_no 'no, you don\'t have the rights to publish this data as open data'
a_unsure 'you\'re not sure if you have the rights to publish this data as open data'
a_complicated 'the rights in this data are complicated or unclear'
label_standard_1 'You should have a <strong>clear legal right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_1'
dependency :rule => 'A'
condition_A :q_publisherRights, '!=', :a_yes
label_basic_2 'You must have the <strong>right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_2'
dependency :rule => 'A'
condition_A :q_publisherRights, '==', :a_no
q_rightsRiskAssessment 'Where do you detail the risks people might encounter if they use this data?',
:discussion_topic => :iq_rightsRiskAssessment,
:display_on_certificate => true,
:text_as_statement => 'Risks in using this data are described at',
:help_text => 'It can be risky for people to use data without a clear legal right to do so. For example, the data might be taken down in response to a legal challenge. Give a URL for a page that describes the risk of using this data.'
dependency :rule => 'A'
condition_A :q_publisherRights, '==', :a_complicated
a_1 'Risk Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Risk Documentation URL',
:requirement => ['pilot_2']
label_pilot_2 'You should document <strong>risks associated with using this data</strong>, so people can work out how they want to use it.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_2'
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_complicated
condition_B :q_rightsRiskAssessment, '==', {:string_value => '', :answer_reference => '1'}
q_publisherOrigin 'Was <em>all</em> this data originally created or gathered by you?',
:discussion_topic => :iq_publisherOrigin,
:display_on_certificate => true,
:text_as_statement => 'This data was',
:help_text => 'If any part of this data was sourced outside your organisation by other individuals or organisations then you need to give extra information about your right to publish it.',
:pick => :one,
:required => :required
dependency :rule => '(A or B)'
condition_A :q_publisherRights, '==', :a_yes
condition_B :q_publisherRights, '==', :a_unsure
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'originally created or generated by its curator'
q_thirdPartyOrigin 'Was some of this data extracted or calculated from other data?',
:discussion_topic => :iq_thirdPartyOrigin,
:help_text => 'An extract or smaller part of someone else\'s data still means your rights to use it might be affected. There might also be legal issues if you analysed their data to produce new results from it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
a_false 'no'
a_true 'yes',
:requirement => ['basic_3']
label_basic_3 'You indicated that this data wasn\'t originally created or gathered by you, and wasn\'t crowdsourced, so it must have been extracted or calculated from other data sources.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_3'
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_false
condition_D :q_thirdPartyOrigin, '!=', :a_true
q_thirdPartyOpen 'Are <em>all</em> sources of this data already published as open data?',
:discussion_topic => :iq_thirdPartyOpen,
:display_on_certificate => true,
:text_as_statement => 'This data is created from',
:help_text => 'You\'re allowed to republish someone else\'s data if it\'s already under an open data licence or if their rights have expired or been waived. If any part of this data is not like this then you\'ll need legal advice before you can publish it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'open data sources',
:requirement => ['basic_4']
label_basic_4 'You should get <strong>legal advice to make sure you have the right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_4'
dependency :rule => 'A and B and C and D and E'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_true
condition_D :q_thirdPartyOpen, '==', :a_false
condition_E :q_thirdPartyOpen, '==', :a_false
q_crowdsourced 'Was some of this data crowdsourced?',
:discussion_topic => :iq_crowdsourced,
:display_on_certificate => true,
:text_as_statement => 'Some of this data is',
:help_text => 'If the data includes information contributed by people outside your organisation, you need their permission to publish their contributions as open data.',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'crowdsourced',
:requirement => ['basic_5']
label_basic_5 'You indicated that the data wasn\'t originally created or gathered by you, and wasn\'t extracted or calculated from other data, so it must have been crowdsourced.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_5'
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_false
condition_D :q_crowdsourced, '!=', :a_true
q_crowdsourcedContent 'Did contributors to this data use their judgement?',
:discussion_topic => :iq_crowdsourcedContent,
:help_text => 'If people used their creativity or judgement to contribute data then they have copyright over their work. For example, writing a description or deciding whether or not to include some data in a dataset would require judgement. So contributors must transfer or waive their rights, or license the data to you before you can publish it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
a_false 'no'
a_true 'yes'
q_claUrl 'Where is the Contributor Licence Agreement (CLA)?',
:discussion_topic => :iq_claUrl,
:display_on_certificate => true,
:text_as_statement => 'The Contributor Licence Agreement is at',
:help_text => 'Give a link to an agreement that shows contributors allow you to reuse their data. A CLA will either transfer contributor\'s rights to you, waive their rights, or license the data to you so you can publish it.',
:help_text_more_url => 'http://en.wikipedia.org/wiki/Contributor_License_Agreement',
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
a_1 'Contributor Licence Agreement URL',
:string,
:input_type => :url,
:placeholder => 'Contributor Licence Agreement URL',
:required => :required
q_cldsRecorded 'Have all contributors agreed to the Contributor Licence Agreement (CLA)?',
:discussion_topic => :iq_cldsRecorded,
:help_text => 'Check all contributors agree to a CLA before you reuse or republish their contributions. You should keep a record of who gave contributions and whether or not they agree to the CLA.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
a_false 'no'
a_true 'yes',
:requirement => ['basic_6']
label_basic_6 'You must get <strong>contributors to agree to a Contributor Licence Agreement</strong> (CLA) that gives you the right to publish their work as open data.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_6'
dependency :rule => 'A and B and C and D and E'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
condition_E :q_cldsRecorded, '==', :a_false
q_sourceDocumentationUrl 'Where do you describe sources of this data?',
:discussion_topic => :iq_sourceDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The sources of this data are described at',
:help_text => 'Give a URL that documents where the data was sourced from (its provenance) and the rights under which you publish the data. This helps people understand where the data comes from.'
dependency :rule => 'A'
condition_A :q_publisherOrigin, '==', :a_false
a_1 'Data Sources Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Data Sources Documentation URL',
:requirement => ['pilot_3']
label_pilot_3 'You should document <strong>where the data came from and the rights under which you publish it</strong>, so people are assured they can use parts which came from third parties.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_3'
dependency :rule => 'A and B'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_sourceDocumentationMetadata 'Is documentation about the sources of this data also in machine-readable format?',
:discussion_topic => :iq_sourceDocumentationMetadata,
:display_on_certificate => true,
:text_as_statement => 'The curator has published',
:help_text => 'Information about data sources should be human-readable so people can understand it, as well as in a metadata format that computers can process. When everyone does this it helps other people find out how the same open data is being used and justify its ongoing publication.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable data about the sources of this data',
:requirement => ['standard_2']
label_standard_2 'You should <strong>include machine-readable data about the sources of this data</strong>.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_2'
dependency :rule => 'A and B and C'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_sourceDocumentationMetadata, '==', :a_false
label_group_3 'Licensing',
:help_text => 'how you give people permission to use this data',
:customer_renderer => '/partials/fieldset'
q_copyrightURL 'Where have you published the rights statement for this dataset?',
:discussion_topic => :iq_copyrightURL,
:display_on_certificate => true,
:text_as_statement => 'The rights statement is at',
:help_text => 'Give the URL to a page that describes the right to re-use this dataset. This should include a reference to its license, attribution requirements, and a statement about relevant copyright. A rights statement helps people understand what they can and can\'t do with the data.'
a_1 'Rights Statement URL',
:string,
:input_type => :url,
:placeholder => 'Rights Statement URL',
:requirement => ['pilot_4']
label_pilot_4 'You should <strong>publish a rights statement</strong> that details copyright, licensing and how people should give attribution to the data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_4'
dependency :rule => 'A'
condition_A :q_copyrightURL, '==', {:string_value => '', :answer_reference => '1'}
q_dataLicence 'Under which licence can people reuse this data?',
:discussion_topic => :iq_dataLicence,
:display_on_certificate => true,
:text_as_statement => 'This data is available under',
:help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it. Creative content includes the organisation and selection of items within data, but does not include facts. So people need a waiver or a licence which proves that they can use the data and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the data, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
a_cc_by 'Creative Commons Attribution',
:text_as_statement => 'Creative Commons Attribution'
a_cc_by_sa 'Creative Commons Attribution Share-Alike',
:text_as_statement => 'Creative Commons Attribution Share-Alike'
a_cc_zero 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_odc_by 'Open Data Commons Attribution License',
:text_as_statement => 'Open Data Commons Attribution License'
a_odc_odbl 'Open Data Commons Open Database License (ODbL)',
:text_as_statement => 'Open Data Commons Open Database License (ODbL)'
a_odc_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)',
:text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)'
a_na 'Not applicable',
:text_as_statement => ''
a_other 'Other...',
:text_as_statement => ''
q_dataNotApplicable 'Why doesn\'t a licence apply to this data?',
:discussion_topic => :iq_dataNotApplicable,
:display_on_certificate => true,
:text_as_statement => 'This data is not licensed because',
:pick => :one,
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_na
a_norights 'there is no copyright in this data',
:text_as_statement => 'there is no copyright in it',
:help_text => 'Copyright only applies to data if you spent intellectual effort creating what\'s in it, for example, by writing text that\'s within the data, or deciding whether particular data is included. There\'s no copyright if the data only contains facts where no judgements were made about whether to include them or not.'
a_expired 'copyright has expired',
:text_as_statement => 'copyright has expired',
:help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.'
a_waived 'copyright has been waived',
:text_as_statement => '',
:help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.'
q_dataWaiver 'Which waiver do you use to waive copyright in the data?',
:discussion_topic => :iq_dataWaiver,
:display_on_certificate => true,
:text_as_statement => 'Rights in the data have been waived with',
:help_text => 'You need a statement to show people copyright has been waived, so they understand that they can do whatever they like with this data. Standard waivers already exist like PDDL and CCZero but you can write your own with legal advice.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A and B'
condition_A :q_dataLicence, '==', :a_na
condition_B :q_dataNotApplicable, '==', :a_waived
a_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)',
:text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)'
a_cc0 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_other 'Other...',
:text_as_statement => ''
q_dataOtherWaiver 'Where is the waiver for the copyright in the data?',
:discussion_topic => :iq_dataOtherWaiver,
:display_on_certificate => true,
:text_as_statement => 'Rights in the data have been waived with',
:help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive copyright in the data.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_dataLicence, '==', :a_na
condition_B :q_dataNotApplicable, '==', :a_waived
condition_C :q_dataWaiver, '==', :a_other
a_1 'Waiver URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Waiver URL'
q_otherDataLicenceName 'What is the name of the licence?',
:discussion_topic => :iq_otherDataLicenceName,
:display_on_certificate => true,
:text_as_statement => 'This data is available under',
:help_text => 'If you use a different licence, we need the name so people can see it on your Open Data Certificate.',
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_1 'Other Licence Name',
:string,
:required => :required,
:placeholder => 'Other Licence Name'
q_otherDataLicenceURL 'Where is the licence?',
:discussion_topic => :iq_otherDataLicenceURL,
:display_on_certificate => true,
:text_as_statement => 'This licence is at',
:help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.',
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_1 'Other Licence URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Other Licence URL'
q_otherDataLicenceOpen 'Is the licence an open licence?',
:discussion_topic => :iq_otherDataLicenceOpen,
:help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.',
:help_text_more_url => 'http://opendefinition.org/',
:pick => :one,
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_false 'no'
a_true 'yes',
:requirement => ['basic_7']
label_basic_7 'You must <strong>publish open data under an open licence</strong> so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_7'
dependency :rule => 'A and B'
condition_A :q_dataLicence, '==', :a_other
condition_B :q_otherDataLicenceOpen, '==', :a_false
q_contentRights 'Is there any copyright in the content of this data?',
:discussion_topic => :iq_contentRights,
:display_on_certificate => true,
:text_as_statement => 'There are',
:pick => :one,
:required => :required
a_norights 'no, the data only contains facts and numbers',
:text_as_statement => 'no rights in the content of the data',
:help_text => 'There is no copyright in factual information. If the data does not contain any content that was created through intellectual effort, there are no rights in the content.'
a_samerights 'yes, and the rights are all held by the same person or organisation',
:text_as_statement => '',
:help_text => 'Choose this option if the content in the data was all created by or transferred to the same person or organisation.'
a_mixedrights 'yes, and the rights are held by different people or organisations',
:text_as_statement => '',
:help_text => 'In some data, the rights in different records are held by different people or organisations. Information about rights needs to be kept in the data too.'
q_explicitWaiver 'Is the content of the data marked as public domain?',
:discussion_topic => :iq_explicitWaiver,
:display_on_certificate => true,
:text_as_statement => 'The content has been',
:help_text => 'Content can be marked as public domain using the <a href="http://creativecommons.org/publicdomain/">Creative Commons Public Domain Mark</a>. This helps people know that it can be freely reused.',
:pick => :one
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_norights
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'marked as public domain',
:requirement => ['standard_3']
label_standard_3 'You should <strong>mark public domain content as public domain</strong> so that people know they can reuse it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_3'
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_norights
condition_B :q_explicitWaiver, '==', :a_false
q_contentLicence 'Under which licence can others reuse content?',
:discussion_topic => :iq_contentLicence,
:display_on_certificate => true,
:text_as_statement => 'The content is available under',
:help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it but creative content does not include facts. So people need a waiver or a licence which proves that they can use the content and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the content, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_samerights
a_cc_by 'Creative Commons Attribution',
:text_as_statement => 'Creative Commons Attribution'
a_cc_by_sa 'Creative Commons Attribution Share-Alike',
:text_as_statement => 'Creative Commons Attribution Share-Alike'
a_cc_zero 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_na 'Not applicable',
:text_as_statement => ''
a_other 'Other...',
:text_as_statement => ''
q_contentNotApplicable 'Why doesn\'t a licence apply to the content of the data?',
:discussion_topic => :iq_contentNotApplicable,
:display_on_certificate => true,
:text_as_statement => 'The content in this data is not licensed because',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
a_norights 'there is no copyright in the content of this data',
:text_as_statement => 'there is no copyright',
:help_text => 'Copyright only applies to content if you spent intellectual effort creating it, for example, by writing text that\'s within the data. There\'s no copyright if the content only contains facts.'
a_expired 'copyright has expired',
:text_as_statement => 'copyright has expired',
:help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.'
a_waived 'copyright has been waived',
:text_as_statement => '',
:help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.'
q_contentWaiver 'Which waiver do you use to waive copyright?',
:discussion_topic => :iq_contentWaiver,
:display_on_certificate => true,
:text_as_statement => 'Copyright has been waived with',
:help_text => 'You need a statement to show people you\'ve done this, so they understand that they can do whatever they like with this data. Standard waivers already exist like CCZero but you can write your own with legal advice.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A and B and C'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
condition_C :q_contentNotApplicable, '==', :a_waived
a_cc0 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_other 'Other...',
:text_as_statement => 'Other...'
q_contentOtherWaiver 'Where is the waiver for the copyright?',
:discussion_topic => :iq_contentOtherWaiver,
:display_on_certificate => true,
:text_as_statement => 'Copyright has been waived with',
:help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive your copyright.',
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
condition_C :q_contentNotApplicable, '==', :a_waived
condition_D :q_contentWaiver, '==', :a_other
a_1 'Waiver URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Waiver URL'
q_otherContentLicenceName 'What\'s the name of the licence?',
:discussion_topic => :iq_otherContentLicenceName,
:display_on_certificate => true,
:text_as_statement => 'The content is available under',
:help_text => 'If you use a different licence, we need its name so people can see it on your Open Data Certificate.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_1 'Licence Name',
:string,
:required => :required,
:placeholder => 'Licence Name'
q_otherContentLicenceURL 'Where is the licence?',
:discussion_topic => :iq_otherContentLicenceURL,
:display_on_certificate => true,
:text_as_statement => 'The content licence is at',
:help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_1 'Licence URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Licence URL'
q_otherContentLicenceOpen 'Is the licence an open licence?',
:discussion_topic => :iq_otherContentLicenceOpen,
:help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.',
:help_text_more_url => 'http://opendefinition.org/',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_false 'no'
a_true 'yes',
:requirement => ['basic_8']
label_basic_8 'You must <strong>publish open data under an open licence</strong> so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_8'
dependency :rule => 'A and B and C'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
condition_C :q_otherContentLicenceOpen, '==', :a_false
q_contentRightsURL 'Where are the rights and licensing of the content explained?',
:discussion_topic => :iq_contentRightsURL,
:display_on_certificate => true,
:text_as_statement => 'The rights and licensing of the content are explained at',
:help_text => 'Give the URL for a page where you describe how someone can find out the rights and licensing of a piece of content from the data.',
:required => :required
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_mixedrights
a_1 'Content Rights Description URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Content Rights Description URL'
q_copyrightStatementMetadata 'Does your rights statement include machine-readable versions of',
:discussion_topic => :iq_copyrightStatementMetadata,
:display_on_certificate => true,
:text_as_statement => 'The rights statement includes data about',
:help_text => 'It\'s good practice to embed information about rights in machine-readable formats so people can automatically attribute this data back to you when they use it.',
:help_text_more_url => 'https://github.com/theodi/open-data-licensing/blob/master/guides/publisher-guide.md',
:pick => :any
dependency :rule => 'A'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
a_dataLicense 'data licence',
:text_as_statement => 'its data licence',
:requirement => ['standard_4']
a_contentLicense 'content licence',
:text_as_statement => 'its content licence',
:requirement => ['standard_5']
a_attribution 'attribution text',
:text_as_statement => 'what attribution text to use',
:requirement => ['standard_6']
a_attributionURL 'attribution URL',
:text_as_statement => 'what attribution link to give',
:requirement => ['standard_7']
a_copyrightNotice 'copyright notice or statement',
:text_as_statement => 'a copyright notice or statement',
:requirement => ['exemplar_1']
a_copyrightYear 'copyright year',
:text_as_statement => 'the copyright year',
:requirement => ['exemplar_2']
a_copyrightHolder 'copyright holder',
:text_as_statement => 'the copyright holder',
:requirement => ['exemplar_3']
label_standard_4 'You should provide <strong>machine-readable data in your rights statement about the licence</strong> for this data, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_4'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_dataLicense
label_standard_5 'You should provide <strong>machine-readable data in your rights statement about the licence for the content</strong> of this data, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_5'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_contentLicense
label_standard_6 'You should provide <strong>machine-readable data in your rights statement about the text to use when citing the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_6'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_attribution
label_standard_7 'You should provide <strong>machine-readable data in your rights statement about the URL to link to when citing this data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_7'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_attributionURL
label_exemplar_1 'You should provide <strong>machine-readable data in your rights statement about the copyright statement or notice of this data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_1'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightNotice
label_exemplar_2 'You should provide <strong>machine-readable data in your rights statement about the copyright year for the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_2'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightYear
label_exemplar_3 'You should provide <strong>machine-readable data in your rights statement about the copyright holder for the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_3'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightHolder
label_group_4 'Privacy',
:help_text => 'how you protect people\'s privacy',
:customer_renderer => '/partials/fieldset'
q_dataPersonal 'Can individuals be identified from this data?',
:discussion_topic => :iq_dataPersonal,
:display_on_certificate => true,
:text_as_statement => 'This data contains',
:pick => :one,
:required => :pilot
a_not_personal 'no, the data is not about people or their activities',
:text_as_statement => 'no data about individuals',
:help_text => 'Remember that individuals can still be identified even if data isn\'t directly about them. For example, road traffic flow data combined with an individual\'s commuting patterns could reveal information about that person.'
a_summarised 'no, the data has been anonymised by aggregating individuals into groups, so they can\'t be distinguished from other people in the group',
:text_as_statement => 'aggregated data',
:help_text => 'Statistical disclosure controls can help to make sure that individuals are not identifiable within aggregate data.'
a_individual 'yes, there is a risk that individuals be identified, for example by third parties with access to extra information',
:text_as_statement => 'information that could identify individuals',
:help_text => 'Some data is legitimately about individuals like civil service pay or public expenses for example.'
q_statisticalAnonAudited 'Has your anonymisation process been independently audited?',
:discussion_topic => :iq_statisticalAnonAudited,
:display_on_certificate => true,
:text_as_statement => 'The anonymisation process has been',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataPersonal, '==', :a_summarised
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_8']
label_standard_8 'You should <strong>have your anonymisation process audited independently</strong> to ensure it reduces the risk of individuals being reidentified.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_8'
dependency :rule => 'A and B'
condition_A :q_dataPersonal, '==', :a_summarised
condition_B :q_statisticalAnonAudited, '==', :a_false
q_appliedAnon 'Have you attempted to reduce or remove the possibility of individuals being identified?',
:discussion_topic => :iq_appliedAnon,
:display_on_certificate => true,
:text_as_statement => 'This data about individuals has been',
:help_text => 'Anonymisation reduces the risk of individuals being identified from the data you publish. The best technique to use depends on the kind of data you have.',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_dataPersonal, '==', :a_individual
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'anonymised'
q_lawfulDisclosure 'Are you required or permitted by law to publish this data about individuals?',
:discussion_topic => :iq_lawfulDisclosure,
:display_on_certificate => true,
:text_as_statement => 'By law, this data about individuals',
:help_text => 'The law might require you to publish data about people, such as the names of company directors. Or you might have permission from the affected individuals to publish information about them.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'can be published',
:requirement => ['pilot_5']
label_pilot_5 'You should <strong>only publish personal data without anonymisation if you are required or permitted to do so by law</strong>.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_5'
dependency :rule => 'A and B and C'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_false
q_lawfulDisclosureURL 'Where do you document your right to publish data about individuals?',
:discussion_topic => :iq_lawfulDisclosureURL,
:display_on_certificate => true,
:text_as_statement => 'The right to publish this data about individuals is documented at'
dependency :rule => 'A and B and C'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_true
a_1 'Disclosure Rationale URL',
:string,
:input_type => :url,
:placeholder => 'Disclosure Rationale URL',
:requirement => ['standard_9']
label_standard_9 'You should <strong>document your right to publish data about individuals</strong> for people who use your data and for those affected by disclosure.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_9'
dependency :rule => 'A and B and C and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_lawfulDisclosureURL, '==', {:string_value => '', :answer_reference => '1'}
q_riskAssessmentExists 'Have you assessed the risks of disclosing personal data?',
:discussion_topic => :iq_riskAssessmentExists,
:display_on_certificate => true,
:text_as_statement => 'The curator has',
:help_text => 'A risk assessment measures risks to the privacy of individuals in your data as well as the use and disclosure of that information.',
:pick => :one
dependency :rule => 'A and (B or C)'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
a_false 'no',
:text_as_statement => 'not carried out a privacy risk assessment'
a_true 'yes',
:text_as_statement => 'carried out a privacy risk assessment',
:requirement => ['pilot_6']
label_pilot_6 'You should <strong>assess the risks of disclosing personal data</strong> if you publish data about individuals.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_6'
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_false
q_riskAssessmentUrl 'Where is your risk assessment published?',
:discussion_topic => :iq_riskAssessmentUrl,
:display_on_certificate => true,
:text_as_statement => 'The risk assessment is published at',
:help_text => 'Give a URL to where people can check how you have assessed the privacy risks to individuals. This may be redacted or summarised if it contains sensitive information.'
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
a_1 'Risk Assessment URL',
:string,
:input_type => :url,
:placeholder => 'Risk Assessment URL',
:requirement => ['standard_10']
label_standard_10 'You should <strong>publish your privacy risk assessment</strong> so people can understand how you have assessed the risks of disclosing data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_10'
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '==', {:string_value => '', :answer_reference => '1'}
q_riskAssessmentAudited 'Has your risk assessment been independently audited?',
:discussion_topic => :iq_riskAssessmentAudited,
:display_on_certificate => true,
:text_as_statement => 'The risk assessment has been',
:help_text => 'It\'s good practice to check your risk assessment was done correctly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.',
:pick => :one
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_11']
label_standard_11 'You should <strong>have your risk assessment audited independently</strong> to ensure it has been carried out correctly.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_11'
dependency :rule => 'A and (B or C) and D and E and F'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_F :q_riskAssessmentAudited, '==', :a_false
q_anonymisationAudited 'Has your anonymisation approach been independently audited?',
:discussion_topic => :iq_anonymisationAudited,
:display_on_certificate => true,
:text_as_statement => 'The anonymisation of the data has been',
:help_text => 'It is good practice to make sure your process to remove personal identifiable data works properly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.',
:pick => :one
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_12']
label_standard_12 'You should <strong>have your anonymisation process audited independently</strong> by an expert to ensure it is appropriate for your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_12'
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_anonymisationAudited, '==', :a_false
end
section_practical 'Practical Information',
:description => 'Findability, accuracy, quality and guarantees' do
label_group_6 'Findability',
:help_text => 'how you help people find your data',
:customer_renderer => '/partials/fieldset'
q_onWebsite 'Is there a link to your data from your main website?',
:discussion_topic => :onWebsite,
:help_text => 'Data can be found more easily if it is linked to from your main website.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_13']
label_standard_13 'You should <strong>ensure that people can find the data from your main website</strong> so that people can find it more easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_13'
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_false
repeater 'Web Page' do
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_true
q_webpage 'Which page on your website links to the data?',
:discussion_topic => :webpage,
:display_on_certificate => true,
:text_as_statement => 'The website links to the data from',
:help_text => 'Give a URL on your main website that includes a link to this data.',
:required => :required
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_true
a_1 'Web page URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Web page URL'
end
q_listed 'Is your data listed within a collection?',
:discussion_topic => :listed,
:help_text => 'Data is easier for people to find when it\'s in relevant data catalogs like academic, public sector or health for example, or when it turns up in relevant search results.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_14']
label_standard_14 'You should <strong>ensure that people can find your data when they search for it</strong> in locations that list data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_14'
dependency :rule => 'A'
condition_A :q_listed, '==', :a_false
repeater 'Listing' do
dependency :rule => 'A'
condition_A :q_listed, '==', :a_true
q_listing 'Where is it listed?',
:discussion_topic => :listing,
:display_on_certificate => true,
:text_as_statement => 'The data appears in this collection',
:help_text => 'Give a URL where this data is listed within a relevant collection. For example, data.gov.uk (if it\'s UK public sector data), hub.data.ac.uk (if it\'s UK academia data) or a URL for search engine results.',
:required => :required
dependency :rule => 'A'
condition_A :q_listed, '==', :a_true
a_1 'Listing URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Listing URL'
end
q_referenced 'Is this data referenced from your own publications?',
:discussion_topic => :referenced,
:help_text => 'When you reference your data within your own publications, such as reports, presentations or blog posts, you give it more context and help people find and understand it better.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_15']
label_standard_15 'You should <strong>reference data from your own publications</strong> so that people are aware of its availability and context.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_15'
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_false
repeater 'Reference' do
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_true
q_reference 'Where is your data referenced?',
:discussion_topic => :reference,
:display_on_certificate => true,
:text_as_statement => 'This data is referenced from',
:help_text => 'Give a URL to a document that cites or references this data.',
:required => :required
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_true
a_1 'Reference URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Reference URL'
end
label_group_7 'Accuracy',
:help_text => 'how you keep your data up-to-date',
:customer_renderer => '/partials/fieldset'
q_serviceType 'Does the data behind your API change?',
:discussion_topic => :serviceType,
:display_on_certificate => true,
:text_as_statement => 'The data behind the API',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_static 'no, the API gives access to unchanging data',
:text_as_statement => 'will not change',
:help_text => 'Some APIs just make accessing an unchanging dataset easier, particularly when there\'s lots of it.'
a_changing 'yes, the API gives access to changing data',
:text_as_statement => 'will change',
:help_text => 'Some APIs give instant access to more up-to-date and ever-changing data'
q_timeSensitive 'Will your data go out of date?',
:discussion_topic => :timeSensitive,
:display_on_certificate => true,
:text_as_statement => 'The accuracy or relevance of this data will',
:pick => :one
dependency :rule => '(A or B or (C and D))'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
a_true 'yes, this data will go out of date',
:text_as_statement => 'go out of date',
:help_text => 'For example, a dataset of bus stop locations will go out of date over time as some are moved or new ones created.'
a_timestamped 'yes, this data will go out of date over time but it’s time stamped',
:text_as_statement => 'go out of date but it is timestamped',
:help_text => 'For example, population statistics usually include a fixed timestamp to indicate when the statistics were relevant.',
:requirement => ['pilot_7']
a_false 'no, this data does not contain any time-sensitive information',
:text_as_statement => 'not go out of date',
:help_text => 'For example, the results of an experiment will not go out of date because the data accurately reports observed outcomes.',
:requirement => ['standard_16']
label_pilot_7 'You should <strong>put timestamps in your data when you release it</strong> so people know the period it relates to and when it will expire.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_7'
dependency :rule => '(A or B or (C and D)) and (E and F)'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
condition_E :q_timeSensitive, '!=', :a_timestamped
condition_F :q_timeSensitive, '!=', :a_false
label_standard_16 'You should <strong>publish updates to time-sensitive data</strong> so that it does not go stale.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_16'
dependency :rule => '(A or B or (C and D)) and (E)'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
condition_E :q_timeSensitive, '!=', :a_false
q_frequentChanges 'Does this data change at least daily?',
:discussion_topic => :frequentChanges,
:display_on_certificate => true,
:text_as_statement => 'This data changes',
:help_text => 'Tell people if the underlying data changes on most days. When data changes frequently it also goes out of date quickly, so people need to know if you also update it frequently and quickly too.',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'at least daily'
q_seriesType 'What type of dataset series is this?',
:discussion_topic => :seriesType,
:display_on_certificate => true,
:text_as_statement => 'This data is a series of',
:pick => :one,
:required => :exemplar
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
a_dumps 'regular copies of a complete database',
:text_as_statement => 'copies of a database',
:help_text => 'Choose if you publish new and updated copies of your full database regularly. When you create database dumps, it\'s useful for people to have access to a feed of the changes so they can keep their copies up to date.'
a_aggregate 'regular aggregates of changing data',
:text_as_statement => 'aggregates of changing data',
:help_text => 'Choose if you create new datasets regularly. You might do this if the underlying data can\'t be released as open data or if you only publish data that\'s new since the last publication.'
q_changeFeed 'Is a feed of changes available?',
:discussion_topic => :changeFeed,
:display_on_certificate => true,
:text_as_statement => 'A feed of changes to this data',
:help_text => 'Tell people if you provide a stream of changes that affect this data, like new entries or amendments to existing entries. Feeds might be in RSS, Atom or custom formats.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_seriesType, '==', :a_dumps
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'is available',
:requirement => ['exemplar_4']
label_exemplar_4 'You should <strong>provide a feed of changes to your data</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_4'
dependency :rule => 'A and B and C and D'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_seriesType, '==', :a_dumps
condition_D :q_changeFeed, '==', :a_false
q_frequentSeriesPublication 'How often do you create a new release?',
:discussion_topic => :frequentSeriesPublication,
:display_on_certificate => true,
:text_as_statement => 'New releases of this data are made',
:help_text => 'This determines how out of date this data becomes before people can get an update.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
a_rarely 'less than once a month',
:text_as_statement => 'less than once a month'
a_monthly 'at least every month',
:text_as_statement => 'at least every month',
:requirement => ['pilot_8']
a_weekly 'at least every week',
:text_as_statement => 'at least every week',
:requirement => ['standard_17']
a_daily 'at least every day',
:text_as_statement => 'at least every day',
:requirement => ['exemplar_5']
label_pilot_8 'You should <strong>create a new dataset release every month</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_8'
dependency :rule => 'A and B and (C and D and E)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_monthly
condition_D :q_frequentSeriesPublication, '!=', :a_weekly
condition_E :q_frequentSeriesPublication, '!=', :a_daily
label_standard_17 'You should <strong>create a new dataset release every week</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_17'
dependency :rule => 'A and B and (C and D)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_weekly
condition_D :q_frequentSeriesPublication, '!=', :a_daily
label_exemplar_5 'You should <strong>create a new dataset release every day</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_5'
dependency :rule => 'A and B and (C)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_daily
q_seriesPublicationDelay 'How long is the delay between when you create a dataset and when you publish it?',
:discussion_topic => :seriesPublicationDelay,
:display_on_certificate => true,
:text_as_statement => 'The lag between creation and publication of this data is',
:pick => :one
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_extreme 'longer than the gap between releases',
:text_as_statement => 'longer than the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes more than a day for it to be published.'
a_reasonable 'about the same as the gap between releases',
:text_as_statement => 'about the same as the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes about a day for it to be published.',
:requirement => ['pilot_9']
a_good 'less than half the gap between releases',
:text_as_statement => 'less than half the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes less than twelve hours for it to be published.',
:requirement => ['standard_18']
a_minimal 'there is minimal or no delay',
:text_as_statement => 'minimal',
:help_text => 'Choose this if you publish within a few seconds or a few minutes.',
:requirement => ['exemplar_6']
label_pilot_9 'You should <strong>have a reasonable delay between when you create and publish a dataset</strong> that is less than the gap between releases so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_9'
dependency :rule => 'A and (B and C and D)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_reasonable
condition_C :q_seriesPublicationDelay, '!=', :a_good
condition_D :q_seriesPublicationDelay, '!=', :a_minimal
label_standard_18 'You should <strong>have a short delay between when you create and publish a dataset</strong> that is less than half the gap between releases so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_18'
dependency :rule => 'A and (B and C)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_good
condition_C :q_seriesPublicationDelay, '!=', :a_minimal
label_exemplar_6 'You should <strong>have minimal or no delay between when you create and publish a dataset</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_6'
dependency :rule => 'A and (B)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_minimal
q_provideDumps 'Do you also publish dumps of this dataset?',
:discussion_topic => :provideDumps,
:display_on_certificate => true,
:text_as_statement => 'The curator publishes',
:help_text => 'A dump is an extract of the whole dataset into a file that people can download. This lets people do analysis that\'s different to analysis with API access.',
:pick => :one
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'dumps of the data',
:requirement => ['standard_19']
label_standard_19 'You should <strong>let people download your entire dataset</strong> so that they can do more complete and accurate analysis with all the data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_19'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_false
q_dumpFrequency 'How frequently do you create a new database dump?',
:discussion_topic => :dumpFrequency,
:display_on_certificate => true,
:text_as_statement => 'Database dumps are created',
:help_text => 'Faster access to more frequent extracts of the whole dataset means people can get started quicker with the most up-to-date data.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
a_rarely 'less frequently than once a month',
:text_as_statement => 'less frequently than once a month'
a_monthly 'at least every month',
:text_as_statement => 'at least every month',
:requirement => ['pilot_10']
a_weekly 'within a week of any change',
:text_as_statement => 'within a week of any change',
:requirement => ['standard_20']
a_daily 'within a day of any change',
:text_as_statement => 'within a day of any change',
:requirement => ['exemplar_7']
label_pilot_10 'You should <strong>create a new database dump every month</strong> so that people have the latest data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_10'
dependency :rule => 'A and B and C and (D and E and F)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_monthly
condition_E :q_dumpFrequency, '!=', :a_weekly
condition_F :q_dumpFrequency, '!=', :a_daily
label_standard_20 'You should <strong>create a new database dump within a week of any change</strong> so that people have less time to wait for the latest data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_20'
dependency :rule => 'A and B and C and (D and E)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_weekly
condition_E :q_dumpFrequency, '!=', :a_daily
label_exemplar_7 'You should <strong>create a new database dump within a day of any change</strong> so that people find it easier to get the latest data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_7'
dependency :rule => 'A and B and C and (D)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_daily
q_corrected 'Will your data be corrected if it has errors?',
:discussion_topic => :corrected,
:display_on_certificate => true,
:text_as_statement => 'Any errors in this data are',
:help_text => 'It\'s good practice to fix errors in your data especially if you use it yourself. When you make corrections, people need to be told about them.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_timeSensitive, '!=', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'corrected',
:requirement => ['standard_21']
label_standard_21 'You should <strong>correct data when people report errors</strong> so everyone benefits from improvements in accuracy.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_21'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_timeSensitive, '!=', :a_true
condition_C :q_corrected, '==', :a_false
label_group_8 'Quality',
:help_text => 'how much people can rely on your data',
:customer_renderer => '/partials/fieldset'
q_qualityUrl 'Where do you document issues with the quality of this data?',
:discussion_topic => :qualityUrl,
:display_on_certificate => true,
:text_as_statement => 'Data quality is documented at',
:help_text => 'Give a URL where people can find out about the quality of your data. People accept that errors are inevitable, from equipment malfunctions or mistakes that happen in system migrations. You should be open about quality so people can judge how much to rely on this data.'
a_1 'Data Quality Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Data Quality Documentation URL',
:requirement => ['standard_22']
label_standard_22 'You should <strong>document any known issues with your data quality</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_22'
dependency :rule => 'A'
condition_A :q_qualityUrl, '==', {:string_value => '', :answer_reference => '1'}
q_qualityControlUrl 'Where is your quality control process described?',
:discussion_topic => :qualityControlUrl,
:display_on_certificate => true,
:text_as_statement => 'Quality control processes are described at',
:help_text => 'Give a URL for people to learn about ongoing checks on your data, either automatic or manual. This reassures them that you take quality seriously and encourages improvements that benefit everyone.'
a_1 'Quality Control Process Description URL',
:string,
:input_type => :url,
:placeholder => 'Quality Control Process Description URL',
:requirement => ['exemplar_8']
label_exemplar_8 'You should <strong>document your quality control process</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_8'
dependency :rule => 'A'
condition_A :q_qualityControlUrl, '==', {:string_value => '', :answer_reference => '1'}
label_group_9 'Guarantees',
:help_text => 'how much people can depend on your data’s availability',
:customer_renderer => '/partials/fieldset'
q_backups 'Do you take offsite backups?',
:discussion_topic => :backups,
:display_on_certificate => true,
:text_as_statement => 'The data is',
:help_text => 'Taking a regular offsite backup helps ensure that the data won\'t be lost in the case of accident.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'backed up offsite',
:requirement => ['standard_23']
label_standard_23 'You should <strong>take a result offsite backup</strong> so that the data won\'t be lost if an accident happens.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_23'
dependency :rule => 'A'
condition_A :q_backups, '==', :a_false
q_slaUrl 'Where do you describe any guarantees about service availability?',
:discussion_topic => :slaUrl,
:display_on_certificate => true,
:text_as_statement => 'Service availability is described at',
:help_text => 'Give a URL for a page that describes what guarantees you have about your service being available for people to use. For example you might have a guaranteed uptime of 99.5%, or you might provide no guarantees.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Service Availability Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Service Availability Documentation URL',
:requirement => ['standard_24']
label_standard_24 'You should <strong>describe what guarantees you have around service availability</strong> so that people know how much they can rely on it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_24'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_slaUrl, '==', {:string_value => '', :answer_reference => '1'}
q_statusUrl 'Where do you give information about the current status of the service?',
:discussion_topic => :statusUrl,
:display_on_certificate => true,
:text_as_statement => 'Service status is given at',
:help_text => 'Give a URL for a page that tells people about the current status of your service, including any faults you are aware of.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Service Status URL',
:string,
:input_type => :url,
:placeholder => 'Service Status URL',
:requirement => ['exemplar_9']
label_exemplar_9 'You should <strong>have a service status page</strong> that tells people about the current status of your service.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_9'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_statusUrl, '==', {:string_value => '', :answer_reference => '1'}
q_onGoingAvailability 'How long will this data be available for?',
:discussion_topic => :onGoingAvailability,
:display_on_certificate => true,
:text_as_statement => 'The data is available',
:pick => :one
a_experimental 'it might disappear at any time',
:text_as_statement => 'experimentally and might disappear at any time'
a_short 'it\'s available experimentally but should be around for another year or so',
:text_as_statement => 'experimentally for another year or so',
:requirement => ['pilot_11']
a_medium 'it\'s in your medium-term plans so should be around for a couple of years',
:text_as_statement => 'for at least a couple of years',
:requirement => ['standard_25']
a_long 'it\'s part of your day-to-day operations so will stay published for a long time',
:text_as_statement => 'for a long time',
:requirement => ['exemplar_10']
label_pilot_11 'You should <strong>guarantee that your data will be available in this form for at least a year</strong> so that people can decide how much to rely on your data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_11'
dependency :rule => 'A and B and C'
condition_A :q_onGoingAvailability, '!=', :a_short
condition_B :q_onGoingAvailability, '!=', :a_medium
condition_C :q_onGoingAvailability, '!=', :a_long
label_standard_25 'You should <strong>guarantee that your data will be available in this form in the medium-term</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_25'
dependency :rule => 'A and B'
condition_A :q_onGoingAvailability, '!=', :a_medium
condition_B :q_onGoingAvailability, '!=', :a_long
label_exemplar_10 'You should <strong>guarantee that your data will be available in this form in the long-term</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_10'
dependency :rule => 'A'
condition_A :q_onGoingAvailability, '!=', :a_long
end
section_technical 'Technical Information',
:description => 'Locations, formats and trust' do
label_group_11 'Locations',
:help_text => 'how people can access your data',
:customer_renderer => '/partials/fieldset'
q_datasetUrl 'Where is your dataset?',
:discussion_topic => :datasetUrl,
:display_on_certificate => true,
:text_as_statement => 'This data is published at',
:help_text => 'Give a URL to the dataset itself. Open data should be linked to directly on the web so people can easily find and reuse it.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_oneoff
a_1 'Dataset URL',
:string,
:input_type => :url,
:placeholder => 'Dataset URL',
:requirement => ['basic_9', 'pilot_12']
label_basic_9 'You must <strong>provide either a URL to your data or a URL to documentation</strong> about it so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_9'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'}
label_pilot_12 'You should <strong>have a URL that is a direct link to the data itself</strong> so that people can access it easily.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_12'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'}
q_versionManagement 'How do you publish a series of the same dataset?',
:discussion_topic => :versionManagement,
:requirement => ['basic_10'],
:pick => :any
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_current 'as a single URL that\'s regularly updated',
:help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current dataset.',
:requirement => ['standard_26']
a_template 'as consistent URLs for each release',
:help_text => 'Choose this if your dataset URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['pilot_13']
a_list 'as a list of releases',
:help_text => 'Choose this if you have a list of datasets on a web page or a feed (like Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['standard_27']
label_standard_26 'You should <strong>have a single persistent URL to download the current version of your data</strong> so that people can access it easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_26'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_current
label_pilot_13 'You should <strong>use a consistent pattern for different release URLs</strong> so that people can download each one automatically.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_13'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_template
label_standard_27 'You should <strong>have a document or feed with a list of available releases</strong> so people can create scripts to download them all.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_27'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_list
label_basic_10 'You must <strong>provide access to releases of your data through a URL</strong> that gives the current version, a discoverable series of URLs or through a documentation page so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_10'
dependency :rule => 'A and (B and C and D and E)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_versionManagement, '!=', :a_current
condition_D :q_versionManagement, '!=', :a_template
condition_E :q_versionManagement, '!=', :a_list
q_currentDatasetUrl 'Where is your current dataset?',
:discussion_topic => :currentDatasetUrl,
:display_on_certificate => true,
:text_as_statement => 'The current dataset is available at',
:help_text => 'Give a single URL to the most recent version of the dataset. The content at this URL should change each time a new version is released.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_current
a_1 'Current Dataset URL',
:string,
:input_type => :url,
:placeholder => 'Current Dataset URL',
:required => :required
q_versionsTemplateUrl 'What format do dataset release URLs follow?',
:discussion_topic => :versionsTemplateUrl,
:display_on_certificate => true,
:text_as_statement => 'Releases follow this consistent URL pattern',
:help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_template
a_1 'Version Template URL',
:string,
:input_type => :text,
:placeholder => 'Version Template URL',
:required => :required
q_versionsUrl 'Where is your list of dataset releases?',
:discussion_topic => :versionsUrl,
:display_on_certificate => true,
:text_as_statement => 'Releases of this data are listed at',
:help_text => 'Give a URL to a page or feed with a machine-readable list of datasets. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_list
a_1 'Version List URL',
:string,
:input_type => :url,
:placeholder => 'Version List URL',
:required => :required
q_endpointUrl 'Where is the endpoint for your API?',
:discussion_topic => :endpointUrl,
:display_on_certificate => true,
:text_as_statement => 'The API service endpoint is',
:help_text => 'Give a URL that\'s a starting point for people\'s scripts to access your API. This should be a service description document that helps the script to work out which services exist.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Endpoint URL',
:string,
:input_type => :url,
:placeholder => 'Endpoint URL',
:requirement => ['basic_11', 'standard_28']
label_basic_11 'You must <strong>provide either an API endpoint URL or a URL to its documentation</strong> so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_11'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'}
label_standard_28 'You should <strong>have a service description document or single entry point for your API</strong> so that people can access it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_28'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'}
q_dumpManagement 'How do you publish database dumps?',
:discussion_topic => :dumpManagement,
:pick => :any
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
a_current 'as a single URL that\'s regularly updated',
:help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current database dump.',
:requirement => ['standard_29']
a_template 'as consistent URLs for each release',
:help_text => 'Choose this if your database dump URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['exemplar_11']
a_list 'as a list of releases',
:help_text => 'Choose this if you have a list of database dumps on a web page or a feed (such as Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['exemplar_12']
label_standard_29 'You should <strong>have a single persistent URL to download the current dump of your database</strong> so that people can find it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_29'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_current
label_exemplar_11 'You should <strong>use a consistent pattern for database dump URLs</strong> so that people can can download each one automatically.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_11'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_template
label_exemplar_12 'You should <strong>have a document or feed with a list of available database dumps</strong> so people can create scripts to download them all',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_12'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_list
q_currentDumpUrl 'Where is the current database dump?',
:discussion_topic => :currentDumpUrl,
:display_on_certificate => true,
:text_as_statement => 'The most recent database dump is always available at',
:help_text => 'Give a URL to the most recent dump of the database. The content at this URL should change each time a new database dump is created.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_current
a_1 'Current Dump URL',
:string,
:input_type => :url,
:placeholder => 'Current Dump URL',
:required => :required
q_dumpsTemplateUrl 'What format do database dump URLs follow?',
:discussion_topic => :dumpsTemplateUrl,
:display_on_certificate => true,
:text_as_statement => 'Database dumps follow the consistent URL pattern',
:help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_template
a_1 'Dump Template URL',
:string,
:input_type => :text,
:placeholder => 'Dump Template URL',
:required => :required
q_dumpsUrl 'Where is your list of available database dumps?',
:discussion_topic => :dumpsUrl,
:display_on_certificate => true,
:text_as_statement => 'A list of database dumps is at',
:help_text => 'Give a URL to a page or feed with a machine-readable list of database dumps. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_list
a_1 'Dump List URL',
:string,
:input_type => :url,
:placeholder => 'Dump List URL',
:required => :required
q_changeFeedUrl 'Where is your feed of changes?',
:discussion_topic => :changeFeedUrl,
:display_on_certificate => true,
:text_as_statement => 'A feed of changes to this data is at',
:help_text => 'Give a URL to a page or feed that provides a machine-readable list of the previous versions of the database dumps. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A'
condition_A :q_changeFeed, '==', :a_true
a_1 'Change Feed URL',
:string,
:input_type => :url,
:placeholder => 'Change Feed URL',
:required => :required
label_group_12 'Formats',
:help_text => 'how people can work with your data',
:customer_renderer => '/partials/fieldset'
q_machineReadable 'Is this data machine-readable?',
:discussion_topic => :machineReadable,
:display_on_certificate => true,
:text_as_statement => 'This data is',
:help_text => 'People prefer data formats which are easily processed by a computer, for speed and accuracy. For example, a scanned photocopy of a spreadsheet would not be machine-readable but a CSV file would be.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable',
:requirement => ['pilot_14']
label_pilot_14 'You should <strong>provide your data in a machine-readable format</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_14'
dependency :rule => 'A'
condition_A :q_machineReadable, '==', :a_false
q_openStandard 'Is this data in a standard open format?',
:discussion_topic => :openStandard,
:display_on_certificate => true,
:text_as_statement => 'The format of this data is',
:help_text => 'Open standards are created through a fair, transparent and collaborative process. Anyone can implement them and there’s lots of support so it’s easier for you to share data with more people. For example, XML, CSV and JSON are open standards.',
:help_text_more_url => 'https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/183962/Open-Standards-Principles-FINAL.pdf',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'a standard open format',
:requirement => ['standard_30']
label_standard_30 'You should <strong>provide your data in an open standard format</strong> so that people can use widely available tools to process it more easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_30'
dependency :rule => 'A'
condition_A :q_openStandard, '==', :a_false
q_dataType 'What kind of data do you publish?',
:discussion_topic => :dataType,
:pick => :any
a_documents 'human-readable documents',
:help_text => 'Choose this if your data is meant for human consumption. For example; policy documents, white papers, reports and meeting minutes. These usually have some structure to them but are mostly text.'
a_statistical 'statistical data like counts, averages and percentages',
:help_text => 'Choose this if your data is statistical or numeric data like counts, averages or percentages. Like census results, traffic flow information or crime statistics for example.'
a_geographic 'geographic information, such as points and boundaries',
:help_text => 'Choose this if your data can be plotted on a map as points, boundaries or lines.'
a_structured 'other kinds of structured data',
:help_text => 'Choose this if your data is structured in other ways. Like event details, railway timetables, contact information or anything that can be interpreted as data, and analysed and presented in multiple ways.'
q_documentFormat 'Do your human-readable documents include formats that',
:discussion_topic => :documentFormat,
:display_on_certificate => true,
:text_as_statement => 'Documents are published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_documents
a_semantic 'describe semantic structure like HTML, Docbook or Markdown',
:text_as_statement => 'in a semantic format',
:help_text => 'These formats label structures like chapters, headings and tables that make it easy to automatically create summaries like tables of contents and glossaries. They also make it easy to apply different styles to the document so its appearance changes.',
:requirement => ['standard_31']
a_format 'describe information on formatting like OOXML or PDF',
:text_as_statement => 'in a display format',
:help_text => 'These formats emphasise appearance like fonts, colours and positioning of different elements within the page. These are good for human consumption, but aren\'t as easy for people to process automatically and change style.',
:requirement => ['pilot_15']
a_unsuitable 'aren\'t meant for documents like Excel, JSON or CSV',
:text_as_statement => 'in a format unsuitable for documents',
:help_text => 'These formats better suit tabular or structured data.'
label_standard_31 'You should <strong>publish documents in a format that exposes semantic structure</strong> so that people can display them in different styles.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_31'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_documents
condition_B :q_documentFormat, '!=', :a_semantic
label_pilot_15 'You should <strong>publish documents in a format designed specifically for them</strong> so that they\'re easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_15'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_documents
condition_B :q_documentFormat, '!=', :a_semantic
condition_C :q_documentFormat, '!=', :a_format
q_statisticalFormat 'Does your statistical data include formats that',
:discussion_topic => :statisticalFormat,
:display_on_certificate => true,
:text_as_statement => 'Statistical data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_statistical
a_statistical 'expose the structure of statistical hypercube data like <a href="http://sdmx.org/">SDMX</a> or <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a>',
:text_as_statement => 'in a statistical data format',
:help_text => 'Individual observations in hypercubes relate to a particular measure and a set of dimensions. Each observation may also be related to annotations that give extra context. Formats like <a href="http://sdmx.org/">SDMX</a> and <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a> are designed to express this underlying structure.',
:requirement => ['exemplar_13']
a_tabular 'treat statistical data as a table like CSV',
:text_as_statement => 'in a tabular data format',
:help_text => 'These formats arrange statistical data within a table of rows and columns. This lacks extra context about the underlying hypercube but is easy to process.',
:requirement => ['standard_32']
a_format 'focus on the format of tabular data like Excel',
:text_as_statement => 'in a presentation format',
:help_text => 'Spreadsheets use formatting like italic or bold text, and indentation within fields to describe its appearance and underlying structure. This styling helps people to understand the meaning of your data but makes it less suitable for computers to process.',
:requirement => ['pilot_16']
a_unsuitable 'aren\'t meant for statistical or tabular data like Word or PDF',
:text_as_statement => 'in a format unsuitable for statistical data',
:help_text => 'These formats don\'t suit statistical data because they obscure the underlying structure of the data.'
label_exemplar_13 'You should <strong>publish statistical data in a format that exposes dimensions and measures</strong> so that it\'s easy to analyse.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_13'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
label_standard_32 'You should <strong>publish tabular data in a format that exposes tables of data</strong> so that it\'s easy to analyse.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_32'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
condition_C :q_statisticalFormat, '!=', :a_tabular
label_pilot_16 'You should <strong>publish tabular data in a format designed for that purpose</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_16'
dependency :rule => 'A and (B and C and D)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
condition_C :q_statisticalFormat, '!=', :a_tabular
condition_D :q_statisticalFormat, '!=', :a_format
q_geographicFormat 'Does your geographic data include formats that',
:discussion_topic => :geographicFormat,
:display_on_certificate => true,
:text_as_statement => 'Geographic data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_geographic
a_specific 'are designed for geographic data like <a href="http://www.opengeospatial.org/standards/kml/">KML</a> or <a href="http://www.geojson.org/">GeoJSON</a>',
:text_as_statement => 'in a geographic data format',
:help_text => 'These formats describe points, lines and boundaries, and expose structures in the data which make it easier to process automatically.',
:requirement => ['exemplar_14']
a_generic 'keeps data structured like JSON, XML or CSV',
:text_as_statement => 'in a generic data format',
:help_text => 'Any format that stores normal structured data can express geographic data too, particularly if it only holds data about points.',
:requirement => ['pilot_17']
a_unsuitable 'aren\'t designed for geographic data like Word or PDF',
:text_as_statement => 'in a format unsuitable for geographic data',
:help_text => 'These formats don\'t suit geographic data because they obscure the underlying structure of the data.'
label_exemplar_14 'You should <strong>publish geographic data in a format designed that purpose</strong> so that people can use widely available tools to process it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_14'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_geographic
condition_B :q_geographicFormat, '!=', :a_specific
label_pilot_17 'You should <strong>publish geographic data as structured data</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_17'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_geographic
condition_B :q_geographicFormat, '!=', :a_specific
condition_C :q_geographicFormat, '!=', :a_generic
q_structuredFormat 'Does your structured data include formats that',
:discussion_topic => :structuredFormat,
:display_on_certificate => true,
:text_as_statement => 'Structured data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_structured
a_suitable 'are designed for structured data like JSON, XML, Turtle or CSV',
:text_as_statement => 'in a structured data format',
:help_text => 'These formats organise data into a basic structure of things which have values for a known set of properties. These formats are easy for computers to process automatically.',
:requirement => ['pilot_18']
a_unsuitable 'aren\'t designed for structured data like Word or PDF',
:text_as_statement => 'in a format unsuitable for structured data',
:help_text => 'These formats don\'t suit this kind of data because they obscure its underlying structure.'
label_pilot_18 'You should <strong>publish structured data in a format designed that purpose</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_18'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_structured
condition_B :q_structuredFormat, '!=', :a_suitable
q_identifiers 'Does your data use persistent identifiers?',
:discussion_topic => :identifiers,
:display_on_certificate => true,
:text_as_statement => 'The data includes',
:help_text => 'Data is usually about real things like schools or roads or uses a coding scheme. If data from different sources use the same persistent and unique identifier to refer to the same things, people can combine sources easily to create more useful data. Identifiers might be GUIDs, DOIs or URLs.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'persistent identifiers',
:requirement => ['standard_33']
label_standard_33 'You should <strong>use identifiers for things in your data</strong> so that they can be easily related with other data about those things.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_33'
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_false
q_resolvingIds 'Can the identifiers in your data be used to find extra information?',
:discussion_topic => :resolvingIds,
:display_on_certificate => true,
:text_as_statement => 'The persistent identifiers',
:pick => :one
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_true
a_false 'no, the identifiers can\'t be used to find extra information',
:text_as_statement => ''
a_service 'yes, there is a service that people can use to resolve the identifiers',
:text_as_statement => 'resolve using a service',
:help_text => 'Online services can be used to give people information about identifiers such as GUIDs or DOIs which can\'t be directly accessed in the way that URLs are.',
:requirement => ['standard_34']
a_resolvable 'yes, the identifiers are URLs that resolve to give information',
:text_as_statement => 'resolve because they are URLs',
:help_text => 'URLs are useful for both people and computers. People can put a URL into their browser and read more information, like <a href="http://opencorporates.com/companies/gb/08030289">companies</a> and <a href="http://data.ordnancesurvey.co.uk/doc/postcodeunit/EC2A4JE">postcodes</a>. Computers can also process this extra information using scripts to access the underlying data.',
:requirement => ['exemplar_15']
label_standard_34 'You should <strong>provide a service to resolve the identifiers you use</strong> so that people can find extra information about them.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_34'
dependency :rule => 'A and (B and C)'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '!=', :a_service
condition_C :q_resolvingIds, '!=', :a_resolvable
label_exemplar_15 'You should <strong>link to a web page of information about each of the things in your data</strong> so that people can easily find and share that information.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_15'
dependency :rule => 'A and (B)'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '!=', :a_resolvable
q_resolutionServiceURL 'Where is the service that is used to resolve the identifiers?',
:discussion_topic => :resolutionServiceURL,
:display_on_certificate => true,
:text_as_statement => 'The identifier resolution service is at',
:help_text => 'The resolution service should take an identifier as a query parameter and give back some information about the thing it identifies.'
dependency :rule => 'A and B'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '==', :a_service
a_1 'Identifier Resolution Service URL',
:string,
:input_type => :url,
:placeholder => 'Identifier Resolution Service URL',
:requirement => ['standard_35']
label_standard_35 'You should <strong>have a URL through which identifiers can be resolved</strong> so that more information about them can be found by a computer.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_35'
dependency :rule => 'A and B and C'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '==', :a_service
condition_C :q_resolutionServiceURL, '==', {:string_value => '', :answer_reference => '1'}
q_existingExternalUrls 'Is there third-party information about things in your data on the web?',
:discussion_topic => :existingExternalUrls,
:help_text => 'Sometimes other people outside your control provide URLs to the things your data is about. For example, your data might have postcodes in it that link to the Ordnance Survey website.',
:pick => :one,
:required => :exemplar
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_true
a_false 'no'
a_true 'yes'
q_reliableExternalUrls 'Is that third-party information reliable?',
:discussion_topic => :reliableExternalUrls,
:help_text => 'If a third-party provides public URLs about things in your data, they probably take steps to ensure data quality and reliability. This is a measure of how much you trust their processes to do that. Look for their open data certificate or similar hallmarks to help make your decision.',
:pick => :one,
:required => :exemplar
dependency :rule => 'A and B'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
a_false 'no'
a_true 'yes'
q_externalUrls 'Does your data use those third-party URLs?',
:discussion_topic => :externalUrls,
:display_on_certificate => true,
:text_as_statement => 'Third-party URLs are',
:help_text => 'You should use third-party URLs that resolve to information about the things your data describes. This reduces duplication and helps people combine data from different sources to make it more useful.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
condition_C :q_reliableExternalUrls, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'referenced in this data',
:requirement => ['exemplar_16']
label_exemplar_16 'You should <strong>use URLs to third-party information in your data</strong> so that it\'s easy to combine with other data that uses those URLs.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_16'
dependency :rule => 'A and B and C and D'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
condition_C :q_reliableExternalUrls, '==', :a_true
condition_D :q_externalUrls, '==', :a_false
label_group_13 'Trust',
:help_text => 'how much trust people can put in your data',
:customer_renderer => '/partials/fieldset'
q_provenance 'Do you provide machine-readable provenance for your data?',
:discussion_topic => :provenance,
:display_on_certificate => true,
:text_as_statement => 'The provenance of this data is',
:help_text => 'This about the origins of how your data was created and processed before it was published. It builds trust in the data you publish because people can trace back how it has been handled.',
:help_text_more_url => 'http://www.w3.org/TR/prov-primer/',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable',
:requirement => ['exemplar_17']
label_exemplar_17 'You should <strong>provide a machine-readable provenance trail</strong> about your data so that people can trace how it was processed.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_17'
dependency :rule => 'A'
condition_A :q_provenance, '==', :a_false
q_digitalCertificate 'Where do you describe how people can verify that data they receive comes from you?',
:discussion_topic => :digitalCertificate,
:display_on_certificate => true,
:text_as_statement => 'This data can be verified using',
:help_text => 'If you deliver important data to people they should be able to check that what they receive is the same as what you published. For example, you can digitally sign the data you publish, so people can tell if it has been tampered with.'
a_1 'Verification Process URL',
:string,
:input_type => :url,
:placeholder => 'Verification Process URL',
:requirement => ['exemplar_18']
label_exemplar_18 'You should <strong>describe how people can check that the data they receive is the same as what you published</strong> so that they can trust it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_18'
dependency :rule => 'A'
condition_A :q_digitalCertificate, '==', {:string_value => '', :answer_reference => '1'}
end
section_social 'Social Information',
:description => 'Documentation, support and services' do
label_group_15 'Documentation',
:help_text => 'how you help people understand the context and content of your data',
:customer_renderer => '/partials/fieldset'
q_documentationMetadata 'Does your data documentation include machine-readable data for:',
:discussion_topic => :documentationMetadata,
:display_on_certificate => true,
:text_as_statement => 'The documentation includes machine-readable data for',
:pick => :any
dependency :rule => 'A'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_title 'title',
:text_as_statement => 'title',
:requirement => ['standard_36']
a_description 'description',
:text_as_statement => 'description',
:requirement => ['standard_37']
a_issued 'release date',
:text_as_statement => 'release date',
:requirement => ['standard_38']
a_modified 'modification date',
:text_as_statement => 'modification date',
:requirement => ['standard_39']
a_accrualPeriodicity 'frequency of releases',
:text_as_statement => 'release frequency',
:requirement => ['standard_40']
a_identifier 'identifier',
:text_as_statement => 'identifier',
:requirement => ['standard_41']
a_landingPage 'landing page',
:text_as_statement => 'landing page',
:requirement => ['standard_42']
a_language 'language',
:text_as_statement => 'language',
:requirement => ['standard_43']
a_publisher 'publisher',
:text_as_statement => 'publisher',
:requirement => ['standard_44']
a_spatial 'spatial/geographical coverage',
:text_as_statement => 'spatial/geographical coverage',
:requirement => ['standard_45']
a_temporal 'temporal coverage',
:text_as_statement => 'temporal coverage',
:requirement => ['standard_46']
a_theme 'theme(s)',
:text_as_statement => 'theme(s)',
:requirement => ['standard_47']
a_keyword 'keyword(s) or tag(s)',
:text_as_statement => 'keyword(s) or tag(s)',
:requirement => ['standard_48']
a_distribution 'distribution(s)',
:text_as_statement => 'distribution(s)'
label_standard_36 'You should <strong>include a machine-readable data title in your documentation</strong> so that people know how to refer to it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_36'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_title
label_standard_37 'You should <strong>include a machine-readable data description in your documentation</strong> so that people know what it contains.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_37'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_description
label_standard_38 'You should <strong>include a machine-readable data release date in your documentation</strong> so that people know how timely it is.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_38'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_issued
label_standard_39 'You should <strong>include a machine-readable last modification date in your documentation</strong> so that people know they have the latest data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_39'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_modified
label_standard_40 'You should <strong>provide machine-readable metadata about how frequently you release new versions of your data</strong> so people know how often you update it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_40'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_accrualPeriodicity
label_standard_41 'You should <strong>include a canonical URL for the data in your machine-readable documentation</strong> so that people know how to access it consistently.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_41'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_identifier
label_standard_42 'You should <strong>include a canonical URL to the machine-readable documentation itself</strong> so that people know how to access to it consistently.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_42'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_landingPage
label_standard_43 'You should <strong>include the data language in your machine-readable documentation</strong> so that people who search for it will know whether they can understand it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_43'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_language
label_standard_44 'You should <strong>indicate the data publisher in your machine-readable documentation</strong> so people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_44'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_publisher
label_standard_45 'You should <strong>include the geographic coverage in your machine-readable documentation</strong> so that people understand where your data applies to.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_45'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_spatial
label_standard_46 'You should <strong>include the time period in your machine-readable documentation</strong> so that people understand when your data applies to.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_46'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_temporal
label_standard_47 'You should <strong>include the subject in your machine-readable documentation</strong> so that people know roughly what your data is about.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_47'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_theme
label_standard_48 'You should <strong>include machine-readable keywords or tags in your documentation</strong> to help people search within the data effectively.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_48'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_keyword
q_distributionMetadata 'Does your documentation include machine-readable metadata for each distribution on:',
:discussion_topic => :distributionMetadata,
:display_on_certificate => true,
:text_as_statement => 'The documentation about each distribution includes machine-readable data for',
:pick => :any
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
a_title 'title',
:text_as_statement => 'title',
:requirement => ['standard_49']
a_description 'description',
:text_as_statement => 'description',
:requirement => ['standard_50']
a_issued 'release date',
:text_as_statement => 'release date',
:requirement => ['standard_51']
a_modified 'modification date',
:text_as_statement => 'modification date',
:requirement => ['standard_52']
a_rights 'rights statement',
:text_as_statement => 'rights statement',
:requirement => ['standard_53']
a_accessURL 'URL to access the data',
:text_as_statement => 'a URL to access the data',
:help_text => 'This metadata should be used when your data isn\'t available as a download, like an API for example.'
a_downloadURL 'URL to download the dataset',
:text_as_statement => 'a URL to download the dataset'
a_byteSize 'size in bytes',
:text_as_statement => 'size in bytes'
a_mediaType 'type of download media',
:text_as_statement => 'type of download media'
label_standard_49 'You should <strong>include machine-readable titles within your documentation</strong> so people know how to refer to each data distribution.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_49'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_title
label_standard_50 'You should <strong>include machine-readable descriptions within your documentation</strong> so people know what each data distribution contains.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_50'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_description
label_standard_51 'You should <strong>include machine-readable release dates within your documentation</strong> so people know how current each distribution is.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_51'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_issued
label_standard_52 'You should <strong>include machine-readable last modification dates within your documentation</strong> so people know whether their copy of a data distribution is up-to-date.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_52'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_modified
label_standard_53 'You should <strong>include a machine-readable link to the applicable rights statement</strong> so people can find out what they can do with a data distribution.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_53'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_rights
q_technicalDocumentation 'Where is the technical documentation for the data?',
:discussion_topic => :technicalDocumentation,
:display_on_certificate => true,
:text_as_statement => 'The technical documentation for the data is at'
a_1 'Technical Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Technical Documentation URL',
:requirement => ['pilot_19']
label_pilot_19 'You should <strong>provide technical documentation for the data</strong> so that people understand how to use it.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_19'
dependency :rule => 'A'
condition_A :q_technicalDocumentation, '==', {:string_value => '', :answer_reference => '1'}
q_vocabulary 'Do the data formats use vocabularies or schemas?',
:discussion_topic => :vocabulary,
:help_text => 'Formats like CSV, JSON, XML or Turtle use custom vocabularies or schemas which say what columns or properties the data contains.',
:pick => :one,
:required => :standard
a_false 'no'
a_true 'yes'
q_schemaDocumentationUrl 'Where is documentation about your data vocabularies?',
:discussion_topic => :schemaDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The vocabularies used by this data are documented at'
dependency :rule => 'A'
condition_A :q_vocabulary, '==', :a_true
a_1 'Schema Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Schema Documentation URL',
:requirement => ['standard_54']
label_standard_54 'You should <strong>document any vocabulary you use within your data</strong> so that people know how to interpret it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_54'
dependency :rule => 'A and B'
condition_A :q_vocabulary, '==', :a_true
condition_B :q_schemaDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_codelists 'Are there any codes used in this data?',
:discussion_topic => :codelists,
:help_text => 'If your data uses codes to refer to things like geographical areas, spending categories or diseases for example, these need to be explained to people.',
:pick => :one,
:required => :standard
a_false 'no'
a_true 'yes'
q_codelistDocumentationUrl 'Where are any codes in your data documented?',
:discussion_topic => :codelistDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The codes in this data are documented at'
dependency :rule => 'A'
condition_A :q_codelists, '==', :a_true
a_1 'Codelist Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Codelist Documentation URL',
:requirement => ['standard_55']
label_standard_55 'You should <strong>document the codes used within your data</strong> so that people know how to interpret them.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_55'
dependency :rule => 'A and B'
condition_A :q_codelists, '==', :a_true
condition_B :q_codelistDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
label_group_16 'Support',
:help_text => 'how you communicate with people who use your data',
:customer_renderer => '/partials/fieldset'
q_contactUrl 'Where can people find out how to contact someone with questions about this data?',
:discussion_topic => :contactUrl,
:display_on_certificate => true,
:text_as_statement => 'Find out how to contact someone about this data at',
:help_text => 'Give a URL for a page that describes how people can contact someone if they have questions about the data.'
a_1 'Contact Documentation',
:string,
:input_type => :url,
:placeholder => 'Contact Documentation',
:requirement => ['pilot_20']
label_pilot_20 'You should <strong>provide contact information for people to send questions</strong> about your data to.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_20'
dependency :rule => 'A'
condition_A :q_contactUrl, '==', {:string_value => '', :answer_reference => '1'}
q_improvementsContact 'Where can people find out how to improve the way your data is published?',
:discussion_topic => :improvementsContact,
:display_on_certificate => true,
:text_as_statement => 'Find out how to suggest improvements to publication at'
a_1 'Improvement Suggestions URL',
:string,
:input_type => :url,
:placeholder => 'Improvement Suggestions URL',
:requirement => ['pilot_21']
label_pilot_21 'You should <strong>provide instructions about how suggest improvements</strong> to the way you publish data so you can discover what people need.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_21'
dependency :rule => 'A'
condition_A :q_improvementsContact, '==', {:string_value => '', :answer_reference => '1'}
q_dataProtectionUrl 'Where can people find out how to contact someone with questions about privacy?',
:discussion_topic => :dataProtectionUrl,
:display_on_certificate => true,
:text_as_statement => 'Find out where to send questions about privacy at'
a_1 'Confidentiality Contact Documentation',
:string,
:input_type => :url,
:placeholder => 'Confidentiality Contact Documentation',
:requirement => ['pilot_22']
label_pilot_22 'You should <strong>provide contact information for people to send questions about privacy</strong> and disclosure of personal details to.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_22'
dependency :rule => 'A'
condition_A :q_dataProtectionUrl, '==', {:string_value => '', :answer_reference => '1'}
q_socialMedia 'Do you use social media to connect with people who use your data?',
:discussion_topic => :socialMedia,
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_56']
label_standard_56 'You should <strong>use social media to reach people who use your data</strong> and discover how your data is being used',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_56'
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_false
repeater 'Account' do
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_true
q_account 'Which social media accounts can people reach you on?',
:discussion_topic => :account,
:display_on_certificate => true,
:text_as_statement => 'Contact the curator through these social media accounts',
:help_text => 'Give URLs to your social media accounts, like your Twitter or Facebook profile page.',
:required => :required
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_true
a_1 'Social Media URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Social Media URL'
end
q_forum 'Where should people discuss this dataset?',
:discussion_topic => :forum,
:display_on_certificate => true,
:text_as_statement => 'Discuss this data at',
:help_text => 'Give a URL to your forum or mailing list where people can talk about your data.'
a_1 'Forum or Mailing List URL',
:string,
:input_type => :url,
:placeholder => 'Forum or Mailing List URL',
:requirement => ['standard_57']
label_standard_57 'You should <strong>tell people where they can discuss your data</strong> and support one another.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_57'
dependency :rule => 'A'
condition_A :q_forum, '==', {:string_value => '', :answer_reference => '1'}
q_correctionReporting 'Where can people find out how to request corrections to your data?',
:discussion_topic => :correctionReporting,
:display_on_certificate => true,
:text_as_statement => 'Find out how to request data corrections at',
:help_text => 'Give a URL where people can report errors they spot in your data.'
dependency :rule => 'A'
condition_A :q_corrected, '==', :a_true
a_1 'Correction Instructions URL',
:string,
:input_type => :url,
:placeholder => 'Correction Instructions URL',
:requirement => ['standard_58']
label_standard_58 'You should <strong>provide instructions about how people can report errors</strong> in your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_58'
dependency :rule => 'A and B'
condition_A :q_corrected, '==', :a_true
condition_B :q_correctionReporting, '==', {:string_value => '', :answer_reference => '1'}
q_correctionDiscovery 'Where can people find out how to get notifications of corrections to your data?',
:discussion_topic => :correctionDiscovery,
:display_on_certificate => true,
:text_as_statement => 'Find out how to get notifications about data corrections at',
:help_text => 'Give a URL where you describe how notifications about corrections are shared with people.'
dependency :rule => 'A'
condition_A :q_corrected, '==', :a_true
a_1 'Correction Notification URL',
:string,
:input_type => :url,
:placeholder => 'Correction Notification URL',
:requirement => ['standard_59']
label_standard_59 'You should <strong>provide a mailing list or feed with updates</strong> that people can use to keep their copies of your data up-to-date.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_59'
dependency :rule => 'A and B'
condition_A :q_corrected, '==', :a_true
condition_B :q_correctionDiscovery, '==', {:string_value => '', :answer_reference => '1'}
q_engagementTeam 'Do you have anyone who actively builds a community around this data?',
:discussion_topic => :engagementTeam,
:help_text => 'A community engagement team will engage through social media, blogging, and arrange hackdays or competitions to encourage people to use the data.',
:help_text_more_url => 'http://theodi.org/guide/engaging-reusers',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['exemplar_19']
label_exemplar_19 'You should <strong>build a community of people around your data</strong> to encourage wider use of your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_19'
dependency :rule => 'A'
condition_A :q_engagementTeam, '==', :a_false
q_engagementTeamUrl 'Where is their home page?',
:discussion_topic => :engagementTeamUrl,
:display_on_certificate => true,
:text_as_statement => 'Community engagement is done by',
:required => :required
dependency :rule => 'A'
condition_A :q_engagementTeam, '==', :a_true
a_1 'Community Engagement Team Home Page URL',
:string,
:input_type => :url,
:placeholder => 'Community Engagement Team Home Page URL',
:required => :required
label_group_17 'Services',
:help_text => 'how you give people access to tools they need to work with your data',
:customer_renderer => '/partials/fieldset'
q_libraries 'Where do you list tools to work with your data?',
:discussion_topic => :libraries,
:display_on_certificate => true,
:text_as_statement => 'Tools to help use this data are listed at',
:help_text => 'Give a URL that lists the tools you know or recommend people can use when they work with your data.'
a_1 'Tool URL',
:string,
:input_type => :url,
:placeholder => 'Tool URL',
:requirement => ['exemplar_20']
label_exemplar_20 'You should <strong>provide a list of software libraries and other readily-available tools</strong> so that people can quickly get to work with your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_20'
dependency :rule => 'A'
condition_A :q_libraries, '==', {:string_value => '', :answer_reference => '1'}
end
end
| 54.451513 | 724 | 0.690873 |
b9fb5ecf465adf420f9cd2faf086a170e95147c1 | 1,840 | # frozen_string_literal: true
require_relative './orms/active_record/models'
RSpec.describe Surrealist do
describe 'nested object surrealization' do
context 'object that has self-referencing assocation to surrealize' do
it 'works' do
expect(Executive.first.build_schema.fetch(:assistant).fetch(:executive))
.to be_nil
end
end
context 'object that has self-referencing nested association to surrealize' do
it 'works' do
expect(PromKing.first.build_schema.fetch(:prom).fetch(:prom_couple).fetch(:prom_king))
.to be_nil
end
end
context 'object that has association to surrealize' do
it 'works' do
expect(Employee.first.build_schema.fetch(:manager).keys)
.to include(:name)
end
end
context 'nested collection of objects to surrealize' do
let(:subject) { Answer.first.question.build_schema }
it 'works' do
expect(subject.fetch(:answers)).to be_a Array
expect(subject.fetch(:answers)[0].fetch(:question)).to be_nil
end
end
context 'collection of objects to surrealize' do
context 'has self-referencing assocations' do
let(:subject) { Surrealist.surrealize_collection(Executive.all) }
it 'works' do
expect(subject).to match(/"executive":null/)
expect(subject).to match(/"assistant":\{.+?\}/)
end
end
context 'has associations' do
it 'works' do
expect(Surrealist.surrealize_collection(Employee.all))
.not_to include('Manager')
end
end
end
context 'parameters' do
let(:instance) { Employee.first }
it_behaves_like 'error is raised for invalid params: instance'
it_behaves_like 'error is not raised for valid params: instance'
end
end
end
| 29.206349 | 94 | 0.655435 |
1a4885f2f38d4de3a5e5e08733d48f5eaa8124dd | 1,133 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
Gem::Specification.new do |spec|
spec.name = 'aws-sdk-opsworks'
spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip
spec.summary = 'AWS SDK for Ruby - AWS OpsWorks'
spec.description = 'Official AWS Ruby gem for AWS OpsWorks. This gem is part of the AWS SDK for Ruby.'
spec.author = 'Amazon Web Services'
spec.homepage = 'http://github.com/aws/aws-sdk-ruby'
spec.license = 'Apache-2.0'
spec.email = ['[email protected]']
spec.require_paths = ['lib']
spec.files = Dir['lib/**/*.rb']
spec.metadata = {
'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-opsworks',
'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-opsworks/CHANGELOG.md'
}
spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.48.2')
spec.add_dependency('aws-sigv4', '~> 1.1')
end
| 37.766667 | 109 | 0.659312 |
797184ed105255c31dd6fd703cdd197cbba681f4 | 247 | # frozen_string_literal: true
class CreatePostReceivers < ActiveRecord::Migration[5.2]
def change
create_table :post_receivers do |t|
t.references :user, foreign_key: true
t.references :post, foreign_key: true
end
end
end
| 22.454545 | 56 | 0.724696 |
ac52ae18a49fce9179d8f55f5dd9e70c2d1e3b76 | 888 | class Scheduler
# Wait for the given file descriptor to become readable.
def wait_readable(fd)
end
# Wait for the given file descriptor to become writable.
def wait_writable(fd)
end
# Wait for the given file descriptor to match the specified events within the specified timeout.
def wait_for_single_fd(fd, events, timeout)
end
# Sleep the current task for the specified duration, or forever if not specified.
def wait_sleep(duration = nil)
end
# The Ruby virtual machine is going to enter a system level blocking operation.
def enter_blocking_region
end
# The Ruby virtual machine has completed the system level blocking operation.
def exit_blocking_region
end
# Intercept the creation of a non-blocking fiber.
def fiber(&block)
Fiber.new(blocking: false, &block)
end
# Invoked when the thread exits.
def run
# Implement event loop here.
end
end
| 24.666667 | 97 | 0.762387 |
edbf56103329142e7a8fa34c3a9532cc326541bf | 2,946 | module Watir
class IFrame < HTMLElement
#
# Move Driver context into the iframe
#
def switch_to!
locate unless located?
wd.switch!
end
#
# Returns text of iframe body.
# #body ensures context so this method does not have to
#
# @return [String]
#
def text
body.text
end
#
# Returns HTML code of iframe.
#
# @return [String]
#
def html
wd.page_source
end
#
# Delegate sending keystrokes to FramedDriver
#
def send_keys(*args)
wd.send_keys(*args)
end
#
# Executes JavaScript snippet in context of frame.
#
# @see Watir::Browser#execute_script
#
def execute_script(script, *args)
args.map! { |e| e.is_a?(Element) ? e.wd : e }
returned = driver.execute_script(script, *args)
browser.wrap_elements_in(self, returned)
end
#
# Provides access to underlying Selenium Objects as delegated by FramedDriver
#
# @return [Watir::FramedDriver]
#
def wd
super
FramedDriver.new(@element, browser)
end
#
# @api private
#
# Always relocate a FramedDriver to ensure proper context switching
#
# @return [Boolean]
#
def relocate?
true
end
private
def unknown_exception
UnknownFrameException
end
end # IFrame
class IFrameCollection < ElementCollection
end # IFrameCollection
class Frame < IFrame
end # Frame
class FrameCollection < IFrameCollection
end # FrameCollection
module Container
def frame(*args)
Frame.new(self, extract_selector(args).merge(tag_name: 'frame'))
end
def frames(*args)
FrameCollection.new(self, extract_selector(args).merge(tag_name: 'frame'))
end
end # Container
#
# @api private
#
class FramedDriver
include Exception
def initialize(element, browser)
@element = element
@browser = browser
@driver = browser.wd
end
def ==(other)
wd == other.wd
end
alias eql? ==
def send_keys(*args)
switch!
@driver.switch_to.active_element.send_keys(*args)
end
def switch!
@driver.switch_to.frame @element
@browser.default_context = false
rescue Selenium::WebDriver::Error::NoSuchFrameError => e
raise UnknownFrameException, e.message
end
def wd
@element
end
def respond_to_missing?(meth, _include_private = false)
@driver.respond_to?(meth) || @element.respond_to?(meth) || super
end
def method_missing(meth, *args, &blk)
if %i[find_element find_elements].include?(meth)
@driver.send(meth, *args, &blk)
elsif @driver.respond_to?(meth)
switch!
@driver.send(meth, *args, &blk)
elsif @element.respond_to?(meth)
@element.send(meth, *args, &blk)
else
super
end
end
end # FramedDriver
end # Watir
| 19.006452 | 81 | 0.615411 |
bf0abcc53ac5faca2c7d85e835587c23c73e6f73 | 621 | cask :v1 => 'quick-search-box' do
version '2.0.0.1447'
sha256 '3fec80343c50a5b492e140fef13bd1bc4cce835beb3952591e8b4638e5940470'
url "https://qsb-mac.googlecode.com/files/GoogleQuickSearchBox-#{version}.Release.dmg"
name 'Quick Search Box'
homepage 'https://code.google.com/p/qsb-mac/'
license :oss
tags :vendor => 'Google'
app 'Quick Search Box.app'
postflight do
system '/bin/chmod', '-R', '--', 'u+w', staged_path
end
zap :delete => '~/Library/Application Support/Google/Quick Search Box',
:rmdir => '~/Library/Application Support/Google/'
caveats do
discontinued
end
end
| 25.875 | 88 | 0.695652 |
032152b49197977fb0eeabe3c150b6c71bbed28a | 344 | class Role < ActiveRecord::Base
has_and_belongs_to_many :activists, :join_table => :activists_roles
belongs_to :resource,
:polymorphic => true
#,
#:optional => true
validates :resource_type,
:inclusion => { :in => Rolify.resource_types },
:allow_nil => true
scopify
end
| 22.933333 | 69 | 0.590116 |
6263f7ef556ad364a828c3bd0a3643f53f49df7c | 1,710 | Pod::Spec.new do |s|
# 框架的名称
s.name = "BRPickerView"
# 框架的版本号
s.version = "2.7.5"
# 框架的简单介绍
s.summary = "A custom picker view for iOS."
# 框架的详细描述(详细介绍,要比简介长)
s.description = <<-DESC
A custom picker view for iOS, Include "日期选择器,时间选择器,地址选择器,自定义字符串选择器,支持自定义样式,适配深色模式", Support the Objective - C language.
DESC
# 框架的主页
s.homepage = "https://github.com/91renb/BRPickerView"
# 证书类型
s.license = { :type => "MIT", :file => "LICENSE" }
# 作者
s.author = { "任波" => "[email protected]" }
# 社交网址
s.social_media_url = 'https://www.irenb.com'
# 框架支持的平台和版本
s.platform = :ios, "8.0"
# GitHub下载地址和版本
s.source = { :git => "https://github.com/91renb/BRPickerView.git", :tag => s.version.to_s }
s.public_header_files = 'BRPickerView/BRPickerView.h'
# 本地框架源文件的位置(包含所有文件)
#s.source_files = "BRPickerView/**/*.{h,m}"
# 一级目录(pod库中根目录所含文件)
s.source_files = "BRPickerView/BRPickerView.h"
# 二级目录(根目录是s,使用s.subspec设置子目录,这里设置子目录为ss)
s.subspec 'Base' do |ss|
ss.source_files = 'BRPickerView/Base/*.{h,m}'
# 框架包含的资源包
ss.resources = 'BRPickerView/Base/BRPickerView.bundle'
end
s.subspec 'DatePickerView' do |ss|
ss.dependency 'BRPickerView/Base'
ss.source_files = 'BRPickerView/DatePickerView/*.{h,m}'
end
s.subspec 'AddressPickerView' do |ss|
ss.dependency 'BRPickerView/Base'
ss.source_files = 'BRPickerView/AddressPickerView/*.{h,m}'
end
s.subspec 'StringPickerView' do |ss|
ss.dependency 'BRPickerView/Base'
ss.source_files = 'BRPickerView/StringPickerView/*.{h,m}'
end
# 框架要求ARC环境下使用
s.requires_arc = true
end
| 27.142857 | 139 | 0.630409 |
030430728c2ac838d13b3d5638bd1cc384841b04 | 1,936 | class EintragsController < AuthController
before_action :set_eintrag, only: [:show, :edit, :update, :destroy]
# GET /eintrags
# GET /eintrags.json
def index
@eintrags = Eintrag.all
end
# GET /eintrags/1
# GET /eintrags/1.json
def show
end
# GET /eintrags/new
def new
@eintrag = Eintrag.new
end
# GET /eintrags/1/edit
def edit
end
# POST /eintrags
# POST /eintrags.json
def create
@eintrag = Eintrag.new(eintrag_params)
respond_to do |format|
if @eintrag.save
format.html { redirect_to @eintrag, notice: 'Eintrag was successfully created.' }
format.json { render :show, status: :created, location: @eintrag }
else
format.html { render :new }
format.json { render json: @eintrag.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /eintrags/1
# PATCH/PUT /eintrags/1.json
def update
respond_to do |format|
if @eintrag.update(eintrag_params)
format.html { redirect_to @eintrag, notice: 'Eintrag was successfully updated.' }
format.json { render :show, status: :ok, location: @eintrag }
else
format.html { render :edit }
format.json { render json: @eintrag.errors, status: :unprocessable_entity }
end
end
end
# DELETE /eintrags/1
# DELETE /eintrags/1.json
def destroy
@eintrag.destroy
respond_to do |format|
format.html { redirect_to eintrags_url, notice: 'Eintrag was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_eintrag
@eintrag = Eintrag.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def eintrag_params
params.require(:eintrag).permit(:kosten_traeger_id, :duration, :date, :comment, :user_id)
end
end
| 25.813333 | 95 | 0.661674 |
ed7164e14de4fdcc9b1281a0a51c5cbc12ebfbec | 307 | class Multiclone < Formula
desc ""
homepage ""
url "https://github.com/osteele/multiclone/releases/download/v0.1.0/multiclone_0.1.0_macOS_64-bit.tar.gz"
version "0.1.0"
sha256 "108bdf0f49e5064346e98e537d9c191dfef4894cc217ba79a47ed0e462327dd6"
def install
bin.install "multiclone"
end
end
| 25.583333 | 107 | 0.765472 |
f7bbc01f66fd37ed21ee6f96bce472c7a08ce132 | 395 | module Maria
class ImagesController < ApplicationController
def new
@image = Image.new
end
def create
@image = Image.new(params[:image])
if @image.save
redirect_to image_path(@image)
else
render :new
end
end
def show
@image = Image.find(params[:id])
end
def index
@images = Image.all
end
end
end
| 14.62963 | 48 | 0.574684 |
62be8bd62ffe3167a11de0f9cf6c1a816390d4e9 | 7,218 | module ChargeBee
class Invoice < Model
class LineItem < Model
attr_accessor :id, :subscription_id, :date_from, :date_to, :unit_amount, :quantity, :amount, :pricing_model, :is_taxed, :tax_amount, :tax_rate, :discount_amount, :item_level_discount_amount, :description, :entity_description, :entity_type, :tax_exempt_reason, :entity_id, :customer_id
end
class Discount < Model
attr_accessor :amount, :description, :entity_type, :entity_id
end
class LineItemDiscount < Model
attr_accessor :line_item_id, :discount_type, :coupon_id, :discount_amount
end
class Tax < Model
attr_accessor :name, :amount, :description
end
class LineItemTax < Model
attr_accessor :line_item_id, :tax_name, :tax_rate, :is_partial_tax_applied, :is_non_compliance_tax, :taxable_amount, :tax_amount, :tax_juris_type, :tax_juris_name, :tax_juris_code, :tax_amount_in_local_currency, :local_currency_code
end
class LineItemTier < Model
attr_accessor :line_item_id, :starting_unit, :ending_unit, :quantity_used, :unit_amount
end
class LinkedPayment < Model
attr_accessor :txn_id, :applied_amount, :applied_at, :txn_status, :txn_date, :txn_amount
end
class DunningAttempt < Model
attr_accessor :attempt, :transaction_id, :dunning_type, :created_at, :txn_status, :txn_amount
end
class AppliedCredit < Model
attr_accessor :cn_id, :applied_amount, :applied_at, :cn_reason_code, :cn_create_reason_code, :cn_date, :cn_status
end
class AdjustmentCreditNote < Model
attr_accessor :cn_id, :cn_reason_code, :cn_create_reason_code, :cn_date, :cn_total, :cn_status
end
class IssuedCreditNote < Model
attr_accessor :cn_id, :cn_reason_code, :cn_create_reason_code, :cn_date, :cn_total, :cn_status
end
class LinkedOrder < Model
attr_accessor :id, :document_number, :status, :order_type, :reference_id, :fulfillment_status, :batch_id, :created_at
end
class Note < Model
attr_accessor :entity_type, :note, :entity_id
end
class ShippingAddress < Model
attr_accessor :first_name, :last_name, :email, :company, :phone, :line1, :line2, :line3, :city, :state_code, :state, :country, :zip, :validation_status
end
class BillingAddress < Model
attr_accessor :first_name, :last_name, :email, :company, :phone, :line1, :line2, :line3, :city, :state_code, :state, :country, :zip, :validation_status
end
attr_accessor :id, :po_number, :customer_id, :subscription_id, :recurring, :status, :vat_number,
:price_type, :date, :due_date, :net_term_days, :currency_code, :total, :amount_paid, :amount_adjusted,
:write_off_amount, :credits_applied, :amount_due, :paid_at, :dunning_status, :next_retry_at,
:voided_at, :resource_version, :updated_at, :sub_total, :sub_total_in_local_currency, :total_in_local_currency,
:local_currency_code, :tax, :first_invoice, :has_advance_charges, :term_finalized, :is_gifted,
:expected_payment_date, :amount_to_collect, :round_off_amount, :line_items, :discounts, :line_item_discounts,
:taxes, :line_item_taxes, :line_item_tiers, :linked_payments, :dunning_attempts, :applied_credits,
:adjustment_credit_notes, :issued_credit_notes, :linked_orders, :notes, :shipping_address, :billing_address,
:payment_owner, :void_reason_code, :deleted
# OPERATIONS
#-----------
def self.create(params={}, env=nil, headers={})
Request.send('post', uri_path("invoices"), params, env, headers)
end
def self.charge(params, env=nil, headers={})
Request.send('post', uri_path("invoices","charge"), params, env, headers)
end
def self.charge_addon(params, env=nil, headers={})
Request.send('post', uri_path("invoices","charge_addon"), params, env, headers)
end
def self.stop_dunning(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"stop_dunning"), params, env, headers)
end
def self.import_invoice(params, env=nil, headers={})
Request.send('post', uri_path("invoices","import_invoice"), params, env, headers)
end
def self.apply_payments(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"apply_payments"), params, env, headers)
end
def self.apply_credits(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"apply_credits"), params, env, headers)
end
def self.list(params={}, env=nil, headers={})
Request.send_list_request('get', uri_path("invoices"), params, env, headers)
end
def self.invoices_for_customer(id, params={}, env=nil, headers={})
Request.send('get', uri_path("customers",id.to_s,"invoices"), params, env, headers)
end
def self.invoices_for_subscription(id, params={}, env=nil, headers={})
Request.send('get', uri_path("subscriptions",id.to_s,"invoices"), params, env, headers)
end
def self.retrieve(id, env=nil, headers={})
Request.send('get', uri_path("invoices",id.to_s), {}, env, headers)
end
def self.pdf(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"pdf"), params, env, headers)
end
def self.add_charge(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"add_charge"), params, env, headers)
end
def self.add_addon_charge(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"add_addon_charge"), params, env, headers)
end
def self.close(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"close"), params, env, headers)
end
def self.collect_payment(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"collect_payment"), params, env, headers)
end
def self.record_payment(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"record_payment"), params, env, headers)
end
def self.refund(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"refund"), params, env, headers)
end
def self.record_refund(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"record_refund"), params, env, headers)
end
def self.remove_payment(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"remove_payment"), params, env, headers)
end
def self.remove_credit_note(id, params, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"remove_credit_note"), params, env, headers)
end
def self.void_invoice(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"void"), params, env, headers)
end
def self.write_off(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"write_off"), params, env, headers)
end
def self.delete(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"delete"), params, env, headers)
end
def self.update_details(id, params={}, env=nil, headers={})
Request.send('post', uri_path("invoices",id.to_s,"update_details"), params, env, headers)
end
end # ~Invoice
end # ~ChargeBee | 40.550562 | 290 | 0.708368 |
e9b3a2001b241e09daa4332086619b3542e01a40 | 2,675 | require 'fakefs/spec_helpers'
require 'spec_helper'
describe Bosh::Cli::Command::ImportCompiledPackages do
subject(:command) { described_class.new }
describe 'import compiled_packages' do
with_director
context 'when director is targeted' do
with_target
context 'when the user is logged in' do
with_logged_in_user
context 'when the tarball of compiled packages does not exist' do
it 'fails with an error' do
expect {
subject.perform('/does/not/exist.tgz')
}.to raise_error(Bosh::Cli::CliError, 'Archive does not exist')
end
end
context 'when the archive of compiled packages exists' do
include FakeFS::SpecHelpers
before { FileUtils.touch('/some-real-archive.tgz') }
before { allow(Bosh::Cli::Client::CompiledPackagesClient).to receive(:new).with(director).and_return(client) }
let(:client) { instance_double('Bosh::Cli::Client::CompiledPackagesClient') }
it 'makes the proper request' do
expect(client).to receive(:import).with('/some-real-archive.tgz')
command.perform('/some-real-archive.tgz')
end
context 'when the task errs' do
let(:some_task_id) { '1' }
context 'when the task status is :error' do
before { allow(client).to receive(:import).and_return([:error, some_task_id]) }
it 'changes the exit status to 1' do
expect {
command.perform('/some-real-archive.tgz')
}.to change { command.exit_code }.from(0).to(1)
end
end
context 'when the task status is :failed' do
before { allow(client).to receive(:import).and_return([:failed, some_task_id]) }
it 'changes the exit status to 1' do
expect {
command.perform('/some-real-archive.tgz')
}.to change { command.exit_code }.from(0).to(1)
end
end
end
context 'when the task is done' do
let(:some_task_id) { '1' }
context 'when the task status is :done' do
it 'returns exit status 0' do
allow(client).to receive(:import).and_return([:done, some_task_id])
command.perform('/some-real-archive.tgz')
expect(command.exit_code).to eq(0)
end
end
end
end
end
it_requires_logged_in_user ->(command) { command.perform(nil) }
end
it_requires_target ->(command) { command.perform(nil) }
end
end
| 33.024691 | 120 | 0.575701 |
269b84eab57b8c9b71312c58bec7cb1a0d4efc50 | 448 | require_relative '../../linux/cap/change_host_name'
module VagrantPlugins
module GuestPhoton
module Cap
class ChangeHostName
extend VagrantPlugins::GuestLinux::Cap::ChangeHostName
def self.change_name_command(name)
return <<-EOH.gsub(/^ {14}/, "")
# Set the hostname
echo '#{name}' > /etc/hostname
hostname '#{name}'
EOH
end
end
end
end
end
| 22.4 | 62 | 0.580357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.