text stringlengths 10 2.61M |
|---|
require 'rails_helper'
include AdminHelpers
RSpec.feature 'Listing performances' do
before do
@hr = create(:hr)
assign_permission(@hr, :read, Performance)
login_as(@hr, scope: :hr)
@employee = create(:employee)
@performance1 = create(:performance, employee: @employee)
@performance2 = create(:performance, employee: @employee)
visit admin_employee_performances_path(@employee)
end
scenario 'should has list of performances' do
expect(page).to have_content(@performance1.year)
expect(page).to have_content(@performance2.score)
end
end
|
class BackupGenerator < Rails::Generator::Base
# This method gets initialized when the generator gets run.
# It will receive an array of arguments inside @args
def initialize(runtime_args, runtime_options = {})
super
end
# Processes the file generation/templating
# This will automatically be run after the initialize method
def manifest
record do |m|
# Generates the Rake Tasks and Backup Database
m.directory "lib/tasks"
m.file "backup.rake", "lib/tasks/backup.rake"
# Generates the configuration file
m.directory "config"
m.file "backup.rb", "config/backup.rb"
# Generates the database migration file
m.migration_template "create_backup_tables.rb",
"db/migrate",
:migration_file_name => "create_backup_tables"
# Outputs the generators message to the terminal
puts message
end
end
def message
<<-MESSAGE
==============================================================
Backup's files have been generated!
==============================================================
1: Add the "Backup" gem to the config/environment.rb file!
config.gem "backup"
2: Migrate the database!
rake db:migrate
3: Set up some "Backup Settings" inside the backup configuration file!
config/backup.rb
4: Run the backups! Enjoy.
rake backup:run trigger="your-specified-trigger"
For More Information:
http://github.com/meskyanichi/backup
==============================================================
MESSAGE
end
end |
require 'json'
require 'cgi'
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'nexus', 'config.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'nexus', 'exception.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'nexus', 'rest.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'nexus', 'util.rb'))
Puppet::Type.type(:nexus_repository).provide(:ruby) do
desc "Uses Ruby's rest library"
confine :feature => :restclient
WRITE_ONCE_ERROR_MESSAGE = "%s is write-once only and cannot be changed without force."
PROVIDER_TYPE_MAPPING = {
'maven1' => {
:provider => {
:hosted => 'maven1',
:proxy => 'maven1',
:virtual => 'maven1'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'maven1',
},
'maven2' => {
:provider => {
:hosted => 'maven2',
:proxy => 'maven2',
:virtual => 'maven2'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'maven2',
},
'obr' => {
:provider => {
:hosted => 'obr-proxy',
:proxy => 'obr-proxy',
:virtual => 'obr-proxy'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'obr',
},
'nuget' => {
:provider => {
:hosted => 'nuget-proxy',
:proxy => 'nuget-proxy',
:virtual => 'nuget-proxy'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'nuget',
},
'site' => {
:provider => {
:hosted => 'site',
:proxy => 'site',
:virtual => 'site'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.WebSiteRepository',
:format => 'site',
},
'npm' => {
:provider => {
:hosted => 'npm-hosted',
:proxy => 'npm-proxy',
:virtual => 'npm-proxy'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'npm',
},
'rubygems' => {
:provider => {
:hosted => 'rubygems-hosted',
:proxy => 'rubygems-proxy',
:virtual => 'rubygems-proxy'
},
:providerRole => 'org.sonatype.nexus.proxy.repository.Repository',
:format => 'rubygems',
},
}
def initialize(value={})
super(value)
@dirty_flag = false
end
def self.instances
begin
repositories = Nexus::Rest.get_all_plus_n('/service/local/repositories')
repositories['data'].collect do |repository|
remote_storage = repository.has_key?('remoteStorage') ? repository['remoteStorage'] : {}
remote_authentication = remote_storage.has_key?('authentication') ? remote_storage['authentication'] : {}
remote_connection = remote_storage.has_key?('connectionSettings') ? remote_storage['connectionSettings'] : {}
new(
:ensure => :present,
:name => repository['id'],
:label => repository['name'],
:provider_type => repository.has_key?('format') ? repository['format'].to_sym : nil, # TODO using the format because it maps 1:1 to the provider_type
:type => repository.has_key?('repoType') ? repository['repoType'].to_sym : nil,
:policy => repository.has_key?('repoPolicy') ? repository['repoPolicy'].downcase.to_sym : nil,
:exposed => repository.has_key?('exposed') ? repository['exposed'].to_s.to_sym : nil,
:write_policy => repository.has_key?('writePolicy') ? repository['writePolicy'].downcase.to_sym : nil,
:browseable => repository.has_key?('browseable') ? repository['browseable'].to_s.to_sym : nil,
:indexable => repository.has_key?('indexable') ? repository['indexable'].to_s.to_sym : nil,
:not_found_cache_ttl => repository.has_key?('notFoundCacheTTL') ? Integer(repository['notFoundCacheTTL']) : nil,
:local_storage_url => repository.has_key?('overrideLocalStorageUrl') ? repository['overrideLocalStorageUrl'] : nil,
:remote_storage => remote_storage.has_key?('remoteStorageUrl') ? remote_storage['remoteStorageUrl'].to_s : nil,
:remote_auto_block => repository.has_key?('autoBlockActive') ? repository['autoBlockActive'].to_s.to_sym : nil,
:remote_checksum_policy => repository.has_key?('checksumPolicy') ? repository['checksumPolicy'].downcase.to_sym : nil,
:remote_download_indexes => repository.has_key?('downloadRemoteIndexes') ? repository['downloadRemoteIndexes'].to_s.to_sym : nil,
:remote_file_validation => repository.has_key?('fileTypeValidation') ? repository['fileTypeValidation'].to_s.to_sym : nil,
:remote_item_max_age => repository.has_key?('itemMaxAge') ? repository['itemMaxAge'] : nil,
:remote_artifact_max_age => repository.has_key?('artifactMaxAge') ? repository['artifactMaxAge'] : nil,
:remote_metadata_max_age => repository.has_key?('metadataMaxAge') ? repository['metadataMaxAge'] : nil,
:remote_request_timeout => remote_connection.has_key?('connectionTimeout') ? remote_connection['connectionTimeout'] : nil,
:remote_request_retries => remote_connection.has_key?('retrievalRetryCount') ? remote_connection['retrievalRetryCount'] : nil,
:remote_query_string => remote_connection.has_key?('queryString') ? CGI.unescapeHTML(remote_connection['queryString']) : nil,
:remote_user_agent => remote_connection.has_key?('userAgentString') ? remote_connection['userAgentString'] : nil,
:remote_user => remote_authentication.has_key?('username') ? remote_authentication['username'] : nil,
:remote_password_ensure => remote_authentication.has_key?('password') ? :present : :absent,
:remote_ntlm_host => remote_authentication.has_key?('ntlmHost') ? remote_authentication['ntlmHost'] : nil,
:remote_ntlm_domain => remote_authentication.has_key?('ntlmDomain') ? remote_authentication['ntlmDomain'] : nil
)
end
rescue => e
raise Puppet::Error, "Error while retrieving all nexus_repository instances: #{e}"
end
end
def self.prefetch(resources)
repositories = instances
resources.keys.each do |name|
if provider = repositories.find { |repository| repository.name == name }
resources[name].provider = provider
end
end
end
def create
begin
Nexus::Rest.create('/service/local/repositories', map_resource_to_data)
rescue Exception => e
raise Puppet::Error, "Error while creating nexus_repository #{resource[:name]}: #{e}"
end
end
def flush
if @dirty_flag
begin
Nexus::Rest.update("/service/local/repositories/#{resource[:name]}", map_resource_to_data)
rescue Exception => e
raise Puppet::Error, "Error while updating nexus_repository #{resource[:name]}: #{e}"
end
@property_hash = resource.to_hash
end
end
def destroy
raise "The current configuration prevents the deletion of nexus_repository #{resource[:name]}; If this change is" +
" intended, please update the configuration file (#{Nexus::Config.file_path}) in order to perform this change." \
unless Nexus::Config.can_delete_repositories
begin
Nexus::Rest.destroy("/service/local/repositories/#{resource[:name]}")
rescue Exception => e
raise Puppet::Error, "Error while deleting nexus_repository #{resource[:name]}: #{e}"
end
end
def exists?
@property_hash[:ensure] == :present
end
# Returns the resource in a representation as expected by Nexus:
#
# {
# :data => {
# :id => <resource name>
# :name => <resource label>
# ...
# }
# }
def map_resource_to_data
content_type_details = PROVIDER_TYPE_MAPPING[resource[:provider_type].to_s] or raise Puppet::Error, "Nexus_repository[#{resource[:name]}]: unable to find a suitable mapping for type #{resource[:provider_type]}"
data = {
:id => resource[:name],
:name => resource[:label],
:repoType => resource[:type].to_s,
:provider => content_type_details[:provider][resource[:type]],
:providerRole => content_type_details[:providerRole],
:format => content_type_details[:format],
:repoPolicy => resource[:policy].to_s.upcase,
:exposed => Nexus::Util::sym_to_bool(resource[:exposed]),
:writePolicy => resource[:write_policy].to_s.upcase,
:browseable => Nexus::Util::sym_to_bool(resource[:browseable]),
:indexable => Nexus::Util::sym_to_bool(resource[:indexable]),
:notFoundCacheTTL => resource[:not_found_cache_ttl],
}
data[:overrideLocalStorageUrl] = resource[:local_storage_url] unless resource[:local_storage_url].nil?
if :proxy == resource[:type]
proxy_properties = {
:autoBlockActive => Nexus::Util::sym_to_bool(resource[:remote_auto_block]),
:checksumPolicy => resource[:remote_checksum_policy].to_s.upcase,
:downloadRemoteIndexes => Nexus::Util::sym_to_bool(resource[:remote_download_indexes]),
:fileTypeValidation => Nexus::Util::sym_to_bool(resource[:remote_file_validation]),
:itemMaxAge => resource[:remote_item_max_age],
:artifactMaxAge => resource[:remote_artifact_max_age],
:metadataMaxAge => resource[:remote_metadata_max_age],
:remoteStorage => {
:remoteStorageUrl => resource[:remote_storage],
:authentication => {
:ntlmDomain => resource[:remote_ntlm_domain],
:ntlmHost => resource[:remote_ntlm_host],
:password => resource[:remote_password_ensure] == :present ? resource[:remote_password] : nil,
:username => resource[:remote_user],
},
:connectionSettings => {
:connectionTimeout => resource[:remote_request_timeout],
:queryString => resource[:remote_query_string],
:retrievalRetryCount => resource[:remote_request_retries],
:userAgentString => resource[:remote_user_agent],
}
}
}
#recursively remove nil and empty hashes
Nexus::Util.strip_hash(proxy_properties)
data = data.merge(proxy_properties)
end
{:data => data}
end
mk_resource_methods
def type=(value)
raise Puppet::Error, WRITE_ONCE_ERROR_MESSAGE % 'type'
end
def provider_type=(value)
raise Puppet::Error, WRITE_ONCE_ERROR_MESSAGE % 'provider_type'
end
def policy=(value)
@dirty_flag = true
end
def exposed=(value)
@dirty_flag = true
end
def write_policy=(value)
raise Puppet::Error, "Write policy cannot be changed." unless resource[:type] == :hosted
@dirty_flag = true
end
def browseable=(value)
@dirty_flag = true
end
def indexable=(value)
@dirty_flag = true
end
def not_found_cache_ttl=(value)
@dirty_flag = true
end
def local_storage_url=(value)
@dirty_flag = true
end
def remote_storage=(value)
@dirty_flag = true
end
def remote_auto_block=(value)
@dirty_flag = true
end
def remote_checksum_policy=(value)
@dirty_flag = true
end
def remote_download_indexes=(value)
@dirty_flag = true
end
def remote_file_validation=(value)
@dirty_flag = true
end
def remote_item_max_age=(value)
@dirty_flag = true
end
def remote_artifact_max_age=(value)
@dirty_flag = true
end
def remote_metadata_max_age=(value)
@dirty_flag = true
end
def remote_request_timeout=(value)
@dirty_flag = true
end
def remote_request_retries=(value)
@dirty_flag = true
end
def remote_query_string=(value)
@dirty_flag = true
end
def remote_user_agent=(value)
@dirty_flag = true
end
def remote_user=(value)
@dirty_flag = true
end
def remote_password_ensure=(value)
@dirty_flag = true
end
def remote_password(value)
@dirty_flag = true
end
def remote_ntlm_host=(value)
@dirty_flag = true
end
def remote_ntlm_domain=(value)
@dirty_flag = true
end
end
|
class RenameOrchIdColumnToConcers < ActiveRecord::Migration
def change
rename_column :concerts, :orch_id, :orchestra_id
end
end
|
module Algorithmia
class Client
attr_reader :api_key
def initialize(api_key)
@api_key = api_key
end
def algo(endpoint)
Algorithmia::Algorithm.new(self, endpoint)
end
def file(endpoint)
Algorithmia::DataFile.new(self, endpoint)
end
def dir(endpoint)
Algorithmia::DataDirectory.new(self, endpoint)
end
end
end
|
require 'rails_helper'
feature 'User adds a Procedure to an unstarted visit', js: true do
let!(:protocol) { create_and_assign_protocol_to_me }
let!(:participant) { Participant.first }
let!(:appointment) { Appointment.first }
let!(:services) { protocol.organization.inclusive_child_services(:per_participant) }
scenario 'and sees that a core has been created' do
given_i_am_viewing_a_visit
when_i_add_2_procedures_to_same_group
then_i_should_see_a_new_core_created
end
scenario 'and sees that the entire multiselect dropdown is disabled' do
given_i_am_viewing_a_visit
when_i_add_2_procedures_to_same_group
then_i_should_see_that_the_multiselect_dropdown_is_disabled
end
scenario 'and sees that the incomplete button is disabled' do
given_i_am_viewing_a_visit
when_i_add_2_procedures_to_same_group
then_i_should_see_that_it_the_incomplete_button_is_disabled
end
scenario 'and sees that the complete button is disabled' do
given_i_am_viewing_a_visit
when_i_add_2_procedures_to_same_group
then_i_should_see_that_it_the_complete_button_is_disabled
end
def when_i_add_2_procedures_to_same_group
add_a_procedure services.first, 2
end
def then_i_should_see_a_new_core_created
expect(page).to have_css('.core')
end
def then_i_should_see_that_the_multiselect_dropdown_is_disabled
expect(page).to have_css('button.multiselect.disabled')
end
def then_i_should_see_that_it_the_incomplete_button_is_disabled
expect(page).to have_css('button.complete_all.disabled')
end
def then_i_should_see_that_it_the_complete_button_is_disabled
expect(page).to have_css('button.incomplete_all.disabled')
end
end
|
class Dietdocument < ActiveRecord::Base
has_attached_file :dietscan
do_not_validate_attachment_file_type :dietscan
validates_presence_of :student_id
belongs_to :student
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
# get '/current_user', to: 'application#current_user'
get '/check_user', to: 'application#check_user'
namespace :api do
namespace :v1 do
resources :users #, only: [:create, :show]
post '/login', to: 'auth#create'
get '/profile', to: 'users#profile'
get '/games', to: 'users#games'
post '/newgame', to: 'users#newgame'
get '/user_games', to: 'users#user_games'
get '/high_scores', to: 'users#high_scores'
get '/user_high_scores', to: 'users#user_high_scores'
patch '/updategame', to: 'users#updategame'
patch '/updateuser', to: 'users#updateuser'
end
end
end
|
# frozen_string_literal: true
class Voter < ApplicationRecord
before_save { username.downcase! }
self.primary_key = 'username'
has_many :texts, inverse_of: 'author'
has_many :links, inverse_of: 'author'
has_many :comments, inverse_of: 'author'
has_many :jets, inverse_of: 'owner'
has_many :saved_posts
has_many :posts, through: :saved_posts, source: :posts
has_many :saved_comments
has_many :comments, through: :saved_comments, source: :comments
has_many :subscriptions
has_many :jets, through: :subscriptions
validates :username, uniqueness: true, length: { minimum: 3, maximum: 10 } if :not_deleted_or_removed
acts_as_voter
private
def not_deleted_or_removed
username != '[deleted]' ||
username != '[removed]' ||
username != 'deleted' ||
username != 'removed'
end
end
|
class HomePageController < ApplicationController
def index
if signed_in?
@feed_photos = current_user.feed_photos.order(created_at: 'desc').includes(album: :user).first(10)
end
end
end
|
require_relative 'sliding_piece.rb'
require_relative 'pieces.rb'
require 'byebug'
class Bishop < Piece
include SlidingPiece
attr_reader :move_dirs
def initialize(board, pos, color)
@move_dirs = {:diagonals => true, :straight => false}
super(board,pos, color)
end
end
|
class Article < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many :has_categories, dependent: :destroy
has_many :categories, through: :has_categories
#validaciones para el titulo del articulo y cuerpo del articulo
validates :title, presence: true, length: { minimum: 2}, uniqueness: true
validates :body, presence: true, length: { minimum: 10}
#cada vez que se crea un articulo coloca el contador de visitas en 0
before_create :set_visist_count
after_create :save_categories
#aqui le decimos el archivo que va a guardar y configuramos el temaño de la imagen
has_attached_file :cover, styles: {medium:"1280x720", thumb:"400x400"}
#validamos el tipo de archivo que queremos subir ya sea imagen, pdf, etc...
validates_attachment_content_type :cover, content_type: /\Aimage\/.*\Z/
scope :ultimos, ->{ order("created_at DESC") }
#scope :ultimos, ->{ order("created_at DESC").limit(9) }
#setter personalizado
def categories=(value)
@categories = value
end
def update_visist_count
self.update(visist_count: self.visist_count + 1)
end
private
def save_categories
@categories.each do |category_id|
HasCategory.create(category_id: category_id, article_id: self.id)
end
end
def set_visist_count
self.visist_count ||= 0
end
end
|
class EdtfDateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
errors = value.reject(&:empty?).select { |date| invalid?(date) }
return if errors.to_a.empty?
record.errors.add(attribute, "Invalid EDTF #{'date'.pluralize(errors.size)}: #{errors.join(',')}")
end
def invalid?(value)
Date.edtf(value).nil?
end
end
|
# Book order entity
class Order
attr_accessor :book, :reader, :date
def initialize(book, reader, date = Time.new)
@book = book
@reader = reader
@date = date
end
def to_s
"Order: #{@book}, #{@reader}, #{@date}"
end
def hash
@id
end
end
|
Rails.application.routes.draw do
devise_for :users
resources :contacts, only: :index do
get 'errors', on: :collection
end
resources :contact_lists, except: %i[new show destroy]
root to: 'contacts#index'
end
|
require 'tech_docs_gem/version'
require 'middleman'
require 'middleman-autoprefixer'
require 'middleman-sprockets'
require 'middleman-syntax'
require 'tech_docs_gem/unique_identifier_generator'
require 'tech_docs_gem/unique_identifier_extension'
require 'tech_docs_gem/tech_docs_html_renderer'
require 'table_of_contents/heading'
require 'table_of_contents/headings_builder'
require 'table_of_contents/heading_tree'
require 'table_of_contents/heading_tree_builder'
require 'table_of_contents/heading_tree_renderer'
module TechDocs
def self.load(context)
context.activate :autoprefixer
context.activate :sprockets
context.activate :syntax
context.files.watch :source, path: 'tech_docs_gem/lib/extra_source'
context.after_configuration do
sprockets.append_path 'tech_docs_gem/lib/assets/javascripts'
end
end
end
class TechDocsExtension < Middleman::Extension
def after_configuration
::Sass.load_paths.concat(["#{__dir__}/assets/stylesheets"])
@app.set :markdown_engine, :redcarpet
@app.set :markdown,
renderer: TechDocsHTMLRenderer.new(
with_toc_data: true
),
fenced_code_blocks: true,
tables: true,
no_intra_emphasis: true
# Reload the browser automatically whenever files change
@app.configure :development do
activate :livereload
end
@app.configure :build do
activate :minify_css
activate :minify_javascript
end
@app.config[:tech_docs] = YAML.load_file('config/tech-docs.yml').with_indifferent_access
@app.activate :unique_identifier
end
helpers do
require 'table_of_contents/helpers'
include TableOfContents::Helpers
end
end
::Middleman::Extensions.register(:tech_docs, TechDocsExtension)
|
module OnTheWay
class MapquestDirections
include Endpoint
def initialize(start_point, end_point)
@start_point = start_point
@end_point = end_point
end
def url
"/directions/v2/route?key=#{mapquest_api_key}&ambiguities=ignore&from=#{start_location}&to=#{end_location}&#{options}"
end
def query_base_url
'http://open.mapquestapi.com'
end
def mapquest_api_key
ENV['MAPQUEST_API_KEY']
end
def start_location
"#{@start_point.latitude},#{@start_point.longitude}"
end
def end_location
"#{@end_point.latitude},#{@end_point.longitude}"
end
def options
"narrativeType=none&routeType=bicycle&fullShape=true&outShapeFormat=raw"
end
def find_route
json = JSON.parse(response.body)
Route.new(json['route']['shape']['shapePoints'])
end
end
end
|
module GamestateManagement
require 'yaml'
def save_game(name, word, dash_row, gallow, failure_count, used_letters)
# create save_games directory or check existance
directory_path = 'save_games'
Dir.mkdir(directory_path) unless File.exist?(directory_path)
# create file to save game
puts 'Enter the desired name of your save file: '
filename = gets.chomp
save = File.open("./save_games/#{filename}_#{name}.yaml", 'w') unless File.exist?("./save_games/#{filename}_#{name}.yaml")
# write the yaml code into the created file
YAML.dump([name, word, dash_row, gallow, failure_count, used_letters], save)
save.close
end
def load_game(name)
# display all saved YAML files
puts 'Select a save from the following files.'
saves = Dir.glob("./save_games/*#{name}*")
pp saves
# select the file that should be laoded
puts 'Please enter the name of the yaml file (the part before the underscore): '
input = gets.chomp
filename = "./save_games/#{input}_#{name}.yaml"
# load the saved YAML file
data_storage = YAML.safe_load(File.read(filename))
player.load_name(data_storage[0])
board.word.load_word(data_storage[1], data_storage[2])
board.gallow.load_gallow(data_storage[3], data_storage[4])
board.load_used_letters(data_storage[5])
end
end
|
# frozen_string_literal: true
shared_examples "manage opinions permissions" do
context "when authorization handler is Everyone" do
before do
component = opinion.component
visit ::Decidim::EngineRouter.admin_proxy(component.participatory_space).edit_component_permissions_path(component.id)
end
it "is possible to select Example authorization handler" do
within ".card.withdraw-permission" do
expect(page).to have_content("Withdraw")
check "Example authorization (Direct)"
end
find("*[type=submit]").click
expect(page).to have_admin_callout("successfully")
end
end
end
|
require 'test_helper'
class NewArticleTest < ActionDispatch::IntegrationTest
def setup
@user = User.create(username: "Chris", email: "Chris@example.com", password: "password", admin: true)
end
test "create a new article" do
sign_in_as(@user, "password")
get create_article_path
assert_template 'articles/create'
assert_difference 'Article.count', 1 do
post_via_redirect articles_path, article: {title: "Test article", description: "This is a test description"}
end
assert_template 'articles/index'
assert_match "Test article", response.body
end
end |
require 'pry'
class String
def sentence?
self.end_with?(".")
end
def question?
self.end_with?("?")
end
def exclamation?
self.end_with?("!")
end
# def count_sentences
# self.split("." || "?" || "!").length
# end
def count_sentences
count = 0
array = self.split(" ")
array.each {|word| count += 1 if word.end_with?("!", "?", ".")}
count
end
end
|
class CreateLocations < ActiveRecord::Migration[5.1]
def change
create_table :locations do |t|
t.string :name
t.string :address
t.string :phone
t.string :open_time
t.text :description
t.float :radius
t.boolean :status
t.integer :max_table
t.integer :sum_rate
t.decimal :min_booking
t.decimal :min_order
t.float :rate_avg
t.boolean :status_booking
t.boolean :status_order
t.timestamps
end
end
end
|
def translate(sentence)
latin = sentence.split.map{ |word|
phoneme = word[0, %w(a e i o u).map { |vowel|
"#{word}aeiou".index(vowel)
}.min]
if phoneme.include?("q") || phoneme.include?("Q")
if word[phoneme.length] == "u"
phoneme += "u"
end
end
if phoneme.length > 0 && is_upper?(phoneme[0..0])
"#{word[phoneme.length..-1]}#{phoneme}ay".capitalize!
elsif word.length > 1 && !is_alpha?(word[-1])
punc = word[-1]
"#{word[phoneme.length..-2]}#{phoneme}ay" + punc
else
"#{word[phoneme.length..-1]}#{phoneme}ay"
end
}.join(" ")
latin
end
def is_upper?(c)
c == c.upcase
end
def is_alpha?(str)
!str.match(/[^A-Za-z]/)
end
|
class CreateParticipate < ActiveRecord::Migration
def change
create_table :participates do |t|
t.string :user, null: false, unique: true
t.string :contest, null: false, unique: true
t.integer :year, null: false, unique: true
t.string :division, null: false, unique: true
t.integer :round, null: false, unique: true
end
end
end
|
json.array!(@graduations) do |graduation|
json.extract! graduation, :id
json.url graduation_url(graduation, format: :json)
end
|
class Hexadecimal
attr_reader :input
def initialize(input)
@input = input
end
def to_decimal
hex_pattern = /^[[:xdigit:]]+$/
if hex_pattern === input
input.to_i(16)
else
return 0
end
end
end |
class RemoveWorkoutIdFromWorkoutDetails < ActiveRecord::Migration[5.2]
def change
remove_column :workout_details, :workout_id
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_page_name
private
def set_page_name
@current_action = action_name
@current_controller = controller_name
@page_name ||= "#{@current_controller.humanize}#{@current_action.humanize}"
end
end
|
# frozen_string_literal: true
class Api::V1::CompaniesController < ApplicationController
before_action :set_company, only: %i[ show ]
def index
@companies = Company.all
render json: @companies.select(:id, :name)
end
def show
render json: {
id: @company.id,
name: @company.name
}, status: :ok
end
def create
@company = Company.create!(company_params)
render json: {
id: @company.id,
name: @company.name,
collaborators: @company.collaborators,
message: "#{@company.name} has been created"
}, status: :created
end
private
def set_company
@company = Company.find(params[:id])
end
def company_params
params.require(:company).permit(:name, collaborators_attributes: [:name, :email])
end
end
|
class LikesController < ApplicationController
before_action :authenticate_user!
before_action :set_like
def create
@like = current_user.likes.create(review_id: params[:review_id])
redirect_back(fallback_location: root_path)
end
def destroy
@like = Like.find_by(review_id: params[:review_id], user_id: current_user.id)
@like.destroy
redirect_back(fallback_location: root_path)
end
private
def set_like
@review = Review.find(params[:review_id])
end
end
|
class Interaction < ApplicationRecord
belongs_to :client
belongs_to :artist
has_one :tattoo_information, dependent: :destroy
has_one :conversation, dependent: :destroy
has_many :appointments, dependent: :destroy
scope :booked, -> { where(type: 'Booking') }
scope :inquired, -> { where(type: 'Inquiry') }
scope :applied, -> { where(type: 'Application') }
end
|
require 'spec_helper'
require 'appdirect_logfile'
describe AppdirectLogfile do
describe '#records' do
subject(:logfile) do
described_class.new(io)
end
let(:io) { double('file', lines:[line]) }
let(:line) { double('line') }
it 'parses the log lines' do
record = double('log record')
AppdirectLogRecord.stub(new: record)
logfile.records.should eq([record])
end
end
end
|
FactoryGirl.define do
factory :appointment do
start Time.current + Random.new.rand(1..10).hours
status 'free'
cost 100
showing_time 30
user
after(:build) do |appointment|
appointment.phone = appointment.user.phone if appointment.user
end
trait :with_organization do
organization factory: [:organization, :with_services]
after(:build) do |appointment|
appointment.worker = appointment.organization.workers.take
end
end
trait :with_worker do
worker
end
trait :completed do
status :complete
end
trait :valid do
sequence :phone do |_n|
(Random.new.rand * 100_000_000).ceil.to_s
end
sequence :firstname do |_n|
Faker::Name.first_name
end
after(:build) do |appointment, _evaluator|
appointment.services = appointment.organization.services
end
end
trait :multi_services do
sequence :phone do |_n|
(Random.new.rand * 100_000_000).ceil.to_s
end
sequence :firstname do |_n|
Faker::Name.first_name
end
after(:build) do |appointment, _evaluator|
appointment.organization = FactoryGirl.create(:organization_with_multi_services)
appointment.services = appointment.organization.services.where(is_collection: false)
end
end
end
end
|
class Cgo < Formula
desc "A terminal based gopher client"
homepage "https://github.com/kieselsteini/cgo"
url "https://github.com/kieselsteini/cgo/archive/ca69bbb.tar.gz"
version "0.4.1"
sha256 "fda68e99e5aaa72198183c19264d61cfaa3e90a16f60c0150e1f79083499d170"
depends_on "telnet"=> :optional
depends_on "mplayer" => :optional
def install
system "make"
system "make", "install", "PREFIX=#{prefix}"
end
test do
system "#{bin}/cgo", "-v"
end
end
|
#--
# Copyright (c) 2010-2013 Michael Berkovich, tr8nhub.com
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
###########################################################################
## API for getting translations from the main server
###########################################################################
class Tr8n::Api::ApplicationController < Tr8n::Api::BaseController
# for ssl access to the dashboard - using ssl_requirement plugin
ssl_allowed :sync if respond_to?(:ssl_allowed)
before_filter :validate_remote_application, :only => [:translations]
def index
ensure_get
ensure_application
render_response(application.to_api_hash(:definition => params[:definition]))
end
def version
ensure_get
ensure_application
render_response(:version => application.version)
end
def languages
ensure_get
ensure_application
render_response(application.languages.collect{|l| l.to_api_hash(:definition => (params[:definition] == "true"))})
end
def featured_locales
ensure_get
ensure_application
render_response(application.featured_languages.collect{|lang| lang.locale})
end
def sources
ensure_get
ensure_application
render_response(application.sources)
end
def components
ensure_get
ensure_application
render_response(application.components)
end
def translators
ensure_get
ensure_application
render_response(application.translators)
end
def sync
ensure_push_enabled
sync_log = Tr8n::Logs::ExchangeSync.create(:started_at => Time.now,
:keys_received => 0, :translations_received => 0,
:keys_sent => 0, :translations_sent => 0)
method = params[:method] || "push"
payload = []
if method == "push"
payload = push_translations(sync_log)
elsif method == "pull"
payload = pull_translations(sync_log)
end
sync_log.finished_at = Time.now
sync_log.save
render_response(:translation_keys => payload)
rescue Tr8n::Exception => ex
render_error(ex.message)
end
def translations
ensure_get
ensure_application
sync_log = Tr8n::Logs::CacheSync.create(:application => application,
:started_at => Time.now,
:keys_received => 0, :translations_received => 0,
:keys_sent => 0, :translations_sent => 0)
languages = application.languages
source_ids = application.sources.collect{|src| src.id}
sync_log.locales = application.languages.collect{|l| l.locale}
sync_log.sources = application.sources.collect{|s| s.source}
@filename = "translations_#{Date.today.to_s(:db)}.json"
self.response.headers["Content-Type"] ||= 'text/json'
self.response.headers["Content-Disposition"] = "attachment; filename=#{@filename}"
self.response.headers['Last-Modified'] = Time.now.ctime.to_s
lang_ids = languages.collect{|l| l.id}
locales = {}
Tr8n::Language.all.each do |l|
locales[l.id.to_s] = l.locale
end
self.response_body = Enumerator.new do |results|
t = 0
tk = 0
sql = %"
select tr8n_translations.translation_key_id as translation_key_id, tr8n_translation_keys.key as translation_key_hash, tr8n_translation_keys.label as translation_key_label, tr8n_translation_keys.description as translation_key_description,
tr8n_translations.language_id as translation_language_id, tr8n_translations.label as translation_label, tr8n_translations.context as translation_context
from tr8n_translations
inner join tr8n_translation_keys on tr8n_translations.translation_key_id = tr8n_translation_keys.id
where tr8n_translations.translation_key_id in (select tr8n_translation_key_sources.translation_key_id from tr8n_translation_key_sources where tr8n_translation_key_sources.translation_source_id in (#{source_ids.join(',')}))
and tr8n_translations.language_id in (#{lang_ids.join(',')})
and tr8n_translations.rank >= #{application.threshold}
order by tr8n_translations.translation_key_id asc;
"
#pp sql
tkey = nil
last_sent_id = nil
Tr8n::Translation.connection.execute(sql).each do |rec|
#pp rec["translation_key_label"]
if tkey.nil? or tkey["id"] != rec["translation_key_id"]
unless tkey.nil?
results << "#{tkey.to_json}\n"
last_sent_id = tkey["id"]
pp "#{tk} keys and #{t} translations have been sent" if tk % 1000 == 0
end
tkey = {
"key" => rec["translation_key_hash"],
"id" => rec["translation_key_id"],
"label" => rec["translation_key_label"],
"translations" => {}
}
unless rec["translation_key_description"].blank?
tkey["description"] = rec["translation_key_description"]
end
tk += 1
end
locale = locales[rec["translation_language_id"].to_s]
next unless locale
tkey["translations"][locale] = [
{"label" => rec["translation_label"]}
]
t += 1
#GC.start if i % 500==0
end
if tkey and last_sent_id != tkey["id"]
results << "#{tkey.to_json}\n"
end
sync_log.update_attributes(:keys_sent => tk, :translations_sent => t, :finished_at => Time.now)
end
end
private
def ensure_push_enabled
raise Tr8n::Exception.new("Push is disabled") unless Tr8n::Config.synchronization_push_enabled?
raise Tr8n::Exception.new("Unauthorized server push attempt") unless Tr8n::Config.synchronization_push_servers.include?(request.env['REMOTE_HOST'])
end
def translator
@translator ||= Tr8n::Config.system_translator
end
def sync_languages
@sync_languages ||= Tr8n::Language.enabled_languages
end
def batch_size
@batch_size ||= Tr8n::Config.synchronization_batch_size
end
def push_translations(sync_log, opts = {})
payload = []
# already parsed by Rails
# keys = JSON.parse(params[:translation_keys])
keys = params[:translation_keys]
return payload unless keys
sync_log.keys_received += keys.size
keys.each do |tkey_hash|
# pp tkey_hash
tkey, remaining_translations = Tr8n::TranslationKey.create_from_sync_hash(tkey_hash, translator)
next unless tkey
sync_log.translations_received += tkey_hash[:translations].size if tkey_hash[:translations]
sync_log.translations_sent += remaining_translations.size
tkey.mark_as_synced!
payload << tkey.to_sync_hash(:translations => remaining_translations, :languages => sync_languages)
end
payload
end
def pull_translations(sync_log, opts = {})
payload = []
# find all keys that have changed since the last sync
changed_keys = Tr8n::TranslationKey.where("synced_at is null or updated_at > synced_at").limit(batch_size)
sync_log.keys_sent += changed_keys.size
changed_keys.each do |tkey|
tkey_hash = tkey.to_sync_hash(:languages => sync_languages)
payload << tkey_hash
sync_log.translations_sent += tkey_hash["translations"].size if tkey_hash["translations"]
tkey.mark_as_synced!
end
payload
end
end |
class PostsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound do |exception|
render :json => { :success => false }, :status => :not_found
end
# GET /posts
# GET /posts.ext_json
def index
@posts =Post.all
respond_to do |format|
format.html # index.html.erb (no data required)
format.json {render :json => {:successful=>true, :total=>@posts.length, :data=> @posts }}
end
end
# POST /posts
def create
data= params[:data]
json_obj= ActiveSupport::JSON.decode(data)
@post = Post.new(json_obj)
if @post.save
render :json => { :success => true, :message => "Created new @Post #{@post.id}", :data => @post }
else
render :json =>{:success =>false, :message=> @post.errors}
end
end
# PUT /posts/1
def update
@posts = Post.find(params[:id])
if @posts.update_attributes(ActiveSupport::JSON.decode(params[:data]))
render :json => { :success => true, :message => "Posts was updated", :data => @posts }
else
render :json =>{:success =>false, :message=> @posts.errors}
end
render :json => @post.to_ext_json(:success => @post.update_attributes(params[:post]))
end
# DELETE /posts/1
def destroy
@posts = Post.find(params[:id])
if @posts.destroy
render :json => { :success => true, :message => "Posts was deleted"}
else
render :json =>{:success =>false, :message=> @posts.errors}
end
end
end
|
class BoatsController < ApplicationController
before_action :authenticate_user!
before_action :owned_boat, only: [:edit, :update, :destroy]
before_action :set_boat, only: [:show, :edit, :update, :destroy]
def index
@boats = Boat.all
end
def show
@boat = Boat.find(params[:id])
end
def new
@boat = current_user.boats.new
end
def create
# @boat = Boat.new(boat_params) //original one
@boat = current_user.boats.new(boat_params)
if @boat.save
redirect_to boat_url(@boat)
else
render 'new'
end
end
def edit
@boat = Boat.find(params[:id])
end
def update
@boat = Boat.find(params[:id])
if @boat.update(boat_params)
redirect_to boat_url(@boat)
else
render 'edit'
end
end
def destroy
@boat = Boat.find(params[:id])
@boat.destroy
redirect_to '/'
end
private
def boat_params
params.require(:boat).permit(:avatar, :name, :country_code, :container_capacity, :user_id )
end
def set_boat
@boat = Boat.find(params[:id])
end
def owned_boat
@boat = Boat.find(params[:id])
unless current_user == @boat.user
flash[:alert] = "That post doesn't belong to you!"
redirect_to boats_path
end
end
end
|
# frozen_string_literal: true
require 'net/http'
require 'uri'
module JsonWebTokenModule
class JsonWebToken
def self.verify(token)
JWT.decode(
token,
nil,
true, # Verify the signature of this token
algorithm: 'RS256',
iss: Rails.application.credentials.dig(:auth0, :domain),
verify_iss: true,
aud: Rails.application.credentials.dig(:auth0, :api_identifier),
verify_aud: true
) do |header|
jwks_hash[header['kid']]
end
end
# Check if the token is valid, using the JSON Web Key Set (JWKS) for Auth0 account.
def self.jwks_hash
jwks_raw = Net::HTTP.get URI("#{Rails.application.credentials.dig(:auth0, :domain)}.well-known/jwks.json")
jwks_keys = Array(JSON.parse(jwks_raw)['keys'])
Hash[
jwks_keys
.map do |k|
[
k['kid'],
OpenSSL::X509::Certificate.new(
Base64.decode64(k['x5c'].first)
).public_key
]
end
]
end
def self.token_user
url = URI("#{Rails.application.credentials.dig(:auth0, :domain)}oauth/token")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request['content-type'] = 'application/json'
request.body = "{\"client_id\":\"#{Rails.application.credentials.dig(:auth0, :client_id)}\",\"client_secret\":\"#{Rails.application.credentials.dig(:auth0, :client_secret)}\",\"audience\":\"#{Rails.application.credentials.dig(:auth0, :api_identifier)}\",\"grant_type\":\"client_credentials\"}"
response = http.request(request)
response.read_body
end
def self.revoke_token_user(token)
url = URI("#{Rails.application.credentials.dig(:auth0, :domain)}oauth/revoke")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request['content-type'] = 'application/json'
request.body = "{\"client_id\":\"#{Rails.application.credentials.dig(:auth0, :client_id)}\",\"client_secret\":\"#{Rails.application.credentials.dig(:auth0, :client_secret)}\",\"audience\":\"#{Rails.application.credentials.dig(:auth0, :api_identifier)}\",\"token\": \"#{token}\"}"
response = http.request(request)
response.read_body
end
end
end
|
require "asmaa/version"
require 'sqlite3'
module Asmaa
@db = SQLite3::Database.new File.join(File.dirname(File.expand_path(__FILE__)), 'asmaa.db')
def self.get_gender name
query = @db.prepare "SELECT * FROM names WHERE first_name=?"
first_name = name.split()[0]
query.bind_param 1, first_name
result = query.execute.next
unless result.nil?
result[0]
else
"unknown"
end
end
def self.is_male? name
self.get_gender(name) == 'male'
end
def self.is_female? name
self.get_gender(name) == 'female'
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Professor.create(name: "Admin Dashboard", email: "admin@admin.com", password: "password", is_approved: true, is_admin: true)
Professor.create(name: "Matt Baker", email: "matt@madzcintiztz.com", password: "password")
Student.create(name: "Duke", email: "duke@duke.com", password: "password")
Project.create(title: "Mad Zcienz", hypothesis: "cool shit will happen", summary: "do experiments, yo", time_budget: 400, professor_id: 2)
Record.create(student_id: 1, project_id: 1)
# Active Project
Project.create(title: "Why does the sun shine?", hypothesis: "The Sun is a mass of incandescent gas", summary: "a gigantic nuclear furnace", time_budget: 400, professor_id: 2, status: "active")
# Completed Project
Project.create(title: "SCIENCE!", hypothesis: "it's poetry in motion", summary: "She blinded me, with SCIENCE!", time_budget: 10000, professor_id: 2, status: "complete")
# Rejected Project
Project.create(title: "Weird Science", hypothesis: "cool shit will happen", summary: "do experiments, yo", time_budget: 400, professor_id: 2, status: "rejected")
10.times do
Professor.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password",
is_approved: true)
end
Professor.all.each do |professor|
Project.create!(professor_id: professor.id,
title: Faker::Hipster.sentence,
hypothesis: Faker::Lorem.sentence,
summary: Faker::Lorem.paragraph(20),
time_budget: rand(100..700),
status: "active")
end
30.times do
Student.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password")
end
Student.all.each do |student|
Record.create!(student_id: student.id,
project_id: rand(1..10),
hours_worked: 0)
end
Student.all.each do |student|
rand(1..10).times do
Record.create!(student_id: student.id,
project_id: rand(1..10),
hours_worked: rand(10..50),
observations: Faker::Lorem.paragraph(2, true))
end
end
Professor.find(1).projects.destroy_all
|
class AddMinPriceToSurveys < ActiveRecord::Migration
def change
add_column :surveys, :min_price, :integer
end
end
|
require 'delegate'
# present a person for the view
class PersonPresenter < SimpleDelegator
def bio_html
html_from(bio)
end
def twitter_handle
"@#{twitter}"
end
def twitter_url
"http://twitter.com/#{twitter}"
end
private
def html_from(markdown)
Kramdown::Document.new(markdown || '').to_html
end
end
|
require 'rails_helper'
RSpec.describe 'Users API', type: :request do
# rubocop:disable Style/BlockDelimiters
let(:valid_attributes) {
{ name: 'louiss', email: 'louiss@yahoo.com',
password: 'password' }
}
# rubocop:enable Style/BlockDelimiters
before { post '/api/v1/users', params: valid_attributes }
describe 'POST /users' do
context 'when the request is valid' do
it 'creates a user' do
json = JSON.parse(response.body)
expect(json['user']['name']).to eq('louiss')
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when the request is invalid' do
before { post '/api/v1/users', params: { name: 'louisss' } }
it 'returns creation status as false' do
json = JSON.parse(response.body)
expect(json['error']).to match('Invalid name or password')
end
it 'returns a validation failure message' do
json = JSON.parse(response.body)
expect(json['error'])
.to match('Invalid name or password')
end
end
end
describe 'POST /login' do
context 'when user logs in with valid parameters' do
let(:login_attributes) { { email: 'louiss@yahoo.com', password: 'password' } }
before { post '/api/v1/login', params: login_attributes }
it 'logs in a user' do
json = JSON.parse(response.body)
expect(json['user']['email']).to eq('louiss@yahoo.com')
expect(json['user']['name']).to eq('louiss')
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
end
context 'when user logs in with invalid parameters' do
let(:login_attributes) { { name: 'louiss', password: 'pass' } }
before { post '/api/v1/login', params: login_attributes }
it 'returns login status as not_logged_in' do
json = JSON.parse(response.body)
expect(json['loggedIn']).to match(false)
end
it 'returns an error message' do
json = JSON.parse(response.body)
expect(json['error']).to match('Invalid name or password')
end
end
describe 'GET /auto_login' do
let(:login_attributes) { { name: 'louiss', password: 'password' } }
context 'when the current user is not authorized' do
before { get '/api/v1/auto_login' }
it 'validates an un-authorized user' do
json = JSON.parse(response.body)
expect(json['message']).to eq('Please log in')
end
it 'returns status code 401' do
expect(response).to have_http_status(401)
end
end
context 'when the current user is authorized' do
after { get '/api/v1/auto_login' }
it 'returns the name of current user' do
json = JSON.parse(response.body)
expect(json['user']['name']).to match('louiss')
end
end
end
end
|
require 'rails_helper'
feature "Membership" do
scenario "User can see their membership" do
user = User.create(name: "Ian Douglas", email: "ian@turing.io", password: "password")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit '/account/membership'
expect(page).to have_content('You are on the trial subscription')
end
end
|
class CouncilsProperties < ActiveRecord::Base
attr_accessible :council_id, :property_id
belongs_to :council
belongs_to :property
end
|
class CreateDelays < ActiveRecord::Migration[5.0]
OLD_AVERAGE_DELAYS = {
"Shortly after payment" => "shortly",
"See description / T-O-S" => "see_description",
"3 days at most" => "three_days",
"One week at most" => "one_week",
"2 weeks at most" => "two_weeks",
"One month at most" => "one_month",
"2 months at most" => "two_months",
"More than 2 months" => "more_than_two_months"
}
def up
create_table :delays do |t|
t.string :key
t.timestamps
end
add_column :proposals, :delay_id, :integer
OLD_AVERAGE_DELAYS.values.each{ |key| Delay.find_or_create_by(key: key) }
Proposal.find_each do |proposal|
proposal.update(delay_id: Delay.find_by_key(OLD_AVERAGE_DELAYS[proposal.average_delay].to_s).try(:id))
end
remove_column :proposals, :average_delay
end
def down
add_column :proposals, :average_delay, :string
Proposal.find_each do |proposal|
proposal.update(average_delay: proposal.delay.try(:name))
end
remove_column :proposals, :delay_id, :integer
drop_table :delays
end
end |
#encoding: utf-8
class Inscricao < ActiveRecord::Base
attr_accessible :atividade_id, :nome, :cpf, :rg, :celular, :email, :endereco, :numero, :complemento, :bairro, :cep, :matricula, :tamanho, :contrato, :termo, :adessao
attr_accessor :contrato
attr_accessor :termo
attr_accessor :adessao
validate :termos_aceitos
validates_presence_of :nome, :message => "preenchimento obrigatório"
validates_presence_of :cpf, :message => "preenchimento obrigatório"
validates_presence_of :rg, :message => "preenchimento obrigatório"
validates_presence_of :celular, :message => "preenchimento obrigatório"
validates_presence_of :email, :message => "preenchimento obrigatório"
validates_presence_of :endereco, :message => "preenchimento obrigatório"
validates_presence_of :numero, :message => "preenchimento obrigatório"
validates_presence_of :bairro, :message => "preenchimento obrigatório"
validates_presence_of :cep, :message => "preenchimento obrigatório"
validates_presence_of :matricula, :message => "preenchimento obrigatório"
validates_presence_of :tamanho, :message => "preenchimento obrigatório"
validates_uniqueness_of :matricula, :scope => [:atividade_id], :message => ' => Aluno já matrículado nessa atividade'
before_create :validar_vagas
after_update :notificar_confirmacao
after_create :diminuir_fila, :enviar_notificaoes
before_destroy :aumentar_fila
belongs_to :atividade, :class_name => "Atividade", :foreign_key => "atividade_id"
def termos_aceitos
if (self.contrato == '0') or (self.termo == '0') or (self.adessao == '0')
errors.add("Termos e condições: ", "todos os itens devem ser aceitos")
end
end
def enviar_notificaoes
InscricaoMailer.notificar_secretaria(self).deliver
InscricaoMailer.notificar_pai_aguardando(self).deliver
end
def validar_vagas
atividade = Atividade.find(self.atividade_id)
if atividade.vagas <= 0
raise "Não a vagas disponíveis"
end
end
def aumentar_fila
atividade = Atividade.find(self.atividade_id)
atividade.vagas = atividade.vagas + 1
atividade.save
end
def diminuir_fila
atividade = Atividade.find(self.atividade_id)
atividade.vagas = atividade.vagas - 1
atividade.save
end
def notificar_confirmacao
if self.status == 3
InscricaoMailer.notificar_pai_confirmacao(self).deliver
end
end
def status_str
case self.status
when 1 then "Aguarando pagamento"
when 3 then "Matrículado"
end
end
end
|
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "rsolr-em"
gemspec.summary = "EventMachine Connection for RSolr"
gemspec.description = "EventMachine/async based connection driver for RSolr -- compatible with Ruby 1.8"
gemspec.email = "goodieboy@gmail.com"
gemspec.homepage = "http://github.com/mwmitchell/rsolr-em"
gemspec.authors = ["Colin Steele", "Matt Mitchell"]
gemspec.files = FileList['lib/**/*.rb', 'LICENSE', 'README.rdoc', 'VERSION']
gemspec.test_files = ['spec/**/*.rb', 'Rakefile']
gemspec.add_dependency('eventmachine', '>=0.12.10')
gemspec.add_dependency('rsolr', '>=1.0.0.beta3')
now = Time.now
gemspec.date = "#{now.year}-#{now.month}-#{now.day}"
gemspec.has_rdoc = true
end
# Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler not available. Install it with: gem install jeweler"
end |
class AddTypeToOrders < ActiveRecord::Migration
def change
add_column :orders , :readyorpo , :string
end
end
|
class PhotoGallery
attr_reader :title, :photos, :filter, :page, :tag, :total_pages
def initialize(params, photo_filter=nil)
if photo_filter
@title = photo_filter.title
@photos = photo_filter.photos
@filter = photo_filter.filter
end
# TODO: fix this
@page_size = PhotosController::PHOTOS_PER_PAGE
extract_params(params)
end
def more_pages?
page < total_pages
end
def previous_pages?
page > 1
end
def previous_params
pparams = @params.dup
pparams[:page] -= 1
pparams
end
def next_params
nparams = @params.dup
nparams[:page] += 1
nparams
end
def tag
@params[:tag]
end
private
def extract_params params
@params = params.except(:controller, :action)
@page = @params[:page] = @params[:page] ? params[:page].to_i : 1
@total_pages = (1.0 * @photos.count / @page_size).ceil
@photos = @photos.
recent.
skip([@page - 1, 0].max * @page_size).
limit(@page_size).
only(:id, :title, :views, :votes, :thumbnail_sm_url)
@tag = @params[:tag] = params[:tag]
@popular = @params[:popular] = params[:popular]
@category = @params[:category] = params[:category].downcase if Photo.category?(params[:category])
@contestant = Contestant.find(params[:contestant_id]) if params[:contestant_id]
@params[:contestant_id] = @contestant.id if @contestant
@params.keep_if { |key, val| val }
end
end |
#
# Author:: Kaustubh Deorukhkar (<kaustubh@clogeny.com>)
# Copyright:: Copyright (c) 2013 Opscode, Inc.
#
require 'chef/knife/cloud/service'
require 'chef/knife/cloud/exceptions'
class Chef
class Knife
class Cloud
class FogService < Service
attr_accessor :fog_version
def initialize(options = {})
@fog_version = Chef::Config[:knife][:cloud_fog_version]
# Load specific version of fog. Any other classes/modules using fog are loaded after this.
gem "fog", Chef::Config[:knife][:cloud_fog_version]
require 'fog'
Chef::Log.debug("Using fog version: #{Gem.loaded_specs["fog"].version}")
super
end
def connection
@connection ||= begin
connection = Fog::Compute.new(@auth_params)
rescue Excon::Errors::Unauthorized => e
ui.fatal("Connection failure, please check your username and password.")
exit 1
rescue Excon::Errors::SocketError => e
ui.fatal("Connection failure, please check your authentication URL.")
exit 1
end
end
# cloud server specific implementation methods for commands.
def create_server(options = {})
begin
server = connection.servers.create(options[:server_def])
rescue Excon::Errors::BadRequest => e
response = Chef::JSONCompat.from_json(e.response.body)
if response['badRequest']['code'] == 400
message = "Bad request (400): #{response['badRequest']['message']}"
ui.fatal(message)
else
message = "Unknown server error (#{response['badRequest']['code']}): #{response['badRequest']['message']}"
ui.fatal(message)
end
raise CloudExceptions::ServerCreateError, message
end
msg_pair("Instance Name", server.name)
msg_pair("Instance ID", server.id)
print "\n#{ui.color("Waiting for server [wait time = #{options[:server_create_timeout]}]", :magenta)}"
# wait for it to be ready to do stuff
server.wait_for(Integer(options[:server_create_timeout])) { print "."; ready? }
puts("\n")
server
end
def delete_server(server_name)
begin
server = connection.servers.get(server_name)
msg_pair("Instance Name", server.name)
msg_pair("Instance ID", server.id)
puts "\n"
ui.confirm("Do you really want to delete this server")
# delete the server
server.destroy
rescue NoMethodError
error_message = "Could not locate server '#{server_name}'."
ui.error(error_message)
raise CloudExceptions::ServerDeleteError, error_message
rescue Excon::Errors::BadRequest => e
response = Chef::JSONCompat.from_json(e.response.body)
ui.fatal("Unknown server error (#{response['badRequest']['code']}): #{response['badRequest']['message']}")
raise e
end
end
def list_servers
begin
servers = connection.servers.all
rescue Excon::Errors::BadRequest => e
response = Chef::JSONCompat.from_json(e.response.body)
ui.fatal("Unknown server error (#{response['badRequest']['code']}): #{response['badRequest']['message']}")
raise e
end
end
def list_images
begin
images = connection.images.all
rescue Excon::Errors::BadRequest => e
response = Chef::JSONCompat.from_json(e.response.body)
ui.fatal("Unknown server error (#{response['badRequest']['code']}): #{response['badRequest']['message']}")
raise e
end
end
def delete_server_on_failure(server = nil)
server.destroy if ! server.nil?
end
end
end
end
end
|
class CreateBoatTypeModifications < ActiveRecord::Migration[5.0]
def change
create_table :boat_type_modifications do |t|
t.integer :boat_type_id
t.integer :boat_option_type_id
t.string :name
t.string :description
t.boolean :is_active, default: true
t.string :bow_view
t.string :aft_view
t.string :top_view
t.string :accomodation_view
t.timestamps
end
end
end
|
class BookSubjectsController < ApplicationController
before_action :set_book_subject, only: [:show, :edit, :update, :destroy]
# GET /book_subjects
# GET /book_subjects.json
def index
@book_subjects = BookSubject.all
end
# GET /book_subjects/1
# GET /book_subjects/1.json
def show
end
# GET /book_subjects/new
def new
@subject = Subject.all
@book = Book.all
@book_subject = BookSubject.new
end
# GET /book_subjects/1/edit
def edit
end
# POST /book_subjects
# POST /book_subjects.json
def create
@book_subject = BookSubject.new(book_subject_params)
respond_to do |format|
if @book_subject.save
format.html { redirect_to @book_subject, notice: 'Book subject was successfully created.' }
format.json { render :show, status: :created, location: @book_subject }
else
format.html { render :new }
format.json { render json: @book_subject.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /book_subjects/1
# PATCH/PUT /book_subjects/1.json
def update
respond_to do |format|
if @book_subject.update(book_subject_params)
format.html { redirect_to @book_subject, notice: 'Book subject was successfully updated.' }
format.json { render :show, status: :ok, location: @book_subject }
else
format.html { render :edit }
format.json { render json: @book_subject.errors, status: :unprocessable_entity }
end
end
end
# DELETE /book_subjects/1
# DELETE /book_subjects/1.json
def destroy
@book_subject.destroy
respond_to do |format|
format.html { redirect_to book_subjects_url, notice: 'Book subject was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book_subject
@book_subject = BookSubject.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_subject_params
params.require(:book_subject).permit(:book_id, :subject_id)
end
end
|
module AEditor
class IntegrityError < Exception; end
module Helpers
def check_integer(int)
raise TypeError, 'expected integer' unless int.kind_of?(Integer)
end
def check_boolean(bool)
raise TypeError, 'expected boolean' unless bool == true or bool == false
end
def check_valid_utf8(str)
raise TypeError unless str.kind_of?(String)
str.unpack("U*")
end
def determine_bytes_of_char(first_byte)
check_integer(first_byte)
unless first_byte.between?(0, 255)
raise ArgumentError, "outside range 0..255"
end
return 1 if first_byte < 0x80
bytes = 2
bit = 5
until first_byte[bit] == 0
bit -= 1
bytes += 1
end
bytes
end
end # module Helpers
module Model
class NotifyInfo
def initialize
@x1, @y1 = 0, 0
@source_x2, @source_y2 = 0, 0
@dest_x2, @dest_y2 = 0, 0
@event = nil
end
attr_accessor :x1, :y1
attr_accessor :source_x2, :source_y2
attr_accessor :dest_x2, :dest_y2
attr_accessor :event
end
#
# maybe it would be good to keep track of
# if the model is saved on disk? In case
# the saved-state changes then all observers
# gets a notify.
#
#
class Caretaker
include Helpers
def initialize
@bytes = [0]
@text = ""
@observers = []
@notify_info = NotifyInfo.new
end
attr_reader :bytes, :text, :observers
def attach(observer)
unless observer.respond_to?(:model_update)
raise NoMethodError, "observer needs to respond to `model_update'"
end
@observers << observer
end
def detach(observer)
@observers.delete(observer)
end
# convert from (x,y) to (byte offset)
def p2b(x, y)
check_integer(x)
check_integer(y)
unless y.between?(0, @bytes.size-1)
raise ArgumentError,
"y must between 0..#{@bytes.size-1}, but was #{y}."
end
if x < 0
raise ArgumentError,
"x must be greater or equal to 0, but was #{x}."
end
n = 0
0.upto(y-1) do |iy|
n += @bytes[iy]
end
x.downto(1) do |ix|
char = @text[n]
raise ArgumentError if char == 10 or char == nil
n += determine_bytes_of_char(char)
end
n
end
# convert from (byte offset) to (x,y)
def b2p(byte)
check_integer(byte)
raise ArgumentError, "byte outside range" if byte < 0
n = 0
0.upto(@bytes.size-1) do |y|
nextn = n + @bytes[y]
unless byte < nextn or (byte <= nextn and y == @bytes.size-1)
n = nextn
next
end
x = 0
while byte > n
char = @text[n]
raise ArgumentError if char == 10 or char == nil
n += determine_bytes_of_char(char)
x += 1
end
x -= 1 if n > byte
return [x, y]
end
raise ArgumentError, "byte outside range"
end
# replace a region with something else
def replace(x1, y1, x2, y2, utf8_str)
$logger.debug "model replace xy1=#{x1.inspect},#{y1.inspect} " +
"xy2=#{x2.inspect},#{y2.inspect} text.size=#{utf8_str.size}"
check_integer(x1)
check_integer(y1)
check_integer(x2)
check_integer(y2)
raise ArgumentError, "negative range" if y1 > y2
raise ArgumentError, "negative range" if y1 == y2 and x1 > x2
check_valid_utf8(utf8_str)
begin
text_begin_line = p2b(0, y1)
text_begin_insert = p2b(x1, y1)
rescue ArgumentError => e
raise ArgumentError,
"first position (#{x1},#{y1}) is invalid, " +
"reason=#{e.message}"
end
begin
text_end_line = p2b(0, y2) + @bytes[y2]
text_end_insert = p2b(x2, y2)
rescue ArgumentError => e
raise ArgumentError,
"second position (#{x1},#{y1}) is invalid, " +
"reason=#{e.message}"
end
b1 = text_begin_line
w1 = text_begin_insert - text_begin_line
b2 = text_end_insert
w2 = text_end_line - text_end_insert
text = @text[b1, w1] + utf8_str + @text[b2, w2]
b3 = text_begin_insert
w3 = text_end_insert - text_begin_insert
bytes = text.map{|str| str.size}
if text.empty? or
(y2 == @bytes.size-1 and w2 == 0 and utf8_str =~ /\n\z/)
bytes << 0
end
bytes_w = 1+y2-y1
notify(:before, x1, y1, x2, y2, nil, nil)
@text[b3, w3] = utf8_str
@bytes[y1, bytes_w] = bytes
newx2, newy2 = b2p(b3+utf8_str.size)
notify(:after, x1, y1, x2, y2, newx2, newy2)
end
def notify(notify_type, x1, y1, s_x2, s_y2, d_x2, d_y2)
@notify_info.event = notify_type
@notify_info.x1 = x1
@notify_info.y1 = y1
@notify_info.source_x2 = s_x2
@notify_info.source_y2 = s_y2
@notify_info.dest_x2 = d_x2
@notify_info.dest_y2 = d_y2
@observers.each do |obs|
obs.model_update(self, @notify_info)
end
end
private :notify
def line(y)
w = @bytes[y]
b = p2b(0, y)
@text[b, w]
end
def glyphs(y)
line(y).unpack('U*')
end
# replace everything
def load(utf8_str)
y2 = @bytes.size-1
x2 = glyphs(y2).size
replace(0, 0, x2, y2, utf8_str)
end
def array_of_bytes
@bytes.map
end
def check_integrity
errors = []
# ensure that the number of bytes is in sync
bytes = array_of_bytes.inject(0) {|a, b| a + b}
ts = @text.size
if bytes != ts
errors << "mismatch bytes=#{bytes}, text.size=#{ts}"
end
# all lines should be valid UTF-8 encoded
# all lines (except the last line) should end with newline
n = 0
ary = array_of_bytes
ary.pop
ary.each_with_index do |b, i|
text = @text[n, b]
break if text == nil
if text =~ /[^\n]\z/
errors << "missing newline on line ##{i}"
end
if text =~ /\n(?!\z)/
errors << "newline in the middle of the line ##{i}"
end
begin
text.unpack("U*")
rescue ArgumentError
errors << "malformed UTF-8 in line ##{i}"
end
n += b
end
begin
@text.unpack("U*")
rescue ArgumentError
errors << "malformed UTF-8 somewhere (maybe on last line)"
end
return if errors.empty?
raise IntegrityError, errors.join("\n")
end
end
end # module Model
module View
DIRTY_NONE = 0
DIRTY_CURSOR = 1
DIRTY_ALL = 0xff
class Line
def initialize
@folded_lines = 0
@lexer_state = 0
@bookmark = false
@dirty = true
end
attr_reader :lexer_state
attr_accessor :dirty, :folded_lines, :bookmark
end
class Base
include Helpers
def initialize(model)
raise TypeError unless model.kind_of?(Model::Caretaker)
@model = model
@canvas = nil
@lexer = nil
@lines = []
@dirty = DIRTY_ALL
@scroll_x, @scroll_y = 0, 0
@cursor_x, @cursor_y = 0, 0
@width, @height = 5, 5
@sel_x, @sel_y = 0, 0
@sel_mode = false
@search_pattern = ''
@search_results = nil
sync_lines
end
attr_reader :model, :canvas, :lexer, :lines, :dirty
attr_reader :scroll_x, :scroll_y, :cursor_x, :cursor_y
attr_reader :sel_x, :sel_y, :sel_mode
attr_reader :width, :height
def sync_lines
@lines = @model.bytes.map { Line.new }
end
def model_update(model, info)
if info.event == :before
@old_p = xy2p(@cursor_x, @cursor_y)
#$logger.info "view old_p=#{@old_p}"
return
end
return if info.event != :after
if @cursor_y > info.source_y2
@cursor_y += info.dest_y2 - info.source_y2
elsif @cursor_y >= info.y1
is_before = ((@cursor_y == info.y1) and
(@old_p < info.x1))
is_after = ((@cursor_y == info.source_y2) and
(@old_p >= info.source_x2))
case
when is_before
# do nothing
when is_after
@old_p += info.dest_x2 - info.source_x2
@cursor_y += info.dest_y2 - info.source_y2
@cursor_x = py2x(@old_p, @cursor_y)
else
@cursor_y = info.y1
@cursor_x = py2x(info.x1, @cursor_y)
end
end
# flag affected lines as dirty
sy = info.source_y2
dy = info.dest_y2
n = dy - sy
if n > 0
n.times { @lines.insert(sy, Line.new) }
else
@lines.slice!(dy, -n)
end
info.y1.upto([sy, dy].min) do |i|
@lines[i].dirty = true
end
@search_results = nil # clear search results
end
def canvas=(can)
raise TypeError unless can == nil or can.kind_of?(Canvas::Base)
@canvas = can
end
def lexer=(lex)
raise TypeError unless lex == nil or lex.kind_of?(Lexer::Base)
@lexer = lex
end
def update
#$logger.info "view update, " +
# "scroll=#{@scroll_x},#{@scroll_y} " +
# "cursor=#{@cursor_x},#{@cursor_y} " +
# "size=#{@width},#{@height}"
return unless @canvas
@canvas.reset_counters
if @lexer
@lexer.reset_counters
@lexer.resize(@height*5)
end
vis = visible
found_i = nil
if @scroll_y >= 0
vis.each_with_index do |y, i|
if y >= @scroll_y
found_i = i
break
end
end
else
found_i = @scroll_y
end
@canvas.scroll_x = @scroll_x
cy = nil
0.upto(@height-1) do |y|
fragment = nil
ay = nil
options = 0
render_ay = nil
if found_i and (found_i + y).between?(0, vis.size-1)
ay = vis[found_i + y]
end
if @cursor_y == ay
cy = y
end
pens = nil
if ay and ay.between?(0, @model.bytes.size-1)
b = @model.p2b(0, ay)
w = @model.bytes[ay]
fragment = @model.text[b, w]
options |= 1 if @lines[ay].bookmark
options |= 2 if @lines[ay].folded_lines > 0
render_ay = ay
pens = @lexer.colorize(ay) if @lexer
end
@canvas.render_row(y, fragment, render_ay, pens, options)
end
@canvas.cursor_show(@cursor_x, cy) if cy
@canvas.refresh
msg = ""
if @lexer
msg = " lexer=#{@lexer.status}"
end
$logger.info "update: " +
"scroll=#{@scroll_x},#{@scroll_y} " +
"cursor=#{@cursor_x},#{@cursor_y} " +
"size=#{@width},#{@height} " +
"canvas=#{@canvas.count_hit},#{@canvas.count_miss}" + msg
end
def update_cursor
return unless @canvas
vis = visible
found_i = nil
if @scroll_y >= 0
vis.each_with_index do |y, i|
if y >= @scroll_y
found_i = i
break
end
end
else
found_i = @scroll_y
end
@canvas.scroll_x = @scroll_x
cy = nil
0.upto(@height-1) do |y|
ay = nil
if found_i and (found_i + y).between?(0, vis.size-1)
ay = vis[found_i + y]
end
if @cursor_y == ay
cy = y
end
end
@canvas.cursor_show(@cursor_x, cy)
@canvas.refresh
end
# NOTE: there is intentionally no check for if y is
# inside the buffer.. because we want to be able to
# scroll outside the buffer.
def scroll_y=(y)
check_integer(y)
@scroll_y = y
end
def scroll_x=(x)
check_integer(x)
@scroll_x = x
end
# purpose:
# convert from visible y coordinates to absolute y coordinates.
def vy2ay(vy)
check_integer(vy)
vis = visible
unless vy.between?(0, vis.size-1)
raise ArgumentError, "#{vy} is outside 0..#{vis.size-1}"
end
vis[vy]
end
# purpose:
# convert from absolute y coordinates to visible y coordinates.
#
# in case the specified y coordinate are not-visible
# the it floors the y coordinate to the nearest visible.
def ay2vy(ay)
check_integer(ay)
raise ArgumentError unless ay.between?(0, lines.size-1)
vis = visible
vis.each_with_index do |y, i|
fl = @lines[y].folded_lines
return i if ay.between?(y, y+fl)
end
raise 'should not happen'
end
def cursor_y=(y)
check_integer(y)
raise ArgumentError unless y.between?(0, @lines.size-1)
return if y == @cursor_y
@cursor_y = y
@dirty |= DIRTY_CURSOR
end
def cursor_x=(x)
check_integer(x)
raise ArgumentError if x < 0
@cursor_x = x
end
def cursor
[@cursor_x, @cursor_y]
end
def scroll
[@scroll_x, @scroll_y]
end
def size
[@width, @height]
end
def resize(width, height)
check_integer(width)
check_integer(height)
raise ArgumentError, "width must be positive" if width < 1
raise ArgumentError, "height must be positive" if height < 1
$logger.info "view resize from #{@width}x#{@height} " +
"to #{width}x#{height}"
@width, @height = width, height
end
# determine how wide the glyph are: 1=halfwidth, 2=fullwidth.
def measure_width(x, glyph)
return 1 unless @canvas
return 1 unless @canvas.respond_to?(:measure_width)
w = @canvas.measure_width(x, glyph)
return w if glyph == 9
return 1 if w != 1 and w != 2
w
end
# translate from canvas coordinates to buffer coordinates
def xy2p(x, y)
sx = 0
glyphs = @model.glyphs(y)
glyphs.each_with_index do |glyph, i|
return i if sx >= x or glyph == 10
sx += measure_width(sx, glyph)
end
glyphs.size
end
# translate from buffer coordinates to canvas coordinates
def py2x(p, y)
sx = 0
@model.glyphs(y).each_with_index do |glyph, i|
return sx if i >= p or glyph == 10
sx += measure_width(sx, glyph)
end
sx
end
# convert from visual-x, abs-y to byte
def vxay2b(x, y)
@model.p2b(xy2p(x, y), y)
end
# convert from byte to visual-x, abs-y
def b2vxay(b)
px, y = @model.b2p(b)
x = py2x(px, y)
[x, y]
end
# get list of folding levels
def folds
@lines.map{|l| l.folded_lines}
end
# get list of visible lines
def visible
res = []
i = 0
while i < @lines.size
res << i
i += @lines[i].folded_lines + 1
end
res
end
def check_integrity
errors = []
if @lines.size < 1
errors << "the number of lines must be 1 or greater"
end
if @dirty & DIRTY_CURSOR == 0
unless @scroll_y.between?(0, @lines.size-1)
errors << "scrolled over the edge, scroll_y=#{@scroll_y}"
end
end
unless @cursor_y.between?(0, @lines.size-1)
errors << "cursor over the edge, cursor_y=#{@cursor_y}"
end
return if errors.empty?
raise IntegrityError, errors.join("\n")
end
end
class Caretaker < Base
def scroll_to_cursor
if @cursor_x < @scroll_x
@scroll_x = @cursor_x
end
if @cursor_x >= @scroll_x + @width
@scroll_x = @cursor_x + 1 - @width
end
if @cursor_y < @scroll_y
@scroll_y = @cursor_y
end
if @cursor_y >= @scroll_y
h1 = @height - 1
bot = ay2vy(@scroll_y) + h1
cvy = ay2vy(@cursor_y)
if cvy > bot
say = vy2ay(bot)
if @cursor_y > say
newsvy = [cvy - h1, 0].max
@scroll_y = vy2ay(newsvy)
end
end
end
end
def insert(utf8_string)
ary = utf8_string.unpack("U*")
#raise ArgumentError, 'supply only one letter' if ary.size != 1
cx, cy = cursor
$logger.info "view operation insert " +
"x=#{cx} y=#{cy} text=#{utf8_string.inspect}"
p = xy2p(cx, cy)
@model.replace(p, cy, p, cy, utf8_string)
end
def edit_breakline
b = @model.p2b(0, @cursor_y)
w = @model.bytes[@cursor_y]
istr = @model.text[b, w].match(/\A\s*/).to_s
cb = vxay2b(@cursor_x, @cursor_y)
if b + istr.size >= cb
cx, cy = @cursor_x, @cursor_y
@model.replace(0, cy, 0, cy, "\n")
@cursor_x, @cursor_y = cx, (cy+1)
return
end
rem = b + istr.size - cb
if rem >= 0
cx, cy = @cursor_x, @cursor_y
@model.replace(0, cy, istr.size, cy, "\n" + istr)
@cursor_x, @cursor_y = cx, (cy+1)
return
end
insert("\n" + istr)
end
def delete_left
cx, cy = cursor
$logger.info "view operation backspace x=#{cx} y=#{cy}"
return if cy == 0 and cx == 0
p = xy2p(cx, cy)
if p == 0
x = @model.glyphs(cy-1).size-1
@model.replace(x, cy-1, 0, cy, '')
return
end
@model.replace(p-1, cy, p, cy, '')
end
def delete_right
cx, cy = cursor
$logger.info "view operation backspace x=#{cx} y=#{cy}"
pos = xy2p(cx, cy)
x = @model.glyphs(cy).size
if cy+1 < @model.bytes.size and pos >= x-1
@model.replace(x-1, cy, 0, cy+1, '')
return
end
if cy+1 >= @model.bytes.size and pos >= x
return # reached end of buffer.. nothing to do
end
@model.replace(pos, cy, pos+1, cy, '')
end
def move_to_lineend
x = 0
@model.glyphs(@cursor_y).each do |glyph|
break if glyph == 10
x += measure_width(x, glyph)
end
@cursor_x = x
end
def move_to_linebegin(smart=true)
unless smart
@cursor_x = 0
return
end
cx = @cursor_x
b1 = vxay2b(0, @cursor_y)
b2 = vxay2b(@cursor_x, @cursor_y)
move_to_lineend
b3 = vxay2b(@cursor_x, @cursor_y)
text = @model.text[b1, b3-b1]
m = text.match(/\A\s*/)
if m.to_s.size == text.size
b = @model.p2b(0, @cursor_y)
(@cursor_y-1).downto(0) do |y|
w = @model.bytes[y]
b -= w
m = @model.text[b, w].match(/\A\s*(?=\S)/u)
next unless m
rx, ry = b2vxay(b + m.to_s.size)
@cursor_x = (cx != rx) ? rx : 0
return
end
@cursor_x = 0
return
end
br = m.end(0) + b1
if b2 != br
@cursor_x, dummy = b2vxay(br)
return
end
@cursor_x = 0
end
def move_pageup
$logger.info "view operation pageup"
scroll_vy = ay2vy(@scroll_y)
cursor_vy = ay2vy(@cursor_y)
h1 = @height - 1
if scroll_vy == 0
@cursor_y = 0
elsif scroll_vy - h1 >= 0
@scroll_y = vy2ay(scroll_vy - h1)
@cursor_y = vy2ay(cursor_vy - h1)
else
@scroll_y = 0
@cursor_y = vy2ay(cursor_vy - scroll_vy)
end
end
def move_pagedown
$logger.info "view operation pagedown"
scroll_vy = ay2vy(@scroll_y)
cursor_vy = ay2vy(@cursor_y)
last_vy = ay2vy(@lines.size-1)
h1 = @height - 1
if scroll_vy + h1 >= last_vy
@cursor_y = vy2ay(last_vy)
elsif cursor_vy + h1 <= last_vy
@scroll_y = vy2ay(scroll_vy + h1)
@cursor_y = vy2ay(cursor_vy + h1)
else
@cursor_y = vy2ay(last_vy - h1 + cursor_vy - scroll_vy)
@scroll_y = vy2ay(last_vy - h1)
end
end
def move_top
$logger.info "view operation top"
@cursor_y = 0
end
def move_bottom
$logger.info "view operation bottom"
@cursor_y = visible.last
end
def move_wordleft
$logger.info "view operation wordleft"
b1 = vxay2b(0, @cursor_y)
b2 = vxay2b(@cursor_x, @cursor_y)
text = @model.text[b1, b2-b1]
m = /(?: \s+ | \w+ | . )\z/ux.match(text)
return false unless m
@cursor_x, @cursor_y = b2vxay(m.begin(0) + b1)
true
end
def move_wordright
$logger.info "view operation wordright"
oldx = @cursor_x
b1 = vxay2b(@cursor_x, @cursor_y)
move_to_lineend
b2 = vxay2b(@cursor_x, @cursor_y)
@cursor_x = oldx
text = @model.text[b1, b2-b1]
m = /\A(?: \s+ | \w+ | . )/ux.match(text)
return false unless m
@cursor_x, @cursor_y = b2vxay(m.end(0) + b1)
true
end
def selection_begin
$logger.info "view operation selection begin"
@sel_x, @sel_y = @cursor_x, @cursor_y
@sel_mode = true
end
def selection_end
$logger.info "view operation selection end"
@sel_mode = false
end
def selection
return '' unless @sel_mode
sb = vxay2b(@sel_x, @sel_y)
cb = vxay2b(@cursor_x, @cursor_y)
min, max = [sb, cb].sort
txt = @model.text[min, max-min]
#$logger.info "text: #{txt.inspect}"
txt
end
def selection_erase
$logger.info "view operation selection erase"
return unless @sel_mode
@sel_mode = false
sb = vxay2b(@sel_x, @sel_y)
cb = vxay2b(@cursor_x, @cursor_y)
min, max = [sb, cb].sort
ax, ay = @model.b2p(min)
bx, by = @model.b2p(max)
@model.replace(ax, ay, bx, by, '')
end
def selection_to_fold
return unless @sel_mode
@sel_mode = false
min, max = [[@sel_y, @sel_x], [@cursor_y, @cursor_x]].sort
miny, minx = min
maxy, maxx = max
collapse(miny, maxy - ((maxx == 0) ? 1 : 0))
@cursor_y = miny
end
def toggle_bookmark
$logger.info "view operation toggle bookmark"
l = @lines[@cursor_y]
l.bookmark = !l.bookmark
end
def goto_prev_bookmark
$logger.info "view operation goto prev bookmark"
before = []
after = []
@lines.each_with_index do |l, y|
if l.bookmark
if y < @cursor_y
before << y
else
after << y
end
end
end
res = before.reverse + after.reverse
@cursor_y = res[0] if res.size > 0
end
def goto_next_bookmark
$logger.info "view operation goto next bookmark"
before = []
after = []
@lines.each_with_index do |l, y|
if l.bookmark
if y <= @cursor_y
before << y
else
after << y
end
end
end
res = after + before
@cursor_y = res[0] if res.size > 0
end
def search_init(pattern)
$logger.info "view search init, pattern=#{pattern.inspect}"
unless pattern.kind_of?(String) or pattern.kind_of?(Regexp)
raise TypeError, "must be either String or Regexp"
end
@search_pattern = pattern
@search_results = nil
search_sync
@search_results.size
end
def search_sync
return if @search_results
@search_results = []
@model.text.scan(@search_pattern) do
@search_results << [
Regexp.last_match.begin(0), Regexp.last_match.end(0)]
end
$logger.info "view search_sync, results = #{@search_results.size}"
@search_results.size
end
def search_down
search_sync
$logger.info "view search down"
cb = vxay2b(@cursor_x, @cursor_y)
@search_results.each do |b1, b2|
if b1 > cb
@sel_x, @sel_y = b2vxay(b1)
@cursor_x, @cursor_y = b2vxay(b2)
@sel_mode = true
return true
end
end
false
end
def search_up
search_sync
$logger.info "view search up"
cb = vxay2b(@cursor_x, @cursor_y)
@search_results.reverse_each do |b1, b2|
if b1 < cb
@cursor_x, @cursor_y = b2vxay(b1)
@sel_x, @sel_y = b2vxay(b2)
@sel_mode = true
return true
end
end
false
end
def collapse(y1, y2)
check_integer(y1)
check_integer(y2)
if y1 < 0 or y2 >= @lines.size
raise ArgumentError, "invalid line number"
end
if y2 <= y1
raise ArgumentError,
"second argument must be greater than first argument"
end
@lines[y1].folded_lines = y2-y1
end
def expand
@lines[@cursor_y].folded_lines = 0
end
def move_to_prev_visible_line
visible.reverse_each do |y|
if @cursor_y > y
@cursor_y = y
return
end
end
end
def move_to_next_visible_line
visible.each do |y|
if @cursor_y < y
@cursor_y = y
return
end
end
end
end
end # module View
module Canvas
class Base
def initialize
reset_counters
@view = nil
@scroll_x = 0
end
attr_reader :view
attr_accessor :scroll_x
attr_reader :count_hit, :count_miss
def view=(v)
raise TypeError unless v == nil or v.kind_of?(View::Caretaker)
@view = v
end
def render_row(y, utf8_string, render_ay, pens, options)
raise NoMethodError, "derived class should implement this method"
end
def width
raise NoMethodError, "derived class should implement this method"
end
def height
raise NoMethodError, "derived class should implement this method"
end
def cursor_show(x, y)
raise NoMethodError, "derived class should implement this method"
end
def reset_counters
@count_hit = 0
@count_miss = 0
end
end
end # module Canvas
module Lexer
# purpose:
# remember the most recently used pen-lines
class LRU
def initialize
@capacity = 1
@pens = {}
@used = []
end
attr_reader :capacity, :used, :pens
def resize(n)
raise ArgumentError if n < 0
@capacity = n
wipe
end
def wipe
while @used.size > @capacity
@pens.delete(@used.pop)
end
end
private :wipe
def size
@used.size
end
def store(key, value)
@used.delete(key)
@used.unshift(key)
@pens[key] = value
wipe
end
alias_method('[]=', :store)
def has_key?(key)
@pens.has_key?(key)
end
# note: remember to .clone the data you get from .load
def load(key)
return nil unless has_key?(key)
@used.delete(key)
@used.unshift(key)
@pens[key]
end
alias_method('[]', :load)
def delete(key)
@used.delete(key)
@pens.delete(key)
end
def displace(y, n)
displaced = {}
@used.each_with_index do |key, i|
if key >= y
@used[i] = key+n
displaced[key+n] = @pens.delete(key)
end
end
@pens.merge!(displaced)
end
alias :insert :displace
private :displace
public :insert
def remove_in_range(y, n)
ary = []
@used.each {|key| ary << key if key >= y and key < y+n }
ary.each {|key| delete(key) }
end
private :remove_in_range
def remove(y, n)
remove_in_range(y, n)
displace(y+n, -n)
end
end
class Base
def initialize(model)
@model = model
end
def resize(n)
raise "derived class must overload"
end
def model_update(model, info)
raise "derived class must overload"
end
def colorize(ay)
raise "derived class must overload"
end
def status
"-none-"
end
end
class Simple < Base
def initialize(model)
erase
super(model)
end
attr_reader :lru, :count_sync_hit, :count_sync_miss
attr_reader :count_color_hit, :count_color_miss, :dirty_lines
def reset_counters
@count_sync_hit = 0
@count_sync_miss = 0
@count_color_hit = 0
@count_color_miss = 0
end
def count_hit
@count_sync_hit + @count_color_hit
end
def count_miss
@count_sync_miss + @count_color_miss
end
def erase
reset_counters
@dirty_lines = []
@right_states = []
@left = 0
@right = 0
@pens = []
@lru = LRU.new
end
def status
"#{@count_sync_hit}+#{@count_color_hit}/#{@count_sync_miss}+#{@count_color_miss}"
end
def resize(n)
@lru.resize(n)
end
def dirty(y)
#puts "dirty #{y}" if $dbg
@dirty_lines[y] = true if y < @dirty_lines.size
@lru.delete(y)
end
def model_update(model, info)
return if info.event == :before
return if info.event != :after
sy = info.source_y2
dy = info.dest_y2
n = dy - sy
if n > 0
#puts "model_update: insert n=#{n}, dy=#{dy}" if $dbg
dirty(sy) # dirtify the line before splitting
n.times do
@right_states.insert(sy, nil)
@dirty_lines.insert(sy, true)
end
@lru.insert(sy, n) # displace all cached pens
else
#puts "model_update: removing n=#{n}, dy=#{dy}" if $dbg
@right_states.slice!(dy, -n)
@dirty_lines.slice!(dy, -n)
@lru.remove(dy, -n) # displace all cached pens
end
info.y1.upto([sy, dy].min) {|i| dirty(i) }
end
def set_right_state(y, state)
propagate = false
rs = @right_states
if y < @right_states.size
old = @right_states[y]
if state != old
propagate = true
#if $dbg
# puts "propagate #{y}->#{y+1}, because #{state.inspect} is " +
# "distinct from #{old.inspect}"
#end
end
elsif y >= @right_states.size
propagate = true
#puts "propagate #{y}->#{y+1}, because y >= size" if $dbg
end
dirty(y)
(y-@right_states.size).times { @right_states << nil }
(y-@dirty_lines.size).times { @dirty_lines << true }
@right_states[y] = state
@dirty_lines[y] = false
#puts "rs=#{@right_states.inspect} prop=#{propagate}" if $dbg
dirty(y+1) if propagate
#puts "rs=#{@right_states.inspect}" if $dbg
end
def sync_states(number_of_states)
0.upto(number_of_states) do |i|
if i < @dirty_lines.size and i > @right_states.size
raise "should not happen, i=#{i} " +
"rs.size=#{@right_states.size} dl=#{@dirty_lines.size}"
end
if i < @dirty_lines.size and @dirty_lines[i] == false
@count_sync_hit += 1
next
end
@count_sync_miss += 1
@left = (i == 0) ? 0 : @right_states[i - 1]
lex_line(@model.line(i))
set_right_state(i, @right)
end
end
def colorize(line_number)
#puts "line #{line_number}"
sync_states(line_number-1) # TODO: move outside renderloop
if @lru.has_key?(line_number)
@count_color_hit += 1
return @lru[line_number]
end
@count_color_miss += 1
i = line_number
@left = (i == 0) ? 0 : @right_states[i - 1]
lex_line(@model.line(i))
set_right_state(i, @right)
@lru[i] = @pens
@pens
end
end
end # module Lexer
end # module AEditor |
class Support::Schools::HeadteacherController < Support::BaseController
before_action :set_school
attr_reader :form, :school
def edit
@form = Support::School::ChangeHeadteacherForm.new(school: school, **contact_details)
end
def update
@form = Support::School::ChangeHeadteacherForm.new(school: school, **headteacher_params)
if form.save
flash[:success] = success_message
redirect_to support_school_path(school)
else
render(:edit)
end
end
private
def contact_details
contact = school.headteacher_contact || school.contacts.first
{
email_address: contact&.email_address,
full_name: contact&.full_name,
id: contact&.id,
phone_number: contact&.phone_number,
role: contact&.role,
title: contact&.title,
}
end
def success_message
"#{school.name}'s headteacher details updated"
end
# Filters
def set_school
@school = School.gias_status_open.where_urn_or_ukprn_or_provision_urn(params[:school_urn]).first
authorize school, :update_headteacher?
end
# Params
def headteacher_params
@headteacher_params ||= params.require(:support_school_change_headteacher_form).permit(
:email_address,
:full_name,
:id,
:phone_number,
:title,
).to_h
end
end
|
require 'open3'
require 'colorize'
require 'lock'
def sheepdog_ping(tag,r)
host = Socket.gethostname
ok = redis_ping(r,host)
errval = !ok
event = {
time: Time.new.to_s,
elapsed: 0,
user: ENV['USER'],
host: host, # sending host
command: 'sheepdog_ping.rb',
tag: tag,
stdout: "",
stderr: "",
status: 0,
err: "SUCCESS"
}
event
end
# Run a command and return an event
def run(tag, cmd, verbose=false)
starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
stdout = ""
tag = cmd.gsub(/[\s"']+/,"") if not tag
lockname = tag.gsub("/","-")+".sheepdog"
begin
if Lock.create(lockname) # this will wait for a lock to expire
print(cmd.green+"\n") if verbose
begin
stdout, stderr, status = Open3.capture3(cmd)
errval = status.exitstatus
rescue Errno::ENOENT
stderr = "Command not found"
err = "CMD_NOT_FOUND"
errval = 1
end
else
stderr = "Lock error"
err = "LOCKED"
errval = 1
end
ensure
Lock.release(lockname)
end
ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed = ending - starting
time = Time.now
# timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
timestamp = time.to_i
event = {
time: time.to_s,
elapsed: elapsed.round(),
user: ENV['USER'],
host: Socket.gethostname, # sending host
command: cmd,
tag: tag,
stdout: stdout,
stderr: stderr,
status: errval
}
if errval != 0
event[:err] = "FAIL"
else
event[:err] = "SUCCESS"
end
event
end
|
class Reminder < ApplicationRecord
include ApplicationHelper
belongs_to :user
before_save :send_notification_reminder
validates :title, uniqueness: true
validates :description, uniqueness: true
def send_notification_reminder
registration_id = self.user.fcm_token
puts "starttttttt"
send_notification(registration_id, self.title, self.description, "reminder", self.user_id, nil)
puts "endddddd"
end
end
|
#Add remote data source and pull in stories from Reddit, Mashable and Digg.
# http://mashable.com/stories.json
#http://www.reddit.com/r/aww/.json
# These stories will also be upvoted based on our rules. No more user input!
# Pull the json, parse it and then make a new story hash out of each story(Title, Category, Upvotes)
# Add each story to an array and display your "Front page"
require 'pry'
require 'pry-byebug'
require 'rest-client'
require 'json'
#category base upvote multiplier
def cat_points(entry_upvotes, category)
default_votes = entry_upvotes
if category == "cats"
5 * default_votes
elsif category == "Watercooler"
10 * default_votes
else
default_votes
end
end
# #Reddit API ##########################################
#
# #Make the HTTP request:
# reddit_data = RestClient.get("http://www.reddit.com/.json")
#
# # parse the stuff we care about: response.body
# results = JSON.parse(reddit_data.body)
#
# #list of each entry
# entries = results["data"]["children"]
#
# #Iterate through each entry in entries and print out title, subject and upvotes
# entries.each do |entry|
# puts "Title: #{entry["data"]["title"]}\n Category: #{entry["data"]["subreddit"]}\n Upvotes: #{entry["data"]["upss"]}\n\n"
# end
#############################################################################
#Mashable API ##########################################
#Make the HTTP request:
mashable_data = RestClient.get("http://mashable.com/stories.json")
# parse the stuff we care about: response.body
results = JSON.parse(mashable_data.body)
#list of each entry
entries = results["new"]
#Iterate through each entry in entries and print out title, subject and upvotes
entries.each do |entry|
puts "Title: #{entry['title']}\n Category: #{entry["channel"]}\n Upvotes: #{cat_points(entry["shares"]["total"], entry["channel"])}"
end
|
module Nails
class Router
def clear()
@controller = nil
@method = nil
@route_table = []
end
def initialize()
clear
end
# A url in the router such as /user/:user_id/post/:post_id gets converted to a regular expression
# where each param gets converted to a named group
def url_reg_exp(url)
'\A' + url.gsub(/:(\w+)/){"(?<#{$1}>\\d+)" } + '\z'
end
def add_route(verb, url, options)
controller, method = options[:to].to_s.split('#')
@route_table += [[verb, url_reg_exp(url), controller, method]]
end
def get(url, options)
add_route("get", url, options)
end
def post(url, options)
controller, method = options[:to].to_s.split('#')
@route_table += [["post", url_reg_exp(url), controller, method]]
end
# This is the magic behind routes.rb, and it is somewhat poorly named, but mirrors the name in the Rails Router
# so that in an application's routes.rb file you can write:
# Nails.app.router.draw do
# get "/", to: "static#home"
# end
#
# which again mirrors a Rails app.
#
# For those unfamiliar with instance_exec, it takes the block given in the routes.rb file and
# executes it as if it were the body of a method defined in this class
def draw(&block)
clear()
instance_exec(&block)
end
# Routes a url based on the @routing_table. We pass in the params because on a post request,
# there can already be a params hash but we still have to add relevant values from the url.
def route(url, method="get", params={})
method = method.downcase
# Would be nice if Ruby had an lchomp, or had a strip(char)
url = url.sub(/\A\//, '').chomp("/")
@route_table.each do |r|
if (method == r[0])
if (match = url.match(r[1]))
return [r[2], r[3], params.merge(params_from_match(match))]
elsif (url == '')
return [r[2], r[3], params]
end
end
end
puts "route: #{url} not found"
nil
end
def params_from_match(match)
params = {}
match.names.each do |name|
params[name] = match[name]
end
params
end
end # class Router
end # module Nails |
class PostSearchResultsController < ApplicationController
def show
if params[:q]
keywords = params[:q].split(/[\p{blank}\s]+/)
groupings = keywords.reduce({}) do |acc, elem|
acc.merge(elem => { title_or_body_or_tags_name_cont: elem })
end
posts = Post.ransack(combinator: 'and', groupings: groupings).result(distinct: true)
posts_with_username = posts.order(created_at: :desc).with_user
render_for_react(
props: {
posts: posts_with_username,
title: keywords.join(' '),
}
)
else
render_for_react
end
end
end
|
require File.dirname(__FILE__) + '/../spec_helper'
describe 'Event' do
describe 'when triggered' do
it 'should create an instance' do
lambda { RandomEvent.trigger }.should change(RandomEvent, :count).from(0).to(1)
end
describe 'with a source' do
it 'should create an instance with the specified source attribute' do
source = Comment.make
RandomEvent.trigger :source => source
RandomEvent.first.source.should == source
end
end
describe 'with extra attributes' do
it 'should serialize the extra attributes as a hash called "data"' do
source = Comment.make
RandomEvent.trigger :source => source, :some_numbers => [2, 4, 6, 8], :a_string => 'radu was here'
RandomEvent.first.data.should == {
:some_numbers => [2, 4, 6, 8],
:a_string => 'radu was here'
}
end
end
describe 'without extra attributes' do
it 'should create an instance with a nil data attribute' do
RandomEvent.trigger :source => Comment.make
RandomEvent.first.data.should be_nil
end
end
describe 'with a source_type defined on the Event' do
it 'should be invalid if the source\'s class doesn\'t match the specified source_type' do
e = EventWithCommentSourceType.trigger :source => User.make
e.errors.on(:source).should include('must be an instance of Comment')
end
it 'should be valid if the source\'s class matches the specified source_type' do
e = EventWithCommentSourceType.trigger :source => Comment.make
e.should be_valid
end
end
end
end
|
class QuestionsController < ApplicationController
def index
@questions = Question.order(created_at: :desc)
end
def show
@question = Question.find(params[:id])
@body = Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(@question.body)
@answer = Answer.new
@answers = Answer.where(question_id: params[:id]).order(best_answer: :desc, created_at: :asc)
end
def new
if user_signed_in?
@question = Question.new
else
flash[:notice] = "You need to be signed in to ask a question."
redirect_to new_user_session_path
end
end
def create
@question = Question.new(question_params)
unless user_signed_in?
flash[:notice] = "You need to be signed in to ask a question."
redirect_to new_user_session_path
end
if @question.save
flash[:notice] = "Your question has been added."
redirect_to questions_path
else
flash[:error] = @question.errors.full_messages.join(". ")
render :new
end
end
def edit
if user_signed_in?
@question = Question.find(params[:id])
else
flash[:notice] = "You need to be signed in to edit a question."
redirect_to new_user_session_path
end
if @question.belongs_to_user?(@user)
render 'edit'
else
flash[:notice] = "You don't have permission to edit this question."
redirect_to question_path(@question.id)
end
end
def update
unless user_signed_in?
flash[:notice] = "You need to be signed in to ask a question."
redirect_to new_user_session_path
end
@question = Question.find(params[:id])
if @question.update(question_params) && @question.belongs_to_user?(@user)
flash[:notice] = "The question has been edited."
redirect_to question_path(id: @question.id)
else
flash[:error] = @question.errors.full_messages.join(". ")
render :new
end
end
def destroy
@question = Question.find(params[:id])
@user = current_user.id
if @question.belongs_to_user?(@user)
@question.delete
@question.answers.delete
flash[:notice] = "The question has been deleted."
redirect_to questions_path
else
flash[:error] = "You don't have permission to delete this question."
redirect_to question_path(@question.id)
end
end
protected
def question_params
params.require(:question).permit(:title, :body)
end
end
|
module Awspec::Type
class Glue < ResourceBase
def initialize(name)
super
@display_name = name
end
def resource_via_client
@resource_via_client ||= get_catalog(@display_name)
end
def id
@id ||= @display_name
end
def has_catalog?(catalog)
check_existence
get_catalog(catalog)
end
def has_get_databases_permission?()
get_databases(id)
end
def has_create_database_permission?(database:)
create_database(id, database)
end
def has_delete_database_permission?(database:)
delete_database(id, database)
end
def has_get_database_permission?(database:)
get_database(id, database)
end
def has_get_tables_permission?(database:)
get_tables(id, database)
end
def has_get_table_permission?(database:, table:)
get_table(id, database, table)
end
def has_create_table_permission?(database:, table:, description:, columns:, partition_keys:)
create_table(id, database, table, description, columns, partition_keys)
end
def has_update_table_permission?(database:, table:, description:, columns:, partition_keys:)
update_table_description(id, database, table, description, columns, partition_keys)
end
def has_delete_table_permission?(database:, table:)
delete_table(id, database, table)
end
end
end
|
require 'optparse'
require 'lol_dba/sql_generator'
module LolDba
class CLI
class << self
def start
options = {}
OptionParser.new do |opts|
opts.on('-d', '--debug', 'Show stack traces when an error occurs.') { |v| options[:debug] = v }
opts.on_tail("-v", "--version", "Show version") do
puts LolDba::VERSION
exit
end
end.parse!
new(Dir.pwd, options).start
end
end
def initialize(path, options)
@path, @options = path, options
end
def start
load_application
arg = ARGV.first
if arg =~ /db:find_indexes/
LolDba.simple_migration
elsif arg !~ /\[/
LolDba::SqlGenerator.generate("all")
else
which = arg.match(/.*\[(.*)\].*/).captures[0]
LolDba::SqlGenerator.generate(which)
end
rescue Exception => e
$stderr.puts "Failed: #{e.class}: #{e.message}" if @options[:debug]
$stderr.puts e.backtrace.map { |t| " from #{t}" } if @options[:debug]
end
protected
# Tks to https://github.com/voormedia/rails-erd/blob/master/lib/rails_erd/cli.rb
def load_application
require "#{@path}/config/environment"
end
end
end
|
# => Author:: DanAurea
# => Version:: 0.1
# => Copyright:: © 2016
# => License:: Distributes under the same terms as Ruby
##
## Controls the data flow into an item object and updates the view whenever data changes.
##
class Controller
##
## Initialisation
##
def initialize ()
@title = "MyApp"
@width = 900
@height = 500
@borderWidth = 0
@resizable = true
@position = "CENTER"
## Create content variable sent from controller to view called
@content = Hash.new(0)
if Core::DEBUG
puts "Main controller instanciation"
end
end
##
## Invoke methods when inherited
##
## @param subclass The subclass
##
## @return Itself
##
def self.inherited(subclass)
super
return self
end
##
## Loads a file.
##
## @param filePath The file path
## @param debugInfo The debug information
##
## @return Itself
##
def loadFile(filePath, debugInfo)
begin
require filePath
rescue LoadError
if Core::DEBUG
puts debugInfo + ": " + File.basename(filePath) + " not found in " + Core::ROOT + debugInfo.downcase
end
exit(1)
end
return self
end
##
## Render view called by controller
##
## @param name The view to render
##
def render(name, **args)
if Core::DEBUG
puts "Loading view..."
end
name = Core::VIEW + name
filePath = Core::viewPath(name)
self.loadFile(filePath, "View")
## Will retrieve class constant name for dynamic instanciation
viewName = Object.const_get(name)
view = viewName.new()
## Force children controller and view
## to run parent initialize if overriden.
Core::forceParentInit(self)
Core::forceParentInit(view)
## Set values sent from previous view in
## content of current view.
args.each{
|key, value|
@content[key.to_s] = value
}
self.setProperties(view)
## Collect content from controller and send it to view
view.controller = self
view.controller.run()
view.content = @content.clone()
## Refer controller methods in view for easier
## call.
self.class.instance_methods(false).each() do |method|
if !view.class.method_defined?(method)
view.define_singleton_method(method) do |*arguments|
self.controller.send(method, *arguments)
end
end
end
## Will render view with content retrieved in controller
view.setInstanceVars()
view.run()
Fenetre::css(:priorite => "PRIORITY_APPLICATION")
## Display content builded in view with Gtk
view.window.show_all
end
##
## Sets the properties of window
##
def setProperties(view)
## Set window properties
view.headerBar.title = @title
view.window.set_titlebar (view.headerBar)
view.window.set_size_request(@width, @height)
view.window.border_width = @borderWidth
view.window.set_resizable(@resizable)
view.window.set_window_position(Object.const_get("Gtk::WindowPosition::" + @position))
end
##
## Loads a model.
##
## @param name The model to load
##
## @return Model instance
##
def loadModel(name)
filePath = Core::modelPath(name)
self.loadFile(filePath, "Model")
## Will retrieve class constant name for dynamic instanciation
modelName = Object.const_get(name)
## Make an only one instance of model (Singleton pattern)
## to ensure date integrity.
model = modelName.instance()
self.instance_variable_set("@" + name, model)
return model
end
## Invoke all method in controller for collecting contents to send on view.
##
## @return itself
##
def run()
if Core::DEBUG
raise "Controller #{self.class.name} can't collect content because run method is not redefined."
end
return self
end
end
|
require 'money'
require_relative './item_presenter.rb'
class ItemsPresenter
# The following has been added to resolve deprecation warnings
Money.rounding_mode = BigDecimal::ROUND_HALF_UP
Money.locale_backend = :i18n
I18n.locale = :en
def initialize(items)
@items = items
end
def show_all
header = <<-EOF
Products on sale:
| ID | Name | Price |
----------------------
EOF
rows = @items.map do |item|
<<-EOF
| #{item.id} | #{item.name} | #{ItemPresenter.new(item).format_price} |
EOF
end.reduce(:+)
footer = <<-EOF
When scanning an item, please use one of the IDs specified above.
EOF
header + rows + footer
end
end
|
class ChangeBaknIdToStockHolds < ActiveRecord::Migration[5.0]
def change
change_column(:stock_holds, :bank_id, :string, :limit => 50)
rename_column :stock_holds, :bank_id, :bank_name
end
end
|
class ChangeLastDoneFormatForChores < ActiveRecord::Migration
def self.up
change_table :chores do |t|
t.change :last_done, :date
end
end
def self.down
change_table :chores do |t|
t.change :last_done, :datetime
end
end
end
|
$:.unshift File.join(File.dirname(__FILE__), "..", "lib")
require 'pdf/merger'
describe PDF::Merger do
before(:each) do
@pdf = PDF::Merger.new
@pdf.add_file :text_field01, "test_template.pdf"
@pdf.add_file :text_field02, "test_template.pdf"
end
it "should create PDF document" do
@pdf.to_s.should_not be_nil
end
it "should save PDF document" do
@pdf.save_as "test_output.pdf"
File.exist?("test_output.pdf").should be_true
File.delete("test_output.pdf") # Comment this out to view the output
end
end
|
class User < ActiveRecord::Base
belongs_to :race
has_many :dependents
has_one :qualification
has_one :agency, through: :qualification
has_many :applications
has_many :dwellings, through: :applications
validates :email, :presence => true,
:uniqueness => true,
:format => { :with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
has_secure_password
after_initialize :create_masked_user_id
def create_masked_user_id
random_letters = ('a'..'z').to_a.shuffle[0,4].join
random_numbers = 10000 + Random.rand(100000 - 10000)
kind_of_agent = 'applicant'
masked_user_id = random_numbers.to_s + kind_of_agent + random_letters
self.masked_user_id = masked_user_id
self.save
end
def completed_profile?
qualification.present?
end
end |
json.array!(@breeders) do |breeder|
json.extract! breeder, :name, :address1, :address2, :city, :state, :zip, :phone, :website, :email
json.url breeder_url(breeder, format: :json)
end
|
require 'rails_helper'
RSpec.describe Referrer::User, type: :model do
before :each do
@user = Referrer::User.create!
end
before :each, with_main_app_user: true do
@main_app_user = User.create!
end
before :each, with_sources: true do
@session = @user.sessions.create!(active_from: 10.days.ago, active_until: 10.days.since)
@source_0 = @session.sources.create!(referrer: 'http://test.com', entry_point: 'http://dummy.com',
client_duplicate_id: 1, created_at: 7.days.ago)
@source_1 = @session.sources.create!(referrer: 'http://test.com', entry_point: 'http://dummy.com',
client_duplicate_id: 2, created_at: 5.days.ago)
@source_2 = @session.sources.create!(referrer: 'http://test.com', entry_point: 'http://dummy.com',
client_duplicate_id: 3, created_at: 2.days.ago)
end
describe 'token' do
it 'should be generated' do
expect(@user.token.length).to be > 0
end
end
describe 'link_with', with_main_app_user: true do
it 'should work' do
expect(@user.linked_with?(@main_app_user)).to eq(false)
@user.link_with(@main_app_user)
expect(@user.linked_with?(@main_app_user)).to eq(true)
end
end
describe 'link_with?', with_main_app_user: true do
it 'should return true' do
@user.users_main_app_users.create(main_app_user: @main_app_user)
expect(@user.users_main_app_users.size).to eq(1)
expect(@user.linked_with?(@main_app_user)).to eq(true)
end
it 'should return false' do
expect(@user.linked_with?(@main_app_user)).to eq(false)
end
end
describe 'linked_objects' do
it 'should return' do
expect(@user.linked_objects).to eq([])
@user.link_with(@main_app_user)
expect(@user.reload.linked_objects).to eq([@main_app_user])
end
it 'should not return' do
expect(@user.linked_objects).to eq([])
end
end
describe 'source_at(time)' do
it 'should return source', with_sources: true do
expect(@user.source_at(4.days.ago)).to eq(@source_1)
end
it 'should not return source due no suitable sources', with_sources: true do
expect(@session.source_at(8.days.ago)).to eq(nil)
end
it 'should not return source due no sessions' do
expect(@user.source_at(4.days.ago)).to eq(nil)
end
end
end
|
class ApplicationController < ActionController::Base
# protect_from_forgery with: :exception
def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authenticate_user!
redirect_to '/login' unless current_user
end
def current_bartender
@current_bartender ||= Bartender.find_by(id: session[:bartender_id]) if session[:bartender_id]
end
helper_method :current_bartender
def authenticate_bartender!
redirect_to '/bartender_login' unless current_bartender
end
end
|
=begin
識別子判定プログラム
compiler.rb
7061-0503 Ryosuke Takata
=end
# 判定用定数(識別子なら1)
EMPTY = 0
ID = "識別子"
# 各種変数
str = ""
token = ""
tokens = []
judges = []
# 区切り文字判定
def isseparater?(ch)
return true if ch.match(/\s|\W/)
return false
end
# ファイル入力
File.open('./test.c', 'r') do |file|
str = file.read
end
# トークン分割・識別子判定ループ
state = EMPTY
count = 0
str.each_char do |ch|
# トークン文字数カウント
count += 1
# トークン文字列
token.concat(ch)
# 最初の文字が英字の場合,識別子判定
if count == 1 and ch.match(/[a-z]/)
state = ID
end
# 区切り文字の場合,分割して追加する
if isseparater?(ch)
tokens << token.partition(/\s|\W/)
judges << state
judges << EMPTY if count != 1
# トークン初期化
token = ""
count = 0
# 識別子判定初期化
state = EMPTY
end
end
# 整形
tokens_adj = []
judges_adj = []
tokens.flatten!.delete("")
tokens.each_with_index do |token, i|
if token != "\n" and token != ' '
tokens_adj << tokens[i]
judges_adj << judges[i]
end
end
# 表示
tokens_adj.each_with_index do |token, i|
print token, "\t", judges_adj[i], "\n"
end
|
require 'test_helper'
class ProductsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@client = users(:client)
@admin = users(:admin)
end
test 'all can view products' do
get products_path, xhr: true
assert_response :success
end
test 'only admin can create product' do
perform_action_as @client do
post products_path, xhr: true, params: {:product => {:name => 'FishOil', :price => 9.99, :weight => 2.7, :detail => '', :category => 'health products'}}
assert_response :forbidden
end
perform_action_as @admin do
post products_path, xhr: true, params: {:product => {:name => 'FishOil', :price => 9.99, :weight => 2.7, :detail => '', :category => 'health products'}}
assert_response :success
end
end
test 'create new product through dashboard' do
perform_action_as @admin do
sz = Product.count
post products_path, params: {:product => {:name => 'FishOil', :price => 9.99, :weight => 2.7, :detail => '', :category => 'health products'}}, xhr: true
assert_response :success
assert_equal(sz+1, Product.count)
body = JSON.parse response.body
assert(body["product"])
end
end
test 'update product' do
perform_action_as @admin do
product = Product.first
put product_path(product.id), xhr: true, params: {:product => {:price => 19.99}}
assert_response :success
assert_equal(19.99, Product.find(product.id).price)
end
end
test 'delete product' do
sz = Product.count
perform_action_as @admin do
delete product_path(Product.first.id), xhr: true
end
assert_response :success
assert_equal(sz-1, Product.count)
end
end
|
# Raised when executing a SEC.
class Tem::SecExecError < StandardError
attr_reader :line_info
attr_reader :buffer_state, :key_state
attr_reader :trace
def initialize(secpack, tem_trace, buffer_state, key_state)
super 'SEC execution failed on the TEM'
if tem_trace
if tem_trace[:ip]
@ip_line_info = secpack.line_info_for_addr tem_trace[:ip]
@ip_label_info = secpack.label_info_for_addr tem_trace[:ip]
end
if tem_trace[:sp]
@sp_line_info = secpack.line_info_for_addr tem_trace[:sp]
end
end
@ip_line_info ||= [0, :unknown, []]
@ip_label_info ||= [0, :unknown]
@sp_line_info ||= [0, :unknown, []]
line_ip, atom, backtrace = *@ip_line_info
set_backtrace backtrace
@ip_atom = atom
@ip_label = @ip_label_info[1]
if tem_trace and tem_trace[:ip]
@ip_delta = tem_trace[:ip] - line_ip
@ip_label_delta = tem_trace[:ip] - @ip_label_info[0]
else
@ip_delta = @ip_label_delta = 0
end
line_sp, atom, backtrace = *@sp_line_info
@sp_atom = atom
if tem_trace and tem_trace[:sp]
@sp_delta = tem_trace[:sp] - line_sp
else
@sp_delta = 0
end
@trace = tem_trace
@buffer_state = buffer_state
@key_state = key_state
end
def bstat_str
if @buffer_state.nil?
"no buffer state available"
else
@buffer_state.inspect
end
end
def kstat_str
if @key_state.nil?
"no key state available"
else
@key_state.inspect
end
end
def trace_str
if @trace.nil?
"no trace available"
else
"ip=#{'%04x' % @trace[:ip]} (#{@ip_atom}+0x#{'%x' % @ip_delta}) " +
"sp=#{'%04x' % @trace[:sp]} (#{@sp_atom}+0x#{'%x' % @sp_delta}) " +
"out=#{'%04x' % @trace[:out]} " +
"pscell=#{'%04x' % @trace[:pscell]}"
end
end
def to_s
string = <<ENDSTRING
SECpack execution generated an exception on the TEM
TEM Trace: #{trace_str}
TEM Buffer Status:#{bstat_str}
TEM Key Status:#{kstat_str}
TEM execution error at #{@ip_label}+0x#{'%x' % @ip_label_delta}:
ENDSTRING
string.strip
end
def inspect
trace_str + "\n" + bstat_str + "\n" + kstat_str
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Assertion do
before(:each) do
@valid_attributes = {
:type => ,
:ind => ,
:version => ,
:submitter => ,
:modified => ,
:modifiable => ,
:disputing => ,
:contributor => ,
:tempId => ,
:person_id => ,
:event_type => ,
:event_scope => ,
:title => ,
:fact_type => ,
:fact_scope => ,
:title => ,
:detail => ,
:value => ,
:name_type => ,
:rel_scope => "value for rel_scope"
}
end
it "should create a new instance given valid attributes" do
Assertion.create!(@valid_attributes)
end
end
|
require 'game'
describe Game do
subject(:game) { described_class.new(player1, player2, weapons) }
let(:player1) { double :player1, name: 'Ed', choice: :paper, add_score: nil }
let(:player2) { double :player2, name: 'Computer', choice: :paper}
let(:weapons) { double :weapons, compare: nil, result: :paper }
let(:paper) { double :paper }
describe 'defaults' do
it 'should initialize with two players' do
expect(game.player1).to eq player1
expect(game.player2).to eq player2
end
it 'should initialize with a nil winner' do
expect(game.winner).to be nil
end
it 'should initialize with current player 1' do
expect(game.current).to be player1
end
end
describe '#outcome' do
it 'should call weapons.compare' do
expect(weapons).to receive(:compare)
game.outcome
end
end
describe '#switch' do
it 'should switch players' do
game.switch
expect(game.current).to be player2
end
end
describe '#round' do
it 'should monitor how many rounds have been played' do
game.outcome
game.outcome
expect(game.round).to eq 3
end
end
describe '#score' do
it 'should monitor the player scores' do
expect(player1).to receive(:add_score)
game.outcome
end
end
describe '#game_over?' do
it 'should know when a game is over' do
allow(player1).to receive(:score).and_return(3)
expect(game.game_over?).to eq true
end
end
end
|
module Concerns::Help::Association
extend ActiveSupport::Concern
included do
belongs_to :help_category
belongs_to :help_content
accepts_nested_attributes_for :help_content
end
end
|
module Task
module RecordScopes
def generic_effective_in(beginning_col, ending_col, interval)
return where("0 AND 'interval is empty'") if interval.empty?
int_beginning, int_ending = *interval.endpoints
s = scoped
if int_ending != Time::FOREVER
# Beginning column is never null
s = s.where("#{beginning_col} < :int_ending",
:int_ending => int_ending)
end
if int_beginning != Time::NEVER
s = s.where("#{ending_col} > :int_beginning OR #{ending_col} IS NULL",
:int_beginning => int_beginning)
end
s
end
def generic_effective_on(beginning, ending, date)
where(
"#{beginning} <= :date AND (:date < #{ending} OR #{ending} IS NULL)",
:date => date
)
end
end
end
|
class PlayersController < ApplicationController
require 'will_paginate/array'
autocomplete :player, :name, display_value: :autocomplete_display, full: true
# GET /players
# GET /players.json
def index
@players = Player.paginate(page: params[:page]).order("name")
@title = "All Players"
end
# GET /players/1
# GET /players/1.json
def show
@player = Player.find(params[:id])
@title = @player.name
end
def search
@positions = Player.all_positions
@teams = Team.all
@stats = (PlayerStats.column_names - ["id", "created_at", "updated_at"]).map{|c| [c.titleize, c]}
end
def results
players = Player.arel_table
@players = Player.years_stats
@players = @players.where(players[:name].matches("%#{params[:search]}%")) if params[:search].present?
@players = @players.where(players[:position].matches("%#{params[:position]}%")) if params[:position].present?
@players = @players.where("players_years.year = ?", params[:year]) if params[:year].present?
@players = @players.where("player_stats.#{params[:filter_by]} >= ?", params[:stats]) if params[:filter_by].present? && params[:stats].present?
@players = @players.uniq
@players = @players.paginate(page: params[:page]).order("name")
@title = "Results"
render :index
end
def games
@year = params[:year]
@player = Player.find(params[:id])
@games = @player.players_games.joins(:game).where("games.year = ?", @year)
render partial: "games"
end
# Given a team and a year, find all players that have played in all games for their team in that year.
def playallgames
@players = Player.find_by_sql(["SELECT p.* FROM players p, players_teams pt, teams t WHERE p.id = pt.player_id AND pt.start <= ?
AND pt.end >= ? AND pt.team_id = t.id AND t.id = ?
AND NOT EXISTS (SELECT * FROM games g WHERE (g.away_team_id = t.id OR g.home_team_id = t.id)
AND g.year = ? AND NOT EXISTS (SELECT * FROM players_games pg WHERE pg.game_id = g.id
AND pg.team_id = t.id AND pg.player_id = p.id))",
params[:year], params[:year], params[:team], params[:year]]).paginate(page: params[:page])
@title = "Query 1 Result"
render :index
end
def averageyards
pid = ActiveRecord::Base.sanitize(params[:player])
startyear = ActiveRecord::Base.sanitize(params[:start])
endyear = ActiveRecord::Base.sanitize(params[:end])
filterfield = ActiveRecord::Base.sanitize(params[:filter_by])
result = ActiveRecord::Base.connection.execute("SELECT AVG(ps.#{filterfield}) FROM games g, players p, players_games pg, player_stats ps
WHERE p.id = #{pid} AND p.id = pg.player_id AND pg.game_id = g.id
AND g.year >= #{startyear} AND g.year <= #{endyear} AND pg.player_stats_id = ps.id")
@result = "Average #{filterfield} per game between #{startyear} and #{endyear} for #{Player.find(params[:player]).name}: #{Float(result[0][0]).round(2)}"
@title = "Query 2 Result"
render :base_result
end
def yardsagainstteam
pid = ActiveRecord::Base.sanitize(params[:player1])
tid = ActiveRecord::Base.sanitize(params[:team])
startyear = ActiveRecord::Base.sanitize(params[:start])
endyear = ActiveRecord::Base.sanitize(params[:end])
filterfield = ActiveRecord::Base.sanitize(params[:filter_by])
result = ActiveRecord::Base.connection.execute("SELECT SUM(ps.#{filterfield}) FROM games g, players p, teams t, players_games pg, player_stats ps
WHERE p.id = #{pid} AND p.id = pg.player_id AND pg.game_id = g.id
AND ((g.home_team_id=#{tid} AND g.away_team_id = pg.team_id)
OR (g.away_team_id=#{tid} AND g.home_team_id = pg.team_id))
AND g.year >= #{startyear} AND g.year <= #{endyear} AND pg.player_stats_id = ps.id")
@result = "Total #{filterfield} between #{startyear} and #{endyear} against #{Team.find(params[:team]).name} for #{Player.find(params[:player1]).name}: #{Float(result[0][0]).round(2)}"
@title = "Query 3 Result"
render :base_result
end
def recordagainstteam
pid = ActiveRecord::Base.sanitize(params[:player2])
tid = ActiveRecord::Base.sanitize(params[:team])
startyear = ActiveRecord::Base.sanitize(params[:start])
endyear = ActiveRecord::Base.sanitize(params[:end])
result = ActiveRecord::Base.connection.execute("SELECT SUM(ts.wins), SUM(ts.losses), SUM(ts.ties) FROM games g, players p, players_games pg, team_stats ts
WHERE p.id = #{pid} AND p.id = pg.player_id AND pg.game_id = g.id
AND ((g.home_team_id=#{tid} AND g.away_team_id = pg.team_id AND g.away_team_stats_id=ts.id)
OR (g.away_team_id=#{tid} AND g.home_team_id = pg.team_id AND g.home_team_stats_id=ts.id))
AND g.year >= #{startyear} AND g.year <= #{endyear}")[0]
@result = "Total record between #{startyear} and #{endyear} against #{Team.find(params[:team]).name} for #{Player.find(params[:player2]).name}: #{result[0]}-#{result[1]}-#{result[2]}"
@title = "Query 3 Result"
render :base_result
end
end
|
class BuyersController < ApplicationController
wrap_parameters format: :json
wrap_parameters :buyer, include: [:first_name, :last_name, :password, :email]
# before_action :set_buyer, only: [:show, :edit, :update, :destroy]
def index
render json: Buyer.all, except: :password_digest
end
def show
buyer = Buyer.find_by(id: params[:id])
render json: {
buyer: buyer.as_json( except: :password_digest),
msg: 'heyyy'
}
# render json: buyer, except: :password_digest
end
def new
end
def edit
end
def create
buyer = Buyer.new(buyer_params)
if buyer.valid?
buyer.save
# payload = { id: buyer.id }
# hmac_secret = 'secret'
# token = JWT.encode(payload, hmac_secret, 'HS256')
# render json: { id: buyer.id, first_name: buyer.first_name, token: token }
render json: { msg: 'succefully created buyer!', buyer: buyer}
else
render json: { error: 'failed to create buyer: invalid email or password', buyer: buyer}
end
end
def update
buyer = Buyer.find_by(id: params[:id])
buyer.update(buyer_params)
render json: buyer
end
def destroy
buyer = Buyer.delete(params[:id])
render json: buyer
end
private
# Only allow a list of trusted parameters through.
def buyer_params
params.require(:buyer).permit(:first_name, :last_name, :password, :email)
end
end |
require 'spec_helper'
describe 'EXIM Trade Events API V1', type: :request do
include_context 'TradeEvent::Exim data'
describe 'GET /v1/trade_events/exim/search' do
let(:params) { { size: 100 } }
before { get '/v1/trade_events/exim/search', params }
subject { response }
context 'when search parameters are empty' do
it_behaves_like 'a successful search request'
it_behaves_like 'it contains all TradeEvent::Exim results'
end
context 'when q is specified' do
let(:params) { { q: 'Baltimore' } }
it_behaves_like 'a successful search request'
it_behaves_like 'it contains all TradeEvent::Exim results that match "Baltimore"'
it_behaves_like "an empty result when a query doesn't match any documents"
end
end
end
|
class CreateLeaveResets < ActiveRecord::Migration
def self.up
create_table :leave_resets do |t|
t.date :reset_date
t.integer :reset_type
t.string :reset_remark
t.integer :resetted_by
t.integer :status
t.integer :reset_value
t.integer :employee_count
t.timestamps
end
end
def self.down
drop_table :leave_resets
end
end
|
FactoryBot.define do
sequence(:email) { |n| "user#{n}@example.com" }
factory :user do
email
password "1234567890"
admin false
end
factory :admin, parent: :user do
id 1
admin true
end
end
|
require 'spec_helper'
describe User do
describe '#profile_incomplete?' do
context 'when user has both home and work zips filled out' do
let!(:user){ create(:user, home_zip: '90405', work_zip: '90305') }
it 'returns false' do
expect(user.profile_incomplete?).to eq false
end
end
context 'when user has just home zip filled out' do
let!(:user){ create(:user, home_zip: '90405') }
it 'returns true' do
expect(user.profile_incomplete?).to eq true
end
end
context 'when user has just work zip filled out' do
let!(:user){ create(:user, work_zip: '90305') }
it 'returns true' do
expect(user.profile_incomplete?).to eq true
end
end
context 'when user has neither home or work zips filled out' do
let!(:user){ create(:user) }
it 'returns true' do
expect(user.profile_incomplete?).to eq true
end
end
end
end
|
class CreateDonationAdditionalFields < ActiveRecord::Migration
def self.up
create_table :donation_additional_fields do |t|
t.string :name
t.boolean :status
t.boolean :is_mandatory
t.string :input_type
t.integer :priority
t.timestamps
end
end
def self.down
drop_table :donation_additional_fields
end
end
|
class AddTweetBodyToPosts < ActiveRecord::Migration
def change
add_column :posts, :tweet_body, :text
end
end
|
class CreateTaggings < ActiveRecord::Migration
def change
create_table :taggings do |t|
t.references :tag, null: false
t.references :taggable, polymorphic: true, index: true, null: false
t.string :source
t.references :last_updated_by
t.integer :confidence
t.text :notes
t.timestamps
end
add_index :taggings, [:tag_id, :taggable_id, :taggable_type], unique: true
reversible do |dir|
# one-time data migration
dir.up do
# create taggings from existing combos
sql = <<-SQL
INSERT INTO taggings (tag_id, taggable_id, taggable_type, created_at, updated_at)
SELECT tag_id, supplier_id, 'Supplier', now(), now() from combos;
SQL
TagGroup.connection.execute(sql)
end
end
end
end
|
class TransactionBuilder
def initialize(activity, account, transaction_list)
@activity = activity
@account = account
@transaction_list = transaction_list
end
def build_transactions
clear_old_transactions
create_transactions
end
private
def create_transactions
@transaction_list.each do |date, value|
transaction = Transaction.new(
planned_date: date,
planned: value,
transactable: @activity,
account: @account
)
transaction.save!
end
end
def clear_old_transactions
Transaction.where(transactable: @activity, account: @account).delete_all
end
end
|
class AddGamesTable < ActiveRecord::Migration[5.1]
def change
create_table :games do |t|
t.string :secret_word
t.string :guesses
end
end
end
|
class PrizeLocal < ActiveRecord::Base
belongs_to :prize
belongs_to :local
attr_accessor :association_should_exist
end
|
class Blog < ApplicationRecord
belongs_to :user
validates :title, uniqueness: {case_sensitive: false}, presence: true
validates :body, uniqueness: {case_sensitive: false}, length: {maximum: 200}, presence: true
# validates :book_name, presence: true
# validates :comment, presence: true
end
|
# Copyright (c) 2014 Mitchell Hashimoto
# Under The MIT License (MIT)
#---------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache License, Version 2.0.
# See License.txt in the project root for license information.
#--------------------------------------------------------------------------
require "log4r"
require "vagrant/util/subprocess"
require "vagrant/util/scoped_hash_override"
require "vagrant/util/which"
require "#{Vagrant::source_root}/lib/vagrant/action/builtin/synced_folders"
module VagrantPlugins
module WinAzure
module Action
# This middleware uses `rsync` to sync the folders
class SyncFolders < Vagrant::Action::Builtin::SyncedFolders
include Vagrant::Util::ScopedHashOverride
def initialize(app, env)
@app = app
@logger = Log4r::Logger.new("vagrant_azure::action::sync_folders")
end
def call(env)
if env[:machine].config.vm.guest != :windows
super
else
@app.call(env)
env[:machine].config.vm.synced_folders.each do |id, data|
data = scoped_hash_override(data, :azure)
# Ignore disabled shared folders
next if data[:disabled]
hostpath = File.expand_path(data[:hostpath], env[:root_path])
guestpath = data[:guestpath]
env[:ui].info(I18n.t("vagrant_azure.copy_folder",
:hostpath => hostpath,
:guestpath => guestpath))
# Create the host path if it doesn't exist and option flag is set
if data[:create]
begin
FileUtils::mkdir_p(hostpath)
rescue => err
raise Errors::MkdirError,
:hostpath => hostpath,
:err => err
end
end
env[:machine].communicate.upload(hostpath, guestpath)
end
end
end
end
end
end
end
|
# frozen_string_literal: true
require 'prometheus/client'
module Vmpooler
class Metrics
class Promstats < Metrics
attr_reader :prefix, :endpoint, :metrics_prefix
# Constants for Metric Types
M_COUNTER = 1
M_GAUGE = 2
M_SUMMARY = 3
M_HISTOGRAM = 4
# Customised Bucket set to use for the Pooler clone times set to more appropriate intervals.
POOLER_CLONE_TIME_BUCKETS = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 120.0, 180.0, 240.0, 300.0, 600.0].freeze
POOLER_READY_TIME_BUCKETS = [30.0, 60.0, 120.0, 180.0, 240.0, 300.0, 500.0, 800.0, 1200.0, 1600.0].freeze
# Same for redis connection times - this is the same as the current Prometheus Default.
# https://github.com/prometheus/client_ruby/blob/master/lib/prometheus/client/histogram.rb#L14
REDIS_CONNECT_BUCKETS = [1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 18.0, 23.0].freeze
@p_metrics = {}
def initialize(logger, params = {})
@prefix = params['prefix'] || 'vmpooler'
@metrics_prefix = params['metrics_prefix'] || 'vmpooler'
@endpoint = params['endpoint'] || '/prometheus'
@logger = logger
# Setup up prometheus registry and data structures
@prometheus = Prometheus::Client.registry
end
# Metrics structure used to register the metrics and also translate/interpret the incoming metrics.
def vmpooler_metrics_table
{
errors: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Count of errors for pool',
prom_metric_prefix: "#{@metrics_prefix}_errors",
metric_suffixes: {
markedasfailed: 'timeout waiting for instance to initialise',
duplicatehostname: 'unable to create instance due to duplicate hostname',
staledns: 'unable to create instance due to duplicate DNS record'
},
param_labels: %i[template_name]
},
user: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Number of pool instances this user created created',
prom_metric_prefix: "#{@metrics_prefix}_user",
param_labels: %i[user poolname]
},
usage_litmus: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Pools by Litmus job usage',
prom_metric_prefix: "#{@metrics_prefix}_usage_litmus",
param_labels: %i[user poolname]
},
usage_jenkins_instance: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Pools by Jenkins instance usage',
prom_metric_prefix: "#{@metrics_prefix}_usage_jenkins_instance",
param_labels: %i[jenkins_instance value_stream poolname]
},
usage_branch_project: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Pools by branch/project usage',
prom_metric_prefix: "#{@metrics_prefix}_usage_branch_project",
param_labels: %i[branch project poolname]
},
usage_job_component: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'Pools by job/component usage',
prom_metric_prefix: "#{@metrics_prefix}_usage_job_component",
param_labels: %i[job_name component_to_test poolname]
},
checkout: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Pool checkout counts',
prom_metric_prefix: "#{@metrics_prefix}_checkout",
metric_suffixes: {
nonresponsive: 'checkout failed - non responsive machine',
empty: 'checkout failed - no machine',
success: 'successful checkout',
invalid: 'checkout failed - invalid template'
},
param_labels: %i[poolname]
},
delete: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Delete machine',
prom_metric_prefix: "#{@metrics_prefix}_delete",
metric_suffixes: {
success: 'succeeded',
failed: 'failed'
},
param_labels: []
},
ondemandrequest_generate: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Ondemand request',
prom_metric_prefix: "#{@metrics_prefix}_ondemandrequest_generate",
metric_suffixes: {
duplicaterequests: 'failed duplicate request',
success: 'succeeded'
},
param_labels: []
},
ondemandrequest_fail: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Ondemand request failure',
prom_metric_prefix: "#{@metrics_prefix}_ondemandrequest_fail",
metric_suffixes: {
toomanyrequests: 'too many requests',
invalid: 'invalid poolname'
},
param_labels: %i[poolname]
},
config: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'vmpooler pool configuration request',
prom_metric_prefix: "#{@metrics_prefix}_config",
metric_suffixes: { invalid: 'Invalid' },
param_labels: %i[poolname]
},
poolreset: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Pool reset counter',
prom_metric_prefix: "#{@metrics_prefix}_poolreset",
metric_suffixes: { invalid: 'Invalid Pool' },
param_labels: %i[poolname]
},
connect: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'vmpooler connect (to vSphere)',
prom_metric_prefix: "#{@metrics_prefix}_connect",
metric_suffixes: {
open: 'Connect Succeeded',
fail: 'Connect Failed'
},
param_labels: []
},
migrate_from: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'vmpooler machine migrated from',
prom_metric_prefix: "#{@metrics_prefix}_migrate_from",
param_labels: %i[host_name]
},
migrate_to: {
mtype: M_COUNTER,
torun: %i[manager],
docstring: 'vmpooler machine migrated to',
prom_metric_prefix: "#{@metrics_prefix}_migrate_to",
param_labels: %i[host_name]
},
api_vm: {
mtype: M_COUNTER,
torun: %i[api],
docstring: 'Total number of HTTP request/sub-operations handled by the Rack application under the /vm endpoint',
prom_metric_prefix: "#{@metrics_prefix}_http_requests_vm_total",
param_labels: %i[method subpath operation]
},
ready: {
mtype: M_GAUGE,
torun: %i[manager],
docstring: 'vmpooler number of machines in ready State',
prom_metric_prefix: "#{@metrics_prefix}_ready",
param_labels: %i[poolname]
},
running: {
mtype: M_GAUGE,
torun: %i[manager],
docstring: 'vmpooler number of machines running',
prom_metric_prefix: "#{@metrics_prefix}_running",
param_labels: %i[poolname]
},
connection_available: {
mtype: M_GAUGE,
torun: %i[manager],
docstring: 'vmpooler redis connections available',
prom_metric_prefix: "#{@metrics_prefix}_connection_available",
param_labels: %i[type provider]
},
time_to_ready_state: {
mtype: M_HISTOGRAM,
torun: %i[manager],
buckets: POOLER_READY_TIME_BUCKETS,
docstring: 'Time taken for machine to read ready state for pool',
prom_metric_prefix: "#{@metrics_prefix}_time_to_ready_state",
param_labels: %i[poolname]
},
migrate: {
mtype: M_HISTOGRAM,
torun: %i[manager],
buckets: POOLER_CLONE_TIME_BUCKETS,
docstring: 'vmpooler time taken to migrate machine for pool',
prom_metric_prefix: "#{@metrics_prefix}_migrate",
param_labels: %i[poolname]
},
clone: {
mtype: M_HISTOGRAM,
torun: %i[manager],
buckets: POOLER_CLONE_TIME_BUCKETS,
docstring: 'vmpooler time taken to clone machine',
prom_metric_prefix: "#{@metrics_prefix}_clone",
param_labels: %i[poolname]
},
destroy: {
mtype: M_HISTOGRAM,
torun: %i[manager],
buckets: POOLER_CLONE_TIME_BUCKETS,
docstring: 'vmpooler time taken to destroy machine',
prom_metric_prefix: "#{@metrics_prefix}_destroy",
param_labels: %i[poolname]
},
connection_waited: {
mtype: M_HISTOGRAM,
torun: %i[manager],
buckets: REDIS_CONNECT_BUCKETS,
docstring: 'vmpooler redis connection wait time',
prom_metric_prefix: "#{@metrics_prefix}_connection_waited",
param_labels: %i[type provider]
}
}
end
# Helper to add individual prom metric.
# Allow Histograms to specify the bucket size.
def add_prometheus_metric(metric_spec, name, docstring)
case metric_spec[:mtype]
when M_COUNTER
metric_class = Prometheus::Client::Counter
when M_GAUGE
metric_class = Prometheus::Client::Gauge
when M_SUMMARY
metric_class = Prometheus::Client::Summary
when M_HISTOGRAM
metric_class = Prometheus::Client::Histogram
else
raise("Unable to register metric #{name} with metric type #{metric_spec[:mtype]}")
end
if (metric_spec[:mtype] == M_HISTOGRAM) && (metric_spec.key? :buckets)
prom_metric = metric_class.new(
name.to_sym,
docstring: docstring,
labels: metric_spec[:param_labels] + [:vmpooler_instance],
buckets: metric_spec[:buckets],
preset_labels: { vmpooler_instance: @prefix }
)
else
prom_metric = metric_class.new(
name.to_sym,
docstring: docstring,
labels: metric_spec[:param_labels] + [:vmpooler_instance],
preset_labels: { vmpooler_instance: @prefix }
)
end
@prometheus.register(prom_metric)
end
# Top level method to register all the prometheus metrics.
def setup_prometheus_metrics(torun)
@p_metrics = vmpooler_metrics_table
@p_metrics.each do |_name, metric_spec|
# Only register metrics appropriate to api or manager
next if (torun & metric_spec[:torun]).empty?
if metric_spec.key? :metric_suffixes
# Iterate thru the suffixes if provided to register multiple counters here.
metric_spec[:metric_suffixes].each do |metric_suffix|
add_prometheus_metric(
metric_spec,
"#{metric_spec[:prom_metric_prefix]}_#{metric_suffix[0]}",
"#{metric_spec[:docstring]} #{metric_suffix[1]}"
)
end
else
# No Additional counter suffixes so register this as metric.
add_prometheus_metric(
metric_spec,
metric_spec[:prom_metric_prefix],
metric_spec[:docstring]
)
end
end
end
# locate a metric and check/interpet the sub-fields.
def find_metric(label)
sublabels = label.split('.')
metric_key = sublabels.shift.to_sym
raise("Invalid Metric #{metric_key} for #{label}") unless @p_metrics.key? metric_key
metric = @p_metrics[metric_key].clone
if metric.key? :metric_suffixes
metric_subkey = sublabels.shift.to_sym
raise("Invalid Metric #{metric_key}_#{metric_subkey} for #{label}") unless metric[:metric_suffixes].key? metric_subkey.to_sym
metric[:metric_name] = "#{metric[:prom_metric_prefix]}_#{metric_subkey}"
else
metric[:metric_name] = metric[:prom_metric_prefix]
end
# Check if we are looking for a parameter value at last element.
if metric.key? :param_labels
metric[:labels] = {}
# Special case processing here - if there is only one parameter label then make sure
# we append all of the remaining contents of the metric with "." separators to ensure
# we get full nodenames (e.g. for Migration to node operations)
if metric[:param_labels].length == 1
metric[:labels][metric[:param_labels].first] = sublabels.join('.')
else
metric[:param_labels].reverse_each do |param_label|
metric[:labels][param_label] = sublabels.pop(1).first
end
end
end
metric
end
# Helper to get lab metrics.
def get(label)
metric = find_metric(label)
[metric, @prometheus.get(metric[:metric_name])]
end
# Note - Catch and log metrics failures so they can be noted, but don't interrupt vmpooler operation.
def increment(label)
begin
counter_metric, c = get(label)
c.increment(labels: counter_metric[:labels])
rescue StandardError => e
@logger.log('s', "[!] prometheus error logging metric #{label} increment : #{e}")
end
end
def gauge(label, value)
begin
unless value.nil?
gauge_metric, g = get(label)
g.set(value.to_i, labels: gauge_metric[:labels])
end
rescue StandardError => e
@logger.log('s', "[!] prometheus error logging gauge #{label}, value #{value}: #{e}")
end
end
def timing(label, duration)
begin
# https://prometheus.io/docs/practices/histograms/
unless duration.nil?
histogram_metric, hm = get(label)
hm.observe(duration.to_f, labels: histogram_metric[:labels])
end
rescue StandardError => e
@logger.log('s', "[!] prometheus error logging timing event label #{label}, duration #{duration}: #{e}")
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Skill, type: :model do
it_behaves_like 'it has a valid factory', :skill
subject { build(:skill) }
describe '#level' do
it 'has a minimum value of 0.0' do
subject.level = -0.1
expect(subject.save).to be_falsey
end
it 'has a maximum value of 100.0' do
subject.level = 100.1
expect(subject.save).to be_falsey
end
it 'saves a number within the range 0-100' do
subject.level = 50.0
expect(subject.save).to be_truthy
end
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
mount_uploader :avatar, AvatarUploader
has_many :topics, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :messages, dependent: :destroy
has_many :relationships, foreign_key: 'follower_id', dependent: :destroy
has_many :reverse_relationships, foreign_key: 'followed_id', class_name: 'Relationship', dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed #sourceは多:多の時に探し出すモデル(テーブル)を指定する
has_many :followers, through: :reverse_relationships, source: :follower
def follow(other_user)
relationships.create(followed_id: other_user.id)
end
def unfollow(other_user)
relationships.find_by(followed_id: other_user.id).destroy
end
def following?(other_user)
relationships.find_by(followed_id: other_user.id)
end
def friend
followers & followed_users
end
def self.find_for_facebook_oauth(auth, sign_in_resource=nil)
user = User.where(provider: auth.provider, uid: auth.uid).first
user = User.new(
name: auth.info.name,
nick_name: auth.info.name,
email: auth.info.email || User.create_email,
image_url: auth.info.image,
provider: auth.provider,
uid: auth.uid,
password: Devise.friendly_token[0,20]
) unless user
user.skip_confirmation!
user.save
user
end
def self.find_for_twitter_oauth(auth, sign_in_resource=nil)
user = User.where(provider: auth.provider, uid: auth.uid).first
user = User.new(
name: auth.info.name,
nick_name: auth.info.nickname,
email: User.create_email,
image_url: auth.info.image,
provider: auth.provider,
uid: auth.uid,
password: Devise.friendly_token[0,20]
) unless user
user.skip_confirmation!
user.save
user
end
def update_without_current_password(params, *options)
params.delete(:current_password)
if params[:password].blank? && params[:password_confirmation].blank?
params.delete(:password)
params.delete(:password_confirmation)
end
result = update_attributes(params, *options)
clean_up_passwords
result
end
def self.create_email
SecureRandom.uuid + '@example.com'
end
end
|
module RTALogger
class LogTopicWrapper
def initialize(context_id, topic, level = 0)
@context_id = context_id
@topic = topic
level = level - 1
level = 0 if level.negative?
level = 5 if level > 5
self.level = level
end
attr_accessor :progname
attr_accessor :context_id
# Logging severity.
module Severity
# Low-level information, mostly for developers.
DEBUG = 0
# Generic (useful) information about system operation.
INFO = 1
# A warning.
WARN = 2
# A handleable error condition.
ERROR = 3
# An unhandleable error that results in a program crash.
FATAL = 4
# An unknown message that should always be logged.
UNKNOWN = 5
end
include Severity
# Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
attr_reader :level
# Set logging severity threshold.
#
# +severity+:: The Severity of the log message.
def level=(severity)
if severity.is_a?(Integer)
severity = 0 if severity.negative?
severity = 5 if severity > 5
@level = severity
else
case severity.to_s.downcase
when 'debug'
@level = DEBUG
when 'info'
@level = INFO
when 'warn'
@level = WARN
when 'error'
@level = ERROR
when 'fatal'
@level = FATAL
when 'unknown'
@level = UNKNOWN
else
raise ArgumentError, "invalid log level: #{severity}"
end
end
end
# Returns +true+ iff the current severity level allows for the printing of
# +DEBUG+ messages.
def debug?;
@level <= DEBUG;
end
# Returns +true+ iff the current severity level allows for the printing of
# +INFO+ messages.
def info?;
@level <= INFO;
end
# Returns +true+ iff the current severity level allows for the printing of
# +WARN+ messages.
def warn?;
@level <= WARN;
end
# Returns +true+ iff the current severity level allows for the printing of
# +ERROR+ messages.
def error?;
@level <= ERROR;
end
# Returns +true+ iff the current severity level allows for the printing of
# +FATAL+ messages.
def fatal?;
@level <= FATAL;
end
def add(severity, message = nil, progname = nil)
severity ||= UNKNOWN
if progname.nil?
progname = @progname
end
if message.nil?
if block_given?
message = yield
else
message = progname
progname = @progname
end
end
rta_logger_topic_log(severity, message)
true
end
alias log add
def debug(progname = nil, &block)
add(DEBUG, nil, progname, &block)
end
def info(progname = nil, &block)
add(INFO, nil, progname, &block)
end
def warn(progname = nil, &block)
add(WARN, nil, progname, &block)
end
def error(progname = nil, &block)
add(ERROR, nil, progname, &block)
end
def fatal(progname = nil, &block)
add(FATAL, nil, progname, &block)
end
def unknown(progname = nil, &block)
add(UNKNOWN, nil, progname, &block)
end
private
def rta_logger_topic_log(severity, message)
return if @topic.nil?
case severity
when DEBUG
@topic.debug(@context_id, message)
when INFO
@topic.info(@context_id, message)
when WARN
@topic.warning(@context_id, message)
when ERROR
@topic.error(@context_id, message)
when FATAL
@topic.fatal(@context_id, message)
when UNKNOWN
@topic.unknown(@context_id, message)
end
end
end
end
|
require_relative '../code.rb'
describe "bracket_match?" do
it "returns true" do
expect(bracket_match?("Hi! What is your name again (I forgot)?")).to eq true
end
it "returns false" do
expect(bracket_match?("Hi! What is (your name again? I forgot")).to eq false
end
it "returns false" do
expect(bracket_match?(")(")).to eq false
end
end
|
module Nlg
class Paragraph
attr_accessor :defaults, :dataset, :sentences
# The parameters, dataset and defaults are both hashes.
# For example:
#
# defaults = { "tense" => "present",
# "verb" => "have",
# "pronoun" => "it",
# "voice" => "active",
# "aspect" => "habitual",
# "preposition" => "of" }
#
# dataset = {"subject"=>"Pune",
# "objects"=>
# { "population"=>
# {"value"=>"57841284790",
# "specifications"=>{}},
# "rainfall"=>
# {"value"=>"198",
# "specifications"=>{"complement"=>"mm"}},
# "high temperature"=>
# {"value"=>"45",
# "specifications"=>{"complement"=>"°C"},
# "conjugated_with"=>["low temperature"]},
# "low temperature"=>
# {"value"=>"20",
# "specifications"=>{"complement"=>"°C"},
# "conjugated_with"=>["high temperature", "low temperature", "rainfall"]},
# "forts"=>
# {"value"=>["sinhgad", "lohgad"],
# "specifications"=>{"preposition"=>"named"},
# "conjugated_with"=>["high temperature", "low temperature", "rainfall"]}
# }
# }
#
# method to set defaults, build_conjugations and initialize other attributes
def initialize(dataset, defaults)
@subject = dataset['subject']
@objects = {}
@conjugations = {}
@defaults = defaults
@sentences = []
# Iterating through all the objects and building conjugations.
dataset['objects'].each do |object_type, object_details|
# A check to allow objects to be created with "conjugated" => false only if not already
# present. build_conjugations method called which recursively builds the conjugations.
unless @objects.has_key?(object_type)
sentence_object = SentenceObject.new(object_type, object_details, "conjugated" => false)
@objects[object_type] = sentence_object
build_conjugations(object_type, dataset['objects'])
end
end
end
def build
puts @conjugations.inspect, @objects.inspect
# Paragraph generation by generating individual sentences.
@objects.each do |object_type, sentence_object|
sentence = Sentence.new(:subject => @subject, :specifications => @defaults.merge(sentence_object.specifications))
@sentences << sentence.build(object_type, sentence_object)
end
end
# Method called internally in initialize to build conjugations among sentences of a paragraph.
# The example dataset will give the conjugations,
#
# @conjugations ={"population"=>[], "forts"=>["low temperature", "rainfall", "high temperature"]}
def build_conjugations(object_type, objects, parent_object = nil)
object_details = objects[object_type]
# Condition for setting the parent_object to be passed recursively
parent_object = object_type unless parent_object
# Creating the @conjugations[parent_object] array recursively to finally
# build the conjugations.
conjugated_with = object_details['conjugated_with']
unless conjugated_with.nil? or conjugated_with.empty?
conjugated_with.each do |conjugated_object|
if objects.has_key?(conjugated_object)
# Creating object with "conjugated" => true if its present in "conjugated_with" array.
unless @objects.has_key?(conjugated_object)
sentence_object = SentenceObject.new(conjugated_object, objects[conjugated_object], "conjugated" => true)
@objects[conjugated_object] = sentence_object
end
# Creating array if does not already exist.
@conjugations[parent_object] ||= []
# Checking if currently iterating object included in the array already/is the parent_object itself.
unless @conjugations[parent_object].include?(conjugated_object) or conjugated_object == parent_object
# If an already parsed object with "conjugated" = false comes as a conjugation
# to the object being parsed.
if @objects[conjugated_object].conjugated == false
@objects[conjugated_object].conjugated = true
@conjugations[parent_object] = @conjugations[parent_object].concat(@conjugations[conjugated_object]).uniq
@conjugations.delete(conjugated_object)
end
# Appending to the conjugations array for the parent_object.
@conjugations[parent_object] << conjugated_object
# recursive call for building conjugations for a parent_object
build_conjugations(conjugated_object, objects, parent_object)
end
else
raise NlgException.new "No object named #{conjugation_object}"
end
end
else
# adding independent sentences which have no conjugations
@conjugations[object_type] = [] if @objects[object_type].conjugated == false
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.