text stringlengths 10 2.61M |
|---|
# An intro to the exercise.
puts "I will now count my chickens:"
# Counting the number of hens.
puts "Hens #{25 + 30 / 6}"
# Counting the number of roosters.
puts "Roosters #{100 - 25 * 3 % 4}"
# Switching to a differnt count.
puts "Now I will count the eggs:"
# Doing some math with Ruby.
puts 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Intro to the next section
puts "Is it true that 3 + 2 < 5 - 7?"
# Outputting the result of the math question before.
puts 3 + 2 < 5 - 7
# First part of the question.
puts "What is 3 + 2? #{3 + 2}"
# Second part of the question.
puts "What is 5 - 7? #{5 - 7}"
# Just a line of text.
puts "Oh, that's why it's false."
# More text.
puts "How about some more."
# Comparing with greater than.
puts "Is is greater? #{5 > -2}"
# Comparing with greater or equal.
puts "Is it greater or equal? #{5 >= -2}"
# Comparing with less or equal.
puts "Is it less or equal? #{5 <= -2}"
puts "Using floats."
# An intro to the exercise.
puts "I will now count my chickens:"
# Counting the number of hens.
puts "Hens #{25.0 + 30.0 / 6.0}"
# Counting the number of roosters.
puts "Roosters #{100.0 - 25.0 * 3.0 % 4.0}"
# Switching to a differnt count.
puts "Now I will count the eggs:"
# Doing some math with Ruby.
puts 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
# Intro to the next section
puts "Is it true that 3 + 2 < 5 - 7?"
# Outputting the result of the math question before.
puts 3.0 + 2.0 < 5.0 - 7.0
# First part of the question.
puts "What is 3 + 2? #{3.0 + 2.0}"
# Second part of the question.
puts "What is 5 - 7? #{5.0 - 7.0}"
# Just a line of text.
puts "Oh, that's why it's false."
# More text.
puts "How about some more."
# Comparing with greater than.
puts "Is is greater? #{5.0 > -2.0}"
# Comparing with greater or equal.
puts "Is it greater or equal? #{5.0 >= -2.0}"
# Comparing with less or equal.
puts "Is it less or equal? #{5.0 <= -2.0}" |
class CreateCategoryFieldValues < ActiveRecord::Migration[5.0]
def change
create_table :category_field_values do |t|
t.references :item, foreign_key: true
t.references :category_field, foreign_key: true
t.string :value, null: true
t.timestamps
end
end
end
|
module ROM
describe Dynamo::Relation do
include_context 'dynamo' do
let(:table_name) { :hash_table }
let(:table) { build(:hash_table, table_name: table_name.to_s) }
end
include_context 'rom setup' do
let(:definitions) {
Proc.new do
relation(:hash_table) { }
commands(:hash_table) do
define(:create) { result :one }
define(:update) { result :one }
define(:delete) { result :one }
end
end
}
end
context 'creation' do
let(:hash) { build(:hash) }
specify { expect { subject.command(:hash_table).create.call(hash) }.to_not raise_error }
end
end
end
|
require 'simplecov'
SimpleCov.start
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'minitest/pride'
require 'webmock'
require 'vcr'
VCR.configure do |config|
config.cassette_library_dir = "test/vcr_cassettes"
config.hook_into :webmock
config.before_record do |r|
r.request.headers.delete('Authorization')
end
end
class ActiveSupport::TestCase
def stub_omniauth
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({
provider: 'twitter',
extra: {
raw_info: {
uid: "338656919",
name: "Justin Pease",
screen_name: "JustinPease",
}
},
credentials: {
token: ENV["oauth_token"],
secret: ENV["oauth_token_secret"]
}
})
end
end
class ActionDispatch::IntegrationTest
include Capybara::DSL
def setup
Capybara.app = CuriousTweets::Application
stub_omniauth
end
def stub_omniauth
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({
provider: 'twitter',
extra: {
raw_info: {
uid: "338656919",
name: "Justin Pease",
screen_name: "JustinPease",
}
},
credentials: {
token: ENV["oauth_token"],
secret: ENV["oauth_token_secret"]
}
})
end
end
|
require "httplog/extensions/replacers/full_replacer"
module Extensions
module DataFilters
class BaseFilter
attr_accessor :filtered_keys
def initialize(opts={})
@filtered_keys = opts.fetch(:filtered_keys, [])
@replacer = opts.fetch(:replacer, default_replacer).new(opts)
end
def filter(data)
raise "override this method in subclass"
end
def suitable?(data)
raise "override this method in subclass"
end
private
def default_replacer
Extensions::Replacers::FullReplacer
end
end
end
end
|
class WeightsController < ApplicationController
layout 'internal'
before_action :authenticate_user!
before_action :block_crossprofile_access
before_action :recover_profile
def index
@weights = @profile.weights
end
def new; end
def edit
@weight = Weight.find(params[:id])
end
def create
@weight = Weight.new(weight_params)
@weight.profile = @profile
if @weight.save
flash[:success] = 'Weight registered sucessfully'
redirect_to profile_weights_path(profile_email: @profile.email)
else
render 'new'
end
end
def update
@weight = Weight.find(params[:id])
if @weight.update(weight_params)
flash[:success] = 'Weight updated sucessfully'
redirect_to profile_weights_path(profile_email: @weight.profile.email)
else
render 'edit'
end
end
def destroy
@weight = Weight.find(params[:id])
profile_email = @weight.profile.email
@weight.destroy
redirect_to profile_weights_path(profile_email: profile_email)
end
private
def weight_params
params.require(:weight).permit(:value, :date)
end
end
|
include Migrations::DisableUpdatedAt
class CreateOrgaTypes < ActiveRecord::Migration[5.0]
def up
create_table :orga_types do |t|
t.string :name
t.timestamps
end
OrgaType.create!(name: 'Root')
OrgaType.create!(name: 'Organization')
OrgaType.create!(name: 'Project')
OrgaType.create!(name: 'Location')
OrgaType.create!(name: 'Network')
add_reference :orgas, :orga_type, references: :orga_types, index: true, after: :id
without_updated_at do
Orga.unscoped.all.each do |orga|
if orga.id == 1
orga.orga_type_id = OrgaType.where(name: 'Root').first['id']
else
if orga.parent_orga_id != 1
orga.orga_type_id = OrgaType.where(name: 'Project').first['id']
else
orga.orga_type_id = OrgaType.where(name: 'Organization').first['id']
end
end
orga.save(validate: false)
end
end
end
def down
drop_table :orga_types
remove_reference(:orgas, :orga_type, index: true)
end
end
|
module Validators
extend ActiveSupport::Concern
included do
validates :embodiment, presence: true
validates :deadline_on, presence: true
validates :unit, presence: true
validates :quantification, presence: true
end
end
|
require "lucie/utils"
module Status
#
# An error raised by Status::* classes.
#
class StatusError < StandardError; end
#
# A base class for Status::* classes.
#
class Common
include Lucie::Utils
attr_reader :path
def self.base_name name # :nodoc:
module_eval %-
@@base_name = name
-
end
def initialize path, debug_options = {}
@path = path
@debug_options = debug_options
@messenger = debug_options[ :messenger ]
end
def to_s
read_latest_status.to_s
end
def update message
write_status_file "incomplete", message
end
def read
Dir[ File.join( @path, "#{ base_name }.*" ) ].each do | each |
return IO.read( each )
end
nil
end
def start!
start_timer
remove_old_status_file
touch_status_file "incomplete"
end
def succeed!
elapsed = stop_timer
remove_old_status_file
touch_status_file "success.in#{ elapsed }s"
end
def fail!
elapsed = stop_timer
remove_old_status_file
touch_status_file "failed.in#{ elapsed }s"
end
def succeeded?
read_latest_status == 'success'
end
def failed?
read_latest_status == 'failed'
end
def incomplete?
read_latest_status == 'incomplete'
end
def elapsed_time
file = status_file
raise Status::StatusError, "Could not find status file" unless file
match_elapsed_time( File.basename( file ) )
end
##############################################################################
private
##############################################################################
def base_name
instance_eval do | obj |
obj.class.__send__ :class_variable_get, :@@base_name
end
end
def status_file
Dir[ "#{ @path }/#{ base_name }.*" ].first
end
def match_status file_name
return /\A#{ base_name }\.([^\.]+)(\..+)?/.match( file_name )[ 1 ]
end
def match_elapsed_time file_name
match = /\A#{ base_name }\.[^\.]+\.in(\d+)s\Z/.match( file_name )
raise StatusError, "Could not parse elapsed time." if !match or !$1
return $1.to_i
end
def read_latest_status
file = status_file
return match_status( File.basename( file ) ).downcase if file
nil
end
def write_status_file status, message
filename = File.join( @path, "#{ base_name }.#{ status }" )
mkdir_p( @path, @debug_options ) unless FileTest.directory?( @path )
write_file filename, message, @debug_options
end
def touch_status_file status
filename = File.join( @path, "#{ base_name }.#{ status }" )
mkdir_p( @path, @debug_options ) unless FileTest.directory?( @path )
touch filename, @debug_options
end
def remove_old_status_file
Dir[ File.join( @path, "#{ base_name }.*" ) ].each do | each |
rm_f each, @debug_options
end
end
############################################################################
# Timer operations
############################################################################
def start_timer
@time = Time.now
end
def stop_timer
( Time.now - @time ).ceil
end
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
class Message < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
attribute :message_title, :validate => true
attribute :message_body, :validate => true
def headers
{
:subject => "A message",
:to => 'itay289@gmail.com',
:from => %("#{name}" <#{email}>)
}
end
validates :name, presence: true
validates :email, presence: true,
presence: { with: /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i }
validates :message_title, presence: true
validates :message_body, presence: true, length: { minimum: 10 }
end
|
require_relative "Task"
require_relative "../common/FileHandler"
require_relative "../common/Utilities"
class TaskCrud < Utilities
def finaliza_tarefa(lista_tarefas)
if lista_tarefas.length > 0
puts
print_list(lista_tarefas)
puts
puts 'selecione o índice da tarefa que deseja finalizar:'
indice = gets.to_i
lista_tarefas[indice -1].mark_as_done
puts "tarefa '#{lista_tarefas[indice -1].description}' Finalizada com sucesso"
return
end
puts "não há itens na lista!"
end
def carregar_lista(file)
file = FileHandler.read(file)
if file
lista_tarefas = []
file.each_line do |line|
line = line.split(",")
tarefa = Task.new(line[0], true?(line[1].strip))
lista_tarefas << tarefa
end
file.close
return lista_tarefas
end
puts 'arquivo não existe ou está vazio!'
end
def salvar_lista(lista_tarefas, file_name)
if FileHandler.write(lista_tarefas, file_name)
puts "salvo com sucesso"
return
end
puts "Não há itens para salvar!"
end
def insere_tarefa()
print 'Digite sua tarefa: '
tarefa = Task.new (gets.strip)
puts
puts 'Tarefa cadastrada: ' + tarefa.description
return tarefa
end
def ver_tarefas(lista_tarefas)
if lista_tarefas.length > 0
print_list(lista_tarefas)
else
puts 'lista vazia!'
end
end
end |
class Admin::ApplicationController < ApplicationController
before_action :authenticate_user!
before_action :authenticate_admin!
private
def authenticate_admin!
return if current_user&.admin?
redirect_to root_path, alert: t('admin.alert')
end
end
|
require 'row'
describe Dodecaphony::Row do
it "initializes with an array of strings and returns the original row" do
tone_row = %w[ a a# b c db d eb e f f# g g# ]
new_dod = Dodecaphony::Row.new tone_row
expect(new_dod.to_a).to eq tone_row
end
it "raises an error for a row with more than 12 pitches" do
expect{ Dodecaphony::Row.new %w[ a a# b c c# d eb e f f# g ab a] }.
to raise_error(ArgumentError, 'incorrect number of pitches (13) in row')
end
it "raises an error for a row with less than 12 pitches" do
expect{ Dodecaphony::Row.new %w[ a a# b eb e f f# g ab a] }.
to raise_error(ArgumentError, 'incorrect number of pitches (10) in row')
end
it "raises an error for duplicate pitches" do
expect{ Dodecaphony::Row.new %w[a a# b c c# d eb e f f g ab]}.
to raise_error(ArgumentError, 'duplicate pitch (f)')
end
it "can respell the row, favoring sharps" do
tone_row = %w[ c c+ d d# fb f gb g a- b-- bb b ]
new_dod = Dodecaphony::Row.new tone_row
expect(new_dod.spell_with_sharps).to eq %w[ C C# D D# E F F# G G# A A# B ]
end
it "can respell the row, favoring flats" do
tone_row = %w[ c c+ d d# fb f gb g a- b-- bb b ]
new_dod = Dodecaphony::Row.new tone_row
expect(new_dod.spell_with_flats).to eq %w[ C Db D Eb E F Gb G Ab A Bb B ]
end
it "returns a reasonable string" do
tone_row = Dodecaphony::Row.new %w[ a f# g ab e f b bb d c# c eb ]
expect(tone_row.to_s).to eq "a f# g ab e f b bb d c# c eb"
end
it "returns an array" do
tone_row = Dodecaphony::Row.new %w[a f# g ab e f b b- d c# c eb]
expect(tone_row.to_a).to eq %w[a f# g ab e f b b- d c# c eb]
end
it "returns its pitches" do
tone_row = Dodecaphony::Row.new %w[a f# g ab e f b b- d c# c eb]
first_pitch = Dodecaphony::Pitch.new "a"
expect(tone_row.pitches.to_a[0].name).to eq first_pitch.name
end
it "can check for equality with other rows" do
row1 = Dodecaphony::Row.new %w[a f# g ab e f b b- d c# c eb]
row2 = Dodecaphony::Row.new %w[a f# g ab e f b b- d c# c eb]
expect(row1).to eq row2
end
it "knows when rows are unequal" do
row1 = Dodecaphony::Row.new %w[a f# g ab e f b b- d c# c eb]
row2 = Dodecaphony::Row.new %w[a b b- c d- d e- e f g- g a-]
expect(row1).to_not eq row2
end
end
|
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
if logged_in?
@user = User.find_by(name: session[:user_name])
@user.events.create(name: params[:event][:name])
redirect_to @user
else
flash.now[:error] = "You're not logged in so you can't create events"
end
end
def show
@event = Event.find(params[:id])
end
def index
@events = Event.all
end
end
|
class PodInfosController < ApplicationController
before_action :set_pod_info, only: [:show, :edit, :update, :destroy]
# GET /pod_infos
# GET /pod_infos.json
def index
@pod_infos = PodInfo.all
end
# GET /pod_infos/1
# GET /pod_infos/1.json
def show
end
# GET /pod_infos/new
def new
@pod_info = PodInfo.new
end
# GET /pod_infos/1/edit
def edit
end
# POST /pod_infos
# POST /pod_infos.json
def create
@pod_info = PodInfo.new(pod_info_params)
respond_to do |format|
if @pod_info.save
format.html { redirect_to @pod_info, notice: 'Pod info was successfully created.' }
format.json { render action: 'show', status: :created, location: @pod_info }
else
format.html { render action: 'new' }
format.json { render json: @pod_info.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pod_infos/1
# PATCH/PUT /pod_infos/1.json
def update
respond_to do |format|
if @pod_info.update(pod_info_params)
format.html { redirect_to @pod_info, notice: 'Pod info was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @pod_info.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pod_infos/1
# DELETE /pod_infos/1.json
def destroy
@pod_info.destroy
respond_to do |format|
format.html { redirect_to pod_infos_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pod_info
@pod_info = PodInfo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pod_info_params
params[:pod_info]
end
end
|
Deface::Override.new(:virtual_path => "spree/layouts/admin",
:name => "Add Pos tab to menu",
:insert_bottom => "[data-hook='admin_tabs'], #admin_tabs[data-hook]",
:text => " <%= tab( :pos , :url => admin_pos_path) %>",
:sequence => {:after => "promo_admin_tabs"},
:disabled => false)
|
class AddLevelToUsers < ActiveRecord::Migration
def change
add_column :users, :level, :string, :null => false, :default => 'New Seller'
end
end
|
Pod::Spec.new do |s|
s.name = 'GeoFireX-Swift'
s.version = '1.0.0'
s.summary = 'The framework ported from GeoFireX for Swift.'
s.description = <<-DESC
This framework helps you to get geometry data from Firebase with geohash. Basic logic is the same as GeoFireX by codediodeio. (https://github.com/codediodeio/geofirex)
DESC
s.homepage = 'https://github.com/nob3rise/geofirex-swift'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = "Nob"
s.social_media_url = "https://twitter.com/noby111"
s.source = { :git => 'https://github.com/nob3rise/geofirex-swift.git', :tag => s.version.to_s }
s.ios.deployment_target = '13.0'
s.source_files = 'GeoFireX-Swift/Classes/**/*'
s.swift_versions = ['4.0', '4.1', '4.2', '5.0']
s.static_framework = true
s.dependency 'Firebase/Core'
s.dependency 'Firebase/Firestore'
s.dependency 'FirebaseFirestoreSwift'
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
class Club < ActiveRecord::Base
has_many :memberships
has_many :members, :through => :memberships
has_many :current_memberships
has_one :sponsor
has_one :sponsored_member, :through => :sponsor, :source => :sponsorable, :source_type => "Member"
private
def private_method
"I'm sorry sir, this is a *private* club, not a *pirate* club"
end
end |
require_relative "../../lib/extractor"
require_relative "../../lib/supervisor"
describe Charger::Extractor do
let(:file) { "input.txt" }
let(:supervisor) { Charger::Supervisor.new(input: file) }
let(:expected_data) do
" Name Balance \n Tom: $500.00 \n Lisa: $-93.00 \n Quincy: error \n"
end
subject { described_class.new(input: input, supervisor: supervisor) }
context "File" do
let(:input) { file }
it "reads from file" do
expect(subject).to receive(:take_file)
subject.extract
end
end
context "STDIN" do
let(:results) { `ruby lib/app.rb < input.txt` }
let(:input) { nil }
it "reads from stdin" do
expect(results).to eq(expected_data)
end
end
end
|
class Api::UsersController < ApplicationController
def index
if params[:filter] == "recent"
limit_param = params[:limit].to_i
limit = limit_param > 0 ? limit_param : 3
@users = User.all.order(id: :desc).limit(limit).pluck(:id)
render json: @users
else
@users = User.all
render :index
end
end
def create
@user = User.new(user_params)
if @user.save
log_in(@user)
render :show
else
render json: @user.errors.full_messages, status: 422
end
end
def update
if current_user.id != Integer( params[:id])
render json: ['please edit your own profile'], status: 404
else
# @user = User.find(params[:id])
if current_user.update(update_params)
@user = current_user
render :show_full_user
else
render json: @user.errors.full_messages, status: 422
end
end
end
def show
@user = User.find(params[:id])
render :show
end
def show_name
@user = User.includes(:products, :upvotes, :upvoted_products, :reviews).find_by(username: params[:username])
if @user
render :show_full_user
else
render json: ['username not found'], status: 404
end
end
def redirect_to_profile
@user = User.with_attached_profile_picture.find_by(username: params[:username])
if @user
redirect_to "/#/@#{params[:username]}"
else
render json: ['username not found'], status: 404
end
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :profile_picture, :profile_header)
end
def update_params
params.require(:user).permit( :email, :profile_picture, :profile_header, :name)
end
end
|
require 'rails_helper'
RSpec.describe "Api::V1::Projects", type: :request do
describe "GET /api/v1/projects/:id" do
before { get "/api/v1/projects/#{project.id}" }
describe "response" do
subject { response }
context "when project is released" do
let(:project) { create(:project, :released, name: "foo", title: "bar") }
it { is_expected.to have_http_status(:success) }
describe "body" do
subject { response.body }
it { is_expected.to eq(
{
data: {
id: project.id.to_s,
type: "project",
attributes: {
name: "foo",
title: "bar"
}
}
}.to_json
) }
end
end
context "when project is not released" do
let(:project) { create(:project) }
it { is_expected.to have_http_status(:not_found) }
describe "body" do
subject { response.body }
it { is_expected.to eq(
{
errors: [
{
status: "404",
title: "Not Found"
}
]
}.to_json
) }
end
end
end
end
end
|
module Neo4j
module Shared
extend ActiveSupport::Concern
extend ActiveModel::Naming
include ActiveModel::Conversion
begin
include ActiveModel::Serializers::Xml
rescue NameError; end # rubocop:disable Lint/HandleExceptions
include ActiveModel::Serializers::JSON
module ClassMethods
# TODO: Deprecate neo4j_session_name(name)
# remove?
def neo4j_session
Neo4j::ActiveBase.current_session
end
# remove?
def current_transaction
Neo4j::ActiveBase.current_transaction
end
# This should be used everywhere. Should make it easy
# to support a session-per-model system
def neo4j_query(*args)
Neo4j::ActiveBase.query(*args)
end
def new_query
Neo4j::ActiveBase.new_query
end
end
included do
self.include_root_in_json = Neo4j::Config.include_root_in_json
@_declared_properties ||= Neo4j::Shared::DeclaredProperties.new(self)
def self.i18n_scope
:neo4j
end
def self.inherited(other)
attributes.each_pair do |k, v|
other.inherit_property k.to_sym, v.clone, declared_properties[k].options
end
super
end
end
def declared_properties
self.class.declared_properties
end
def neo4j_query(*args)
self.class.neo4j_query(*args)
end
end
end
|
#==============================================================================
# ** Window_Chat
#------------------------------------------------------------------------------
# Esta classe lida com a janela do bate-papo.
#------------------------------------------------------------------------------
# Autor: Valentine
#==============================================================================
class Window_Chat < Window_Base
def initialize
@data = []
# Quando a resolução é alterada, a coordenada y é
#reajustada no adjust_windows_position da Scene_Map
super(12, adjust_y, 373, 158)
self.windowskin = Cache.system('WindowChat')
@scroll_bar = Scroll_Bar.new(self, Configs::MAX_CHAT_LINES, line_height)
@message_box = Text_Box.new(self, 78, 156, 291, 100, false, Vocab::SecondaryText)
@channel_box = Combo_Box.new(self, 4, 156, 70, [Vocab::Map, Vocab::All, Vocab::Party, Vocab::Guild, Vocab::Private], :list_up) { change_channel }
@private_box = Text_Box.new(self, 267, 134, 80, Configs::MAX_CHARACTERS)
@private_box.visible = false
write_message($network.motd, Configs::GLOBAL_COLOR)
@global_antispam_time = Time.now
self.opacity = 0
# Deixa o chat embaixo das outras janelas mesmo
#que o contents seja recriado posteriormente
self.z = 99
end
def adjust_y
Graphics.height - 181
end
def contents_height
@data.size * line_height
end
def in_border_area?
in_area?
end
def global_chat_spawning?
@global_antispam_time > Time.now
end
def refresh
contents.height == Configs::MAX_CHAT_LINES * line_height ? contents.clear : create_contents
contents.font.outline = false
contents.font.shadow = true
contents.font.bold = true
contents.font.size = 17
@scroll_bar.refresh
@data.each_with_index do |line, i|
change_color(text_color(line.color_id))
draw_text(0, line_height * i, width, line_height, line.text)
end
end
def change_channel
@private_box.visible = (@channel_box.index == Enums::Chat::PRIVATE)
end
def private(name)
# Impede que o nome do jogador seja alterado
@private_box.text = name.clone
@channel_box.index = Enums::Chat::PRIVATE
change_channel
end
def update
super
update_trigger
click
end
def update_trigger
return unless Input.trigger?(:C)
return if $typing && $typing != @message_box
send_message
if @message_box.active
@message_box.active = false
self.opacity = 0
else
@message_box.active = true
self.opacity = 255
end
end
def send_message
return unless @message_box.active
return if @message_box.text.strip.empty?
if @message_box.text == '/clear'
@data.clear
refresh
elsif @channel_box.index == Enums::Chat::GLOBAL && global_chat_spawning? && @message_box.text != '/who'
write_message(Vocab::GlobalSpawning, Configs::ERROR_COLOR)
Sound.play_buzzer
elsif @channel_box.index == Enums::Chat::PARTY && $game_actors[1].party_members.size == 0
write_message(Vocab::NotParty, Configs::ERROR_COLOR)
Sound.play_buzzer
elsif @channel_box.index == Enums::Chat::GUILD && $game_actors[1].guild.empty?
write_message(Vocab::NotGuild, Configs::ERROR_COLOR)
Sound.play_buzzer
elsif @channel_box.index == Enums::Chat::PRIVATE && @private_box.text.strip.size < Configs::MIN_CHARACTERS
write_message(sprintf(Vocab::Insufficient, Vocab::Name, Configs::MIN_CHARACTERS), Configs::ERROR_COLOR)
Sound.play_buzzer
else
$network.send_chat_message(@message_box.text, @channel_box.index, @private_box.text)
@global_antispam_time = Time.now + Configs::GLOBAL_ANTISPAM_TIME if @channel_box.index == Enums::Chat::GLOBAL && @message_box.text != '/who'
end
@message_box.clear
end
def click
return unless Mouse.click?(:L)
self.opacity = @message_box.active ? 255 : 0
end
def write_message(message, color_id)
# Remove o caractere de nova linha do comando Chamar Script
word_wrap(message.delete("\n")).each do |line|
@data << Chat_Line.new(line, color_id)
self.oy += line_height if @data.size > 7 && @data.size <= Configs::MAX_CHAT_LINES
@data.shift if @data.size > Configs::MAX_CHAT_LINES
end
refresh
end
end
|
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@product = Product.where(user_id: params[:id])
@user_info = UserInfo.find_by(user_id: @user.id)
@product = Product.where(user_id: @user.id)
@search_rate3 = search_rate(3)
@search_rate2 = search_rate(2)
@search_rate1 = search_rate(1)
@valution = @search_rate3.count - @search_rate1.count
@exclusion_products = Product.where(user_id: params[:id]).limit(6)
end
def new
@user = User.new
@user.build_user_info
end
def create
@user = User.new(strong_params)
if
@user.save
@user_image = UserImage.new(user_id: @user.id,image_url: 'member_no_image.png')
@user_image.save
sign_in @user
redirect_to user_infos_path(@user), notice: "ユーザー登録に成功しました"
else
redirect_to :back, flash: { error: @user.errors.full_messages }
end
end
# ユーザーの評価の配列を取り出す関数
def search_rate(rate)
@rate_id = @user.id
@return = Rate.where(user_id: @rate_id, rate: rate)
end
private
def strong_params
params.require(:user).permit(
:nickname, :email, :password, :password_confirmation,user_info_attributes:[:id, :first_name, :last_name, :kana_first_name, :kana_last_name, :birth_year, :birth_month, :birth_day],
)
end
end
|
#
# This file was ported to ruby from Composer php source code.
#
# Original Source: Composer\Package\Dumper\ArrayDumper.php
# Ref SHA: 346133d2a112dbc52163eceeee67814d351efe3f
#
# (c) Nils Adermann <naderman@naderman.de>
# Jordi Boggiano <j.boggiano@seld.be>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
module Composer
module Package
module Dumper
# Dumps a hash from a package
#
# PHP Authors:
# Konstantin Kudryashiv <ever.zet@gmail.com>
# Jordi Boggiano <j.boggiano@seld.be>
#
# Ruby Authors:
# Ioannis Kappas <ikappas@devworks.gr>
class HashDumper
class << self
def attr_dumpers
@attr_dumpers ||= []
end
def attr_dumper( attr, options = {}, &block)
if block_given?
attr_dumpers.push({ attr: attr, options: options, callback: block })
else
attr_dumpers.push({ attr: attr, options: options })
end
end
end
def dump(package)
# verify supplied arguments
unless package
raise ArgumentError,
'Invalid package configuration supplied.'
end
unless package.respond_to?(:pretty_name)
raise UnexpectedValueError,
'The package specified is missing the "pretty_name" method.'
end
unless package.respond_to?(:pretty_version)
raise UnexpectedValueError,
'The package specified is missing the "pretty_version" method.'
end
unless package.respond_to?(:version)
raise UnexpectedValueError,
'The package specified is missing the "version" method.'
end
data = {}
data['name'] = package.pretty_name
data['version'] = package.pretty_version
data['version_normalized'] = package.version
# load class specific attributes
HashDumper.attr_dumpers.each do |dumper|
if package.respond_to? dumper[:attr]
if dumper[:callback]
instance_exec package, data, &dumper[:callback]
else
attr_value = package.send dumper[:attr]
unless attr_value.nil? || attr_value.empty?
if dumper[:options][:to]
attr_key = dumper[:options][:to]
else
attr_key = dumper[:attr].to_s.tr('_', '-')
end
data[attr_key] = attr_value
end
end
end
end
data
end
require_relative 'hash_dumper/package_attribute_dumpers'
require_relative 'hash_dumper/complete_package_attribute_dumpers'
require_relative 'hash_dumper/root_package_attribute_dumpers'
end
end
end
end
|
class BoardCase
attr_accessor :boardcase_content
def initialize
@boardcase_content = " "
end
def add_content(player)
@boardcase_content = player.sign #on met le signe du joueur en cours dans l'array
end
end |
# require 'purchase/cart'
# require 'purchase/creation'
class Purchase < ApplicationRecord
# include Creation
# include Cart
belongs_to :customer
has_many :order_items
# has_many :workflows, as: :workable, class_name: "Workflow::Base"
before_create :generate_purchase_number
PURCHASE_NUMBER_PREFIX = "811"
state_machine :status, initial: :in_checkout do
event :confirm do
transition [:in_checkout] => :confirmed
end
event :cancel do
transition [:confirmed] => :canceled
end
end
def create_or_update_cart_item(item_param)
oi = self.order_items.where(catalog_id: item_param[:catalog_id]).last
return if oi.blank? && item_param[:quantity].to_i == 0
oi ||= OrderItem.create_item(self, item_param[:quantity], item_param[:catalog_id])
oi.quantity = item_param[:quantity]
oi.save
oi.destroy if oi.quantity == 0
end
def self.create_purchase(options)
purchase = Purchase.new
purchase.customer_id=options[:customer_id]
purchase.save!
purchase
end
def update_cart_data(items_param)
items_param.each do |items_param|
self.create_or_update_cart_item(items_param)
end
end
def prepare_cart_data
cart_data = {
:purchase_id => self.number
}
cart_data[:items] = self.order_items.map do |oi|
{
:price => oi.price,
:title => oi.title,
:quantity => oi.quantity,
:catalog_id => oi.catalog_id,
:order_item_id => oi.id,
:owner_id => oi.catalog.store_owner_id
}
end
cart_data
end
# def quotation_request_workflows
# self.workflows.select{|workflow| workflow.type="Workflow::QuotationRequest"}
# end
# def pending_quotation_request_workflow
# self.quotation_request_workflows.detect{|workflow| workflow.in_progress?}
# end
# def submit_quote_request(params)
# workflow = self.pending_quotation_request_workflow
# if params[:comment]
# request = workflow.pending_request
# request.create_comment!(:data => params[:comment])
# end
# workflow.submit!
# workflow
# # workflow.create_quotation_request
# # end
# def prepare_qoute_cart_Data
# workflow = self.pending_quotation_request_workflow
# data = workflow.try(:prepare_qoute_cart_Data) || {}
# data[:purchase_id] = self.number
# data
# end
# def add_to_qoute_cart(params)
# workflow = self.pending_quotation_request_workflow
# workflow ||= Workflow::QuotationRequest.create!(:workable => self)
# workflow.add_to_qoute_cart(params, self.customer_id)
# end
private
def generate_purchase_number
record = true
while record
random = "#{PURCHASE_NUMBER_PREFIX}#{Array.new(8){rand(10)}.join}"
record = Purchase.where(number: random).count > 0 ? true : false
end
self.number = random
end
end
|
# frozen_string_literal: true
# rot13.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that rot-13 'encryption' for yossarian-bot.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require_relative "yossarian_plugin"
class Rot13 < YossarianPlugin
include Cinch::Plugin
use_blacklist
def usage
"!r13 <message> - 'Encrypt' <message> with the ROT-13 cipher. Alias: !rot13."
end
def match?(cmd)
cmd =~ /^(!)?(r13)|(rot13)$/
end
match /r13 (.+)/, method: :rot13
match /rot13 (.+)/, method: :rot13
def rot13(m, text)
m.reply text.tr("A-Ma-mN-Zn-z", "N-Zn-zA-Ma-m"), true
end
end
|
require_relative 'view'
require_relative 'recipe'
require_relative 'scrape_allrecipes_service'
require 'open-uri'
require 'nokogiri'
require 'pry-byebug'
class Controller
def initialize(cookbook) # cookbook is an instance of Cookbook class
@view = View.new
@cookbook = cookbook
end
def create
#1. Ask user for information
recipe_array = @view.ask_for_recipe_info
#2. Create the instance of recipe
recipe = Recipe.new(
name: recipe_array[0],
description: recipe_array[1],
rating: recipe_array[2],
prep_time: recipe_array[3]
)
#3. Store the info
@cookbook.add_recipe(recipe)
end
def list
#1. Get all the recipes from the repo
recipes = @cookbook.all
#2. Ask view to display it all
@view.display(recipes)
end
def destroy
#1. Ask which one to be destroyed
index = @view.ask_for_input
#2. Find the right recipe on repository (cookbook)
#3. Ask the cookbook to destroy the recipe
recipe = @cookbook.remove_recipe(index)
end
def import
ingredient = @view.ask_for_ingredient
scraper = ScrapeAllrecipesService.new(ingredient)
recipes_array = scraper.call
index = @view.display_imported_recipes(recipes_array)
prep_time = scraper.fetch_prep_time(index)
recipes_array[index][:prep_time] = prep_time
recipe = Recipe.new(recipes_array[index])
@cookbook.add_recipe(recipe)
end
def mark_as_done
# 0) Print all the recipes and their indexes
list
# 1) Ask which recipe index to mark as done
# 2) Get the answer back from the user
index = @view.ask_which_recipe_to_mark_as_done
# 3) Find the correct recipe in the repo
# 4) Trigger the model method to mark it as done
# 5) Cookbook should PERSIST the change
@cookbook.mark_as_done(index)
end
end
|
class Api::V1::Transactions::TransactionInvoiceController < ApplicationController
def show
@transaction = Transaction.find(params[:transaction_id])
@invoice = @transaction.invoice
end
end
|
#!/usr/bin/ruby
module MyEnumerable
def my_each
for i in 0..self.length-1
puts self[i]
end
end
end
class Array
include MyEnumerable
end
[1,2,3,4].my_each { |i| puts i} #prints 1 2 3 4 in the terminal
|
require 'cells_helper'
RSpec.describe LoyaltyAccount::Cell::ExpirationDate do
let(:account) { Struct.new(:expiration_date).new(expires) }
let(:result) { cell(account).() }
def have_text(text)
have_selector '.loyalty_account_expiration_date', text: text
end
def have_warning_icon
have_selector '.fa.fa-warning'
end
context 'expires in future' do
let(:expires) { 6.months.from_now }
it '' do
expect(result).to have_text 'In 6 months'
expect(result).not_to have_warning_icon
end
end
context 'expires tomorrow' do
let(:expires) { 2.days.from_now - 5.seconds }
it '' do
expect(result).to have_text 'Tomorrow'
expect(result).not_to have_warning_icon
end
end
context 'expires today' do
let(:expires) { Date.today }
it '' do
expect(result).to have_text 'Today'
expect(result).to have_warning_icon
end
end
context 'expired yesterday' do
let(:expires) { 2.days.ago + 5.seconds }
it '' do
expect(result).to have_text 'Yesterday'
expect(result).to have_warning_icon
end
end
context 'expired in past' do
let(:expires) { 6.months.ago }
it '' do
expect(result).to have_text '6 months ago'
expect(result).to have_warning_icon
end
end
context 'unknown' do
let(:expires) { nil }
it '' do
expect(result).to have_text 'Unknown'
expect(result).to have_warning_icon
end
end
end
|
Rails.application.routes.draw do
authenticated do
resources :users, only: [:show] do
resources :answers
end
resources :questions do
collection do
get :answered
end
resources :answers do
member do
patch :select_answer
end
end
end
end
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "welcome#welcome", as: :welcome
end
|
require 'spec_helper'
require 'cinema/netflix'
require 'rspec/its'
require 'rspec-html-matchers'
describe Cinema::Netflix do
let(:netflix) { Cinema::Netflix.new('data/movies.txt') }
describe '.pay' do
it { expect { netflix.pay(5) }.to change { netflix.account }.by 5 }
end
describe '.how_much?' do
it "should raise error if movie wasn't found" do
expect { netflix.how_much?('abcd') }.to raise_error(RuntimeError,'Movie not found!')
end
context 'differen prices' do
it { expect(netflix.how_much?('Citizen Kane')).to eq 1 }
it { expect(netflix.how_much?('Lawrence of Arabia')).to eq 1.5 }
it { expect(netflix.how_much?('Blade Runner')).to eq 3 }
it { expect(netflix.how_much?('Up')).to eq 5 }
end
end
describe '.show' do
let(:movie_params) do
{ genre: 'Drama',
period: :classic,
country: 'France' }
end
context 'when not payed' do
it 'should raise error when not enough funds' do
expect { netflix.show(movie_params) }.to raise_error(RuntimeError,'Not enough funds!')
end
end
context 'when payed' do
before do
netflix.pay(10)
end
it 'should decrease balance' do
expect { netflix.show(movie_params) }.to change { netflix.account }.by(-1.5)
end
it 'should add money to cashbox' do
expect { netflix.show(movie_params) }.to change { Cinema::Netflix.cash }.by Money.new(1.5 * 100, 'USD')
end
context 'returned movie should have pre-setted params' do
subject { netflix.show(movie_params) }
its(:genre) { is_expected.to include('Drama') }
its(:period) { is_expected.to eq(:classic) }
its(:country) { is_expected.to include('France') }
end
it 'should print a message' do
time = Regexp.new(/([0-1][0-9]|[2][0-3]):[0-5][0-9]/)
expect { netflix.show(movie_params) }.to output(/Now showing: «(.*?)» #{time} - #{time}/).to_stdout
end
end
context 'filters usage' do
before do
netflix.pay(30)
end
context 'it should take a block' do
let(:block) { proc { |movie| movie.genre.include?('Action') && movie.year == 2000 } }
context 'returned movie should have pre-setted params' do
subject { netflix.show(&block) }
its(:genre) { is_expected.to include('Action') }
its(:year) { is_expected.to eq 2000 }
end
end
context 'it should use a defined filters' do
before do
netflix.define_filter(:before_60) { |movie| movie.year < 1960 }
netflix.define_filter(:crimes_only) { |movie| movie.genre.include?('Crime') }
end
context 'returned movie should have pre-setted params' do
subject { netflix.show(before_60: true, crimes_only: true) }
its(:year) { is_expected.to be < 1960 }
its(:genre) { is_expected.to include('Crime') }
end
end
context 'it should use filter and hash combined' do
before do
netflix.define_filter(:not_usa) { |movie| !movie.country.include?('USA') }
end
context 'returned movie should have pre-setted params' do
subject { netflix.show(not_usa: true, genre: 'Drama') }
its(:country) { is_expected.not_to include 'USA' }
its(:genre) { is_expected.to include('Drama') }
end
end
context 'it should use a defined filter with extra options' do
before do
netflix.define_filter(:custom_year) { |movie, year| movie.year > year }
end
context 'returned movie should have pre-setted params' do
subject { netflix.show(custom_year: 2010) }
its(:year) { is_expected.to be > 2010 }
end
end
end
end
describe '.define_filter' do
before do
netflix.define_filter(:custom_year) { |movie, year| movie.year > year }
end
it 'should store filters as blocks' do
expect(netflix.filters[:custom_year]).to be_a Proc
end
it 'should define new filter based on old one' do
expect(netflix.define_filter(:certain_custom_year, from: :custom_year, arg: 2014).arity).to eq 1
end
it 'should raise error if filter doesn\'t exist' do
expect { netflix.define_filter(:certain_custom_year, from: :blabla, arg: 2014) }.to raise_error(RuntimeError,'Filter doesn\'t exist!')
end
end
describe '.by_genre' do
context 'it should return array of films with specified genre' do
it { expect(netflix.by_genre.comedy).to all(have_attributes(genre: include('Comedy'))) }
end
it 'should raise error if entered genre is incorrect' do
expect { netflix.by_genre.cmdy }.to raise_error(RuntimeError, 'Incorrect genre "cmdy".')
end
end
describe '.by_county' do
context 'it should return array of films with specified genre' do
it { expect(netflix.by_country.japan).to all(have_attributes(country: include('Japan'))) }
end
it 'should raise error if entered genre is incorrect' do
expect { netflix.by_country.jpan }.to raise_error(RuntimeError, 'No film from such country was found.')
end
end
describe '.render_to' do
include RSpecHtmlMatchers
before { netflix.render_to('data/html_pages/page.html') }
let(:rendered) { open('data/html_pages/page.html').read }
it 'should contain columns with movie attributes' do
expect(rendered).to have_tag('tr') do
with_tag 'td', text: 'Title:'
with_tag 'td', text: 'Year:'
with_tag 'td', text: 'Country:'
with_tag 'td', text: 'Date:'
with_tag 'td', text: 'Genre:'
with_tag 'td', text: 'Duration:'
with_tag 'td', text: 'Director:'
with_tag 'td', text: 'Budget:'
with_tag 'td', text: 'Rating:'
with_tag 'td', text: 'Cast:'
end
end
it 'should support UTF-8' do
expect(rendered).to have_tag('meta', with: { charset: 'UTF-8' })
end
end
end
|
# $LOAD_PATH << File.dirname(__FILE__) +'/../lib'
require 'rubygems'
require 'glutton_ratelimit'
puts "Maximum of 12 executions every 5 seconds (Bursty):"
rl = GluttonRatelimit::BurstyTokenBucket.new 12, 5
start = Time.now
n = 0
rl.times(25) do
puts "#{n += 1} - #{Time.now - start}"
# Simulating a constant-time task:
sleep 0.1
end
# The 25th execution should occur after 10 seconds has elapsed.
puts "Maximum of 3 executions every 3 seconds (Averaged):"
rl = GluttonRatelimit::AveragedThrottle.new 3, 3
# AverageThrottle will attempt to evenly space executions within the allowed period.
start = Time.now
n = 0
rl.times(7) do
puts "#{n += 1} - #{Time.now - start}"
# Simulating a 0 to 1 second random-time task:
sleep rand
end
# The 7th execution should occur after 6 seconds has elapsed. |
source 'http://rubygems.org'
gem 'rails', '~> 3.2.0'
gem 'json'
gem 'jquery-rails'
gem 'sass-rails'
gem 'thin'
gem 'therubyracer'
gem 'whenever', :require => false
gem 'sorcery'
gem 'simple_form'
gem 'carrierwave'
gem 'savon'
gem 'draper'
gem 'kaminari'
gem 'delayed_job_active_record'
gem 'daemons'
gem 'sunspot_rails'
gem 'paper_trail'
gem 'mini_magick'
gem 'nokogiri'
gem 'active_attr'
gem 'gritter'
gem 'dotiw'
gem 'colorize' # Used for colored console output
gem 'bootstrap-sass', '2.0.0'
gem 'bootstrap'
gem 'rails-gallery'
group :development do
gem 'sqlite3', :require => false
gem 'pry'
gem 'rails-dev-tweaks'
gem 'sunspot_solr'
gem 'progress_bar' # Sunspot launch progress bar
end
group :production do
gem 'pg'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'coffee-rails'
gem 'uglifier'
gem 'compass-rails'
end
group :test do
gem 'rspec-rails' # Lower Level Software Testing
gem "capybara" # Simple Browser Driver
gem "selenium-webdriver"
gem "cucumber-rails", :require => false
gem "factory_girl_rails", "~> 3.0"
gem "sunspot_test"
gem 'database_cleaner'
gem 'faker'
end
|
class UsersController < ApplicationController
before_action :set_user, :check_userself, :only => [:show, :edit, :coupon]
def show
if @user.invite_token == ""
@secure_number = SecureRandom.hex(8)
#Invitation.create!(invite_token: @secure_number)
@user.invite_token = @secure_number
@user.save
end
@invite_link = "http://localhost:3000" + "/invitations/" + @user.invite_token
@invited_users = User.joins("INNER JOIN invitations ON invitations.invited_id = users.id").where("user_id = #{current_user.id}")
end
def update
set_user
if @user == current_user
if @user.update(user_params)
flash[:notice] = "個人資料已更新"
redirect_to user_path(@user)
else
render edit_user_path(@user)
flash[:alert] = @user.errors.full_messages.to_sentence
end
else
flash[:alert] = "權限不足!"
redirect_to root_path
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email, :role, :name, :tel, :cel, :invite_token)
end
def check_userself
if current_user!=@user
redirect_to root_path
flash[:alert] = "權限不足!"
end
end
end
|
class BundleContent < ActiveRecord::Migration
def self.up
create_table "bundle_contents" do |t|
t.column :content, :text, :limit => 16777215
end
add_column "bundles", :bundle_content_id, :integer
end
def self.down
drop_table "bundle_contents"
remove_column "bundles", :bundle_content_id
end
end
|
class Agendas::TagsController < TagsController
before_action :set_taggable
private
def set_taggable
@taggable = Agenda.find(params[:agenda_id])
end
end
|
class UsersController < ApplicationController
def index
authorize! :manage, User
@users = User.all_paged(params.slice(*User::DEFAULT_FILTERS.keys).symbolize_keys)
@filters = params.reverse_merge(User::DEFAULT_FILTERS)
end
def new
if current_user
redirect_to root_path
end
@user = User.new
@is_human = IsHuman.new(@user)
render :layout => false if request.xhr?
end
def create
if IsHuman.correct?(params[:user])
@user = User.build(params[:user])
if @user.save
cookies[:auth_token] = @user.auth_token
redirect_to_root_or_last_location "Registered successfully!"
else
render "new"
end
else
# Is human test failed
@user = User.new(params[:user])
@is_human = IsHuman.new(@user)
flash.now[:alert] = "We don't think you are human, please try again."
render "new"
end
end
def edit
@user = get_editable_user(params[:id])
authorize! :edit, @user
prep_view
end
def update
@user = get_editable_user(params[:id])
authorize! :edit, @user
if @user.update_attributes(filtered_params)
handle_redirect
else
prep_view
render 'edit'
end
end
def mark_all_as_viewed
current_user.last_viewed_all_at = DateTime.now.utc
current_user.save
redirect_to latest_posts_path, :notice => "Marked all posts as read"
end
private
def filtered_params
filtered = params[:user]
if cannot? :change_role, @user
filtered.delete(:role)
end
if cannot? :change_status, @user
filtered.delete(:active)
end
if cannot? :change_password, @user
filtered.delete(:password)
filtered.delete(:password_confirmation)
end
filtered
end
def get_editable_user(id)
if id.present? #and can? :manage, User
user = User.find(id)
authorize! :edit, user
return user
end
current_user
end
def handle_redirect
if can? :manage, User
redirect_to users_url, :notice => 'User has been updated'
else
redirect_to my_profile_path, :notice => 'Your profile as been updated'
end
end
def prep_view
@replays = @user.replays.paginate(:page => params[:page], :per_page => 5).order('created_at desc')
end
end
|
require_relative './test_helper'
require 'time'
require './lib/merchant'
require './lib/merchant_repository'
require 'mocha/minitest'
class MerchantRepositoryTest < Minitest::Test
def setup
@engine = mock
@m_repo = MerchantRepository.new("./fixture_data/merchants_sample.csv", @engine)
end
def test_it_exists_and_has_attributes
assert_instance_of MerchantRepository, @m_repo
assert_equal false, @m_repo.all.nil?
assert_equal @m_repo.engine, @engine
end
def test_find_by_id
turing = Merchant.new({id: 1,
name: "Turing School",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
target = Merchant.new({id: 2,
name: "target",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
@m_repo.all << turing
@m_repo.all << target
assert_equal turing, @m_repo.find_by_id(1)
assert_equal target, @m_repo.find_by_id(2)
assert_nil @m_repo.find_by_id(154151554)
end
def test_find_by_name
turing = Merchant.new({id: 1,
name: "Turing School",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
target = Merchant.new({id: 2,
name: "target",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
@m_repo.all << turing
@m_repo.all << target
assert_equal turing, @m_repo.find_by_name("TurInG School")
assert_equal target, @m_repo.find_by_name("targeT")
assert_nil @m_repo.find_by_name("548947asdoihogihof")
end
def test_find_all_by_name
turing = Merchant.new({id: 1,
name: "Turing School",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
target = Merchant.new({id: 2,
name: "target",
created_at: "01/07/21",
updated_at: "01/07/21"}, @engine)
@m_repo.all << turing
@m_repo.all << target
assert_equal [target], @m_repo.find_all_by_name("arget")
assert_equal [], @m_repo.find_all_by_name("targetTuring")
end
def test_new_highest_id
start = 12334365
expected = (start + 1)
assert_equal expected, @m_repo.new_highest_id
end
def test_create
attributes = {id: 2,
name: "Exciting Store",
created_at: "01/07/21",
updated_at: "01/07/21"}
@m_repo.create(attributes)
expected = @m_repo.find_all_by_name("Exciting Store")
assert_equal expected[0].id, @m_repo.all.last.id
end
def test_update
attributes = {
name: "TSSD"
}
@m_repo.update(12334141, attributes)
expected = @m_repo.find_by_id(12334141)
merchant_test_updated_at = @m_repo.find_by_id(12334141).updated_at.strftime("%d/%m/%Y")
assert_equal "TSSD", expected.name
assert_equal Time.now.strftime("%d/%m/%Y"), merchant_test_updated_at
end
def test_delete
assert_equal 12, @m_repo.all.count
@m_repo.delete(12334141)
assert_equal 11, @m_repo.all.count
assert_nil @m_repo.find_by_id(12334141)
end
def test_inspect
assert_equal "<MerchantRepository 12 rows>", @m_repo.inspect
end
end
|
module BGGTigris
def self.nickname
'tigris'
end
def self.my_turn?(doc, username)
current = doc.css('img[alt="Current Player"]').first.parent.css('.t_medtitle').first.content
username == current
end
def self.icon
'http://farm1.staticflickr.com/129/344808931_e82e768a14_s.jpg'
end
end
|
# This file configures our Error logging.
Rails.application.config.to_prepare do
# In the Era schema, the column is ERROR_LOG.ZUSERID:
NdrError.user_column = :custom_user_column
# Authenticate all users:
NdrError.check_current_user_authentication = ->(_context) { true }
end
|
FactoryGirl.define do
factory :word do
text_hindi "भालू"
text_romanized "baalu"
meaning
category
end
end
|
class GFA
##
# Find all independent modules by greedily crawling the linking entries for
# each segment, and returns an Array of GFA objects containing each individual
# module. If +recalculate+ is false, it trusts the current calculated
# matrix unless none exists
def split_modules(recalculate = true)
recalculate_matrix if recalculate || @matrix.nil?
missing_segments = (0 .. @matrix_segment_names.size - 1).to_a
modules = []
until missing_segments.empty?
mod = matrix_find_module(missing_segments[0])
mod.segments.set.map(&:name).map(&:value).each do |name|
missing_segments.delete(@matrix_segment_names.index(name))
end
modules << mod
end
modules
end
##
# Finds the entire module containing the segment with index +segment_index+
# in the matrix (requires calling +recalculate_matrix+ first!). Returns the
# module as a new GFA
def matrix_find_module(segment_index)
# Initialize
segs = [segment_index]
edges = []
new_segs = true
# Iterate until no new segments are found
while new_segs
new_segs = false
segs.each do |seg|
@matrix.size.times do |k|
next if seg == k
v = @matrix[[seg, k].max][[seg, k].min]
next if v.empty?
edges += v
unless segs.include?(k)
new_segs = true
segs << k
end
end
end
end
# Save as GFA and return
o = GFA.new
segs.each { |k| o << segments[k] }
edges.uniq.each { |k| o << @matrix_edges[k] }
o
end
##
# Calculates a matrix where all links between segments are represented by the
# following variables:
#
# +@matrix_segment_names+ includes the names of all segments (as String) with
# the order indicating the segment index in the matrix
#
# +@matrix+ is an Array of Arrays of Arrays, where the first index indicates
# the row index segment, the second index indicates the column index segment,
# and the third index indicates each of the links between those two. Note that
# matrix only stores the lower triangle, so the row index must be stictly less
# than the column index. For example, +@matrix[3][1]+ returns an Array of all
# index links between the segment with index 3 and the segment with index 1:
# ```
# [
# [ ], # Row 0 is always empty
# [[] ], # Row 1 stores connections to column 0
# [[], [] ], # Row 2 stores connections to columns 0 and 1
# [[], [], [] ], # Row 3 stores connections to columns 0, 1, and 2
# ... # &c
# ]
# ```
#
# +@matrix_edges+ is an Array of GFA::Record objects representing all edges in
# the GFA. The order indicates the index used by the values of +@matrix+
def recalculate_matrix
@matrix_segment_names = segments.set.map(&:name).map(&:value)
@matrix = @matrix_segment_names.size.times.map { |i| Array.new(i) { [] } }
@matrix_edges = all_edges
@matrix_edges.each_with_index do |edge, k|
names = edge.segments(self).map(&:name).map(&:value)
indices = names.map { |i| @matrix_segment_names.index(i) }
indices.each do |a|
indices.each do |b|
break if a == b
@matrix[[a, b].max][[a, b].min] << k
end
end
end
end
end
|
require 'bindable_block'
class Surrogate
class Options
attr_accessor :options, :default_proc
def initialize(options, default_proc)
self.options, self.default_proc = options, default_proc
end
def has?(name)
options.has_key? name
end
def [](key)
options[key]
end
def to_hash
options
end
def default(instance, invocation, &no_default)
if options.has_key? :default
options[:default]
elsif default_proc
# This works for now, but it's a kind of crappy solution because
# BindableBlock adds and removes methods for each time it is invoked.
#
# A better solution would be to instantiate it before passing it to
# the options, then we only have to bind it to an instance and invoke
BindableBlock.new(instance.class, &default_proc)
.bind(instance)
.call(*invocation.args, &invocation.block)
else
no_default.call
end
end
end
end
|
module TheCityAdmin
class UserBarcode < ApiObject
tc_attr_accessor :id,
:barcode,
:created_at
# Constructor.
#
# @param json_data JSON data of the user barcode.
def initialize(json_data)
initialize_from_json_object(json_data)
end
end
end
|
require 'json'
class Product
def initialize(wombat_product, config={})
@wombat_product = wombat_product['product']
@config = config
@ebay_product = {}
end
def search_params
{ start_time_from: @config['ebay_start_time_from'],
start_time_to: @config['ebay_start_time_to'],
end_time_from: Time.now.to_s,
end_time_to: (Time.now + 30*24*60*60),
include_variations: 'true',
detail_level: 'ReturnAll',
pagination: { entries_per_page: 25,
page_number: @config['ebay_page_number'] }
}
end
def ebay_product
@ebay_product = ebay_product_initial_values(@config, @wombat_product)
@ebay_product[:PrimaryCategory] = ebay_product_primary_category(@config) if @config['category_id']
@ebay_product[:ReturnPolicy] = ebay_product_return_policy(@config) if @config['return_policy']
@ebay_product[:ShippingDetails] = ebay_product_shipping_details(@config) if ebay_product_shipping_details_present?(@config)
@ebay_product[:PaymentMethods] = ebay_product_payment_methods(@config) if @config['payment_methods']
@ebay_product[:PictureDetails] = ebay_product_picture_details(@wombat_product) if @wombat_product['images'].is_a?(Array)
@ebay_product[:ItemSpecifics] = ebay_product_item_specifics(@wombat_product) if @wombat_product['properties']
if ebay_product_variants_present?(@wombat_product)
@ebay_product[:Variations] = ebay_product_variantions_set(@wombat_product)
else
@ebay_product[:Quantity] = @wombat_product['quantity']
@ebay_product[:StartPrice] = @wombat_product['price']
end
@ebay_product[:listing_details] = ebay_product_listing_details(@wombat_product)
{ item: @ebay_product }
end
def self.wombat_product_hash(ebay_product)
wombat_product = wombat_product_initial_values(ebay_product)
wombat_product[:images] = wombat_product_images(ebay_product) if ebay_product[:picture_details][:picture_url]
if wombat_variants_present?(ebay_product)
wombat_product[:variants] = wombat_variants(ebay_product)
else
wombat_product[:quantity] = ebay_product[:quantity]
wombat_product[:start_price] = ebay_product[:price]
end
wombat_product
end
private
def self.wombat_product_id(ebay_product)
ebay_product[:application_data] || ebay_product[:item_id]
end
def self.wombat_product_initial_values(ebay_product)
wombat_product = {}
wombat_product['id'] = wombat_product_id(ebay_product)
{ 'ebay_item_id' => :item_id,
'name' => :title,
'sku' => :sku,
'description' => :description }.each do |wombat_key, ebay_value|
wombat_product[wombat_key] = ebay_product[ebay_value]
end
wombat_product
end
def self.wombat_product_images(ebay_product)
[ebay_product[:picture_details][:picture_url]].flatten.map { |picture_url| { url: picture_url } }
end
def self.wombat_variants(ebay_product)
[ebay_product[:variations][:variation]].flatten.map { |variation| wombat_variant(variation) }
end
def self.wombat_variants_present?(ebay_product)
ebay_product[:variations] && ebay_product[:variations][:variation] && !ebay_product[:variations][:variation].empty?
end
def self.wombat_variant(variation)
wombat_variant = {}
{ sku: :sku,
start_price: :price,
quantity: :quantity }.each do |wombat_key, ebay_value|
wombat_variant[wombat_key] = variation[ebay_value]
end
wombat_variant[:options] = {}
variation[:variation_specifics][:name_value_list].each do |name_value|
wombat_variant[:options].merge({ name_value[:name] => name_value[:value] })
end
wombat_variant
end
def ebay_product_initial_values(config, wombat_product)
ebay_product = {}
{ 'country' => :Country,
'currency' => :Currency,
'listing_duration' => :ListingDuration,
'location' => :Location,
'dispatch_time_max' => :DispatchTimeMax,
'paypal_email_address' => :PayPalEmailAddress,
'condition_id' => :ConditionID }.each do |womabt_key, ebay_value|
ebay_product[ebay_value] = config[womabt_key] if config[womabt_key]
end
ebay_product[:ItemID] = wombat_product['ebay_item_id'] if wombat_product['ebay_item_id']
ebay_product[:ApplicationData] = wombat_product['id']
{ 'name' => :Title,
'sku' => :SKU,
'description' => :Description }.each do |wombat_key, ebay_value|
ebay_product[ebay_value] = wombat_product[wombat_key]
end
ebay_product
end
def ebay_product_primary_category(config)
{ CategoryID: config['category_id'] }
end
def ebay_product_return_policy(config)
JSON.parse(config['return_policy'])
end
def ebay_product_shipping_details(config)
shipping_details = {}
shipping_details[:ShippingType] = config['shipping_type'] if config['shipping_type']
shipping_details[:ShippingServiceOptions] = JSON.parse(config['shipping_service_options']) if config['shipping_service_options']
shipping_details
end
def ebay_product_shipping_details_present?(config)
config['shipping_service_options'] || config['shipping_type']
end
def ebay_product_payment_methods(config)
config['payment_methods'].split(',').map(&:strip)
end
def ebay_product_picture_details(wombat_product)
{ :PictureURL => wombat_product['images'].map { |image| image['url'].split('&').first } }
end
def ebay_product_item_specifics(wombat_product)
{ :NameValueList => wombat_product['properties'].map { |name, value| { Name: name, Value: value } } }
end
def ebay_product_variants_present?(wombat_product)
wombat_product['variants'].is_a?(Array) && wombat_product['variants'].first
end
def ebay_product_variants(wombat_product)
wombat_product['variants'].map { |variant| ebay_product_variant(variant) }
end
def ebay_product_variant(variant)
ebay_variant = {}
{ 'price' => :StartPrice,
'quantity' => :Quantity,
'sku' => :SKU }.each do |wombat_key, ebay_value|
ebay_variant[ebay_value] = variant[wombat_key]
end
ebay_variant[:Deleted] = true if variant['deleted_at'].is_a?(String) && !variant['deleted_at'].strip.empty?
ebay_variant[:VariationSpecifics] = {}
ebay_variant[:VariationSpecifics][:NameValueList] = variant['options'].map { |name, value| { Name: name, Value: value } }
ebay_variant
end
def ebay_product_variant_pictures(wombat_product)
wombat_product['variants'].map do |variant|
ebay_variant = {}
ebay_variant[:VariationSpecificValue] = variant['options'].map { |name, value| value }
ebay_variant[:PictureURL] = variant['images'].map { |image| image['url'].split('&').first }
ebay_variant
end
end
def ebay_product_variation_specifics(wombat_product)
option_types = @wombat_product['variants'].map{ |v| v['options'] }
variation_specifics = {}
variation_specifics[:NameValueList] = @wombat_product['options'].map do |key|
{ Name: key, Value: option_types.map { |option_type| option_type[key] } }
end
variation_specifics
end
def ebay_product_variantions_set(wombat_product)
ebay_variations_set = {}
ebay_variations_set[:VariationSpecificsSet] = ebay_product_variation_specifics(wombat_product) if wombat_product["options"]
ebay_variations_set[:Variation] = ebay_product_variants(wombat_product)
ebay_variations_set[:Pictures] = {}
ebay_variations_set[:Pictures][:VariationSpecificName] = wombat_product['options'].dup if wombat_product['options']
ebay_variations_set[:Pictures][:VariationSpecificPictureSet] = ebay_product_variant_pictures(wombat_product)
ebay_variations_set
end
def ebay_product_listing_details(wombat_product)
{ start_time: wombat_product['available_on'] }
end
end
|
class BikesController < ApplicationController
def index
@bikes = Bike.all
render json: @bikes, include: [:zipcode]
end
def show
@bike = Bike.find(params[:id])
if @bike
render json: @bike
else
render json: {message:"We couldn't find a bike with that id"}
end
end
def create
@bike = Bike.new(
title: params[:title],
description: params[:description],
image: params[:image],
zipcode_id: params[:zipcode_id]
)
if @bike.save
redirect_to 'http://localhost:3001/'
else
render status: 422
end
end
end
|
class EventAnalyzer
attr_accessor :app_sha, :good_count, :count, :good_ips, :bad_ips
EXPECTED_IP_NETBLOCK = 28
def initialize(app_sha)
self.app_sha = app_sha
reset
end
def execute
reset
# SQL is very fast at counting and sorting
# also this could theoretically be a very large data set so summarize data in the SQL server
ip_event_counts = Event.where(app_sha: app_sha).select('ip, COUNT(*) AS event_count').group(:ip)
# group available IPs by their /28 netblock using a hash
# note that if the number of unique IPs was expected to be very large we might store the masked IP
# in the database as well and let SQL handling the grouping
netblocks = {}
ip_event_counts.each do |ip|
netblock = ip_to_netblock(ip[:ip])
netblocks[netblock] ||= []
netblocks[netblock] << ip
end
# find the "good" IP range
# since the sample is random, don't assume there will be 14 good IPs -- instead, find the
# most commonly seen netblock and assume those are the "good" apps that don't have malware
highest_event_count = 0
good_netblock = nil
netblocks.each do |netblock, ip_list|
event_count = ip_list.map{|ip| ip[:event_count].to_i }.inject(0, :+)
if event_count > highest_event_count
good_netblock = netblock
highest_event_count = event_count
end
end
# if results were found, store good IP range and event count, put the rest in the bad IP list
if good_netblock.present?
self.good_ips = netblocks[good_netblock].map{|ip| ip_to_dotted(ip[:ip]) }
self.count = highest_event_count
netblocks.each do |netblock, ip_list|
unless netblock == good_netblock
bad_ips << ip_list.map{|ip| ip_to_dotted(ip[:ip]) }
self.count += ip_list.map{|ip| ip[:event_count].to_i }.inject(0, :+)
end
end
self.bad_ips = bad_ips.flatten
end
result
end
def result
{ 'count' => count, 'good_ips' => good_ips, 'bad_ips' => bad_ips }
end
protected
def reset
self.good_count = 0
self.count = 0
self.good_ips = []
self.bad_ips = []
end
def ip_to_object(ip)
IPAddr.new(ip.to_i, Socket::AF_INET)
end
def ip_to_dotted(ip)
ip_to_object(ip).to_s
end
def ip_to_netblock(ip)
ip_to_object(ip).mask(EXPECTED_IP_NETBLOCK).to_i
end
end
|
require "rails_helper"
require "app/services/manage_hound"
require "app/services/add_hound_to_repo"
require "app/models/github_user"
describe AddHoundToRepo do
describe "#run" do
context "with org repo" do
context "when repo is part of a team" do
context "when request succeeds" do
it "adds Hound user to first repo team with admin access" do
github_team_id = 1001
github = build_github(github_team_id: github_team_id)
allow(github).to receive(:add_user_to_team).and_return(true)
result = AddHoundToRepo.run("foo/bar", github)
expect(result).to eq true
expect(github).to have_received(:add_user_to_team).
with(github_team_id, hound_github_username)
end
end
context "when request fails" do
it "returns false" do
github = build_github
allow(github).to receive(:add_user_to_team).and_return(false)
result = AddHoundToRepo.run("foo/bar", github)
expect(result).to eq false
end
end
end
context "when repo is not part of a team" do
context "when Services team does not exist" do
it "adds hound to new Services team" do
repo_name = "foo/bar"
github_team = double("GithubTeam", id: 1001)
github = build_github
allow(github).to receive(:user_teams).and_return([])
allow(github).to receive(:org_teams).and_return([])
allow(github).to receive(:add_user_to_team)
allow(github).to receive(:create_team).and_return(github_team)
AddHoundToRepo.run(repo_name, github)
expect(github).to have_received(:create_team).with(
org_name: "foo",
team_name: AddHoundToRepo::GITHUB_TEAM_NAME,
repo_name: repo_name
)
expect(github).to have_received(:add_user_to_team).
with(github_team.id, hound_github_username)
end
end
context "when Services team exists" do
it "adds user to existing Services team" do
services_team = double(
"GithubTeam",
id: 222,
name: "Services",
permission: "push"
)
github = build_github(github_team_id: services_team.id)
allow(github).to receive(:repo_teams).and_return([])
allow(github).to receive(:org_teams).and_return([services_team])
allow(github).to receive(:add_repo_to_team)
allow(github).to receive(:add_user_to_team)
repo_name = "foo/bar"
AddHoundToRepo.run(repo_name, github)
expect(github).to have_received(:add_repo_to_team).
with(services_team.id, repo_name)
expect(github).to have_received(:add_user_to_team).
with(services_team.id, hound_github_username)
end
context "when team name is lowercase" do
it "adds user to the team" do
services_team = double(
"GithubTeam",
id: 222,
name: "services",
permission: "push"
)
github = build_github(github_team_id: services_team.id)
allow(github).to receive(:repo_teams).and_return([])
allow(github).to receive(:org_teams).and_return([services_team])
allow(github).to receive(:add_repo_to_team)
allow(github).to receive(:add_user_to_team)
repo_name = "foo/bar"
AddHoundToRepo.run(repo_name, github)
expect(github).to have_received(:add_repo_to_team).
with(services_team.id, repo_name)
expect(github).to have_received(:add_user_to_team).
with(services_team.id, hound_github_username)
end
end
end
end
context "when Services team has pull access" do
it "updates permissions to push access" do
github_team =
double("RepoTeams", id: 222, name: "Services", permission: "pull")
github = build_github
allow(github).to receive(:add_user_to_team)
allow(github).to receive(:user_teams).and_return([])
allow(github).to receive(:org_teams).and_return([github_team])
allow(github).to receive(:update_team)
allow(github).to receive(:add_repo_to_team)
AddHoundToRepo.run("foo/bar", github)
expect(github).to have_received(:update_team).
with(github_team.id, permission: "push")
end
end
end
context "when repo is not part of an organization" do
it "adds user as collaborator" do
repo_name = "foo/bar"
github_repo = double("GithubRepo", organization: false)
github = double("GithubApi", repo: github_repo, add_collaborator: nil)
AddHoundToRepo.run(repo_name, github)
expect(github).to have_received(:add_collaborator).
with(repo_name, hound_github_username)
end
end
end
def build_github(github_team_id: 10)
github_team = double("GithubTeam", id: github_team_id, permission: "admin")
github_repo = double("GithubRepo", organization: double(login: "foo"))
double(
"GithubApi",
repo: github_repo,
user_teams: [github_team],
repo_teams: [github_team],
)
end
def hound_github_username
ENV["HOUND_GITHUB_USERNAME"]
end
end
|
class CreatePdcaPosts < ActiveRecord::Migration[5.0]
def change
create_table :pdca_posts do |t|
t.text :plan
t.text :do
t.text :check
t.text :action
t.references :user, foreign_key: true
t.timestamps
end
add_index :pdca_posts, [:user_id, :created_at]
end
end
|
=begin
#EVE Swagger Interface
#An OpenAPI for EVE Online
OpenAPI spec version: 0.8.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.3.1
=end
require 'spec_helper'
require 'json'
# Unit tests for EVEOpenAPI::ContactsApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'ContactsApi' do
before do
# run before each test
@instance = EVEOpenAPI::ContactsApi.new
end
after do
# run after each test
end
describe 'test an instance of ContactsApi' do
it 'should create an instance of ContactsApi' do
expect(@instance).to be_instance_of(EVEOpenAPI::ContactsApi)
end
end
# unit tests for delete_characters_character_id_contacts
# Delete contacts
# Bulk delete contacts --- Alternate route: `/dev/characters/{character_id}/contacts/` Alternate route: `/v2/characters/{character_id}/contacts/`
# @param character_id An EVE character ID
# @param contact_ids A list of contacts to delete
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :token Access token to use if unable to set a header
# @return [nil]
describe 'delete_characters_character_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_alliances_alliance_id_contacts
# Get alliance contacts
# Return contacts of an alliance --- Alternate route: `/dev/alliances/{alliance_id}/contacts/` Alternate route: `/v2/alliances/{alliance_id}/contacts/` --- This route is cached for up to 300 seconds
# @param alliance_id An EVE alliance ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [Integer] :page Which page of results to return
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetAlliancesAllianceIdContacts200Ok>]
describe 'get_alliances_alliance_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_alliances_alliance_id_contacts_labels
# Get alliance contact labels
# Return custom labels for an alliance's contacts --- Alternate route: `/dev/alliances/{alliance_id}/contacts/labels/` Alternate route: `/legacy/alliances/{alliance_id}/contacts/labels/` Alternate route: `/v1/alliances/{alliance_id}/contacts/labels/` --- This route is cached for up to 300 seconds
# @param alliance_id An EVE alliance ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetAlliancesAllianceIdContactsLabels200Ok>]
describe 'get_alliances_alliance_id_contacts_labels test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_characters_character_id_contacts
# Get contacts
# Return contacts of a character --- Alternate route: `/dev/characters/{character_id}/contacts/` Alternate route: `/v2/characters/{character_id}/contacts/` --- This route is cached for up to 300 seconds
# @param character_id An EVE character ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [Integer] :page Which page of results to return
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetCharactersCharacterIdContacts200Ok>]
describe 'get_characters_character_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_characters_character_id_contacts_labels
# Get contact labels
# Return custom labels for a character's contacts --- Alternate route: `/dev/characters/{character_id}/contacts/labels/` Alternate route: `/legacy/characters/{character_id}/contacts/labels/` Alternate route: `/v1/characters/{character_id}/contacts/labels/` --- This route is cached for up to 300 seconds
# @param character_id An EVE character ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetCharactersCharacterIdContactsLabels200Ok>]
describe 'get_characters_character_id_contacts_labels test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_corporations_corporation_id_contacts
# Get corporation contacts
# Return contacts of a corporation --- Alternate route: `/dev/corporations/{corporation_id}/contacts/` Alternate route: `/v2/corporations/{corporation_id}/contacts/` --- This route is cached for up to 300 seconds
# @param corporation_id An EVE corporation ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [Integer] :page Which page of results to return
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetCorporationsCorporationIdContacts200Ok>]
describe 'get_corporations_corporation_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for get_corporations_corporation_id_contacts_labels
# Get corporation contact labels
# Return custom labels for a corporation's contacts --- Alternate route: `/dev/corporations/{corporation_id}/contacts/labels/` Alternate route: `/legacy/corporations/{corporation_id}/contacts/labels/` Alternate route: `/v1/corporations/{corporation_id}/contacts/labels/` --- This route is cached for up to 300 seconds
# @param corporation_id An EVE corporation ID
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [String] :if_none_match ETag from a previous request. A 304 will be returned if this matches the current ETag
# @option opts [String] :token Access token to use if unable to set a header
# @return [Array<GetCorporationsCorporationIdContactsLabels200Ok>]
describe 'get_corporations_corporation_id_contacts_labels test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for post_characters_character_id_contacts
# Add contacts
# Bulk add contacts with same settings --- Alternate route: `/dev/characters/{character_id}/contacts/` Alternate route: `/v2/characters/{character_id}/contacts/`
# @param character_id An EVE character ID
# @param contact_ids A list of contacts
# @param standing Standing for the contact
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [Array<Integer>] :label_ids Add custom labels to the new contact
# @option opts [String] :token Access token to use if unable to set a header
# @option opts [BOOLEAN] :watched Whether the contact should be watched, note this is only effective on characters
# @return [Array<Integer>]
describe 'post_characters_character_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for put_characters_character_id_contacts
# Edit contacts
# Bulk edit contacts with same settings --- Alternate route: `/dev/characters/{character_id}/contacts/` Alternate route: `/v2/characters/{character_id}/contacts/`
# @param character_id An EVE character ID
# @param contact_ids A list of contacts
# @param standing Standing for the contact
# @param [Hash] opts the optional parameters
# @option opts [String] :datasource The server name you would like data from
# @option opts [Array<Integer>] :label_ids Add custom labels to the contact
# @option opts [String] :token Access token to use if unable to set a header
# @option opts [BOOLEAN] :watched Whether the contact should be watched, note this is only effective on characters
# @return [nil]
describe 'put_characters_character_id_contacts test' do
it "should work" do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
|
# require_relative 'prescription'
class Interaction < ActiveRecord::Base
belongs_to :med1, class_name: "Prescription"
belongs_to :med2, class_name: "Prescription"
def self.interactions(med)
self.all.select{|med1| med1.med1_id == med.id}
end
end
|
# encoding: utf-8
control "V-92629" do
title "The Apache web server log files must only be accessible by privileged users."
desc "Log data is essential in the investigation of events. If log data were to become compromised, competent forensic analysis and discovery of the true source of potentially malicious system activity would be difficult, if not impossible, to achieve. In addition, access to log records provides information an attacker could potentially use to their advantage since each event record might contain communication ports, protocols, services, trust relationships, user names, etc.
The web server must protect the log data from unauthorized read, write, copy, etc. This can be done by the web server if the web server is also doing the logging function. The web server may also use an external log system. In either case, the logs must be protected from access by non-privileged users.false"
impact 0.5
tag "check": "Determine the location of the 'HTTPD_ROOT' directory and the 'httpd.conf' file:
# httpd -V | egrep -i 'httpd_root|server_config_file'
-D HTTPD_ROOT='/etc/httpd'
-D SERVER_CONFIG_FILE='conf/httpd.conf'
Review the log file location.
To determine permissions for log files, from the command line, navigate to the directory where the log files are located and enter the following command:
ls -alH <HTTPD_ROOT>/log*
Note the owner and group permissions on these files. Only system administrators and service accounts running the server should have permissions to the files.
If any users other than those authorized have read access to the log files, this is a finding.
"
tag "fix": "To protect the integrity of the data that is being captured in the log files, ensure that only the members of the Auditors group, Administrators, and the user assigned to run the web server software is granted permissions to read the log files."
# Write Check Logic Here
end
|
module SlackBotServer
class App
def initialize
@filenames = ['', '.html', 'index.html', '/index.html']
@rack_static = ::Rack::Static.new(
-> { [404, {}, []] },
root: File.expand_path('../../public', __FILE__),
urls: ['/']
)
check_database!
end
def self.instance
@instance ||= Rack::Builder.new do
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :get
end
end
run SlackBotServer::App.new
end.to_app
end
def call(env)
# api
response = Api::Endpoints::RootEndpoint.call(env)
# Check if the App wants us to pass the response along to others
if response[1]['X-Cascade'] == 'pass'
# static files
request_path = env['PATH_INFO']
@filenames.each do |path|
response = @rack_static.call(env.merge('PATH_INFO' => request_path + path))
return response if response[0] != 404
end
end
# Serve error pages or respond with API response
case response[0]
when 404, 500
content = @rack_static.call(env.merge('PATH_INFO' => "/errors/#{response[0]}.html"))
[response[0], content[1], content[2]]
else
response
end
end
def check_database!
rc = Mongoid.default_client.command(ping: 1)
return if rc && rc.ok?
fail rc.documents.first['error'] || 'Unexpected error.'
rescue StandardError => e
warn "Error connecting to MongoDB: #{e.message}"
raise e
end
end
end
|
require_relative '../spec_helper'
RSpec.describe OpenAPIParser::PathItemFinder do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'parse_path_parameters' do
subject { OpenAPIParser::PathItemFinder.new(root.paths) }
it 'matches a single parameter with no additional characters' do
result = subject.parse_path_parameters('{id}', '123')
expect(result).to eq({'id' => '123'})
end
it 'matches a single parameter with extension' do
result = subject.parse_path_parameters('{id}.json', '123.json')
expect(result).to eq({'id' => '123'})
end
it 'matches a single parameter with additional characters' do
result = subject.parse_path_parameters('stuff_{id}_hoge', 'stuff_123_hoge')
expect(result).to eq({'id' => '123'})
end
it 'matches multiple parameters with additional characters' do
result = subject.parse_path_parameters('{stuff_with_underscores-and-hyphens}_{id}_hoge', '4_123_hoge')
expect(result).to eq({'stuff_with_underscores-and-hyphens' => '4', 'id' => '123'})
end
# Open API spec does not specifically define what characters are acceptable as a parameter name,
# so allow everything in between {}.
it 'matches when parameter contains regex characters' do
result = subject.parse_path_parameters('{id?}.json', '123.json')
expect(result).to eq({'id?' => '123'})
result = subject.parse_path_parameters('{id.}.json', '123.json')
expect(result).to eq({'id.' => '123'})
result = subject.parse_path_parameters('{{id}}.json', '{123}.json')
expect(result).to eq({'id' => '123'})
end
it 'fails to match' do
result = subject.parse_path_parameters('stuff_{id}_', '123')
expect(result).to be_nil
result = subject.parse_path_parameters('{p1}-{p2}.json', 'foo.json')
expect(result).to be_nil
result = subject.parse_path_parameters('{p1}.json', 'foo.txt')
expect(result).to be_nil
result = subject.parse_path_parameters('{{id}}.json', '123.json')
expect(result).to be_nil
end
it 'fails to match when a Regex escape character is used in the path' do
result = subject.parse_path_parameters('{id}.json', '123-json')
expect(result).to be_nil
end
it 'fails to match no input' do
result = subject.parse_path_parameters('', '')
expect(result).to be_nil
end
it 'matches when the last character of the variable is the same as the next character' do
result = subject.parse_path_parameters('{p1}schedule', 'adminsschedule')
expect(result).to eq({'p1' => 'admins'})
result = subject.parse_path_parameters('{p1}schedule', 'usersschedule')
expect(result).to eq({'p1' => 'users'})
end
end
describe 'find' do
subject { OpenAPIParser::PathItemFinder.new(root.paths) }
it do
expect(subject.class).to eq OpenAPIParser::PathItemFinder
result = subject.operation_object(:get, '/pets')
expect(result.class).to eq OpenAPIParser::PathItemFinder::Result
expect(result.original_path).to eq('/pets')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1pets/get').object_reference
expect(result.path_params.empty?).to eq true
result = subject.operation_object(:get, '/pets/1')
expect(result.original_path).to eq('/pets/{id}')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1pets~1{id}/get').object_reference
expect(result.path_params['id']).to eq '1'
result = subject.operation_object(:post, '/pets/lessie/adopt/123')
expect(result.original_path).to eq('/pets/{nickname}/adopt/{param_2}')
expect(result.operation_object.object_reference)
.to eq root.find_object('#/paths/~1pets~1{nickname}~1adopt~1{param_2}/post').object_reference
expect(result.path_params['nickname']).to eq 'lessie'
expect(result.path_params['param_2']).to eq '123'
end
it 'matches path items that end in a file extension' do
result = subject.operation_object(:get, '/animals/123/456.json')
expect(result.original_path).to eq('/animals/{groupId}/{id}.json')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1animals~1{groupId}~1{id}.json/get').object_reference
expect(result.path_params['groupId']).to eq '123'
expect(result.path_params['id']).to eq '456'
end
it 'ignores invalid HTTP methods' do
expect(subject.operation_object(:exit, '/pets')).to eq(nil)
expect(subject.operation_object(:blah, '/pets')).to eq(nil)
end
end
end
|
module WsdlMapperTesting
class FakeS8r
def initialize
@xmls = {}
end
def xml_for_input(input, xml)
@xmls[input] = xml
end
def to_xml(input)
@xmls.fetch input
end
end
end
|
class Skill
class << self
def all
['Organized', 'Clean', 'Punctual', 'Strong', 'Crazy', 'Flexible']
end
end
end
|
# Widget for displaying the image data.
# If you want mouse events for interacting with the image, they can be put in this class.
class ImageWidget < Qt::Widget
# Initialize the widget.
def initialize(parent=nil)
@parent = parent
super(parent)
setMinimumSize(512, 512)
@pixmap = Qt::Pixmap.new
end
# This method paints the image to the screen.
def paintEvent(event)
painter = Qt::Painter.new
painter.begin(self)
painter.drawPixmap(0, 0, @pixmap)
painter.end
end
# Converts the RMagick object to a Qt pixmap.
def load_pixmap
blob = @parent.image.to_blob {
self.format = "PGM"
self.depth = 8
}
@pixmap.loadFromData(Qt::ByteArray.fromRawData(blob, blob.size))
update
end
end
|
source "https://supermarket.getchef.com"
metadata
cookbook 'apt'
cookbook 'elasticsearch'
cookbook 'memcached'
cookbook 'runit'
# Convenience function to use local (development) cookbooks instead of remote
# repositories if they are found in ./cookbooks.
#
# Important:
# - local cookbook folder names MUST be identical to the cookbook name
# found in the metadata.rb files or they will NOT be used. As an example:
# /cookbooks/chef-percona will not be used whereas ./cookbooks/percona will
# - make sure to remove Berksfile.lock or the known remotes will be used
#
def load_cookbook(dep, options)
cookbooks = '.cookbooks'
if Dir.exists?("#{cookbooks}/#{dep}")
cookbook dep, path: "#{cookbooks}/#{dep}"
else
cookbook dep, options
end
end
# Define cookbooks using standard Berksfile cookbook syntax
load_cookbook 'git-ppa', git: 'https://github.com/alt3/chef-git-ppa'
load_cookbook 'nginx', git: 'https://github.com/phlipper/chef-nginx'
load_cookbook 'percona', git: 'https://github.com/phlipper/chef-percona'
load_cookbook 'redis', git: 'https://github.com/phlipper/chef-redis'
load_cookbook 'postgresql', git: 'https://github.com/phlipper/chef-postgresql'
load_cookbook 'mongodb', git: 'https://github.com/edelight/chef-mongodb'
load_cookbook 'php5-ppa', git: 'https://github.com/alt3/chef-php5-ppa'
load_cookbook 'hhvm', git: 'https://github.com/jubianchi/hhvm-cookbook'
load_cookbook "curl", git: "https://github.com/phlipper/chef-curl"
load_cookbook "composer", git: "https://github.com/Morphodo/chef-composer"
load_cookbook 'phpunit', git: 'https://github.com/alt3/chef-phpunit'
load_cookbook 'phpcs', git: 'https://github.com/alt3/chef-phpcs'
load_cookbook 'heroku', git: 'https://github.com/alt3/chef-heroku.git'
load_cookbook 'java', git: 'https://github.com/agileorbit-cookbooks/java'
load_cookbook 'logstash', git: 'https://github.com/lusis/chef-logstash'
load_cookbook 'kibana_lwrp', git: 'https://github.com/lusis/chef-kibana'
load_cookbook 'cakebox', git: 'https://github.com/alt3/chef-cakebox'
|
require 'test_driver/logger'
require 'test_driver/process'
module Browsers
PROGRAM_FILES = ENV[ENV.has_key?('ProgramFiles(x86)') ? 'ProgramFiles(x86)' : 'ProgramFiles']
def os_version
if @windows_version.nil?
@windows_version = mac? ? System::Environment.o_s_version.version.major : nil
end
@windows_version
end
def mac?
if @is_mac.nil?
@is_mac = RbConfig::CONFIG['target_os'] =~ /darwin/i != nil
end
@is_mac
end
# Base host class.
# Derived class needs to have below methods implemented:
# name - name of the host
# path - path to the host
class BrowserBase < ProcessWrapper
include TestLogger
include Browsers
def self.get_browser(name)
browser_constant_name = NAMES.select do |i|
Browsers.const_get(i).new.short_name == name
end.first
Browsers.const_get(browser_constant_name) if browser_constant_name
end
def short_name
name.split.last.downcase
end
def initialize
super
@platform = mac? ? 'mac' : 'win'
end
def start(url)
info "Starting #{name}"
__start path, url_to_args(url)
end
def stop
info "Stopping #{name}"
__stop
end
def path
mac? ? mac_path : windows_path
end
def url_to_args(url)
"#{url}"
end
def installed?
__exist? path
end
def name
raise "Sub-classes must provide the browser's name (should match what Silverlight's HtmlPage.BrowserInformation.Name returns)"
end
end
class IE < BrowserBase
def name
"Microsoft Internet Explorer"
end
def windows_path
"#{PROGRAM_FILES}/Internet Explorer/iexplore.exe"
end
def supported?
installed? and not mac?
end
end
class Safari < BrowserBase
def name
"Apple Safari"
end
def windows_path
"#{PROGRAM_FILES}/Safari/Safari.exe"
end
def mac_path
"/Applications/Firefox.app/Contents/MacOS/safari"
end
def supported?
installed?
end
end
class FireFox < BrowserBase
def name
"Mozilla Firefox"
end
def windows_path
"#{PROGRAM_FILES}/Mozilla Firefox/firefox.exe"
end
def mac_path
"/Applications/Firefox.app/Contents/MacOS/firefox #{url} &"
end
def supported?
installed?
end
end
class Chrome < BrowserBase
def name
"Google Chrome"
end
def windows_path
"#{ENV['SystemDrive']}#{ENV['HOMEPATH']}\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
end
def supported?
installed? and not mac?
end
end
class Opera < BrowserBase
def name
"Opera"
end
def windows_path
"#{PROGRAM_FILES}/Opera/opera.exe"
end
def mac_path
"/Applications/Opera.app"
end
def supported?
installed?
end
end
NAMES = constants - ["PROGRAM_FILES", "BrowserBase"]
end
|
form_for @content, :html => {:multipart => true} do |content|
tab "content" do
tab_item content.object.new_record? ? t('.new_content') : t('.edit_content', :name => content.object.name) do
content.text_field :name
content.text_area :description
content.select :purpose, t('.purpose')
end
tab_item t('.source') do
p "Enter either the URL where your content is located <em>OR</em> select the local file that contains the content"
content.text_field :url
content.file_field :content_file
content.text_field :base_url
end
end
submit_combo
end
|
# Migration to create preferences table
class UpdatePreferences < ActiveRecord::Migration[4.2]
def change
remove_column :preferences, :service, :string
remove_column :preferences, :url, :string
add_column :preferences, :auto_close_brackets, :boolean, after: :user_id
add_column :preferences, :smart_indent, :boolean, after: :user_id
end
end
|
class Favorite < ApplicationRecord
belongs_to :petprofile
belongs_to :user
end
|
class AddResetToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :reset, :string
add_column :users, :reset_confirmation, :string
end
end
|
# typed: strict
# frozen_string_literal: true
module Packwerk
class NodeProcessorFactory < T::Struct
extend T::Sig
const :root_path, String
const :context_provider, Packwerk::ConstantDiscovery
const :constant_name_inspectors, T::Array[ConstantNameInspector]
const :checkers, T::Array[Checker]
sig { params(filename: String, node: AST::Node).returns(NodeProcessor) }
def for(filename:, node:)
::Packwerk::NodeProcessor.new(
reference_extractor: reference_extractor(node: node),
filename: filename,
checkers: checkers,
)
end
private
sig { params(node: AST::Node).returns(::Packwerk::ReferenceExtractor) }
def reference_extractor(node:)
::Packwerk::ReferenceExtractor.new(
context_provider: context_provider,
constant_name_inspectors: constant_name_inspectors,
root_node: node,
root_path: root_path,
)
end
end
end
|
class Product < ActiveRecord::Base
validates :description, :name, presence: true
validates :price, numericality: {only_integer: true}
def formatted_price
price_in_dollars = price.to_f * 10
sprintf("$%.2f", price_in_dollars)
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{coolerator.vision}
s.version = "0.2.10"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Corey Innis"]
s.date = %q{2009-11-19}
s.description = %q{A Rails plugin}
s.email = %q{corey@coolerator.net}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
".gitmodules",
".screwrc",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"app/placeholder.txt",
"app/placeholder.txt",
"coolerator.vision.gemspec",
"lib/coolerator.vision.rb",
"public/javascripts/vendor/coolerator/coolerator.base.js",
"public/javascripts/vendor/coolerator/coolerator.base.js",
"public/javascripts/vendor/coolerator/coolerator.filter.js",
"public/javascripts/vendor/coolerator/coolerator.filter.js",
"public/javascripts/vendor/coolerator/coolerator.module.js",
"public/javascripts/vendor/coolerator/coolerator.module.js",
"public/javascripts/vendor/coolerator/coolerator.registrar.js",
"public/javascripts/vendor/coolerator/coolerator.registrar.js",
"public/javascripts/vendor/coolerator/coolerator.remote.js",
"public/javascripts/vendor/coolerator/coolerator.remote.js",
"public/javascripts/vendor/coolerator/coolerator.view.js",
"public/javascripts/vendor/coolerator/coolerator.view.js",
"public/javascripts/vendor/jquery/jquery.easing.js",
"public/javascripts/vendor/jquery/jquery.easing.js",
"public/javascripts/vendor/jquery/jquery.js",
"public/javascripts/vendor/jquery/jquery.js",
"public/javascripts/vendor/prez/prez.js",
"public/javascripts/vendor/prez/prez.js",
"rails/init.rb",
"script/pair",
"spec/coolerator.vision_spec.rb",
"spec/javascripts/support/spec_helper.js",
"spec/javascripts/vendor/coolerator/coolerator.base_spec.js",
"spec/javascripts/vendor/coolerator/coolerator.filter_spec.js",
"spec/javascripts/vendor/coolerator/coolerator.module_spec.js",
"spec/javascripts/vendor/coolerator/coolerator.registrar_spec.js",
"spec/javascripts/vendor/coolerator/coolerator.remote_spec.js",
"spec/javascripts/vendor/coolerator/coolerator.view_spec.js",
"spec/spec.opts",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/coreyti/coolerator.vision}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.5}
s.summary = %q{A Rails plugin}
s.test_files = [
"spec/coolerator.vision_spec.rb",
"spec/spec_helper.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/array_extension.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/asset_location.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/asset_manager.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/configuration.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/dispatcher.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/js_file.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/dir.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/file.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/file_not_found.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/root.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/spec_dir.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/spec_runner.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/streaming_spec_runner.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources/suite_completion.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/resources.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/server.rb",
"spec/support/vendor/screw-unit/lib/screw_unit/string_extension.rb",
"spec/support/vendor/screw-unit/lib/screw_unit.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/array_extension_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/asset_location_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/asset_manager_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/configuration_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/dispatcher_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/js_file_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/dir_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/file_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/root_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/spec_dir_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/spec_suite_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/resources/suite_completion_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit/server_spec.rb",
"spec/support/vendor/screw-unit/spec/screw_unit_spec_helper.rb",
"spec/support/vendor/screw-unit/spec/screw_unit_spec_suite.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rspec>, [">= 1.2.9"])
else
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
else
s.add_dependency(%q<rspec>, [">= 1.2.9"])
end
end
|
class InstrumentController < ApplicationController
helper :work, :edition
def show
@instrument = Instrument.find(params[:id])
end
end
|
Rails.application.routes.draw do
devise_for :users
mount Ckeditor::Engine => '/ckeditor'
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
#top
get '/', to: 'top#index'
#user
get '/user/question', to: 'user#question'
#cart
get '/cart/complete', to: 'cart#complete'
get '/cart/:id', to: 'cart#index'
#post
get 'posts', to: 'posts#index'
get 'posts/:id', to: 'posts#show'
#contact
get 'contacts', to: 'contacts#index'
get 'contacts/:id', to: 'contacts#show'
post 'contacts', to: 'contacts#create'
#like
resources :likes, only: [:create, :destroy]
end
|
class ProductsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index, :show]
before_action :set_product, only: [:show]
def index
@products = Product.all
end
def show
set_product
end
private
#def product_params
#params.require(:product).permit(:name, :description, :logo, :pictures, :add_info)
#end
def set_product
@product = Product.find(params[:id])
end
end
|
#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
class Runner < Thor
desc "solve", "solve problems"
method_option :all, :type => :boolean, :default => true, :aliases => "-a", :desc => "Run all tests"
method_option :only, :type => :array, :required => false, :aliases => "-o", :desc => "Run specific tests"
method_option :except, :type => :array, :required => false, :aliases => "-e", :desc => "Exclude specific tests"
def solve
# Get RB files, excluding this one, sort by number
files = Dir['**/*'].grep(/\d+\.rb/i).sort{ |a,b| a.scan(/\d+/).first.to_i <=> b.scan(/\d+/).first.to_i }
files = files.map{ |e| File.basename(e, '.*') }
files = files.find_all{|f| options[:only].include?(f)} unless options[:only].nil?
files = files.find_all{|f| not options[:except].include?(f)} unless options[:except].nil?
threads = []
files.each do |file|
threads << Thread.new {
problem_num = File.basename(file, '.*')
start = Time.new
ans = `ruby #{file}.rb`.strip
span = (Time.new - start) * 1000.0
span = (sprintf "%.4f ms", span)
msg = "Problem: #{problem_num}\t"
msg+= "Solution: #{ans}".widen(30)
msg+= "Timespan: #{span}"
puts msg
}
end
threads.each(&:join)
end
default_task = :all
no_tasks do
def capture_stdout(&block)
original_stdout = $stdout
$stdout = fake = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
fake.string
end
end
end
class Solution
def initialize(problem,answer,elapsed)
@problem = problem
@answer = answer
@elapsed = elapsed
end
def problem; @problem end
def answer; @answer end
def elapsed; @elapsed end
end
class String
def widen(width)
wide = self
while wide.length < 30
wide = wide.gsub(/$/, ' ')
end
wide
end
end
# !! NOTHING BELOW THIS
#
# Starts the process if this is being used as a script
# If this is being used as a library this will be skipped
if __FILE__ == $0
Runner.start
end |
class AddCashFlowLotSizeToProperties < ActiveRecord::Migration
def change
add_column :properties,:cash_flow,:decimal,precision: 15,scale: 2
add_column :properties,:lot_size,:integer
end
end |
class AddHtmlCacheFields < ActiveRecord::Migration
def up
add_column :repositories, :notes_html, :text
add_column :production_units, :notes_html, :text
add_column :assessments, :notes_html, :text
add_column :assessments, :preservation_risks_html, :text
add_column :collections, :notes_html, :text
add_column :collections, :description_html, :text
add_column :collections, :private_description_html, :text
end
def down
remove_column :repositories, :notes_html
remove_column :producers, :notes_html
remove_column :assessments, :notes_html
remove_column :assessments, :preservation_risks_html
remove_column :collections, :notes_html
remove_column :collections, :description_html
remove_column :collections, :private_description_html
end
end |
Refinery::PagesController.class_eval do
before_action :find_all_landing_images, :only => [:home]
protected
def find_all_landing_images
@landing_images = Refinery::LandingImages::LandingImage.order('position ASC')
end
end |
class HomeController < ApplicationController
def index
@email = user_signed_in? ? current_user.email : 'undefined'
end
end
|
#1から10000までの数字を順にカンマ区切りで出力するプログラムを作成する
#出力条件
#3の倍数のときは数字を出力せずに文字列Fizzを出力
#5の倍数のときは数字を出力せずに文字列Buzzを出力
#15の倍数のときは数字を出力せずに文字列FizzBuzzを出力
#
#追加制限
#剰余演算子は使用しない
#最大値まで第1引数の倍数を配列にして返すメソッド
def multiple_calc(multi, max)
score_result = []
work = multi
while (work <= max)
score_result.push(work)
work += multi
end
return score_result
end
#初期値設定
MIN = 1
MAX = 10000
MULTI_FIZZBUZZ = 15
MULTI_FIZZ = 3
MULTI_BUZZ = 5
arr = []
#予め倍数を格納した配列を作成
score_FB = multiple_calc(MULTI_FIZZBUZZ, MAX)
score_F = multiple_calc(MULTI_FIZZ, MAX)
score_B = multiple_calc(MULTI_BUZZ, MAX)
#配列への格納
(MIN..MAX).each do |number|
if score_FB.include?(number)
arr.push(:FizzBuzz)
elsif score_F.include?(number)
arr.push(:Fizz)
elsif score_B.include?(number)
arr.push(:Buzz)
else
arr.push(number)
end
end
#出力
print arr.join(",")
|
class AddLastSyncToGsNodes < ActiveRecord::Migration
def change
add_column :gs_nodes, :last_sync, :datetime
end
end
|
require 'maestro_plugin'
require 'puppet_blacksmith'
# overwrite git execution to use our utils
module Blacksmith
class Git
def exec_git(cmd)
new_cmd = "LANG=C #{git_cmd_with_path(cmd)}"
Maestro.log.debug("Running git: #{new_cmd}")
exit_status, out = Maestro::Util::Shell.run_command(new_cmd)
if !exit_status.success?
raise Blacksmith::Error, "Command #{new_cmd} failed with exit status #{exit_status.exit_code}\n#{out}"
end
return out
end
end
end
module MaestroDev
module Plugin
class PuppetForgeWorker < Maestro::MaestroWorker
PUSH_MSG = "[blacksmith] Bump version"
attr_accessor :forge, :modulefile
def validate_fields
errors = []
errors << "Missing Forge username" if get_field('forge_username', '').empty?
errors << "Missing Forge password" if get_field('forge_password', '').empty?
raise ConfigError, "Configuration errors: #{errors.join(', ')}" unless errors.empty?
end
def forge_push
validate_fields
username = get_field('forge_username')
self.forge = Blacksmith::Forge.new(username, get_field('forge_password'), get_field('forge_url'))
log_output("Uploading file to the Puppet Forge as '#{forge.username}' at '#{forge.url}'")
path = get_field('path') || get_field('scm_path')
raise ConfigError, "Missing module path" unless path
Maestro.log.debug("Looking for metadata files")
git = Blacksmith::Git.new(path)
modulefile_path = Blacksmith::Modulefile::FILES.find {|f| File.exists?("#{git.path}/#{f}")}
raise PluginError, "metadata.json or Modulefile not found at #{git.path}/#{modulefile_path}" unless modulefile_path
self.modulefile = Blacksmith::Modulefile.new(File.join(git.path, modulefile_path))
Maestro.log.debug("Checking if last commit was automated")
if last_commit_was_automated?(git.path)
log_output("Module was already released")
not_needed
return
end
Maestro.log.debug("Tagging version #{modulefile.version}")
git.tag!(modulefile.version)
log_output("Tagged version #{modulefile.version}")
# pushing the package set or find the build under pkg/
pkg_path = File.expand_path(File.join(path,"pkg"))
regex = /^#{username}-#{modulefile.name}-.*\.tar\.gz$/
package = get_field('package')
if package
# if it doesn't exist, then try as a relative path
package = File.expand_path(File.join(path, package)) unless File.exists?(package)
raise PluginError, "Unable to find package to upload at #{get_field('package')} nor #{package}" unless File.exists?(package)
else
f = Dir.new(pkg_path).select{|f| f.match(regex)}.last
raise PluginError, "Unable to find package to upload at #{pkg_path} with #{regex}" unless f
package = File.expand_path(File.join(pkg_path, f))
end
log_output("Uploading module #{modulefile.name}/#{modulefile.version} from #{package}")
forge.push!(modulefile.name, package)
new_version = modulefile.bump!
log_output("Bumping version from #{modulefile.version} to #{new_version}")
git.commit_modulefile!
git.push!
log_output("Finished Puppet module release")
rescue Blacksmith::Error => e
raise PluginError, e.message
end
private
def last_commit_was_automated?(path)
# get last commit
# --pretty=%B would be better but not available in git 1.7
cmd = "cd #{path} && LANG=C git log -1 --pretty=oneline"
Maestro.log.debug("Running git: #{cmd}")
result = Maestro::Util::Shell.run_command(cmd)
Maestro.log.debug("Git output: [#{result[0].exit_code}] #{result[1]}")
output = result[1]
output.empty? or output.include?(PUSH_MSG)
end
def log_output(msg)
Maestro.log.info(msg)
write_output("#{msg}\n")
end
end
end
end
|
require 'rails_helper'
describe Item do
%i(price seller title).each do |field|
it "requires a #{field}" do
# item = build :item, :price => nil
item = build :item, field => nil
expect( item.valid? ).to be false
end
end
it 'requires price to be positive' do
item = build :item, price: -1.00
# expect( item ).not_to be_valid ~> valid?
expect( item.valid? ).to be false
end
end
|
class ClientAddrsController < ApplicationController
before_filter :authenticate, :only => [:create, :edit, :update, :new]
def new
@title = "Add Address for Client"
@client = client_account
@client_addr = @client.client_addrs.new
end
def create
@client = client_account
@client_addr = @client.client_addrs.build(params[:client_addr])
if @client_addr.save
flash[:success] = "Added Address for the Client"
redirect_to client_account
else
@title = "Sign Up"
render 'new'
end
end
def edit
@client = client_account
@client_addr = @client.client_addrs.find_by_id(params[:id])
@title = "Edit Client Address"
end
def update
@client = client_account
@client_addr = @client.client_addrs.find(params[:id])
if @client_addr.update_attributes(params[:client_addr])
redirect_to @client, :flash => { :success => "Address Updated!" }
else
@title = "Edit Client Address"
render 'edit'
end
end
def destroy
@client = client_account
@client_addr = @client.client_addrs.find_by_id(params[:id])
@client_addr.destroy
redirect_to @client
end
end |
class RemoveSlugFromCategories < ActiveRecord::Migration[4.2]
def change
remove_column :categories, :slug, :remove
end
end
|
module Whiteplanes
Token = Struct.new(:token, :step, :parameter)
@tokens = {
push: Token.new(' ', 2, true),
copy: Token.new(' \t ', 3, true),
slide: Token.new(' \t\n', 3, true),
duplicate: Token.new(' \n ', 3, false),
swap: Token.new(' \n\t', 3, false),
discard: Token.new(' \n\n', 3, false),
add: Token.new('\t ', 4, false),
sub: Token.new('\t \t', 4, false),
mul: Token.new('\t \n', 4, false),
div: Token.new('\t \t ', 4, false),
mod: Token.new('\t \t\t', 4, false),
store: Token.new('\t\t ', 3, false),
retrieve: Token.new('\t\t\t', 3, false),
register: Token.new('\n ', 3, true),
call: Token.new('\n \t', 3, true),
jump: Token.new('\n \n', 3, true),
equal: Token.new('\n\t ', 3, true),
less: Token.new('\n\t\t', 3, true),
return: Token.new('\n\t\n', 3, false),
end: Token.new('\n\n\n', 3, false),
cout: Token.new('\t\n ', 4, false),
iout: Token.new('\t\n \t', 4, false),
cin: Token.new('\t\n\t ', 4, false),
iin: Token.new('\t\n\t\t', 4, false)
}
class Push
def process(context)
context.stack << @param.to_i(2)
end
end
class Copy
def process(context)
context.stack << context.stack[@param.to_i(2)]
end
end
class Slide
def process(context)
value = context.stack.pop
@param.to_i(2).times do
context.stack.pop
end
context.stack << value
end
end
class Duplicate
def process(context)
context.stack << context.stack.last
end
end
class Swap
def process(context)
context.stack[-1], context.stack[-2] = context.stack[-2], context.stack[-1]
end
end
class Discard
def process(context)
context.stack.pop
end
end
class Add
def process(context)
lhs, rhs = context.stack.pop, context.stack.pop
context.stack << lhs + rhs
end
end
class Sub
def process(context)
lhs, rhs = context.stack.pop, context.stack.pop
context.stack << lhs - rhs
end
end
class Mul
def process(context)
lhs, rhs = context.stack.pop, context.stack.pop
context.stack << lhs * rhs
end
end
class Div
def process(context)
lhs, rhs = context.stack.pop, context.stack.pop
context.stack << lhs / rhs
end
end
class Mod
def process(context)
lhs, rhs = context.stack.pop, context.stack.pop
context.stack << lhs % rhs
end
end
class Store
def process(context)
value = context.stack.pop
address = context.stack.pop
context.heap[address] = value
end
end
class Retrieve
def process(context)
address = context.stack.pop
context.stack << context.heap[address]
end
end
class Register
def process(context)
context.labels[@param] = @location
end
end
class Call
def process(context)
context.callstack << @location
context.counter = context.labels[@param]
end
end
class Jump
def process(context)
context.counter = context.labels[@param]
end
end
class Equal
def process(context)
value = context.stack.pop
context.counter = context.labels[@param] if value == 0
end
end
class Less
def process(context)
value = context.stack.pop
context.counter = context.labels[@param] if value != 0
end
end
class Return
def process(context)
context.counter = context.callstack.pop
end
end
class End
def process(context)
context.counter = (2**(0.size * 8 -2) -1) - 1
end
end
class Cout
def process(context)
value = context.stack.pop
context.output(value.chr)
end
end
class Iout
def process(context)
value = context.stack.pop
context.output(value)
end
end
class Cin
def process(context)
address = context.stack.pop
value = context.input(:cin)
context.heap[address] = value.ord
end
end
class Iin
def process(context)
address = context.stack.pop
value = context.input(:iin)
context.heap[address] = value
end
end
# Set property.
@tokens.keys.each do |name|
command = const_get name.capitalize
token = @tokens[name.to_sym]
command.class_eval do
instance_variable_set("@token", token.token)
instance_variable_set("@step", token.step)
instance_variable_set("@parameter", token.parameter)
def initialize(parameter, location)
instance_variable_set("@param", parameter)
instance_variable_set("@location", location)
end
def self.token
instance_variable_get("@token")
end
def self.step
instance_variable_get("@step")
end
def self.parameter
instance_variable_get("@parameter")
end
end
end
end |
class RMQ
# @return [RMQResource]
def self.resource
RMQResource
end
# @return [RMQResource]
def resource
RMQResource
end
end
class RMQResource
class << self
def find(resource_type, resource_name)
application = PMApplication.current_application
application.resources.getIdentifier(resource_name.to_s,
resource_type.to_s,
application.package_name)
end
def layout(name)
self.find("layout", name)
end
# the string value all up inside your 'res/values/strings.xml' (or nil)
def string(name=nil)
return nil unless name
resource_id = find(:string, name)
return nil if resource_id.nil? || resource_id == 0
PMApplication.current_application.resources.getString(resource_id)
end
end
end
|
# 1. que diga "Bienvenido a la calculadora mas deahuevo"
# input <=
# output <= "Bienvenido a la calculadora mas deahuevo"
puts "Bienvenido a la calculadora mas deahuevo"
# 6. repetir hasta que escriba "salir"
# input <= codigo de los pasos 2, 3 y 4
# output <= loop until "salir"
while true
# 2. imprimir "Ingrese la operacion"
# input <=
# output <= imprimir "Ingrese la operacion"
puts "Ingrese la operacion"
# 3. ingrese la operacion
# input <= "2 + 3"
# output <= [2.0, '+', 3.0]
operacion = gets.chomp.strip
break if operacion == "salir"
matches = operacion.match(/^\s*(?<num1>\d+)\s*(?<operador>\+|\-|\*|\/)\s*(?<num2>\d+)\s*$/)
if matches.nil? #validacion de la operacion match.
puts "vayase al demonio, es invalido"
next
end
num1 = matches[:num1].to_f
operador = matches[:operador].to_sym
num2 = matches[:num2].to_f
#puts output.inspect
# 4. operar la operacion
# input <= [2.0, '+', 3.0]
# output <= 5.0
resultado = case operador
when :+ then num1 + num2
when :- then num1 - num2
when :* then num1 * num2
when :/ then num1 / num2
when :% then num1 % num2
end
#resultado = [num1,num2].inject(operador)
#otra forma de operar.
#puts resultado.inspect
# 5. imprima el resultado
# input <= resultado
# output <= imprimir 5.0
puts resultado
end |
class PassangerVagon
attr_reader :type
def initialize
@type = 'passanger'
end
end |
require 'bookmark'
require 'database_helpers'
describe Bookmark do
let(:bookmark) {described_class}
describe '.all' do
it "calls all bookmarks" do
# connection = PG.connect(dbname: 'bookmark_manager_test')
bookmark = Bookmark.create(url: "http://www.makersacademy.com", title: "Makers Academy")
Bookmark.create(url: "http://www.destroyallsoftware.com", title: "Destroy All Software")
Bookmark.create(url: "http://www.google.com", title: "Google")
bookmarks = Bookmark.all
expect(bookmarks.length).to eq 3
expect(bookmarks.first).to be_a Bookmark
expect(bookmarks.first.id).to eq bookmark.id
expect(bookmarks.first.title).to eq 'Makers Academy'
expect(bookmarks.first.url).to eq 'http://www.makersacademy.com'
end
end
describe '.create' do
it "creates a new bookmark" do
bookmark = Bookmark.create(url: 'http://www.testbookmark.com', title: 'Test Bookmark')
persisted_data = persisted_data(id: bookmark.id)
expect(bookmark).to be_a Bookmark
expect(bookmark.id).to eq persisted_data.first['id']
expect(bookmark.title).to eq 'Test Bookmark'
expect(bookmark.url).to eq 'http://www.testbookmark.com'
end
end
describe '.delete' do
it 'deletes a bookmark' do
bookmark = Bookmark.create(url: 'http://www.testbookmark.com', title: 'Test Bookmark')
Bookmark.create(url: "http://www.destroyallsoftware.com", title: "Destroy All Software")
Bookmark.create(url: "http://www.google.com", title: "Google")
Bookmark.delete(title: 'Test Bookmark')
bookmarks = Bookmark.all
expect(bookmarks.length).to eq 2
expect(bookmarks.first.title).to eq 'Destroy All Software'
expect(bookmarks.first.url).to eq 'http://www.destroyallsoftware.com'
end
end
describe '.update' do
it 'updates a bookmark' do
bookmark = Bookmark.create(url: 'http://www.testbookmark.com', title: 'Test Bookmark')
Bookmark.update(old_title: 'Test Bookmark', new_title: 'Updated Bookmark', new_url: 'http:/www.updatedurl.com')
bookmarks = Bookmark.all
expect(bookmarks.first.title).to eq 'Updated Bookmark'
end
end
end
|
class PerformancePiecesController < ApplicationController
def new
@piece = Piece.new
end
def create
@performance_piece = PerformancePiece.new(performance_piece_params)
if @performance_piece.save
flash[:success] = "Piece Added!"
else
flash[:warning] = "Oops! There was a problem"
end
redirect_to user_performance_path(current_user, params[:performance_id])
end
private
def performance_piece_params
params.require(:piece).permit(:title).merge(performance_id: params[:performance_id])
end
end
|
module BF
module Instruction
DECREMENT = Instruction::Decrement.new
INCREMENT = Instruction::Increment.new
INPUT_CHARACTER = Instruction::InputCharacter.new
JUMP = Instruction::Jump.new
JUMP_RETURN = Instruction::JumpReturn.new
MOVE_LEFT = Instruction::MoveLeft.new
MOVE_RIGHT = Instruction::MoveRight.new
OUTPUT_CHARACTER = Instruction::OutputCharacter.new
def self.act(command, program)
return if instructions[command].nil?
instructions[command].call(program)
end
def self.instructions
{
'>' => MOVE_RIGHT,
'<' => MOVE_LEFT,
'+' => INCREMENT,
'-' => DECREMENT,
'.' => OUTPUT_CHARACTER,
',' => INPUT_CHARACTER,
'[' => JUMP,
']' => JUMP_RETURN,
}
end
def self.keys
@keys ||= instructions.keys
end
def self.valid_alleles
keys.reject{|a| a == ','}
end
#
# def call(program)
# raise 'sub-classes implement details'
# end
end
end
|
class BookUsersController < ApplicationController
before_action :set_book_user, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
load_and_authorize_resource
# GET /book_users
# GET /book_users.json
def index
@book_users = BookUser.set_current_user_records(current_user)
end
# GET /book_users/1
# GET /book_users/1.json
def show
end
# GET /book_users/new
def new
@book_user = BookUser.new
end
# GET /book_users/1/edit
def edit
end
# POST /book_users
# POST /book_users.json
def create
@book_user = BookUser.new
BookUser.create_book_user(params[:id],current_user,@book_user)
respond_to do |format|
if @book_user.save
# format.html { redirect_to @book_user, notice: 'Book user was successfully created.' }
# format.json { render :show, status: :created, location: @book_user }
format.js{}
else
# format.html { render :new }
# format.json { render json: @book_user.errors, status: :unprocessable_entity }
format.js {}
end
end
end
# PATCH/PUT /book_users/1
# PATCH/PUT /book_users/1.json
def update
respond_to do |format|
if @book_user.update(book_user_params)
format.html { redirect_to @book_user, notice: 'Book user was successfully updated.' }
format.json { render :show, status: :ok, location: @book_user }
else
format.html { render :edit }
format.json { render json: @book_user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /book_users/1
# DELETE /book_users/1.json
def destroy
@book_user.destroy
respond_to do |format|
format.html { redirect_to book_users_url, notice: 'Book user was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book_user
@book_user = BookUser.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_user_params
params.require(:book_user).permit(:book_id, :user_id, :from, :to, :status_id)
end
end
|
# frozen_string_literal: true
# Encapsulates the many genders that are affected by this
class Gender < ActiveRecord::Base
has_many :subjects
alias_attribute :name, :sex
end
|
require 'sinatra/base'
require 'idobata_gateway/strategies'
module IdobataGateway
class Application < Sinatra::Base
configure do
set :show_exceptions, false
end
helpers do
def strategy
IdobataGateway::Strategies.find(params[:strategy]).new(self, params[:hook_id])
rescue IdobataGateway::Strategies::StrategyNotFound => ex
halt 404, ex.message
end
end
post '/:strategy/:hook_id' do
strategy.execute.status
end
error do
request.env['sinatra.error'].message
end
end
end |
require File.dirname(__FILE__) + '/test_helper'
require 'nokogiri'
require 'sanitize'
class HttpclientTest < Test::Unit::TestCase
def setup
@junit_url = 'http://127.0.0.1:3000/caterpillar/test_bench/junit'
end
def teardown
# Nothing really
end
def test_get
# SIMPLE GET
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
response = client.get(@junit_url)
assert_equal(200, response.status_code)
assert_equal(0, client.cookie_manager.cookies.size)
end
def test_get_cookie
# COOKIE AND SESSION TEST
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
session_id = nil
url = @junit_url+'/session_cookie'
response = client.get(url)
assert_equal(200, response.status_code)
cookies = client.cookie_manager.cookies.dup
assert_equal(1, cookies.length)
xml = response.content
doc = Nokogiri::XML(xml)
assert(doc)
nodes = doc.xpath('//id/text()')
assert_equal(1, nodes.length)
session_id = nodes[0].content
assert(session_id)
# GET again and assert that the session remains the same
xml = doc = nodes = response = client = nil
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
cookies.each {|cookie| client.cookie_manager.add(cookie)}
assert_equal(1, client.cookie_manager.cookies.size)
response = client.get(url)
assert_equal(200, response.status_code)
xml = response.content
doc = Nokogiri::XML(xml)
assert(doc)
nodes = doc.xpath('//id/text()')
assert_equal(1, nodes.length)
_session_id = nodes[0].content
assert_equal(session_id,_session_id)
end
def test_post_redirection
# TEST POST + REDIRECTION
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
url = @junit_url+'/post_redirect_get'
#status code
#POST doesn't redirect
response = client.post(url)
assert_equal(302, response.status_code)
assert_equal(0, client.cookie_manager.cookies.size)
#redirection
#POST_CONTENT doesn't return header
response = client.post_content(url)
assert_equal('/caterpillar/test_bench/junit/redirect_target', response)
end
def test_post_params
# TEST POST + PARAMS
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
url = @junit_url+'/post_params'
params = {'foo' => 'bar', 'baz' => 'xyz'}
response = client.post(url,params)
assert_equal(200, response.status_code)
assert_equal(0, client.cookie_manager.cookies.size)
xml = response.content
doc = Nokogiri::XML(xml)
assert(doc)
for key,value in params do
n = doc.xpath('//'+ key)
assert (n)
assert_equal(value,n[0].content)
end
end
def test_post_cookies
# TEST POST REDIRECT + PRESET COOKIES
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
url = @junit_url+'/post_cookies'
cookie1 = WebAgent::Cookie.new
host1 = URI::HTTP.build({:userinfo => "blabla", :host => "127.0.0.1" , :port => "3000", :path => "/post_cookies", :query => "", :fragment => ""})
cookie1.url = host1
cookie1.name = "foo"
cookie1.value = "bar"
assert cookie1
cookie2 = WebAgent::Cookie.new
cookie2.url = host1
cookie2.name = "baz-baz"
cookie2.value = Time.now.to_date.to_s
assert cookie2
client.cookie_manager.add(cookie1)
assert_equal(1, client.cookie_manager.cookies.size)
client.cookie_manager.add(cookie2)
assert_equal(2, client.cookie_manager.cookies.size)
response = client.post_content(url)
assert_equal(3, client.cookie_manager.cookies.size)
xml = response
doc = Nokogiri::XML(xml)
assert(doc)
client.cookie_manager.cookies.each do |cookie|
key = cookie.name
value = cookie.value
n = doc.xpath('//'+ key)
assert(n)
#assert(n.size > 0, "COOKIE #{key} NOT FOUND")
#assert_equal(value,n[0].content, "COOKIE #{key} HAS DIFFERENT VALUE")
end
end
def test_server_cookies
# TEST SERVER COOKIES
client = HTTPClient.new
assert client
assert_equal(0, client.cookie_manager.cookies.size)
url = @junit_url+'/foobarcookies'
response = client.post(url)
assert_equal(200, response.status)
# server sends three cookies
assert_equal(3, client.cookie_manager.cookies.size)
# then head to a new url
url = @junit_url+'/foobarcookiestxt'
response = client.post_content(url)
#self.assertEqual(200, response.status)
assert_equal('__g00d____yrcl____3ver__',response)
end
def test_sanity
#CLIENT 1
client_1 = HTTPClient.new
assert client_1
assert_equal(0, client_1.cookie_manager.cookies.size)
cookie1 = WebAgent::Cookie.new
host1 = URI::HTTP.build({:userinfo => "blabla", :host => "127.0.0.1" , :port => "3000", :path => "/post_cookies", :query => "", :fragment => ""})
cookie1.url = host1
cookie1.name = "foo"
cookie1.value = "bar"
assert cookie1
cookie2 = WebAgent::Cookie.new
cookie2.url = host1
cookie2.name = "baz"
cookie2.value = "xyz"
assert cookie2
client_1.cookie_manager.add(cookie1.dup)
assert_equal(1, client_1.cookie_manager.cookies.size)
client_1.cookie_manager.add(cookie2.dup)
assert_equal(2, client_1.cookie_manager.cookies.size)
#CLIENT 2
client_2 = HTTPClient.new
assert client_2
assert_equal(0, client_2.cookie_manager.cookies.size)
host1 = URI::HTTP.build({:userinfo => "blabla", :host => "127.0.0.1" , :port => "3000", :path => "/post_cookies", :query => "", :fragment => ""})
cookie1 = WebAgent::Cookie.new
cookie1.url = host1
cookie1.name = "foo"
cookie1.value = "bar"
assert cookie1
cookie2 = WebAgent::Cookie.new
cookie2.url = host1
cookie2.name = "baz"
cookie2.value = "xyz"
assert cookie2
cookie3 = WebAgent::Cookie.new
cookie3.url = host1
cookie3.name = "pippo"
cookie3.value = "pluto"
assert cookie3
client_2.cookie_manager.add(cookie1.dup)
assert_equal(1, client_2.cookie_manager.cookies.size)
client_2.cookie_manager.add(cookie2.dup)
assert_equal(2, client_2.cookie_manager.cookies.size)
client_2.cookie_manager.add(cookie3.dup)
assert_equal(3, client_2.cookie_manager.cookies.size)
assert_equal(2, client_1.cookie_manager.cookies.size)
end
end
|
class Api::SearchResultsController < ApplicationController
def search
@search_results = Project
.search_by_title(params[:query])
.includes(:searchable)
render :search
end
end
|
# frozen_string_literal: true
require 'test_helper'
module Admin
class HoldsControllerTest < ActionController::TestCase
setup do
@hold = holds(:hold2)
@hold11 = holds(:hold11)
sign_in AdminUser.create!(email: 'admin@example.com', password: 'password')
end
test "test index method" do
get :index
assert_equal("200", response.code)
assert_response :success
end
test "test show method" do
get :show, params: { id: @hold.id}
assert_equal("200", response.code)
assert_response :success
end
test "Teacher set no longer exist for hold" do
# @hold11 = this hold does not have any teacher-set.
get :show, params: { id: @hold11.id }
assert_equal("200", response.code)
assert_response :success
end
test "test close method with format js" do
put :close, params: { id: @hold.id }
assert_equal("302", response.code)
assert_response :redirect
end
end
end
|
class AddStartLocationIdAndDestinationLocationIdToRides < ActiveRecord::Migration[5.0]
def change
add_column :rides, :start_location_id, :integer
add_column :rides, :destination_location_id, :integer
end
end
|
module MugMultiples
class Face < MugMultiples::Image
def eyes?
eyes.count > 0
end
def eyes(opts={})
eyes(opts)
end
def detect_eyes(opts={})
detect_objects(:eyes, opts)
end
end
end |
module Api
module V0
class EndpointsController < ApplicationController
def create
endpoint = Endpoint.create!(create_params)
render :json => endpoint, :status => :created, :location => api_v0x0_endpoint_url(endpoint.id)
end
def destroy
Endpoint.destroy(params[:id])
head :no_content
rescue ActiveRecord::RecordNotFound
head :not_found
end
def index
render json: Endpoint.all
end
def show
render json: Endpoint.find(params[:id])
rescue ActiveRecord::RecordNotFound
head :not_found
end
def update
Endpoint.update(params[:id], update_params)
head :no_content
rescue ActiveRecord::RecordNotFound
head :not_found
end
private
def create_params
ActionController::Parameters.new(JSON.parse(request.body.read)).permit(:role, :port, :source_id, :default, :scheme, :host, :path, :tenant_id)
end
def update_params
params.permit(:role, :port, :source_id, :default, :scheme, :host, :path)
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.