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
|
---|---|---|---|---|---|
26f66c2e24503f79cff183ff7264f6553ea6dd19 | 921 | # encoding: utf-8
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |gem|
gem.name = "fluent-plugin-multi-format-parser"
gem.description = "Multi format parser plugin for Fluentd"
gem.homepage = "https://github.com/repeatedly/fluent-plugin-multi-format-parser"
gem.summary = gem.description
gem.version = File.read("VERSION").strip
gem.authors = ["Masahiro Nakagawa"]
gem.email = "[email protected]"
gem.has_rdoc = false
#gem.platform = Gem::Platform::RUBY
gem.license = 'Apache License (2.0)'
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.require_paths = ['lib']
gem.add_dependency "fluentd", [">= 0.14.0", "< 2"]
gem.add_development_dependency "rake", ">= 0.9.2"
end
| 40.043478 | 85 | 0.64278 |
91cd251d0c1a209507cc58621b63ea5b3b31c36f | 150 | class RemoveDefaultFromSongName < ActiveRecord::Migration[5.2]
def change
change_column_default :songs, :name, from: "Title", to: nil
end
end
| 25 | 63 | 0.746667 |
abfd16937f5e169c34e34bd79bb0c5b1cb9f2ecb | 241 | class CreateZipBoundaries < ActiveRecord::Migration
def change
create_table :zip_boundaries do |t|
t.string :name
t.string :zip_type
t.text :bounds, limit: 4294967295
t.timestamps null: false
end
end
end
| 20.083333 | 51 | 0.680498 |
d5b953646ed8f13b8d2f42539593bf06c59fd9ca | 191 | # frozen_string_literal: true
module Spina
module Admin
module Conferences
module Accounts
class ApplicationJob < ActiveJob::Base
end
end
end
end
end
| 14.692308 | 46 | 0.65445 |
03b9bd2687f608002c86b15006423afb6cf53bfb | 36,353 | # Copyright 2021 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
#
# frozen_string_literal: true
require_relative "../mock_server/spanner_mock_server"
require_relative "../test_helper"
require_relative "models/singer"
require_relative "models/album"
require "securerandom"
module MockServerTests
def self.create_random_singers_result(row_count, lock_version = false)
first_names = %w[Pete Alice John Ethel Trudy Naomi Wendy]
last_names = %w[Wendelson Allison Peterson Johnson Henderson Ericsson]
col_id = Google::Cloud::Spanner::V1::StructType::Field.new name: "id", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
col_first_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "first_name", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
col_last_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "last_name", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
col_last_performance = Google::Cloud::Spanner::V1::StructType::Field.new name: "last_performance", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::TIMESTAMP)
col_picture = Google::Cloud::Spanner::V1::StructType::Field.new name: "picture", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::BYTES)
col_revenues = Google::Cloud::Spanner::V1::StructType::Field.new name: "revenues", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::NUMERIC)
col_lock_version = Google::Cloud::Spanner::V1::StructType::Field.new name: "lock_version", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push col_id, col_first_name, col_last_name, col_last_performance, col_picture, col_revenues
metadata.row_type.fields.push col_lock_version if lock_version
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
(1..row_count).each { |_|
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: SecureRandom.random_number(1000000).to_s),
Google::Protobuf::Value.new(string_value: first_names.sample),
Google::Protobuf::Value.new(string_value: last_names.sample),
Google::Protobuf::Value.new(string_value: StatementResult.random_timestamp_string),
Google::Protobuf::Value.new(string_value: Base64.encode64(SecureRandom.alphanumeric(SecureRandom.random_number(10..200)))),
Google::Protobuf::Value.new(string_value: SecureRandom.random_number(1000.0..1000000.0).to_s),
)
row.values.push Google::Protobuf::Value.new(string_value: lock_version.to_s) if lock_version
result_set.rows.push row
}
StatementResult.new result_set
end
def self.create_random_albums_result(row_count)
adjectives = ["daily", "happy", "blue", "generous", "cooked", "bad", "open"]
nouns = ["windows", "potatoes", "bank", "street", "tree", "glass", "bottle"]
col_id = Google::Cloud::Spanner::V1::StructType::Field.new name: "id", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
col_title = Google::Cloud::Spanner::V1::StructType::Field.new name: "title", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
col_singer_id = Google::Cloud::Spanner::V1::StructType::Field.new name: "singer_id", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push col_id, col_title, col_singer_id
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
(1..row_count).each { |_|
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: SecureRandom.random_number(1000000).to_s),
Google::Protobuf::Value.new(string_value: "#{adjectives.sample} #{nouns.sample}"),
Google::Protobuf::Value.new(string_value: SecureRandom.random_number(1000000).to_s)
)
result_set.rows.push row
}
StatementResult.new result_set
end
def self.register_select_tables_result spanner_mock_server
sql = "SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, PARENT_TABLE_NAME, ON_DELETE_ACTION FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=''"
table_catalog = Google::Cloud::Spanner::V1::StructType::Field.new name: "TABLE_CATALOG", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
table_schema = Google::Cloud::Spanner::V1::StructType::Field.new name: "TABLE_SCHEMA", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
table_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "TABLE_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
parent_table_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "PARENT_TABLE_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
on_delete_action = Google::Cloud::Spanner::V1::StructType::Field.new name: "ON_DELETE_ACTION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push table_catalog, table_schema, table_name, parent_table_name, on_delete_action
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: "singers"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: "albums"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: "all_types"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: "table_with_commit_timestamps"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: ""),
Google::Protobuf::Value.new(string_value: "versioned_singers"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
)
result_set.rows.push row
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
def self.register_singers_columns_result spanner_mock_server
register_singers_columns_result_with_options spanner_mock_server, "singers", false
end
def self.register_versioned_singers_columns_result spanner_mock_server
register_singers_columns_result_with_options spanner_mock_server, "versioned_singers", true
end
def self.register_singers_columns_result_with_options spanner_mock_server, table_name, with_version_column
sql = "SELECT COLUMN_NAME, SPANNER_TYPE, IS_NULLABLE, CAST(COLUMN_DEFAULT AS STRING) AS COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='#{table_name}' ORDER BY ORDINAL_POSITION ASC"
column_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
spanner_type = Google::Cloud::Spanner::V1::StructType::Field.new name: "SPANNER_TYPE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
is_nullable = Google::Cloud::Spanner::V1::StructType::Field.new name: "IS_NULLABLE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_default = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_DEFAULT", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
ordinal_position = Google::Cloud::Spanner::V1::StructType::Field.new name: "ORDINAL_POSITION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push column_name, spanner_type, is_nullable, column_default, ordinal_position
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "id"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "1")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "first_name"),
Google::Protobuf::Value.new(string_value: "STRING(MAX)"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "2")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "last_name"),
Google::Protobuf::Value.new(string_value: "STRING(MAX)"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "3")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "last_performance"),
Google::Protobuf::Value.new(string_value: "TIMESTAMP"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "4")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "picture"),
Google::Protobuf::Value.new(string_value: "BYTES(MAX)"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "5")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "revenues"),
Google::Protobuf::Value.new(string_value: "NUMERIC"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "6")
)
result_set.rows.push row
if with_version_column
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "lock_version"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "7")
)
result_set.rows.push row
end
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
def self.register_singers_primary_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'singers' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' AND (T.PARENT_TABLE_NAME IS NULL OR COLUMN_NAME NOT IN ( SELECT COLUMN_NAME FROM TABLE_PK_COLS WHERE TABLE_NAME = T.PARENT_TABLE_NAME )) ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_singers_primary_and_parent_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'singers' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_versioned_singers_primary_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'versioned_singers' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' AND (T.PARENT_TABLE_NAME IS NULL OR COLUMN_NAME NOT IN ( SELECT COLUMN_NAME FROM TABLE_PK_COLS WHERE TABLE_NAME = T.PARENT_TABLE_NAME )) ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_versioned_singers_primary_and_parent_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'versioned_singers' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_albums_columns_result spanner_mock_server
sql = "SELECT COLUMN_NAME, SPANNER_TYPE, IS_NULLABLE, CAST(COLUMN_DEFAULT AS STRING) AS COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='albums' ORDER BY ORDINAL_POSITION ASC"
column_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
spanner_type = Google::Cloud::Spanner::V1::StructType::Field.new name: "SPANNER_TYPE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
is_nullable = Google::Cloud::Spanner::V1::StructType::Field.new name: "IS_NULLABLE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_default = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_DEFAULT", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
ordinal_position = Google::Cloud::Spanner::V1::StructType::Field.new name: "ORDINAL_POSITION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push column_name, spanner_type, is_nullable, column_default, ordinal_position
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "id"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "1")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "title"),
Google::Protobuf::Value.new(string_value: "STRING(MAX)"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "2")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "singer_id"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "3")
)
result_set.rows.push row
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
def self.register_albums_primary_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'albums' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' AND (T.PARENT_TABLE_NAME IS NULL OR COLUMN_NAME NOT IN ( SELECT COLUMN_NAME FROM TABLE_PK_COLS WHERE TABLE_NAME = T.PARENT_TABLE_NAME )) ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_albums_primary_and_parent_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'albums' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_all_types_columns_result spanner_mock_server
sql = "SELECT COLUMN_NAME, SPANNER_TYPE, IS_NULLABLE, CAST(COLUMN_DEFAULT AS STRING) AS COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='all_types' ORDER BY ORDINAL_POSITION ASC"
column_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
spanner_type = Google::Cloud::Spanner::V1::StructType::Field.new name: "SPANNER_TYPE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
is_nullable = Google::Cloud::Spanner::V1::StructType::Field.new name: "IS_NULLABLE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_default = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_DEFAULT", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
ordinal_position = Google::Cloud::Spanner::V1::StructType::Field.new name: "ORDINAL_POSITION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push column_name, spanner_type, is_nullable, column_default, ordinal_position
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "id"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "1")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_string"),
Google::Protobuf::Value.new(string_value: "STRING(MAX)"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "2")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_int64"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "3")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_float64"),
Google::Protobuf::Value.new(string_value: "FLOAT64"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "4")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_numeric"),
Google::Protobuf::Value.new(string_value: "NUMERIC"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "5")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_bool"),
Google::Protobuf::Value.new(string_value: "BOOL"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "6")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_bytes"),
Google::Protobuf::Value.new(string_value: "BYTES(MAX)"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "7")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_date"),
Google::Protobuf::Value.new(string_value: "DATE"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "8")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_timestamp"),
Google::Protobuf::Value.new(string_value: "TIMESTAMP"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "9")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_json"),
Google::Protobuf::Value.new(string_value: "JSON"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "10")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_string"),
Google::Protobuf::Value.new(string_value: "ARRAY<STRING(MAX)>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "11")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_int64"),
Google::Protobuf::Value.new(string_value: "ARRAY<INT64>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "12")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_float64"),
Google::Protobuf::Value.new(string_value: "ARRAY<FLOAT64>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "13")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_numeric"),
Google::Protobuf::Value.new(string_value: "ARRAY<NUMERIC>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "14")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_bool"),
Google::Protobuf::Value.new(string_value: "ARRAY<BOOL>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "15")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_bytes"),
Google::Protobuf::Value.new(string_value: "ARRAY<BYTES(MAX)>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "16")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_date"),
Google::Protobuf::Value.new(string_value: "ARRAY<DATE>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "17")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_timestamp"),
Google::Protobuf::Value.new(string_value: "ARRAY<TIMESTAMP>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "18")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "col_array_json"),
Google::Protobuf::Value.new(string_value: "ARRAY<JSON>"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "19")
)
result_set.rows.push row
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
def self.register_all_types_primary_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'all_types' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' AND (T.PARENT_TABLE_NAME IS NULL OR COLUMN_NAME NOT IN ( SELECT COLUMN_NAME FROM TABLE_PK_COLS WHERE TABLE_NAME = T.PARENT_TABLE_NAME )) ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_all_types_primary_and_parent_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'all_types' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_table_with_commit_timestamps_columns_result spanner_mock_server
sql = "SELECT COLUMN_NAME, SPANNER_TYPE, IS_NULLABLE, CAST(COLUMN_DEFAULT AS STRING) AS COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='table_with_commit_timestamps' ORDER BY ORDINAL_POSITION ASC"
column_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
spanner_type = Google::Cloud::Spanner::V1::StructType::Field.new name: "SPANNER_TYPE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
is_nullable = Google::Cloud::Spanner::V1::StructType::Field.new name: "IS_NULLABLE", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_default = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_DEFAULT", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
ordinal_position = Google::Cloud::Spanner::V1::StructType::Field.new name: "ORDINAL_POSITION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push column_name, spanner_type, is_nullable, column_default, ordinal_position
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "id"),
Google::Protobuf::Value.new(string_value: "INT64"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "1")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "value"),
Google::Protobuf::Value.new(string_value: "STRING(MAX)"),
Google::Protobuf::Value.new(string_value: "NO"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "2")
)
result_set.rows.push row
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "last_updated"),
Google::Protobuf::Value.new(string_value: "TIMESTAMP"),
Google::Protobuf::Value.new(string_value: "YES"),
Google::Protobuf::Value.new(null_value: "NULL_VALUE"),
Google::Protobuf::Value.new(string_value: "3")
)
result_set.rows.push row
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
def self.register_table_with_commit_timestamps_primary_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'table_with_commit_timestamps' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' AND (T.PARENT_TABLE_NAME IS NULL OR COLUMN_NAME NOT IN ( SELECT COLUMN_NAME FROM TABLE_PK_COLS WHERE TABLE_NAME = T.PARENT_TABLE_NAME )) ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
def self.register_table_with_commit_timestamps_primary_and_parent_key_columns_result spanner_mock_server
sql = "WITH TABLE_PK_COLS AS ( SELECT C.TABLE_NAME, C.COLUMN_NAME, C.INDEX_NAME, C.COLUMN_ORDERING, C.ORDINAL_POSITION FROM INFORMATION_SCHEMA.INDEX_COLUMNS C WHERE C.INDEX_TYPE = 'PRIMARY_KEY' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '') SELECT INDEX_NAME, COLUMN_NAME, COLUMN_ORDERING, ORDINAL_POSITION FROM TABLE_PK_COLS INNER JOIN INFORMATION_SCHEMA.TABLES T USING (TABLE_NAME) WHERE TABLE_NAME = 'table_with_commit_timestamps' AND TABLE_CATALOG = '' AND TABLE_SCHEMA = '' ORDER BY ORDINAL_POSITION"
register_key_columns_result spanner_mock_server, sql
end
private
def self.register_key_columns_result spanner_mock_server, sql
index_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "INDEX_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_name = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_NAME", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
column_ordering = Google::Cloud::Spanner::V1::StructType::Field.new name: "COLUMN_ORDERING", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::STRING)
ordinal_position = Google::Cloud::Spanner::V1::StructType::Field.new name: "ORDINAL_POSITION", type: Google::Cloud::Spanner::V1::Type.new(code: Google::Cloud::Spanner::V1::TypeCode::INT64)
metadata = Google::Cloud::Spanner::V1::ResultSetMetadata.new row_type: Google::Cloud::Spanner::V1::StructType.new
metadata.row_type.fields.push index_name, column_name, column_ordering, ordinal_position
result_set = Google::Cloud::Spanner::V1::ResultSet.new metadata: metadata
row = Google::Protobuf::ListValue.new
row.values.push(
Google::Protobuf::Value.new(string_value: "PRIMARY_KEY"),
Google::Protobuf::Value.new(string_value: "id"),
Google::Protobuf::Value.new(string_value: "ASC"),
Google::Protobuf::Value.new(string_value: "1"),
)
result_set.rows.push row
spanner_mock_server.put_statement_result sql, StatementResult.new(result_set)
end
end
| 62.894464 | 651 | 0.730531 |
ab288458b2e10e6b0ee90b1c65d7920a70805c77 | 1,021 |
module Applocale
module ParseXLSXModule
class Helper
def self.collabel_to_colno(collabel)
if collabel.match(/^(\d)+$/)
return collabel.to_i
end
number = collabel.tr("A-Z", "1-9a-q").to_i(27)
number -= 1 if number > 27
return number
end
end
end
end
module Applocale
module Config
class SheetInfoByRow
def to_keyStrWithColNo(sheetcontent)
sheetcontent.header_rowno = self.row
keycolno = Applocale::ParseXLSXModule::Helper.collabel_to_colno(self.key_col)
sheetcontent.keyStr_with_colno = Applocale::ParseModelModule::KeyStrWithColNo.new(nil, keycolno)
sheetcontent.lang_with_colno_list = Array.new
self.lang_cols.each do |lang, collabel|
colno = Applocale::ParseXLSXModule::Helper.collabel_to_colno(collabel)
obj = Applocale::ParseModelModule::LangWithColNo.new(nil,lang, colno)
sheetcontent.lang_with_colno_list.push(obj)
end
end
end
end
end | 27.594595 | 104 | 0.670911 |
187b002086bf46e5fe9dbd7b69f87e5296b9d355 | 125 | class RemoveTitleFromEvents < ActiveRecord::Migration[6.1]
def change
remove_column :events, :title, :string
end
end
| 20.833333 | 58 | 0.752 |
ac7b9a52d9178cb83c9dc502dc9a2736b4fcf6a2 | 273 |
require './tl_installer'
class SetupError < StandardError; end
if $0 == __FILE__
begin
ToplevelInstaller.invoke
rescue SetupError
raise if $DEBUG
$stderr.puts $!.message
$stderr.puts "Try 'ruby #{$0} --help' for detailed usage."
exit 1
end
end
| 17.0625 | 62 | 0.67033 |
21e88d78dcbe2fd778b1d93520d743208cbf6024 | 450 | RSpec::Matchers.define :be_allowed_to do |ability, resource|
match do |api_user|
api_user.may?(ability, resource)
end
description do
"have the ability to #{ability} #{resource}"
end
failure_message_for_should do
"expected user to have the ability to #{ability} #{resource}, but it didn't."
end
failure_message_for_should_not do
"expected user bot to have the ability to #{ability} #{resource}, but it did."
end
end
| 25 | 82 | 0.711111 |
ab18a2d999058765bce7f3975a2d237f444bd5ba | 934 | require 'yaml'
module DogWatch
module Model
##
# Manages API configuration. Currently handles
# credential only.
##
class Config
attr_accessor :api_key
attr_accessor :app_key
attr_accessor :timeout
# @param [String] api_key
# @param [String] app_key
# @param [Integer] timeout
def initialize(api_key = nil, app_key = nil, timeout = 5)
@api_key = api_key unless api_key.nil?
@app_key = app_key unless app_key.nil?
@timeout = timeout
return unless app_key.nil? || api_key.nil?
from_file
end
def from_file
begin
config_file = IO.read("#{Dir.home}/.dogwatch/credentials")
rescue
raise('No credentials supplied')
end
credentials = YAML.load(config_file)
@api_key = credentials['api_key']
@app_key = credentials['app_key']
end
end
end
end
| 23.35 | 68 | 0.600642 |
f88fef848b1613eaaaa874d0b13de0e35c9b525b | 384 | module FilterChain
class FilterChainError < RuntimeError; end
class NextFilterMissingError < FilterChainError; end
class MissingCollectorError < FilterChainError; end
class UnknownFormatError < FilterChainError; end
class MissingRequiredOptError < FilterChainError; end
class InvalidStateError < FilterChainError; end
class MissingBlockError < FilterChainError; end
end | 42.666667 | 55 | 0.828125 |
269e160d43a15fba0120722df95b5c2174d08353 | 1,552 | #
# Author:: John Keiser (<[email protected]>)
# Copyright:: Copyright 2012-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "chef/chef_fs/file_system/chef_server/cookbook_dir"
class Chef
module ChefFS
module FileSystem
module ChefServer
class VersionedCookbookDir < CookbookDir
# See Erchef code
# https://github.com/opscode/chef_objects/blob/968a63344d38fd507f6ace05f73d53e9cd7fb043/src/chef_regex.erl#L94
VALID_VERSIONED_COOKBOOK_NAME = /^([.a-zA-Z0-9_-]+)-(\d+\.\d+\.\d+)$/
def initialize(name, parent, options = {})
super(name, parent)
# If the name is apache2-1.0.0 and versioned_cookbooks is on, we know
# the actual cookbook_name and version.
if name =~ VALID_VERSIONED_COOKBOOK_NAME
@cookbook_name = $1
@version = $2
else
@exists = false
end
end
end
end
end
end
end
| 33.73913 | 120 | 0.661727 |
08476ad69660084f39dce9d4ba110436e0f40ea6 | 329 | class CreateProfiles < ActiveRecord::Migration
def change
create_table :profiles do |t|
t.string :name
t.text :biography
t.references :user, index: true, null: false
t.text :neuron_ids, array: true, default: []
t.timestamps null: false
end
add_foreign_key :profiles, :users
end
end
| 23.5 | 50 | 0.662614 |
5d37c82148465fbe831a832557a181d9023071b2 | 204 | cask "phonetrans" do
version :latest
sha256 :no_check
url "https://dl.imobie.com/phonetrans-mac.dmg"
name "PhoneTrans"
homepage "https://www.imobie.com/phonetrans/"
app "PhoneTrans.app"
end
| 18.545455 | 48 | 0.715686 |
bbb8c81b88352fa91a94579bb87d9f99e1d11186 | 2,479 | require 'nokogiri/xml/pp'
require 'nokogiri/xml/parse_options'
require 'nokogiri/xml/sax'
require 'nokogiri/xml/searchable'
require 'nokogiri/xml/node'
require 'nokogiri/xml/attribute_decl'
require 'nokogiri/xml/element_decl'
require 'nokogiri/xml/element_content'
require 'nokogiri/xml/character_data'
require 'nokogiri/xml/namespace'
require 'nokogiri/xml/attr'
require 'nokogiri/xml/dtd'
require 'nokogiri/xml/cdata'
require 'nokogiri/xml/text'
require 'nokogiri/xml/document'
require 'nokogiri/xml/document_fragment'
require 'nokogiri/xml/processing_instruction'
require 'nokogiri/xml/node_set'
require 'nokogiri/xml/syntax_error'
require 'nokogiri/xml/xpath'
require 'nokogiri/xml/xpath_context'
require 'nokogiri/xml/builder'
require 'nokogiri/xml/reader'
require 'nokogiri/xml/notation'
require 'nokogiri/xml/entity_decl'
require 'nokogiri/xml/entity_reference'
require 'nokogiri/xml/schema'
require 'nokogiri/xml/relax_ng'
module Nokogiri
class << self
###
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
def XML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block
Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
end
end
module XML
# Original C14N 1.0 spec canonicalization
XML_C14N_1_0 = 0
# Exclusive C14N 1.0 spec canonicalization
XML_C14N_EXCLUSIVE_1_0 = 1
# C14N 1.1 spec canonicalization
XML_C14N_1_1 = 2
class << self
###
# Parse an XML document using the Nokogiri::XML::Reader API. See
# Nokogiri::XML::Reader for mor information
def Reader string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
# Give the options to the user
yield options if block_given?
if string_or_io.respond_to? :read
return Reader.from_io(string_or_io, url, encoding, options.to_i)
end
Reader.from_memory(string_or_io, url, encoding, options.to_i)
end
###
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
Document.parse(thing, url, encoding, options, &block)
end
####
# Parse a fragment from +string+ in to a NodeSet.
def fragment string
XML::DocumentFragment.parse(string)
end
end
end
end
| 32.618421 | 94 | 0.713191 |
f77cf47fb71fe3df8c90c8d8d833ba204017d4f9 | 6,184 | # encoding: utf-8
require 'cases/helper'
require 'models/topic'
require 'models/person'
require 'bigdecimal'
class NumericalityValidationTest < ActiveModel::TestCase
def teardown
Topic.clear_validators!
end
NIL = [nil]
BLANK = ["", " ", " \t \r \n"]
BIGDECIMAL_STRINGS = %w(12345678901234567890.1234567890) # 30 significant digits
FLOAT_STRINGS = %w(0.0 +0.0 -0.0 10.0 10.5 -10.5 -0.0001 -090.1 90.1e1 -90.1e5 -90.1e-5 90e-5)
INTEGER_STRINGS = %w(0 +0 -0 10 +10 -10 0090 -090)
FLOATS = [0.0, 10.0, 10.5, -10.5, -0.0001] + FLOAT_STRINGS
INTEGERS = [0, 10, -10] + INTEGER_STRINGS
BIGDECIMAL = BIGDECIMAL_STRINGS.collect! { |bd| BigDecimal.new(bd) }
JUNK = ["not a number", "42 not a number", "0xdeadbeef", "0xinvalidhex", "0Xdeadbeef", "00-1", "--3", "+-3", "+3-1", "-+019.0", "12.12.13.12", "123\nnot a number"]
INFINITY = [1.0/0.0]
def test_default_validates_numericality_of
Topic.validates_numericality_of :approved
invalid!(NIL + BLANK + JUNK)
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
end
def test_validates_numericality_of_with_nil_allowed
Topic.validates_numericality_of :approved, allow_nil: true
invalid!(JUNK + BLANK)
valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
end
def test_validates_numericality_of_with_integer_only
Topic.validates_numericality_of :approved, only_integer: true
invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
valid!(INTEGERS)
end
def test_validates_numericality_of_with_integer_only_and_nil_allowed
Topic.validates_numericality_of :approved, only_integer: true, allow_nil: true
invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY)
valid!(NIL + INTEGERS)
end
def test_validates_numericality_with_greater_than
Topic.validates_numericality_of :approved, greater_than: 10
invalid!([-10, 10], 'must be greater than 10')
valid!([11])
end
def test_validates_numericality_with_greater_than_or_equal
Topic.validates_numericality_of :approved, greater_than_or_equal_to: 10
invalid!([-9, 9], 'must be greater than or equal to 10')
valid!([10])
end
def test_validates_numericality_with_equal_to
Topic.validates_numericality_of :approved, equal_to: 10
invalid!([-10, 11] + INFINITY, 'must be equal to 10')
valid!([10])
end
def test_validates_numericality_with_less_than
Topic.validates_numericality_of :approved, less_than: 10
invalid!([10], 'must be less than 10')
valid!([-9, 9])
end
def test_validates_numericality_with_less_than_or_equal_to
Topic.validates_numericality_of :approved, less_than_or_equal_to: 10
invalid!([11], 'must be less than or equal to 10')
valid!([-10, 10])
end
def test_validates_numericality_with_odd
Topic.validates_numericality_of :approved, odd: true
invalid!([-2, 2], 'must be odd')
valid!([-1, 1])
end
def test_validates_numericality_with_even
Topic.validates_numericality_of :approved, even: true
invalid!([-1, 1], 'must be even')
valid!([-2, 2])
end
def test_validates_numericality_with_greater_than_less_than_and_even
Topic.validates_numericality_of :approved, greater_than: 1, less_than: 4, even: true
invalid!([1, 3, 4])
valid!([2])
end
def test_validates_numericality_with_other_than
Topic.validates_numericality_of :approved, other_than: 0
invalid!([0, 0.0])
valid!([-1, 42])
end
def test_validates_numericality_with_proc
Topic.send(:define_method, :min_approved, lambda { 5 })
Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved }
invalid!([3, 4])
valid!([5, 6])
Topic.send(:remove_method, :min_approved)
end
def test_validates_numericality_with_symbol
Topic.send(:define_method, :max_approved, lambda { 5 })
Topic.validates_numericality_of :approved, less_than_or_equal_to: :max_approved
invalid!([6])
valid!([4, 5])
Topic.send(:remove_method, :max_approved)
end
def test_validates_numericality_with_numeric_message
Topic.validates_numericality_of :approved, less_than: 4, message: "smaller than %{count}"
topic = Topic.new("title" => "numeric test", "approved" => 10)
assert !topic.valid?
assert_equal ["smaller than 4"], topic.errors[:approved]
Topic.validates_numericality_of :approved, greater_than: 4, message: "greater than %{count}"
topic = Topic.new("title" => "numeric test", "approved" => 1)
assert !topic.valid?
assert_equal ["greater than 4"], topic.errors[:approved]
end
def test_validates_numericality_of_for_ruby_class
Person.validates_numericality_of :karma, allow_nil: false
p = Person.new
p.karma = "Pix"
assert p.invalid?
assert_equal ["is not a number"], p.errors[:karma]
p.karma = "1234"
assert p.valid?
ensure
Person.clear_validators!
end
def test_validates_numericality_with_invalid_args
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, equal_to: "foo" }
end
private
def invalid!(values, error = nil)
with_each_topic_approved_value(values) do |topic, value|
assert topic.invalid?, "#{value.inspect} not rejected as a number"
assert topic.errors[:approved].any?, "FAILED for #{value.inspect}"
assert_equal error, topic.errors[:approved].first if error
end
end
def valid!(values)
with_each_topic_approved_value(values) do |topic, value|
assert topic.valid?, "#{value.inspect} not accepted as a number"
end
end
def with_each_topic_approved_value(values)
topic = Topic.new(title: "numeric test", content: "whatever")
values.each do |value|
topic.approved = value
yield topic, value
end
end
end
| 31.712821 | 165 | 0.717658 |
ffa41ba07e4edfcfc213ca310bf6935955ab4ab9 | 74 | Chronic::Parser::DEFAULT_OPTIONS[:endian_precedence] = [:little, :middle]
| 37 | 73 | 0.77027 |
61923910cae4564fb3363104264633665b26278e | 390 | class AddRegistrationClosedAtToParliament < ActiveRecord::Migration
class Parliament < ActiveRecord::Base; end
def up
add_column :parliaments, :registration_closed_at, :datetime
parliament = Parliament.first!
parliament.update!(registration_closed_at: "2017-05-22T23:59:59.999999+01:00")
end
def down
remove_column :parliaments, :registration_closed_at
end
end
| 26 | 82 | 0.771795 |
1a7a2ec1adf066b1be387ee8836306814868741c | 260 | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.timestamps null: false
end
end
end
| 21.666667 | 43 | 0.623077 |
6abade48df800e1fa24bb1a6b832ad81c0bc9847 | 319 | module Bootswitch
module Helpers
def themes
Bootswitch.configuration.themes
end
def theme_name
send(Bootswitch.configuration.theme_method) || Bootswitch.configuration.default_theme
end
def theme_stylesheet_link_tag
render(partial: 'theme/stylesheet_link_tag')
end
end
end | 21.266667 | 91 | 0.736677 |
4a9330cbb8ad87fbd68cbd91440f884c02ae74c9 | 2,975 | class EventsController < ApplicationController
after_action :create_notifications, only: [:create], if: -> { @event.persisted? }
def edit
@event = Event.find(params[:id])
end
def create
@trip_location = TripLocation.find(params[:trip_location_id])
@event = Event.new(event_params)
@event.trip_location = @trip_location
@event.user_id = current_user.id
if @event.save
redirect_to trip_trip_location_path(@trip_location.trip, @trip_location), notice: "The event was created"
else
redirect_to trip_trip_location_path(@trip_location.trip, @trip_location), notice: "There was an error creating the event"
end
end
def update
@event = Event.find(params[:id])
@event.assign_attributes(event_params)
if @event.save
redirect_to trip_trip_location_path(@event.trip_location.trip, @event.trip_location), notice: "The event was updated"
else
redirect_to trip_trip_location_path(@event.trip_location.trip, @event.trip_location), notice: "There was an error updating the event"
end
end
def destroy
@event = Event.find(params[:id])
@event.destroy
redirect_to trip_trip_location_path(@event.trip_location.trip, @event.trip_location), notice: "The event was deleted"
end
private
def event_params
params.require(:event).permit(:name,
:start_at,
:start_at_time,
:end_at,
:end_at_time,
:description,
:location_id)
end
def create_notifications
message = " created a new event on "
trip_link = "<a href=#{trip_path(@trip_location.trip)}>#{@trip_location.trip.name}</a>"
heading = "#{current_user.name} #{message} #{trip_link}"
mobile_url = @trip_location.custom_email_html(@event, message, "new_event")
push_message = "#{current_user.name} #{message} #{@trip_location.trip.name}"
@trip_location.participants.each do |participant|
unless current_user == participant
Notification.create(heading: heading, recipient: participant, sender: current_user, notify_type: "new_event", trip_location_id: @trip_location.id, user_setting_key: UserSetting::NOTIFICATION_EMAIL_NEW_ACTIVITY_IN_MY_TRIPS, context: mobile_url)
if participant.ios_device_token.present?
device_token = participant.ios_device_token
type = "ios"
else
device_token = participant.android_device_token
type = "android"
end
data = { notify_type: "new_event", sender_user_id: current_user.id, recipient_user_id: participant.id, trip_location_id: @trip_location.id, trip_id: @trip_location.trip.id, name: current_user.name, device_token: device_token, device_type: type, message: push_message }
Notification.send_push_notification(data) if device_token.present?
end
end
end
end
| 40.753425 | 276 | 0.676639 |
1113fb2abb43ee287c073c1520c4a354dff1fc98 | 1,458 | require 'simplecov'
SimpleCov.start
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'll_pay'
LlPay.oid_partner = '201103171000000000'
LlPay.rsa_pri_key = <<-EOF
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANa4zOJbVHFp7T2c
fpiAbTYrghTpcPGt1ZetPeSoWa5d27+RofmV8QjhJq/PF5uKKRe2mjYySVQRi3/x
dXoPlWgGKWA8Yf0fbVIEsQiYjLJvPn856XHlXaDe0P+TJXYlu7fv2M0KDMDb3Vbb
DmloRrwehWfdbpfle3scL3M4U2dvAgMBAAECgYBogxyelKueZFuoIHLyEZiWxEiV
myZxTBZptFYq5NJ5749VSDJZxGTE2Ko26oroFzB3LVcUSBevBrcquEFg/xLN4W98
VvRh4K/fZoLGaq702qgLxi6GaT5D/qxCS5nR+ywD7x8HygKWEnLlcgJnYy+b23Bm
omy7jveK5GCsSBsmSQJBAPpa5CPjfjcWQ96mxDeWnHnaoEEfEIxpV4CvCG6hPs8z
6hN2GwjRgw212K+YN24C02UubnJjTYFmPcqGW3ln1h0CQQDbkDnd+9IU3+cJv9lL
CHetlpqJu889fHNRDKJjZN1TcuOoFbFpHcWRy8e9HVf2+6HyviviACjbAm/zkSfr
KQ37AkBfQMvCl+DCxtbl1N+dItHATx1gCZi7Q61GSdJUfUcvgNoTs4EPtt89DS43
iRu14J9bxPHC1eN8U1E5SCtvosFFAkAmRd3QdDUKrnz3lhmqmq9B8x69I5/cd/Ui
C7HC4bIy+bP1eNKUIDxwTbVjodnTk8mHJt8/Zge5JZOeQY9TzrRBAkEA4zz/xhlM
aFHWL/XRi/w6mxWEUSB0MaKznI1IQKxtmk4/dZnIi0CYRMOweQ5Z7srxL7IKlhEE
d2q+YV7MPK9i9Q==
-----END PRIVATE KEY-----
EOF
LlPay::YT_PUB_KEY = <<-EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWuMziW1Rxae09nH6YgG02K4IU
6XDxrdWXrT3kqFmuXdu/kaH5lfEI4SavzxebiikXtpo2MklUEYt/8XV6D5VoBilg
PGH9H21SBLEImIyybz5/Oelx5V2g3tD/kyV2Jbu379jNCgzA291W2w5paEa8HoVn
3W6X5Xt7HC9zOFNnbwIDAQAB
-----END PUBLIC KEY-----
EOF
LlPay.md5_key = '201408071000001543test_20140812'
| 38.368421 | 64 | 0.886145 |
1c6f9bd842007f450d6d5708a8065effa7a8239e | 1,038 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/weibo_2/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["simsicon"]
gem.email = ["[email protected]"]
gem.description = %q{WeioOAuth2 is a Ruby gem that provides a wrapper for interacting with sina weibo's v2 API,
which is currently the latest version. The output data format is Hashie::Mash}
gem.summary = "A oauth2 gem for weibo"
gem.homepage = "http://github.com/simsicon/weibo_2"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "weibo_2"
gem.require_paths = ["lib"]
gem.version = WeiboOAuth2::Version
gem.add_development_dependency "rspec", "~> 2.6"
gem.add_runtime_dependency 'oauth2'
gem.add_runtime_dependency 'hashie'
gem.add_runtime_dependency 'multi_json'
gem.add_runtime_dependency 'rest-client'
end
| 39.923077 | 115 | 0.66185 |
ff2c60ad0eca6709ac7542d70b9854502f994c39 | 559 | FactoryGirl.define do
factory :iiiflayer, class: Trifle::IIIFLayer do
transient do
image nil
end
sequence(:title) { |n| "Layer #{n}"}
sequence(:description) { |n| "test description #{n}" }
width '1000'
height '2000'
sequence(:image_source ) { |n| "oubliette:testtest#{n}" }
sequence(:image_location) { |n| "folder/layer_image#{n}.ptif" }
embed_xywh "0,0,1000,2000"
after :build do |layer,evaluator|
layer.instance_variable_set(:@container, evaluator.image) if evaluator.image.present?
end
end
end | 29.421053 | 91 | 0.652952 |
f8fe9547e566af9411aa8249f2b43a0eff7b7e95 | 316 | module Miam
class AuthenticationHandler
Error = Class.new(StandardError)
AuthResult = Struct.new(
:account_id,
:owner_type,
:owner_name,
:policy_name,
:statement
)
def initialize(token)
@token = token
end
def allow!
raise Error
end
end
end
| 15.047619 | 36 | 0.598101 |
f8de99268d62da887bbb8127728b69a665a89206 | 221 | # frozen_string_literal: true
FactoryBot.define do
factory :eve_type_dogma_attribute, class: Eve::TypeDogmaAttribute do
association :type, factory: :eve_type
sequence(:attribute_id)
value { 1 }
end
end
| 18.416667 | 70 | 0.742081 |
03c59bfccb1f04ed4e92ef5e8fee132bf144d013 | 5,108 | require 'bigdecimal'
#
#--
# Contents:
# sqrt(x, prec)
# sin (x, prec)
# cos (x, prec)
# atan(x, prec) Note: |x|<1, x=0.9999 may not converge.
# log (x, prec)
# PI (prec)
# E (prec) == exp(1.0,prec)
#
# where:
# x ... BigDecimal number to be computed.
# |x| must be small enough to get convergence.
# prec ... Number of digits to be obtained.
#++
#
# Provides mathematical functions.
#
# Example:
#
# require "bigdecimal"
# require "bigdecimal/math"
#
# include BigMath
#
# a = BigDecimal((PI(100)/2).to_s)
# puts sin(a,100) # -> 0.10000000000000000000......E1
#
module BigMath
module_function
# Computes the square root of x to the specified number of digits of
# precision.
#
# BigDecimal.new('2').sqrt(16).to_s
# -> "0.14142135623730950488016887242096975E1"
#
def sqrt(x,prec)
x.sqrt(prec)
end
# Computes the sine of x to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
def sin(x, prec)
raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
two = BigDecimal("2")
x = -x if neg = x < 0
if x > (twopi = two * BigMath.PI(prec))
if x > 30
x %= twopi
else
x -= twopi while x > twopi
end
end
x1 = x
x2 = x.mult(x,n)
sign = 1
y = x
d = y
i = one
z = one
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
sign = -sign
x1 = x2.mult(x1,n)
i += two
z *= (i-one) * i
d = sign * x1.div(z,m)
y += d
end
neg ? -y : y
end
# Computes the cosine of x to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
def cos(x, prec)
raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
two = BigDecimal("2")
x = -x if x < 0
if x > (twopi = two * BigMath.PI(prec))
if x > 30
x %= twopi
else
x -= twopi while x > twopi
end
end
x1 = one
x2 = x.mult(x,n)
sign = 1
y = one
d = y
i = BigDecimal("0")
z = one
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
sign = -sign
x1 = x2.mult(x1,n)
i += two
z *= (i-one) * i
d = sign * x1.div(z,m)
y += d
end
y
end
# Computes the arctangent of x to the specified number of digits of precision.
#
# If x is NaN, returns NaN.
def atan(x, prec)
raise ArgumentError, "Zero or negative precision for atan" if prec <= 0
return BigDecimal("NaN") if x.nan?
pi = PI(prec)
x = -x if neg = x < 0
return pi.div(neg ? -2 : 2, prec) if x.infinite?
return pi / (neg ? -4 : 4) if x.round(prec) == 1
x = BigDecimal("1").div(x, prec) if inv = x > 1
x = (-1 + sqrt(1 + x**2, prec))/x if dbl = x > 0.5
n = prec + BigDecimal.double_fig
y = x
d = y
t = x
r = BigDecimal("3")
x2 = x.mult(x,n)
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = -t.mult(x2,n)
d = t.div(r,m)
y += d
r += 2
end
y *= 2 if dbl
y = pi / 2 - y if inv
y = -y if neg
y
end
# Computes the value of pi to the specified number of digits of precision.
def PI(prec)
raise ArgumentError, "Zero or negative argument for PI" if prec <= 0
n = prec + BigDecimal.double_fig
zero = BigDecimal("0")
one = BigDecimal("1")
two = BigDecimal("2")
m25 = BigDecimal("-0.04")
m57121 = BigDecimal("-57121")
pi = zero
d = one
k = one
w = one
t = BigDecimal("-80")
while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = t*m25
d = t.div(k,m)
k = k+two
pi = pi + d
end
d = one
k = one
w = one
t = BigDecimal("956")
while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = t.div(m57121,n)
d = t.div(k,m)
pi = pi + d
k = k+two
end
pi
end
# Computes e (the base of natural logarithms) to the specified number of
# digits of precision.
def E(prec)
raise ArgumentError, "Zero or negative precision for E" if prec <= 0
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
y = one
d = y
z = one
i = 0
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
i += 1
z *= i
d = one.div(z,m)
y += d
end
y
end
end
| 24.676329 | 80 | 0.540525 |
7aeec39e070cfc54b8764dd8c823c975cd903b7f | 1,585 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20171004163118) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "letters", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.integer "score"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "age"
t.integer "missed_math"
t.integer "missed_science"
t.integer "missed_spelling"
t.integer "missed_counting"
t.integer "missed_colors"
end
create_table "words", force: :cascade do |t|
t.string "name"
t.integer "letter_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 35.222222 | 86 | 0.735647 |
18ebe5499886dc69600a7618a63f47c63447bfd7 | 1,649 | # 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_06_01
module Models
#
# Parameters that define the retention policy for flow log.
#
class RetentionPolicyParameters
include MsRestAzure
# @return [Integer] Number of days to retain flow log records. Default
# value: 0 .
attr_accessor :days
# @return [Boolean] Flag to enable/disable retention. Default value:
# false .
attr_accessor :enabled
#
# Mapper for RetentionPolicyParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RetentionPolicyParameters',
type: {
name: 'Composite',
class_name: 'RetentionPolicyParameters',
model_properties: {
days: {
client_side_validation: true,
required: false,
serialized_name: 'days',
default_value: 0,
type: {
name: 'Number'
}
},
enabled: {
client_side_validation: true,
required: false,
serialized_name: 'enabled',
default_value: false,
type: {
name: 'Boolean'
}
}
}
}
}
end
end
end
end
| 26.596774 | 76 | 0.532444 |
e9c00624a4fb7b36f9418e2fca69a43169357de4 | 2,187 | class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :comment_to_comments, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :favorited_posts, through: :favorites, source: :post
#DM
has_many :messages, dependent: :destroy
has_many :entries, dependent: :destroy
has_many :rooms, through: :entries
# follow機能
has_many :following_relationships, foreign_key: "follower_id", class_name:"Relationship", dependent: :destroy
has_many :followings, through: :following_relationships
has_many :follower_relationships, foreign_key: "following_id", class_name:"Relationship", dependent: :destroy
has_many :followers, through: :follower_relationships
# block機能
has_many :blocking_block_relationships, foreign_key: "blocked_id", class_name:"BlockRelationship", dependent: :destroy
has_many :blockings, through: :blocking_block_relationships
has_many :blocked_block_relationships, foreign_key: "blocking_id", class_name:"BlockRelationship", dependent: :destroy
has_many :blockeds, through: :blocked_block_relationships
# 検索機能
def self.search(search)
return User.all unless search
User.where(['name LIKE ?', "%#{search}%"])
end
# follow機能
def following?(other_user)
following_relationships.find_by(following_id: other_user.id)
end
def follow!(other_user)
following_relationships.create!(following_id: other_user.id)
end
def unfollow!(other_user)
following_relationships.find_by(following_id: other_user.id).destroy
end
# block機能
def blocking?(other_user)
blocking_block_relationships.find_by(blocking_id: other_user.id)
end
def block!(other_user)
blocking_block_relationships.create!(blocking_id: other_user.id)
end
def unblock!(other_user)
blocking_block_relationships.find_by(blocking_id: other_user.id).destroy
end
# バリデーション
validates :name, presence: true
end
| 28.402597 | 120 | 0.769547 |
f7b59b96cda2cd163194bc6eeef61f5358dae128 | 851 | Pod::Spec.new do |s|
s.name = 'KeenClient'
s.version = '3.2.1'
s.license = 'MIT'
s.platform = :ios
s.summary = 'Keen iOS client library.'
s.homepage = 'https://github.com/keenlabs/KeenClient-iOS'
s.author = { 'Daniel Kador' => '[email protected]' }
s.source = { :git => 'https://github.com/keenlabs/KeenClient-iOS.git',
:tag => 'v3.2.1' }
s.description = 'The Keen iOS client is designed to be simple to develop with, yet ' \
'incredibly flexible. Our goal is to let you decide what events are ' \
'important to you, use your own vocabulary to describe them, and ' \
'decide when you want to send them to Keen service.'
s.source_files = 'KeenClient'
s.dependency 'JSONKit'
s.dependency 'ISO8601DateFormatter', '>= 0.6'
s.requires_arc = false
end | 38.681818 | 90 | 0.611046 |
bf610bcba1f422b52c078cd80c9e500c6ef5ce59 | 401 | RSpec.describe LastFM::Top::Artists do
subject { described_class }
describe 'successful processing' do
context 'when no primary args' do
let(:output) do
VCR.use_cassette 'services/lastfm/top/artists/success' do
subject.call(limit: 5, page: 2, profile_id: 1)
end
end
it { expect(output).to eq(Helpers::LastFM::Top.artists_data) }
end
end
end
| 25.0625 | 68 | 0.653367 |
18e62f6b2fd9b7fe3b506fbcd9363c1346bba183 | 174 | module QuizzesHelper
def flash_message
if flash[:message]
flash[:message]
end
end
def user_created_quiz?
@quiz.user_id == current_user.id
end
end
| 13.384615 | 36 | 0.678161 |
ed04849092e050bcec0b4f4778f5be9c88080797 | 141 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_many2many_session'
| 35.25 | 79 | 0.808511 |
d582d654d0bc94f8bc87655e6a8f8a5411249e41 | 937 | # Shared specs for testing CORS headers
module Spec
module Support
module SharedExamples
module Requests
module CorsHeadersSpec
def self.included(base)
describe 'CORS headers' do
it 'sets the allowed origins' do
assert_equal 'http://localhost',
last_response.headers.fetch('Access-Control-Allow-Origin')
end
it 'sets the allowed HTTP methods' do
assert_includes %w(GET POST PUT PATCH OPTIONS DELETE).join(','),
last_response.headers.fetch('Access-Control-Allow-Methods')
end
it 'sets the allowed headers' do
assert_includes %w(Content-Type Accept Auth-Token).join(','),
last_response.headers.fetch('Access-Control-Allow-Headers')
end
end
end
end
end
end
end
end
| 28.393939 | 80 | 0.562433 |
e99986e76ee15e207b92eff80baecfcc195d8601 | 247 | class CreateRepositories < ActiveRecord::Migration[4.2]
def change
create_table :repositories do |t|
t.string :uri
t.string :name
t.timestamps null: false
end
add_index :repositories, :name, unique: true
end
end
| 20.583333 | 55 | 0.676113 |
ed1a10759f58e021807947ce8383beb85b6df2d1 | 1,090 | require 'redis/distributed'
class Redis
class DistributedStore < Distributed
@@timeout = 5
attr_reader :ring
def initialize(addresses, options = { })
nodes = addresses.map do |address|
::Redis::Store.new _merge_options(address, options)
end
_extend_namespace options
@ring = Redis::HashRing.new nodes
end
def nodes
ring.nodes
end
def reconnect
nodes.each {|node| node.reconnect }
end
def set(key, value, options = nil)
node_for(key).set(key, value, options)
end
def get(key, options = nil)
node_for(key).get(key, options)
end
def setnx(key, value, options = nil)
node_for(key).setnx(key, value, options)
end
private
def _extend_namespace(options)
@namespace = options[:namespace]
extend ::Redis::Store::Namespace if @namespace
end
def _merge_options(address, options)
address.merge({
:timeout => options[:timeout] || @@timeout,
:namespace => options[:namespace]
})
end
end
end
| 21.372549 | 59 | 0.610092 |
7a48418192fbf11b520013b6c4118213f9cbf839 | 984 | # -*- coding: utf-8 -*-
class User < ActiveRecord::Base
before_destroy :check_all_events_finished
has_many :created_events, class_name: 'Event', foreign_key: :owner_id, dependent: :nullify
has_many :tickets, dependent: :nullify
has_many :participating_events, through: :tickets, source: :event
def self.find_or_create_from_auth_hash(auth_hash)
provider = auth_hash[:provider]
uid = auth_hash[:uid]
nickname = auth_hash[:info][:nickname]
image_url = auth_hash[:info][:image]
User.find_or_create_by(provider: provider, uid: uid) do |user|
user.nickname = nickname
user.image_url = image_url
end
end
private
def check_all_events_finished
now = Time.zone.now
if created_events.where(':now < end_time', now: now).exists?
errors[:base] << '公開中の未終了イベントが存在します。'
end
if participating_events.where(':now < end_time', now: now).exists?
errors[:base] << '未終了の参加イベントが存在します。'
end
errors.blank?
end
end
| 28.114286 | 92 | 0.698171 |
39a10b07fbad3fb05c32b7b4437062ed062c7b56 | 466 | class CreateBookmarkRatingRubrics < ActiveRecord::Migration[4.2]
def self.up
if table_exists?(:bookmark_rating_rubrics) == false
create_table :bookmark_rating_rubrics do |t|
t.column 'display_text', :string, null: false
t.column 'minimum_rating', :integer, null: false
t.column 'maximum_rating', :integer, null: false
t.timestamps
end
end
end
def self.down
drop_table :bookmark_rating_rubrics
end
end
| 27.411765 | 64 | 0.690987 |
611a992d7a975844273ce2d062e6e5f93b7829c5 | 802 | class CreateBlockReportNotFollowingMessageWorker
include Sidekiq::Worker
include ReportErrorHandler
include WorkerErrorHandler
sidekiq_options queue: 'messaging', retry: 0, backtrace: false
def unique_key(user_id, options = {})
user_id
end
def unique_in(*args)
3.seconds
end
# options:
def perform(user_id, options = {})
user = User.find(user_id)
return if user.unauthorized_or_expire_token?
BlockReport.send_start_message(user)
message = BlockReport.not_following_message(user)
event = BlockReport.build_direct_message_event(user.uid, message)
User.egotter.api_client.create_direct_message_event(event: event)
rescue => e
unless ignorable_report_error?(e)
handle_worker_error(e, user_id: user_id, options: options)
end
end
end
| 26.733333 | 69 | 0.75187 |
9186c64e220d07e30c32f02d7c4d56ee11851352 | 89 | class Users::UnlocksController < Devise::UnlocksController
layout 'authentication'
end
| 22.25 | 58 | 0.820225 |
d5647626cd91eba1dc78f89ba3c2b6dc57702380 | 986 | 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 Mario
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.8125 | 82 | 0.778905 |
4a5f1aae1683dd3823e4b707b68d0e067671b4df | 8,237 | =begin
#Selling Partner APIs for Fulfillment Outbound
#The Selling Partner API for Fulfillment Outbound lets you create applications that help a seller fulfill Multi-Channel Fulfillment orders using their inventory in Amazon's fulfillment network. You can get information on both potential and existing fulfillment orders.
OpenAPI spec version: 2020-07-01
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.26
=end
require 'date'
module AmzSpApi::FulfillmentOutboundApiModel
# Information for tracking package deliveries.
class TrackingEvent
attr_accessor :event_date
attr_accessor :event_address
attr_accessor :event_code
# A description for the corresponding event code.
attr_accessor :event_description
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'event_date' => :'eventDate',
:'event_address' => :'eventAddress',
:'event_code' => :'eventCode',
:'event_description' => :'eventDescription'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'event_date' => :'Object',
:'event_address' => :'Object',
:'event_code' => :'Object',
:'event_description' => :'Object'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `AmzSpApi::FulfillmentOutboundApiModel::TrackingEvent` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `AmzSpApi::FulfillmentOutboundApiModel::TrackingEvent`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'event_date')
self.event_date = attributes[:'event_date']
end
if attributes.key?(:'event_address')
self.event_address = attributes[:'event_address']
end
if attributes.key?(:'event_code')
self.event_code = attributes[:'event_code']
end
if attributes.key?(:'event_description')
self.event_description = attributes[:'event_description']
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 @event_date.nil?
invalid_properties.push('invalid value for "event_date", event_date cannot be nil.')
end
if @event_address.nil?
invalid_properties.push('invalid value for "event_address", event_address cannot be nil.')
end
if @event_code.nil?
invalid_properties.push('invalid value for "event_code", event_code cannot be nil.')
end
if @event_description.nil?
invalid_properties.push('invalid value for "event_description", event_description cannot be nil.')
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?
return false if @event_date.nil?
return false if @event_address.nil?
return false if @event_code.nil?
return false if @event_description.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
event_date == o.event_date &&
event_address == o.event_address &&
event_code == o.event_code &&
event_description == o.event_description
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[event_date, event_address, event_code, event_description].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
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.openapi_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]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
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
AmzSpApi::FulfillmentOutboundApiModel.const_get(type).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)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
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.175781 | 268 | 0.64186 |
f84f48b2ff65dfbf63f40261e1565cf977a3e440 | 85 | Rails.application.routes.draw do
mount Alchemy::JsonApi::Engine => "/jsonapi/"
end
| 21.25 | 47 | 0.741176 |
f83e89a47c6bdc49c361c6e3d6cd5238df81a30a | 50,426 | module ApplicationHelper
include_concern 'ViewsShared'
include_concern 'Flash'
include_concern 'Listnav'
include_concern 'Navbar'
include_concern 'PageLayouts'
include_concern 'Tasks'
include Sandbox
include JsHelper
include StiRoutingHelper
include ToolbarHelper
include TextualSummaryHelper
include PlanningHelper
include NumberHelper
include PlanningHelper
include Title
include ReactjsHelper
include Webpack
VALID_PERF_PARENTS = {
"EmsCluster" => :ems_cluster,
"Host" => :host
}.freeze
# Need to generate paths w/o hostname by default to make proxying work.
#
def url_for_only_path(args)
url_for(:only_path => true, **args)
end
def settings(*path)
@settings ||= {}
@settings.fetch_path(*path)
end
def settings_default(default, *path)
settings(*path) || default
end
def documentation_link(url = nil, documentation_subject = "")
if url
link_to(_("For more information, visit the %{subject} documentation.") % {:subject => documentation_subject},
url, :rel => 'external',
:class => 'documentation-link', :target => '_blank')
end
end
def websocket_origin
proto = request.ssl? ? 'wss' : 'ws'
# Retrieve the host that needs to be explicitly allowed for websocket connections
host = if request.env['HTTP_X_FORWARDED_HOST']
# Use the first proxy (production)
request.env['HTTP_X_FORWARDED_HOST'].split(/,\s*/).first
else
# Use the HOST header (development)
request.env['HTTP_HOST']
end
"#{proto}://#{host}"
end
# Create a hidden div area based on a condition (using for hiding nav panes)
def hidden_div_if(condition, options = {}, &block)
hidden_tag_if(:div, condition, options, &block)
end
# Create a hidden span tag based on a condition (using for hiding nav panes)
def hidden_span_if(condition, options = {}, &block)
hidden_tag_if(:span, condition, options, &block)
end
def hidden_tag_if(tag, condition, options = {}, &block)
options[:style] = "display: none" if condition
if block_given?
content_tag(tag, options, &block)
else
# TODO: Remove this old open-tag-only way in favor of block style
tag(tag, options, true)
end
end
def hover_class(item)
if item.fetch_path(:link) ||
item.fetch_path(:value).kind_of?(Array) &&
item[:value].any? { |val| val[:link] }
''
else
'no-hover'
end
end
# Check role based authorization for a UI task
def role_allows?(**options)
if options[:feature].nil?
$log.debug("Auth failed - no feature was specified (required)")
return false
end
Rbac.role_allows?(options.merge(:user => User.current_user)) rescue false
end
module_function :role_allows?
public :role_allows?
alias_method :role_allows, :role_allows?
Vmdb::Deprecation.deprecate_methods(self, :role_allows => :role_allows?)
# NB: This differs from controller_for_model; until they're unified,
# make sure you have the right one.
def model_to_controller(record)
record.class.base_model.name.underscore
end
def type_has_quadicon(type)
!%w(
ConfigurationProfile
Account
GuestApplication
SystemService
Filesystem
ChargebackRate
ServiceTemplateProvisionRequest
MiqProvisionRequest
MiqProvisionRequestTemplate
MiqWebServiceWorker
CustomizationTemplateSysprep
CustomizationTemplateCloudInit
CustomizationTemplateKickstart
PxeImageType
IsoDatastore
MiqTask
MiqRequest
PxeServer
).include?(type)
end
CONTROLLER_TO_MODEL = {
"ManageIQ::Providers::CloudManager::Template" => VmOrTemplate,
"ManageIQ::Providers::CloudManager::Vm" => VmOrTemplate,
"ManageIQ::Providers::InfraManager::Template" => VmOrTemplate,
"ManageIQ::Providers::InfraManager::Vm" => VmOrTemplate,
"ManageIQ::Providers::AutomationManager" => ConfigurationScript
}.freeze
def controller_to_model
model = self.class.model
CONTROLLER_TO_MODEL[model.to_s] || model
end
MODEL_STRING = {
"all_vms" => VmOrTemplate,
"all_miq_templates" => MiqTemplate,
"based_volumes" => CloudVolume,
"instances" => Vm,
"images" => MiqTemplate,
"groups" => Account,
"users" => Account,
"host_services" => SystemService,
"chargebacks" => ChargebackRate,
"playbooks" => ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook,
"physical_servers_with_host" => PhysicalServer,
"manageiq/providers/automation_managers" => ConfigurationScript,
"vms" => VmOrTemplate,
"ServiceCatalog" => ServiceTemplate
}.freeze
HAS_ASSOCATION = {
"groups" => "groups",
"users" => "users",
"event_logs" => "event_logs",
"OsProcess" => "processes",
"scan_histories" => "scan_histories",
"based_volumes" => "based_volumes",
"PersistentVolume" => "persistent_volumes",
"PhysicalSwitch" => "physical_switches"
}.freeze
def model_to_report_data
# @report_data_additional_options[:model] is most important, others can be removed
return @report_data_additional_options[:model] if @report_data_additional_options && @report_data_additional_options[:model]
return @display.classify if @display && @display != "main"
return params[:db].classify if params[:db]
return params[:display].classify if params[:display]
controller.class.model.to_s if defined? controller.class.model
end
def model_string_to_constant(model_string)
MODEL_STRING[model_string] || model_string.singularize.classify.constantize
end
def restful_routed?(record_or_model)
model = if record_or_model.kind_of?(Class)
record_or_model
else
record_or_model.class
end
model = ui_base_model(model)
respond_to?("#{model.model_name.route_key}_path")
end
def restful_routed_action?(controller = controller_name, action = action_name)
restful_routed?("#{controller.camelize}Controller".constantize.model) && !%w(explorer show_list).include?(action)
rescue
false
end
# Returns whether records support feature or not.
#
# Params:
# records - an array of record instances or a single instance of a record
# feature - symbol, a feature from SupportsFeatureMixin::QUERYABLE_FEATURES
# Returns:
# boolean - true if all records support the feature
# - false in case the record (or one of many records) does not
# support the feature
def records_support_feature?(records, feature)
unsupported_record = Array.wrap(records).find do |record|
if record.respond_to?("supports_#{feature}?")
!record.supports?(feature)
else # TODO: remove with deleting AvailabilityMixin module
!record.is_available?(feature)
end
end
unsupported_record.nil?
end
# Default action is show
def url_for_record(record, action = "show")
@id = record.id
db = if controller.kind_of?(VmOrTemplateController)
"vm_or_template"
elsif record.kind_of?(VmOrTemplate)
controller_for_vm(model_for_vm(record))
elsif record.kind_of?(ManageIQ::Providers::AnsibleTower::AutomationManager) ||
record.kind_of?(ManageIQ::Providers::ExternalAutomationManager::InventoryRootGroup)
"automation_manager"
elsif record.kind_of?(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook)
"ansible_playbook"
elsif record.kind_of?(ManageIQ::Providers::EmbeddedAutomationManager::Authentication)
"ansible_credential"
elsif record.kind_of?(ManageIQ::Providers::EmbeddedAutomationManager::ConfigurationScriptSource)
"ansible_repository"
elsif record.kind_of?(ManageIQ::Providers::Foreman::ConfigurationManager)
"provider_foreman"
elsif record.class.respond_to?(:db_name)
record.class.db_name
else
record.class.base_class.to_s
end
url_for_db(db, action, record)
end
# Create a url for a record that links to the proper controller
def url_for_db(db, action = "show", item = nil)
if item && restful_routed?(item)
return polymorphic_path(item)
end
if @vm && %w(Account User Group Patch GuestApplication).include?(db)
return url_for_only_path(:controller => "vm_or_template",
:action => @lastaction,
:id => @vm,
:show => @id)
elsif @host && %w(Patch GuestApplication).include?(db)
return url_for_only_path(:controller => "host", :action => @lastaction, :id => @host, :show => @id)
elsif %w(ConfiguredSystem ConfigurationProfile).include?(db)
return url_for_only_path(:controller => "provider_foreman", :action => @lastaction, :id => @record, :show => @id)
else
controller, action = db_to_controller(db, action)
return url_for_only_path(:controller => controller, :action => action, :id => @id)
end
end
TREE_WITH_TAB = {
"diagnostics_server_list" => "svr",
"db_details" => "tb",
"report_info" => "msc"
}.freeze
# Create a url to show a record from the passed in view
def view_to_url(view, parent = nil)
association = view_to_association(view, parent)
if association.nil?
controller, action = db_to_controller(view.db)
if controller == "ems_cloud" && action == "show"
return ems_clouds_path
end
if controller == "ems_infra" && action == "show"
return ems_infras_path
end
if controller == "ems_physical_infra" && action == "show"
return ems_physical_infras_path
end
if controller == "ems_container" && action == "show"
return ems_containers_path
end
if controller == "ems_middleware" && action == "show"
return ems_middlewares_path
end
if controller == "ems_network" && action == "show"
return ems_networks_path
end
if request[:controller] == 'service' && view.db == 'GenericObject'
action = 'show'
return url_for_only_path(:action => action, :id => params[:id]) + "?display=generic_objects&generic_object_id="
end
# If we do not want to use redirect or any kind of click action
if %w(Job VmdbDatabaseSetting VmdbDatabaseConnection VmdbIndex).include?(view.db) &&
%w(ops).include?(params[:controller])
return false
end
if %w(MiqTask).include?(view.db) && %w(miq_task).include?(params[:controller])
return true
end
if @explorer
# showing a list view of another CI inside vmx
if %w(SecurityGroup
FloatingIp
NetworkRouter
NetworkPort
CloudNetwork
CloudSubnet
LoadBalancer
CloudVolume).include?(view.db)
return url_for_only_path(:controller => controller, :action => "show") + "/"
elsif ["Vm"].include?(view.db) && parent && request.parameters[:controller] != "vm"
# this is to handle link to a vm in vm explorer from service explorer
return url_for_only_path(:controller => "vm_or_template", :action => "show") + "/"
elsif %w(ConfigurationProfile).include?(view.db) &&
request.parameters[:controller] == "provider_foreman"
return url_for_only_path(:action => action, :id => nil) + "/"
elsif %w(ManageIQ::Providers::AutomationManager::InventoryRootGroup EmsFolder).include?(view.db) &&
request.parameters[:controller] == "automation_manager"
return url_for_only_path(:action => action, :id => nil) + "/"
elsif %w(ConfiguredSystem).include?(view.db) && (request.parameters[:controller] == "provider_foreman" || request.parameters[:controller] == "automation_manager")
return url_for_only_path(:action => action, :id => nil) + "/"
elsif %w(MiqWidget
ConfigurationScript
MiqReportResult).include?(view.db) &&
%w(report automation_manager).include?(request.parameters[:controller])
suffix = ''
if params[:tab_id] == "saved_reports" || params[:pressed] == "miq_report_run" || params[:action] == "reload"
suffix = x_node
end
return "/" + request.parameters[:controller] + "/tree_select?id=" + suffix
elsif %w(User MiqGroup MiqUserRole Tenant).include?(view.db) &&
%w(ops).include?(request.parameters[:controller])
if @tagging
return false # when tagging Users, Groups, Roles and Tenants, the table is non-clickable
else
return "/" + request.parameters[:controller] + "/tree_select/?id=" + x_node.split("-")[1]
end
elsif %w(VmdbTableEvm MiqServer).include?(view.db) &&
%w(ops report).include?(request.parameters[:controller])
return "/" + request.parameters[:controller] + "/tree_select/?id=" + TREE_WITH_TAB[active_tab]
elsif %w(MiqAction
MiqAlert
ScanItemSet
MiqSchedule
PxeServer
PxeImageType
IsoDatastore
CustomizationTemplate).include?(view.db) &&
%w(miq_policy ops pxe report).include?(params[:controller])
return "/#{params[:controller]}/tree_select/?id=#{TreeBuilder.get_prefix_for_model(view.db)}"
elsif %w(MiqPolicy).include?(view.db) && %w(miq_policy).include?(params[:controller])
return "/#{params[:controller]}/tree_select/?id=#{x_node}"
else
return url_for_only_path(:action => action) + "/" # In explorer, don't jump to other controllers
end
else
controller = "vm_cloud" if controller == "template_cloud"
controller = "vm_infra" if controller == "template_infra"
return url_for_only_path(:controller => controller, :action => action, :id => nil) + "/"
end
else
# need to add a check for @explorer while setting controller incase building a link for details screen to show items
# i.e users list view screen inside explorer needs to point to vm_or_template controller
return url_for_only_path(:controller => parent.kind_of?(VmOrTemplate) && !@explorer ? parent.class.base_model.to_s.underscore : request.parameters["controller"],
:action => association,
:id => parent.id) + "?#{@explorer ? "x_show" : "show"}="
end
end
def view_to_association(view, parent)
case view.db
when "OrchestrationStackOutput" then "outputs"
when "OrchestrationStackParameter" then "parameters"
when "OrchestrationStackResource" then "resources"
when 'AdvancedSetting', 'Filesystem', 'FirewallRule', 'GuestApplication', 'Patch',
'RegistryItem', 'ScanHistory', 'OpenscapRuleResult'
then view.db.tableize
when "SystemService"
case parent.class.base_class.to_s.downcase
when "host" then "host_services"
when "vm" then @lastaction
end
when "CloudService" then "host_cloud_services"
else view.scoped_association
end
end
# Convert a db name to a controller name and an action
def db_to_controller(db, action = "show")
action = "x_show" if @explorer
case db
when "ActionSet"
controller = "miq_action"
action = "show_set"
when "AutomationRequest"
controller = "miq_request"
action = "show"
when "ConditionSet"
controller = "condition"
when "ManageIQ::Providers::EmbeddedAutomationManager::ConfigurationScriptSource"
controller = "ansible_repository"
when "ScanItemSet"
controller = "ops"
action = "ap_show"
when "MiqEventDefinition"
controller = "event"
action = "_none_"
when "User", "Group", "Patch", "GuestApplication"
controller = "vm"
action = @lastaction
when "Host" && action == 'x_show'
controller = "infra_networking"
action = @lastaction
when "MiqReportResult"
controller = "report"
action = "show_saved"
when "MiqSchedule"
if request.parameters["controller"] == "report"
controller = "report"
action = "show_schedule"
else
controller = "ops"
action = "schedule_show"
end
when "MiqAeClass"
controller = "miq_ae_class"
action = "show_instances"
when "MiqAeInstance"
controller = "miq_ae_class"
action = "show_details"
when "SecurityGroup"
controller = "security_group"
action = "show"
when "ServiceResource", "ServiceTemplate"
controller = "catalog"
when "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook"
controller = "ansible_playbook"
when "ManageIQ::Providers::EmbeddedAutomationManager::Authentication"
controller = "ansible_credential"
when "MiqWorker"
controller = request.parameters[:controller]
when "OrchestrationStackOutput", "OrchestrationStackParameter", "OrchestrationStackResource",
"ManageIQ::Providers::CloudManager::OrchestrationStack",
"ManageIQ::Providers::AnsibleTower::AutomationManager::Job", "ConfigurationScript"
controller = request.parameters[:controller]
when "ContainerVolume"
controller = "persistent_volume"
when /^ManageIQ::Providers::(\w+)Manager$/
controller = "ems_#{$1.underscore}"
when /^ManageIQ::Providers::(\w+)Manager::(\w+)$/
controller = "#{$2.underscore}_#{$1.underscore}"
when "EmsAutomation"
controller = "automation_manager"
when "GenericObject" && request.parameters[:controller] == 'service'
controller = request.parameters[:controller]
action = 'generic_object'
else
controller = db.underscore
end
return controller, action
end
# Method to create the center toolbar XML
def build_toolbar(tb_name)
_toolbar_builder.call(tb_name)
end
def _toolbar_builder
ToolbarBuilder.new(
self,
binding,
:active => @active,
:changed => @changed,
:condition => @condition,
:condition_policy => @condition_policy,
:dashboard => @dashboard,
:display => @display,
:edit => @edit,
:explorer => @explorer,
:ght_type => @ght_type,
:gtl_buttons => @gtl_buttons,
:gtl_type => @gtl_type,
:html => @html,
:lastaction => @lastaction,
:layout => @layout,
:miq_request => @miq_request,
:msg_title => @msg_title,
:perf_options => @perf_options,
:policy => @policy,
:record => @record,
:report => @report,
:report_result_id => @report_result_id,
:request_tab => @request_tab,
:resolve => @resolve,
:sb => @sb,
:selected_zone => @selected_zone,
:settings => @settings,
:showtype => @showtype,
:tabform => @tabform,
:widget_running => @widget_running,
:widgetsets => @widgetsets,
:render_chart => @render_chart,
)
end
# Convert a field (Vm.hardware.disks-size) to a col (disks.size)
def field_to_col(field)
dbs, fld = field.split("-")
(dbs.include?(".") ? "#{dbs.split(".").last}.#{fld}" : fld)
end
def controller_model_name(controller)
ui_lookup(:model => (controller.camelize + "Controller").constantize.model.name)
end
def is_browser_ie?
browser_info(:name) == "explorer"
end
def is_browser_ie7?
is_browser_ie? && browser_info(:version).starts_with?("7")
end
def is_browser?(name)
browser_name = browser_info(:name)
name.kind_of?(Array) ? name.include?(browser_name) : (browser_name == name)
end
def is_browser_os?(os)
browser_os = browser_info(:os)
os.kind_of?(Array) ? os.include?(browser_os) : (browser_os == os)
end
def browser_info(typ)
session.fetch_path(:browser, typ).to_s
end
############# Following methods generate JS lines for render page blocks
def javascript_for_timer_type(timer_type)
case timer_type
when "Monthly"
[
javascript_hide("weekly_span"),
javascript_hide("daily_span"),
javascript_hide("hourly_span"),
javascript_show("monthly_span")
]
when "Weekly"
[
javascript_hide("daily_span"),
javascript_hide("hourly_span"),
javascript_hide("monthly_span"),
javascript_show("weekly_span")
]
when "Daily"
[
javascript_hide("hourly_span"),
javascript_hide("monthly_span"),
javascript_hide("weekly_span"),
javascript_show("daily_span")
]
when "Hourly"
[
javascript_hide("daily_span"),
javascript_hide("monthly_span"),
javascript_hide("weekly_span"),
javascript_show("hourly_span")
]
when nil
[]
else
[
javascript_hide("daily_span"),
javascript_hide("hourly_span"),
javascript_hide("monthly_span"),
javascript_hide("weekly_span")
]
end
end
# Show/hide the Save and Reset buttons based on whether changes have been made
def javascript_for_miq_button_visibility(display, prefix = nil)
if prefix
"miqButtons('#{display ? 'show' : 'hide'}', '#{prefix}');".html_safe
else
"miqButtons('#{display ? 'show' : 'hide'}');".html_safe
end
end
def javascript_for_miq_button_visibility_changed(changed)
return "" if changed == session[:changed]
session[:changed] = changed
javascript_for_miq_button_visibility(changed)
end
# reload all toolbars
def javascript_reload_toolbars
"sendDataWithRx({redrawToolbar: #{toolbar_from_hash.to_json}});"
end
def set_edit_timer_from_schedule(schedule)
@edit[:new][:timer] ||= ReportHelper::Timer.new
if schedule.run_at.nil?
t = Time.now.in_time_zone(@edit[:tz]) + 1.day # Default date/time to tomorrow in selected time zone
@edit[:new][:timer].typ = 'Once'
@edit[:new][:timer].start_date = "#{t.month}/#{t.day}/#{t.year}"
else
@edit[:new][:timer].update_from_miq_schedule(schedule.run_at, @edit[:tz])
end
end
# Check if a parent chart has been selected and applies
def perf_parent?
@perf_options[:model] == "VmOrTemplate" &&
@perf_options[:typ] != "realtime" &&
VALID_PERF_PARENTS.keys.include?(@perf_options[:parent])
end
# Determine the type of report (performance/trend/chargeback) based on the model
def model_report_type(model)
if model
if model.ends_with?("Performance", "MetricsRollup")
return :performance
elsif model == ApplicationController::TREND_MODEL
return :trend
elsif model.starts_with?("Chargeback")
return model.downcase.to_sym
end
end
nil
end
def show_taskbar_in_header?
return false if @explorer
return false if controller.action_name.end_with?("tagging_edit")
hide_actions = %w(
auth_error
change_tab
show
)
return false if @layout == "" && hide_actions.include?(controller.action_name)
hide_layouts = %w(
about
chargeback
container_dashboard
ems_infra_dashboard
exception
miq_ae_automate_button
miq_ae_class
miq_ae_export
miq_ae_tools
miq_policy
miq_policy_export
miq_policy_rsop
monitor_alerts_list
monitor_alerts_most_recent
monitor_alerts_overview
ops
pxe
report
server_build
)
return false if hide_layouts.include?(@layout)
return false if @layout == "configuration" && @tabform != "ui_4"
true
end
def taskbar_in_header?
# this is just @show_taskbar ||= show_taskbar_in_header? .. but nil
if @show_taskbar.nil?
@show_taskbar = show_taskbar_in_header?
else
@show_taskbar
end
end
# checking if any of the toolbar is visible
def toolbars_visible?
(@toolbars['history_tb'] || @toolbars['center_tb'] || @toolbars['view_tb']) &&
(@toolbars['history_tb'] != 'blank_view_tb' && @toolbars['history_tb'] != 'blank_view_tb' && @toolbars['view_tb'] != 'blank_view_tb')
end
# Format a column in a report view for display on the screen
def format_col_for_display(view, row, col, tz = nil)
tz ||= ["miqschedule"].include?(view.db.downcase) ? MiqServer.my_server.server_timezone : Time.zone
celltext = view.format(col,
row[col],
:tz => tz).gsub(/\\/, '\&') # Call format, then escape any backslashes
celltext
end
def check_if_button_is_implemented
if !@flash_array && !@refresh_partial # if no button handler ran, show not implemented msg
add_flash(_("Button not yet implemented"), :error)
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
elsif @flash_array && @lastaction == "show"
@ems = @record = identify_record(params[:id])
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
end
end
# Return a blank tb if a placeholder is needed for AJAX explorer screens, return nil if no center toolbar to be shown
delegate :center_toolbar_filename, :to => :_toolbar_chooser
delegate :history_toolbar_filename, :to => :_toolbar_chooser
delegate :x_view_toolbar_filename, :to => :_toolbar_chooser
delegate :view_toolbar_filename, :to => :_toolbar_chooser
def _toolbar_chooser
ToolbarChooser.new(
self,
binding,
:alert_profiles => @alert_profiles,
:conditions => @conditions,
:dialog => @dialog,
:display => @display,
:explorer => @explorer,
:in_a_form => @in_a_form,
:lastaction => @lastaction,
:layout => @layout,
:nodetype => @nodetype,
:policies => @policies,
:record => @record,
:report => @report,
:sb => @sb,
:showtype => @showtype,
:tabform => @tabform,
:view => @view,
:center_toolbar => @center_toolbar
)
end
# Calculate hash of toolbars to render
#
# keys are toolbar <div> names and values are toobar identifiers (now YAML files)
#
def calculate_toolbars
toolbars = {}
if inner_layout_present? # x_taskbar branch
toolbars['history_tb'] = history_toolbar_filename
elsif display_back_button? # taskbar branch
toolbars['summary_center_tb'] = controller.restful? ? "summary_center_restful_tb" : "summary_center_tb"
end
# FIXME: singular vs plural for controller.class.toolbar_singular
toolbars['center_tb'] = if controller.class.toolbar_plural.present? && params[:action] == 'show_list'
"#{controller.class.toolbar_plural}_center_tb"
elsif controller.class.toolbar_singular.present?
"#{controller.class.toolbar_singular}_center_tb"
elsif controller.try(:toolbar)
controller.toolbar.to_s
else
center_toolbar_filename
end
toolbars['custom_tb'] = controller.custom_toolbar
toolbars['view_tb'] = inner_layout_present? ? x_view_toolbar_filename : view_toolbar_filename
toolbars
end
# check if back to summary button needs to be show
def display_back_button?
# don't need to back button if @record is not there or @record doesnt have name or
# evm_display_name column, i.e MiqProvisionRequest
return false if @display == "dashboard"
if (@lastaction != "show" || (@lastaction == "show" && @display != "main")) &&
@record &&
(@record.respond_to?('name') && [email protected]?)
return true
else
return false
end
end
def display_adv_search?
%w(auth_key_pair_cloud
availability_zone
automation_manager
cloud_network
cloud_object_store_container
cloud_object_store_object
cloud_subnet
cloud_tenant
cloud_volume
cloud_volume_backup
cloud_volume_snapshot
cloud_volume_type
configuration_job
configuration_scripts
container
container_build
container_group
container_image
container_image_registry
container_node
container_project
container_replicator
container_route
container_service
container_template
ems_cloud
ems_cluster
ems_container
ems_infra
ems_middleware
ems_network
ems_physical_infra
ems_storage
flavor
floating_ip
generic_object_definition
host
host_aggregate
load_balancer
middleware_deployment
middleware_domain
middleware_server
miq_template
network_port
network_router
offline
orchestration_stack
persistent_volume
physical_server
provider_foreman
resource_pool
retired
security_group
service
services
storage
templates
vm).include?(@layout)
end
# Do we show or hide the clear_search link in the list view title
def clear_search_status
!!(@edit&.fetch_path(:adv_search_applied, :text))
end
# Should we allow the user input checkbox be shown for an atom in the expression editor
QS_VALID_USER_INPUT_OPERATORS = ["=", "!=", ">", ">=", "<", "<=", "INCLUDES", "STARTS WITH", "ENDS WITH", "CONTAINS"].freeze
QS_VALID_FIELD_TYPES = %i(string boolean integer float percent bytes megabytes).freeze
def qs_show_user_input_checkbox?
return true if @edit[:expression_method]
return false unless @edit[:adv_search_open] # Only allow user input for advanced searches
return false unless QS_VALID_USER_INPUT_OPERATORS.include?(@edit[@expkey][:exp_key])
val = (@edit[@expkey][:exp_typ] == "field" && # Field atoms with certain field types return true
QS_VALID_FIELD_TYPES.include?(@edit[@expkey][:val1][:type])) ||
(@edit[@expkey][:exp_typ] == "tag" && # Tag atoms with a tag category chosen return true
@edit[@expkey][:exp_tag]) ||
(@edit[@expkey][:exp_typ] == "count" && # Count atoms with a count col chosen return true
@edit[@expkey][:exp_count])
val
end
# Should we allow the field alias checkbox to be shown for an atom in the expression editor
def adv_search_show_alias_checkbox?
@edit[:adv_search_open] # Only allow field aliases for advanced searches
end
def pressed2model_action(pressed)
pressed =~ /^(ems_cluster|miq_template|infra_networking|automation_manager_provider|configuration_manager_provider)_(.*)$/ ? [$1, $2] : pressed.split('_', 2)
end
def model_for_ems(record)
raise _("Record is not ExtManagementSystem class") unless record.kind_of?(ExtManagementSystem)
if record.kind_of?(ManageIQ::Providers::CloudManager)
ManageIQ::Providers::CloudManager
elsif record.kind_of?(ManageIQ::Providers::ContainerManager)
ManageIQ::Providers::ContainerManager
else
ManageIQ::Providers::InfraManager
end
end
def model_for_vm(record)
raise _("Record is not VmOrTemplate class") unless record.kind_of?(VmOrTemplate)
if record.kind_of?(ManageIQ::Providers::CloudManager::Vm)
ManageIQ::Providers::CloudManager::Vm
elsif record.kind_of?(ManageIQ::Providers::InfraManager::Vm)
ManageIQ::Providers::InfraManager::Vm
elsif record.kind_of?(ManageIQ::Providers::CloudManager::Template)
ManageIQ::Providers::CloudManager::Template
elsif record.kind_of?(ManageIQ::Providers::InfraManager::Template)
ManageIQ::Providers::InfraManager::Template
end
end
def controller_for_vm(model)
case model.to_s
when "ManageIQ::Providers::CloudManager::Template", "ManageIQ::Providers::CloudManager::Vm"
"vm_cloud"
when "ManageIQ::Providers::InfraManager::Template", "ManageIQ::Providers::InfraManager::Vm"
"vm_infra"
else
"vm_or_template"
end
end
def controller_for_stack(model)
case model.to_s
when "ManageIQ::Providers::AnsibleTower::AutomationManager::Job"
"configuration_job"
else
model.name.underscore
end
end
def model_from_active_tree(tree)
case tree
when :automation_manager_cs_filter_tree
"ManageIQ::Providers::AnsibleTower::AutomationManager::ConfiguredSystem"
when :configuration_manager_cs_filter_tree
"ManageIQ::Providers::Foreman::ConfigurationManager::ConfiguredSystem"
when :configuration_manager_providers_tree
"ManageIQ::Providers::Foreman::ConfigurationManager" if x_node.include?("fr")
"ManageIQ::Providers::ConfigurationManager" if x_node == "root"
when :instances_filter_tree
"ManageIQ::Providers::CloudManager::Vm"
when :images_filter_tree
"ManageIQ::Providers::CloudManager::Template"
when :svcs_tree
"Service"
when :vms_filter_tree
"ManageIQ::Providers::InfraManager::Vm"
when :templates_filter_tree
"ManageIQ::Providers::InfraManager::Template"
when :templates_images_filter_tree
"MiqTemplate"
when :vms_instances_filter_tree
"Vm"
end
end
def configuration_manager_scripts_tree(tree)
case tree
when :automation_manager_cs_filter_tree
"ManageIQ::Providers::AnsibleTower::AutomationManager::ConfiguredSystem"
when :configuration_manager_cs_filter_tree
"ManageIQ::Providers::Foreman::ConfigurationManager::ConfiguredSystem"
when :configuration_scripts_tree
"ConfigurationScript"
end
end
def object_types_for_flash_message(klass, record_ids)
if klass == VmOrTemplate
object_ary = klass.where(:id => record_ids).collect { |rec| ui_lookup(:model => model_for_vm(rec).to_s) }
obj_hash = object_ary.each.with_object(Hash.new(0)) { |obj, h| h[obj] += 1 }
obj_hash.collect { |k, v| v == 1 ? k : k.pluralize }.sort.to_sentence
else
object = ui_lookup(:model => klass.to_s)
record_ids.length == 1 ? object : object.pluralize
end
end
# FIXME: params[:type] is used in multiple contexts, we should rename it to
# :gtl_type or remove it as we move to the Angular GTL component
def pagination_or_gtl_request?
%i(ppsetting searchtag entry sortby sort_choice type page).find { |k| params[k] }
end
def update_gtl_div(action_url = 'explorer', button_div = 'center_tb')
render :update do |page|
page << javascript_prologue
page.replace("gtl_div",
:partial => "layouts/x_gtl",
:locals => {:action_url => action_url, :button_div => button_div})
page << "miqSparkle(false)"
end
end
def perfmenu_click?
return false unless params[:menu_click]
perf_menu_click
true
end
def javascript_process_redirect_args(args)
# there's no model for ResourceController - defaulting to traditional routing
begin
model = self.class.model
rescue StandardError => _err
model = nil
end
if model && args.class == Hash && args[:action] == 'show' && restful_routed?(model)
args.delete(:action)
polymorphic_path_redirect(model, args)
else
args
end
end
def javascript_redirect(args)
render :update do |page|
page << javascript_prologue
page.redirect_to(args)
end
end
def polymorphic_path_redirect(model, args)
record = args[:record] ? args[:record] : model.find(args[:id] || params[:id])
args.delete(:record)
args.delete(:id)
polymorphic_path(record, args)
end
def javascript_open_window(url)
ex = ExplorerPresenter.open_window(url)
ex.spinner_off
render :json => ex.for_render
end
# this keeps the main_div wrapping tag, replaces only the inside
def replace_main_div(args, options = {})
ex = ExplorerPresenter.main_div.update('main_div', render_to_string(args))
ex.replace("flash_msg_div", render_to_string(:partial => "layouts/flash_msg")) if options[:flash]
ex.spinner_off if options[:spinner_off]
render :json => ex.for_render
end
def javascript_miq_button_visibility(changed)
render :json => ExplorerPresenter.buttons(changed).for_render
end
def record_no_longer_exists?(what, model = nil)
return false unless what.nil?
if !@bang || @flash_array.empty?
# We already added a better flash message in 'identify_record'
# in that case we keep that flash message
# otherwise we make a new one.
# FIXME: a refactoring of identify_record and related is needed
add_flash(
if model.present?
_("%{model} no longer exists") % {:model => ui_lookup(:model => model)}
else
_("Error: Record no longer exists in the database")
end,
:error, true
)
session[:flash_msgs] = @flash_array
end
# Error message is displayed in 'show_list' action if such action exists
# otherwise we assume that the 'explorer' action must exist that will display it.
redirect_to(:action => respond_to?(:show_list) ? 'show_list' : 'explorer')
end
def pdf_page_size_style
"#{@options[:page_size].sub(/^US-/i, '') || "legal"} #{@options[:page_layout]}"
end
GTL_VIEW_LAYOUTS = %w(action
auth_key_pair_cloud
availability_zone
alerts_overview
alerts_list
alerts_most_recent
cloud_network
cloud_object_store_container
cloud_object_store_object
cloud_subnet
cloud_tenant
cloud_topology
cloud_volume
cloud_volume_backup
cloud_volume_snapshot
cloud_volume_type
condition
configuration_job
configuration_script_source
container
container_build
container_dashboard
container_group
container_image
container_image_registry
container_node
container_project
container_replicator
container_route
container_service
container_template
container_topology
ems_block_storage
ems_cloud
ems_cluster
ems_container
ems_infra
ems_infra_dashboard
ems_middleware
ems_network
ems_object_storage
ems_physical_infra
ems_storage
infra_topology
event
flavor
floating_ip
generic_object
generic_object_definition
guest_device
host
host_aggregate
load_balancer
manageiq/providers/embedded_ansible/automation_manager/playbook
manageiq/providers/embedded_automation_manager/authentication
manageiq/providers/embedded_automation_manager/configuration_script_source
middleware_deployment
middleware_domain
middleware_server
middleware_server_group
miq_schedule
miq_template
monitor_alerts_overview
monitor_alerts_list
monitor_alerts_most_recent
network_port
network_router
network_topology
offline
orchestration_stack
physical_infra_topology
physical_rack
physical_chassis
physical_switch
physical_storage
physical_server
persistent_volume
policy
policy_group
policy_profile
resource_pool
retired
scan_profile
security_group
services
storage
templates).freeze
def render_gtl_view_tb?
GTL_VIEW_LAYOUTS.include?(@layout) && @gtl_type && !@tagitems &&
!@ownershipitems && !@retireitems && !@politems && !@in_a_form &&
%w(show show_list).include?(params[:action]) && @display != "custom_button_events"
end
def update_paging_url_parms(action_url, parameter_to_update = {}, post = false)
url = update_query_string_params(parameter_to_update)
action, an_id = action_url.split("/", 2)
if !post && controller.restful? && action == 'show'
polymorphic_path(@record, url)
else
url[:action] = action
url[:id] = an_id unless an_id.nil?
url_for_only_path(url)
end
end
def update_query_string_params(update_this_param)
exclude_params = %w(button flash_msg page ppsetting pressed sortby sort_choice type)
query_string = Rack::Utils.parse_query(URI("?#{request.query_string}").query)
updated_query_string = query_string.symbolize_keys
updated_query_string.delete_if { |k, _v| exclude_params.include?(k.to_s) }
updated_query_string.merge!(update_this_param)
end
def placeholder_if_present(password)
password.present? ? "\u25cf" * 8 : ''
end
def title_for_host_record(record)
record.openstack_host? ? _("Node") : _("Host")
end
def title_for_cluster_record(record)
record.openstack_cluster? ? _("Deployment Role") : _("Cluster")
end
def miq_tab_header(id, active = nil, options = {}, &_block)
tag_options = {:class => "#{options[:class]} #{active == id ? 'active' : ''}",
:id => "#{id}_tab"}.merge!(options)
content_tag(:li, tag_options) do
content_tag(:a, :href => "##{id}", 'data-toggle' => 'tab') do
yield
end
end
end
def miq_tab_content(id, active = nil, options = {}, &_block)
lazy = options[:lazy] && active != id
classname = %w(tab-pane)
classname << options[:class] if options[:class]
classname << 'active' if active == id
classname << 'lazy' if lazy
options.delete(:lazy)
options.delete(:class)
content_tag(:div, :id => id, :class => classname.join(' '), **options) do
yield unless lazy
end
end
def tree_with_advanced_search?
%i(automation_manager_providers
automation_manager_cs_filter
configuration_manager_cs_filter
configuration_scripts
configuration_manager_providers
images
images_filter
instances
instances_filter
providers
storage
svcs
templates_filter
templates_images_filter
vandt
vms_filter
vms_instances_filter).include?(x_tree[:type])
end
def fonticon_or_fileicon(item)
return nil unless item
decorated = item.decorate
[
decorated.try(:fonticon),
decorated.try(:secondary_icon),
decorated.try(:fileicon)
]
end
private :fonticon_or_fileicon
CONTENT_TYPE_ID = {
"report" => "r",
"menu" => "m",
"chart" => "c"
}.freeze
LIST_ICON_FOR = %w(
MiqReportResult
MiqSchedule
MiqUserRole
MiqWidget
).freeze
def process_show_list_options(options, curr_model = nil)
@report_data_additional_options = ApplicationController::ReportDataAdditionalOptions.from_options(options)
@report_data_additional_options.with_quadicon_options(
:embedded => @embedded,
:showlinks => @showlinks,
:policy_sim => @policy_sim,
:lastaction => @lastaction,
:in_a_form => @in_a_form,
:display => @display
)
@report_data_additional_options.with_row_button(@row_button) if @row_button
@report_data_additional_options.with_menu_click(params[:menu_click]) if params[:menu_click]
@report_data_additional_options.with_sb_controller(params[:sb_controller]) if params[:sb_controller]
@report_data_additional_options.with_model(curr_model) if curr_model
@report_data_additional_options.with_no_checkboxes(@no_checkboxes || options[:no_checkboxes])
# FIXME: we would like to freeze here, but the @gtl_type is calculated no sooner than in view templates.
# So until that if fixed we cannot freeze.
# @report_data_additional_options.freeze
end
def from_additional_options(additional_options)
if additional_options[:match_via_descendants].present?
additional_options[:match_via_descendants] = additional_options[:match_via_descendants].constantize
end
if additional_options[:parent_id].present? && additional_options[:parent_class_name].present?
parent_id = additional_options[:parent_id]
parent_class = additional_options[:parent_class_name].constantize
additional_options[:parent] = parent_class.find(parent_id) if parent_class < ActiveRecord::Base
end
@row_button = additional_options[:row_button]
@no_checkboxes = additional_options[:no_checkboxes]
additional_options
end
# Restore instance variables necessary for proper rendering of quadicons.
# This is a temporary solution that is ot be replaced by proper
# parametrization of an ancessor class of QuadiconHelper.
def restore_quadicon_options(quadicon_options)
@embedded = quadicon_options[:embedded]
@showlinks = quadicon_options[:showlinks]
@policy_sim = quadicon_options[:policy_sim]
# @explorer
# @view.db
# @parent
@lastaction = quadicon_options[:lastaction]
# we also need to pass the @display because @display passed throught the
# session does not persist the null value
@display = quadicon_options[:display]
# need to pass @in_a_form so get_view does not set advanced search options
# in the forms that render gtl that mess up @edit
@in_a_form = quadicon_options[:in_a_form]
# take GTL type from the component
@gtl_type = quadicon_options[:gtl_type]
end
# Wrapper around jquery-rjs' remote_function which adds an extra .html_safe()
# Remove if merged: https://github.com/amatsuda/jquery-rjs/pull/3
def remote_function(options)
super(options).to_str
end
def appliance_name
MiqServer.my_server.name
end
def vmdb_build_info(key)
case key
when :version then Vmdb::Appliance.VERSION
when :build then Vmdb::Appliance.BUILD
end
end
def plugin_name(engine)
engine.respond_to?(:plugin_name) ? engine.plugin_name : engine.to_s.gsub(/ManageIQ::|::Engine/, '')
end
def vmdb_plugins_sha
Vmdb::Plugins.versions
end
def user_role_name
User.current_user.miq_user_role_name
end
def rbac_common_feature_for_buttons(pressed)
# return feature that should be checked for the button that came in
case pressed
when "rbac_project_add", "rbac_tenant_add"
"rbac_tenant_add"
else
pressed
end
end
def action_url_for_views
if @lastaction == "scan_history"
"scan_history"
elsif %w(all_jobs jobs ui_jobs all_ui_jobs).include?(@lastaction)
"jobs"
else
@lastaction && @lastaction != "get_node_info" ? @lastaction : "show_list"
end
end
def route_exists?(hash)
begin
url_for_only_path(hash)
rescue
return false
end
true
end
def translate_header_text(text)
if text == "Region"
Vmdb::Appliance.PRODUCT_NAME + " " + _(text)
else
_(text)
end
end
def parse_nodetype_and_id(x_node)
x_node.split('_').last.split('-')
end
def r
@r ||= proc { |opts| render_to_string(opts) }
end
# Test if just succesfully deleted an entity that was being displayed
def single_delete_test(any_button = false)
@flash_array.present? && @single_delete &&
(any_button || params[:pressed] == "#{table_name}_delete")
end
# redirect to show_list (after succesfully deleted the entity being displayed)
def single_delete_redirect
javascript_redirect(:action => 'show_list',
:flash_msg => @flash_array[0][:message],
:flash_error => @flash_array[0][:level] == :error)
end
def accessible_select_event_types
ApplicationController::Timelines::SELECT_EVENT_TYPE.map { |key, value| [_(key), value] }
end
def unique_html_id(prefix = 'unknown')
"#{prefix}-#{rand(36**8).to_s(36)}"
end
def miq_favicon_link_tag
Settings.server.custom_favicon ? favicon_link_tag('/upload/custom_favicon.ico') : favicon_link_tag
end
def provider_paused?(record)
provider = if record.kind_of?(ExtManagementSystem)
record
elsif record.respond_to?(:ext_management_system)
record.ext_management_system
elsif record.respond_to?(:manager)
record.manager
end
provider.try(:enabled?) == false
end
end
| 34.872752 | 170 | 0.633979 |
082201cb166cde420b15fe8b4f681d4c190950b7 | 4,245 | if databases.count > 1
puppetdb_query_url = "http://localhost:8080/pdb/query"
test_name "test database fallback" do
step "clear puppetdb databases" do
databases.each do |database|
clear_and_restart_puppetdb(database)
end
end
with_puppet_running_on master, {'master' => { 'autosign' => 'true'}} do
step "Run agents once to activate nodes" do
run_agent_on agents, "--test --server #{master}"
end
end
step "Verify that the number of active nodes is what we expect" do
result = on databases[0], %Q|curl -G #{puppetdb_query_url}/v4/nodes|
parsed_result = JSON.parse(result.stdout)
assert_equal(agents.length, parsed_result.length,
"Expected query to return '#{agents.length}' active nodes; returned '#{parsed_result.length}'")
end
step "shut down database" do
stop_puppetdb(databases[0])
end
step "check that the fallback db is responsive to queries and has no nodes" do
result = on databases[1], %Q|curl -G #{puppetdb_query_url}/v4/nodes|
parsed_result = JSON.parse(result.stdout)
assert_equal(0, parsed_result.length,
"Expected query to return 0 active nodes; returned '#{parsed_result.length}'")
end
with_puppet_running_on master, {'master' => {'autosign' => 'true'}} do
step "attempt to populate database with first host down" do
run_agent_on agents, "--test --server #{master}"
end
end
step "Verify that fallback occurred" do
result = on databases[1], %Q|curl -G #{puppetdb_query_url}/v4/nodes|
parsed_result = JSON.parse(result.stdout)
assert_equal(agents.length, parsed_result.length,
"Expected query to return '#{agents.length}' active nodes; returned '#{parsed_result.length}'")
end
step "clean and restart primary database" do
clear_and_restart_puppetdb(databases[0])
end
with_puppet_running_on master, {'master' => {'autosign' => 'true'}} do
step "run agents to populate db again" do
run_agent_on agents, "--test --server #{master}"
end
end
step "check that the first db is responsive to queries" do
result = on databases[0], %Q|curl -G #{puppetdb_query_url}/v4/nodes|
parsed_result = JSON.parse(result.stdout)
assert_equal(agents.length, parsed_result.length,
"Expected query to return '#{agents.length}' active nodes; returned '#{parsed_result.length}'")
end
step "change config so that we can't connectn to the first database" do
manifest = <<-EOS
include puppetdb::params
ini_setting {'server_urls':
ensure => present,
section => 'main',
path => "${puppetdb::params::puppet_confdir}/puppetdb.conf",
setting => 'server_urls',
value => "https://#{databases[0].node_name}:123456,https://#{databases[1].node_name}:8081",
}
EOS
apply_manifest_on(master, manifest)
end
step "clean and restart primary database" do
databases.each do |db|
clear_and_restart_puppetdb(db)
end
end
with_puppet_running_on master, {'master' => {'autosign' => 'true'}} do
step "run agents to populate db again" do
run_agent_on agents, "--test --server #{master}"
end
end
step "Verify that fallback occurred" do
result = on databases[1], %Q|curl -G #{puppetdb_query_url}/v4/nodes|
parsed_result = JSON.parse(result.stdout)
assert_equal(agents.length, parsed_result.length,
"Expected query to return '#{agents.length}' active nodes; returned '#{parsed_result.length}'")
end
step "revert config" do
manifest = <<-EOS
include puppetdb::params
ini_setting {'server_urls':
ensure => present,
section => 'main',
path => "${puppetdb::params::puppet_confdir}/puppetdb.conf",
setting => 'server_urls',
value => "#{databases.map {|db| "https://#{db.node_name}:8081"}.join(',')}",
}
EOS
apply_manifest_on(master, manifest)
end
end
end
| 35.974576 | 114 | 0.620024 |
1d1a2c55cecb3ad2616d18dbef8df9fe4f83df99 | 954 | # Encoding: utf-8
# frozen_string_literal: true
require 'chefspec'
require 'chefspec/berkshelf'
require 'fauxhai'
ChefSpec::Coverage.start!
require 'chef/application'
# rubocop:disable all
LOGLEVEL = :fatal
SUSE_OPTS = {
:platform => 'suse',
:version => '12.3',
:log_level => LOGLEVEL,
}
REDHAT_OPTS = {
:platform => 'redhat',
:version => '7.4',
:log_level => LOGLEVEL,
:file_cache_path => '/tmp'
}
UBUNTU_OPTS = {
:platform => 'ubuntu',
:version => '16.04',
:log_level => LOGLEVEL,
:file_cache_path => '/tmp'
}
CENTOS_OPTS = {
:platform => 'centos',
:version => '7.4.1708',
:log_level => LOGLEVEL,
:file_cache_path => '/tmp'
}
FEDORA_OPTS = {
:platform => 'fedora',
:version => '27',
:log_level => LOGLEVEL,
:file_cache_path => '/tmp'
}
# rubocop:enable all
shared_context 'rabbitmq-stubs' do
before do
allow_any_instance_of(Chef::Config).to receive(:file_cache_path)
.and_return('/tmp')
end
end
| 18.705882 | 68 | 0.649895 |
1a46be4714ec1d9426c7ed79a19fe8f43bcdf267 | 188 | require 'togostanza'
require_relative '../stanza'
FaStanza::Stanza.root = File.expand_path('../..', __FILE__)
TogoStanza.sprockets.append_path File.expand_path('../../assets', __FILE__)
| 26.857143 | 75 | 0.739362 |
1d494829c982248768664039a2a3a42fbaaca147 | 7,396 | =begin
Copyright (c) 2019 Aspose Pty Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=end
require 'date'
module AsposeSlidesCloud
# Represents chart axes
class Axes
# Gets or sets the horizontal axis.
attr_accessor :horizontal_axis
# Gets or sets the vertical axis.
attr_accessor :vertical_axis
# Gets or sets the secondary horizontal axis.
attr_accessor :secondary_horizontal_axis
# Gets or sets the secondary vertical axis.
attr_accessor :secondary_vertical_axis
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'horizontal_axis' => :'HorizontalAxis',
:'vertical_axis' => :'VerticalAxis',
:'secondary_horizontal_axis' => :'SecondaryHorizontalAxis',
:'secondary_vertical_axis' => :'SecondaryVerticalAxis'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'horizontal_axis' => :'Axis',
:'vertical_axis' => :'Axis',
:'secondary_horizontal_axis' => :'Axis',
:'secondary_vertical_axis' => :'Axis'
}
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?(:'HorizontalAxis')
self.horizontal_axis = attributes[:'HorizontalAxis']
end
if attributes.has_key?(:'VerticalAxis')
self.vertical_axis = attributes[:'VerticalAxis']
end
if attributes.has_key?(:'SecondaryHorizontalAxis')
self.secondary_horizontal_axis = attributes[:'SecondaryHorizontalAxis']
end
if attributes.has_key?(:'SecondaryVerticalAxis')
self.secondary_vertical_axis = attributes[:'SecondaryVerticalAxis']
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
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?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
horizontal_axis == o.horizontal_axis &&
vertical_axis == o.vertical_axis &&
secondary_horizontal_axis == o.secondary_horizontal_axis &&
secondary_vertical_axis == o.secondary_vertical_axis
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
[horizontal_axis, vertical_axis, secondary_horizontal_axis, secondary_vertical_axis].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = AsposeSlidesCloud.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.725664 | 107 | 0.657112 |
3992419a274e6c97bd2e6bb31e0dce782ec4f058 | 266 | class FetchSourceCitation < ApplicationJob
def perform(source)
if source.source_type == 'PubMed'
Scrapers::PubMed.populate_source_fields(source)
elsif source.source_type == 'ASCO'
Scrapers::Asco.populate_source_fields(source)
end
end
end
| 26.6 | 53 | 0.736842 |
1a7beb513feeb33b2c5161c1fd4bab792856771a | 361 | require "bundler/setup"
require "grate"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.066667 | 66 | 0.750693 |
1c83a643c83ebfcba94ae8dc957b1d8107f04f7f | 352 | class ActsAsSolr::ParserInstance
include ActsAsSolr::ParserMethods
include ActsAsSolr::CommonMethods
attr_accessor :configuration, :solr_configuration
def table_name
"documents"
end
def primary_key
"id"
end
def find(*args)
[]
end
public :parse_results, :reorder, :parse_query, :add_scores, :replace_types
end | 18.526316 | 76 | 0.721591 |
87bde509a5f1b0eb6449541eae8757c060d83ca2 | 7,403 | #
# Author:: Adam Jacob (<[email protected]>)
# Author:: Nuo Yan (<[email protected]>)
# Author:: Christopher Brown (<[email protected]>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'forwardable'
require 'chef/config'
require 'chef/mixin/params_validate'
require 'chef/mixin/from_file'
require 'chef/couchdb'
require 'chef/index_queue'
require 'chef/data_bag'
require 'chef/mash'
require 'chef/json_compat'
class Chef
class DataBagItem
extend Forwardable
include Chef::Mixin::FromFile
include Chef::Mixin::ParamsValidate
include Chef::IndexQueue::Indexable
VALID_ID = /^[\-[:alnum:]_]+$/
DESIGN_DOCUMENT = {
"version" => 1,
"language" => "javascript",
"views" => {
"all" => {
"map" => <<-EOJS
function(doc) {
if (doc.chef_type == "data_bag_item") {
emit(doc.name, doc);
}
}
EOJS
},
"all_id" => {
"map" => <<-EOJS
function(doc) {
if (doc.chef_type == "data_bag_item") {
emit(doc.name, doc.name);
}
}
EOJS
}
}
}
def self.validate_id!(id_str)
if id_str.nil? || ( id_str !~ VALID_ID )
raise Exceptions::InvalidDataBagItemID, "Data Bag items must have an id matching #{VALID_ID.inspect}, you gave: #{id_str.inspect}"
end
end
# Define all Hash's instance methods as delegating to @raw_data
def_delegators(:@raw_data, *(Hash.instance_methods - Object.instance_methods))
attr_accessor :couchdb_rev, :couchdb_id, :couchdb
attr_reader :raw_data
# Create a new Chef::DataBagItem
def initialize(couchdb=nil)
@couchdb_rev = nil
@couchdb_id = nil
@data_bag = nil
@raw_data = Mash.new
@couchdb = couchdb || Chef::CouchDB.new
end
def chef_server_rest
Chef::REST.new(Chef::Config[:chef_server_url])
end
def self.chef_server_rest
Chef::REST.new(Chef::Config[:chef_server_url])
end
def raw_data
@raw_data
end
def validate_id!(id_str)
self.class.validate_id!(id_str)
end
def raw_data=(new_data)
unless new_data.respond_to?(:[]) && new_data.respond_to?(:keys)
raise Exceptions::ValidationFailed, "Data Bag Items must contain a Hash or Mash!"
end
validate_id!(new_data["id"])
@raw_data = new_data
end
def data_bag(arg=nil)
set_or_return(
:data_bag,
arg,
:regex => /^[\-[:alnum:]_]+$/
)
end
def name
object_name
end
def object_name
raise Exceptions::ValidationFailed, "You must have an 'id' or :id key in the raw data" unless raw_data.has_key?('id')
raise Exceptions::ValidationFailed, "You must have declared what bag this item belongs to!" unless data_bag
id = raw_data['id']
"data_bag_item_#{data_bag}_#{id}"
end
def self.object_name(data_bag_name, id)
"data_bag_item_#{data_bag_name}_#{id}"
end
def to_hash
result = self.raw_data
result["chef_type"] = "data_bag_item"
result["data_bag"] = self.data_bag
result["_rev"] = @couchdb_rev if @couchdb_rev
result
end
# Serialize this object as a hash
def to_json(*a)
result = {
"name" => self.object_name,
"json_class" => self.class.name,
"chef_type" => "data_bag_item",
"data_bag" => self.data_bag,
"raw_data" => self.raw_data
}
result["_rev"] = @couchdb_rev if @couchdb_rev
result.to_json(*a)
end
def self.from_hash(h)
item = new
item.raw_data = h
item
end
# Create a Chef::DataBagItem from JSON
def self.json_create(o)
bag_item = new
bag_item.data_bag(o["data_bag"])
o.delete("data_bag")
o.delete("chef_type")
o.delete("json_class")
o.delete("name")
if o.has_key?("_rev")
bag_item.couchdb_rev = o["_rev"]
o.delete("_rev")
end
if o.has_key?("_id")
bag_item.couchdb_id = o["_id"]
bag_item.index_id = bag_item.couchdb_id
o.delete("_id")
end
bag_item.raw_data = Mash.new(o["raw_data"])
bag_item
end
# Load a Data Bag Item by name from CouchDB
def self.cdb_load(data_bag, name, couchdb=nil)
(couchdb || Chef::CouchDB.new).load("data_bag_item", object_name(data_bag, name))
end
# Load a Data Bag Item by name via either the RESTful API or local data_bag_path if run in solo mode
def self.load(data_bag, name)
if Chef::Config[:solo]
bag = Chef::DataBag.load(data_bag)
item = bag[name]
else
item = Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data/#{data_bag}/#{name}")
end
if item.kind_of?(DataBagItem)
item
else
item = from_hash(item)
item.data_bag(data_bag)
item
end
end
# Remove this Data Bag Item from CouchDB
def cdb_destroy
Chef::Log.debug "Destroying data bag item: #{self.inspect}"
@couchdb.delete("data_bag_item", object_name, @couchdb_rev)
end
def destroy(data_bag=data_bag, databag_item=name)
chef_server_rest.delete_rest("data/#{data_bag}/#{databag_item}")
end
# Save this Data Bag Item to CouchDB
def cdb_save
@couchdb_rev = @couchdb.store("data_bag_item", object_name, self)["rev"]
end
# Save this Data Bag Item via RESTful API
def save(item_id=@raw_data['id'])
r = chef_server_rest
begin
if Chef::Config[:why_run]
Chef::Log.warn("In whyrun mode, so NOT performing data bag item save.")
else
r.put_rest("data/#{data_bag}/#{item_id}", self)
end
rescue Net::HTTPServerException => e
raise e unless e.response.code == "404"
r.post_rest("data/#{data_bag}", self)
end
self
end
# Create this Data Bag Item via RESTful API
def create
chef_server_rest.post_rest("data/#{data_bag}", self)
self
end
# Set up our CouchDB design document
def self.create_design_document(couchdb=nil)
(couchdb || Chef::CouchDB.new).create_design_document("data_bag_items", DESIGN_DOCUMENT)
end
def ==(other)
other.respond_to?(:to_hash) &&
other.respond_to?(:data_bag) &&
(other.to_hash == to_hash) &&
(other.data_bag.to_s == data_bag.to_s)
end
# As a string
def to_s
"data_bag_item[#{id}]"
end
def inspect
"data_bag_item[#{data_bag.inspect}, #{raw_data['id'].inspect}, #{raw_data.inspect}]"
end
def pretty_print(pretty_printer)
pretty_printer.pp({"data_bag_item('#{data_bag}', '#{id}')" => self.to_hash})
end
def id
@raw_data['id']
end
end
end
| 26.629496 | 138 | 0.617452 |
87a813af3dbba8436ba448b58a2bb3325a18c957 | 1,249 | # frozen_string_literal: true
require 'prime' # Ruby Prime
module PrimeMultiplier
# class that generates the first `count` prime numbers
class Prime
class << self
def generate(count)
return [] if count < 1
# this is used to obtain the last prime number so we can set it as
# the max ceiling value when calculating the primes until that number
# If this can't be used we could set an arbitrary high value to run
# or add a breakpoint if we have enough values
prime = ::Prime.first(count).last
@primes = primes_until(prime)
@primes.take(count)
end
# The algorithm used to calculate the prime numbers is
# based on the pseudocode present on the wikipedia page
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants
def primes_until(number)
numbers = (0..number).to_a
# both 0 and 1 are not prime numbers
numbers[0] = numbers[1] = nil
max_val = Math.sqrt(number)
(2..max_val).each do |i|
next if numbers[i].nil?
(i**2..number).step(i).each do |j|
numbers[j] = nil
end
end
numbers.compact
end
end
end
end
| 27.755556 | 82 | 0.619696 |
4a69252dec27acf11dc1c1edd00c3b350e6995f5 | 1,650 | # -*- encoding: utf-8 -*-
# stub: unf 0.1.4 ruby lib
Gem::Specification.new do |s|
s.name = "unf".freeze
s.version = "0.1.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Akinori MUSHA".freeze]
s.date = "2014-04-04"
s.description = "This is a wrapper library to bring Unicode Normalization Form support\nto Ruby/JRuby.\n".freeze
s.email = ["[email protected]".freeze]
s.extra_rdoc_files = ["README.md".freeze, "LICENSE".freeze]
s.files = ["LICENSE".freeze, "README.md".freeze]
s.homepage = "https://github.com/knu/ruby-unf".freeze
s.licenses = ["2-clause BSDL".freeze]
s.rubygems_version = "3.1.4".freeze
s.summary = "A wrapper library to bring Unicode Normalization Form support to Ruby/JRuby".freeze
s.installed_by_version = "3.1.4" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<unf_ext>.freeze, [">= 0"])
s.add_development_dependency(%q<shoulda>.freeze, [">= 0"])
s.add_development_dependency(%q<bundler>.freeze, [">= 1.2.0"])
s.add_development_dependency(%q<rake>.freeze, [">= 0.9.2.2"])
s.add_development_dependency(%q<rdoc>.freeze, ["> 2.4.2"])
else
s.add_dependency(%q<unf_ext>.freeze, [">= 0"])
s.add_dependency(%q<shoulda>.freeze, [">= 0"])
s.add_dependency(%q<bundler>.freeze, [">= 1.2.0"])
s.add_dependency(%q<rake>.freeze, [">= 0.9.2.2"])
s.add_dependency(%q<rdoc>.freeze, ["> 2.4.2"])
end
end
| 40.243902 | 114 | 0.676364 |
611820f8e8c6451c405b0d1d216b4098c6b7b210 | 1,126 | require File.dirname(__FILE__) + '/spec_helper'
describe "Transfigr.presenter(obj)" do
before(:each) do
Transfigr.add(:active_presenter_format) do
def format!(o)
:presenter_format_formatted
end
end
Transfigr.activate!(:active_presenter_format)
end
it "should setup a presenter" do
Transfigr.presenter(Object.new).should be_an_instance_of(Transfigr::Presenter)
end
it "should allow me to call me to call a format via to_<format> on an activated format" do
Transfigr.presenter(Object.new).to_active_presenter_format.should == :presenter_format_formatted
end
it "should raise a FormatterNotFound when calling to_<unknown_format>" do
Transfigr.should_not be_defined(:not_defined)
lambda do
Transfigr.presenter(Object.new).to_not_defined
end.should raise_error(Transfigr::FormatterNotFound)
end
it "should fall back to the objects to_xxx method if there is no format one found" do
class PresenterFoo
def to_xxx
:fallback
end
end
Transfigr.presenter(PresenterFoo.new).to_xxx.should == :fallback
end
end | 28.871795 | 100 | 0.728242 |
bbcb5096121decc6e04bafa87a5e7a9baa45903f | 252 | #!/usr/bin/env ruby
# encoding: utf-8
require_relative '../../environment.rb'
include Sinatra::Mimsy::Helpers
name = "Granfelt, C.E."
Catalog.where(collector: name).find_each do |catalog|
catalog.collector = "Granfelt, Carl-Eric"
catalog.save
end | 22.909091 | 53 | 0.72619 |
7aa789bc123f003ef40c1da0a1d05b317cbda197 | 7,175 | require "spec_helper"
describe Mongoid::Attributes::Readonly do
describe ".attr_readonly" do
after do
Person.readonly_attributes.clear
end
context "when providing a single field" do
before do
Person.attr_readonly :title
end
it "adds the field to readonly attributes" do
expect(Person.readonly_attributes.to_a).to eq([ "title" ])
end
end
context "when providing a field alias" do
before do
Person.attr_readonly :aliased_timestamp
end
it "adds the database field name to readonly attributes" do
expect(Person.readonly_attributes.to_a).to eq([ "at" ])
end
end
context "when providing multiple fields" do
before do
Person.attr_readonly :title, :terms
end
it "adds the fields to readonly attributes" do
expect(Person.readonly_attributes.to_a).to eq([ "title", "terms" ])
end
end
context "when creating a new document with a readonly field" do
before do
Person.attr_readonly :title, :terms, :aliased_timestamp
end
let(:person) do
Person.create(title: "sir", terms: true, aliased_timestamp: Time.at(42))
end
it "sets the first readonly value" do
expect(person.title).to eq("sir")
end
it "sets the second readonly value" do
expect(person.terms).to be true
end
it "sets the third readonly value" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "persists the first readonly value" do
expect(person.reload.title).to eq("sir")
end
it "persists the second readonly value" do
expect(person.reload.terms).to be true
end
it "persists the third readonly value" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating an existing readonly field" do
before do
Person.attr_readonly :title, :terms, :score, :aliased_timestamp
end
let(:person) do
Person.create(title: "sir", terms: true, score: 1, aliased_timestamp: Time.at(42))
end
context "when updating via the setter" do
before do
person.title = "mr"
person.aliased_timestamp = Time.at(43)
person.save
end
it "does not update the first field" do
expect(person.title).to eq("sir")
end
it "does not update the second field" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "does not persist the first field" do
expect(person.reload.title).to eq("sir")
end
it "does not persist the second field" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating via inc" do
context 'with single field operation' do
it "raises an error " do
expect {
person.inc(score: 1)
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
context 'with multiple fields operation' do
it "raises an error " do
expect {
person.inc(score: 1, age: 1)
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
end
context "when updating via bit" do
context 'with single field operation' do
it "raises an error " do
expect {
person.bit(score: { or: 13 })
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
context 'with multiple fields operation' do
it "raises an error " do
expect {
person.bit(
age: { and: 13 }, score: { or: 13 }, inte: { and: 13, or: 10 }
)
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
end
context "when updating via []=" do
before do
person[:title] = "mr"
person[:aliased_timestamp] = Time.at(43)
person.save
end
it "does not update the first field" do
expect(person.title).to eq("sir")
end
it "does not update the second field" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "does not persist the first field" do
expect(person.reload.title).to eq("sir")
end
it "does not persist the second field" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating via write_attribute" do
before do
person.write_attribute(:title, "mr")
person.write_attribute(:aliased_timestamp, Time.at(43))
person.save
end
it "does not update the first field" do
expect(person.title).to eq("sir")
end
it "does not update the second field" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "does not persist the first field" do
expect(person.reload.title).to eq("sir")
end
it "does not persist the second field" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating via update_attributes" do
before do
person.update_attributes(title: "mr", aliased_timestamp: Time.at(43))
person.save
end
it "does not update the first field" do
expect(person.title).to eq("sir")
end
it "does not update the second field" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "does not persist the first field" do
expect(person.reload.title).to eq("sir")
end
it "does not persist the second field" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating via update_attributes!" do
before do
person.update_attributes!(title: "mr", aliased_timestamp: Time.at(43))
person.save
end
it "does not update the first field" do
expect(person.title).to eq("sir")
end
it "does not update the second field" do
expect(person.aliased_timestamp).to eq(Time.at(42))
end
it "does not persist the first field" do
expect(person.reload.title).to eq("sir")
end
it "does not persist the second field" do
expect(person.reload.aliased_timestamp).to eq(Time.at(42))
end
end
context "when updating via update_attribute" do
it "raises an error" do
expect {
person.update_attribute(:title, "mr")
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
context "when updating via remove_attribute" do
it "raises an error" do
expect {
person.remove_attribute(:title)
}.to raise_error(Mongoid::Errors::ReadonlyAttribute)
end
end
end
end
end
| 26.378676 | 90 | 0.585784 |
1803e6a18544e61dd99489b2dca4d04256fb84e0 | 1,523 | require 'spec_helper'
describe Keyword do
it { should have_many :wordcounts }
it { should have_many(:articles).through :wordcounts }
it { should respond_to :name }
it { should respond_to :metaphone }
it { should respond_to :stem }
it { should respond_to :synonyms }
let(:keyword) { FactoryGirl.create :keyword }
subject { keyword }
it { should be_valid }
it 'deserialises the metaphone field' do
keyword.reload.metaphone.should eq( ["RJST", "RKST"] )
end
it 'deserialised the synonyms field' do
keyword.reload.synonyms.should include('enrollment')
end
describe "creating a new Keyword" do
let(:kw) { Keyword.create!(:name => 'example') }
subject { kw }
its(:name) { should eq('example') }
its(:stem) { should eq('exampl') }
its(:metaphone) { should eq(["AKSM", nil]) }
its(:synonyms) { should eq(["illustration", "instance", "representative", "model", "exemplar", "good example", "deterrent example", "lesson", "object lesson", "case", "exercise", "admonition", "happening", "ideal", "information", "internal representation", "mental representation", "monition", "natural event", "occurrence", "occurrent", "representation", "warning", "word of advice"]) }
end
end
# == Schema Information
#
# Table name: keywords
#
# id :integer not null, primary key
# name :string(255)
# metaphone :string(255)
# stem :string(255)
# synonyms :text
# created_at :datetime not null
# updated_at :datetime not null
#
| 33.108696 | 391 | 0.655942 |
ff6180c28fe76370c62596e15d196c2bb53e8813 | 5,688 | describe Ansible::Runner do
let(:uuid) { "201ac780-7bf4-0136-3b9e-54e1ad8b3cf4" }
let(:env_vars) { {"ENV1" => "VAL1", "ENV2" => "VAL2"} }
let(:extra_vars) { {"id" => uuid} }
let(:tags) { "tag" }
describe ".run" do
let(:playbook) { "/path/to/my/playbook" }
before { expect(File).to receive(:exist?).with(playbook).and_return(true) }
it "calls launch with expected arguments" do
expected_extra_vars = "--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"#{uuid}\\\\\\\"\\\\\\}"
expected_command_line = [
"ansible-runner run",
"--json --playbook /path/to/my/playbook --ident result --hosts localhost --cmdline #{expected_extra_vars}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run(env_vars, extra_vars, playbook)
end
it "calls launch with expected tag" do
extra_vars_and_tag = "--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"#{uuid}\\\\\\\"\\\\\\}\\ --tags\\ tag"
expected_command_line = [
"ansible-runner run",
"--json --playbook /path/to/my/playbook --ident result --hosts localhost --cmdline #{extra_vars_and_tag}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run(env_vars, extra_vars, playbook, :tags => tags)
end
context "with special characters" do
let(:env_vars) { {"ENV1" => "pa$%w0rd!'"} }
let(:extra_vars) { {"name" => "john's server"} }
it "calls launch with expected arguments" do
expected_extra_vars = "--extra-vars\\ \\\\\\{\\\\\\\"name\\\\\\\":\\\\\\\"john\\\\\\'s\\\\\\ server\\\\\\\"\\\\\\}"
expected_command_line = [
"ansible-runner run",
"--json --playbook /path/to/my/playbook --ident result --hosts localhost --cmdline #{expected_extra_vars}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run(env_vars, extra_vars, playbook)
end
end
end
describe ".run_async" do
let(:playbook) { "/path/to/my/playbook" }
before { expect(File).to receive(:exist?).with(playbook).and_return(true) }
it "calls ansible-runner with start" do
expected_extra_vars = "--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"201ac780-7bf4-0136-3b9e-54e1ad8b3cf4\\\\\\\"\\\\\\}"
expected_command_line = [
"ansible-runner start",
"--json --playbook #{playbook} --ident result --hosts localhost --cmdline #{expected_extra_vars}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
result = described_class.run_async(env_vars, extra_vars, playbook)
expect(result).kind_of?(Ansible::Runner::ResponseAsync)
end
end
describe ".run_queue" do
let(:playbook) { "/path/to/my/playbook" }
let(:zone) { FactoryGirl.create(:zone) }
let(:user) { FactoryGirl.create(:user) }
it "queues Ansible::Runner.run in the right zone" do
described_class.run_queue(env_vars, extra_vars, playbook, user.name, :zone => zone.name)
expect(MiqQueue.count).to eq(1)
expect(MiqQueue.first.zone).to eq(zone.name)
end
end
describe ".run_role" do
let(:role_name) { "my-custom-role" }
let(:role_path) { "/path/to/my/roles" }
before { expect(File).to receive(:exist?).with(File.join(role_path)).and_return(true) }
it "runs ansible-runner with the role" do
expected_command_line = [
"ansible-runner run",
"--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"201ac780-7bf4-0136-3b9e-54e1ad8b3cf4\\\\\\\"\\\\\\}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run_role(env_vars, extra_vars, role_name, :roles_path => role_path)
end
it "runs ansible-runner with role and tag" do
expected_command_line = [
"ansible-runner run",
"--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"201ac780-7bf4-0136-3b9e-54e1ad8b3cf4\\\\\\\"\\\\\\}\\ --tags\\ tag"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run_role(env_vars, extra_vars, role_name, :roles_path => role_path, :tags => tags)
end
end
describe ".run_role_async" do
let(:role_name) { "my-custom-role" }
let(:role_path) { "/path/to/my/roles" }
before { expect(File).to receive(:exist?).with(File.join(role_path)).and_return(true) }
it "runs ansible-runner with the role" do
expected_command_line = [
"ansible-runner start",
"--extra-vars\\ \\\\\\{\\\\\\\"id\\\\\\\":\\\\\\\"201ac780-7bf4-0136-3b9e-54e1ad8b3cf4\\\\\\\"\\\\\\}"
]
expect(AwesomeSpawn).to receive(:launch)
.with(env_vars, a_string_including(*expected_command_line), {})
described_class.run_role_async(env_vars, extra_vars, role_name, :roles_path => role_path)
end
end
describe ".run_role_queue" do
let(:role_name) { "my-custom-role" }
let(:role_path) { "/path/to/my/roles" }
let(:zone) { FactoryGirl.create(:zone) }
let(:user) { FactoryGirl.create(:user) }
it "queues Ansible::Runner.run in the right zone" do
described_class.run_role_queue(env_vars, extra_vars, role_name, user.name, {:zone => zone.name}, :roles_path => role_path)
expect(MiqQueue.count).to eq(1)
expect(MiqQueue.first.zone).to eq(zone.name)
end
end
end
| 38.174497 | 130 | 0.611287 |
f73ae53fd7be16d48d94b55fab7caf72cc0e53d8 | 33 | require_relative "./concurrent"
| 16.5 | 32 | 0.787879 |
e22468fc8eb7a6bce8814527d2e889d711f63268 | 389 | require('rspec')
require('word_count')
describe('word_count') do
it("counts the number of times a word has been repeated in a sentence") do
expect(("crazy people are crazy").word_count("crazy")).to eq(2)
end
it ("checks if it counts word that are part of a larger world") do
expect(("monkeys are monkeying around").word_count("monkey")).to eq(2)
end
end
| 32.416667 | 78 | 0.670951 |
2102d2026a8f5d6bede37bd12bd11a67556be823 | 566 | # frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
@user = user
can :read, [Book, Article, TeamMember, Bookstore, Author, Series]
return if user.blank? # user is a guest
user_abilities
admin_abilities if user.is_a?(Admin)
end
private
def admin_abilities
can :index, AdminPanel::DashboardController
can :manage, [Book, Article, TeamMember, Bookstore, Author, Order, PromoCode, Series, Setting]
end
def user_abilities
can :modify, @user
can :toggle_favorite, Book
end
end
| 20.962963 | 98 | 0.710247 |
5dba2f21d9f54023f87fd6e0b86294f97b8c04d1 | 1,661 | class Interact::AttitudesController < Interact::BaseController
before_action :set_attitude, only: [:create, :like, :dislike, :cancel]
def index
@attitudes = Attitude.page(params[:page])
render json: @attitudes
end
def new
@attitude = Attitude.new
end
def create
@attitude.opinion = params[:opinion] || attitude_params[:opinion]
if @attitude.save
render json: @attitude.as_json(root: true), status: :ok
else
process_errors(@attitude)
end
end
def like
@attitude.opinion = 'liked'
if @attitude.save
render json: @attitude.as_json(root: true), status: :created
else
process_errors(@attitude)
end
end
def dislike
@attitude.opinion = 'disliked'
if @attitude.save
render json: @attitude.as_json(root: true), status: :accepted
else
process_errors(@attitude)
end
end
def cancel
if @attitude.opinion == 'liked'
@attitude.opinion = 'like_canceled'
elsif @attitude.opinion == 'disliked'
@attitude.opinion = 'dislike_canceled'
end
if @attitude.save
render json: @attitude.as_json(root: true), status: :accepted
else
process_errors(@attitude)
end
end
private
def set_attitude
@attitude = Attitude.find_or_initialize_by(
attitudinal_type: params[:attitudinal_type].classify,
attitudinal_id: params[:attitudinal_id],
user_id: current_user.id
)
end
def attitude_params
params.fetch(:attitude, {}).permit(
:opinion
)
end
def growth_entity_type
params[:attitudinal_type]
end
def growth_entity_id
params[:attitudinal_id]
end
end
| 20.256098 | 72 | 0.666466 |
398b198f6d68736c7989038593125975298d7ae6 | 92 | class CommentSerializer < ActiveModel::Serializer
attributes :body, :rating, :user_id
end
| 23 | 49 | 0.793478 |
f7b5941005850fbfe5c203176d0e9653bcc90ad9 | 99 | class WelcomeController < ApplicationController
layout "application"
def index
end
end
| 12.375 | 47 | 0.747475 |
7a37621c784cdd8f9e2aea8db9d388aa5522c5cf | 1,252 | module Factory
def self.create_user(params = {})
User.create!(params.reverse_merge({
email: "[email protected]",
name: "Test User",
password: "password",
password_confirmation: "password",
provider: "email",
confirmed_at: DateTime.now
}))
end
def self.create_admin(params = {})
create_user(params.reverse_merge({
email: "[email protected]",
admin: true,
}))
end
def self.create_album(params = {})
Album.create!(params.reverse_merge({
title: "Test Album",
}))
end
def self.create_photo(params = {})
Photo.create!(params.reverse_merge({
path: "test-album",
filename: "P1080110.JPG",
}))
end
def self.create_photo_version(params = {photo: create_photo})
PhotoVersion.create!(params.reverse_merge({
filename: "P1080110.JPG",
size: PhotoSize.original.name,
width: 4,
height: 3,
}))
end
def self.create_comment(params = {photo: create_photo})
Comment.create!(params.reverse_merge({
body: "example comment",
}))
end
def self.create_google_auth(params = {user: create_admin})
GoogleAuthorization.create!(params.reverse_merge({
access_token: "access-token",
}))
end
end
| 23.185185 | 63 | 0.634185 |
bf5e70f43588487b8496e86abaaee25213f39b50 | 473 | require 'telephone_appointments/version'
require 'telephone_appointments/api'
require 'telephone_appointments/response'
require 'telephone_appointments/summary_document_activity'
require 'telephone_appointments/dropped_summary_document_activity'
require 'active_support/core_ext/module/attribute_accessors'
module TelephoneAppointments
mattr_writer :api
def self.api
@api ||= TelephoneAppointments::Api.new
end
class UnsavedObject < StandardError; end
end
| 24.894737 | 66 | 0.839323 |
28d67f86cec4fcebd8ecf2202c81f3306e15dca8 | 4,275 | # frozen_string_literal: true
require "spec_helper"
module Family
RSpec.describe CelebrityFamily, type: :model, versioning: true do
it "should utilise the suffix properly" do
expect(PaperTrail::Version.friendly_item_type_from_class(described_class)). to eq("Celebrity Family")
end
describe "#reify" do
context "belongs_to" do
it "uses the correct item_type in queries" do
parent = described_class.new(name: "Jermaine Jackson")
parent.path_to_stardom = "Emulating Motown greats such as the Temptations and "\
"The Supremes"
child1 = parent.children.build(name: "Jaimy Jermaine Jackson")
parent.children.build(name: "Autumn Joy Jackson")
parent.save!
parent.update_attributes!(
name: "Hazel Gordy",
children_attributes: { id: child1.id, name: "Jay Jackson" }
)
# We expect `reify` for all versions to have item_type 'Family::CelebrityFamily',
# not 'Family::Family'. See PR #1106
expect(parent.versions.count).to eq(2) # A create and an update
parent.versions.each do |parent_version|
expect(parent_version.item_type).to eq(parent.class.name)
end
end
end
context "has_many" do
it "uses the correct item_type in queries" do
parent = described_class.new(name: "Gomez Addams")
parent.path_to_stardom = "Buy a Victorian house next to a sprawling graveyard, "\
"and just become super aloof."
parent.children.build(name: "Wednesday")
parent.save!
parent.name = "Morticia Addams"
parent.children.build(name: "Pugsley")
parent.save!
# We expect `reify` for all versions to have item_type 'Family::CelebrityFamily',
# not 'Family::Family'. See PR #1106
previous_parent = parent.versions.last.reify(has_many: true)
expect(parent.versions.count).to eq(2)
parent.versions.each do |parent_version|
expect(parent_version.item_type).to eq(parent.class.name)
end
end
end
context "has_many through" do
it "uses the correct item_type in queries" do
parent = described_class.new(name: "Grandad")
parent.path_to_stardom = "Took a suitcase and started running a market trading "\
"company out of it, while proclaiming, 'This time next "\
"year, we'll be millionaires!'"
parent.grandsons.build(name: "Del Boy")
parent.save!
parent.name = "Del"
parent.grandsons.build(name: "Rodney")
parent.save!
# We expect `reify` for all versions to have item_type 'Family::CelebrityFamily',
# not 'Family::Family'. See PR #1106
previous_parent = parent.versions.last.reify(has_many: true)
expect(parent.versions.count).to eq(2)
parent.versions.each do |parent_version|
expect(parent_version.item_type).to eq(parent.class.name)
end
end
end
context "has_one" do
it "uses the correct item_type in queries" do
parent = described_class.new(name: "Minnie Marx")
parent.path_to_stardom = "Gain a relentless dedication to the stage by having a "\
"mother who performs as a yodeling harpist, and then "\
"bring up 5 boys who have a true zest for comedy."
parent.build_mentee(name: "Abraham Schönberg")
parent.save!
parent.update_attributes(
name: "Samuel Marx",
mentee_attributes: { id: parent.mentee.id, name: "Al Shean" }
)
# We expect `reify` for all versions to have item_type 'Family::CelebrityFamily',
# not 'Family::Family'. See PR #1106
previous_parent = parent.versions.last.reify(has_one: true)
expect(parent.versions.count).to eq(2)
parent.versions.each do |parent_version|
expect(parent_version.item_type).to eq(parent.class.name)
end
end
end
end
end
end
| 42.326733 | 107 | 0.601404 |
387fbd445cb757df6709d71409020142a4c41644 | 684 | $:.push File.expand_path("../lib", __FILE__)
require "basecustom/version"
Gem::Specification.new do |s|
s.name = 'basecustom'
s.version = BaseCustom::VERSION
s.licenses = ['MIT']
s.summary = "Define your own numeric base!"
s.description = "Define your own numeric base! Highly advanced and ultimately simple!"
s.authors = ["Daniel P. Clark"]
s.email = "[email protected]"
s.files = ['lib/basecustom/version.rb', 'lib/basecustom.rb', 'README.md', 'LICENSE', 'test/bc_test.rb']
s.homepage = 'https://github.com/danielpclark/BaseCustom'
s.platform = 'ruby'
s.require_paths = ['lib']
s.required_ruby_version = '>= 1.8'
end
| 38 | 111 | 0.646199 |
28357e073be25b58cb82d343038bff6453a9754c | 2,239 | # frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "computed_model/version"
Gem::Specification.new do |spec|
spec.name = "computed_model"
spec.version = ComputedModel::VERSION
spec.authors = ["Masaki Hara", "Masayuki Izumi", "Wantedly, Inc."]
spec.email = ["[email protected]", "[email protected]", "[email protected]"]
spec.summary = %q{Batch loader with dependency resolution and computed fields}
spec.description = <<~DSC
ComputedModel is a helper for building a read-only model (sometimes called a view)
from multiple sources of models.
It comes with batch loading and dependency resolution for better performance.
It is designed to be universal. It's as easy as pie to pull data from both
ActiveRecord and remote server (such as ActiveResource).
DSC
spec.homepage = "https://github.com/wantedly/computed_model"
spec.licenses = ['MIT']
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/wantedly/computed_model"
spec.metadata["changelog_uri"] = "https://github.com/wantedly/computed_model/blob/master/CHANGELOG.md"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# For ActiveSupport::Concern
spec.add_development_dependency "activesupport"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "activerecord", "~> 6.1"
spec.add_development_dependency "sqlite3", "~> 1.4"
spec.add_development_dependency "factory_bot", "~> 6.1"
spec.add_development_dependency "simplecov", "~> 0.21.2"
spec.add_development_dependency "simplecov-lcov", "~> 0.8.0"
end
| 44.78 | 104 | 0.703439 |
333bdd5078a3de61d5c1e3dc0b0ebdf20fbd2569 | 3,000 | require 'formula'
class Vim < Formula
homepage 'http://www.vim.org/'
# This package tracks debian-unstable: http://packages.debian.org/unstable/vim
url 'http://ftp.de.debian.org/debian/pool/main/v/vim/vim_7.3.923.orig.tar.gz'
sha1 'f308d219dd9c6b56e84109ace4e7487a101088f5'
head 'https://vim.googlecode.com/hg/'
# We only have special support for finding depends_on :python, but not yet for
# :ruby, :perl etc., so we use the standard environment that leaves the
# PATH as the user has set it right now.
env :std
LANGUAGES = %w(lua mzscheme perl python tcl ruby)
DEFAULT_LANGUAGES = %w(ruby python)
option "override-system-vi", "Override system vi"
option "disable-nls", "Build vim without National Language Support (translated messages, keymaps)"
LANGUAGES.each do |language|
option "with-#{language}", "Build vim with #{language} support"
option "without-#{language}", "Build vim without #{language} support"
end
depends_on :hg => :build if build.head?
depends_on :python => :recommended
def install
ENV['LUA_PREFIX'] = HOMEBREW_PREFIX
language_opts = LANGUAGES.map do |language|
if DEFAULT_LANGUAGES.include? language and !build.include? "without-#{language}"
"--enable-#{language}interp"
elsif build.include? "with-#{language}"
"--enable-#{language}interp"
end
end.compact
opts = language_opts
opts << "--disable-nls" if build.include? "disable-nls"
# Avoid that vim always links System's Python even if configure tells us
# it has found a brewed Python. Verify with `otool -L`.
if python && python.brewed?
ENV.prepend 'LDFLAGS', "-F#{python.framework}"
end
# XXX: Please do not submit a pull request that hardcodes the path
# to ruby: vim can be compiled against 1.8.x or 1.9.3-p385 and up.
# If you have problems with vim because of ruby, ensure a compatible
# version is first in your PATH when building vim.
# We specify HOMEBREW_PREFIX as the prefix to make vim look in the
# the right place (HOMEBREW_PREFIX/share/vim/{vimrc,vimfiles}) for
# system vimscript files. We specify the normal installation prefix
# when calling "make install".
system "./configure", "--prefix=#{HOMEBREW_PREFIX}",
"--mandir=#{man}",
"--enable-gui=no",
"--without-x",
"--enable-multibyte",
"--with-tlib=ncurses",
"--enable-cscope",
"--with-features=huge",
*opts
system "make"
# If stripping the binaries is not enabled, vim will segfault with
# statically-linked interpreters like ruby
# http://code.google.com/p/vim/issues/detail?id=114&thanks=114&ts=1361483471
system "make", "install", "prefix=#{prefix}", "STRIP=/usr/bin/true"
ln_s bin+'vim', bin+'vi' if build.include? 'override-system-vi'
end
end
| 40 | 100 | 0.643667 |
f8d68e05247ecaa7fae480491f031b696e45541d | 6,332 | module Sequel
class Database
# ---------------------
# :section: 5 - Methods that set defaults for created datasets
# This methods change the default behavior of this database's datasets.
# ---------------------
# The default class to use for datasets
DatasetClass = Sequel::Dataset
@identifier_input_method = nil
@identifier_output_method = nil
@quote_identifiers = nil
class << self
# The identifier input method to use by default for all databases (default: adapter default)
attr_reader :identifier_input_method
# The identifier output method to use by default for all databases (default: adapter default)
attr_reader :identifier_output_method
# Whether to quote identifiers (columns and tables) by default for all databases (default: adapter default)
attr_accessor :quote_identifiers
end
# Change the default identifier input method to use for all databases,
def self.identifier_input_method=(v)
@identifier_input_method = v.nil? ? false : v
end
# Change the default identifier output method to use for all databases,
def self.identifier_output_method=(v)
@identifier_output_method = v.nil? ? false : v
end
# The class to use for creating datasets. Should respond to
# new with the Database argument as the first argument, and
# an optional options hash.
attr_reader :dataset_class
# The identifier input method to use by default for this database (default: adapter default)
attr_reader :identifier_input_method
# The identifier output method to use by default for this database (default: adapter default)
attr_reader :identifier_output_method
# If the database has any dataset modules associated with it,
# use a subclass of the given class that includes the modules
# as the dataset class.
def dataset_class=(c)
unless @dataset_modules.empty?
c = Class.new(c)
@dataset_modules.each{|m| c.send(:include, m)}
end
@dataset_class = c
reset_default_dataset
end
# Equivalent to extending all datasets produced by the database with a
# module. What it actually does is use a subclass of the current dataset_class
# as the new dataset_class, and include the module in the subclass.
# Instead of a module, you can provide a block that is used to create an
# anonymous module.
#
# This allows you to override any of the dataset methods even if they are
# defined directly on the dataset class that this Database object uses.
#
# Examples:
#
# # Introspec columns for all of DB's datasets
# DB.extend_datasets(Sequel::ColumnsIntrospection)
#
# # Trace all SELECT queries by printing the SQL and the full backtrace
# DB.extend_datasets do
# def fetch_rows(sql)
# puts sql
# puts caller
# super
# end
# end
def extend_datasets(mod=nil, &block)
raise(Error, "must provide either mod or block, not both") if mod && block
mod = Module.new(&block) if block
if @dataset_modules.empty?
@dataset_modules = [mod]
@dataset_class = Class.new(@dataset_class)
else
@dataset_modules << mod
end
@dataset_class.send(:include, mod)
reset_default_dataset
end
# Set the method to call on identifiers going into the database:
#
# DB[:items] # SELECT * FROM items
# DB.identifier_input_method = :upcase
# DB[:items] # SELECT * FROM ITEMS
def identifier_input_method=(v)
reset_default_dataset
@identifier_input_method = v
end
# Set the method to call on identifiers coming from the database:
#
# DB[:items].first # {:id=>1, :name=>'foo'}
# DB.identifier_output_method = :upcase
# DB[:items].first # {:ID=>1, :NAME=>'foo'}
def identifier_output_method=(v)
reset_default_dataset
@identifier_output_method = v
end
# Set whether to quote identifiers (columns and tables) for this database:
#
# DB[:items] # SELECT * FROM items
# DB.quote_identifiers = true
# DB[:items] # SELECT * FROM "items"
def quote_identifiers=(v)
reset_default_dataset
@quote_identifiers = v
end
# Returns true if the database quotes identifiers.
def quote_identifiers?
@quote_identifiers
end
private
# The default dataset class to use for the database
def dataset_class_default
self.class.const_get(:DatasetClass)
end
# Reset the default dataset used by most Database methods that
# create datasets. Usually done after changes to the identifier
# mangling methods.
def reset_default_dataset
Sequel.synchronize{@symbol_literal_cache.clear}
@default_dataset = dataset
end
# The method to apply to identifiers going into the database by default.
# Should be overridden in subclasses for databases that fold unquoted
# identifiers to lower case instead of uppercase, such as
# MySQL, PostgreSQL, and SQLite.
def identifier_input_method_default
:upcase
end
# The method to apply to identifiers coming the database by default.
# Should be overridden in subclasses for databases that fold unquoted
# identifiers to lower case instead of uppercase, such as
# MySQL, PostgreSQL, and SQLite.
def identifier_output_method_default
:downcase
end
# Whether to quote identifiers by default for this database, true
# by default.
def quote_identifiers_default
true
end
# Reset the identifier mangling options. Overrides any already set on
# the instance. Only for internal use by shared adapters.
def reset_identifier_mangling
@quote_identifiers = @opts.fetch(:quote_identifiers){(qi = Database.quote_identifiers).nil? ? quote_identifiers_default : qi}
@identifier_input_method = @opts.fetch(:identifier_input_method){(iim = Database.identifier_input_method).nil? ? identifier_input_method_default : (iim if iim)}
@identifier_output_method = @opts.fetch(:identifier_output_method){(iom = Database.identifier_output_method).nil? ? identifier_output_method_default : (iom if iom)}
reset_default_dataset
end
end
end
| 35.977273 | 170 | 0.686829 |
1c8b890a2db9c38883f8346558abe0ad7361c5e6 | 875 | class UsersController < ApplicationController
def index
if params[:query]
@users = User.where('username LIKE ?', "%#{params[:query]}%")
else
@users = User.all
end
render json: @users
end
def create
@user = User.new(user_params)
if @user.save
render json: @user, status: :created
else
render json: @user.errors.full_messages, status: :unprocessable_entity
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
render json: @user
end
def show
render json: User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
render json: @user
else
render json: @user.errors.full_messages, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:username)
end
end
| 19.021739 | 76 | 0.64 |
18678c01dc75f20edfc3f45bfacae690f57b9112 | 5,457 | require File.dirname(__FILE__) + '/helper'
class BacktraceTest < Test::Unit::TestCase
should "parse a backtrace into lines" do
array = [
"app/models/user.rb:13:in `magic'",
"app/controllers/users_controller.rb:8:in `index'"
]
backtrace = HoptoadNotifier::Backtrace.parse(array)
line = backtrace.lines.first
assert_equal '13', line.number
assert_equal 'app/models/user.rb', line.file
assert_equal 'magic', line.method
line = backtrace.lines.last
assert_equal '8', line.number
assert_equal 'app/controllers/users_controller.rb', line.file
assert_equal 'index', line.method
end
should "parse a windows backtrace into lines" do
array = [
"C:/Program Files/Server/app/models/user.rb:13:in `magic'",
"C:/Program Files/Server/app/controllers/users_controller.rb:8:in `index'"
]
backtrace = HoptoadNotifier::Backtrace.parse(array)
line = backtrace.lines.first
assert_equal '13', line.number
assert_equal 'C:/Program Files/Server/app/models/user.rb', line.file
assert_equal 'magic', line.method
line = backtrace.lines.last
assert_equal '8', line.number
assert_equal 'C:/Program Files/Server/app/controllers/users_controller.rb', line.file
assert_equal 'index', line.method
end
should "be equal with equal lines" do
one = build_backtrace_array
two = one.dup
assert_equal one, two
assert_equal HoptoadNotifier::Backtrace.parse(one), HoptoadNotifier::Backtrace.parse(two)
end
should "parse massive one-line exceptions into multiple lines" do
original_backtrace = HoptoadNotifier::Backtrace.
parse(["one:1:in `one'\n two:2:in `two'\n three:3:in `three`"])
expected_backtrace = HoptoadNotifier::Backtrace.
parse(["one:1:in `one'", "two:2:in `two'", "three:3:in `three`"])
assert_equal expected_backtrace, original_backtrace
end
context "with a project root" do
setup do
@project_root = '/some/path'
HoptoadNotifier.configure {|config| config.project_root = @project_root }
end
teardown do
reset_config
end
should "filter out the project root" do
backtrace_with_root = HoptoadNotifier::Backtrace.parse(
["#{@project_root}/app/models/user.rb:7:in `latest'",
"#{@project_root}/app/controllers/users_controller.rb:13:in `index'",
"/lib/something.rb:41:in `open'"],
:filters => default_filters)
backtrace_without_root = HoptoadNotifier::Backtrace.parse(
["[PROJECT_ROOT]/app/models/user.rb:7:in `latest'",
"[PROJECT_ROOT]/app/controllers/users_controller.rb:13:in `index'",
"/lib/something.rb:41:in `open'"])
assert_equal backtrace_without_root, backtrace_with_root
end
end
context "with a project root equals to a part of file name" do
setup do
# Heroku-like
@project_root = '/app'
HoptoadNotifier.configure {|config| config.project_root = @project_root }
end
teardown do
reset_config
end
should "filter out the project root" do
backtrace_with_root = HoptoadNotifier::Backtrace.parse(
["#{@project_root}/app/models/user.rb:7:in `latest'",
"#{@project_root}/app/controllers/users_controller.rb:13:in `index'",
"/lib/something.rb:41:in `open'"],
:filters => default_filters)
backtrace_without_root = HoptoadNotifier::Backtrace.parse(
["[PROJECT_ROOT]/app/models/user.rb:7:in `latest'",
"[PROJECT_ROOT]/app/controllers/users_controller.rb:13:in `index'",
"/lib/something.rb:41:in `open'"])
assert_equal backtrace_without_root, backtrace_with_root
end
end
context "with a blank project root" do
setup do
HoptoadNotifier.configure {|config| config.project_root = '' }
end
teardown do
reset_config
end
should "not filter line numbers with respect to any project root" do
backtrace = ["/app/models/user.rb:7:in `latest'",
"/app/controllers/users_controller.rb:13:in `index'",
"/lib/something.rb:41:in `open'"]
backtrace_with_root =
HoptoadNotifier::Backtrace.parse(backtrace, :filters => default_filters)
backtrace_without_root =
HoptoadNotifier::Backtrace.parse(backtrace)
assert_equal backtrace_without_root, backtrace_with_root
end
end
should "remove notifier trace" do
inside_notifier = ['lib/hoptoad_notifier.rb:13:in `voodoo`']
outside_notifier = ['users_controller:8:in `index`']
without_inside = HoptoadNotifier::Backtrace.parse(outside_notifier)
with_inside = HoptoadNotifier::Backtrace.parse(inside_notifier + outside_notifier,
:filters => default_filters)
assert_equal without_inside, with_inside
end
should "run filters on the backtrace" do
filters = [lambda { |line| line.sub('foo', 'bar') }]
input = HoptoadNotifier::Backtrace.parse(["foo:13:in `one'", "baz:14:in `two'"],
:filters => filters)
expected = HoptoadNotifier::Backtrace.parse(["bar:13:in `one'", "baz:14:in `two'"])
assert_equal expected, input
end
def build_backtrace_array
["app/models/user.rb:13:in `magic'",
"app/controllers/users_controller.rb:8:in `index'"]
end
def default_filters
HoptoadNotifier::Configuration::DEFAULT_BACKTRACE_FILTERS
end
end
| 33.27439 | 93 | 0.669782 |
5d2170c91c13ad0d373aa928ac4fd8156e00f3d7 | 4,472 | # encoding: utf-8
require File.dirname(__FILE__) + '/../../spec_helper'
describe SendGrid4r::REST::Stats::Subuser do
describe 'integration test', :it do
before do
Dotenv.load
@client = SendGrid4r::Client.new(api_key: ENV['SILVER_API_KEY'])
@subuser = ENV['SUBUSER2']
@email1 = ENV['MAIL']
@password1 = ENV['PASS']
@ip = ENV['IP']
subusers = @client.get_subusers
count = subusers.count { |subuser| subuser.username == @subuser }
@client.post_subuser(
username: @subuser,
email: @email1,
password: @password1,
ips: [@ip]
) if count == 0
end
context 'without block call' do
it '#get_subusers_stats with mandatory params' do
begin
top_stats = @client.get_subusers_stats(
start_date: '2015-01-01',
subusers: @subuser
)
expect(top_stats).to be_a(Array)
top_stats.each do |global_stat|
expect(global_stat).to be_a(SendGrid4r::REST::Stats::TopStat)
global_stat.stats.each do |stat|
expect(stat).to be_a(SendGrid4r::REST::Stats::Stat)
expect(stat.metrics).to be_a(SendGrid4r::REST::Stats::Metric)
expect(stat.metrics.blocks.nil?).to be(false)
expect(stat.metrics.bounce_drops.nil?).to be(false)
expect(stat.metrics.bounces.nil?).to be(false)
expect(stat.metrics.clicks.nil?).to be(false)
expect(stat.metrics.deferred.nil?).to be(false)
expect(stat.metrics.delivered.nil?).to be(false)
expect(stat.metrics.invalid_emails.nil?).to be(false)
expect(stat.metrics.opens.nil?).to be(false)
expect(stat.metrics.processed.nil?).to be(false)
expect(stat.metrics.requests.nil?).to be(false)
expect(stat.metrics.spam_report_drops.nil?).to be(false)
expect(stat.metrics.spam_reports.nil?).to be(false)
expect(stat.metrics.unique_clicks.nil?).to be(false)
expect(stat.metrics.unique_opens.nil?).to be(false)
expect(stat.metrics.unsubscribe_drops.nil?).to be(false)
expect(stat.metrics.unsubscribes.nil?).to be(false)
end
end
rescue RestClient::ExceptionWithResponse => e
puts e.inspect
raise e
end
end
it '#get_subusers_stats with all params' do
begin
top_stats = @client.get_subusers_stats(
start_date: '2015-01-01',
end_date: '2015-01-02',
aggregated_by: SendGrid4r::REST::Stats::AggregatedBy::WEEK,
subusers: @subuser
)
expect(top_stats.class).to be(Array)
top_stats.each do |global_stat|
expect(global_stat).to be_a(SendGrid4r::REST::Stats::TopStat)
global_stat.stats.each do |stat|
expect(stat).to be_a(SendGrid4r::REST::Stats::Stat)
expect(stat.metrics).to be_a(SendGrid4r::REST::Stats::Metric)
end
end
rescue RestClient::ExceptionWithResponse => e
puts e.inspect
raise e
end
end
it '#get_subusers_stats_sums with mandatory params' do
begin
top_stat = @client.get_subusers_stats_sums(start_date: '2015-01-01')
expect(top_stat).to be_a(SendGrid4r::REST::Stats::TopStat)
top_stat.stats.each do |stat|
expect(stat).to be_a(SendGrid4r::REST::Stats::Stat)
expect(stat.metrics).to be_a(SendGrid4r::REST::Stats::Metric)
end
rescue RestClient::ExceptionWithResponse => e
puts e.inspect
raise e
end
end
it '#get_subusers_stats_sums with all params' do
begin
top_stat = @client.get_subusers_stats_sums(
start_date: '2015-01-01',
end_date: '2015-01-02',
sort_by_metric: 'opens',
sort_by_direction: 'desc',
limit: 5,
offset: 0
)
expect(top_stat).to be_a(SendGrid4r::REST::Stats::TopStat)
top_stat.stats.each do |stat|
expect(stat).to be_a(SendGrid4r::REST::Stats::Stat)
expect(stat.metrics).to be_a(SendGrid4r::REST::Stats::Metric)
end
rescue RestClient::ExceptionWithResponse => e
puts e.inspect
raise e
end
end
end
end
end
| 37.579832 | 78 | 0.584526 |
1102df483853298d25b5f5af2cb089e29e62f2aa | 3,235 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
require_relative 'instrumentation'
module NewRelic::Agent::Instrumentation
module Curb
module Chain
def self.instrument!
Curl::Easy.class_eval do
include NewRelic::Agent::Instrumentation::Curb::Easy
def http_head_with_newrelic(*args, &blk)
http_head_with_tracing { http_head_without_newrelic(*args, &blk) }
end
alias_method :http_head_without_newrelic, :http_head
alias_method :http_head, :http_head_with_newrelic
def http_post_with_newrelic(*args, &blk)
http_post_with_tracing { http_post_without_newrelic(*args, &blk) }
end
alias_method :http_post_without_newrelic, :http_post
alias_method :http_post, :http_post_with_newrelic
def http_put_with_newrelic(*args, &blk)
http_put_with_tracing { http_put_without_newrelic(*args, &blk) }
end
alias_method :http_put_without_newrelic, :http_put
alias_method :http_put, :http_put_with_newrelic
# Hook the #http method to set the verb.
def http_with_newrelic verb
http_with_tracing(verb) { http_without_newrelic(verb) }
end
alias_method :http_without_newrelic, :http
alias_method :http, :http_with_newrelic
# Hook the #perform method to mark the request as non-parallel.
def perform_with_newrelic
perform_with_tracing { perform_without_newrelic }
end
alias_method :perform_without_newrelic, :perform
alias_method :perform, :perform_with_newrelic
# Record the HTTP verb for future #perform calls
def method_with_newrelic verb
method_with_tracing { method_without_newrelic(verb) }
end
alias_method :method_without_newrelic, :method
alias_method :method, :method_with_newrelic
# We override this method in order to ensure access to header_str even
# though we use an on_header callback
def header_str_with_newrelic
header_str_with_tracing { header_str_without_newrelic }
end
alias_method :header_str_without_newrelic, :header_str
alias_method :header_str, :header_str_with_newrelic
end
Curl::Multi.class_eval do
include NewRelic::Agent::Instrumentation::Curb::Multi
# Add CAT with callbacks if the request is serial
def add_with_newrelic(curl)
add_with_tracing(curl) { add_without_newrelic curl }
end
alias_method :add_without_newrelic, :add
alias_method :add, :add_with_newrelic
# Trace as an External/Multiple call if the first request isn't serial.
def perform_with_newrelic(&blk)
perform_with_tracing { perform_without_newrelic(&blk) }
end
alias_method :perform_without_newrelic, :perform
alias_method :perform, :perform_with_newrelic
end
end
end
end
end
| 34.784946 | 93 | 0.671406 |
1c3bcf7640ca09f9c4c7ce0913fc1fed3e1ddc61 | 5,905 | # encoding: UTF-8
require File.expand_path('../test_helper', __FILE__)
class TestNode < Minitest::Test
def setup
@file_name = "model/bands.utf-8.xml"
# Strip spaces to make testing easier
XML.default_keep_blanks = false
file = File.join(File.dirname(__FILE__), @file_name)
@doc = XML::Document.file(file)
end
def teardown
XML.default_keep_blanks = true
@doc = nil
end
def nodes
# Find all nodes with a country attributes
@doc.find('*[@country]')
end
def test_doc_class
assert_instance_of(XML::Document, @doc)
end
def test_doc_node_type
assert_equal XML::Node::DOCUMENT_NODE, @doc.node_type
end
def test_root_class
assert_instance_of(XML::Node, @doc.root)
end
def test_root_node_type
assert_equal XML::Node::ELEMENT_NODE, @doc.root.node_type
end
def test_node_class
for n in nodes
assert_instance_of(XML::Node, n)
end
end
def test_context
node = @doc.root
context = node.context
assert_instance_of(XML::XPath::Context, context)
end
def test_find
assert_instance_of(XML::XPath::Object, self.nodes)
end
def test_node_child_get
assert_instance_of(TrueClass, @doc.root.child?)
assert_instance_of(XML::Node, @doc.root.child)
if defined?(Encoding)
assert_equal(Encoding::UTF_8, @doc.root.child.name.encoding)
assert_equal("m\u00F6tley_cr\u00FCe", @doc.root.child.name)
else
assert_equal("m\303\266tley_cr\303\274e", @doc.root.child.name)
end
end
def test_node_doc
for n in nodes
assert_instance_of(XML::Document, n.doc) if n.document?
end
end
def test_name
node = @doc.root.children.last
assert_equal("iron_maiden", node.name)
end
def test_node_find
nodes = @doc.root.find('./fixnum')
for node in nodes
assert_instance_of(XML::Node, node)
end
end
def test_equality
node_a = @doc.find_first('*[@country]')
node_b = @doc.root.child
# On the ruby side these are different objects
refute(node_a.equal?(node_b))
# But they are the same underlying libxml node so specify they are equal
assert(node_a == node_b)
assert(node_a.eql?(node_b))
file = File.join(File.dirname(__FILE__), @file_name)
doc2 = XML::Document.file(file)
node_a2 = doc2.find_first('*[@country]')
refute(node_a == node_a2)
refute(node_a.eql?(node_a2))
assert_equal(node_a.to_s, node_a2.to_s)
refute(node_a.equal?(node_a2))
end
def test_equality_2
parent = XML::Node.new('parent')
child = XML::Node.new('child')
parent << child
node_a = child.parent
node_b = child.parent
# In this case the nodes are equal - the parent being the root
assert(node_a.equal?(node_b))
assert(node_a == node_b)
assert(node_a.eql?(node_b))
end
def test_equality_nil
node = @doc.root
assert(node != nil)
end
def test_equality_wrong_type
node = @doc.root
assert_raises(TypeError) do
assert(node != 'abc')
end
end
def test_content
node = @doc.root.last
assert_equal("Iron Maiden is a British heavy metal band formed in 1975.",
node.content)
end
def test_base
doc = XML::Parser.string('<person />').parse
assert_nil(doc.root.base_uri)
end
# We use the same facility that libXSLT does here to disable output escaping.
# This lets you specify that the node's content should be rendered unaltered
# whenever it is being output. This is useful for things like <script> and
# <style> nodes in HTML documents if you don't want to be forced to wrap them
# in CDATA nodes. Or if you are sanitizing existing HTML documents and want
# to preserve the content of any of the text nodes.
#
def test_output_escaping
text = '<bad-script>if (a < b || b > c) { return "text"; }<stop/>return ">>>snip<<<";</bad-script>'
node = XML::Parser.string(text).parse.root
assert_equal text, node.to_s
text_noenc = '<bad-script>if (a < b || b > c) { return "text"; }<stop/>return ">>>snip<<<";</bad-script>'
node.output_escaping = false
assert_equal text_noenc, node.to_s
node.output_escaping = true
assert_equal text, node.to_s
node.output_escaping = nil
assert_equal text_noenc, node.to_s
node.output_escaping = true
assert_equal text, node.to_s
end
# Just a sanity check for output escaping.
def test_output_escaping_sanity
text = '<bad-script>if (a < b || b > c) { return "text"; }<stop/>return ">>>snip<<<";</bad-script>'
node = XML::Parser.string(text).parse.root
affected = node.find('//text()')
check_escaping = lambda do |flag|
assert_equal('bad-script', node.name)
assert_equal(flag, node.output_escaping?)
affected.each do |x|
assert_equal(flag ? 'text' : 'textnoenc', x.name)
assert_equal(flag, x.output_escaping?)
end
end
node.output_escaping = false
check_escaping[false]
node.output_escaping = true
check_escaping[true]
node.output_escaping = nil
check_escaping[false]
node.output_escaping = true
check_escaping[true]
affected.first.output_escaping = true
affected.last.output_escaping = false
assert node.output_escaping?.nil?
end
def test_space_preserve
node = @doc.root
node.space_preserve = false
assert_equal XML::Node::SPACE_DEFAULT, node.space_preserve
node.space_preserve = true
assert_equal XML::Node::SPACE_PRESERVE, node.space_preserve
end
def test_empty
text = '<name> </name>'
doc = XML::Parser.string(text).parse
node = doc.root
assert(!node.empty?)
text_node = node.first
assert(text_node.empty?)
end
def test_set_content
node = XML::Node.new('test')
node.content = "unescaped & string"
assert_equal("unescaped & string", node.content)
assert_equal("<test>unescaped & string</test>", node.to_s)
end
end
| 25.452586 | 125 | 0.683827 |
1cb3a8fc50b90cbfe999e2b46ad11095ac1c8552 | 1,036 | require 'spec_helper'
describe 'datadog_agent::integrations::system_core' do
context 'supported agents' do
ALL_SUPPORTED_AGENTS.each do |agent_major_version|
let(:pre_condition) { "class {'::datadog_agent': agent_major_version => #{agent_major_version}}" }
if agent_major_version == 5
let(:conf_file) { "/etc/dd-agent/conf.d/system_core.yaml" }
else
let(:conf_file) { "#{CONF_DIR}/system_core.d/conf.yaml" }
end
it { should compile.with_all_deps }
it { should contain_file(conf_file).with(
owner: DD_USER,
group: DD_GROUP,
mode: PERMISSIONS_FILE,
)}
it { should contain_file(conf_file).that_requires("Package[#{PACKAGE_NAME}]") }
it { should contain_file(conf_file).that_notifies("Service[#{SERVICE_NAME}]") }
context 'with default parameters' do
it { should contain_file(conf_file).with_content(%r{instances:}) }
it { should contain_file(conf_file).with_content(%r{ - foo: bar}) }
end
end
end
end
| 35.724138 | 104 | 0.661197 |
f84b6c2f2ac38aedd8bc94d0c66da40e491ab759 | 2,723 | module ActsAsCached
module Config
extend self
@@class_config = {}
mattr_reader :class_config
def valued_keys
[ :store, :version, :pages, :per_page, :ttl, :finder, :cache_id, :find_by, :key_size ]
end
def setup(options)
config = options['defaults']
case options[RAILS_ENV]
when Hash then config.update(options[RAILS_ENV])
when String then config[:disabled] = true
end
config.symbolize_keys!
setup_benchmarking! if config[:benchmarking] && !config[:disabled]
setup_cache_store! config
config
end
def setup_benchmarking!
Benchmarking.inject_into_logs!
end
def setup_cache_store!(config)
config[:store] =
if config[:store].nil?
setup_memcache config
elsif config[:store].respond_to? :constantize
config[:store].constantize.new
else
config[:store]
end
end
def setup_memcache(config)
if(config[:env_override])
config[:namespace] << "-#{config[:env_override]}"
else
config[:namespace] << "-#{RAILS_ENV}"
end
silence_warnings do
Object.const_set :CACHE, memcache_client(config)
Object.const_set :SESSION_CACHE, memcache_client(config) if config[:session_servers]
end
CACHE.servers = Array(config.delete(:servers))
SESSION_CACHE.servers = Array(config[:session_servers]) if config[:session_servers]
setup_session_store if config[:sessions]
setup_fragment_store! if config[:fragments]
setup_fast_hash! if config[:fast_hash]
setup_fastest_hash! if config[:fastest_hash]
CACHE
end
def memcache_client(config)
(config[:client] || "MemCache").constantize.new(config)
end
def setup_session_store
ActionController::Base.session_store = :mem_cache_store
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update 'cache' => defined?(SESSION_CACHE) ? SESSION_CACHE : CACHE
end
def setup_fragment_store!
ActsAsCached::FragmentCache.setup!
end
# break compatiblity with non-ruby memcache clients in exchange for speedup.
# consistent across all platforms.
def setup_fast_hash!
def CACHE.hash_for(key)
(0...key.length).inject(0) do |sum, i|
sum + key[i]
end
end
end
# break compatiblity with non-ruby memcache clients in exchange for speedup.
# NOT consistent across all platforms. Object#hash gives different results
# on different architectures. only use if all your apps are running the
# same arch.
def setup_fastest_hash!
def CACHE.hash_for(key) key.hash end
end
end
end
| 27.785714 | 125 | 0.660668 |
e209c4bb45746c619f8c5e9d906c22f82481ed91 | 1,129 | class Cc65 < Formula
desc "6502 C compiler"
homepage "https://cc65.github.io/cc65/"
url "https://github.com/cc65/cc65/archive/V2.19.tar.gz"
sha256 "157b8051aed7f534e5093471e734e7a95e509c577324099c3c81324ed9d0de77"
license "Zlib"
head "https://github.com/cc65/cc65.git"
bottle do
sha256 "d0010fe7f4b58daea95dd57f4116668bd2bedfbd5392e73412162292034d456d" => :big_sur
sha256 "47405e34cd591b17d9ed65842f25ac7c6d9f61e98f21b9c403596257d7e23dae" => :arm64_big_sur
sha256 "a773d68d33b81899ebe7c10d294c0d6e2c2eab9063206f787b1e8c5b8e36f437" => :catalina
sha256 "bd750ae3470b736a6b7260723ead51d6e871edc8d8607f53b670f03c84932a00" => :mojave
end
conflicts_with "grc", because: "both install `grc` binaries"
def install
system "make", "PREFIX=#{prefix}"
system "make", "install", "PREFIX=#{prefix}"
end
def caveats
<<~EOS
Library files have been installed to:
#{pkgshare}
EOS
end
test do
(testpath/"foo.c").write "int main (void) { return 0; }"
system bin/"cl65", "foo.c" # compile and link
assert_predicate testpath/"foo", :exist? # binary
end
end
| 30.513514 | 95 | 0.728078 |
2621c05018c4004e4e0721545f6995ff3d3ca4a0 | 1,544 | module CandidateInterface
class OfferReviewComponent < SummaryListComponent
def initialize(course_choice:)
@course_choice = course_choice
end
def rows
rows = [
provider_row,
course_row,
location_row,
]
rows << conditions_row if @course_choice.offer.conditions.any?
rows
end
private
attr_reader :course_choice
def provider_row
{
key: 'Provider',
value: @course_choice.current_course.provider.name,
}
end
def course_row
{
key: 'Course',
value: course_row_value,
}
end
def location_row
{
key: 'Location',
value: @course_choice.current_course_option.site.name,
}
end
def conditions_row
{
key: 'Conditions',
value: render(OfferConditionsReviewComponent.new(conditions: @course_choice.offer.conditions_text, provider: @course_choice.current_course.provider.name)),
}
end
def course_row_value
if CycleTimetable.find_down?
tag.p(@course_choice.current_course.name_and_code, class: 'govuk-!-margin-bottom-0') +
tag.p(@course_choice.current_course.description, class: 'govuk-body')
else
govuk_link_to(
@course_choice.current_course.name_and_code,
@course_choice.current_course.find_url,
target: '_blank',
rel: 'noopener',
) +
tag.p(@course_choice.current_course.description, class: 'govuk-body')
end
end
end
end
| 23.753846 | 163 | 0.628238 |
336f7713538ab17f353f8d765b64bed5437bf4da | 4,041 | # frozen_string_literal: true
require 'rails_helper'
include Warden::Test::Helpers
# NOTE: If you generated more than one work, you have to set "js: true"
RSpec.feature 'Create a DenverImage' do
let(:user) { User.new(email: '[email protected]') { |u| u.save(validate: false) } }
let(:admin_set_id) { AdminSet.find_or_create_default_admin_set_id }
let(:permission_template) { Hyrax::PermissionTemplate.find_or_create_by!(source_id: admin_set_id) }
let(:workflow) { Sipity::Workflow.create!(active: true, name: 'test-workflow', permission_template: permission_template) }
let(:work_type) { "denver_image" }
let(:new_work_path) { "concern/#{work_type.to_s.pluralize}/new" }
before do
# Create a single action that can be taken
Sipity::WorkflowAction.create!(name: 'submit', workflow: workflow)
# Grant the user access to deposit into the admin set.
Hyrax::PermissionTemplateAccess.create!(
permission_template_id: permission_template.id,
agent_type: 'user',
agent_id: user.user_key,
access: 'deposit'
)
login_as user
visit new_work_path
end
it 'renders the new Denver Work page' do
expect(page).to have_content "Add New Denver Image"
end
it 'adds files to work' do
click_link "Files"
expect(page).to have_content "Add files"
expect(page).to have_content "Add folder"
within('span#addfiles') do
attach_file("files[]", Rails.root.join('spec', 'fixtures', 'hyrax', 'image.jp2'), visible: false)
attach_file("files[]", Rails.root.join('spec', 'fixtures', 'hyrax', 'jp2_fits.xml'), visible: false)
end
end
it 'applys work visibility' do
find('body').click
choose("#{work_type}_visibility_open")
expect(page).to have_content('Please note, making something visible to the world (i.e. marking this as Public) may be viewed as publishing which could impact your ability to')
end
it 'saves the work' do
click_link "Descriptions"
fill_in("#{work_type}_title", with: 'My Test Work')
select('Organisational', from: "#{work_type}_creator__creator_name_type")
fill_in("#{work_type}_creator__creator_organization_name", with: 'Ubiquity Press')
check('agreement')
click_on('Save')
expect(page).to have_content('My Test Work')
expect(page).to have_content('Public')
expect(page).to have_content("Your files are being processed by Hyku in the background.")
end
context "when rendering the form" do
before do
click_on "Additional fields"
end
it "renders all simple worktype fields" do
worktype_simple_fields = %w[title alt_title resource_type institution abstract keyword subject org_unit
related_exhibition related_exhibition_venue license rights_holder
rights_statement extent language location longitude latitude
georeferenced add_info]
worktype_simple_fields.each do |field|
expect(page).to have_field("#{work_type}_#{field}")
end
end
it "renders complex name fields" do
worktype_complex_name_fields = %w[creator contributor]
worktype_complex_name_fields.each do |field|
expect(page).to have_field("#{work_type}_#{field}__#{field}_family_name")
expect(page).to have_field("#{work_type}_#{field}__#{field}_given_name")
end
end
it "renders complex identifier fields" do
worktype_complex_fields = %w[alternate_identifier related_identifier]
worktype_complex_fields.each do |field|
expect(page).to have_field("#{work_type}_#{field}__#{field}")
end
end
it "renders all date fields" do
worktype_date_fields = %w[date_published related_exhibition_date]
worktype_date_fields.each do |field|
expect(page).to have_field("#{work_type}_#{field}__#{field}_year")
expect(page).to have_field("#{work_type}_#{field}__#{field}_month")
expect(page).to have_field("#{work_type}_#{field}__#{field}_day")
end
end
end
end
| 39.617647 | 179 | 0.693145 |
ac663ab69d7125283ead8df6f2e338a8c1df7721 | 3,648 | module DeviseActiveDirectoryAuthenticatable
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
class_option :user_model, :type => :string, :default => "user", :desc => "User model to update"
class_option :group_model, :type => :string, :default => "group", :desc => "Group model to update"
class_option :update_model, :type => :boolean, :default => true, :desc => "Update models to change from database_authenticatable to active_directory_authenticatable or insert the code"
class_option :add_rescue, :type => :boolean, :default => true, :desc => "Update Application Controller with resuce_from for DeviseActiveDirectoryAuthenticatable::ActiveDirectoryException"
def create_default_devise_settings
inject_into_file "config/initializers/devise.rb", default_devise_settings, :after => "Devise.setup do |config|\n"
end
def update_user_model
gsub_file "app/models/#{options.user_model}.rb", /:database_authenticatable/, ":ad_user" if options.update_model?
end
def update_group_model
inject_into_class "app/models/#{options.group_model}.rb", options.group_model, "devise :ad_group" if options.update_model?
end
def update_application_controller
inject_into_class "app/controllers/application_controller.rb", ApplicationController, rescue_from_exception if options.add_rescue?
end
private
def default_devise_settings
settings = <<-eof
# ==> Basic Active Directory Configuration
## Active Directory server settings
# config.ad_settings = {
# :host => 'domain-controller.example.local',
# :base => 'dc=example,dc=local',
# :port => 636,
# :encryption => :simple_tls,
# :auth => {
# :method => :simple
# }
# }
# config.ad_attr_mapping = {
##Attribute mapping for user object
# :AdUser => {
# #Attributes are lowercase
# :objectguid => :objectguid, #Required
# :username => :userprincipalname,
# :dn => :dn,
# :firstname => :givenName,
# :lastname => :sn,
# :whenchanged => :whenchanged,
# :whencreated => :whencreated,
# },
##Attribute mapping for group objects
# :AdGroup => {
# #Attributes are lowercase
# :objectguid => :objectguid, #Required
# :dn => :dn,
# :name => :name,
# :description => :description,
# :whencreated => :whencreated,
# :whenchanged => :whenchanged,
# }
# }
##Username attribute
##Maps to :login_with in the devise configuration
# config.ad_username = :userPrincipalName
##Create the user if they're not found
##If this is false, you will need to create the user object before they will be allowed to login
# config.ad_create_user = true
##Log LDAP queries to the Rails logger
# config.ad_logger = true
##Update the user object from the AD
# config.ad_update_users = true
##Update the group object from the AD
# config.ad_update_groups = true
##Update the group memberships from the AD, this uses the ancestory gem to store the hierarchy
# config.ad_update_group_memberships = true
##Update the user memberships from the AD
# config.ad_update_user_memberships = true
##Uses caching when doing AD queries for DNs. This speeds things up significantly.
# config.ad_caching = true
eof
settings
end
def rescue_from_exception
<<-eof
rescue_from DeviseActiveDirectoryAuthenticatable::ActiveDirectoryException do |exception|
render :text => exception, :status => 500
end
eof
end
end
end
| 32.864865 | 191 | 0.676809 |
ab1b7b92ecc60ca9b1c60a2c258a5256b6217d63 | 40 | module KamiText
VERSION = "0.1.0"
end
| 10 | 19 | 0.675 |
acc31da65b13d120faa53859ea5caaf1c6c30277 | 380 | # A job that downloads and generates thumbnails in the background for an image
# uploaded with the upload bookmarklet.
class UploadPreprocessorDelayedStartJob < ApplicationJob
queue_as :default
queue_with_priority(-1)
def perform(source, referer_url, uploader)
UploadService::Preprocessor.new(source: source, referer_url: referer_url).delayed_start(uploader)
end
end
| 34.545455 | 101 | 0.807895 |
289d4f547511eaa5feb9f3f5a06c1b90bfef4a5b | 1,309 | # == Schema Information
#
# Table name: element_value_identifier_contents
#
# id :integer not null, primary key
# value :integer
# type :string(255)
# created_at :datetime
# updated_at :datetime
#
require 'spec_helper'
describe ElementValue::PulldownVocabulary do
let(:content){create(:element_value_pulldown_vocabulary)}
describe "methods" do
describe ".reference_class" do
subject{content.reference_class}
it "Vocabulary::ElementValueが返ること" do
expect(subject).to eq(Vocabulary::ElementValue)
end
end
describe ".included_by_keyword?" do
let(:keyword){'松江'}
let(:eve){create(:vocabulary_element_value)}
subject{content.included_by_keyword?(keyword)}
before do
content.stub(:reference){eve}
end
it "参照している語彙の名前にキーワードを含む場合、Trueが返ること" do
eve.stub(:name){"松江城"}
expect(subject).to be_true
end
it "参照している語彙の名前にキーワードを含む場合、Trueが返ること" do
eve.stub(:name){"県立美術館"}
expect(subject).to be_false
end
end
describe "Concerns::ElementValueVocabulary" do
describe ".formatted_value" do
subject{content.formatted_value}
it_behaves_like "Concerns::ElementValueVocabulary#formatted_valueの検証"
end
end
end
end
| 23.8 | 77 | 0.667685 |
38ca7e325b1f96e7b82b91c2fa07473ace11991b | 610 | require 'test_helper'
class UsersHelperTest < ActionView::TestCase
test 'roles' do
assert_respond_to roles, :each
end
test 'roles label' do
assert_match /href/, roles_label
end
test 'user taggings' do
@user = users :franco
assert_equal @user.taggings, user_taggings
@user = User.new
assert_equal 1, user_taggings.size
assert user_taggings.all?(&:new_record?)
end
test 'user actions columns' do
assert_kind_of Integer, user_actions_columns
end
private
def current_user
users :franco
end
def ldap
ldaps :ldap_server
end
end
| 16.486486 | 48 | 0.690164 |
f70c5428dff9af0522f24da904b59db6654eff5a | 1,364 | class Bcftools < Formula
desc "Tools for BCF/VCF files and variant calling from samtools"
homepage "https://www.htslib.org/"
url "https://github.com/samtools/bcftools/releases/download/1.11/bcftools-1.11.tar.bz2"
sha256 "3ceee47456ec481f34fa6c34beb6fe892b5b365933191132721fdf126e45a064"
license "MIT"
livecheck do
url "https://github.com/samtools/bcftools/releases/latest"
regex(%r{href=.*?/tag/v?(\d+(?:\.\d+)+)["' >]}i)
end
bottle do
sha256 "fb3b25ef0fa059b400d4094e9719208c74b7665c45d378aec46f26efe5c179c6" => :catalina
sha256 "cbc6f8a457ddb9d4e6c14a1b5f78023f66305aa9df7f8495252b9a774821fec9" => :mojave
sha256 "d6ea207bfe680f637147e39e7cf2f3311709dc3c1964bdf5d3506d13200da7a8" => :high_sierra
sha256 "8239db528c841f58d0b79bdf36266c574eca6e8e6c030da2e59edc3f9c4ebee5" => :x86_64_linux
end
depends_on "gsl"
depends_on "htslib"
depends_on "xz"
def install
system "./configure", "--prefix=#{prefix}",
"--with-htslib=#{Formula["htslib"].opt_prefix}",
"--enable-libgsl"
system "make", "install"
pkgshare.install "test/query.vcf"
end
test do
output = shell_output("#{bin}/bcftools stats #{pkgshare}/query.vcf")
assert_match "number of SNPs:\t3", output
assert_match "fixploidy", shell_output("#{bin}/bcftools plugin -l")
end
end
| 35.894737 | 94 | 0.708944 |
acda1aaf20f28e8232968d12705e90f66648ce69 | 152 | class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = UserDecorator.find(params[:id])
end
end
| 15.2 | 45 | 0.697368 |
b9eab9de2c768624bab7052ad4e8e2c9ae75aaea | 715 | # == Schema Information
#
# Table name: partners
#
# id :bigint not null, primary key
# email :string
# name :string
# send_reminders :boolean default(FALSE), not null
# status :integer default("uninvited")
# created_at :datetime not null
# updated_at :datetime not null
# organization_id :integer
#
FactoryBot.define do
factory :partner do
sequence(:name) { |n| "Leslie Sue, the #{n}" }
sequence(:email) { |n| "leslie#{n}@gmail.com" }
send_reminders { true }
organization { Organization.try(:first) || create(:organization) }
end
trait :approved do
status { :approved }
end
end
| 26.481481 | 70 | 0.581818 |
e956d9c8fe5d8b94b58d2210b41a40abc86f28da | 546 | cask "deepstream" do
version "5.2.1"
sha256 "3a51f7bb5f730367a37b560afc58ca14934af9dfdbd147179f9916809c95db93"
url "https://github.com/deepstreamIO/deepstream.io/releases/download/v#{version}/deepstream.io-mac-#{version}.pkg",
verified: "github.com/deepstreamIO/deepstream.io/"
appcast "https://github.com/deepstreamIO/deepstream.io/releases.atom"
name "deepstream"
homepage "https://deepstream.io/"
pkg "deepstream.io-mac-#{version}.pkg"
uninstall pkgutil: "deepstream.io"
caveats do
files_in_usr_local
end
end
| 28.736842 | 117 | 0.754579 |
d53932877775f421f192bf3cd425cd94a7e7d1e0 | 401 | class CreateEvents < ActiveRecord::Migration[5.1]
def self.up
create_table :events do |t|
t.string :name
t.text :description
t.date :occurs_at
t.string :picture
t.string :url
t.string :twitter
t.references :user
t.date :starts_votes_at
t.date :end_votes_at
t.timestamps
end
end
def self.down
drop_table :events
end
end
| 18.227273 | 49 | 0.625935 |
1c0cc2fb5b2fca3b6e88024117b6ef7a18d3de68 | 625 | require 'rails_helper'
describe "when removing a user's account" do
context "as the user" do
describe "on their profile page" do
before do
user = FactoryGirl.create(:user)
log_in user
visit edit_user_path(user)
end
it "deletes their account", js: true do
click_link("Delete Account")
expect(page).to have_content "removed"
end
it "sends an email to the user informing them that their account was deleted" do
ActionMailer::Base.deliveries.last.subject.should == "Your Joerator account has been removed."
end
end
end
end
| 26.041667 | 102 | 0.6512 |
fff817f7721b513e65f2f45a6dafa9908a7fad37 | 928 | class CatController < ApplicationController
rescue_from ActiveRecord::RecordInvalid, with: :creation_error
def index
response = HTTParty.get('http://thecatapi.com/api/images/get?format=xml')
parsed_response = Hash.from_xml(response.body)
if format_data(parsed_response).present?
image = format_data(parsed_response)['image']
History.create!({
id: image['id'],
url: image['url'],
source_url: image['source_url']
})
api_response = format_data(parsed_response)
status = 200
else
api_response = {}
status = 500
end
render json: api_response, status: status
end
private
def format_data(response)
response['response']['data']['images'] rescue {}
end
def creation_error(exception)
render json: exception.record.errors.messages,
title: 'Failed to save new cat.',
status: :bad_request
end
end
| 23.794872 | 77 | 0.659483 |
f7352b67e9dac1f5fa01e74c04829891c30187ff | 4,580 | require File.expand_path('../../test_helper.rb', __FILE__)
require File.expand_path('../memory_profiler.rb', __FILE__)
class MemoryProfilerTest < Test::Unit::TestCase
# Stub the plugin instance where necessary and run
# @plugin=PluginName.new(last_run, memory, options)
# date hash hash
def test_success_linux
@plugin=MemoryProfiler.new(nil,{},{})
@plugin.expects(:`).with("cat /proc/meminfo").returns(File.read(File.dirname(__FILE__)+'/fixtures/proc_meminfo.txt')).once
@plugin.expects(:`).with("uname").returns('Linux').once
res = @plugin.run()
assert res[:errors].empty?
assert !res[:memory][:solaris]
assert_equal 7, res[:reports].first.keys.size
r = res[:reports].first
assert_equal 0, r["Swap Used"]
assert_equal 255, r["Swap Total"]
assert_equal 25, r["% Memory Used"]
assert_equal 0, r["% Swap Used"]
assert_equal 264, r["Memory Used"]
assert_equal 1024, r["Memory Total"]
assert_equal 760, r["Memory Available"]
end
def test_success_linux_second_run
# shouldn't run uname again as it is stored in memory
@plugin=MemoryProfiler.new(Time.now-60*10,{:solaris=>false},{})
@plugin.expects(:`).with("cat /proc/meminfo").returns(File.read(File.dirname(__FILE__)+'/fixtures/proc_meminfo.txt')).once
@plugin.expects(:`).with("uname").returns('Linux').never
res = @plugin.run()
assert_equal false,res[:memory][:solaris]
end
def test_success_with_no_buffers
@plugin=MemoryProfiler.new(nil,{},{})
@plugin.expects(:`).with("cat /proc/meminfo").returns(File.read(File.dirname(__FILE__)+'/fixtures/no_buffers.txt')).once
@plugin.expects(:`).with("uname").returns('Linux').once
res = @plugin.run()
assert res[:errors].empty?
assert !res[:memory][:solaris]
assert_equal 6, res[:reports].first.keys.size
end
def test_success_solaris
@plugin=MemoryProfiler.new(nil,{},{})
@plugin.expects(:`).with("prstat -c -Z 1 1").returns(File.read(File.dirname(__FILE__)+'/fixtures/prstat.txt')).once
@plugin.expects(:`).with("/usr/sbin/prtconf | grep Memory").returns(File.read(File.dirname(__FILE__)+'/fixtures/prtconf.txt')).once
@plugin.expects(:`).with("swap -s").returns(File.read(File.dirname(__FILE__)+'/fixtures/swap.txt')).once
@plugin.expects(:`).with("uname").returns('SunOS').once
res = @plugin.run()
assert res[:errors].empty?
assert res[:memory][:solaris]
assert_equal 6, res[:reports].first.keys.size
r = res[:reports].first
assert_equal 1388, r["Swap Used"]
assert_equal 2124.1, r["Swap Total"]
assert_equal (1388/2124.to_f*100).to_i, r["% Swap Used"]
assert_equal 2, r["% Memory Used"]
assert_equal 872, r["Memory Used"]
assert_equal 32763, r["Memory Total"]
end
def test_success_solaris_second_run
@plugin=MemoryProfiler.new(Time.now-60*10,{:solaris=>true},{})
@plugin.expects(:`).with("prstat -c -Z 1 1").returns(File.read(File.dirname(__FILE__)+'/fixtures/prstat.txt')).once
@plugin.expects(:`).with("/usr/sbin/prtconf | grep Memory").returns(File.read(File.dirname(__FILE__)+'/fixtures/prtconf.txt')).once
@plugin.expects(:`).with("swap -s").returns(File.read(File.dirname(__FILE__)+'/fixtures/swap.txt')).once
@plugin.expects(:`).with("uname").returns('SunOS').never
res = @plugin.run()
assert_equal true,res[:memory][:solaris]
end
def test_success_solaris_with_gb_swap_units
@plugin=MemoryProfiler.new(nil,{},{})
@plugin.expects(:`).with("prstat -c -Z 1 1").returns(File.read(File.dirname(__FILE__)+'/fixtures/prstat.txt')).once
@plugin.expects(:`).with("/usr/sbin/prtconf | grep Memory").returns(File.read(File.dirname(__FILE__)+'/fixtures/prtconf.txt')).once
@plugin.expects(:`).with("swap -s").returns(File.read(File.dirname(__FILE__)+'/fixtures/swap_gb.txt')).once
@plugin.expects(:`).with("uname").returns('SunOS').once
res = @plugin.run()
assert res[:errors].empty?
assert res[:memory][:solaris]
r = res[:reports].first
assert_equal 6, r.keys.size
assert_equal 1388, r["Swap Used"]
assert_equal 86016, r["Swap Total"]
assert_equal (1388/86016.to_f*100).to_i, r["% Swap Used"]
assert_equal 2, r["% Memory Used"]
assert_equal 872, r["Memory Used"]
assert_equal 32763, r["Memory Total"]
end
end | 42.803738 | 137 | 0.641048 |
e9e3ddf83af233083abb982118364a2681a11bcd | 6,142 | #!/usr/bin/env rackup -s thin
#
# async_chat.ru
# raggi/thin
#
# Created by James Tucker on 2008-06-19.
# Copyright 2008 James Tucker <[email protected]>.
# Uncomment if appropriate for you..
EM.epoll
# EM.kqueue # bug on OS X in 0.12?
class DeferrableBody
include EventMachine::Deferrable
def initialize
@queue = []
end
def schedule_dequeue
return unless @body_callback
EventMachine::next_tick do
next unless body = @queue.shift
body.each do |chunk|
@body_callback.call(chunk)
end
schedule_dequeue unless @queue.empty?
end
end
def call(body)
@queue << body
schedule_dequeue
end
def each &blk
@body_callback = blk
schedule_dequeue
end
end
class Chat
module UserBody
attr_accessor :username
end
def initialize
@users = {}
end
def render_page
[] << <<-EOPAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style>
body {
font-family: sans-serif;
margin: 0;
padding: 0;
margin-top: 4em;
margin-bottom: 1em;
}
#header {
background: silver;
height: 4em;
width: 100%;
position: fixed;
top: 0px;
border-bottom: 1px solid black;
padding-left: 0.5em;
}
#messages {
width: 100%;
height: 100%;
}
.message {
margin-left: 1em;
}
#send_form {
position: fixed;
bottom: 0px;
height: 1em;
width: 100%;
}
#message_box {
background: silver;
width: 100%;
border: 0px;
border-top: 1px solid black;
}
.gray {
color: gray;
}
</style>
<script type="text/javascript" src="http://ra66i.org/tmp/jquery-1.2.6.min.js"></script>
<script type="text/javascript">
XHR = function() {
var request = false;
try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {
try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e1) {
try { request = new XMLHttpRequest(); } catch(e2) {
return false;
}
}
}
return request;
}
scroll = function() {
window.scrollBy(0,50);
setTimeout('scroll()',100);
}
focus = function() {
$('#message_box').focus();
}
send_message = function(message_box) {
xhr = XHR();
xhr.open("POST", "/", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
xhr.send("message="+escape(message_box.value));
scroll();
message_box.value = '';
focus();
return false;
}
new_message = function(username, message) {
// TODO html escape message
formatted_message = "<div class='message'>" + username + ": " + message + "</div>";
messages_div = $('#messages');
$(formatted_message).appendTo(messages_div);
scroll();
return true;
}
</script>
<title>Async Chat</title>
</head>
<body>
<div id="header">
<h1>Async Chat</h1>
</div>
<div id="messages" onclick="focus();">
<span class="gray">Your first message will become your nickname!</span>
<span>Users: #{@users.map{|k,u|u.username}.join(', ')}</span>
</div>
<form id="send_form" onSubmit="return send_message(this.message)">
<input type="text" id="message_box" name="message"></input>
</form>
<script type="text/javascript">focus();</script>
</body>
</html>
EOPAGE
end
def register_user(user_id, renderer)
body = create_user(user_id)
body.call render_page
body.errback { delete_user user_id }
body.callback { delete_user user_id }
EventMachine::next_tick do
renderer.call [200, {'Content-Type' => 'text/html'}, body]
end
end
def new_message(user_id, message)
return unless @users[user_id]
if @users[user_id].username == :anonymous
username = unique_username(message)
log "User: #{user_id} is #{username}"
@users[user_id].username = message
message = "<span class='gray'>-> #{username} signed on.</span>"
end
username ||= @users[user_id].username
log "User: #{username} sent: #{message}"
@users.each do |id, body|
EventMachine::next_tick { body.call [js_message(username, message)] }
end
end
private
def unique_username(name)
name.concat('_') while @users.any? { |id,u| name == u.username }
name
end
def log(str)
print str, "\n"
end
def add_user(id, body)
@users[id] = body
end
def delete_user(id)
message = "User: #{id} - #{@users[id].username if @users[id]} disconnected."
log message
new_message(id, message)
@users.delete id
end
def js_message(username, message)
%(<script type="text/javascript">new_message("#{username}","#{message}");</script>)
end
def create_user(id)
message = "User: #{id} connected."
log message
new_message(id, message)
body = DeferrableBody.new
body.extend UserBody
body.username = :anonymous
add_user(id, body)
body
end
end
class AsyncChat
AsyncResponse = [-1, {}, []].freeze
AjaxResponse = [200, {}, []].freeze
def initialize
@chat = Chat.new
end
def call(env)
request = Rack::Request.new(env)
# TODO - cookie me, baby
user_id = request.env['REMOTE_ADDR']
if request.xhr?
message = request['message']
@chat.new_message(user_id, Rack::Utils.escape_html(message))
AjaxResponse
else
renderer = request.env['async.callback']
@chat.register_user(user_id, renderer)
AsyncResponse
end
end
end
run AsyncChat.new
| 24.766129 | 111 | 0.564311 |
1a13563cb5354d598bb7ddd360fa73bd3ef7fb80 | 198 | class <%= class_name %>Processor < ApplicationProcessor
subscribes_to :<%= singular_name %>
def on_message(message)
logger.debug "<%= class_name %>Processor received: " + message
end
end | 24.75 | 66 | 0.712121 |
ed3c35662e884767b2de1eaaf53fe6be2229378c | 5,746 | # frozen_string_literal: true
# == Schema Information
#
# Table name: tags
#
# id :integer not null, primary key
# name :string(255) default("latest"), not null
# repository_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
# digest :string(255)
# image_id :string(255) default("")
# marked :boolean default(FALSE)
# username :string(255)
# scanned :integer default(0)
#
# Indexes
#
# index_tags_on_repository_id (repository_id)
# index_tags_on_user_id (user_id)
#
# A tag as defined by Docker. It belongs to a repository and an author. The
# name follows the format as defined in registry/api/v2/names.go from Docker's
# Distribution project. The default name for a tag is "latest".
class Tag < ActiveRecord::Base
# NOTE: as a Hash because in Rails 5 we'll be able to pass a proper prefix.
enum status: { scan_none: 0, scan_working: 1, scan_done: 2 }
# A tag belongs to a repository and has an author.
belongs_to :repository
belongs_to :author, class_name: "User", foreign_key: "user_id", inverse_of: "tags"
# A tag may have scan results which contain vulnerabilities.
has_many :scan_results, dependent: :destroy
has_many :vulnerabilities, -> { uniq }, through: :scan_results
# We don't validate the tag, because we will fetch that from the registry,
# and that's guaranteed to have a good format.
#
# See https://github.com/SUSE/Portus/pull/1494 on why we didn't use the
# `uniqueness` constraint directly.
#
# NOTE: if we ever remove MySQL support, replace this with the proper
# validator.
validates :name, presence: true, unique_tag: true
# Returns a string containing the username of the user that pushed this tag.
def owner
return author.display_username if author
username.presence || "someone"
end
# Delete all the tags that match the given digest. Call this method if you
# want to:
#
# - Safely remove tags (with its re-tags) on the DB.
# - Remove the manifest digest on the registry.
# - Preserve the activities related to the tags that are to be removed.
#
# Returns true on success, false otherwise.
def delete_by_digest!(actor)
dig = fetch_digest
return false if dig.blank?
Tag.where(digest: dig).update_all(marked: true)
begin
Registry.get.client.delete(repository.full_name, dig, "manifests")
rescue ::Portus::RequestError, ::Portus::Errors::NotFoundError,
::Portus::RegistryClient::RegistryError => e
Rails.logger.error "Could not delete tag on the registry: #{e.message}"
return false
end
success = true
Tag.where(digest: dig).find_each do |tag|
success &&= tag&.delete_by!(actor)
end
success
end
# Delete this tag and update its activity.
def delete_by!(actor)
logger.tagged("catalog") { logger.info "Removed the tag '#{name}'." }
# If the tag is no longer there, ignore this call and return early.
unless Tag.find_by(id: id)
logger.tagged("catalog") { logger.info "Ignoring..." }
return
end
# Delete tag and create the corresponding activities.
destroyed = destroy
create_delete_activities!(actor) if destroyed
destroyed
end
# Returns vulnerabilities if there are any available and security scanning is
# enabled.
def fetch_vulnerabilities
return unless ::Portus::Security.enabled?
vulnerabilities if scanned == Tag.statuses[:scan_done]
end
# Updates the columns related to vulnerabilities with the given
# attributes. This will apply to only this tag, or all tags sharing the same
# digest (depending on whether the digest is known).
def update_vulnerabilities(scanned:, vulnerabilities: nil)
ScanResult.squash_data!(tag: self, vulnerabilities: vulnerabilities)
if digest.blank?
update_columns(scanned: scanned)
else
Tag.where(digest: digest).update_all(scanned: scanned)
end
end
protected
# Fetch the digest for this tag. Usually the digest should already be
# initialized since it's provided by the event notification that created this
# tag. However, it might happen that the digest column is left blank (e.g.
# legacy Portus, unknown error, etc). In these cases, this method will fetch
# the manifest from the registry and update the column directly (skipping
# validations).
#
# Returns a string containing the digest on success. Otherwise it returns
# nil.
def fetch_digest
if digest.blank?
client = Registry.get.client
begin
_, dig, = client.manifest(repository.full_name, name)
update_column(:digest, dig)
dig
rescue ::Portus::RequestError, ::Portus::Errors::NotFoundError,
::Portus::RegistryClient::ManifestError => e
Rails.logger.error "Could not fetch manifest digest: #{e}"
nil
end
else
digest
end
end
# Create/update the activities for a delete operation.
def create_delete_activities!(actor)
PublicActivity::Activity.where(recipient: self).update_all(
parameters: {
namespace_id: repository.namespace.id,
namespace_name: repository.namespace.clean_name,
repo_name: repository.name,
tag_name: name
}
)
# Create the delete activity.
repository.create_activity(
:delete,
owner: actor,
recipient: self,
parameters: {
repository_name: repository.name,
namespace_id: repository.namespace.id,
namespace_name: repository.namespace.clean_name,
tag_name: name
}
)
end
end
| 32.834286 | 84 | 0.678559 |
1de7a2e86fb4a69d87c41b1aa150df28b8091a6f | 2,828 | module Kabu
include Numo
class PatternStrategy < Strategy
def initialize
@length = 102
end
def set_env
@closes = Soks.parse(@soks[0..-2], :close)
@open = @soks[-1].open
@soks = @soks[0..-2]
end
def decide(env)
buy_patterns = [Pattern.double_bottom1,
Pattern.double_bottom2,
Pattern.double_bottom3,
Pattern.pull_back1,
Pattern.pull_back2,
Pattern.peak_out1,
]
if @capital
volume = @capital / @company.unit / @open
volume = volume.to_i * @company.unit
else
volume = 1
end
buy_patterns.each {|p| p.thr = 1}
if @position
highs = @soks[-15..-1].high(14)
high = (not highs[-1] == @soks[-1].high and highs[-2] == @soks[-2].high)
gain = @position.gain(@closes[-1],1)
if @position.buy?
if high
return Action::Sell.new(@code, @date, @open, @position.volume)
elsif @position.term > 5 and gain < 0
return Action::Sell.new(@code, @date, @open, @position.volume)
end
end
return Action::None.new(@code, @open)
else
low = @soks[-11..-1].low(10)
high = @soks[-11..-1].high(10)
buy_patterns.each do |pattern|
if pattern.correspond? @closes[-51..-2] and low[-2] == @soks[-2].low and
not pattern.correspond? @closes[-50..-1]
return Action::Buy.new(@code, @date, @open, volume)
end
end
return Action::None.new(@code, @open)
end
end
end
class PatternStrategyN
attr_accessor :length, :all_data, :code, :n, :pattern
def initialize
@length = 102
@pattern = Pattern.pull_back1
end
def set_env(soks,env)
env[:closes] = Soks.parse(soks[0..-2], :close)
env[:open] = soks[-1].open
env[:soks] = soks[0..-2]
end
def setup
end
def decide(env)
closes = env[:closes]
open = env[:open]
date = env[:date]
code = env[:code]
soks = env[:soks]
position = env[:position]
capital = env[:capital]
com = env[:com]
if capital
volume = capital / open
volume = (volume / com.unit).to_i * com.unit
else
volume = 1
end
if position
if position.term >= @n
return Action::Sell.new(code, date, open, 1)
else
return Action::None.new(code, open)
end
else
low = soks[-10..-1].low(10)[-1]
if @pattern.correspond? closes[-50..-1] and low == soks[-1].low
return Action::Buy.new(code, date, open, 1)
else
return Action::None.new(code, open)
end
end
end
end
end
| 25.709091 | 83 | 0.51662 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.