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
|
---|---|---|---|---|---|
28cdb898f8a1ab4211c4cdd1e77d34da24080dbb | 1,154 | class Ascii < Formula
desc "List ASCII idiomatic names and octal/decimal code-point forms"
homepage "http://www.catb.org/~esr/ascii/"
url "http://www.catb.org/~esr/ascii/ascii-3.18.tar.gz"
sha256 "728422d5f4da61a37a17b4364d06708e543297de0a5f70305243236d80df072d"
bottle do
cellar :any_skip_relocation
sha256 "d5f4c8fe4ad1467c1708e49268a42f0d201f8c18ed912cf3de330bdf1f219cc1" => :mojave
sha256 "858e5bd8f55367349f936f47346a7d4dc2afed7c8f3d9fca16c42071f537f644" => :high_sierra
sha256 "52fb2a78a1409f4f6db0b59589f773c4427c87a84a7fee1809e5f0a4d50e4d65" => :sierra
sha256 "bbb5f365f96e42dfaa8af31f21daa8809b0a628451599fab7bc7509ceeb0d14f" => :el_capitan
sha256 "ab520ebbe64a946a0ac0466537a0e207e49cd85979e41582ab542dcaef9db3ff" => :yosemite
end
head do
url "https://gitlab.com/esr/ascii.git"
depends_on "xmlto" => :build
end
def install
ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog" if build.head?
bin.mkpath
man1.mkpath
system "make"
system "make", "PREFIX=#{prefix}", "install"
end
test do
assert_match "Official name: Line Feed", shell_output(bin/"ascii 0x0a")
end
end
| 34.969697 | 93 | 0.760832 |
114a124d43a132c575b9edaaafa19a7c38087ca0 | 1,925 | Rails.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
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}"
}
# 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
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.url = "http://localhost:3000"
Paperclip::Attachment.default_options[:path] = "#{Rails.root}/test/test_files/:class/:id_partition/:style.:extension"
end
| 42.777778 | 119 | 0.769351 |
ab064986317144f0edff3e03bf2cb3b00215414b | 1,370 | module Admin
class BaseAdminController < ApplicationController
include AdminSessionTimeout
layout "admin"
before_action :end_expired_admin_sessions, :ensure_authenticated_user
after_action :update_last_seen_at
helper_method :admin_signed_in?, :admin_timeout_in_minutes, :service_operator_signed_in?
private
def ensure_authenticated_user
unless admin_signed_in?
session[:requested_admin_path] = request.fullpath
redirect_to admin_sign_in_path
end
end
def admin_user
@admin_user ||= DfeSignIn::User.find(session[:user_id])
end
def service_operator_signed_in?
admin_user.is_service_operator?
end
def payroll_operator_signed_in?
admin_user.is_payroll_operator?
end
def support_agent_signed_in?
admin_user.is_support_agent?
end
def ensure_service_team
render "admin/auth/failure", status: :unauthorized unless service_operator_signed_in? || support_agent_signed_in?
end
def ensure_service_operator
render "admin/auth/failure", status: :unauthorized unless service_operator_signed_in?
end
def ensure_payroll_operator
render "admin/auth/failure", status: :unauthorized unless payroll_operator_signed_in?
end
def update_last_seen_at
session[:admin_last_seen_at] = Time.zone.now
end
end
end
| 25.849057 | 119 | 0.745985 |
f83be87616aad35b32344b1810ac10e6f0b0da6a | 2,432 | # encoding: UTF-8
#
# Author:: Xabier de Zuazo (<[email protected]>)
# Copyright:: Copyright (c) 2015 Onddo Labs, SL.
# 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 'spec_helper'
describe file('/home/bob/.ssh') do
it { should be_directory }
it { should be_owned_by 'bob' }
it { should be_grouped_into 'bob' }
it { should be_mode 700 }
end
content = [
'# Generated by Chef',
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP+u3R2+C0nD4VgsRgN9rOiz'\
'D2ePBrf8508VR5envsmEY5oF+TM3k/wb2xBY45KXOu9yQjQi9RcCYvrCAu3wPTrx07vRetkDIvs'\
'/O383zQQanrHMGckNzh83uwDU4JcJqBP2EwkTMUqlk6xyrGuQyjmWFKWjjUUkmHFII5azAh+9bp'\
'4OjULE9h9fy4Y3ZOxHMrHuC5AjkWhvy88ItmGBf0sj0iW0893UVrzdfB20dz+G9pM2lE5NK/b/z'\
'fF7UlIjgI9oR9w2+YaNZE/fmuHpH94Gx/Ptlwxb2tmdEReA8DPsnHMIML3ltcpJrwgVdTJEAAz1'\
'JnARx [email protected]',
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/N6jNVB8vZLzexKbkq2bXPR'\
'KUakmf8qrSQI9Bl1C8+6//uKpe909DrZzEkJzPC9BgpNnWtJ25SxHogKb1SybAk0OFc61X7wl1k'\
'noo+OcuW6Moi0vpNiUGy2VnM0nyecLoQxggvnj1392uoMdS4VY71PGdcBac7p9IwAwYxlsuFEKR'\
'cfKisJAHDEblgSFyC9lLMMjTSxxKn8s5AaR1h+Lb3Kwibd7ikvIgYRybTbD12FtQRxuWZBVm39C'\
'M3539gT6514IaYyYVDyIEFDyGjK2UV27ah56jMaRFGX4IIh2gH5P2XaV7As5p8RPYoWwf+pCz19'\
'mrPd/ [email protected] comment'
].join("\n") << "\n"
describe file('/home/bob/.ssh/authorized_keys') do
it { should be_file }
it { should be_owned_by 'bob' }
it { should be_grouped_into 'bob' }
it { should be_mode 600 }
its(:content) { should eq content }
end
describe file('/home/bob2/.ssh') do
it { should be_directory }
it { should be_owned_by 'bob2' }
it { should be_grouped_into 'bob2' }
it { should be_mode 700 }
end
describe file('/home/bob2/.ssh/authorized_keys') do
it { should be_file }
it { should be_owned_by 'bob2' }
it { should be_grouped_into 'bob2' }
it { should be_mode 600 }
its(:content) { should eq content }
end
| 36.298507 | 80 | 0.765214 |
87793a24ee646410789b360055a3d64ed1180ccd | 44 | module ArduinoStrip
VERSION = '0.1.0'
end
| 11 | 19 | 0.704545 |
18a30cd97a0b5c2ffc5ab5ac421b8f0699440355 | 1,449 | require 'pry'
=begin
Multiply All Pairs
Write a method that takes two Array arguments in which each Array contains a
list of numbers, and returns a new Array that contains the product of every
pair of numbers that can be formed between the elements of the two Arrays. The
results should be sorted by increasing value.
You may assume that neither argument is an empty Array.
Examples:
multiply_all_pairs([2, 4], [4, 3, 1, 2]) == [2, 4, 4, 6, 8, 8, 12, 16]
- Understand the problem
- Input
- Two Array of numbers
- Output
- New Array of numbers that contains the product of every pair of numbers
that can be formed between the elements of the two Arrays.
- Rules
- You may assume that neither argument is an empty Array.
- The results should be sorted by increasing value.
- Examples
- Covered by examples
- Algorithm
1. Assign empty Array to `result`
2. Iterate over `array_1`
- Iterate over `array_2`
- Multiply `current_number_array_1` with `current_number_array_2`
- Add new number to `result`
3. Sort `result` by increasing value.
4. Return `result`
- Code
=end
def multiply_all_pairs(array_1, array_2)
result = []
array_1.each do |current_number_array_1|
array_2.each do |current_number_array_2|
result << current_number_array_1 * current_number_array_2
end
end
result.sort
end
puts multiply_all_pairs([2, 4], [4, 3, 1, 2]) == [2, 4, 4, 6, 8, 8, 12, 16]
| 25.421053 | 78 | 0.708075 |
39bf0d93f7a37a1fd9b9a1f5fef8a6c5b8ff9631 | 853 | module VolumesHelpers
def parse_volume(vol)
elements = vol.split(':')
if elements.size >= 2 # Bind mount or volume used
if elements[0].start_with?('/') && elements[1] && elements[1].start_with?('/') # Bind mount
{bind_mount: elements[0], path: elements[1], flags: elements[2..-1].join(',')}
elsif !elements[0].start_with?('/') && elements[1].start_with?('/') # Real volume
{volume: elements[0], path: elements[1], flags: elements[2..-1].join(',')}
else
raise ArgumentError, "Volume definition '#{vol}' not in right format"
end
elsif elements.size == 1 && elements[0].start_with?('/') # anon volume
{bind_mount: nil, path: elements[0], flags: nil} # anon vols do not support flags
else
raise ArgumentError, "Volume definition '#{vol}' not in right format"
end
end
end
| 40.619048 | 97 | 0.622509 |
b9c32bc51be5c8b6578e46643c3c270454841f8a | 14,049 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Ci::Config::Entry::Root do
let(:user) {}
let(:project) {}
let(:root) { described_class.new(hash, user: user, project: project) }
describe '.nodes' do
it 'returns a hash' do
expect(described_class.nodes).to be_a(Hash)
end
context 'when filtering all the entry/node names' do
it 'contains the expected node names' do
# No inheritable fields should be added to the `Root`
#
# Inheritable configuration can only be added to `default:`
#
# The purpose of `Root` is have only globally defined configuration.
expect(described_class.nodes.keys)
.to match_array(%i[before_script image services after_script
variables cache stages types include default workflow])
end
end
end
context 'when configuration is valid' do
context 'when top-level entries are defined' do
let(:hash) do
{
before_script: %w(ls pwd),
image: 'image:1.0',
default: {},
services: ['postgres:9.1', 'mysql:5.5'],
variables: { VAR: 'root', VAR2: { value: 'val 2', description: 'this is var 2' } },
after_script: ['make clean'],
stages: %w(build pages release),
cache: { key: 'k', untracked: true, paths: ['public/'] },
rspec: { script: %w[rspec ls] },
spinach: { before_script: [], variables: {}, script: 'spinach' },
release: {
stage: 'release',
before_script: [],
after_script: [],
variables: { 'VAR' => 'job' },
script: ["make changelog | tee release_changelog.txt"],
release: {
tag_name: 'v0.06',
name: "Release $CI_TAG_NAME",
description: "./release_changelog.txt"
}
}
}
end
context 'when deprecated types/type keywords are defined' do
let(:project) { create(:project, :repository) }
let(:user) { create(:user) }
let(:hash) do
{ types: %w(test deploy),
rspec: { script: 'rspec', type: 'test' } }
end
before do
root.compose!
end
it 'returns array of types as stages with a warning' do
expect(root.jobs_value[:rspec][:stage]).to eq 'test'
expect(root.stages_value).to eq %w[test deploy]
expect(root.warnings).to match_array([
"root `types` is deprecated in 9.0 and will be removed in 15.0.",
"jobs:rspec `type` is deprecated in 9.0 and will be removed in 15.0."
])
end
it 'logs usage of keywords' do
expect(Gitlab::AppJsonLogger).to(
receive(:info)
.with(event: 'ci_used_deprecated_keyword',
entry: root[:stages].key.to_s,
user_id: user.id,
project_id: project.id)
)
root.compose!
end
end
describe '#compose!' do
before do
root.compose!
end
it 'creates nodes hash' do
expect(root.descendants).to be_an Array
end
it 'creates node object for each entry' do
expect(root.descendants.count).to eq 11
end
it 'creates node object using valid class' do
expect(root.descendants.first)
.to be_an_instance_of Gitlab::Ci::Config::Entry::Default
expect(root.descendants.second)
.to be_an_instance_of Gitlab::Config::Entry::Unspecified
end
it 'sets correct description for nodes' do
expect(root.descendants.first.description)
.to eq 'Default configuration for all jobs.'
expect(root.descendants.second.description)
.to eq 'List of external YAML files to include.'
end
it 'sets correct variables value' do
expect(root.variables_value).to eq('VAR' => 'root', 'VAR2' => 'val 2')
end
describe '#leaf?' do
it 'is not leaf' do
expect(root).not_to be_leaf
end
end
end
context 'when composed' do
before do
root.compose!
end
describe '#errors' do
it 'has no errors' do
expect(root.errors).to be_empty
end
end
describe '#stages_value' do
context 'when stages key defined' do
it 'returns array of stages' do
expect(root.stages_value).to eq %w[build pages release]
end
end
end
describe '#jobs_value' do
it 'returns jobs configuration' do
expect(root.jobs_value.keys).to eq([:rspec, :spinach, :release])
expect(root.jobs_value[:rspec]).to eq(
{ name: :rspec,
script: %w[rspec ls],
before_script: %w(ls pwd),
image: { name: 'image:1.0' },
services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }],
stage: 'test',
cache: [{ key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }],
job_variables: {},
root_variables_inheritance: true,
ignore: false,
after_script: ['make clean'],
only: { refs: %w[branches tags] },
scheduling_type: :stage }
)
expect(root.jobs_value[:spinach]).to eq(
{ name: :spinach,
before_script: [],
script: %w[spinach],
image: { name: 'image:1.0' },
services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }],
stage: 'test',
cache: [{ key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }],
job_variables: {},
root_variables_inheritance: true,
ignore: false,
after_script: ['make clean'],
only: { refs: %w[branches tags] },
scheduling_type: :stage }
)
expect(root.jobs_value[:release]).to eq(
{ name: :release,
stage: 'release',
before_script: [],
script: ["make changelog | tee release_changelog.txt"],
release: { name: "Release $CI_TAG_NAME", tag_name: 'v0.06', description: "./release_changelog.txt" },
image: { name: "image:1.0" },
services: [{ name: "postgres:9.1" }, { name: "mysql:5.5" }],
cache: [{ key: "k", untracked: true, paths: ["public/"], policy: "pull-push", when: 'on_success' }],
only: { refs: %w(branches tags) },
job_variables: { 'VAR' => 'job' },
root_variables_inheritance: true,
after_script: [],
ignore: false,
scheduling_type: :stage }
)
end
end
end
end
context 'when a mix of top-level and default entries is used' do
let(:hash) do
{ before_script: %w(ls pwd),
after_script: ['make clean'],
default: {
image: 'image:1.0',
services: ['postgres:9.1', 'mysql:5.5']
},
variables: { VAR: 'root' },
stages: %w(build pages),
cache: { key: 'k', untracked: true, paths: ['public/'] },
rspec: { script: %w[rspec ls] },
spinach: { before_script: [], variables: { VAR: 'job' }, script: 'spinach' } }
end
context 'when composed' do
before do
root.compose!
end
describe '#errors' do
it 'has no errors' do
expect(root.errors).to be_empty
end
end
describe '#jobs_value' do
it 'returns jobs configuration' do
expect(root.jobs_value).to eq(
rspec: { name: :rspec,
script: %w[rspec ls],
before_script: %w(ls pwd),
image: { name: 'image:1.0' },
services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }],
stage: 'test',
cache: [{ key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }],
job_variables: {},
root_variables_inheritance: true,
ignore: false,
after_script: ['make clean'],
only: { refs: %w[branches tags] },
scheduling_type: :stage },
spinach: { name: :spinach,
before_script: [],
script: %w[spinach],
image: { name: 'image:1.0' },
services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }],
stage: 'test',
cache: [{ key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }],
job_variables: { 'VAR' => 'job' },
root_variables_inheritance: true,
ignore: false,
after_script: ['make clean'],
only: { refs: %w[branches tags] },
scheduling_type: :stage }
)
end
end
end
end
context 'when most of entires not defined' do
before do
root.compose!
end
let(:hash) do
{ cache: { key: 'a' }, rspec: { script: %w[ls] } }
end
describe '#nodes' do
it 'instantizes all nodes' do
expect(root.descendants.count).to eq 11
end
it 'contains unspecified nodes' do
expect(root.descendants.first)
.not_to be_specified
end
end
describe '#variables_value' do
it 'returns root value for variables' do
expect(root.variables_value).to eq({})
end
end
describe '#stages_value' do
it 'returns an array of root stages' do
expect(root.stages_value).to eq %w[.pre build test deploy .post]
end
end
describe '#cache_value' do
it 'returns correct cache definition' do
expect(root.cache_value).to eq([key: 'a', policy: 'pull-push', when: 'on_success'])
end
end
end
context 'when variables resembles script-type job' do
before do
root.compose!
end
let(:hash) do
{
variables: { script: "ENV_VALUE" },
rspec: { script: "echo Hello World" }
}
end
describe '#variables_value' do
it 'returns root value for variables' do
expect(root.variables_value).to eq("script" => "ENV_VALUE")
end
end
describe '#jobs_value' do
it 'returns one job' do
expect(root.jobs_value.keys).to contain_exactly(:rspec)
end
end
end
##
# When nodes are specified but not defined, we assume that
# configuration is valid, and we assume that entry is simply undefined,
# despite the fact, that key is present. See issue #18775 for more
# details.
#
context 'when entries are specified but not defined' do
before do
root.compose!
end
let(:hash) do
{ variables: nil, rspec: { script: 'rspec' } }
end
describe '#variables_value' do
it 'undefined entry returns a root value' do
expect(root.variables_value).to eq({})
end
end
end
end
context 'when configuration is not valid' do
before do
root.compose!
end
context 'when before script is a number' do
let(:hash) do
{ before_script: 123 }
end
describe '#valid?' do
it 'is not valid' do
expect(root).not_to be_valid
end
end
describe '#errors' do
it 'reports errors from child nodes' do
expect(root.errors)
.to include 'before_script config should be a string or a nested array of strings up to 10 levels deep'
end
end
end
context 'when job does not have commands' do
let(:hash) do
{ before_script: ['echo 123'], rspec: { stage: 'test' } }
end
describe '#errors' do
it 'reports errors about missing script or trigger' do
expect(root.errors)
.to include 'jobs rspec config should implement a script: or a trigger: keyword'
end
end
end
end
context 'when value is not a hash' do
let(:hash) { [] }
describe '#valid?' do
it 'is not valid' do
expect(root).not_to be_valid
end
end
describe '#errors' do
it 'returns error about invalid type' do
expect(root.errors.first).to match /should be a hash/
end
end
end
describe '#specified?' do
it 'is concrete entry that is defined' do
expect(root.specified?).to be true
end
end
describe '#[]' do
before do
root.compose!
end
let(:hash) do
{ cache: { key: 'a' }, rspec: { script: 'ls' } }
end
context 'when entry exists' do
it 'returns correct entry' do
expect(root[:cache])
.to be_an_instance_of Gitlab::Ci::Config::Entry::Caches
expect(root[:jobs][:rspec][:script].value).to eq ['ls']
end
end
context 'when entry does not exist' do
it 'always return unspecified node' do
expect(root[:some][:unknown][:node])
.not_to be_specified
end
end
end
end
| 32.148741 | 125 | 0.509218 |
acbda46ee2458b262d51395c15ccb492117a3355 | 1,614 | #! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'parseyaml function' do
describe 'success' do
it 'parses valid yaml' do
pp = <<-EOS
$a = "---\nhunter: washere\ntests: passing\n"
$o = parseyaml($a)
$tests = $o['tests']
notice(inline_template('tests are <%= @tests.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/tests are "passing"/)
end
end
end
describe 'failure' do
it 'returns the default value on incorrect yaml' do
pp = <<-EOS
$a = "---\nhunter: washere\ntests: passing\n:"
$o = parseyaml($a, {'tests' => 'using the default value'})
$tests = $o['tests']
notice(inline_template('tests are <%= @tests.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/tests are "using the default value"/)
end
end
it 'raises error on incorrect yaml' do
pp = <<-EOS
$a = "---\nhunter: washere\ntests: passing\n:"
$o = parseyaml($a)
$tests = $o['tests']
notice(inline_template('tests are <%= @tests.inspect %>'))
EOS
apply_manifest(pp, :expect_failures => true) do |r|
expect(r.stderr).to match(/(syntax error|did not find expected key)/)
end
end
it 'raises error on incorrect number of arguments' do
pp = <<-EOS
$o = parseyaml()
EOS
apply_manifest(pp, :expect_failures => true) do |r|
expect(r.stderr).to match(/wrong number of arguments/i)
end
end
end
end
| 27.355932 | 77 | 0.586121 |
03a9b10aba73a7cef6bf82e362545a3876a42def | 769 | class AdminProduct < Upmin::Model
# The attributes method overwrites default attributes shown for a model, and replaces them with the provided attributes. These don't all need to be editable, but as long as there is an :attr_name= method available upmin assumes that the attribute should be editable.
attributes :name, :short_desc, :price, :manufacturer, :free_shipping
# The actions method overwrites all actions and uses the provided list of models.
actions :update_price
# You can use custom methods inside of admin that are explicitly for admin pages. For example, you might want a method to update the price and automatically add a 10% markup.
def update_price(price)
model.price = price # * 1.10 # our markup is 10%
model.save!
end
end
| 48.0625 | 269 | 0.762029 |
bf73483b5d8afcf0a3c80c55df870f84ae8fd95c | 461 | class Board < ApplicationRecord
has_many :board_replies, dependent: :destroy
validates :title, presence: true, length: {maximum: 100}
validates :name, presence: true, length: {maximum: 50}
validates :content, length: {maximum: 200}, if: "content.present?"
# search boards by title
# @param [String] title search target title
# @return [Board] search result
def self.get_by_title(title)
Board.where("title like ?", "%#{title}%")
end
end
| 28.8125 | 68 | 0.700651 |
abe93d10e9d2d92f3364a2bbd0fbd4862e35a9dd | 1,298 | require "language/node"
class NowCli < Formula
desc "The command-line interface for Now"
homepage "https://zeit.co/now"
url "https://registry.npmjs.org/now/-/now-20.0.0.tgz"
sha256 "471d4fb8507b64d1caefa5a5a1433432ccf26b1a2965d9c47e88da3934320b96"
license "Apache-2.0"
livecheck do
url :stable
end
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "a33ec53e45f2ef38fe23a0a2e66205783c4e9d6a037d4b5de38bac3b8a1448e8" => :catalina
sha256 "831da3bb99d51a4a0e566bc7f0494dda30be6b8f16170f97afc36a51c843eda7" => :mojave
sha256 "a52be7278a1492daa225ecd47b7326f41f60ea2070397903bc3ef09f7f6aec1a" => :high_sierra
end
depends_on "node"
disable! date: "2021-01-31", because: "is not receiving updates upstream"
def install
rm Dir["dist/{*.exe,xsel}"]
inreplace "dist/index.js", "t.default=getUpdateCommand",
"t.default=async()=>'brew upgrade now-cli'"
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system "#{bin}/now", "init", "jekyll"
assert_predicate testpath/"jekyll/_config.yml", :exist?, "_config.yml must exist"
assert_predicate testpath/"jekyll/README.md", :exist?, "README.md must exist"
end
end
| 32.45 | 93 | 0.718028 |
ab1e583d195401043ecc43ab0fdb08daadcb5618 | 196 | require 'coderay'
class Out::Handlers::Yaml < Out::Handler
match /^.*(eslintrc|yaml|yml)$/
def execute(*arguments)
puts CodeRay.scan(File.read(arguments.last), :yaml).terminal
end
end
| 19.6 | 64 | 0.69898 |
bb5be64cd3fd66545f04944e926b405ab0dc1fd3 | 215 | class CreateChannels < ActiveRecord::Migration[5.0]
def change
create_table :channels do |t|
t.string :name, null: false
t.timestamps
end
add_index :channels, :name, unique: true
end
end
| 21.5 | 51 | 0.674419 |
e918f60dd2fbd2ed2a509d69919f555b69880d46 | 467 | class CoreIndicatorTranslation < ActiveRecord::Base
attr_accessible :core_indicator_id, :name, :name_abbrv, :description, :locale, :summary
belongs_to :core_indicator
validates :name, :name_abbrv, :locale, :presence => true
# this will always call validation to fail due to the translations being
# created while the event is created. probably way to fix
# validates :indicator_id, :presence => true
default_scope order('locale ASC, name ASC')
end
| 38.916667 | 89 | 0.75803 |
628507add89386e02e48d04ab8d00a6dd7bf78fa | 3,152 | require 'daddy/git'
require 'nokogiri'
namespace :dad do
task :publish do
fail('設定「cucumber.title」がありません。') unless Daddy.config.cucumber.title?
if File.exist?("db/schema.rb")
fail unless system('rake db:schema:load RAILS_ENV=test')
end
system("mkdir -p features/reports")
system("rm -Rf features/reports/*")
fail unless system("bundle exec rake dad:cucumber PUBLISH=true EXPAND=false COVERAGE=false features/開発日記")
system("mkdir -p features/reports/diary")
system("mv features/reports/index.html features/reports/diary")
system("mv features/reports/images features/reports/diary")
unless ENV['SKIP_SPEC']
fail unless system("bundle exec rake dad:cucumber PUBLISH=true EXPAND=false features/仕様書")
system("mkdir -p features/reports/spec")
system("mv features/reports/index.html features/reports/spec")
system("mv features/reports/images features/reports/spec")
end
git = Daddy::Git.new
branch = git.current_branch
# 公開
base_dir = dad_publish_base_dir
system("sudo mkdir -p #{base_dir}")
system("sudo chown -R #{ENV['USER']}:#{ENV['USER']} #{base_dir}")
system("mkdir -p #{base_dir}/#{branch}")
system("rm -Rf #{base_dir}/#{branch}/*")
system("cp -Rf features/reports/* #{base_dir}/#{branch}/")
if File.exist? 'coverage'
system("cp -Rf coverage #{base_dir}/#{branch}/")
end
# 開発日記を統合
if branch == 'master'
features = {}
dad_publish_sprint_dirs(base_dir).each do |dir|
dad_publish_extract_features(dir).each do |div|
feature = features[div['id']]
if feature
div.css('div.narrative').each do |narrative|
feature.add_child(narrative)
end
div.css('div.scenario').each do |scenario|
feature.add_child(scenario)
end
else
features[div['id']] = div
end
end
end
# 空HTMLを生成
system("bundle exec rake dad:cucumber PUBLISH=true EXPAND=false COVERAGE=false features/support")
doc = Nokogiri::HTML(File.read('features/reports/index.html'))
contents_div = doc.css('div.contents').first
features.keys.sort.each do |key|
contents_div.add_child(features[key])
end
File.write("#{base_dir}/index.html", doc)
end
end
end
def self.dad_publish_sprint_dirs(base_dir)
ret = Dir[base_dir + '/p*'].sort{|a, b| File.basename(a)[1..-1].to_f <=> File.basename(b)[1..-1].to_f}
ret << base_dir + '/master'
ret
end
def self.dad_publish_extract_features(dir)
ret = []
return [] unless File.exist?(dir) and File.directory?(dir)
html = dir + '/diary/index.html'
return [] unless File.exist?(html)
doc = Nokogiri::HTML(File.read(html))
doc.css('div.feature').each do |div|
div.css('img.screenshot').each do |img|
img['src'] = File.basename(dir) + '/diary/' + img['src']
end
ret << div
end
ret
end
def self.dad_publish_base_dir
'/var/lib/daddy/' + dad_publish_title_to_dirname
end
def self.dad_publish_title_to_dirname
Daddy.config.cucumber.title.sub(' ', '_').downcase
end
| 30.019048 | 110 | 0.643401 |
625610358ea5f92528b1ba97371187623cb27dc1 | 1,925 | require 'mysql-statsd'
describe Mysql::Statsd::Runner do
let(:config_path) { "spec/config.yml" }
subject { Mysql::Statsd::Runner.new config_path }
before :each do
Mysql2::Client.any_instance.stub :connect
end
it "should set the statsd namespace as mysql" do
subject.statsd.namespace.should == 'ns'
end
it "should set the statds host from the config file" do
subject.statsd.host.should == 'statsdhost'
end
it "should set the mysql host from the config file" do
subject.mysql.query_options[:host].should == 'mysqlhost'
end
it "should set the mysql user from the config file" do
subject.mysql.query_options[:username].should == 'user'
end
describe "#run!" do
before :each do
subject.mysql.stub(:query).and_return []
end
it "should query the global status" do
subject.mysql.should_receive(:query).with("SHOW GLOBAL STATUS").and_return [{'Variable_name' => 'Fake', 'Value' => 1}]
subject.run!
end
it "should instrument the process list" do
subject.mysql.stub(:query).with("SHOW PROCESSLIST").and_return [{'Command' => 'Jump', 'State' => 'Long Lived'}, {'Command' => 'Jump', 'State' => 'Long Dead'}]
subject.statsd.should_receive(:gauge).with('state.long_lived', 1)
subject.statsd.should_receive(:gauge).with('state.long_dead', 1)
subject.statsd.should_receive(:gauge).with('command.jump', 2)
subject.run!
end
it "should query configured queries" do
subject.mysql.stub(:query).with("SELECT count(1) as 'users.count' from users").and_return [{'users.count' => 15}]
subject.statsd.should_receive(:gauge).with('users.count', 15)
subject.run!
end
context "with a config file without queries" do
let(:config_path) { "spec/config_without_queries.yml" }
it "should not break" do
lambda { subject.run! }.should_not raise_exception
end
end
end
end
| 32.083333 | 164 | 0.672727 |
91e300584f35fb2ff69e9269a991a970a6802c35 | 2,041 | # Author:: Dheeraj Dubey([email protected])
# Copyright:: Copyright 2008-2016, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "chef/resource/package"
require "chef/mixin/uris"
class Chef
class Resource
class PowershellPackage < Chef::Resource::Package
include Chef::Mixin::Uris
resource_name :powershell_package
provides :powershell_package
description "Use the powershell_package resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The powershell_package resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the Register-PackageSource command"
introduced "12.16"
allowed_actions :install, :remove
property :package_name, [String, Array],
description: "The name of the package. Default value: the name of the resource block.",
coerce: proc { |x| [x].flatten }
property :version, [String, Array],
description: "The version of a package to be installed or upgraded.",
coerce: proc { |x| [x].flatten }
property :source, String,
description: "Specify the source of the package.",
introduced: "14.0"
property :skip_publisher_check, [true, false],
description: "Skip validating module author.",
default: false, introduced: "14.3"
end
end
end
| 38.509434 | 326 | 0.702597 |
7a91314e16a880aa5506655cebd5db95f7252b41 | 5,549 | require 'fog/core'
require 'fog/json'
require 'fog/rackspace/mock_data'
require 'fog/rackspace/service'
require 'fog/rackspace/errors'
module Fog
module Rackspace
extend Fog::Provider
US_AUTH_ENDPOINT = 'https://identity.api.rackspacecloud.com/v2.0' unless defined? US_AUTH_ENDPOINT
UK_AUTH_ENDPOINT = 'https://lon.identity.api.rackspacecloud.com/v2.0' unless defined? UK_AUTH_ENDPOINT
module Errors
class ServiceError < Fog::Errors::Error
attr_reader :response_data, :status_code, :transaction_id
def to_s
status = status_code ? "HTTP #{status_code}" : "HTTP <Unknown>"
"[#{status} | #{transaction_id}] #{super}"
end
def self.slurp(error, service=nil)
data = nil
message = nil
status_code = nil
if error.response
status_code = error.response.status
unless error.response.body.empty?
begin
data = Fog::JSON.decode(error.response.body)
message = extract_message(data)
rescue => e
Fog::Logger.warning("Received exception '#{e}' while decoding>> #{error.response.body}")
message = error.response.body
data = error.response.body
end
end
end
new_error = super(error, message)
new_error.instance_variable_set(:@response_data, data)
new_error.instance_variable_set(:@status_code, status_code)
new_error.set_transaction_id(error, service)
new_error
end
def set_transaction_id(error, service)
return unless service && service.respond_to?(:request_id_header) && error.response
@transaction_id = error.response.headers[service.request_id_header]
end
def self.extract_message(data)
if data.is_a?(Hash)
message = data.values.first['message'] if data.values.first.is_a?(Hash)
message ||= data['message']
end
message || data.inspect
end
end
class InternalServerError < ServiceError; end
class Conflict < ServiceError; end
class ServiceUnavailable < ServiceError; end
class MethodNotAllowed < ServiceError; end
class BadRequest < ServiceError
attr_reader :validation_errors
def to_s
"#{super} - #{validation_errors}"
end
def self.slurp(error, service=nil)
new_error = super(error)
unless new_error.response_data.nil? or new_error.response_data['badRequest'].nil?
new_error.instance_variable_set(:@validation_errors, new_error.response_data['badRequest']['validationErrors'])
end
status_code = error.response ? error.response.status : nil
new_error.instance_variable_set(:@status_code, status_code)
new_error.set_transaction_id(error, service)
new_error
end
end
end
service(:auto_scale, 'AutoScale')
service(:block_storage, 'BlockStorage')
service(:cdn, 'CDN')
service(:compute, 'Compute')
service(:compute_v2, 'Compute v2')
service(:dns, 'DNS')
service(:storage, 'Storage')
service(:load_balancers, 'LoadBalancers')
service(:identity, 'Identity')
service(:databases, 'Databases')
service(:monitoring, 'Monitoring')
service(:queues, 'Queues')
service(:networking, 'Networking')
service(:orchestration, 'Orchestration')
service(:networkingV2, 'NetworkingV2')
def self.authenticate(options, connection_options = {})
rackspace_auth_url = options[:rackspace_auth_url]
rackspace_auth_url ||= options[:rackspace_endpoint] == Fog::Compute::RackspaceV2::LON_ENDPOINT ? UK_AUTH_ENDPOINT : US_AUTH_ENDPOINT
url = rackspace_auth_url.match(/^https?:/) ? \
rackspace_auth_url : 'https://' + rackspace_auth_url
uri = URI.parse(url)
connection = Fog::Core::Connection.new(url, false, connection_options)
@rackspace_api_key = options[:rackspace_api_key]
@rackspace_username = options[:rackspace_username]
response = connection.request({
:expects => [200, 204],
:headers => {
'X-Auth-Key' => @rackspace_api_key,
'X-Auth-User' => @rackspace_username
},
:method => 'GET',
:path => (uri.path and not uri.path.empty?) ? uri.path : 'v1.0'
})
response.headers.reject do |key, value|
!['X-Server-Management-Url', 'X-Storage-Url', 'X-CDN-Management-Url', 'X-Auth-Token'].include?(key)
end
end
def self.json_response?(response)
return false unless response && response.headers
response.get_header('Content-Type') =~ %r{application/json}i ? true : false
end
def self.normalize_url(endpoint)
return nil unless endpoint
str = endpoint.chomp " "
str = str.chomp "/"
str.downcase
end
# CGI.escape, but without special treatment on spaces
def self.escape(str,extra_exclude_chars = '')
# '-' is a special character inside a regex class so it must be first or last.
# Add extra excludes before the final '-' so it always remains trailing, otherwise
# an unwanted range is created by mistake.
str.gsub(/([^a-zA-Z0-9_.#{extra_exclude_chars}-]+)/) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end
end
end
end
| 36.993333 | 138 | 0.620112 |
e8a184b4045256c39136ff040ac20d4b21a60f1d | 278 | require "sleepr/version"
module Sleepr
def initialize
end
def self.session_timing(hour,min)
if hour == 14 && min == 30
puts "Time to Session! Come Come Come!!"
else
puts "Please dont come late!!!!!!"
end
end
end
| 18.533333 | 52 | 0.55036 |
1c9bbc391c727709aa82be7dea99d62b612e06b2 | 3,976 | # Copyright, 2016, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# 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.
require 'samovar'
require_relative 'command/build'
require_relative 'command/clean'
require_relative 'command/create'
require_relative 'command/clone'
require_relative 'command/fetch'
require_relative 'command/list'
require_relative 'command/status'
require_relative 'command/visualize'
require_relative 'context'
require_relative 'configuration'
require_relative 'version'
require 'fileutils'
require 'console'
module Teapot
module Command
class Top < Samovar::Command
self.description = "A decentralised package manager and build tool."
options do
option '-c/--configuration <name>', "Specify a specific build configuration.", default: ENV['TEAPOT_CONFIGURATION']
option '--root <path>', "Work in the given root directory."
option '--verbose | --quiet', "Verbosity of output for debugging.", key: :logging
option '-h/--help', "Print out help information."
option '-v/--version', "Print out the application version."
end
nested :command, {
"create" => Create,
"clone" => Clone,
"fetch" => Fetch,
"list" => List,
"status" => Status,
"build" => Build,
"visualize" => Visualize,
"clean" => Clean,
}, default: 'build'
def root
::Build::Files::Path.expand(@options[:root] || Dir.getwd)
end
def verbose?
@options[:logging] == :verbose
end
def quiet?
@options[:logging] == :quiet
end
def logger
@logger ||= Console::Logger.new(Console.logger, verbose: self.verbose?).tap do |logger|
if verbose?
logger.debug!
elsif quiet?
logger.warn!
else
logger.info!
end
end
end
def configuration
@options[:configuration]
end
def context(root = self.root)
Context.new(root, configuration: configuration)
end
def call
if @options[:version]
puts "teapot v#{Teapot::VERSION}"
elsif @options[:help]
print_usage(output: $stdout)
else
@command.call
end
rescue Teapot::IncompatibleTeapotError => error
logger.error(command, error) do
"Supported minimum version #{Teapot::MINIMUM_LOADER_VERSION.dump} to #{Teapot::LOADER_VERSION.dump}."
end
raise
rescue ::Build::Dependency::UnresolvedDependencyError => error
logger.error(command, error) do |buffer|
buffer.puts "Unresolved dependencies:"
error.chain.unresolved.each do |name, parent|
buffer.puts "#{parent} depends on #{name.inspect}"
conflicts = error.chain.conflicts[name]
if conflicts
conflicts.each do |conflict|
buffer.puts " - provided by #{conflict.name}"
end
end
end
buffer.puts "Cannot continue due to unresolved dependencies!"
end
raise
rescue StandardError => error
logger.error(command, error)
raise
end
end
end
end
| 28.811594 | 119 | 0.689889 |
03065c2d69e418477aa1cc29b2c12efe11edfeae | 835 | # frozen_string_literal: true
module Parsers
module LastFm
class UpdateUnknown
def self.call
Album.where(:last_fm_url => nil).each_unchecked("last.fm") do |album|
new(album).call
end
end
def initialize(album)
@album = album
end
def call
hash = last_fm.album.get_info(
:album => album.name,
:artist => album.artist.name,
:autocorrect => 1
)
UpdateAlbum.call(hash, album, :ignore_artist => true)
rescue Lastfm::ApiError => error
raise error unless error.message == "Album not found"
end
private
attr_reader :album
def last_fm
@last_fm ||= Lastfm.new(
ENV["LAST_FM_API_KEY"], ENV["LAST_FM_API_SECRET"]
)
end
end
end
end
| 20.875 | 77 | 0.559281 |
edde487582c945acb6928ab4e2a3adf827be5193 | 374 | FactoryBot.define do
factory :library_entry do
association :media, factory: :anime
association :user, strategy: :build
status { 'planned' }
progress { 0 }
time_spent { progress * 24 }
trait :nsfw do
association :media, :nsfw, factory: :anime, strategy: :build
end
trait :with_rating do
rating { rand(1..19) }
end
end
end
| 22 | 66 | 0.63369 |
ac6b8d3e1b11a85c82975c0db08b5633ecee99e1 | 2,291 | require "ffi" unless defined?(FFI)
class Statfs
#
# Statfs provides a simple interface to the statvfs system call.
# Since the statvfs struct varies a bit across platforms, this
# likely only works on Linux and OSX at the moment.
#
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function(:statvfs, %i{string pointer}, :int)
attach_function(:strerror, [:int], :string)
FSBLKCNT_T = if RbConfig::CONFIG["host_os"] =~ /darwin|osx|mach/i
:uint
else
:ulong
end
# See http://man7.org/linux/man-pages/man2/statvfs.2.html
class Statvfs < FFI::Struct
spec = [
:f_bsize, :ulong, # Filesystem block size
:f_frsize, :ulong, # Fragement size
:f_blocks, FSBLKCNT_T, # Size of fs in f_frsize units
:f_bfree, FSBLKCNT_T, # Number of free blocks
:f_bavail, FSBLKCNT_T, # Number of free blocks for unpriviledged users
:f_files, FSBLKCNT_T, # Number of inodes
:f_ffree, FSBLKCNT_T, # Number of free inodes
:f_favail, FSBLKCNT_T, # Number of free inodes for unprivilged users
:f_fsid, :ulong, # Filesystem ID
:f_flag, :ulong, # Mount Flags
:f_namemax, :ulong # Max filename length
]
# Linux has this at the end of the struct and if we don't include
# it we end up getting a memory corruption error when th object
# gets GCd.
if RbConfig::CONFIG["host_os"] =~ /linux/i
spec << :f_spare
spec << [:int, 6]
end
layout(*spec)
end
def initialize(path)
@statvfs = stat(path)
end
#
# @returns [Integer] Free inodes on the given filesystem
#
def free_inodes
@statvfs[:f_favail]
end
#
# @returns [Integer] Free space in KB on the given filesystem
#
def free_space
# Since we are running as root we could report f_bfree but will
# stick with f_bavail since it will typically be more
# conservative.
(@statvfs[:f_frsize] * @statvfs[:f_bavail]) / 1024
end
private
def stat(path)
statvfs = Statvfs.new
if statvfs(path, statvfs.to_ptr) != 0
raise "StatvfsFailedException", command.stderr
end
statvfs
end
end
| 28.6375 | 84 | 0.612833 |
3342852261e690e50801c9874ca87608df309f89 | 3,148 | class SplashMultiListCustomizableJournals < ActiveRecord::Migration[6.0]
def up
# First get all customizable_journals entries that belong to a multi list custom field and that have more than one
# value (a comma separated list). Return the values, splashed using unnest(string_to_array(...)). E.g. `1,2,3` will
# be returned as three rows with the value_part `1`, `2` and `3` respectively.
# Those are then inserted into the journals table.
# Lastly, the entries with the unsplashed values are deleted.
execute <<~SQL
WITH existing_journals AS (
SELECT *
FROM (
SELECT customizable_journals.* FROM customizable_journals
JOIN custom_fields
ON custom_fields.id = customizable_journals.custom_field_id AND field_format = 'list' AND multi_value = true
) customizable_journals
, unnest(string_to_array(customizable_journals.value, ',')) value_part
WHERE customizable_journals.value LIKE '%,%'
),
splash_journals AS (
INSERT INTO
customizable_journals (
journal_id,
custom_field_id,
value
)
SELECT
journal_id,
custom_field_id,
value_part
FROM existing_journals
RETURNING *
),
delete_journals AS (
DELETE
FROM
customizable_journals
WHERE id IN (SELECT id from existing_journals)
)
SELECT * FROM splash_journals;
SQL
end
# Group all customizable_journals by journal_id and custom_field_id and return those, for which
# two or more are returned. That way, we get all the once we need to aggregate again. We aggregate
# to a comma separated list within the same query.
# That query then serves to return all data that we need to insert into the customizable_journals again.
# Lastly, all customizable_journals entries that where not just created and that belong to a group of more than one
# value per journal and custom field are deleted.
def down
execute <<~SQL
WITH aggregated_value AS (
SELECT
journal_id,
custom_field_id,
string_agg(value, ',') AS value
FROM
customizable_journals
GROUP BY
journal_id,
custom_field_id
HAVING COUNT(value) > 1
),
insert_aggregated AS (
INSERT INTO
customizable_journals (
journal_id,
custom_field_id,
value
)
SELECT
journal_id,
custom_field_id,
value
FROM
aggregated_value
RETURNING *
)
DELETE FROM
customizable_journals
WHERE
id IN (
SELECT
id
FROM
customizable_journals
JOIN aggregated_value
ON
customizable_journals.custom_field_id = aggregated_value.custom_field_id
AND customizable_journals.journal_id = aggregated_value.journal_id
)
AND id NOT IN (
SELECT id FROM insert_aggregated
)
SQL
end
end
| 31.48 | 119 | 0.623888 |
f8f2e35a977ebf99d364309e1478821d71ed62cc | 2,307 | require "active_support/core_ext/integer/time"
Rails.application.routes.default_url_options[:host] = "localhost:3000"
Rails.application.routes.default_url_options[:protocol] = "http"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp", "caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
config.action_mailer.default_options = { from: ENV["DEFAULT_SMTP_FROM"] }
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Uncomment if you wish to allow Action Cable access from any origin.
# config.action_cable.disable_request_forgery_protection = true
end
| 35.492308 | 85 | 0.76723 |
87c978baf24b3f59159239c17acbc84a4643596f | 10,413 | require_relative 'test_helper'
# Unit Test for SemanticLogger::Logger
class LoggerTest < Minitest::Test
describe SemanticLogger::Logger do
include InMemoryAppenderHelper
let :dimensions do
{action: 'hit', user: 'jbloggs', state: 'FL'}
end
# Ensure that any log level can be logged
SemanticLogger::LEVELS.each do |level|
describe "##{level}" do
describe 'positional parameter' do
it 'logs message' do
logger.send(level, 'hello world')
assert log = log_message
assert_equal 'hello world', log.message
end
it 'adds message from block' do
logger.send(level, 'hello world') { 'Calculations' }
assert log = log_message
assert_equal 'hello world -- Calculations', log.message
end
it 'logs message and payload' do
logger.send(level, 'hello world', payload)
assert log = log_message
assert_equal 'hello world', log.message
assert_equal payload, log.payload
end
it 'logs with backtrace' do
SemanticLogger.stub(:backtrace_level_index, 0) do
logger.send(level, 'hello world', payload) { 'Calculations' }
assert log = log_message
assert_equal 'hello world -- Calculations', log.message
assert_equal payload, log.payload
assert log.backtrace
assert log.backtrace.size.positive?, log.backtrace
end
end
it 'logs with backtrace and exception' do
SemanticLogger.stub(:backtrace_level_index, 0) do
exc = RuntimeError.new('Test')
logger.send(level, 'hello world', exc)
assert log = log_message
assert_equal 'hello world', log.message
assert log.backtrace
assert log.backtrace.size.positive?, log.backtrace
assert log.exception
refute log.exception.backtrace
assert_equal 'RuntimeError', log.exception.class.name
end
end
end
describe 'keyword arguments' do
it 'logs message' do
logger.send(level, message: 'hello world')
assert log = log_message
assert_equal 'hello world', log.message
end
it 'logs payload and message' do
logger.send(level, message: 'hello world', payload: payload)
assert log = log_message
assert_equal 'hello world', log.message
assert_equal payload, log.payload
end
it 'logs payload and message from block' do
logger.send(level) { {message: 'hello world', payload: payload} }
assert log = log_message
assert_equal 'hello world', log.message
assert_equal payload, log.payload
end
it 'logs payload from block' do
logger.send(level) { {'test_key1' => 'hello world', 'test_key2' => payload} }
assert log = log_message
assert_equal log.payload, 'test_key1' => 'hello world', 'test_key2' => payload
end
it 'logs payload only' do
logger.send(level, payload: payload)
assert log = log_message
refute log.message
assert_equal payload, log.payload
end
it 'logs duration' do
logger.send(level, duration: 123.44, message: 'hello world', payload: payload)
assert log = log_message
assert_equal 'hello world', log.message
assert_equal payload, log.payload
assert_equal 123.44, log.duration
end
it 'does not log when below min_duration' do
logger.send(level, min_duration: 200, duration: 123.45, message: 'hello world', payload: {tracking_number: '123456', even: 2, more: 'data'})
refute log_message
end
it 'logs metric' do
metric_name = '/my/custom/metric'
logger.send(level, metric: metric_name, duration: 123.44, message: 'hello world', payload: payload)
assert log = log_message
assert_equal 'hello world', log.message
assert_equal payload, log.payload
assert_equal 123.44, log.duration
assert_equal metric_name, log.metric
end
describe 'metrics appender' do
let :appender do
InMemoryMetricsAppender.new
end
it 'logs metric only events' do
metric_name = '/my/custom/metric'
logger.send(level, metric: metric_name, dimensions: dimensions)
assert log = log_message
assert_equal metric_name, log.metric
assert_equal dimensions, log.dimensions
refute log.message
end
end
it 'for compatibility handles random payload logged as keyword arguments' do
logger.send(level, payload)
assert log = log_message
refute log.message
refute log.exception
refute log.metric
assert_equal payload, log.payload
end
end
describe '#filter' do
describe 'at the appender level' do
it 'Proc' do
appender.filter = ->(log) { (/\AExclude/ =~ log.message).nil? }
logger.send(level, 'Exclude this log message', @hash) { 'Calculations' }
refute log_message
end
it 'RegExp' do
filter = /\ALogger/
appender.filter = ->(log) { (/\AExclude/ =~ log.message).nil? }
logger.send(level, 'Exclude this log message', @hash) { 'Calculations' }
refute log_message
end
end
describe 'at the logger level' do
it 'Proc' do
logger.filter = ->(log) { (/\AExclude/ =~ log.message).nil? }
logger.send(level, 'Exclude this log message', @hash) { 'Calculations' }
refute log_message
end
it 'RegExp' do
filter = /\ALogger/
logger.filter = ->(log) { (/\AExclude/ =~ log.message).nil? }
logger.send(level, 'Exclude this log message', @hash) { 'Calculations' }
refute log_message
end
end
end
end
end
describe 'when level is too high' do
it 'does not log' do
SemanticLogger.default_level = :error
logger.info('Exclude this log message')
refute log_message
end
end
describe 'Compatibility' do
# Ensure that any log level can be logged
Logger::Severity.constants.each do |level|
it "log Ruby logger #{level} info" do
logger.level = Logger::Severity.const_get(level)
if level.to_s == 'UNKNOWN'
assert_equal Logger::Severity.const_get('ERROR') + 1, logger.send(:level_index)
else
assert_equal Logger::Severity.const_get(level) + 1, logger.send(:level_index)
end
end
end
end
describe '#level?' do
it 'return true for debug? with :trace level' do
SemanticLogger.default_level = :trace
assert_equal :trace, logger.level
assert_equal true, logger.debug?
assert_equal true, logger.trace?
end
it 'return false for debug? with global :debug level' do
SemanticLogger.default_level = :debug
assert_equal :debug, logger.level, logger.inspect
assert_equal true, logger.debug?, logger.inspect
assert_equal false, logger.trace?, logger.inspect
end
it 'return true for debug? with global :info level' do
SemanticLogger.default_level = :info
assert_equal :info, logger.level, logger.inspect
assert_equal false, logger.debug?, logger.inspect
assert_equal false, logger.trace?, logger.inspect
end
it 'return false for debug? with instance :debug level' do
logger.level = :debug
assert_equal :debug, logger.level, logger.inspect
assert_equal true, logger.debug?, logger.inspect
assert_equal false, logger.trace?, logger.inspect
end
it 'return true for debug? with instance :info level' do
logger.level = :info
assert_equal :info, logger.level, logger.inspect
assert_equal false, logger.debug?, logger.inspect
assert_equal false, logger.trace?, logger.inspect
end
end
describe '.tagged' do
it 'sets global defaults' do
assert_equal [], SemanticLogger.tags
assert_equal 0, SemanticLogger.backtrace_level_index
end
it 'add tags to log entries' do
logger.tagged('12345', 'DJHSFK') do
logger.info('hello world')
assert log = log_message
assert_equal 'hello world', log.message
assert_equal %w[12345 DJHSFK], log.tags
end
end
it 'add embedded tags to log entries' do
logger.tagged('First Level', 'tags') do
logger.tagged('Second Level') do
assert_equal ['First Level', 'tags', 'Second Level'], logger.tags
logger.info('hello world')
assert log = log_message
assert_equal 'hello world', log.message
assert_equal ['First Level', 'tags', 'Second Level'], log.tags
end
assert_equal ['First Level', 'tags'], logger.tags
end
end
it 'also supports named tagging' do
logger.tagged(level1: 1) do
assert_equal({level1: 1}, SemanticLogger.named_tags)
logger.tagged(level2: 2, more: 'data') do
assert_equal({level1: 1, level2: 2, more: 'data'}, SemanticLogger.named_tags)
logger.tagged(level3: 3) do
assert_equal({level1: 1, level2: 2, more: 'data', level3: 3}, SemanticLogger.named_tags)
end
end
end
end
it 'is compatible with rails logging that uses arrays and nils' do
logger.tagged('', %w[12345 DJHSFK], nil) do
logger.info('hello world')
assert log = log_message
assert_equal 'hello world', log.message
assert_equal %w[12345 DJHSFK], log.tags
end
end
end
end
end
| 33.482315 | 152 | 0.581293 |
613b6b65800f83fd4b0c29cab9abc664784db03c | 2,301 | # frozen_string_literal: true
require 'spec_helper'
if defined?(Rails)
enabled = true
else
puts '[INFO] Skipping Rails spec'
end
if enabled
require 'action_controller/railtie'
RSpec.describe 'Rails integration', :allow_running_agent, :spec_logger do
include Rack::Test::Methods
include_context 'event_collector'
let(:app) do
Rails.application
end
after :all do
ElasticAPM.stop
ElasticAPM::Transport::Worker.adapter = nil
end
before :all do
module RailsTestApp
class Application < Rails::Application
RailsTestHelpers.setup_rails_test_config(config)
config.elastic_apm.api_request_time = '200ms'
config.elastic_apm.disable_start_message = true
config.elastic_apm.metrics_interval = '1s'
config.elastic_apm.pool_size = Concurrent.processor_count
config.elastic_apm.log_path = 'spec/elastic_apm.log'
end
end
class ApplicationController < ActionController::Base
def index
render_ok
end
def other
render_ok
end
private
def render_ok
if Rails.version.start_with?('4')
render text: 'Yes!'
else
render plain: 'Yes!'
end
end
end
ElasticAPM::Transport::Worker.adapter = EventCollector::TestAdapter
RailsTestApp::Application.initialize!
RailsTestApp::Application.routes.draw do
get '/other', to: 'application#other'
root to: 'application#index'
end
end
it 'handles multiple threads' do
request_count = 20
paths = ['/', '/other']
count = Concurrent::AtomicFixnum.new
Array.new(request_count).map do
Thread.new do
env = Rack::MockRequest.env_for(paths.sample)
status, = Rails.application.call(env)
# The request is occasionally unsuccessful so we want to only
# compare the metricset counts to the number of successful
# requests.
count.increment if status == 200
end
end.each(&:join)
sleep 2 # wait for metrics to collect
expect(EventCollector.metricsets_summary.values).to eq(
Array.new(5).map { count.value }
)
end
end
end
| 24.478723 | 75 | 0.629292 |
4ae2e0b8835b5eea91908cfae57ae7d1d1e9a2fb | 7,012 | require "hangman"
describe "Hangman" do
let(:hangman) { Hangman.new }
describe "PART 2" do
describe "#try_guess" do
it "should accept a char as an arg" do
hangman.try_guess("o")
end
it "should call Hangman#already_attempted?" do
expect(hangman).to receive(:already_attempted?).with("o")
hangman.try_guess("o")
end
context "if the char was already attempted" do
it "should print 'that has already been attempted'" do
hangman.instance_variable_set(:@attempted_chars, ["o"])
expect { hangman.try_guess("o") }.to output(/already/).to_stdout
end
it "should return false to indicate the guess was previously attempted" do
hangman.instance_variable_set(:@attempted_chars, ["o"])
expect(hangman.try_guess("o")).to eq(false)
end
end
context "if the char was not already attempted" do
it "should add the char to @attempted_chars" do
hangman.try_guess("o")
expect(hangman.attempted_chars).to eq(["o"])
hangman.try_guess("c")
expect(hangman.attempted_chars).to eq(["o", "c"])
hangman.try_guess("x")
expect(hangman.attempted_chars).to eq(["o", "c", "x"])
end
it "should return true to indicate the guess was not previously attempted" do
expect(hangman.try_guess("o")).to eq(true)
end
end
context "if the char has no match indices in @secret_word" do
it "should decrement @remaining_incorrect_guesses" do
allow(Hangman).to receive(:random_word).and_return("bootcamp")
hangman.try_guess("o")
expect(hangman.remaining_incorrect_guesses).to eq(5)
hangman.try_guess("x")
expect(hangman.remaining_incorrect_guesses).to eq(4)
end
end
it "should call Hangman#get_matching_indices with the char" do
allow(Hangman).to receive(:random_word).and_return("bootcamp")
allow(hangman).to receive(:get_matching_indices) { [1, 2] }
expect(hangman).to receive(:get_matching_indices).with("o")
hangman.try_guess("o")
end
it "should call Hangman#fill_indices with the char and it's matching indices" do
allow(Hangman).to receive(:random_word).and_return("bootcamp")
expect(hangman).to receive(:fill_indices).with("o", [1, 2])
hangman.try_guess("o")
end
end
describe "#ask_user_for_guess" do
it "should print 'Enter a char:'" do
allow(hangman).to receive(:gets).and_return("o\n")
expect { hangman.ask_user_for_guess }.to output(/Enter a char/).to_stdout
end
it "should call gets.chomp to get input from the user " do
char = double("o\n", :chomp => "o")
allow(hangman).to receive(:gets).and_return(char)
expect(char).to receive(:chomp)
expect(hangman).to receive(:gets)
hangman.ask_user_for_guess
end
it "should call Hangman#try_guess with the user's char" do
char = double("o\n", :chomp => "o")
allow(hangman).to receive(:gets).and_return(char)
expect(hangman).to receive(:try_guess).with(char.chomp)
hangman.ask_user_for_guess
end
it "should return the return value of Hangman#try_guess" do
char = double("o\n", :chomp => "o")
allow(hangman).to receive(:gets).and_return(char)
allow(hangman).to receive(:try_guess).and_return(false)
expect(hangman.ask_user_for_guess).to eq(false)
allow(hangman).to receive(:try_guess).and_return(true)
expect(hangman.ask_user_for_guess).to eq(true)
end
end
describe "win?" do
context "when @guess_word matches @secret_word" do
it "should print 'WIN'" do
allow(Hangman).to receive(:random_word).and_return("cat")
hangman.instance_variable_set(:@guess_word, ["c", "a", "t"])
expect { hangman.win? }.to output(/WIN/).to_stdout
end
it "should return true" do
allow(Hangman).to receive(:random_word).and_return("cat")
hangman.instance_variable_set(:@guess_word, ["c", "a", "t"])
expect(hangman.win?).to eq(true)
end
end
context "when @guess_word does not match @secret_word" do
it "should return false" do
allow(Hangman).to receive(:random_word).and_return("cat")
hangman.instance_variable_set(:@guess_word, ["c", "_", "t"])
expect(hangman.win?).to eq(false)
end
end
end
describe "lose?" do
context "when @remaining_incorrect_guesses is 0" do
it "should print 'LOSE'" do
hangman.instance_variable_set(:@remaining_incorrect_guesses, 0)
expect { hangman.lose? }.to output(/LOSE/).to_stdout
end
it "should return true" do
hangman.instance_variable_set(:@remaining_incorrect_guesses, 0)
expect(hangman.lose?).to eq(true)
end
end
context "when @remaining_incorrect_guesses is not 0" do
it "should return false" do
hangman.instance_variable_set(:@remaining_incorrect_guesses, 2)
expect(hangman.lose?).to eq(false)
end
end
end
describe "game_over?" do
it "should call Hangman#win?" do
allow(hangman).to receive(:lose?).and_return(false)
allow(hangman).to receive(:win?).and_return(true)
expect(hangman).to receive(:win?)
hangman.game_over?
end
it "should call Hangman#lose?" do
allow(hangman).to receive(:win?).and_return(false)
allow(hangman).to receive(:lose?).and_return(true)
expect(hangman).to receive(:lose?)
hangman.game_over?
end
context "when the game is won or lost" do
it "should print @secret_word" do
allow(Hangman).to receive(:random_word).and_return("cat")
allow(hangman).to receive(:lose?).and_return(false)
allow(hangman).to receive(:win?).and_return(true)
expect { hangman.game_over? }.to output(/cat/).to_stdout
allow(hangman).to receive(:lose?).and_return(true)
allow(hangman).to receive(:win?).and_return(false)
expect { hangman.game_over? }.to output(/cat/).to_stdout
end
it "should return true" do
allow(hangman).to receive(:lose?).and_return(false)
allow(hangman).to receive(:win?).and_return(true)
expect(hangman.game_over?).to eq(true)
allow(hangman).to receive(:lose?).and_return(true)
allow(hangman).to receive(:win?).and_return(false)
expect(hangman.game_over?).to eq(true)
end
end
context "when the game is not over" do
it "should return false" do
allow(hangman).to receive(:lose?).and_return(false)
allow(hangman).to receive(:win?).and_return(false)
expect(hangman.game_over?).to eq(false)
end
end
end
end
end
| 34.885572 | 86 | 0.622647 |
ff13c1427f6e6690329800332acd5c9796e087de | 813 | # frozen_string_literal: true
RSpec.describe ZohoHub::WithAttributes do
class TestClass
include ZohoHub::WithAttributes
attributes :one, :two, :three
end
describe '.attributes' do
context 'when attributes are passed' do
it 'adds the attributes to the list of attr_accessors' do
test = TestClass.new
test.one = 1
test.two = 2
expect(test.one).to eq(1)
expect(test.two).to eq(2)
end
end
context 'when attributes are not passed' do
it 'returns the list of attributes' do
expect(TestClass.attributes).to eq(%i[one two three])
end
end
end
describe '#attributes' do
it 'returns the class attributes' do
test = TestClass.new
expect(test.attributes).to eq(%i[one two three])
end
end
end
| 22.583333 | 63 | 0.644526 |
4a1527e41e9a4779d55ef30de090d31aae3ef55e | 407 | # frozen_string_literal: true
require 'dry/struct'
module Httpc
module Structs
class HttpResponse < Dry::Struct
attribute :content, Types::Strict::String
attribute :status_code, Types::Strict::Int
attribute :url_after_redirects, Types::String.optional
attribute :content_type, Types::String.optional
def success?
status_code == 200
end
end
end
end
| 21.421053 | 60 | 0.690418 |
3327211ea0f171405184edc0d808c8112116fd51 | 189 | class ExerciseSerializer < ActiveModel::Serializer
attributes :id, :name,:description,:reps,:author_id,:rest_period,:equipment_needed,:weight,:sets,:rating
has_many :target_muscles
end
| 37.8 | 106 | 0.804233 |
26b5c450eb98d51392731d0cb9484382ba510a1e | 9,976 | require 'rails_helper'
RSpec.describe TestTrack::ConfigUpdater do
let(:schema_file_path) { Rails.root.join('tmp', 'test_track_schema.yml') }
let(:errors) { double(full_messages: ["this is wrong"]) }
subject { described_class.new(schema_file_path) }
before do
File.delete(schema_file_path) if File.exist?(schema_file_path)
end
describe "#drop_split" do
it "destroys the split config" do
allow(TestTrack::Remote::SplitConfig).to receive(:destroy_existing).and_call_original
expect(subject.drop_split(:old_split)).to be_truthy
expect(TestTrack::Remote::SplitConfig).to have_received(:destroy_existing).with(:old_split)
end
context "schema file" do
it "removes the split from the schema file" do
given_schema <<-YML.strip_heredoc
---
identifier_types: []
splits:
old_split:
'false': 50
'true': 50
YML
subject.drop_split(:old_split)
expect_schema <<-YML.strip_heredoc
---
identifier_types: []
splits: {}
YML
end
end
context "aliased as #finish_split" do
it "destroys the split config" do
allow(TestTrack::Remote::SplitConfig).to receive(:destroy_existing).and_call_original
expect(subject.finish_split(:old_split)).to be_truthy
expect(TestTrack::Remote::SplitConfig).to have_received(:destroy_existing).with(:old_split)
end
end
end
describe "#split" do
let(:split_config) { instance_double(TestTrack::Remote::SplitConfig, save: true) }
let(:invalid_split_config) { instance_double(TestTrack::Remote::SplitConfig, save: false, errors: errors) }
it "updates split_config" do
allow(TestTrack::Remote::SplitConfig).to receive(:new).and_call_original
expect(subject.split(:name, foo: 20, bar: 80)).to be_truthy
expect(TestTrack::Remote::SplitConfig).to have_received(:new).with(name: :name, weighting_registry: { foo: 20, bar: 80 })
end
it "calls save on the split" do
allow(TestTrack::Remote::SplitConfig).to receive(:new).and_return(split_config)
expect(subject.split(:name, foo: 20, bar: 80)).to be_truthy
expect(split_config).to have_received(:save)
end
it "blows up if the split doesn't save" do
allow(TestTrack::Remote::SplitConfig).to receive(:new).and_return(invalid_split_config)
expect { subject.split(:name, foo: 20, bar: 80) }.to raise_error(/this is wrong/)
end
context "schema file" do
it "persists the splits" do
subject.split(:name, foo: 20, bar: 80)
expect_schema <<-YML.strip_heredoc
---
identifier_types: []
splits:
name:
bar: 80
foo: 20
YML
end
it "persists multiple splits" do
subject.split(:name, foo: 20, bar: 80)
subject.split(:gnome, baz: 30, bop: 70)
subject.split(:nom, wibble: 40, wobble: 60)
expect_schema <<-YML.strip_heredoc
---
identifier_types: []
splits:
gnome:
baz: 30
bop: 70
name:
bar: 80
foo: 20
nom:
wibble: 40
wobble: 60
YML
end
it "does not overwrite existing splits" do
given_schema <<-YML.strip_heredoc
---
identifier_types:
- some_identifier_type
splits:
red_button:
'false': 50
'true': 50
YML
subject.split(:name, foo: 20, bar: 80)
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- some_identifier_type
splits:
name:
bar: 80
foo: 20
red_button:
'false': 50
'true': 50
YML
end
it "deletes splits that are no longer on the test track server" do
given_schema <<-YML.strip_heredoc
---
identifier_types:
- some_identifier_type
splits:
blue_button:
'false': 50
'true': 50
really_old_split:
'false': 50
'true': 50
YML
allow(TestTrack::Remote::SplitRegistry).to receive(:reset).and_call_original
allow(TestTrack::Remote::SplitRegistry).to receive(:to_hash).and_return(
"blue_button" => { "true" => 50, "false" => 50 },
"split_for_another_app" => { "true" => 50, "false" => 50 }
)
subject.split(:name, foo: 20, bar: 80)
expect(TestTrack::Remote::SplitRegistry).to have_received(:reset)
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- some_identifier_type
splits:
blue_button:
'false': 50
'true': 50
name:
bar: 80
foo: 20
YML
end
it "alphabetizes the splits and the weighting registries" do
given_schema <<-YML.strip_heredoc
---
identifier_types: []
splits:
a:
'false': 50
'true': 50
b:
'false': 50
'true': 50
d:
'false': 50
'true': 50
YML
subject.split(:c, true: 50, false: 50)
expect_schema <<-YML.strip_heredoc
---
identifier_types: []
splits:
a:
'false': 50
'true': 50
b:
'false': 50
'true': 50
c:
'false': 50
'true': 50
d:
'false': 50
'true': 50
YML
end
end
end
describe "#identifier_type" do
let(:identifier_type) { instance_double(TestTrack::Remote::IdentifierType, save: true) }
let(:invalid_identifier_type) { instance_double(TestTrack::Remote::IdentifierType, save: false, errors: errors) }
it "updates identifier_type" do
allow(TestTrack::Remote::IdentifierType).to receive(:new).and_call_original
expect(subject.identifier_type(:my_id)).to be_truthy
expect(TestTrack::Remote::IdentifierType).to have_received(:new).with(name: :my_id)
end
it "calls save on the identifier_type" do
allow(TestTrack::Remote::IdentifierType).to receive(:new).and_return(identifier_type)
expect(subject.identifier_type(:my_id)).to be_truthy
expect(identifier_type).to have_received(:save)
end
it "blows up if the identifier_type doesn't save" do
allow(TestTrack::Remote::IdentifierType).to receive(:new).and_return(invalid_identifier_type)
expect { subject.identifier_type(:my_id) }.to raise_error(/this is wrong/)
end
context "schema file" do
it "persists the identifier types" do
subject.identifier_type(:my_id)
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- my_id
splits: {}
YML
end
it "alphabetizes the identifier types" do
subject.identifier_type(:b)
subject.identifier_type(:a)
subject.identifier_type(:d)
subject.identifier_type(:c)
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- a
- b
- c
- d
splits: {}
YML
end
it "does not overwrite existing identifier types" do
given_schema <<-YML.strip_heredoc
---
identifier_types:
- some_identifier_type
splits:
blue_button:
'false': 50
'true': 50
YML
subject.identifier_type(:my_id)
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- my_id
- some_identifier_type
splits:
blue_button:
'false': 50
'true': 50
YML
end
end
end
describe "#load_schema" do
it "updates the split_config and identifier_types" do
allow(TestTrack::Remote::SplitConfig).to receive(:new).and_call_original
allow(TestTrack::Remote::IdentifierType).to receive(:new).and_call_original
given_schema <<-YML.strip_heredoc
---
identifier_types:
- a
- b
- c
splits:
balance_unit:
dollar: 50
pound: 25
doge: 25
blue_button:
'false': 50
'true': 50
YML
subject.load_schema
expect(TestTrack::Remote::SplitConfig).to have_received(:new).with(
name: "balance_unit",
weighting_registry: { "dollar" => 50, "pound" => 25, "doge" => 25 }
)
expect(TestTrack::Remote::SplitConfig).to have_received(:new).with(
name: "blue_button",
weighting_registry: { "true" => 50, "false" => 50 }
)
expect(TestTrack::Remote::IdentifierType).to have_received(:new).with(name: "a")
expect(TestTrack::Remote::IdentifierType).to have_received(:new).with(name: "b")
expect(TestTrack::Remote::IdentifierType).to have_received(:new).with(name: "c")
expect_schema <<-YML.strip_heredoc
---
identifier_types:
- a
- b
- c
splits:
balance_unit:
dollar: 50
pound: 25
doge: 25
blue_button:
'false': 50
'true': 50
YML
end
end
def given_schema(yaml)
File.open(schema_file_path, "w") do |f|
f.write yaml
end
allow(TestTrack::Remote::SplitRegistry).to receive(:to_hash).and_return(YAML.safe_load(yaml)["splits"])
end
def expect_schema(yaml)
File.open(schema_file_path, "r") do |f|
expect(f.read).to eq yaml
end
end
end
| 28.502857 | 127 | 0.558641 |
1d4bbe2a0ec9e8719b8685cd6abcaaef319c984a | 1,182 | # encoding: UTF-8
#= ruby-hl7.rb
# Ruby HL7 is designed to provide a simple, easy to use library for
# parsing and generating HL7 (2.x) messages.
#
#
# Author: Mark Guzman (mailto:[email protected])
#
# Copyright: (c) 2006-2009 Mark Guzman
#
# License: BSD
#
# $Id$
#
# == License
# see the LICENSE file
#
require 'rubygems'
require 'stringio'
require 'date'
module HL7 # :nodoc:
VERSION = '1.2.3'
def self.ParserConfig
@parser_cfg ||= { :empty_segment_is_error => true }
end
end
# Encapsulate HL7 specific exceptions
class HL7::Exception < StandardError
end
# Parsing failed
class HL7::ParseError < HL7::Exception
end
# Attempting to use an invalid indice
class HL7::RangeError < HL7::Exception
end
# Attempting to assign invalid data to a field
class HL7::InvalidDataError < HL7::Exception
end
# Attempting to add an empty segment
# This error per configuration setting
class HL7::EmptySegmentNotAllowed < HL7::ParseError
end
require 'message_parser'
require 'message'
require 'segment_list_storage'
require 'segment_generator'
require 'segment_fields'
require 'segment'
require 'segment_default'
require 'core_ext/date_time'
require 'core_ext/string'
| 19.377049 | 67 | 0.744501 |
03ec6d6e54563e9e34f853168a2660d0d9fbe871 | 368 | require "bundler/setup"
require "elite_trader"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.533333 | 66 | 0.755435 |
bbd02021afe5c3e7cf77a5705dbc35215b3c9df5 | 1,213 | class Odpi < Formula
desc "Oracle Database Programming Interface for Drivers and Applications"
homepage "https://oracle.github.io/odpi/"
url "https://github.com/oracle/odpi/archive/v3.3.0.tar.gz"
sha256 "113349161c95e6a896fafed6f1f4160547435848b8fe06fce9659738a7c5e8f5"
bottle do
cellar :any
sha256 "72b2a344080349aaf5f6aaa6167f43df59e5dd7da3d8912d60eb989058e35624" => :catalina
sha256 "7505b4d90a69f0fca41be9316063e4eeb858fd7c9b8b795274532eb3b5248b25" => :mojave
sha256 "fa3483646ef433386054229455ffe1a0109d6bb007cdaa8693c9d97ebd82f301" => :high_sierra
sha256 "f25b9d7fc748ea250f30fe171f268f940ed5462e7e4da1c9b8eb16167a8579db" => :x86_64_linux
end
def install
system "make"
lib.install Dir["lib/*"]
include.install Dir["include/*"]
end
test do
(testpath/"test.c").write <<~EOS
#include <stdio.h>
#include <dpi.h>
int main()
{
dpiContext* context = NULL;
dpiErrorInfo errorInfo;
dpiContext_create(DPI_MAJOR_VERSION, DPI_MINOR_VERSION, &context, &errorInfo);
return 0;
}
EOS
system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lodpic", "-o", "test"
system "./test"
end
end
| 28.880952 | 94 | 0.704864 |
7955097a7176eb362077a5434b86871d7361a61d | 189 | # frozen_string_literal: true
module Daitai
module SortWith
def sort_with
lambda do |comparator, sortable|
sortable.sort(&comparator)
end.curry
end
end
end
| 15.75 | 38 | 0.677249 |
d55a00bf4fba8e977fe28dbf7843a610e6256685 | 1,310 | require './lib/brakeman/version'
require './gem_common'
gem_priv_key = File.expand_path("~/.ssh/gem-private_key.pem")
Gem::Specification.new do |s|
s.name = %q{brakeman}
s.version = Brakeman::Version
s.authors = ["Justin Collins"]
s.email = "[email protected]"
s.summary = "Security vulnerability scanner for Ruby on Rails."
s.description = "Brakeman detects security vulnerabilities in Ruby on Rails applications via static analysis."
s.homepage = "http://brakemanscanner.org"
s.files = ["bin/brakeman", "CHANGES.md", "FEATURES", "README.md"] + Dir["lib/**/*"]
s.executables = ["brakeman"]
s.license = "Brakeman Public Use License"
s.cert_chain = ['brakeman-public_cert.pem']
s.signing_key = gem_priv_key if File.exist? gem_priv_key and $0 =~ /gem\z/
if File.exist? 'bundle/load.rb'
# Pull in vendored dependencies
s.files << 'bundle/load.rb'
s.files += Dir['bundle/ruby/*/gems/**/*'].reject do |path|
# Skip unnecessary files in dependencies
path =~ /^bundle\/ruby\/\d\.\d\.\d\/gems\/[^\/]+\/(Rakefile|benchmark|bin|doc|example|man|site|spec|test)/
end
else
Brakeman::GemDependencies.dev_dependencies(s) unless ENV['BM_PACKAGE']
Brakeman::GemDependencies.base_dependencies(s)
Brakeman::GemDependencies.extended_dependencies(s)
end
end
| 39.69697 | 112 | 0.694656 |
2886e3d87eb0bf0dc0afd5957e3695a4248eee21 | 1,422 | # +-------------------------------------------------------------------------
# | Copyright (C) 2016 Yunify, Inc.
# +-------------------------------------------------------------------------
# | Licensed under the Apache License, Version 2.0 (the "License");
# | you may not use this work except in compliance with the License.
# | You may obtain a copy of the License in the LICENSE file, or 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 'qingstor/sdk'
# ----------------------------------------------------------------------------
When(/^initialize QingStor service$/) do
init_qingstor_service
end
Then(/^the QingStor service is initialized$/) do
raise if @qs_service.nil?
end
# ----------------------------------------------------------------------------
When(/^list buckets$/) do
@list_buckets_output = @qs_service.list_buckets
end
Then(/^list buckets status code is (\d+)$/) do |status_code|
raise unless @list_buckets_output[:status_code].to_s == status_code
end
| 37.421053 | 78 | 0.528129 |
1ac78070daeceea874c8d7b2e0fe9d7b7601c9ee | 1,553 | require 'rails_helper'
require_relative 'shared_examples'
RSpec.describe DeliverPetitionEmailJob, type: :job do
let(:requested_at) { Time.current.change(usec: 0) }
let(:requested_at_as_string) { requested_at.getutc.iso8601(6) }
let(:petition) { FactoryBot.create(:debated_petition) }
let(:signature) { FactoryBot.create(:validated_signature, petition: petition) }
let(:email) { FactoryBot.create(:petition_email, petition: petition) }
let(:timestamp_name) { 'petition_email' }
let :arguments do
{
signature: signature,
timestamp_name: timestamp_name,
petition: petition,
requested_at: requested_at_as_string,
email: email
}
end
before do
petition.set_email_requested_at_for(timestamp_name, to: requested_at)
end
it_behaves_like "a job to send an signatory email"
context "when the signature is the creator" do
before do
allow(signature).to receive(:creator?).and_return(true)
end
it "uses the correct notify job to generate the email" do
expect {
subject.perform(**arguments)
}.to have_enqueued_job(EmailCreatorAboutOtherBusinessEmailJob).with(signature, email)
end
end
context "when the signature is not the creator" do
before do
allow(signature).to receive(:creator?).and_return(false)
end
it "uses the correct mailer method to generate the email" do
expect {
subject.perform(**arguments)
}.to have_enqueued_job(EmailSignerAboutOtherBusinessEmailJob).with(signature, email)
end
end
end
| 29.301887 | 91 | 0.717321 |
7aff8be2a86addcd57dd7e4e6e49f06a7c28a860 | 164 | class AddThumbToSong < ActiveRecord::Migration
def self.up
add_column :songs, :thumb, :text
end
def self.down
remove_column :songs, :thumb
end
end
| 16.4 | 46 | 0.707317 |
e23a9829d9f27b0978073ca0a85b342cb96f042f | 1,475 | # -*- encoding: utf-8 -*-
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes.rb', __FILE__)
describe "String#upcase" do
it "returns a copy of self with all lowercase letters upcased" do
"Hello".upcase.should == "HELLO"
"hello".upcase.should == "HELLO"
end
ruby_version_is ''...'2.4' do
it "is locale insensitive (only replaces a-z)" do
"äöü".upcase.should == "äöü"
str = Array.new(256) { |c| c.chr }.join
expected = Array.new(256) do |i|
c = i.chr
c.between?("a", "z") ? c.upcase : c
end.join
str.upcase.should == expected
end
end
it "taints result when self is tainted" do
"".taint.upcase.tainted?.should == true
"X".taint.upcase.tainted?.should == true
"x".taint.upcase.tainted?.should == true
end
it "returns a subclass instance for subclasses" do
StringSpecs::MyString.new("fooBAR").upcase.should be_an_instance_of(StringSpecs::MyString)
end
end
describe "String#upcase!" do
it "modifies self in place" do
a = "HeLlO"
a.upcase!.should equal(a)
a.should == "HELLO"
end
it "returns nil if no modifications were made" do
a = "HELLO"
a.upcase!.should == nil
a.should == "HELLO"
end
it "raises a RuntimeError when self is frozen" do
lambda { "HeLlo".freeze.upcase! }.should raise_error(RuntimeError)
lambda { "HELLO".freeze.upcase! }.should raise_error(RuntimeError)
end
end
| 27.314815 | 94 | 0.64678 |
87e81a4642a3da9649b0b4b5cffe0b9f46e31c34 | 1,844 | require 'spec_helper'
describe 'plugin install' do
step_into :node_build_plugin_install
platform 'ubuntu'
context 'with default attributes' do
recipe do
node_build_plugin_install '/tmp/plugins/default-attributes'
end
it { is_expected.to install_node_build_plugin_install('/tmp/plugins/default-attributes') }
it { is_expected.to create_directory(::File.dirname('/tmp/plugins/default-attributes')).with(user: nil, group: nil) }
it { is_expected.to sync_git('/tmp/plugins/default-attributes').with(repository: 'https://github.com/nodenv/node-build.git', revision: 'master') }
end
context 'with custom attributes' do
recipe do
node_build_plugin_install '/tmp/plugins/custom-attributes' do
owner 'user'
group 'group'
git_url 'https://url.git'
git_revision 'revision'
end
end
it { is_expected.to install_node_build_plugin_install('/tmp/plugins/custom-attributes') }
it { is_expected.to create_directory(::File.dirname('/tmp/plugins/custom-attributes')).with(user: 'user', group: 'group') }
it { is_expected.to sync_git('/tmp/plugins/custom-attributes').with(repository: 'https://url.git', revision: 'revision') }
end
context 'with deprecated attributes' do
let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
recipe do
node_build_plugin_install '/tmp/plugins/deprecated-attributes' do
user 'user'
end
end
it do
RSpec.configure { |config| config.log_level = :warn }
expect { chef_run }
.to not_raise_error
.and output(/User property is deprecated/).to_stdout_from_any_process
RSpec.configure { |config| config.log_level = :fatal }
end
it { is_expected.to sync_git('/tmp/plugins/deprecated-attributes').with(user: 'user', group: nil) }
end
end
| 35.461538 | 150 | 0.698482 |
28c7a50bfb4d9faedfdbe94cf530b07dafc95667 | 649 | # == Schema Information
#
# Table name: diagnosticos
#
# id :integer not null, primary key
# historia_clinica_id :integer
# cie10_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Diagnostico < ActiveRecord::Base
belongs_to :historia_clinica
belongs_to :cie10
#validates :codigo, :presence => { message: " Es un Campo Obligatorio" }, if: -> { required_for_step?(:e_impresion_diagnostica) }
#validates :descripcion, :presence => { message: " Es un Campo Obligatorio" }, if: -> { required_for_step?(:e_impresion_diagnostica) }
end
| 32.45 | 136 | 0.647149 |
395b1f5b08ee96d895d7fad4870cabbe5b89d96a | 669 | cask 'chatty' do
version '0.9.3'
sha256 'f99c14bc5914e9c623652f5f834c93c5982724739964f7039218c2d6adeaf8f5'
# github.com/chatty/chatty was verified as official when first introduced to the cask
url "https://github.com/chatty/chatty/releases/download/v#{version}/Chatty_#{version}.zip"
appcast 'https://github.com/chatty/chatty/releases.atom'
name 'Chatty'
homepage 'https://chatty.github.io/'
suite 'Chatty'
preflight do
# There is no sub-folder in the ZIP; the root *is* the folder
FileUtils.mv(staged_path.children, staged_path.join('Chatty').tap(&:mkpath))
end
zap trash: '~/.chatty'
caveats do
depends_on_java '7+'
end
end
| 27.875 | 92 | 0.729447 |
d58e6a2607a3039f47ae9af4a3c8204d50cb0596 | 1,306 | class Rclone < Formula
desc "Rsync for cloud storage"
homepage "https://rclone.org/"
url "https://github.com/ncw/rclone/archive/v1.50.0.tar.gz"
sha256 "d428befa998f08f0767d8dff66641e497de4d7e834ed5a3347453938d886b26b"
head "https://github.com/ncw/rclone.git"
bottle do
cellar :any_skip_relocation
sha256 "2664279c78128cf49abd8ed8f36f81939c4f6ff844d470eda916f6719f36982a" => :catalina
sha256 "822807a26e15e713b8761188777effc00c3ab6c39037183e7e1b217b134e7413" => :mojave
sha256 "11daaf06fe25bf93bed5115dfaf3f527812864eb3e938a95bbd64c6ffa6deefe" => :high_sierra
end
depends_on "go" => :build
def install
ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache"
mkdir_p buildpath/"src/github.com/ncw/"
ln_s buildpath, buildpath/"src/github.com/ncw/rclone"
system "go", "build", "-o", bin/"rclone"
man1.install "rclone.1"
system bin/"rclone", "genautocomplete", "bash", "rclone.bash"
system bin/"rclone", "genautocomplete", "zsh", "_rclone"
bash_completion.install "rclone.bash" => "rclone"
zsh_completion.install "_rclone"
end
test do
(testpath/"file1.txt").write "Test!"
system "#{bin}/rclone", "copy", testpath/"file1.txt", testpath/"dist"
assert_match File.read(testpath/"file1.txt"), File.read(testpath/"dist/file1.txt")
end
end
| 37.314286 | 93 | 0.728943 |
1d117fb3034b76593b07c769c7fde533f5a858ce | 886 | # Copyright (C) 2015-2017 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/collection/view/builder/aggregation'
require 'mongo/collection/view/builder/map_reduce'
require 'mongo/collection/view/builder/op_query'
require 'mongo/collection/view/builder/find_command'
require 'mongo/collection/view/builder/flags'
require 'mongo/collection/view/builder/modifiers'
| 42.190476 | 74 | 0.786682 |
e2d114db089b9f5a81aa4846a044af0d5da150cb | 565 | #!/usr/bin/env ruby
require 'kramdown'
require_relative 'configuration'
=begin
This file contains utility functions several different files may
want access to, like markdown rendering.
=end
def getMarkdown(filename)
begin
t = File.read(Configuration::Private + "/" + filename)
return Kramdown::Document.new(t).to_html
rescue Exception => e
return ""
end
end
def getDirSize(dirname)
size = 0
for filename in Dir.entries(dirname)
if( filename != "." and filename != ".." )
size += File.size(dirname + "/" + filename)
end
end
return size
end
| 19.482759 | 65 | 0.709735 |
ed8fcc77e28f5291cb7b563c645cdc340b78e915 | 459 | class NabesController < ApplicationController
before_action :force_compression
def index
data =
Place
.where.not(post_published_at: nil) # skip places missing posts
.pluck(:cached_nabes) # aggregate cached nabes data
.flatten # dedupe and sort
.uniq { |n| n["identifier"] }
.sort_by { |n| n["name"] }
render json: {
meta: {
count: data.size
},
data: data
}
end
end
| 19.956522 | 70 | 0.586057 |
3984659a8d295b54ab647ddd4f6b2eb49259c5a0 | 347 | ENV['RACK_ENV'] = 'test'
require "sinatra/activerecord"
require "division"
require "employee"
require "rspec"
require "pry"
require "pg"
RSpec.configure do |config|
config.after(:each) do
Division.all().each() do |division|
division.destroy()
end
Employee.all().each() do |employee|
employee.destroy()
end
end
end
| 18.263158 | 39 | 0.67147 |
e8b33b48b296dee4456c61c63e6a33c1b5a4cdc5 | 12,062 | class OrdersController < ApplicationController
before_action :logged_in_user, only: [:list_orders, :show, :destroy,
:add_one_item_to_order,
:add_items_in_shopping_cart_to_order,
:month_income, :year_income, :monthly, :month_average]
before_action :correct_user, only: [:list_orders, :destroy, :month_income, :year_income,
:monthly, :month_average]
protect_from_forgery :except => :index
@@pre_time_monthly = nil
@@pre_time_month_average = nil
@@pre_time_month_income = nil
@@pre_time_year_income = nil
def list_orders
# @user = current_user
@user = User.find(params[:id])
@orders = @user.orders.paginate(:page => params[:page], :per_page => 6)
@orders_not_finished = []
@orders_finished = []
@user.orders.each do |item|
is_finished = true
item.order_items.each do |sub_item|
if sub_item.progress < 4
is_finished = false
break
end
end
if is_finished
@orders_finished.append(item)
else
@orders_not_finished.append(item)
end
end
end
def show
@order = Order.find(params[:id])
@user = @order.user
@order_items = @order.order_items.paginate(:page => params[:page], :per_page => 6)
end
def destroy
if params[:order_id].blank?
@item = Order.find(params[:id])
else
@item = Order.find(params[:order_id])
end
order_id = @item.id
is_buyer_order = false
if @item.link_order_id.nil?
is_buyer_order = true
end
@item.destroy
if is_buyer_order
Order.all.each do |item|
if item.link_order_id == order_id
item.destroy
end
end
end
flash[:success] = "Order id #{order_id} deleted!"
if current_user.character != 'administrator'
redirect_to(list_orders_path(id: params[:id]))
else
redirect_to('/all_orders')
end
end
def add_one_item_to_order
@product = Product.find(params[:id])
@shop = Shop.find(@product.shop_id)
@seller = User.find(@shop.user_id)
lack_info = []
if current_user.receiver_name.blank?
lack_info.append('收货人姓名')
end
if current_user.receiver_address.blank?
lack_info.append('收货人地址')
end
if current_user.receiver_name.blank?
lack_info.append('收货人联系电话')
end
if lack_info != []
flash[:danger] = "请完善您的 " + lack_info.inject { |all_info, info| all_info + ', ' + info }
else
@order_buyer = Order.new(receiver_name: current_user.receiver_name,
receiver_address: current_user.receiver_address,
receiver_phone_number: current_user.receiver_phone_number,
order_time: Time.now, user_id: current_user.id,
total_price: @product.price)
@order_buyer.save
@order_seller = Order.new(link_order_id: @order_buyer.id,
receiver_name: current_user.receiver_name,
receiver_address: current_user.receiver_address,
receiver_phone_number: current_user.receiver_phone_number,
order_time: Time.now, user_id: @seller.id,
total_price: @product.price)
@order_seller.save
@first = OrderItem.new(product_id: @product.id, amount: 1,
order_id: @order_buyer.id, progress: 0,
total_price: @product.price)
@first.save
@second = OrderItem.new(product_id: @product.id, amount: 1,
order_id: @order_seller.id, corresponding_id: @first.id, progress: 0,
total_price: @product.price)
@second.save
@first.update(:corresponding_id => @second.id)
flash[:success] = "您已购买该商品!"
end
redirect_to(@product)
end
def add_items_in_shopping_cart_to_order
lack_info = []
if current_user.receiver_name.blank?
lack_info.append('收货人姓名')
end
if current_user.receiver_address.blank?
lack_info.append('收货人地址')
end
if current_user.receiver_name.blank?
lack_info.append('收货人联系电话')
end
if lack_info != []
flash[:danger] = "请完善您的 " + lack_info.inject { |all_info, info| all_info + ', ' + info }
else
@shopping_cart = current_user.shopping_cart
@order_buyer = Order.new(receiver_name: current_user.receiver_name,
receiver_address: current_user.receiver_address,
receiver_phone_number: current_user.receiver_phone_number,
order_time: Time.now,
user_id: current_user.id)
@order_buyer.save
buyer_order_value_cnt = 0.0
created_order = Hash.new
order_seller_list = []
@shopping_cart.shopping_cart_items.each do |t|
@product = t.product
@shop = Shop.find(@product.shop_id)
@seller = User.find(@shop.user_id)
if !created_order.has_key?(@product.shop_id)
@order_seller = Order.new(link_order_id: @order_buyer.id,
receiver_name: current_user.receiver_name,
receiver_address: current_user.receiver_address,
receiver_phone_number: current_user.receiver_phone_number,
order_time: Time.now,
user_id: @seller.id)
order_seller_list.append(@order_seller)
@order_seller.save
created_order[@product.shop_id] = @order_seller.id
end
@first = OrderItem.new(product_id: @product.id, amount: t.amount,
order_id: @order_buyer.id, progress: 0,
total_price: t.amount * @product.price)
@first.save
@second = OrderItem.new(product_id: @product.id, amount: t.amount,
order_id: created_order[@product.shop_id],
corresponding_id: @first.id, progress: 0,
total_price: t.amount * @product.price)
buyer_order_value_cnt += t.amount * @product.price
@second.save
@first.update(:corresponding_id => @second.id)
t.destroy
flash[:success] = "您已成功购买购物车中的商品!"
end
@order_buyer.update(total_price: buyer_order_value_cnt)
order_seller_list.each do |item|
seller_order_value_cnt = 0
item.order_items.each do |sub_item|
seller_order_value_cnt += sub_item.total_price
end
item.update(total_price: seller_order_value_cnt)
end
end
redirect_to(user_shopping_cart_path(current_user.id))
end
def graph
@user = User.find(params[:user_id])
# 'debug>>>>>>>>>', current_user, @user, current_user == @user
end
def monthly
@user = User.find(params[:user_id])
# print 'debug>>>>>>curuser', current_user.name
if params[:time].blank?
if params.keys.count == 4
redirect_to(order_graph_path)
return
else
if @@pre_time_monthly.nil?
redirect_to(order_graph_path)
end
time = @@pre_time_monthly.to_s.split('-')
end
else
time = params[:time].to_s.split('-')
@@pre_time_monthly = params[:time]
end
year = time[0]
month = time[1]
number_of_days = days_in_month(year.to_i, month.to_i)
@days = (1..number_of_days).to_a
@quantity = []
@number = []
(1..number_of_days).each do |date|
sum = 0
number_day = 0
Order.where(user_id: @user.id, order_time: year + '-' + month + '-' + date.to_s).find_each do |item|
number_order = 0
sum += item.total_price
item.order_items.find_each do |order_item|
number_order += order_item.amount
end
number_day += number_order
end
@number.append(number_day)
@quantity.append(sum)
end
end
def month_average
@user = User.find(params[:user_id])
if params[:time].blank?
if params.keys.count == 4
redirect_to(order_graph_path)
return
else
if @@pre_time_month_average.nil?
redirect_to(order_graph_path)
end
year = @@pre_time_month_average.to_s
end
else
year = params[:time].to_s
@@pre_time_month_average = params[:time]
end
@month = %w(01 02 03 04 05 06 07 08 09 10 11 12)
@quantity = []
@month.each do |month|
sum = 0
Order.where("user_id = :uid and order_time >= :s_time and order_time <= :e_time", {uid: @user.id, s_time: year + '-' + month + '-01', e_time: year + '-' + month + '-' + days_in_month(year.to_i, month.to_i).to_s}).find_each do |item|
sum += item.total_price
end
#puts sum
@quantity.append(sum)
end
sum = 0
(0..11).each do |i|
sum += @quantity[i]
end
@avg = sum / 12
#puts @month
#puts @quantity
end
def category
categories = Hash["clothes" => 0, "books" => 1, "office" => 2, "digital" => 3, "entertainment" => 4, "fruits_and_animals" => 5, "virtual_items" => 6]
@sum = Array.new
(0..6).each do |i|
@sum[i] = 0
end
Order.where(user_id: params[:user_id]).find_each do |order|
order.order_items.each do |item|
product = item.product
if categories.has_key?(product.category)
@sum[categories[product.category]] += item.amount
end
end
end
end
def month_income
@user = User.find(params[:user_id])
if params[:time].blank?
if params.keys.count == 4
redirect_to(order_graph_path)
return
else
if @@pre_time_month_income.nil?
redirect_to(order_graph_path)
end
time = @@pre_time_month_income.to_s.split('-')
end
else
time = params[:time].to_s.split('-')
@@pre_time_month_income = params[:time]
end
year = time[0]
month = time[1]
number_of_days = days_in_month(year.to_i, month.to_i)
@days = (1..number_of_days).to_a
@income = Array.new(number_of_days, 0)
Order.where(user_id: @user.id).find_each do |order|
order_time = order.order_time
if year == order_time.year.to_s and month == order_time.month.to_s
@income[(order_time.day) - 1] += order.total_price
end
end
#print @income
end
def year_income
@user = User.find(params[:user_id])
if params[:time].blank?
if params.keys.count == 4
redirect_to(order_graph_path)
return
else
if @@pre_time_year_income.nil?
redirect_to(order_graph_path)
end
year = @@pre_time_year_income.to_s
end
else
year = params[:time].to_s
@@pre_time_year_income = params[:time]
end
@income = Array.new(12, 0)
Order.where(user_id: @user.id).find_each do |order|
order_time = order.order_time
if year == order_time.year.to_s
@income[(order_time.month) - 1] += order.total_price
end
end
#print @income
sum = 0
(0..11).each do |i|
sum += @income[i]
end
@avg = sum / 12
end
private
def days_in_month(year, month)
big = [1, 3, 5, 7, 8, 10, 12]
small = [4, 6, 9, 11]
if big.include?(month)
return 31
end
if small.include?(month)
return 30
end
if year % 4 == 0 && year % 100 != 0 || year % 400 == 0
return 29
else
return 28
end
end
end
| 33.692737 | 239 | 0.567153 |
79db51beff1a19457c8e099cb571732f1bfa6932 | 865 |
require 'rake'
Gem::Specification.new do |s|
s.name = 'firefox-data'
s.version = '1.0.2'
s.date = '2017-04-30'
s.summary = 'A library to extract data from firefox profiles.'
s.description = 'The firefox-data library extracts various types of ' + \
'data from firefox profiles.'
s.homepage = 'https://github.com/galdor/rb-firefox-data'
s.license = 'ISC'
s.author = 'Nicolas Martyanoff'
s.email = '[email protected]'
s.required_ruby_version = '>= 2.4.0'
s.files = FileList['firefox-data.gemspec', 'LICENSE',
'bin/*.rb', 'lib/**/*.rb']
s.executables = ['firefox-data']
s.add_runtime_dependency 'ffi', '~> 1.9', '>= 1.9.17'
s.add_runtime_dependency 'json-schema', '~> 2.8', '>= 2.8.0'
s.add_runtime_dependency 'ruby-termios', '~> 1.0', '>= 1.0.2'
s.add_runtime_dependency 'thor', '~> 0.19', '>= 0.19.4'
end
| 32.037037 | 75 | 0.624277 |
e20ce9e10236c0e6282d98c203ea2b069760f523 | 1,172 | # frozen_string_literal: true
module PgRls
# Tenant Controller
module Tenant
class << self
def switch(resource)
connection_adapter = PgRls.connection_class
find_tenant(resource)
connection_adapter.connection.execute(format('SET rls.tenant_id = %s',
connection_adapter.connection.quote(tenant.tenant_id)))
"RLS changed to '#{tenant.send(@method)}'"
rescue StandardError => e
puts 'connection was not made'
puts @error || e
end
attr_reader :tenant
def fetch
@fetch ||= tenant.find_by_tenant_id(
PgRls.connection_class.connection.execute(
"SELECT current_setting('rls.tenant_id')"
).getvalue(0, 0)
)
rescue ActiveRecord::StatementInvalid
'no tenant is selected'
end
def find_tenant(resource)
@tenant = nil
PgRls.search_methods.each do |method|
@method = method
@tenant ||= PgRls.main_model.send("find_by_#{method}", resource)
rescue NoMethodError => e
@error = e
end
end
end
end
end
| 27.255814 | 108 | 0.587884 |
e97f69e6dbce436a82006373a83b5d793a79c99f | 5,666 | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that braces used for hash literals have or don't have
# surrounding space depending on configuration.
#
# @example EnforcedStyle: space (default)
# # The `space` style enforces that hash literals have
# # surrounding space.
#
# # bad
# h = {a: 1, b: 2}
#
# # good
# h = { a: 1, b: 2 }
#
# @example EnforcedStyle: no_space
# # The `no_space` style enforces that hash literals have
# # no surrounding space.
#
# # bad
# h = { a: 1, b: 2 }
#
# # good
# h = {a: 1, b: 2}
#
# @example EnforcedStyle: compact
# # The `compact` style normally requires a space inside
# # hash braces, with the exception that successive left
# # braces or right braces are collapsed together in nested hashes.
#
# # bad
# h = { a: { b: 2 } }
# foo = { { a: 1 } => { b: { c: 2 } } }
#
# # good
# h = { a: { b: 2 }}
# foo = {{ a: 1 } => { b: { c: 2 }}}
#
# @example EnforcedStyleForEmptyBraces: no_space (default)
# # The `no_space` EnforcedStyleForEmptyBraces style enforces that
# # empty hash braces do not contain spaces.
#
# # bad
# foo = { }
# bar = { }
#
# # good
# foo = {}
# bar = {}
#
# @example EnforcedStyleForEmptyBraces: space
# # The `space` EnforcedStyleForEmptyBraces style enforces that
# # empty hash braces contain space.
#
# # bad
# foo = {}
#
# # good
# foo = { }
# foo = { }
# foo = { }
#
class SpaceInsideHashLiteralBraces < Base
include SurroundingSpace
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Space inside %<problem>s.'
def on_hash(node)
tokens = processed_source.tokens_within(node)
return unless tokens.first.left_brace? && tokens.last.right_curly_brace?
check(tokens[0], tokens[1])
check(tokens[-2], tokens[-1]) if tokens.size > 2
end
private
def check(token1, token2)
# No offense if line break inside.
return if token1.line < token2.line
return if token2.comment? # Also indicates there's a line break.
is_empty_braces = token1.left_brace? && token2.right_curly_brace?
expect_space = expect_space?(token1, token2)
if offense?(token1, expect_space)
incorrect_style_detected(token1, token2,
expect_space, is_empty_braces)
else
correct_style_detected
end
end
def expect_space?(token1, token2)
is_same_braces = token1.type == token2.type
is_empty_braces = token1.left_brace? && token2.right_curly_brace?
if is_same_braces && style == :compact
false
elsif is_empty_braces
cop_config['EnforcedStyleForEmptyBraces'] != 'no_space'
else
style != :no_space
end
end
def incorrect_style_detected(token1, token2,
expect_space, is_empty_braces)
brace = (token1.text == '{' ? token1 : token2).pos
range = expect_space ? brace : space_range(brace)
detected_style = expect_space ? 'no_space' : 'space'
add_offense(range, message: message(brace, is_empty_braces, expect_space)) do |corrector|
autocorrect(corrector, range)
ambiguous_or_unexpected_style_detected(detected_style, token1.text == token2.text)
end
end
def autocorrect(corrector, range)
case range.source
when /\s/ then corrector.remove(range)
when '{' then corrector.insert_after(range, ' ')
else corrector.insert_before(range, ' ')
end
end
def ambiguous_or_unexpected_style_detected(style, is_match)
if is_match
ambiguous_style_detected(style, :compact)
else
unexpected_style_detected(style)
end
end
def offense?(token1, expect_space)
has_space = token1.space_after?
expect_space ? !has_space : has_space
end
def message(brace, is_empty_braces, expect_space)
inside_what = if is_empty_braces
'empty hash literal braces'
else
brace.source
end
problem = expect_space ? 'missing' : 'detected'
format(MSG, problem: "#{inside_what} #{problem}")
end
def space_range(token_range)
if token_range.source == '{'
range_of_space_to_the_right(token_range)
else
range_of_space_to_the_left(token_range)
end
end
def range_of_space_to_the_right(range)
src = range.source_buffer.source
end_pos = range.end_pos
end_pos += 1 while /[ \t]/.match?(src[end_pos])
range_between(range.begin_pos + 1, end_pos)
end
def range_of_space_to_the_left(range)
src = range.source_buffer.source
begin_pos = range.begin_pos
begin_pos -= 1 while /[ \t]/.match?(src[begin_pos - 1])
range_between(begin_pos, range.end_pos - 1)
end
end
end
end
end
| 30.961749 | 99 | 0.545711 |
1af5448e98c288d46b303bc031e2e6e3dcd94d2b | 650 | require_relative 'spec_helper'
describe DressCode::Generator do
before :each do
doc = DressCode::Document.new({
:component => 'button',
:prose => "```html\n<button>I am a button</button>\n```",
:path => '/whever/button.css',
:relative_path => 'button.css'
})
@docs = [doc]
end
it "generates the styleguide html file" do
generator = DressCode::Generator.new({
:out_file => 'tmp/styleguide.html',
:docs => @docs
})
generator.generate()
File.exists?('tmp/styleguide.html').should == true
# nokogiri this crap up
end
it "includes css files"
it "includes js files"
end
| 21.666667 | 63 | 0.613846 |
187f4c223defc083b71c441281497f5a7cf0cdf1 | 2,829 | RSpec.describe Owners do
describe ".for" do
subject { described_class.for(*paths) }
context "with one path" do
let(:paths) { ["example/app/controllers/users_controller.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["@org/auth", "@org/blog"])
end
end
context "with multiple paths" do
let(:paths) {[
"example/app/controllers/posts_controller.rb",
"example/app/models/user.rb",
]}
it "parses owners correctly" do
expect(subject).to eq(["@org/blog", "@org/auth", "[email protected]"])
end
end
context "with no paths" do
let(:paths) { [] }
it "parses owners correctly" do
expect(subject).to eq([])
end
end
context "with no matches" do
let(:paths) { ["some-path-without-owners"] }
it "parses owners correctly" do
expect(subject).to be_empty
end
end
context "with a regex matcher" do
let(:paths) { ["example/app/models/blog.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["[email protected]", "@blogger", "@org/blog"])
end
end
context "with a rule containing whitespace" do
let(:paths) { ["example/app/models/post.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["[email protected]", "@whitespace", "@org/blog"])
end
end
context "with multiple owners" do
let(:paths) { ["example/app/models/comment.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["[email protected]", "@owner", "@duplicate", "@org/blog"])
end
end
context "with multiple comma separated owners" do
let(:paths) { ["example/db/schema.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["@org/blog", "@multiple", "@owners"])
end
end
context "with empty comma separated owners" do
let(:paths) { ["example/db/schema.rb"] }
it "parses owners correctly" do
expect(subject).to eq(["@org/blog", "@multiple", "@owners"])
end
end
context "with comments" do
let(:paths) { ["example/comment"] }
it "parses owners correctly" do
expect(subject).to eq(["@org/blog"])
end
end
end
describe ".for_diff" do
subject { described_class.for_diff(ref, base_ref) }
context "when comparing one commit" do
let(:ref) { "781b3b2" }
let(:base_ref) { "6f4f89a" }
it "parses owners correctly" do
expect(subject).to eq(["@org/blog"])
end
end
context "when comparing multiple commits" do
let(:ref) { "781b3b2" }
let(:base_ref) { "ba7cd78" }
it "parses owners correctly" do
expect(subject).to eq(["@org/blog", "[email protected]", "@whitespace"])
end
end
end
end
| 25.486486 | 88 | 0.588194 |
e8c275acae195523f620174041ce6fa79f0079b9 | 1,228 | module Scrapbox2markdown
module Converters
class Heading
# [pattern, replace]
PATTERNS = [
[/\[\*\*\*\*\*\s(.*?)\]/, '# '],
[/\[\*\*\*\*\s(.*?)\]/, '## '],
[/\[\*\*\*\s(.*?)\]/, '### '],
[/\[\*\*\s(.*?)\]/, '##### '],
[/\[\*\s(.*?)\]/, '##### '],
[/\[\*{6,}\s(.*?)\]/, ''],
]
def initialize(lines)
@lines = lines
end
def convert!
@lines.each do |line|
PATTERNS.each do |pattern|
# インラインコードは変換しない
unmatch = /`.*#{pattern[0]}.*`/
to_headings!(line, pattern, unmatch)
end
end
end
# シンプルに見出しにするだけ
# インラインコードのことは考慮しない
def self.to_headings!(line)
PATTERNS.each do |pattern|
line.gsub!(pattern[0]) { |_| pattern[1] + $1 }
end
end
private
# [***** Heading] => # Heading
def to_headings!(line, pattern, unmatch)
convertibles = Scrapbox2markdown::Tokenizer.new(line, unmatch).convertible_tokens
convertibles.each do |convertible|
line.gsub!(convertible) { |match| match.sub(pattern[0]) { |_| pattern[1] + $1 }}
end
end
end
end
end
| 25.583333 | 90 | 0.444625 |
380f942e9a4d426d0f8a4958f7c4242ab8d9b7cb | 13,817 | # frozen_string_literal: true
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = 'e0d679b5c401cf80fbad8d16fa0d502611e6d7b1553fd830bda4b68dbdcd4616bf52ba0fcd0bb7f07f1e341038b9ee881ea96b7d2b9c2e4843dfdb35ad1da278'
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = '3d85fb331f122324e515bce3e90df42766082c385e08a6e76d3b848847c705a20a0e863b22089ba237eb31dfbd6ac1117370f92d06b10bd5120186a7204e948d'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 48.651408 | 154 | 0.751393 |
289e45807838f6a27fa9932f7c3f846027b87816 | 5,431 | module ActiveAdmin
# This is the class where all the register blocks are evaluated.
class ResourceDSL < DSL
def initialize(config, resource_class)
@resource = resource_class
super(config)
end
private
def belongs_to(target, options = {})
config.belongs_to(target, options)
end
# Scope collection to a relation
def scope_to(*args, &block)
config.scope_to(*args, &block)
end
# Create a scope
def scope(*args, &block)
config.scope(*args, &block)
end
# Store relations that should be included
def includes(*args)
config.includes.push *args
end
#
# Rails 4 Strong Parameters Support
#
# Either
#
# permit_params :title, :author, :body, tags: []
#
# Or
#
# permit_params do
# defaults = [:title, :body]
# if current_user.admin?
# defaults + [:author]
# else
# defaults
# end
# end
#
# Keys included in the `permitted_params` setting are automatically whitelisted.
#
def permit_params(*args, &block)
param_key = config.param_key.to_sym
controller do
define_method :permitted_params do
params.permit *active_admin_namespace.permitted_params,
param_key => block ? instance_exec(&block) : args
end
end
end
# Configure the index page for the resource
def index(options = {}, &block)
options[:as] ||= :table
config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block)
end
# Configure the show page for the resource
def show(options = {}, &block)
config.set_page_presenter :show, ActiveAdmin::PagePresenter.new(options, &block)
end
def form(options = {}, &block)
config.set_page_presenter :form, ActiveAdmin::PagePresenter.new(options, &block)
end
# Configure the CSV format
#
# For example:
#
# csv do
# column :name
# column("Author") { |post| post.author.full_name }
# end
#
# csv col_sep: ";", force_quotes: true do
# column :name
# end
#
def csv(options={}, &block)
options[:resource] = @resource
config.csv_builder = CSVBuilder.new(options, &block)
end
# Member Actions give you the functionality of defining both the
# action and the route directly from your ActiveAdmin registration
# block.
#
# For example:
#
# ActiveAdmin.register Post do
# member_action :comments do
# @post = Post.find(params[:id]
# @comments = @post.comments
# end
# end
#
# Will create a new controller action comments and will hook it up to
# the named route (comments_admin_post_path) /admin/posts/:id/comments
#
# You can treat everything within the block as a standard Rails controller
# action.
#
def action(set, name, options = {}, &block)
set << ControllerAction.new(name, options)
title = options.delete(:title)
controller do
callback = ActiveAdmin::Dependency.rails >= 4 ? :before_action : :before_filter
send(callback, only: [name]) { @page_title = title } if title
define_method(name, &block || Proc.new{})
end
end
def member_action(name, options = {}, &block)
action config.member_actions, name, options, &block
end
def collection_action(name, options = {}, &block)
action config.collection_actions, name, options, &block
end
# Defined Callbacks
#
# == After Build
# Called after the resource is built in the new and create actions.
#
# ActiveAdmin.register Post do
# after_build do |post|
# post.author = current_user
# end
# end
#
# == Before / After Create
# Called before and after a resource is saved to the db on the create action.
#
# == Before / After Update
# Called before and after a resource is saved to the db on the update action.
#
# == Before / After Save
# Called before and after the object is saved in the create and update action.
# Note: Gets called after the create and update callbacks
#
# == Before / After Destroy
# Called before and after the object is destroyed from the database.
#
delegate :before_build, :after_build, to: :controller
delegate :before_create, :after_create, to: :controller
delegate :before_update, :after_update, to: :controller
delegate :before_save, :after_save, to: :controller
delegate :before_destroy, :after_destroy, to: :controller
# This code defines both *_filter and *_action for Rails 3.2 to Rails 5.
actions = [
:before, :skip_before,
:after, :skip_after,
:around, :skip
]
destination = ActiveAdmin::Dependency.rails >= 4 ? :action : :filter
[:action, :filter].each do |name|
actions.each do |action|
define_method "#{action}_#{name}" do |*args, &block|
controller.public_send "#{action}_#{destination}", *args, &block
end
end
end
# Specify which actions to create in the controller
#
# Eg:
#
# ActiveAdmin.register Post do
# actions :index, :show
# end
#
# Will only create the index and show actions (no create, update or delete)
delegate :actions, to: :controller
end
end
| 28.434555 | 87 | 0.62088 |
623ef8a71007224a73eb5f894b15fbecd34f1833 | 1,867 | Pod::Spec.new do |s|
s.name = "Zee5PlayerPlugin"
s.version = '1.1.15'
s.summary = "Zee5PlayerPlugin"
s.description = <<-DESC
Zee5PlayerPlugin.
DESC
s.homepage = "https://github.com/applicaster/Zee5PlayerPlugin-iOS"
s.license = 'CMPS'
s.author = "Applicaster LTD."
s.source = { :git => "[email protected]:applicaster-plugins/Zee5PlayerPlugin-iOS.git", :tag => s.version.to_s }
s.platform = :ios, '10.0'
s.requires_arc = true
s.ios.deployment_target = "10.0"
s.swift_version = '5.1'
s.libraries = 'z'
s.frameworks = 'UIKit','AVFoundation'
s.source_files = 'PluginClasses/**/*.{h,m,swift,pch}'
s.resources = [ 'PluginClasses/**/*.{xib,storyboard,png,ttf,xcassets,json}']
s.xcconfig = {
'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES',
'ENABLE_BITCODE' => 'YES',
'SWIFT_VERSION' => '5.1',
'OTHER_CFLAGS' => '-fembed-bitcode',
'OTHER_LDFLAGS' => '-objc -ObjC -framework "FBAudienceNetwork" -framework "GoogleCast" -framework "FBSDKCoreKit"',
'GCC_SYMBOLS_PRIVATE_EXTERN' => 'YES'
}
s.dependency 'ZappPlugins'
s.dependency 'ApplicasterSDK'
s.dependency 'ZappSDK'
s.dependency 'FBAudienceNetwork'
s.dependency 'PlayKit', '3.16.0'
s.dependency 'PlayKit_IMA', '1.7.1'
s.dependency 'SnapKit'
s.dependency 'google-cast-sdk', '3.5.3'
s.dependency 'ConvivaSDK'
s.dependency 'ComScore'
s.dependency 'LotameDMP', '~> 5.0'
s.dependency 'Zee5CoreSDK'
s.dependency 'FBSDKCoreKit'
s.dependency 'CarbonKit'
s.dependency 'DropDown'
s.dependency 'UICircularProgressRing'
s.dependency 'SDWebImage'
s.dependency 'DownloadToGo'
s.dependency 'SQLite.swift'
s.dependency 'React', '~> 0.59.10'
s.dependency 'ZeeHomeScreen'
end
| 34.574074 | 120 | 0.635244 |
ac59fce1a0fedf78d49b62aad655d8b82249280d | 2,644 | module Metro
class Model
#
# A song property maintains a Gosu::Song.
#
# A song is stored in the properties as the path in the assets folder and is converted into
# a Gosu::Song when it is retrieved within the system. When retrieving a song the Song
# Property will attempt to use a song that already exists that meets that criteria.
#
# The songs are cached within the song property to help performance by reducing the unncessary
# creation of similar song.
#
# @example Defining a song property
#
# class Song < Metro::Model
# property :song
# end
#
# @example Defining a song property providing a default
#
# class Song < Metro::Model
# property :song, path: 'happy-song.wav'
# end
#
# @example Using a song property with a different property name
#
# class Song < Metro::Model
# property :intro, type: :song, path: 'intro-song.wav'
# end
#
class SongProperty < Metro::Model::Property
# By default, getting an unsupported value will return the default song
get do |value|
default_song
end
# By default, setting an unsupported value will save the default song
set do |value|
default_song_name
end
# Generate a song from the specified string filepath
get String do |filename|
self.class.song_for path: filename, window: model.window
end
# The assumption here is that the string is a song filepath
set String do |filename|
filename
end
# Setting the song value with a Metro::Song will save the string filepath
set Metro::Song do |song|
song.path
end
#
# @return the default song for the song property. This is based on the default
# song name.
#
def default_song
self.class.song_for path: default_song_name, window: model.window
end
#
# @return a string song name that is default. If the property was not created with
# a default value the the default song is the missing song found in Metro.
#
def default_song_name
options[:path] or 'missing.ogg'
end
#
# Returns a Metro::Song. This is composed of the metadata provided and a Gosu::Song.
#
# Songs are cached within the property to increase performance.
#
# @param [Hash] options the path, window, and other parameters necessary to generate
# a song.
#
def self.song_for(options)
Song.find_or_create(options)
end
end
end
end | 29.707865 | 98 | 0.627458 |
1cc5777cd151a551b6a598a3dc7a3c86950d6dfd | 1,860 | # frozen_string_literal: true
FactoryBot.define do
factory :meal, class: "Meals::Meal" do
transient do
communities { [] }
no_calendars { false }
head_cook { nil }
head_cook_role_title { nil }
asst_cooks { [] }
cleaners { [] }
end
served_at { Time.current + 7.days }
capacity { 64 }
community { Defaults.community }
source_form { "main" }
association :formula, factory: :meal_formula
association :creator, factory: :user
after(:build) do |meal, evaluator|
meal.communities += evaluator.communities.presence || [meal.community]
unless evaluator.head_cook == false
head_cook = evaluator.head_cook || create(:user, community: meal.community)
build_assignment(meal, evaluator.head_cook_role_title || "Head Cook", head_cook)
end
evaluator.asst_cooks.each { |user| build_assignment(meal, "Assistant Cook", user) }
evaluator.cleaners.each { |user| build_assignment(meal, "Cleaner", user) }
if meal.calendars.empty? && !evaluator.no_calendars
meal.calendars = [create(:calendar, meal_hostable: true)]
end
end
trait :with_menu do
title { "Yummy food" }
entrees { "Good stuff" }
allergens { %w[Dairy Soy] }
end
trait :open do
status { "open" }
end
trait :closed do
status { "closed" }
end
trait :finalized do
with_menu
status { "finalized" }
after(:build) do |meal|
meal.cost = build(:meal_cost, :with_parts)
end
end
trait :cancelled do
with_menu
status { "cancelled" }
end
end
end
def build_assignment(meal, role_title, user)
role = meal.formula.roles.detect { |r| r.title == role_title } ||
create(:meal_role, community: meal.community)
meal.assignments.build(role: role, user: user)
end
| 25.833333 | 89 | 0.631183 |
f7a271eef12f05225bb9fafa036a401dd0f95d3a | 1,222 | # frozen_string_literal: true
module ApplicationHelper
def google_maps_api_source
if APP_CONFIG.google_maps_api_key
"https://maps.googleapis.com/maps/api/js?libraries=geometry&key=#{APP_CONFIG.google_maps_api_key}"
else
'https://maps.googleapis.com/maps/api/js?libraries=geometry'
end
end
def map_config_attributes
{
'data-map-center': APP_CONFIG.map.center,
'data-map-zoom': APP_CONFIG.map.zoom
}
end
def title(page_title)
content_for(:title) { page_title.to_s }
end
def meta_title(options = {})
title = content_for(:title) || options[:fallback]
title << " | #{APP_CONFIG.app_name}" unless user_signed_in? || title.blank?
title
end
def twitterized_type(type)
case type
when 'alert' then 'alert-warning'
when 'error' then 'alert-danger'
when 'notice' then 'alert-info'
else type
end
end
def transparent_gif_image_data
'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
end
def options_for_array_collection(model, attr_name, *_args)
"#{model}::#{attr_name.to_s.upcase}".safe_constantize.map { |e| [model.human_attribute_name("#{attr_name}_#{e}"), e] }
end
end
| 26.565217 | 122 | 0.700491 |
b9173265f234c9a3d37bbcda3185b0de23ae23ad | 1,354 | cask "logitech-unifying" do
if MacOS.version <= :yosemite
version "1.2.359"
sha256 "e6fd9c1b536033f3346b32c391bd58587ea9f549cab7839cf8a1dbc62a739825"
else
version "1.3.375"
sha256 "82fe3df612e775ec8789fa821f4f62d4b3a55278276d03474580fee668ee50b7"
end
url "https://download01.logi.com/web/ftp/pub/controldevices/unifying/unifying#{version}_mac.zip"
name "Logitech Unifying Software"
desc "Utility for pairing devices with Unifying receivers"
homepage "https://support.logi.com/hc/en-001/articles/360025297913-Unifying-Software"
livecheck do
url "https://support.logi.com/api/v2/help_center/en-us/articles.json?label_names=webcontent=productdownload,websoftware=ec9eb8f1-8e0b-11e9-a62b-5b664cf4d3da"
regex(/unifying(\d+(?:\.\d+)+)_mac\.zip/i)
end
pkg "Unifying Installer.app/Contents/Resources/Logitech Unifying Signed.mpkg"
uninstall pkgutil: [
"com.Logitech.Unifying Software.pkg",
"com.Logitech.Updater.pkg",
],
delete: "/Applications/Utilities/Logitech Unifying Software.app",
quit: "com.logitech.unifying.assistant"
zap trash: [
"/Library/Application Support/Logitech.localized",
"~/Library/Caches/com.Logitech.Updater",
"~/Library/Preferences/com.Logitech.Updater.plist",
"~/Library/Preferences/com.logitech.unifying.assistant.plist",
]
end
| 37.611111 | 161 | 0.742245 |
f80cb824d5804bccfad276cdab2f8af9ce6769b1 | 5,399 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataFactory::Mgmt::V2018_06_01
module Models
#
# A copy activity source for a CosmosDB (MongoDB API) database.
#
class CosmosDbMongoDbApiSource < CopySource
include MsRestAzure
def initialize
@type = "CosmosDbMongoDbApiSource"
end
attr_accessor :type
# @return Specifies selection filter using query operators. To return all
# documents in a collection, omit this parameter or pass an empty
# document ({}). Type: string (or Expression with resultType string).
attr_accessor :filter
# @return [MongoDbCursorMethodsProperties] Cursor methods for Mongodb
# query.
attr_accessor :cursor_methods
# @return Specifies the number of documents to return in each batch of
# the response from MongoDB instance. In most cases, modifying the batch
# size will not affect the user or the application. This property's main
# purpose is to avoid hit the limitation of response size. Type: integer
# (or Expression with resultType integer).
attr_accessor :batch_size
# @return Query timeout. Type: string (or Expression with resultType
# string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
attr_accessor :query_timeout
# @return [Array<AdditionalColumns>] Specifies the additional columns to
# be added to source data. Type: array of objects (or Expression with
# resultType array of objects).
attr_accessor :additional_columns
#
# Mapper for CosmosDbMongoDbApiSource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'CosmosDbMongoDbApiSource',
type: {
name: 'Composite',
class_name: 'CosmosDbMongoDbApiSource',
model_properties: {
additional_properties: {
client_side_validation: true,
required: false,
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
source_retry_count: {
client_side_validation: true,
required: false,
serialized_name: 'sourceRetryCount',
type: {
name: 'Object'
}
},
source_retry_wait: {
client_side_validation: true,
required: false,
serialized_name: 'sourceRetryWait',
type: {
name: 'Object'
}
},
max_concurrent_connections: {
client_side_validation: true,
required: false,
serialized_name: 'maxConcurrentConnections',
type: {
name: 'Object'
}
},
type: {
client_side_validation: true,
required: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
filter: {
client_side_validation: true,
required: false,
serialized_name: 'filter',
type: {
name: 'Object'
}
},
cursor_methods: {
client_side_validation: true,
required: false,
serialized_name: 'cursorMethods',
type: {
name: 'Composite',
class_name: 'MongoDbCursorMethodsProperties'
}
},
batch_size: {
client_side_validation: true,
required: false,
serialized_name: 'batchSize',
type: {
name: 'Object'
}
},
query_timeout: {
client_side_validation: true,
required: false,
serialized_name: 'queryTimeout',
type: {
name: 'Object'
}
},
additional_columns: {
client_side_validation: true,
required: false,
serialized_name: 'additionalColumns',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'AdditionalColumnsElementType',
type: {
name: 'Composite',
class_name: 'AdditionalColumns'
}
}
}
}
}
}
}
end
end
end
end
| 32.721212 | 79 | 0.487868 |
28a3ecc16958cd84773fb7d6257701ab7279ac1b | 2,450 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Compute::Mgmt::V2019_07_01
module Models
#
# This is the regional replication status.
#
class RegionalReplicationStatus
include MsRestAzure
# @return [String] The region to which the gallery Image Version is being
# replicated to.
attr_accessor :region
# @return [ReplicationState] This is the regional replication state.
# Possible values include: 'Unknown', 'Replicating', 'Completed',
# 'Failed'
attr_accessor :state
# @return [String] The details of the replication status.
attr_accessor :details
# @return [Integer] It indicates progress of the replication job.
attr_accessor :progress
#
# Mapper for RegionalReplicationStatus class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RegionalReplicationStatus',
type: {
name: 'Composite',
class_name: 'RegionalReplicationStatus',
model_properties: {
region: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'region',
type: {
name: 'String'
}
},
state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'state',
type: {
name: 'String'
}
},
details: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'details',
type: {
name: 'String'
}
},
progress: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'progress',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 28.16092 | 79 | 0.508163 |
6a351aafb14cfb781f6b4b6e9d7862d87b746061 | 1,039 | require 'pry'
=begin
Right Triangles
Write a method that takes a positive integer, n, as an argument, and displays a
right triangle whose sides each have n stars. The hypotenuse of the triangle
(the diagonal side in the images below) should have one end at the lower-left of
the triangle, and the other end at the upper-right.
Examples:
triangle(5)
*
**
***
****
*****
triangle(9)
*
**
***
****
*****
******
*******
********
*********
Understand the problem
- input: Positive Integer
- output: displayed right triangle whose sides each have n stars
- rules:
- The hypotenuse of the triangle should have one end at the lower-left of the
triangle, and the other end at the upper-right
Test cases
- Well covered by examples
Describe Agorithm
- write method to calculate spaces
- iterate
Begin coding
=end
SPACE = " "
STAR = "*"
def triangle(n)
1.upto(n) do |i|
spaces = SPACE * (n - i)
stars = STAR * i
puts spaces + stars
end
end
triangle(5)
triangle(9)
| 16.234375 | 80 | 0.640038 |
d5f24dd4dd784b51157f00512a6ae8bb10c74aae | 190 | require 'pact/matchers/expected_type'
module Pact
class ActualType < Pact::ExpectedType
def initialize value
@value = value
end
def to_s
type
end
end
end | 11.875 | 39 | 0.652632 |
2699de53b18c5b89ca798e5bd1c0371502004e26 | 1,765 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
module NewRelic
module Agent
class SamplerCollection
include Enumerable
def initialize(event_listener)
@samplers = []
event_listener.subscribe(:before_harvest) { poll_samplers }
end
def each(&blk)
@samplers.each(&blk)
end
def clear()
@samplers.clear
end
def sampler_class_registered?(sampler_class)
self.any? { |s| s.class == sampler_class }
end
def poll_samplers
@samplers.delete_if do |sampler|
begin
sampler.poll
false # it's okay. don't delete it.
rescue => e
::NewRelic::Agent.logger.warn("Removing #{sampler} from list", e)
true # remove the sampler
end
end
end
def add_sampler(sampler_class)
if sampler_class.supported_on_this_platform?
if !sampler_class_registered?(sampler_class)
@samplers << sampler_class.new
::NewRelic::Agent.logger.debug("Registered #{sampler_class.name} for harvest time sampling.")
else
::NewRelic::Agent.logger.warn("Ignoring addition of #{sampler_class.name} because it is already registered.")
end
else
::NewRelic::Agent.logger.debug("#{sampler_class.name} not supported on this platform.")
end
rescue NewRelic::Agent::Sampler::Unsupported => e
::NewRelic::Agent.logger.info("#{sampler_class.name} not available: #{e}")
rescue => e
::NewRelic::Agent.logger.error("Error registering sampler:", e)
end
end
end
end
| 30.431034 | 121 | 0.617564 |
5d6695102bec1964525f93d58f97596568605823 | 1,464 | require 'helper'
require 'thor/core_ext/hash_with_indifferent_access'
describe Thor::CoreExt::HashWithIndifferentAccess do
before do
@hash = Thor::CoreExt::HashWithIndifferentAccess.new :foo => 'bar', 'baz' => 'bee', :force => true
end
it "has values accessible by either strings or symbols" do
expect(@hash['foo']).to eq('bar')
expect(@hash[:foo]).to eq('bar')
expect(@hash.values_at(:foo, :baz)).to eq(['bar', 'bee'])
expect(@hash.delete(:foo)).to eq('bar')
end
it "handles magic boolean predicates" do
expect(@hash.force?).to be_true
expect(@hash.foo?).to be_true
expect(@hash.nothing?).to be_false
end
it "handles magic comparisions" do
expect(@hash.foo?('bar')).to be_true
expect(@hash.foo?('bee')).to be_false
end
it "maps methods to keys" do
expect(@hash.foo).to eq(@hash['foo'])
end
it "merges keys independent if they are symbols or strings" do
@hash.merge!('force' => false, :baz => "boom")
expect(@hash[:force]).to eq(false)
expect(@hash[:baz]).to eq("boom")
end
it "creates a new hash by merging keys independent if they are symbols or strings" do
other = @hash.merge('force' => false, :baz => "boom")
expect(other[:force]).to eq(false)
expect(other[:baz]).to eq("boom")
end
it "converts to a traditional hash" do
expect(@hash.to_hash.class).to eq(Hash)
expect(@hash).to eq({ 'foo' => 'bar', 'baz' => 'bee', 'force' => true })
end
end
| 29.877551 | 102 | 0.645492 |
e2ac4983a3614db0826cedc6a217e4ad443ae5ed | 3,944 | # frozen_string_literal: true
class Course::Forum::PostsController < Course::Forum::ComponentController
before_action :load_topic
authorize_resource :topic
skip_authorize_resource :post, only: :toggle_answer
before_action :authorize_locked_topic, only: [:create]
before_action :add_topic_breadcrumb
include Course::Discussion::PostsConcern
def create
result = @post.class.transaction do
raise ActiveRecord::Rollback unless @post.save && create_topic_subscription && update_topic_pending_status
raise ActiveRecord::Rollback unless @topic.update_column(:latest_post_at, @post.created_at)
true
end
if result
send_created_notification(@post)
redirect_to course_forum_topic_path(current_course, @forum, @topic),
success: t('course.discussion.posts.create.success')
else
redirect_to course_forum_topic_path(current_course, @forum, @topic),
danger: t('course.discussion.posts.create.failure',
error: @post.errors.full_messages.to_sentence)
end
end
def edit
# Sanitize input before passing to the form helper for display when editing in case the text
# has not been sanitized before save.
@post.text = helpers.format_html(@post.text)
end
def update
if @post.update(post_params)
redirect_to course_forum_topic_path(current_course, @forum, @topic),
success: t('course.discussion.posts.update.success')
else
render 'edit'
end
end
def vote
@post.cast_vote!(current_user, post_vote_param)
redirect_to course_forum_topic_path(current_course, @forum, @topic),
success: t('.success')
end
# Mark/unmark the post as the correct answer
def toggle_answer
authorize!(:toggle_answer, @topic)
if @post.toggle_answer
redirect_to course_forum_topic_path(current_course, @forum, @topic), success: t('.success')
else
redirect_to course_forum_topic_path(current_course, @forum, @topic),
danger: @post.errors.full_messages.to_sentence
end
end
def destroy
if @topic.posts.count == 1 && @topic.destroy
redirect_to course_forum_path(current_course, @forum),
success: t('course.forum.topics.destroy.success', title: @topic.title)
elsif @post.destroy
@topic.update_column(:latest_post_at, @topic.posts.last&.created_at || @topic.created_at)
redirect_to course_forum_topic_path(current_course, @forum, @topic),
success: t('course.discussion.posts.destroy.success')
else
redirect_to course_forum_topic_path(current_course, @forum, @topic),
danger: t('course.discussion.posts.destroy.failure',
error: @post.errors.full_messages.to_sentence)
end
end
# Render a new post in a separate page
def reply
node = @post
@post_chain = [node]
# Show up to reply-post + 2 parent posts
2.times do
break if node.parent.nil?
@post_chain << node.parent
node = node.parent
end
@post_chain = @post_chain.reverse
@reply_post = @post.children.build
end
protected
def create_topic_subscription
@topic.ensure_subscribed_by(current_user)
end
def discussion_topic
@topic.acting_as
end
def skip_update_topic_status
true
end
private
def topic_id_param
params.permit(:topic_id)[:topic_id]
end
def load_topic
@topic ||= @forum.topics.friendly.find(topic_id_param)
end
def add_topic_breadcrumb
add_breadcrumb @topic.title, course_forum_topic_path(current_course, @forum, @topic)
end
def post_vote_param
params.permit(:vote)[:vote].to_i
end
def send_created_notification(post)
return unless current_user
Course::Forum::PostNotifier.post_replied(current_user, current_course_user, post)
end
def authorize_locked_topic
authorize!(:reply, @topic)
end
end
| 29.432836 | 112 | 0.698783 |
4a59aa0df7e5d69a3c0ea2fc15fb396c30a6831a | 558 | require_relative 'boot'
require 'rails'
Bundler.require(*Rails.groups)
require 'nfg_ui'
module TestApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
# Settings in config/environments/* take precedence over those specified here.
config.load_defaults 5.2
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 27.9 | 82 | 0.765233 |
b97bf9bc804cd8f835fdef55dde70b779a6362bb | 45 | module Hashie
VERSION = '4.1.0'.freeze
end
| 11.25 | 26 | 0.688889 |
b9c0ad4b72827c9e0633dace283f32f081570e5d | 882 | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'the_comments/version'
Gem::Specification.new do |gem|
gem.name = "the_comments"
gem.version = TheComments::VERSION
gem.authors = ["Ilya N. Zykin"]
gem.email = ["[email protected]"]
gem.description = %q{ Comments with threading for Rails 4 }
gem.summary = %q{ the_comments by the-teacher }
gem.homepage = "https://github.com/open-cook/the_comments"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency 'state_machine'
gem.add_dependency 'the_sortable_tree'
# gem.add_dependency 'rails', '>= 4.0'
end
| 35.28 | 75 | 0.646259 |
219702935cf1aca44aa17914fb38db06d2ad2b5d | 314 | # frozen_string_literal: true
# Demonstrates a "custom versions association name". Instead of the association
# being named `versions`, it will be named `paper_trail_versions`.
class Document < ActiveRecord::Base
has_paper_trail(
versions: { name: :paper_trail_versions },
on: %i[create update]
)
end
| 28.545455 | 79 | 0.748408 |
1a42f6a01a52de5c053e1175c924db4c4cec67ba | 10,841 | require 'spec_helper'
describe AjaxDatatablesRails::Base do
params = {
:draw => '5',
:columns => {
"0" => {
:data => '0',
:name => '',
:searchable => true,
:orderable => true,
:search => { :value => '', :regex => false }
},
"1" => {
:data => '1',
:name => '',
:searchable => true,
:orderable => true,
:search => { :value => '', :regex => false }
}
},
:order => { "0" => { :column => '1', :dir => 'desc' } },
:start => '0',
:length => '10',
:search => { :value => '', :regex => false },
'_' => '1403141483098'
}
let(:view) { double('view', :params => params) }
describe 'an instance' do
it 'requires a view_context' do
expect { AjaxDatatablesRails::Base.new }.to raise_error
end
it 'accepts an options hash' do
datatable = AjaxDatatablesRails::Base.new(view, :foo => 'bar')
expect(datatable.options).to eq(:foo => 'bar')
end
end
describe 'helper methods' do
describe '#offset' do
it 'defaults to 0' do
default_view = double('view', :params => {})
datatable = AjaxDatatablesRails::Base.new(default_view)
expect(datatable.send(:offset)).to eq(0)
end
it 'matches the value on view params[:start] minus 1' do
paginated_view = double('view', :params => { :start => '11' })
datatable = AjaxDatatablesRails::Base.new(paginated_view)
expect(datatable.send(:offset)).to eq(10)
end
end
describe '#page' do
it 'calculates page number from params[:start] and #per_page' do
paginated_view = double('view', :params => { :start => '11' })
datatable = AjaxDatatablesRails::Base.new(paginated_view)
expect(datatable.send(:page)).to eq(2)
end
end
describe '#per_page' do
it 'defaults to 10' do
datatable = AjaxDatatablesRails::Base.new(view)
expect(datatable.send(:per_page)).to eq(10)
end
it 'matches the value on view params[:length]' do
other_view = double('view', :params => { :length => 20 })
datatable = AjaxDatatablesRails::Base.new(other_view)
expect(datatable.send(:per_page)).to eq(20)
end
end
describe '#sort_column' do
it 'returns a column name from the #sorting_columns array' do
sort_view = double(
'view', :params => params
)
datatable = AjaxDatatablesRails::Base.new(sort_view)
allow(datatable).to receive(:sortable_displayed_columns) { ["0", "1"] }
allow(datatable).to receive(:sortable_columns) { ['User.foo', 'User.bar', 'User.baz'] }
expect(datatable.send(:sort_column, sort_view.params[:order]["0"])).to eq('users.bar')
end
end
describe '#sort_direction' do
it 'matches value of params[:sSortDir_0]' do
sorting_view = double(
'view',
:params => {
:order => {
'0' => { :column => '1', :dir => 'desc' }
}
}
)
datatable = AjaxDatatablesRails::Base.new(sorting_view)
expect(datatable.send(:sort_direction, sorting_view.params[:order]["0"])).to eq('DESC')
end
it 'can only be one option from ASC or DESC' do
sorting_view = double(
'view',
:params => {
:order => {
'0' => { :column => '1', :dir => 'foo' }
}
}
)
datatable = AjaxDatatablesRails::Base.new(sorting_view)
expect(datatable.send(:sort_direction, sorting_view.params[:order]["0"])).to eq('ASC')
end
end
describe "#configure" do
let(:datatable) do
class FooDatatable < AjaxDatatablesRails::Base
end
FooDatatable.new view
end
context "when model class name is regular" do
it "should successfully get right model class" do
expect(
datatable.send(:search_condition, 'User.bar', 'bar')
).to be_a(Arel::Nodes::Matches)
end
end
context "when custom named model class" do
it "should successfully get right model class" do
expect(
datatable.send(:search_condition, 'Statistics::Request.bar', 'bar')
).to be_a(Arel::Nodes::Matches)
end
end
context "when model class name camelcased" do
it "should successfully get right model class" do
expect(
datatable.send(:search_condition, 'PurchasedOrder.bar', 'bar')
).to be_a(Arel::Nodes::Matches)
end
end
context "when model class name is namespaced" do
it "should successfully get right model class" do
expect(
datatable.send(:search_condition, 'Statistics::Session.bar', 'bar')
).to be_a(Arel::Nodes::Matches)
end
end
context "when model class defined but not found" do
it "raise 'uninitialized constant'" do
expect {
datatable.send(:search_condition, 'UnexistentModel.bar', 'bar')
}.to raise_error(NameError, /uninitialized constant/)
end
end
context 'when using deprecated notation' do
it 'should successfully get right model class if exists' do
expect(
datatable.send(:search_condition, 'users.bar', 'bar')
).to be_a(Arel::Nodes::Matches)
end
it 'should display a deprecated message' do
expect(AjaxDatatablesRails::Base).to receive(:deprecated)
datatable.send(:search_condition, 'users.bar', 'bar')
end
end
end
describe '#sortable_columns' do
it 'returns an array representing database columns' do
datatable = AjaxDatatablesRails::Base.new(view)
expect(datatable.sortable_columns).to eq([])
end
end
describe '#searchable_columns' do
it 'returns an array representing database columns' do
datatable = AjaxDatatablesRails::Base.new(view)
expect(datatable.searchable_columns).to eq([])
end
end
end
describe 'perform' do
let(:results) { double('Collection', :offset => [], :limit => []) }
let(:view) { double('view', :params => params) }
let(:datatable) { AjaxDatatablesRails::Base.new(view) }
let(:records) { double('Array').as_null_object }
before(:each) do
allow(datatable).to receive(:sortable_columns) { ['User.foo', 'User.bar'] }
allow(datatable).to receive(:sortable_displayed_columns) { ["0", "1"] }
end
describe '#paginate_records' do
it 'defaults to Extensions::SimplePaginator#paginate_records' do
allow(records).to receive_message_chain(:offset, :limit)
expect { datatable.send(:paginate_records, records) }.not_to raise_error
end
end
describe '#sort_records' do
it 'calls #order on a collection' do
expect(results).to receive(:order)
datatable.send(:sort_records, results)
end
end
describe '#filter_records' do
let(:records) { double('User', :where => []) }
let(:search_view) { double('view', :params => params) }
it 'applies search like functionality on a collection' do
datatable = AjaxDatatablesRails::Base.new(search_view)
allow(datatable).to receive(:searchable_columns) { ['users.foo'] }
expect(records).to receive(:where)
records.where
datatable.send(:filter_records, records)
end
end
describe '#filter_records with multi word model' do
let(:records) { double('UserData', :where => []) }
let(:search_view) { double('view', :params => params) }
it 'applies search like functionality on a collection' do
datatable = AjaxDatatablesRails::Base.new(search_view)
allow(datatable).to receive(:searchable_columns) { ['user_datas.bar'] }
expect(records).to receive(:where)
records.where
datatable.send(:filter_records, records)
end
end
end
describe 'hook methods' do
let(:datatable) { AjaxDatatablesRails::Base.new(view) }
describe '#data' do
it 'raises a MethodNotImplementedError' do
expect { datatable.data }.to raise_error(
AjaxDatatablesRails::Base::MethodNotImplementedError,
'Please implement this method in your class.'
)
end
end
describe '#get_raw_records' do
it 'raises a MethodNotImplementedError' do
expect { datatable.get_raw_records }.to raise_error(
AjaxDatatablesRails::Base::MethodNotImplementedError,
'Please implement this method in your class.'
)
end
end
end
end
describe AjaxDatatablesRails::Configuration do
let(:config) { AjaxDatatablesRails::Configuration.new }
describe "default config" do
it "default db_adapter should :pg (postgresql)" do
expect(config.db_adapter).to eq(:pg)
end
end
describe "custom config" do
it 'should accept db_adapter custom value' do
config.db_adapter = :mysql2
expect(config.db_adapter).to eq(:mysql2)
end
end
describe '#typecast' do
params = {
:draw => '5',
:columns => {
"0" => {
:data => '0',
:name => '',
:searchable => true,
:orderable => true,
:search => { :value => '', :regex => false }
},
"1" => {
:data => '1',
:name => '',
:searchable => true,
:orderable => true,
:search => { :value => '', :regex => false }
}
},
:order => { "0" => { :column => '1', :dir => 'desc' } },
:start => '0',
:length => '10',
:search => { :value => '', :regex => false },
'_' => '1403141483098'
}
let(:view) { double('view', :params => params) }
let(:datatable) { AjaxDatatablesRails::Base.new(view) }
it 'returns VARCHAR if :db_adapter is :pg' do
expect(datatable.send(:typecast)).to eq('VARCHAR')
end
it 'returns CHAR if :db_adapter is :mysql2' do
allow_any_instance_of(AjaxDatatablesRails::Configuration).to receive(:db_adapter) { :mysql2 }
expect(datatable.send(:typecast)).to eq('CHAR')
end
it 'returns TEXT if :db_adapter is :sqlite3' do
allow_any_instance_of(AjaxDatatablesRails::Configuration).to receive(:db_adapter) { :sqlite3 }
expect(datatable.send(:typecast)).to eq('TEXT')
end
end
end
describe AjaxDatatablesRails do
describe "configurations" do
context "configurable from outside" do
before(:each) do
AjaxDatatablesRails.configure do |config|
config.db_adapter = :mysql2
end
end
it "should have custom value" do
expect(AjaxDatatablesRails.config.db_adapter).to eq(:mysql2)
end
end
end
end
| 30.798295 | 100 | 0.589982 |
1a7c3d43f068d824879c846dff24fbdb058845df | 1,540 | {
matrix_id: '1475',
name: 'GD00_a',
group: 'Pajek',
description: 'Pajek network: Graph Drawing contest 2000',
author: 'Graph Drawing Contest',
editor: 'V. Batagelj',
date: '2000',
kind: 'directed graph',
problem_2D_or_3D: '0',
num_rows: '352',
num_cols: '352',
nonzeros: '458',
num_explicit_zeros: '0',
num_strongly_connected_components: '352',
pattern_symmetry: '0.000',
numeric_symmetry: '0.000',
rb_type: 'binary',
structure: 'unsymmetric',
cholesky_candidate: 'no',
positive_definite: 'no',
notes: '------------------------------------------------------------------------------
Pajek network converted to sparse adjacency matrix for inclusion in UF sparse
matrix collection, Tim Davis. For Pajek datasets, See V. Batagelj & A. Mrvar,
http://vlado.fmf.uni-lj.si/pub/networks/data/.
------------------------------------------------------------------------------
The original problem had 3D xyz coordinates, but all values of z were equal
to 0.5, and have been removed. This graph has 2D coordinates.
',
aux_fields: 'nodename: full 352-by-96
coord: full 352-by-2
', norm: '7.082111e+00',
min_singular_value: '0',
condition_number: 'Inf',
svd_rank: '178',
null_space_dimension: '174',
full_numerical_rank: 'no',
svd_gap: '129722925881091.437500',
image_files: 'GD00_a.png,GD00_a_gplot.png,GD00_a_scc.png,GD00_a_svd.png,GD00_a_APlusAT_graph.gif,GD00_a_graph.gif,',
}
| 37.560976 | 120 | 0.590909 |
ed51611f2a7e5bc191c245df33de18f7087b85d3 | 198 | require "spec_helper"
RSpec.describe Helix do
it "has a version number" do
expect(Helix::VERSION).not_to be nil
end
it "does something useful" do
expect(false).to eq(true)
end
end
| 16.5 | 40 | 0.70202 |
e82c2db2b2cf765fed82a7e1928ae98266f7a3a8 | 535 | class DropSpreeIdFromSalesforceContacts < ActiveRecord::Migration
def up
return if ENV["DEPLOYMENT"] == "production"
HerokuConnect.change_schema("salesforce") do
remove_column :contact, :spree_id__c
remove_column :order__c, :contact__r__spree_id__c
end
end
def down
return if ENV["DEPLOYMENT"] == "production"
HerokuConnect.change_schema("salesforce") do
add_column :contact, :spree_id__c, "varchar(14)"
add_column :order__c, :contact__r__spree_id__c, "varchar(14)"
end
end
end
| 29.722222 | 67 | 0.721495 |
acb58058074ca8177a5fcbf7a977fcdf775462e2 | 658 | module BandwidthIris
INSERVICE_NUMBER_PATH = 'inserviceNumbers'
class InServiceNumber
extend ClientWrapper
def self.list(client, query = nil)
list = client.make_request(:get, client.concat_account_path(INSERVICE_NUMBER_PATH), query)
return list
end
wrap_client_arg :list
def self.get(client, number)
client.make_request(:get, "#{client.concat_account_path(INSERVICE_NUMBER_PATH)}/#{URI.escape(number)}")[0]
end
wrap_client_arg :get
def self.totals(client)
client.make_request(:get, "#{client.concat_account_path(INSERVICE_NUMBER_PATH)}/totals")[0]
end
wrap_client_arg :totals
end
end
| 27.416667 | 112 | 0.724924 |
61cf16fec754837876d18040e95191ec45caf0a7 | 1,310 | # 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 'google/apis/workflows_v1/service.rb'
require 'google/apis/workflows_v1/classes.rb'
require 'google/apis/workflows_v1/representations.rb'
require 'google/apis/workflows_v1/gem_version.rb'
module Google
module Apis
# Workflows API
#
# Manage workflow definitions. To execute workflows and manage executions, see
# the Workflows Executions API.
#
# @see https://cloud.google.com/workflows
module WorkflowsV1
# Version of the Workflows API this client connects to.
# This is NOT the gem version.
VERSION = 'V1'
# See, edit, configure, and delete your Google Cloud Platform data
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 34.473684 | 82 | 0.738168 |
edb07c649936994d7b4db440ed6859ffe833e769 | 2,342 | # Copyright 2014 Bob Aman
#
# 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 'multiterm/version'
require 'multiterm/terminal'
module MultiTerm
##
# Memoized copy of the default configuration.
def self.configuration
@@configuration ||= read_configuration
end
##
# Loads the configuration file for the current path.
def self.read_configuration(path=nil)
if path != nil && File.exists?(path) && File.directory?(path)
current_path = path
elsif path != nil && File.exists?(path) && !File.directory?(path)
current_path = File.dirname(path)
else
current_path = File.expand_path('.')
end
home_path = File.expand_path('~')
search_path = current_path
while search_path != '/' && search_path != home_path
if File.exists?(File.join(search_path, '.multiterm.yml'))
settings = YAML.load(File.read(File.join(search_path, '.multiterm.yml')))
settings[:root] = File.expand_path(search_path)
return settings if settings
end
search_path = File.expand_path(File.join(search_path, '..'))
end
return nil
end
def self.execute
if configuration
app = Osaka::Terminal.new
app.activate
tab_config = {
:directory => configuration[:root],
:new_tab => false
}.merge(configuration[:parent])
app.tab_configure(tab_config)
for tab_config in configuration[:tabs]
tab_config = {
:directory => configuration[:root],
:new_tab => true
}.merge(tab_config)
tab_config[:directory] = File.realdirpath(
tab_config[:directory],
(configuration[:root] || File.expand_path('.'))
)
app.tab_configure(tab_config)
end
else
puts "Missing '.multiterm.yml' configuration."
end
end
end
| 32.082192 | 81 | 0.658839 |
1dbce179b53402d446ed8c831e167b9a425427a6 | 1,086 |
Pod::Spec.new do |s|
s.name = "YLLXfyun"
s.version = "0.0.2"
s.summary = "A short description of YLLXfyun."
s.description = "xunfei"
s.homepage = "https://github.com/yuliang6/YLLXfyun"
s.license = "MIT"
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
s.author = { "yuliangliang" => "[email protected]" }
s.ios.deployment_target = "7.0"
s.source = { :git => "https://github.com/yuliang6/YLLXfyun.git", :tag => "#{s.version}" }
s.source_files = "Classes", "Classes/**/*.{h,m}"
s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# s.resource = "icon.png"
#s.resources = "Assets/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
s.frameworks = 'AVFoundation','SystemConfiguration','Foundation','CoreTelephony','AudioToolbox','UIKit','CoreLocation','AddressBook','QuartzCore','CoreGraphics'
s.libraries = 'z'
s.vendored_frameworks = 'Assets/iflyMSC.framework'
# s.requires_arc = true
# s.dependency "JSONKit", "~> 1.4"
end
| 25.255814 | 161 | 0.612339 |
264895955917df34d7de2f65a2a45f550ba81f16 | 461 | module Mastercard
module Common
class OAuthParameters
attr_accessor :params
def initialize()
self.params = Hash.new
end
# add a parameter to the hash and as an instance variable to the class
def add_parameter(key, value)
self.params[key.to_sym] = value
self.class.send(:define_method, key) do
value
end
end
end
end
end | 20.954545 | 77 | 0.550976 |
0385d7c05ae5f9b3bec6261c9645e121be0897c0 | 2,277 | # Copyright 2011-2018, The Trustees of Indiana University and Northwestern
# University. Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# --- END LICENSE_HEADER BLOCK ---
require 'rails_helper'
describe BatchRegistries do
subject { FactoryGirl.build(:batch_registries) }
describe '#save' do
it "persists an error when the user doesn't exist" do
batch_registries = FactoryGirl.build(:batch_registries, user_id: 10000)
batch_registries.save
expect(batch_registries.error).to be true
expect(batch_registries.error_message).to be_present
end
it 'persists' do
subject.save
subject.reload
expect(subject.file_name).to be_present
expect(subject.dir).to be_present
expect(subject.user_id).to be_present
expect(subject.collection).to be_present
expect(subject.complete).not_to be_nil
expect(subject.error).not_to be_nil
expect(subject.error_email_sent).not_to be_nil
expect(subject.processed_email_sent).not_to be_nil
expect(subject.completed_email_sent).not_to be_nil
expect(subject.locked).not_to be_nil
end
it { is_expected.to validate_presence_of(:collection) }
it { is_expected.to validate_presence_of(:file_name) }
it { is_expected.to validate_presence_of(:user_id) }
end
describe '#file_name=' do
subject { BatchRegistries.new }
it 'generates a replay name' do
expect { subject.file_name = "file.mp4" }.to change { subject.replay_name }
expect(subject.replay_name.ends_with?(subject.file_name)).to be true
end
it "doesn't overwrite the existing replay name" do
subject.replay_name = "replay-name"
expect { subject.file_name = "file.mp4" }.not_to change { subject.replay_name }
end
end
end
| 36.725806 | 85 | 0.72859 |
bf7889e38f28e5e94bacaaacb1abf6381d1e58bb | 66 | class PageController < ApplicationController
def home
end
end
| 13.2 | 44 | 0.80303 |
f7fef35cf602653cb791267aa3c0d6dac7740255 | 2,348 | # frozen_string_literal: true
require 'date'
require 'schema_dot_org'
require 'schema_dot_org/aggregate_offer'
# Model the Schema.org `Thing > Place`. See https://schema.org/Product
#
module SchemaDotOrg
class SportsEvent < SchemaType
attr_accessor :name,
:start_date,
:end_date,
:url,
:description,
:location,
:image,
:offers,
:performer
validates :name, type: String
validates :start_date, type: Date
validates :end_date, type: Date, allow_nil: true
validates :url, type: String
validates :description, type: String, allow_nil: true
validates :location, type: SchemaDotOrg::Place
validates :image, type: String, allow_nil: true
validates :offers, type: SchemaDotOrg::Offer
validates :performer, type: String, allow_nil: true
def _to_json_struct
{
"name" => name,
"startDate" => start_date,
"endDate" => end_date,
"url" => url,
"description" => description,
"location" => location.to_json_struct,
"image" => image,
"offers" => offers.to_json_struct,
"performer" => performer
}
end
def image
@image || []
end
end
end
#
#
# {
# "@context": "http://schema.org",
# "@type": "SportsEvent",
# "name": "FC Barcelona vs Getafe",
# "startDate": "2020-02-15T16:00:00",
# "endDate": null,
# "url": "https://www.viagogo.co.uk/Sports-Tickets/Football/Spanish-Premier-League/FC-Barcelona-Tickets/E-3876816",
# "description": null,
# "location": {
# "@type": "Place",
# "name": "Camp Nou",
# "address": {
# "@type": "PostalAddress",
# "addressLocality": "Barcelona",
# "addressCountry": "Spain"
# }
# },
# "image": null,
# "offers": {
# "@type": "Offer",
# "category": "Secondary",
# "priceCurrency": "USD",
# "price": "52.17",
# "url": "https://www.viagogo.co.uk/Sports-Tickets/Football/Spanish-Premier-League/FC-Barcelona-Tickets/E-3876816",
# "availability": "http://schema.org/InStock",
# "validFrom": "2017-01-07T00:00:00"
# },
# "performer": null
# }
| 28.634146 | 120 | 0.546422 |
bb519c22b5591541c482047a4c6d606ce16cfe12 | 1,992 | # The game loop.
#
class Loop
class Break < StandardError; end
def self.shared_instance
@shared_instance ||= Loop.new
end
def initialize
@frame_count = 0
@time_count = 0
end
# Root game object instance.
#
attr_reader :root
def root=(set)
@root = set
@renderer = Renderer.new(root)
end
# - parameter current_time: current time in milliseconds.
#
def perform_update(current_time)
raise "There is no root node for the game" unless root
# Profiler.shared_instance.end_of("OUTSIDE OF LOOP")
# Profiler.shared_instance.flush
# Profiler.shared_instance.start_of("ALL_LOGIC")
last_time = @last_time || current_time
milliseconds_delta = current_time - last_time
# If the game logic is completed in less than 16ms, it's running faster than
# 60fps. In that case we can just make this thread wait to save on
# processing.
if milliseconds_delta < 8
sleep_time = 8 - milliseconds_delta
Platform.delay(sleep_time * 0.001)
milliseconds_delta = current_time - last_time
end
seconds_delta = milliseconds_delta * 0.001
@last_time = current_time
Time.delta = seconds_delta
@time_count = @time_count + seconds_delta
if @time_count >= 1
# TODO: enable by app config
# puts "#{@frame_count} FPS"
@time_count = 0
@frame_count = 0
else
@frame_count = @frame_count + 1
end
# Profiler.shared_instance.start_of("internal input update")
Input.shared_instance.update
# Profiler.shared_instance.end_of("internal input update")
# Profiler.shared_instance.start_of("perform_update")
@root.perform_update
# Profiler.shared_instance.end_of("perform_update")
# Profiler.shared_instance.start_of("draw_frame")
@renderer.draw_frame
# Profiler.shared_instance.end_of("draw_frame")
# Profiler.shared_instance.end_of("ALL_LOGIC")
# Profiler.shared_instance.start_of("OUTSIDE OF LOOP")
rescue Break
end
end
| 26.918919 | 80 | 0.697289 |
87de64a798cb83c21ef9dafe045c43ff32d9cfc7 | 569 | cask "zeplin" do
version "3.23.1,1238"
sha256 :no_check
url "https://api.zeplin.io/urls/download-mac"
name "Zeplin"
desc "Share, organize and collaborate on designs"
homepage "https://zeplin.io/"
livecheck do
url "https://api.appcenter.ms/v0.1/public/sparkle/apps/8926efff-e734-b6d3-03d0-9f41d90c34fc"
strategy :sparkle
end
auto_updates true
depends_on macos: ">= :high_sierra"
app "Zeplin.app"
zap trash: [
"~/Library/Caches/io.zeplin.osx",
"~/Library/Logs/Zeplin",
"~/Library/Preferences/io.zeplin.osx.plist",
]
end
| 21.884615 | 96 | 0.683656 |
1af72ab83142757ca0a7453e19fe3fc3be88e6a7 | 833 | module ProcSpecs
def self.new_proc_in_method
Proc.new
end
class SourceLocation
def self.my_proc
proc { true }
end
def self.my_lambda
lambda { true }
end
def self.my_proc_new
Proc.new { true }
end
def self.my_multiline_proc
proc do
'a'.upcase
1 + 22
end
end
def self.my_multiline_lambda
lambda do
'a'.upcase
1 + 22
end
end
def self.my_multiline_proc_new
Proc.new do
'a'.upcase
1 + 22
end
end
def self.my_detached_proc
body = proc { true }
proc &body
end
def self.my_detached_lambda
body = lambda { true }
lambda &body
end
def self.my_detached_proc_new
body = Proc.new { true }
Proc.new &body
end
end
end
| 15.145455 | 34 | 0.557023 |
7abf575359c3d5bea90085564ead11a82255fd7f | 4,799 | require 'net/http'
require 'uri'
require 'digest/sha1'
require 'rack/file'
module DAV4Rack
class RemoteFile < Rack::File
attr_accessor :path
alias :to_path :path
# path:: path to file (Actual path, preferably a URL since this is a *REMOTE* file)
# args:: Hash of arguments:
# :size -> Integer - number of bytes
# :mime_type -> String - mime type
# :last_modified -> String/Time - Time of last modification
# :sendfile -> True or String to define sendfile header variation
# :cache_directory -> Where to store cached files
# :cache_ref -> Reference to be used for cache file name (useful for changing URLs like S3)
# :sendfile_prefix -> String directory prefix. Eg: 'webdav' will result in: /wedav/#{path.sub('http://', '')}
# :sendfile_fail_gracefully -> Boolean if true will simply proxy if unable to determine proper sendfile
def initialize(path, args={})
@path = path
@args = args
@heads = {}
@cache_file = args[:cache_directory] ? cache_file_path : nil
@redefine_prefix = nil
if(@cache_file && File.exists?(@cache_file))
@root = ''
@path_info = @cache_file
@path = @path_info
elsif(args[:sendfile])
@redefine_prefix = 'sendfile'
@sendfile_header = args[:sendfile].is_a?(String) ? args[:sendfile] : nil
else
setup_remote
end
do_redefines(@redefine_prefix) if @redefine_prefix
end
# env:: Environment variable hash
# Process the call
def call(env)
serving(env)
end
# env:: Environment variable hash
# Return an empty result with the proper header information
def sendfile_serving(env)
header = @sendfile_header || env['sendfile.type'] || env['HTTP_X_SENDFILE_TYPE']
unless(header)
raise 'Failed to determine proper sendfile header value' unless @args[:sendfile_fail_gracefully]
setup_remote
do_redefines('remote')
call(env)
end
prefix = (@args[:sendfile_prefix] || env['HTTP_X_ACCEL_REMOTE_MAPPING']).to_s.sub(/^\//, '').sub(/\/$/, '')
[200, {
"Last-Modified" => last_modified,
"Content-Type" => content_type,
"Content-Length" => size,
"Redirect-URL" => @path,
"Redirect-Host" => @path.scan(%r{^https?://([^/\?]+)}).first.first,
header => "/#{prefix}"
},
['']]
end
# env:: Environment variable hash
# Return self to be processed
def remote_serving(e)
[200, {
"Last-Modified" => last_modified,
"Content-Type" => content_type,
"Content-Length" => size
}, self]
end
# Get the remote file
def remote_each
if(@store)
yield @store
else
@con.request_get(@call_path) do |res|
res.read_body(@store) do |part|
@cf.write part if @cf
yield part
end
end
end
end
# Size based on remote headers or given size
def size
@heads['content-length'] || @size
end
private
# Content type based on provided or remote headers
def content_type
@mime_type || @heads['content-type']
end
# Last modified type based on provided, remote headers or current time
def last_modified
@heads['last-modified'] || @modified || Time.now.httpdate
end
# Builds the path for the cached file
def cache_file_path
raise IOError.new 'Write permission is required for cache directory' unless File.writable?(@args[:cache_directory])
"#{@args[:cache_directory]}/#{Digest::SHA1.hexdigest((@args[:cache_ref] || @path).to_s + size.to_s + last_modified.to_s)}.cache"
end
# prefix:: prefix of methods to be redefined
# Redefine methods to do what we want in the proper situation
def do_redefines(prefix)
self.public_methods.each do |method|
m = method.to_s.dup
next unless m.slice!(0, prefix.to_s.length + 1) == "#{prefix}_"
self.class.class_eval "undef :'#{m}'"
self.class.class_eval "alias :'#{m}' :'#{method}'"
end
end
# Sets up all the requirements for proxying a remote file
def setup_remote
if(@cache_file)
begin
@cf = File.open(@cache_file, 'w+')
rescue
@cf = nil
end
end
@uri = URI.parse(@path)
@con = Net::HTTP.new(@uri.host, @uri.port)
@call_path = @uri.path + (@uri.query ? "?#{@uri.query}" : '')
res = @con.request_get(@call_path)
@heads = res.to_hash
res.value
@store = nil
@redefine_prefix = 'remote'
end
end
end
| 32.208054 | 134 | 0.585747 |
6170b8ebbc5103c3cfede8529b3b45c9a07c82d2 | 160 | module Cryptozoologist
module Addresses
def self.list
["Street", "Lane", "Avenue", "Boulevard", "Circle", "Court", "Way", "Drive"]
end
end
end | 22.857143 | 82 | 0.625 |
f737808b4cd0323b2785e20a6e2116db23e51c59 | 1,461 | module Spree
# Tax calculation is broken out at this level to allow easy integration with 3rd party
# taxation systems. Those systems are usually geared toward calculating all items at once
# rather than one at a time.
#
# To use an alternative tax calculator do this:
# Spree::ReturnAuthorization.reimbursement_tax_calculator = calculator_object
# where `calculator_object` is an object that responds to "call" and accepts a reimbursement object
class ReimbursementTaxCalculator
class << self
def call(reimbursement)
reimbursement.return_items.includes(:inventory_unit).each do |return_item|
set_tax!(return_item)
end
end
private
def set_tax!(return_item)
calculated_refund = Spree::ReturnItem.refund_amount_calculator.new.compute(return_item)
percent_of_tax = if return_item.pre_tax_amount <= 0 || calculated_refund <= 0
0
else
return_item.pre_tax_amount / calculated_refund
end
additional_tax_total = percent_of_tax * return_item.inventory_unit.additional_tax_total
included_tax_total = percent_of_tax * return_item.inventory_unit.included_tax_total
return_item.update_attributes!(additional_tax_total: additional_tax_total,
included_tax_total: included_tax_total)
end
end
end
end
| 38.447368 | 101 | 0.680356 |
39dbfb54527edebbb9db23f175705307f06bbade | 1,108 | require 'rake'
Gem::Specification.new do |s|
s.name = 'json_rpc_client_2'
s.homepage = 'https://github.com/reinerRubin/json_rpc_client_ruby_2'
s.license = 'MIT'
s.authors = ['Fredrik Liljegren', 'Lars Olsson', 'Denis Dervisevic', 'Reiner Rubin']
s.version = '0.1.1'
s.date = '2015-04-03'
s.summary = 'JSON-RPC 2.0 client.'
s.description = 'Asynchronous (EventMachine) JSON-RPC 2.0 over HTTP client.'
s.files = FileList['lib/**/*.rb', '[A-Z]*', 'test/**/*.rb'].to_a
s.platform = Gem::Platform::RUBY
s.require_path = 'lib'
s.required_ruby_version = '>= 2.0.0'
s.add_dependency('em-http-request')
s.add_dependency('addressable')
s.add_dependency('json')
s.add_dependency('logger')
s.add_dependency('null_logger')
s.add_development_dependency('rack')
s.add_development_dependency('rake')
s.add_development_dependency('webmock')
s.add_development_dependency('timeout')
s.add_development_dependency('test-unit')
end
| 38.206897 | 100 | 0.606498 |
1dfb4672c9f26e5972ef21ebbd132e22ae81b560 | 241 | module Puppet::Parser::Functions
newfunction(
:myfirstfunction,
:type => :rvalue,
:doc => "Testing the first function. ") do |args|
value = args[0]
result = "Hello World Function: " + value
return result
end
end
| 21.909091 | 53 | 0.630705 |
5d8e15b4c36fe0c5337825f4caedad76d21bb9b2 | 435 | # frozen_string_literal: true
module WasteCarriersEngine
class CompanyPostcodeFormsController < PostcodeFormsController
def new
super(CompanyPostcodeForm, "company_postcode_form")
end
def create
super(CompanyPostcodeForm, "company_postcode_form")
end
private
def transient_registration_attributes
params.fetch(:company_postcode_form, {}).permit(:temp_company_postcode)
end
end
end
| 21.75 | 77 | 0.758621 |
08d6e2cafe22ee962772dbf7ef91564059f39bcb | 25 | module SettingHelper
end
| 8.333333 | 20 | 0.88 |
115dfb516431e10306274e6b87ceb8e4ff0c5bfe | 1,945 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
Paperclip.options[:command_path] = ENV['IMAGEMAGICK_DIR']
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 34.122807 | 85 | 0.761954 |
398b345de980cdd5f87e0c4a9076bafd9166064b | 396 | shared_examples_for :hash_values_at do |method|
before { @method = method }
it "returns an array of values for the given keys" do
h = new_hash(:a => 9, :b => 'a', :c => -10, :d => nil)
h.send(@method).should be_kind_of(Array)
h.send(@method).should == []
h.send(@method, :a, :d, :b).should be_kind_of(Array)
h.send(@method, :a, :d, :b).should == [9, nil, 'a']
end
end
| 30.461538 | 58 | 0.593434 |
ac39ebfdc101c3d3edd0327e3d906bdaa123eafc | 386 | require 'nokogiri'
require 'open-uri'
require 'pry'
require_relative "../lib/beer_presenter/version"
require_relative "../lib/beer_presenter/common"
require_relative "../lib/beer_presenter/cli"
require_relative "../lib/beer_presenter/beer"
require_relative "../lib/beer_presenter/brewery"
require_relative "../lib/beer_presenter/style"
require_relative "../lib/beer_presenter/scraper"
| 32.166667 | 48 | 0.800518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.