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
|
---|---|---|---|---|---|
382ed4bb1d42fec302efd73e17563df6e8b01a3e | 1,777 | module VestalVersions
# Allows specific versions to be tagged with a custom string. Useful for assigning a more
# meaningful value to a version for the purpose of reversion.
module VersionTagging
extend ActiveSupport::Concern
# Adds an instance method which allows version tagging through the parent object.
# Accepts a single string argument which is attached to the version record associated with
# the current version number of the parent object.
#
# Returns the given tag if successful, nil if not. Tags must be unique within the scope of
# the parent object. Tag creation will fail if non-unique.
#
# Version records corresponding to version number 1 are not typically created, but one will
# be built to house the given tag if the parent object's current version number is 1.
def tag_version(tag)
v = versions.at(version) || versions.build(:number => 1)
t = v.tag!(tag)
versions.reload
t
end
end
# Instance methods included into VestalVersions::Version to enable version tagging.
module TaggingVersionMethods
extend ActiveSupport::Concern
included do
validates_uniqueness_of :tag, :scope => [:versioned_id, :versioned_type], :if => :validate_tags?
end
# Attaches the given string to the version tag column. If the uniqueness validation fails,
# nil is returned. Otherwise, the given string is returned.
def tag!(tag)
write_attribute(:tag, tag)
save ? tag : nil
end
# Simply returns a boolean signifying whether the version instance has a tag value attached.
def tagged?
!tag.nil?
end
def validate_tags?
tagged? && tag != 'deleted'
end
Version.class_eval{ include TaggingVersionMethods }
end
end
| 34.173077 | 102 | 0.708497 |
332076debc72e504855b3bdd8f2239108f8ebb94 | 446 | require 'require_all'
require_all File.dirname(__FILE__) + '/data-scrapper/'
# -*- coding: utf-8 -*-
# how I run test for data-wrangler DataWrangler::Annotate::Compound.by_inchikey("BRMWTNUJHUMWMS-LURJTMIESA-N")
module DataScrapper
module Annotate
# autoload the compound annotation and protein annotation module
autoload :Compound, 'data-scrapper/annotate/compound'
autoload :Protein, 'data-scrapper/annotate/protein'
end
end
| 34.307692 | 111 | 0.76009 |
62f3722a39296748ac4ced192b1c1b454fdc91ea | 8,018 | # frozen_string_literal: true
require "set"
RSpec.describe "The library itself" do
def check_for_git_merge_conflicts(filename)
merge_conflicts_regex = /
<<<<<<<|
=======|
>>>>>>>
/x
failing_lines = []
each_line(filename) do |line, number|
failing_lines << number + 1 if line =~ merge_conflicts_regex
end
return if failing_lines.empty?
"#{filename} has unresolved git merge conflicts on lines #{failing_lines.join(", ")}"
end
def check_for_tab_characters(filename)
failing_lines = []
each_line(filename) do |line, number|
failing_lines << number + 1 if line =~ /\t/
end
return if failing_lines.empty?
"#{filename} has tab characters on lines #{failing_lines.join(", ")}"
end
def check_for_extra_spaces(filename)
failing_lines = []
each_line(filename) do |line, number|
next if line =~ /^\s+#.*\s+\n$/
failing_lines << number + 1 if line =~ /\s+\n$/
end
return if failing_lines.empty?
"#{filename} has spaces on the EOL on lines #{failing_lines.join(", ")}"
end
def check_for_straneous_quotes(filename)
return if File.expand_path(filename) == __FILE__
failing_lines = []
each_line(filename) do |line, number|
failing_lines << number + 1 if line =~ /’/
end
return if failing_lines.empty?
"#{filename} has an straneous quote on lines #{failing_lines.join(", ")}"
end
def check_for_expendable_words(filename)
failing_line_message = []
useless_words = %w[
actually
basically
clearly
just
obviously
really
simply
]
pattern = /\b#{Regexp.union(useless_words)}\b/i
each_line(filename) do |line, number|
next unless word_found = pattern.match(line)
failing_line_message << "#{filename}:#{number.succ} has '#{word_found}'. Avoid using these kinds of weak modifiers."
end
failing_line_message unless failing_line_message.empty?
end
def check_for_specific_pronouns(filename)
failing_line_message = []
specific_pronouns = /\b(he|she|his|hers|him|her|himself|herself)\b/i
each_line(filename) do |line, number|
next unless word_found = specific_pronouns.match(line)
failing_line_message << "#{filename}:#{number.succ} has '#{word_found}'. Use more generic pronouns in documentation."
end
failing_line_message unless failing_line_message.empty?
end
it "has no malformed whitespace" do
exempt = /\.gitmodules|fixtures|vendor|LICENSE|vcr_cassettes|rbreadline\.diff|index\.txt$/
error_messages = []
tracked_files.each do |filename|
next if filename =~ exempt
error_messages << check_for_tab_characters(filename)
error_messages << check_for_extra_spaces(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "has no estraneous quotes" do
exempt = /vendor|vcr_cassettes|LICENSE|rbreadline\.diff/
error_messages = []
tracked_files.each do |filename|
next if filename =~ exempt
error_messages << check_for_straneous_quotes(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "does not include any unresolved merge conflicts" do
error_messages = []
exempt = %r{lock/lockfile_spec|quality_spec|vcr_cassettes|\.ronn|lockfile_parser\.rb}
tracked_files.each do |filename|
next if filename =~ exempt
error_messages << check_for_git_merge_conflicts(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "maintains language quality of the documentation" do
included = /ronn/
error_messages = []
man_tracked_files.each do |filename|
next unless filename =~ included
error_messages << check_for_expendable_words(filename)
error_messages << check_for_specific_pronouns(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "maintains language quality of sentences used in source code" do
error_messages = []
exempt = /vendor|vcr_cassettes|CODE_OF_CONDUCT/
lib_tracked_files.each do |filename|
next if filename =~ exempt
error_messages << check_for_expendable_words(filename)
error_messages << check_for_specific_pronouns(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "documents all used settings" do
exemptions = %w[
forget_cli_options
gem.changelog
gem.ci
gem.coc
gem.linter
gem.mit
gem.rubocop
gem.test
git.allow_insecure
inline
trust-policy
use_gem_version_promoter_for_major_updates
]
all_settings = Hash.new {|h, k| h[k] = [] }
documented_settings = []
Bundler::Settings::BOOL_KEYS.each {|k| all_settings[k] << "in Bundler::Settings::BOOL_KEYS" }
Bundler::Settings::NUMBER_KEYS.each {|k| all_settings[k] << "in Bundler::Settings::NUMBER_KEYS" }
Bundler::Settings::ARRAY_KEYS.each {|k| all_settings[k] << "in Bundler::Settings::ARRAY_KEYS" }
Bundler::Settings::STRING_KEYS.each {|k| all_settings[k] << "in Bundler::Settings::STRING_KEYS" }
key_pattern = /([a-z\._-]+)/i
lib_tracked_files.each do |filename|
each_line(filename) do |line, number|
line.scan(/Bundler\.settings\[:#{key_pattern}\]/).flatten.each {|s| all_settings[s] << "referenced at `#{filename}:#{number.succ}`" }
end
end
documented_settings = File.read("lib/bundler/man/bundle-config.1.ronn")[/LIST OF AVAILABLE KEYS.*/m].scan(/^\* `#{key_pattern}`/).flatten
documented_settings.each do |s|
all_settings.delete(s)
expect(exemptions.delete(s)).to be_nil, "setting #{s} was exempted but was actually documented"
end
exemptions.each do |s|
expect(all_settings.delete(s)).to be_truthy, "setting #{s} was exempted but unused"
end
error_messages = all_settings.map do |setting, refs|
"The `#{setting}` setting is undocumented\n\t- #{refs.join("\n\t- ")}\n"
end
expect(error_messages.sort).to be_well_formed
expect(documented_settings).to be_sorted
end
it "can still be built" do
with_built_bundler do |_gem_path|
expect(err).to be_empty, "bundler should build as a gem without warnings, but\n#{err}"
end
end
it "ships the correct set of files" do
git_list = git_ls_files(ruby_core? ? "lib/bundler lib/bundler.rb libexec/bundle*" : "lib exe CHANGELOG.md LICENSE.md README.md bundler.gemspec")
gem_list = loaded_gemspec.files
expect(git_list.sort).to eq(gem_list.sort)
end
it "does not contain any warnings" do
exclusions = %w[
lib/bundler/capistrano.rb
lib/bundler/deployment.rb
lib/bundler/gem_tasks.rb
lib/bundler/vlad.rb
lib/bundler/templates/gems.rb
]
files_to_require = lib_tracked_files.grep(/\.rb$/) - exclusions
files_to_require.reject! {|f| f.start_with?("lib/bundler/vendor") }
files_to_require.map! {|f| File.expand_path(f, source_root) }
files_to_require.sort!
sys_exec("ruby -w") do |input, _, _|
files_to_require.each do |f|
input.puts "require '#{f}'"
end
end
warnings = last_command.stdboth.split("\n")
# ignore warnings around deprecated Object#=~ method in RubyGems
warnings.reject! {|w| w =~ %r{rubygems\/version.rb.*deprecated\ Object#=~} }
expect(warnings).to be_well_formed
end
it "does not use require internally, but require_relative" do
exempt = %r{templates/|\.5|\.1|vendor/}
all_bad_requires = []
lib_tracked_files.each do |filename|
next if filename =~ exempt
each_line(filename) do |line, number|
line.scan(/^ *require "bundler/).each { all_bad_requires << "#{filename}:#{number.succ}" }
end
end
expect(all_bad_requires).to be_empty, "#{all_bad_requires.size} internal requires that should use `require_relative`: #{all_bad_requires}"
end
private
def each_line(filename, &block)
File.readlines(filename, :encoding => "UTF-8").each_with_index(&block)
end
end
| 32.330645 | 148 | 0.681841 |
bb84c2b960f4cbbf1225a93d202efe44f8e29f27 | 1,130 | class Dcled < Formula
desc "Linux driver for dream cheeky USB message board"
homepage "https://www.jeffrika.com/~malakai/dcled/index.html"
url "https://www.jeffrika.com/~malakai/dcled/dcled-2.2.tgz"
sha256 "0da78c04e1aa42d16fa3df985cf54b0fbadf2d8ff338b9bf59bfe103c2a959c6"
bottle do
cellar :any
sha256 "91cf7fa30d905efaf7499f0667c65e25ddb69d82be3f52b93d1df6a400fd7141" => :high_sierra
sha256 "bfc1532d76b4d37c706d065bc98feb5a3aeff20751a713d7b7efb08c0976fe9e" => :sierra
sha256 "53d07c9548eaeba12645e944ce92c27a02667758176815220dc4ee2a8945c661" => :el_capitan
sha256 "2ead7c4eb3c170690890c294936a2d3fc39def2fc332ce4c1da6d17cc8f91b50" => :yosemite
sha256 "47a0b2e1eba58932936c25726d631d19f0f2a0a7b8872aff9e1d3a83b4e3cfc9" => :mavericks
end
depends_on "libhid"
depends_on "libusb"
def install
system "make", "CC=#{ENV.cc}",
"LIBUSB_CFLAGS=-I#{Formula["libusb"].opt_include}/libusb-1.0"
system "make", "install",
"FONTDIR=#{share}/#{name}",
"INSTALLDIR=#{bin}"
end
test do
system "#{bin}/dcled", "--help"
end
end
| 36.451613 | 93 | 0.726549 |
628977ee8c7ff02698d34b4fd3355f281b96c475 | 403 | class CreateVersions < ActiveRecord::Migration[4.2]
def change
create_table :versions do |t|
t.string :item_type, null: false
t.integer :item_id, null: false
t.string :event, null: false
t.string :whodunnit
t.jsonb :object
t.jsonb :object_changes
t.datetime :created_at
end
add_index :versions, [:item_type, :item_id]
end
end
| 26.866667 | 51 | 0.627792 |
ac9d5f4875bc96f18d737b4675d7bae0b9fc3fb9 | 825 | require 'minitest/autorun'
require 'exchange_rate_history'
require 'exchange_rate_history/source'
require 'exchange_rate_history/sources/ECB90Day'
require_relative 'exchange_rate_history/helpers.rb'
class ExchangeRateHistoryTest < Minitest::Test
def setup
# nothing
end
def teardown
# nothing
end
def test_init_source_with_default_creates_ECB90Day
suppress_output do
ExchangeRateHistory.init_source()
end
assert_equal ECB90Day, ExchangeRateHistory.source.class
end
def test_init_source_with_defined_source_creates_it
source_class_def = {:file_name => "ECB90Day.rb",
:class_name => "ECB90Day"}
suppress_output do
ExchangeRateHistory.init_source(source_class_def)
end
assert_equal ECB90Day, ExchangeRateHistory.source.class
end
end | 23.571429 | 59 | 0.762424 |
4a864a007d6ba0e3f8c646235a5e16990dc3f7cc | 295 | shared_examples 'an idempotent resource' do
it 'should run with changes and no errors' do
expect(@result.exit_code).to eq 2
end
it 'should run a second time without changes' do
result = apply_manifest_on_with_exit(get_working_node, @pp)
expect(result.exit_code).to eq 0
end
end
| 26.818182 | 61 | 0.752542 |
1aecb40046f4e5f4740a02e38e343659e5849302 | 1,135 | require 'rmagick'
imgl = Magick::ImageList.new
imgl.new_image(400, 150) { self.background_color = 'white' }
gc = Magick::Draw.new
gc.stroke('black').stroke_width(15)
gc.fill_opacity(0)
gc.stroke_linecap('butt')
# Draw lines with miter join
gc.stroke_linejoin('miter')
gc.polyline(25, 100, 75, 25, 125, 100)
# Draw lines with round join
gc.stroke_linejoin('round')
gc.polyline(150, 100, 200, 25, 250, 100)
# Draw lines with bevel join
gc.stroke_linejoin('bevel')
gc.polyline(275, 100, 325, 25, 375, 100)
# Show line endpoints in pink
gc.fill('lightpink').fill_opacity(0)
gc.stroke('lightpink').stroke_width(2)
gc.stroke_linejoin('miter')
gc.polyline(25, 100, 75, 25, 125, 100)
gc.polyline(150, 100, 200, 25, 250, 100)
gc.polyline(275, 100, 325, 25, 375, 100)
gc.fill_opacity(1)
gc.circle(75, 25, 76, 26)
gc.circle(200, 25, 201, 26)
gc.circle(325, 25, 326, 26)
# Annotate
gc.fill('black')
gc.stroke('transparent')
gc.pointsize(14)
gc.font_weight(Magick::BoldWeight)
gc.text(35, 120, "\"'miter' join\"")
gc.text(160, 120, "\"'round' join\"")
gc.text(280, 120, "\"'bevel' join\"")
gc.draw(imgl)
imgl.write('stroke_linejoin.gif')
| 23.645833 | 60 | 0.701322 |
f736a7db774d0630aec42e7a40ce17ef15ee3089 | 1,622 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::SidekiqMiddleware::WorkerContext::Server do
let(:worker_class) do
Class.new do
def self.name
"TestWorker"
end
# To keep track of the context that was active for certain arguments
cattr_accessor(:contexts) { {} }
include ApplicationWorker
feature_category :foo
worker_context user: nil
def perform(identifier, *args)
self.class.contexts.merge!(identifier => Gitlab::ApplicationContext.current)
end
end
end
let(:other_worker) do
Class.new do
def self.name
"OtherWorker"
end
include Sidekiq::Worker
def perform
end
end
end
before do
stub_const("TestWorker", worker_class)
stub_const("OtherWorker", other_worker)
end
around do |example|
with_sidekiq_server_middleware do |chain|
chain.add described_class
Sidekiq::Testing.inline! { example.run }
end
end
describe "#call" do
it 'applies a class context' do
Gitlab::ApplicationContext.with_context(user: build_stubbed(:user)) do
TestWorker.perform_async("identifier", 1)
end
expect(TestWorker.contexts['identifier'].keys).not_to include('meta.user')
end
it 'takes the feature category from the worker' do
TestWorker.perform_async('identifier', 1)
expect(TestWorker.contexts['identifier']).to include('meta.feature_category' => 'foo')
end
it "doesn't fail for unknown workers" do
expect { OtherWorker.perform_async }.not_to raise_error
end
end
end
| 22.84507 | 92 | 0.673243 |
1c7c30cddc2df96643a2636d76d7aa937dc82ce6 | 330 | module Ecm
module Frontend
module Generators
class SimpleNavigationGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def generate_config
template "config_navigation.rb", "config/navigation.rb"
end
end
end
end
end
| 23.571429 | 65 | 0.633333 |
ab96e0d0f0b3fec1fea0eef7abb746bd9b008be2 | 108 | class Aggregator < Thor
module Constants
SETTINGS = YAML.load_file('config/settings.yml')
end
end
| 13.5 | 52 | 0.722222 |
f76cafb4d1fcc72b8efe7b76761f1d1e7a4ec162 | 5,431 | # -*- encoding: utf-8 -*-
#
module Brcobranca
module Boleto
class Itau < Base # Banco Itaú
# Usado somente em carteiras especiais com registro para complementar o número do cocumento
attr_reader :seu_numero
validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.'
validates_length_of :convenio, maximum: 5, message: 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :numero_documento, maximum: 8, message: 'deve ser menor ou igual a 8 dígitos.'
validates_length_of :conta_corrente, maximum: 5, message: 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :seu_numero, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.'
# Nova instancia do Itau
# @param (see Brcobranca::Boleto::Base#initialize)
def initialize(campos = {})
campos = { carteira: '175' }.merge!(campos)
super(campos)
end
# Codigo do banco emissor (3 dígitos sempre)
#
# @return [String] 3 caracteres numéricos.
def banco
'341'
end
# Número do convênio/contrato do cliente junto ao banco.
# @return [String] 5 caracteres numéricos.
def convenio=(valor)
@convenio = valor.to_s.rjust(5, '0') if valor
end
# Conta corrente
# @return [String] 5 caracteres numéricos.
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(5, '0') if valor
end
# Número seqüencial utilizado para identificar o boleto.
# @return [String] 8 caracteres numéricos.
def numero_documento=(valor)
@numero_documento = valor.to_s.rjust(8, '0') if valor
end
# Número seqüencial utilizado para identificar o boleto.
# @return [String] 7 caracteres numéricos.
def seu_numero=(valor)
@seu_numero = valor.to_s.rjust(7, '0') if valor
end
# Dígito verificador do nosso número.
#
# Para a grande maioria das carteiras, são considerados para a obtenção do DAC/DV, os dados
# "AGENCIA(sem DAC/DV)/CONTA(sem DAC/DV)/CARTEIRA/NOSSO NUMERO", calculado pelo criterio do Modulo 10.<br/>
# A excecao, estão as carteiras 112, 126, 131, 146, 150 e 168 cuja obtenção esta baseada apenas nos
# dados "CARTEIRA/NOSSO NUMERO".
#
# @return [String] 1 caracteres numéricos.
def nosso_numero_dv
if %w(112 126 131 146 150 168).include?(carteira)
"#{carteira}#{numero_documento}".modulo10
else
"#{agencia}#{conta_corrente}#{carteira}#{numero_documento}".modulo10
end
end
# Calcula o dígito verificador para conta corrente do Itau.
# Retorna apenas o dígito verificador da conta ou nil caso seja impossível calcular.
def agencia_conta_corrente_dv
"#{agencia}#{conta_corrente}".modulo10
end
# Nosso número para exibir no boleto.
# @return [String]
# @example
# boleto.nosso_numero_boleto #=> "175/12345678-4"
def nosso_numero_boleto
"#{carteira}/#{numero_documento}-#{nosso_numero_dv}"
end
# Agência + conta corrente do cliente para exibir no boleto.
# @return [String]
# @example
# boleto.agencia_conta_boleto #=> "0811 / 53678-8"
def agencia_conta_boleto
"#{agencia} / #{conta_corrente}-#{agencia_conta_corrente_dv}"
end
# Segunda parte do código de barras.
#
# CARTEIRAS 198, 106, 107,122, 142, 143, 195 e 196<br/>
# 01 a 03 | 03 | 9(3) | Código do Banco na Câmara de Compensação = ‘341’<br/>
# 04 a 04 | 01 | 9(1) | Código da Moeda = '9'<br/>
# 05 a 05 | 01 | 9(1) | DAC do Código de Barras MOD 11-2a9<br/>
# 06 a 09 | 04 | 9(04) | Fator de Vencimento<br/>
# 10 a 19 | 10 | 9(08) | V(2) Valor<br/>
# 20 a 22 | 03 | 9(3) | Carteira<br/>
# 23 a 30 | 08 | 9(8) | Nosso Número<br/>
# 31 a 37 | 07 | 9(7) | Seu Número (Número do Documento)<br/>
# 38 a 42 | 05 | 9(5) | Código do Cliente (fornecido pelo Banco)<br/>
# 43 a 43 | 01 | 9(1) | DAC dos campos acima (posições 20 a 42) MOD 10<br/>
# 44 a 44 | 01 | 9(1) | Zero<br/>
#
# DEMAIS CARTEIRAS<br/>
# 01 a 03 | 03 | 9(03) | Código do Banco na Câmara de Compensação = '341'<br/>
# 04 a 04 | 01 | 9(01) | Código da Moeda = '9'<br/>
# 05 a 05 | 01 | 9(01) | DAC código de Barras MOD 11-2a9<br/>
# 06 a 09 | 04 | 9(04) | Fator de Vencimento<br/>
# 10 a 19 | 10 | 9(08)V(2) | Valor<br/>
# 20 a 22 | 03 | 9(03) | Carteira<br/>
# 23 a 30 | 08 | 9(08) | Nosso Número<br/>
# 31 a 31 | 01 | 9(01) | DAC [Agência /Conta/Carteira/Nosso Número] MOD 10<br/>
# 32 a 35 | 04 | 9(04) | N.º da Agência cedente<br/>
# 36 a 40 | 05 | 9(05) | N.º da Conta Corrente<br/>
# 41 a 41 | 01 | 9(01) | DAC [Agência/Conta Corrente] MOD 10<br/>
# 42 a 44 | 03 | 9(03) | Zeros<br/>
#
# @return [String] 25 caracteres numéricos.
def codigo_barras_segunda_parte
case carteira.to_i
when 198, 106, 107, 122, 142, 143, 195, 196
dv = "#{carteira}#{numero_documento}#{seu_numero}#{convenio}".modulo10
"#{carteira}#{numero_documento}#{seu_numero}#{convenio}#{dv}0"
else
"#{carteira}#{numero_documento}#{nosso_numero_dv}#{agencia}#{conta_corrente}#{agencia_conta_corrente_dv}000"
end
end
end
end
end
| 40.834586 | 118 | 0.607807 |
f75314a48d8f8e03b71d7b60939daaf53b1d186e | 342 | str1 = "Qoo"
str2 = "Qoo"
# compare two string
if str1 == str2
puts "str1 == str2"
else
puts "NOT str1 == str2"
end
# compare two string
if str1.eql?(str2)
puts "str1.eql?(str2)"
else
puts "NOT str1.eql?(str2)"
end
# compare two String object
if str1.equal?(str2)
puts "str1.equal?(str2)"
else
puts "NOT str1.equal?(str2)"
end | 14.869565 | 30 | 0.654971 |
012b4c8a7c0846d8e0fc9c17b70561f18f5ee942 | 149 | module Stupidedi
BlankSlate =
if RUBY_VERSION < "1.9"
require "blankslate"
::BlankSlate
else
::BasicObject
end
end
| 12.416667 | 27 | 0.597315 |
acee8ebc0bd7442781bd85db7e26457714e5218d | 1,031 | class SongsController < ApplicationController
def index
@songs = Song.all
end
def show
@song = Song.find(params[:id])
end
def new
@song = Song.new
end
def upload
CSV.foreach(params[:file].path, headers: true) do |song|
s = Song.create(title: song[0]) unless !song[0]
artist = Artist.find_or_create_by(name: song[1]) unless !song[1]
s.artist_id = artist
end
redirect_to songs_path
end
def create
@song = Song.new(song_params)
if @song.save
redirect_to @song
else
render :new
end
end
def edit
@song = Song.find(params[:id])
end
def update
@song = Song.find(params[:id])
@song.update(song_params)
if @song.save
redirect_to @song
else
render :edit
end
end
def destroy
@song = Song.find(params[:id])
@song.destroy
flash[:notice] = "Song deleted."
redirect_to songs_path
end
private
def song_params
params.require(:song).permit(:title, :artist_name)
end
end
| 15.861538 | 70 | 0.621726 |
08db902ad040a277079b9195c90b94dd76bc74d4 | 1,674 | # encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.centralnic.com/uy.com/status_available.expected
#
# and regenerate the tests with the following rake task
#
# $ rake genspec:parsers
#
require 'spec_helper'
require 'whois/record/parser/whois.centralnic.com.rb'
describe Whois::Record::Parser::WhoisCentralnicCom, "status_available.expected" do
before(:each) do
file = fixture("responses", "whois.centralnic.com/uy.com/status_available.txt")
part = Whois::Record::Part.new(:body => File.read(file))
@parser = klass.new(part)
end
context "#referral_whois" do
it do
lambda { @parser.referral_whois }.should raise_error(Whois::PropertyNotSupported)
end
end
context "#referral_url" do
it do
lambda { @parser.referral_url }.should raise_error(Whois::PropertyNotSupported)
end
end
context "#status" do
it do
@parser.status.should == :available
end
end
context "#available?" do
it do
@parser.available?.should == true
end
end
context "#registered?" do
it do
@parser.registered?.should == false
end
end
context "#created_on" do
it do
@parser.created_on.should == nil
end
end
context "#updated_on" do
it do
lambda { @parser.updated_on }.should raise_error(Whois::PropertyNotSupported)
end
end
context "#expires_on" do
it do
@parser.expires_on.should == nil
end
end
context "#nameservers" do
it do
@parser.nameservers.should be_a(Array)
@parser.nameservers.should == []
end
end
end
| 23.577465 | 87 | 0.678614 |
e25a61a2991eede22235b52d7baf1f02082b3825 | 1,705 | require 'rails_helper'
module Logical
describe UrlCreator do
describe "#create" do
let(:new_url) { "http://www.url.com" }
let(:owner_identifier) { Logical::Uuid.generate }
it "creates a new small URL" do
expect { Logical::UrlCreator.new(new_url, owner_identifier).create }.
to change { Physical::SmallUrl.count }.
from(0).to(1)
end
it "encrypts the original URL correctly" do
small_url = Logical::UrlCreator.new(new_url, owner_identifier).create
expect(Logical::UrlEncryptor.new(small_url.salt).
decrypt(small_url.encrypted_url)).
to eq(new_url)
end
it "uses a 32-byte salt" do
small_url = Logical::UrlCreator.new(new_url, owner_identifier).create
expect(small_url.salt.length).to eq(64)
end
it "creates a new owner when a new owner param is given" do
expect { Logical::UrlCreator.new(new_url, owner_identifier).create }.
to change { Physical::Owner.count }.
from(0).to(1)
expect(Physical::Owner.find_by(external_identifier: owner_identifier)).to_not be_nil
end
it "creates a small URL with a nil owner when no owner specified" do
Logical::UrlCreator.new(new_url, nil).create
expect(Physical::SmallUrl.last.owner).
to be_nil
end
context "owner already exists" do
let!(:owner) { FactoryGirl.create(:owner) }
it "creates a small URL with the existing owner ID" do
small_url = Logical::UrlCreator.new(new_url, owner.external_identifier).create
expect(small_url.owner_id).to eq(owner.id)
end
end
end
end
end
| 33.431373 | 92 | 0.639296 |
081196c1ad1bd487bb96ddf5c7921b08910aa994 | 1,167 | =begin
#Tatum API
## Authentication <!-- ReDoc-Inject: <security-definitions> -->
OpenAPI spec version: 3.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.31
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Tatum::ScryptaTxScriptSig
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'ScryptaTxScriptSig' do
before do
# run before each test
@instance = Tatum::ScryptaTxScriptSig.new
end
after do
# run after each test
end
describe 'test an instance of ScryptaTxScriptSig' do
it 'should create an instance of ScryptaTxScriptSig' do
expect(@instance).to be_instance_of(Tatum::ScryptaTxScriptSig)
end
end
describe 'test attribute "asm"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "hex"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 24.829787 | 102 | 0.727506 |
3991b54c29aea80ac0cea5c9cfc8a8afee3cf17b | 5,194 | module Match
class Runner
attr_accessor :changes_to_commit
def run(params)
FastlaneCore::PrintTable.print_values(config: params,
hide_keys: [:workspace],
title: "Summary for match #{Match::VERSION}")
params[:workspace] = GitHelper.clone(params[:git_url], params[:shallow_clone], skip_docs: params[:skip_docs], branch: params[:git_branch])
spaceship = SpaceshipEnsure.new(params[:username]) unless params[:readonly]
# Verify the App ID (as we don't want 'match' to fail at a later point)
spaceship.bundle_identifier_exists(params) if spaceship
# Certificate
cert_id = certificate(params: params)
spaceship.certificate_exists(params, cert_id) if spaceship
# Provisioning Profile
uuid = profile(params: params,
certificate_id: cert_id)
spaceship.profile_exists(params, uuid) if spaceship
# Done
if self.changes_to_commit and !params[:readonly]
message = GitHelper.generate_commit_message(params)
GitHelper.commit_changes(params[:workspace], message, params[:git_url], params[:git_branch])
end
TablePrinter.print_summary(params, uuid)
UI.success "All required keys, certificates and provisioning profiles are installed 🙌".green
rescue Spaceship::Client::UnexpectedResponse, Spaceship::Client::InvalidUserCredentialsError, Spaceship::Client::NoUserCredentialsError => ex
UI.error("An error occured while verifying your certificates and profiles with the Apple Developer Portal.")
UI.error("If you already have your certificates stored in git, you can run `match` in readonly mode")
UI.error("to just install the certificates and profiles without accessing the Dev Portal.")
UI.error("To do so, just pass `readonly: true` to your match call.")
raise ex
ensure
GitHelper.clear_changes
end
def certificate(params: nil)
cert_type = :distribution
cert_type = :development if params[:type] == "development"
cert_type = :enterprise if Match.enterprise? && params[:type] == "enterprise"
certs = Dir[File.join(params[:workspace], "certs", cert_type.to_s, "*.cer")]
keys = Dir[File.join(params[:workspace], "certs", cert_type.to_s, "*.p12")]
if certs.count == 0 or keys.count == 0
UI.important "Couldn't find a valid code signing identity in the git repo for #{cert_type}... creating one for you now"
UI.crash!("No code signing identity found and can not create a new one because you enabled `readonly`") if params[:readonly]
cert_path = Generator.generate_certificate(params, cert_type)
self.changes_to_commit = true
else
cert_path = certs.last
UI.message "Installing certificate..."
if FastlaneCore::CertChecker.installed?(cert_path)
UI.verbose "Certificate '#{File.basename(cert_path)}' is already installed on this machine"
else
Utils.import(cert_path, params[:keychain_name])
end
# Import the private key
# there seems to be no good way to check if it's already installed - so just install it
Utils.import(keys.last, params[:keychain_name])
end
return File.basename(cert_path).gsub(".cer", "") # Certificate ID
end
def profile(params: nil, certificate_id: nil)
prov_type = params[:type].to_sym
profile_name = [Match::Generator.profile_type_name(prov_type), params[:app_identifier]].join("_").gsub("*", '\*') # this is important, as it shouldn't be a wildcard
profiles = Dir[File.join(params[:workspace], "profiles", prov_type.to_s, "#{profile_name}.mobileprovision")]
# Install the provisioning profiles
profile = profiles.last
if params[:force_for_new_devices] && !params[:readonly]
params[:force] = device_count_different?(profile: profile) unless params[:force]
end
if profile.nil? or params[:force]
UI.user_error!("No matching provisioning profiles found and can not create a new one because you enabled `readonly`") if params[:readonly]
profile = Generator.generate_provisioning_profile(params: params,
prov_type: prov_type,
certificate_id: certificate_id)
self.changes_to_commit = true
end
FastlaneCore::ProvisioningProfile.install(profile)
parsed = FastlaneCore::ProvisioningProfile.parse(profile)
uuid = parsed["UUID"]
Utils.fill_environment(params, uuid)
return uuid
end
def device_count_different?(profile: nil)
if profile
parsed = FastlaneCore::ProvisioningProfile.parse(profile)
uuid = parsed["UUID"]
portal_profile = Spaceship.provisioning_profile.all.detect { |i| i.uuid == uuid }
if portal_profile
profile_device_count = portal_profile.devices.count
portal_device_count = Spaceship.device.all.count
return portal_device_count != profile_device_count
end
end
return false
end
end
end
| 42.92562 | 170 | 0.665961 |
38975c7fdd5159054f67209548c5bb8d860c1f4a | 867 | require_relative "lib/h3/version"
Gem::Specification.new do |spec|
spec.name = "h3"
spec.version = H3::VERSION
spec.licenses = ["MIT"]
spec.summary = "C Bindings for Uber's H3 library"
spec.homepage = "https://github.com/StuartApp/h3_ruby"
spec.authors = ["Lachlan Laycock", "Sean Handley"]
spec.email = "[email protected]"
spec.required_ruby_version = ">= 2.5"
spec.files = `git ls-files --recurse-submodules`.split("\n")
spec.add_runtime_dependency "ffi", "~> 1.9"
spec.add_runtime_dependency "rgeo-geojson", "~> 2.1"
spec.add_runtime_dependency "zeitwerk", "~> 2.1"
spec.add_development_dependency "coveralls", "~> 0.8"
spec.add_development_dependency "rake", "~> 12.3"
spec.add_development_dependency "rspec", "~> 3.8"
spec.add_development_dependency "yard", "~> 0.9"
spec.extensions << "ext/h3/extconf.rb"
end
| 33.346154 | 62 | 0.687428 |
33924ee2f4e4acf01a04dd4e3079856489ab4532 | 10,349 | #%Header {
##############################################################################
#
# File adanaxis-data/spaces/level25/space.rb
#
# Copyright: Andy Southgate 2002-2007, 2020
#
# 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.
#
##############################################################################
#%Header } ZivN8a2GxPE7afcjjEO4SA
# $Id: space.rb,v 1.4 2007/06/27 13:18:58 southa Exp $
# $Log: space.rb,v $
# Revision 1.4 2007/06/27 13:18:58 southa
# Debian packaging
#
# Revision 1.3 2007/06/27 12:58:17 southa
# Debian packaging
#
# Revision 1.2 2007/06/12 11:09:36 southa
# Level 28
#
# Revision 1.1 2007/06/08 13:17:14 southa
# Level 25
#
require 'Mushware.rb'
require 'Adanaxis.rb'
class Adanaxis_level25 < AdanaxisSpace
def initialize(inParams = {})
super
mTimeoutSpawnAdd(:mSpawn0, 40000)
mTimeoutSpawnAdd(:mSpawn1, 60000) if AdanaxisRuby.cGameDifficulty > 1
mTimeoutSpawnAdd(:mSpawn2, 100000)
mIsBattleSet(true)
end
def mLoad(game)
mLoadStandard(game)
mMusicAdd('game1', 'mushware-except-for-this.ogg')
MushGame.cSoundDefine("voice-intro", "mush://waves/voice-L25.ogg|null:")
end
def mPrecacheListBuild
super
mPrecacheListAdd(mPieceLibrary.mAttendantTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mCisternTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mFreshenerTex('red'))
mPrecacheListAdd(mPieceLibrary.mHarpikTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mRailTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mLimescaleTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mVendorTex('red', 'blue'))
mPrecacheListAdd(mPieceLibrary.mWarehouseTex('red'))
end
def mInitialPiecesCreate
super
MushTools.cRandomSeedSet(25)
diff = AdanaxisRuby.cGameDifficulty
angVel = MushTools.cRotationInXYPlane(Math::PI / 1200);
MushTools.cRotationInZWPlane(Math::PI / 1314).mRotate(angVel);
MushTools.cRotationInYZPlane(Math::PI / 1575).mRotate(angVel);
vel = MushVector.new(-0.05*(1+diff),0,0,0)
angPos = MushTools.cRotationInXZPlane(Math::PI/2)
2.times do |param|
mPieceLibrary.mFreshenerCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(200, 100, -400+800*param, -800),
:angular_velocity => angVel
)
)
end
(10+diff).times do |param|
mPieceLibrary.mRailCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(100, 0, 0, -700) +
MushTools.cRandomUnitVector * (20 + rand(200)),
:angular_position => MushTools.cRandomOrientation
),
:ai_state => :dormant,
:ai_state_msec => 10000+200*param
)
end
8.times do |param|
mPieceLibrary.mRailCreate(
:colour => 'blue',
:post => MushPost.new(
:position => MushVector.new(50, 0, 0, -200) +
MushTools.cRandomUnitVector * (20 + rand(100)),
:angular_position => MushTools.cRandomOrientation
),
:ai_state => :dormant,
:ai_state_msec => 100+200*param
)
end
12.times do |param|
['blue', 'red'].each do |colour|
mPieceLibrary.mAttendantCreate(
:colour => colour,
:post => MushPost.new(
:position => MushVector.new(200, 0, 0, -500+((colour == 'red')?-200:200)) +
MushTools.cRandomUnitVector * (20 + rand(100)),
:angular_position => MushTools.cRandomOrientation
)
)
end
end
4.times do |param|
['blue', 'red'].each do |colour|
mPieceLibrary.mHarpikCreate(
:colour => colour,
:post => MushPost.new(
:position => MushVector.new(200, 0, 0, -500+((colour == 'red')?-200:200)) +
MushTools.cRandomUnitVector * (120 + rand(100)),
:angular_position => MushTools.cRandomOrientation
)
)
end
end
[-1,1].each do |param|
mPieceLibrary.mCisternCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(100*param, -20, 0, -250+100*param),
:velocity => vel,
:angular_position => angPos
),
:patrol_points => [
MushVector.new(-200, 50*param, 0, -250),
MushVector.new(200, 50*param, 0, -250)
],
:ammo_count => 2 + 2 * diff,
:ai_state => :patrol,
:ai_state_msec => 10000+250*param,
:weapon => :harpik_spawner
)
end
[-1,1].each do |param|
mPieceLibrary.mWarehouseCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(50, 100*param, 200, -250+50*param),
:angular_position => angPos
),
:patrol_points => [
MushVector.new(-300, 100*param, -400, -250+50*param),
MushVector.new(300, 100*param, -400, -250+50*param)
],
:ai_state => :patrol,
:ai_state_msec => 8000+250*param,
:remnant => :player_rail
)
end
mPieceLibrary.mCisternCreate(
:colour => 'blue',
:post => MushPost.new(
:position => MushVector.new(100, -20, 0, -1400),
:velocity => vel,
:angular_position => angPos
),
:patrol_points => [
MushVector.new(-200, 200, 0, -1000),
MushVector.new(200, 200, 0, -1000)
],
:ammo_count => 10,
:ai_state => :patrol,
:ai_state_msec => 10000,
:weapon => :harpik_spawner
)
3.times do |param|
mPieceLibrary.mVendorCreate(
:colour => 'blue',
:post => MushPost.new(
:position => MushVector.new(-200, -20, -200, -400-100*param),
:velocity => vel,
:angular_position => angPos
)
)
end
3.times do |param|
mPieceLibrary.mLimescaleCreate(
:colour => 'blue',
:post => MushPost.new(
:position => MushVector.new(-400, 0, 0, -1000) +
MushTools.cRandomUnitVector * (100 + rand(100)),
:angular_position => MushTools.cRandomOrientation
)
)
end
if diff < 1
$currentLogic.mRemnant.mCreate(
:item_type => :player_heavy_missile,
:post => MushPost.new(
:position => MushVector.new(5, 1, 0, -20)
)
)
end
2.times do |param|
$currentLogic.mRemnant.mCreate(
:item_type => :player_heavy_cannon,
:post => MushPost.new(
:position => MushVector.new(7, 2, 0, -30-10*param)
)
)
end
1.times do |param|
$currentLogic.mRemnant.mCreate(
:item_type => :player_light_missile,
:post => MushPost.new(
:position => MushVector.new(4, 6, 0, -60-10*param)
)
)
end
(3-diff).times do |param|
$currentLogic.mRemnant.mCreate(
:item_type => :player_rail,
:post => MushPost.new(
:position => MushVector.new(3, 0, 12, -100-10*param)
)
)
end
3.times do |param|
$currentLogic.mRemnant.mCreate(
:item_type => :player_flak,
:post => MushPost.new(
:position => MushVector.new(3, 0, 12, -140-10*param)
)
)
end
mStandardCosmos(25)
end
def mSpawn0
diff = AdanaxisRuby.cGameDifficulty
12.times do |param|
['blue', 'red',].each do |colour|
mPieceLibrary.mHarpikCreate(
:colour => colour,
:post => MushPost.new(
:position => MushVector.new(0, 0, 0, ((colour == 'red')?-400:-900)) +
MushTools.cRandomUnitVector * (100 + rand(200)),
:angular_position => MushTools.cRandomOrientation
),
:spawned => true
)
end
end
MushGame.cVoicePlay('voice-E3-1') # 'Hostile import detected'
return true
end
def mSpawn1
diff = AdanaxisRuby.cGameDifficulty
2.times do |param|
['blue', 'red', 'red'].each do |colour|
mPieceLibrary.mLimescaleCreate(
:colour => colour,
:post => MushPost.new(
:position => MushVector.new(-400, 0, 0, -700+((colour == 'red')?-400:400)) +
MushTools.cRandomUnitVector * (100 + rand(100)),
:angular_position => MushTools.cRandomOrientation
),
:spawned => true
)
end
end
MushGame.cVoicePlay('voice-E3-3') # 'Hostile import detected'
return true
end
def mSpawn2
diff = AdanaxisRuby.cGameDifficulty
mPieceLibrary.mCisternCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(-300,0,0,-200),
:velocity => MushVector.new(0, 0, 0, 0)
),
:spawned => true,
:patrol_points => [
MushVector.new(500,0,0,-200),
MushVector.new(-500,0,0,-200)
],
:ammo_count => 6+4*diff,
:ai_state => :dormant,
:ai_state_msec => 2000,
:weapon => :vendor_spawner
)
(4+2*diff).times do |param|
mPieceLibrary.mVendorCreate(
:colour => 'red',
:post => MushPost.new(
:position => MushVector.new(-100,0,0,-100-50*param)
),
:spawned => true
)
end
MushGame.cVoicePlay('voice-E3-2') # 'Hostile import detected'
return true
end
end
| 29.48433 | 88 | 0.580926 |
4a510b766d2163a2ef8870c98ff489a80fdcbaa6 | 3,049 | require 'httparty'
require 'active_support/all'
require 'nokogiri'
require 'nokogumbo'
module CryptoNews
class BotNewsScraper
def initialize
@url = Rails.application.credentials.telegram[:news_api]
end
# scrape_articles takes in the time interval to scrape and returns
# a list of newly posted articles from the url provided.
def scrape_articles(interval, last_article_sent)
scraped = scrape_url(@url)
last_article_sent = scraped[0]['date'] if last_article_sent.nil?
new_articles, last_article_sent = retrieve_new_articles(scraped, last_article_sent)
if new_articles.empty?
puts "There are no new articles in the last #{interval} seconds."
else
new_articles = parse_articles(new_articles) # parse HTML. Remove HTML tags.
puts "The new articles in the past #{interval} seconds are: #{new_articles}."
end
return new_articles, last_article_sent
end
private
def scrape_url(url)
response = HTTParty.get(url)
scraped_articles = response.parsed_response['articles']
return scraped_articles
end
def parse_articles(news)
news.each do |article|
noko_title = Nokogiri.HTML5(article['title'])
noko_description = Nokogiri.HTML5(article['description'])
article['title'] = noko_title.text
article['description'] = noko_description.text
end
return news
end
# retrieve_new_articles takes in articles from the url and returns newly
# posted articles.
# Input: parsed_articles => Articles scraped from the url.
# : last_article_sent => Time of the last article sent from the
# previous interval.
# barricade_article: Time of the last article sent from the previous interval
# Output: last_article_sent => Time of the last article sent in current interval.
# : new_articles => List of newly posted articles since the last interval.
def retrieve_new_articles(parsed_articles, last_article_sent)
i = 0
new_articles = [] # Empty the last interval's new articles list
barricade_article = last_article_sent # Sets the last article from the previous interval to be the current interval's "barricade".
Time.zone = 'Singapore'
current_time = Time.zone.now.strftime("%FT%T.%L%z") # The current time that the scraping occurs.
while current_time > barricade_article # Compare time of current article appended with the previous scrape interval's article time.
break if parsed_articles[i]['date'] == barricade_article
new_articles << parsed_articles[i]
# puts "Appended article with title #{parsed_articles[i]['title']} to the new articles list"
current_time = parsed_articles[i]['date'] # With each iteration, current time changes to the "date" index of the current article appended to "new articles"
i += 1 # Move down to the next article
end
last_article_sent = parsed_articles[0]['date']
return new_articles, last_article_sent
end
end
end
| 42.943662 | 163 | 0.706461 |
ab1092782eeee4730d4575e887b240b0bf3bcbc8 | 363 | RSpec::Matchers.define :be_uniq do
match do |actual|
values_match? actual.uniq, actual
end
failure_message do |actual|
diff = actual.to_a.dup
actual.uniq.each { |value| diff.delete_at diff.index(value) }
diff = diff.uniq
"expected that #{actual.inspect} to be uniq, but found the following repeated elements: #{diff.inspect}"
end
end
| 27.923077 | 108 | 0.705234 |
ac8ef4e1ff4696370f653ab3d514be2d356e93e9 | 1,114 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Cabbage
class Application < Rails::Application
# 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.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.259259 | 99 | 0.733393 |
0158001ca416a81a01e52c7fde0b57b9a2353f32 | 1,238 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
Gem::Specification.new do |spec|
spec.name = 'aws-sdk-swf'
spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip
spec.summary = 'AWS SDK for Ruby - Amazon SWF'
spec.description = 'Official AWS Ruby gem for Amazon Simple Workflow Service (Amazon SWF). This gem is part of the AWS SDK for Ruby.'
spec.author = 'Amazon Web Services'
spec.homepage = 'https://github.com/aws/aws-sdk-ruby'
spec.license = 'Apache-2.0'
spec.email = ['[email protected]']
spec.require_paths = ['lib']
spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb']
spec.metadata = {
'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-swf',
'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-swf/CHANGELOG.md'
}
spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0')
spec.add_dependency('aws-sigv4', '~> 1.1')
end
| 38.6875 | 137 | 0.663166 |
28779a9671c43cfdc46f106f72f5c540b0844a2d | 39 | module Wso2soap
VERSION = "0.0.1"
end | 13 | 19 | 0.692308 |
acf9fe4df2aecf2842bf59c5e8d23b40efa9283d | 343 | cask "eaglefiler" do
version "1.9.2"
sha256 "79b864922d251186944a6fa147193b1ab4cbafc740bd204d9e826735380318c6"
url "https://c-command.com/downloads/EagleFiler-#{version}.dmg"
appcast "https://c-command.com/eaglefiler/help/version-history"
name "EagleFiler"
homepage "https://c-command.com/eaglefiler/"
app "EagleFiler.app"
end
| 28.583333 | 75 | 0.763848 |
e28d9a57f2997608a1dcbf90d5e922ad2b313c67 | 612 | # frozen_string_literal: true
require "fbase_auth"
require "webmock/rspec"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.before :all, :mock_api_host do
@url = "#{FbaseAuth.config.host}#{described_class::PATH}?key=#{FbaseAuth.config.api_key}"
stub_request(:post, @url).to_return body: { 'message': "ok" }.to_json
end
end
| 27.818182 | 93 | 0.732026 |
391e1756330afb3e77a670755775f7a7a62ffeca | 2,298 | # frozen_string_literal: true
module Cask
class Cmd
class List < AbstractCommand
option "-1", :one, false
option "--versions", :versions, false
option "--full-name", :full_name, false
option "--json", :json, false
def self.usage
<<~EOS
`cask list`, `cask ls` [<options>] [<casks>]
-1 - Force output to be one entry per line.
This is the default when output is not to a terminal.
--versions - Show the version number for installed formulae, or only the specified
casks if <casks> are provided.
--full-name - Print casks with fully-qualified names.
--json - Print a JSON representation of <cask>. See the docs for examples of using the JSON
output: <https://docs.brew.sh/Querying-Brew>
List all installed casks.
If <casks> are provided, limit information to just those casks.
EOS
end
def self.help
"lists installed Casks or the casks provided in the arguments"
end
def run
output = args.any? ? provided_list : Caskroom.casks
if json?
puts JSON.generate(output.map(&:to_h))
elsif one?
puts output.map(&:to_s)
elsif full_name?
puts output.map(&:full_name).sort(&tap_and_name_comparison)
elsif versions?
puts output.map(&self.class.method(:format_versioned))
elsif !output.empty? && args.any?
puts output.map(&self.class.method(:list_artifacts))
elsif !output.empty?
puts Formatter.columns(output.map(&:to_s))
end
end
def provided_list
casks.each do |cask|
raise CaskNotInstalledError, cask unless cask.installed?
end
casks
end
def self.list_artifacts(cask)
cask.artifacts.group_by(&:class).each do |klass, artifacts|
next unless klass.respond_to?(:english_description)
return "==> #{klass.english_description}", artifacts.map(&:summarize_installed)
end
end
def self.format_versioned(cask)
cask.to_s.concat(cask.versions.map(&:to_s).join(" ").prepend(" "))
end
end
end
end
| 31.916667 | 106 | 0.585292 |
ac310d19045c1ce58d42886239c83eb6563f247e | 2,548 | require 'spec_helper'
require 'resource_helper'
describe DataPackage::Resource do
it "should initialize and serialize" do
resource = DataPackage::Resource.new(base_path, standard_resource)
resource.format.should == 'csv'
resource.name.should == 'standard'
resource.path.should == 'standard.csv'
resource.schema.fields.length.should == 10
resource.schema.primary_key.should == ['id']
modified_resource = standard_resource.merge(
'format' => 'csv',
'dialect' => DataPackage::Dialect.new.to_hash,
'schema' => standard_resource['schema'].merge(
'primaryKey' => 'id'
)
)
resource.to_hash.should == modified_resource
end
it "should initialize and deserialize a remote resource" do
resource = DataPackage::Resource.new(base_path, remote_resource)
resource.format.should == 'csv'
resource.name.should == 'country-codes'
resource.path.should == 'data/country-codes.csv'
resource.url.should == 'https://datahub.com/datasets/country-codes.csv'
resource.schema.fields.length.should == 3
resource.schema.primary_key.should == ['id']
modified_resource = remote_resource.merge(
'format' => 'csv',
'schema' => remote_resource['schema'].merge(
'primaryKey' => 'id'
)
)
resource.to_hash.should == modified_resource.merge('format' => 'csv')
end
describe "#each" do
it "should enumerate over inline data" do
resource = DataPackage::Resource.new(base_path, inline_resource)
row_count = 0
resource.each do |row|
row_count += 1
end
row_count.should == 3
end
it "should enumerate over local file data" do
resource = DataPackage::Resource.new(base_path, standard_resource)
row_count = 0
resource.each { |row| row_count += 1 }
row_count.should == 10
end
it "should not enumerate URL data" do
resource = DataPackage::Resource.new(base_path, http_resource)
expect{ resource.each_row{|row| nil} }.to raise_error
end
it "should raise if the data format is unexpected" do
resource = DataPackage::Resource.new(base_path, standard_resource.merge('format' => 'unknown'))
expect{ resource.each_row{|row| nil} }.to raise_error
end
it "should raise if data, path or url aren't present" do
invalid = standard_resource.dup
invalid.delete('path')
resource = DataPackage::Resource.new(base_path, invalid)
expect{ resource.each_row{|row| nil} }.to raise_error
end
end
end | 30.333333 | 101 | 0.669152 |
6a929093332a0c223e80c83bed5606748cd462c3 | 57 | name 'influxdb-test'
version '0.0.1'
depends 'influxdb'
| 11.4 | 20 | 0.719298 |
38b779dae4f6472fdeaa22732843dd9519bbb900 | 1,345 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sengiri_yaml/version'
Gem::Specification.new do |spec|
spec.name = "sengiri_yaml"
spec.version = SengiriYaml::VERSION
spec.authors = ["sue445"]
spec.email = ["[email protected]"]
spec.summary = %q{divide yaml file}
spec.description = %q{divide yaml file}
spec.homepage = "https://github.com/sue445/sengiri_yaml"
spec.license = "MIT"
spec.required_ruby_version = ">= 2.6"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = spec.homepage
spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/master/CHANGELOG.md"
spec.metadata["rubygems_mfa_required"] = "true"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler"
spec.add_development_dependency "coveralls"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rspec-power_assert"
spec.add_development_dependency "rspec-temp_dir"
spec.add_development_dependency "yard"
end
| 37.361111 | 78 | 0.701859 |
e2a57c010b301aa18f27c7d260f16d3f4b1c5c27 | 1,129 | module HtmlMockup::Release::Finalizers
class Zip < Base
attr_reader :release
# @option options :prefix Prefix to put before the version (default = "html")
# @option options :zip The zip command
def call(release, options = {})
if options
options = @options.dup.update(options)
else
options = @options
end
options = {
:zip => "zip",
:prefix => "html"
}.update(options)
name = [options[:prefix], release.scm.version].join("-") + ".zip"
release.log(self, "Finalizing release to #{release.target_path + name}")
if File.exist?(release.target_path + name)
release.log(self, "Removing existing target #{release.target_path + name}")
FileUtils.rm_rf(release.target_path + name)
end
begin
`#{options[:zip]} -v`
rescue Errno::ENOENT
raise RuntimeError, "Could not find zip in #{options[:zip].inspect}"
end
::Dir.chdir(release.build_path) do
`#{options[:zip]} -r -9 "#{release.target_path + name}" ./*`
end
end
end
end | 26.880952 | 83 | 0.577502 |
b9bd5c7356f9eedebc78f0291062a88340b50e73 | 5,141 | #--
# Copyright (c) 2007-2009, John Mettraux, [email protected]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
require 'monitor'
require 'fileutils'
require 'openwfe/service'
require 'openwfe/omixins'
require 'openwfe/rudefinitions'
require 'openwfe/flowexpressionid'
require 'openwfe/expool/journal_replay'
module OpenWFE
#
# Keeping a replayable track of the events in an OpenWFEru engine
#
class Journal < Service
include MonitorMixin
include OwfeServiceLocator
include JournalReplay
include FeiMixin
attr_reader :workdir, :donedir
FREQ = '1m'
#
# once per minute, makes sure the buckets are flushed
def initialize (service_name, application_context)
super # necessary since we're extending MonitorMixin
@buckets = {}
@workdir = get_work_directory + '/journal'
@donedir = @workdir + '/done'
FileUtils.makedirs(@donedir) unless File.exist?(@donedir)
get_expression_pool.add_observer(:all) do |event, *args|
#ldebug { ":#{event} for #{args[0].class.name}" }
queue_event(event, *args)
end
@thread_id = get_scheduler.schedule_every(FREQ) do
flush_buckets()
end
end
#
# Will flush the journal of every open instance.
#
def stop
get_scheduler.unschedule(@thread_id) if @thread_id
flush_buckets()
end
protected
#
# Queues the events before a flush.
#
# If the event is a :terminate, the individual bucket will get
# flushed.
#
def queue_event (event, *args)
#ldebug { "queue_event() :#{event}" }
return if event == :stop
return if event == :launch
return if event == :reschedule
wfid = extract_fei(args[0]).parent_wfid
#
# maybe args[0] could be a FlowExpression instead
# of a FlowExpressionId instance
#puts "___#{event}__wfid : #{wfid}"
e = serialize_event(event, *args)
bucket = nil
synchronize do
bucket = get_bucket(wfid)
bucket << e
#ldebug { "queue_event() bucket : #{bucket.object_id}" }
if event == :terminate
bucket.flush
@buckets.delete(wfid)
end
end
#
# minimizing the sync block
# TODO : spin that off this thread, to the
# flush thread...
#
if event == :terminate
if @application_context[:keep_journals] == true
#
# 'move' journal to the done/ subdir of journal/
#
FileUtils.cp(
bucket.path,
@donedir + "/" + File.basename(bucket.path))
end
FileUtils.rm bucket.path
end
end
#
# Makes sure that all the buckets are persisted to disk
#
def flush_buckets
count = 0
synchronize do
@buckets.each do |k, v|
v.flush
count += 1
end
@buckets.clear
end
linfo { "flush_buckets() flushed #{count} buckets" } \
if count > 0
end
def get_bucket (wfid)
@buckets[wfid] ||= Bucket.new(get_path(wfid))
end
def serialize_event (event, *args)
args.insert(0, event)
args.insert(1, Time.now)
args.to_yaml
end
def get_path (wfid)
"#{@workdir}/#{wfid.to_s}.journal"
end
#
# for each process instance, there is one bucket holding the
# events waiting to get written in the journal
#
class Bucket
attr_reader :path, :events
def initialize (path)
super()
@path = path
@events = []
end
def << (event)
@events << event
end
def size
@events.size
end
alias :length :size
def flush
File.open(@path, 'a+') do |f|
@events.each do |e|
f.puts e
end
end
@events.clear
end
end
end
end
| 24.364929 | 79 | 0.596771 |
ffcd52346656dbf57a9fb1e842e45a9fa1ab8a62 | 1,886 | #encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/activerecord'
set :database, "sqlite3:barbershop.db"
class Client < ActiveRecord::Base
validates :name, presence: true, length: { minimum: 3 }
validates :phone, presence: true, length: { in: 6..12 }
validates :barber, presence: true
validates :datestamp, presence: true
validates :color, presence: true
end
class Barber < ActiveRecord::Base
end
class Contact < ActiveRecord::Base
validates :email, presence: true, length: { minimum: 4 }
validates :contact, presence: true, length: { in: 2..5000 }
end
before do
@barbers = Barber.all
#@clients = Client.all
#@contacts = Contact.all
end
get '/' do
erb :index
end
get '/visit' do
@booking = Client.new
erb :visit
end
post '/visit' do
@booking = Client.new params[:client]
# @client_name = params[:client_name]
# @client_phone = params[:client_phone]
# ...
# Client.create :name => @client_name, :phone => @client_phone, :datestamp => @datetime, :barber => @barber, :color => @color
# OR
# c = Client.new
# c.name = @client_name
# ...
# c.save
if @booking.save
erb "Спасибо! #{@booking[:name].capitalize}, мы будем ждать Вас #{@booking[:datestamp]}"
else
@error = @booking.errors.full_messages.first
erb :visit
end
end
get '/contacts' do
@contact = { :email => '', :contact => '' }
erb :contacts
end
post '/contacts' do
@contact = Contact.new params[:client]
if @contact.save
erb "Спасибо! Мы напишем Вам ответ на адрес #{@contact[:email]}"
else
@error = @contact.errors.full_messages.first
erb :contacts
end
end
get '/about' do
erb :about
end
get '/barber/:id' do
@barber = Barber.find params[:id]
erb :barber
end
get '/bookings' do
@clients = Client.order 'created_at DESC'
erb :bookings
end
get '/client/:id' do
@client = Client.find params[:id]
erb :client
end | 19.645833 | 126 | 0.683457 |
bb652f2884e21b9b9728413d0c4f2a5b4f3ccf8a | 394 | class User < ApplicationRecord
has_secure_password
has_many :movie_logs
has_many :movies, through: :movie_logs
validates :name, presence: true
validates :email, presence: true, uniqueness: true
def self.from_omniauth(auth)
self.where(email: auth["info"]["email"]).first_or_create do |u|
u.name = auth["info"]["name"]
u.password = SecureRandom.hex
end
end
end
| 26.266667 | 67 | 0.705584 |
e975ee5b52fa03368900d951aae0d93d88d5c749 | 4,677 | require_relative '../../../spec_helper_min'
require_relative '../../../support/helpers'
describe Carto::Superadmin::UserMigrationImportsController do
include HelperMethods
let(:superadmin_headers) do
credentials = Cartodb.config[:superadmin]
{
'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(
credentials['username'],
credentials['password']),
'HTTP_ACCEPT' => "application/json"
}
end
let(:invalid_headers) do
{
'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials('not', 'trusworthy'),
'HTTP_ACCEPT' => "application/json"
}
end
describe '#create' do
before(:all) do
@user = FactoryGirl.create(:carto_user)
@organization = FactoryGirl.create(:organization)
end
after(:all) do
@user.destroy
@organization.destroy
end
let(:import_for_user) do
{
exported_file: 'https://carto.com/something/else',
database_host: '127.0.0.1',
org_import: false,
json_file: 'id/user_id.json',
import_metadata: false
}
end
let(:import_for_organization) do
{
exported_file: '/path/to/nowhere',
database_host: '127.0.0.1',
org_import: true,
json_file: 'my_pretty_json',
import_metadata: false
}
end
it 'returns 401 if not authorized' do
Resque.expects(:enqueue).with(Resque::UserMigrationJobs::Import, anything).never
post_json(superadmin_user_migration_imports_path, import_for_user, invalid_headers) do |response|
response.status.should eq 401
end
end
it 'creates an import for user' do
Resque.expects(:enqueue).with(Resque::UserMigrationJobs::Import, anything).once
post_json(superadmin_user_migration_imports_path, import_for_user, superadmin_headers) do |response|
response.status.should eq 201
response.body[:id].should be
response.body[:state].should eq 'pending'
response.body[:imported_file].should be_nil
response.body[:json_file].should be_nil
response.body[:log].should be_nil
import = Carto::UserMigrationImport.find(response.body[:id])
import.state.should eq 'pending'
end
end
it 'creates an import for organization' do
Resque.expects(:enqueue).with(Resque::UserMigrationJobs::Import, anything).once
post_json(superadmin_user_migration_imports_path, import_for_organization, superadmin_headers) do |response|
response.status.should eq 201
response.body[:id].should be
response.body[:state].should eq 'pending'
response.body[:imported_file].should be_nil
response.body[:json_file].should be_nil
response.body[:log].should be_nil
import = Carto::UserMigrationImport.find(response.body[:id])
import.state.should eq 'pending'
end
end
it 'returns an error if not passing parameters' do
Resque.expects(:enqueue).with(Resque::UserMigrationJobs::Import, anything).never
post_json(superadmin_user_migration_imports_path, {}, superadmin_headers) do |response|
response.status.should eq 422
response.body[:errors].should be
end
end
end
describe '#show' do
before(:all) do
@user = FactoryGirl.create(:carto_user)
@import = Carto::UserMigrationImport.create(
exported_file: 'some_url',
database_host: 'some_ip',
org_import: false,
json_file: 'some_path'
)
end
after(:all) do
@import.destroy
@user.destroy
end
it 'returns 401 if not authorized' do
get_json(superadmin_user_migration_import_path(id: @import.id), {}, invalid_headers) do |response|
response.status.should eq 401
end
end
it 'returns the import if authorized and task is pending' do
get_json(superadmin_user_migration_import_path(id: @import.id), {}, superadmin_headers) do |response|
response.status.should eq 200
response.body[:id].should eq @import.id
response.body[:state].should eq @import.state
end
end
it 'includes the log when task is complete' do
@import.update_attributes(state: 'complete')
@import.log.update_attributes(entries: 'Lorem ipsum')
get_json(superadmin_user_migration_import_path(id: @import.id), {}, superadmin_headers) do |response|
response.status.should eq 200
response.body[:id].should eq @import.id
response.body[:state].should eq @import.state
response.body[:log].should eq @import.log.entries
end
end
end
end
| 32.706294 | 114 | 0.672653 |
613280bcc28c68fa4dca1125744f1b3419fb059b | 3,445 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Selector::RegexpDisassembler do
it 'handles strings' do
verify_strings(
/abcdef/ => %w[abcdef],
/abc def/ => ['abc def']
)
end
it 'handles escaped characters' do
verify_strings(
/abc\\def/ => %w[abc\def],
/abc\.def/ => %w[abc.def],
/\nabc/ => ["\nabc"],
%r{abc/} => %w[abc/],
/ab\++cd/ => %w[ab+ cd]
)
end
it 'handles wildcards' do
verify_strings(
/abc.*def/ => %w[abc def],
/.*def/ => %w[def],
/abc./ => %w[abc],
/abc.*/ => %w[abc],
/abc.def/ => %w[abc def],
/abc.def.ghi/ => %w[abc def ghi]
)
end
it 'handles optional characters' do
verify_strings(
/abc*def/ => %w[ab def],
/abc*/ => %w[ab],
/abc?def/ => %w[ab def],
/abc?/ => %w[ab],
/abc?def?/ => %w[ab de],
/abc?def?g/ => %w[ab de g]
)
end
it 'handles character classes' do
verify_strings(
/abc[a-z]/ => %w[abc],
/abc[a-z]def[0-9]g/ => %w[abc def g],
/[0-9]abc/ => %w[abc],
/[0-9]+/ => %w[],
/abc[0-9&&[^7]]/ => %w[abc]
)
end
it 'handles posix bracket expressions' do
verify_strings(
/abc[[:alpha:]]/ => %w[abc],
/[[:digit:]]abc/ => %w[abc],
/abc[[:print:]]def/ => %w[abc def]
)
end
it 'handles repitition' do
verify_strings(
/abc{3}/ => %w[abccc],
/abc{3}d/ => %w[abcccd],
/abc{0}/ => %w[ab],
/abc{,2}/ => %w[ab],
/abc{2,}/ => %w[abcc],
/def{1,5}/ => %w[def],
/abc+def/ => %w[abc def],
/ab(cde){,4}/ => %w[ab],
/(ab){,2}cd/ => %w[cd],
/(abc){2,3}/ => %w[abcabc],
/(abc){3}/ => %w[abcabcabc],
/ab{2,3}cd/ => %w[abb cd],
/(ab){2,3}cd/ => %w[abab cd]
)
end
it 'handles non-greedy repetition' do
verify_strings(
/abc.*?/ => %w[abc],
/abc+?/ => %w[abc],
/abc*?cde/ => %w[ab cde],
/(abc)+?def/ => %w[abc def],
/ab(cde)*?fg/ => %w[ab fg]
)
end
it 'handles alternation' do
verify_strings(
/abc|def/ => [],
/ab(?:c|d)/ => %w[ab],
/ab(c|d)ef/ => %w[ab ef]
)
end
it 'handles grouping' do
verify_strings(
/(abc)/ => %w[abc],
/(abc)?/ => [],
/ab(cde)/ => %w[abcde],
/(abc)de/ => %w[abcde],
/ab(cde)fg/ => %w[abcdefg],
/ab(?<name>cd)ef/ => %w[abcdef],
/gh(?>ij)kl/ => %w[ghijkl],
/m(n.*p)q/ => %w[mn pq],
/(?:ab(cd)*){2,3}/ => %w[ab],
/(ab(cd){3})?/ => [],
/(ab(cd)+){2}/ => %w[abcd]
)
end
it 'handles meta characters' do
verify_strings(
/abc\d/ => %w[abc],
/abc\wdef/ => %w[abc def],
/\habc/ => %w[abc]
)
end
it 'handles character properties' do
verify_strings(
/ab\p{Alpha}cd/ => %w[ab cd],
/ab\p{Blank}/ => %w[ab],
/\p{Digit}cd/ => %w[cd]
)
end
it 'handles backreferences' do
verify_strings(
/a(?<group>abc).\k<group>.+/ => %w[aabc]
)
end
it 'handles subexpressions' do
verify_strings(
/\A(?<paren>a\g<paren>*b)+\z/ => %w[a b]
)
end
it 'handles anchors' do
verify_strings(
/^abc/ => %w[abc],
/def$/ => %w[def],
/^abc$/ => %w[abc]
)
end
def verify_strings(hsh)
hsh.each do |regexp, expected|
expect(Capybara::Selector::RegexpDisassembler.new(regexp).substrings).to eq expected
end
end
end
| 21.942675 | 90 | 0.458926 |
333c4ddf1912b314dfef4ef14fc1fe8d6deb6862 | 403 | module APNS
class NotificationResponse
def initialize(response)
@response = response
end
def success?
@response.success?
end
def device_unsubscribed?
@response.validation_error? &&
@response.body['errors'] &&
@response.body['errors']['device'] &&
@response.body['errors']['device'].include?('unsubscribed')
end
end
end
| 19.190476 | 65 | 0.602978 |
eddd1846760a43f0ee6ac621d5854fb13c0e9eaa | 1,092 | # (c) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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.
module OneviewCookbook
module API300
module C7000
# LogicalInterconnectGroup API300 C7000 provider
class LogicalInterconnectGroupProvider < API200::LogicalInterconnectGroupProvider
# TODO: Inherit from API300::Synergy::LogicalInterconnectGroupProvider once the SDK
# API::C7000::LogicalInterconnectGroup #add_interconnect method accepts the
# logical_downlink & enclosure_index parameters. Update README when it does too.
end
end
end
end
| 45.5 | 91 | 0.770147 |
ff75135481236764d08991ec2df044884fa69ff8 | 1,268 | require 'rails_helper'
RSpec.feature 'SMS appointment reminders' do
scenario 'Executing the SMS appointment reminders job' do
travel_to '2017-11-28 08:00 UTC' do
given_appointments_due_sms_reminders_exist
when_the_task_is_executed
then_the_required_jobs_are_scheduled
end
end
def given_appointments_due_sms_reminders_exist
@agent = create(:resource_manager)
# past the reminder window
@past = create(:appointment, start_at: 5.days.from_now)
# in the window but no mobile number
@no_mobile = create(:appointment, mobile: '', start_at: 2.days.from_now, agent: @agent)
# in the window but the 'mobile' number is not valid UK
@no_uk_mobile = create(:appointment, mobile: '0121 123 4567', start_at: 2.days.from_now, agent: @agent)
# in the window with a mobile number
@mobile = create(:appointment, start_at: 2.days.from_now, agent: @agent)
end
def when_the_task_is_executed
@job_class = double(SmsAppointmentReminderJob, perform_later: true)
SmsAppointmentReminders.new(@job_class).call
end
def then_the_required_jobs_are_scheduled
expect(@job_class).to have_received(:perform_later).at_most(:once)
expect(@job_class).to have_received(:perform_later).with(@mobile)
end
end
| 36.228571 | 107 | 0.746845 |
edfc80ef33c8e58f39cc1a9a3a842961e216ee1d | 305 | module ConcertoRemoteVideo
class RemoteVideoController < ConcertoRemoteVideo::ApplicationController
def preview
@video_data = RemoteVideo.preview({
video_vendor: params[:video_vendor],
video_id: params[:video_id]
})
render json: @video_data
end
end
end | 25.416667 | 74 | 0.688525 |
33dbd7cdda230a82622a174fc776743d9abea099 | 2,489 | require File.dirname(__FILE__) + '/../spec_helper'
module VoteSpecHelper
def valid_vote_attributes
{
:choice_id => choices(:topic_one_choice_one).id,
:irc_nick => '_matta_'
}
end
end
describe Vote do
fixtures :topics, :choices, :votes
include VoteSpecHelper
include UsersXmlMock
before(:each) do
setup_users_xml_mock
@vote = topics(:topic_one).votes.build
end
it "should be valid with valid attributes" do
@vote.attributes = valid_vote_attributes
@vote.should be_valid
end
it "should belong to a topic" do
@vote.should belong_to(:topic)
end
it "should belong to a choice" do
@vote.should belong_to(:choice)
end
it "should validate the pressence of the choice" do
@vote.should validate_presence_of(:choice)
end
it "should validate the pressence of an irc_nick" do
@vote.should validate_presence_of(:irc_nick)
end
it "should not be valid if user's irc_nick is not found" do
@vote.attributes = valid_vote_attributes.with(:irc_nick => 'qqq')
@vote.should_not be_valid
end
it "should not be valid if user has already voted with the choice on the topic" do
@vote.attributes = valid_vote_attributes.with(:irc_nick => 'lachie')
@vote.should be_valid
@vote.user_id.should == 1
@vote.save
@vote = topics(:topic_one).votes.build
@vote.attributes = valid_vote_attributes.with(:irc_nick => 'lachie')
@vote.should have_at_least(1).error_on(:choice_id)
end
it "should ve valid if the user has already voted for a different choice" do
@vote.attributes = valid_vote_attributes.merge(
:irc_nick => "lachie",
:choice_id => choices(:topic_one_choice_two).id
)
@vote.should be_valid
end
it "should have set the face from the user's faces profile if they have a mugshot" do
@vote.attributes = valid_vote_attributes
@vote.should be_valid
@vote.face.should == 'http://faces.rubyonrails.com.au/mugshots/35/rbbq-avatar-large_thumb.png'
end
it "should not have set the face from the user's faces profile if they don't have a mugshot" do
@vote.attributes = valid_vote_attributes.with(:irc_nick => 'chris')
@vote.should be_valid
@vote.face.should be_nil
end
describe "from fixture 'topic_two_vote_one'" do
before(:each) do
@vote = votes(:topic_two_vote_one)
end
it "should be valid" do
@vote.should be_valid
end
end
end | 25.927083 | 98 | 0.686621 |
2116978bb3f01fdf638ad7d2dfb99de12234f241 | 116 | ENV['RAILS_ENV'] = 'test'
require_relative './dummy/config/environment'
Rails.backtrace_cleaner.remove_silencers!
| 19.333333 | 45 | 0.793103 |
ed8da6e970a0677312dc03b9bfb8ad7b155c1f7c | 4,748 | # 808b062e576afed924691af91bd7061f
# Generated: 2008-09-22 16:25:11
################################################################################
# require File.dirname(__FILE__) + '/../../spec_helper'
# require File.dirname(__FILE__) + '/fixtures/classes'
#
# describe "Array#zip" do
# it "returns an array of arrays containing corresponding elements of each array" do
# [1, 2, 3, 4].zip(["a", "b", "c", "d", "e"]).should ==
# [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
# end
#
# it "fills in missing values with nil" do
# [1, 2, 3, 4, 5].zip(["a", "b", "c", "d"]).should ==
# [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, nil]]
# end
#
# it "properly handles recursive arrays" do
# a = []; a << a
# b = [1]; b << b
#
# a.zip(a).should == [ [a[0], a[0]] ]
# a.zip(b).should == [ [a[0], b[0]] ]
# b.zip(a).should == [ [b[0], a[0]], [b[1], a[1]] ]
# b.zip(b).should == [ [b[0], b[0]], [b[1], b[1]] ]
# end
#
# # MRI 1.8.6 uses to_ary, but it's been fixed in 1.9
# compliant_on(:ruby, :jruby) do
# it "tries to convert the passed argument to an Array using #to_ary" do
# obj = mock('[3,4]')
# obj.should_receive(:to_ary).and_return([3, 4])
# [1, 2].zip(obj).should == [[1, 3], [2, 4]]
# end
#
# it "checks whether the passed argument responds to #to_ary" do
# obj = mock('[3,4]')
# obj.should_receive(:respond_to?).with(:to_ary).any_number_of_times.and_return(true)
# obj.should_receive(:method_missing).with(:to_ary).and_return([3, 4])
# [1, 2].zip(obj).should == [[1, 3], [2, 4]]
# end
# end
#
# compliant_on(:r19) do
# it "calls to_a on its arguments" do
# [1, 2, 3].zip("f" .. "z", 1 .. 9).should ==
# [[1, "f", 1], [2, "g", 2], [3, "h", 3]]
#
# obj = mock('[3,4]')
# obj.should_receive(:respond_to?).with(:to_a).any_number_of_times.and_return(true)
# obj.should_receive(:method_missing).with([:to_a]).and_return([3, 4])
#
# [1, 2].zip(obj).should == [[1, 3], [2, 4]]
# end
# end
#
# it "calls block if supplied" do
# values = []
# [1, 2, 3, 4].zip(["a", "b", "c", "d", "e"]) { |value|
# values << value
# }.should == nil
#
# values.should == [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
# end
#
# it "does not return subclass instance on Array subclasses" do
# ArraySpecs::MyArray[1, 2, 3].zip(["a", "b"]).class.should == Array
# end
# end
puts 'not implemented: zip_spec.rb'
unless true
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'
describe "Array#zip" do
it "returns an array of arrays containing corresponding elements of each array" do
[1, 2, 3, 4].zip(["a", "b", "c", "d", "e"]).should ==
[[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
end
it "fills in missing values with nil" do
[1, 2, 3, 4, 5].zip(["a", "b", "c", "d"]).should ==
[[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, nil]]
end
it "properly handles recursive arrays" do
a = []; a << a
b = [1]; b << b
a.zip(a).should == [ [a[0], a[0]] ]
a.zip(b).should == [ [a[0], b[0]] ]
b.zip(a).should == [ [b[0], a[0]], [b[1], a[1]] ]
b.zip(b).should == [ [b[0], b[0]], [b[1], b[1]] ]
end
# MRI 1.8.6 uses to_ary, but it's been fixed in 1.9
compliant_on(:ruby, :jruby) do
it "tries to convert the passed argument to an Array using #to_ary" do
obj = mock('[3,4]')
obj.should_receive(:to_ary).and_return([3, 4])
[1, 2].zip(obj).should == [[1, 3], [2, 4]]
end
it "checks whether the passed argument responds to #to_ary" do
obj = mock('[3,4]')
obj.should_receive(:respond_to?).with(:to_ary).any_number_of_times.and_return(true)
obj.should_receive(:method_missing).with(:to_ary).and_return([3, 4])
[1, 2].zip(obj).should == [[1, 3], [2, 4]]
end
end
compliant_on(:r19) do
it "calls to_a on its arguments" do
[1, 2, 3].zip("f" .. "z", 1 .. 9).should ==
[[1, "f", 1], [2, "g", 2], [3, "h", 3]]
obj = mock('[3,4]')
obj.should_receive(:respond_to?).with(:to_a).any_number_of_times.and_return(true)
obj.should_receive(:method_missing).with([:to_a]).and_return([3, 4])
[1, 2].zip(obj).should == [[1, 3], [2, 4]]
end
end
it "calls block if supplied" do
values = []
[1, 2, 3, 4].zip(["a", "b", "c", "d", "e"]) { |value|
values << value
}.should == nil
values.should == [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
end
it "does not return subclass instance on Array subclasses" do
ArraySpecs::MyArray[1, 2, 3].zip(["a", "b"]).class.should == Array
end
end
end # remove with unless true
| 33.914286 | 91 | 0.513479 |
398a728e8299d9a8c71bea9b68c9fa4d3f0bbf19 | 459 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_05_01
module Models
#
# Defines values for VirtualNetworkGatewayConnectionType
#
module VirtualNetworkGatewayConnectionType
IPsec = "IPsec"
Vnet2Vnet = "Vnet2Vnet"
ExpressRoute = "ExpressRoute"
VPNClient = "VPNClient"
end
end
end
| 25.5 | 70 | 0.716776 |
ab3e414df3c925f3e9d28818660727983b5c414b | 550 | require 'json'
require 'ginko/name_query'
module Ginko
class BankMap
include NameQuery
load_path = File.join(File.dirname(__FILE__), '../../data/banks.json')
@@data = JSON.parse(File.read(load_path)).freeze
def initialize
@result = {}
end
def find_by(k, v)
bank_data = data.select {|bank| bank[k] == v }.first || {}
bank_data.empty? ? nil : Bank.new(bank_data)
end
private
def item_klass
Bank
end
def data
@@data
end
def result
@result
end
end
end
| 16.666667 | 74 | 0.592727 |
ed2f76b47ffeb531614376966eb004eccb5c5ce7 | 1,024 | # encoding: utf-8
require 'test_helper'
class I18nLocaleTagSimpleTest < Test::Unit::TestCase
include I18n::Locale
test "returns 'de' as the language subtag in lowercase" do
assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').subtags
end
test "returns a formatted tag string from #to_s" do
assert_equal 'de-Latn-DE', Tag::Simple.new('de-Latn-DE').to_s
end
test "returns an array containing the formatted subtags from #to_a" do
assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').to_a
end
# Tag inheritance
test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do
assert_equal 'de-Latn', Tag::Simple.new('de-Latn-DE').parent.to_s
end
test "#parent returns 'de' as the parent of 'de-Latn'" do
assert_equal 'de', Tag::Simple.new('de-Latn').parent.to_s
end
test "#self_and_parents returns an array of 3 tags for 'de-Latn-DE'" do
assert_equal %w(de-Latn-DE de-Latn de), Tag::Simple.new('de-Latn-DE').self_and_parents.map { |tag| tag.to_s}
end
end
| 31.030303 | 112 | 0.696289 |
115ea503f4452db62a856b3076b38955ba493926 | 7,928 | class User < ActiveRecord::Base
include Authorization::StatefulRoles
include Activities::User
COUNTERS_TO_RELEVANCE = {
"topicos_count" => "user_relevancia_peso_topicos",
"inspirations_count" => "user_relevancia_peso_inspiracoes",
"comments_count" => "user_relevancia_peso_comentarios",
"adesoes_count" => "user_relevancia_peso_apoios"
}.freeze
TYPES = [
["Cidadão", "Cidadao"],
["Gestor público", "GestorPublico"],
["Parlamentar", "Parlamentar"],
["ONG", "Ong"],
["Movimento", "Movimento"],
["Conferência", "Conferencia"],
["Empresa", "Empresa"],
["Poder público", "PoderPublico"],
["Igreja", "Igreja"],
["Universidade", "Universidade"],
["Outro tipo de organização", "Organizacao"],
["Administrador", "Admin"]
].freeze
STATES = [
["Não confirmado", "pending"],
["Ativo", "active"],
["Banido", "suspended"],
["Apagado", "deleted"]
].freeze
ORDERS = ["relevancia", "recentes", "mais_topicos", "mais_comentarios", "mais_apoios", "a-z", "z-a"].freeze
GENRES = [["Masculino", "m"], ["Feminino", "f"]]
attr_accessible :login, :email, :name, :password, :password_confirmation, :type, :provider, :uid, :state
attr_accessor :old_password
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :confirmable,
:validatable, :encryptable, :omniauthable,
:encryptor => :restful_authentication_sha1,
:omniauth_providers => [:facebook]
before_save :default_values
before_destroy :destroy_comments_by_user
has_many :comments
# Tanto pessoas físicas quanto jurídicas são usuários, e portanto têm login
# e senha para criar propostas e editar seus perfis. Algumas pessoas físicas
# - cidadãos, gestores pub. - podem pertencer a uma pessoa jurídica - empresa,
# ONG, poder público -, e isso se dá na forma de uma árvore de usuários.
#
# Por exemplo:
#
# Empresa 1 -> Cidadão 3, Cidadão 5
# ONG 2 -> Cidadão 6, Cidadão 7
acts_as_tree
# Contém nome, telefone, sexo, site, etc.
has_one :dado, :class_name => "UserDado", :dependent => :delete
delegate :nome, :descricao, :sexo, :idade, :site_url, :fone, :fax, :email_de_contato, :aniversario, {:to => :dado, :allow_nil => true}
# Usuários possuem problemas e propostas
has_many :topicos, :dependent => :destroy
# Usuários aderem (se solidarizam) aos tópicos
has_many :adesoes, :dependent => :destroy
has_many :topicos_aderidos, :through => :adesoes, :source => :topico
# Usuários seguem os tópicos
has_many :seguidos, :dependent => :destroy
# Guarda cada vez q o usuario fez login
has_many :historico_de_logins, :dependent => :destroy, :class_name => 'HistoricoDeLogin'
# Observatorios
has_many :observatorios, :dependent => :destroy
has_many :inspirations, :dependent => :destroy
# O usuário pode incluir tags em tópicos.
acts_as_tagger
# O usuário tem uma imagem, seu avatar.
has_many :imagens, :as => :responsavel, :dependent => :destroy
def imagem
imagem = self.imagens.first
imagem ? imagem : nil
end
# O usuário tem uma localização: cidade, bairro, ponto no mapa...
has_one :local, :as => :responsavel, :dependent => :destroy
# oauth authorizations
has_many :authorizations, :class_name => "UserAuthorization"
validates_length_of :name,
:maximum => 100
validates_presence_of :email
validates_length_of :email,
:within => 6..100
validates_uniqueness_of :email
scope :do_tipo, lambda { |user_type|
if user_type and not user_type.blank? and user_type != "usuarios"
{
:conditions => { :type => user_type.to_s.classify },
:include => [ :local ]
}
end
}
scope :do_pais, lambda { |pais|
if not pais.nil? and pais.kind_of?(Pais)
{
:conditions => [ "locais.pais_id = ?", pais.id ],
:include => [ :local ]
}
end
}
scope :do_estado, lambda { |estado|
unless estado.blank?
if estado.kind_of?(Estado)
estado_id = estado.id
elsif estado.kind_of?(String)
if (estado.size == "2") and (estado.to_i == 0) #eh uma abreviacao...
estado_id = Estado.find_by_abrev(estado).id
else
estado_id = Estado.find(estado).id
end
else
estado_id = estado
end
{
:conditions => [ "locais.estado_id = ?", estado_id ],
:include => [ :local ]
}
end
}
scope :da_cidade, lambda { |cidade|
if cidade.kind_of?(Cidade)
cidade_id = cidade.id
elsif (cidade.to_i > 0)
cidade_id = cidade.to_i
else
cidade_id = nil
end
if cidade_id and not cidade_id.blank?
{
:conditions => [ "locais.cidade_id = ?", cidade_id ],
:include => [ :local ]
}
end
}
scope :do_bairro, lambda { |bairro|
if not bairro.nil? and bairro.kind_of?(Bairro)
{
:conditions => [ "locais.bairro_id = ?", bairro.id ],
:include => [ :local ]
}
end
}
scope :cadastrado_em, lambda { |dia|
unless dia.nil?
{ :conditions => [ "DATE(users.created_at) = '#{dia.strftime('%Y-%m-%d')}' " ] }
end
}
scope :nao_admin,
:conditions => [ "users.type <> ?", "Admin" ]
scope :nao_confirmados,
:conditions => { :confirmed_at => nil }
scope :ativos,
:conditions => { :state => "active" }
scope :aleatorios,
:order => "rand()"
scope :com_observatorio_ativo,
:include => [ :observatorios ],
:conditions => [ "observatorios.receber_email = ?", true ]
def self.find_by_id_criptografado(crypted_id)
begin
User.find(User.decrypt(crypted_id))
rescue ActiveRecord::RecordNotFound
return false
end
end
def self.find_by_auth(auth)
authorization = UserAuthorization.find_by_provider_and_uid(auth.provider, auth.uid)
authorization.user if authorization
end
def self.from_email(email)
where(:email => email).first_or_initialize do |user|
user.password = Devise.friendly_token[0,20]
end
end
def add_auth_provider(auth)
UserAuthorization.create :user => self, :provider => auth.provider, :uid => auth.uid
end
def default_values
self.type ||= "Cidadao"
end
# Apaga os comentarios do usuario
# antes de apaga-lo dos dados.
def destroy_comments_by_user
Comment.find_comments_by_user(self).each{ |c| c.destroy }
end
# Metodo abstrato:
# i.e. os filhos implementam.
def nome_do_tipo
end
# Metodo abstrato:
def nome_da_classe
end
def admin?
self.class == Admin
end
def pessoa?
self.class == Cidadao or
self.class == GestorPublico or
self.class == Parlamentar
end
def organizacao?
self.class == Organizacao or
self.class == Empresa or
self.class == Ong or
self.class == PoderPublico or
self.class == Universidade or
self.class == Igreja or
self.class == Conferencia
end
def poder_publico?
self.class == PoderPublico
end
def id_criptografado
return User.encrypt(self.id.to_s)
end
# User tem bairro?
def tem_bairro?
self.local and self.local.bairro
end
# User tem cidade?
def tem_cidade?
self.local and self.local.cidade
end
def self.update_counters(id, counters)
super id, CalculateRelevance.for_counters(counters, COUNTERS_TO_RELEVANCE)
end
# Don't use this method on application flow. Only for rake tasks
def reset_counters
User.reset_counters(id, :topicos, :inspirations, :comments, :adesoes)
self.relevancia = CalculateRelevance.for_counters(reload.attributes, COUNTERS_TO_RELEVANCE)["relevancia"]
self.save(:validate => false)
end
def descricao_basica
end
def display_name
self.nome
end
def owns?(model)
self == model or (model.respond_to?(:user) and self == model.user)
end
end
| 26.965986 | 136 | 0.644551 |
5d20b4a58139be9ae56483d8d4471024888a4932 | 1,058 | cask "netnewswire" do
version "6.0.1"
sha256 "0b18c95a269ab1b1ea61fe4f7b74176c8a3fbc3abf89ec983e0bccfd38687e79"
url "https://github.com/brentsimmons/NetNewsWire/releases/download/mac-#{version}/NetNewsWire#{version}.zip",
verified: "github.com/brentsimmons/NetNewsWire/"
name "NetNewsWire"
desc "Free and open-source RSS reader"
homepage "https://ranchero.com/netnewswire/"
auto_updates true
conflicts_with cask: "homebrew/cask-versions/netnewswire-beta"
depends_on macos: ">= :catalina"
app "NetNewsWire.app"
zap trash: [
"~/Library/Application Scripts/com.ranchero.NetNewsWire-Evergreen.Subscribe-to-Feed",
"~/Library/Application Support/NetNewsWire",
"~/Library/Caches/com.ranchero.NetNewsWire-Evergreen",
"~/Library/Containers/com.ranchero.NetNewsWire-Evergreen.Subscribe-to-Feed",
"~/Library/Preferences/com.ranchero.NetNewsWire-Evergreen.plist",
"~/Library/Saved Application State/com.ranchero.NetNewsWire-Evergreen.savedState",
"~/Library/WebKit/com.ranchero.NetNewsWire-Evergreen",
]
end
| 39.185185 | 111 | 0.76087 |
4a2ac69b04eb602a0a154749ce67b059835f0ddc | 6,589 | #--
# Copyright:: Copyright (c) Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "mixin/convert_to_class_name"
# Structured deprecations have a unique URL associated with them, which must exist before the deprecation is merged.
class Chef
class Deprecated
class << self
include Chef::Mixin::ConvertToClassName
def create(type, message, location)
Chef::Deprecated.const_get(convert_to_class_name(type.to_s)).new(message, location)
end
end
class Base
BASE_URL = "https://docs.chef.io/deprecations_".freeze
attr_reader :message, :location
def initialize(msg = nil, location = nil)
@message = msg
@location = location
end
def link
"Please see #{url} for further details and information on how to correct this problem."
end
# Render the URL for the deprecation documentation page.
#
# @return [String]
def url
"#{BASE_URL}#{self.class.doc_page}/"
end
# Render the user-visible message for this deprecation.
#
# @return [String]
def to_s
"Deprecation CHEF-#{self.class.deprecation_id} from #{location}\n\n #{message}\n\n#{link}"
end
# Check if this deprecation has been silenced.
#
# @return [Boolean]
def silenced?
# Check if all warnings have been silenced.
return true if Chef::Config[:silence_deprecation_warnings] == true
# Check if this warning has been silenced by the config.
return true if Chef::Config[:silence_deprecation_warnings].any? do |silence_spec|
if silence_spec.is_a? Integer
# Integers can end up matching the line number in the `location` string
silence_spec = "CHEF-#{silence_spec}"
else
# Just in case someone uses a symbol in the config by mistake.
silence_spec = silence_spec.to_s
end
# Check for a silence by deprecation name, or by location.
self.class.deprecation_key == silence_spec || self.class.deprecation_id.to_s == silence_spec || "chef-#{self.class.deprecation_id}" == silence_spec.downcase || location.include?(silence_spec)
end
# check if this warning has been silenced by inline comment.
return true if location =~ /^(.*?):(\d+):in/ && begin
# Don't buffer the whole file in memory, so read it one line at a time.
line_no = $2.to_i
location_file = ::File.open($1)
(line_no - 1).times { location_file.readline } # Read all the lines we don't care about.
relevant_line = location_file.readline
relevant_line.match?(/#.*chef:silence_deprecation($|[^:]|:#{self.class.deprecation_key})/)
end
false
end
class << self
attr_reader :deprecation_id, :doc_page
# Return the deprecation key as would be used with {Chef::Deprecated.create}.
#
# @return [String]
def deprecation_key
Chef::Mixin::ConvertToClassName.convert_to_snake_case(name, "Chef::Deprecated")
end
# Set the ID and documentation page path for this deprecation.
#
# Used in subclasses to set the data for each type of deprecation.
#
# @example
# class MyDeprecation < Base
# target 123, "my_deprecation"
# end
# @param id [Integer] Deprecation ID number. This must be unique among
# all deprecations.
# @param page [String, nil] Optional documentation page path. If not
# specified, the deprecation key is used.
# @return [void]
def target(id, page = nil)
@deprecation_id = id
@doc_page = page || "#{deprecation_key}"
end
end
end
class InternalApi < Base
target 0
end
class JsonAutoInflate < Base
target 1
end
class ExitCode < Base
target 2
end
# id 3 has been deleted
class Attributes < Base
target 4
end
class CustomResource < Base
target 5, "custom_resource_cleanups"
end
class EasyInstall < Base
target 6
end
class VerifyFile < Base
target 7
end
class SupportsProperty < Base
target 8
end
class ChefRest < Base
target 9
end
class DnfPackageAllowDowngrade < Base
target 10
end
class PropertyNameCollision < Base
target 11
end
class LaunchdHashProperty < Base
target 12
end
class ChefPlatformMethods < Base
target 13
end
class RunCommand < Base
target 14
end
class PackageMisc < Base
target 15
end
class MultiresourceMatch < Base
target 16
end
class UseInlineResources < Base
target 17
end
class LocalListen < Base
target 18
end
class NamespaceCollisions < Base
target 19
end
class DeployResource < Base
target 21
end
class ErlResource < Base
target 22
end
class FreebsdPkgProvider < Base
target 23
end
# id 25 was deleted
# id 3694 was deleted
# Returned when using the deprecated option on a property
class Property < Base
target 24
def to_s
"Deprecated resource property used from #{location}\n\n #{message}\n\nPlease consult the resource documentation for more information."
end
end
class ShellOut < Base
target 26
end
class LocaleLcAll < Base
target 27
end
class ChefSugar < Base
target 28
end
class KnifeBootstrapApis < Base
target 29
end
class ArchiveFileIntegerFileMode < Base
target 30
end
class ResourceNameWithoutProvides < Base
target 31
end
class Generic < Base
def url
"https://docs.chef.io/chef_deprecations_client/"
end
def to_s
"Deprecation from #{location}\n\n #{message}\n\n#{link}"
end
end
end
end
| 25.440154 | 201 | 0.630293 |
39dff3205f937254a80361c6597d408b2e0b1769 | 753 | require 'rubygems'
gem 'rspec'
require 'folder_cleaner'
describe FolderCleaner do
before :each do
@path = "dirpath"
@dir_handler = mock("dir_handler").as_null_object
end
it "should remove an empty folder" do
set_directory_contents(@path, @dir_handler, [])
@dir_handler.should_receive(:delete).with(@path)
FolderCleaner.Clean(@path, @dir_handler)
end
it "should keep a folder with an mp3 file in it" do
set_directory_contents(@path, @dir_handler, ["test.mp3"])
@dir_handler.should_not_receive(:delete)
FolderCleaner.Clean(@path, @dir_handler)
end
def set_directory_contents(dir, dir_handler, contents)
dir_handler.should_receive(:find_mp3_files).with(dir).and_return(contents)
end
end
| 25.965517 | 79 | 0.722444 |
62c88bc047b859f33fc975b18243eb46997db1b7 | 1,124 | # frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Checks that right braces for adjacent single line lets are aligned.
#
# @example
#
# # bad
# let(:foobar) { blahblah }
# let(:baz) { bar }
# let(:a) { b }
#
# # good
# let(:foobar) { blahblah }
# let(:baz) { bar }
# let(:a) { b }
#
class AlignRightLetBrace < Base
extend AutoCorrector
MSG = 'Align right let brace'
def self.autocorrect_incompatible_with
[Layout::ExtraSpacing]
end
def on_new_investigation
return if processed_source.blank?
token_aligner =
RuboCop::RSpec::AlignLetBrace.new(processed_source.ast, :end)
token_aligner.offending_tokens.each do |let|
add_offense(let.loc.end) do |corrector|
corrector.insert_before(
let.loc.end, token_aligner.indent_for(let)
)
end
end
end
end
end
end
end
| 23.914894 | 75 | 0.512456 |
33dd0da369d86294c9d1d20a64e2d9954191c43e | 586 | # This migration comes from acts_as_taggable_on_engine (originally 5)
# This migration is added to circumvent issue #623 and have special characters
# work properly
if ActiveRecord.gem_version >= Gem::Version.new('5.0')
class ChangeCollationForTagNames < ActiveRecord::Migration[4.2]; end
else
class ChangeCollationForTagNames < ActiveRecord::Migration; end
end
ChangeCollationForTagNames.class_eval do
def up
execute("ALTER TABLE #{ActsAsTaggableOn.tags_table} MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;") if ActsAsTaggableOn::Utils.using_mysql?
end
end
| 41.857143 | 159 | 0.803754 |
b96a63469fe526834cf0725c39dbc8f618722b2a | 522 | module Sector
def self.included(stocks)
stocks.extend(ClassMethods)
end
module ClassMethods
@@base_uri = "https://www.alphavantage.co/query?"
def get_sector_performance(apikey)
begin
response = HTTParty.get("#{@@base_uri}function=SECTOR&apikey=#{apikey}")
rescue
return "Oops! It seems you have a bad URI, please make sure the parameters are valid."
else
@data = JSON.parse(response.body)
check_if_data_is_valid(limit=nil)
end
end
end
end
| 23.727273 | 94 | 0.66092 |
61b5e5df96f7ab4614fe381185093eb6a80eb15e | 455 | module HelperModule
def logged_in?
!current_user.nil?
end
def log_in(user)
session[:user_id] = user.id
end
def remember(user)
cookies.permanent.signed[:user_id] = user.id
end
def current_user
@current_user ||= User.return_current_user(session[:user_id]) if session[:user_id]
end
def log_out
session.delete(:user_id)
@current_user = nil
end
def creator(event)
User.find_it(event.creator_id)
end
end
| 16.851852 | 86 | 0.692308 |
267d13381f4ab6ae94b8aa28fa5d3b7687993ced | 1,090 | module ActivityActionsHelper
def toggle_follow_action(activity_object)
action = activity_object.action_from(current_subject)
action ||= activity_object.received_actions.build :actor_id => current_subject.actor_id
action.follow ^= true
action
end
# Show the {SocialStream::Models::Subject Subjects} that follow
# the {ActivityObject object}
#
# TODO: DRY with ActivitiesHelper#like_sentence
def followers_sentence(object, options = {})
options[:followers_shown] ||= 2
followers_count = object.follower_count
return "" unless followers_count > 0
followers =
object.followers.
map{ |a| a.subject }.
map{ |l| link_to l.name, l }
followers_other = followers_count - options[:followers_shown]
if followers_other > 0
followers.push t("activity_action.sentence.more", :count => followers_other)
end
t("#{ object.object_type.underscore }.activity_action.sentence.follow", :followers => followers.to_sentence, :count => followers_count, :default => :"activity_action.sentence.follow").html_safe
end
end
| 30.277778 | 197 | 0.722018 |
b93afa0e7a5401d94e40ce8158d7c4f2fbd153db | 483 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::CloudHSMV2
class Resource
# @param options ({})
# @option options [Client] :client
def initialize(options = {})
@client = options[:client] || Client.new(options)
end
# @return [Client]
def client
@client
end
end
end
| 20.125 | 74 | 0.670807 |
28536e359e51c538e3bbfc8fe2bedef816eb7a73 | 1,456 | class UploadsController < ApplicationController
skip_before_action :authenticate_user!
before_action :find_model, :authorize_access!
def show
uploader = @model.send(upload_mount)
unless uploader.file_storage?
return redirect_to uploader.url
end
unless uploader.file && uploader.file.exists?
return not_found!
end
disposition = uploader.image? ? 'inline' : 'attachment'
send_file uploader.file.path, disposition: disposition
end
private
def find_model
unless upload_model && upload_mount
return not_found!
end
@model = upload_model.find(params[:id])
end
def authorize_access!
authorized =
case @model
when Project
can?(current_user, :read_project, @model)
when Group
can?(current_user, :read_group, @model)
when Note
can?(current_user, :read_project, @model.project)
else
# No authentication required for user avatars.
true
end
return if authorized
if current_user
not_found!
else
authenticate_user!
end
end
def upload_model
upload_models = {
"user" => User,
"project" => Project,
"note" => Note,
"group" => Group
}
upload_models[params[:model]]
end
def upload_mount
upload_mounts = %w(avatar attachment file)
if upload_mounts.include?(params[:mounted_as])
params[:mounted_as]
end
end
end
| 20.222222 | 59 | 0.649038 |
38824d06dae526ce9426f92518cd48e4b1a3d227 | 1,449 | # frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[6.1]
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.string :current_sign_in_ip
# t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.string :name
t.integer :followers
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
| 30.829787 | 104 | 0.648723 |
2894557b12b95f1bcb38ef9f7584240eebd25b07 | 232 | require 'alquran'
RSpec.describe Alquran::Edition do
describe 'index' do
before :all do
@editions = Alquran::Edition.fetch
end
it 'must have number' do
expect(@editions.size).to be(135)
end
end
end
| 16.571429 | 40 | 0.650862 |
f88233393c6ae7df0b9b7c737c5375e543ddd02f | 217 | class MoveComprehensionQuestionsToCohortExercises < ActiveRecord::Migration
def change
remove_reference :comprehension_questions, :exercise
add_reference :comprehension_questions, :cohort_exercise
end
end
| 31 | 75 | 0.83871 |
bbcbe0cf2a01ee0599c2d0ebec347f27220b8e9a | 407 | #!/usr/bin/env ruby
nkill = rand(5)
ngot = 0
done = false
args = ARGV.join(' ')
Signal.trap("INT") do
ngot += 1
end
puts "pid=#{$$},args=#{args}ngot=#{ngot}/#{nkill},state=entering"
while not done
sleep 1
if ngot < nkill
puts "pid=#{$$},args=#{args}ngot=#{ngot}/#{nkill},state=continuing"
else
puts "pid=#{$$},args=#{args}ngot=#{ngot}/#{nkill},state=exiting"
done = true
end
end
| 17.695652 | 71 | 0.597052 |
625e1076a54f1fe663f880d11f431aeb06cd5595 | 3,600 | # frozen_string_literal: true
# Usage data utilities
#
# * distinct_count(relation, column = nil, batch: true, start: nil, finish: nil)
# Does a distinct batch count, smartly reduces batch_size and handles errors
#
# Examples:
# issues_using_zoom_quick_actions: distinct_count(ZoomMeeting, :issue_id),
#
# * count(relation, column = nil, batch: true, start: nil, finish: nil)
# Does a non-distinct batch count, smartly reduces batch_size and handles errors
#
# Examples:
# active_user_count: count(User.active)
#
# * alt_usage_data method
# handles StandardError and fallbacks by default into -1 this way not all measures fail if we encounter one exception
# there might be cases where we need to set a specific fallback in order to be aligned wih what version app is expecting as a type
#
# Examples:
# alt_usage_data { Gitlab::VERSION }
# alt_usage_data { Gitlab::CurrentSettings.uuid }
# alt_usage_data(fallback: nil) { Gitlab.config.registry.enabled }
#
# * redis_usage_data method
# handles ::Redis::CommandError, Gitlab::UsageDataCounters::BaseCounter::UnknownEvent
# returns -1 when a block is sent or hash with all values -1 when a counter is sent
# different behaviour due to 2 different implementations of redis counter
#
# Examples:
# redis_usage_data(Gitlab::UsageDataCounters::WikiPageCounter)
# redis_usage_data { ::Gitlab::UsageCounters::PodLogs.usage_totals[:total] }
module Gitlab
module Utils
module UsageData
extend self
FALLBACK = -1
def count(relation, column = nil, batch: true, start: nil, finish: nil)
if batch
Gitlab::Database::BatchCount.batch_count(relation, column, start: start, finish: finish)
else
relation.count
end
rescue ActiveRecord::StatementInvalid
FALLBACK
end
def distinct_count(relation, column = nil, batch: true, batch_size: nil, start: nil, finish: nil)
if batch
Gitlab::Database::BatchCount.batch_distinct_count(relation, column, batch_size: batch_size, start: start, finish: finish)
else
relation.distinct_count_by(column)
end
rescue ActiveRecord::StatementInvalid
FALLBACK
end
def alt_usage_data(value = nil, fallback: FALLBACK, &block)
if block_given?
yield
else
value
end
rescue
fallback
end
def redis_usage_data(counter = nil, &block)
if block_given?
redis_usage_counter(&block)
elsif counter.present?
redis_usage_data_totals(counter)
end
end
def with_prometheus_client(fallback: nil)
return fallback unless Gitlab::Prometheus::Internal.prometheus_enabled?
prometheus_address = Gitlab::Prometheus::Internal.uri
yield Gitlab::PrometheusClient.new(prometheus_address, allow_local_requests: true)
end
def measure_duration
result = nil
duration = Benchmark.realtime do
result = yield
end
[result, duration]
end
def with_finished_at(key, &block)
yield.merge(key => Time.now)
end
private
def redis_usage_counter
yield
rescue ::Redis::CommandError, Gitlab::UsageDataCounters::BaseCounter::UnknownEvent
FALLBACK
end
def redis_usage_data_totals(counter)
counter.totals
rescue ::Redis::CommandError, Gitlab::UsageDataCounters::BaseCounter::UnknownEvent
counter.fallback_totals
end
end
end
end
| 31.304348 | 134 | 0.6725 |
113caf0e498c3fd4a937cf5a720aae20a1f33375 | 5,224 | module Binance
module Api
class Order
class << self
def all!(limit: 500, orderId: nil, recvWindow: 5000, symbol: nil, api_key: nil, api_secret_key: nil)
raise Error.new(message: "max limit is 500") unless limit <= 500
raise Error.new(message: "symbol is required") if symbol.nil?
timestamp = Configuration.timestamp
params = { limit: limit, orderId: orderId, recvWindow: recvWindow, symbol: symbol, timestamp: timestamp }
Request.send!(api_key_type: :read_info, path: "/api/v3/allOrders",
params: params.delete_if { |key, value| value.nil? },
security_type: :user_data, tld: Configuration.tld, api_key: api_key,
api_secret_key: api_secret_key)
end
# Be careful when accessing without a symbol!
def all_open!(recvWindow: 5000, symbol: nil, api_key: nil, api_secret_key: nil)
timestamp = Configuration.timestamp
params = { recvWindow: recvWindow, symbol: symbol, timestamp: timestamp }
Request.send!(api_key_type: :read_info, path: "/api/v3/openOrders",
params: params, security_type: :user_data, tld: Configuration.tld, api_key: api_key,
api_secret_key: api_secret_key)
end
def cancel!(orderId: nil, originalClientOrderId: nil, newClientOrderId: nil, recvWindow: nil, symbol: nil,
api_key: nil, api_secret_key: nil)
raise Error.new(message: "symbol is required") if symbol.nil?
raise Error.new(message: "either orderid or originalclientorderid " \
"is required") if orderId.nil? && originalClientOrderId.nil?
timestamp = Configuration.timestamp
params = { orderId: orderId, origClientOrderId: originalClientOrderId,
newClientOrderId: newClientOrderId, recvWindow: recvWindow,
symbol: symbol, timestamp: timestamp }.delete_if { |key, value| value.nil? }
Request.send!(api_key_type: :trading, method: :delete, path: "/api/v3/order",
params: params, security_type: :trade, tld: Configuration.tld, api_key: api_key,
api_secret_key: api_secret_key)
end
def create!(icebergQuantity: nil, newClientOrderId: nil, newOrderResponseType: nil,
price: nil, quantity: nil, recvWindow: nil, stopPrice: nil, symbol: nil,
side: nil, type: nil, timeInForce: nil, test: false, api_key: nil, api_secret_key: nil)
timestamp = Configuration.timestamp
params = {
icebergQty: icebergQuantity, newClientOrderId: newClientOrderId,
newOrderRespType: newOrderResponseType, price: price, quantity: quantity,
recvWindow: recvWindow, stopPrice: stopPrice, symbol: symbol, side: side,
type: type, timeInForce: timeInForce, timestamp: timestamp,
}.delete_if { |key, value| value.nil? }
ensure_required_create_keys!(params: params)
path = "/api/v3/order#{"/test" if test}"
Request.send!(api_key_type: :trading, method: :post, path: path,
params: params, security_type: :trade, tld: Configuration.tld, api_key: api_key,
api_secret_key: api_secret_key)
end
def status!(orderId: nil, originalClientOrderId: nil, recvWindow: nil, symbol: nil,
api_key: nil, api_secret_key: nil)
raise Error.new(message: "symbol is required") if symbol.nil?
raise Error.new(message: "either orderid or originalclientorderid " \
"is required") if orderId.nil? && originalClientOrderId.nil?
timestamp = Configuration.timestamp
params = {
orderId: orderId, origClientOrderId: originalClientOrderId, recvWindow: recvWindow,
symbol: symbol, timestamp: timestamp,
}.delete_if { |key, value| value.nil? }
Request.send!(api_key_type: :trading, path: "/api/v3/order",
params: params, security_type: :user_data, tld: Configuration.tld, api_key: api_key,
api_secret_key: api_secret_key)
end
private
def additional_required_create_keys(type:)
case type
when :limit
[:price, :timeInForce].freeze
when :stop_loss, :take_profit
[:stopPrice].freeze
when :stop_loss_limit, :take_profit_limit
[:price, :stopPrice, :timeInForce].freeze
when :limit_maker
[:price].freeze
else
[].freeze
end
end
def ensure_required_create_keys!(params:)
keys = required_create_keys.dup.concat(additional_required_create_keys(type: params[:type]))
missing_keys = keys.select { |key| params[key].nil? }
raise Error.new(message: "required keys are missing: #{missing_keys.join(", ")}") unless missing_keys.empty?
end
def required_create_keys
[:symbol, :side, :type, :quantity, :timestamp].freeze
end
end
end
end
end
| 51.722772 | 118 | 0.612366 |
28ffd9d395775ccbeb0f6779d4bfc8081c9a7c09 | 1,316 | module Chewy
class Type
module Observe
extend ActiveSupport::Concern
def self.update_proc(type_name, *args, &block)
options = args.extract_options!
method = args.first
Proc.new do
backreference = if method && method.to_s == 'self'
self
elsif method
send(method)
else
instance_eval(&block)
end
Chewy.derive_type(type_name).update_index(backreference, options)
end
end
module MongoidMethods
def update_index(type_name, *args, &block)
update_proc = Observe.update_proc(type_name, *args, &block)
after_save &update_proc
after_destroy &update_proc
end
end
module ActiveRecordMethods
def update_index(type_name, *args, &block)
update_proc = Observe.update_proc(type_name, *args, &block)
if Chewy.use_after_commit_callbacks
after_commit &update_proc
else
after_save &update_proc
after_destroy &update_proc
end
end
end
module ClassMethods
def update_index(objects, options = {})
Chewy.strategy.current.update(self, objects, options)
true
end
end
end
end
end
| 24.37037 | 75 | 0.587386 |
38c2f5f23ba3772dff80a8aa7ae39969e78af228 | 1,831 | require 'rack'
require 'jasny_bundle/mime_types'
module JasnyBundle
class Middleware
def initialize(app, origin, options={})
@app = app
@origin = origin
@options = options
@mime_types = JasnyBundle::MimeTypes.new(Rack::Mime::MIME_TYPES)
end
def access_control_headers
{
"Access-Control-Allow-Origin" => origin,
"Access-Control-Allow-Methods" => "GET",
"Access-Control-Allow-Headers" => "x-requested-with",
"Access-Control-Max-Age" => "3628800"
}
end
def call(env)
@ssl_request = Rack::Request.new(env).scheme == "https"
# intercept the "preflight" request
if env["REQUEST_METHOD"] == "OPTIONS"
return [200, access_control_headers, []]
else
code, headers, body = @app.call(env)
set_headers! headers, body, env["PATH_INFO"]
[code, headers, body]
end
end
private
def origin
if !wildcard_origin? and allow_ssl? and ssl_request?
uri = URI(@origin)
uri.scheme = "https"
uri.to_s
else
@origin
end
end
def wildcard_origin?
@origin == '*'
end
def ssl_request?
@ssl_request
end
def allow_ssl?
@options[:allow_ssl]
end
def extension(path)
if path.nil? || path.length == 0
nil
else
"." + path.split("?").first.split(".").last
end
end
def font_asset?(path)
@mime_types.font? extension(path)
end
def set_headers!(headers, body, path)
if ext = extension(path) and font_asset?(ext)
headers.merge!(access_control_headers)
headers.merge!('Content-Type' => mime_type(ext)) if headers['Content-Type']
end
end
def mime_type(extension)
@mime_types[extension]
end
end
end
| 21.797619 | 83 | 0.587657 |
4a6b526dc91cdcdfa28121e09183b026dc0c2592 | 1,815 | class TeamMembersController < ApplicationController
layout 'team'
def send_welcome_email
@team_member = TeamMember.find(params[:id])
authorize @team_member
@team_member.send_welcome!(current_user.id)
redirect_to team_team_members_url(current_team), :notice => 'Welcome email sent'
end
def new
authorize current_team
emails = SimpleTextAreaParser.parse(params[:emails] || "")
@add_team_members = AddTeamMembers.users_from_emails(current_team, emails)
end
def create
authorize current_team
@add_team_members = AddTeamMembers.new(params[:add_team_members])
if @add_team_members.save(current_team)
redirect_to team_team_members_url(current_team), notice: "Team members added"
else
render :action => 'new'
end
end
def index
@team_members_welcome_email_unsent = current_team.team_members.welcome_email_unsent
@team_members = current_team.team_members.welcome_email_sent
@captain = TeamPolicy.new(current_user, current_team).captain?
end
def edit
@team_member = TeamMember.find(params[:id])
authorize @team_member
end
def update
@team_member = TeamMember.find(params[:id])
authorize @team_member
if @team_member.update(permitted_params.team_member)
redirect_to team_team_members_url(@team_member.team), :notice => 'Team member updated'
else
render :edit
end
end
def destroy
@team_member = TeamMember.find(params[:id])
authorize @team_member
DestroysTeamMember.new(@team_member).destroy
if current_user.id == @team_member.user_id
redirect_to teams_url, :notice => 'You have removed yourself from the team'
else
redirect_to team_team_members_url(@team_member.team), :notice => 'Team member is now removed from the team'
end
end
end
| 27.5 | 113 | 0.734435 |
edaf1950bc79f109be0676a0d65ad5ffe5d8afd6 | 349 | module ResponsesHelper
def options_for_responses_select(issue)
responses = issue.available_responses
tags = "".html_safe
blank_text = "-- #{l(:label_responses)} --"
tags << content_tag('option', blank_text, :value => '') if responses.size > 1
tags << options_for_select(responses.map { |r| [r.name, r.id] })
tags
end
end
| 31.727273 | 81 | 0.670487 |
33165d5e81c28b01a4f1c933be45910d17f84fe0 | 1,307 | #!/home/software/ruby-1.8.7/bin/ruby -w
require 'RMagick'
imgl = Magick::ImageList.new
imgl.new_image(390, 240, Magick::HatchFill.new('white','lightcyan2'))
gc = Magick::Draw.new
# Draw path
gc.fill_opacity 0
gc.stroke 'red'
gc.stroke_width 3
gc.path "M20,120 C20,20 170,20 170,120 S320,220 320,120"
# Annotate
# Show end points
gc.fill_opacity 0
gc.stroke 'gray50'
gc.stroke_width 1
gc.circle 20,120, 23, 123
gc.circle 170,120, 173, 123
gc.circle 320,120, 323, 123
# Show control points
gc.fill_opacity 1
gc.circle 20, 20, 23, 23
gc.circle 170, 20, 173, 23
gc.circle 320,220, 323, 223
# Show connector lines
gc.line 20,120, 20, 20
gc.line 170, 20, 170,220
gc.line 320,220, 320,120
# Show auto control point
gc.fill_opacity 0
gc.stroke 'blue'
gc.stroke_width 3
gc.circle 170,220, 173,223
# Add labels
gc.font_weight Magick::NormalWeight
gc.font_style Magick::NormalStyle
gc.stroke "none" # unset stroke color
gc.fill 'black'
# Add end point labels
gc.text 30,125, "'20,120'"
gc.text 180,125, "'170,120'"
gc.text 330,125, "'320,120'"
# Add control point labels
gc.text 30, 25, "'20,20'"
gc.text 180, 25, "'170,20'"
gc.text 330,225, "'320,220'"
# Add auto control point label
gc.text 180,225, "'auto ctl point'"
gc.draw imgl
imgl.border!(1,1, 'lightcyan2')
imgl.write 'path.gif'
| 20.107692 | 69 | 0.704667 |
1cdc438d2545ef421673e2bda63ecfef2f6b427d | 100 | module Spree
module Admin
class PriceFiltersController < ResourceController
end
end
end
| 14.285714 | 53 | 0.76 |
ab7b1b52017b36d31711cb7d9129d33d6f727fe2 | 14,445 | RSpec.describe UnifonicSms do
describe "Default Attributes" do
it "has a version number" do
expect(UnifonicSms::VERSION).not_to be nil
end
it "Can get base path based on method url" do
url = UnifonicSms.base_path("Messages/Send")
expect(url).not_to be "/rest/Messages/Send"
end
it "Has an Api key" do
expect(UnifonicSms.api_key).not_to be nil
end
it "Has a sender phone number" do
expect(UnifonicSms.sender_phone).not_to be nil
end
end
describe "Account Methods" do
it "Can get account's balance" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Account/GetBalance").
with(body: {"AppSid"=>"#{UnifonicSms.api_key}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
"success" => "true",
"message" => "",
"errorCode" => "ER-00",
data: {
"Balance" => "48.03200",
"CurrencyCode" => "USD",
"SharedBalance" => "0.00000"
}
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.balance
expect(response[:balance]).not_to be nil
end
end
describe "SMS Methods" do
it "Can send SMS message to one number" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/Send").
with(body: {"AppSid"=>"#{UnifonicSms.api_key}",
"Body"=>"#{@test_message_body}",
"Priority"=>"High", "Recipient"=>"#{@test_filtered_recipent_number}",
"SenderID"=>"#{UnifonicSms.sender_phone}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: { data: {
"MessageID" => "6542",
"Status" => "Sent",
"NumberOfUnits" => "1",
"Cost" => 0.4,
"Balance" => "100",
"Recipient" => "#{@test_filtered_recipent_number}",
"DateCreated" => "2014-07-22"
}}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.send_message(@test_recipent_number, @test_message_body)
expect(response[:message_id]).not_to be nil
end
it "Can send Bulk SMS messages to multiple numbers" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/SendBulk").
with(body: {"AppSid"=>"#{UnifonicSms.api_key}",
"Body"=>"#{@test_message_body}",
"Recipient"=>"#{@test_number}, #{@test_number}, #{@test_number}",
"SenderID"=>"#{UnifonicSms.sender_phone}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
data: {
Messages: [
{
"MessageID" => "310856",
"Recipient" => "962795949563",
"Status" => "Queued"
},
{
"MessageID" => "310857",
"Recipient" => "962790606334",
"Status" => "Queued"
}
],
"NumberOfUnits" => 2,
"Cost" => 0,
"Balance" => 136408.541,
"TimeCreated" => "2014-10-16 09:16:55",
"CurrencyCode" => "USD"
}}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.send_bulk("#{@test_number}, #{@test_number}, #{@test_number}", @test_message_body)
expect(response[:cost]).not_to be nil
end
it "Can get SMS message status" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/GetMessageIDStatus")
.with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "MessageID"=>"#{@test_message_id}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'})
.to_return(status: 200,
body: {"Status" => "Sent"}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.message_status(@test_message_id)
expect(response[:status]).not_to be nil
end
it "Can get SMS messages report" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/GetMessagesReport").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}",
"SenderID"=>"#{UnifonicSms.sender_phone}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: { "TotalTextMessages" => "150",
"NumberOfUnits" => "160",
"Cost" => "35"}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.messages_report
expect(response[:total_text_messages]).not_to be nil
end
it "Can get SMS messages details" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/GetMessagesDetails").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "SenderID"=>"#{UnifonicSms.sender_phone}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
data: {
"TotalTextMessages" => "3",
"Page" => "1",
messages: [
{
"MessageID" => "6423",
"Body" => "Message Body",
"Recipient" => 962795989856,
"Status" => "Sent",
"Datecreated" => "2014-07-22",
"SenderID" => "TestSender",
"NumberOfUnits" => "2",
"Cost" => "0.04",
},
{
"message_id" => "6422",
"Body" => "Message Body",
"Recipient" => 962795989876,
"Status" => "Sent",
"Datecreated" => "2014-07-22",
"SenderID" => "TestSender",
"NumberOfUnits" => "1",
"Cost" => "0.02",
},
{
"message_id" => "6421",
"Body" => "Message Body",
"Recipient" => 9627895985555,
"Status" => "Sent",
"Datecreated" => "2014-07-22",
"SenderID" => "TestSender",
"NumberOfUnits" => "2",
"Cost" => "0.04",
}
],
"TotalTextMessages" => "6421",
"page" => 1
}
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.messages_details
expect(response[:total_text_messages]).not_to be nil
end
it "Can get SMS Schedualed messages" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/GetScheduled").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
"MessageID" => "24",
"MessageBody" => "test",
"SenderID" => "123456",
"Recipient" => "962795516342,962795516348",
"TimeScheduled" => "2015-04-29 12:38:06",
"Status" => "scheduled"
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.schedualed_messages
expect(response[:code]).to eq(0)
end
it "Can stop SMS Schedualed messages" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/StopScheduled").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "MessageID"=>"#{@test_message_id}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
"success" => "true",
"message" => "",
"errorCode" => "ER-00",
"data" => nil
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.stop_schedualed_messages(@test_message_id)
expect(response[:code]).to eq(0)
end
it "Can create Keyword method enables you to manage your numbers" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/Keyword").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "Keyword"=>"#{@test_keyword}",
"Number"=>"#{@test_number}", "Rule"=>"#{@test_role}", "SenderID"=>"#{UnifonicSms.sender_phone}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: { "success" => "true" }.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.keyword(@test_number, @test_keyword, @test_role)
expect(response[:code]).to eq(0)
end
it "Can create Retrieve all incoming messages" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/Inbox").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "Number"=>"#{@test_number}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
"success" => "true",
"message" => "",
"errorCode" => "ER-00",
data: {
"NumberOfMessages" => 19,
Messages: [
{
"MessageFrom" => "+962795949563",
"Message" => "new",
"DateReceived" => "2015-09-15 13:40:56"
},
{
"MessageFrom" => "+962795949563",
"Message" => "Areen",
"DateReceived" => "2015-09-15 13:18:10"
}
]
}
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.inbox(@test_number)
expect(response[:code]).to eq(0)
end
it "Can retrieve outbound messaging pricing for a given country" do
if @mock_test
stub_request(:post, "http://api.unifonic.com/rest/Messages/Pricing").
with( body: {"AppSid"=>"#{UnifonicSms.api_key}", "CountryCode"=>"#{@test_country_code}"},
headers: {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(status: 200,
body: {
"success" => "true",
"message" => "",
"errorCode" => "ER-00",
data: {
Jordan: {
Orange: {
"CountryCode" => "JO",
"CountryPrefix" => "962",
"OperatorPrefix" => "77",
"MCC" => "416",
"MNC" => "77",
"Cost" => "0.02800"
},
Umnia: {
"CountryCode" => "JO",
"CountryPrefix" => "962",
"OperatorPrefix" => "78",
"MCC" => "416",
"MNC" => "3",
"Cost" => "0.02800"
},
Zain: {
"CountryCode" => "JO",
"CountryPrefix" => "962",
"OperatorPrefix" => "79",
"MCC" => "416",
"MNC" => "1",
"Cost" => "0.02800"
}
},
"CurrencyCode" => "USD"
}
}.to_json,
headers: {'Content-Type'=>'application/json'})
end
response = UnifonicSms.pricing(@test_country_code)
expect(response[:code]).to eq(0)
end
end
end
| 40.125 | 121 | 0.407823 |
1d59f52abd06a9e14bcaa78152931c1046c8cf26 | 1,344 | require 'angular-rails-templates/compact_javascript_escape'
module AngularRailsTemplates
class Processor
AngularJsTemplateWrapper = Tilt::ERBTemplate.new "#{File.dirname __FILE__}/javascript_template.js.erb"
include CompactJavaScriptEscape
def self.instance
@instance ||= new
end
def self.call(input)
instance.call(input)
end
def self.cache_key
instance.cache_key
end
attr_reader :cache_key, :config
def config
Rails.configuration.angular_templates
end
def initialize(options = {})
@cache_key = [self.class.name, VERSION, options].freeze
end
def template_name(name)
path = name.sub /^(#{config.ignore_prefix.join('|')})/, ''
"#{path}.#{config.extension}"
end
def call(input)
file_path = Pathname.new(input[:filename]).relative_path_from(Rails.root).to_s
unless config.inside_paths.any? { |folder| file_path.match(folder.to_s) }
return input[:data]
end
locals = {}
locals[:angular_template_name] = template_name(input[:name])
locals[:angular_module] = config.module_name
locals[:source_file] = "#{input[:filename]}".sub(/^#{Rails.root}\//,'')
locals[:html] = escape_javascript(input[:data].chomp)
AngularJsTemplateWrapper.render(nil, locals)
end
end
end
| 24.436364 | 106 | 0.668155 |
5d3407b3e43a4ac5fe1ffab752aadb50c19c47bd | 1,684 | # Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
#
# The MIT License (MIT)
#
# 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.
module Fog
module Compute
class Azure
class Real
def create_storage_account(name, options)
@stg_svc.create_storage_account(name, options)
end
end
class Mock
def create_storage_account(name, options)
storage = ::Azure::StorageManagement::StorageAccount.new
storage.name = name
storage.status = "Created"
storage.label = name
storage.location = options[:location]
storage
end
end
end
end
end
| 38.272727 | 79 | 0.720903 |
e214d943288c2c8afde783fd84f932538fb79393 | 2,007 | cask 'bluestacks' do
version '4.70.5.2403'
sha256 '423a56ea65d05f26d07606349ffae9f1719453fd71a8b066c35c1652b9c7edc9'
url "https://cdn3.bluestacks.com/downloads/mac/bgp_mac/#{version}/BlueStacksInstaller_#{version}.dmg"
appcast 'https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://cloud.bluestacks.com/api/getdownloadnow?platform=mac'
name 'BlueStacks'
homepage 'https://www.bluestacks.com/'
depends_on macos: '>= :sierra'
installer manual: 'BlueStacks Installer.app'
uninstall_preflight do
set_ownership "#{appdir}/BlueStacks.app"
end
uninstall launchctl: [
'com.BlueStacks.AppPlayer.bstservice_helper',
'com.BlueStacks.AppPlayer.Service',
'com.BlueStacks.AppPlayer.UninstallWatcher',
'com.BlueStacks.AppPlayer.Updater',
],
delete: '/Library/PrivilegedHelperTools/com.BlueStacks.AppPlayer.bstservice_helper'
zap trash: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.bluestacks.bluestacks.sfl*',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.bluestacks.bluestacks-support-tool.sfl*',
'~/Library/BlueStacks',
'~/Library/Caches/com.bluestacks.BlueStacks',
'~/Library/Caches/com.bluestacks.BlueStacks-Support-Tool',
'~/Library/Caches/KSCrashReports/BlueStacks',
'~/Library/Logs/BlueStacks',
'~/Library/Preferences/com.BlueStacks.AppPlayer.DiagnosticTimestamp.txt',
'~/Library/Preferences/com.BlueStacks.AppPlayer.plist',
'~/Library/Preferences/com.BlueStacks.AppPlayer.SavedFrame.plist',
'~/Library/Preferences/com.bluestacks.BlueStacks.plist',
],
rmdir: '~/Library/Caches/KSCrashReports'
end
| 48.95122 | 170 | 0.671151 |
339dc3ab833351103ccbc4a933079a0107efa477 | 2,983 | require_relative '../../spec_helper'
describe 'osl-keepalived::haproxy_phpbb' do
before do
stub_data_bag_item('osl_keepalived', 'haproxy_phpbb').and_return(
id: 'haproxy_phpbb',
auth_pass: 'foobar'
)
end
ALL_PLATFORMS.each do |p|
context "#{p[:platform]} #{p[:version]}" do
cached(:chef_run) do
ChefSpec::SoloRunner.new(p).converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
it do
expect(chef_run).to create_keepalived_vrrp_sync_group('haproxy-phpbb-group').with(
group: %w(haproxy-phpbb-ipv4 haproxy-phpbb-ipv6)
)
end
%w(ipv4 ipv6).each do |ip|
it do
expect(chef_run.keepalived_vrrp_instance("haproxy-phpbb-#{ip}")).to notify('service[keepalived]').to(:reload)
end
end
it do
expect(chef_run.keepalived_vrrp_sync_group('haproxy-phpbb-group')).to \
notify('service[keepalived]').to(:reload)
end
end
context "#{p[:platform]} #{p[:version]} for lb1.phpbb.com" do
cached(:chef_run) do
ChefSpec::SoloRunner.new(p) do |node|
node.automatic_attrs['fqdn'] = 'lb1.phpbb.com'
end.converge(described_recipe)
end
it do
expect(chef_run).to create_keepalived_vrrp_instance('haproxy-phpbb-ipv4').with(
master: true,
interface: 'eth0',
virtual_router_id: 3,
priority: 200,
authentication: { auth_type: 'PASS', auth_pass: 'foobar' },
virtual_ipaddress: %w(140.211.15.244/24)
)
end
it do
expect(chef_run).to create_keepalived_vrrp_instance('haproxy-phpbb-ipv6').with(
master: true,
interface: 'eth0',
virtual_router_id: 4,
priority: 200,
authentication: { auth_type: 'PASS', auth_pass: 'foobar' },
virtual_ipaddress: %w(2605:bc80:3010:103::8cd3:ff4/64)
)
end
end
context "#{p[:platform]} #{p[:version]} for lb2.phpbb.com" do
cached(:chef_run) do
ChefSpec::SoloRunner.new(p) do |node|
node.automatic_attrs['fqdn'] = 'lb2.phpbb.com'
end.converge(described_recipe)
end
it do
expect(chef_run).to create_keepalived_vrrp_instance('haproxy-phpbb-ipv4').with(
master: false,
interface: 'eth0',
virtual_router_id: 3,
priority: 100,
authentication: { auth_type: 'PASS', auth_pass: 'foobar' },
virtual_ipaddress: %w(140.211.15.244/24)
)
end
it do
expect(chef_run).to create_keepalived_vrrp_instance('haproxy-phpbb-ipv6').with(
master: false,
interface: 'eth0',
virtual_router_id: 4,
priority: 100,
authentication: { auth_type: 'PASS', auth_pass: 'foobar' },
virtual_ipaddress: %w(2605:bc80:3010:103::8cd3:ff4/64)
)
end
end
end
end
| 33.144444 | 119 | 0.598056 |
912f3684168e0277db256f74f2e3724344d62786 | 355 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'abbyy'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
end
| 27.307692 | 69 | 0.721127 |
f7fdbc431204337f0eec3fffd095429feca7abf4 | 294 | module Spree::ShippingMethodDecorator
def self.prepended(base)
base.translates :name, fallbacks_for_empty_translations: true, versioning: :paper_trail
end
Spree::ShippingMethod.include SpreeGlobalize::Translatable
end
::Spree::ShippingMethod.prepend(Spree::ShippingMethodDecorator)
| 29.4 | 91 | 0.819728 |
284d712964c163e34671ffbd1dec6ee983f5704e | 2,989 | require 'rails_helper'
RSpec.describe '/accounts', type: :request do
let(:user) { create(:user, :with_accounts) }
let(:account) { user.accounts.first }
before do
sign_in user
end
describe 'GET /index' do
it 'renders a successful response' do
get accounts_url
expect(response).to be_successful
expect(response.body).to include(account.name)
end
end
describe 'GET /show' do
it 'renders a successful response' do
get account_url(account)
expect(response).to be_successful
expect(response.body).to include(account.name)
end
end
describe 'GET /new' do
it 'renders a successful response' do
get new_account_url
expect(response).to be_successful
end
end
describe 'GET /edit' do
it 'render a successful response' do
get edit_account_url(account)
expect(response).to be_successful
end
end
describe 'POST /create' do
let(:valid_attributes) do
{
name: Faker::Lorem.word,
note: Faker::Lorem.sentence,
balance: Faker::Number.number(digits: 4)
}
end
let(:invalid_attributes) do
{
title: Faker::Lorem.word,
user: user
}
end
context 'with valid parameters' do
it 'creates a new Account' do
expect do
post accounts_url, params: { account: valid_attributes }
end.to change(Account, :count).by(1)
end
it 'redirects to the created account' do
post accounts_url, params: { account: valid_attributes }
expect(response).to redirect_to(account_url(Account.last))
end
end
context 'with invalid parameters' do
it 'does not create a new Account' do
expect do
post accounts_url, params: { account: invalid_attributes }
end.to change(Account, :count).by(0)
end
it "renders a successful response (i.e. to display the 'new' template)" do
post accounts_url, params: { account: invalid_attributes }
expect(response).to be_successful
end
end
end
describe 'PATCH /update' do
let(:new_attributes) do
{
name: Faker::Lorem.word,
note: Faker::Lorem.sentence,
balance: Faker::Number.number(digits: 4)
}
end
it 'updates the requested account' do
patch account_url(account), params: { account: new_attributes }
account.reload
expect(account.name).to eq(new_attributes[:name])
end
it 'redirects to the account' do
patch account_url(account), params: { account: new_attributes }
account.reload
expect(response).to redirect_to(account_url(account))
end
end
describe 'DELETE /destroy' do
it 'destroys the requested account' do
expect { delete account_url(account) }.to change(Account, :count).by(-1)
end
it 'redirects to the accounts list' do
delete account_url(account)
expect(response).to redirect_to(accounts_url)
end
end
end
| 25.767241 | 80 | 0.645366 |
bb2a661a54b49bc71865f668bff66c5bb9e4e923 | 788 | require "rails_helper"
RSpec.describe AccidentOrIncidentTypeForm, :with_stubbed_opensearch, :with_test_queue_adapter do
# Default set of valid attributes
let(:type) { "Accident" }
let(:params) do
{
type: type
}
end
let(:form) { described_class.new(params) }
describe "validations" do
context "with valid attributes" do
let(:type) { "Accident" }
it "is valid" do
expect(form).to be_valid
end
end
context "when missing type" do
let(:type) { nil }
it "is not valid" do
expect(form).not_to be_valid
end
end
context "when type is not `accident` or `incident`" do
let(:type) { "disaster" }
it "is not valid" do
expect(form).not_to be_valid
end
end
end
end
| 19.7 | 96 | 0.615482 |
ff2e2150fcbd7bb26777b85c8ed3d94252705b6e | 180 | class RemoveFileFromPassagesAndArtifacts < ActiveRecord::Migration[5.2]
def change
remove_column :artifacts, :file, :file
remove_column :passages, :file, :file
end
end
| 25.714286 | 71 | 0.755556 |
28585ca85a820bb6561c5aa10807d696efa85646 | 139 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_fifabot_session'
| 34.75 | 77 | 0.805755 |
ffc6d839295752d7ffc12ea99c7bbeb4d2406697 | 1,488 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bomdb/version'
Gem::Specification.new do |spec|
spec.name = "bomdb"
spec.version = BomDB::VERSION
spec.authors = ["Duane Johnson"]
spec.email = ["[email protected]"]
spec.summary = %q{Book of Mormon Database}
spec.description = %q{A command-line queryable database of multiple editions of the Book of Mormon}
spec.homepage = "http://bomdb.wordtree.org"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject{ |f| f =~ %r|data/.*\.json| }
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.bindir = "bin"
spec.add_dependency 'sequel', '~> 4.49'
spec.add_dependency 'sqlite3', '~> 1.4'
spec.add_dependency 'thor', '~> 0.20'
spec.add_dependency 'constellation', '~> 0.1'
spec.add_dependency 'colorize', '~> 0.7'
spec.add_dependency 'text_clean', '~> 0'
spec.add_dependency 'levenshtein-ffi', '~> 1.1'
spec.add_dependency 'mericope', '~> 0.3'
# spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'byebug', '~> 4.0'
spec.add_development_dependency 'rspec', '~> 3.2'
end
| 41.333333 | 103 | 0.62164 |
5da7803e09d9f8a3ea4e75dc737dc5356f3cff2a | 628 | require "knife_spec_helper"
describe Chef::Knife::TagList do
before(:each) do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::TagList.new
@knife.name_args = [ Chef::Config[:node_name], "sadtag" ]
@node = Chef::Node.new
allow(@node).to receive :save
@node.tags << "sadtag" << "happytag"
allow(Chef::Node).to receive(:load).and_return @node
end
describe "run" do
it "can list tags on a node" do
expected = %w{sadtag happytag}
expect(@node.tags).to eq(expected)
expect(@knife).to receive(:output).with(expected)
@knife.run
end
end
end
| 26.166667 | 61 | 0.643312 |
6190dd5bc046a8ea66816502d7c1f221dccdad77 | 511 | require 'ebay_trading/types/store_vacation_preferences'
module EbayTrading # :nodoc:
module Types # :nodoc:
# == Attributes
# object_node :vacation_preferences, 'VacationPreferences', :class => StoreVacationPreferences, :optional => true
class StorePreferences
include XML::Mapping
include Initializer
root_element_name 'StorePreferences'
object_node :vacation_preferences, 'VacationPreferences', :class => StoreVacationPreferences, :optional => true
end
end
end
| 30.058824 | 118 | 0.739726 |
28cf795afab5a2f5110d9740b2cc7cb111321bb3 | 7,350 | # frozen_string_literal: true
require 'logger'
require 'memoize'
require 'obj'
require 'travis/yml/helper/obj'
Obj.include Memoize, Travis::Yml::Helper::Obj
require 'json'
require 'travis/yml/config'
require 'travis/yml/configs'
require 'travis/yml/errors'
require 'travis/yml/doc'
require 'travis/yml/docs'
require 'travis/yml/parts'
require 'travis/yml/matrix'
require 'travis/yml/schema'
require 'travis/yml/support/yaml'
Integer = Fixnum unless defined?(Integer) # Ruby 2.4
module Travis
module Yml
DEFAULTS = {
language: 'ruby',
os: 'linux'
}
# These exist so we can parametrize things a little for testing (e.g. so
# tests don't break elsewhere just because a default has changed here).
OPTS = {
alert: true, # alert on secures that accept a string
defaults: true, # add defaults to required keys
empty: false, # warn on empty keys
fix: true, # try fixing unknown keys and values
line: true, # add line numbers to messages
support: false, # warn about features unsupported on the given language, os etc
drop: false, # drop unknown keys and values, invalid conditions, and values missing required keys
merge_normalized: false # whether to normalize configs before merging
}
# These are meant as examples. Clients will want to determine their own
# representations.
MSGS = {
alias_key: 'the key %{alias} is an alias for %{key}, using %{key}',
alias_value: 'the value %{alias} is an alias for %{value}, using %{value}',
overwrite: 'both %{key} and %{other} given. %{key} overwrites %{other}',
default: 'missing %{key}, using the default %<default>p',
deprecated: 'deprecated: %{info}',
deprecated_key: 'deprecated key: %<key>p (%{info})',
deprecated_value: 'deprecated value: %<value>p (%{info})',
downcase: 'using lower case of %{value}',
duplicate: 'duplicate values: %{values}',
duplicate_key: 'duplicate key: %{key}',
edge: 'this key is experimental and might change or be removed',
flagged: 'please email [email protected] to enable %<key>p',
required: 'missing required key: %{key}',
secure: 'expected an encrypted string',
empty: 'dropping empty key: %{key}',
find_key: 'key %{original} is not known, but %{key} is, using %{key}',
find_value: 'value %{original} is not known, but %{value} is, using %{value}',
clean_key: 'key %{original} contains unsupported characters, using %{key}',
clean_value: 'value %{original} is not known, but %{value} is, using %{value}',
strip_key: 'key %{original} contains whitespace, using %{key}',
underscore_key: 'key %{original} is not underscored, using %{key}',
unexpected_seq: 'unexpected sequence, using the first value (%{value})',
unknown_key: 'unknown key %<key>p (%{value})',
unknown_value: 'dropping unknown value: %{value}',
unknown_var: 'unknown template variable %<var>p',
unsupported: '%{key} (%{value}) is not supported on %{on_key} %{on_value}',
invalid_type: 'dropping unexpected %{actual}, expected %{expected} (%{value})',
invalid_secure: 'invalid value on secure string: %{value}',
invalid_format: 'dropping invalid format %{value}',
invalid_condition: 'invalid condition: %{condition} (%{message})',
invalid_env_var: 'invalid env var: %{var}',
invalid_ref: 'invalid import reference: %s',
skip_allow_failure: 'skipping jobs allow failure rule #%{number} because its condition does not match: %{condition}',
skip_exclude: 'skipping jobs exclude rule #%{number} because its condition does not match: %{condition}',
skip_import: 'skipping import %{source} because its condition does not match: %{condition}',
skip_job: 'skipping job #%{number} because its condition does not match: %{condition}',
skip_notification: 'skipping notification %{type} #%{number}, condition does not match: %{condition}',
skip_stage: 'skipping stage #%{number} because its condition does not match: %{condition}',
invalid_ownership: 'Cannot import a private config file from another owner (%s)',
invalid_visibility: 'Private repo %s referenced from a public repo',
import_not_allowed: 'importing from private repo %{repo} is not allowed as per its settings',
too_many_imports: 'Too many imports, max: %{max}',
unknown_import: 'import not found: %{source}'
}
class << self
include Memoize
def metrics
@metrics ||= Travis::Metrics.setup(config.metrics.to_h, logger)
end
def config
@config ||= Config.load
end
def logger
@logger ||= Logger.new($stdout)
end
def load(parts, opts = {})
apply(Parts.load(parts), opts)
end
def expand
bench { Doc::Schema.build(schema) }
end
memoize :expand
def schema
Schema.json
end
memoize :schema
def write
File.write('schema.json', JSON.pretty_generate(schema))
end
def apply(value, opts = {})
invalid_format unless value.is_a?(Hash)
opts = OPTS.merge(opts) unless ENV['ENV'] == 'test'
node = Doc.apply(expand, value, opts)
node
end
def matrix(config)
config, data = config.values_at(:config, :data) if config[:config]
Matrix.new(config, data)
end
def configs(*args)
Configs.new(*args)
end
def msg(msg)
level, key, code, args = msg
msg = MSGS[code] || raise(UnknownMessage, 'Unknown message %p' % code)
msg = msg % args if args
msg = '[%s] on %s: %s' % [level, key, msg]
msg = msg.sub('()', '')
msg
rescue KeyError => e
msg = "unable to generate message (level: %s, key: %s, code: %s, args: %s)" % [level, key, code, args]
Raven.capture_message(msg) if defined?(Raven)
msg
end
def keys
@keys ||= expand.all_keys - r_keys
end
# R's known keys on root should definitely be reduced
def r_keys
%w(
r_packages
r_binary_packages
r_github_packages
apt_packages
bioc_packages
brew_packages
bioc
bioc_check
bioc_required
bioc_use_devel
cran
disable_homebrew
latex
pandoc
pandoc_version
r_build_args
r_check_args
r_check_revdep
warnings_are_errors
remotes
repos
)
end
memoize :r_keys
def expand_keys
expand.expand_keys - [:jobs] # TODO
end
def invalid_format
raise InvalidConfigFormat, 'Input must parse into a hash'
end
def bench(key = nil)
now = Time.now
yield.tap do
puts "Schema.#{(key || caller[2][/`(.*)'/] && $1).to_s.ljust(6)} took #{Time.now - now} sec"
end
end
end
end
end
| 36.029412 | 123 | 0.59415 |
7a0f37ca26f99ddf17782dbcd8d45d417b8b4c37 | 1,304 | require 'orel'
require 'stringio'
Orel.logger = Logger.new(File.dirname(__FILE__) + "/../../log/test.log")
Orel.logger.info "\n\nBeginning test #{Time.now}\n"
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => 'orel_test',
:username => 'root'
)
module Orel
module Test
def self.connection
@connection ||= Orel::Connection.new(Orel::AR)
end
# Print '---' before and after the block is executed.
def self.wrap
puts '---'
yield
puts '---'
end
# Print '---' before and after the block is executed,
# and also sort anything written to stdout within the
# block. This is to deal with the fact that relations
# are not ordered, but we need ordered output to
# check with simple string comparisons.
def self.wrap_and_sort
puts '---'
out = $stdout
str = String.new
begin
$stdout = StringIO.new(str)
yield
ensure
$stdout = out
str.split("\n").sort.each { |line|
puts line
}
end
puts '---'
end
# Print '---' before and after the results of
# a sql query.
def self.show(*args)
wrap {
connection.query(*args).each { |row|
puts row.join(',')
}
}
end
end
end
| 22.101695 | 72 | 0.575153 |
33b70d5f57f44c19dfb13d9191818bf714f9ad77 | 1,457 | class Newlisp < Formula
desc "Lisp-like, general-purpose scripting language"
homepage "http://www.newlisp.org/"
url "http://www.newlisp.org/downloads/newlisp-10.7.5.tgz"
sha256 "dc2d0ff651c2b275bc4af3af8ba59851a6fb6e1eaddc20ae75fb60b1e90126ec"
bottle do
sha256 arm64_big_sur: "24b3c02002fa7c832d9a817c552b19bd520ae06f82ab526b8e993ae0a3d77d99"
sha256 big_sur: "509f6892a0eabf53cebe424f2f2163ded090b7942e8fe8e43047f43781b0535e"
sha256 catalina: "62fd116459d24ab0db976221fb16fd83a7a7db5447298bcc7f8b0dbf9a55f91f"
sha256 mojave: "179146b49c20011f3da4dbdb9b66a6ed66d5dd9f15d07aeca9b8717219a62eeb"
sha256 high_sierra: "5a0d4085a0e7fc364b3165be7e92a9dfeb2f4882e1971663ac74c70348a5c4a4"
sha256 x86_64_linux: "cf8de711e794fa5b226a3bca90f3200e2ecfbb5917e8a3e9f3fee10c8bad505f"
end
depends_on "readline"
def install
# Required to use our configuration
ENV.append_to_cflags "-DNEWCONFIG -c"
system "./configure-alt", "--prefix=#{prefix}", "--mandir=#{man}"
system "make"
system "make", "check"
system "make", "install"
end
def caveats
<<~EOS
If you have brew in a custom prefix, the included examples
will need to be be pointed to your newlisp executable.
EOS
end
test do
path = testpath/"test.lsp"
path.write <<~EOS
(println "hello")
(exit 0)
EOS
assert_equal "hello\n", shell_output("#{bin}/newlisp #{path}")
end
end
| 32.377778 | 92 | 0.738504 |
62077bb7185d0090191bb2bfe74a55498181bcde | 7,577 | require "rails_helper"
describe Courses::GenerateCourseNameService do
let(:service) { described_class.new }
let(:subjects) { [] }
let(:is_send) { false }
let(:level) { "primary" }
let(:course) { Course.new(level: level, subjects: subjects, is_send: is_send) }
let(:modern_languages) { find_or_create(:secondary_subject, :modern_languages) }
let(:generated_title) { service.execute(course: course) }
before do
SecondarySubject.clear_modern_languages_cache
modern_languages
end
shared_examples "with SEND" do
context "With SEND" do
let(:is_send) { true }
it "Appends SEND information to the title" do
expect(generated_title).to end_with(" (SEND)")
end
end
end
context "With no subjects" do
it "Returns an empty string" do
expect(generated_title).to eq("")
end
end
context "Generating a title for a further education course" do
let(:level) { "further_education" }
it "returns 'Further education'" do
expect(generated_title).to eq("Further education")
end
include_examples "with SEND"
end
context "Generating a title for non-further education course" do
let(:level) { "primary" }
context "With a single subject" do
let(:subjects) { [Subject.new(subject_name: "Physical education")] }
it "Returns the subject name" do
expect(generated_title).to eq("Physical education")
end
include_examples "with SEND"
end
context "With multiple subjects" do
let(:subjects) { [find_or_create(:secondary_subject, :physics), find_or_create(:secondary_subject, :english)] }
it "Returns a name containing both subjects in the order they were given" do
expect(generated_title).to eq("Physics with English")
end
include_examples "with SEND"
end
context "With modern languages" do
context "with one language" do
let(:subjects) { [modern_languages, find_or_create(:modern_languages_subject, :french)] }
it "Returns a name modern language with language" do
expect(generated_title).to eq("Modern Languages (French)")
end
include_examples "with SEND"
end
context "with two languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :french),
find_or_create(:modern_languages_subject, :german),
]
end
it "Returns a name modern language with both languages" do
expect(generated_title).to eq("Modern Languages (French and German)")
end
include_examples "with SEND"
end
context "with three languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :french),
find_or_create(:modern_languages_subject, :german),
find_or_create(:modern_languages_subject, :japanese),
]
end
it "Returns a name modern language with three languages" do
expect(generated_title).to eq("Modern Languages (French, German, Japanese)")
end
include_examples "with SEND"
end
context "with four or more languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :french),
find_or_create(:modern_languages_subject, :german),
find_or_create(:modern_languages_subject, :japanese),
find_or_create(:modern_languages_subject, :spanish),
]
end
it "Returns just modern languages" do
expect(generated_title).to eq("Modern Languages")
end
include_examples "with SEND"
end
end
context "Names which require altering" do
context "Communications and media studies -> Media studies" do
context "With single subject" do
let(:subjects) do
[find_or_create(:secondary_subject, :communication_and_media_studies)]
end
it "Returns the title Media studies" do
expect(generated_title).to eq("Media studies")
end
end
context "With multiple subjects" do
let(:subjects) do
[
find_or_create(:secondary_subject, :communication_and_media_studies),
find_or_create(:secondary_subject, :mathematics),
]
end
it "Returns the title Media studies" do
expect(generated_title).to eq("Media studies with Mathematics")
end
end
end
context "English as a second language -> English" do
context "With a single language" do
let(:subjects) do
[modern_languages, find_or_create(:modern_languages_subject, :english_as_a_second_lanaguge_or_other_language)]
end
it "Returns the title Modern Languages (English)" do
expect(generated_title).to eq("Modern Languages (English)")
end
end
context "With two languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :english_as_a_second_lanaguge_or_other_language),
find_or_create(:modern_languages_subject, :spanish),
]
end
it "Returns the title Modern Languages (English and Spanish)" do
expect(generated_title).to eq("Modern Languages (English and Spanish)")
end
end
context "With three languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :english_as_a_second_lanaguge_or_other_language),
find_or_create(:modern_languages_subject, :french),
find_or_create(:modern_languages_subject, :spanish),
]
end
it "Returns the title Modern Languages (English, French, Spanish)" do
expect(generated_title).to eq("Modern Languages (English, French, Spanish)")
end
end
end
context "Modern Languages (Other) -> Should be ignored for the title" do
context "With a single language" do
let(:subjects) do
[modern_languages, find_or_create(:modern_languages_subject, :modern_languages_other)]
end
it "Returns the title Modern Languages" do
expect(generated_title).to eq("Modern Languages")
end
end
context "With two languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :modern_languages_other),
find_or_create(:modern_languages_subject, :spanish),
]
end
it "Returns the title Modern Languages (Spanish)" do
expect(generated_title).to eq("Modern Languages (Spanish)")
end
end
context "With three languages" do
let(:subjects) do
[
modern_languages,
find_or_create(:modern_languages_subject, :modern_languages_other),
find_or_create(:modern_languages_subject, :french),
find_or_create(:modern_languages_subject, :spanish),
]
end
it "Returns the title Modern Languages (French and Spanish)" do
expect(generated_title).to eq("Modern Languages (French and Spanish)")
end
end
end
end
end
end
| 31.702929 | 122 | 0.623334 |
793095a5a3be596253ecbce7563047a99dcf4102 | 729 | #
# Copyright:: Copyright (c) 2012 Opscode, Inc.
# Copyright:: Copyright (c) 2014 GitLab.com
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
runit_service 'redis' do
action :disable
end
| 33.136364 | 74 | 0.748971 |
11434573b9397147b1169e64ece31c7b7b46050d | 269 | class Texmacs < Cask
version '1.99.1'
sha256 'b6aab5bcb263e847c97062824b8852380cab4159306b035fcca199f92d243d51'
url "http://www.texmacs.org/Download/ftp/tmftp/macos/TeXmacs-#{version}.dmg"
homepage 'http://www.texmacs.org/'
app "TeXmacs-#{version}.app"
end
| 26.9 | 78 | 0.754647 |
bb069ccd57990f172dcba99eb18565b5e105e5c5 | 1,415 | shared_examples 'ports::portmap' do
context 'portmap/rpcbind' do
describe port(111) do
it { should be_listening.with('tcp') }
it { should be_listening.with('udp') }
end
end
end
shared_examples 'services::portmap' do
context 'portmap/rpcbind' do
name = 'rpcbind'
check_enabled = true
check_running = true
# RHEL/CentOS
if os[:family] == 'redhat'
name = 'portmap' if host_inventory[:platform_version].to_i <= 5
if host_inventory[:platform_version].to_f >= 7.1
name = 'rpcbind'
# Due to lazy-starting services, this needs a kick to wake up
describe command("systemctl start #{name}") do
its(:exit_status) { should eq 0 }
end
check_enabled = false
end
elsif os[:family] == 'amazon'
name = 'rpcbind'
elsif %w(debian ubuntu).include?(os[:family])
# Ubuntu
if host_inventory[:platform_version].to_i >= 12 &&
host_inventory[:platform_version].to_i <= 13
name = 'rpcbind-boot'
check_running = false
elsif host_inventory[:platform_version].to_i <= 6
name = 'portmap'
else
name = 'rpcbind'
end
end
describe service(name) do
it { should be_enabled } if check_enabled
it { should be_running } if check_running
end unless name == ''
include_examples 'ports::portmap' # unless name == ''
end
end
| 27.745098 | 69 | 0.619081 |
d5196d9eb72b0da0868bb9d3b915be45d38f8ecf | 476 | # pass a response object to the controller to set
# header status and content.
module Blix::Rest
class Response
attr_accessor :status
attr_reader :headers
attr_accessor :content
def initialize
@status = 200
@headers = {}
@content = nil
end
def set(status,content=nil,headers=nil)
@status = status if status
@content = String.new(content) if content
@headers.merge!(headers) if headers
end
end
end
| 17.62963 | 49 | 0.647059 |
ab389cf85f8442cf65c380172c8a9d3681967663 | 240 | module Contacts
class Engine < ::Rails::Engine
isolate_namespace Contacts
config.to_prepare do
Dir.glob(Rails.root + "app/decorators/**/*_decorator*.rb").each do |c|
require_dependency(c)
end
end
end
end
| 21.818182 | 76 | 0.658333 |
6a66e81a78ad4904f397aaecc11fce85bc028286 | 982 | # Copyright 2011-2019, The Trustees of Indiana University and Northwestern
# University. 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 LICENSE_HEADER BLOCK ---
module FedoraMigrate
module MasterFile
class MhMetadataDatastreamMover < FedoraMigrate::SimpleXmlDatastreamMover
def fields_to_copy
%w(workflow_id workflow_name percent_complete percent_succeeded percent_failed status_code operation error encoder_classname)
end
end
end
end
| 40.916667 | 133 | 0.768839 |
1ab1e617485d4d2c2e5b5265c8ea24ce768c7c90 | 3,172 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should not be too long" do
@user.name = "a" * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
valid_addresses = %w[[email protected] [email protected] [email protected] [email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test "email validation should reject invalid addresses" do
invalid_addresses = %w[user@example,com USER.foo.COM [email protected]. first.last@foo_bar.jp alice+bob@baz+biz.cn]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "email address should be saved as lower-case" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?(:remember, '')
end
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
test "should follow and unfollow a user" do
michael = users(:michael)
archer = users(:archer)
assert_not michael.following?(archer)
michael.follow(archer)
assert michael.following?(archer)
assert archer.followers.include?(michael)
michael.unfollow(archer)
assert_not michael.following?(archer)
end
test "feed should have the right posts" do
michael = users(:michael)
archer = users(:archer)
lana = users(:lana)
lana.microposts.each do |p|
assert michael.feed.include?(p)
end
michael.microposts.each do |p|
assert michael.feed.include?(p)
end
archer.microposts.each do |p|
assert_not michael.feed.include?(p)
end
end
end
| 27.824561 | 117 | 0.672446 |
263f829f576ac9cda9e708424558f488045f1dd0 | 2,181 | require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
@user = users(:michael)
@other_user = users(:archer)
end
test "should redirect index when not logged in" do
get users_path
assert_redirected_to login_url
end
test "should get new" do
get signup_path
assert_response :success
assert_select "title", "Sign up | #{@base_title}"
end
test "should redirect edit when not logged in" do
get edit_user_path(@user)
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect update when not logged in" do
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert_not flash.empty?
assert_redirected_to login_url
end
test "should not allow the admin attribute to be edited via the web" do
log_in_as(@other_user)
assert_not @other_user.admin?
patch user_path(@other_user), params: {
user: { password: "password",
password_confirmation: "password",
admin: 1 } }
assert_not @other_user.reload.admin?
end
test "should redirect edit when logged in as wrong user" do
log_in_as(@other_user)
get edit_user_path(@user)
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect update when logged in as wrong user" do
log_in_as(@other_user)
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to login_url
end
test "should redirect destroy when logged in as a non-admin" do
log_in_as(@other_user)
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to root_url
end
end
| 29.08 | 78 | 0.640532 |
2656ce5d13980334d0e15819f413d2b576594b2f | 127 | json.extract! client, :id, :name, :address, :phone_number, :created_at, :updated_at
json.url client_url(client, format: :json)
| 42.333333 | 83 | 0.748031 |
f798f32b2cd8f0e616e7adc32af83064f80a9a14 | 544 | cask 'virtualhostx' do
version '8.7.13,80_62'
sha256 'd5dbb0dbbb7e4c5c6d13da6fd538358a717944dbd962273ac47796ae6c963c77'
# downloads-clickonideas.netdna-ssl.com/virtualhostx was verified as official when first introduced to the cask
url "https://downloads-clickonideas.netdna-ssl.com/virtualhostx/virtualhostx#{version.after_comma}.zip"
appcast 'https://shine.clickontyler.com/appcast.php?id=38'
name 'VirtualHostX'
homepage 'https://clickontyler.com/virtualhostx/'
depends_on macos: '>= :sierra'
app 'VirtualHostX.app'
end
| 36.266667 | 113 | 0.786765 |
f7d530cfb5054de5f6c318695c3b547adbd70443 | 1,456 | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "lib"))
require "active_record_extended/version"
Gem::Specification.new do |spec|
spec.name = "active_record_extended"
spec.version = ActiveRecordExtended::VERSION
spec.authors = ["George Protacio-Karaszi", "Dan McClain", "Olivier El Mekki"]
spec.email = ["[email protected]", "[email protected]", "[email protected]"]
spec.summary = "Adds extended functionality to Activerecord Postgres implementation"
spec.description = "Adds extended functionality to Activerecord Postgres implementation"
spec.homepage = "https://github.com/georgekaraszi/ActiveRecordExtended"
spec.license = "MIT"
spec.files = Dir["README.md", "lib/**/*"]
spec.test_files = `git ls-files -- spec/*`.split("\n")
spec.require_paths = ["lib"]
spec.required_ruby_version = ">= 2.4"
spec.add_dependency "activerecord", ">= 5.1", "< 7.1.0"
spec.add_dependency "ar_outer_joins", "~> 0.2"
spec.add_dependency "pg", "< 3.0"
spec.add_development_dependency "bundler", ">= 1.16", "< 3.0"
spec.add_development_dependency "database_cleaner", "~> 1.6"
spec.add_development_dependency "rake", ">= 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "simplecov", "~> 0.16"
end
| 44.121212 | 104 | 0.648352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.