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
|
---|---|---|---|---|---|
01e7f899792ca5e6fc11ae888738e1b6da9cd85c | 190 | module Ecommerce
class PaymentMethod < ApplicationRecord
has_many :payments
enum status: {active: 1, inactive: 2}
scope :is_active, -> { where(status: "active") }
end
end
| 17.272727 | 52 | 0.678947 |
eda5a8b4e89815bf85635dea4bf440695616dbdd | 266 | # frozen_string_literal: true
class AddIndexesOnChannlType < ActiveRecord::Migration[5.0]
disable_ddl_transaction!
def change
add_index :channels, :channel_type, algorithm: :concurrently
add_index :channels, :status, algorithm: :concurrently
end
end
| 24.181818 | 64 | 0.778195 |
38a8e8af35c8c81cbe38e8ce5295145776701216 | 7,960 | module Gitlab
module Auth
MissingPersonalTokenError = Class.new(StandardError)
REGISTRY_SCOPES = [:read_registry].freeze
# Scopes used for GitLab API access
API_SCOPES = [:api, :read_user].freeze
# Scopes used for OpenID Connect
OPENID_SCOPES = [:openid].freeze
# Default scopes for OAuth applications that don't define their own
DEFAULT_SCOPES = [:api].freeze
AVAILABLE_SCOPES = (API_SCOPES + REGISTRY_SCOPES).freeze
# Other available scopes
OPTIONAL_SCOPES = (AVAILABLE_SCOPES + OPENID_SCOPES - DEFAULT_SCOPES).freeze
class << self
prepend EE::Gitlab::Auth
include Gitlab::CurrentSettings
def find_for_git_client(login, password, project:, ip:)
raise "Must provide an IP for rate limiting" if ip.nil?
# `user_with_password_for_git` should be the last check
# because it's the most expensive, especially when LDAP
# is enabled.
result =
service_request_check(login, password, project) ||
build_access_token_check(login, password) ||
lfs_token_check(login, password) ||
oauth_access_token_check(login, password) ||
personal_access_token_check(password) ||
user_with_password_for_git(login, password) ||
Gitlab::Auth::Result.new
rate_limit!(ip, success: result.success?, login: login)
Gitlab::Auth::UniqueIpsLimiter.limit_user!(result.actor)
return result if result.success? || current_application_settings.password_authentication_enabled? || Gitlab::LDAP::Config.enabled?
# If sign-in is disabled and LDAP is not configured, recommend a
# personal access token on failed auth attempts
raise Gitlab::Auth::MissingPersonalTokenError
end
def find_with_user_password(login, password)
# Avoid resource intensive login checks if password is not provided
return unless password.present?
Gitlab::Auth::UniqueIpsLimiter.limit_user! do
user = User.by_login(login)
# If no user is found, or it's an LDAP server, try LDAP.
# LDAP users are only authenticated via LDAP
if user.nil? || user.ldap_user?
# Second chance - try LDAP authentication
return unless Gitlab::LDAP::Config.enabled?
Gitlab::LDAP::Authentication.login(login, password)
else
user if user.active? && user.valid_password?(password)
end
end
end
def rate_limit!(ip, success:, login:)
rate_limiter = Gitlab::Auth::IpRateLimiter.new(ip)
return unless rate_limiter.enabled?
if success
# Repeated login 'failures' are normal behavior for some Git clients so
# it is important to reset the ban counter once the client has proven
# they are not a 'bad guy'.
rate_limiter.reset!
else
# Register a login failure so that Rack::Attack can block the next
# request from this IP if needed.
rate_limiter.register_fail!
if rate_limiter.banned?
Rails.logger.info "IP #{ip} failed to login " \
"as #{login} but has been temporarily banned from Git auth"
end
end
end
private
def service_request_check(login, password, project)
matched_login = /(?<service>^[a-zA-Z]*-ci)-token$/.match(login)
return unless project && matched_login.present?
underscored_service = matched_login['service'].underscore
if Service.available_services_names.include?(underscored_service)
# We treat underscored_service as a trusted input because it is included
# in the Service.available_services_names whitelist.
service = project.public_send("#{underscored_service}_service") # rubocop:disable GitlabSecurity/PublicSend
if service && service.activated? && service.valid_token?(password)
Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
end
end
end
def user_with_password_for_git(login, password)
user = find_with_user_password(login, password)
return unless user
raise Gitlab::Auth::MissingPersonalTokenError if user.two_factor_enabled?
Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
end
def oauth_access_token_check(login, password)
if login == "oauth2" && password.present?
token = Doorkeeper::AccessToken.by_token(password)
if valid_oauth_token?(token)
user = User.find_by(id: token.resource_owner_id)
Gitlab::Auth::Result.new(user, nil, :oauth, full_authentication_abilities)
end
end
end
def personal_access_token_check(password)
return unless password.present?
token = PersonalAccessTokensFinder.new(state: 'active').find_by(token: password)
if token && valid_scoped_token?(token, AVAILABLE_SCOPES)
Gitlab::Auth::Result.new(token.user, nil, :personal_token, abilities_for_scope(token.scopes))
end
end
def valid_oauth_token?(token)
token && token.accessible? && valid_scoped_token?(token, [:api])
end
def valid_scoped_token?(token, scopes)
AccessTokenValidationService.new(token).include_any_scope?(scopes)
end
def abilities_for_scope(scopes)
scopes.map do |scope|
self.public_send(:"#{scope}_scope_authentication_abilities") # rubocop:disable GitlabSecurity/PublicSend
end.flatten.uniq
end
def lfs_token_check(login, password)
deploy_key_matches = login.match(/\Alfs\+deploy-key-(\d+)\z/)
actor =
if deploy_key_matches
DeployKey.find(deploy_key_matches[1])
else
User.by_login(login)
end
return unless actor
token_handler = Gitlab::LfsToken.new(actor)
authentication_abilities =
if token_handler.user?
full_authentication_abilities
else
read_authentication_abilities
end
if Devise.secure_compare(token_handler.token, password)
Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
end
end
def build_access_token_check(login, password)
return unless login == 'gitlab-ci-token'
return unless password
build = ::Ci::Build.running.find_by_token(password)
return unless build
return unless build.project.builds_enabled?
if build.user
# If user is assigned to build, use restricted credentials of user
Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
else
# Otherwise use generic CI credentials (backward compatibility)
Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
end
end
public
def build_authentication_abilities
[
:read_project,
:build_download_code,
:build_read_container_image,
:build_create_container_image
]
end
def read_authentication_abilities
[
:read_project,
:download_code,
:read_container_image
]
end
def full_authentication_abilities
read_authentication_abilities + [
:push_code,
:create_container_image,
:admin_container_image
]
end
alias_method :api_scope_authentication_abilities, :full_authentication_abilities
def read_registry_scope_authentication_abilities
[:read_container_image]
end
# The currently used auth method doesn't allow any actions for this scope
def read_user_scope_authentication_abilities
[]
end
end
end
end
| 33.586498 | 138 | 0.655402 |
7a1aa6ece617e5036788c640237f06d6640c36b1 | 1,018 | class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def create
@link = Link.find(params[:link_id])
@comment = @link.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @link, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:link_id, :body, :user_id)
end
end
| 26.789474 | 93 | 0.663065 |
0354f666ed16087c05516f3733b0d0e1d44763cb | 2,709 | class Ice < Formula
desc "Comprehensive RPC framework"
homepage "https://zeroc.com"
url "https://github.com/zeroc-ice/ice/archive/v3.7.3.tar.gz"
sha256 "7cbfac83684a7434499f165e784a7a7bb5b89140717537067d7b969eccc111eb"
revision 1
bottle do
cellar :any
sha256 "0f6f68633091f43037d3e089c7a0b1d6eae005b965b6cda36df27e126d6ceb64" => :catalina
sha256 "b1e4e7562f96c13849068d9d1b4e8e328715b18fa7cfafed5402fc9488cf274c" => :mojave
sha256 "4e43e7f8bd3b7f971f5127c9817c3109015a1826fac7aa6ab4f6f493cf5a38aa" => :high_sierra
end
depends_on "lmdb"
depends_on "mcpp"
# Build failure and code generation (slice2swift) fixes for Swift 5.2
# Can be removed in next upstream release
patch do
url "https://github.com/zeroc-ice/ice/commit/c6306e50ce3e5d48c3a0b0e3aab4129c3f430eeb.patch?full_index=1"
sha256 "09178ee9792587411df6592a4c2a6d01ea7b706cf68d0d5501c0e91d398e0c38"
end
def install
ENV.O2 # Os causes performance issues
args = [
"prefix=#{prefix}",
"V=1",
"MCPP_HOME=#{Formula["mcpp"].opt_prefix}",
"LMDB_HOME=#{Formula["lmdb"].opt_prefix}",
"CONFIGS=shared cpp11-shared xcodesdk cpp11-xcodesdk",
"PLATFORMS=all",
"SKIP=slice2confluence",
"LANGUAGES=cpp objective-c",
]
system "make", "install", *args
(libexec/"bin").mkpath
%w[slice2py slice2rb slice2js].each do |r|
mv bin/r, libexec/"bin"
end
end
def caveats
<<~EOS
slice2py, slice2js and slice2rb were installed in:
#{opt_libexec}/bin
You may wish to add this directory to your PATH.
EOS
end
test do
(testpath / "Hello.ice").write <<~EOS
module Test
{
interface Hello
{
void sayHello();
}
}
EOS
(testpath / "Test.cpp").write <<~EOS
#include <Ice/Ice.h>
#include <Hello.h>
class HelloI : public Test::Hello
{
public:
virtual void sayHello(const Ice::Current&) override {}
};
int main(int argc, char* argv[])
{
Ice::CommunicatorHolder ich(argc, argv);
auto adapter = ich->createObjectAdapterWithEndpoints("Hello", "default -h localhost -p 10000");
adapter->add(std::make_shared<HelloI>(), Ice::stringToIdentity("hello"));
adapter->activate();
return 0;
}
EOS
system "#{bin}/slice2cpp", "Hello.ice"
system ENV.cxx, "-DICE_CPP11_MAPPING", "-std=c++11", "-c", "-I#{include}", "-I.", "Hello.cpp"
system ENV.cxx, "-DICE_CPP11_MAPPING", "-std=c++11", "-c", "-I#{include}", "-I.", "Test.cpp"
system ENV.cxx, "-L#{lib}", "-o", "test", "Test.o", "Hello.o", "-lIce++11"
system "./test"
end
end
| 29.445652 | 109 | 0.641196 |
18a5d1dc616005539ebc07f1f387d0794e55b21e | 10,328 | =begin
Trulioo Ruby SDK
Gem version: 1.0.3
Trulioo OpenAPI version: v1
Generated by OpenAPI Generator version: 5.0.1
=end
require 'date'
require 'time'
module Trulioo
class Location
# House / Civic / Building number of home address
attr_accessor :building_number
# Name of building of home address
attr_accessor :building_name
# Flat/Unit/Apartment number of home address
attr_accessor :unit_number
# Street name of primary residence
attr_accessor :street_name
# Street type of primary residence (e.g. St, Rd etc)
attr_accessor :street_type
# City of home address
attr_accessor :city
# Suburb / Subdivision / Municipality of home address
attr_accessor :suburb
# County / District of home address
attr_accessor :county
# State of primary residence. US sources expect 2 characters. Australian sources expect 2 or 3 characters.
attr_accessor :state_province_code
# Country of physical address (ISO 3166-1 alpha-2)
attr_accessor :country
# ZIP Code or Postal Code of home address
attr_accessor :postal_code
# Post Office Box
attr_accessor :po_box
attr_accessor :additional_fields
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'building_number' => :'BuildingNumber',
:'building_name' => :'BuildingName',
:'unit_number' => :'UnitNumber',
:'street_name' => :'StreetName',
:'street_type' => :'StreetType',
:'city' => :'City',
:'suburb' => :'Suburb',
:'county' => :'County',
:'state_province_code' => :'StateProvinceCode',
:'country' => :'Country',
:'postal_code' => :'PostalCode',
:'po_box' => :'POBox',
:'additional_fields' => :'AdditionalFields'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'building_number' => :'String',
:'building_name' => :'String',
:'unit_number' => :'String',
:'street_name' => :'String',
:'street_type' => :'String',
:'city' => :'String',
:'suburb' => :'String',
:'county' => :'String',
:'state_province_code' => :'String',
:'country' => :'String',
:'postal_code' => :'String',
:'po_box' => :'String',
:'additional_fields' => :'LocationAdditionalFields'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Trulioo::Location` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Trulioo::Location`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'building_number')
self.building_number = attributes[:'building_number']
end
if attributes.key?(:'building_name')
self.building_name = attributes[:'building_name']
end
if attributes.key?(:'unit_number')
self.unit_number = attributes[:'unit_number']
end
if attributes.key?(:'street_name')
self.street_name = attributes[:'street_name']
end
if attributes.key?(:'street_type')
self.street_type = attributes[:'street_type']
end
if attributes.key?(:'city')
self.city = attributes[:'city']
end
if attributes.key?(:'suburb')
self.suburb = attributes[:'suburb']
end
if attributes.key?(:'county')
self.county = attributes[:'county']
end
if attributes.key?(:'state_province_code')
self.state_province_code = attributes[:'state_province_code']
end
if attributes.key?(:'country')
self.country = attributes[:'country']
end
if attributes.key?(:'postal_code')
self.postal_code = attributes[:'postal_code']
end
if attributes.key?(:'po_box')
self.po_box = attributes[:'po_box']
end
if attributes.key?(:'additional_fields')
self.additional_fields = attributes[:'additional_fields']
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 &&
building_number == o.building_number &&
building_name == o.building_name &&
unit_number == o.unit_number &&
street_name == o.street_name &&
street_type == o.street_type &&
city == o.city &&
suburb == o.suburb &&
county == o.county &&
state_province_code == o.state_province_code &&
country == o.country &&
postal_code == o.postal_code &&
po_box == o.po_box &&
additional_fields == o.additional_fields
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[building_number, building_name, unit_number, street_name, street_type, city, suburb, county, state_province_code, country, postal_code, po_box, additional_fields].hash
end
# :nocov:
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# :nocov:
# :nocov:
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif 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
end
self
end
# :nocov:
# :nocov:
# 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 :Time
Time.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
# models (e.g. Pet) or oneOf
klass = Trulioo.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# :nocov:
# :nocov:
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# :nocov:
# :nocov:
# 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
# :nocov:
# :nocov:
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# :nocov:
# :nocov:
# 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
# :nocov:
end
end
| 29.678161 | 195 | 0.611445 |
284fc1d7f11823fa98cde4623fc1a94d176798e9 | 718 | # frozen_string_literal: true
module Stupidedi
module Versions
module ThirtyForty
module SegmentDefs
s = Schema
e = ElementDefs
r = ElementReqs
FOB = s::SegmentDef.build(:FOB, "F.O.B. Related Instructions",
"To specify transportation instructions relating to shipment",
e::E146 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E309 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E352 .simple_use(r::Optional, s::RepeatCount.bounded(1)),
e::E309 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E352 .simple_use(r::Optional, s::RepeatCount.bounded(1)))
end
end
end
end
| 34.190476 | 72 | 0.630919 |
bf3c30476e31754a10b9df1eaa1a1517a070880e | 367 | # -*- encoding : utf-8 -*-
Gistub::Application.config.secret_token = ENV['GISTUB_SECRET_TOKEN'] || '9d823ec9de09d00bec258fee515a324f9499cc3d334bdd8955a4e779094cf1bf37f6c2d77ff65ef6222ab038a8b49f6e1fd81949b05ffdbaa64e5df2fc5f507b'
Gistub::Application.config.secret_key_base = ENV['GISTUB_SECRET_KEY_BASE'] || 'something like 4f9499cc3d334bdd8955a4e779094cf1bf37f6c2'
| 73.4 | 202 | 0.852861 |
8792ff4dcd0d9d47dc963955c9cdc961c274f5bb | 18,385 | require "hanami/cli/commands/generate/app"
module Hanami
# Hanami CLI
#
# @since 1.1.0
class CLI
module Commands
# @since 1.1.0
# @api private
class New < Command # rubocop:disable Metrics/ClassLength
# @since 1.1.0
# @api private
class DatabaseConfig
# @since 1.1.0
# @api private
SUPPORTED_ENGINES = {
'mysql' => { type: :sql, mri: 'mysql2', jruby: 'jdbc-mysql' },
'mysql2' => { type: :sql, mri: 'mysql2', jruby: 'jdbc-mysql' },
'postgresql' => { type: :sql, mri: 'pg', jruby: 'jdbc-postgres' },
'postgres' => { type: :sql, mri: 'pg', jruby: 'jdbc-postgres' },
'sqlite' => { type: :sql, mri: 'sqlite3', jruby: 'jdbc-sqlite3' },
'sqlite3' => { type: :sql, mri: 'sqlite3', jruby: 'jdbc-sqlite3' }
}.freeze
# @since 1.1.0
# @api private
DEFAULT_ENGINE = 'sqlite'.freeze
# @since 1.1.0
# @api private
attr_reader :engine
# @since 1.1.0
# @api private
attr_reader :name
# @since 1.1.0
# @api private
def initialize(engine, name)
@engine = engine
@name = name
unless SUPPORTED_ENGINES.key?(engine.to_s) # rubocop:disable Style/GuardClause
warn %(`#{engine}' is not a valid database engine)
exit(1)
end
end
# @since 1.1.0
# @api private
def to_hash
{
gem: gem,
uri: uri,
type: type
}
end
# @since 1.1.0
# @api private
def type
SUPPORTED_ENGINES[engine][:type]
end
# @since 1.1.0
# @api private
def sql?
type == :sql
end
# @since 1.1.0
# @api private
def sqlite?
%w[sqlite sqlite3].include?(engine)
end
private
# @since 1.1.0
# @api private
def platform
Hanami::Utils.jruby? ? :jruby : :mri
end
# @since 1.1.0
# @api private
def platform_prefix
'jdbc:'.freeze if Hanami::Utils.jruby?
end
# @since 1.1.0
# @api private
def uri
{
development: environment_uri(:development),
test: environment_uri(:test)
}
end
# @since 1.1.0
# @api private
def gem
SUPPORTED_ENGINES[engine][platform]
end
# @since 1.1.0
# @api private
def base_uri # rubocop:disable Metrics/MethodLength
case engine
when 'mysql', 'mysql2'
if Hanami::Utils.jruby?
"mysql://localhost/#{name}"
else
"mysql2://localhost/#{name}"
end
when 'postgresql', 'postgres'
"postgresql://localhost/#{name}"
when 'sqlite', 'sqlite3'
"sqlite://db/#{Shellwords.escape(name)}"
end
end
# @since 1.1.0
# @api private
def environment_uri(environment)
case engine
when 'sqlite', 'sqlite3'
"#{platform_prefix}#{base_uri}_#{environment}.sqlite"
else
"#{platform_prefix if sql?}#{base_uri}_#{environment}"
end
end
end
# @since 1.1.0
# @api private
class TestFramework
# @since 1.1.0
# @api private
RSPEC = 'rspec'.freeze
# @since 1.1.0
# @api private
MINITEST = 'minitest'.freeze
# @since 1.1.0
# @api private
VALID_FRAMEWORKS = [MINITEST, RSPEC].freeze
# @since 1.1.0
# @api private
attr_reader :framework
# @since 1.1.0
# @api private
def initialize(hanamirc, framework)
@framework = (framework || hanamirc.options.fetch(:test))
assert_framework!
end
# @since 1.1.0
# @api private
def rspec?
framework == RSPEC
end
# @since 1.1.0
# @api private
def minitest?
framework == MINITEST
end
private
# @since 1.1.0
# @api private
def assert_framework!
unless supported_framework? # rubocop:disable Style/GuardClause
warn "`#{framework}' is not a valid test framework. Please use one of: #{valid_test_frameworks.join(', ')}"
exit(1)
end
end
# @since 1.1.0
# @api private
def valid_test_frameworks
VALID_FRAMEWORKS.map { |name| "`#{name}'" }
end
# @since 1.1.0
# @api private
def supported_framework?
VALID_FRAMEWORKS.include?(framework)
end
end
# @since 1.1.0
# @api private
class TemplateEngine
# @since 1.1.0
# @api private
class UnsupportedTemplateEngine < ::StandardError
end
# @since 1.1.0
# @api private
SUPPORTED_ENGINES = %w[erb haml slim].freeze
# @since 1.1.0
# @api private
DEFAULT_ENGINE = 'erb'.freeze
# @since 1.1.0
# @api private
attr_reader :name
# @since 1.1.0
# @api private
def initialize(hanamirc, engine)
@name = (engine || hanamirc.options.fetch(:template))
assert_engine!
end
private
# @since 1.1.0
# @api private
def assert_engine!
unless supported_engine? # rubocop:disable Style/GuardClause
warn "`#{name}' is not a valid template engine. Please use one of: #{valid_template_engines.join(', ')}"
exit(1)
end
end
# @since 1.1.0
# @api private
def valid_template_engines
SUPPORTED_ENGINES.map { |name| "`#{name}'" }
end
# @since 1.1.0
# @api private
def supported_engine?
SUPPORTED_ENGINES.include?(@name.to_s)
end
end
# @since 1.1.0
# @api private
DEFAULT_APPLICATION_NAME = 'web'.freeze
# @since 1.1.0
# @api private
DEFAULT_APPLICATION_BASE_URL = '/'.freeze
# @since 1.1.0
# @api private
attr_reader :target_path
desc "Generate a new Hanami project"
argument :project, required: true, desc: "The project name"
option :database, desc: "Database (#{DatabaseConfig::SUPPORTED_ENGINES.keys.join('/')})", default: DatabaseConfig::DEFAULT_ENGINE, aliases: ["-d"]
option :application_name, desc: "App name", default: DEFAULT_APPLICATION_NAME
option :application_base_url, desc: "App base URL", default: DEFAULT_APPLICATION_BASE_URL
option :template, desc: "Template engine (#{TemplateEngine::SUPPORTED_ENGINES.join('/')})", default: TemplateEngine::DEFAULT_ENGINE
option :test, desc: "Project testing framework (#{TestFramework::VALID_FRAMEWORKS.join('/')})", default: Hanami::Hanamirc::DEFAULT_TEST_SUITE
option :hanami_head, desc: "Use Hanami HEAD (true/false)", type: :boolean, default: false
example [
"bookshelf # Basic usage",
"bookshelf --test=rspec # Setup RSpec testing framework",
"bookshelf --database=postgres # Setup Postgres database",
"bookshelf --template=slim # Setup Slim template engine",
"bookshelf --hanami-head # Use Hanami HEAD"
]
# @since 1.1.0
# @api private
#
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def call(project:, **options)
project = Utils::String.underscore(project)
database_config = DatabaseConfig.new(options[:database], project)
test_framework = TestFramework.new(hanamirc, options[:test])
template_engine = TemplateEngine.new(hanamirc, options[:template])
options[:project] = project
context = Context.new(
project: project,
database: database_config.type,
database_config_hash: database_config.to_hash,
database_config: database_config,
test_framework: test_framework,
template_engine: template_engine,
test: options.fetch(:test),
application_name: options.fetch(:application_name),
application_base_url: options.fetch(:application_base_url),
hanami_head: options.fetch(:hanami_head),
hanami_model_version: '~> 1.2',
code_reloading: code_reloading?,
hanami_version: hanami_version,
project_module: Utils::String.classify(project),
options: options
)
assert_project_name!(context)
directory = project_directory(project)
files.mkdir(directory)
Dir.chdir(directory) do
generate_application_templates(context)
generate_empty_directories(context)
generate_test_templates(context)
generate_sql_templates(context)
generate_git_templates(context)
init_git
generate_app(context)
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
private
# @since 1.1.0
# @api private
def assert_project_name!(context)
if context.project.include?(File::SEPARATOR) # rubocop:disable Style/GuardClause
raise ArgumentError.new("PROJECT must not contain #{File::SEPARATOR}.")
end
end
# @since 1.1.0
# @api private
#
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def generate_application_templates(context)
source = templates.find("hanamirc.erb")
destination = project.hanamirc(context)
generate_file(source, destination, context)
source = templates.find(".env.development.erb")
destination = project.env(context, "development")
generate_file(source, destination, context)
source = templates.find(".env.test.erb")
destination = project.env(context, "test")
generate_file(source, destination, context)
source = templates.find("README.md.erb")
destination = project.readme(context)
generate_file(source, destination, context)
source = templates.find("Gemfile.erb")
destination = project.gemfile(context)
generate_file(source, destination, context)
source = templates.find("config.ru.erb")
destination = project.config_ru(context)
generate_file(source, destination, context)
source = templates.find("config", "boot.erb")
destination = project.boot(context)
generate_file(source, destination, context)
source = templates.find("config", "environment.erb")
destination = project.environment(context)
generate_file(source, destination, context)
source = templates.find("lib", "project.erb")
destination = project.project(context)
generate_file(source, destination, context)
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def generate_empty_directories(context)
source = templates.find(".gitkeep.erb")
destination = project.keep(project.public_directory(context))
generate_file(source, destination, context)
destination = project.keep(project.initializers(context))
generate_file(source, destination, context)
destination = project.keep(project.entities(context))
generate_file(source, destination, context)
destination = project.keep(project.repositories(context))
generate_file(source, destination, context)
destination = project.keep(project.mailers(context))
generate_file(source, destination, context)
destination = project.keep(project.mailers_templates(context))
generate_file(source, destination, context)
destination = project.keep(project.entities_spec(context))
generate_file(source, destination, context)
destination = project.keep(project.repositories_spec(context))
generate_file(source, destination, context)
destination = project.keep(project.mailers_spec(context))
generate_file(source, destination, context)
destination = project.keep(project.support_spec(context))
generate_file(source, destination, context)
if context.database_config.sql? # rubocop:disable Style/ConditionalAssignment
destination = project.keep(project.migrations(context))
else
destination = project.keep(project.db(context))
end
generate_file(source, destination, context)
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
# rubocop:disable Style/IdenticalConditionalBranches
def generate_test_templates(context)
if context.test_framework.rspec?
source = templates.find("rspec", "Rakefile.erb")
destination = project.rakefile(context)
generate_file(source, destination, context)
source = templates.find("rspec", "rspec.erb")
destination = project.dotrspec(context)
generate_file(source, destination, context)
source = templates.find("rspec", "spec_helper.erb")
destination = project.spec_helper(context)
generate_file(source, destination, context)
source = templates.find("rspec", "features_helper.erb")
destination = project.features_helper(context)
generate_file(source, destination, context)
source = templates.find("rspec", "capybara.erb")
destination = project.capybara(context)
generate_file(source, destination, context)
else # minitest (default)
source = templates.find("minitest", "Rakefile.erb")
destination = project.rakefile(context)
generate_file(source, destination, context)
source = templates.find("minitest", "spec_helper.erb")
destination = project.spec_helper(context)
generate_file(source, destination, context)
source = templates.find("minitest", "features_helper.erb")
destination = project.features_helper(context)
generate_file(source, destination, context)
end
end
# rubocop:enable Style/IdenticalConditionalBranches
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# @since 1.1.0
# @api private
def generate_sql_templates(context)
return unless context.database_config.sql?
source = templates.find("schema.sql.erb")
destination = project.db_schema(context)
generate_file(source, destination, context)
end
# @since 1.1.0
# @api private
def generate_git_templates(context)
return if git_dir_present?
source = context.database_config.sqlite? ? 'gitignore_with_sqlite.erb' : 'gitignore.erb'
source = templates.find(source)
destination = project.gitignore(context)
generate_file(source, destination, context)
end
# @since 1.1.0
# @api private
def target_path
Pathname.pwd
end
# @since 1.1.0
# @api private
def generate_app(context)
Hanami::CLI::Commands::New::App.new(command_name: "generate app", out: @out, files: @files).call(app: context.application_name, application_base_url: context.application_base_url, **context.options)
end
# @since 1.1.0
# @api private
def init_git
return if git_dir_present?
say(:run, "git init . from \".\"")
system("git init #{Shellwords.escape(target)}", out: File::NULL)
end
# @since 1.1.0
# @api private
def git_dir_present?
files.directory?('.git')
end
# @since 1.1.0
# @api private
def target
Pathname.new('.')
end
# @since 1.1.0
# @api private
def hanamirc
@hanamirc ||= Hanamirc.new(Pathname.new('.'))
end
# @since 1.1.0
# @api private
def project_directory(project)
@name == '.' ? '.' : project
end
# @since 1.1.0
# @api private
def code_reloading?
!Hanami::Utils.jruby?
end
# @since 1.1.0
# @api private
def hanami_version
Hanami::Version.gem_requirement
end
# @since 1.1.0
# @api private
def generate_file(source, destination, context)
super
say(:create, destination)
end
# @since 1.1.0
# @api private
class App < Commands::Generate::App
requirements.clear
# @since 1.1.0
# @api private
def initialize(*)
super
@templates = Templates.new(self.class.superclass)
end
end
end
end
register "new", Commands::New
end
end
| 31.918403 | 208 | 0.553875 |
b92b682989d12ba1dcb1799c3d82b1b0eae3c190 | 214 | class AddRegistrantChangedAtToDomain < ActiveRecord::Migration
def change
add_column :domains, :registrant_verification_asked_at, :datetime
add_index :domains, :registrant_verification_asked_at
end
end
| 30.571429 | 69 | 0.82243 |
e8e25219772d13cb09f53fc25c7798941dedfcba | 2,041 | class Zbackup < Formula
desc "Globally-deduplicating backup tool (based on ideas in rsync)"
homepage "http://zbackup.org"
url "https://github.com/zbackup/zbackup/archive/1.4.4.tar.gz"
sha256 "efccccd2a045da91576c591968374379da1dc4ca2e3dec4d3f8f12628fa29a85"
revision 8
bottle do
cellar :any
sha256 "07ca77fddf0e9a79bb5923ace0c64a8ea0ea95ef6bb04e744f7b3f82ba0cd79f" => :mojave
sha256 "21d8cad2823234c8c3670e5fb565db3024ca7cc4632786b14f3f4ae2b7ec3f37" => :high_sierra
sha256 "0b89a926af81bb4d7270f8724f7a4e9ec0dd763669603dd480d12f5690c86d96" => :sierra
sha256 "34bbe1ac111fd38719ea48a27bcb84d5563b5b4ca2579e4b15a9ad6ae224fdcd" => :el_capitan
end
depends_on "cmake" => :build
depends_on "lzo"
depends_on "openssl"
depends_on "protobuf"
depends_on "xz" # get liblzma compression algorithm library from XZutils
# These fixes are upstream and can be removed in version 1.5+
patch do
url "https://github.com/zbackup/zbackup/commit/7e6adda6b1df9c7b955fc06be28fe6ed7d8125a2.diff?full_index=1"
sha256 "b33b3693fff6fa89b40a02c8c14f73e2e270e2c5e5f0e27ccb038b0d2fb304d4"
end
patch do
url "https://github.com/zbackup/zbackup/commit/f4ff7bd8ec63b924a49acbf3a4f9cf194148ce18.diff?full_index=1"
sha256 "060491c216a145d34a8fd3385b138630718579404e1a2ec2adea284a52699672"
end
needs :cxx11
def install
ENV.cxx11
# Avoid collision with protobuf 3.x CHECK macro
inreplace [
"backup_creator.cc",
"check.hh",
"chunk_id.cc",
"chunk_storage.cc",
"compression.cc",
"encrypted_file.cc",
"encryption.cc",
"encryption_key.cc",
"mt.cc",
"tests/bundle/test_bundle.cc",
"tests/encrypted_file/test_encrypted_file.cc",
"unbuffered_file.cc",
],
/\bCHECK\b/, "ZBCHECK"
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
system "#{bin}/zbackup", "--non-encrypted", "init", "."
system "echo test | #{bin}/zbackup --non-encrypted backup backups/test.bak"
end
end
| 32.396825 | 110 | 0.732974 |
e8d28bba1b48569914dde06cb0cdf5597746043e | 276 | # coding: utf-8
require 'yard'
YARD::Rake::YardocTask.new(:doc) do |yard|
yard.files = Dir['lib/**/*.rb']
yard.options = [
'--no-private',
'--readme', 'README.rdoc',
'--output-dir', 'doc/yardoc',
'--template-path', 'doc/yardoc_templates'
]
end
| 19.714286 | 45 | 0.565217 |
1d3eae5c89d1e8908736a722202a10570da75ee2 | 8,908 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "helper"
describe Google::Cloud::Spanner::Transaction, :batch_update, :mock_spanner do
let(:instance_id) { "my-instance-id" }
let(:database_id) { "my-database-id" }
let(:session_id) { "session123" }
let(:session_grpc) { Google::Cloud::Spanner::V1::Session.new name: session_path(instance_id, database_id, session_id) }
let(:session) { Google::Cloud::Spanner::Session.from_grpc session_grpc, spanner.service }
let(:transaction_id) { "tx789" }
let(:transaction_grpc) { Google::Cloud::Spanner::V1::Transaction.new id: transaction_id }
let(:transaction) { Google::Cloud::Spanner::Transaction.from_grpc transaction_grpc, session }
let(:tx_selector) { Google::Cloud::Spanner::V1::TransactionSelector.new id: transaction_id }
let(:default_options) { { metadata: { "google-cloud-resource-prefix" => database_path(instance_id, database_id) } } }
let(:timestamp) { Time.parse "2017-01-01 20:04:05.06 -0700" }
let(:date) { Date.parse "2017-01-02" }
let(:file) { StringIO.new "contents" }
it "can execute a single DML query" do
mock = Minitest::Mock.new
mock.expect :execute_batch_dml, batch_response_grpc, [{ session: session_grpc.name, transaction: tx_selector, statements: [statement_grpc("UPDATE users SET active = true")], seqno: 1 }, default_options]
session.service.mocked_service = mock
row_counts = transaction.batch_update do |b|
b.batch_update "UPDATE users SET active = true"
end
mock.verify
_(row_counts.count).must_equal 1
_(row_counts.first).must_equal 1
end
it "can execute a DML query with multiple statements and param types" do
mock = Minitest::Mock.new
statements = []
statements << statement_grpc("UPDATE users SET active = @active", params: Google::Protobuf::Struct.new(fields: { "active" => Google::Protobuf::Value.new(bool_value: true) }), param_types: { "active" => Google::Cloud::Spanner::V1::Type.new(code: :BOOL) })
statements << statement_grpc("UPDATE users SET age = @age", params: Google::Protobuf::Struct.new(fields: { "age" => Google::Protobuf::Value.new(string_value: "29") }), param_types: { "age" => Google::Cloud::Spanner::V1::Type.new(code: :INT64) })
statements << statement_grpc("UPDATE users SET score = @score", params: Google::Protobuf::Struct.new(fields: { "score" => Google::Protobuf::Value.new(number_value: 0.9) }), param_types: { "score" => Google::Cloud::Spanner::V1::Type.new(code: :FLOAT64) })
statements << statement_grpc("UPDATE users SET updated_at = @updated_at", params: Google::Protobuf::Struct.new(fields: { "updated_at" => Google::Protobuf::Value.new(string_value: "2017-01-02T03:04:05.060000000Z") }), param_types: { "updated_at" => Google::Cloud::Spanner::V1::Type.new(code: :TIMESTAMP) })
statements << statement_grpc("UPDATE users SET birthday = @birthday", params: Google::Protobuf::Struct.new(fields: { "birthday" => Google::Protobuf::Value.new(string_value: "2017-01-02") }), param_types: { "birthday" => Google::Cloud::Spanner::V1::Type.new(code: :DATE) })
statements << statement_grpc("UPDATE users SET name = @name", params: Google::Protobuf::Struct.new(fields: { "name" => Google::Protobuf::Value.new(string_value: "Charlie") }), param_types: { "name" => Google::Cloud::Spanner::V1::Type.new(code: :STRING) })
statements << statement_grpc("UPDATE users SET avatar = @avatar", params: Google::Protobuf::Struct.new(fields: { "avatar" => Google::Protobuf::Value.new(string_value: Base64.strict_encode64("contents")) }), param_types: { "avatar" => Google::Cloud::Spanner::V1::Type.new(code: :BYTES) })
statements << statement_grpc("UPDATE users SET project_ids = @list", params: Google::Protobuf::Struct.new(fields: { "list" => Google::Protobuf::Value.new(list_value: Google::Protobuf::ListValue.new(values: [Google::Protobuf::Value.new(string_value: "1"), Google::Protobuf::Value.new(string_value: "2"), Google::Protobuf::Value.new(string_value: "3")])) }), param_types: { "list" => Google::Cloud::Spanner::V1::Type.new(code: :ARRAY, array_element_type: Google::Cloud::Spanner::V1::Type.new(code: :INT64)) })
statements << statement_grpc("UPDATE users SET settings = @dict", params: Google::Protobuf::Struct.new(fields: { "dict" => Google::Protobuf::Value.new(list_value: Google::Protobuf::ListValue.new(values: [Google::Protobuf::Value.new(string_value: "production")])) }), param_types: { "dict" => Google::Cloud::Spanner::V1::Type.new(code: :STRUCT, struct_type: Google::Cloud::Spanner::V1::StructType.new(fields: [Google::Cloud::Spanner::V1::StructType::Field.new(name: "env", type: Google::Cloud::Spanner::V1::Type.new(code: :STRING))])) })
mock.expect :execute_batch_dml, batch_response_grpc(9), [{ session: session_grpc.name, transaction: tx_selector, statements: statements, seqno: 1 }, default_options]
session.service.mocked_service = mock
row_counts = transaction.batch_update do |b|
b.batch_update "UPDATE users SET active = @active", params: { active: true }
b.batch_update "UPDATE users SET age = @age", params: { age: 29 }
b.batch_update "UPDATE users SET score = @score", params: { score: 0.9 }
b.batch_update "UPDATE users SET updated_at = @updated_at", params: { updated_at: timestamp }
b.batch_update "UPDATE users SET birthday = @birthday", params: { birthday: date }
b.batch_update "UPDATE users SET name = @name", params: { name: "Charlie" }
b.batch_update "UPDATE users SET avatar = @avatar", params: { avatar: file }
b.batch_update "UPDATE users SET project_ids = @list", params: { list: [1,2,3] }
b.batch_update "UPDATE users SET settings = @dict", params: { dict: { env: :production } }
end
mock.verify
_(row_counts.count).must_equal 9
_(row_counts.first).must_equal 1
_(row_counts.last).must_equal 1
end
it "raises ArgumentError if no block is provided" do
err = expect do
transaction.batch_update
end.must_raise ArgumentError
_(err.message).must_equal "block is required"
end
describe "when used with execute_update" do
def results_grpc
Google::Cloud::Spanner::V1::PartialResultSet.new(
metadata: Google::Cloud::Spanner::V1::ResultSetMetadata.new(
row_type: Google::Cloud::Spanner::V1::StructType.new(
fields: []
)
),
values: [],
stats: Google::Cloud::Spanner::V1::ResultSetStats.new(
row_count_exact: 1
)
)
end
def results_enum
Array(results_grpc).to_enum
end
it "increases seqno for each request" do
mock = Minitest::Mock.new
session.service.mocked_service = mock
expect_execute_streaming_sql results_enum, session_grpc.name, "UPDATE users SET active = true", transaction: tx_selector, seqno: 1, options: default_options
statement = statement_grpc("UPDATE users SET age = @age", params: Google::Protobuf::Struct.new(fields: { "age" => Google::Protobuf::Value.new(string_value: "29") }), param_types: { "age" => Google::Cloud::Spanner::V1::Type.new(code: :INT64) })
mock.expect :execute_batch_dml, batch_response_grpc, [{ session: session_grpc.name, transaction: tx_selector, statements: [statement], seqno: 2 }, default_options]
expect_execute_streaming_sql results_enum, session_grpc.name, "UPDATE users SET active = false", transaction: tx_selector, seqno: 3, options: default_options
transaction.execute_update "UPDATE users SET active = true"
transaction.batch_update do |b|
b.batch_update "UPDATE users SET age = @age", params: { age: 29 }
end
transaction.execute_update "UPDATE users SET active = false"
mock.verify
end
end
def statement_grpc sql, params: nil, param_types: {}
Google::Cloud::Spanner::V1::ExecuteBatchDmlRequest::Statement.new \
sql: sql, params: params, param_types: param_types
end
def batch_result_sets_grpc count, row_count_exact: 1
count.times.map do
Google::Cloud::Spanner::V1::ResultSet.new(
stats: Google::Cloud::Spanner::V1::ResultSetStats.new(
row_count_exact: row_count_exact
)
)
end
end
def batch_response_grpc count = 1
Google::Cloud::Spanner::V1::ExecuteBatchDmlResponse.new(
result_sets: batch_result_sets_grpc(count),
status: Google::Rpc::Status.new(code: 0)
)
end
end
| 60.598639 | 540 | 0.700269 |
6a914c8f8318aaf2e5ec6d3e2fefd378c9dc6d87 | 1,458 | class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table(:users) do |t|
## Database authenticatable
t.string :email, null: false
t.string :encrypted_password, null: false
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
add_trackable t
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
end
def self.down
change_table(:users) do |t|
## Database authenticatable
t.remove :email
t.remove :encrypted_password
## Recoverable
t.remove :reset_password_token
t.remove :reset_password_sent_at
## Rememberable
t.remove :remember_created_at
remove_trackable t
remove_timestamps t
end
end
private
## Trackable
def add_trackable(t)
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
end
def remove_trackable(t)
t.remove :sign_in_count
t.remove :current_sign_in_at
t.remove :last_sign_in_at
t.remove :current_sign_in_ip
t.remove :last_sign_in_ip
end
def remove_timestamps(t)
t.remove :created_at
t.remove :updated_at
end
end
| 21.761194 | 57 | 0.670782 |
9174b71a6f0e1185d86a6825f5b1437d3b4e0eb2 | 711 | # Prompt https://adventofcode.com/2018/day/2
boxes = File.open("input.txt").read
boxes = boxes.split("\n").map(&:strip)
answer = "Shit."
File.readlines("input.txt").each do |box_id|
box_id = box_id.strip
tracker = Hash.new(0)
box_id.each_char do |x|
tracker[x] += 1
end
boxes.each do |box|
diff_chars_count = 0
box.length.times.each do |x|
if box[x] != box_id[x]
diff_chars_count += 1
end
end
if diff_chars_count == 1
puts "First box: #{box_id}"
puts "Second box: #{box}"
answer = (box_id.scan(/./) & box.scan(/./))
end
end
end
puts "Answer #{answer.join('')}" | 25.392857 | 55 | 0.535865 |
f8bd6096f2539345604651cae234d054891f7f6b | 17,982 | require 'fileutils'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/blank'
require 'active_support/key_generator'
require 'active_support/message_verifier'
require 'rails/engine'
module Rails
# In Rails 3.0, a Rails::Application object was introduced which is nothing more than
# an Engine but with the responsibility of coordinating the whole boot process.
#
# == Initialization
#
# Rails::Application is responsible for executing all railties and engines
# initializers. It also executes some bootstrap initializers (check
# Rails::Application::Bootstrap) and finishing initializers, after all the others
# are executed (check Rails::Application::Finisher).
#
# == Configuration
#
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
# the application object has several specific configurations, for example
# "cache_classes", "consider_all_requests_local", "filter_parameters",
# "logger" and so forth.
#
# Check Rails::Application::Configuration to see them all.
#
# == Routes
#
# The application object is also responsible for holding the routes and reloading routes
# whenever the files change in development.
#
# == Middlewares
#
# The Application is also responsible for building the middleware stack.
#
# == Booting process
#
# The application is also responsible for setting up and executing the booting
# process. From the moment you require "config/application.rb" in your app,
# the booting process goes like this:
#
# 1) require "config/boot.rb" to setup load paths
# 2) require railties and engines
# 3) Define Rails.application as "class MyApp::Application < Rails::Application"
# 4) Run config.before_configuration callbacks
# 5) Load config/environments/ENV.rb
# 6) Run config.before_initialize callbacks
# 7) Run Railtie#initializer defined by railties, engines and application.
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
# 8) Custom Railtie#initializers added by railties, engines and applications are executed
# 9) Build the middleware stack and run to_prepare callbacks
# 10) Run config.before_eager_load and eager_load! if eager_load is true
# 11) Run config.after_initialize callbacks
#
# == Multiple Applications
#
# If you decide to define multiple applications, then the first application
# that is initialized will be set to +Rails.application+, unless you override
# it with a different application.
#
# To create a new application, you can instantiate a new instance of a class
# that has already been created:
#
# class Application < Rails::Application
# end
#
# first_application = Application.new
# second_application = Application.new(config: first_application.config)
#
# In the above example, the configuration from the first application was used
# to initialize the second application. You can also use the +initialize_copy+
# on one of the applications to create a copy of the application which shares
# the configuration.
#
# If you decide to define rake tasks, runners, or initializers in an
# application other than +Rails.application+, then you must run those
# these manually.
class Application < Engine
autoload :Bootstrap, 'rails/application/bootstrap'
autoload :Configuration, 'rails/application/configuration'
autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack'
autoload :Finisher, 'rails/application/finisher'
autoload :Railties, 'rails/engine/railties'
autoload :RoutesReloader, 'rails/application/routes_reloader'
class << self
def inherited(base)
super
Rails.app_class = base
add_lib_to_load_path!(find_root(base.called_from))
end
def instance
super.run_load_hooks!
end
def create(initial_variable_values = {}, &block)
new(initial_variable_values, &block).run_load_hooks!
end
def find_root(from)
find_root_with_flag "config.ru", from, Dir.pwd
end
# Makes the +new+ method public.
#
# Note that Rails::Application inherits from Rails::Engine, which
# inherits from Rails::Railtie and the +new+ method on Rails::Railtie is
# private
public :new
end
attr_accessor :assets, :sandbox
alias_method :sandbox?, :sandbox
attr_reader :reloaders
delegate :default_url_options, :default_url_options=, to: :routes
INITIAL_VARIABLES = [:config, :railties, :routes_reloader, :reloaders,
:routes, :helpers, :app_env_config, :secrets] # :nodoc:
def initialize(initial_variable_values = {}, &block)
super()
@initialized = false
@reloaders = []
@routes_reloader = nil
@app_env_config = nil
@ordered_railties = nil
@railties = nil
@message_verifiers = {}
@ran_load_hooks = false
# are these actually used?
@initial_variable_values = initial_variable_values
@block = block
end
# Returns true if the application is initialized.
def initialized?
@initialized
end
def run_load_hooks! # :nodoc:
return self if @ran_load_hooks
@ran_load_hooks = true
ActiveSupport.run_load_hooks(:before_configuration, self)
@initial_variable_values.each do |variable_name, value|
if INITIAL_VARIABLES.include?(variable_name)
instance_variable_set("@#{variable_name}", value)
end
end
instance_eval(&@block) if @block
self
end
# Implements call according to the Rack API. It simply
# dispatches the request to the underlying middleware stack.
def call(env)
env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"]
super(env)
end
# Reload application routes regardless if they changed or not.
def reload_routes!
routes_reloader.reload!
end
# Return the application's KeyGenerator
def key_generator
# number of iterations selected based on consultation with the google security
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
@caching_key_generator ||=
if secrets.secret_key_base
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
ActiveSupport::CachingKeyGenerator.new(key_generator)
else
ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token)
end
end
# Returns a message verifier object.
#
# This verifier can be used to generate and verify signed messages in the application.
#
# It is recommended not to use the same verifier for different things, so you can get different
# verifiers passing the +verifier_name+ argument.
#
# ==== Parameters
#
# * +verifier_name+ - the name of the message verifier.
#
# ==== Examples
#
# message = Rails.application.message_verifier('sensitive_data').generate('my sensible data')
# Rails.application.message_verifier('sensitive_data').verify(message)
# # => 'my sensible data'
#
# See the +ActiveSupport::MessageVerifier+ documentation for more information.
def message_verifier(verifier_name)
@message_verifiers[verifier_name] ||= begin
secret = key_generator.generate_key(verifier_name.to_s)
ActiveSupport::MessageVerifier.new(secret)
end
end
# Convenience for loading config/foo.yml for the current Rails env.
#
# Example:
#
# # config/exception_notification.yml:
# production:
# url: http://127.0.0.1:8080
# namespace: my_app_production
# development:
# url: http://localhost:3001
# namespace: my_app_development
#
# # config/production.rb
# Rails.application.configure do
# config.middleware.use ExceptionNotifier, config_for(:exception_notification)
# end
def config_for(name)
yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
if yaml.exist?
require "yaml"
require "erb"
(YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {}
else
raise "Could not load configuration. No such file - #{yaml}"
end
rescue Psych::SyntaxError => e
raise "YAML syntax error occurred while parsing #{yaml}. " \
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
"Error: #{e.message}"
end
# Stores some of the Rails initial environment parameters which
# will be used by middlewares and engines to configure themselves.
def env_config
@app_env_config ||= begin
validate_secret_key_config!
super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.redirect_filter" => config.filter_redirect,
"action_dispatch.secret_token" => secrets.secret_token,
"action_dispatch.secret_key_base" => secrets.secret_key_base,
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
"action_dispatch.logger" => Rails.logger,
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
"action_dispatch.key_generator" => key_generator,
"action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt,
"action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
"action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
"action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt,
"action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer,
"action_dispatch.cookies_digest" => config.action_dispatch.cookies_digest
})
end
end
# If you try to define a set of rake tasks on the instance, these will get
# passed up to the rake tasks defined on the application's class.
def rake_tasks(&block)
self.class.rake_tasks(&block)
end
# Sends the initializers to the +initializer+ method defined in the
# Rails::Initializable module. Each Rails::Application class has its own
# set of initializers, as defined by the Initializable module.
def initializer(name, opts={}, &block)
self.class.initializer(name, opts, &block)
end
# Sends any runner called in the instance of a new application up
# to the +runner+ method defined in Rails::Railtie.
def runner(&blk)
self.class.runner(&blk)
end
# Sends any console called in the instance of a new application up
# to the +console+ method defined in Rails::Railtie.
def console(&blk)
self.class.console(&blk)
end
# Sends any generators called in the instance of a new application up
# to the +generators+ method defined in Rails::Railtie.
def generators(&blk)
self.class.generators(&blk)
end
# Sends the +isolate_namespace+ method up to the class method.
def isolate_namespace(mod)
self.class.isolate_namespace(mod)
end
## Rails internal API
# This method is called just after an application inherits from Rails::Application,
# allowing the developer to load classes in lib and use them during application
# configuration.
#
# class MyApplication < Rails::Application
# require "my_backend" # in lib/my_backend
# config.i18n.backend = MyBackend
# end
#
# Notice this method takes into consideration the default root path. So if you
# are changing config.root inside your application definition or having a custom
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
# you need to load files in lib/ during the application configuration as well.
def self.add_lib_to_load_path!(root) #:nodoc:
path = File.join root, 'lib'
if File.exist?(path) && !$LOAD_PATH.include?(path)
$LOAD_PATH.unshift(path)
end
end
def require_environment! #:nodoc:
environment = paths["config/environment"].existent.first
require environment if environment
end
def routes_reloader #:nodoc:
@routes_reloader ||= RoutesReloader.new
end
# Returns an array of file paths appended with a hash of
# directories-extensions suitable for ActiveSupport::FileUpdateChecker
# API.
def watchable_args #:nodoc:
files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
ActiveSupport::Dependencies.autoload_paths.each do |path|
dirs[path.to_s] = [:rb]
end
[files, dirs]
end
# Initialize the application passing the given group. By default, the
# group is :default
def initialize!(group=:default) #:nodoc:
raise "Application has been already initialized." if @initialized
run_initializers(group, self)
@initialized = true
self
end
def initializers #:nodoc:
Bootstrap.initializers_for(self) +
railties_initializers(super) +
Finisher.initializers_for(self)
end
def config #:nodoc:
@config ||= Application::Configuration.new(self.class.find_root(self.class.called_from))
end
def config=(configuration) #:nodoc:
@config = configuration
end
def secrets #:nodoc:
@secrets ||= begin
secrets = ActiveSupport::OrderedOptions.new
yaml = config.paths["config/secrets"].first
if File.exist?(yaml)
require "erb"
all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {}
env_secrets = all_secrets[Rails.env]
secrets.merge!(env_secrets.symbolize_keys) if env_secrets
end
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
secrets.secret_key_base ||= config.secret_key_base
# Fallback to config.secret_token if secrets.secret_token isn't set
secrets.secret_token ||= config.secret_token
secrets
end
end
def secrets=(secrets) #:nodoc:
@secrets = secrets
end
def to_app #:nodoc:
self
end
def helpers_paths #:nodoc:
config.helpers_paths
end
console do
require "pp"
end
console do
unless ::Kernel.private_method_defined?(:y)
if RUBY_VERSION >= '2.0'
require "psych/y"
else
module ::Kernel
def y(*objects)
puts ::Psych.dump_stream(*objects)
end
private :y
end
end
end
end
# Return an array of railties respecting the order they're loaded
# and the order specified by the +railties_order+ config.
#
# While when running initializers we need engines in reverse
# order here when copying migrations from railties we need then in the same
# order as given by +railties_order+
def migration_railties # :nodoc:
ordered_railties.flatten - [self]
end
protected
alias :build_middleware_stack :app
def run_tasks_blocks(app) #:nodoc:
railties.each { |r| r.run_tasks_blocks(app) }
super
require "rails/tasks"
task :environment do
ActiveSupport.on_load(:before_initialize) { config.eager_load = false }
require_environment!
end
end
def run_generators_blocks(app) #:nodoc:
railties.each { |r| r.run_generators_blocks(app) }
super
end
def run_runner_blocks(app) #:nodoc:
railties.each { |r| r.run_runner_blocks(app) }
super
end
def run_console_blocks(app) #:nodoc:
railties.each { |r| r.run_console_blocks(app) }
super
end
# Returns the ordered railties for this application considering railties_order.
def ordered_railties #:nodoc:
@ordered_railties ||= begin
order = config.railties_order.map do |railtie|
if railtie == :main_app
self
elsif railtie.respond_to?(:instance)
railtie.instance
else
railtie
end
end
all = (railties - order)
all.push(self) unless (all + order).include?(self)
order.push(:all) unless order.include?(:all)
index = order.index(:all)
order[index] = all
order
end
end
def railties_initializers(current) #:nodoc:
initializers = []
ordered_railties.reverse.flatten.each do |r|
if r == self
initializers += current
else
initializers += r.initializers
end
end
initializers
end
def default_middleware_stack #:nodoc:
default_stack = DefaultMiddlewareStack.new(self, config, paths)
default_stack.build_stack
end
def build_original_fullpath(env) #:nodoc:
path_info = env["PATH_INFO"]
query_string = env["QUERY_STRING"]
script_name = env["SCRIPT_NAME"]
if query_string.present?
"#{script_name}#{path_info}?#{query_string}"
else
"#{script_name}#{path_info}"
end
end
def validate_secret_key_config! #:nodoc:
if secrets.secret_key_base.blank?
ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " +
"Read the upgrade documentation to learn more about this new config option."
if secrets.secret_token.blank?
raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`"
end
end
end
end
end
| 34.186312 | 135 | 0.671449 |
1d840dd47f45bb7d9636246d71fbc47e1c04cb2e | 503 | cask 'blu-ray-player-pro' do
version '3.2.9'
sha256 '792bb782fec10576ab69d2980189bf617eca2a9e1acc4b6a65d1ee2e288876b8'
url 'https://www.macblurayplayer.com/user/download/Macgo_Mac_Bluray_Player_Pro.dmg'
appcast 'https://macblurayplayer.com/products/mac-bluray-player-pro/Appcast.xml',
checkpoint: '5a2f9b1e9b0a7c2f202385a752949a945d8c3884692b5432b5534fb599ba6aa9'
name 'Macgo Mac Blu-ray Player Pro'
homepage 'https://www.macblurayplayer.com/'
app 'Blu-ray Player Pro.app'
end
| 38.692308 | 88 | 0.789264 |
212b3e05466bd9f7a2c4d5a2b8edf468c29434c6 | 862 | # 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
# Shared Smoke Test Definitions
Given(/I create a client in region '(.*?)'/) do |region|
@regional_client = Aws::ApplicationDiscoveryService::Client.new(region: region)
end
When(/I call the operation '(.*?)' with params:/) do |operation, params|
opts = JSON.parse(params, symbolize_names: true)
begin
@regional_client.send(operation.to_sym, opts)
@operation_raised_error = false
rescue StandardError
@operation_raised_error = true
end
end
Then(/I expect an error was raised/) do
expect(@operation_raised_error).to be_truthy
end
Then(/I expect an error was not raised/) do
expect(@operation_raised_error).not_to be_truthy
end
| 28.733333 | 81 | 0.75058 |
62d8cf72912b7b68ededa8a5392bad393b6eaad8 | 4,818 | require 'rails_helper'
RSpec.describe PrivacyNotification, type: :model do
it "has a valid factory" do
expect(FactoryBot.build(:privacy_notification)).to be_valid
end
describe "#petitions.sample" do
let(:subject) { privacy_notification.petitions.sample }
let(:ignore_petitions_before) { 1.year.ago }
let(:privacy_notification) do
FactoryBot.create(:privacy_notification, signature: signature)
end
context "validated signature" do
let(:signature) do
FactoryBot.create(:validated_signature)
end
Petition::MODERATED_STATES.each do |state|
context "petition #{state}" do
context "petition created before ignore_petitions_before date" do
let!(:petition) do
FactoryBot.create(
"#{state}_petition",
created_at: ignore_petitions_before - 1.day,
signatures: [signature]
)
end
it "does not include petition" do
expect(subject).not_to include(petition)
end
end
context "petition created after ignore_petitions_before date" do
let!(:petition) do
FactoryBot.create(
"#{state}_petition",
created_at: ignore_petitions_before + 1.day,
signatures: [signature]
)
end
it "does include petition" do
expect(subject).to include(petition)
end
end
end
end
(Petition::STATES - Petition::MODERATED_STATES).each do |state|
context "petition #{state} and created after ignore_petitions_before date" do
let!(:petition) do
FactoryBot.create(
"#{state}_petition",
created_at: ignore_petitions_before + 1.day,
signatures: [signature]
)
end
it "does not include petition" do
expect(subject).not_to include(petition)
end
end
end
end
(Signature::STATES - [Signature::VALIDATED_STATE]).each do |state|
context "signature #{state}, petition moderated and created after ignore_petitions_before date" do
let(:signature) do
FactoryBot.create("#{state}_signature")
end
let!(:petition) do
FactoryBot.create(
:open_petition,
created_at: ignore_petitions_before + 1.day,
signatures: [signature]
)
end
it "does not include petition" do
expect(subject).not_to include(petition)
end
end
end
context "more than 5 petitions" do
let(:privacy_notification) do
FactoryBot.create(
:privacy_notification,
id: "6613a3fd-c2c4-5bc2-a6de-3dc0b2527dd6"
)
end
let!(:petitions) do
6.times.map do |n|
petition = FactoryBot.create(
:open_petition,
created_at: ignore_petitions_before + (6 - n).days
)
petition.tap do |petition|
FactoryBot.create(
:validated_signature,
email: "[email protected]",
petition: petition
)
end
end
end
it "only returns the 5 most recent petitions" do
expect(subject).to eq(petitions.first(5))
end
end
end
describe "#petitions.remaining_count" do
let(:subject) { privacy_notification.petitions.remaining_count }
context "more than 5 petitions" do
let(:privacy_notification) do
FactoryBot.create(
:privacy_notification,
id: "6613a3fd-c2c4-5bc2-a6de-3dc0b2527dd6"
)
end
let!(:petitions) do
6.times.map do
petition = FactoryBot.create(:open_petition)
petition.tap do |petition|
FactoryBot.create(
:validated_signature,
email: "[email protected]",
petition: petition
)
end
end
end
it "returns the number of remaining petitions" do
expect(subject).to eq(1)
end
end
context "less than 5 petitions" do
let(:privacy_notification) do
FactoryBot.create(
:privacy_notification,
id: "6613a3fd-c2c4-5bc2-a6de-3dc0b2527dd6"
)
end
let!(:petitions) do
3.times.map do
petition = FactoryBot.create(:open_petition)
petition.tap do |petition|
FactoryBot.create(
:validated_signature,
email: "[email protected]",
petition: petition
)
end
end
end
it "returns zero" do
expect(subject).to eq(0)
end
end
end
end
| 26.916201 | 104 | 0.565172 |
033cf4983dd7208f4797196e58ad885cbe93d1db | 519 | module GlobalConstant
class ClientToken < GlobalConstant::Base
class << self
def not_deployed
'notDeployed'
end
def deployment_started
'deploymentStarted'
end
def deployment_completed
'deploymentCompleted'
end
def deployment_failed
'deploymentFailed'
end
def bt_to_sc_min
0.00001
end
def bt_to_sc_step
0.00001
end
def bt_to_sc_max
100000
end
end
end
end
| 12.658537 | 42 | 0.576108 |
1c48f0d64e2834a4feddfb02bd6527080e042d94 | 1,806 | #
# Be sure to run `pod lib lint RTRootNavigationController_Swift.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'RTRootNavigationController_Swift'
s.version = '0.1.0'
s.summary = 'Transparently make every view controller has its own navigation bar'
# 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/CharmingZzz/RTRootNavigationController_Swift'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '[email protected]' => '[email protected]' }
s.source = { :git => 'https://github.com/CharmingZzz/RTRootNavigationController_Swift.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'RTRootNavigationController_Swift/Classes/**/*.{swift}'
# s.resource_bundles = {
# 'RTRootNavigationController_Swift' => ['RTRootNavigationController_Swift/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 42 | 128 | 0.674972 |
390bc6f130eada28f5ca0188698555350e3ed311 | 1,497 | require 'rdf'
require 'rdf/reasoner/extensions'
module RDF
##
# RDFS/OWL reasonsing for RDF.rb.
#
# @see https://www.w3.org/TR/2013/REC-sparql11-entailment-20130321/
# @author [Gregg Kellogg](https://greggkellogg.net/)
module Reasoner
require 'rdf/reasoner/format'
autoload :OWL, 'rdf/reasoner/owl'
autoload :RDFS, 'rdf/reasoner/rdfs'
autoload :Schema, 'rdf/reasoner/schema'
autoload :VERSION, 'rdf/reasoner/version'
# See https://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
#
#
ISO_8601 = %r(^
# Year
([\+-]?\d{4}(?!\d{2}\b))
# Month
((-?)((0[1-9]|1[0-2])
(\3([12]\d|0[1-9]|3[01]))?
| W([0-4]\d|5[0-2])(-?[1-7])?
| (00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))
([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)
([\.,]\d+(?!:))?)?
(\17[0-5]\d([\.,]\d+)?)?
([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?
)?
)?
$)x.freeze
##
# Add entailment support for the specified regime
#
# @param [Array<:owl, :rdfs, :schema>] regime
def apply(*regime)
regime.each {|r| require "rdf/reasoner/#{r.to_s.downcase}"}
end
module_function :apply
##
# Add all entailment regimes
def apply_all
apply(*%w(rdfs owl schema))
end
module_function :apply_all
##
# A reasoner error
class Error < RuntimeError; end
end
end
| 26.263158 | 97 | 0.514362 |
1d77d2058ed73a21a118a53f4f847709267be617 | 2,673 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::RecoveryServicesBackup::Mgmt::V2019_05_13
module Models
#
# Generic backup copy.
#
class GenericRecoveryPoint < RecoveryPoint
include MsRestAzure
def initialize
@objectType = "GenericRecoveryPoint"
end
attr_accessor :objectType
# @return [String] Friendly name of the backup copy.
attr_accessor :friendly_name
# @return [String] Type of the backup copy.
attr_accessor :recovery_point_type
# @return [DateTime] Time at which this backup copy was created.
attr_accessor :recovery_point_time
# @return [String] Additional information associated with this backup
# copy.
attr_accessor :recovery_point_additional_info
#
# Mapper for GenericRecoveryPoint class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'GenericRecoveryPoint',
type: {
name: 'Composite',
class_name: 'GenericRecoveryPoint',
model_properties: {
objectType: {
client_side_validation: true,
required: true,
serialized_name: 'objectType',
type: {
name: 'String'
}
},
friendly_name: {
client_side_validation: true,
required: false,
serialized_name: 'friendlyName',
type: {
name: 'String'
}
},
recovery_point_type: {
client_side_validation: true,
required: false,
serialized_name: 'recoveryPointType',
type: {
name: 'String'
}
},
recovery_point_time: {
client_side_validation: true,
required: false,
serialized_name: 'recoveryPointTime',
type: {
name: 'DateTime'
}
},
recovery_point_additional_info: {
client_side_validation: true,
required: false,
serialized_name: 'recoveryPointAdditionalInfo',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.136842 | 75 | 0.521511 |
e81977169ffaf4d0837a56e2ea0efb0eecc2a96f | 8,774 | #--
# Copyright 2006, 2007 by Chad Fowler, Rich Kilmer, Jim Weirich, Eric Hodel
# and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
# Make sure rubygems isn't already loaded.
if ENV['RUBYOPT'] and defined? Gem then
ENV.delete 'RUBYOPT'
require 'rbconfig'
config = defined?(RbConfig) ? RbConfig : Config
ruby = File.join config::CONFIG['bindir'], config::CONFIG['ruby_install_name']
ruby << config::CONFIG['EXEEXT']
exec(ruby, 'setup.rb', *ARGV)
end
$:.unshift 'lib'
require 'rubygems'
require 'getoptlong'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--prefix', GetoptLong::REQUIRED_ARGUMENT ],
[ '--no-format-executable', GetoptLong::NO_ARGUMENT ],
[ '--no-rdoc', GetoptLong::NO_ARGUMENT ],
[ '--no-ri', GetoptLong::NO_ARGUMENT ],
[ '--vendor', GetoptLong::NO_ARGUMENT ],
[ '--destdir', GetoptLong::REQUIRED_ARGUMENT ]
)
prefix = ''
format_executable = true
rdoc = true
ri = true
site_or_vendor = :sitelibdir
install_destdir = ''
opts.each do | opt, arg |
case opt
when '--help'
puts <<HELP
ruby setup.rb [options]:
RubyGems will install the gem command with a name matching ruby's
prefix and suffix. If ruby was installed as `ruby18`, gem will be
installed as `gem18`.
By default, this RubyGems will install gem as:
#{Gem.default_exec_format % 'gem'}
Options:
--help Print this message
--prefix=DIR Prefix path for installing RubyGems
Will not affect gem repository location
--no-format-executable Force installation as `gem`
--no-rdoc Don't build RDoc for RubyGems
--no-ri Don't build ri for RubyGems
--vendor Install into vendorlibdir not sitelibdir
(Requires Ruby 1.8.7)
--destdir Root directory to install rubygems into
Used mainly for packaging RubyGems
HELP
exit 0
when '--no-rdoc'
rdoc = false
when '--no-ri'
ri = false
when '--no-format-executable'
format_executable = false
when '--prefix'
prefix = File.expand_path(arg)
when '--vendor'
vendor_dir_version = Gem::Version::Requirement.create('>= 1.8.7')
unless vendor_dir_version.satisfied_by? Gem.ruby_version then
abort "To use --vendor you need ruby #{vendor_dir_version}, current #{Gem.ruby_version}"
end
site_or_vendor = :vendorlibdir
when '--destdir'
install_destdir = File.expand_path(arg)
end
end
require 'fileutils'
require 'rbconfig'
require 'tmpdir'
require 'pathname'
unless install_destdir.empty? then
default_dir = Pathname.new(Gem.default_dir)
top_dir = Pathname.new(RbConfig::TOPDIR)
ENV['GEM_HOME'] ||= File.join(install_destdir,
default_dir.relative_path_from(top_dir))
end
include FileUtils::Verbose
# check ruby version
required_version = Gem::Version::Requirement.create("> 1.8.3")
unless required_version.satisfied_by? Gem.ruby_version then
abort "Expected Ruby version #{required_version}, was #{Gem.ruby_version}"
end
# install stuff
lib_dir = nil
bin_dir = nil
if prefix.empty?
lib_dir = Gem::ConfigMap[site_or_vendor]
bin_dir = Gem::ConfigMap[:bindir]
else
# Apple installed RubyGems into libdir, and RubyGems <= 1.1.0 gets confused
# about installation location, so switch back to sitelibdir/vendorlibdir.
if defined?(APPLE_GEM_HOME) and
# just in case Apple and RubyGems don't get this patched up proper.
(prefix == Gem::ConfigMap[:libdir] or
# this one is important
prefix == File.join(Gem::ConfigMap[:libdir], 'ruby')) then
lib_dir = Gem::ConfigMap[site_or_vendor]
bin_dir = Gem::ConfigMap[:bindir]
else
lib_dir = File.join prefix, 'lib'
bin_dir = File.join prefix, 'bin'
end
end
unless install_destdir.empty?
top_dir = Pathname.new(RbConfig::TOPDIR)
lib_dir_p = Pathname.new(lib_dir)
bin_dir_p = Pathname.new(bin_dir)
lib_dir = File.join install_destdir, lib_dir_p.relative_path_from(top_dir)
bin_dir = File.join install_destdir, bin_dir_p.relative_path_from(top_dir)
end
mkdir_p lib_dir
mkdir_p bin_dir
Dir.chdir 'lib' do
lib_files = Dir[File.join('**', '*rb')]
lib_files.each do |lib_file|
dest_file = File.join lib_dir, lib_file
dest_dir = File.dirname dest_file
mkdir_p dest_dir unless File.directory? dest_dir
install lib_file, dest_file, :mode => 0644
end
end
bin_file_names = []
Dir.chdir 'bin' do
bin_files = Dir['*']
bin_files.delete 'update_rubygems'
bin_files.each do |bin_file|
bin_file_formatted = if format_executable then
Gem.default_exec_format % bin_file
else
bin_file
end
dest_file = File.join bin_dir, bin_file_formatted
bin_tmp_file = File.join Dir.tmpdir, bin_file
begin
cp bin_file, bin_tmp_file
bin = File.readlines bin_tmp_file
bin[0] = "#!#{Gem.ruby}\n"
File.open bin_tmp_file, 'w' do |fp|
fp.puts bin.join
end
install bin_tmp_file, dest_file, :mode => 0755
bin_file_names << dest_file
ensure
rm bin_tmp_file
end
next unless Gem.win_platform?
begin
bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
File.open bin_cmd_file, 'w' do |file|
file.puts <<-TEXT
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"#{File.basename(Gem.ruby)}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"#{File.basename(Gem.ruby)}" "%~dpn0" %*
TEXT
end
install bin_cmd_file, "#{dest_file}.bat", :mode => 0755
ensure
rm bin_cmd_file
end
end
end
# Replace old bin files with ones that abort.
old_bin_files = {
'gem_mirror' => 'gem mirror',
'gem_server' => 'gem server',
'gemlock' => 'gem lock',
'gemri' => 'ri',
'gemwhich' => 'gem which',
'index_gem_repository.rb' => 'gem generate_index',
}
old_bin_files.each do |old_bin_file, new_name|
old_bin_path = File.join bin_dir, old_bin_file
next unless File.exist? old_bin_path
deprecation_message = "`#{old_bin_file}` has been deprecated. Use `#{new_name}` instead."
File.open old_bin_path, 'w' do |fp|
fp.write <<-EOF
#!#{Gem.ruby}
abort "#{deprecation_message}"
EOF
end
next unless Gem.win_platform?
File.open "#{old_bin_path}.bat", 'w' do |fp|
fp.puts %{@ECHO.#{deprecation_message}}
end
end
# Remove source caches
if install_destdir.empty?
require 'rubygems/source_info_cache'
user_cache_file = File.join(install_destdir,
Gem::SourceInfoCache.user_cache_file)
system_cache_file = File.join(install_destdir,
Gem::SourceInfoCache.system_cache_file)
rm_f user_cache_file if File.writable? File.dirname(user_cache_file)
rm_f system_cache_file if File.writable? File.dirname(system_cache_file)
end
# install RDoc
gem_doc_dir = File.join Gem.dir, 'doc'
rubygems_name = "rubygems-#{Gem::RubyGemsVersion}"
rubygems_doc_dir = File.join gem_doc_dir, rubygems_name
if File.writable? gem_doc_dir and
(not File.exist? rubygems_doc_dir or
File.writable? rubygems_doc_dir) then
puts "Removing old RubyGems RDoc and ri"
Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
rm_rf dir
end
def run_rdoc(*args)
begin
gem 'rdoc'
rescue Gem::LoadError
end
require 'rdoc/rdoc'
args << '--quiet'
args << '--main' << 'README'
args << '.' << 'README' << 'LICENSE.txt' << 'GPL.txt'
r = RDoc::RDoc.new
r.document args
end
if ri then
ri_dir = File.join rubygems_doc_dir, 'ri'
puts "Installing #{rubygems_name} ri into #{ri_dir}"
run_rdoc '--ri', '--op', ri_dir
end
if rdoc then
rdoc_dir = File.join rubygems_doc_dir, 'rdoc'
puts "Installing #{rubygems_name} rdoc into #{rdoc_dir}"
run_rdoc '--op', rdoc_dir
end
else
puts "Skipping RDoc generation, #{gem_doc_dir} not writable"
puts "Set the GEM_HOME environment variable if you want RDoc generated"
end
puts
puts "-" * 78
puts
release_notes = File.join File.dirname(__FILE__), 'doc', 'release_notes',
"rel_#{Gem::RubyGemsVersion.gsub '.', '_'}.rdoc"
if File.exist? release_notes then
puts File.read(release_notes)
else
puts "Oh-no! Unable to find release notes in:\n\t#{release_notes}"
end
puts
puts "-" * 78
puts
puts "RubyGems installed the following executables:"
puts bin_file_names.map { |name| "\t#{name}\n" }
puts
puts "If `gem` was installed by a previous RubyGems installation, you may need"
puts "to remove it by hand."
puts
| 26.191045 | 94 | 0.656143 |
d50a21bce5761f203571eaf735da5db7118878d7 | 4,985 | class NationalProject < ActiveRecord::Base
self.inheritance_column = nil # иначе колонка type используется для
# single table inheritance т.е наследования сущностей, хранящихся в одной таблице
acts_as_journalized
has_many :projects, foreign_key: "national_project_id"
has_many :projects_federal, foreign_key: "federal_project_id", class_name: "Project"
has_many :agreements, foreign_key: 'national_project_id'
# bbm( исправил следующую строку т.к. по-моему она не должна была работать
has_many :agreements_federal, foreign_key: 'federal_project_id'
# )
has_many :national_work_package_quarterly_targets, -> { where(type: 'National') }, foreign_key: 'national_project_id', class_name: "WorkPackageQuarterlyTarget"
has_many :national_plan_fact_yearly_target_values, -> { where(type: 'National') }, foreign_key: 'national_project_id', class_name: "PlanFactYearlyTargetValue"
has_many :national_plan_quarterly_target_values, -> { where(type: 'National') }, foreign_key: 'national_project_id', class_name: "PlanQuarterlyTargetValue"
has_many :national_plan_fact_quarterly_target_values, -> { where(type: 'National') }, foreign_key: 'national_project_id', class_name: "PlanFactQuarterlyTargetValue"
has_many :federal_work_package_quarterly_targets, -> { where(type: 'Federal') }, foreign_key: 'federal_project_id', class_name: "WorkPackageQuarterlyTarget"
has_many :federal_plan_fact_yearly_target_values, -> { where(type: 'Federal') }, foreign_key: 'federal_project_id', class_name: "PlanFactYearlyTargetValue"
has_many :federal_plan_quarterly_target_values, -> { where(type: 'Federal') }, foreign_key: 'federal_project_id', class_name: "PlanQuarterlyTargetValue"
has_many :federal_plan_fact_quarterly_target_values, -> { where(type: 'Federal') }, foreign_key: 'federal_project_id', class_name: "PlanFactQuarterlyTargetValue"
def to_s
name
end
def self.visible_federal_projects(current_user)
slq = <<-SQL
select distinct np.*
from national_projects as np
inner join(
select project_id, national_project_id, federal_project_id
from members as m
inner join projects as p
on p.id = m.project_id
where user_id = ?
) as mu
on (np.id = mu.federal_project_id and np.parent_id = mu.national_project_id)
SQL
nps = NationalProject.find_by_sql([slq, current_user.id])
nps
end
def self.visible_national_projects(current_user)
slq = <<~SQL
select distinct np.*
from national_projects as np
inner join(
select DISTINCT national_project_id
from members as m
inner join projects as p
on p.id = m.project_id
where user_id = ?
) as mu
on (np.id = mu.national_project_id);
SQL
nps = NationalProject.find_by_sql([slq, current_user.id])
nps
end
def self.visible_national_federal_projects(current_user)
exclude_status_id = Project::STATUS_ARCHIVED
slq = <<~SQL
select distinct np.*
from national_projects as np
inner join(
select status, project_id, national_project_id, federal_project_id
from members as m
inner join projects as p
on p.id = m.project_id
where user_id = ?
) as mu
on ((np.id = mu.federal_project_id and np.parent_id = mu.national_project_id) or (np.id = mu.national_project_id))
WHERE status <> ?
order by np.id
SQL
nps = NationalProject.find_by_sql([slq, current_user.id, exclude_status_id])
nps
end
def self.visible_national_projects_with_problems(current_user)
exclude_status_id = Project::STATUS_ARCHIVED
slq = <<~SQL
select distinct np.*
from national_projects as np
inner join(
select DISTINCT status, project_id, national_project_id, federal_project_id
from members as m
inner join projects as p
on p.id = m.project_id
where m.user_id = ? AND p.status <> ?
) as mu
on ((np.id = mu.federal_project_id and np.parent_id = mu.national_project_id) or (np.id = mu.national_project_id))
left join v_project_risk_on_work_packages_stat as vprowps
on ((np.id = vprowps.national_project_id or np.id = vprowps.federal_project_id) AND mu.project_id = vprowps.project_id)
where (vprowps.type = 'created_problem' or vprowps.type = 'created_risk')
order by np.id;
SQL
nps = NationalProject.find_by_sql([slq, current_user.id, exclude_status_id])
nps
end
def self.national_projects
NationalProject.where(type: ['National', 'Default'])
end
def self.federal_projects
NationalProject.where(type: 'Federal')
end
def self.default_project
NationalProject.find_by(type: 'Default').id
end
end
| 43.72807 | 166 | 0.687061 |
d5cbfad8ed1b4ae39f43178aeb665135b47aae57 | 46 | module HashExtensions
VERSION = "0.1.0"
end
| 11.5 | 21 | 0.717391 |
6aab22611b3537fe4362521aad03cfb73d32d065 | 5,338 | module ActiveRecord
class Base
class ConnectionSpecification #:nodoc:
attr_reader :config, :adapter_method
def initialize (config, adapter_method)
@config, @adapter_method = config, adapter_method
end
end
##
# :singleton-method:
# The connection handler
class_attribute :connection_handler, :instance_writer => false
self.connection_handler = ConnectionAdapters::ConnectionHandler.new
# Returns the connection currently associated with the class. This can
# also be used to "borrow" the connection to do database work that isn't
# easily done without going straight to SQL.
def connection
self.class.connection
end
# Establishes the connection to the database. Accepts a hash as input where
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
# example for regular databases (MySQL, Postgresql, etc):
#
# ActiveRecord::Base.establish_connection(
# :adapter => "mysql",
# :host => "localhost",
# :username => "myuser",
# :password => "mypass",
# :database => "somedatabase"
# )
#
# Example for SQLite database:
#
# ActiveRecord::Base.establish_connection(
# :adapter => "sqlite",
# :database => "path/to/dbfile"
# )
#
# Also accepts keys as strings (for parsing from YAML for example):
#
# ActiveRecord::Base.establish_connection(
# "adapter" => "sqlite",
# "database" => "path/to/dbfile"
# )
#
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
# may be returned on an error.
def self.establish_connection(spec = nil)
case spec
when nil
raise AdapterNotSpecified unless defined? RAILS_ENV
establish_connection(RAILS_ENV)
when ConnectionSpecification
self.connection_handler.establish_connection(name, spec)
when Symbol, String
if configuration = configurations[spec.to_s]
establish_connection(configuration)
else
raise AdapterNotSpecified, "#{spec} database is not configured"
end
else
spec = spec.symbolize_keys
unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end
begin
require 'rubygems'
gem "activerecord-#{spec[:adapter]}-adapter"
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
rescue LoadError
begin
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
rescue LoadError
raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{$!})"
end
ensure
require 'active_record/ext/mysql2' if spec[:adapter] == 'mysql2'
end
adapter_method = "#{spec[:adapter]}_connection"
if !respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
end
remove_connection
establish_connection(ConnectionSpecification.new(spec, adapter_method))
end
end
class << self
# Deprecated and no longer has any effect.
def allow_concurrency
ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_concurrency has been deprecated and no longer has any effect. Please remove all references to allow_concurrency.")
end
# Deprecated and no longer has any effect.
def allow_concurrency=(flag)
ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_concurrency= has been deprecated and no longer has any effect. Please remove all references to allow_concurrency=.")
end
# Deprecated and no longer has any effect.
def verification_timeout
ActiveSupport::Deprecation.warn("ActiveRecord::Base.verification_timeout has been deprecated and no longer has any effect. Please remove all references to verification_timeout.")
end
# Deprecated and no longer has any effect.
def verification_timeout=(flag)
ActiveSupport::Deprecation.warn("ActiveRecord::Base.verification_timeout= has been deprecated and no longer has any effect. Please remove all references to verification_timeout=.")
end
# Returns the connection currently associated with the class. This can
# also be used to "borrow" the connection to do database work unrelated
# to any of the specific Active Records.
def connection
retrieve_connection
end
def connection_pool
connection_handler.retrieve_connection_pool(self)
end
def retrieve_connection
connection_handler.retrieve_connection(self)
end
# Returns true if +ActiveRecord+ is connected.
def connected?
connection_handler.connected?(self)
end
def remove_connection(klass = self)
connection_handler.remove_connection(klass)
end
delegate :clear_active_connections!, :clear_reloadable_connections!,
:clear_all_connections!,:verify_active_connections!, :to => :connection_handler
end
end
end
| 37.591549 | 188 | 0.667853 |
01505924cb5d01c58df85b557179e9fef18755cb | 7,673 | #
# Author:: AJ Christensen (<[email protected]>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/provider/service/init'
class Chef
class Provider
class Service
class Debian < Chef::Provider::Service::Init
UPDATE_RC_D_ENABLED_MATCHES = /\/rc[\dS].d\/S|not installed/i
UPDATE_RC_D_PRIORITIES = /\/rc([\dS]).d\/([SK])(\d\d)/i
provides :service, platform_family: "debian"
def self.provides?(node, resource)
super && Chef::Platform::ServiceHelpers.service_resource_providers.include?(:debian)
end
def self.supports?(resource, action)
Chef::Platform::ServiceHelpers.config_for_service(resource.service_name).include?(:initd)
end
def load_current_resource
super
@priority_success = true
@rcd_status = nil
current_resource.priority(get_priority)
current_resource.enabled(service_currently_enabled?(current_resource.priority))
current_resource
end
def define_resource_requirements
# do not call super here, inherit only shared_requirements
shared_resource_requirements
requirements.assert(:all_actions) do |a|
update_rcd = "/usr/sbin/update-rc.d"
a.assertion { ::File.exists? update_rcd }
a.failure_message Chef::Exceptions::Service, "#{update_rcd} does not exist!"
# no whyrun recovery - this is a base system component of debian
# distros and must be present
end
requirements.assert(:all_actions) do |a|
a.assertion { @priority_success }
a.failure_message Chef::Exceptions::Service, "/usr/sbin/update-rc.d -n -f #{current_resource.service_name} failed - #{@rcd_status.inspect}"
# This can happen if the service is not yet installed,so we'll fake it.
a.whyrun ["Unable to determine priority of service, assuming service would have been correctly installed earlier in the run.",
"Assigning temporary priorities to continue.",
"If this service is not properly installed prior to this point, this will fail."] do
temp_priorities = {"6"=>[:stop, "20"],
"0"=>[:stop, "20"],
"1"=>[:stop, "20"],
"2"=>[:start, "20"],
"3"=>[:start, "20"],
"4"=>[:start, "20"],
"5"=>[:start, "20"]}
current_resource.priority(temp_priorities)
end
end
end
def get_priority
priority = {}
@rcd_status = popen4("/usr/sbin/update-rc.d -n -f #{current_resource.service_name} remove") do |pid, stdin, stdout, stderr|
[stdout, stderr].each do |iop|
iop.each_line do |line|
if UPDATE_RC_D_PRIORITIES =~ line
# priority[runlevel] = [ S|K, priority ]
# S = Start, K = Kill
# debian runlevels: 0 Halt, 1 Singleuser, 2 Multiuser, 3-5 == 2, 6 Reboot
priority[$1] = [($2 == "S" ? :start : :stop), $3]
end
if line =~ UPDATE_RC_D_ENABLED_MATCHES
enabled = true
end
end
end
end
# Reduce existing priority back to an integer if appropriate, picking
# runlevel 2 as a baseline
if priority[2] && [2..5].all? { |runlevel| priority[runlevel] == priority[2] }
priority = priority[2].last
end
unless @rcd_status.exitstatus == 0
@priority_success = false
end
priority
end
def service_currently_enabled?(priority)
enabled = false
priority.each { |runlevel, arguments|
Chef::Log.debug("#{new_resource} runlevel #{runlevel}, action #{arguments[0]}, priority #{arguments[1]}")
# if we are in a update-rc.d default startup runlevel && we start in this runlevel
if %w[ 1 2 3 4 5 S ].include?(runlevel) && arguments[0] == :start
enabled = true
end
}
enabled
end
# Override method from parent to ensure priority is up-to-date
def action_enable
if new_resource.priority.nil?
priority_ok = true
else
priority_ok = @current_resource.priority == new_resource.priority
end
if current_resource.enabled and priority_ok
Chef::Log.debug("#{new_resource} already enabled - nothing to do")
else
converge_by("enable service #{new_resource}") do
enable_service
Chef::Log.info("#{new_resource} enabled")
end
end
load_new_resource_state
new_resource.enabled(true)
end
def enable_service
if new_resource.priority.is_a? Integer
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove")
shell_out!("/usr/sbin/update-rc.d #{new_resource.service_name} defaults #{new_resource.priority} #{100 - new_resource.priority}")
elsif new_resource.priority.is_a? Hash
# we call the same command regardless of we're enabling or disabling
# users passing a Hash are responsible for setting their own start priorities
set_priority
else # No priority, go with update-rc.d defaults
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove")
shell_out!("/usr/sbin/update-rc.d #{new_resource.service_name} defaults")
end
end
def disable_service
if new_resource.priority.is_a? Integer
# Stop processes in reverse order of start using '100 - start_priority'
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove")
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} stop #{100 - new_resource.priority} 2 3 4 5 .")
elsif new_resource.priority.is_a? Hash
# we call the same command regardless of we're enabling or disabling
# users passing a Hash are responsible for setting their own stop priorities
set_priority
else
# no priority, using '100 - 20 (update-rc.d default)' to stop in reverse order of start
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove")
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} stop 80 2 3 4 5 .")
end
end
def set_priority
args = ""
new_resource.priority.each do |level, o|
action = o[0]
priority = o[1]
args += "#{action} #{priority} #{level} . "
end
shell_out!("/usr/sbin/update-rc.d -f #{new_resource.service_name} remove")
shell_out!("/usr/sbin/update-rc.d #{new_resource.service_name} #{args}")
end
end
end
end
end
| 41.252688 | 152 | 0.595074 |
7a2b4c7b28ff325689e29b109d237f1163da3ab8 | 114 | class AddPlanetToUser < ActiveRecord::Migration[5.2]
def change
add_column :users, :planet, :text
end
end
| 19 | 52 | 0.72807 |
f815de31192302c11ea738c3756ec8d9ef1fe046 | 2,673 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Mysql::Mgmt::V2017_12_01_preview
module Models
#
# Represents a server to be created.
#
class ServerForCreate
include MsRestAzure
# @return [Sku] The SKU (pricing tier) of the server.
attr_accessor :sku
# @return [ServerPropertiesForCreate] Properties of the server.
attr_accessor :properties
# @return [String] The location the resource resides in.
attr_accessor :location
# @return [Hash{String => String}] Application-specific metadata in the
# form of key-value pairs.
attr_accessor :tags
#
# Mapper for ServerForCreate class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ServerForCreate',
type: {
name: 'Composite',
class_name: 'ServerForCreate',
model_properties: {
sku: {
client_side_validation: true,
required: false,
serialized_name: 'sku',
type: {
name: 'Composite',
class_name: 'Sku'
}
},
properties: {
client_side_validation: true,
required: true,
serialized_name: 'properties',
type: {
name: 'Composite',
polymorphic_discriminator: 'createMode',
uber_parent: 'ServerPropertiesForCreate',
class_name: 'ServerPropertiesForCreate'
}
},
location: {
client_side_validation: true,
required: true,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| 29.054348 | 77 | 0.481481 |
e83e4668168a280f3b4c46e760b91d02eb985439 | 145 | class AddExcludeStateToPatrons < ActiveRecord::Migration
def change
add_column :patrons, :exclude_state, :integer, :default => 0
end
end
| 24.166667 | 64 | 0.758621 |
1d05ca3a55ce3df05ed553c205b4df6bd0451e62 | 499 | require 'formula'
class Lensfun < Formula
homepage 'http://lensfun.sourceforge.net/'
head 'git://git.code.sf.net/p/lensfun/code'
url 'https://downloads.sourceforge.net/project/lensfun/0.2.8/lensfun-0.2.8.tar.bz2'
sha1 '0e85eb7692620668d27e2303687492ad68c90eb4'
revision 1
depends_on 'doxygen' => :optional
depends_on 'glib'
depends_on 'libpng'
depends_on 'pkg-config' => :build
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
end
| 24.95 | 85 | 0.707415 |
e86fd3721cd62202e53f9d799de37176a1d4b0b5 | 11,048 | =begin
#Xero Payroll AU
#This is the Xero Payroll API for orgs in Australia region.
The version of the OpenAPI document: 2.4.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'time'
require 'date'
module XeroRuby::PayrollAu
require 'bigdecimal'
class DeductionType
# Name of the earnings rate (max length = 100)
attr_accessor :name
# See Accounts
attr_accessor :account_code
# Indicates that this is a pre-tax deduction that will reduce the amount of tax you withhold from an employee.
attr_accessor :reduces_tax
# Most deductions don’t reduce your superannuation guarantee contribution liability, so typically you will not set any value for this.
attr_accessor :reduces_super
# Boolean to determine if the deduction type is reportable or exempt from W1
attr_accessor :is_exempt_from_w1
# Xero identifier
attr_accessor :deduction_type_id
# Last modified timestamp
attr_accessor :updated_date_utc
attr_accessor :deduction_category
NONE = "NONE".freeze
UNIONFEES = "UNIONFEES".freeze
WORKPLACEGIVING = "WORKPLACEGIVING".freeze
# Is the current record
attr_accessor :current_record
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'Name',
:'account_code' => :'AccountCode',
:'reduces_tax' => :'ReducesTax',
:'reduces_super' => :'ReducesSuper',
:'is_exempt_from_w1' => :'IsExemptFromW1',
:'deduction_type_id' => :'DeductionTypeID',
:'updated_date_utc' => :'UpdatedDateUTC',
:'deduction_category' => :'DeductionCategory',
:'current_record' => :'CurrentRecord'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'name' => :'String',
:'account_code' => :'String',
:'reduces_tax' => :'Boolean',
:'reduces_super' => :'Boolean',
:'is_exempt_from_w1' => :'Boolean',
:'deduction_type_id' => :'String',
:'updated_date_utc' => :'DateTime',
:'deduction_category' => :'String',
:'current_record' => :'Boolean'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `XeroRuby::PayrollAu::DeductionType` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `XeroRuby::PayrollAu::DeductionType`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'account_code')
self.account_code = attributes[:'account_code']
end
if attributes.key?(:'reduces_tax')
self.reduces_tax = attributes[:'reduces_tax']
end
if attributes.key?(:'reduces_super')
self.reduces_super = attributes[:'reduces_super']
end
if attributes.key?(:'is_exempt_from_w1')
self.is_exempt_from_w1 = attributes[:'is_exempt_from_w1']
end
if attributes.key?(:'deduction_type_id')
self.deduction_type_id = attributes[:'deduction_type_id']
end
if attributes.key?(:'updated_date_utc')
self.updated_date_utc = attributes[:'updated_date_utc']
end
if attributes.key?(:'deduction_category')
self.deduction_category = attributes[:'deduction_category']
end
if attributes.key?(:'current_record')
self.current_record = attributes[:'current_record']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if [email protected]? && @name.to_s.length > 100
invalid_properties.push('invalid value for "name", the character length must be smaller than or equal to 100.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if [email protected]? && @name.to_s.length > 100
deduction_category_validator = EnumAttributeValidator.new('String', ["NONE", "UNIONFEES", "WORKPLACEGIVING"])
return false unless deduction_category_validator.valid?(@deduction_category)
true
end
# Custom attribute writer method with validation
# @param [Object] name Value to be assigned
def name=(name)
if !name.nil? && name.to_s.length > 100
fail ArgumentError, 'invalid value for "name", the character length must be smaller than or equal to 100.'
end
@name = name
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] deduction_category Object to be assigned
def deduction_category=(deduction_category)
validator = EnumAttributeValidator.new('String', ["NONE", "UNIONFEES", "WORKPLACEGIVING"])
unless validator.valid?(deduction_category)
fail ArgumentError, "invalid value for \"deduction_category\", must be one of #{validator.allowable_values}."
end
@deduction_category = deduction_category
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name &&
account_code == o.account_code &&
reduces_tax == o.reduces_tax &&
reduces_super == o.reduces_super &&
is_exempt_from_w1 == o.is_exempt_from_w1 &&
deduction_type_id == o.deduction_type_id &&
updated_date_utc == o.updated_date_utc &&
deduction_category == o.deduction_category &&
current_record == o.current_record
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[name, account_code, reduces_tax, reduces_super, is_exempt_from_w1, deduction_type_id, updated_date_utc, deduction_category, current_record].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(parse_date(value))
when :Date
Date.parse(parse_date(value))
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BigDecimal
BigDecimal(value.to_s)
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
XeroRuby::PayrollAu.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
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
# customized data_parser
def parse_date(datestring)
seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0
return Time.at(seconds_since_epoch).strftime('%Y-%m-%dT%l:%M:%S%z').to_s
end
end
end
| 32.398827 | 212 | 0.638758 |
336b4fcd3c867a1f18121cc89c4b3f2a48d1376f | 254 | class Servel::HomeApp
FAVICON_PATH = "/favicon.ico"
def initialize(roots)
@roots = roots
end
def call(env)
return [404, {}, []] if env["PATH_INFO"] == FAVICON_PATH
Servel::HamlContext.render('home.haml', { roots: @roots })
end
end | 21.166667 | 62 | 0.641732 |
e25adef072733974d1efe95ed1aac6dc8e8b364d | 162 | require 'spec_helper'
describe 'customer-syslog' do
context 'with defaults for all parameters' do
it { should contain_class('customer-syslog') }
end
end
| 20.25 | 50 | 0.740741 |
62c8f4422cc65aed44b20a0304f6ea8f7a0ea9df | 71 | module QuickSearchArchivesSpaceSearcher
VERSION = '1.0.0'.freeze
end
| 17.75 | 39 | 0.802817 |
ff46eab8bba7e7e534af38abe030623d76bc75ad | 7,354 | ##
# Manages changes of attributes in a block of text
class RDoc::Markup::AttributeManager
##
# The NUL character
NULL = "\000".freeze
##
# We work by substituting non-printing characters in to the text. For now
# I'm assuming that I can substitute a character in the range 0..8 for a 7
# bit character without damaging the encoded string, but this might be
# optimistic
A_PROTECT = 004
PROTECT_ATTR = A_PROTECT.chr
##
# This maps delimiters that occur around words (such as *bold* or +tt+)
# where the start and end delimiters and the same. This lets us optimize
# the regexp
MATCHING_WORD_PAIRS = {}
##
# And this is used when the delimiters aren't the same. In this case the
# hash maps a pattern to the attribute character
WORD_PAIR_MAP = {}
##
# This maps HTML tags to the corresponding attribute char
HTML_TAGS = {}
##
# And this maps _special_ sequences to a name. A special sequence is
# something like a WikiWord
SPECIAL = {}
##
# Return an attribute object with the given turn_on and turn_off bits set
def attribute(turn_on, turn_off)
RDoc::Markup::AttrChanger.new turn_on, turn_off
end
def change_attribute(current, new)
diff = current ^ new
attribute(new & diff, current & diff)
end
def changed_attribute_by_name(current_set, new_set)
current = new = 0
current_set.each do |name|
current |= RDoc::Markup::Attribute.bitmap_for(name)
end
new_set.each do |name|
new |= RDoc::Markup::Attribute.bitmap_for(name)
end
change_attribute(current, new)
end
def copy_string(start_pos, end_pos)
res = @str[start_pos...end_pos]
res.gsub!(/\000/, '')
res
end
##
# Map attributes like <b>text</b>to the sequence
# \001\002<char>\001\003<char>, where <char> is a per-attribute specific
# character
def convert_attrs(str, attrs)
# first do matching ones
tags = MATCHING_WORD_PAIRS.keys.join("")
re = /(^|\W)([#{tags}])([#:\\]?[\w.\/-]+?\S?)\2(\W|$)/
1 while str.gsub!(re) do
attr = MATCHING_WORD_PAIRS[$2]
attrs.set_attrs($`.length + $1.length + $2.length, $3.length, attr)
$1 + NULL * $2.length + $3 + NULL * $2.length + $4
end
# then non-matching
unless WORD_PAIR_MAP.empty? then
WORD_PAIR_MAP.each do |regexp, attr|
str.gsub!(regexp) {
attrs.set_attrs($`.length + $1.length, $2.length, attr)
NULL * $1.length + $2 + NULL * $3.length
}
end
end
end
##
# Converts HTML tags to RDoc attributes
def convert_html(str, attrs)
tags = HTML_TAGS.keys.join '|'
1 while str.gsub!(/<(#{tags})>(.*?)<\/\1>/i) {
attr = HTML_TAGS[$1.downcase]
html_length = $1.length + 2
seq = NULL * html_length
attrs.set_attrs($`.length + html_length, $2.length, attr)
seq + $2 + seq + NULL
}
end
##
# Converts special sequences to RDoc attributes
def convert_specials(str, attrs)
unless SPECIAL.empty?
SPECIAL.each do |regexp, attr|
str.scan(regexp) do
attrs.set_attrs($`.length, $&.length,
attr | RDoc::Markup::Attribute::SPECIAL)
end
end
end
end
##
# A \ in front of a character that would normally be processed turns off
# processing. We do this by turning \< into <#{PROTECT}
PROTECTABLE = %w[<\\]
##
# Escapes special sequences of text to prevent conversion to RDoc
def mask_protected_sequences
protect_pattern = Regexp.new("\\\\([#{Regexp.escape(PROTECTABLE.join(''))}])")
@str.gsub!(protect_pattern, "\\1#{PROTECT_ATTR}")
end
##
# Unescapes special sequences of text
def unmask_protected_sequences
@str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
end
##
# Creates a new attribute manager that understands bold, emphasized and
# teletype text.
def initialize
add_word_pair("*", "*", :BOLD)
add_word_pair("_", "_", :EM)
add_word_pair("+", "+", :TT)
add_html("em", :EM)
add_html("i", :EM)
add_html("b", :BOLD)
add_html("tt", :TT)
add_html("code", :TT)
end
##
# Adds a markup class with +name+ for words wrapped in the +start+ and
# +stop+ character. To make words wrapped with "*" bold:
#
# am.add_word_pair '*', '*', :BOLD
def add_word_pair(start, stop, name)
raise ArgumentError, "Word flags may not start with '<'" if
start[0,1] == '<'
bitmap = RDoc::Markup::Attribute.bitmap_for name
if start == stop then
MATCHING_WORD_PAIRS[start] = bitmap
else
pattern = /(#{Regexp.escape start})(\S+)(#{Regexp.escape stop})/
WORD_PAIR_MAP[pattern] = bitmap
end
PROTECTABLE << start[0,1]
PROTECTABLE.uniq!
end
##
# Adds a markup class with +name+ for words surrounded by HTML tag +tag+.
# To process emphasis tags:
#
# am.add_html 'em', :EM
def add_html(tag, name)
HTML_TAGS[tag.downcase] = RDoc::Markup::Attribute.bitmap_for name
end
##
# Adds a special handler for +pattern+ with +name+. A simple URL handler
# would be:
#
# @am.add_special(/((https?:)\S+\w)/, :HYPERLINK)
def add_special(pattern, name)
SPECIAL[pattern] = RDoc::Markup::Attribute.bitmap_for name
end
##
# Processes +str+ converting attributes, HTML and specials
def flow(str)
@str = str
mask_protected_sequences
@attrs = RDoc::Markup::AttrSpan.new @str.length
convert_attrs(@str, @attrs)
convert_html(@str, @attrs)
convert_specials(str, @attrs)
unmask_protected_sequences
split_into_flow
end
##
# Debug method that prints a string along with its attributes
def display_attributes
puts
puts @str.tr(NULL, "!")
bit = 1
16.times do |bno|
line = ""
@str.length.times do |i|
if (@attrs[i] & bit) == 0
line << " "
else
if bno.zero?
line << "S"
else
line << ("%d" % (bno+1))
end
end
end
puts(line) unless line =~ /^ *$/
bit <<= 1
end
end
def split_into_flow
res = []
current_attr = 0
str = ""
str_len = @str.length
# skip leading invisible text
i = 0
i += 1 while i < str_len and @str[i].chr == "\0"
start_pos = i
# then scan the string, chunking it on attribute changes
while i < str_len
new_attr = @attrs[i]
if new_attr != current_attr
if i > start_pos
res << copy_string(start_pos, i)
start_pos = i
end
res << change_attribute(current_attr, new_attr)
current_attr = new_attr
if (current_attr & RDoc::Markup::Attribute::SPECIAL) != 0 then
i += 1 while
i < str_len and (@attrs[i] & RDoc::Markup::Attribute::SPECIAL) != 0
res << RDoc::Markup::Special.new(current_attr,
copy_string(start_pos, i))
start_pos = i
next
end
end
# move on, skipping any invisible characters
begin
i += 1
end while i < str_len and @str[i].chr == "\0"
end
# tidy up trailing text
if start_pos < str_len
res << copy_string(start_pos, str_len)
end
# and reset to all attributes off
res << change_attribute(current_attr, 0) if current_attr != 0
res
end
end
| 23.722581 | 82 | 0.605249 |
acc244d92e04adec4fb667eac048788bac493090 | 8,589 | Петронелла Уайет: Надо Мной запугали из Оксфорда для того, чтобы быть Тори
Это не просто сегодняшние студенты университета, которые подвергаются нападению за их взгляды
Я не могу помнить время, когда я не мечтал о победе места в Оксфордском университете.
И мой отец и мой старший брат были, в каком я вообразил, было самое большое место в мире изучения, современный покрасневший вином греческий симпозиум, поощряющий двойные столбы цивилизации, свободомыслия и терпимости.
Все же, в течение двух недель после поднятия моего места в Вустер-Колледже в конце восьмидесятых, чтобы прочитать историю, я упаковал свои сумки, ускоряя первый скандал моей жизни.
Мой отец сломался и кричал.
Друзья были сбиты с толку.
Вечерний Стандартный дневник утверждал, что я ушел, потому что я возразил против поддерживающих студентов, занимающихся сексом в комнате, следующей за моим.
Уилсон A N писателя объявил шаловливо, что я отбыл, потому что я был вынужден пить из кружек с обитыми краями.
Правда была менее забавной.
Я убежал.
Да, бежал, потому что я подвергся систематическому запугиванию и запугиванию.
Не вследствие моего скорее outré имя или факт, что я приехал из частной школы.
Я преследовался по одной причине только, и в этой колыбели воображаемого просвещения это было и фанатичным и варварским: мой отец, покойный Вудро Уайет, был высококлассным советником Маргарет Тэтчер, и я был консервативным сторонником.
Почему поднимают это теперь, Вы могли бы спросить.
Ну, в недавних докладах предполагается, что новое поколение студентов Права центра переносит подобное преследование.
Такова институциализированная и увеличивающаяся ненависть к студентам Тори в Оксфорде, что на прошлой неделе группа их потребовала ту же самую защиту равных прав как геи, инвалиды и этнические меньшинства.
Консервативные члены комнаты отдыха для студентов (JCR) Колледжа Корпус-Кристи утверждают, что "часто активно изолируются, лично нападаются и заставляются чувствовать себя не приветствующимися" из-за их политических взглядов.
Они хотят создать почту в комитете по равным возможностям колледжа, чтобы гарантировать, что их мнения могут быть переданы свободно.
Их ситуации не помогла недавняя Би-би-си Два документальных фильма, Страна чудес: Молодой, Яркий и справа, о студенческой политике, которая изобразила Тори как чудаков и неонацистов.
Это показало выпускника Джо Кука, бывшего президента Oxford University Conservative Association (OUCA), едущей в Роллс-ройсе, спортивном серебряный костюм и тростник с серебряным верхом.
В других университетах консервативные студенты говорят, что их рассматривают как "козлов отпущения" для введения более высокой платы за обучение."
Люк Блэк, 20 лет, вице-президент Ноттингемской университетской Консервативной ассоциации, сказал воскресную газету что "есть растущий Левый уклон в университетах.
Люди предполагают, что мы походим на Клуб Bullingdon, не встречая нас."
Сэмюэль Робертс, 21 года, студент истории в Корпус-Кристи, который предложил движение для большей защиты, говорит, что такой климат "неудобен", в то время как Стефани Черилл, 19 лет, избранный президент OUCA, говорит, что было ухудшение в отношении участников JCR к людям, которые Правы из центра.
"Это ставит под угрозу атмосферу интеллектуального обсуждения, а также к благосостоянию участников", говорит она.
Я был в меньшинстве одного в течение моих первых нескольких недель в Оксфорде.
Я поднялся в сентябре 1986, cripplingly застенчивые 18 лет.
Ненависть к Консервативной партии была в его самом лихорадочном.
Год прежде, университет голосовал, чтобы отказаться от Маргарет Тэтчер - бывшего студента - почетная ученая степень из-за сокращений финансирования высшего образования.
Атмосфера сделала бы Сталинистскую дрожь с предчувствием.
В течение первых нескольких дней freshers" неделя, когда новые студенты социализируют друг с другом и Донами, у меня был вкус полыни, которая должна была прибыть.
Я должен был найти, что Доны не только потворствовали в ядовитых из студентов Тори, но и приняли сторону склонности.
Политика шахтеров" удар, приватизация и возражение правительства санкциям против апартеида Южная Африка была принесена в комнаты с панелями леса обучающей программы.
Мой первый включил перевод французских текстов 18-го века на английский язык, и я был неподготовлен к тому, что следовало.
"Мисс Уайет", сказал Дон, Гарри Питт (теперь покойный), "пожалуйста, переведите первый параграф".
Я споткнулся его.
Маленький человек с лицом как жидкое тесто пирога, Питт хорошо разбирался в желчи.
"Thatcherites отказываются узнавать, что французский или они просто глупы? " он потребовал.
Другие студенты хихикали.
Слезы укололи заднюю часть моих глаз.
"Я предлагаю, чтобы Вы взяли некоторые основные французские уроки в свое свободное время - то есть, если Вы не слишком заняты, социализируя", Питт брюзжал.
Я шел назад к моим комнатам печальное число.
На обеде в колледже тем вечером я сел у меня; тогда я чувствовал легкий сигнал на плече.
Это был английский студент второго года по имени Джеймс, который представился как член OUCA.
"Я знаю, кто Вы", сказал он любезно.
Я боюсь, что это походит на это.
Любой подозревал в том, что он Тори, выбран.
Это достаточно плохо для меня, но они знают, что Ваш отец близко к Маргарет Тэтчер, таким образом, это будет хуже для Вас.
Большая часть Тори freshers притворяется, что они - Лейбористская партия.
Позже, в местном пабе, я малодушно попытался скрыть.
Я настоял, что не соглашался со всем, что г-жа Тэтчер сказала.
Эта уловка оказалась неудачной.
Первый год студент PPE, который по иронии судьбы был в Итон, сказал: "Вы - дочь фашистской свиньи".
Вы загрязнены.
Другие студенты подняли рефрен.
Я был извращен, грязен.
"Как Тори занимаются сексом? " один спрошенный.
Они бьют друг друга, не так ли?
Я чувствовал способ, которым гомосексуалисты, должно быть, чувствовали перед либеральным законодательством шестидесятых.
Я когда-либо был бы в состоянии провести нормальную жизнь в Оксфорде?
Я был бы вынужден встретить аналогично мыслящих людей только после наступления темноты?
Я должен был бы повернуться к Лейбористской партии и подавить свои естественные предпочтения?
За эти три года до меня растянулся как чистилище остракизма и изоляции.
Единственным открыто Доном Тори был Норман Стоун, профессор Современной истории, который базировался в моем колледже.
За него ненавидели то, что он был не только консерватором, но и советником внешней политики Тэтчер и одного из ее спичрайтеров.
Он почти никогда не был там.
Он ненавидел место как провинциальное и мелкое, и для его приверженности марксистско-детерминистскому представлению об истории.
В 1997 он поднял профессорство в университете Bilkent, в Анкаре, Турция.
"Вы не будете счастливы здесь", сказал он мне.
Я начал переключать от Оксфорда до моих родителей" дом в Лондоне, находя убежище с моим большим количеством непредубежденных столичных друзей и семьи.
Я сказал моему отцу, что ненавидел Оксфорд и почему.
Он был недоверчив.
В течение его времени там в сороковых, были приняты все политические взгляды.
"Но это - лучшее место в мире", сказал он трогательно.
Они не сделали бы этого, не среди моих полных сновидений шпилей.
Даже у моих коммунистических друзей всегда были безупречные манеры.
Его rheumy глаза начали покрываться облаками.
Дайте ему шанс.
Я уверен, что это - все просто поддразнивание.
Это разбило бы мое сердце, если бы Вы уехали.
Исчерпанный моими частыми поездками в Лондон, мое эмоциональное сопротивление ухудшалось.
Мой друг мужского пола, также сторонник Тори, уступил давлению и отказался от своего кредо.
Во время обучающей программы на следующей неделе, когда другой Дон истории предположил в полной серьезности, что я был "врагом людей", я решил сделать то же самое.
Внутри краснея с позором, я признался, что был " промыт мозги моими родителями" и назван их "старыми дураками".
Отсрочка была коротка.
Именно мой отец забил гвоздь в гроб моей Оксфордской карьеры.
В то время, он написал две колонки в прессе Мердока каждую неделю.
Моя дверь была заперта.
Я сжался внутри, и после того, как пять минут, мои преследователи сдались.
Когда они уехали, я упаковал чемодан и сел на первый поезд в Лондон.
Я никогда не возвращался.
Вы можете назвать меня хнычущим мещанином.
Но номер 18 лет должен подвергнуться такому запугиванию и купоросу в учебном заведении.
Еще более трагичный то, что это был Оксфорд, который не только произвел 14 премьер-министров Тори, но и, по сей день, скрывается позади плохо заслуженной репутации равенства и свободы мысли.
| 89.46875 | 298 | 0.808476 |
91dc350a46bdec902623decba9b48e93563a99cb | 3,244 | # encoding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require 'cucumber/rb_support/rb_step_definition'
require 'cucumber/rb_support/rb_language'
module Cucumber
describe StepMatch do
WORD = Cucumber::RUBY_1_9 ? '[[:word:]]' : '\w'
before do
@rb_language = RbSupport::RbLanguage.new(nil)
end
def stepdef(regexp)
RbSupport::RbStepDefinition.new(@rb_language, regexp, lambda{})
end
def step_match(regexp, name)
stepdef = stepdef(regexp)
StepMatch.new(stepdef, name, nil, stepdef.arguments_from(name))
end
it "should format one group when we use Unicode" do
m = step_match(/I (#{WORD}+) ok/, "I æøåÆØÅæøåÆØÅæøåÆØÅæøåÆØÅ ok")
m.format_args("<span>%s</span>").should == "I <span>æøåÆØÅæøåÆØÅæøåÆØÅæøåÆØÅ</span> ok"
end
it "should format several groups when we use Unicode" do
m = step_match(/I (#{WORD}+) (#{WORD}+) (#{WORD}+) this (#{WORD}+)/, "I ate æøåÆØÅæøåÆØÅæøåÆØÅæøåÆØÅ egg this morning")
m.format_args("<span>%s</span>").should == "I <span>ate</span> <span>æøåÆØÅæøåÆØÅæøåÆØÅæøåÆØÅ</span> <span>egg</span> this <span>morning</span>"
end
it "should deal with Unicode both inside and outside arguments" do
"Jæ vø ålsker døtte løndet".should =~ /Jæ (.+) ålsker (.+) løndet/
m = step_match(/Jæ (#{WORD}+) ålsker (#{WORD}+) løndet/, "Jæ vø ålsker døtte løndet")
m.format_args("<span>%s</span>").should == "Jæ <span>vø</span> ålsker <span>døtte</span> løndet"
end
it "should format groups with format string" do
m = step_match(/I (#{WORD}+) (\d+) (#{WORD}+) this (#{WORD}+)/, "I ate 1 egg this morning")
m.format_args("<span>%s</span>").should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
end
it "should format groups with format string when there are dupes" do
m = step_match(/I (#{WORD}+) (\d+) (#{WORD}+) this (#{WORD}+)/, "I bob 1 bo this bobs")
m.format_args("<span>%s</span>").should == "I <span>bob</span> <span>1</span> <span>bo</span> this <span>bobs</span>"
end
it "should format groups with block" do
m = step_match(/I (#{WORD}+) (\d+) (#{WORD}+) this (#{WORD}+)/, "I ate 1 egg this morning")
m.format_args(&lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
end
it "should format groups with proc object" do
m = step_match(/I (#{WORD}+) (\d+) (#{WORD}+) this (#{WORD}+)/, "I ate 1 egg this morning")
m.format_args(lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
end
it "should format groups even when first group is optional and not matched" do
m = step_match(/should( not)? be flashed '([^']*?)'$/, "I should be flashed 'Login failed.'")
m.format_args("<span>%s</span>").should == "I should be flashed '<span>Login failed.</span>'"
end
it "should format embedded groups" do
m = step_match(/running( (\d+) times)? (\d+) meters/, "running 5 times 10 meters")
m.format_args("<span>%s</span>").should == "running<span> 5 times</span> <span>10</span> meters"
end
end
end | 47.014493 | 150 | 0.624229 |
5dd0630c3df0bf14aa13cdd5b0c578dd7f704348 | 2,231 | require File.expand_path('../../../test/test_helper.rb', __FILE__)
class SegmentTest < Minitest::Test
include Test::Helpers::All
def test_create
assert_tend_class "segment", "create", {name: "test by steve 2"}
end
def test_get_find
assert_tend_class "segment", "find", 1
end
def test_update
assert_tend_instance segment, "update", {name: "test2"}
end
def test_delete
assert_tend_instance segment, "delete"
end
def test_assign_one_string
assert_tend_class "segment", "assign|one_string", "[email protected]", "renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212"
end
def test_assign_as_strings
assert_tend_class "segment", "assign|as_strings", "[email protected]", "renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212,renamed test by steve 96f63274-9dc3-407a-98a0-21d54bd3f590"
end
def test_assign_one_array
assert_tend_class "segment", "assign|one_array", "[email protected]", ["renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212"]
end
def test_assign_as_array
assert_tend_class "segment", "assign|as_array", "[email protected]", ["renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212","renamed test by steve 96f63274-9dc3-407a-98a0-21d54bd3f590"]
end
def test_detach_one_string
assert_tend_class "segment", "detach|one_string", "[email protected]", "renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212"
end
def test_detach_as_strings
assert_tend_class "segment", "detach|as_strings", "[email protected]", "renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212,renamed test by steve 96f63274-9dc3-407a-98a0-21d54bd3f590"
end
def test_detach_one_array
assert_tend_class "segment", "detach|one_array", "[email protected]", ["renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212"]
end
def test_detach_as_array
assert_tend_class "segment", "detach|as_array", "[email protected]", ["renamed test by steve e31f1b3a-20bd-4605-9844-bab71e230212","renamed test by steve 96f63274-9dc3-407a-98a0-21d54bd3f590"]
end
def segment
s = nil
VCR.use_cassette("segment_find") do
s = Tend::Segment.find 1
end
s
end
end | 35.983871 | 202 | 0.755715 |
87a52194245000accafda0882271b343cc7cd0c1 | 860 | require 'spec_helper'
describe 'freeradius::policy' do
include_context 'redhat_common_dependencies'
let(:title) { 'test' }
let(:params) do
{
:source => 'puppet:///modules/test/path/to/policy',
}
end
it do
is_expected.to contain_file('/etc/raddb/policy.d/test')
.with_ensure('present')
.with_group('radiusd')
.with_mode('0644')
.with_owner('root')
.with_source('puppet:///modules/test/path/to/policy')
.that_notifies('Service[radiusd]')
.that_requires('Package[freeradius]')
.that_requires('Group[radiusd]')
end
it do
is_expected.to contain_concat__fragment('policy-test')
.with_content(%r{\s+\$INCLUDE /etc/raddb/policy.d/test\n})
.with_order('50')
.with_target('/etc/raddb/policy.conf')
.that_requires('File[/etc/raddb/policy.d/test]')
end
end
| 25.294118 | 64 | 0.646512 |
089854d45af11bc44a8c5e6f66b15bd539250de0 | 525 | class StoryMailer < ApplicationMailer
def for_campaign(campaign, story, email_subscription)
@campaign = campaign
@story = story
@email_subscription = email_subscription
@unsubscribe_url = unsubscribe_url(id: Rails.application.message_verifier(:unsubscribe).generate(@email_subscription.id), title: @campaign.title, link: campaign_url(@campaign))
if @email_subscription.use?
mail(to: email_subscription.email, subject: "[빠띠 캠페인즈] #{story.title}", template_name: "for_campaign")
end
end
end
| 37.5 | 180 | 0.752381 |
ff075259e213974f598eec4f9b5bb83514df3085 | 3,490 | #! /usr/bin/env ruby
#
# <script name>
#
# DESCRIPTION:
# what is this thing supposed to do, monitor? How do alerts or
# alarms work?
#
# OUTPUT:
# plain text, metric data, etc
#
# PLATFORMS:
# Linux, Windows, BSD, Solaris, etc
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: <?>
#
# USAGE:
# example commands
#
# NOTES:
# Does it behave differently on specific platforms, specific use cases, etc
#
# LICENSE:
# <your name> <your email>
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
# !/usr/bin/env ruby
#
# MySQL Health Plugin
# ===
#
# This plugin counts the maximum connections your MySQL has reached and warns you according to specified limits
#
# Copyright 2012 Panagiotis Papadomitsos <[email protected]>
#
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
require 'mysql'
class CheckMySQLHealth < Sensu::Plugin::Check::CLI
option :user,
description: 'MySQL User',
short: '-u USER',
long: '--user USER',
default: 'root'
option :password,
description: 'MySQL Password',
short: '-p PASS',
long: '--password PASS',
required: true
option :hostname,
description: 'Hostname to login to',
short: '-h HOST',
long: '--hostname HOST',
default: 'localhost'
option :port,
description: 'Port to connect to',
short: '-P PORT',
long: '--port PORT',
default: '3306'
option :socket,
description: 'Socket to use',
short: '-s SOCKET',
long: '--socket SOCKET'
option :maxwarn,
description: "Number of connections upon which we'll issue a warning",
short: '-w NUMBER',
long: '--warnnum NUMBER',
default: 100
option :maxcrit,
description: "Number of connections upon which we'll issue an alert",
short: '-c NUMBER',
long: '--critnum NUMBER',
default: 128
option :usepc,
description: 'Use percentage of defined max connections instead of absolute number',
short: '-a',
long: '--percentage',
default: false
def run
db = Mysql.real_connect(config[:hostname], config[:user], config[:password], config[:database], config[:port].to_i, config[:socket])
max_con = db
.query("SHOW VARIABLES LIKE 'max_connections'")
.fetch_hash
.fetch('Value')
.to_i
used_con = db
.query("SHOW GLOBAL STATUS LIKE 'Threads_connected'")
.fetch_hash
.fetch('Value')
.to_i
if config[:usepc]
pc = used_con.fdiv(max_con) * 100
critical "Max connections reached in MySQL: #{used_con} out of #{max_con}" if pc >= config[:maxcrit].to_i
warning "Max connections reached in MySQL: #{used_con} out of #{max_con}" if pc >= config[:maxwarn].to_i
ok "Max connections is under limit in MySQL: #{used_con} out of #{max_con}"
else
critical "Max connections reached in MySQL: #{used_con} out of #{max_con}" if used_con >= config[:maxcrit].to_i
warning "Max connections reached in MySQL: #{used_con} out of #{max_con}" if used_con >= config[:maxwarn].to_i
ok "Max connections is under limit in MySQL: #{used_con} out of #{max_con}"
end
rescue Mysql::Error => e
critical "MySQL check failed: #{e.error}"
ensure
db.close if db
end
end
| 28.373984 | 136 | 0.62235 |
26c70c9d19ca8fd4a1f875a63fc53a5221175751 | 818 | class YouTube < Liquid::Tag
Syntax = /^\s*([^\s]+)(\s+(\d+)\s+(\d+)\s*)?/
def initialize(tagName, markup, tokens)
super
if markup =~ Syntax then
@id = $1
if $2.nil? then
@width = 560
@height = 420
else
@width = $2.to_i
@height = $3.to_i
end
else
raise "No YouTube ID provided in the \"youtube\" tag"
end
end
def render(context)
# "<iframe width=\"#{@width}\" height=\"#{@height}\" src=\"http://www.youtube.com/embed/#{@id}\" frameborder=\"0\"allowfullscreen></iframe>"
"<div class=\"video-responsive\"><iframe width=\"#{@width}\" height=\"#{@height}\" src=\"http://www.youtube.com/embed/#{@id}?color=white&theme=light\" allowfullscreen></iframe></div>"
end
Liquid::Template.register_tag "youtube", self
end
| 28.206897 | 187 | 0.56846 |
d5765f6d620ea6899b2bb96e75c841229523efdc | 186 | module Hardware
def self.oldest_cpu
if MacOS.version >= :mojave
:nehalem
elsif MacOS.version >= :sierra
:penryn
else
generic_oldest_cpu
end
end
end
| 15.5 | 34 | 0.634409 |
211a53aca6407057b87b94135c00ff2049901a97 | 1,818 | class IcarusVerilog < Formula
desc "Verilog simulation and synthesis tool"
homepage "http://iverilog.icarus.com/"
url "ftp://icarus.com/pub/eda/verilog/v10/verilog-10.3.tar.gz"
mirror "https://deb.debian.org/debian/pool/main/i/iverilog/iverilog_10.3.orig.tar.gz"
sha256 "86bd45e7e12d1bc8772c3cdd394e68a9feccb2a6d14aaf7dae0773b7274368ef"
bottle do
sha256 "bf40a384b8432dfb72276e31e87d550b9b47515dc68bdfb25f0cde9becd4ac10" => :catalina
sha256 "0237851e478bcb76567111f14c1e42fe79161a8cd28ca04127295fc40db14113" => :mojave
sha256 "96a15af23212d29f9410e073418c9388447955245fa8c38cf3b27ccf8fabd178" => :high_sierra
sha256 "ded40d14a1cd74f2b764d9cf667d48ee8b6c010e77d88ca47afc99188ace1255" => :sierra
end
head do
url "https://github.com/steveicarus/iverilog.git"
depends_on "autoconf" => :build
end
# parser is subtly broken when processed with an old version of bison
depends_on "bison" => :build
uses_from_macos "flex" => :build
uses_from_macos "bzip2"
uses_from_macos "zlib"
def install
system "autoconf" if build.head?
system "./configure", "--prefix=#{prefix}"
# https://github.com/steveicarus/iverilog/issues/85
ENV.deparallelize
system "make", "install", "BISON=#{Formula["bison"].opt_bin}/bison"
end
test do
(testpath/"test.v").write <<~EOS
module main;
initial
begin
$display("Boop");
$finish;
end
endmodule
EOS
system bin/"iverilog", "-otest", "test.v"
assert_equal "Boop", shell_output("./test").chomp
# test syntax errors do not cause segfaults
(testpath/"error.v").write "error;"
assert_equal "-:1: error: variable declarations must be contained within a module.",
shell_output("#{bin}/iverilog error.v 2>&1", 1).chomp
end
end
| 33.666667 | 93 | 0.707921 |
21912b1d5d724f2e07e6ed3c61e8adee3c45afc2 | 5,015 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "Christmas_List_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.380531 | 114 | 0.762512 |
e28d5001c20ee2f255ace766f88a45b922db96ae | 519 | class TimestampVotes < ActiveRecord::Migration[5.1]
def change
add_column :votes, :updated_at, :datetime, null: true
ActiveRecord::Base.connection.execute("update votes set updated_at = comments.created_at from comments where comments.id = comment_id and votes.updated_at is null")
ActiveRecord::Base.connection.execute("update votes set updated_at = stories.created_at from stories where stories.id = story_id and votes.updated_at is null")
change_column_null :votes, :updated_at, false
end
end
| 57.666667 | 168 | 0.776493 |
87f3a09f29b44bd3bca4d4bdcebdc11145088a71 | 266 | class Payment < ApplicationRecord
belongs_to :order
has_one_attached :file
validates :file, attached: true, content_type: [:png, :jpg, :jpeg], :unless => :compra_click_method?
private
def compra_click_method?
self.payment_method == "compra_click"
end
end
| 20.461538 | 101 | 0.755639 |
3837e88c949d02896794824282f99dd10051b003 | 509 | module Coupler
module Models
class Transformer
class Runner
instance_methods.each do |m|
undef_method m unless m =~ /^__|^instance_eval$/
end
def initialize(code, input)
@input = input
@code = code
end
def run
instance_eval(@code, __FILE__, __LINE__)
end
def value
@input
end
def method_missing(name)
raise NoMethodError
end
end
end
end
end
| 17.551724 | 58 | 0.526523 |
d5aad4519ab4e1d4d687dc1aa16dab5fa990e9b8 | 6,743 | require_relative '../spec_helper'
describe "Ruby apps" do
# https://github.com/heroku/heroku-buildpack-ruby/issues/1025
describe "bin/rake binstub" do
it "loads git gems at build time when executing `rake`" do
Hatchet::Runner.new("git_gemspec").tap do |app|
app.before_deploy do
File.open("Rakefile", "w+") do |f|
f.puts(<<~EOF)
task "assets:precompile" do
require 'mini_histogram'
puts "successfully loaded git gem"
end
EOF
end
end
app.deploy do
expect(app.output).to match("successfully loaded git gem")
expect(app.run("rake assets:precompile")).to match("successfully loaded git gem")
end
end
end
it "loads bundler into memory" do
Hatchet::Runner.new("default_ruby").tap do |app|
app.before_deploy do
File.open("Rakefile", "w+") do |f|
f.puts(<<~EOF)
task "assets:precompile" do
puts Bundler.methods
puts "bundler loaded in rake context"
end
EOF
end
end
app.deploy do
expect(app.output).to match("bundler loaded in rake context")
expect(app.run("rake assets:precompile")).to match("bundler loaded in rake context")
end
end
end
it "loads custom rake binstub" do
Hatchet::Runner.new("default_ruby").tap do |app|
app.before_deploy do
FileUtils.mkdir_p("bin")
File.open("bin/rake", "w+") do |f|
f.puts(<<~EOF)
#!/usr/bin/env ruby
puts "rake assets:precompile" # Needed to trigger the `rake -P` task detection
puts "custom rake binstub called"
EOF
end
FileUtils.chmod("+x", "bin/rake")
end
app.deploy do
expect(app.output).to match("custom rake binstub called")
expect(app.run("rake")).to match("custom rake binstub called")
end
end
end
end
describe "bad ruby version" do
it "gives a helpful error" do
Hatchet::Runner.new('ruby_version_does_not_exist', allow_failure: true, stack: DEFAULT_STACK).deploy do |app|
expect(app.output).to match("The Ruby version you are trying to install does not exist: ruby-2.9.0.lol")
end
end
end
describe "exporting path" do
it "puts local bin dir in path" do
before_deploy = Proc.new do
FileUtils.mkdir_p("bin")
File.open("bin/bloop", "w+") do |f|
f.puts(<<~EOF)
#!/usr/bin/env bash
echo "bloop"
EOF
end
FileUtils.chmod("+x", "bin/bloop")
File.open("Rakefile", "a") do |f|
f.puts(<<~EOF)
task "run:bloop" do
puts `bloop`
raise "Could not bloop" unless $?.success?
end
EOF
end
end
buildpacks = [
:default,
"https://github.com/schneems/buildpack-ruby-rake-deploy-tasks"
]
config = { "DEPLOY_TASKS" => "run:bloop"}
Hatchet::Runner.new('default_ruby', stack: DEFAULT_STACK, buildpacks: buildpacks, config: config, before_deploy: before_deploy).deploy do |app|
expect(app.output).to match("bloop")
end
end
end
describe "running Ruby from outside the default dir" do
it "works" do
buildpacks = [
:default,
"https://github.com/sharpstone/force_absolute_paths_buildpack"
]
config = {FORCE_ABSOLUTE_PATHS_BUILDPACK_IGNORE_PATHS: "BUNDLE_PATH"}
Hatchet::Runner.new('cd_ruby', stack: DEFAULT_STACK, buildpacks: buildpacks, config: config).deploy do |app|
expect(app.output).to match("cd version ruby 2.5.1")
expect(app.run("which ruby").strip).to eq("/app/bin/ruby")
end
end
end
describe "bundler ruby version matcher" do
it "installs a version even when not present in the Gemfile.lock" do
Hatchet::Runner.new('bundle-ruby-version-not-in-lockfile', stack: DEFAULT_STACK).deploy do |app|
expect(app.output).to match("2.5.1")
expect(app.run("ruby -v")).to match("2.5.1")
end
end
it "works even when patchfile is specified" do
Hatchet::Runner.new('problem_gemfile_version', stack: DEFAULT_STACK).deploy do |app|
expect(app.output).to match("2.5.1")
end
end
end
describe "2.5.0" do
it "works" do
Hatchet::Runner.new("ruby_25", stack: "heroku-18").deploy do |app|
expect(app.output).to include("There is a more recent Ruby version available")
end
end
end
describe "Rake detection" do
context "Ruby 1.9+" do
it "runs a rake task if the gem exists" do
Hatchet::Runner.new('default_with_rakefile').deploy do |app, heroku|
expect(app.output).to include("foo")
end
end
end
end
describe "database configuration" do
context "no active record" do
it "writes a heroku specific database.yml" do
Hatchet::Runner.new("default_ruby").deploy do |app, heroku|
expect(app.output).to include("Writing config/database.yml to read from DATABASE_URL")
expect(app.output).not_to include("Your app was upgraded to bundler")
expect(app.output).not_to include("Your Ruby version is not present on the next stack")
end
end
end
context "active record 4.1+" do
it "doesn't write a heroku specific database.yml" do
Hatchet::Runner.new("activerecord41_scaffold").deploy do |app, heroku|
expect(app.output).not_to include("Writing config/database.yml to read from DATABASE_URL")
end
end
end
end
end
describe "Raise errors on specific gems" do
it "should raise on sqlite3" do
before_deploy = -> { run!(%Q{echo "ruby '2.5.4' >> Gemfile"}) }
Hatchet::Runner.new("sqlite3_gemfile", allow_failure: true, before_deploy: before_deploy).deploy do |app|
expect(app).not_to be_deployed
expect(app.output).to include("Detected sqlite3 gem which is not supported")
expect(app.output).to include("devcenter.heroku.com/articles/sqlite3")
end
end
end
describe "No Lockfile" do
it "should not deploy" do
Hatchet::Runner.new("no_lockfile", allow_failure: true).deploy do |app|
expect(app).not_to be_deployed
expect(app.output).to include("Gemfile.lock required")
end
end
end
describe "Rack" do
it "should not overwrite already set environment variables" do
custom_env = "FFFUUUUUUU"
app = Hatchet::Runner.new("default_ruby", config: {"RACK_ENV" => custom_env})
app.deploy do |app|
expect(app.run("env")).to match(custom_env)
end
end
end
| 32.109524 | 149 | 0.614563 |
7a15eb24082a0af0931532a7797f09304ea2cd6d | 1,374 | module HTMLProofer
# Mostly handles issue management and collecting of external URLs.
class Check
attr_reader :node, :html, :element, :src, :path, :options, :issues, :external_urls
def initialize(src, path, html, options)
@src = src
@path = path
@html = remove_ignored(html)
@options = options
@issues = []
@external_urls = {}
end
def create_element(node)
@node = node
Element.new(node, self)
end
def run
raise NotImplementedError, 'HTMLProofer::Check subclasses must implement #run'
end
def add_issue(desc, line: nil, status: -1, content: nil)
@issues << Issue.new(@path, desc, line: line, status: status, content: content)
end
def add_to_external_urls(url)
return if @external_urls[url]
add_path_for_url(url)
end
def add_path_for_url(url)
if @external_urls[url]
@external_urls[url] << @path
else
@external_urls[url] = [@path]
end
end
def self.subchecks
classes = []
ObjectSpace.each_object(Class) do |c|
next unless c.superclass == self
classes << c
end
classes
end
def blank?(attr)
attr.nil? || attr.empty?
end
private
def remove_ignored(html)
html.css('code, pre, tt').each(&:unlink)
html
end
end
end
| 21.46875 | 86 | 0.601892 |
d59ebe5b393635cad95491e614d8f60e52a50ae1 | 1,179 | #--
# Copyright (c) 2019 Fuyuki Academy
#
# 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.
#++
FactoryBot.define do
factory :assignment_essay_comment do
end
end
| 40.655172 | 72 | 0.771841 |
bf1ebdb4c5739f0cd4f703777566a39172652c6a | 8,726 | # frozen_string_literal: true
require "cases/helper"
module ActiveRecord
class Migration
class IndexTest < ActiveRecord::TestCase
attr_reader :connection, :table_name
def setup
super
@connection = ActiveRecord::Base.connection
@table_name = :testings
connection.create_table table_name do |t|
t.column :foo, :string, limit: 100
t.column :bar, :string, limit: 100
t.string :first_name
t.string :last_name, limit: 100
t.string :key, limit: 100
t.boolean :administrator
end
end
teardown do
connection.drop_table :testings rescue nil
ActiveRecord::Base.primary_key_prefix_type = nil
end
def test_rename_index
# keep the names short to make Oracle and similar behave
connection.add_index(table_name, [:foo], name: "old_idx")
connection.rename_index(table_name, "old_idx", "new_idx")
assert_deprecated do
assert_not connection.index_name_exists?(table_name, "old_idx", false)
assert connection.index_name_exists?(table_name, "new_idx", true)
end
end
def test_rename_index_too_long
too_long_index_name = good_index_name + "x"
# keep the names short to make Oracle and similar behave
connection.add_index(table_name, [:foo], name: "old_idx")
e = assert_raises(ArgumentError) {
connection.rename_index(table_name, "old_idx", too_long_index_name)
}
assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
assert connection.index_name_exists?(table_name, "old_idx")
end
def test_double_add_index
connection.add_index(table_name, [:foo], name: "some_idx")
assert_raises(ArgumentError) {
connection.add_index(table_name, [:foo], name: "some_idx")
}
end
def test_remove_nonexistent_index
assert_raise(ArgumentError) { connection.remove_index(table_name, "no_such_index") }
end
def test_add_index_works_with_long_index_names
connection.add_index(table_name, "foo", name: good_index_name)
assert connection.index_name_exists?(table_name, good_index_name)
connection.remove_index(table_name, name: good_index_name)
end
def test_add_index_does_not_accept_too_long_index_names
too_long_index_name = good_index_name + "x"
e = assert_raises(ArgumentError) {
connection.add_index(table_name, "foo", name: too_long_index_name)
}
assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
assert_not connection.index_name_exists?(table_name, too_long_index_name)
connection.add_index(table_name, "foo", name: good_index_name)
end
def test_internal_index_with_name_matching_database_limit
good_index_name = "x" * connection.index_name_length
connection.add_index(table_name, "foo", name: good_index_name, internal: true)
assert connection.index_name_exists?(table_name, good_index_name)
connection.remove_index(table_name, name: good_index_name)
end
def test_index_symbol_names
connection.add_index table_name, :foo, name: :symbol_index_name
assert connection.index_exists?(table_name, :foo, name: :symbol_index_name)
connection.remove_index table_name, name: :symbol_index_name
assert_not connection.index_exists?(table_name, :foo, name: :symbol_index_name)
end
def test_index_exists
connection.add_index :testings, :foo
assert connection.index_exists?(:testings, :foo)
assert !connection.index_exists?(:testings, :bar)
end
def test_index_exists_on_multiple_columns
connection.add_index :testings, [:foo, :bar]
assert connection.index_exists?(:testings, [:foo, :bar])
end
def test_index_exists_with_custom_name_checks_columns
connection.add_index :testings, [:foo, :bar], name: "my_index"
assert connection.index_exists?(:testings, [:foo, :bar], name: "my_index")
assert_not connection.index_exists?(:testings, [:foo], name: "my_index")
end
def test_valid_index_options
assert_raise ArgumentError do
connection.add_index :testings, :foo, unqiue: true
end
end
def test_unique_index_exists
connection.add_index :testings, :foo, unique: true
assert connection.index_exists?(:testings, :foo, unique: true)
end
def test_named_index_exists
connection.add_index :testings, :foo, name: "custom_index_name"
assert connection.index_exists?(:testings, :foo)
assert connection.index_exists?(:testings, :foo, name: "custom_index_name")
assert !connection.index_exists?(:testings, :foo, name: "other_index_name")
end
def test_remove_named_index
connection.add_index :testings, :foo, name: "custom_index_name"
assert connection.index_exists?(:testings, :foo)
connection.remove_index :testings, :foo
assert !connection.index_exists?(:testings, :foo)
end
def test_add_index_attribute_length_limit
connection.add_index :testings, [:foo, :bar], length: { foo: 10, bar: nil }
assert connection.index_exists?(:testings, [:foo, :bar])
end
def test_add_index
connection.add_index("testings", "last_name")
connection.remove_index("testings", "last_name")
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", column: ["last_name", "first_name"])
# Oracle adapter cannot have specified index name larger than 30 characters
# Oracle adapter is shortening index name when just column list is given
unless current_adapter?(:OracleAdapter)
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", name: :index_testings_on_last_name_and_first_name)
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", "last_name_and_first_name")
end
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name"], length: 10)
connection.remove_index("testings", "last_name")
connection.add_index("testings", ["last_name"], length: { last_name: 10 })
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], length: 10)
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], length: { last_name: 10, first_name: 20 })
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["key"], name: "key_idx", unique: true)
connection.remove_index("testings", name: "key_idx", unique: true)
connection.add_index("testings", %w(last_name first_name administrator), name: "named_admin")
connection.remove_index("testings", name: "named_admin")
# Selected adapters support index sort order
if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter)
connection.add_index("testings", ["last_name"], order: { last_name: :desc })
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc })
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc, first_name: :asc })
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], order: :desc)
connection.remove_index("testings", ["last_name", "first_name"])
end
end
if current_adapter?(:PostgreSQLAdapter)
def test_add_partial_index
connection.add_index("testings", "last_name", where: "first_name = 'john doe'")
assert connection.index_exists?("testings", "last_name")
connection.remove_index("testings", "last_name")
assert !connection.index_exists?("testings", "last_name")
end
end
private
def good_index_name
"x" * connection.allowed_index_name_length
end
end
end
end
| 39.844749 | 118 | 0.675567 |
21f824ae96eeaa647bdcd4bbf1f37537ccc4971c | 291 | test_cask 'with-zap-quit' do
version '1.2.3'
sha256 '8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b'
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage 'http://example.com/fancy-pkg'
pkg 'MyFancyPkg/Fancy.pkg'
zap quit: 'my.fancy.package.app'
end
| 24.25 | 75 | 0.756014 |
625fbc483029c000890adb1dec5ce9f6fa8ddb00 | 6,178 | # To add new service you should build a class inherited from Service
# and implement a set of methods
class Service < ActiveRecord::Base
include Sortable
serialize :properties, JSON
default_value_for :active, false
default_value_for :push_events, true
default_value_for :issues_events, true
default_value_for :confidential_issues_events, true
default_value_for :merge_requests_events, true
default_value_for :tag_push_events, true
default_value_for :note_events, true
default_value_for :build_events, true
default_value_for :pipeline_events, true
default_value_for :wiki_page_events, true
after_initialize :initialize_properties
after_commit :reset_updated_properties
after_commit :cache_project_has_external_issue_tracker
after_commit :cache_project_has_external_wiki
belongs_to :project, inverse_of: :services
has_one :service_hook
validates :project_id, presence: true, unless: Proc.new { |service| service.template? }
scope :visible, -> { where.not(type: ['GitlabIssueTrackerService', 'GitlabCiService']) }
scope :issue_trackers, -> { where(category: 'issue_tracker') }
scope :external_wikis, -> { where(type: 'ExternalWikiService').active }
scope :active, -> { where(active: true) }
scope :without_defaults, -> { where(default: false) }
scope :push_hooks, -> { where(push_events: true, active: true) }
scope :tag_push_hooks, -> { where(tag_push_events: true, active: true) }
scope :issue_hooks, -> { where(issues_events: true, active: true) }
scope :confidential_issue_hooks, -> { where(confidential_issues_events: true, active: true) }
scope :merge_request_hooks, -> { where(merge_requests_events: true, active: true) }
scope :note_hooks, -> { where(note_events: true, active: true) }
scope :build_hooks, -> { where(build_events: true, active: true) }
scope :pipeline_hooks, -> { where(pipeline_events: true, active: true) }
scope :wiki_page_hooks, -> { where(wiki_page_events: true, active: true) }
scope :external_issue_trackers, -> { issue_trackers.active.without_defaults }
default_value_for :category, 'common'
def activated?
active
end
def template?
template
end
def category
read_attribute(:category).to_sym
end
def initialize_properties
self.properties = {} if properties.nil?
end
def title
# implement inside child
end
def description
# implement inside child
end
def help
# implement inside child
end
def to_param
# implement inside child
end
def fields
# implement inside child
[]
end
def test_data(project, user)
Gitlab::DataBuilder::Push.build_sample(project, user)
end
def event_channel_names
[]
end
def event_names
supported_events.map { |event| "#{event}_events" }
end
def event_field(event)
nil
end
def global_fields
fields
end
def supported_events
%w(push tag_push issue confidential_issue merge_request wiki_page)
end
def execute(data)
# implement inside child
end
def test(data)
# default implementation
result = execute(data)
{ success: result.present?, result: result }
end
def can_test?
!project.empty_repo?
end
# reason why service cannot be tested
def disabled_title
"Please setup a project repository."
end
# Provide convenient accessor methods
# for each serialized property.
# Also keep track of updated properties in a similar way as ActiveModel::Dirty
def self.prop_accessor(*args)
args.each do |arg|
class_eval %{
def #{arg}
properties['#{arg}']
end
def #{arg}=(value)
self.properties ||= {}
updated_properties['#{arg}'] = #{arg} unless #{arg}_changed?
self.properties['#{arg}'] = value
end
def #{arg}_changed?
#{arg}_touched? && #{arg} != #{arg}_was
end
def #{arg}_touched?
updated_properties.include?('#{arg}')
end
def #{arg}_was
updated_properties['#{arg}']
end
}
end
end
# Provide convenient boolean accessor methods
# for each serialized property.
# Also keep track of updated properties in a similar way as ActiveModel::Dirty
def self.boolean_accessor(*args)
self.prop_accessor(*args)
args.each do |arg|
class_eval %{
def #{arg}?
ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(#{arg})
end
}
end
end
# Returns a hash of the properties that have been assigned a new value since last save,
# indicating their original values (attr => original value).
# ActiveRecord does not provide a mechanism to track changes in serialized keys,
# so we need a specific implementation for service properties.
# This allows to track changes to properties set with the accessor methods,
# but not direct manipulation of properties hash.
def updated_properties
@updated_properties ||= ActiveSupport::HashWithIndifferentAccess.new
end
def reset_updated_properties
@updated_properties = nil
end
def async_execute(data)
return unless supported_events.include?(data[:object_kind])
Sidekiq::Client.enqueue(ProjectServiceWorker, id, data)
end
def issue_tracker?
self.category == :issue_tracker
end
def self.available_services_names
%w[
asana
assembla
bamboo
buildkite
builds_email
pipelines_email
bugzilla
campfire
custom_issue_tracker
drone_ci
emails_on_push
external_wiki
flowdock
gemnasium
hipchat
irker
jira
pivotaltracker
pushover
redmine
slack
teamcity
]
end
def self.create_from_template(project_id, template)
service = template.dup
service.template = false
service.project_id = project_id
service if service.save
end
private
def cache_project_has_external_issue_tracker
if project && !project.destroyed?
project.cache_has_external_issue_tracker
end
end
def cache_project_has_external_wiki
if project && !project.destroyed?
project.cache_has_external_wiki
end
end
end
| 25.113821 | 95 | 0.696018 |
918e6a9eb774e04f2fbff7b089b19c6d0a3f3985 | 5,911 | require 'spec_helper'
describe 'cis_hardening::services::special' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
# Check for main class
it {
is_expected.to contain_class('cis_hardening::services::special')
}
# 2.2.1 - Time Synchronization
# Ensure Time Synchronization is in use - Section 2.2.1.1
it {
is_expected.to contain_package('ntp').with(
'ensure' => 'present',
)
}
# Ensure ntp is configured - Section 2.2.1.3
it {
is_expected.to contain_file('/etc/ntp.conf').with(
'ensure' => 'present',
'owner' => 'root',
'group' => 'root',
'mode' => '0644',
'source' => 'puppet:///modules/cis_hardening/etc_ntp_conf',
).that_requires('Package[ntp]')
}
it {
is_expected.to contain_file('/etc/sysconfig/ntpd').with(
'ensure' => 'present',
'owner' => 'root',
'group' => 'root',
'mode' => '0644',
'source' => 'puppet:///modules/cis_hardening/etc_sysconfig_ntpd',
).that_requires('File[/etc/ntp.conf]')
}
it {
is_expected.to contain_file_line('ntp_options').with(
'ensure' => 'present',
'path' => '/usr/lib/systemd/system/ntpd.service',
'line' => 'ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS',
'match' => '^ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS',
)
}
# Ensure X Window System is not installed - Section 2.2.2
it {
is_expected.to contain_package('xorg-x11-server-Xorg').with(
'ensure' => 'absent',
)
}
# Ensure Avahi Server is not enabled - Section 2.2.3
it {
is_expected.to contain_service('avahi-daemon').with(
'enable' => false,
)
}
it {
is_expected.to contain_service('avahi-autoipd').with
}
# Ensure CUPS is not enabled - Section 2.2.4
it {
is_expected.to contain_service('cups').with(
'enable' => false,
)
}
# Ensure DHCP Server is not enabled - Section 2.2.5
it {
is_expected.to contain_service('dhcpd').with(
'enable' => false,
)
}
# Ensure LDAP Server is not enabled - Section 2.2.6
it {
is_expected.to contain_service('slapd').with(
'enable' => false,
)
}
# Ensure NFS and RPC are not enabled - Section 2.2.7
it {
is_expected.to contain_service('nfs').with(
'enable' => false,
)
}
it {
is_expected.to contain_service('nfs-server').with(
'enable' => false,
)
}
it {
is_expected.to contain_service('rpcbind').with(
'enable' => false,
)
}
# Ensure DNS Server is not enabled - Section 2.2.8
it {
is_expected.to contain_service('named').with(
'enable' => false,
)
}
# Ensure FTP Server is not enabled - Section 2.2.9
it {
is_expected.to contain_service('vsftpd').with(
'enable' => false,
)
}
# Ensure HTTP Server is not enabled - Section 2.2.10
it {
is_expected.to contain_service('httpd').with(
'enable' => false,
)
}
# Ensure IMAP and POP3 Server are not enabled - Section 2.2.11
it {
is_expected.to contain_service('dovecot').with(
'enable' => false,
)
}
# Ensure Samba is not enabled - Section 2.2.12
it {
is_expected.to contain_service('smb').with(
'enable' => false,
)
}
# Ensure HTTP Proxy Server is not enabled - Section 2.2.13
it {
is_expected.to contain_service('squid').with(
'enable' => false,
)
}
# Ensure SNMP Server is not enabled - Section 2.2.14
it {
is_expected.to contain_service('snmpd').with(
'enable' => false,
)
}
# Ensure MTA is configured for local-only mode - Section 2.2.15
it {
is_expected.to contain_file_line('smptp_local_only_mode').with(
'ensure' => 'present',
'path' => '/etc/postfix/main.cf',
'line' => 'inet_interfaces = loopback-only',
'match' => '^inet_interfaces\ =',
)
}
# Ensure NIS Server is not enabled - Section 2.2.16
it {
is_expected.to contain_service('ypserv').with(
'enable' => false,
)
}
# Ensure RSH Server is not enabled - Section 2.2.17
it {
is_expected.to contain_service('rsh.socket').with(
'enable' => false,
)
}
it {
is_expected.to contain_service('rlogin.socket').with(
'enable' => false,
)
}
it {
is_expected.to contain_service('rexec.socket').with(
'enable' => false,
)
}
# Ensure Telnet Server is not enabled - Section 2.2.18
it {
is_expected.to contain_service('telnet.socket').with(
'enable' => false,
)
}
# Ensure tftp Server is not enabled - Section 2.2.19
it {
is_expected.to contain_service('tftp.socket').with(
'enable' => false,
)
}
# Ensure Rsync Service is not enabled - Section 2.2.20
it {
is_expected.to contain_service('rsyncd').with(
'enable' => false,
)
}
# Ensure Talk server is not enabled - Section 2.2.21
it {
is_expected.to contain_service('ntalk').with(
'enable' => false,
)
}
# Ensure manifest compiles with all dependencies
it {
is_expected.to compile.with_all_deps
}
end
end
end
| 25.812227 | 76 | 0.521401 |
1cb61208bfc0d907d6370e3ad2c925d2f71fc0f3 | 2,299 | require 'spec_helper'
describe OpenSSLExtensions::X509::Request do
subject { extended_certificate_request('geocerts') }
context 'subject_alternative_names' do
context 'on a CSR with SANs' do
subject { extended_certificate_request('sans') }
it 'returns a collection of the alternative names' do
subject.subject_alternative_names.should ==
['mail.sipchem.local',
'mail.sipchem.com',
'sipchem.com',
'autodiscover.sipchem.local',
'autodiscover.sipchem.com',
'sipc-cas01',
'sipc-cas02',
'sipchem.local' ]
end
end
context 'on a CSR without SANs' do
it 'returns an empty collection' do
subject.subject_alternative_names.should == []
end
end
end
context 'challenge_password?' do
context 'on a CSR with a challenge password' do
subject { extended_certificate_request('challenge') }
its(:challenge_password?) { should be_true }
end
context 'on a CSR without a challenge password' do
its(:challenge_password?) { should be_false }
end
end
context 'strength' do
it 'is 2048 bits' do
subject.strength.should == 2048
end
it 'is 1024 bits' do
extended_certificate_request('1024').strength.should == 1024
end
end
context 'equality (==)' do
it 'is true with matching PEMs' do
extended_certificate_request('geocerts').should ==
extended_certificate_request('geocerts')
end
it 'is false with mismatched PEMs' do
certificate = extended_certificate_request('geocerts')
certificate.should_receive(:to_pem).and_return('DIFFERENTPEM')
extended_certificate_request('geocerts').should_not == certificate
end
end
context 'in a collection, uniq' do
it 'removes duplicate certificates' do
[extended_certificate_request('geocerts'),
extended_certificate_request('geocerts')].uniq.should ==
[extended_certificate_request('geocerts')]
end
it 'does not modify non-duplicates' do
[extended_certificate_request('geocerts'),
extended_certificate_request('1024')].uniq.should ==
[extended_certificate_request('geocerts'),
extended_certificate_request('1024')]
end
end
end
| 29.474359 | 72 | 0.667247 |
b9aa54684215a63adb81e9668c8ec8a19f2dd3cd | 52 | module JsonMatchers
VERSION = "0.10.0".freeze
end
| 13 | 27 | 0.730769 |
bf56e1d5aea7de9d48c090dff7ea70b48d81b978 | 1,108 | #! /usr/bin/env ruby
#: Count trees on the way down with a toboggan
def read_map(filename)
hsize = (File.open(filename) { |f| next f.readline }).rstrip.size
res = Array.new(hsize)
File.open(filename) do |f|
f.each_line.each_with_index do |l, row|
res[row] = l.rstrip.each_char.map { |c| c == '#' ? 1 : 0 }
end
end
res
end
def count_trees(woods_map, v_step, h_step, v_start = 0, h_start = 0)
v = v_start
h = h_start
v_size = woods_map.size
h_size = woods_map[0].size
count = 0
while true
v = v + v_step
return count if v > v_size - 1
h = (h + h_step) % h_size
count += woods_map[v][h] # row first, then column
end
end
def main(argv)
filename = argv[0] || './input-day3.txt'
woods_map = read_map(filename)
trees_counts = [
count_trees(woods_map, 1, 1),
count_trees(woods_map, 1, 3),
count_trees(woods_map, 1, 5),
count_trees(woods_map, 1, 7),
count_trees(woods_map, 2, 1),
]
print "Trees encountered: #{trees_counts}\n"
print "Multiplied: #{trees_counts.reduce(1, :*)}\n"
0
end
if __FILE__ == $0
exit(main ARGV)
end
| 23.574468 | 68 | 0.636282 |
abf8fed81d93152bcea64842fb664b68ed39dfa0 | 2,181 | # The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory.
# config.active_storage.service = :test
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
Rails.application.routes.default_url_options =
config.action_mailer.default_url_options
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
config.middleware.use Clearance::BackDoor
config.active_job.queue_adapter = :test
end
| 35.754098 | 85 | 0.770747 |
337f381485e96c9a59ceb1898538b1057d770d8d | 2,193 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
require 'sinatra'
require_relative 'sinatra_test_cases'
require_relative '../../../helpers/exceptions'
include NewRelic::TestHelpers::Exceptions
configure do
# display exceptions so we see what's going on
disable :show_exceptions
# create a condition (sintra's version of a before_filter) that returns the
# value that was passed into it.
set :my_condition do |boolean|
condition do
halt 404 unless boolean
end
end
end
get '/' do
"root path"
end
get '/user/login' do
"please log in"
end
# this action will always return 404 because of the condition.
get '/user/:id', :my_condition => false do |id|
"Welcome #{id}"
end
get '/raise' do
raise "Uh-oh"
end
# check that pass works properly
set(:pass_condition) { |_| condition { pass { halt 418, "I'm a teapot." } } }
get('/pass', :pass_condition => true) {}
get '/pass' do
"I'm not a teapot."
end
error(NewRelic::TestHelpers::Exceptions::TestError) { halt 200, 'nothing happened' }
set(:error_condition) { |_| condition { raise NewRelic::TestHelpers::Exceptions::TestError } }
get('/error', :error_condition => true) {}
set(:precondition_check) do |_|
condition do
raise "Boo" if $precondition_already_checked
$precondition_already_checked = true
end
end
get('/precondition', :precondition_check => true) do
'precondition only happened once'
end
get '/route/:name' do |name|
# usually this would be a db test or something
pass if name != 'match'
'first route'
end
get '/route/no_match' do
'second route'
end
before '/filtered' do
@filtered = true
end
get '/filtered' do
@filtered ? 'got filtered' : 'nope'
end
newrelic_ignore '/ignored'
get '/ignored' do
"don't trace me bro"
end
get(/\/regex.*/) do
"Yeah, regex's!"
end
module Sinatra
class Application < Base
# Override to not accidentally start the app in at_exit handler
set :run, Proc.new { false }
end
end
class SinatraClassicTest < Minitest::Test
include SinatraTestCases
def app
Sinatra::Application
end
end
| 21.086538 | 94 | 0.705426 |
917ed0a038d5aff2b2c3c6091537d75fae22ed31 | 2,108 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Elasticsearch
module DSL
module Search
module Filters
# A filter which wraps a query so it can be used as a filter
#
# @example
#
# search do
# query do
# filtered do
# filter do
# query do
# query_string :title do
# query 'Ruby OR Python'
# end
# end
# end
# end
# end
# end
#
# @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-filter.html
#
class Query
include BaseComponent
def initialize(*args, &block)
super
if block
@query = Elasticsearch::DSL::Search::Query.new(*args, &block)
@block = nil
end
end
# Converts the query definition to a Hash
#
# @return [Hash]
#
def to_hash
hash = super
if @query
_query = @query.respond_to?(:to_hash) ? @query.to_hash : @query
hash[self.name].update(_query)
end
hash
end
end
end
end
end
end
| 29.277778 | 108 | 0.553605 |
bb56046aa9172864e8bf4f015e57d19e4fe87e14 | 212 | class AddUploadRefToInspectionsAndRoadways < ActiveRecord::Migration[5.2]
def change
add_reference :inspections, :upload, foreign_key: true
add_reference :roadways, :upload, foreign_key: true
end
end
| 30.285714 | 73 | 0.783019 |
f781b36535382cb81faac654d984e65d9e2364cf | 458 | Rails.application.routes.draw do
get 'home/index'
get 'home/tables_simple'
get 'home/data'
get 'home/dashboard'
devise_for :users, controllers: {
registrations: 'users/registrations', confirmations: 'users/confirmations'
}
devise_scope :user do
authenticated :user do
root 'home#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end
end | 20.818182 | 78 | 0.69214 |
e2eff528b6f6911c04d9af72104807984fe844a7 | 172 | class AddFieldsToSignUp < ActiveRecord::Migration
def change
add_column :users, :tos_accepted, :boolean
add_column :users, :camping_preferred, :boolean
end
end
| 24.571429 | 51 | 0.761628 |
bbe42305509a3c961c0bcada1dac7c91198bffe8 | 408 | module Invitable
extend ActiveSupport::Concern
included do
include InstanceMethods
end
module InstanceMethods
def attendances
invitations.accepted
end
def attending_students
invitations.where(role: "Student").accepted.order('updated_at asc')
end
def attending_coaches
invitations.where(role: "Coach").accepted.order('updated_at asc')
end
end
end
| 17 | 73 | 0.710784 |
aba07da209d858cbc395ebb44a34661753045688 | 425 | # Rahel: TimeSpan
# 2014-04-17 [email protected]
module Rahel
class TimeSpan < Individual
property "begin", :date, cardinality: 1
property "end", :date, cardinality: 1
property "display_as_year", :bool, cardinality: 1, default: true
property "time_span_label", :string, cardinality: 1
property "is_time_span_of", :objekt, range: "Rahel::Event", inverse: "ocurred_at", cardinality: 1
end
end
| 32.692308 | 101 | 0.712941 |
e9c129b3f2dae66313d2c9a7f23edc3a8002fd48 | 2,214 | # frozen_string_literal: true
#
# Cookbook:: vault_resources
# Resource:: vault_initialize
#
# See LICENSE file
#
resource_name :vault_initialize
provides :vault_initialize
unified_mode true
property :secret_shares, Integer, required: true, desired_state: false
property :secret_threshold, Integer, required: true, desired_state: false
property :print_sensitive, [true, false], default: false, desired_state: false
default_action :configure
load_current_value do
# Make sure the Vault client is configured prior to loading this resource
# Wait until vault has started
vault = VaultResources::ClientFactory.vault_client
begin
vault.with_retries(Vault::HTTPConnectionError, max_wait: 1, attempts: 10) do |attempt, e|
Chef::Log.warn("Received exception #{e} from Vault - attempt #{attempt}") unless e.nil?
vault.logical.read('sys/health')
end
rescue Vault::HTTPServerError => e_init
Chef::Log.warn("Response Code: #{e_init.code}")
# Response codes of 501 and 503 are ok, they represent uninitialized and sealed respectively
raise unless e_init.code == 501 || e_init.code == 503
current_value_does_not_exist! unless vault.sys.init_status.initialized?
rescue Vault::HTTPClientError => e_init
Chef::Log.warn("Response Code: #{e_init.code}")
# Response code(s) of 429 is ok, it represents a server in standby mode
raise unless e_init.code == 429
end
end
action :configure do
# Return if already initialized
vault = VaultResources::ClientFactory.vault_client
return if vault.sys.init_status.initialized?
Chef::Log.warn('Detected uninitialized Vault, running initialize now')
vault_init_response = vault.sys.init(secret_shares: new_resource.secret_shares, \
secret_threshold: new_resource.secret_threshold)
init_data = {
'keys' => vault_init_response.keys_base64,
'token' => vault_init_response.root_token,
}
node.run_state['vault_init_secrets'] = init_data
# Print to screen if it is a local run, since db item saves don't persist
# Only enable print_sensitive on local workstations
Chef::Log.warn("\n#{JSON.pretty_generate(init_data)}\n") \
if new_resource.print_sensitive
end
| 36.295082 | 96 | 0.743902 |
b99b9987eb2b15633abb51a7c9837e3084f7bff2 | 1,695 | class DevelopersController < ApplicationController
before_action :authenticate_user!, only: %i[new create edit update]
before_action :require_new_developer!, only: %i[new create]
def index
@developers_count = Developer.count.round(-1)
@query = DeveloperQuery.new(params)
end
def new
@developer = current_user.build_developer
end
def create
@developer = current_user.build_developer(developer_params)
if @developer.save
url = developer_path(@developer)
event = Analytics::Event.added_developer_profile(url)
redirect_to event, notice: t(".created")
else
render :new, status: :unprocessable_entity
end
end
def edit
@developer = Developer.find(params[:id])
authorize @developer
end
def update
@developer = Developer.find(params[:id])
authorize @developer
if @developer.update(developer_params)
redirect_to @developer, notice: t(".updated")
else
render :edit, status: :unprocessable_entity
end
end
def show
@developer = Developer.find(params[:id])
authorize @developer, policy_class: DeveloperPolicy
end
private
def require_new_developer!
if current_user.developer.present?
redirect_to edit_developer_path(current_user.developer)
end
end
def developer_params
params.require(:developer).permit(
:name,
:available_on,
:hero,
:bio,
:website,
:github,
:twitter,
:linkedin,
:avatar,
:cover_image,
:search_status,
location_attributes: [:city, :state, :country],
role_type_attributes: RoleType::TYPES,
role_level_attributes: RoleLevel::TYPES
)
end
end
| 22.905405 | 69 | 0.683186 |
183eb2bb3c78fd4a9407e18f3676e3bc3e6b717f | 11,221 | require File.expand_path(File.join(File.dirname(__FILE__), "test_helper"))
class RequestTest < Test::Unit::TestCase
context "Authrequest" do
should "create the deflated SAMLRequest URL parameter" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /^<samlp:AuthnRequest/, inflated
end
should "create the deflated SAMLRequest URL parameter including the Destination" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /<samlp:AuthnRequest[^<]* Destination='http:\/\/example.com'/, inflated
end
should "create the SAMLRequest URL parameter without deflating" do
settings = OneLogin::RubySaml::Settings.new
settings.compress_request = false
settings.idp_sso_target_url = "http://example.com"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
assert_match /^<samlp:AuthnRequest/, decoded
end
should "create the SAMLRequest URL parameter with IsPassive" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.passive = true
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /<samlp:AuthnRequest[^<]* IsPassive='true'/, inflated
end
should "create the SAMLRequest URL parameter with ProtocolBinding" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.protocol_binding = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /<samlp:AuthnRequest[^<]* ProtocolBinding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'/, inflated
end
should "create the SAMLRequest URL parameter with AttributeConsumingServiceIndex" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.attributes_index = 30
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /<samlp:AuthnRequest[^<]* AttributeConsumingServiceIndex='30'/, inflated
end
should "create the SAMLRequest URL parameter with ForceAuthn" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.force_authn = true
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example\.com\?SAMLRequest=/
payload = CGI.unescape(auth_url.split("=").last)
decoded = Base64.decode64(payload)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
inflated = zstream.inflate(decoded)
zstream.finish
zstream.close
assert_match /<samlp:AuthnRequest[^<]* ForceAuthn='true'/, inflated
end
should "accept extra parameters" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings, { :hello => "there" })
assert auth_url =~ /&hello=there$/
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings, { :hello => nil })
assert auth_url =~ /&hello=$/
end
context "when the target url doesn't contain a query string" do
should "create the SAMLRequest parameter correctly" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example.com\?SAMLRequest/
end
end
context "when the target url contains a query string" do
should "create the SAMLRequest parameter correctly" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com?field=value"
auth_url = OneLogin::RubySaml::Authrequest.new.create(settings)
assert auth_url =~ /^http:\/\/example.com\?field=value&SAMLRequest/
end
end
context "when the settings indicate to sign (embebed) the request" do
should "create a signed request" do
settings = OneLogin::RubySaml::Settings.new
settings.compress_request = false
settings.idp_sso_target_url = "http://example.com?field=value"
settings.security[:authn_requests_signed] = true
settings.security[:embed_sign] = true
settings.certificate = ruby_saml_cert_text
settings.private_key = ruby_saml_key_text
params = OneLogin::RubySaml::Authrequest.new.create_params(settings)
request_xml = Base64.decode64(params["SAMLRequest"])
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], request_xml
request_xml =~ /<ds:SignatureMethod Algorithm='http:\/\/www.w3.org\/2000\/09\/xmldsig#rsa-sha1'\/>/
request_xml =~ /<ds:DigestMethod Algorithm='http:\/\/www.w3.org\/2000\/09\/xmldsig#rsa-sha1'\/>/
end
should "create a signed request with 256 digest and signature methods" do
settings = OneLogin::RubySaml::Settings.new
settings.compress_request = false
settings.idp_sso_target_url = "http://example.com?field=value"
settings.security[:authn_requests_signed] = true
settings.security[:embed_sign] = true
settings.security[:signature_method] = XMLSecurity::Document::SHA256
settings.security[:digest_method] = XMLSecurity::Document::SHA512
settings.certificate = ruby_saml_cert_text
settings.private_key = ruby_saml_key_text
params = OneLogin::RubySaml::Authrequest.new.create_params(settings)
request_xml = Base64.decode64(params["SAMLRequest"])
assert_match %r[<ds:SignatureValue>([a-zA-Z0-9/+=]+)</ds:SignatureValue>], request_xml
request_xml =~ /<ds:SignatureMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmldsig-more#rsa-sha256'\/>/
request_xml =~ /<ds:DigestMethod Algorithm='http:\/\/www.w3.org\/2001\/04\/xmldsig-more#rsa-sha512'\/>/
end
end
context "when the settings indicate to sign the request" do
should "create a signature parameter" do
settings = OneLogin::RubySaml::Settings.new
settings.compress_request = false
settings.idp_sso_target_url = "http://example.com?field=value"
settings.assertion_consumer_service_binding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign"
settings.security[:authn_requests_signed] = true
settings.security[:embed_sign] = false
settings.security[:signature_method] = XMLSecurity::Document::SHA1
settings.certificate = ruby_saml_cert_text
settings.private_key = ruby_saml_key_text
params = OneLogin::RubySaml::Authrequest.new.create_params(settings)
assert params['Signature']
assert params['SigAlg'] == XMLSecurity::Document::SHA1
# signature_method only affects the embedeed signature
settings.security[:signature_method] = XMLSecurity::Document::SHA256
params = OneLogin::RubySaml::Authrequest.new.create_params(settings)
assert params['Signature']
assert params['SigAlg'] == XMLSecurity::Document::SHA1
end
end
should "create the saml:AuthnContextClassRef element correctly" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.authn_context = 'secure/name/password/uri'
auth_doc = OneLogin::RubySaml::Authrequest.new.create_authentication_xml_doc(settings)
assert auth_doc.to_s =~ /<saml:AuthnContextClassRef>secure\/name\/password\/uri<\/saml:AuthnContextClassRef>/
end
should "create the saml:AuthnContextClassRef with comparison exact" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.authn_context = 'secure/name/password/uri'
auth_doc = OneLogin::RubySaml::Authrequest.new.create_authentication_xml_doc(settings)
assert auth_doc.to_s =~ /<samlp:RequestedAuthnContext[\S ]+Comparison='exact'/
assert auth_doc.to_s =~ /<saml:AuthnContextClassRef>secure\/name\/password\/uri<\/saml:AuthnContextClassRef>/
end
should "create the saml:AuthnContextClassRef with comparison minimun" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.authn_context = 'secure/name/password/uri'
settings.authn_context_comparison = 'minimun'
auth_doc = OneLogin::RubySaml::Authrequest.new.create_authentication_xml_doc(settings)
assert auth_doc.to_s =~ /<samlp:RequestedAuthnContext[\S ]+Comparison='minimun'/
assert auth_doc.to_s =~ /<saml:AuthnContextClassRef>secure\/name\/password\/uri<\/saml:AuthnContextClassRef>/
end
should "create the saml:AuthnContextDeclRef element correctly" do
settings = OneLogin::RubySaml::Settings.new
settings.idp_sso_target_url = "http://example.com"
settings.authn_context_decl_ref = 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
auth_doc = OneLogin::RubySaml::Authrequest.new.create_authentication_xml_doc(settings)
assert auth_doc.to_s =~ /<saml:AuthnContextDeclRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport<\/saml:AuthnContextDeclRef>/
end
end
end
| 46.176955 | 151 | 0.698957 |
3802fff5a445f46a45333197fe9b61b13c95b8ce | 221 | # frozen_string_literal: true
module LogMarker
class << self
attr_accessor :ml_alias, :marker
def config
yield self
end
end
@ml_alias = :p!
@marker = -> { (['=' * 150] * 5).join("\n") }
end
| 14.733333 | 49 | 0.574661 |
61fec39bb9ba3d503fcd8137fe104bf71ec8b477 | 184 | maintainer "Opscode, Inc."
maintainer_email "[email protected]"
license "Apache 2.0"
description "LWRPs for managing AWS resources"
version "0.8"
| 30.666667 | 52 | 0.641304 |
01aa762694b18df71ed58d3a20ddf2c12f7bc072 | 382 | # encoding: utf-8
name 'bach_krb5'
maintainer 'Bloomberg Finance L.P.'
description 'Wrapper cookbook for krb5 community cookbook'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
depends 'krb5', '~> 2.0.0'
depends 'bcpc', '= 0.1.0'
depends 'bcpc-hadoop', '= 0.1.0'
%w(ubuntu).each do |os|
supports os
end
| 23.875 | 72 | 0.643979 |
618a4844d27dc855d8361b40a3a499c5627a9a39 | 567 | #encoding: utf-8
##
## config.rb
## Gaetan JUVIN 27/07/2015
##
require 'logger'
require 'gconfig'
module Rabbitmq
class Receiver
extend GConfig
default logger: Logger.new(STDOUT)
default host: '8.8.8.8'
default port: 5672
default user: nil
default password: nil
default queue: nil
default vhost: '/'
default verbose: false
default prefetch: 100
default durable: true
default exclusive: false
default heartbeat: 5
default auto_delete: false
end
end
| 19.551724 | 43 | 0.608466 |
f7c9fed22bdeae13e26d5f6e8c2cd0e1ce8f5491 | 9,027 | require File.dirname(__FILE__) + '/migs/migs_codes'
require 'digest/md5' # Used in add_secure_hash
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class MigsGateway < Gateway
include MigsCodes
API_VERSION = 1
SERVER_HOSTED_URL = 'https://migs.mastercard.com.au/vpcpay'
MERCHANT_HOSTED_URL = 'https://migs.mastercard.com.au/vpcdps'
# MiGS is supported throughout Asia Pacific, Middle East and Africa
# MiGS is used in Australia (AU) by ANZ (eGate), CBA (CommWeb) and more
# Source of Country List: http://www.scribd.com/doc/17811923
self.supported_countries = %w(AU AE BD BN EG HK ID IN JO KW LB LK MU MV MY NZ OM PH QA SA SG TT VN)
# The card types supported by the payment gateway
self.supported_cardtypes = [:visa, :master, :american_express, :diners_club, :jcb]
self.money_format = :cents
# The homepage URL of the gateway
self.homepage_url = 'http://mastercard.com/mastercardsps'
# The name of the gateway
self.display_name = 'MasterCard Internet Gateway Service (MiGS)'
# Creates a new MigsGateway
# The advanced_login/advanced_password fields are needed for
# advanced methods such as the capture, refund and status methods
#
# ==== Options
#
# * <tt>:login</tt> -- The MiGS Merchant ID (REQUIRED)
# * <tt>:password</tt> -- The MiGS Access Code (REQUIRED)
# * <tt>:secure_hash</tt> -- The MiGS Secure Hash
# (Required for Server Hosted payments)
# * <tt>:advanced_login</tt> -- The MiGS AMA User
# * <tt>:advanced_password</tt> -- The MiGS AMA User's password
def initialize(options = {})
requires!(options, :login, :password)
@test = options[:login].start_with?('TEST')
@options = options
super
end
# ==== Options
#
# * <tt>:order_id</tt> -- A reference for tracking the order (REQUIRED)
# * <tt>:unique_id</tt> -- A unique id for this request (Max 40 chars).
# If not supplied one will be generated.
def purchase(money, creditcard, options = {})
requires!(options, :order_id)
post = {}
post[:Amount] = amount(money)
add_invoice(post, options)
add_creditcard(post, creditcard)
add_standard_parameters('pay', post, options[:unique_id])
commit(post)
end
# MiGS works by merchants being either purchase only or authorize/capture
# So authorize is the same as purchase when in authorize mode
alias_method :authorize, :purchase
# ==== Options
#
# * <tt>:unique_id</tt> -- A unique id for this request (Max 40 chars).
# If not supplied one will be generated.
def capture(money, authorization, options = {})
requires!(@options, :advanced_login, :advanced_password)
post = options.merge(:TransNo => authorization)
post[:Amount] = amount(money)
add_advanced_user(post)
add_standard_parameters('capture', post, options[:unique_id])
commit(post)
end
# ==== Options
#
# * <tt>:unique_id</tt> -- A unique id for this request (Max 40 chars).
# If not supplied one will be generated.
def refund(money, authorization, options = {})
requires!(@options, :advanced_login, :advanced_password)
post = options.merge(:TransNo => authorization)
post[:Amount] = amount(money)
add_advanced_user(post)
add_standard_parameters('refund', post, options[:unique_id])
commit(post)
end
def credit(money, authorization, options = {})
deprecated CREDIT_DEPRECATION_MESSAGE
refund(money, authorization, options)
end
# Checks the status of a previous transaction
# This can be useful when a response is not received due to network issues
#
# ==== Parameters
#
# * <tt>unique_id</tt> -- Unique id of transaction to find.
# This is the value of the option supplied in other methods or
# if not supplied is returned with key :MerchTxnRef
def status(unique_id)
requires!(@options, :advanced_login, :advanced_password)
post = {}
add_advanced_user(post)
add_standard_parameters('queryDR', post, unique_id)
commit(post)
end
# Generates a URL to redirect user to MiGS to process payment
# Once user is finished MiGS will redirect back to specified URL
# With a response hash which can be turned into a Response object
# with purchase_offsite_response
#
# ==== Options
#
# * <tt>:order_id</tt> -- A reference for tracking the order (REQUIRED)
# * <tt>:locale</tt> -- Change the language of the redirected page
# Values are 2 digit locale, e.g. en, es
# * <tt>:return_url</tt> -- the URL to return to once the payment is complete
# * <tt>:card_type</tt> -- Providing this skips the card type step.
# Values are ActiveMerchant formats: e.g. master, visa, american_express, diners_club
# * <tt>:unique_id</tt> -- Unique id of transaction to find.
# If not supplied one will be generated.
def purchase_offsite_url(money, options = {})
requires!(options, :order_id, :return_url)
requires!(@options, :secure_hash)
post = {}
post[:Amount] = amount(money)
add_invoice(post, options)
add_creditcard_type(post, options[:card_type]) if options[:card_type]
post.merge!(
:Locale => options[:locale] || 'en',
:ReturnURL => options[:return_url]
)
add_standard_parameters('pay', post, options[:unique_id])
add_secure_hash(post)
SERVER_HOSTED_URL + '?' + post_data(post)
end
# Parses a response from purchase_offsite_url once user is redirected back
#
# ==== Parameters
#
# * <tt>data</tt> -- All params when offsite payment returns
# e.g. returns to http://company.com/return?a=1&b=2, then input "a=1&b=2"
def purchase_offsite_response(data)
requires!(@options, :secure_hash)
response_hash = parse(data)
expected_secure_hash = calculate_secure_hash(response_hash.reject{|k, v| k == :SecureHash}, @options[:secure_hash])
unless response_hash[:SecureHash] == expected_secure_hash
raise SecurityError, "Secure Hash mismatch, response may be tampered with"
end
response_object(response_hash)
end
private
def add_advanced_user(post)
post[:User] = @options[:advanced_login]
post[:Password] = @options[:advanced_password]
end
def add_invoice(post, options)
post[:OrderInfo] = options[:order_id]
end
def add_creditcard(post, creditcard)
post[:CardNum] = creditcard.number
post[:CardSecurityCode] = creditcard.verification_value if creditcard.verification_value?
post[:CardExp] = format(creditcard.year, :two_digits) + format(creditcard.month, :two_digits)
end
def add_creditcard_type(post, card_type)
post[:Gateway] = 'ssl'
post[:card] = CARD_TYPES.detect{|ct| ct.am_code == card_type}.migs_long_code
end
def parse(body)
params = CGI::parse(body)
hash = {}
params.each do |key, value|
hash[key.gsub('vpc_', '').to_sym] = value[0]
end
hash
end
def commit(post)
data = ssl_post MERCHANT_HOSTED_URL, post_data(post)
response_hash = parse(data)
response_object(response_hash)
end
def response_object(response)
Response.new(success?(response), response[:Message], response,
:test => @test,
:authorization => response[:TransactionNo],
:fraud_review => fraud_review?(response),
:avs_result => { :code => response[:AVSResultCode] },
:cvv_result => response[:CSCResultCode]
)
end
def success?(response)
response[:TxnResponseCode] == '0'
end
def fraud_review?(response)
ISSUER_RESPONSE_CODES[response[:AcqResponseCode]] == 'Suspected Fraud'
end
def add_standard_parameters(action, post, unique_id = nil)
post.merge!(
:Version => API_VERSION,
:Merchant => @options[:login],
:AccessCode => @options[:password],
:Command => action,
:MerchTxnRef => unique_id || generate_unique_id.slice(0, 40)
)
end
def post_data(post)
post.collect { |key, value| "vpc_#{key}=#{CGI.escape(value.to_s)}" }.join("&")
end
def add_secure_hash(post)
post[:SecureHash] = calculate_secure_hash(post, @options[:secure_hash])
end
def calculate_secure_hash(post, secure_hash)
sorted_values = post.sort_by(&:to_s).map(&:last)
input = secure_hash + sorted_values.join
Digest::MD5.hexdigest(input).upcase
end
end
end
end
| 34.719231 | 123 | 0.624792 |
188f46edb5921e4be13271d83784ba412352af23 | 365 | class AddRatingOfDifficultyToQuestions < ActiveRecord::Migration[4.2]
def self.up
add_column :questions, :average_difficulty_rating, :float, default: 0
add_column :questions, :number_of_ratings, :integer, default: 0
end
def self.down
remove_column :questions, :number_of_ratings
remove_column :questions, :average_difficulty_rating
end
end
| 30.416667 | 73 | 0.775342 |
e93d4a0414dfbdb37d57103ef8d67be2d87f7035 | 965 | Pod::Spec.new do |s|
s.name = "HHStringAttributes"
s.version = "0.1.0"
s.summary = "A simple Attributes Library."
s.description = <<-DESC
Makes it way easier to generate attribute dictionaries needed for NSAttributedString.
DESC
s.homepage = "https://github.com/WaterSource/HHStringAttributes"
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "何源" => "[email protected]"}
s.source = { :git => "https://github.com/WaterSource/HHStringAttributes.git", :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.source_files = 'HHStringAttributes/Classes/*.{h,m}'
#s.resources = "YFPhotoAlbum/Assets/*.png"
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit'
s.dependency 'Slash', '~> 0.1.4'
end
| 38.6 | 114 | 0.59171 |
ff12ec28459b03d22990ac0329afb39facd5c699 | 570 | module ApplicationHelper
def footer_class
'page-footer row bg-dark text-white'
end
def main_col_class(text)
content_for :main_col_class, text
end
def title(text)
content_for :title, text
end
def body_container_class
"container mt-5"
end
def card_header
content_tag :div, class: card_header_class do
yield
end
end
def card_title_class
"card-title mt-3 text-center"
end
def err
content_for :err do
yield
end
end
end
| 16.285714 | 53 | 0.592982 |
ed572c14bd28533e123071e206b72f7b606d5263 | 727 | name 'mszlx_baseline'
maintainer 'The Authors'
maintainer_email '[email protected]'
license 'All Rights Reserved'
description 'Installs/Configures mszlx_baseline'
version '0.1.0'
chef_version '>= 14.0'
# The `issues_url` points to the location where issues for this cookbook are
# tracked. A `View Issues` link will be displayed on this cookbook's page when
# uploaded to a Supermarket.
#
# issues_url 'https://github.com/<insert_org_here>/mszlx_baseline/issues'
# The `source_url` points to the development repository for this cookbook. A
# `View Source` link will be displayed on this cookbook's page when uploaded to
# a Supermarket.
#
# source_url 'https://github.com/<insert_org_here>/mszlx_baseline'
depends 'iptables' | 34.619048 | 79 | 0.775791 |
ff7a68b15e6bc9d9341e3116a2f4802a02ea934e | 233 | class CoupError < StandardError
end
class CommandError < CoupError
end
class ValidationError < CoupError
end
class InternalError < StandardError
end
class CallError < InternalError
end
class ConfigError < InternalError
end | 10.130435 | 35 | 0.802575 |
623deae99926149337ff1ccf667a0ae564079f7a | 1,184 | # Cookbook Name:: travis_php
# Recipe:: default
# Copyright 2011-2015, Travis CI GmbH <[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.
| 53.818182 | 79 | 0.779561 |
1c0a2b63d7ea69916b73ec2926324453cb5b9618 | 3,298 | module Fog
module Compute
class AWS
class Real
require 'fog/aws/parsers/compute/describe_tags'
# Describe all or specified tags
#
# ==== Parameters
# * filters<~Hash> - List of filters to limit results with
#
# === Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * 'requestId'<~String> - Id of request
# * 'tagSet'<~Array>:
# * 'resourceId'<~String> - id of resource tag belongs to
# * 'resourceType'<~String> - type of resource tag belongs to
# * 'key'<~String> - Tag's key
# * 'value'<~String> - Tag's value
#
# {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html]
def describe_tags(filters = {})
params = Fog::AWS.indexed_filters(filters)
request({
'Action' => 'DescribeTags',
:idempotent => true,
:parser => Fog::Parsers::Compute::AWS::DescribeTags.new
}.merge!(params))
end
end
class Mock
def describe_tags(filters = {})
response = Excon::Response.new
tag_set = deep_clone(self.data[:tags])
aliases = {
'key' => 'key',
'resource-id' => 'resourceId',
'resource-type' => 'resourceType',
'value' => 'value'
}
for filter_key, filter_value in filters
filter_attribute = aliases[filter_key]
case filter_attribute
when 'key'
tag_set.reject! { |k,_| k != filter_value }
when 'value'
tag_set.each { |k,values| values.reject! { |v, _| v != filter_value } }
when 'resourceId'
filter_resources(tag_set, 'resourceId', filter_value)
when 'resourceType'
filter_resources(tag_set, 'resourceType', filter_value)
end
end
tagged_resources = []
tag_set.each do |key, values|
values.each do |value, resources|
resources.each do |resource|
tagged_resources << resource.merge({
'key' => key,
'value' => value
})
end
end
end
response.status = 200
response.body = {
'requestId' => Fog::AWS::Mock.request_id,
'tagSet' => tagged_resources
}
response
end
private
def filter_resources(tag_set, filter, value)
value_hash_list = tag_set.values
value_hash_list.each do |value_hash|
value_hash.each do |_, resource_list|
resource_list.reject! { |resource| resource[filter] != value }
end
end
end
def deep_clone(obj)
case obj
when Hash
obj.inject({}) { |h, pair| h[pair.first] = deep_clone(pair.last); h }
when Array
obj.map { |o| deep_clone(o) }
else
obj
end
end
end
end
end
end
| 30.537037 | 131 | 0.487871 |
0127ec69650527f17df476a629529fb04e400b00 | 361 | class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "testing"
end
get '/' do
erb :index
end
helpers do
def logged_in?
!!session[:user_id]
end
def current_user
User.find(session[:user_id])
end
end
end
| 14.44 | 43 | 0.628809 |
f8a9384d996557a4b3b8eda7c87658dca900782b | 338 | # frozen_string_literal: true
class ViteRuby::CLI::Dev < ViteRuby::CLI::Build
DEFAULT_ENV = CURRENT_ENV || 'development'
desc 'Start the Vite development server.'
shared_options
option(:force, desc: 'Force Vite to re-bundle dependencies', type: :boolean)
def call(**options)
super { |args| ViteRuby.run(args) }
end
end
| 24.142857 | 78 | 0.713018 |
ff5a8b564d6b535e421faa9cdf9963acd64d926f | 2,956 | # 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::Network::Mgmt::V2016_12_01
module Models
#
# Response for ListAuthorizations API service call retrieves all
# authorizations that belongs to an ExpressRouteCircuit.
#
class AuthorizationListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<ExpressRouteCircuitAuthorization>] The authorizations in
# an ExpressRoute Circuit.
attr_accessor :value
# @return [String] The URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<ExpressRouteCircuitAuthorization>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [AuthorizationListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for AuthorizationListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'AuthorizationListResult',
type: {
name: 'Composite',
class_name: 'AuthorizationListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCircuitAuthorizationElementType',
type: {
name: 'Composite',
class_name: 'ExpressRouteCircuitAuthorization'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.267327 | 85 | 0.548038 |
9131513d1dbf1850baac1c4fdf218ffa8d998aa6 | 570 | cask :v1 => 'visual-studio-code' do
version '0.10.2'
sha256 '3371bff1e11daa49ad77ad1eed683d1baaf073477c1baff20626250d5ee6153e'
# vo.msecnd.net is the official download host per the vendor homepage
url "https://az764295.vo.msecnd.net/public/#{version}/VSCode-darwin.zip"
name 'Visual Studio Code'
homepage 'https://code.visualstudio.com/'
license :mit
tags :vendor => 'Microsoft'
app 'Visual Studio Code.app'
zap :delete => [
'~/Library/Application Support/Code',
'~/Library/Caches/Code',
]
end
| 30 | 75 | 0.661404 |
61ee7a44b0aa0db382b96bbf6461fc3078119be0 | 318 | class SponsorPolicy < ApplicationPolicy
def index?
is_admin_or_chapter_organiser?
end
def create?
is_admin_or_chapter_organiser?
end
def show?
is_admin_or_chapter_organiser?
end
def edit?
is_admin_or_chapter_organiser?
end
def update?
is_admin_or_chapter_organiser?
end
end
| 14.454545 | 39 | 0.748428 |
5ddcd24dcfa77b077098c2bb6f51b75314cbfb53 | 4,654 | # Copyright 2018 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.
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'google/compute/property/instancegroup_named_ports'
require 'google/compute/property/integer'
require 'google/compute/property/network_selflink'
require 'google/compute/property/region_selflink'
require 'google/compute/property/string'
require 'google/compute/property/subnetwork_selflink'
require 'google/compute/property/time'
require 'google/compute/property/zone_name'
require 'google/object_store'
require 'puppet'
Puppet::Type.newtype(:gcompute_instance_group) do
@doc = <<-DOC
Represents an Instance Group resource. Instance groups are self-managed and can contain
identical or different instances. Instance groups do not use an instance template. Unlike
managed instance groups, you must create and add instances to an instance group manually.
DOC
autorequire(:gauth_credential) do
credential = self[:credential]
raise "#{ref}: required property 'credential' is missing" if credential.nil?
[credential]
end
autorequire(:gcompute_zone) do
reference = self[:zone]
raise "#{ref} required property 'zone' is missing" if reference.nil?
reference.autorequires
end
ensurable
newparam :credential do
desc <<-DESC
A gauth_credential name to be used to authenticate with Google Cloud
Platform.
DESC
end
newparam(:project) do
desc 'A Google Cloud Platform project to manage.'
end
newparam(:name, namevar: true) do
# TODO(nelsona): Make this description to match the key of the object.
desc 'The name of the InstanceGroup.'
end
newparam(:zone, parent: Google::Compute::Property::ZoneNameRef) do
desc 'A reference to the zone where the instance group resides.'
end
newproperty(:creation_timestamp, parent: Google::Compute::Property::Time) do
desc 'Creation timestamp in RFC3339 text format. (output only)'
end
newproperty(:description, parent: Google::Compute::Property::String) do
desc <<-DOC
An optional description of this resource. Provide this property when you create the resource.
DOC
end
newproperty(:id, parent: Google::Compute::Property::Integer) do
desc 'A unique identifier for this instance group. (output only)'
end
newproperty(:name, parent: Google::Compute::Property::String) do
desc <<-DOC
The name of the instance group. The name must be 1-63 characters long, and comply with
RFC1035.
DOC
end
newproperty(:named_ports, parent: Google::Compute::Property::InstanceGroupNamedPortsArray) do
desc <<-DOC
Assigns a name to a port number. For example: {name: "http", port: 80}. This allows the
system to reference ports by the assigned name instead of a port number. Named ports can also
contain multiple ports. For example: [{name: "http", port: 80},{name: "http", port: 8080}]
Named ports apply to all instances in this instance group.
DOC
end
newproperty(:network, parent: Google::Compute::Property::NetworkSelfLinkRef) do
desc 'The network to which all instances in the instance group belong.'
end
newproperty(:region, parent: Google::Compute::Property::RegionSelfLinkRef) do
desc 'The region where the instance group is located (for regional resources).'
end
newproperty(:subnetwork, parent: Google::Compute::Property::SubnetworkSelfLinkRef) do
desc 'The subnetwork to which all instances in the instance group belong.'
end
# Returns all properties that a provider can export to other resources
def exports
provider.exports
end
end
| 36.645669 | 99 | 0.698539 |
e84d0015e6722cda97d640d75bd4238659950d04 | 1,169 | # 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::Scheduler::Mgmt::V2016_03_01
module Models
#
# Model object.
#
#
class Sku
include MsRestAzure
# @return [SkuDefinition] Gets or set the SKU. Possible values include:
# 'Standard', 'Free', 'P10Premium', 'P20Premium'
attr_accessor :name
#
# Mapper for Sku class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Sku',
type: {
name: 'Composite',
class_name: 'Sku',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'Enum',
module: 'SkuDefinition'
}
}
}
}
}
end
end
end
end
| 23.38 | 77 | 0.518392 |
1c38d42269a4744cf533091e546ece44b8cb4dab | 1,407 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "brcobranca/version"
Gem::Specification.new do |s|
s.name = "brcobranca"
s.version = Brcobranca::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Kivanio Barbosa"]
s.date = %q{2011-04-14}
s.description = %q{Gem para emissão de bloquetos de cobrança de bancos brasileiros.}
s.summary = %q{Gem que permite trabalhar com bloquetos de cobrança para bancos brasileiros.}
s.email = %q{[email protected]}
s.homepage = %q{http://rubygems.org/gems/brcobranca}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.requirements = ["GhostScript > 8.0, para gear PDF e c\303\263digo de Barras"]
s.rubyforge_project = "brcobranca"
s.add_runtime_dependency(%q<rghost>, [">= 0.8.7"])
s.add_runtime_dependency(%q<rghost_barcode>, [">= 0.8"])
s.add_runtime_dependency(%q<parseline>, [">= 1.0.3"])
s.add_runtime_dependency(%q<activemodel>, [">= 3.0.0"])
s.post_install_message = %[
===========================================================================
Visite http://www.boletorails.com.br para ver exemplos!
===========================================================================
]
end | 41.382353 | 94 | 0.5828 |
2861e613f7758bc4ce7a6f28e68fac815bd5f31f | 1,645 | ActionController::Routing::Routes.draw do |map|
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Default request should redirect to login
map.connect '', :controller => 'bodysize', :action => 'home'
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
| 42.179487 | 113 | 0.67234 |
1a0dd99c8e54d9e071db254969caf2e7578d0555 | 405 | class CreateMailees < ActiveRecord::Migration
def self.up
create_table :mailees, :force => true, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8' do |t|
t.column :user_id, :integer
t.column :email, :string
t.timestamp :created_at
end
add_index :mailees, :user_id
end
def self.down
if table_exists?(:mailees)
drop_table :mailees
end
end
end
| 23.823529 | 98 | 0.646914 |
62ab001d2b10b4ecbb655793a259088d70a0e3dc | 1,929 | #!/usr/bin/env gem build
# encoding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sneakers/version'
Gem::Specification.new do |gem|
gem.name = 'sneakers'
gem.version = Sneakers::VERSION
gem.authors = ['Dotan Nahum']
gem.email = ['[email protected]']
gem.description = %q( Fast background processing framework for Ruby and RabbitMQ )
gem.summary = %q( Fast background processing framework for Ruby and RabbitMQ )
gem.homepage = 'https://github.com/jondot/sneakers'
gem.license = 'MIT'
gem.required_ruby_version = Gem::Requirement.new(">= 2.2")
gem.files = `git ls-files`.split($/).reject { |f| f == 'Gemfile.lock' }
gem.executables = gem.files.grep(/^bin/).
reject { |f| f =~ /^bin\/ci/ }.
map { |f| File.basename(f) }
gem.test_files = gem.files.grep(/^(test|spec|features)\//)
gem.require_paths = ['lib']
gem.add_dependency 'serverengine', '~> 2.1.0'
gem.add_dependency 'bunny', '~> 2.14'
gem.add_dependency 'concurrent-ruby', '~> 1.0'
gem.add_dependency 'thor'
gem.add_dependency 'rake', '>= 12.3'
# for integration environment (see .travis.yml and integration_spec)
gem.add_development_dependency 'rabbitmq_http_api_client'
gem.add_development_dependency 'redis'
gem.add_development_dependency 'minitest', '~> 5.11'
gem.add_development_dependency 'rr', '~> 1.2.1'
gem.add_development_dependency 'unparser', '0.2.2' # keep below 0.2.5 for ruby 2.0 compat.
gem.add_development_dependency 'metric_fu', '~> 4.12'
gem.add_development_dependency 'simplecov', '~> 0.16'
gem.add_development_dependency 'simplecov-rcov-text'
gem.add_development_dependency 'guard', '~> 2.15'
gem.add_development_dependency 'guard-minitest', '~> 2.4'
gem.add_development_dependency 'pry-byebug', '~> 3.7'
end
| 41.934783 | 92 | 0.667185 |
217db36bc11fe8caa7021ae674d82627470f8919 | 661 | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
Courses::Application.config.secret_key_base = 'c0651ea13e0eca33ae888c0a0beeb08966caede86770c5486fdd0d9c6e6ddd398ff3d31a112274d46cf20ad18ccb9a7d4598889aff9dcd9af978ea8113e67b29'
| 50.846154 | 176 | 0.815431 |
1d0478869c31a7ff4751765cbf542df6382fc254 | 3,842 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'aws-sdk-iam'
class MetasploitModule < Msf::Auxiliary
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Amazon Web Services IAM credential enumeration',
'Description' => %q(
Provided AWS credentials, this module will call the authenticated
API of Amazon Web Services to list all IAM credentials associated
with the account
),
'Author' => ['Aaron Soto <[email protected]>'],
'License' => MSF_LICENSE
)
)
register_options(
[
OptString.new('ACCESS_KEY_ID', [true, 'AWS Access Key ID (eg. "AKIAXXXXXXXXXXXXXXXX")', '']),
OptString.new('SECRET_ACCESS_KEY', [true, 'AWS Secret Access Key (eg. "CA1+XXXXXXXXXXXXXXXXXXXXXX6aYDHHCBuLuV79")', ''])
]
)
end
def handle_aws_errors(e)
if e.class.module_parents.include?(Aws)
fail_with(Failure::UnexpectedReply, e.message)
else
raise e
end
end
def describe_iam_users(i)
user = i.user_name
print_good " User Name: #{user}"
print_good " User ID: #{i.user_id}"
print_good " Creation Date: #{i.create_date}"
print_good " Tags: #{i.tags}"
print_good " Groups: #{i.group_list}"
print_good " SSH Pub Keys: #{@iam.list_ssh_public_keys(user_name: user).ssh_public_keys}"
policies = i.attached_managed_policies
if policies.empty?
print_good " Policies: []"
else
print_good " Policies: #{policies[0].policy_name}"
policies[1..policies.length].each do |p|
print_good " #{p.policy_name}"
end
end
certs = @iam.list_signing_certificates(user_name: user).certificates
if certs.empty?
print_good " Signing certs: []"
else
print_good " Signing certs: #{certs[0].certificate_id} (#{certs[0].status})"
certs[1..certs.length].each do |c|
print_good " #{c.certificate_id} (#{c.status})"
end
end
@users.each do |u|
if u.user_name == user
print_good " Password Used: #{u.password_last_used || '(Never)'}"
end
end
keys = @iam.list_access_keys(user_name: user).access_key_metadata
if keys.empty?
print_good " AWS Access Keys: []"
else
print_good " AWS Access Keys: #{keys[0].access_key_id} (#{keys[0].status})"
keys[1..keys.length].each do |k|
print_good " #{k.access_key_id} (#{k.status})"
end
end
begin
console_login = @iam.get_login_profile(user_name: user).empty? ? 'Disabled' : 'Enabled'
print_good " Console login: #{console_login}"
rescue Aws::IAM::Errors::NoSuchEntity
print_good " Console login: Disabled"
end
mfa = @iam.list_mfa_devices(user_name: i.user_name).mfa_devices
mfa_enabled = mfa.empty? ? 'Disabled' : "Enabled on #{mfa[0].enable_date}"
print_good " Two-factor auth: #{mfa_enabled}"
print_status ''
end
def run
@iam = Aws::IAM::Client.new(
region: 'us-west-1', # This is meaningless, but required. Thanks AWS.
access_key_id: datastore['ACCESS_KEY_ID'],
secret_access_key: datastore['SECRET_ACCESS_KEY']
)
@users = @iam.list_users.users
creds = @iam.get_account_authorization_details
users = creds.user_detail_list
if users.empty?
print_status 'No users found.'
return
end
print_good "Found #{users.count} users."
users.each do |i|
describe_iam_users(i)
end
rescue ::Exception => e
handle_aws_errors(e)
end
end
| 30.983871 | 128 | 0.603071 |
e844c7f8d4a293c3dc32f4e5e9e1dc1620ff53dc | 23,357 | require 'java'
require 'rbconfig'
require 'test/unit'
TopLevelConstantExistsProc = Proc.new do
include_class 'java.lang.String'
end
class TestHigherJavasupport < Test::Unit::TestCase
TestHelper = org.jruby.test.TestHelper
JArray = ArrayList = java.util.ArrayList
FinalMethodBaseTest = org.jruby.test.FinalMethodBaseTest
Annotation = java.lang.annotation.Annotation
ClassWithPrimitive = org.jruby.test.ClassWithPrimitive
def test_java_int_primitive_assignment
assert_nothing_raised {
cwp = ClassWithPrimitive.new
cwp.an_int = nil
assert_equal 0, cwp.an_int
}
end
def test_java_passing_class
assert_equal("java.util.ArrayList", TestHelper.getClassName(ArrayList))
end
@@include_java_lang = Proc.new {
include_package "java.lang"
java_alias :JavaInteger, :Integer
}
def test_java_class_loading_and_class_name_collisions
assert_raises(NameError) { System }
@@include_java_lang.call
assert_nothing_raised { System }
assert_equal(10, JavaInteger.new(10).intValue)
assert_raises(NoMethodError) { Integer.new(10) }
end
Random = java.util.Random
Double = java.lang.Double
def test_constructors_and_instance_methods
r = Random.new
assert_equal(Random, r.class)
r = Random.new(1001)
assert_equal(10.0, Double.new(10).doubleValue())
assert_equal(10.0, Double.new("10").doubleValue())
assert_equal(Random, r.class)
assert_equal(Fixnum, r.nextInt.class)
assert_equal(Fixnum, r.nextInt(10).class)
end
Long = java.lang.Long
def test_instance_methods_differing_only_on_argument_type
l1 = Long.new(1234)
l2 = Long.new(1000)
assert(l1.compareTo(l2) > 0)
end
def test_dispatching_on_nil
sb = TestHelper.getInterfacedInstance()
assert_equal(nil , sb.dispatchObject(nil))
end
def test_class_methods
result = java.lang.System.currentTimeMillis()
assert_equal(Fixnum, result.class)
end
Boolean = java.lang.Boolean
def test_class_methods_differing_only_on_argument_type
assert_equal(true, Boolean.valueOf("true"))
assert_equal(false, Boolean.valueOf(false))
end
Character = java.lang.Character
def test_constants
assert_equal(9223372036854775807, Long::MAX_VALUE)
assert(! defined? Character::Y_DATA) # Known private field in Character
# class definition with "_" constant causes error
assert_nothing_raised { org.jruby.javasupport.test.ConstantHolder }
end
def test_using_arrays
list = JArray.new
list.add(10)
list.add(20)
array = list.toArray
assert_equal(10, array[0])
assert_equal(20, array[1])
assert_equal(2, array.length)
array[1] = 1234
assert_equal(10, array[0])
assert_equal(1234, array[1])
assert_equal([10, 1234], array.entries)
assert_equal(10, array.min)
end
def test_creating_arrays
array = Double[3].new
assert_equal(3, array.length)
array[0] = 3.14
array[2] = 17.0
assert_equal(3.14, array[0])
assert_equal(17.0, array[2])
end
Pipe = java.nio.channels.Pipe
def test_inner_classes
assert_equal("java.nio.channels.Pipe$SinkChannel",
Pipe::SinkChannel.java_class.name)
assert(Pipe::SinkChannel.instance_methods.include?("keyFor"))
end
def test_subclasses_and_their_return_types
l = ArrayList.new
r = Random.new
l.add(10)
assert_equal(10, l.get(0))
l.add(r)
r_returned = l.get(1)
# Since Random is a public class we should get the value casted as that
assert_equal("java.util.Random", r_returned.java_class.name)
assert(r_returned.nextInt.kind_of?(Fixnum))
end
HashMap = java.util.HashMap
def test_private_classes_interfaces_and_return_types
h = HashMap.new
assert_equal(HashMap, h.class)
h.put("a", 1)
iter = h.entrySet.iterator
inner_instance_entry = iter.next
# The class implements a public interface, MapEntry, so the methods
# on that should be available, even though the instance is of a
# private class.
assert_equal("a", inner_instance_entry.getKey)
end
def test_extending_java_interfaces
if java.lang.Comparable.instance_of?(Module)
anonymous = Class.new(Object)
anonymous.send :include, java.lang.Comparable
anonymous.send :include, java.lang.Runnable
assert anonymous < java.lang.Comparable
assert anonymous < java.lang.Runnable
assert anonymous.new.kind_of?(java.lang.Runnable)
assert anonymous.new.kind_of?(java.lang.Comparable)
else
assert Class.new(java.lang.Comparable)
end
end
def test_support_of_other_class_loaders
assert_helper_class = Java::JavaClass.for_name("org.jruby.test.TestHelper")
assert_helper_class2 = Java::JavaClass.for_name("org.jruby.test.TestHelper")
assert(assert_helper_class.java_class == assert_helper_class2.java_class, "Successive calls return the same class")
method = assert_helper_class.java_method('loadAlternateClass')
alt_assert_helper_class = method.invoke_static()
constructor = alt_assert_helper_class.constructor();
alt_assert_helper = constructor.new_instance();
identityMethod = alt_assert_helper_class.java_method('identityTest')
identity = identityMethod.invoke(alt_assert_helper)
assert_equal("ABCDEFGH", identity)
end
module Foo
include_class("java.util.ArrayList")
end
include_class("java.lang.String") {|package,name| "J#{name}" }
include_class ["java.util.Hashtable", "java.util.Vector"]
def test_class_constants_defined_under_correct_modules
assert_equal(0, Foo::ArrayList.new.size)
assert_equal("a", JString.new("a").to_s)
assert_equal(0, Vector.new.size)
assert_equal(0, Hashtable.new.size)
end
def test_high_level_java_should_only_deal_with_proxies_and_not_low_level_java_class
a = JString.new
assert(a.getClass().class != "Java::JavaClass")
end
# We had a problem with accessing singleton class versus class earlier. Sanity check
# to make sure we are not writing class methods to the same place.
include_class 'org.jruby.test.AlphaSingleton'
include_class 'org.jruby.test.BetaSingleton'
def test_make_sure_we_are_not_writing_class_methods_to_the_same_place
assert_nothing_raised { AlphaSingleton.getInstance.alpha }
end
include_class 'org.jruby.javasupport.test.Color'
def test_lazy_proxy_method_tests_for_alias_and_respond_to
color = Color.new('green')
assert_equal(true, color.respond_to?(:setColor))
assert_equal(false, color.respond_to?(:setColorBogus))
end
class MyColor < Color
alias_method :foo, :getColor
def alias_test
alias_method :foo2, :setColorReallyBogus
end
end
def test_accessor_methods
my_color = MyColor.new('blue')
assert_equal('blue', my_color.foo)
assert_raises(NoMethodError) { my_color.alias_test }
my_color.color = 'red'
assert_equal('red', my_color.color)
my_color.setDark(true)
assert_equal(true, my_color.dark?)
my_color.dark = false
assert_equal(false, my_color.dark?)
end
# No explicit test, but implicitly EMPTY_LIST.each should not blow up interpreter
# Old error was EMPTY_LIST is a private class implementing a public interface with public methods
include_class 'java.util.Collections'
def test_empty_list_each_should_not_blow_up_interpreter
assert_nothing_raised { Collections::EMPTY_LIST.each {|element| } }
end
def test_already_loaded_proxies_should_still_see_extend_proxy
JavaUtilities.extend_proxy('java.util.List') do
def foo
true
end
end
assert_equal(true, Foo::ArrayList.new.foo)
end
def test_same_proxy_does_not_raise
# JString already included and it is the same proxy, so do not throw an error
# (e.g. intent of include_class already satisfied)
assert_nothing_raised do
begin
old_stream = $stderr.dup
$stderr.reopen(Config::CONFIG['target_os'] =~ /Windows|mswin/ ? 'NUL:' : '/dev/null')
$stderr.sync = true
class << self
include_class("java.lang.String") {|package,name| "J#{name}" }
end
ensure
$stderr.reopen(old_stream)
end
end
end
include_class 'java.util.Calendar'
def test_date_time_conversion
# Test java.util.Date <=> Time implicit conversion
calendar = Calendar.getInstance
calendar.setTime(Time.at(0))
java_date = calendar.getTime
assert_equal(java_date.getTime, Time.at(0).to_i)
end
def test_expected_java_string_methods_exist
# test that the list of JString methods contains selected methods from Java
jstring_methods = %w[bytes charAt char_at compareTo compareToIgnoreCase compare_to
compare_to_ignore_case concat contentEquals content_equals endsWith
ends_with equals equalsIgnoreCase equals_ignore_case getBytes getChars
getClass get_bytes get_chars get_class hashCode hash_code indexOf
index_of intern java_class java_object java_object= lastIndexOf last_index_of
length matches notify notifyAll notify_all regionMatches region_matches replace
replaceAll replaceFirst replace_all replace_first split startsWith starts_with
subSequence sub_sequence substring taint tainted? toCharArray toLowerCase
toString toUpperCase to_char_array to_lower_case to_string
to_upper_case trim wait]
jstring_methods.each { |method| assert(JString.public_instance_methods.include?(method), "#{method} is missing from JString") }
end
include_class 'java.math.BigDecimal'
def test_big_decimal_interaction
assert_equal(BigDecimal, BigDecimal.new("1.23").add(BigDecimal.new("2.34")).class)
end
def test_direct_package_access
a = java.util.ArrayList.new
assert_equal(0, a.size)
end
Properties = Java::java.util.Properties
def test_declare_constant
p = Properties.new
p.setProperty("a", "b")
assert_equal("b", p.getProperty("a"))
end
if java.awt.event.ActionListener.instance_of?(Module)
class MyBadActionListener
include java.awt.event.ActionListener
end
else
class MyBadActionListener < java.awt.event.ActionListener
end
end
def test_expected_missing_interface_method
assert_raises(NoMethodError) { MyBadActionListener.new.actionPerformed }
end
def test_that_misspelt_fq_class_names_dont_stop_future_fq_class_names_with_same_inner_most_package
assert_raises(NameError) { Java::java.til.zip.ZipFile }
assert_nothing_raised { Java::java.util.zip.ZipFile }
end
def test_that_subpackages_havent_leaked_into_other_packages
assert_equal(false, Java::java.respond_to?(:zip))
assert_equal(false, Java::com.respond_to?(:util))
end
def test_that_sub_packages_called_java_javax_com_org_arent_short_circuited
#to their top-level conterparts
assert(!com.equal?(java.flirble.com))
end
def test_that_we_get_the_same_package_instance_on_subsequent_calls
assert(com.flirble.equal?(com.flirble))
end
@@include_proc = Proc.new do
Thread.stop
include_class "java.lang.System"
include_class "java.lang.Runtime"
Thread.current[:time] = System.currentTimeMillis
Thread.current[:mem] = Runtime.getRuntime.freeMemory
end
# Disabled temporarily...keeps failing for no obvious reason
=begin
def test_that_multiple_threads_including_classes_dont_step_on_each_other
# we swallow the output to $stderr, so testers don't have to see the
# warnings about redefining constants over and over again.
threads = []
begin
old_stream = $stderr.dup
$stderr.reopen(Config::CONFIG['target_os'] =~ /Windows|mswin/ ? 'NUL:' : '/dev/null')
$stderr.sync = true
50.times do
threads << Thread.new(&@@include_proc)
end
# wait for threads to all stop, then wake them up
threads.each {|t| Thread.pass until t.stop?}
threads.each {|t| t.run}
# join each to let them run
threads.each {|t| t.join }
# confirm they all successfully called currentTimeMillis and freeMemory
ensure
$stderr.reopen(old_stream)
end
threads.each do |t|
assert(t[:time])
assert(t[:mem])
end
end
=end
unless (java.lang.System.getProperty("java.specification.version") == "1.4")
if javax.xml.namespace.NamespaceContext.instance_of?(Module)
class NSCT
include javax.xml.namespace.NamespaceContext
# JRUBY-66: No super here...make sure we still work.
def initialize(arg)
end
def getNamespaceURI(prefix)
'ape:sex'
end
end
else
class NSCT < javax.xml.namespace.NamespaceContext
# JRUBY-66: No super here...make sure we still work.
def initialize(arg)
end
def getNamespaceURI(prefix)
'ape:sex'
end
end
end
def test_no_need_to_call_super_in_initialize_when_implementing_java_interfaces
# No error is a pass here for JRUBY-66
assert_nothing_raised do
javax.xml.xpath.XPathFactory.newInstance.newXPath.setNamespaceContext(NSCT.new(1))
end
end
end
def test_can_see_inner_class_constants_with_same_name_as_top_level
# JRUBY-425: make sure we can reference inner class names that match
# the names of toplevel constants
ell = java.awt.geom.Ellipse2D
assert_nothing_raised { ell::Float.new }
end
def test_that_class_methods_are_being_camel_cased
assert(java.lang.System.respond_to?("current_time_millis"))
end
if Java::java.lang.Runnable.instance_of?(Module)
class TestInitBlock
include Java::java.lang.Runnable
def initialize(&block)
raise if !block
@bar = block.call
end
def bar; @bar; end
end
else
class TestInitBlock < Java::java.lang.Runnable
def initialize(&block)
raise if !block
@bar = block.call
end
def bar; @bar; end
end
end
def test_that_blocks_are_passed_through_to_the_constructor_for_an_interface_impl
assert_nothing_raised {
assert_equal("foo", TestInitBlock.new { "foo" }.bar)
}
end
def test_no_collision_with_ruby_allocate_and_java_allocate
# JRUBY-232
assert_nothing_raised { java.nio.ByteBuffer.allocate(1) }
end
# JRUBY-636 and other "extending Java classes"-issues
class BigInt < java.math.BigInteger
def initialize(val)
super(val)
end
def test
"Bit count = #{bitCount}"
end
end
def test_extend_java_class
assert_equal 2, BigInt.new("10").bitCount
assert_equal "Bit count = 2", BigInt.new("10").test
end
class TestOS < java.io.OutputStream
attr_reader :written
def write(p)
@written = true
end
end
def test_extend_output_stream
_anos = TestOS.new
bos = java.io.BufferedOutputStream.new _anos
bos.write 32
bos.flush
assert _anos.written
end
def test_impl_shortcut
has_run = false
java.lang.Runnable.impl do
has_run = true
end.run
assert has_run
end
# JRUBY-674
OuterClass = org.jruby.javasupport.test.OuterClass
def test_inner_class_proxies
assert defined?(OuterClass::PublicStaticInnerClass)
assert OuterClass::PublicStaticInnerClass.instance_methods.include?("a")
assert !defined?(OuterClass::ProtectedStaticInnerClass)
assert !defined?(OuterClass::DefaultStaticInnerClass)
assert !defined?(OuterClass::PrivateStaticInnerClass)
assert defined?(OuterClass::PublicInstanceInnerClass)
assert OuterClass::PublicInstanceInnerClass.instance_methods.include?("a")
assert !defined?(OuterClass::ProtectedInstanceInnerClass)
assert !defined?(OuterClass::DefaultInstanceInnerClass)
assert !defined?(OuterClass::PrivateInstanceInnerClass)
end
# Test the new "import" syntax
def test_import
assert_nothing_raised {
import java.nio.ByteBuffer
ByteBuffer.allocate(10)
}
end
def test_java_exception_handling
list = ArrayList.new
begin
list.get(5)
assert(false)
rescue java.lang.IndexOutOfBoundsException => e
assert(/java\.lang\.IndexOutOfBoundsException/ === e.message)
end
end
# test for JRUBY-698
def test_java_method_returns_null
include_class 'org.jruby.test.ReturnsNull'
rn = ReturnsNull.new
assert_equal("", rn.returnNull.to_s)
end
# test for JRUBY-664
class FinalMethodChildClass < FinalMethodBaseTest
end
def test_calling_base_class_final_method
assert_equal("In foo", FinalMethodBaseTest.new.foo)
assert_equal("In foo", FinalMethodChildClass.new.foo)
end
# test case for JRUBY-679
# class Weather < java.util.Observable
# def initialize(temp)
# super()
# @temp = temp
# end
# end
# class Meteorologist < java.util.Observer
# attr_reader :updated
# def initialize(weather)
# weather.addObserver(self)
# end
# def update(obs, arg)
# @updated = true
# end
# end
# def test_should_be_able_to_have_different_ctor_arity_between_ruby_subclass_and_java_superclass
# assert_nothing_raised do
# w = Weather.new(32)
# m = Meteorologist.new(w)
# w.notifyObservers
# assert(m.updated)
# end
# end
class A < java.lang.Object
include org.jruby.javasupport.test.Interface1
def method1
end
end
A.new
class B < A
include org.jruby.javasupport.test.Interface2
def method2
end
end
B.new
class C < B
end
C.new
def test_interface_methods_seen
ci = org.jruby.javasupport.test.ConsumeInterfaces.new
ci.addInterface1(A.new)
ci.addInterface1(B.new)
ci.addInterface2(B.new)
ci.addInterface1(C.new)
ci.addInterface2(C.new)
end
class LCTestA < java::lang::Object
include org::jruby::javasupport::test::Interface1
def method1
end
end
LCTestA.new
class LCTestB < LCTestA
include org::jruby::javasupport::test::Interface2
def method2
end
end
LCTestB.new
class java::lang::Object
def boo
'boo!'
end
end
def test_lowercase_colon_package_syntax
assert_equal(java::lang::String, java.lang.String)
assert_equal('boo!', java.lang.String.new('xxx').boo)
ci = org::jruby::javasupport::test::ConsumeInterfaces.new
assert_equal('boo!', ci.boo)
assert_equal('boo!', LCTestA.new.boo)
assert_equal('boo!', LCTestB.new.boo)
ci.addInterface1(LCTestA.new)
ci.addInterface1(LCTestB.new)
ci.addInterface2(LCTestB.new)
end
def test_marsal_java_object_fails
assert_raises(TypeError) { Marshal.dump(java::lang::Object.new) }
end
def test_string_from_bytes
assert_equal('foo', String.from_java_bytes('foo'.to_java_bytes))
end
# JRUBY-2088
def test_package_notation_with_arguments
assert_raises(ArgumentError) do
java.lang("ABC").String
end
assert_raises(ArgumentError) do
java.lang.String(123)
end
assert_raises(ArgumentError) do
Java::se("foobar").com.Foobar
end
end
# JRUBY-1545
def test_creating_subclass_to_java_interface_raises_type_error
assert_raises(TypeError) do
eval(<<CLASSDEF)
class FooXBarBarBar < Java::JavaLang::Runnable
end
CLASSDEF
end
end
# JRUBY-781
def test_that_classes_beginning_with_small_letter_can_be_referenced
assert_equal Module, org.jruby.test.smallLetterClazz.class
assert_equal Class, org.jruby.test.smallLetterClass.class
end
# JRUBY-1076
def test_package_module_aliased_methods
assert java.lang.respond_to?(:__constants__)
assert java.lang.respond_to?(:__methods__)
java.lang.String # ensure java.lang.String has been loaded
assert java.lang.__constants__.include?('String')
end
# JRUBY-2106
def test_package_load_doesnt_set_error
$! = nil
undo = javax.swing.undo
assert_nil($!)
end
# JRUBY-2106
def test_top_level_package_load_doesnt_set_error
$! = nil
Java::boom
assert_nil($!)
$! = nil
Java::Boom
assert_nil($!)
end
# JRUBY-2169
def test_java_class_resource_methods
# FIXME? not sure why this works, didn't modify build.xml
# to copy this file, yet it finds it anyway
props_file = 'test_java_class_resource_methods.properties'
# nothing special about this class, selected at random for testing
jc = org.jruby.javasupport.test.RubyTestObject.java_class
# get resource as URL
url = jc.resource(props_file)
assert(java.net.URL === url)
assert(/^foo=bar/ =~ java.io.DataInputStream.new(url.content).read_line)
# get resource as stream
is = jc.resource_as_stream(props_file)
assert(java.io.InputStream === is)
assert(/^foo=bar/ =~ java.io.DataInputStream.new(is).read_line)
# get resource as string
str = jc.resource_as_string(props_file)
assert(/^foo=bar/ =~ str)
end
# JRUBY-2169
def test_ji_extended_methods_for_java_1_5
jc = java.lang.String.java_class
ctor = jc.constructors[0]
meth = jc.java_instance_methods[0]
field = jc.fields[0]
# annotations
assert(Annotation[] === jc.annotations)
assert(Annotation[] === ctor.annotations)
assert(Annotation[] === meth.annotations)
assert(Annotation[] === field.annotations)
# TODO: more extended methods to test
end
# JRUBY-2169
def test_java_class_ruby_class
assert java.lang.Object.java_class.ruby_class == java.lang.Object
assert java.lang.Runnable.java_class.ruby_class == java.lang.Runnable
end
def test_null_toString
assert nil == org.jruby.javasupport.test.NullToString.new.to_s
end
# JRUBY-2277
# kind of a strange place for this test, but the error manifested
# when JI was enabled. the actual bug was a problem in alias_method,
# and not related to JI; see related test in test_methods.rb
def test_alias_method_with_JI_enabled_does_not_raise
name = Object.new
def name.to_str
"new_name"
end
assert_nothing_raised { String.send("alias_method", name, "to_str") }
end
# JRUBY-2671
def test_coerce_array_to_java_with_javaobject_inside
x = nil
assert_nothing_raised { x = java.util.ArrayList.new([java.lang.Integer.new(1)]) }
assert_equal("[1]", x.to_string)
end
# JRUBY-2865
def test_extend_default_package_class
cls = Class.new(Java::DefaultPackageClass);
assert_nothing_raised { cls.new }
end
# JRUBY-3046
def test_java_methods_have_arity
assert_nothing_raised do
assert_equal(-1, java.lang.String.instance_method(:toString).arity)
end
end
# JRUBY-3476
def test_object_with_singleton_returns_java_class
x = java.lang.Object.new
def x.foo; end
assert(x.java_class.kind_of?Java::JavaClass)
end
# JRUBY-4524
class IncludePackageSuper
def self.const_missing(a)
a
end
end
class IncludePackageSub < IncludePackageSuper
include_package 'java.util'
def arraylist
ArrayList
end
def blahblah
BlahBlah
end
end
def test_include_package_chains_super
assert_equal java.util.ArrayList, IncludePackageSub.new.arraylist
assert_equal :BlahBlah, IncludePackageSub.new.blahblah
end
# JRUBY-4529
def test_float_always_coerces_to_java_float
assert_nothing_raised do
a = 1.0
loop do
a /= 2
a.to_java :float
break if a == 0.0
end
end
end
end
| 28.55379 | 131 | 0.715374 |
03cfa8f9ffeb629288644b1829c135a4ab710538 | 198 | class CreateTweets < ActiveRecord::Migration
def change
create_table :tweets do |t|
t.string :handle1
t.string :handle2
t.string :tweet
t.timestamps
end
end
end
| 16.5 | 44 | 0.646465 |
4a75a31d00406c604e30df8b97665d9a6c9aecc0 | 55 | # frozen_string_literal: true
require 'spree/core'
| 13.75 | 30 | 0.745455 |
7a3dde4cb0718a14ae67acfc8d3dd2abc3e61fd0 | 970 | module Endicia
class Label
attr_accessor :image,
:status,
:tracking_number,
:final_postage,
:transaction_date_time,
:transaction_id,
:postmark_date,
:postage_balance,
:pic,
:error_message,
:reference_id,
:cost_center,
:request_body,
:request_url,
:response_body,
:requester_id
def initialize(result)
self.response_body = filter_response_body(result.body.dup)
self.image = result["LabelRequestResponse"]["Base64LabelImage"]
end
private
def filter_response_body(string)
# Strip image data for readability:
string.sub(/<Base64LabelImage>.+<\/Base64LabelImage>/,
"<Base64LabelImage>[data]</Base64LabelImage>")
end
end
end
| 30.3125 | 69 | 0.513402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.