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
|
---|---|---|---|---|---|
33ef2c634965ea818a76e36036b0dedde4108faa | 1,564 | require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
# require "action_mailer/railtie"
require "action_view/railtie"
# require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
#require File.expand_path("../../lib/log4r.rb", __FILE__)
#include Log4r
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MaestroUnlimited
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
config.colorize_logging = false
# require File.dirname(__FILE__) + "/../lib/custom_logger"
if Rails.env.production?
null_logger = Logger.new(nil).tap {|log| def log.write(msg); end }
config.logger = null_logger
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Don't generate system test files.
config.generators.system_tests = nil
config.generators.template_engine = :erb
config.enable_dependency_loading = true
config.autoload_paths << Rails.root.join("lib")
config.generators do |g|
g.orm :active_record
g.assets false
g.helper false
end
end
end
| 31.918367 | 82 | 0.741688 |
f8470d058abce7026b22a3487b655fc4546e1812 | 163 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe AgendasTagging, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| 20.375 | 56 | 0.766871 |
6aede4d837511541138e97f9a5eee712696e3eb5 | 8,050 | =begin
#Ory Kratos API
#Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests.
The version of the OpenAPI document: v0.8.2-alpha.1
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.2.1
=end
require 'date'
require 'time'
module OryKratosClient
class SubmitSelfServiceRecoveryFlowWithLinkMethodBody
# Sending the anti-csrf token is only required for browser login flows.
attr_accessor :csrf_token
# Email to Recover Needs to be set when initiating the flow. If the email is a registered recovery email, a recovery link will be sent. If the email is not known, a email with details on what happened will be sent instead. format: email
attr_accessor :email
# Method supports `link` only right now.
attr_accessor :method
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'csrf_token' => :'csrf_token',
:'email' => :'email',
:'method' => :'method'
}
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
{
:'csrf_token' => :'String',
:'email' => :'String',
:'method' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `OryKratosClient::SubmitSelfServiceRecoveryFlowWithLinkMethodBody` 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 `OryKratosClient::SubmitSelfServiceRecoveryFlowWithLinkMethodBody`. 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?(:'csrf_token')
self.csrf_token = attributes[:'csrf_token']
end
if attributes.key?(:'email')
self.email = attributes[:'email']
end
if attributes.key?(:'method')
self.method = attributes[:'method']
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.nil?
invalid_properties.push('invalid value for "email", email cannot be nil.')
end
if @method.nil?
invalid_properties.push('invalid value for "method", method cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @email.nil?
return false if @method.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
csrf_token == o.csrf_token &&
email == o.email &&
method == o.method
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
[csrf_token, email, method].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 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
# 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 = OryKratosClient.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 32.2 | 429 | 0.639503 |
ab9fa7ecd9f4567ff11f9fbd6142a8bd0536d5c2 | 379 | class SortedArray < Array
def initialize(*args, &sort_by)
@sort_by = sort_by || Proc.new { |x,y| x <=> y }
super(*args)
self.sort!() &sort_by
end
def insert(i, v)
insert_before = index(find { |x| @sort_by.call(x, v) == 1 })
super(insert_before ? insert_before : -1, v)
end
def <<(v)
insert(0, v)
end
alias push <<
alias unshift <<
end
| 18.047619 | 64 | 0.580475 |
1d758b55b97ae80496e4568072f71bc96121f93c | 2,357 | # encoding: utf-8
OS_PLATFORM = RbConfig::CONFIG["host_os"]
VENDOR_PATH = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "vendor"))
#TODO: Figure out better means to keep this version in sync
if OS_PLATFORM == "linux"
FILEBEAT_URL = "https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.5.4-linux-x86_64.tar.gz"
elsif OS_PLATFORM == "darwin"
FILEBEAT_URL = "https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.5.4-darwin-x86_64.tar.gz"
end
LSF_URL = "https://download.elastic.co/logstash-forwarder/binaries/logstash-forwarder_#{OS_PLATFORM}_amd64"
require "fileutils"
@files=[]
task :default do
system("rake -T")
end
require "logstash/devutils/rake"
namespace :test do
namespace :integration do
task :setup do
Rake::Task["test:integration:setup:filebeat"].invoke
Rake::Task["test:integration:setup:lsf"].invoke
end
namespace :setup do
desc "Download lastest stable version of Logstash-forwarder"
task :lsf do
destination = File.join(VENDOR_PATH, "logstash-forwarder")
FileUtils.rm_rf(destination)
FileUtils.mkdir_p(destination)
download_destination = File.join(destination, "logstash-forwarder")
puts "Logstash-forwarder: downloading from #{LSF_URL} to #{download_destination}"
download(LSF_URL, download_destination)
File.chmod(0755, download_destination)
end
desc "Download nigthly filebeat for integration testing"
task :filebeat do
FileUtils.mkdir_p(VENDOR_PATH)
download_destination = File.join(VENDOR_PATH, "filebeat.tar.gz")
destination = File.join(VENDOR_PATH, "filebeat")
FileUtils.rm_rf(download_destination)
FileUtils.rm_rf(destination)
FileUtils.rm_rf(File.join(VENDOR_PATH, "filebeat.tar"))
puts "Filebeat: downloading from #{FILEBEAT_URL} to #{download_destination}"
download(FILEBEAT_URL, download_destination)
untar_all(download_destination, File.join(VENDOR_PATH, "filebeat")) { |e| e }
end
end
end
end
# Uncompress all the file from the archive this only work with
# one level directory structure and its fine for LSF and filebeat packaging.
def untar_all(file, destination)
untar(file) do |entry|
out = entry.full_name.split("/").last
File.join(destination, out)
end
end
| 35.179104 | 108 | 0.714892 |
edc78b6cefc3085b0770663252c162ac8fcee7c1 | 3,909 | # encoding: utf-8
require 'json'
require_relative '../helper'
module Reporter
#
# Used to send inspec reports to Chef Automate via the data_collector service
#
class ChefAutomate
include ReportHelpers
def initialize(opts)
@entity_uuid = opts[:entity_uuid]
@run_id = opts[:run_id]
@node_name = opts[:node_info][:node]
@environment = opts[:node_info][:environment]
@roles = opts[:node_info][:roles]
@recipes = opts[:node_info][:recipes]
@insecure = opts[:insecure]
if defined?(Chef) &&
defined?(Chef::Config) &&
Chef::Config[:data_collector] &&
Chef::Config[:data_collector][:token] &&
Chef::Config[:data_collector][:server_url]
dc = Chef::Config[:data_collector]
@url = dc[:server_url]
@token = dc[:token]
end
end
# Method used in order to send the inspec report to the data_collector server
def send_report(report)
unless @entity_uuid && @run_id
Chef::Log.error "entity_uuid(#{@entity_uuid}) or run_id(#{@run_id}) can't be nil, not sending report to Chef Automate"
return false
end
json_report = enriched_report(report).to_json
report_size = json_report.bytesize
if report_size > 5*1024*1024
Chef::Log.warn "Compliance report size is #{(report_size / (1024*1024.0)).round(2)} MB."
end
unless json_report
Chef::Log.warn 'Something went wrong, report can\'t be nil'
return false
end
if defined?(Chef) &&
defined?(Chef::Config)
headers = { 'Content-Type' => 'application/json' }
unless @token.nil?
headers['x-data-collector-token'] = @token
headers['x-data-collector-auth'] = 'version=1.0'
end
# Enable OpenSSL::SSL::VERIFY_NONE via `node['audit']['insecure']`
# See https://github.com/chef/chef/blob/master/lib/chef/http/ssl_policies.rb#L54
if @insecure
Chef::Config[:verify_api_cert] = false
Chef::Config[:ssl_verify_mode] = :verify_none
end
begin
Chef::Log.info "Report to Chef Automate: #{@url}"
Chef::Log.debug "Audit Report: #{json_report}"
http = Chef::HTTP.new(@url)
http.post(nil, json_report, headers)
return true
rescue => e
Chef::Log.error "send_report: POST to #{@url} returned: #{e.message}"
return false
end
else
Chef::Log.warn 'data_collector.token and data_collector.server_url must be defined in client.rb!'
Chef::Log.warn 'Further information: https://github.com/chef-cookbooks/audit#direct-reporting-to-chef-automate'
return false
end
end
# ***************************************************************************************
# TODO: We could likely simplify/remove alot of the extra logic we have here with a small
# revamp of the Automate expected input.
# ***************************************************************************************
def enriched_report(final_report)
return nil unless final_report.is_a?(Hash)
# Remove nil profiles if any
final_report[:profiles].select! { |p| p }
# Label this content as an inspec_report
final_report[:type] = 'inspec_report'
# Ensure controls are never stored or shipped, since this was an accidential
# addition in InSpec and will be remove in the next inspec major release
final_report.delete(:controls)
final_report[:node_name] = @node_name
final_report[:end_time] = Time.now.utc.strftime('%FT%TZ')
final_report[:node_uuid] = @entity_uuid
final_report[:environment] = @environment
final_report[:roles] = @roles
final_report[:recipes] = @recipes
final_report[:report_uuid] = @run_id
final_report
end
end
end
| 34.901786 | 126 | 0.600665 |
628582fe5dbd48a058a28ae5b5e210b41520cc8d | 1,801 | require 'test_helper'
class AdminsControllerTest < ActionController::TestCase
# All kinds of admins
def setup
@tom = admins(:tom) # root
@jerry = admins(:jerry) # admin
@mary = admins(:mary) # expert
@barack = admins(:barack) # operator
@michelle = admins(:michelle) # guest
@hillary = admins(:hillary) # nobody
@to_delete = admins(:to_delete) # to be deleted in the test
end
test "root should get index" do
sign_in @tom # from Devise, root
get :index
assert_response :success
assert_not_nil assigns(:admins)
assert_select 'h1', "Listing admins"
assert_select 'tr td a', minimum: 2
end
test "non-root should not get index" do
sign_in @jerry # admin
get :index
assert_response :redirect # 302
sign_in @mary # expert
get :index
assert_response :redirect # 302
sign_in @barack # operator
get :index
assert_response :redirect # 302
sign_in @michelle # guest
get :index
assert_response :redirect # 302
sign_in @hillary # nobody
get :index
assert_response :redirect # 302
end
test "should update admin" do
sign_in @tom # Only a root can update an admin's role
patch :update,
id: @hillary,
admin: {role: "guest"}
assert_redirected_to admins_path
end
test "should update name" do
sign_in @tom # Only a root can update an admin's name
patch :update,
id: @hillary,
admin: {name: "Hillary Clinton"}
assert_redirected_to admins_path
end
test "should destroy admin" do
sign_in @tom # Only a root can delete an admin
assert_difference('Admin.count', -1) do
delete :destroy, id: @to_delete
end
assert_redirected_to admins_path
end
end
| 24.671233 | 64 | 0.642421 |
266a36460f53e7300c56f2e36d56734e3c08334c | 157 | class UsersController < ApplicationController
def edit
end
def destroy
current_user.destroy
clear_session
redirect_to root_path
end
end
| 14.272727 | 45 | 0.757962 |
6214255090960fc376cc17953c72414784c48305 | 710 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe FriendshipPolicy, type: :policy do
let(:kurt) { create(:user, :male, first_name: 'Kurt') }
let(:mary) { create(:user, :male, first_name: 'Mary') }
let(:friendship) { create(:friendship, active_friend: kurt, passive_friend: mary) }
context 'policy for actions for a friend request receiver' do
subject { FriendshipPolicy.new(mary, friendship) }
it { is_expected.to permit_action(:update) }
it { is_expected.to permit_action(:destroy) }
end
context 'policy for actions for a friend request sender' do
subject { FriendshipPolicy.new(kurt, friendship) }
it { is_expected.to permit_action(:destroy) }
end
end
| 33.809524 | 85 | 0.71831 |
28f904b0463a3cf66eab6e43d26e7f59f41064ef | 11,695 | class LlvmAT6 < Formula
desc "Next-gen compiler infrastructure"
homepage "https://llvm.org/"
url "https://releases.llvm.org/6.0.1/llvm-6.0.1.src.tar.xz"
sha256 "b6d6c324f9c71494c0ccaf3dac1f16236d970002b42bb24a6c9e1634f7d0f4e2"
license "NCSA"
revision OS.mac? ? 3 : 4
bottle do
cellar :any
sha256 "3b8315438ee3bf9eaed52b8f293e5aabbbfde7bcab4eded5de9a62b214d0b8b9" => :catalina
sha256 "5f628b4b14fe10a7b3654902a126956561983ba7aa96dc1d519bfdde5b0552c0" => :mojave
sha256 "bc740b2c28da83adc7bbfecb1c76a1777a963236de52af18f4413d6b090119ec" => :high_sierra
sha256 "95f3236a8fd89bd91f02a5cb53589ed39aa9c91d5f5e904acc435630c8cfee06" => :x86_64_linux
end
# Clang cannot find system headers if Xcode CLT is not installed
pour_bottle? do
reason "The bottle needs the Xcode CLT to be installed."
satisfy { !OS.mac? || MacOS::CLT.installed? }
end
keg_only :versioned_formula
# https://llvm.org/docs/GettingStarted.html#requirement
depends_on "cmake" => :build
depends_on "libffi"
unless OS.mac?
depends_on "gcc" # needed for libstdc++
depends_on "binutils" # needed for gold and strip
depends_on "libedit" # llvm requires <histedit.h>
depends_on "libelf" # openmp requires <gelf.h>
depends_on "ncurses"
depends_on "libxml2"
depends_on "zlib"
depends_on "[email protected]"
end
resource "clang" do
url "https://releases.llvm.org/6.0.1/cfe-6.0.1.src.tar.xz"
sha256 "7c243f1485bddfdfedada3cd402ff4792ea82362ff91fbdac2dae67c6026b667"
unless OS.mac?
patch do
url "https://github.com/xu-cheng/clang/commit/83c39729df671c06b003e2638a2d5600a8a2278c.patch?full_index=1"
sha256 "c8a038fb648278d9951d03a437723d5a55abc64346668566b707d555ae5997a6"
end
end
end
resource "clang-extra-tools" do
url "https://releases.llvm.org/6.0.1/clang-tools-extra-6.0.1.src.tar.xz"
sha256 "0d2e3727786437574835b75135f9e36f861932a958d8547ced7e13ebdda115f1"
end
resource "compiler-rt" do
url "https://releases.llvm.org/6.0.1/compiler-rt-6.0.1.src.tar.xz"
sha256 "f4cd1e15e7d5cb708f9931d4844524e4904867240c306b06a4287b22ac1c99b9"
end
if OS.mac?
resource "libcxx" do
url "https://releases.llvm.org/6.0.1/libcxx-6.0.1.src.tar.xz"
sha256 "7654fbc810a03860e6f01a54c2297a0b9efb04c0b9aa0409251d9bdb3726fc67"
end
end
resource "libunwind" do
url "https://releases.llvm.org/6.0.1/libunwind-6.0.1.src.tar.xz"
sha256 "a8186c76a16298a0b7b051004d0162032b9b111b857fbd939d71b0930fd91b96"
end
resource "lld" do
url "https://releases.llvm.org/6.0.1/lld-6.0.1.src.tar.xz"
sha256 "e706745806921cea5c45700e13ebe16d834b5e3c0b7ad83bf6da1f28b0634e11"
end
resource "lldb" do
url "https://releases.llvm.org/6.0.1/lldb-6.0.1.src.tar.xz"
sha256 "6b8573841f2f7b60ffab9715c55dceff4f2a44e5a6d590ac189d20e8e7472714"
end
resource "openmp" do
url "https://releases.llvm.org/6.0.1/openmp-6.0.1.src.tar.xz"
sha256 "66afca2b308351b180136cf899a3b22865af1a775efaf74dc8a10c96d4721c5a"
end
resource "polly" do
url "https://releases.llvm.org/6.0.1/polly-6.0.1.src.tar.xz"
sha256 "e7765fdf6c8c102b9996dbb46e8b3abc41396032ae2315550610cf5a1ecf4ecc"
end
# Clang cannot find system headers if Xcode CLT is not installed
if OS.mac?
pour_bottle? do
reason "The bottle needs the Xcode CLT to be installed."
satisfy { MacOS::CLT.installed? }
end
end
def install
# Apple's libstdc++ is too old to build LLVM
ENV.libcxx if ENV.compiler == :clang
(buildpath/"tools/clang").install resource("clang")
(buildpath/"tools/clang/tools/extra").install resource("clang-extra-tools")
(buildpath/"projects/openmp").install resource("openmp")
(buildpath/"projects/libcxx").install resource("libcxx") if OS.mac?
(buildpath/"projects/libunwind").install resource("libunwind")
(buildpath/"tools/lld").install resource("lld")
(buildpath/"tools/polly").install resource("polly")
(buildpath/"projects/compiler-rt").install resource("compiler-rt")
# compiler-rt has some iOS simulator features that require i386 symbols
# I'm assuming the rest of clang needs support too for 32-bit compilation
# to work correctly, but if not, perhaps universal binaries could be
# limited to compiler-rt. llvm makes this somewhat easier because compiler-rt
# can almost be treated as an entirely different build from llvm.
ENV.permit_arch_flags
args = %W[
-DLIBOMP_ARCH=x86_64
-DLINK_POLLY_INTO_TOOLS=ON
-DLLVM_BUILD_EXTERNAL_COMPILER_RT=ON
-DLLVM_BUILD_LLVM_DYLIB=ON
-DLLVM_ENABLE_EH=ON
-DLLVM_ENABLE_FFI=ON
-DLLVM_ENABLE_RTTI=ON
-DLLVM_INCLUDE_DOCS=OFF
-DLLVM_INSTALL_UTILS=ON
-DLLVM_OPTIMIZED_TABLEGEN=ON
-DLLVM_TARGETS_TO_BUILD=all
-DWITH_POLLY=ON
-DFFI_INCLUDE_DIR=#{Formula["libffi"].opt_lib}/libffi-#{Formula["libffi"].version}/include
-DFFI_LIBRARY_DIR=#{Formula["libffi"].opt_lib}
]
if OS.mac?
args << "-DLLVM_CREATE_XCODE_TOOLCHAIN=ON"
args << "-DLLVM_ENABLE_LIBCXX=ON"
else
args << "-DLLVM_CREATE_XCODE_TOOLCHAIN=OFF"
args << "-DLLVM_ENABLE_LIBCXX=OFF"
args << "-DCLANG_DEFAULT_CXX_STDLIB=libstdc++"
end
if OS.mac? && MacOS.version >= :mojave
sdk_path = MacOS::CLT.installed? ? "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk" : MacOS.sdk_path
args << "-DDEFAULT_SYSROOT=#{sdk_path}"
end
mkdir "build" do
system "cmake", "-G", "Unix Makefiles", "..", *(std_cmake_args + args)
system "make"
system "make", "install"
system "make", "install-xcode-toolchain" if OS.mac?
end
(share/"cmake").install "cmake/modules"
(share/"clang/tools").install Dir["tools/clang/tools/scan-{build,view}"]
# scan-build is in Perl, so the @ in our path needs to be escaped
inreplace "#{share}/clang/tools/scan-build/bin/scan-build",
"$RealBin/bin/clang", "#{bin}/clang".gsub("@", "\\@")
bin.install_symlink share/"clang/tools/scan-build/bin/scan-build", share/"clang/tools/scan-view/bin/scan-view"
man1.install_symlink share/"clang/tools/scan-build/man/scan-build.1"
# install llvm python bindings
xz = OS.mac? ? "2.7": "3.8"
(lib/"python#{xz}/site-packages").install buildpath/"bindings/python/llvm"
(lib/"python#{xz}/site-packages").install buildpath/"tools/clang/bindings/python/clang"
unless OS.mac?
# Strip executables/libraries/object files to reduce their size
system("strip", "--strip-unneeded", "--preserve-dates", *(Dir[bin/"**/*", lib/"**/*"]).select do |f|
f = Pathname.new(f)
f.file? && (f.elf? || f.extname == ".a")
end)
end
end
def caveats
<<~EOS
To use the bundled libc++ please add the following LDFLAGS:
LDFLAGS="-L#{opt_lib} -Wl,-rpath,#{opt_lib}"
EOS
end
test do
assert_equal prefix.to_s, shell_output("#{bin}/llvm-config --prefix").chomp
(testpath/"omptest.c").write <<~EOS
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
int main() {
#pragma omp parallel num_threads(4)
{
printf("Hello from thread %d, nthreads %d\\n", omp_get_thread_num(), omp_get_num_threads());
}
return EXIT_SUCCESS;
}
EOS
clean_version = version.to_s[/(\d+\.?)+/]
system "#{bin}/clang", "-L#{lib}", "-fopenmp", "-nobuiltininc",
"-I#{lib}/clang/#{clean_version}/include",
*("-Wl,-rpath=#{lib}" unless OS.mac?),
"omptest.c", "-o", "omptest", *ENV["LDFLAGS"].split
testresult = shell_output("./omptest")
sorted_testresult = testresult.split("\n").sort.join("\n")
expected_result = <<~EOS
Hello from thread 0, nthreads 4
Hello from thread 1, nthreads 4
Hello from thread 2, nthreads 4
Hello from thread 3, nthreads 4
EOS
assert_equal expected_result.strip, sorted_testresult.strip
(testpath/"test.c").write <<~EOS
#include <stdio.h>
int main()
{
printf("Hello World!\\n");
return 0;
}
EOS
(testpath/"test.cpp").write <<~EOS
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
EOS
unless OS.mac?
system "#{bin}/clang++", "-v", "test.cpp", "-o", "test"
assert_equal "Hello World!", shell_output("./test").chomp
end
if OS.mac?
# Testing default toolchain and SDK location.
system "#{bin}/clang++", "-v",
"-std=c++11", "test.cpp", "-o", "test++"
assert_includes MachO::Tools.dylibs("test++"), "/usr/lib/libc++.1.dylib"
assert_equal "Hello World!", shell_output("./test++").chomp
system "#{bin}/clang", "-v", "test.c", "-o", "test"
assert_equal "Hello World!", shell_output("./test").chomp
# Testing Command Line Tools
if MacOS::CLT.installed?
toolchain_path = "/Library/Developer/CommandLineTools"
sdk_path = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"
system "#{bin}/clang++", "-v",
"-isysroot", sdk_path,
"-isystem", "#{toolchain_path}/usr/include/c++/v1",
"-isystem", "#{toolchain_path}/usr/include",
"-isystem", "#{sdk_path}/usr/include",
"-std=c++11", "test.cpp", "-o", "testCLT++"
assert_includes MachO::Tools.dylibs("testCLT++"), "/usr/lib/libc++.1.dylib"
assert_equal "Hello World!", shell_output("./testCLT++").chomp
system "#{bin}/clang", "-v", "test.c", "-o", "testCLT"
assert_equal "Hello World!", shell_output("./testCLT").chomp
end
# Testing Xcode
if MacOS::Xcode.installed?
system "#{bin}/clang++", "-v",
"-isysroot", MacOS.sdk_path,
"-isystem", "#{MacOS::Xcode.toolchain_path}/usr/include/c++/v1",
"-isystem", "#{MacOS::Xcode.toolchain_path}/usr/include",
"-isystem", "#{MacOS.sdk_path}/usr/include",
"-std=c++11", "test.cpp", "-o", "testXC++"
assert_includes MachO::Tools.dylibs("testXC++"), "/usr/lib/libc++.1.dylib"
assert_equal "Hello World!", shell_output("./testXC++").chomp
system "#{bin}/clang", "-v",
"-isysroot", MacOS.sdk_path,
"test.c", "-o", "testXC"
assert_equal "Hello World!", shell_output("./testXC").chomp
end
# link against installed libc++
# related to https://github.com/Homebrew/legacy-homebrew/issues/47149
system "#{bin}/clang++", "-v",
"-isystem", "#{opt_include}/c++/v1",
"-std=c++11", "-stdlib=libc++", "test.cpp", "-o", "testlibc++",
"-L#{opt_lib}", "-Wl,-rpath,#{opt_lib}"
assert_includes MachO::Tools.dylibs("testlibc++"), "#{opt_lib}/libc++.1.dylib"
assert_equal "Hello World!", shell_output("./testlibc++").chomp
(testpath/"scanbuildtest.cpp").write <<~EOS
#include <iostream>
int main() {
int *i = new int;
*i = 1;
delete i;
std::cout << *i << std::endl;
return 0;
}
EOS
assert_includes shell_output("#{bin}/scan-build clang++ scanbuildtest.cpp 2>&1"),
"warning: Use of memory after it is freed"
(testpath/"clangformattest.c").write <<~EOS
int main() {
printf("Hello world!"); }
EOS
assert_equal "int main() { printf(\"Hello world!\"); }\n",
shell_output("#{bin}/clang-format -style=google clangformattest.c")
end
end
end
| 36.319876 | 114 | 0.637452 |
6afe4db41ea6011345e5c752271c17381bdea911 | 784 | class SendInvite
prepend SimpleCommand
include ActiveModel::Validations
def initialize(email, list, sender, recipient = nil)
@email = email
@list = list
@sender = sender
@recipient = recipient
end
def call
create_invitation
end
private
attr_reader :email, :list, :sender, :recipient
def create_invitation
invitation = sender.sent_invites.create(
email: email,
list: list,
recipient: recipient
)
if invitation.persisted?
email_invitation
return invitation
else
invitation.errors.each do |err|
errors.add(err.attribute, err.type)
end
return nil
end
end
def email_invitation
# Add mailer here
return true
end
end
| 19.6 | 54 | 0.625 |
5d9f0c3e0645ce055a13ce02a496fecc79b162b5 | 100 | class Image < ActiveRecord::Base
belongs_to :user
has_many :thumbnails, class_name: "Image"
end
| 20 | 43 | 0.76 |
ff724b537a3b6937e3077a3f4b6946a506650409 | 165 | require "date"
class Date
# Returns "00:00:00".
#
# Provided for parity with {Time#to_hms}.
#
# @return [String]
def to_hms
"00:00:00"
end
end
| 10.3125 | 43 | 0.587879 |
91896d2b9cf36e0b8e772883282d88822890a37d | 670 | class AddGroupsSourceToLabs < ActiveRecord::Migration[5.2]
def change
#Create groups_source column in labs
unless column_exists? :labs, :groups_source_id
add_reference :labs, :groups_source, index: true, after: :source_id
end
#for each lab with a status of 'released' or 'retrieved', get groups_source_id for the source attached to the current lab and push that into the groups_source column
@labs = Lab.where(status: "released").or(Lab.where(status: "retrieved"))
@labs.each do |lab|
groups_source = GroupsSource.where(source: lab.source_id).first
lab.update_attribute(:groups_source_id, groups_source.id)
end
end
end
| 41.875 | 169 | 0.735821 |
878001f0f9263f8db647d7b23ad6c50a29b0dec3 | 264 | module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title = '')
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
page_title + ' | ' + base_title
end
end
end
| 22 | 51 | 0.674242 |
bb36daa81e5a8bfa2d8d60fc12ec3044ecc87c95 | 829 | require 'concurrent'
require 'open-uri'
def get_year_end_closing(symbol, year)
uri = "http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=11&b=01&c=#{year}&d=11&e=31&f=#{year}&g=m"
data = open(uri) {|f| f.collect{|line| line.strip } }
price = data[1].split(',')[4]
price.to_f
[symbol, price.to_f]
end
def get_top_stock(symbols, year, timeout = 5)
stock_prices = symbols.collect{|symbol| Concurrent::dataflow{ get_year_end_closing(symbol, year) }}
Concurrent::dataflow(*stock_prices) { |*prices|
prices.reduce(['', 0.0]){|highest, price| price.last > highest.last ? price : highest}
}.value(timeout)
end
symbols = ['AAPL', 'GOOG', 'IBM', 'ORCL', 'MSFT']
year = 2008
top_stock, highest_price = get_top_stock(symbols, year)
puts "Top stock of #{year} is #{top_stock} closing at price $#{highest_price}"
| 33.16 | 107 | 0.683957 |
6a7bb02cc1a60ab14286ad8b1a5d302028c50db1 | 448 | require 'spec_helper'
describe Rack::App::Router do
include Rack::App::Test
let(:router) { rack_app.router }
rack_app Rack::App do
end
describe 'merge_router!' do
subject { router.merge_router!(other_router) }
context 'when not static router given' do
let(:other_router) { 'nope, this is a string' }
it { expect { subject }.to raise_error(ArgumentError, /must implement :endpoints interface/) }
end
end
end
| 22.4 | 100 | 0.685268 |
188aac14ac46c8d89705ee764f553d478bf50c5b | 619 | module TransactionAccountable
def new_credit(transaction_account_id, credit_amount, at = Time.zone.now)
credit = new_transaction(transaction_account_id, 0, credit_amount, at)
end
def new_debit(transaction_account_id, debit_amount, at = Time.zone.now)
debit = new_transaction(transaction_account_id, debit_amount, 0, at)
end
private
def new_transaction(transaction_account_id, debit_amount, credit_amount, at)
self.transaction_ledgers.new(:transaction_account_id => transaction_account_id, :debit => debit_amount, :credit => credit_amount, :period => "#{at.month}-#{at.year}")
end
end
| 38.6875 | 172 | 0.767367 |
4a252f1c9dc4daa7bc9c7282ccbd7219e1075a85 | 1,097 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20201224005133) do
create_table "missions", force: :cascade do |t|
t.string "title"
t.datetime "startdate"
t.datetime "enddate"
t.integer "user_id"
t.text "description"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
end
end
| 36.566667 | 86 | 0.749316 |
01bb070e5b880c8dff530b6c395a6446ea5b09e7 | 1,041 | # frozen_string_literal: true
require_relative 'helper'
class TestConditionsDiskUsage < Minitest::Test
# valid?
def test_valid_should_return_false_if_no_above_given
c = Conditions::DiskUsage.new
c.mount_point = '/'
c.watch = stub(name: 'foo')
refute c.valid?
end
def test_valid_should_return_false_if_no_mount_point_given
c = Conditions::DiskUsage.new
c.above = 90
c.watch = stub(name: 'foo')
refute c.valid?
end
def test_valid_should_return_true_if_required_options_all_set
c = Conditions::DiskUsage.new
c.above = 90
c.mount_point = '/'
c.watch = stub(name: 'foo')
assert c.valid?
end
# test
def test_test_should_return_true_if_above_limit
c = Conditions::DiskUsage.new
c.above = 90
c.mount_point = '/'
c.expects(:`).returns('91')
assert c.test
end
def test_test_should_return_false_if_below_limit
c = Conditions::DiskUsage.new
c.above = 90
c.mount_point = '/'
c.expects(:`).returns('90')
refute c.test
end
end
| 19.641509 | 63 | 0.684918 |
6163eaf9004a0f5c1089876205e538d671bdf4e5 | 157 | include_recipe 'scp_sitecore_modules::azuretoolkit'
include_recipe 'scp_sitecore_modules::sxa_181_sc91'
include_recipe 'scp_sitecore_modules::jss_1101_sc91'
| 39.25 | 52 | 0.88535 |
18692960b0831c1facb4b61557aff701330a3c86 | 1,111 | require 'observer'
class Employee
include Observable
attr_reader :name, :title
attr_reader :salary
def initialize(name, title, salary)
super()
@name = name
@title = title
@salary = salary
end
def salary=(new_salary)
old_salary = @salary
@salary = new_salary
if old_salary != new_salary
changed
notify_observers(self)
end
end
def title=(new_title)
old_title = @title
@title = new_title
if old_title != new_title
changed
notify_observers(self)
end
end
end
class Payroll
def update (changed_employee)
puts "#{changed_employee.name} の給料は
#{changed_employee.salary} です"
end
end
class TaxMan
def update (changed_employee)
puts "#{changed_employee.name}
に新しい税金の請求書を送ります"
end
end
fred = Employee.new(
'Fred',
'Crane Operator',
30000.0,
)
payroll = Payroll.new
tax_man = TaxMan.new
fred.add_observer(payroll)
fred.add_observer(tax_man)
fred.salary=350000.0
| 17.919355 | 43 | 0.59856 |
5d0e9ed344c1c01339c1a90b317d14831f6ab2f3 | 613 | module Intrigue
module Ident
module SshCheck
class ArrayOs < Intrigue::Ident::SshCheck::Base
def generate_checks
[
{
:type => "fingerprint",
:category => "operating_system",
:tags => ["SSHServer"],
:vendor => "Array Networks",
:product => "ArrayOS",
:references => [],
:version => nil,
:match_type => :content_banner,
:match_content => /^ArrayOS$/i,
:match_details => "banner",
:hide => false,
:inference => false
}
]
end
end
end
end
end
| 21.892857 | 49 | 0.491028 |
618597bb6bd03bb473787dd20024d8d116829790 | 1,303 | module DisqusApi
class Namespace
attr_reader :api, :name, :specification
# @param [Api] api
# @param [String, Symbol] name
def initialize(api, name)
@api = api
@name = name
@specification = @api.specifications[@name]
@specification or raise(ArgumentError, "No such namespace <#@name>")
end
# @param [String, Symbol] action
# @param [Hash] arguments Action params
# @return [Request]
def build_action_request(action, arguments = {})
Request.new(api, name, action, arguments)
end
# @param [String, Symbol, Hash] action
# @param [Hash] arguments
# @return [Hash] response
def request_action(action, arguments = {})
build_action_request(action, arguments).response
end
alias_method :perform_action, :request_action
# DisqusApi.v3.users.---->>[details]<<-----
#
# Forwards all API calls under a specific namespace
def method_missing(method_name, *args)
if specification.has_key?(method_name.to_s)
request_action(method_name, *args)
else
raise NoMethodError, "No action #{method_name} registered for #@name namespace"
end
end
def respond_to?(method_name, include_private = false)
specification[method_name.to_s] || super
end
end
end | 29.613636 | 87 | 0.657713 |
e8edfde5bd1a3830a03dbb5e2b1ec60002734a15 | 529 | require_relative '../../test_helper'
class StateAfterBeingCopiedTest < StateMachinesTest
def setup
@machine = StateMachines::Machine.new(Class.new)
@machine.states << @state = StateMachines::State.new(@machine, :parked)
@copied_state = @state.dup
end
def test_should_not_have_the_context
state_context = nil
@state.context { state_context = self }
copied_state_context = nil
@copied_state.context { copied_state_context = self }
refute_same state_context, copied_state_context
end
end
| 26.45 | 75 | 0.73913 |
281705d8e727eab77a64ff3714611fa5a994b464 | 16,345 | require 'rpi_gpio'
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Ported by: Rigel
#
# 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.
# Commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# Entry flags
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# Control flags
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# Move flags
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# Function set flags
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
# Offset for up to 4 rows.
LCD_ROW_OFFSETS = [0x00, 0x40, 0x14, 0x54]
# Char LCD plate GPIO numbers.
LCD_PLATE_RS = 15
LCD_PLATE_RW = 14
LCD_PLATE_EN = 13
LCD_PLATE_D4 = 12
LCD_PLATE_D5 = 11
LCD_PLATE_D6 = 10
LCD_PLATE_D7 = 9
LCD_PLATE_RED = 6
LCD_PLATE_GREEN = 7
LCD_PLATE_BLUE = 8
# Char LCD plate button names.
SELECT = 0
RIGHT = 1
DOWN = 2
UP = 3
LEFT = 4
# PWM duty cycles
PWM_FREQUENCY=240
class Adafruit_CharLCD
def initialize(rs, en, d4, d5, d6, d7, cols, lines, backlight=nil,
invert_polarity=true,
enable_pwm=false,
initial_backlight=1.0)
#Initialize the LCD. RS, EN, and D4...D7 parameters should be the pins
#connected to the LCD RS, clock enable, and data line 4 through 7 connections.
#The LCD will be used in its 4-bit mode so these 6 lines are the only ones
#required to use the LCD. You must also pass in the number of columns and
#lines on the LCD.
#If you would like to control the backlight, pass in the pin connected to
#the backlight with the backlight parameter. The invert_polarity boolean
#controls if the backlight is one with a LOW signal or HIGH signal. The
#default invert_polarity value is true, i.e. the backlight is on with a
#LOW signal.
#You can enable PWM of the backlight pin to have finer control on the
#brightness. To enable PWM make sure your hardware supports PWM on the
#provided backlight pin and set enable_pwm to true (the default is false).
#The appropriate PWM library will be used depending on the platform, but
#you can provide an explicit one with the pwm parameter.
#The initial state of the backlight is ON, but you can set it to an
#explicit initial state with the initial_backlight parameter (0 is off,
#1 is on/full bright).
# Save column and line state.
@_cols = cols
@_lines = lines
# Save GPIO state and pin numbers.
@_rs = rs
@_en = en
@_d4 = d4
@_d5 = d5
@_d6 = d6
@_d7 = d7
# Save backlight state.
@_backlight = backlight
@_pwm_enabled = enable_pwm
@_blpol = !invert_polarity
#Setting up the pins
[rs, en, d4, d5, d6, d7].each do |pin|
RPi::GPIO.setup pin, :as => :output, :initialize => :low
end
#setup backlight
if @_backlight !=nil
RPi::GPIO.setup @_backlight, :as =>:output,:initialize=>:low
if enable_pwm
@_backlightPWM=RPi::GPIO::PWM.new(@_backlight, PWM_FREQUENCY)
@_backlightPWM.start(_pwm_duty_cycle(initial_backlight))
else
#FIXME: I really need to not work through the logic at 03:21 ... https://github.com/adafruit/Adafruit_Python_CharLCD/blob/f5a43f9c331180aeeef9cc86395ad84ca7deb631/Adafruit_CharLCD/Adafruit_CharLCD.py#L148
if(initial_backlight>0)
else
end
end
end
# Initialize the display.
# Initialize the display.
write8(0x33)
write8(0x32)
# Initialize display control, function, and mode registers.
@_displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF
@_displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_2LINE | LCD_5x8DOTS
@_displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT
# Write registers.
write8(LCD_DISPLAYCONTROL | @_displaycontrol)
write8(LCD_FUNCTIONSET | @_displayfunction)
write8(LCD_ENTRYMODESET | @_displaymode) # set the entry mode
clear()
end
def home()
#Move the cursor back to its home (first line and first column).
write8(LCD_RETURNHOME) # set cursor position to zero
sleep(0.003) # this command takes a long time!
end
def clear()
#Clear the LCD.
write8(LCD_CLEARDISPLAY) # command to clear display
sleep(0.003) # 3000 microsecond sleep, clearing the display takes a long time
end
def set_cursor(col, row)
#Move the cursor to an explicit column and row position.
# Clamp row to the last row of the display.
if row > @_lines
row = @_lines - 1
end
# Set location.
write8(LCD_SETDDRAMADDR | (col + LCD_ROW_OFFSETS[row]))
end
def enable_display(enable)
#Enable or disable the display. Set enable to true to enable.
if(enable)
@_displaycontrol |= LCD_DISPLAYON
else
@_displaycontrol &= ~LCD_DISPLAYON
end
write8(@_displaycontrol|LCD_DISPLAYCONTROL)
end
def show_cursor(show)
#Show or hide the cursor. Cursor is shown if show is true.
if(show)
@_displaycontrol |= LCD_CURSORON
else
@_displaycontrol &= ~LCD_CURSORON
end
write8(@_displaycontrol|LCD_DISPLAYCONTROL)
end
def blink(blink)
#Turn on or off cursor blinking. Set blink to true to enable blinking."""
if blink
@_displaycontrol |= LCD_BLINKON
else
@_displaycontrol &= ~LCD_BLINKON
end
write8(@_displaycontrol|LCD_DISPLAYCONTROL)
end
def move_left()
#Move display left one position.
write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT)
end
def move_right()
#Move display right one position.
write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT)
end
def set_left_to_right()
#Set text direction left to right."""
@_displaymode |= LCD_ENTRYLEFT
write8(LCD_ENTRYMODESET | @_displaymode)
end
def set_right_to_left()
#Set text direction right to left.
@_displaymode &= ~LCD_ENTRYLEFT
write8(LCD_ENTRYMODESET | @_displaymode)
end
def autoscroll(autoscroll)
#Autoscroll will 'right justify' text from the cursor if set true,
#otherwise it will 'left justify' the text.
if autoscroll
@_displaymode |= LCD_ENTRYSHIFTINCREMENT
else
@_displaymode &= ~LCD_ENTRYSHIFTINCREMENT
end
write8(LCD_ENTRYMODESET | @_displaymode)
end
def message(text)
#Write text to display. Note that text can include newlines.
line = 0
# Iterate through each character.
text.split("").each{|char|#Bit of a hacky way to do it but 🤷
# Advance to next line if character is a new line.
if(char == "\n")
line += 1
# Move to left or right side depending on text direction.
if (@_displaymode & LCD_ENTRYLEFT )> 0
col = 0
else
@_cols-1
end
set_cursor(col, line)
# Write the character to the display.
else
write8(char.ord, true)
end
}
end
def set_backlight(backlight)
#Enable or disable the backlight. If PWM is not enabled (default), a
#non-zero backlight value will turn on the backlight and a zero value will
#turn it off. If PWM is enabled, backlight can be any value from 0.0 to
#1.0, with 1.0 being full intensity backlight.
if @_backlight !=nil
if @_pwm_enabled
@_backlightPWM=_pwm_duty_cycle(backlight)
else
puts backlight
if(backlight>0)
RPi::GPIO.set_high @_backlight
else
RPi::GPIO.set_low @_backlight
end
end
end
end
def write8(value, char_mode=false)
#Write 8-bit value in character or data mode. Value should be an int
#value from 0-255, and char_mode is true if character data or false if
#non-character data (default).
# One millisecond delay to prevent writing too quickly.
sleep(0.001)
# Set character / data bit.
if(char_mode)
RPi::GPIO.set_high @_rs
else
RPi::GPIO.set_low @_rs
end
# Write upper 4 bits.
{@_d4=>4,@_d5=>5,@_d6=>6,@_d7=>7}.each{|pin,bit|#This is super jankey, but it should work
if((value>>bit)& 1)>0
RPi::GPIO.set_high pin
else
RPi::GPIO.set_low pin
end
}
#RPi::GPIO.output([@_d4,@_d5,@_d6,@_d7],
# ((value >> 4) & 1) > 0,
# ((value >> 5) & 1) > 0,
# ((value >> 6) & 1) > 0,
# ((value >> 7) & 1) > 0)
#RPi::GPIO.output_pins({ @_d4: ((value >> 4) & 1) > 0,
# @_d5: ((value >> 5) & 1) > 0,
# @_d6: ((value >> 6) & 1) > 0,
# @_d7: ((value >> 7) & 1) > 0 })
_pulse_enable()
# Write lower 4 bits.
{@_d4=>0,@_d5=>1,@_d6=>2,@_d7=>3}.each{|pin,bit|#This is super jankey, but it should work
if((value>>bit)&1)>0
RPi::GPIO.set_high pin
else
RPi::GPIO.set_low pin
end
}
#RPi::GPIO.output([@_d4,@_d5,@_d6,@_d7],
# (value & 1) > 0,
# ((value >> 1) & 1) > 0,
# ((value >> 2) & 1) > 0,
# ((value >> 3) & 1) > 0)
_pulse_enable()
end
def create_char(location, pattern)
#Fill one of the first 8 CGRAM locations with custom characters.
#The location parameter should be between 0 and 7 and pattern should
#provide an array of 8 bytes containing the pattern. E.g. you can easyly
#design your custom character at http://www.quinapalus.com/hd44780udg.html
#To show your custom character use eg. lcd.message('\x01')
# only position 0..7 are allowed
location &= 0x7
write8(LCD_SETCGRAMADDR | (location << 3))
(0..8).each{|i|
write8(pattern[i], true)
}
end
def _pulse_enable()
# Pulse the clock enable line off, on, off to send command.
RPi::GPIO.set_low @_en
sleep(0.000001) # 1 microsecond pause - enable pulse must be > 450ns
RPi::GPIO.set_high @_en
sleep(0.000001) # 1 microsecond pause - enable pulse must be > 450ns
RPi::GPIO.set_low @_en
sleep(0.000001) # commands need > 37us to settle
end
def _pwm_duty_cycle(intensity)
# Convert intensity value of 0.0 to 1.0 to a duty cycle of 0.0 to 100.0
intensity = 100.0*intensity
# Invert polarity if required.
if not @_blpol
intensity = 100.0-intensity
end
return intensity
end
end
#Not comfertable with this bit of code just yet ...
class Adafruit_RGBCharLCD < Adafruit_CharLCD
def initialize(rs, en, d4, d5, d6, d7, cols, lines, red, green, blue,
invert_polarity=True,
enable_pwm=False,
initial_color=[1.0, 1.0, 1.0])
# Initialize the LCD with RGB backlight. RS, EN, and D4...D7 parameters
# should be the pins connected to the LCD RS, clock enable, and data line
# 4 through 7 connections. The LCD will be used in its 4-bit mode so these
# 6 lines are the only ones required to use the LCD. You must also pass in
# the number of columns and lines on the LCD.
# The red, green, and blue parameters define the pins which are connected
# to the appropriate backlight LEDs. The invert_polarity parameter is a
# boolean that controls if the LEDs are on with a LOW or HIGH signal. By
# default invert_polarity is True, i.e. the backlight LEDs are on with a
# low signal. If you want to enable PWM on the backlight LEDs (for finer
# control of colors) and the hardware supports PWM on the provided pins,
# set enable_pwm to True. Finally you can set an explicit initial backlight
# color with the initial_color parameter. The default initial color is
# white (all LEDs lit).
# You can optionally pass in an explicit GPIO class,
# for example if you want to use an MCP230xx GPIO extender. If you don't
# pass in an GPIO instance, the default GPIO for the running platform will
# be used.
super(rs, en, d4, d5, d6, d7,cols,lines,false,invert_polarity,enable_pwm)
@_red = red
@_green = green
@_blue = blue
# Setup backlight pins.
[@_red, @_green, @_blue].each{|pin|
RPi::GPIO.setup pin, :as => :output, :initialize => :low
}
if enable_pwm
# Determine initial backlight duty cycles.
@_backlightPWM=[]
inital_color=_rgb_to_duty_cycle(inital_color)
{@_red=>initial_color[0], @_green=>initial_color[1], @_blue=>initial_color[2]}.each{|pin,color|
@_backlightPWM.push<<RPi::GPIO::PWM.new(pin, PWM_FREQUENCY)
@_backlightPWM[-1].start(color)
}
rdc, gdc, bdc = _rgb_to_duty_cycle(initial_color)
pwm.start(red, rdc)
pwm.start(green, gdc)
pwm.start(blue, bdc)
else
_rgb_to_pins(rgb).each{|pin,value|
if(value)
RPi::GPIO.set_high pin
end
}
end
end
def _rgb_to_duty_cycle(rgb)
# Convert tuple of RGB 0-1 values to tuple of duty cycles (0-100).
rgb.each{|color|
color=color.clamp(0.0,1.0)
color=_pwm_duty_cycle(color)
}
return rgb
end
def _rgb_to_pins(rgb)
# Convert tuple of RGB 0-1 values to dict of pin values.
retDict={}
{@_red=>rgb[0],@_green=>rgb[1],@_blue=>rgb[2]}.each{|pin,color|
if(color>0)#FIXME There has to be a more elegant way of doing this ...
retDict[pin]=@_blpol
else
retDict[pin]=!@_blpol
end
}
end
def set_color(red, green, blue)
# Set backlight color to provided red, green, and blue values. If PWM
# is enabled then color components can be values from 0.0 to 1.0, otherwise
# components should be zero for off and non-zero for on.
if @_pwm_enabled
# Set duty cycle of PWM pins.
rgb=_rgb_to_duty_cycle([red, green, blue])
for i in (0..2)
@_backlightPWM[i].duty_cycle=rgb[i]
end
else
# Set appropriate backlight pins based on polarity and enabled colors.
{@_red=>red,@_green=>green,@_blue=>blue}.each{|pin,value|
if value>0
RPi::GPIO.output(pin, @_blpol)
else
RPi::GPIO.output(pin,!@_blpol)
end
}
end
end
def set_backlight(backlight)
# Enable or disable the backlight. If PWM is not enabled (default), a
# non-zero backlight value will turn on the backlight and a zero value will
# turn it off. If PWM is enabled, backlight can be any value from 0.0 to
# 1.0, with 1.0 being full intensity backlight. On an RGB display this
# function will set the backlight to all white.
set_color(backlight, backlight, backlight)
end
end
| 36.647982 | 212 | 0.639095 |
919e3288bfdbc3076018737e54b226e17b8305cf | 442 | ActiveAdmin.register Offer do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if params[:action] == 'create' && current_user.admin?
# permitted
# end
end
| 29.466667 | 120 | 0.69457 |
185012b57d357e0ef78e34279e63c5edb7dce1fa | 3,515 | require "spec_helper"
describe "documentation" do
let(:request) do
double({
env: {}
})
end
let(:render_context) do
double({
request: request
})
end
def render_navigation(configuration, options = {})
Navigatrix::Renderer.new(configuration, options.merge(render_context: render_context)).render
end
it "renders a basic navigation" do
request.stub(env: {
"PATH_INFO" => "/about-us"
})
rendered = render_navigation({
"Home" => "/",
"About Us" => "/about-us",
"Blog" => "/blog",
"Contact" => "/contact"
})
desired = <<-HTML
<ul>
<li><a href="/">Home</a></li>
<li class="active">About Us</li>
<li><a href="/blog">Blog</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
HTML
rendered.should match_html(desired)
end
it "renders a more sophisticated nav" do
render_context.stub(controller_name: "users")
request.stub(env: {
"PATH_INFO" => "/users/1"
})
rendered = render_navigation({
"Home" => "/",
"Users" => {
:path => "/users",
:active_states => [
{:path => "/my_account"},
{:path => /\/users\/\d*/},
]
},
"Sign In" => {
:path => "/sign_in",
:render? => false
},
"Sign Out" => {
:path => "/sign_out",
:render? => true
}
}, {
:item => {
:active_class => "active-nav-item"
},
:list => {
:html_attributes => {
:class => "nav"
}
}
})
desired = <<-HTML
<ul class="nav">
<li><a href="/">Home</a></li>
<li class="active-nav-item"><a href="/users">Users</a></li>
<li><a href="/sign_out">Sign Out</a></li>
</ul>
HTML
rendered.should match_html(desired)
end
it "accepts item options" do
render_context.stub(controller_name: "users")
request.stub(env: {
"PATH_INFO" => "/users"
})
rendered = render_navigation({
"Users" => "/users",
"Clients" => "/clients"
}, {
item: {
:active_class => "custom-active",
:inactive_class => "custom-inactive",
:html_attributes => {
"class" => "nav-item",
"data-item" => "nav"
}
}
})
rendered.should match_html <<-HTML
<ul>
<li class="nav-item custom-active" data-item="nav">Users</li>
<li class="nav-item custom-inactive" data-item="nav"><a href="/clients">Clients</a></li>
</ul>
HTML
end
it "accepts item options on each item" do
render_context.stub(controller_name: "users")
request.stub(env: {
"PATH_INFO" => "/users"
})
rendered = render_navigation({
"Users" => {
:path => "/users",
:active_class => "custom-active"
},
"Clients" => {
:path => "/clients",
:inactive_class => "custom-inactive"
}
})
rendered.should match_html <<-HTML
<ul>
<li class="custom-active">Users</li>
<li class="custom-inactive"><a href="/clients">Clients</a></li>
</ul>
HTML
end
end
RSpec::Matchers.define :match_html do |expected|
match do |actual|
clean(expected) == clean(actual)
end
failure_message_for_should do |actual|
"expected that #{clean(actual)} to equal #{clean(expected)}"
end
def clean(text)
text.strip.gsub("\n", "").gsub(/(?<=\>)\s+?(?=\<)/, "")
end
end
| 22.677419 | 97 | 0.51266 |
1a8b62d64e32aacaf08f1be1a699bd2459cdbb21 | 3,727 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'sensu_api'))
Puppet::Type.type(:sensu_hook).provide(:sensu_api, :parent => Puppet::Provider::SensuAPI) do
desc "Provider sensu_hook using sensu API"
mk_resource_methods
def self.instances
hooks = []
namespaces.each do |namespace|
data = api_request('hooks', nil, {:namespace => namespace})
next if data.nil?
data.each do |d|
hook = {}
hook[:ensure] = :present
hook[:resource_name] = d['metadata']['name']
hook[:namespace] = d['metadata']['namespace']
hook[:name] = "#{hook[:resource_name]} in #{hook[:namespace]}"
hook[:labels] = d['metadata']['labels']
hook[:annotations] = d['metadata']['annotations']
d.each_pair do |key, value|
next if key == 'metadata'
if !!value == value
value = value.to_s.to_sym
end
if type_properties.include?(key.to_sym)
hook[key.to_sym] = value
end
end
hooks << new(hook)
end
end
hooks
end
def self.prefetch(resources)
hooks = instances
resources.keys.each do |name|
if provider = hooks.find { |c| c.resource_name == resources[name][:resource_name] && c.namespace == resources[name][:namespace] }
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def initialize(value = {})
super(value)
@property_flush = {}
end
type_properties.each do |prop|
define_method "#{prop}=".to_sym do |value|
@property_flush[prop] = value
end
end
def create
spec = {}
metadata = {}
metadata[:name] = resource[:resource_name]
type_properties.each do |property|
value = resource[property]
next if value.nil?
next if value == :absent || value == [:absent]
if [:true, :false].include?(value)
value = convert_boolean_property_value(value)
end
if property == :namespace
metadata[:namespace] = value
elsif property == :labels
metadata[:labels] = value
elsif property == :annotations
metadata[:annotations] = value
else
spec[property] = value
end
end
spec[:metadata] = metadata
opts = {
:namespace => spec[:metadata][:namespace],
:method => 'post',
}
api_request('hooks', spec, opts)
@property_hash[:ensure] = :present
end
def flush
if !@property_flush.empty?
spec = {}
metadata = {}
metadata[:name] = resource[:resource_name]
type_properties.each do |property|
if @property_flush[property]
value = @property_flush[property]
else
value = resource[property]
end
next if value.nil?
if [:true, :false].include?(value)
value = convert_boolean_property_value(value)
elsif value == :absent
value = nil
end
if property == :namespace
metadata[:namespace] = value
elsif property == :labels
metadata[:labels] = value
elsif property == :annotations
metadata[:annotations] = value
else
spec[property] = value
end
end
spec[:metadata] = metadata
opts = {
:namespace => spec[:metadata][:namespace],
:method => 'put',
}
api_request("hooks/#{resource[:resource_name]}", spec, opts)
end
@property_hash = resource.to_hash
end
def destroy
opts = {
:namespace => resource[:namespace],
:method => 'delete',
}
api_request("hooks/#{resource[:resource_name]}", nil, opts)
@property_hash.clear
end
end
| 27.007246 | 135 | 0.583043 |
214979c7273e234b3191121e7c106a1458565113 | 779 | cask "font-source-serif-pro" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/trunk/ofl/sourceserifpro",
verified: "github.com/google/fonts/",
using: :svn,
trust_cert: true
name "Source Serif Pro"
homepage "https://fonts.google.com/specimen/Source+Serif+Pro"
font "SourceSerifPro-Black.ttf"
font "SourceSerifPro-BlackItalic.ttf"
font "SourceSerifPro-Bold.ttf"
font "SourceSerifPro-BoldItalic.ttf"
font "SourceSerifPro-ExtraLight.ttf"
font "SourceSerifPro-ExtraLightItalic.ttf"
font "SourceSerifPro-Italic.ttf"
font "SourceSerifPro-Light.ttf"
font "SourceSerifPro-LightItalic.ttf"
font "SourceSerifPro-Regular.ttf"
font "SourceSerifPro-SemiBold.ttf"
font "SourceSerifPro-SemiBoldItalic.ttf"
end
| 31.16 | 65 | 0.744544 |
f734ffb7aaf8cb9b2a48e7956b28f8299146fbb0 | 4,061 | ##
# This Service serves as an interface for the Slack Web API
#
# @see https://github.com/slack-ruby/slack-ruby-client
class SlackService
##
# Returns the id of a usergroup
#
# @param [String] usergroup_handle The text after the `@` used to reference a
# group in slack - ex: ombuteam
# @param [Slack::Web::Client] client
# @return [[:ok, String]] if success
# @return [[:error, String]] if failure
# @see https://api.slack.com/methods/usergroups.list
def self.find_usergroup_id(usergroup_handle, client)
response = client.usergroups_list
return [:error, response["error"]] unless response["ok"]
usergroup = response.usergroups.find { |group| group["handle"] == usergroup_handle }
return [:error, "Usergroup handle not found"] if usergroup.nil?
[:ok, usergroup.id]
end
##
# Returns a list of all user ids in a given group
#
# @param [String] usergroup_id ID of a Slack group
# @param [Slack::Web::Client] client
# @return [[:ok, Array<String>]] if success
# @return [[:error, String]] if failure
# @see https://api.slack.com/methods/usergroups.users.list
def self.find_usergroup_user_ids(usergroup_id, client)
begin
response = client.usergroups_users_list({usergroup: usergroup_id})
[:ok, response["users"]]
rescue Slack::Web::Api::Errors::NoSuchSubteam
[:error, "Usergroup Not Found"]
end
end
##
# Returns a SlackUser
#
# @param [String] user_id ID of a Slack user
# @param [Slack::Web::Client] client
# @return [[:ok, SlackService::SlackUser]] if success
# @return [[:error, String]] if failure
# @see https://api.slack.com/methods/users.info
def self.find_slack_user(user_id, client)
begin
response = client.users_info({user: user_id})
user = SlackUser.new(
client: client,
id: response["user"]["id"],
name: response["user"]["name"],
first_name: response["user"]["profile"]["first_name"],
real_name: response["user"]["real_name"],
tz: response["user"]["tz"],
email: response["user"]["profile"]["email"]
)
[:ok, user]
rescue Slack::Web::Api::Errors::UserNotFound
[:error, "User Not Found"]
end
end
##
# Posts a message to a given channel
#
# The definition of "Channel" includes users in the case od DMs
#
# If `message_parts` is a simple string - it will be added as "Text"
#
# If `message_parts` is a Hash - should include `:text` but must include
# one of `text`, `attachments`, `blocks` - see attached documentation for
# more information
#
# @param [String] channel_id ID of a Slack user
# @param [Hash<>, String] message_parts
# @param [Slack::Web::Client] client
# @return [[:ok, String]] if success
# @return [[:error, String]] if failure
# @see https://api.slack.com/methods/chat.postMessage
# @see https://github.com/slack-ruby/slack-ruby-client/blob/master/lib/slack/web/api/endpoints/chat.rb
def self.send_message(channel_id, message_parts, client)
begin
client.chat_postMessage(cobble_message_params(channel_id, message_parts))
[:ok, "Message Sent"]
rescue Slack::Web::Api::Errors::ChannelNotFound
[:error, "Slack Channel Not Found"]
end
end
##
# Checks to ensure the keys related to a Slack message are correct and
# returns a hash formatted for `chat_postMessage/1`
def self.cobble_message_params(channel_id, message)
return {channel: channel_id, text: message} if message.kind_of?(String)
validate_message_keys(message)
message[:channel] = channel_id
message
end
def self.validate_message_keys(message)
contains_required_key = message.keys.inject(false) { |acc, key|
acc || [:text, :attachments, :blocks].any?(key)
}
raise MessageFormatError.new("Message missing") unless contains_required_key
extra_message_keys = message.keys - [:text, :attachments, :blocks]
raise MessageFormatError.new("Message format incorrect") unless extra_message_keys.empty?
end
end
| 33.561983 | 104 | 0.670278 |
d54c6cdc7b179bc143b4d89dc971c713ed9f7a6b | 234 | class CreateBoardDrawingActions < ActiveRecord::Migration[4.2]
def change
create_table :board_drawing_actions do |t|
t.string :action_type
t.string :uid
t.text :properties
t.timestamps
end
end
end
| 19.5 | 62 | 0.688034 |
2171e8170dcf5517201c7323289b91a780bd3f14 | 481 | module ApplicationHelper
def full_title(page_title = '')
base_title = 'Friend App'
if page_title.empty?
base_title
else
page_title + ' | ' + base_title
end
end
def like_dislike(post)
like = Like.find_by(post: post, user: current_user)
if like
link_to('Dislike!', post_like_path(id: like.id, post_id: post.id), method: :delete)
else
link_to('Like!', post_likes_path(post_id: post.id), method: :post)
end
end
end
| 22.904762 | 89 | 0.642412 |
330fa212a4f6437436c2e33ce61df5f0b9b4cec9 | 7,228 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
#-- encoding: UTF-8
module RedmineDiff
class Diff
VERSION = 0.3
def Diff.lcs(a, b)
astart = 0
bstart = 0
afinish = a.length-1
bfinish = b.length-1
mvector = []
# First we prune off any common elements at the beginning
while (astart <= afinish && bstart <= afinish && a[astart] == b[bstart])
mvector[astart] = bstart
astart += 1
bstart += 1
end
# now the end
while (astart <= afinish && bstart <= bfinish && a[afinish] == b[bfinish])
mvector[afinish] = bfinish
afinish -= 1
bfinish -= 1
end
bmatches = b.reverse_hash(bstart..bfinish)
thresh = []
links = []
(astart..afinish).each { |aindex|
aelem = a[aindex]
next unless bmatches.has_key? aelem
k = nil
bmatches[aelem].reverse.each { |bindex|
if k && (thresh[k] > bindex) && (thresh[k-1] < bindex)
thresh[k] = bindex
else
k = thresh.replacenextlarger(bindex, k)
end
links[k] = [ (k==0) ? nil : links[k-1], aindex, bindex ] if k
}
}
if !thresh.empty?
link = links[thresh.length-1]
while link
mvector[link[1]] = link[2]
link = link[0]
end
end
return mvector
end
def makediff(a, b)
mvector = Diff.lcs(a, b)
ai = bi = 0
while ai < mvector.length
bline = mvector[ai]
if bline
while bi < bline
discardb(bi, b[bi])
bi += 1
end
match(ai, bi)
bi += 1
else
discarda(ai, a[ai])
end
ai += 1
end
while ai < a.length
discarda(ai, a[ai])
ai += 1
end
while bi < b.length
discardb(bi, b[bi])
bi += 1
end
match(ai, bi)
1
end
def compactdiffs
diffs = []
@diffs.each { |df|
i = 0
curdiff = []
while i < df.length
whot = df[i][0]
s = @isstring ? df[i][2].chr : [df[i][2]]
p = df[i][1]
last = df[i][1]
i += 1
while df[i] && df[i][0] == whot && df[i][1] == last+1
s << df[i][2]
last = df[i][1]
i += 1
end
curdiff.push [whot, p, s]
end
diffs.push curdiff
}
return diffs
end
attr_reader :diffs, :difftype
def initialize(diffs_or_a, b = nil, isstring = nil)
if b.nil?
@diffs = diffs_or_a
@isstring = isstring
else
@diffs = []
@curdiffs = []
makediff(diffs_or_a, b)
@difftype = diffs_or_a.class
end
end
def match(ai, bi)
@diffs.push @curdiffs unless @curdiffs.empty?
@curdiffs = []
end
def discarda(i, elem)
@curdiffs.push ['-', i, elem]
end
def discardb(i, elem)
@curdiffs.push ['+', i, elem]
end
def compact
return Diff.new(compactdiffs)
end
def compact!
@diffs = compactdiffs
end
def inspect
@diffs.inspect
end
end
end
module Diffable
def diff(b)
RedmineDiff::Diff.new(self, b)
end
# Create a hash that maps elements of the array to arrays of indices
# where the elements are found.
def reverse_hash(range = (0...self.length))
revmap = {}
range.each { |i|
elem = self[i]
if revmap.has_key? elem
revmap[elem].push i
else
revmap[elem] = [i]
end
}
return revmap
end
def replacenextlarger(value, high = nil)
high ||= self.length
if self.empty? || value > self[-1]
push value
return high
end
# binary search for replacement point
low = 0
while low < high
index = (high+low)/2
found = self[index]
return nil if value == found
if value > found
low = index + 1
else
high = index
end
end
self[low] = value
# $stderr << "replace #{value} : 0/#{low}/#{init_high} (#{steps} steps) (#{init_high-low} off )\n"
# $stderr.puts self.inspect
#gets
#p length - low
return low
end
def patch(diff)
newary = nil
if diff.difftype == String
newary = diff.difftype.new('')
else
newary = diff.difftype.new
end
ai = 0
bi = 0
diff.diffs.each { |d|
d.each { |mod|
case mod[0]
when '-'
while ai < mod[1]
newary << self[ai]
ai += 1
bi += 1
end
ai += 1
when '+'
while bi < mod[1]
newary << self[ai]
ai += 1
bi += 1
end
newary << mod[2]
bi += 1
else
raise "Unknown diff action"
end
}
}
while ai < self.length
newary << self[ai]
ai += 1
bi += 1
end
return newary
end
end
class Array
include Diffable
end
class String
include Diffable
end
=begin
= Diff
(({diff.rb})) - computes the differences between two arrays or
strings. Copyright (C) 2001 Lars Christensen
== Synopsis
diff = Diff.new(a, b)
b = a.patch(diff)
== Class Diff
=== Class Methods
--- Diff.new(a, b)
--- a.diff(b)
Creates a Diff object which represent the differences between
((|a|)) and ((|b|)). ((|a|)) and ((|b|)) can be either be arrays
of any objects, strings, or object of any class that include
module ((|Diffable|))
== Module Diffable
The module ((|Diffable|)) is intended to be included in any class for
which differences are to be computed. Diffable is included into String
and Array when (({diff.rb})) is (({require}))'d.
Classes including Diffable should implement (({[]})) to get element at
integer indices, (({<<})) to append elements to the object and
(({ClassName#new})) should accept 0 arguments to create a new empty
object.
=== Instance Methods
--- Diffable#patch(diff)
Applies the differences from ((|diff|)) to the object ((|obj|))
and return the result. ((|obj|)) is not changed. ((|obj|)) and
can be either an array or a string, but must match the object
from which the ((|diff|)) was created.
=end
| 23.166667 | 102 | 0.574571 |
5d1a0ad6affaa47e7abb31fafc8090775a8bfb69 | 200 | class AddFacilityIdToInspection < ActiveRecord::Migration
def change
add_column :inspections, :facility_id, :integer
add_foreign_key :inspections, :facilities, on_delete: :cascade
end
end
| 28.571429 | 66 | 0.785 |
6a22fdb857b3383d0e0c2b55feb7bade09d9b242 | 436 | # frozen_string_literal: true
require 'spec_helper'
describe 'contribution analytics' do
let(:user) { create(:user) }
let(:group) { create(:group)}
before do
group.add_developer(user)
login_as(user)
end
it 'redirects from -/analytics to -/contribution_analytics' do
get "/groups/#{group.full_path}/-/analytics"
expect(response).to redirect_to(group_contribution_analytics_path(group.full_path))
end
end
| 21.8 | 87 | 0.727064 |
2184801154014f17c22b52509bdea1b1707d50cc | 2,858 | module DataMapper
module Is
module StateMachine
module Data
# This Machine class represents one state machine.
#
# A model (i.e. a DataMapper resource) can have more than one Machine.
class Machine
# The property of the DM resource that will hold this Machine's
# state.
#
# TODO: change :column to :property
attr_accessor :column
# The initial value of this Machine's state
attr_accessor :initial
# The current value of this Machine's state
#
# This is the "primary control" of this Machine's state. All
# other methods key off the value of @current_state_name.
attr_accessor :current_state_name
attr_accessor :events
attr_accessor :states
def initialize(column, initial)
@column, @initial = column, initial
@events, @states = [], []
@current_state_name = initial
end
# Fire (activate) the event with name +event_name+
#
# @api public
def fire_event(event_name, resource)
unless event = find_event(event_name)
raise InvalidEvent, "Could not find event (#{event_name.inspect})"
end
transition = event.transitions.find do |t|
t[:from].to_s == @current_state_name.to_s
end
unless transition
raise InvalidEvent, "Event (#{event_name.inspect}) does not" +
"exist for current state (#{@current_state_name.inspect})"
end
# == Run :exit hook (if present) ==
resource.run_hook_if_present current_state.options[:exit]
# == Change the current_state ==
@current_state_name = transition[:to]
# == Run :enter hook (if present) ==
resource.run_hook_if_present current_state.options[:enter]
end
# Return the current state
#
# @api public
def current_state
find_state(@current_state_name)
# TODO: add caching, i.e. with `@current_state ||= ...`
end
# Find event whose name is +event_name+
#
# @api semipublic
def find_event(event_name)
@events.find { |event| event.name.to_s == event_name.to_s }
# TODO: use a data structure that prevents duplicates
end
# Find state whose name is +event_name+
#
# @api semipublic
def find_state(state_name)
@states.find { |state| state.name.to_s == state_name.to_s }
# TODO: use a data structure that prevents duplicates
end
end
end # Data
end # StateMachine
end # Is
end # DataMapper
| 31.406593 | 80 | 0.558782 |
f73e3ecdf5ea70c6cae704b8ac4c4c622da22b4d | 4,005 | require 'adroll/demo_responses'
module AdRoll
class Service
include DemoResponses
attr_accessor :client
# Override Object's clone method and pass to method_missing
def self.clone(params)
method_missing(:clone, params)
end
def self.method_missing(meth, *args)
# @TODO add logging functionality and put deprecation warnings here
klass = new
klass.send(meth, *args)
end
def initialize(options = {})
@client = options.delete(:client)
end
def service_method
AdRoll::Utils.snakecase(self.class.to_s.gsub(/^.*::/, ''))
end
private
def service_url
raise NotImplementedError
end
def basic_auth
{ username: username, password: password }
end
def username
(client && client.user_name) || AdRoll.user_name
end
def password
(client && client.password) || AdRoll.password
end
def debug_output
$stdout if (client && client.debug?) || AdRoll.debug?
end
def demo_mode
ENV['RAILS_ENV'] == 'demo' || ENV['ADROLLER_DEMO_MODE'] == 'true'
end
# Pass in addtional_query_params if you need query parameters on url for
# HTTP requests that require you to pass in form body
def call_api(request_method, endpoint, params, additional_query_params = nil)
request_uri = File.join(service_url, endpoint.to_s)
response = make_api_call(request_method, request_uri, params, additional_query_params)
JSON.parse(response.body)
rescue JSON::ParserError
{ error: 'JSON::ParserError', response: response.body }
end
def make_api_call(request_method, request_uri, params, additional_query_params = nil)
# Include api_key with every call.
request_uri << "?apikey=#{AdRoll.api_key}"
if demo_mode
make_demo_response(request_method, request_uri, params, additional_query_params)
elsif request_method == :get
perform_get(request_method, request_uri, params)
elsif request_uri.include?('/audience/v1/segments')
perform_post_with_json_body(request_method, request_uri, params)
elsif additional_query_params.present?
perform_post_with_query(request_method, request_uri, params, additional_query_params)
else
perform_post(request_method, request_uri, params)
end
end
def perform_get(request_method, request_uri, params)
# For get requests, format the query params as defined by the AdRoll
# Spec - lists should be ?param=PARAM1,PARAM2
::AdRoll::HTTPartyWrapper.send(request_method,
request_uri,
basic_auth: basic_auth,
query: params,
debug_output: debug_output)
end
def perform_post_with_json_body(request_method, request_uri, params)
HTTParty.send(request_method,
request_uri,
headers: { 'Content-Type' => 'application/json' },
basic_auth: basic_auth,
body: params,
debug_output: debug_output)
end
def perform_post_with_query(request_method, request_uri, params, additional_query_params)
HTTParty.send(request_method,
request_uri,
headers: { 'Content-Type' => 'application/json' },
basic_auth: basic_auth,
query: additional_query_params,
body: params,
debug_output: debug_output)
end
def perform_post(request_method, request_uri, params)
# Unfortunately, HTTParty applies query_string_normalizer to `body`
# as well, so revert back to vanilla HTTParty for other requests.
HTTParty.send(request_method,
request_uri,
basic_auth: basic_auth,
body: params,
debug_output: debug_output)
end
end
end
| 33.099174 | 93 | 0.632959 |
d57a708880db708eaec10d56a8dffb2a5be8ad94 | 218 | require 'spec_helper'
describe GraphicalGitLogger do
it 'has a version number' do
expect(GraphicalGitLogger::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 18.166667 | 53 | 0.733945 |
ff80506109311cdffccdf8e865ddafadd3466617 | 192 | class AddIsFilterSpecsToErpProductsPropertyGroups < ActiveRecord::Migration[5.1]
def change
add_column :erp_products_property_groups, :is_filter_specs, :boolean, default: false
end
end | 38.4 | 88 | 0.822917 |
91b0b5cb28df7aa08f737504749671c2829bec2b | 1,107 | Gem::Specification.new do |s|
s.name = "textfile"
s.version = "1.1.0"
s.authors = ["Piers Chambers"]
s.email = "[email protected]"
s.summary = "Set-like wrapper around GNU comm and related textfile utilities."
s.description = "Set-like wrapper around GNU comm and related textfile utilities.\n\nA common use case is to identify differences between exported datasets where the datasets may exceed 100K rows and each row may exceed 4K characters."
s.homepage = "http://github.com/varyonic/textfile"
s.license = "MIT"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
".travis.yml",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/textfile.rb",
"test/helper.rb",
"test/test_textfile.rb",
"textfile.gemspec"
]
s.add_development_dependency "minitest", '~> 5.0'
s.add_development_dependency "rdoc", "~> 3.12"
end
| 29.918919 | 237 | 0.665763 |
f7902b65ad7e9be9c0a694f7b3d973f519a1a081 | 592 | name 'apache2'
source_url 'https://github.com/sous-chefs/apache2'
issues_url 'https://github.com/sous-chefs/apache2/issues'
maintainer 'Sous Chefs'
maintainer_email '[email protected]'
chef_version '>= 13.0'
license 'Apache-2.0'
description 'Installs and configures apache2'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '5.0.1'
supports 'debian'
supports 'ubuntu'
supports 'redhat'
supports 'centos'
supports 'fedora'
supports 'amazon'
supports 'scientific'
supports 'freebsd'
supports 'suse'
supports 'opensuse'
supports 'opensuseleap'
supports 'arch'
| 24.666667 | 72 | 0.778716 |
614361d3c264963217ed5c5e7e1466e8b852d22e | 1,955 | require 'spec_helper'
require 'rspec/given'
require 'given/assertions'
describe Given::Assertions do
use_natural_assertions_if_supported
Given { extend Given::Assertions }
describe "Assert { }" do
Given { Given::Assertions.enable_asserts }
context "with true assertion" do
When(:result) { Assert { true } }
Then { result != Failure() }
end
context "with false assertion" do
When(:result) {
Assert { false }
}
Then { result == Failure(Given::Assertions::AssertError, /Assert.*false/) }
end
context "when disabled" do
Given { Given::Assertions.enable_asserts false }
When(:result) { Assert { false } }
Then { result != Failure() }
end
end
describe "Precondition { }" do
Given { Given::Assertions.enable_preconditions }
context "with true assertion" do
When(:result) { Precondition { true } }
Then { result != Failure() }
end
context "with false assertion" do
When(:result) {
Precondition { false }
}
Then { result == Failure(Given::Assertions::PreconditionError, /Precondition.*false/) }
end
context "when disabled" do
Given { Given::Assertions.enable_preconditions false }
When(:result) { Precondition { false } }
Then { result != Failure() }
end
end
describe "Postcondition { }" do
Given { Given::Assertions.enable_preconditions }
context "with true assertion" do
When(:result) { Postcondition { true } }
Then { result != Failure() }
end
context "with false assertion" do
When(:result) {
Postcondition { false }
}
Then { result == Failure(Given::Assertions::PostconditionError, /Postcondition.*false/) }
end
context "when disabled" do
Given { Given::Assertions.enable_preconditions false }
When(:result) { Postcondition { false } }
Then { result != Failure() }
end
end
end
| 25.723684 | 95 | 0.625575 |
6273080e15a6f470a6e3f74c7d2356bac94613ca | 699 | require 'spec_helper'
describe UsersController do
describe 'routing' do
it 'routes to #index' do
expect(get('/users')).to route_to('users#index')
end
it 'routes to #show' do
expect(get('/users/1')).to route_to('users#show', id: '1')
end
it 'routes to #edit' do
expect(get('/users/1/edit')).to route_to('users#edit', id: '1')
end
it 'routes to #create' do
expect(post('/users')).to route_to('users#create')
end
it 'routes to #update' do
expect(put('/users/1')).to route_to('users#update', id: '1')
end
it 'routes to #destroy' do
expect(delete('/users/1')).to route_to('users#destroy', id: '1')
end
end
end
| 23.3 | 70 | 0.597997 |
1df0dddb9e8b281c58b69d25f333cf8e2d170c71 | 1,006 | # Copyright (C) 2014 Ruby-GNOME2 Project Team
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class ClutterBlurEffectTest < Test::Unit::TestCase
include ClutterTestUtils
def setup
@blur_effect = Clutter::BlurEffect.new
end
def test_blur_effect_new
assert_kind_of(Clutter::Effect, @blur_effect)
end
end
| 35.928571 | 80 | 0.766402 |
ffe860857e65b4384be4fdcd0f58aec1be81720b | 3,510 | require 'spec_helper'
describe Citygram::Workers::SubscriptionConfirmation do
subject { Citygram::Workers::SubscriptionConfirmation.new }
context 'email' do
include Mail::Matchers
let(:to_email_address) { '[email protected]' }
let(:from_email_address) { ENV.fetch('SMTP_FROM_ADDRESS') }
let(:publisher) { subscription.publisher }
let!(:subscription) { create(:subscription, channel: 'email', email_address: to_email_address) }
it 'retrieves the subscription of interest' do
expect(Subscription).to receive(:first!).with(id: subscription.id).and_return(subscription)
subject.perform(subscription.id)
end
around do |example|
original = Pony.options.dup
Pony.options = Pony.options.merge(via: :test)
example.run
Pony.options = original
end
context 'success' do
before do
subject.perform(subscription.id)
end
it { is_expected.to have_sent_email.from(from_email_address) }
it { is_expected.to have_sent_email.to(to_email_address) }
it { is_expected.to have_sent_email.with_subject("Citygram: You're subscribed to #{publisher.city} #{publisher.title}") }
# it { is_expected.to have_sent_email.with_html_body("<p>Thank you for subscribing!</p>") }
end
end
context 'sms' do
let(:publisher) { subscription.publisher }
let!(:subscription) { create(:subscription, channel: 'sms', phone_number: '212-555-1234') }
before do
body = "Welcome! You are now subscribed to #{publisher.title} in #{publisher.city}. To see current Citygrams please visit #{subject.digest_url(subscription)}. To unsubscribe from all messages, reply REMOVE."
stub_request(:post, "https://dev-account-sid:[email protected]/2010-04-01/Accounts/dev-account-sid/Messages.json").
with(body: {
"Body" => body,
"From"=>"15555555555",
"To"=>"212-555-1234"}).
to_return(status: 200, body: {
'sid' => 'SM10ea1dce707f4bedb44204c9fbc02e39',
'to' => subscription.phone_number,
'from' => '15555555555',
'body' => body,
'status' => 'queued'
}.to_json)
end
it 'retrieves the subscription of interest' do
expect(Subscription).to receive(:first!).with(id: subscription.id).and_return(subscription)
subject.perform(subscription.id)
end
it 'logs exceptions from twilio and retries' do
error = Twilio::REST::RequestError.new('test failure', 1234)
expect(Citygram::App.logger).to receive(:error).with(error)
expect(Citygram::Services::Channels::SMS).to receive(:sms).and_raise(error)
expect {
subject.perform(subscription.id)
}.to raise_error Citygram::Services::Channels::NotificationFailure, /test failure/
end
Citygram::Services::Channels::SMS::UNSUBSCRIBE_ERROR_CODES.each do |error_code|
context "Twilio Error Code: #{error_code}" do
it 'deactivates the subscription' do
error = Twilio::REST::RequestError.new('test failure', error_code)
expect(Citygram::Services::Channels::SMS).to receive(:sms).and_raise(error)
expect {
subject.perform(subscription.id)
}.to change{ subscription.reload.unsubscribed_at.present? }.from(false).to(true)
end
end
end
end
it 'limits the number of retries' do
retries = Citygram::Workers::SubscriptionConfirmation.sidekiq_options_hash["retry"]
expect(retries).to eq 5
end
end
| 37.340426 | 213 | 0.673219 |
189bea4274db92b11c9d29d315207f6ca17bf35a | 4,320 | require 'spec_helper'
require 'date'
require 'time'
RSpec.describe ApexCharts::Utils::DateTime do
context '.convert' do
let(:converted) { described_class.convert(input) }
context 'input is a Time' do
let(:input) { Time.iso8601('2019-06-18T20:20:20+0700') }
it 'converts correctly' do
expect(converted).to eq 1560864020000
end
end
context 'input is a DateTime' do
let(:input) { DateTime.iso8601('2019-06-18T20:20:20+0700') }
it 'converts correctly' do
expect(converted).to eq 1560864020000
end
end
context 'input is a Date' do
let(:input) { Date.iso8601('2019-06-18T00:00:00+07:00') }
before do
ENV['TZ'] = 'UTC'
end
after do
ENV['TZ'] = nil
end
it 'converts correctly' do
expect(converted).to eq 1560816000000
end
end
context 'input is a string of DateTime' do
let(:input) { '2019-06-18T20:20:20+07:00' }
it 'converts correctly' do
expect(converted).to eq 1560864020000
end
end
context 'input is a string of Date' do
let(:input) { '2019-06-18' }
before do
ENV['TZ'] = 'UTC'
end
after do
ENV['TZ'] = nil
end
it 'converts correctly' do
expect(converted).to eq 1560816000000
end
end
context 'input is anything else' do
let(:input) { '2' }
it 'converts correctly' do
expect(converted).to eq '2'
end
end
end
context '.convert_range' do
let(:converted) { described_class.convert_range(input) }
context 'input is a Time' do
let(:input) {
Time.iso8601('2019-06-08T10:10:10+0700')..Time.parse('2019-06-18 20:20:20 +0700')
}
it 'converts correctly' do
expect(converted).to eq 1559963410000..1560864020000
end
end
context 'input is a DateTime' do
let(:input) {
DateTime.iso8601('2019-06-08T10:10:10+0700')..DateTime.parse('2019-06-18T20:20:20+0700')
}
it 'converts correctly' do
expect(converted).to eq 1559963410000..1560864020000
end
end
context 'input is a Date' do
let(:input) { Date.iso8601('2019-06-08')..Date.parse('2019-06-18') }
before do
ENV['TZ'] = 'UTC'
end
after do
ENV['TZ'] = nil
end
it 'converts correctly' do
expect(converted).to eq 1559952000000..1560816000000
end
end
context 'input is a string of DateTime' do
let(:input) { '2019-06-08T10:10:10+07:00'..'2019-06-18T20:20:20+07:00' }
it 'converts correctly' do
expect(converted).to eq 1559963410000..1560864020000
end
end
context 'input is a string of Date' do
let(:input) { '2019-06-08'..'2019-06-18' }
before do
ENV['TZ'] = 'UTC'
end
after do
ENV['TZ'] = nil
end
it 'converts correctly' do
expect(converted).to eq 1559952000000..1560816000000
end
end
context 'input is anything else' do
let(:input) { ['2'] }
it 'converts correctly' do
expect(converted).to eq ['2']
end
end
end
context '.type' do
let(:type) { described_class.type(input) }
context 'input is a Time' do
let(:input) { Time.iso8601('2019-06-18T20:20:20+0700') }
it 'converts correctly' do
expect(type).to eq 'datetime'
end
end
context 'input is a DateTime' do
let(:input) { DateTime.iso8601('2019-06-18T20:20:20+0700') }
it 'converts correctly' do
expect(type).to eq 'datetime'
end
end
context 'input is a Date' do
let(:input) { Date.iso8601('2019-06-18') }
it 'converts correctly' do
expect(type).to eq 'datetime'
end
end
context 'input is a string of DateTime' do
let(:input) { '2019-06-18T20:20:20+07:00' }
it 'converts correctly' do
expect(type).to eq 'datetime'
end
end
context 'input is a string of Date' do
let(:input) { '2019-06-18' }
it 'converts correctly' do
expect(type).to eq 'datetime'
end
end
context 'input is anything else' do
let(:input) { ['2'] }
it 'returns nil' do
expect(type).to eq nil
end
end
end
end
| 21.818182 | 96 | 0.578009 |
01cf77d5a28650892a243ab85e038a5795eb8c0a | 946 | require "rails_helper"
RSpec.describe LocationsController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/locations").to route_to("locations#index")
end
it "routes to #show" do
expect(:get => "/locations/1").to route_to("locations#show", :id => "1")
end
it "routes to #edit" do
expect(:get => "/locations/1/edit").to route_to("locations#edit", :id => "1")
end
it "routes to #create" do
expect(:post => "/locations").to route_to("locations#create")
end
it "routes to #update via PUT" do
expect(:put => "/locations/1").to route_to("locations#update", :id => "1")
end
it "routes to #update via PATCH" do
expect(:patch => "/locations/1").to route_to("locations#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/locations/1").to route_to("locations#destroy", :id => "1")
end
end
end
| 26.277778 | 84 | 0.603594 |
380f8abfee22f7487029a6d736f6af176ad74e50 | 1,268 | require 'spec_helper'
RSpec.describe Algorithms::BinarySearch do
it 'finds the target index' do
sorted_array = [1,3,5,7,9,11,13]
index = described_class.search(sorted_array, 11)
expect(index).to eq 5
index = described_class.search(sorted_array, 1)
expect(index).to eq 0
index = described_class.search(sorted_array, 13)
expect(index).to eq 6
end
it 'finds target in a array with 2 items' do
sorted_array = [1,3]
expect(described_class.search(sorted_array, 1)).to eq 0
expect(described_class.search(sorted_array, 3)).to eq 1
end
it 'finds target in a array with only 1 item' do
sorted_array = [1]
expect(described_class.search(sorted_array, 1)).to eq 0
end
context 'when target is not in the array' do
it 'returns nil' do
sorted_array = [1,3]
expect(described_class.search(sorted_array, 2)).to be nil
end
end
context 'when array is empty' do
it 'returns nil' do
sorted_array = []
expect(described_class.search(sorted_array, 2)).to be nil
end
end
context 'when array is nil' do
it 'raises exception' do
sorted_array = nil
expect { described_class.search(sorted_array, 2) }.to raise_error 'sorted_array can not be nil'
end
end
end
| 25.877551 | 101 | 0.683754 |
e9f3d8b45d368dc6cd622f5b16c042120437fb90 | 609 | # An abstract class for asyncronous jobs that transcode files using FFMpeg
module Hydra::Derivatives::Processors
module Ffmpeg
extend ActiveSupport::Concern
INPUT_OPTIONS = :input_options
OUTPUT_OPTIONS = :output_options
included do
include ShellBasedProcessor
end
module ClassMethods
def encode(path, options, output_file)
inopts = options[INPUT_OPTIONS] ||= "-y"
outopts = options[OUTPUT_OPTIONS] ||= ""
execute "#{Hydra::Derivatives.ffmpeg_path} #{inopts} -i #{Shellwords.escape(path)} #{outopts} #{output_file}"
end
end
end
end
| 27.681818 | 117 | 0.689655 |
e8c9436798edc7bf3144237a43b3d2dafb84de10 | 136 | module Employer
class Employer < OpenStruct
def locations
super.map { |location| Location.new(location) }
end
end
end
| 17 | 53 | 0.683824 |
b90abe61addbe0d987a7994dfd2d82891ab24e11 | 7,794 | =begin
#DocuSign REST API
#The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.13-SNAPSHOT
=end
require 'date'
module DocuSign_eSign
class BccEmailArchiveHistoryList
#
attr_accessor :bcc_email_archive_history
# The last position in the result set.
attr_accessor :end_position
# The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
attr_accessor :next_uri
# The postal code for the billing address.
attr_accessor :previous_uri
# The number of results returned in this response.
attr_accessor :result_set_size
# Starting position of the current result set.
attr_accessor :start_position
# The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
attr_accessor :total_set_size
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'bcc_email_archive_history' => :'bccEmailArchiveHistory',
:'end_position' => :'endPosition',
:'next_uri' => :'nextUri',
:'previous_uri' => :'previousUri',
:'result_set_size' => :'resultSetSize',
:'start_position' => :'startPosition',
:'total_set_size' => :'totalSetSize'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'bcc_email_archive_history' => :'Array<BccEmailArchiveHistory>',
:'end_position' => :'String',
:'next_uri' => :'String',
:'previous_uri' => :'String',
:'result_set_size' => :'String',
:'start_position' => :'String',
:'total_set_size' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'bccEmailArchiveHistory')
if (value = attributes[:'bccEmailArchiveHistory']).is_a?(Array)
self.bcc_email_archive_history = value
end
end
if attributes.has_key?(:'endPosition')
self.end_position = attributes[:'endPosition']
end
if attributes.has_key?(:'nextUri')
self.next_uri = attributes[:'nextUri']
end
if attributes.has_key?(:'previousUri')
self.previous_uri = attributes[:'previousUri']
end
if attributes.has_key?(:'resultSetSize')
self.result_set_size = attributes[:'resultSetSize']
end
if attributes.has_key?(:'startPosition')
self.start_position = attributes[:'startPosition']
end
if attributes.has_key?(:'totalSetSize')
self.total_set_size = attributes[:'totalSetSize']
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 &&
bcc_email_archive_history == o.bcc_email_archive_history &&
end_position == o.end_position &&
next_uri == o.next_uri &&
previous_uri == o.previous_uri &&
result_set_size == o.result_set_size &&
start_position == o.start_position &&
total_set_size == o.total_set_size
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[bcc_email_archive_history, end_position, next_uri, previous_uri, result_set_size, start_position, total_set_size].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = DocuSign_eSign.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 31.427419 | 177 | 0.636259 |
1d7941b8a17e4583b246417ec30b7af7febd4c9c | 405 | # frozen_string_literal: true
require "cli/parser"
require "utils/shell"
module Homebrew
module_function
def security_available_tools_args
Homebrew::CLI::Parser.new do
description <<~EOS
Prints list of available tools for m9/security tap
EOS
end
end
def security_available_tools
security_available_tools_args.parse
puts 'security_available_tools'
end
end | 18.409091 | 58 | 0.74321 |
390daff87198c6d80eec2862d223e0eb9fd56f9c | 5,099 | #
# Be sure to run `pod spec lint PrettyRuler.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "PrettyRuler"
s.version = "2.1.1"
s.summary = "一个漂亮的横向刻度尺自定义控件,用CAShapeLayer实现高效GPU渲染"
# 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
"CAShapeLayer实现高效GPU渲染,漂亮的自定义横向直尺控件,iOS7以上,刻度最小精度0.1,不足0.5时自减,大于0.5时自增"
DESC
s.homepage = "https://github.com/AsTryE/PrettyRuler"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (LICENSE)"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "AsTryE" => "[email protected]" }
# Or just: s.author = "AsTryE"
# s.authors = { "AsTryE" => "[email protected]" }
# s.social_media_url = "http://twitter.com/AsTryE"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
s.ios.deployment_target = "7.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/AsTryE/PrettyRuler.git", :tag => "2.1.1" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "PrettyRuler/PrettyRulerClass/*"
# s.exclude_files = "Classes/Exclude"
s.public_header_files = "PrettyRuler/PrettyRulerClass/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
s.framework = "UIKit","QuartzCore"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 36.949275 | 93 | 0.595019 |
03aebb03ecec8f530dcb7b99fcba0ebbbed051ad | 1,516 | #
# Cookbook Name:: bcpc
# Recipe:: kibana
#
# Copyright 2013, Bloomberg Finance L.P.
#
# 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.
#
include_recipe "bcpc::default"
include_recipe "bcpc::apache2"
remote_file "/tmp/kibana3.tgz" do
source "#{get_binary_server_url}/kibana3.tgz"
owner "root"
mode 00444
not_if { Dir.exists? "/opt/kibana3" }
end
bash "install-kibana" do
code <<-EOH
tar zxf /tmp/kibana3.tgz -C /opt/
EOH
not_if { Dir.exists? "/opt/kibana3" }
end
template "/opt/kibana3/config.js" do
source "kibana-config.js.erb"
user "root"
group "root"
mode 00644
end
template "/etc/apache2/sites-available/kibana-web" do
source "apache-kibana-web.conf.erb"
owner "root"
group "root"
mode 00644
notifies :restart, "service[apache2]", :delayed
end
bash "apache-enable-kibana-web" do
user "root"
code "a2ensite kibana-web"
not_if "test -r /etc/apache2/sites-enabled/kibana-web"
notifies :restart, "service[apache2]", :delayed
end
| 26.137931 | 74 | 0.704485 |
1c604d301f19bfda827b5e466581ae9a3680284b | 570 | # frozen_string_literal: true
require_relative 'command_handler'
module Ftpd
class CmdType < CommandHandler
def cmd_type(argument)
ensure_logged_in
syntax_error unless argument =~ /^\S(?: \S+)?$/
unless argument =~ /^([AEI]( [NTC])?|L .*)$/
error 'Invalid type code', 504
end
case argument
when /^A( [NT])?$/
self.data_type = 'A'
when /^(I|L 8)$/
self.data_type = 'I'
else
error 'Type not implemented', 504
end
reply "200 Type set to #{data_type}"
end
end
end
| 19.655172 | 53 | 0.568421 |
f70e664761d05372f11231cf07e1736089e2655e | 1,630 | class ApplicationController < ActionController::Base
config.relative_url_root = ""
protect_from_forgery
layout 'application'
before_filter :locale_workaround
helper_method :current_user
def paginated_scope(relation)
instance_variable_set "@#{controller_name}", relation.page(params[:page])
end
hide_action :paginated_scope
private
def set_select_domains
@domains = Domain.active
end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def require_user
request_auth unless current_user
end
def require_admin
request_auth and return unless current_user
unauthorized unless current_user.admin
end
def request_auth
respond_to do |format|
format.html {redirect_to login_path}
format.any(:json, :xml) {request_http_basic_authentication}
end
end
def unauthorized
respond_to do |format|
format.html do
flash[:error]=t(:'messages.adminrequired')
redirect_to login_path
end
format.any(:json, :xml) do
render :text=> t(:'messages.adminrequired'), :status => :forbidden
end
end
end
def set_modificator(model, method=action_name, user=current_user)
model.send("#{method}d_by=", user.login) if user
end
def locale_workaround
I18n.locale = I18n.default_locale if Rails.env == "production"
end
end
| 24.328358 | 77 | 0.709816 |
1a7dc0dafe6e5a57158c44bbe3caf923416a1ff4 | 706 | require 'spec_helper'
describe RemoveUnusedTags::Job do
describe "#perform" do
let!(:project) { projects(:socialitis) }
let!(:aggregate_project) { aggregate_projects(:internal_projects_aggregate) }
before do
ActsAsTaggableOn::Tag.destroy_all
ActsAsTaggableOn::Tag.create!(name: "iamunused")
project.tag_list.add("project-tag")
project.save!
aggregate_project.tag_list.add("aggregate-project-tag")
aggregate_project.save!
end
it "removes unused tags" do
RemoveUnusedTags::Job.new.perform
remaining_tags = ActsAsTaggableOn::Tag.all.map(&:name)
remaining_tags.should =~ ['project-tag', 'aggregate-project-tag']
end
end
end
| 28.24 | 81 | 0.699717 |
f7fa394fd5850b5c7d9508851a9f07759f7dec9f | 382 | require 'pathname'
module Gamefic
module Sdk
module Tasks
# Common methods for Rake tasks.
#
module Common
attr_reader :directory
def initialize directory = '.'
@directory = directory
end
def absolute_path
@absolute_path ||= Pathname.new(directory).realpath.to_s
end
end
end
end
end
| 17.363636 | 66 | 0.586387 |
e831ced3525cd60074c1f46e7c3e1e1523942481 | 754 | class SessionsController < ApplicationController
get '/login' do
redirect_if_logged_in
erb :'sessions/new'
end
post '/login' do
redirect_if_logged_in
user = User.find_by(email: params["user"]["email"])
if user && user.authenticate(params["user"]["password"])
session["user_id"] = user.id
flash[:error]="Welcome to Poison, #{user.name}"
redirect "/cocktails"
else
flash[:error]="Either Username or Password does not match with our record, try again"
redirect "/login"
end
end
get '/logout' do
redirect_if_not_logged_in
session.delete("user_id")
redirect "/"
end
end | 30.16 | 98 | 0.568966 |
91fcf3f5c31bba681f74ad322ec8b5c589b315b9 | 43 | require './web.rb'
run GeradorCertificados
| 14.333333 | 23 | 0.790698 |
1a991ca5601ff5fa8bbdaa99c476e7a23da29c72 | 5,775 | module ActsAsSolr #:nodoc:
module InstanceMethods
# Solr id is <class.name>:<id> to be unique across all models
def solr_id
"#{self.class.name}:#{record_id(self)}"
end
# saves to the Solr index
def solr_save
return true if indexing_disabled?
if evaluate_condition(:if, self)
logger.debug "solr_save: #{self.class.name} : #{record_id(self)}"
solr_add to_solr_doc
solr_commit if configuration[:auto_commit]
true
else
solr_destroy
end
end
def indexing_disabled?
evaluate_condition(:offline, self) || !configuration[:if]
end
# remove from index
def solr_destroy
return true if indexing_disabled?
logger.debug "solr_destroy: #{self.class.name} : #{record_id(self)}"
solr_delete solr_id
solr_commit if configuration[:auto_commit]
true
end
# convert instance to Solr document
def to_solr_doc
logger.debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}"
doc = Solr::Document.new
doc.boost = validate_boost(configuration[:boost]) if configuration[:boost]
doc << {:id => solr_id,
solr_configuration[:type_field] => self.class.name,
solr_configuration[:primary_key_field] => record_id(self).to_s}
# iterate through the fields and add them to the document,
configuration[:solr_fields].each do |field_name, options|
#field_type = configuration[:facets] && configuration[:facets].include?(field) ? :facet : :text
field_boost = options[:boost] || solr_configuration[:default_boost]
field_type = get_solr_field_type(options[:type])
solr_name = options[:as] || field_name
value = self.send("#{field_name}_for_solr")
value = set_value_if_nil(field_type) if value.to_s == ""
# add the field to the document, but only if it's not the id field
# or the type field (from single table inheritance), since these
# fields have already been added above.
if field_name.to_s != self.class.primary_key and field_name.to_s != "type"
suffix = get_solr_field_type(field_type)
# This next line ensures that e.g. nil dates are excluded from the
# document, since they choke Solr. Also ignores e.g. empty strings,
# but these can't be searched for anyway:
# http://www.mail-archive.com/[email protected]/msg05423.html
next if value.nil? || value.to_s.strip.empty?
[value].flatten.each do |v|
v = set_value_if_nil(suffix) if value.to_s == ""
field = Solr::Field.new("#{solr_name}_#{suffix}" => ERB::Util.html_escape(v.to_s))
field.boost = validate_boost(field_boost)
doc << field
end
end
end
add_includes(doc)
logger.debug doc.to_xml
doc
end
private
def add_includes(doc)
if configuration[:solr_includes].respond_to?(:each)
configuration[:solr_includes].each do |association, options|
data = options[:multivalued] ? [] : ""
field_name = options[:as] || association.to_s.singularize
field_type = get_solr_field_type(options[:type])
field_boost = options[:boost] || solr_configuration[:default_boost]
suffix = get_solr_field_type(field_type)
case self.class.reflect_on_association(association).macro
when :has_many, :has_and_belongs_to_many
records = self.send(association).to_a
unless records.empty?
records.each {|r| data << include_value(r, options)}
[data].flatten.each do |value|
field = Solr::Field.new("#{field_name}_#{suffix}" => value)
field.boost = validate_boost(field_boost)
doc << field
end
end
when :has_one, :belongs_to
record = self.send(association)
unless record.nil?
doc["#{field_name}_#{suffix}"] = include_value(record, options)
end
end
end
end
end
def include_value(record, options)
if options[:using].is_a? Proc
options[:using].call(record)
elsif options[:using].is_a? Symbol
record.send(options[:using])
else
record.attributes.inject([]){|k,v| k << "#{v.first}=#{ERB::Util.html_escape(v.last)}"}.join(" ")
end
end
def validate_boost(boost)
boost_value = case boost
when Float
return solr_configuration[:default_boost] if boost < 0
boost
when Proc
boost.call(self)
when Symbol
if self.respond_to?(boost)
self.send(boost)
end
end
boost_value || solr_configuration[:default_boost]
end
def condition_block?(condition)
condition.respond_to?("call") && (condition.arity == 1 || condition.arity == -1)
end
def evaluate_condition(which_condition, field)
condition = configuration[which_condition]
case condition
when Symbol
field.send(condition)
when String
eval(condition, binding)
when FalseClass, NilClass
false
when TrueClass
true
else
if condition_block?(condition)
condition.call(field)
else
raise(
ArgumentError,
"The :#{which_condition} option has to be either a symbol, string (to be eval'ed), proc/method, true/false, or " +
"class implementing a static validation method"
)
end
end
end
end
end | 34.580838 | 128 | 0.602424 |
39cca475821c548a359d00803de1d295c82754cb | 462 | require 'spec_helper'
describe Sansu::Operator do
describe '#sum' do
it { expect([1, 2, 3].sum).to eq 6.0 }
end
describe '#mean' do
it { expect([1, 2, 3].mean).to eq 2.0 }
end
describe '#median' do
it { expect([2, 2, 1, 3].median).to eq 2.0 }
it { expect([5, 4, 6].median).to eq 5.0 }
end
describe '#mode' do
it { expect([1, 2, 2, 3].mode).to eq [2.0] }
it { expect([4.5, 6, 6.0, 4.5].mode).to eq [4.5, 6.0] }
end
end
| 21 | 59 | 0.541126 |
6a1c2111ac9cc39d26333d5228c8607f10559aaf | 13,517 | =begin
#Hydrogen Proton API
#Financial engineering module of Hydrogen Atom
OpenAPI spec version: 1.7.18
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.14
=end
require 'date'
module ProtonApi
class PurchaseCalculatorAmountRequest
attr_accessor :deposit_schedule
attr_accessor :portfolio_return
attr_accessor :inflation_rate
attr_accessor :investment_tax
attr_accessor :purchase_horizon
attr_accessor :aggregation_account_ids
attr_accessor :account_ids
attr_accessor :current_savings
attr_accessor :horizon_frequency_interval
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
{
:'deposit_schedule' => :'deposit_schedule',
:'portfolio_return' => :'portfolio_return',
:'inflation_rate' => :'inflation_rate',
:'investment_tax' => :'investment_tax',
:'purchase_horizon' => :'purchase_horizon',
:'aggregation_account_ids' => :'aggregation_account_ids',
:'account_ids' => :'account_ids',
:'current_savings' => :'current_savings',
:'horizon_frequency_interval' => :'horizon_frequency_interval'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'deposit_schedule' => :'Object',
:'portfolio_return' => :'Float',
:'inflation_rate' => :'Float',
:'investment_tax' => :'Float',
:'purchase_horizon' => :'Integer',
:'aggregation_account_ids' => :'Array<String>',
:'account_ids' => :'Array<String>',
:'current_savings' => :'Float',
:'horizon_frequency_interval' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'deposit_schedule')
self.deposit_schedule = attributes[:'deposit_schedule']
end
if attributes.has_key?(:'portfolio_return')
self.portfolio_return = attributes[:'portfolio_return']
end
if attributes.has_key?(:'inflation_rate')
self.inflation_rate = attributes[:'inflation_rate']
else
self.inflation_rate = 0.0
end
if attributes.has_key?(:'investment_tax')
self.investment_tax = attributes[:'investment_tax']
else
self.investment_tax = 0.0
end
if attributes.has_key?(:'purchase_horizon')
self.purchase_horizon = attributes[:'purchase_horizon']
end
if attributes.has_key?(:'aggregation_account_ids')
if (value = attributes[:'aggregation_account_ids']).is_a?(Array)
self.aggregation_account_ids = value
end
end
if attributes.has_key?(:'account_ids')
if (value = attributes[:'account_ids']).is_a?(Array)
self.account_ids = value
end
end
if attributes.has_key?(:'current_savings')
self.current_savings = attributes[:'current_savings']
else
self.current_savings = 0.0
end
if attributes.has_key?(:'horizon_frequency_interval')
self.horizon_frequency_interval = attributes[:'horizon_frequency_interval']
else
self.horizon_frequency_interval = 'year'
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 @portfolio_return.nil?
invalid_properties.push('invalid value for "portfolio_return", portfolio_return cannot be nil.')
end
if @portfolio_return < -1
invalid_properties.push('invalid value for "portfolio_return", must be greater than or equal to -1.')
end
if !@inflation_rate.nil? && @inflation_rate < -1
invalid_properties.push('invalid value for "inflation_rate", must be greater than or equal to -1.')
end
if !@investment_tax.nil? && @investment_tax > 1
invalid_properties.push('invalid value for "investment_tax", must be smaller than or equal to 1.')
end
if !@investment_tax.nil? && @investment_tax < 0
invalid_properties.push('invalid value for "investment_tax", must be greater than or equal to 0.')
end
if @purchase_horizon.nil?
invalid_properties.push('invalid value for "purchase_horizon", purchase_horizon cannot be nil.')
end
if @purchase_horizon < 0
invalid_properties.push('invalid value for "purchase_horizon", must be greater than or equal to 0.')
end
if !@current_savings.nil? && @current_savings < 0
invalid_properties.push('invalid value for "current_savings", must be greater than or equal to 0.')
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 @portfolio_return.nil?
return false if @portfolio_return < -1
return false if !@inflation_rate.nil? && @inflation_rate < -1
return false if !@investment_tax.nil? && @investment_tax > 1
return false if !@investment_tax.nil? && @investment_tax < 0
return false if @purchase_horizon.nil?
return false if @purchase_horizon < 0
return false if !@current_savings.nil? && @current_savings < 0
horizon_frequency_interval_validator = EnumAttributeValidator.new('String', ['year', 'quarter', 'month', 'week'])
return false unless horizon_frequency_interval_validator.valid?(@horizon_frequency_interval.downcase)
true
end
# Custom attribute writer method with validation
# @param [Object] portfolio_return Value to be assigned
def portfolio_return=(portfolio_return)
if portfolio_return.nil?
fail ArgumentError, 'portfolio_return cannot be nil'
end
if portfolio_return < -1
fail ArgumentError, 'invalid value for "portfolio_return", must be greater than or equal to -1.'
end
@portfolio_return = portfolio_return
end
# Custom attribute writer method with validation
# @param [Object] inflation_rate Value to be assigned
def inflation_rate=(inflation_rate)
if !inflation_rate.nil? && inflation_rate < -1
fail ArgumentError, 'invalid value for "inflation_rate", must be greater than or equal to -1.'
end
@inflation_rate = inflation_rate
end
# Custom attribute writer method with validation
# @param [Object] investment_tax Value to be assigned
def investment_tax=(investment_tax)
if !investment_tax.nil? && investment_tax > 1
fail ArgumentError, 'invalid value for "investment_tax", must be smaller than or equal to 1.'
end
if !investment_tax.nil? && investment_tax < 0
fail ArgumentError, 'invalid value for "investment_tax", must be greater than or equal to 0.'
end
@investment_tax = investment_tax
end
# Custom attribute writer method with validation
# @param [Object] purchase_horizon Value to be assigned
def purchase_horizon=(purchase_horizon)
if purchase_horizon.nil?
fail ArgumentError, 'purchase_horizon cannot be nil'
end
if purchase_horizon < 0
fail ArgumentError, 'invalid value for "purchase_horizon", must be greater than or equal to 0.'
end
@purchase_horizon = purchase_horizon
end
# Custom attribute writer method with validation
# @param [Object] current_savings Value to be assigned
def current_savings=(current_savings)
if !current_savings.nil? && current_savings < 0
fail ArgumentError, 'invalid value for "current_savings", must be greater than or equal to 0.'
end
@current_savings = current_savings
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] horizon_frequency_interval Object to be assigned
def horizon_frequency_interval=(horizon_frequency_interval)
validator = EnumAttributeValidator.new('String', ['year', 'quarter', 'month', 'week'])
unless validator.valid?(horizon_frequency_interval.downcase)
fail ArgumentError, 'invalid value for "horizon_frequency_interval", must be one of #{validator.allowable_values}.'
end
@horizon_frequency_interval = horizon_frequency_interval
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 &&
deposit_schedule == o.deposit_schedule &&
portfolio_return == o.portfolio_return &&
inflation_rate == o.inflation_rate &&
investment_tax == o.investment_tax &&
purchase_horizon == o.purchase_horizon &&
aggregation_account_ids == o.aggregation_account_ids &&
account_ids == o.account_ids &&
current_savings == o.current_savings &&
horizon_frequency_interval == o.horizon_frequency_interval
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[deposit_schedule, portfolio_return, inflation_rate, investment_tax, purchase_horizon, aggregation_account_ids, account_ids, current_savings, horizon_frequency_interval].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = ProtonApi.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 33.375309 | 180 | 0.656359 |
8723791971567f6c50bb9ea9a8feb58c802c62c2 | 711 | require 'pathname'
# An isolated operation to perform on a set of files
class Task
include Virtus.value_object
values do
attribute :id, String
attribute :type, String
attribute :status, String
attribute :language, String
attribute :tool, String
attribute :build, Build
attribute :source_files, Array[SourceFile], default: []
end
delegate :pull_request, :ssh_public_key, :ssh_private_key, to: :build
delegate :head_sha, :base_sha, :clone_url, to: :pull_request
def slug
"#{build.slug}/#{id}"
end
def inspect
"<#{self.class.name}: #{id} Run #{tool} on #{language} files>"
end
def read_attribute_for_serialization(name)
public_send(name)
end
end
| 22.21875 | 71 | 0.697609 |
7a5644b800397741615318021b958dd5a77d9308 | 946 | lat = params[:latitude].to_f
lng = params[:longitude].to_f
store = @outlet.store
json.store_name store.name
json.store_id store.id
json.outlet_locality @outlet.locality
json.outlet_phone @outlet.phone_number
json.is_following_store current_user.follow_store?(store)
json.steps @outlet.steps(lat, lng)
json.deals @deals do |deal|
json.id deal.id
json.title deal.title
json.deal_photo deal.deal_photo
json.liked_by_user current_user.favourite_deal?(deal)
json.price_flag deal.has_price?
json.actual_price deal.price.to_i
json.discounted_price deal.discounted_price.to_i
json.deal_type deal.deal_type_to_s
end
json.upcoming_deals @upcoming_deals do |deal|
json.id deal.id
json.title deal.title
json.deal_photo deal.deal_photo
json.liked_by_user current_user.favourite_deal?(deal)
json.actual_price deal.price.to_i
json.discounted_price deal.discounted_price.to_i
json.deal_type deal.deal_type_to_s
end
json.status status
| 27.823529 | 57 | 0.813953 |
7aaaf688812e9927168a26b334a3973013e3e75d | 254 | class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.references :store, index:true
t.string :name
t.decimal :price
t.text :details
t.timestamps null: false
end
end
end
| 21.166667 | 43 | 0.614173 |
7a0550ec6f4f7ab5e42539be2095341c5b22b49a | 1,464 | require_relative 'lib/shipyard_exporter/version'
Gem::Specification.new do |spec|
spec.name = 'shipyard_exporter'
spec.version = ShipyardExporter::VERSION
spec.authors = ['Gan Yi Zhong']
spec.email = ['[email protected]']
spec.summary = 'all-in-one exporter feature for Rails'
spec.description = 'add CSV export features to rails model'
spec.homepage = 'https://github.com/yzgan/shipyard_exporter'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 2.4')
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/yzgan/shipyard_exporter.git'
spec.metadata['changelog_uri'] = 'https://github.com/yzgan/shipyard_exporter/blob/master/CHANGELOG.md'
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_dependency 'activesupport'
spec.add_dependency 'caxlsx'
spec.add_dependency 'caxlsx_rails'
spec.add_dependency 'draper', '~>4.0'
end
| 41.828571 | 104 | 0.691257 |
e9fac640b000ae91cd74232eba93d86d55375790 | 3,790 | require "inspec/resources/command"
module Inspec::Resources
class FileSystemResource < Inspec.resource(1)
name "filesystem"
supports platform: "linux"
supports platform: "windows"
desc "Use the filesystem InSpec resource to test file system"
example <<~EXAMPLE
describe filesystem('/') do
its('size_kb') { should be >= 32000 }
its('free_kb') { should be >= 3200 }
its('type') { should cmp 'ext4' }
its('percent_free') { should be >= 20 }
end
describe filesystem('c:') do
its('size_kb') { should be >= 9000 }
its('free_kb') { should be >= 3200 }
its('type') { should cmp 'NTFS' }
its('percent_free') { should be >= 20 }
end
EXAMPLE
attr_reader :partition
def initialize(partition)
@partition = partition
@cache = nil
# select file system manager
@fsman = nil
os = inspec.os
if os.linux?
@fsman = LinuxFileSystemResource.new(inspec)
elsif os.windows?
@fsman = WindowsFileSystemResource.new(inspec)
else
raise Inspec::Exceptions::ResourceSkipped, "The `filesystem` resource is not supported on your OS yet."
end
end
def info
return @cache unless @cache.nil?
return {} if @fsman.nil?
@cache = @fsman.info(@partition)
end
def to_s
"FileSystem #{@partition}"
end
def size_kb
info = @fsman.info(@partition)
info[:size_kb]
end
def size
Inspec.deprecate(:property_filesystem_size, "The `size` property did not reliably use the correct units. Please use `size_kb` instead.")
if inspec.os.windows?
# On windows, we had a bug prior to #3767 in which the
# 'size' value was be scaled to GB in powershell.
# We now collect it in KB.
(size_kb / (1024 * 1024)).to_i
else
size_kb
end
end
def free_kb
info = @fsman.info(@partition)
info[:free_kb]
end
def percent_free
100 * free_kb / size_kb
end
def type
info = @fsman.info(@partition)
info[:type]
end
def name
info = @fsman.info(@partition)
info[:name]
end
end
class FsManagement
attr_reader :inspec
def initialize(inspec)
@inspec = inspec
end
end
class LinuxFileSystemResource < FsManagement
def info(partition)
cmd = inspec.command("df #{partition} -T")
if cmd.stdout.nil? || cmd.stdout.empty? || cmd.exit_status != 0
raise Inspec::Exceptions::ResourceFailed,
"Unable to get available space for partition #{partition}"
end
value = cmd.stdout.split(/\n/)[1].strip.split(" ")
{
name: partition,
size_kb: value[2].to_i,
free_kb: value[4].to_i,
type: value[1].to_s,
}
end
end
class WindowsFileSystemResource < FsManagement
def info(partition)
cmd = inspec.command <<-EOF.gsub(/^\s*/, "")
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='#{partition}'"
$disk.Size = $disk.Size / 1KB
$disk.FreeSpace = $disk.FreeSpace / 1KB
$disk | select -property DeviceID,Size,FileSystem,FreeSpace | ConvertTo-Json
EOF
raise Inspec::Exceptions::ResourceSkipped, "Unable to get available space for partition #{partition}" if cmd.stdout == "" || cmd.exit_status.to_i != 0
begin
fs = JSON.parse(cmd.stdout)
rescue JSON::ParserError => e
raise Inspec::Exceptions::ResourceFailed,
"Failed to parse JSON from Powershell. " \
"Error: #{e}"
end
{
name: fs["DeviceID"],
size_kb: fs["Size"].to_i,
free_kb: fs["FreeSpace"].to_i,
type: fs["FileSystem"],
}
end
end
end
| 27.071429 | 156 | 0.59657 |
01c622ccac226f39e58acd8c298207717a1232e3 | 287 | if ActiveRecord::Base.connection.database_version < 90500
exclude :test_add_index_which_already_exists_does_not_raise_error_with_option, 'ADD INDEX IF NOT EXISTS is PG >= 9.5'
exclude :test_add_index_with_if_not_exists_matches_exact_index, 'ADD INDEX IF NOT EXISTS is PG >= 9.5'
end
| 57.4 | 119 | 0.825784 |
5da02a7a3d52de541cbd0ed6e49df6d08af314a4 | 1,535 | #!/usr/bin/env ruby
# Each Warden container is a /30 in Warden's network range, which is
# configured as 10.244.0.0/22. There are 256 available entries.
#
# We want two subnets, so I've arbitrarily divided this in half for each.
#
# cf1 will be 10.244.0.0/23
# cf2 will be 10.244.2.0/23
#
# Each network will have 128 subnets, and the first half of each subnet will
# be given static IPs.
require "yaml"
require "netaddr"
IP_ADDRESS_SUFFIX = ENV.fetch("IP_ADDRESS_SUFFIX", 4).to_i
cf1_subnets = []
cf1_start = NetAddr::CIDR.create("10.24#{IP_ADDRESS_SUFFIX}.0.0/30")
cf2_subnets = []
cf2_start = NetAddr::CIDR.create("10.24#{IP_ADDRESS_SUFFIX}.2.0/30")
128.times do
cf1_subnets << cf1_start
cf1_start = NetAddr::CIDR.create(cf1_start.next_subnet)
cf2_subnets << cf2_start
cf2_start = NetAddr::CIDR.create(cf2_start.next_subnet)
end
puts YAML.dump(
"networks" => [
{ "name" => "cf1",
"subnets" => cf1_subnets.collect.with_index do |subnet, idx|
{ "cloud_properties" => {
"name" => "random",
},
"range" => subnet.to_s,
"reserved" => [subnet[1].ip],
"static" => idx < 64 ? [subnet[2].ip] : [],
}
end
},
{ "name" => "cf2",
"subnets" => cf2_subnets.collect.with_index do |subnet, idx|
{ "cloud_properties" => {
"name" => "random",
},
"range" => subnet.to_s,
"reserved" => [subnet[1].ip],
"static" => idx < 64 ? [subnet[2].ip] : [],
}
end
},
])
| 26.465517 | 76 | 0.592834 |
1c6a082a5e5d37183af43601ba248074a457907f | 265 | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "password_security"
end
get '/' do
erb :homepage
end
end | 16.5625 | 43 | 0.690566 |
bfab9c2562ac7d55db78119053decd1f2b31d523 | 372 | Deface::Override.new(virtual_path: 'spree/admin/orders/_shipment',
name: 'add_purchase_postage_to_shipments_page',
insert_after: "strong.stock-location-name",
text: "
<% if shipment.ready? %>
<%= link_to 'Purchase Postage', 'javascript:;', class: 'purchase-postage pull-right btn btn-success', data: { 'order-number' => order.number } %>
<% end %>
") | 46.5 | 151 | 0.680108 |
26e5e84d4fba9f2723a1351ea88b4f94a9515d77 | 21,964 | # ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ====================================================================
require "English"
require "time"
require "stringio"
require "tempfile"
require "svn/util"
require "svn/error"
require "svn/ext/core"
class Time
MILLION = 1_000_000 #:nodoc:
class << self
def from_apr_time(apr_time)
return apr_time if apr_time.is_a?(Time)
sec, usec = apr_time.divmod(MILLION)
Time.at(sec, usec)
end
def from_svn_format(str)
return nil if str.nil?
return str if str.is_a?(Time)
from_apr_time(Svn::Core.time_from_cstring(str))
end
def parse_svn_format(str)
return str if str.is_a?(Time)
matched, result = Svn::Core.parse_date(str, Time.now.to_apr_time)
if matched
from_apr_time(result)
else
nil
end
end
end
def to_apr_time
to_i * MILLION + usec
end
def to_svn_format
Svn::Core.time_to_cstring(self.to_apr_time)
end
def to_svn_human_format
Svn::Core.time_to_human_cstring(self.to_apr_time)
end
end
module Svn
module Core
Util.set_constants(Ext::Core, self)
Util.set_methods(Ext::Core, self)
nls_init
Util.reset_message_directory
# for backward compatibility
SWIG_INVALID_REVNUM = INVALID_REVNUM
SWIG_IGNORED_REVNUM = IGNORED_REVNUM
class << self
alias binary_mime_type? mime_type_is_binary
alias prop_diffs2 prop_diffs
def prop_diffs(target_props, source_props)
Property.prop_diffs(target_props, source_props)
end
end
DEFAULT_CHARSET = default_charset
LOCALE_CHARSET = locale_charset
AuthCredSSLClientCert = AuthCredSslClientCert
AuthCredSSLClientCertPw = AuthCredSslClientCertPw
AuthCredSSLServerTrust = AuthCredSslServerTrust
dirent_all = 0
constants.each do |name|
dirent_all |= const_get(name) if /^DIRENT_/ =~ name
end
DIRENT_ALL = dirent_all
Pool = Svn::Ext::Core::Apr_pool_wrapper_t
class Pool
RECOMMENDED_MAX_FREE_SIZE = ALLOCATOR_RECOMMENDED_MAX_FREE
MAX_FREE_UNLIMITED = ALLOCATOR_MAX_FREE_UNLIMITED
class << self
def number_of_pools
ObjectSpace.each_object(Pool) {}
end
end
alias _initialize initialize
private :_initialize
def initialize(parent=nil)
_initialize(parent)
@parent = parent
end
def destroy
@parent = nil
_destroy
end
private :_destroy
end
class Stream
if Core.const_defined?(:STREAM_CHUNK_SIZE)
CHUNK_SIZE = Core::STREAM_CHUNK_SIZE
else
CHUNK_SIZE = 8192
end
def write(data)
Core.stream_write(self, data)
end
def read(len=nil)
if len.nil?
read_all
else
buf = ""
while len > CHUNK_SIZE
buf << _read(CHUNK_SIZE)
len -= CHUNK_SIZE
end
buf << _read(len)
buf
end
end
def close
Core.stream_close(self)
end
def copy(other, &cancel_proc)
Core.stream_copy2(self, other, cancel_proc)
end
private
def _read(size)
Core.stream_read(self, size)
end
def read_all
buf = ""
while chunk = _read(CHUNK_SIZE)
buf << chunk
end
buf
end
end
class AuthBaton
attr_reader :providers, :parameters
alias _initialize initialize
private :_initialize
def initialize(providers=[], parameters={})
_initialize(providers)
@providers = providers
self.parameters = parameters
end
def [](name)
Core.auth_get_parameter(self, name)
end
def []=(name, value)
Core.auth_set_parameter(self, name, value)
@parameters[name] = value
end
def parameters=(params)
@parameters = {}
params.each do |key, value|
self[key] = value
end
end
end
module Authenticatable
attr_accessor :auth_baton
def add_simple_provider
add_provider(Core.auth_get_simple_provider)
end
if Util.windows?
if Core.respond_to?(:auth_get_windows_simple_provider)
def add_windows_simple_provider
add_provider(Core.auth_get_windows_simple_provider)
end
elsif Core.respond_to?(:auth_get_platform_specific_provider)
def add_windows_simple_provider
add_provider(Core.auth_get_platform_specific_provider("windows","simple"))
end
end
end
if Core.respond_to?(:auth_get_keychain_simple_provider)
def add_keychain_simple_provider
add_provider(Core.auth_get_keychain_simple_provider)
end
end
def add_username_provider
add_provider(Core.auth_get_username_provider)
end
def add_ssl_client_cert_file_provider
add_provider(Core.auth_get_ssl_client_cert_file_provider)
end
def add_ssl_client_cert_pw_file_provider
add_provider(Core.auth_get_ssl_client_cert_pw_file_provider)
end
def add_ssl_server_trust_file_provider
add_provider(Core.auth_get_ssl_server_trust_file_provider)
end
if Core.respond_to?(:auth_get_windows_ssl_server_trust_provider)
def add_windows_ssl_server_trust_provider
add_provider(Core.auth_get_windows_ssl_server_trust_provider)
end
end
def add_simple_prompt_provider(retry_limit, &prompt)
args = [retry_limit]
klass = AuthCredSimple
add_prompt_provider("simple", args, prompt, klass)
end
def add_username_prompt_provider(retry_limit, &prompt)
args = [retry_limit]
klass = AuthCredUsername
add_prompt_provider("username", args, prompt, klass)
end
def add_ssl_server_trust_prompt_provider(&prompt)
args = []
klass = AuthCredSSLServerTrust
add_prompt_provider("ssl_server_trust", args, prompt, klass)
end
def add_ssl_client_cert_prompt_provider(retry_limit, &prompt)
args = [retry_limit]
klass = AuthCredSSLClientCert
add_prompt_provider("ssl_client_cert", args, prompt, klass)
end
def add_ssl_client_cert_pw_prompt_provider(retry_limit, &prompt)
args = [retry_limit]
klass = AuthCredSSLClientCertPw
add_prompt_provider("ssl_client_cert_pw", args, prompt, klass)
end
def add_platform_specific_client_providers(config=nil)
add_providers(Core.auth_get_platform_specific_client_providers(config))
end
private
def add_prompt_provider(name, args, prompt, credential_class)
real_prompt = Proc.new do |*prompt_args|
credential = credential_class.new
prompt.call(credential, *prompt_args)
credential
end
method_name = "swig_rb_auth_get_#{name}_prompt_provider"
baton, provider = Core.send(method_name, real_prompt, *args)
provider.instance_variable_set("@baton", baton)
provider.instance_variable_set("@prompt", real_prompt)
add_provider(provider)
end
def add_provider(provider)
add_providers([provider])
end
def add_providers(new_providers)
if auth_baton
providers = auth_baton.providers
parameters = auth_baton.parameters
else
providers = []
parameters = {}
end
self.auth_baton = AuthBaton.new(providers + new_providers, parameters)
end
end
class AuthProviderObject
class << self
undef new
end
end
Diff = SWIG::TYPE_p_svn_diff_t
class Diff
attr_accessor :original, :modified, :latest, :ancestor
class << self
def version
Core.diff_version
end
def file_diff(original, modified, options=nil)
options ||= Core::DiffFileOptions.new
diff = Core.diff_file_diff_2(original, modified, options)
if diff
diff.original = original
diff.modified = modified
end
diff
end
def file_diff3(original, modified, latest, options=nil)
options ||= Core::DiffFileOptions.new
diff = Core.diff_file_diff3_2(original, modified, latest, options)
if diff
diff.original = original
diff.modified = modified
diff.latest = latest
end
diff
end
def file_diff4(original, modified, latest, ancestor, options=nil)
options ||= Core::DiffFileOptions.new
args = [original, modified, latest, ancestor, options]
diff = Core.diff_file_diff4_2(*args)
if diff
diff.original = original
diff.modified = modified
diff.latest = latest
diff.ancestor = ancestor
end
diff
end
end
def unified(orig_label, mod_label, header_encoding=nil)
header_encoding ||= Svn::Core.locale_charset
output = StringIO.new
args = [
output, self, @original, @modified,
orig_label, mod_label, header_encoding
]
Core.diff_file_output_unified2(*args)
output.rewind
output.read
end
def merge(conflict_original=nil, conflict_modified=nil,
conflict_latest=nil, conflict_separator=nil,
display_original_in_conflict=true,
display_resolved_conflicts=true)
header_encoding ||= Svn::Core.locale_charset
output = StringIO.new
args = [
output, self, @original, @modified, @latest,
conflict_original, conflict_modified,
conflict_latest, conflict_separator,
display_original_in_conflict,
display_resolved_conflicts,
]
Core.diff_file_output_merge(*args)
output.rewind
output.read
end
def conflict?
Core.diff_contains_conflicts(self)
end
def diff?
Core.diff_contains_diffs(self)
end
end
class DiffFileOptions
class << self
def parse(*args)
options = new
options.parse(*args)
options
end
end
def parse(*args)
args = args.first if args.size == 1 and args.first.is_a?(Array)
Svn::Core.diff_file_options_parse(self, args)
end
end
class Version
alias _initialize initialize
def initialize(major=nil, minor=nil, patch=nil, tag=nil)
_initialize
self.major = major if major
self.minor = minor if minor
self.patch = patch if patch
self.tag = tag || ""
end
def ==(other)
valid? and other.valid? and Core.ver_equal(self, other)
end
def compatible?(other)
valid? and other.valid? and Core.ver_compatible(self, other)
end
def valid?
(major and minor and patch and tag) ? true : false
end
alias _tag= tag=
def tag=(value)
@tag = value
self._tag = value
end
def to_a
[major, minor, patch, tag]
end
def to_s
"#{major}.#{minor}.#{patch}#{tag}"
end
end
# Following methods are also available:
#
# [created_rev]
# Returns a revision at which the instance was last modified.
# [have_props?]
# Returns +true+ if the instance has properties.
# [last_author]
# Returns an author who last modified the instance.
# [size]
# Returns a size of the instance.
class Dirent
alias have_props? has_props
# Returns +true+ when the instance is none.
def none?
kind == NODE_NONE
end
# Returns +true+ when the instance is a directory.
def directory?
kind == NODE_DIR
end
# Returns +true+ when the instance is a file.
def file?
kind == NODE_FILE
end
# Returns +true+ when the instance is an unknown node.
def unknown?
kind == NODE_UNKNOWN
end
# Returns a Time when the instance was last changed.
#
# Svn::Core::Dirent#time is replaced by this method, _deprecated_,
# and provided for backward compatibility with the 1.3 API.
def time2
__time = time
__time && Time.from_apr_time(__time)
end
end
Config = SWIG::TYPE_p_svn_config_t
class Config
include Enumerable
class << self
def get(path=nil)
Core.config_get_config(path)
end
alias config get
def read(file, must_exist=true)
Core.config_read(file, must_exist)
end
def ensure(dir)
Core.config_ensure(dir)
end
def read_auth_data(cred_kind, realm_string, config_dir=nil)
Core.config_read_auth_data(cred_kind, realm_string, config_dir)
end
def write_auth_data(hash, cred_kind, realm_string, config_dir=nil)
Core.config_write_auth_data(hash, cred_kind,
realm_string, config_dir)
end
end
def merge(file, must_exist=true)
Core.config_merge(self, file, must_exist)
end
def get(section, option, default=nil)
Core.config_get(self, section, option, default)
end
def get_bool(section, option, default)
Core.config_get_bool(self, section, option, default)
end
def set(section, option, value)
Core.config_set(self, section, option, value)
end
alias_method :[]=, :set
def set_bool(section, option, value)
Core.config_set_bool(self, section, option, value)
end
def each
each_section do |section|
each_option(section) do |name, value|
yield(section, name, value)
true
end
true
end
end
def each_option(section)
receiver = Proc.new do |name, value|
yield(name, value)
end
Core.config_enumerate2(self, section, receiver)
end
def each_section
receiver = Proc.new do |name|
yield(name)
end
Core.config_enumerate_sections2(self, receiver)
end
def find_group(key, section)
Core.config_find_group(self, key, section)
end
def get_server_setting(group, name, default=nil)
Core.config_get_server_setting(self, group, name, default)
end
def get_server_setting_int(group, name, default)
Core.config_get_server_setting_int(self, group, name, default)
end
alias_method :_to_s, :to_s
def to_s
result = ""
each_section do |section|
result << "[#{section}]\n"
each_option(section) do |name, value|
result << "#{name} = #{value}\n"
end
result << "\n"
end
result
end
def inspect
"#{_to_s}#{to_hash.inspect}"
end
def to_hash
sections = {}
each do |section, name, value|
sections[section] ||= {}
sections[section][name] = value
end
sections
end
def ==(other)
other.is_a?(self.class) and to_hash == other.to_hash
end
end
module Property
module_function
def kind(name)
kind, len = Core.property_kind(name)
[kind, name[0...len]]
end
def svn_prop?(name)
Core.prop_is_svn_prop(name)
end
def needs_translation?(name)
Core.prop_needs_translation(name)
end
def categorize(props)
categorize2(props).collect do |categorized_props|
Util.hash_to_prop_array(categorized_props)
end
end
alias_method :categorize_props, :categorize
module_function :categorize_props
def categorize2(props)
Core.categorize_props(props)
end
def diffs(target_props, source_props)
Util.hash_to_prop_array(diffs2(target_props, source_props))
end
alias_method :prop_diffs, :diffs
module_function :prop_diffs
def diffs2(target_props, source_props)
Core.prop_diffs2(target_props, source_props)
end
def has_svn_prop?(props)
Core.prop_has_svn_prop(props)
end
alias_method :have_svn_prop?, :has_svn_prop?
module_function :have_svn_prop?
def valid_name?(name)
Core.prop_name_is_valid(name)
end
end
module Depth
module_function
def from_string(str)
return nil if str.nil?
Core.depth_from_word(str)
end
def to_string(depth)
Core.depth_to_word(depth)
end
def infinity_or_empty_from_recurse(depth_or_recurse)
case depth_or_recurse
when true then DEPTH_INFINITY
when false then DEPTH_EMPTY
else depth_or_recurse
end
end
def infinity_or_immediates_from_recurse(depth_or_recurse)
case depth_or_recurse
when true then DEPTH_INFINITY
when false then DEPTH_IMMEDIATES
else depth_or_recurse
end
end
end
module MimeType
module_function
def parse(source)
file = Tempfile.new("svn-ruby-mime-type")
file.print(source)
file.close
Core.io_parse_mimetypes_file(file.path)
end
def parse_file(path)
Core.io_parse_mimetypes_file(path)
end
def detect(path, type_map={})
Core.io_detect_mimetype2(path, type_map)
end
end
class CommitInfo
alias _date date
def date
Time.from_svn_format(_date)
end
end
# Following methods are also available:
#
# [action]
# Returns an action taken to the path at the revision.
# [copyfrom_path]
# If the path was added at the revision by the copy action from
# another path at another revision, returns an original path.
# Otherwise, returns +nil+.
# [copyfrom_rev]
# If the path was added at the revision by the copy action from
# another path at another revision, returns an original revision.
# Otherwise, returns <tt>-1</tt>.
class LogChangedPath
# Returns +true+ when the path is added by the copy action.
def copied?
Util.copy?(copyfrom_path, copyfrom_rev)
end
end
# For backward compatibility
class Prop
attr_accessor :name, :value
def initialize(name, value)
@name = name
@value = value
end
def ==(other)
other.is_a?(self.class) and
[@name, @value] == [other.name, other.value]
end
end
class MergeRange
def to_a
[self.start, self.end, self.inheritable]
end
def inspect
super.gsub(/>$/, ":#{to_a.inspect}>")
end
def ==(other)
to_a == other.to_a
end
end
class MergeInfo < Hash
class << self
def parse(input)
new(Core.mergeinfo_parse(input))
end
end
def initialize(info)
super()
info.each do |path, ranges|
self[path] = RangeList.new(*ranges)
end
end
def diff(to, consider_inheritance=false)
Core.mergeinfo_diff(self, to, consider_inheritance).collect do |result|
self.class.new(result)
end
end
def merge(changes)
self.class.new(Core.swig_mergeinfo_merge(self, changes))
end
def remove(eraser)
self.class.new(Core.mergeinfo_remove(eraser, self))
end
def sort
self.class.new(Core.swig_mergeinfo_sort(self))
end
def to_s
Core.mergeinfo_to_string(self)
end
end
class RangeList < Array
def initialize(*ranges)
super()
ranges.each do |range|
self << Svn::Core::MergeRange.new(*range.to_a)
end
end
def diff(to, consider_inheritance=false)
result = Core.rangelist_diff(self, to, consider_inheritance)
deleted = result.pop
added = result
[added, deleted].collect do |result|
self.class.new(*result)
end
end
def merge(changes)
self.class.new(*Core.swig_rangelist_merge(self, changes))
end
def remove(eraser, consider_inheritance=false)
self.class.new(*Core.rangelist_remove(eraser, self,
consider_inheritance))
end
def intersect(other, consider_inheritance=false)
self.class.new(*Core.rangelist_intersect(self, other,
consider_inheritance))
end
def reverse
self.class.new(*Core.swig_rangelist_reverse(self))
end
def to_s
Core.rangelist_to_string(self)
end
end
class LogEntry
alias_method(:revision_properties, :revprops)
alias_method(:has_children?, :has_children)
undef_method(:has_children)
end
end
end
| 25.809636 | 86 | 0.613777 |
1a812f6e6b9f7cebe9488c8b3fdde7c625f2d0f9 | 556 | require 'spec_helper'
def execute(query, context = {})
CacheSchema.execute(query, context: context)
end
RSpec.describe 'caching connection fields' do
let(:query) do
%Q{
{
customer(id: #{Customer.last.id}) {
orders {
edges {
node {
id
}
}
}
}
}
}
end
it 'produces the same result on miss or hit' do
cold_results = execute(query)
warm_results = execute(query)
expect(cold_results).to eq warm_results
end
end
| 17.935484 | 49 | 0.534173 |
e813c5050017766c12e608c7f3e11ff7f5cb551f | 293 | require "treetop"
require "polyglot"
require "tweetparser/grammar"
module TweetParser
def self.parse(input)
kcode = $KCODE
$KCODE = "n"
parser = TweetContentParser.new
parsed = parser.parse(input)
$KCODE = kcode
return nil unless parsed
parsed.content
end
end
| 18.3125 | 35 | 0.692833 |
879c4269584c5b2d3872fb33540ce40d782316f7 | 1,377 | require 'active_support/concern'
module Schema::Accessors
extend ActiveSupport::Concern
included do
props = self.schema.properties
raise "Schema #{schema.inspect} has no properties" unless props
generated_methods.module_eval do
props.each do |name, prop|
define_method prop, ""
end
end
end
def initialize(*args)
@_watch_props ||= {}
super
end
def get(*attrs, &on_change)
vals = attrs.map do |attr|
if attr.is_a?(Symbol)
return self.instance_variable_get("@#{attr}")
elsif attr.is_a?(String)
attr = attr.split('.')
return self.instance_variable_get("@#{attr.shift}") if attr.size == 1
# fall-through
end
if attr.is_a?(Array)
val = self.instance_variable_get("@#{attr.shift}")
val = val.get(attr, &on_change) unless attr.empty
val
end
end
# FIXME: race-condition between get and watch
watch(*attrs, &on_change) if on_change
vals.size > 1 ? vals : vals.first
end
def set(attrs = {})
# TODO
end
protected
def get_one(prop, &on_change)
set = (@_watch_props[prop.to_s] ||= Set.new)
set << on_change
end
module ClassMethods
protected
def generated_methods
@generated_methods ||= begin
mod = Module.new
include(mod)
mod
end
end
end
end
| 20.863636 | 78 | 0.615105 |
ac3ba443a37a7a784108d5ca22898d970ce4790d | 243 | Rails.application.routes.draw do
get 'staticpages/home'
get 'staticpages/help'
get 'staticpages/about'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'application#hello'
end
| 22.090909 | 101 | 0.761317 |
91914353c812ac19342fa431b685169bddce7020 | 2,675 | # frozen_string_literal: true
require "spec_helper"
require "bump/dependency"
require "bump/dependency_file"
require "bump/file_updaters/java_script/yarn"
require_relative "../shared_examples_for_file_updaters"
RSpec.describe Bump::FileUpdaters::JavaScript::Yarn do
it_behaves_like "a dependency file updater"
let(:updater) do
described_class.new(
dependency_files: [package_json, yarn_lock],
dependency: dependency,
github_access_token: "token"
)
end
let(:package_json) do
Bump::DependencyFile.new(content: package_json_body, name: "package.json")
end
let(:package_json_body) do
fixture("javascript", "package_files", "package.json")
end
let(:yarn_lock) do
Bump::DependencyFile.new(
name: "yarn.lock",
content: fixture("javascript", "lockfiles", "yarn.lock")
)
end
let(:dependency) do
Bump::Dependency.new(
name: "fetch-factory",
version: "0.0.2",
package_manager: "yarn"
)
end
let(:tmp_path) { Bump::SharedHelpers::BUMP_TMP_DIR_PATH }
before { Dir.mkdir(tmp_path) unless Dir.exist?(tmp_path) }
describe "#updated_dependency_files" do
subject(:updated_files) { updater.updated_dependency_files }
it "doesn't store the files permanently" do
expect { updated_files }.to_not(change { Dir.entries(tmp_path) })
end
it "returns DependencyFile objects" do
updated_files.each { |f| expect(f).to be_a(Bump::DependencyFile) }
end
specify { expect { updated_files }.to_not output.to_stdout }
its(:length) { is_expected.to eq(2) }
describe "the updated package_json_file" do
subject(:updated_package_json_file) do
updated_files.find { |f| f.name == "package.json" }
end
its(:content) { is_expected.to include "\"fetch-factory\": \"^0.0.2\"" }
its(:content) { is_expected.to include "\"etag\": \"^1.0.0\"" }
context "when the minor version is specified" do
let(:dependency) do
Bump::Dependency.new(
name: "fetch-factory",
version: "0.2.1",
package_manager: "yarn"
)
end
let(:package_json_body) do
fixture("javascript", "package_files", "minor_version_specified.json")
end
its(:content) { is_expected.to include "\"fetch-factory\": \"0.2.x\"" }
end
end
describe "the updated yarn_lock" do
subject(:updated_yarn_lock_file) do
updated_files.find { |f| f.name == "yarn.lock" }
end
it "has details of the updated item" do
expect(updated_yarn_lock_file.content).
to include("fetch-factory@^0.0.2")
end
end
end
end
| 29.395604 | 80 | 0.651963 |
210596547a3d047b8e178b977b5cd14157eebe46 | 444 | $LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'rspec'
require 'automatic_foreign_key'
require 'connection'
Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
config.include(AutomaticForeignKeyMatchers)
end
def load_schema
eval(File.read(File.join(File.dirname(__FILE__), 'schema', 'schema.rb')))
end
| 27.75 | 75 | 0.747748 |
2132e5d24847af3dcc06b1a786f11e859c3cd2f4 | 6,628 | # frozen_string_literal: true
module ActiveRecord
module ConnectionAdapters
module MySQL
module DatabaseStatements
# Returns an ActiveRecord::Result instance.
def select_all(*) # :nodoc:
result = if ExplainRegistry.collect? && prepared_statements
unprepared_statement { super }
else
super
end
@connection.abandon_results!
result
end
def query(sql, name = nil) # :nodoc:
execute(sql, name).to_a
end
READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp(:begin, :commit, :explain, :select, :set, :show, :release, :savepoint, :rollback) # :nodoc:
private_constant :READ_QUERY
def write_query?(sql) # :nodoc:
!READ_QUERY.match?(sql)
end
# Executes the SQL statement in the context of this connection.
def execute(sql, name = nil)
if preventing_writes? && write_query?(sql)
raise ActiveRecord::ReadOnlyError, "Write query attempted while in readonly mode: #{sql}"
end
# make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
# made since we established the connection
@connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
super
end
def exec_query(sql, name = "SQL", binds = [], prepare: false)
if without_prepared_statement?(binds)
execute_and_free(sql, name) do |result|
if result
ActiveRecord::Result.new(result.fields, result.to_a)
else
ActiveRecord::Result.new([], [])
end
end
else
exec_stmt_and_free(sql, name, binds, cache_stmt: prepare) do |_, result|
if result
ActiveRecord::Result.new(result.fields, result.to_a)
else
ActiveRecord::Result.new([], [])
end
end
end
end
def exec_delete(sql, name = nil, binds = [])
if without_prepared_statement?(binds)
@lock.synchronize do
execute_and_free(sql, name) { @connection.affected_rows }
end
else
exec_stmt_and_free(sql, name, binds) { |stmt| stmt.affected_rows }
end
end
alias :exec_update :exec_delete
private
def execute_batch(sql, name = nil)
super
@connection.abandon_results!
end
def default_insert_value(column)
super unless column.auto_increment?
end
def last_inserted_id(result)
@connection.last_id
end
def supports_set_server_option?
@connection.respond_to?(:set_server_option)
end
def build_truncate_statements(*table_names)
if table_names.size == 1
super.first
else
super
end
end
def multi_statements_enabled?(flags)
if flags.is_a?(Array)
flags.include?("MULTI_STATEMENTS")
else
(flags & Mysql2::Client::MULTI_STATEMENTS) != 0
end
end
def with_multi_statements
previous_flags = @config[:flags]
unless multi_statements_enabled?(previous_flags)
if supports_set_server_option?
@connection.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_ON)
else
@config[:flags] = Mysql2::Client::MULTI_STATEMENTS
reconnect!
end
end
yield
ensure
unless multi_statements_enabled?(previous_flags)
if supports_set_server_option?
@connection.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_OFF)
else
@config[:flags] = previous_flags
reconnect!
end
end
end
def combine_multi_statements(total_sql)
total_sql.each_with_object([]) do |sql, total_sql_chunks|
previous_packet = total_sql_chunks.last
if max_allowed_packet_reached?(sql, previous_packet)
total_sql_chunks << +sql
else
previous_packet << ";\n"
previous_packet << sql
end
end
end
def max_allowed_packet_reached?(current_packet, previous_packet)
if current_packet.bytesize > max_allowed_packet
raise ActiveRecordError,
"Fixtures set is too large #{current_packet.bytesize}. Consider increasing the max_allowed_packet variable."
elsif previous_packet.nil?
true
else
(current_packet.bytesize + previous_packet.bytesize + 2) > max_allowed_packet
end
end
def max_allowed_packet
@max_allowed_packet ||= show_variable("max_allowed_packet")
end
def exec_stmt_and_free(sql, name, binds, cache_stmt: false)
if preventing_writes? && write_query?(sql)
raise ActiveRecord::ReadOnlyError, "Write query attempted while in readonly mode: #{sql}"
end
materialize_transactions
# make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
# made since we established the connection
@connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
type_casted_binds = type_casted_binds(binds)
log(sql, name, binds, type_casted_binds) do
if cache_stmt
stmt = @statements[sql] ||= @connection.prepare(sql)
else
stmt = @connection.prepare(sql)
end
begin
result = ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
stmt.execute(*type_casted_binds)
end
rescue Mysql2::Error => e
if cache_stmt
@statements.delete(sql)
else
stmt.close
end
raise e
end
ret = yield stmt, result
result.free if result
stmt.close unless cache_stmt
ret
end
end
end
end
end
end
| 32.975124 | 186 | 0.560501 |
bf17c1f0cad4f41dfc5516778887e1e428f64d57 | 3,660 | # From itunes_parser by Pete Higgins
# http://github.com/phiggins/itunes_parser
require 'nokogiri'
module ItunesParser
class NokogiriSax
class SaxDoc < Nokogiri::XML::SAX::Document
def initialize on_track, on_playlist
super()
@on_track, @on_playlist = on_track, on_playlist
@with_callbacks = on_track || on_playlist
@tracks, @playlists = [], [] unless @with_callbacks
@buffer = ""
end
def error(error_message)
raise error_message
end
#def start_element(name, attrs = [])
def start_element_namespace(name, *)
case name
when 'dict' ; start_dict
when 'array'
start_playlist_items if @key_string == 'Playlist Items'
end
end
#def end_element(name)
def end_element_namespace(name, *)
case name
when 'key'
@key_string = @buffer.strip
when 'dict'
end_dict
when 'array'
if @parsing_playlist_items
end_playlist_items
elsif @parsing_playlists
end_playlists
end
else
if @parsing_playlist_items
@current_playlist_items << @buffer.to_i
elsif @parsing_playlists || @parsing_tracks
if name == 'true'
@current << @key_string << true
elsif name == 'false'
@current << @key_string << false
else
@current << @key_string << @buffer.strip
end
end
end
@buffer = ""
end
def characters(string)
@buffer << string
end
def start_tracks
#puts " ** parsing tracks"
@parsing_tracks = true
@current = []
end
def end_tracks
#puts " ** end tracks"
@parsing_tracks = false
end
def start_playlists
#puts " ** parsing playlists"
@parsing_playlists = true
@current = []
end
def end_playlists
@parsing_playlists = false
end
def start_playlist_items
#puts " ** parsing playlist items"
@current_playlist_items = []
@parsing_playlist_items = true
end
def end_playlist_items
#puts " ** end playlist items"
@parsing_playlist_items = false
@current << "Playlist Items"
@current << @current_playlist_items
end
def start_dict
case @key_string
when "Tracks"
start_tracks
when "Playlists"
start_playlists
end
end
def end_dict
if @parsing_playlists && !@parsing_playlist_items
current = Hash[*@current]
if !@with_callbacks
@playlists.push(current)
elsif @on_playlist
@on_playlist.call(current)
end
@current = []
elsif @parsing_tracks
if @current == []
end_tracks
else
current = Hash[*@current]
if !@with_callbacks
@tracks.push(current)
elsif @on_track
@on_track.call(current)
end
@current = []
end
end
end
end
def initialize(xml, params={})
@xml = xml
@on_track = params[:on_track]
@on_playlist = params[:on_playlist]
end
def on_track &block
@on_track = block
end
def on_playlist &block
@on_playlist = block
end
def parse
document = SaxDoc.new(@on_track, @on_playlist)
parser = Nokogiri::XML::SAX::Parser.new(document)
parser.parse(@xml)
self
end
end
end
| 23.461538 | 65 | 0.544809 |
622d3846c31101b30ac6227ae5beb65818dfee80 | 2,532 | require 'net/http'
require 'net/https'
require 'json'
require 'rack/utils'
module PaypalAdaptive
class IpnNotification
def initialize(env=nil)
config = PaypalAdaptive.config(env)
@paypal_base_url = config.paypal_base_url
@ssl_cert_path = config.ssl_cert_path
@ssl_cert_file = config.ssl_cert_file
@api_cert_file = config.api_cert_file
@verify_mode = config.verify_mode
end
# def send_back(data)
# data = "cmd=_notify-validate&#{data}"
# path = "#{@paypal_base_url}/cgi-bin/webscr"
# url = URI.parse path
# http = Net::HTTP.new(url.host, 443)
# http.use_ssl = true
# http.verify_mode = @verify_mode
# http.ca_path = @ssl_cert_path unless @ssl_cert_path.nil?
# if @api_cert_file
# cert = File.read(@api_cert_file)
# http.cert = OpenSSL::X509::Certificate.new(cert)
# http.key = OpenSSL::PKey::RSA.new(cert)
# end
# http.ca_path = @ssl_cert_path unless @ssl_cert_path.blank?
# http.ca_file = @ssl_cert_file unless @ssl_cert_file.blank?
# req = Net::HTTP::Post.new(url.request_uri)
# req.set_form_data(Rack::Utils.parse_nested_query(data))
# req['Accept-Encoding'] = 'identity'
# response_data = http.request(req).body
# @verified = response_data == "VERIFIED"
# end
def send_back(data)
data = "cmd=_notify-validate&#{data}"
path = "#{@paypal_base_url}/cgi-bin/webscr"
url = URI.parse path
http = Net::HTTP.new(url.host, 443)
http.use_ssl = true
http.verify_mode = @verify_mode
http.ca_path = @ssl_cert_path unless @ssl_cert_path.nil?
if @api_cert_file
cert = File.read(@api_cert_file)
http.cert = OpenSSL::X509::Certificate.new(cert)
http.key = OpenSSL::PKey::RSA.new(cert)
end
http.ca_path = @ssl_cert_path unless @ssl_cert_path.blank?
http.ca_file = @ssl_cert_file unless @ssl_cert_file.blank?
req = Net::HTTP::Post.new(url.request_uri)
# we don't want #set_form_data to create a hash and get our
# response out of order; Paypal IPN docs explicitly state that
# the contents of #send_back must be in the same order as they
# were recieved
req.body = data
req.content_type = 'application/x-www-form-urlencoded'
req['Accept-Encoding'] = 'identity'
response_data = http.request(req).body
@verified = response_data == "VERIFIED"
end
def verified?
@verified
end
end
end
| 31.259259 | 68 | 0.64613 |
3391da4324d29dd89aea470346a80feac1dc3e00 | 457 | # frozen_string_literal: true
shared_examples 'class' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_augeas('/etc/sysconfig/elasticsearch') }
it { is_expected.to contain_file('/etc/elasticsearch/elasticsearch.yml') }
it { is_expected.to contain_datacat('/etc/elasticsearch/elasticsearch.yml') }
it { is_expected.to contain_datacat_fragment('main_config') }
it { is_expected.to contain_service('elasticsearch') }
end
| 41.545455 | 79 | 0.772429 |
bb25a3be4e5729dafccbe34db27049ccb6b49cea | 13,258 | module Stupidedi
module Versions
module Interchanges
module ThreeHundred
#
# @see FunctionalGroups::FortyTen::ElementTypes
# @see Schema::CodeList
#
module ElementDefs
# Import definitions of DT, R, ID, Nn, AN, TM, and SimpleElementDef
t = FunctionalGroups::FortyTen::ElementTypes
s = Schema
# Namespace workaround for SpecialAN inner classes
T = t
# Fun (stupid) problem. The specifications declare ISA02 and ISA04 are
# required elements, but they only have "meaningful information" when
# ISA01 and ISA03 qualifiers aren't "00".
#
# Without specifications regarding what should be entered in these
# required elements, our best option is to defer to convention, which
# seems to be that these elements should have 10 spaces -- which means
# they're blank. So we can't really make these elements required! Even
# stupider, these are the only blank elements that should be written
# out space-padded to the min_length -- every other element should be
# collapsed to an empty string.
#
# So this "Special" class overrides to_x12 for empty values, but it
# otherwise looks and acts like a normal AN and StringVal
class SpecialAN < t::AN
def companion
SpecialVal
end
class SpecialVal < T::StringVal
class Empty < T::StringVal::Empty
# @return [String]
def to_x12
" " * definition.min_length
end
end
class NonEmpty < T::StringVal::NonEmpty
def too_short?
false
end
end
end
end
class SeparatorElementVal < Values::SimpleElementVal
extend Forwardable
def_delegators :@value, :to_s, :length
def initialize(value, usage, position)
@value = value
super(usage, position)
end
# @return [SeparatorElementVal]
def copy(changes = {})
SeparatorElementVal.new \
changes.fetch(:value, @value),
changes.fetch(:usage, usage),
changes.fetch(:position, position)
end
def valid?
true
end
def empty?
@value.blank?
end
def too_short?
@value.length < 1
end
def too_long?
@value.length > 1
end
def separator?
true
end
# @return [String]
def to_x12
@value.to_s
end
def inspect
id = definition.try{|d| ansi.bold("[#{d.id}]") }
ansi.element("SeparatorElementVal.value#{id}") << "(#{@value || "nil"})"
end
end
class << SeparatorElementVal
# @group Constructors
###################################################################
# @raise NoMethodError
def empty(usage, position)
SeparatorElementVal.new(nil, usage, position)
end
# @return [SeparatorElementVal]
def value(character, usage, position)
SeparatorElementVal.new(character, usage, position)
end
# @return [SeparatorElementVal]
def parse(character, usage, position)
SeparatorElementVal.new(character, usage, position)
end
# @endgroup
###################################################################
end
I01 = t::ID.new(:I01, "Authorization Information Qualifier", 2, 2,
s::CodeList.build(
"00" => "No Authorization Information Present (No Meaningful Information in I02)",
# "01" => "UCS Communications ID",
# "02" => "EDX Communications ID",
"03" => "Additional Data Identification"))
# "04" => "Rail Communication ID",
# "05" => "Deparment of Defense (DoD) Communication Identifier",
# "06" => "United States Federal Government Communication Identifier"))
I02 = SpecialAN.new(:I02, "Authorization Information", 10, 10)
I03 = t::ID.new(:I03, "Security Information Qualifier", 2, 2,
s::CodeList.build(
"00" => "No Security Information (No Meaningful Information in I04)",
"01" => "Password"))
I04 = SpecialAN.new(:I04, "Security Information", 10, 10)
I05 = t::ID.new(:I05, "Interchange ID Qualifier", 2, 2,
s::CodeList.build(
"01" => "Duns (Dun & Bradstreet)",
"02" => "SCAC (Standard Carrier Alpha Code)",
# "03" => "FMC (Federal Maritime Commission)",
# "04" => "IATA (International Air Transport Association)",
# "07" => s::CodeList.external("583"),
# "08" => "UCC EDI Communications ID (Comm ID)",
# "09" => "X.121 (CCITT)",
# "10" => s::CodeList.external("350"),
# "11" => "DEA (Drug Enforcement Administration)",
"12" => "Phone (Telephone Companies)",
# "13" => "UCS Code (The UCS Code is a Code Used for UCS Transmissions; it includes the Area Code and Telephone Number of a Modem; it Does Not Include Punctation, Blanks, or Access Code)",
"14" => "Duns Plus Suffix",
# "15" => "Petroleum Accountants Society of Canada Company Code",
"16" => "Duns Number With 4-Character Suffix",
# "17" => "American Bankers Association (ABA) Transit Routing Number (Including Check Digit, 9 Digit)",
# "18" => s::CodeList.external("420"),
# "19" => s::CodeList.external("421"),
"20" => s::CodeList.external("121"),
# "21" => s::CodeList.external("422"),
# "22" => s::CodeList.external("423"),
# "23" => s::CodeList.external("424"),
# "24" => s::CodeList.external("425"),
# "25" => s::CodeList.external("426"),
# "26" => s::CodeList.external("296", "300"),
"27" => "Carrier Identification Number as assigned by Health Care Financing Administration (HCFA)",
"28" => "Fiscal Intermediary Identification Number as assigned by Health Care Financing Administration (HCFA)",
"29" => "Medicare Provider and Supplier Identification Number as assigned by Health Care Financing Administration (HCFA)",
"30" => "US Federal Tax Identification Number",
# "31" => "Jurisdiction Identification Number Plus 4 as assigned by the Interational Association of Industrial Accident Boards and Commissions (IAIABC)",
# "32" => "US Federal Employer Identification Number (FEIN)",
"33" => "National Association of Insurance Commissioners Company Code (NAIC)",
# "34" => "Medicaid Provider and Supplier Identification Number as assigned by individual State Medicaid Agencies in conjunction with Health Care Financing Administration (HCFA)",
# "35" => "Statistics Canada Canadian College Student Information System Institution Codes",
# "36" => s::CodeList.external("300"),
# "37" => s::CodeList.external("573"),
# "38" => s::CodeList.external("862"),
# "AM" => s::CodeList.external("497"),
# "NR" => "National Retail Merchants Association (NRMA) Assigned",
# "SA" => s::CodeList.external("851"),
# "SN" => s::CodeList.external("42"),
"ZZ" => "Mutually Defined"))
I06 = SpecialAN.new(:I06, "Interchange Sender ID", 15, 15)
I07 = SpecialAN.new(:I07, "Interchange Receiver ID", 15, 15)
I08 = t::DT.new(:I08, "Interchange Date", 6, 6)
I09 = t::TM.new(:I09, "Interchange Time", 4, 4)
I10 = t::ID.new(:I10, "Interchange Control Standards Identifier", 1, 1,
s::CodeList.build(
"U" => "U.S. EDI Community of ASC X12, TDCC, and UCS"))
I11 = t::ID.new(:I11, "Interchange Control Version Number", 5, 5,
s::CodeList.build(
"00200" => "Standard Issued as ANSI X12.5-1987",
"00300" => "",
"00301" => "Draft Standard for Trial Use Approved for Publication by ASC X12 Procedures Review Board Through October 1990",
"00304" => "Draft Standards for Trial Use Approved for Publication by ASC X12 Procedures Review Board through October 1993",
"00305" => "Draft Standards for Trial Use Approved for Publication by ASC X12 Procedures Review Board through October 1994",
"00401" => "Draft Standards for Trial Use Approved for Publication by ASC X12 Procedures Review Board through October 1997"))
I12 = t::Nn.new(:I12, "Interchange Control Number", 9, 9, 0)
I13 = t::ID.new(:I13, "Acknowledgment Requested", 1, 1,
s::CodeList.build(
"0" => "No Interchange Acknowledgment Requested",
"1" => "Interchange Acknowledgment Requested (TA1)",
"2" => "Interchange Acknowledgment Requested only when Interchange is \"Rejected Because Of Errors\"",
"3" => "Interchange Acknowledgment Requested only when Interchange is \"Rejected Because Of Errors\" or \"Accepted but Errors are Noted\""
))
I14 = t::ID.new(:I14, "Interchange Usage Indicator", 1, 1,
s::CodeList.build(
# "I" => "Information",
"P" => "Production Data",
"T" => "Test Data"))
I15 = Class.new(t::SimpleElementDef) do
def companion
SeparatorElementVal
end
end.new(:I15, "Component Element Separator", 1, 1)
I16 = t::Nn.new(:I16, "Number of Included Functional Groups", 1, 5, 0)
I17 = t::ID.new(:I17, "Interchange Acknowledgement Code", 1, 1,
s::CodeList.build(
"A" => "The Transmitted Interchange Control Structure Header and Trailer Have Been Received and Have No Errors",
"E" => "The Transmitted Interchange Control Structure Header and Trailer Have Been Received and Are Accepted But Errors Are Noted. This Means the Sender Must Not Resend the Data.",
"R" => "The Transmitted Interchange Control Structure Header and Trailer are Rejected Because of Errors"))
I18 = t::ID.new(:I18, "Interchange Note Code", 3, 3,
s::CodeList.build(
"000" => "No error",
"001" => "The Interchange Control Number in the Header and Trailer Do Not Match. The Value From the Header is Used in the Acknowledgement",
"002" => "This Standard as Noted in the Control Standards Identifier is Not Supported",
"003" => "This Version of the Controls is Not Supported",
"004" => "The Segment Terminator is Invalid",
"005" => "Invalid Interchange ID Qualifier for Sender",
"006" => "Invalid Interchange Sender ID",
"007" => "Invalid Interchange ID Qualifier for Receiver",
"008" => "Invalid Interchange Receiver ID",
"009" => "Unknown Interchange Receiver ID",
"010" => "Invalid Authorization Information Qualifier Value",
"011" => "Invalid Authorization Information Value",
"012" => "Invalid Security Information Qualifier Value",
"013" => "Invalid Security Information Value",
"014" => "Invalid Interchange Date Value",
"015" => "Invalid Interchange Time Value",
"016" => "Invalid Interchange Standards Identifier Value",
"017" => "Invalid Interchange Version ID Value",
"018" => "Invalid Interchange Control Number Value",
"019" => "Invalid Acknowledgement Requested Value",
"020" => "Invalid Test Indicator Value",
"021" => "Invalid Number of Included Groups Value",
"022" => "Invalid Control Characters",
"023" => "Improper (Premature) End-of-File (Transmission)",
"024" => "Invalid Interchange Content (ex Invalid GS Segment)",
"025" => "Duplicate Interchange Control Numbers",
"026" => "Invalid Data Structure Separator",
"027" => "Invalid Component Element Separator",
"028" => "Invalid Date in Deferred Delivery Request",
"029" => "Invalid Time in Deferred Delivery Request",
"030" => "Invalid Delivery Time Code in Deferred Delivery Request",
"031" => "Invalid Grade of Service"))
end
end
end
end
end
| 47.862816 | 200 | 0.544275 |
619567df13e160092f8896b8c4af2b7db368f6dc | 2,103 | # frozen_string_literal: true
require_relative '../../../step/track'
module Engine
module Game
module G18Ireland
module Step
class Track < Engine::Step::Track
def hex_neighbors(entity, hex)
super || @game.narrow_connected_hexes(entity)[hex]
end
def process_lay_tile(action)
super
@game.clear_narrow_graph
end
def check_track_restrictions!(entity, old_tile, new_tile)
return if @game.loading || !entity.operator?
connected_paths = if @game.tile_uses_broad_rules?(old_tile, new_tile)
@game.graph_for_entity(entity).connected_paths(entity)
else
# Must update the graph now.
@game.clear_narrow_graph
@game.narrow_connected_paths(entity)
end
old_paths = old_tile.paths
changed_city = false
used_new_track = old_paths.empty?
new_tile.paths.each do |np|
next unless connected_paths[np]
op = old_paths.find { |path| np <= path }
used_new_track = true unless op
old_revenues = op&.nodes && op.nodes.map(&:max_revenue).sort
new_revenues = np&.nodes && np.nodes.map(&:max_revenue).sort
changed_city = true unless old_revenues == new_revenues
end
case @game.class::TRACK_RESTRICTION
when :permissive
true
when :city_permissive
raise GameError, 'Must be city tile or use new track' if new_tile.cities.none? && !used_new_track
when :restrictive
raise GameError, 'Must use new track' unless used_new_track
when :semi_restrictive
raise GameError, 'Must use new track or change city value' if !used_new_track && !changed_city
else
raise
end
end
end
end
end
end
end
| 33.919355 | 111 | 0.545887 |
b975fdc445b089f8582e5b98af0ba52d09ca7dce | 4,998 | # frozen_string_literal: true
RSpec.describe CronKubernetes::CronJob do
subject { CronKubernetes::CronJob.new }
let(:manifest) do
YAML.safe_load <<~MANIFEST
apiVersion: batch/v1
kind: Job
spec:
template:
spec:
containers:
- name: hello
image: ubuntu
restartPolicy: OnFailure
MANIFEST
end
context "initialization" do
it "accepts no parameters" do
expect { CronKubernetes::CronJob.new }.not_to raise_error
end
it "accepts schedule, command, job_manifest, name parameters" do
job = CronKubernetes::CronJob.new(
schedule: "30 0 * * *",
command: "/bin/bash -l -c ls\\ -l",
job_manifest: manifest,
name: "cron-job",
identifier: "my-app"
)
expect(job.schedule).to eq "30 0 * * *"
expect(job.command).to eq "/bin/bash -l -c ls\\ -l"
expect(job.job_manifest).to eq manifest
expect(job.name).to eq "cron-job"
expect(job.identifier).to eq "my-app"
end
end
context "accessors" do
it "has a schedule accessor" do
subject.schedule = "30 0 * * *"
expect(subject.schedule).to eq "30 0 * * *"
end
it "has a command accessor" do
subject.schedule = "/bin/bash -l -c ls\\ -l"
expect(subject.schedule).to eq "/bin/bash -l -c ls\\ -l"
end
it "has a job_manifest accessor" do
subject.job_manifest = manifest
expect(subject.job_manifest).to eq manifest
end
it "has a name accessor" do
subject.name = "cron-job"
expect(subject.name).to eq "cron-job"
end
it "has an identifier accessor" do
subject.name = "my-app"
expect(subject.name).to eq "my-app"
end
end
context "#cron_job_manifest" do
subject do
CronKubernetes::CronJob.new(
schedule: "*/1 * * * *",
command: ["/bin/bash", "-l", "-c", "echo Hello from the Kubernetes cluster"],
job_manifest: manifest,
name: "hello",
identifier: "my-app"
)
end
it "generates a Kubernetes CronJob manifest for the scheduled command" do
# rubocop:disable Layout/TrailingWhitespace
expect(subject.cron_job_manifest.to_yaml).to eq <<~MANIFEST
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: my-app-hello
namespace: default
labels:
cron-kubernetes-identifier: my-app
spec:
schedule: "*/1 * * * *"
jobTemplate:
metadata:
spec:
template:
spec:
containers:
- name: hello
image: ubuntu
command:
- "/bin/bash"
- "-l"
- "-c"
- echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
MANIFEST
# rubocop:enable Layout/TrailingWhitespace
end
context "when no name is provided" do
subject do
CronKubernetes::CronJob.new(
schedule: "*/1 * * * *",
command: ["/bin/bash", "-l", "-c", "echo Hello from the Kubernetes cluster"],
job_manifest: manifest,
identifier: "my-app"
)
end
context "but exists in the Job template metadata" do
let(:manifest) do
YAML.safe_load <<~MANIFEST
apiVersion: batch/v1
kind: Job
metadata:
name: hello-job
spec:
template:
spec:
containers:
- name: hello
image: ubuntu
restartPolicy: OnFailure
MANIFEST
end
it "pulls the name from the Job metadata" do
expect(subject.cron_job_manifest["metadata"]["name"]).to eq "my-app-hello-job-51e2eaa4"
expect(subject.cron_job_manifest["spec"]["jobTemplate"]["metadata"]["name"]).to eq "hello-job"
end
end
context "but exists in the Pod template metadata" do
let(:manifest) do
YAML.safe_load <<~MANIFEST
apiVersion: batch/v1
kind: Job
spec:
template:
metadata:
name: hello-pod
spec:
containers:
- name: hello
image: ubuntu
restartPolicy: OnFailure
MANIFEST
end
it "pulls the name from the Pod metadata" do
expect(subject.cron_job_manifest["metadata"]["name"]).to eq "my-app-hello-pod-51e2eaa4"
job_template = subject.cron_job_manifest["spec"]["jobTemplate"]
pod_template = job_template["spec"]["template"]
expect(pod_template["metadata"]["name"]).to eq "hello-pod"
end
end
end
end
end
| 29.4 | 104 | 0.528011 |
bf216a60dc4cf898be6304ac313f2bcec198600e | 12,864 | # frozen_string_literal: true
require "utils/spdx"
describe SPDX do
describe ".license_data" do
it "has the license list version" do
expect(described_class.license_data["licenseListVersion"]).not_to eq(nil)
end
it "has the release date" do
expect(described_class.license_data["releaseDate"]).not_to eq(nil)
end
it "has licenses" do
expect(described_class.license_data["licenses"].length).not_to eq(0)
end
end
describe ".exception_data" do
it "has the license list version" do
expect(described_class.exception_data["licenseListVersion"]).not_to eq(nil)
end
it "has the release date" do
expect(described_class.exception_data["releaseDate"]).not_to eq(nil)
end
it "has exceptions" do
expect(described_class.exception_data["exceptions"].length).not_to eq(0)
end
end
describe ".download_latest_license_data!", :needs_network do
let(:tmp_json_path) { Pathname.new(TEST_TMPDIR) }
after do
FileUtils.rm tmp_json_path/"spdx_licenses.json"
FileUtils.rm tmp_json_path/"spdx_exceptions.json"
end
it "downloads latest license data" do
described_class.download_latest_license_data! to: tmp_json_path
expect(tmp_json_path/"spdx_licenses.json").to exist
expect(tmp_json_path/"spdx_exceptions.json").to exist
end
end
describe ".parse_license_expression" do
it "returns a single license" do
expect(described_class.parse_license_expression("MIT").first).to eq ["MIT"]
end
it "returns a single license with plus" do
expect(described_class.parse_license_expression("Apache-2.0+").first).to eq ["Apache-2.0+"]
end
it "returns multiple licenses with :any" do
expect(described_class.parse_license_expression(any_of: ["MIT", "0BSD"]).first).to eq ["MIT", "0BSD"]
end
it "returns multiple licenses with :all" do
expect(described_class.parse_license_expression(all_of: ["MIT", "0BSD"]).first).to eq ["MIT", "0BSD"]
end
it "returns multiple licenses with plus" do
expect(described_class.parse_license_expression(any_of: ["MIT", "EPL-1.0+"]).first).to eq ["MIT", "EPL-1.0+"]
end
it "returns multiple licenses with array" do
expect(described_class.parse_license_expression(["MIT", "EPL-1.0+"]).first).to eq ["MIT", "EPL-1.0+"]
end
it "returns license and exception" do
license_expression = { "MIT" => { with: "LLVM-exception" } }
expect(described_class.parse_license_expression(license_expression)).to eq [["MIT"], ["LLVM-exception"]]
end
it "returns licenses and exceptions for compex license expressions" do
license_expression = { any_of: [
"MIT",
:public_domain,
all_of: ["0BSD", "Zlib"],
"curl" => { with: "LLVM-exception" },
] }
result = [["MIT", :public_domain, "curl", "0BSD", "Zlib"], ["LLVM-exception"]]
expect(described_class.parse_license_expression(license_expression)).to eq result
end
it "returns :public_domain" do
expect(described_class.parse_license_expression(:public_domain).first).to eq [:public_domain]
end
end
describe ".valid_license?" do
it "returns true for valid license identifier" do
expect(described_class.valid_license?("MIT")).to eq true
end
it "returns false for invalid license identifier" do
expect(described_class.valid_license?("foo")).to eq false
end
it "returns true for deprecated license identifier" do
expect(described_class.valid_license?("GPL-1.0")).to eq true
end
it "returns true for license identifier with plus" do
expect(described_class.valid_license?("Apache-2.0+")).to eq true
end
it "returns true for :public_domain" do
expect(described_class.valid_license?(:public_domain)).to eq true
end
end
describe ".deprecated_license?" do
it "returns true for deprecated license identifier" do
expect(described_class.deprecated_license?("GPL-1.0")).to eq true
end
it "returns false for non-deprecated license identifier" do
expect(described_class.deprecated_license?("MIT")).to eq false
end
it "returns false for invalid license identifier" do
expect(described_class.deprecated_license?("foo")).to eq false
end
it "returns false for :public_domain" do
expect(described_class.deprecated_license?(:public_domain)).to eq false
end
end
describe ".valid_license_exception?" do
it "returns true for valid license exception identifier" do
expect(described_class.valid_license_exception?("LLVM-exception")).to eq true
end
it "returns false for invalid license exception identifier" do
expect(described_class.valid_license_exception?("foo")).to eq false
end
it "returns false for deprecated license exception identifier" do
expect(described_class.valid_license_exception?("Nokia-Qt-exception-1.1")).to eq false
end
end
describe ".license_expression_to_string" do
it "returns a single license" do
expect(described_class.license_expression_to_string("MIT")).to eq "MIT"
end
it "returns a single license with plus" do
expect(described_class.license_expression_to_string("Apache-2.0+")).to eq "Apache-2.0+"
end
it "returns multiple licenses with :any" do
expect(described_class.license_expression_to_string(any_of: ["MIT", "0BSD"])).to eq "MIT or 0BSD"
end
it "returns multiple licenses with :all" do
expect(described_class.license_expression_to_string(all_of: ["MIT", "0BSD"])).to eq "MIT and 0BSD"
end
it "returns multiple licenses with plus" do
expect(described_class.license_expression_to_string(any_of: ["MIT", "EPL-1.0+"])).to eq "MIT or EPL-1.0+"
end
it "treats array as any_of:" do
expect(described_class.license_expression_to_string(["MIT", "EPL-1.0+"])).to eq "MIT or EPL-1.0+"
end
it "returns license and exception" do
license_expression = { "MIT" => { with: "LLVM-exception" } }
expect(described_class.license_expression_to_string(license_expression)).to eq "MIT with LLVM-exception"
end
it "returns licenses and exceptions for compex license expressions" do
license_expression = { any_of: [
"MIT",
:public_domain,
all_of: ["0BSD", "Zlib"],
"curl" => { with: "LLVM-exception" },
] }
result = "MIT or Public Domain or (0BSD and Zlib) or (curl with LLVM-exception)"
expect(described_class.license_expression_to_string(license_expression)).to eq result
end
it "returns :public_domain" do
expect(described_class.license_expression_to_string(:public_domain)).to eq "Public Domain"
end
end
describe ".license_version_info_info" do
it "returns license without version" do
expect(described_class.license_version_info("MIT")).to eq ["MIT"]
end
it "returns :public_domain without version" do
expect(described_class.license_version_info(:public_domain)).to eq [:public_domain]
end
it "returns license with version" do
expect(described_class.license_version_info("Apache-2.0")).to eq ["Apache", "2.0", false]
end
it "returns license with version and plus" do
expect(described_class.license_version_info("Apache-2.0+")).to eq ["Apache", "2.0", true]
end
it "returns more complicated license with version" do
expect(described_class.license_version_info("CC-BY-3.0-AT")).to eq ["CC-BY", "3.0", false]
end
it "returns more complicated license with version and plus" do
expect(described_class.license_version_info("CC-BY-3.0-AT+")).to eq ["CC-BY", "3.0", true]
end
it "returns license with -only" do
expect(described_class.license_version_info("GPL-3.0-only")).to eq ["GPL", "3.0", false]
end
it "returns license with -or-later" do
expect(described_class.license_version_info("GPL-3.0-or-later")).to eq ["GPL", "3.0", true]
end
end
describe ".licenses_forbid_installation?" do
let(:mit_forbidden) { { "MIT" => described_class.license_version_info("MIT") } }
let(:epl_1_forbidden) { { "EPL-1.0" => described_class.license_version_info("EPL-1.0") } }
let(:epl_1_plus_forbidden) { { "EPL-1.0+" => described_class.license_version_info("EPL-1.0+") } }
let(:multiple_forbidden) {
{
"MIT" => described_class.license_version_info("MIT"),
"0BSD" => described_class.license_version_info("0BSD"),
}
}
let(:any_of_license) { { any_of: ["MIT", "0BSD"] } }
let(:license_array) { ["MIT", "0BSD"] }
let(:all_of_license) { { all_of: ["MIT", "0BSD"] } }
let(:nested_licenses) {
{
any_of: [
"MIT",
{ "MIT" => { with: "LLVM-exception" } },
{ any_of: ["MIT", "0BSD"] },
],
}
}
let(:license_exception) { { "MIT" => { with: "LLVM-exception" } } }
it "allows installation with no forbidden licenses" do
expect(described_class.licenses_forbid_installation?("MIT", {})).to eq false
end
it "allows installation with non-forbidden license" do
expect(described_class.licenses_forbid_installation?("0BSD", mit_forbidden)).to eq false
end
it "forbids installation with forbidden license" do
expect(described_class.licenses_forbid_installation?("MIT", mit_forbidden)).to eq true
end
it "allows installation of later license version" do
expect(described_class.licenses_forbid_installation?("EPL-2.0", epl_1_forbidden)).to eq false
end
it "forbids installation of later license version with plus in forbidden license list" do
expect(described_class.licenses_forbid_installation?("EPL-2.0", epl_1_plus_forbidden)).to eq true
end
it "allows installation when one of the any_of licenses is allowed" do
expect(described_class.licenses_forbid_installation?(any_of_license, mit_forbidden)).to eq false
end
it "forbids installation when none of the any_of licenses are allowed" do
expect(described_class.licenses_forbid_installation?(any_of_license, multiple_forbidden)).to eq true
end
it "allows installation when one of the array licenses is allowed" do
expect(described_class.licenses_forbid_installation?(license_array, mit_forbidden)).to eq false
end
it "forbids installation when none of the array licenses are allowed" do
expect(described_class.licenses_forbid_installation?(license_array, multiple_forbidden)).to eq true
end
it "forbids installation when one of the all_of licenses is allowed" do
expect(described_class.licenses_forbid_installation?(all_of_license, mit_forbidden)).to eq true
end
it "allows installation with license + exception that aren't forbidden" do
expect(described_class.licenses_forbid_installation?(license_exception, epl_1_forbidden)).to eq false
end
it "forbids installation with license + exception that are't forbidden" do
expect(described_class.licenses_forbid_installation?(license_exception, mit_forbidden)).to eq true
end
it "allows installation with nested licenses with no forbidden licenses" do
expect(described_class.licenses_forbid_installation?(nested_licenses, epl_1_forbidden)).to eq false
end
it "allows installation with nested licenses when second hash item matches" do
expect(described_class.licenses_forbid_installation?(nested_licenses, mit_forbidden)).to eq false
end
it "forbids installation with nested licenses when all licenses are forbidden" do
expect(described_class.licenses_forbid_installation?(nested_licenses, multiple_forbidden)).to eq true
end
end
describe ".forbidden_licenses_include?" do
let(:mit_forbidden) { { "MIT" => described_class.license_version_info("MIT") } }
let(:epl_1_forbidden) { { "EPL-1.0" => described_class.license_version_info("EPL-1.0") } }
let(:epl_1_plus_forbidden) { { "EPL-1.0+" => described_class.license_version_info("EPL-1.0+") } }
it "returns false with no forbidden licenses" do
expect(described_class.forbidden_licenses_include?("MIT", {})).to eq false
end
it "returns false with no matching forbidden licenses" do
expect(described_class.forbidden_licenses_include?("MIT", epl_1_forbidden)).to eq false
end
it "returns true with matching license" do
expect(described_class.forbidden_licenses_include?("MIT", mit_forbidden)).to eq true
end
it "returns false with later version of forbidden license" do
expect(described_class.forbidden_licenses_include?("EPL-2.0", epl_1_forbidden)).to eq false
end
it "returns true with later version of forbidden license with later versions forbidden" do
expect(described_class.forbidden_licenses_include?("EPL-2.0", epl_1_plus_forbidden)).to eq true
end
end
end
| 37.835294 | 115 | 0.703436 |
e91801fca6995c3280be8cc6e9ad3a8db269cc7c | 365 | cask "a-slower-speed-of-light" do
version "summer12"
sha256 "4163053a6caa6d258475aa29209fb863fe63139c8d3048661f8a9bc11ffd187c"
url "https://web.mit.edu/gambit/#{version}/speedoflight/beta/A_Slower_Speed_of_Light.dmg"
name "A Slower Speed of Light"
homepage "http://gamelab.mit.edu/games/a-slower-speed-of-light/"
app "A Slower Speed of Light.app"
end
| 33.181818 | 91 | 0.772603 |
1d9f2c551bc81475ef36decca8625879c754bb6f | 992 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
OpenAPI spec version: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 3.3.2-SNAPSHOT
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::Foo
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'Foo' do
before do
# run before each test
@instance = Petstore::Foo.new
end
after do
# run after each test
end
describe 'test an instance of Foo' do
it 'should create an instance of Foo' do
expect(@instance).to be_instance_of(Petstore::Foo)
end
end
describe 'test attribute "bar"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 23.619048 | 157 | 0.72379 |
39f911dfd713df37921f9c2a37f574582c82af89 | 14,596 | require 'spec_helper'
require 'monitor'
describe 'Client - Reconnect' do
before(:each) do
@s = NatsServerControl.new
@s.start_server(true)
end
after(:each) do
@s.kill_server
sleep 1
end
it 'should process errors from a server and reconnect' do
nats = NATS::IO::Client.new
nats.connect({
reconnect: true,
reconnect_time_wait: 2,
max_reconnect_attempts: 1
})
mon = Monitor.new
done = mon.new_cond
errors = []
nats.on_error do |e|
errors << e
end
disconnects = []
nats.on_disconnect do |e|
disconnects << e
end
closes = 0
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
# Trigger invalid subject server error which the client
# detects so that it will disconnect.
nats.subscribe("hello.")
# FIXME: This can fail due to timeout because
# disconnection may have already occurred.
nats.flush(1) rescue nil
# Should have a connection closed at this without reconnecting.
mon.synchronize { done.wait(3) }
expect(errors.count > 1).to eql(true)
expect(errors.first).to be_a(NATS::IO::ServerError)
expect(disconnects.count > 1).to eql(true)
expect(disconnects.first).to be_a(NATS::IO::ServerError)
expect(closes).to eql(0)
nats.close
expect(nats.closed?).to eql(true)
end
it 'should reconnect to server and replay all subscriptions' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = 0
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do
disconnects += 1
end
nats.on_close do
closes += 1
mon.synchronize do
done.signal
end
end
nats.connect
nats.subscribe("foo") do |msg|
msgs << msg
end
nats.subscribe("bar") do |msg|
msgs << msg
end
nats.flush
nats.publish("foo", "hello.0")
nats.flush
@s.kill_server
1.upto(10).each do |n|
nats.publish("foo", "hello.#{n}")
sleep 0.1
end
@s.start_server(true)
sleep 1
mon.synchronize { done.wait(1) }
expect(disconnects).to eql(1)
expect(msgs.count).to eql(11)
expect(reconnects).to eql(1)
expect(closes).to eql(0)
# Cannot guarantee to get all of them since the server
# was interrupted during send but at least some which
# were pending during reconnect should have made it.
expect(msgs.count > 5).to eql(true)
expect(nats.status).to eql(NATS::IO::CONNECTED)
nats.close
end
it 'should abort reconnecting if disabled' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = 0
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do
disconnects += 1
end
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
nats.connect(:reconnect => false)
nats.subscribe("foo") do |msg|
msgs << msg
end
nats.subscribe("bar") do |msg|
msgs << msg
end
nats.flush
nats.publish("foo", "hello")
@s.kill_server
10.times do
nats.publish("foo", "hello")
sleep 0.01
end
# Wait for a bit before checking state again
mon.synchronize { done.wait(1) }
expect(nats.last_error).to be_a(Errno::ECONNRESET)
expect(nats.status).to eql(NATS::IO::DISCONNECTED)
nats.close
end
it 'should give up connecting if no servers available' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = []
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do |e|
disconnects << e
end
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
expect do
nats.connect({
:servers => ["nats://127.0.0.1:4229"],
:max_reconnect_attempts => 2,
:reconnect_time_wait => 1
})
end.to raise_error(Errno::ECONNREFUSED)
# Confirm that we have captured the sticky error
# and that the connection has remained disconnected.
expect(errors.first).to be_a(Errno::ECONNREFUSED)
expect(errors.last).to be_a(Errno::ECONNREFUSED)
expect(errors.count).to eql(3)
expect(nats.last_error).to be_a(Errno::ECONNREFUSED)
expect(nats.status).to eql(NATS::IO::DISCONNECTED)
end
it 'should give up reconnecting if no servers available' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = []
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do |e|
disconnects << e
end
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
nats.connect({
:servers => ["nats://127.0.0.1:4222"],
:max_reconnect_attempts => 1,
:reconnect_time_wait => 1
})
nats.subscribe("foo") do |msg|
msgs << msg
end
nats.subscribe("bar") do |msg|
msgs << msg
end
nats.flush
nats.publish("foo", "hello.0")
nats.flush
@s.kill_server
1.upto(10).each do |n|
nats.publish("foo", "hello.#{n}")
sleep 0.1
end
# Confirm that we have captured the sticky error
# and that the connection is closed due no servers left.
sleep 0.5
mon.synchronize { done.wait(5) }
expect(disconnects.count).to eql(2)
expect(reconnects).to eql(0)
expect(closes).to eql(1)
expect(nats.last_error).to be_a(NATS::IO::NoServersError)
expect(errors.first).to be_a(Errno::ECONNRESET)
expect(errors.last).to be_a(Errno::ECONNREFUSED)
expect(errors.count).to eql(3)
expect(nats.status).to eql(NATS::IO::CLOSED)
end
context 'against a server which is idle during connect' do
before(:all) do
# Start a fake tcp server
@fake_nats_server = TCPServer.new 4444
@fake_nats_server_th = Thread.new do
loop do
# Wait for a client to connect
@fake_nats_server.accept
end
end
end
after(:all) do
@fake_nats_server_th.exit
@fake_nats_server.close
end
it 'should give up reconnecting if no servers available due to timeout errors during connect' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = []
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do |e|
disconnects << e
end
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
nats.connect({
:servers => ["nats://127.0.0.1:4222", "nats://127.0.0.1:4444"],
:max_reconnect_attempts => 1,
:reconnect_time_wait => 1,
:dont_randomize_servers => true,
:connect_timeout => 1
})
# Trigger reconnect logic
@s.kill_server
mon.synchronize { done.wait(7) }
expect(disconnects.count).to eql(2)
expect(reconnects).to eql(0)
expect(closes).to eql(1)
expect(disconnects.last).to be_a(NATS::IO::NoServersError)
expect(nats.last_error).to be_a(NATS::IO::NoServersError)
expect(errors.first).to be_a(Errno::ECONNRESET)
expect(errors[1]).to be_a(NATS::IO::SocketTimeoutError)
expect(errors.last).to be_a(Errno::ECONNREFUSED)
expect(errors.count).to eql(5)
expect(nats.status).to eql(NATS::IO::CLOSED)
end
end
context 'against a server which becomes idle after being connected' do
before(:all) do
# Start a fake tcp server
@fake_nats_server = TCPServer.new 4445
@fake_nats_server_th = Thread.new do
loop do
# Wait for a client to connect
client = @fake_nats_server.accept
begin
client.puts "INFO {}\r\n"
# Read and ignore CONNECT command send by the client
connect_op = client.gets
# Reply to any pending pings client may have sent
sleep 0.1
client.puts "PONG\r\n"
# Make connection go stale so that client gives up
sleep 10
ensure
client.close
end
end
end
end
after(:all) do
@fake_nats_server_th.exit
@fake_nats_server.close
end
it 'should reconnect to a healthy server if connection becomes stale' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = 0
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do
disconnects += 1
end
nats.on_close do
closes += 1
mon.synchronize { done.signal }
end
nats.connect({
:servers => ["nats://127.0.0.1:4445","nats://127.0.0.1:4222"],
:max_reconnect_attempts => -1,
:reconnect_time_wait => 2,
:dont_randomize_servers => true,
:connect_timeout => 1,
:ping_interval => 2
})
mon.synchronize { done.wait(7) }
# Wrap up connection with server and confirm
nats.close
expect(disconnects).to eql(2)
expect(reconnects).to eql(1)
expect(closes).to eql(1)
expect(errors.count).to eql(1)
expect(errors.first).to be_a(NATS::IO::StaleConnectionError)
expect(nats.last_error).to eql(nil)
expect(nats.status).to eql(NATS::IO::CLOSED)
end
end
context 'against a server which stops following protocol after being connected' do
before(:all) do
# Start a fake tcp server
@fake_nats_server = TCPServer.new 4446
@fake_nats_server_th = Thread.new do
loop do
# Wait for a client to connect
client = @fake_nats_server.accept
begin
client.puts "INFO {}\r\n"
# Read and ignore CONNECT command send by the client
connect_op = client.gets
# Reply to any pending pings client may have sent
sleep 0.1
client.puts "PONG\r\n"
sleep 1
client.puts "MSG MSG MSG MSG\r\n"
sleep 10
ensure
client.close
end
end
end
end
after(:all) do
@fake_nats_server_th.exit
@fake_nats_server.close
end
it 'should reconnect to a healthy server after unknown protocol error' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = 0
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do
disconnects += 1
mon.synchronize { done.signal }
end
nats.on_close do
closes += 1
end
nats.connect({
:servers => ["nats://127.0.0.1:4446","nats://127.0.0.1:4222"],
:max_reconnect_attempts => -1,
:reconnect_time_wait => 2,
:dont_randomize_servers => true,
:connect_timeout => 1
})
# Wait for disconnect due to the unknown protocol error
mon.synchronize { done.wait(7) }
expect(errors.first).to be_a(NATS::IO::ServerError)
expect(errors.first.to_s).to include("Unknown protocol")
# Wait a bit for reconnect to occur
sleep 1
expect(nats.status).to eql(NATS::IO::CONNECTED)
expect(disconnects).to eql(1)
expect(reconnects).to eql(1)
expect(closes).to eql(0)
expect(errors.count).to eql(1)
# Wrap up connection with server and confirm
nats.close
expect(nats.status).to eql(NATS::IO::CLOSED)
end
end
context 'against a server to which we have a stale connection after being connected' do
before(:all) do
# Start a fake tcp server
@fake_nats_server = TCPServer.new 4447
@fake_nats_server_th = Thread.new do
loop do
# Wait for a client to connect
client = @fake_nats_server.accept
begin
client.puts "INFO {}\r\n"
# Read and ignore CONNECT command send by the client
connect_op = client.gets
# Reply to any pending pings client may have sent
sleep 0.5
client.puts "PONG\r\n"
sleep 1
client.puts "-ERR 'Stale Connection'\r\n"
sleep 3
ensure
client.close
end
end
end
end
after(:all) do
@fake_nats_server_th.exit
@fake_nats_server.close
end
it 'should try to reconnect after receiving stale connection error' do
msgs = []
errors = []
closes = 0
reconnects = 0
disconnects = 0
nats = NATS::IO::Client.new
mon = Monitor.new
done = mon.new_cond
nats.on_error do |e|
errors << e
end
nats.on_reconnect do
reconnects += 1
end
nats.on_disconnect do
disconnects += 1
mon.synchronize { done.signal }
end
nats.on_close do
closes += 1
end
nats.connect({
:servers => ["nats://127.0.0.1:4447"],
:max_reconnect_attempts => 1,
:reconnect_time_wait => 2,
:dont_randomize_servers => true,
:connect_timeout => 2
})
# Wait for disconnect due to the unknown protocol error
mon.synchronize { done.wait(7) }
expect(errors.first).to be_a(NATS::IO::StaleConnectionError)
# Wait a bit for reconnect logic to trigger
sleep 5
expect(nats.status).to eql(NATS::IO::RECONNECTING)
expect(disconnects).to eql(2)
expect(reconnects).to eql(1)
expect(closes).to eql(0)
expect(errors.count).to eql(2)
# Reconnect here
sleep 5
# Wrap up connection with server and confirm
nats.close
expect(nats.status).to eql(NATS::IO::CLOSED)
end
end
end
| 23.316294 | 100 | 0.591189 |
08c30d02d8f1cb9965941082e0688d9c092f21b3 | 1,225 | class GitUrlSub < Formula
desc "Recursively substitute remote URLs for multiple repos"
homepage "https://gosuri.github.io/git-url-sub"
url "https://github.com/gosuri/git-url-sub/archive/1.0.1.tar.gz"
sha256 "6c943b55087e786e680d360cb9e085d8f1d7b9233c88e8f2e6a36f8e598a00a9"
head "https://github.com/gosuri/git-url-sub.git"
bottle do
cellar :any_skip_relocation
sha256 "f8f1a14a4d3cbc359b741111b56f5c47d252946784501e934fbdc5f82cbd2ed8" => :mojave
sha256 "4eca101481773e802431bc9fc264f5f2db309595d0faf0c02886a559c31baa91" => :high_sierra
sha256 "2fcf47332e070caed126fef2be0a1108a23e18a9d1ba80b6059b45a417af1b31" => :sierra
sha256 "cf954ff293abbcaf8816c8142b5762ebe7601107f76530f6bab0edea71e2d609" => :el_capitan
sha256 "2edfbc5f15001b1c4c08b26251a845533473a79bc2f387d3fd1d74751080cd1b" => :yosemite
sha256 "ce9c28238d1904b9d2c97da10fd7a6be0b1ceafde423311078dfac0bbe8a82dc" => :mavericks
end
def install
system "make", "install", "PREFIX=#{prefix}"
end
test do
system "git", "init"
system "git", "remote", "add", "origin", "foo"
system "#{bin}/git-url-sub", "-c", "foo", "bar"
assert_match(/origin\s+bar \(fetch\)/, shell_output("git remote -v"))
end
end
| 42.241379 | 93 | 0.763265 |
f8b910dc33ec04e517033a41a428808b0fa834e6 | 2,514 | # encoding: utf-8
module LogStash; module Outputs; class SumoLogic;
class Piler
require "logstash/outputs/sumologic/common"
require "logstash/outputs/sumologic/statistics"
require "logstash/outputs/sumologic/message_queue"
include LogStash::Outputs::SumoLogic::Common
attr_reader :is_pile
def initialize(queue, stats, config)
@interval = config["interval"] ||= 0
@pile_max = config["pile_max"] ||= 0
@queue = queue
@stats = stats
@stopping = Concurrent::AtomicBoolean.new(false)
@payload_builder = PayloadBuilder.new(@stats, config)
@header_builder = HeaderBuilder.new(config)
@is_pile = (@interval > 0 && @pile_max > 0)
if (@is_pile)
@pile = Hash.new("")
@semaphore = Mutex.new
end
end # def initialize
def start()
@stopping.make_false()
if (@is_pile)
log_info("starting piler...",
:max => @pile_max,
:timeout => @interval)
@piler_t = Thread.new {
while @stopping.false?
Stud.stoppable_sleep(@interval) { @stopping.true? }
log_dbg("timeout", :timeout => @interval)
enq_and_clear()
end # while
}
end # if
end # def start
def stop()
@stopping.make_true()
if (@is_pile)
log_info("shutting down piler in #{@interval * 2} secs ...")
@piler_t.join(@interval * 2)
log_info("piler is fully shutted down")
end
end # def stop
def input(event)
if (@stopping.true?)
log_warn("piler is shutting down, event is dropped",
"event" => event)
else
headers = @header_builder.build(event)
payload = @payload_builder.build(event)
if (@is_pile)
@semaphore.synchronize {
content = @pile[headers]
size = content.bytesize
if size + payload.bytesize > @pile_max
@queue.enq(Batch.new(headers, content))
@pile[headers] = ""
end
@pile[headers] = @pile[headers].blank? ? payload : "#{@pile[headers]}\n#{payload}"
}
else
@queue.enq(Batch.new(headers, payload))
end # if
end
end # def input
private
def enq_and_clear()
@semaphore.synchronize {
@pile.each do |headers, content|
@queue.enq(Batch.new(headers, content))
end
@pile.clear()
}
end # def enq_and_clear
end
end; end; end | 28.247191 | 94 | 0.565632 |
bb63e79248cdbf3394b25a2c69ca057d1801a855 | 505 | class RosterController < ApplicationController
before_filter :ensure_logged_in
before_filter :set_tab
def index
return unless load_course( params[:course] )
return unless allowed_to_see_course( @course, @user )
@instructors = @course.instructors
@students = @course.students
@breadcrumb = Breadcrumb.for_course(@course)
@breadcrumb.roster = true
end
private
def set_tab
@show_course_tabs = true
@tab = "course_roster"
@title = "Course Roster"
end
end
| 21.956522 | 57 | 0.716832 |
26c3a4e5a10e6dbe758647b0a5b6d14f9da538e6 | 384 | # frozen_string_literal: true
require_relative '../../lib/Sento.rb'
describe PluginMap do
it 'validate the count of start and end' do
maper = described_class.new
maper.add_start(1)
maper.add_end(3)
expect(maper.is_valid_brackets_count()).to eq(true)
maper.add_end(3)
expect(maper.is_valid_brackets_count()).to eq(false)
end
end
| 25.6 | 60 | 0.671875 |
218e9004704ad20d40f7b29832a1c2e8e47a5c85 | 492 | require 'redmine'
ApplicationHelper.prepend(AbsoluteDateHelperPatch::ApplicationHelperWithAbsoluteDate)
Rails.application.config.i18n.load_path += Dir["#{File.dirname(__FILE__)}/config/locales/*.{rb,yml}"]
Redmine::Plugin.register :redmine_absolute_dates do
name 'Redmine Absolute Dates plugin'
author 'suer'
description 'Display absolute create or update dates '
version '0.0.4'
url 'https://github.com/suer/redmine_absolute_dates'
author_url 'http://d.hatena.ne.jp/suer'
end
| 32.8 | 101 | 0.780488 |
aceaa74e35c3bffa9777ed99aa6031ae41eb0bff | 882 | require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'
require 'beaker/puppet_install_helper'
run_puppet_install_helper unless ENV['BEAKER_provision'] == 'no'
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'rhel_mrepo_profiles')
hosts.each do |host|
on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module', 'install', 'puppetlabs-mrepo'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module', 'install', 'puppetlabs-git'), { :acceptable_exit_codes => [0,1] }
end
end
end
| 35.28 | 100 | 0.705215 |
39a617a4be57bdc1daf872a8f60fcf4cee122e1a | 12,083 | # frozen_string_literal: true
require 'lib/settings'
require 'engine/auto_router'
require 'view/game/actionable'
module View
module Game
class RouteSelector < Snabberb::Component
include Actionable
include Lib::Settings
needs :last_entity, store: true, default: nil
needs :last_round, store: true, default: nil
needs :last_company, store: true, default: nil
needs :routes, store: true, default: []
needs :selected_route, store: true, default: nil
needs :selected_company, default: nil, store: true
needs :abilities, store: true, default: nil
# Get routes that have a length greater than zero
# Due to the way this and the map hook up routes needs to have
# an entry, but that route is not valid at zero length
def active_routes
@routes.select { |r| r.chains.any? }
end
def generate_last_routes!
trains = @game.route_trains(@game.round.current_entity)
operating = @game.round.current_entity.operating_history
last_run = operating[operating.keys.max]&.routes
return [] unless last_run
return [] if @abilities&.any?
halts = operating[operating.keys.max]&.halts
nodes = operating[operating.keys.max]&.nodes
last_run.map do |train, connection_hexes|
next unless trains.include?(train)
# A future enhancement to this could be to find trains and move the routes over
@routes << Engine::Route.new(
@game,
@game.phase,
train,
connection_hexes: connection_hexes,
routes: @routes,
halts: halts[train],
nodes: nodes[train],
)
end.compact
end
def render
step = @game.active_step
current_entity = @game.round.current_entity
if @selected_company&.owner == current_entity
ability = @game.abilities(@selected_company, :hex_bonus, time: 'route')
# Clean routes if we select company, but just when we select
unless @last_company
cleanup
store(:last_company, @selected_company, skip: true)
end
store(:abilities, ability ? [ability.type] : nil, skip: true)
else
cleanup if @last_company
store(:last_company, nil, skip: true)
store(:abilities, nil, skip: true)
end
# this is needed for the rare case when moving directly between run_routes steps
if @last_entity != current_entity || @last_round != @game.round
cleanup
store(:last_entity, current_entity, skip: true)
store(:last_round, @game.round, skip: true)
end
trains = @game.route_trains(current_entity)
train_help =
if (helps = @game.train_help(current_entity, trains, @routes)).any?
h('ul',
{ style: { 'padding-left': '20px' } },
helps.map { |help| h('li', [h('p.small_font', help)]) })
end
if @routes.empty? && generate_last_routes!.any?
description = 'Prior routes are autofilled.'
@selected_route = @routes.first
store(:routes, @routes, skip: true)
store(:selected_route, @selected_route, skip: true)
end
if !@selected_route && (first_train = trains[0])
route = Engine::Route.new(@game, @game.phase, first_train, abilities: @abilities, routes: @routes)
@routes << route
store(:routes, @routes, skip: true)
store(:selected_route, route, skip: true)
end
@routes.each(&:clear_cache!)
render_halts = false
trains = trains.flat_map do |train|
onclick = lambda do
unless (route = @routes.find { |t| t.train == train })
route = Engine::Route.new(@game, @game.phase, train, abilities: @abilities, routes: @routes)
@routes << route
store(:routes, @routes)
end
store(:selected_route, route)
end
selected = @selected_route&.train == train
style = {
border: "solid 3px #{selected ? color_for(:font) : color_for(:bg)}",
display: 'inline-block',
cursor: selected ? 'default' : 'pointer',
margin: '0.1rem 0rem',
padding: '3px 6px',
minWidth: '1.5rem',
textAlign: 'center',
whiteSpace: 'nowrap',
}
route = active_routes.find { |t| t.train == train }
children = []
if route
revenue, invalid = begin
[@game.format_revenue_currency(route.revenue), nil]
rescue Engine::GameError => e
['N/A', e.to_s]
end
bg_color = route_prop(@routes.index(route), :color)
style[:backgroundColor] = bg_color
style[:color] = contrast_on(bg_color)
td_props = { style: { paddingRight: '0.8rem' } }
children << h('td.right.middle', td_props, route.distance_str)
if route.halts
render_halts = true
children << h('td.right.middle', td_props,
halt_actions(route, revenue, @game.format_currency(route.subsidy)))
else
children << h('td.right.middle', td_props, revenue)
end
children << h(:td, route.revenue_str)
elsif !selected
style[:border] = '1px solid'
style[:padding] = '5px 8px'
end
invalid_props = {
attrs: {
colspan: '4',
},
style: {
padding: '0 0 0.4rem 0.4rem',
},
}
train_name = step.respond_to?(:train_name) ? step.train_name(current_entity, train) : train.name
[
h(:tr, [h('td.middle', [h(:div, { style: style, on: { click: onclick } }, train_name)]), *children]),
invalid ? h(:tr, [h(:td, invalid_props, invalid)]) : '',
]
end
div_props = {
key: 'route_selector',
hook: {
destroy: -> { cleanup },
},
}
table_props = {
style: {
marginTop: '0.5rem',
textAlign: 'left',
},
}
th_route_props = {
style: {
width: '100%',
},
}
instructions = 'Click revenue centers, again to cycle paths.'
instructions += ' Click button under Revenue to pick number of halts.' if render_halts
h(:div, div_props, [
h(:h3, 'Select Routes'),
h('div.small_font', description),
h('div.small_font', instructions),
train_help,
h(:table, table_props, [
h(:thead, [
h(:tr, [
h(:th, 'Train'),
h(:th, 'Used'),
h(:th, 'Revenue'),
h(:th, th_route_props, 'Route'),
]),
]),
h(:tbody, trains),
]),
actions(render_halts),
dividend_chart,
].compact)
end
def halt_actions(route, revenue, subsidy)
change_halts = lambda do
route.cycle_halts
store(:selected_route, route)
end
[
revenue,
h(:div, [
h('button.small', { style: { margin: '0px', padding: '0.2rem' }, on: { click: change_halts } }, subsidy),
]),
]
end
def cleanup
store(:selected_route, nil, skip: true)
store(:routes, [], skip: true)
end
def actions(render_halts)
current_entity = @game.round.current_entity
submit = lambda do
process_action(Engine::Action::RunRoutes.new(@game.current_entity, routes: active_routes))
cleanup
end
clear = lambda do
@selected_route&.reset!
store(:selected_route, @selected_route)
end
reset_all = lambda do
@game.reset_adjustable_trains!(current_entity, @routes)
@selected_route = nil
store(:selected_route, @selected_route)
@routes.clear
store(:routes, @routes)
end
clear_all = lambda do
@routes.each(&:reset!)
store(:routes, @routes)
end
flash = lambda do |message|
store(:flash_opts, { message: message }, skip: false)
end
auto = lambda do
router = Engine::AutoRouter.new(@game, flash)
@routes = router.compute(
@game.current_entity,
routes: @routes.reject { |r| r.paths.empty? },
path_timeout: setting_for(:path_timeout).to_i,
route_timeout: setting_for(:route_timeout).to_i,
)
store(:routes, @routes)
end
add_train = lambda do
if (new_train = @game.add_route_train(current_entity, @routes))
new_route = Engine::Route.new(@game, @game.phase, new_train, abilities: @abilities, routes: @routes)
@selected_route = new_route
@routes << new_route
store(:selected_route, @selected_route, skip: true)
store(:routes, @routes)
end
end
delete_train = lambda do
if @game.delete_route_train(current_entity, @selected_route)
@routes.delete(@selected_route)
@selected_route = @routes[0]
store(:selected_route, @selected_route, skip: true)
store(:routes, @routes)
end
end
increase_train = lambda do
@game.increase_route_train(current_entity, @selected_route)
store(:selected_route, @selected_route)
end
decrease_train = lambda do
@game.decrease_route_train(current_entity, @selected_route)
store(:selected_route, @selected_route)
end
submit_style = {
minWidth: '6.5rem',
marginTop: '1rem',
padding: '0.2rem 0.5rem',
}
revenue_str = begin
@game.submit_revenue_str(active_routes, render_halts)
rescue Engine::GameError
'(Invalid Route)'
end
buttons = [
h('button.small', { on: { click: clear } }, 'Clear Train'),
h('button.small', { on: { click: clear_all } }, 'Clear All'),
h('button.small', { on: { click: reset_all } }, 'Reset'),
]
if @game_data.dig('settings', 'auto_routing') || @game_data['mode'] == :hotseat
buttons << h('button.small', { on: { click: auto } }, 'Auto')
end
if @game.adjustable_train_list?(current_entity)
buttons << h('button.small', { on: { click: add_train } }, "+#{@game.adjustable_train_label(current_entity)}")
buttons << h('button.small', { on: { click: delete_train } }, "-#{@game.adjustable_train_label(current_entity)}")
end
if @game.adjustable_train_sizes?(current_entity)
buttons << h('button.small', { on: { click: increase_train } }, '+Size')
buttons << h('button.small', { on: { click: decrease_train } }, '-Size')
end
h(:div, { style: { overflow: 'auto', marginBottom: '1rem' } }, [
h(:div, buttons),
h(:button, { style: submit_style, on: { click: submit } }, 'Submit ' + revenue_str),
])
end
def dividend_chart
step = @game.active_step
return nil unless step.respond_to?(:chart)
header, *chart = step.chart(@game.round.current_entity)
rows = chart.map do |r|
h(:tr, [
h('td.padded_number', r[0]),
h(:td, r[1]),
])
end
table_props = {
style: {
margin: '0.5rem 0',
},
}
h(:table, table_props, [
h(:thead, [
h(:tr, [
h(:th, header[0]),
h(:th, header[1]),
]),
]),
h(:tbody, rows),
])
end
end
end
end
| 32.923706 | 123 | 0.53596 |
fff49f0d0b8343f99bcebd2732b157729252bc4b | 1,152 | =begin
The Trust Payments API allows an easy interaction with the Trust Payments web service.
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.
=end
require 'date'
module TrustPayments
class TerminalReceiptFormat
PDF = 'PDF'.freeze
TXT = 'TXT'.freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = TerminalReceiptFormat.constants.select { |c| TerminalReceiptFormat::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #TerminalReceiptFormat" if constantValues.empty?
value
end
end
end
| 32 | 114 | 0.751736 |
390d36958635a3b47e007dbea33d36c74152c7b5 | 1,127 | class ImportBook
def initialize(isbn)
@isbn = isbn
end
def perform
import_params
format_response
end
private
attr_reader :isbn
def import_params
goodreads_api = Goodreads::Client.new
begin
@book = goodreads_api.book_by_isbn(@isbn)
rescue Goodreads::NotFound
{}
end
end
# rubocop:disable Metrics/MethodLength
def format_response
date = convert_date
authors = author_name
{
title: @book.title,
summary: @book.description,
pages: @book.num_pages,
authors: authors,
published_on: date,
remote_cover_url: @book.image_url,
isbn: @book.isbn13
}
end
# rubocop:enable Metrics/MethodLength
def convert_date
return if @book.publication_year.empty?
year = @book.publication_year.to_i
month = (@book.publication_month.presence || '01').to_i
day = (@book.publication_day.presence || '01').to_i
Date.new(year, month, day)
end
def author_name
author = @book.authors.author
if author.is_a?(Array)
author.map(&:name).join(', ')
else
author.name
end
end
end
| 18.783333 | 59 | 0.652174 |