text stringlengths 10 2.61M |
|---|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
# Setup instructions from docs/contributing.rst
$ubuntu_setup_script = <<SETUP_SCRIPT
cd /vagrant
./bootstrap/install-deps.sh
./bootstrap/dev/venv.sh
SETUP_SCRIPT
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.define "ubuntu-trusty", primary: true do |ubuntu_trusty|
ubuntu_trusty.vm.box = "ubuntu/trusty64"
ubuntu_trusty.vm.provision "shell", inline: $ubuntu_setup_script
ubuntu_trusty.vm.provider "virtualbox" do |v|
# VM needs more memory to run test suite, got "OSError: [Errno 12]
# Cannot allocate memory" when running
# letsencrypt.client.tests.display.util_test.NcursesDisplayTest
v.memory = 1024
end
config.vm.network "forwarded_port", guest: 80, host: 1080
config.vm.network "forwarded_port", guest: 433, host: 10443
# Plesk ports
config.vm.network "forwarded_port", guest: 8443, host: 8443
config.vm.network "forwarded_port", guest: 8880, host: 8880
end
end
|
class RanksController < ApplicationController
def index
@users = User.find(Review.group(:user_id).order('count(user_id) desc').limit(3).pluck(:user_id))
@restaurants = Restaurant.all.each do |restaurant|
restaurant.average = restaurant.average_rate
end
@restaurants = @restaurants.sort_by { |restaurant| [restaurant.average ? 1 : 0, restaurant.average]}.reverse
end
end
|
# MiniTest suite for the application's Model
require 'rubygems'
require 'minitest/spec'
require 'blog.rb'
MiniTest::Unit.autorun
SECONDS_PER_DAY = 60 * 60 * 24
describe Tag do
before do
@tags = Hash.new
@tagged = [Object.new, Object.new, Object.new ]
%w(foo bar quux).each_with_index do |tn,idx|
t = Tag.new(tn)
@tags[idx] = t
@tagged.each { |o| t << o }
end
end
it 'Implements each and << properly' do
objs = []
a_tag = @tags.values[0]
a_tag.each { |el| objs << el }
objs.must_equal @tagged
end
it 'finds tags by name' do
x = Tag.find_by_name @tags, :quux
x.size.must_equal 1
end
it 'tag name compares to strings' do
@tags.select { |id,tag| tag.name == 'quux' }.size.must_equal 1
end
end
|
module Rails
class ContentAssistant
IRubyIndexConstants = com.aptana.ruby.core.index.IRubyIndexConstants
# CoreStubber = com.aptana.ruby.internal.core.index.CoreStubber
SearchPattern = com.aptana.index.core.SearchPattern
IndexManager = com.aptana.index.core.IndexManager
RubyLaunchingPlugin = com.aptana.ruby.launching.RubyLaunchingPlugin
def initialize(io, offset)
@src = io.read
@offset = offset
end
def assist
suggestions = []
# TODO Include "location" where each suggestion was found?
image = "platform:/plugin/com.aptana.ruby.ui/icons/full/obj16/instance_var_obj.png"
location = ''
# Handle instance variables in eRB
if prefix.start_with? "@"
dir_name = filepath.removeLastSegments(1).lastSegment
location = "#{dir_name}_controller.rb"
# TODO make location more specific? method defined in?
results = index.query([IRubyIndexConstants::FIELD_DECL], prefix, SearchPattern::PREFIX_MATCH | SearchPattern::CASE_SENSITIVE)
results.each {|r| suggestions << r.word.split('/').first if !r.documents.select {|d| d.end_with? "#{dir_name}_controller.rb" }.empty? } if results # TODO Limit to only words found in the matching controller!
else
# Handle helper methods in eRB
image = "platform:/plugin/com.aptana.ruby.ui/icons/full/obj16/class_method.png"
# Now we look for all methods matching the prefix and then post-filter to only those defined in the helper's files.
gem_and_project_indices.each do |index|
results = index.query([IRubyIndexConstants::METHOD_DECL], "^#{prefix}[^/]*/\\w+?Helper/.+$", SearchPattern::REGEX_MATCH | SearchPattern::CASE_SENSITIVE)
(results || []).each do |r|
# TODO include Helper type name as "location"
r.getDocuments.each {|d| suggestions << r.word.split('/').first }
end
end
end
# Flatten and keep only uniques
suggestions.flatten!
suggestions.uniq!
# Elininate nil
suggestions = suggestions.select {|s| s }
# Sort by display name
suggestions.sort!
# Turn into hash so we can supply image
suggestions = suggestions.map {|s| {:insert => s, :image => image } }
Ruble::Logger.trace "Rails content assist suggestions: #{suggestions.inspect}"
suggestions.inspect
end
private
def parser
@parser ||= org.jrubyparser.Parser.new
end
def parser_config
org.jrubyparser.parser.ParserConfiguration.new(0, org.jrubyparser.CompatVersion::BOTH)
end
def get_children_recursive(parent, type)
children = parent.getChildrenOfType(type)
partial = []
children.each {|c| partial << c; partial << get_children_recursive(c, type) }
partial.flatten!
partial
end
def filepath
org.eclipse.core.runtime.Path.new(ENV['TM_FILEPATH'])
end
def gem_and_project_indices
gem_indices << index
end
def gem_indices
gem_paths = RubyLaunchingPlugin.getGemPaths(project)
gem_paths.collect {|g| index_manager.getIndex(g.toFile.toURI) }.compact
end
def index
index_manager.getIndex(project.locationURI)
end
def index_manager
IndexManager.getInstance
end
def project
file = org.eclipse.core.resources.ResourcesPlugin.workspace.root.getFileForLocation(filepath)
return file.project
end
def offset
@offset
end
def prefix
return @prefix if @prefix
@prefix = @src[0...offset + 1]
# find last period/space/:
index = @prefix.rindex('.')
@prefix = @prefix[(index + 1)..-1] if !index.nil?
index = @prefix.rindex(':')
@prefix = @prefix[(index + 1)..-1] if !index.nil?
index = @prefix.rindex(' ')
@prefix = @prefix[(index + 1)..-1] if !index.nil?
return @prefix
end
def full_prefix
return @full_prefix if @full_prefix
@full_prefix = @src[0...offset + 1]
# find last space/newline
index = @full_prefix.rindex(' ')
@full_prefix = @full_prefix[(index + 1)..-1] if !index.nil?
index = @full_prefix.rindex('\n')
@full_prefix = @full_prefix[(index + 1)..-1] if !index.nil?
index = @full_prefix.rindex('\r')
@full_prefix = @full_prefix[(index + 1)..-1] if !index.nil?
index = @full_prefix.rindex('\t')
@full_prefix = @full_prefix[(index + 1)..-1] if !index.nil?
return @full_prefix
end
end
end |
require 'spec_helper'
require 'base64'
describe Api do
it "should have a class method to return the API version for a service" do
Api.version_for(:auth).should match /v[0-9]+/
end
describe ".call" do
it "should handle GET" do
stub_request(:get, "http://example.com/v1/api_users").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"}).
to_return(status: 200, headers: {'Content-Type'=>'application/json'}, body: '{"x":2,"y":1}')
response = Api.call "http://example.com", :get, 'api_user', "/api_users", {}, {x_api_token: "sjhdfsd"}
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "should handle POST" do
stub_request(:post, "http://example.com/v1/api_users").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"},
body: "this is the body").
to_return(status: 201, body: '{"x":2,"y":1}', headers: {'Content-Type'=>'application/json'})
response = Api.call "http://example.com", :post, 'api_user', "/api_users", "this is the body", {x_api_token: "sjhdfsd"}
response.status.should == 201
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "should handle PUT" do
stub_request(:put, "http://example.com/v1/api_users").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"},
body: "this is the body").
to_return(status: 200, body: '{"x":2,"y":1}', headers: {'Content-Type'=>'application/json'})
response = Api.call "http://example.com", :put, 'api_user', "/api_users", "this is the body", {x_api_token: "sjhdfsd"}
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "should handle DELETE" do
stub_request(:delete, "http://example.com/v1/api_users").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"}).
to_return(status: 200, body: '', headers: {'Content-Type'=>'application/json'})
response = Api.call "http://example.com", :delete, 'api_user', "/api_users", {}, {x_api_token: "sjhdfsd"}
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == nil
end
end
it "Api.get should use Api.call" do
stub_request(:get, "http://forbidden.example.com/v1/api_users/1/groups").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"}).
to_return(status: 200, body: '{"x":2,"y":1}', headers: {'Content-Type'=>'application/json'})
response = Api.get(:api_users, "/api_users/1/groups", {}, {x_api_token: "sjhdfsd"})
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "Api.post should use Api.call" do
stub_request(:post, "http://forbidden.example.com/v1/api_users/1/groups").
with(body: "this is the body",
headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-Api-Token'=>'sjhdfsd'}).
to_return(status: 200, body: '{"x":2,"y":1}', headers: {'Content-Type'=>'application/json'})
response = Api.post(:api_users, "/api_users/1/groups", "this is the body", {x_api_token: "sjhdfsd"})
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "Api.put should use Api.call" do
stub_request(:put, "http://forbidden.example.com/v1/api_users/1/groups").
with(body: "this is the body",
headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-Api-Token'=>'sjhdfsd'}).
to_return(status: 200, body: '{"x":2,"y":1}', headers: {'Content-Type'=>'application/json'})
response = Api.put(:api_users, "/api_users/1/groups", "this is the body", {x_api_token: "sjhdfsd"})
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == {"x"=>2, "y"=>1}
end
it "Api.delete should use Api.call" do
stub_request(:delete, "http://forbidden.example.com/v1/api_users/1/groups").
with(headers: {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'X-API-Token'=>"sjhdfsd"}).
to_return(status: 200, body: '', headers: {'Content-Type'=>'application/json'})
response = Api.delete(:api_users, "/api_users/1/groups", {}, {x_api_token: "sjhdfsd"})
response.status.should == 200
response.headers.should == {"Content-Type"=>"application/json"}
response.body.should == nil
end
it "Api.send_mail should send email asynchronously" do
Api.should_receive(:service_token).and_return("fakeissimo")
stub_request(:post, "http://forbidden.example.com/v1/mails").
with(:body => "{\"from\":\"charles.anka@example.com\",\"to\":\"kajsa.anka@example.com\",\"subject\":\"Test mail\",\"plaintext\":\"Hello world.\",\"html\":null,\"plaintext_url\":null,\"html_url\":null,\"substitutions\":null}",
:headers => {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'User-Agent'=>'Ocean', 'X-Api-Token'=>'fakeissimo'}).
to_return(:status => 200, :body => "", :headers => {})
Api.send_mail from: "charles.anka@example.com", to: "kajsa.anka@example.com",
subject: "Test mail", plaintext: "Hello world."
end
it ".decode_credentials should be able to decode what .encode_credentials produces" do
Api.decode_credentials(Api.encode_credentials("foo", "bar")).should == ["foo", "bar"]
end
it ".encode_credentials should encode username and password into Base64 form" do
Api.encode_credentials("myuser", "mypassword").should ==
::Base64.strict_encode64("myuser:mypassword")
end
it ".decode_credentials should decode username and password from Base64" do
Api.decode_credentials(::Base64.strict_encode64("myuser:mypassword")).should ==
['myuser', 'mypassword']
end
it ".decode_credentials, when given nil, should return empty credentials" do
Api.decode_credentials(nil).should == ['', '']
end
describe ".permitted?" do
it "should return a response with a status of 404 if the token is unknown" do
Api.stub(:get).and_return(double(:status => 404))
Api.permitted?('some-client-token').status.should == 404
end
it "should return a response with a status of 400 if the authentication has expired" do
Api.stub(:get).and_return(double(:status => 400))
Api.permitted?('some-client-token').status.should == 400
end
it "should return a response with a status of 403 if the operation is denied" do
Api.stub(:get).and_return(double(:status => 403))
Api.permitted?('some-client-token').status.should == 403
end
it "should return a response with a status of 200 if the operation is authorized" do
Api.stub(:get).and_return(double(:status => 200))
Api.permitted?('some-client-token').status.should == 200
end
end
describe "class method authorization_string" do
it "should take the extra actions, the controller name and an action name" do
Api.authorization_string({}, "fubars", "show").should be_a(String)
end
it "should take an optional app and an optional context" do
Api.authorization_string({}, "fubars", "show", "some_app", "some_context").should be_a(String)
end
it "should put the app and context in the two last positions" do
qs = Api.authorization_string({}, "fubars", "show", "some_app", "some_context").split(':')
qs[4].should == 'some_app'
qs[5].should == 'some_context'
end
it "should replace a blank app or context with asterisks" do
qs = Api.authorization_string({}, "fubars", "show", nil, " ").split(':')
qs[4].should == '*'
qs[5].should == '*'
end
it "should take an optional service name" do
Api.authorization_string({}, "fubars", "show", "*", "*", "foo").should == "foo:fubars:self:GET:*:*"
end
it "should default the service name to APP_NAME" do
Api.authorization_string({}, "fubars", "show", "*", "*").should == "#{APP_NAME}:fubars:self:GET:*:*"
end
it "should return a string of six colon-separated parts" do
qs = Api.authorization_string({}, "fubars", "show")
qs.should be_a(String)
qs.split(':').length.should == 6
end
it "should use the controller name as the resource name" do
qs = Api.authorization_string({}, "fubars", "show", nil, nil, 'foo').split(':')
qs[1].should == "fubars"
end
end
describe "class method map_authorization" do
it "should return an array of two strings" do
m = Api.map_authorization({}, "fubars", "show")
m.should be_an(Array)
m.length.should == 2
m[0].should be_a(String)
m[1].should be_a(String)
end
it "should translate 'show'" do
Api.map_authorization({}, "fubars", "show").should == ["self", "GET"]
end
it "should translate 'index'" do
Api.map_authorization({}, "fubars", "index").should == ["self", "GET*"]
end
it "should translate 'create'" do
Api.map_authorization({}, "fubars", "create").should == ["self", "POST"]
end
it "should translate 'update'" do
Api.map_authorization({}, "fubars", "update").should == ["self", "PUT"]
end
it "should translate 'destroy'" do
Api.map_authorization({}, "fubars", "destroy").should == ["self", "DELETE"]
end
it "should translate 'connect'" do
Api.map_authorization({}, "fubars", "connect").should == ["connect", "PUT"]
end
it "should translate 'disconnect'" do
Api.map_authorization({}, "fubars", "disconnect").should == ["connect", "DELETE"]
end
it "should raise an error for unknown actions" do
expect { Api.map_authorization({}, "fubars", "blahonga") }.to raise_error
end
it "should insert the extra_action data appropriately" do
Api.map_authorization({'fubars' => {'blahonga_create' => ['blahonga', 'POST']}},
"fubars", "blahonga_create").
should == ['blahonga', 'POST']
end
end
describe ".adorn_basename" do
before :all do
@local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}.gsub('.', '-')
end
it "should return a string" do
Api.adorn_basename("SomeBaseName").should be_a String
end
it "should return a string containing the basename" do
Api.adorn_basename("SomeBaseName").should include "SomeBaseName"
end
it "should return a string containing the Chef environment" do
Api.adorn_basename("SomeBaseName", chef_env: "zuul").should include "zuul"
end
it "should add only the Chef env if the Rails env is production" do
Api.adorn_basename("Q", chef_env: "prod", rails_env: 'production').should == "Q_prod"
Api.adorn_basename("Q", chef_env: "staging", rails_env: 'production').should == "Q_staging"
Api.adorn_basename("Q", chef_env: "master", rails_env: 'production').should == "Q_master"
end
it "should add IP and rails_env if the chef_env is 'dev' or 'ci' or if rails_env isn't 'production'" do
Api.adorn_basename("Q", chef_env: "dev", rails_env: 'development').should == "Q_dev_#{@local_ip}_development"
Api.adorn_basename("Q", chef_env: "dev", rails_env: 'test').should == "Q_dev_#{@local_ip}_test"
Api.adorn_basename("Q", chef_env: "dev", rails_env: 'production').should == "Q_dev_#{@local_ip}_production"
Api.adorn_basename("Q", chef_env: "ci", rails_env: 'development').should == "Q_ci_#{@local_ip}_development"
Api.adorn_basename("Q", chef_env: "ci", rails_env: 'test').should == "Q_ci_#{@local_ip}_test"
Api.adorn_basename("Q", chef_env: "ci", rails_env: 'production').should == "Q_ci_#{@local_ip}_production"
Api.adorn_basename("Q", chef_env: "master", rails_env: 'development').should == "Q_master_#{@local_ip}_development"
Api.adorn_basename("Q", chef_env: "master", rails_env: 'test').should == "Q_master_#{@local_ip}_test"
Api.adorn_basename("Q", chef_env: "staging", rails_env: 'development').should == "Q_staging_#{@local_ip}_development"
Api.adorn_basename("Q", chef_env: "staging", rails_env: 'test').should == "Q_staging_#{@local_ip}_test"
Api.adorn_basename("Q", chef_env: "staging", rails_env: 'production').should == "Q_staging"
Api.adorn_basename("Q", chef_env: "prod", rails_env: 'development').should == "Q_prod_#{@local_ip}_development"
Api.adorn_basename("Q", chef_env: "prod", rails_env: 'test').should == "Q_prod_#{@local_ip}_test"
end
it "should leave out the basename if :suffix_only is true" do
Api.adorn_basename("Q", chef_env: "prod", rails_env: 'production', suffix_only: true).
should == "_prod"
Api.adorn_basename("Q", chef_env: "prod", rails_env: 'development', suffix_only: true).
should == "_prod_#{@local_ip}_development"
end
end
describe ".basename_suffix" do
it "should return a string" do
Api.basename_suffix.should be_a String
end
end
describe ".escape" do
it "should escape the backslash (\)" do
Api.escape("\\").should == "%5C"
end
it "should escape the pipe (|)" do
Api.escape("|").should == "%7C"
end
it "should escape the backslash (\)" do
Api.escape("?").should == "%3F"
end
it "should escape the left bracket" do
Api.escape("[").should == "%5B"
end
it "should escape the right bracket" do
Api.escape("]").should == "%5D"
end
it "should not escape parens" do
Api.escape("()").should == "()"
end
it "should not escape dollar signs" do
Api.escape("$").should == "$"
end
it "should not escape slashes (/)" do
Api.escape("/").should == "/"
end
it "should not escape plusses (+)" do
Api.escape("+").should == "+"
end
it "should not escape asterisks" do
Api.escape("*").should == "*"
end
it "should not escape full stops" do
Api.escape(".").should == "."
end
it "should not escape hyphens" do
Api.escape("-").should == "-"
end
it "should not escape underscores" do
Api.escape("_").should == "_"
end
it "should not escape letters or numbers" do
Api.escape("AaBbCc123").should == "AaBbCc123"
end
end
end
|
class CreateProjectOpenings < ActiveRecord::Migration
def change
create_table :project_openings do |t|
t.integer :project_id, :null => false
t.integer :user_id, :null => false
t.integer :touched
t.timestamps
end
add_index :project_openings, :project_id
add_index :project_openings, :user_id
add_index :project_openings, [:user_id, :project_id], unique: true
end
end
|
FactoryBot.define do
factory :student do
first_name { "Daenerys" }
last_name { "Targaryen" }
end
end
|
require 'spec_helper'
describe "tailgate_venues/index" do
before(:each) do
@theVenue = stub_model(Venue, name:"joes")
@theTailgate = stub_model(Tailgate, name:"party")
assign(:tailgate_venues, [
stub_model(TailgateVenue,
:tailgate => @theTailgate,
:venue => @theVenue,
:latitude => 1.5,
:longitude => 1.5
),
stub_model(TailgateVenue,
:tailgate => @theTailgate,
:venue => @theVenue,
:latitude => 1.5,
:longitude => 1.5
)
])
end
it "renders a list of tailgate_venues" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "tr>td", :text => "party", :count => 2
assert_select "tr>td", :text => "joes", :count => 2
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
disk = './secondDisk.vdi'
Vagrant.configure(2) do |config|
config.vm.box = "centos/7"
config.vm.define "server" do |server|
server.vm.network "private_network", ip: "192.168.10.10"
server.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 2
end
server.vm.hostname = "server"
end
config.vm.define "backup" do |backup|
backup.vm.network "private_network", ip: "192.168.10.20"
backup.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 2
unless File.exist?(disk)
v.customize ['createhd', '--filename', disk, '--variant', 'Fixed', '--size', 10 * 1024]
end
v.customize ['storageattach', :id, '--storagectl', 'IDE', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', disk]
end
backup.vm.hostname = "backup"
config.vm.provision "shell", inline: <<-SHELL
mkdir -p ~root/.ssh
cp ~vagrant/.ssh/auth* ~root/.ssh
SHELL
end
end
|
require 'spec_helper'
require 'file_db'
describe FileDB do
let(:testfile) { 'spec/fixtures/csv/testfile.csv' }
it 'opens a csv file' do
expect(FileDB.open(testfile)).to be_truthy
end
it 'reads a csv file' do
expect(FileDB.read(testfile)).to be_truthy
end
end
|
class AddPhoneNumberToClients < ActiveRecord::Migration
def change
add_column :clients, :contact_number, :string
end
end
|
FactoryGirl.define do
factory :user do
email
name
surname
password
password_confirmation { password }
confirmation_token { Concerns::Token.generate }
end
end
|
module Supersaas
class User < BaseModel
ROLES = [3, 4, -1]
attr_accessor :address, :country, :created_on, :credit, :email, :field_1, :field_2, :fk, :full_name, :id, :mobile, :name, :phone, :role, :super_field
attr_reader :form
def form=(value)
if value.is_a?(Hash)
@form = Supersaas::Form.new(value)
else
@form = value
end
end
end
end |
require 'telegram/bot'
require 'dotenv/load'
LIB_PATH = "lib"
Dir.foreach(LIB_PATH){|f| require_relative File.join(LIB_PATH,f) if f =~ /.*\.rb/}
COMMANDS = {"/make_gif": ContentProvideWayCommand, "/start": Start, "/help": Help}
def content_for_gif? bot, message
return MakeGifFromUrlCommand.new(bot, message, message.text) if message.text =~ %r{https?://.*\..*/?.*}
return MakeGifFromFileCommand.new(bot, message) if message[:video]
nil
end
def get_general_command bot, message
command = message.text.downcase.to_sym if message.text
return COMMANDS[command].new bot, message if COMMANDS.include? command
result = content_for_gif? bot, message
result ||= UnknownCommand.new bot, message
end
def make_gif_command bot, message
case message.data
when "Via URL" then AskForUrlCommand.new bot, message
when "From file on your device" then AskForFileCommand.new bot, message
end
end
def get_command bot, message
case message
when Telegram::Bot::Types::Message then get_general_command bot, message
when Telegram::Bot::Types::CallbackQuery then make_gif_command bot, message
end
end
Telegram::Bot::Client.run(ENV["TOKEN"]) do |bot|
bot.listen do |message|
Thread.start do
command = get_command bot, message
command.exec
end
end
end
|
require 'bulutfon_sdk/rest/base_request'
module BulutfonSDK
module REST
class AutomaticCall < BaseRequest
def initialize(*args)
super(*args)
@resource = 'automatic-calls'
end
def all( params = {} )
prepare_request( 'get', @resource, params)
end
def get( id )
prepare_request( 'get', "#{@resource}/#{id}")
end
def create(params)
prepare_request( 'post', @resource, params)
end
end
end
end
|
require 'spec_helper'
RSpec.describe Manufacturer do
include Helpers::DrugHelpers
before :each do
setup_drug_data
@m1_d1 = Manufacturer.create(name:'RonCo',product_ndc:'16590-843')
@m1_d2 = Manufacturer.create(name:'RonCo',product_ndc:'0069-4200')
@m2_d1 = Manufacturer.create(name:'BobCo',product_ndc:'0069-4190')
end
describe "finding related drugs" do
it "should find drugs when there is a matching set" do
expect( @m1_d1.drugs.length ).to eq 2
expect( @m2_d1.drugs.length ).to eq 1
end
end
end
|
require 'fancy_logger'
require 'pathname'
begin
require 'bundler/setup'
require 'bundler/gem_tasks'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
$logger = FancyLogger.new(STDOUT)
$project_path = Pathname.new(__FILE__).dirname.expand_path
$spec = eval( $project_path.join('jquery-cookie-rails.gemspec').read )
Rake::TaskManager.record_task_metadata = true
def run_command(command)
result = `#{command}`.chomp.strip
message = if result.empty?
command
else
command + "\n" + result.lines.collect { |line| " #{line}" }.join
end
$logger.debug(message)
result
end
namespace :jquery_cookie do
desc 'Update the `jquery-cookie` submodule'
task :update do
jquery_cookie_path = $project_path.join('lib', 'jquery-cookie')
latest_tag = run_command("cd #{jquery_cookie_path} && git describe --abbrev=0 --tags")
run_command "cd #{jquery_cookie_path} && git checkout #{latest_tag}"
end
desc 'Copy the `jquery.cookie.js` file to the `vendor/assets/javascripts` folder'
task :vendor do
jquery_cookie_path = $project_path.join('lib', 'jquery-cookie', 'jquery.cookie.js')
vendor_path = $project_path.join('vendor', 'assets', 'javascripts')
vendor_path.mkpath
run_command "cp #{jquery_cookie_path} #{vendor_path}"
end
end
desc 'Update jquery-cookie and copy `jquery.cookie.js` into vendor'
task :jquery_cookie => ['jquery_cookie:update', 'jquery_cookie:vendor']
desc 'Update jquery-cookie, update jquery-cookie-rails version, tag on git'
task :update => :jquery_cookie do
jquery_cookie_path = $project_path.join('lib', 'jquery-cookie')
latest_tag = run_command("cd #{jquery_cookie_path} && git describe --abbrev=0 --tags")
version = latest_tag.gsub(/^v/, '')
version_path = $project_path.join('VERSION')
run_command "git add ."
run_command "git commit -m \"Version bump to #{version}\""
run_command "git tag #{version}"
end
task :default do
Rake::application.options.show_tasks = :tasks # this solves sidewaysmilk problem
Rake::application.options.show_task_pattern = //
Rake::application.display_tasks_and_comments
end
|
class GradebookRemark < ActiveRecord::Base
belongs_to :student
belongs_to :batch
belongs_to :reportable, :polymorphic => :true
belongs_to :remarkable, :polymorphic => :true
REMARK_TYPES = {"RemarkSet" => "General Remarks", "Subject" => "Subject-Wise Remarks"}
REPORT_TYPES = {"AssessmentGroup" => "Exam", "AssessmentTerm" => "Term", "AssessmentPlan" => "Planner" }
end
|
require('rspec')
require('word')
describe(Word) do
before() do
Word.clear()
end
describe('#word_name') do
it("returns the word") do
test_word = Word.new(:word_name => "Sherman")
expect(test_word.word_name()).to(eq("Sherman"))
end
end
describe('#id') do
it("returns the id of the word") do
test_word = Word.new(:word_name => "Sherman")
expect(test_word.id()).to(eq(1))
end
end
describe('#word_meanings') do
it("initially returns an empty array of word definitions") do
test_word = Word.new(:word_name => "Sherman")
expect(test_word.word_meanings()).to(eq([]))
end
end
describe("#save") do
it("adds a word to an array of saved words") do
test_word = Word.new(:word_name => "Sherman")
test_word.save()
expect(Word.all()).to(eq([test_word]))
end
end
describe(".all") do
it("is empty at first") do
expect(Word.all()).to(eq([]))
end
end
describe(".clear") do
it("empties out all of the saved words") do
Word.new(:word_name => "Sherman").save()
Word.clear()
expect(Word.all()).to(eq([]))
end
end
describe(".find") do
it("returns a word by its id number") do
test_word = Word.new(:word_name => "Sherman")
test_word.save()
test_word2 = Word.new(:word_name => "Damien")
test_word2.save()
expect(Word.find(test_word.id())).to(eq(test_word))
end
end
end
|
class Computacenter::TechSourceMaintenanceBannerComponent < ViewComponent::Base
DATE_TIME_FORMAT = '%A %-d %B %I:%M%P'.freeze
def initialize(techsource)
@techsource = techsource
end
def message
supplier_outage = @techsource.current_supplier_outage
if supplier_outage
"The TechSource website will be closed for maintenance on <span class=\"app-no-wrap\">#{supplier_outage.start_at.strftime(DATE_TIME_FORMAT)}.</span> You can order devices when it reopens on <span class=\"app-no-wrap\">#{supplier_outage.end_at.strftime(DATE_TIME_FORMAT)}.</span>".html_safe
end
end
def render?
banner_periods = @techsource.supplier_outages.collect { |supplier_outage| banner_period(supplier_outage) }
banner_periods.any? { |banner_period| banner_period.cover? current_time }
end
private
def banner_period(supplier_outage)
period_from_start_of_two_days_before_supplier_outage_to_end_of_supplier_outage(supplier_outage)
end
def period_from_start_of_two_days_before_supplier_outage_to_end_of_supplier_outage(supplier_outage)
display_from = 2.days.before(supplier_outage.start_at.beginning_of_day)
display_until = supplier_outage.end_at
display_from..display_until
end
def current_time
Time.zone.now
end
end
|
require 'pry'
class Game
attr_accessor :board, :player_1, :player_2
WIN_COMBINATIONS = [
[0,1,2], #top row horizontal, WIN_COMBINATIONS[0] IN OTHER WORDS THIS IS THE SAME AS COMBO[0]
[3,4,5], #middle row horizontal COMBO[0] == 3
[6,7,8], #bottom row horizontal
[0,3,6], #left-side vertical
[1,4,7], #middle vertical
[2,5,8], #right-side vertical
[2,4,6], #diagonal win 1
[0,4,8], #diagonal win 2
]
def initialize(player_1 = nil, player_2 = nil, board = nil)
@player_1 = player_1 || Players::Human.new("X")
@player_2 = player_2 || Players::Human.new("O")
@board = board || Board.new
#binding.pry
end
def current_player
if @board.turn_count.odd?
@player_2
else
@player_1
end
end
def won?
WIN_COMBINATIONS.find do |combo|
if @board.cells[combo[0]] == "X" && @board.cells[combo[1]] == "X" && @board.cells[combo[2]] == "X"
true
elsif @board.cells[combo[0]] == "O" && @board.cells[combo[1]] == "O" && @board.cells[combo[2]] == "O"
true
else
false
end
end
end
def draw?
if @board.full? && !won?
true
end
end
def over?
if draw?
true
elsif won?
true
end
end
def winner
if won?
@board.cells[won?[0]]
end
end
def turn
player = current_player
potential_move = player.move(@board)
if !@board.valid_move?(potential_move)
turn
elsif @board.valid_move?(potential_move)
@board.update(potential_move, player)
end
end
def play
until over?
turn
end
if won?
puts "Congratulations #{self.winner}!"
end
if draw?
puts "Cat's Game!"
end
end
end
|
require 'rails_helper'
describe Staff::AccountsController do
context 'ログイン前' do
it_behaves_like 'a protected singular staff controller'
end
context 'ログイン後' do
describe '#update' do
let!(:params_hash) { attributes_for(:staff_member) }
let!(:staff_member) { create(:staff_member) }
before do
session[:staff_member_id] = staff_member.id
session[:last_access_time] = 1.second.ago
end
example 'email属性を変更する' do
params_hash[:email] = 'test@example.com'
patch :update, id: staff_member, staff_member: params_hash
staff_member.reload
expect(staff_member.email).to eq 'test@example.com'
end
example '例外ActionController::ParameterMissingが発生' do
bypass_rescue
expect { patch :update, id: staff_member }.to raise_error ActionController::ParameterMissing
end
example 'end_dateの書き換えが不可' do
params_hash[:end_date] = Date.tomorrow
expect { patch :update, id: staff_member, staff_member: params_hash }.not_to change { staff_member.end_date }
end
end
end
end
|
require 'rails_helper'
describe TextMessage, type: :model do
it { should validate_presence_of :number_from }
it { should validate_presence_of :number_to }
describe 'automatically sets number_to and number_from' do
context 'the message is inbound' do
let('message') { create :text_message, inbound: true }
it 'sets number_to to department phone' do
expect(message.number_to).to eq(message.reporting_relationship.user.department.phone_number)
end
it 'sets number_from to client phone' do
expect(message.number_from).to eq(message.reporting_relationship.client.phone_number)
end
end
context 'the message is outbound' do
let('message') { create :text_message, inbound: false }
it 'sets number_to to client phone' do
expect(message.number_to).to eq(message.reporting_relationship.client.phone_number)
end
it 'sets number_from to department phone' do
expect(message.number_from).to eq(message.reporting_relationship.user.department.phone_number)
end
end
end
end
|
module GaleShapley
class Pool
def initialize(entities)
end
# TODO API: delete / include / Add / any? / get first
end
class Algo
attr_reader :companies, :professionals
def initialize(companies, professionals)
@companies = companies
@professionals = professionals
if $DEBUG
puts "Matching #{@companies.size} companies with #{professionals.size} professionals"
puts "Companies data:"
@companies.each do |_, v|
p v
end
puts "Professionals data:"
@professionals.each do |_, v|
p v
end
end
end
def solve!
free_companies_pool = companies.dup
while free_companies_pool.any?
company = free_companies_pool.first[1]
professional = professionals[company.preferences[0]]
# When professional does not have any match yet we match him with the company
if professional.match.nil?
professional.match_with(company)
# Professional is already matched with another company. We check
# to see if the current company is better than the previous match
else
# current company is a better match than the previous company
if professional.prefers?(company)
previous_company = companies[professional.match]
professional.match_with(company)
unless free_companies_pool.keys.include?(previous_company.id)
free_companies_pool[previous_company.id] = previous_company
end
professional.remove_from_prefs(previous_company)
previous_company.remove_matched(professional)
else
professional.remove_from_prefs(company)
company.remove_from_prefs(professional)
end
end
# If company is full remove it from poll of free companies
if company.full?
free_companies_pool.delete(company.id)
end
end # End while
end # End solve
end
end
|
class Project < ActiveRecord::Base
belongs_to :apm
belongs_to :teamlead
belongs_to :developer
end
|
class MemberProfileRegistrationsController < DeviseRegistrationsController
layout "centered", only: [:new, :create]
def create
ensure_can_register_as_role
build_resource(sign_up_params)
# binding.pry
if resource.save
current_user.move_to_profile(resource)
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
def ensure_can_register_as_role
suggested_role = params[:member_profile][:suggested_role]
if suggested_role.present? && can?("register_as_#{suggested_role}".to_sym, MemberProfile)
params[:member_profile][:role] ||= suggested_role
end
end
end |
MRuby::Gem::Specification.new('mitamae') do |spec|
spec.license = 'MIT'
spec.author = [
'Takashi Kokubun',
'Ryota Arai',
]
spec.summary = 'mitamae'
spec.bins = ['mitamae']
spec.add_dependency 'mruby-enumerator', core: 'mruby-enumerator'
spec.add_dependency 'mruby-eval', core: 'mruby-eval'
spec.add_dependency 'mruby-exit', core: 'mruby-exit'
spec.add_dependency 'mruby-hash-ext', core: 'mruby-hash-ext'
spec.add_dependency 'mruby-io', core: 'mruby-io'
spec.add_dependency 'mruby-kernel-ext', core: 'mruby-kernel-ext'
spec.add_dependency 'mruby-object-ext', core: 'mruby-object-ext'
spec.add_dependency 'mruby-print', core: 'mruby-print'
spec.add_dependency 'mruby-struct', core: 'mruby-struct'
spec.add_dependency 'mruby-symbol-ext', core: 'mruby-symbol-ext'
spec.add_dependency 'mruby-at_exit', mgem: 'mruby-at_exit'
spec.add_dependency 'mruby-dir', mgem: 'mruby-dir'
spec.add_dependency 'mruby-dir-glob', mgem: 'mruby-dir-glob'
spec.add_dependency 'mruby-env', mgem: 'mruby-env'
spec.add_dependency 'mruby-file-stat', mgem: 'mruby-file-stat'
spec.add_dependency 'mruby-hashie', mgem: 'mruby-hashie'
spec.add_dependency 'mruby-json', mgem: 'mruby-json'
spec.add_dependency 'mruby-open3', mgem: 'mruby-open3'
spec.add_dependency 'mruby-optparse', mgem: 'mruby-optparse'
spec.add_dependency 'mruby-shellwords', mgem: 'mruby-shellwords'
spec.add_dependency 'mruby-specinfra', mgem: 'mruby-specinfra'
spec.add_dependency 'mruby-tempfile', mgem: 'mruby-tempfile'
spec.add_dependency 'mruby-yaml', github: 'mrbgems/mruby-yaml'
spec.add_dependency 'mruby-erb', github: 'k0kubun/mruby-erb'
spec.add_dependency 'mruby-etc', github: 'eagletmt/mruby-etc'
spec.add_dependency 'mruby-uri', github: 'zzak/mruby-uri'
spec.add_dependency 'mruby-schash', github: 'tatsushid/mruby-schash'
end
|
require 'ant'
namespace :ivy do
ivy_install_version = '2.2.0'
ivy_jar_dir = './.ivy'
ivy_jar_file = "#{ivy_jar_dir}/ivy.jar"
task :download do
mkdir_p ivy_jar_dir
ant.get :src => "http://repo1.maven.org/maven2/org/apache/ivy/ivy/#{ivy_install_version}/ivy-#{ivy_install_version}.jar",
:dest => ivy_jar_file,
:usetimestamp => true
end
task :install => :download do
ant.path :id => 'ivy.lib.path' do
fileset :dir => ivy_jar_dir, :includes => '*.jar'
end
ant.taskdef :resource => "org/apache/ivy/ant/antlib.xml",
#:uri => "antlib:org.apache.ivy.ant",
:classpathref => "ivy.lib.path"
end
end
def ivy_retrieve(org, mod, rev, conf)
ant.retrieve :organisation => org,
:module => mod,
:revision => rev,
:conf => conf,
:pattern => 'javalib/[conf]/[artifact].[ext]',
:inline => true
end
artifacts = %w[
log4j log4j 1.2.16 default
]
task :download_deps => "ivy:install" do
artifacts.each_slice(4) do |*artifact|
ivy_retrieve(*artifact.first)
end
end
task :default => :download_deps
|
class DropWorkshops < ActiveRecord::Migration
def up
drop_table :workshops
end
def down
create_table :workshops do |t|
t.string :title
t.text :body
t.float :atar
t.float :price
t.string :file
t.string :preview
t.string :display
t.timestamps
end
end
end
|
module Crawler
module UrlFrontier
# Maintains and provides URL
class FrontQueue
def self.load_seed(path)
seeds = []
comment = /#.*\Z/
File.read(path).each_line do |line|
line = line.chomp.gsub(comment, '').strip
next if line.empty?
begin
seeds << Addressable::URI.parse(line).to_s
rescue Addressable::URI::InvalidURIError
# do nothing
end
end
new.add(nil, seeds)
end
def initialize
@random = Random.new
@hash_numbers = Crawler::Redis.allocate_hash_numbers!
Crawler::Redis.logging('hash_numbers', "[#{@hash_numbers.join(',')}]")
end
# Maintains and prioritizes url
#
# This method prioritizes url that hasn't been crawled yet as highest priority.
# (So, crawling process behaves like Breadth-First-Search)
def add(source_host, url_set)
grouped_uri = {}
url_set.each do |url|
next unless uri = normalize_url(url)
grouped_uri[uri.host] ||= []
grouped_uri[uri.host] << uri
end
new_hosts = Set.new(Db::Host.exclude_existed(grouped_uri.keys))
urls_with_priority = []
grouped_uri.each do |host, uris|
if new_hosts.member?(host)
sorted_by_prio =
uris.map { |u| [u, prioritize(u, 1)] }
.sort { |a, b| a.last <=> b.last }
# First 5 urls for new host is given highest priority - 0
(0...5).each { |i| sorted_by_prio[i][1] = 0 if sorted_by_prio[i] }
urls_with_priority.concat(sorted_by_prio)
else
urls_with_priority.concat(uris.map { |u| [u, prioritize(u, 1)] })
end
end
#not_buffered = Crawler::Db::UrlBuffer.buffering(source_host, urls_with_priority)
#Crawler::Db::Queue.enqueue(not_buffered)
Crawler::Db::Queue.enqueue(urls_with_priority)
end
# Returns url that should be crawled.
#
# Host of url that is returned may have been accessed recently.
# So, to be polite, crawler must checks access log for host before crawling.
def fetch!
r = @random.rand
prio = if r <= 0.45
0
elsif r <= 0.75
1
elsif r <= 0.9
2
else
3
end
url = Crawler::Db::Queue.dequeue(@hash_numbers.sample, prio)
url ? Addressable::URI.parse(url) : nil
end
private
HOST_MATCHER = /\A[a-z0-9\-\.]+\Z/i
EXTENSION_MATCHER = /\.([a-zA-Z0-9]+)\Z/
WHITELIST = Crawler::Config['url.host_whitelist'].to_a.map { |r| Regexp.compile(r) }
# @param [String, Addressable::URI] url
# @return [Addressable::URI, nil]
def normalize_url(url)
return nil if url.to_s.length > 2000
uri = if url.is_a?(Addressable::URI)
url
else
Addressable::URI.parse(url.to_s)
end
scheme = uri.scheme.to_s.strip.downcase
return nil if scheme != 'http' && scheme != 'https'
host = uri.host.to_s.strip.downcase
return nil unless host =~ HOST_MATCHER
return nil if !WHITELIST.empty? && WHITELIST.find { |wl| wl.match(host) }.nil?
path = uri.path.to_s.strip
path = URI.encode(path) if path == URI.decode(path)
if md = path.match(EXTENSION_MATCHER)
return nil unless %w(htm html).include?(md[1].downcase)
end
values = uri.query_values(Array).to_a.map do |(key, value)|
key = URI.encode(key) if key == URI.decode(key)
value = URI.encode(value) if value && value == URI.decode(value)
[key, value]
end
query = values.sort do |(lk, lv), (rk, rv)|
k = lk <=> rk
k == 0 ? lv.to_s <=> rv.to_s : k
end.map! { |(k, v)| v ? "#{k}=#{v}" : k }.join('&')
query = nil if query.empty?
Addressable::URI.new(scheme: scheme, host: host, path: path, query: query)
rescue Addressable::URI::InvalidURIError => e
Crawler::Log.app.debug("#{e.message} - #{url}")
nil
end
def prioritize(uri, offset)
if uri.path.to_s.empty? || uri.path == '/'
offset + 0
elsif uri.query.to_s.empty?
offset + 1
else
offset + 2
end
end
end
end
end
|
class NotesController < ApplicationController
def index
notes = policy_scope Note
authorize notes
render json: notes
end
def create
note = Note.new
authorize note
note.assign_attributes(permitted_attributes(note))
status = note.save ? 201 : 422
render json: note, status: status
end
end
|
class AddPrefecturesAddressCityAddressBuildingToOrder < ActiveRecord::Migration[5.1]
def change
add_column :orders, :prefectures, :integer
add_column :orders, :address_city, :string
add_column :orders, :address_building, :string
end
end
|
class Backend::BackendController < ApplicationController
before_filter :require_login
private
def require_login
unless session[:author_id]
redirect_to new_login_path
end
end
end
|
# frozen_string_literal: true
require 'application_system_test_case'
class CommentsTest < ApplicationSystemTestCase
setup do
@user = users :maymie
end
test 'comment flow' do
log_in_as @user
text = 'Happiness is when what you think, what you say, and what you do are in harmony.'
within all('.commentable')[5] do
find(:css, 'i.comment.icon').click
click_link 'Cancel'
refute_selector 'form[class = \'ui form\']'
find(:css, 'i.comment.icon').click
fill_in 'comment[text]', with: text
click_button 'Comment'
refute_selector 'form[class = \'ui form\']'
assert_selector 'div[class = \'ui comments\']'
within find('div.ui.comments') do
assert_text text
assert_text @user.name
end
end
assert_text :all, 'Comment successfuly posted'
within all('.commentable')[5] do
within first('div.ui.comments div.comment') do
click_link 'Delete'
page.driver.browser.switch_to.alert.accept
refute_text text
end
refute_selector 'div[class = \'ui comments\']'
end
assert_text :all, 'Your comment was destroyed'
end
end
|
class Api::V1::BaseController < ActionController::API
include Pundit
# before_action :current_user
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
rescue_from StandardError, with: :internal_server_error
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
rescue_from ActiveRecord::RecordNotFound, with: :not_found
private
def current_user
if current_talent
@current_talent
elsif current_talentist
@current_talentist
elsif current_headhunter
@current_headhunter
else
false
end
end
def user_not_authorized(exception)
render json: {
error: "Unauthorized #{exception.policy.class.to_s.underscore.camelize}.#{exception.query}"
}, status: :unauthorized
end
def not_found(exception)
render json: { error: exception.message }, status: :not_found
end
def internal_server_error(exception)
response = { type: exception.class.to_s, message: exception.message, backtrace: exception.backtrace }
render(json: response, status: :internal_server_error)
end
end
|
require 'spec_helper'
describe "module_of_disciplines/index.html.erb" do
before(:each) do
assign(:module_of_disciplines, [
stub_model(ModuleOfDiscipline),
stub_model(ModuleOfDiscipline)
])
end
it "renders a list of module_of_disciplines" do
render
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
box = {
:box => "ubuntu/trusty64",
:hostname => "macdash-dev",
:ram => 256
}
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = box[:box]
config.vm.hostname = "%s" % box[:hostname]
config.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--memory", box[:ram]]
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
config.vm.network :forwarded_port, guest: 5000, host: 5000
config.vm.provision "shell", path: "vagrant.sh"
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string
# last_sign_in_ip :string
# created_at :datetime not null
# updated_at :datetime not null
# profile_id :integer
# role :integer
#
class User < ActiveRecord::Base
# BE CAREFUL: Don't change the existing order, add before admin if you add new roles
# last role must be admin always
enum role: [:student, :faculty, :admin]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:trackable,
:validatable
validates :role,
presence: true,
inclusion: {
in: roles.keys[0..-1-1],
message: "must be either " + roles.keys[0..-1-1].join(" or ") # build error message except last role
}
# Model Associations
belongs_to :profile
has_many :teams
has_many :contributions
has_many :requests
end
|
class AdminMailer < ApplicationMailer
def update_email(current_admin, edited_admin)
@current_admin = current_admin
@edited_admin = edited_admin
mail(to: @edited_admin.email, subject: "Seus dados foram alterados")
end
end
|
require 'rails_helper'
RSpec.describe Deployment, type: :model do
describe 'associations' do
it { is_expected.to belong_to(:app) }
end
describe 'validations' do
it 'does not allow invalid image' do
deployment = build_stubbed(:deployment, image: "ELF\x80\x20")
expect(deployment).not_to be_valid
end
it 'does not allow too big image' do
big_image = 'PK' + 'x' * (Deployment::MAX_IMAGE_SIZE)
deployment = build_stubbed(:deployment, image: big_image)
expect(deployment).not_to be_valid
end
it 'does not allow too debug data' do
debug = 'x' * (Deployment::MAX_DEBUG_DATA_SIZE + 1)
deployment = build_stubbed(:deployment, debug: debug)
expect(deployment).not_to be_valid
end
it 'does not allow too long comments' do
deployment = build_stubbed(:deployment, comment: 'a' * 1025)
expect(deployment).not_to be_valid
end
it 'does not allow invalid tags' do
invalid_tags = ['"foo-bar-baz', '00asd', 'a' * 129]
invalid_tags.each do |tag|
deployment = build_stubbed(:deployment, tag: tag)
expect(deployment).not_to be_valid
end
end
end
end
|
class Temperature
def initialize(opts = {})
@ftemp = opts[:f]
@ctemp = opts[:c]
@ftemp = @ctemp * 1.8 + 32 unless @ctemp.nil?
@ctemp = ((@ftemp - 32) / 1.8).round unless @ftemp.nil?
end
def in_fahrenheit
@ftemp
end
def in_celsius
@ctemp
end
def self.from_celsius(temp)
self.new(:c => temp)
end
def self.from_fahrenheit(temp)
self.new(:f => temp)
end
end
class Celsius < Temperature
def initialize(temp)
@ctemp = temp
@ftemp = @ctemp * 1.8 + 32 unless @ctemp.nil?
end
end
class Fahrenheit < Temperature
def initialize(temp)
@ftemp = temp
@ctemp = ((@ftemp - 32) / 1.8).round unless @ftemp.nil?
end
end |
json.array!(@member_types) do |member_type|
json.extract! member_type, :id, :name, :description
json.url member_type_url(member_type, format: :json)
end
|
# frozen_string_literal: true
module Files
class Certificate
attr_reader :options, :attributes
def initialize(attributes = {}, options = {})
@attributes = attributes || {}
@options = options || {}
end
# int64 - Certificate ID
def id
@attributes[:id]
end
def id=(value)
@attributes[:id] = value
end
# string - Full text of SSL certificate
def certificate
@attributes[:certificate]
end
def certificate=(value)
@attributes[:certificate] = value
end
# date-time - Certificate created at
def created_at
@attributes[:created_at]
end
# string - Certificate status. (One of `Request Generated`, `New`, `Active`, `Active/Expired`, `Expired`, or `Available`)
def display_status
@attributes[:display_status]
end
def display_status=(value)
@attributes[:display_status] = value
end
# array - Domains on this certificate other than files.com domains
def domains
@attributes[:domains]
end
def domains=(value)
@attributes[:domains] = value
end
# date-time - Certificate expiration date/time
def expires_at
@attributes[:expires_at]
end
def expires_at=(value)
@attributes[:expires_at] = value
end
# boolean - Is this certificate automatically managed and renewed by Files.com?
def brick_managed
@attributes[:brick_managed]
end
def brick_managed=(value)
@attributes[:brick_managed] = value
end
# string - Intermediate certificates
def intermediates
@attributes[:intermediates]
end
def intermediates=(value)
@attributes[:intermediates] = value
end
# array - A list of IP addresses associated with this SSL Certificate
def ip_addresses
@attributes[:ip_addresses]
end
def ip_addresses=(value)
@attributes[:ip_addresses] = value
end
# string - X509 issuer
def issuer
@attributes[:issuer]
end
def issuer=(value)
@attributes[:issuer] = value
end
# string - Descriptive name of certificate
def name
@attributes[:name]
end
def name=(value)
@attributes[:name] = value
end
# string - Type of key
def key_type
@attributes[:key_type]
end
def key_type=(value)
@attributes[:key_type] = value
end
# string - Certificate signing request text
def request
@attributes[:request]
end
def request=(value)
@attributes[:request] = value
end
# string - Certificate status (Request Generated, New, Active, Active/Expired, Expired, or Available)
def status
@attributes[:status]
end
def status=(value)
@attributes[:status] = value
end
# string - X509 Subject name
def subject
@attributes[:subject]
end
def subject=(value)
@attributes[:subject] = value
end
# date-time - Certificated last updated at
def updated_at
@attributes[:updated_at]
end
# string - Domain for certificate.
def certificate_domain
@attributes[:certificate_domain]
end
def certificate_domain=(value)
@attributes[:certificate_domain] = value
end
# string - Country.
def certificate_country
@attributes[:certificate_country]
end
def certificate_country=(value)
@attributes[:certificate_country] = value
end
# string - State or province.
def certificate_state_or_province
@attributes[:certificate_state_or_province]
end
def certificate_state_or_province=(value)
@attributes[:certificate_state_or_province] = value
end
# string - City or locale.
def certificate_city_or_locale
@attributes[:certificate_city_or_locale]
end
def certificate_city_or_locale=(value)
@attributes[:certificate_city_or_locale] = value
end
# string - Company name.
def certificate_company_name
@attributes[:certificate_company_name]
end
def certificate_company_name=(value)
@attributes[:certificate_company_name] = value
end
# string - Department name or organization unit 1
def csr_ou1
@attributes[:csr_ou1]
end
def csr_ou1=(value)
@attributes[:csr_ou1] = value
end
# string - Department name or organization unit 2
def csr_ou2
@attributes[:csr_ou2]
end
def csr_ou2=(value)
@attributes[:csr_ou2] = value
end
# string - Department name or organization unit 3
def csr_ou3
@attributes[:csr_ou3]
end
def csr_ou3=(value)
@attributes[:csr_ou3] = value
end
# string - Email address for the certificate owner.
def certificate_email_address
@attributes[:certificate_email_address]
end
def certificate_email_address=(value)
@attributes[:certificate_email_address] = value
end
# string - Confirms the key type.
def key_type_confirm_given
@attributes[:key_type_confirm_given]
end
def key_type_confirm_given=(value)
@attributes[:key_type_confirm_given] = value
end
# string - Certificate private key.
def private_key
@attributes[:private_key]
end
def private_key=(value)
@attributes[:private_key] = value
end
# string - Certificate password.
def password
@attributes[:password]
end
def password=(value)
@attributes[:password] = value
end
# Deactivate SSL Certificate
def deactivate(params = {})
params ||= {}
params[:id] = @attributes[:id]
raise MissingParameterError.new("Current object doesn't have a id") unless @attributes[:id]
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
Api.send_request("/certificates/#{@attributes[:id]}/deactivate", :post, params, @options)
end
# Activate SSL Certificate
#
# Parameters:
# replace_cert - string - Leave blank, set to `any` or `new_ips`.
def activate(params = {})
params ||= {}
params[:id] = @attributes[:id]
raise MissingParameterError.new("Current object doesn't have a id") unless @attributes[:id]
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: replace_cert must be an String") if params.dig(:replace_cert) and !params.dig(:replace_cert).is_a?(String)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
Api.send_request("/certificates/#{@attributes[:id]}/activate", :post, params, @options)
end
# Parameters:
# name - string - Internal certificate name.
# intermediates - string - Any intermediate certificates. PEM or PKCS7 formats accepted.
# certificate - string - The certificate. PEM or PKCS7 formats accepted.
def update(params = {})
params ||= {}
params[:id] = @attributes[:id]
raise MissingParameterError.new("Current object doesn't have a id") unless @attributes[:id]
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: name must be an String") if params.dig(:name) and !params.dig(:name).is_a?(String)
raise InvalidParameterError.new("Bad parameter: intermediates must be an String") if params.dig(:intermediates) and !params.dig(:intermediates).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate must be an String") if params.dig(:certificate) and !params.dig(:certificate).is_a?(String)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
Api.send_request("/certificates/#{@attributes[:id]}", :patch, params, @options)
end
def delete(params = {})
params ||= {}
params[:id] = @attributes[:id]
raise MissingParameterError.new("Current object doesn't have a id") unless @attributes[:id]
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
Api.send_request("/certificates/#{@attributes[:id]}", :delete, params, @options)
end
def destroy(params = {})
delete(params)
end
def save
if @attributes[:id]
update(@attributes)
else
new_obj = Certificate.create(@attributes, @options)
@attributes = new_obj.attributes
end
end
# Parameters:
# page - integer - Current page number.
# per_page - integer - Number of records to show per page. (Max: 10,000, 1,000 or less is recommended).
# action - string - Deprecated: If set to `count` returns a count of matching records rather than the records themselves.
def self.list(params = {}, options = {})
raise InvalidParameterError.new("Bad parameter: page must be an Integer") if params.dig(:page) and !params.dig(:page).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: per_page must be an Integer") if params.dig(:per_page) and !params.dig(:per_page).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: action must be an String") if params.dig(:action) and !params.dig(:action).is_a?(String)
response, options = Api.send_request("/certificates", :get, params, options)
response.data.map { |object| Certificate.new(object, options) }
end
def self.all(params = {}, options = {})
list(params, options)
end
# Parameters:
# id (required) - integer - Certificate ID.
def self.find(id, params = {}, options = {})
params ||= {}
params[:id] = id
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
response, options = Api.send_request("/certificates/#{params[:id]}", :get, params, options)
Certificate.new(response.data, options)
end
def self.get(id, params = {}, options = {})
find(id, params, options)
end
# Parameters:
# name (required) - string - Internal name of the SSL certificate.
# certificate_domain - string - Domain for certificate.
# certificate_country - string - Country.
# certificate_state_or_province - string - State or province.
# certificate_city_or_locale - string - City or locale.
# certificate_company_name - string - Company name.
# csr_ou1 - string - Department name or organization unit 1
# csr_ou2 - string - Department name or organization unit 2
# csr_ou3 - string - Department name or organization unit 3
# certificate_email_address - string - Email address for the certificate owner.
# key_type - string - Any supported key type. Defaults to `RSA-4096`.
# key_type_confirm_given - string - Confirms the key type.
# certificate - string - The certificate. PEM or PKCS7 formats accepted.
# private_key - string - Certificate private key.
# password - string - Certificate password.
# intermediates - string - Intermediate certificates. PEM or PKCS7 formats accepted.
def self.create(params = {}, options = {})
raise InvalidParameterError.new("Bad parameter: name must be an String") if params.dig(:name) and !params.dig(:name).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_domain must be an String") if params.dig(:certificate_domain) and !params.dig(:certificate_domain).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_country must be an String") if params.dig(:certificate_country) and !params.dig(:certificate_country).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_state_or_province must be an String") if params.dig(:certificate_state_or_province) and !params.dig(:certificate_state_or_province).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_city_or_locale must be an String") if params.dig(:certificate_city_or_locale) and !params.dig(:certificate_city_or_locale).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_company_name must be an String") if params.dig(:certificate_company_name) and !params.dig(:certificate_company_name).is_a?(String)
raise InvalidParameterError.new("Bad parameter: csr_ou1 must be an String") if params.dig(:csr_ou1) and !params.dig(:csr_ou1).is_a?(String)
raise InvalidParameterError.new("Bad parameter: csr_ou2 must be an String") if params.dig(:csr_ou2) and !params.dig(:csr_ou2).is_a?(String)
raise InvalidParameterError.new("Bad parameter: csr_ou3 must be an String") if params.dig(:csr_ou3) and !params.dig(:csr_ou3).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate_email_address must be an String") if params.dig(:certificate_email_address) and !params.dig(:certificate_email_address).is_a?(String)
raise InvalidParameterError.new("Bad parameter: key_type must be an String") if params.dig(:key_type) and !params.dig(:key_type).is_a?(String)
raise InvalidParameterError.new("Bad parameter: key_type_confirm_given must be an String") if params.dig(:key_type_confirm_given) and !params.dig(:key_type_confirm_given).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate must be an String") if params.dig(:certificate) and !params.dig(:certificate).is_a?(String)
raise InvalidParameterError.new("Bad parameter: private_key must be an String") if params.dig(:private_key) and !params.dig(:private_key).is_a?(String)
raise InvalidParameterError.new("Bad parameter: password must be an String") if params.dig(:password) and !params.dig(:password).is_a?(String)
raise InvalidParameterError.new("Bad parameter: intermediates must be an String") if params.dig(:intermediates) and !params.dig(:intermediates).is_a?(String)
raise MissingParameterError.new("Parameter missing: name") unless params.dig(:name)
response, options = Api.send_request("/certificates", :post, params, options)
Certificate.new(response.data, options)
end
# Deactivate SSL Certificate
def self.deactivate(id, params = {}, options = {})
params ||= {}
params[:id] = id
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
response, _options = Api.send_request("/certificates/#{params[:id]}/deactivate", :post, params, options)
response.data
end
# Activate SSL Certificate
#
# Parameters:
# replace_cert - string - Leave blank, set to `any` or `new_ips`.
def self.activate(id, params = {}, options = {})
params ||= {}
params[:id] = id
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: replace_cert must be an String") if params.dig(:replace_cert) and !params.dig(:replace_cert).is_a?(String)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
response, _options = Api.send_request("/certificates/#{params[:id]}/activate", :post, params, options)
response.data
end
# Parameters:
# name - string - Internal certificate name.
# intermediates - string - Any intermediate certificates. PEM or PKCS7 formats accepted.
# certificate - string - The certificate. PEM or PKCS7 formats accepted.
def self.update(id, params = {}, options = {})
params ||= {}
params[:id] = id
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise InvalidParameterError.new("Bad parameter: name must be an String") if params.dig(:name) and !params.dig(:name).is_a?(String)
raise InvalidParameterError.new("Bad parameter: intermediates must be an String") if params.dig(:intermediates) and !params.dig(:intermediates).is_a?(String)
raise InvalidParameterError.new("Bad parameter: certificate must be an String") if params.dig(:certificate) and !params.dig(:certificate).is_a?(String)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
response, options = Api.send_request("/certificates/#{params[:id]}", :patch, params, options)
Certificate.new(response.data, options)
end
def self.delete(id, params = {}, options = {})
params ||= {}
params[:id] = id
raise InvalidParameterError.new("Bad parameter: id must be an Integer") if params.dig(:id) and !params.dig(:id).is_a?(Integer)
raise MissingParameterError.new("Parameter missing: id") unless params.dig(:id)
response, _options = Api.send_request("/certificates/#{params[:id]}", :delete, params, options)
response.data
end
def self.destroy(id, params = {}, options = {})
delete(id, params, options)
end
end
end
|
class Api::Picker::SessionsController < Api::PickerController
skip_before_action :authenticate_user_from_token!, :require_picker!, only: [:create, :verify_otp]
before_action :authenticate_user!, except: [:create, :verify_otp]
def create
@user = User.new user_params
@user.inactive = true
@user.role = :ragpicker
if @user.save
if (@invitation = Invitation.find_by(phone_number: @user.phone_number))
@invitation.update(user: @user, accepted_at: @user.created_at)
end
raw = NumberTokenGenerator.instance.generate_unique_code(User, :otp)
@user.update(otp: raw)
SmsService.send_otp @user.phone_number, @user.otp
render json: @user, meta: {
otp: @user.otp
}
else
code, msg =
if user1 = User.find_by(phone_number: user_params[:phone_number])
if user1.otp? && user1.ragpicker?
render json: user1, meta: {
otp: user1.otp
} and return
end
[10100, 'Request submitted for this phone number before']
else
[90002, @user.errors.full_messages.join('. ')]
end
render json: {error: {code: code, msg: msg}}, status: 405
end
end
#def signin
# user = User.ragpickers.find_for_database_authentication(
# phone_number: params[:phone_number].try(:downcase)
# )
# if user && user.valid_password?(params[:password])
# user.last_sign_in_at = Time.now
# user.invalidate_authentication_token
# user.save
# render json: user, serializer: UserDetailSerializer
# else
# user = User.find_for_database_authentication(
# phone_number: params[:phone_number].try(:downcase)
# )
# if user.nil?
# render json: {error: {code: 10000, msg: "User not registered"}}, status: 403
# elsif !user.valid_password?(params[:password])
# render json: {error: {code: 10001, msg: "Invalid password"}}, status: 403
# else
# render json: {error: {code: 90000, msg: "Bad credentials"}}, status: 403
# end
# end
#end
def verify_otp
otp = params[:otp].presence
if otp && (@user = User.find_by(otp: otp)) && !@user.active?
@user.activate_and_invalidate_authentication_token
render json: {status: true, authentication_token: @user.authentication_token}
else
render json: {error: {code: 20009, msg: 'Your OTP is invalid'}}, status: 405
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :avatar,
:full_name, :phone_number, :gender, :address, :city, :notified, :pincode,
:lat, :lon, :yard_number)
end
end
|
require '_spec_helper'
describe "rotate words in an array by 13" do
describe "#is_lowercase?" do
it "returns true when a number is between 97 and 122" do
lowerbound = 97
upperbound = 122
expect(is_lowercase?(lowerbound)).to eq(true)
expect(is_lowercase?(upperbound)).to eq(true)
end
it "returns false when a number is not between 96 and 122" do
lowerbound = 96
upperbound = 123
expect(is_lowercase?(lowerbound)).to eq(false)
expect(is_lowercase?(upperbound)).to eq(false)
end
end
describe "#calculate_lowercase_rotation" do
it "returns the character + 13 for numbers between 64 & 77" do
lowerbound = "a".ord
expect(calculate_lowercase_rotation(lowerbound)).to match("n")
end
it "returns the character + 13 for numbers between 88 & 91" do
upperbound = "z".ord
expect(calculate_lowercase_rotation(upperbound)).to match("m")
end
end
describe "#is_uppercase?" do
it "returns true when a number is between 65 and 90" do
lowerbound = 65
upperbound = 90
expect(is_uppercase?(lowerbound)).to eq(true)
expect(is_uppercase?(upperbound)).to eq(true)
end
it "returns false when a number is not between 64 and 91" do
lowerbound = 64
upperbound = 91
expect(is_uppercase?(lowerbound)).to eq(false)
expect(is_uppercase?(upperbound)).to eq(false)
end
end
describe "#calculate_uppercase_rotation" do
it "returns the character + 13 for numbers between 64 & 77" do
lowerbound = "A".ord
expect(calculate_uppercase_rotation(lowerbound)).to match("N")
end
it "returns the character + 13 for numbers between 88 & 91" do
upperbound = "Z".ord
expect(calculate_uppercase_rotation(upperbound)).to match("M")
end
end
describe "#rotate_letters" do
it "returns a word completely rotated" do
unrotated = "Jul"
rotated = rotate_letters(unrotated)
expect(rotated).to match("Why")
end
end
describe "#rot13" do
# returning the correct case is not required but it should be
describe "uppercase letters" do
it "returns the character + 13 for numbers between 64 & 77" do
lowerbound = "A".ord
expect(calculate_uppercase_rotation(lowerbound)).to match("N")
end
it "returns the character + 13 for numbers between 88 & 91" do
upperbound = "Z".ord
expect(calculate_uppercase_rotation(upperbound)).to match("M")
end
end
describe "lowercase letters" do
it "returns the character + 13 for numbers between 64 & 77" do
lowerbound = "a".ord
expect(calculate_lowercase_rotation(lowerbound)).to match("n")
end
it "returns the character + 13 for numbers between 88 & 91" do
upperbound = "z".ord
expect(calculate_lowercase_rotation(upperbound)).to match("m")
end
end
it "returns characters that are not part of the English alphabet in their original form" do
unrotated = ["?"]
rotated_13 = rot13(unrotated)
expect(rotated_13).to match(["?"])
end
it "returns words rotated by 13 places" do
unrotated = ["Jul", "qvq", "gur", "puvpxra", "pebff", "gur", "ebnq"]
rotated_13 = rot13(unrotated)
expect(rotated_13).to match(["Why", "did", "the", "chicken", "cross", "the", "road"])
end
it "returns rotated characters back to their original form" do
unrotated = ["Jul", "qvq", "gur", "puvpxra", "pebff", "gur", "ebnq"]
rotated_form = rot13(unrotated)
orginial_form = rot13(rotated_form)
expect(unrotated).to match(orginial_form)
end
end
end
|
class AddTccIdToUsers < ActiveRecord::Migration
def change
add_column :users, :tcc_id, :integer
add_index :users, [:tcc_id]
end
end
|
class CreateLoans < ActiveRecord::Migration
def change
create_table :loans do |t|
t.references :financing_plan, index: true, foreign_key: true, null: false
t.integer :amount, null: false
t.float :interest_rate_per_year, null: false
t.integer :term_in_years, null: false
t.timestamps null: false
end
end
end
|
# web elements and functions for page
class BookStorePage
include Capybara::DSL
include RSpec::Matchers
include Capybara::RSpecMatchers
def initialize
@search_box = Element.new(:css, '#searchBox')
@user_name_value = Element.new(:css, '#userName-value')
@go_back_to_store_btn = Element.new(:css, '.text-left #addNewRecordButton')
@add_book = Element.new(:css, '.text-right #addNewRecordButton')
@row_item = Element.new(:css, '.rt-tr-group')
end
def visit
Capybara.visit('books')
end
def add_book(name)
click_link(name)
@add_book.click
# webpage too slow sleep to catch up
sleep 1
page.driver.browser.switch_to.alert.accept
end
def go_back_to_store
@go_back_to_store_btn.click
end
def search_for_book(name)
@search_box.set("")
@search_box.send_keys(name)
end
end
|
#========================================================================
# ** Crossfader, by: KilloZapit
#------------------------------------------------------------------------
# Just a script to tweak the fades to use fancy crossfades like the
# battle transition screens for all fades. By default this is made to use
# an image in the Graphics/System/ directory. You can set it to use no image,
# but it's not hard to make a simple image to use.
#------------------------------------------------------------------------
module KZFadeConfig
# FADE_IMAGE: Transition image used for fades.
# Works the battle transition image, use "" to use no image.
FADE_IMAGE = "Graphics/System/Fade"
# FADE_EDGE: Effects how smooth image fades are.
FADE_EDGE = 100
# FADE_TIME: Set to a number to set how long fades take or leave nil for
# a default value based on the transition_speed method.
FADE_TIME = nil
# FADE_TIME_FACTOR: Multiplier for default fade times.
FADE_TIME_FACTOR = 2
# DO_MAP_FADES: If true, changes map transfers to use crossfades instead.
# Only works with fades to black though, fades to white will be the same.
DO_MAP_FADES = true
# DO_BATTLE_FADES: If true, changes fadeing out after a battle to use
# crossfades after a compleated battle.
DO_BATTLE_FADES = true
# D0_BATTLE_RUN_CROSSFADE: If this is true it will do a normal fade instead of
# a crossfade if the battle ends and some enemies are still alive.
D0_BATTLE_RUN_FADE = true
# DO_GAMEOVER_FADES: changes the gameover scene to use crossfades as well,
# though they will be a lot slower, using the gameover scene's fade times.
DO_GAMEOVER_FADES = true
# DO_GAMEOVER_FADEOUT_FROZEN_GRAPHICS: if this is true it will fade out what
# ever was displayed on the screen before displaying the gameover screen,
# if it is false it will fade directly to the gameover screen instead.
DO_GAMEOVER_FADEOUT_FROZEN_GRAPHICS = false
end
class Scene_Base
def crossfade_time
KZFadeConfig::FADE_TIME || transition_speed * KZFadeConfig::FADE_TIME_FACTOR
end
def perform_transition
Graphics.transition(crossfade_time, KZFadeConfig::FADE_IMAGE,
KZFadeConfig::FADE_EDGE)
end
#--------------------------------------------------------------------------
# * Fade Out All Sounds and Graphics
#--------------------------------------------------------------------------
def fadeout_all(time = 1000)
RPG::BGM.fade(time)
RPG::BGS.fade(time)
RPG::ME.fade(time)
crossfade_to_black
RPG::BGM.stop
RPG::BGS.stop
RPG::ME.stop
end
#--------------------------------------------------------------------------
# * Do a crossfade to a blank screen
#--------------------------------------------------------------------------
def crossfade_to_black
Graphics.freeze
sprite = Sprite.new
sprite.bitmap = Bitmap.new(Graphics.width, Graphics.height)
color = Color.new(0, 0, 0)
sprite.bitmap.fill_rect(0, 0, Graphics.width, Graphics.height, color)
sprite.x = 0
sprite.y = 0
sprite.z = 10000
perform_transition
Graphics.freeze
sprite.dispose
end
end
class Scene_Map
#--------------------------------------------------------------------------
# * Force one frame update during black screens to make sure all the images
# are loaded and all the screen tints are set right.
#--------------------------------------------------------------------------
alias_method :perform_transition_fade_base, :perform_transition
def perform_transition
update_for_fade
perform_transition_fade_base
end
#--------------------------------------------------------------------------
# * Preprocessing for Transferring Player
#--------------------------------------------------------------------------
def pre_transfer
@map_name_window.close
case $game_temp.fade_type
when 0
crossfade_to_black
when 1
white_fadeout(fadeout_speed)
end
end
#--------------------------------------------------------------------------
# * Post Processing for Transferring Player
#--------------------------------------------------------------------------
def post_transfer
case $game_temp.fade_type
when 0
perform_transition
when 1
Graphics.wait(fadein_speed / 2)
update_for_fade
white_fadein(fadein_speed)
end
@map_name_window.open
end
end if KZFadeConfig::DO_MAP_FADES
class Scene_Battle < Scene_Base
def pre_terminate
super
if SceneManager.scene_is?(Scene_Map)
if (!KZFadeConfig::D0_BATTLE_RUN_FADE) || $game_troop.all_dead?
crossfade_to_black
else
Graphics.fadeout(30)
end
elsif SceneManager.scene_is?(Scene_Title)
Graphics.fadeout(60)
end
end
end if KZFadeConfig::DO_BATTLE_FADES
class Scene_Gameover < Scene_Base
#--------------------------------------------------------------------------
# * Start Processing
#--------------------------------------------------------------------------
def start
super
play_gameover_music
fadeout_frozen_graphics if KZFadeConfig::DO_GAMEOVER_FADEOUT_FROZEN_GRAPHICS
create_background
end
#--------------------------------------------------------------------------
# * Execute Transition
#--------------------------------------------------------------------------
def perform_transition
Graphics.transition(fadein_speed, KZFadeConfig::FADE_IMAGE,
KZFadeConfig::FADE_EDGE)
end
#--------------------------------------------------------------------------
# * Fade Out Frozen Graphics
#--------------------------------------------------------------------------
def fadeout_frozen_graphics
Graphics.transition(fadeout_speed, KZFadeConfig::FADE_IMAGE,
KZFadeConfig::FADE_EDGE)
Graphics.freeze
end
end if KZFadeConfig::DO_GAMEOVER_FADES |
# ~*~ encoding: utf-8 ~*~
require File.expand_path(File.join(File.dirname(__FILE__), 'helper'))
context "Precious::Views::Editing" do
include Rack::Test::Methods
setup do
@path = cloned_testpath('examples/revert.git')
Precious::App.set(:gollum_path, @path)
@wiki = Gollum::Wiki.new(@path)
end
teardown do
FileUtils.rm_rf(@path)
end
test "creating page is blocked" do
Precious::App.set(:wiki_options, { allow_editing: false})
post "/gollum/create", :content => 'abc', :page => "D",
:format => 'markdown', :message => 'def'
assert !last_response.ok?
page = @wiki.page('D')
assert page.nil?
end
test ".redirects.gollum file should not be accessible" do
Precious::App.set(:wiki_options, { allow_editing: true, allow_uploads: true })
get '/.redirects.gollum'
assert_match /Accessing this resource is not allowed/, last_response.body
end
test ".redirects.gollum file should not be editable" do
Precious::App.set(:wiki_options, { allow_editing: true, allow_uploads: true })
get '/gollum/edit/.redirects.gollum'
assert_match /Changing this resource is not allowed/, last_response.body
end
test "frontend links for editing are not blocked" do
Precious::App.set(:wiki_options, { allow_editing: true, allow_uploads: true })
get '/A'
assert_match /Delete this Page/, last_response.body, "'Delete this Page' link is blocked in page template"
assert_match /New/, last_response.body, "'New' button is blocked in page template"
assert_match /Upload\b/, last_response.body, "'Upload' link is blocked in page template"
assert_match /Rename/, last_response.body, "'Rename' link is blocked in page template"
assert_match /Edit/, last_response.body, "'Edit' link is blocked in page template"
get '/gollum/overview'
assert_match /New/, last_response.body, "'New' link is blocked in pages template"
get '/gollum/history/A'
assert_no_match /Edit/, last_response.body, "'Edit' link is not blocked in history template"
get '/gollum/compare/A/fc66539528eb96f21b2bbdbf557788fe8a1196ac..b26b791cb7917c4f37dd9cb4d1e0efb24ac4d26f'
assert_no_match /Edit Page/, last_response.body, "'Edit Page' link is not blocked in compare template"
assert_match /Revert Changes/, last_response.body, "'Revert Changes' link is blocked in compare template"
end
test "frontend links for editing blocked" do
Precious::App.set(:wiki_options, { allow_editing: false })
get '/A'
assert_no_match /Delete this Page/, last_response.body, "'Delete this Page' link not blocked in page template"
assert_no_match /New/, last_response.body, "'New' button not blocked in page template"
assert_no_match /Upload\b/, last_response.body, "'Upload' link not blocked in page template"
assert_no_match /Rename/, last_response.body, "'Rename' link not blocked in page template"
assert_no_match /Edit/, last_response.body, "'Edit' link not blocked in page template"
get '/gollum/overview'
assert_no_match /New/, last_response.body, "'New' link not blocked in pages template"
get '/gollum/history/A'
assert_no_match /Edit/, last_response.body, "'Edit' link not blocked in history template"
get '/gollum/compare/A/fc66539528eb96f21b2bbdbf557788fe8a1196ac..b26b791cb7917c4f37dd9cb4d1e0efb24ac4d26f'
assert_no_match /Edit Page/, last_response.body, "'Edit Page' link not blocked in compare template"
assert_no_match /Revert Changes/, last_response.body, "'Revert Changes' link not blocked in compare template"
end
def app
Precious::App
end
end |
class AddMimesToFiles < ActiveRecord::Migration
def change
add_column :uploads, :mime_type , :string
add_column :documents, :mime_type , :string
add_column :aux_files, :mime_type , :string
end
end
|
class Url < ActiveRecord::Base
before_save :validate_url
def clicked!
self.click_count += 1
self.save
end
def validate_url
unless full_url.match(/http[s]{0,1}:\/\/.*/)
self.full_url = "http://" + self.full_url
end
end
end
|
class CreateCivilityVotes < ActiveRecord::Migration
def change
create_table :civility_votes do |t|
t.integer :voter_id
t.integer :debate_id
t.integer :affirmative_id
t.integer :negative_id
t.integer :affirmative_rating
t.integer :negative_rating
t.timestamps null: false
end
end
end
|
# frozen_string_literal: true
module Hyrax
module CoreMetadata
def self.included(work)
work.property :depositor, predicate: ::RDF::URI.new('http://id.loc.gov/vocabulary/relators/dpt'), multiple: false
work.property :title, predicate: ::RDF::Vocab::DC.title
work.property :date_uploaded, predicate: ::RDF::Vocab::DC.dateSubmitted, multiple: false
work.property :date_modified, predicate: ::RDF::Vocab::DC.modified, multiple: false
end
end
end
|
module XCB
class Reply::Geometry < FFI::Struct
layout :response_type, :uint8,
:depth, :uint8,
:sequence, :uint16,
:length, :uint32,
:root, :window,
:x, :int16,
:y, :int16,
:width, :uint16,
:height, :uint16,
:border_width, :uint16,
:pad0, [:uint8, 2]
end
end
|
class Label < ActiveRecord::Base
has_many :images, as: :imageable
has_many :items
end
|
describe Repositories::Workers::ScanRepository do
describe '#perform' do
subject(:worker_result) { described_class.new.perform(repository.id) }
let(:repository) { create :repository_bitbucket }
let(:failure) { false }
let(:error) { nil }
before do
allow(Repository).to receive(:find).and_return(repository)
interactor_result = double(failure?: failure, error: error) # rubocop:disable RSpec/VerifiedDoubles
allow(repository).to receive(:scan).and_return(interactor_result)
end
it 'calls interactor correctly' do
worker_result
expect(repository).to have_received(:scan)
end
context 'when it fails' do
let(:failure) { true }
let(:error) { 'Repository scan failed' }
it 'raise exception' do
expect { worker_result }.to raise_error(described_class::ScanRepositoryError)
end
end
end
end
|
class Datum < ActiveRecord::Base
attr_accessible :book, :format, :name, :uncompressed_size
@@mimetypes = { "CHM" => "application/vnd.ms-htmlhelp", "DJVU" => "image/vnd.djvu", "DOC" => "application/vnd.ms-word.document.macroenabled.12", "EPUB" => "application/epub+zip", "LIT" => "application/x-ms-reader", "MOBI" => "application/x-mobipocket-ebook", "PDB" => "application/vnd.palm", "PDF" => "application/pdf", "PRC" => "application/x-mobipocket-ebook", "RTF" => "application/rtf"}
def show_mime
puts @@mimetypes
end
def get_mime_type
return @@mimetypes[format.upcase]
end
end
|
class Parameter < ActiveRecord::Base
belongs_to :course
belongs_to :college
YEAR = (2009..Time.now.year)
SEMESTER = {
"1" => "Ganjil",
"2" => "Genap"
}
def semester_nama
SEMESTER[semester]
end
def self.semester_nama_options
SEMESTER.to_a.sort
end
end
|
# frozen_string_literal: true
#
# Cookbook Name:: resource_container_host_linux
# Recipe:: default
#
# Copyright 2017, P. van der Velde
#
# Always make sure that apt is up to date
apt_update 'update' do
action :update
end
#
# Include the local recipes
#
include_recipe 'resource_container_host_linux::firewall'
include_recipe 'resource_container_host_linux::consul'
include_recipe 'resource_container_host_linux::docker'
include_recipe 'resource_container_host_linux::meta'
include_recipe 'resource_container_host_linux::network'
include_recipe 'resource_container_host_linux::nomad'
include_recipe 'resource_container_host_linux::provisioning'
|
require 'spec_helper'
require_relative "../../lib/models/reward_type.rb"
RSpec.describe RewardType, type: :model do
it "should be valid with the correct attributes" do
expect(FactoryBot.build(:reward_type, :percent_off)).to be_valid
end
context "#name" do
it "should be present" do
expect(FactoryBot.build(:reward_type)).to_not be_valid
end
it "should be unique" do
FactoryBot.create(:reward_type, :percent_off)
expect(FactoryBot.build(:reward_type, :percent_off)).to_not be_valid
end
end
end
|
FactoryBot.define do
factory :delivery do
customer_id { 1 }
name { Gimei.kanji }
address { Gimei.address.kanji }
postcode { Faker::Address.postcode }
end
end |
module RailsMaps
class Map
def initialize(params)
@name = params[:name]
raise "Map needs a name attribute" unless @name
params = {lat: 0, lon: 0, zoom: nil}.merge(params)
@provider = "http://{s}.tile.osm.org/{z}/{x}/{y}.png"
@attribution = '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
@lat = params[:lat]
@lon = params[:lon]
@zoom = params[:zoom]
@markers = []
@click = Maps::Event.new
end
def center
@center
end
end
end
|
# frozen_string_literal: true
require './commands/recipes/list'
RSpec.describe Commands::Recipes::List do
let(:params) { instance_double(Sinatra::IndifferentHash) }
let(:request) { instance_double(Sinatra::Request) }
let(:command) { described_class.new(request, params) }
let!(:recipe) do
Recipe.create!(
name: "Strawberry",
url: "https://www.example.com/strawberry"
)
end
subject { command.result }
it "lists all recipes" do
expect(subject).to be_success
list_value = subject.value!
expect(list_value.locals[:recipes]).to include(recipe)
end
end
|
# @param {String} s
# @param {String} p
# @return {Boolean}
def is_match(s, p)
match = %r(#{p}).match(s)
return false if match.nil?
match.to_s == s
end
|
class RolesController < ApplicationController
def self.document_params(required: false)
param :name, String, desc: 'Name of the role', required: required
param :description, String, desc: 'Description of the role', required: required
param :permissions, Hash, desc: %(Hash of permissions allowed, such as { projects: ["read", "write"] }. Valid keys: #{Role::PERMISSIONS}.), required: required
end
api :GET, '/roles', 'Returns all roles'
def index
roles = Role.all
authorize(roles)
respond_with_params roles
end
api :POST, '/roles', 'Create a role'
document_params required: true
def create
authorize(Role)
respond_with_params Role.create!(role_params)
end
api :PUT, '/roles/:id', 'Update a role'
document_params
def update
role = Role.find(params[:id])
authorize(role)
respond_with_params role.update!(role_params)
end
api :DELETE, '/roles/:id', 'Destroy a role'
def destroy
role = Role.find(params[:id])
authorize(role)
respond_with_params role.destroy
end
private
def role_params
params.permit(:name, :description, :permissions)
end
end
|
class PaymentSavingSerializer < ActiveModel::Serializer
attributes :id, :booking_id, :payment_for, :amount, :status, :midtrans_id,
:saving_type, :identity_id, :passport_id
belongs_to :booking
end
|
module ApplicationHelper
def login_form_props
{id: 'modal-login-form', title: 'Sign in', form: 'devise/sessions/form'}
end
def add_post_form_props
{id: 'modal-add-post-form', title: 'Add post', form: 'posts/form'}
end
def login_modal_form form_data
render 'shared/form_modal', props: login_form_props.reverse_merge(form_data: form_data) unless user_signed_in? || on_login?
end
def add_post_modal_form form_data
render 'shared/form_modal', props: add_post_form_props.reverse_merge(form_data: form_data) if user_signed_in?
end
private
def on_login?
controller.controller_name == 'sessions' && controller.action_name == 'new'
end
end
|
# frozen-string-literal: true
require File.join(File.dirname(__FILE__), 'helper')
class AIFFExamples < Test::Unit::TestCase
DATA_FILE_PREFIX = 'test/data/aiff-'
context 'TagLib::RIFF::AIFF::File' do
should 'Run TagLib::RIFF::AIFF::File examples' do
# @example Reading the title
title = TagLib::RIFF::AIFF::File.open("#{DATA_FILE_PREFIX}sample.aiff") do |file|
file.tag.title
end
# @example Reading AIFF-specific audio properties
TagLib::RIFF::AIFF::File.open("#{DATA_FILE_PREFIX}sample.aiff") do |file|
file.audio_properties.bits_per_sample # => 16
end
# @example Saving ID3v2 cover-art to disk
TagLib::RIFF::AIFF::File.open("#{DATA_FILE_PREFIX}sample.aiff") do |file|
id3v2_tag = file.tag
cover = id3v2_tag.frame_list('APIC').first
ext = cover.mime_type.rpartition('/')[2]
File.open("#{DATA_FILE_PREFIX}cover-art.#{ext}", 'wb') { |f| f.write cover.picture }
end
# checks
assert_equal 'AIFF Dummy Track Title - ID3v2.4', title
assert_equal true, File.exist?("#{DATA_FILE_PREFIX}cover-art.jpeg")
FileUtils.rm("#{DATA_FILE_PREFIX}cover-art.jpeg")
end
end
end
|
class AddAccountToUsers < ActiveRecord::Migration
def change
add_column :users, :account, :string, :default => "member"
end
end
|
FactoryBot.define do
factory :user do
email { '01@test.com' }
password { '123123123' }
factory :faker do
email { Faker::Internet.email }
password { 'super-password' }
end
end
factory :admin do
email { Faker::Internet.email }
password { 'super-password' }
admin { true }
end
factory :profile do
association :user, factory: :faker
name { Faker::Name.name }
second_name { Faker::Name.middle_name }
surname { Faker::Name.last_name }
end
end
|
require 'net/http'
require 'uri'
require 'json'
require 'yaml'
require 'time'
require 'date'
require 'amazon-drs/deregistrate_device'
require 'amazon-drs/subscription_info'
require 'amazon-drs/replenish'
require 'amazon-drs/error'
require 'amazon-drs/slot_status'
require 'amazon-drs/access_token'
require 'amazon-drs/test_orders'
module AmazonDrs
class Client
attr_accessor :device_model, :serial, :authorization_code, :redirect_uri, :access_token, :refresh_token, :client_id, :client_secret
attr_accessor :on_new_token
attr_writer :user_agent
def initialize(device_model)
@drs_host = 'dash-replenishment-service-na.amazon.com'
@amazon_host = 'api.amazon.com'
@device_model = device_model
@serial = nil
@authorization_code = nil
@redirect_uri = nil
@access_token = nil
@refresh_token = nil
@on_new_token = nil
@client_id = nil
@client_secret = nil
yield(self) if block_given?
end
def user_agent
@user_agent ||= "AmazonDrsRubyGem/#{AmazonDrs::VERSION}/#{RUBY_DESCRIPTION}"
end
def deregistrate_device
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeregisterResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeregisterInput@1.0'
}
path = "/deviceModels/#{@device_model}/devices/#{@serial}/registration"
response = request_drs(:delete, path, headers: headers)
if response.code == '200'
::AmazonDrs::DeregistrateDevice.new(response)
else
::AmazonDrs::Error.new(response)
end
end
def device_status(most_recently_active_date)
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeviceStatusResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeviceStatusInput@1.0'
}
path = '/deviceStatus'
request_drs(:post, path, headers: headers, params: { 'mostRecentlyActiveDate' => convert_to_iso8601(most_recently_active_date) })
if response.code == '200'
::AmazonDrs::DeviceStatus.new(response)
else
::AmazonDrs::Error.new(response)
end
end
# https://developer.amazon.com/public/solutions/devices/dash-replenishment-service/docs/dash-getsubscriptioninfo-endpoint
def subscription_info
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSubscriptionInfoResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSubscriptionInfoInput@1.0'
}
path = '/subscriptionInfo'
response = request_drs(:get, path, headers: headers)
if response.code == '200'
::AmazonDrs::SubscriptionInfo.new(response)
else
::AmazonDrs::Error.new(response)
end
end
# https://developer.amazon.com/public/solutions/devices/dash-replenishment-service/docs/dash-slotstatus-endpoint
def slot_status(slot_id, expected_replenishment_date, remaining_quantity_in_unit, original_quantity_in_unit, total_quantity_on_hand, last_use_date)
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSlotStatusResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSlotStatusInput@1.0'
}
path = "/slotStatus/#{slot_id}"
params = {
'expectedReplenishmentDate' => convert_to_iso8601(expected_replenishment_date),
'remainingQuantityInUnit' => remaining_quantity_in_unit,
'originalQuantityInUnit' => original_quantity_in_unit,
'totalQuantityOnHand' => total_quantity_on_hand,
'lastUseDate' => convert_to_iso8601(last_use_date)
}
response = request_drs(:post, path, headers: headers, params: params)
if response.code == '200'
::AmazonDrs::SlotStatus.new(response)
else
::AmazonDrs::Error.new(response)
end
end
# https://developer.amazon.com/public/solutions/devices/dash-replenishment-service/docs/dash-replenish-endpoint
def replenish(slot_id)
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsReplenishResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsReplenishInput@1.0'
}
path = "/replenish/#{slot_id}"
response = request_drs(:post, path, headers: headers)
if response.code == '200'
::AmazonDrs::Replenish.new(response)
else
::AmazonDrs::Error.new(response)
end
end
# https://developer.amazon.com/public/solutions/devices/dash-replenishment-service/docs/dash-canceltestorder-endpoint
def test_orders(slot_id)
headers = {
'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsCancelTestOrdersResult@1.0',
'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsCancelTestOrdersInput@1.0'
}
path = "/testOrders/#{slot_id}"
response = request_drs(:delete, path, headers: headers)
if response.code == '200'
::AmazonDrs::TestOrders.new(response)
else
::AmazonDrs::Error.new(response)
end
end
def get_token
if @access_token
@access_token
else
resp = request_token
process_token_response(resp)
resp
end
end
private def convert_to_iso8601(input)
case input
when Date, Time
input.iso8601
when String
input
else
input.to_s
end
end
private def process_token_response(resp)
if resp.kind_of?(AmazonDrs::Error)
nil
else
@access_token = resp.access_token
@refresh_token = resp.refresh_token
@on_new_token.call(@access_token, @refresh_token) if @on_new_token
@access_token
end
end
private def request_drs(method, path, headers: {}, params: {})
url = "https://#{@drs_host}#{path}"
if @authorization_code.nil?
raise 'Authorization Code is not set'
end
if @access_token.nil?
get_token
if resp.kind_of?(AmazonDrs::Error)
raise 'Failed to get token'
end
end
resp = request(method, url, headers: headers, params: params)
json = JSON.parse(resp.body)
if resp.code == '400' && json['message'] == 'Invalid token' && @refresh_token
resp = refresh_access_token
process_token_response(resp)
request(method, url, headers: headers, params: params)
else
resp
end
end
private def refresh_access_token
params = {
grant_type: 'refresh_token',
refresh_token: @refresh_token,
client_id: @client_id,
client_secret: @client_secret
}
@access_token = nil
request(:post, "https://#{@amazon_host}/auth/o2/token", params: params)
end
private def request_token
params = {
grant_type: 'authorization_code',
code: @authorization_code,
client_id: @client_id,
client_secret: @client_secret,
redirect_uri: @redirect_uri
}
response = request(:post, "https://#{@amazon_host}/auth/o2/token", params: params)
if response.code == '200'
::AmazonDrs::AccessToken.new(response)
else
::AmazonDrs::Error.new(response)
end
end
private def request(method, url, headers: {}, params: {})
uri = URI.parse(url)
if params.any?{ |key, value| value.is_a?(Enumerable) }
converted_params = []
params.each do |key, value|
if value.is_a?(Enumerable)
value.each_index do |i|
converted_params << ["#{key}[#{i}]", value[i]]
end
else
converted_params << [key, value]
end
end
params = converted_params
end
case method
when :delete
uri.query = URI.encode_www_form(params)
request = Net::HTTP::Delete.new(uri)
when :get
uri.query = URI.encode_www_form(params)
request = Net::HTTP::Get.new(uri)
when :post
request = Net::HTTP::Post.new(uri.path)
request.body = URI.encode_www_form(params)
end
request['Content-Type'] = 'application/x-www-form-urlencoded'
request['User-Agent'] = user_agent
headers.each do |key, value|
request[key.to_s] = value
end
if not @access_token.nil?
request["Authorization"] = "Bearer #{@access_token}"
end
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.request(request)
end
end
end
|
require 'helper'
class TestLazyTemplatetester < Test::Unit::TestCase
context "The LazyTemplatetester" do
setup do
@template_checker = LazyTemplatetester.new
end
should "accept if mandatory key is there and value fits" do
assert @template_checker.check_mustache("{{{mandatory}}}", { :mandatory => true })
assert @template_checker.check_mustache("{{{mandatory}}}{{optional}}", { :mandatory => true })
assert @template_checker.check_mustache("{{# mandatory}}huhu{{/ mandatory}}haha", { :mandatory => :hash })
assert @template_checker.check_mustache("{{^ mandatory}}huhu{{/ mandatory}}haha", { :mandatory => :hash })
assert @template_checker.check_mustache("{{# mandatory?}}huhu{{/ mandatory?}}haha", { :mandatory? => :hash })
assert @template_checker.check_mustache("{{> part}}", { :part => true })
assert @template_checker.check_mustache("{{# mandatory}}{{mand}}{{/ mandatory}}haha", { :mandatory => {:mand => true} })
assert @template_checker.check_mustache("{{{mand1}}}{{# mandatory}}{{mand}}{{/ mandatory}}", { :mand1 => true, :mandatory => {:mand => true} })
end
should "raise if mandatory key is not there or value is wrong" do
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{{mandato}}}", { :mandatory => true })
end
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{# mandatory}}{{mand}}{{/ mandatory}}", { :mandatory => true })
end
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{# mandatory}}{{mand}}{{/ mandatory}}", { :mandatory => {:mind => true} })
end
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{mandatory}}", { :mandatory => :hash })
end
end
should "fit with regexps" do
assert @template_checker.check_mustache("{{{mandato}}}", { /^manda/ => true })
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{{mandito}}}", { /^mandi/ => false })
end
end
should "work with recursive hashes" do
assert @template_checker.check_mustache("{{# mandatory}}{{# inner}}{{mand}}{{/ inner}}{{/ mandatory}}", { :mandatory => {:inner => {:mand => true}} } )
assert_raise LazyTemplateError do
@template_checker.check_mustache("{{# mandatory}}{{# inner}}{{mand}}{{/ inner}}{{/ mandatory}}", { :mandatory => {:inner => true} } )
end
end
end
end
|
puts 'Cadastrando as categorias..............'
categories = [
"Animais e acessórios",
"Esporte",
"Para sua casa",
"Eletrônico e celulares",
"Músicas e hobbies",
"Bebês e crianças",
"Moda e beleza",
"Veículos e barcos",
"Imóveis",
"Emprego e negócios"
]
categories.each do |category|
Category.find_or_create_by(description: category)
end
puts 'Categorias cadastradas com sucesso!'
#####################
puts 'Cadastrando o Administrador padrão'
Admin.create(name: 'Orfenes',
email:'rodrigo@admin.com.br',
password:'123456',
password_confirmation: '123456',
role: 0)
puts 'Adminstrador padrao cadastrado com sucesso'
####################
puts 'Cadastrando o member padrao'
member = Member.new(
email: 'rodrigo@member.com.br',
password:'123456',
password_confirmation: '123456')
member.build_profile_member
member.profile_member.first_name = 'rodrigo'
member.profile_member.second_name = 'orfenes'
member.save!
puts 'Membro padrao cadastrado com sucesso'
|
# frozen_string_literal: true
RSpec.describe GemfileNextAutoSync do
subject do
Bundler.with_original_env do
`cd spec/fixtures && bundle install`
end
end
let!(:original_gemfile) { File.read('spec/fixtures/Gemfile') }
let!(:original_gemfile_next) { File.read('spec/fixtures/Gemfile') }
let!(:original_shared) { File.read('spec/fixtures/Gemfile.shared') }
let!(:original_lock) { File.read('spec/fixtures/Gemfile.lock') }
let!(:original_next_lock) { File.read('spec/fixtures/Gemfile.next.lock') }
after(:each) do
File.write('spec/fixtures/Gemfile', original_gemfile, mode: 'w')
File.write('spec/fixtures/Gemfile.next', original_gemfile_next, mode: 'w')
File.write('spec/fixtures/Gemfile.shared', original_shared, mode: 'w')
File.write('spec/fixtures/Gemfile.lock', original_lock, mode: 'w')
File.write('spec/fixtures/Gemfile.next.lock', original_next_lock, mode: 'w')
end
it 'Both gemfiles include shared gems' do
subject
expect(File.read('spec/fixtures/Gemfile.lock')).to include 'catalogue (0.0.1)'
expect(File.read('spec/fixtures/Gemfile.next.lock')).to include 'catalogue (0.0.1)'
end
it 'Removes shared gem from both gemfiles' do
File.write('spec/fixtures/Gemfile.shared', original_shared.gsub("gem 'catalogue', '0.0.1'", ''), mode: 'w')
subject
expect(File.read('spec/fixtures/Gemfile.lock')).not_to include 'catalogue (0.0.1)'
expect(File.read('spec/fixtures/Gemfile.next.lock')).not_to include 'catalogue (0.0.1)'
end
it 'Append shared gems to both gemfiles' do
File.write('spec/fixtures/Gemfile.shared', original_shared + "\ngem 'Generator_pdf'\n", mode: 'w')
subject
expect(File.read('spec/fixtures/Gemfile.lock')).to include 'Generator_pdf'
expect(File.read('spec/fixtures/Gemfile.next.lock')).to include 'Generator_pdf'
end
it 'Can contain different versions of gems' do
File.write('spec/fixtures/Gemfile', original_gemfile + "\ngem 'Generator_pdf', '0.0.1'\n", mode: 'w')
File.write('spec/fixtures/Gemfile.next', original_gemfile_next + "\ngem 'Generator_pdf', '0.0.2'\n", mode: 'w')
subject
expect(File.read('spec/fixtures/Gemfile.lock')).to include 'Generator_pdf (0.0.1)'
expect(File.read('spec/fixtures/Gemfile.next.lock')).to include 'Generator_pdf (0.0.2)'
end
it 'Works if Gemfile.lock does not exist' do
File.delete('spec/fixtures/Gemfile.lock')
expect { subject }.not_to raise_error
end
it 'Works if Gemfile.next.lock does not exist' do
File.delete('spec/fixtures/Gemfile.next.lock')
expect { subject }.not_to raise_error
end
context 'User install only for Gemfile.next (with BUNDLE_GEMFILE=Gemfile.next env)' do
subject do
Bundler.with_original_env do
`cd spec/fixtures && BUNDLE_GEMFILE=Gemfile.next bundle install`
end
end
it 'Works' do
expect { subject }.not_to raise_error
end
end
end
|
require 'rails_helper'
RSpec.describe 'Current Workout', js: true do
let!(:gym) { create(:gym) }
let!(:workout) { create(:workout, gym: gym) }
let!(:exercise) { create(:exercise, workout: workout) }
let!(:user) { create(:user, gym: gym, current_workout: workout.id) }
before do
sign_in user
visit profile_index_path
end
context 'Current Workout Available' do
it 'completes workout' do
click_link "Start Workout"
expect(page).to have_content("Exercises Completed 0 of 1")
find(".exerciseModalLink").click
fill_in 'exercises_workout_detail__rep_1_weight', with: 30
find("#close-#{exercise.common_exercise.name.downcase.gsub(/[^0-9A-Za-z]/, '')}").click
click_button 'Next Exercise >>'
expect(page).to have_content('Awesome job today. You have completed all the exercises for todays workout.')
end
it 'continues to next exercise' do
exercise2 = create(:exercise, workout: workout)
click_link "Start Workout"
expect(page).to have_content("Exercises Completed 0 of 2")
first(".exerciseModalLink").click
fill_in 'exercises_workout_detail__rep_1_weight', with: 30
find("#close-#{exercise.common_exercise.name.downcase.gsub(/[^0-9A-Za-z]/, '')}").click
click_button 'Next Exercise >>'
expect(page).to have_content("Exercises Completed 1 of 2")
expect(page).to have_content(exercise2.common_exercise.name)
end
context 'previous data' do
let!(:user_previous_workout) { create(:user_previous_workout, workout: workout, user: user) }
let!(:workout_detail) { create(:workout_detail, exercise: exercise, user_previous_workout: user_previous_workout)}
it 'is a placeholder for reference' do
click_link "Start Workout"
find(".exerciseModalLink").click
expect(find('#exercises_workout_detail__rep_1_weight')['placeholder']).to eq(workout_detail.rep_1_weight.to_s)
expect(find('#exercises_workout_detail__rep_1_weight').value).to eq('')
end
it 'is a value for editing' do
click_link 'Workout History'
click_button workout.name
click_link 'Edit'
find(".exerciseModalLink").click
expect(find('#exercises_workout_detail__rep_1_weight')['placeholder']).to eq('')
expect(find('#exercises_workout_detail__rep_1_weight').value).to eq(workout_detail.rep_1_weight.to_s)
end
end
end
end
|
Pod::Spec.new do |s|
s.name = 'BaseMVVM'
s.version = '1.1.0'
s.summary = 'My base MVVM Pod'
s.description = <<-DESC
Used for projects that applies MVVM architect
DESC
s.homepage = 'https://github.com/sonbt91/BaseMVVM'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Son Bui' => 'sonbt91@gmail.com' }
s.source = { :git => 'https://github.com/sonbt91/BaseMVVM.git', :tag => s.version.to_s }
s.ios.deployment_target = '10.0'
s.source_files = '*'
end
Pod::Spec.new do |s|
# 1
s.platform = :ios
s.ios.deployment_target = '10.0'
s.name = "BaseMVVM"
s.summary = "BaseMVVM lets a user select an ice cream flavor."
s.requires_arc = true
# 2
s.version = "1.1.0"
# 3
s.license = { :type => "MIT", :file => "LICENSE" }
# 4 - Replace with your name and e-mail address
s.author = { "Son Bui" => "sonbt91@gmail.com" }
# 5 - Replace this URL with your own Github page's URL (from the address bar)
s.homepage = "https://github.com/sonbt91/BaseMVVM"
# 6 - Replace this URL with your own Git URL from "Quick Setup"
s.source = { :git => "https://github.com/sonbt91/BaseMVVM.git", :tag => "#{s.version}"}
# 7
s.framework = "UIKit"
s.dependency 'SnapKit'
s.dependency 'CocoaLumberjack/Swift'
s.dependency 'Kingfisher'
s.dependency 'KeychainAccess'
s.dependency 'IQKeyboardManagerSwift', '~> 6.0.4'
s.dependency 'Localize-Swift'
s.dependency 'DZNEmptyDataSet'
s.dependency 'RxSwift', '~> 4.0'
s.dependency 'RxCocoa', '~> 4.0'
s.dependency 'Moya/RxSwift', '~> 11.0'
s.dependency 'SwiftyJSON'
# 8
#s.source_files = "BaseMVVM/**/*.{swift}"
s.source_files = "BaseMVVM/*"
# 9
s.resources = "BaseMVVM/**/*.{png,jpeg,jpg,storyboard,xib,xcassets}"
# 10
s.swift_version = "4.2"
end
|
require_relative 'base'
require_relative '../utils/file_path'
require 'yaml'
class IndexCommand < BaseCommand
def initialize(options)
super
@template_path = @config["template_path"]
if @template_path.relative_path?
@template_path = File.join(@config["base_dir"], @template_path)
end
end
def handle
@project_config ={
"projects" => []
}
Dir.foreach(@template_path) do |project_directory|
unless project_directory.start_with?(".")
config_file = File.join(@template_path, project_directory, ".config.yml")
begin
project_config = nil
File.open(config_file, 'r') do |file|
project_config = YAML.load(file)
end
name = project_config["name"]
@project_config["projects"] << project_config["name"]
@project_config[name] = {
"path" => File.join(@template_path, project_directory),
"necessary_args" => if project_config.has_key?("necessary_args") then project_config["necessary_args"] else [] end,
}
rescue
end
end
end
File.open(@project_config_file, 'w') do |file|
file.puts @project_config.to_yaml
end
end
end
|
class Reply < ActiveRecord::Base
belongs_to :post
belongs_to :user
validates_presence_of :content
def author
user.email
end
def posted_on
created_at.to_formatted_s(:long)
end
end
|
require 'spec_helper'
describe PasswordResetService do
let(:user) { FactoryGirl.create :user }
let(:email_address) { user.primary_email_address }
let(:service) { PasswordResetService.new email_address }
# CLASS METHOD: active?
describe ".active?" do
subject { PasswordResetService.active? }
context "when password reset workflow is enabled within tenant configuration" do
# TODO
# it { should be_true }
it "should be true"
end
context "when password reset workflow is disabled within tenant configuration" do
# TODO
# it { should be_false }
it "should be false"
end
end
# METHOD: send_instructions
describe "#send_instructions" do
before { service.send_instructions }
it "generates & stores a new password reset token" do
expect(PasswordResetToken.last.email_address).to eq email_address
end
it "sets a password reset expiry timestamp" do
expect(PasswordResetToken.last.expires_at).to be > Time.now.utc
end
it "sends password reset instructions to the user's email address" do
expect(ActionMailer::Base.deliveries.last.to).to eq [email_address.value]
end
end
# METHOD: can_reset
describe "#can_reset?" do
subject { service.can_reset? }
context "when user is NIL" do
before { user = nil }
it { should be_false }
end
context "when instructions have NOT been sent" do
it { should be_false }
end
context "when instructions have been sent" do
before { service.send_instructions }
context "and have since expired" do
before { Timecop.freeze(service.token.expires_at + 1.minute) }
after { Timecop.return }
it { should be_false }
end
context "and have NOT expired" do
before { Timecop.freeze(service.token.expires_at - 1.minute) }
after { Timecop.return }
it { should be_true }
end
end
end
# METHOD: reset
describe "#reset" do
before { service.send_instructions }
let(:password) { User.random_password.downcase }
let(:password_confirmation) { password }
context "with a valid / matching password & password confirmation" do
let!(:result) { service.reset(password, password_confirmation) }
it "returns true" do
expect(result).to eq true
end
it "updates the user's password" do
found_user = User.find(user.id)
expect(found_user.authenticate(password)).to eq user
end
it "deletes the password reset token" do
found_token = PasswordResetToken.where(id: service.token.id).first
expect(found_token).to be_nil
end
it "sends password reset success message to the user's email address" do
expect(ActionMailer::Base.deliveries.last.to).to eq [email_address.value]
end
end
context "with a blank password" do
let(:password) { " " }
let!(:result) { service.reset(password, password_confirmation) }
it "returns true" do
expect(result).to eq true
end
it "doesn't update the user's password" do
found_user = User.find(user.id)
expect(found_user.authenticate(password)).to be_false
end
it "deletes the password reset token" do
found_token = PasswordResetToken.where(id: service.token.id).first
expect(found_token).to be_nil
end
end
context "with a non-matching password & password confirmation" do
let(:password_confirmation) { password.upcase }
let!(:result) { service.reset(password, password_confirmation) }
it "returns false" do
expect(result).to eq false
end
it "doesn't update the user's password" do
found_user = User.find(user.id)
expect(found_user.authenticate(password)).to be_false
end
it "doesn't delete the password reset token" do
found_token = PasswordResetToken.where(id: service.token.id).first
expect(found_token).not_to be_nil
end
end
end
end |
@team_seeds = {}
@message = ""
def display_menu clear_menu
if clear_menu == "yes"
system "clear"
end
puts "**********************************************************"
puts "**********************************************************"
puts "****Welcome to my tournament generator. Enter a selection:"
puts "**********************************************************"
puts "**** 1. Enter teams"
puts "**** 2. List teams"
puts "**** 3. List matchups"
puts "**** 4. Clear bracket"
puts "**** 0. Exit program"
status_message(@message)
@message = ""
option = gets.chomp.to_i
case option
when 1 then add_team
when 2 then list_teams
when 3 then matchups
when 4 then clear_bracket
when 0 then exit_application
else
@message = "Invalid Selection: please choose from menu"
display_menu("yes")
end
end
def status_message message
puts "**** #{@message}"
end
def ret_menu
puts "return to menu? (y/n):"
ret = gets.chomp.downcase
if ret == "y"
display_menu("yes")
elsif ret == "n"
exit_application
else
ret_menu
end
end
def add_team
system "clear"
puts "Enter school name (eg. UGA):"
school = gets.chomp
puts "Enter ranking:"
seed = gets.chomp.to_i
@team_seeds[seed] = school
@team_seeds = @team_seeds.sort_by{ |k, v| k }.to_h
@message = "Team Added"
ret_menu
end
def list_teams
system "clear"
puts "The #{@team_seeds.length} teams are seeded as follows:"
@team_seeds.each do |seed, school|
puts "#{seed}. #{school}"
end
ret_menu
end
def matchups
system "clear"
bottom_seed = @team_seeds.length
if @team_seeds.length % 2 == 0
top_seed = 1
middle = @team_seeds.length/2
second_tier = middle + 1
else
bye = 1
top_seed = 2
middle = (@team_seeds.length-1)/2
second_tier = middle + 2
end
puts "Matchups are as follows:"
while top_seed < second_tier do
if bye == 1 && top_seed == 2
puts "(#{bye})#{@team_seeds[bye]} bye week first round"
end
puts "(#{top_seed})#{@team_seeds[top_seed]} against (#{bottom_seed})#{@team_seeds[bottom_seed]}"
top_seed += 1
bottom_seed -= 1
end
ret_menu
end
def clear_bracket
@team_seeds = {}
ret_menu
end
def exit_application
puts"**************************************"
puts"************ Goodbye *****************"
puts"**************************************"
end
display_menu("yes")
|
class SalesController < ApplicationController
def show
@sale = Sale.find(params[:id])
@picture = @sale.pictures.first
@category = @sale.category.name
@url = @category + '/' + @picture.img
end
end
|
# Fibonnaci Sequence
# Gabrielle Gustilo & Becca Nelson
# Pseudocode:
#INPUT: An integer
#OUTPUT: True or false
#STEPS:
=begin
DEFINE an array with two values - 0, 1
WHILE the last value of the array is =< the input
variable equals the second to last array value plus the last array value
add the variable to the end of the array
END
IF last value of the array equals the input
return true
ELSE
return false
=end
# Initial Solution
def fibonacci_test(number)
numbers = [0, 1]
while numbers[-1] < number
next_value = numbers[-2] + numbers[-1]
numbers << next_value
end
if numbers[-1] == number
return true
else
return false
end
end
# Refactoring
def fibonacci_test(number)
numbers = [0, 1]
while numbers[-1] < number
numbers << numbers[-2] + numbers[-1]
end
numbers[-1] == number
end
# Test
p fibonacci_test(6765)
p fibonacci_test(25)
# Reflection
=begin
What concepts did you review in this challenge?
We reviewed iterating through arrays and flow control.
What is still confusing to you about Ruby?
After solving this one, we researched alternate solutions to see if there is a more elegant way to do
this. We found one-line solutions that are absurdly long, and lots of other possible solutions. I
know how to come up with simple solutions, but it's someies confusing to try to undestand solutions with more complex methods.
What are you going to study to get more prepared for Phase 1?
I would like to review ruby enumerable methods.
=end |
require "cubing_average"
require "comparable_solve"
describe CubingAverage do
it "saves singles" do
singles = [stub, stub]
CubingAverage.new(singles).singles.should == singles
end
it "accepts time as second attribute for .new, and caches it" do
CubingAverage.new([stub], 40).time.should == 40
end
it "defaults to an empty single array" do
CubingAverage.new.singles.should == []
end
it "allows more averages to be pushed in it" do
old_single = stub
new_single = stub
average = CubingAverage.new([old_single])
average << new_single
average.singles.should == [old_single, new_single]
end
it "doesn't mess with the original singles array" do
single = stub
singles = [single]
average = CubingAverage.new(singles)
singles << stub
average.singles.should == [single]
end
describe "#time" do
let(:single_5) { stub :time => 5, :dnf? => false }
let(:single_6) { stub :time => 6, :dnf? => false }
let(:single_7) { stub :time => 7, :dnf? => false }
let(:single_10) { stub :time => 10, :dnf? => false }
let(:single_dnf) { stub :time => 20, :dnf? => true }
before do
single_5.extend(ComparableSolve)
single_5.extend(ComparableSolve)
single_6.extend(ComparableSolve)
single_7.extend(ComparableSolve)
single_10.extend(ComparableSolve)
single_dnf.extend(ComparableSolve) # TODO omg, remove this shit by decoupling Single from ActiveRecord :)
end
it "actually changes if other times are pushed in" do
average = CubingAverage.new([single_5] * 5)
lambda {
average << single_10
average << single_10
}.should change(average, :time)
end
it "returns nil for an empty singles array" do
average = CubingAverage.new([])
average.time.should == nil
end
context "one single" do
it "returns the time" do
CubingAverage.new([single_5]).time.should == 5
end
it "returns nil if the single is DNF" do
CubingAverage.new([single_dnf]).time.should == nil
end
end
context "five singles" do
it "returns 10 for [10, 6, 7, 5, 5]" do
singles = [single_10, single_6, single_7, single_5, single_5]
CubingAverage.new(singles).time.should == 6
end
it "returns 5 for [dnf, 7, 6, 5, 5]" do
singles = [single_dnf, single_7, single_6, single_5, single_5]
CubingAverage.new(singles).time.should == 6
end
it "returns nil for [dnf, 5, 5, 5, dnf]" do
singles = [single_dnf] + [single_5] * 3 + [single_dnf]
CubingAverage.new(singles).time.should == nil
end
it "returns 6.67 for [7, 10, 6, 7, 5]" do
singles = [single_7, single_10, single_6, single_7, single_5]
("%.2f" % CubingAverage.new(singles).time).should == "6.67"
end
end
end
describe "#dnf?" do
it "returns true if time is nil" do
average = CubingAverage.new
average.stub(:time => nil)
average.should be_dnf
end
end
describe "best, worst" do
let(:single_1) { stub :dnf? => false, :time => 40 }
let(:single_2) { stub :dnf? => false, :time => 13 }
let(:single_3) { stub :dnf? => false, :time => 23 }
let(:single_dnf) { stub :dnf? => true, :time => 9 }
before do
single_1.extend(ComparableSolve)
single_2.extend(ComparableSolve)
single_3.extend(ComparableSolve)
single_dnf.extend(ComparableSolve)
end
describe "#best" do
it "returns the single with fastest time if everything's solved" do
CubingAverage.new([single_1, single_2, single_3]).best.should == single_2
end
it "takes notice of dnf singles and ignores them" do
CubingAverage.new([single_1, single_dnf]).best.should == single_1
end
it "chooses any single if all are dnf" do
CubingAverage.new([single_dnf, single_dnf]).best.should == single_dnf
end
end
describe "#worst" do
it "returns the single with worst time if everything's solved" do
CubingAverage.new([single_2, single_1, single_3]).worst.should == single_1
end
it "instantly chooses a dnf solve if there is any" do
CubingAverage.new([single_1, single_dnf]).worst.should == single_dnf
end
end
end
describe "comparison" do
def average(time, dnf = false)
CubingAverage.new.tap do |a|
a.stub(:time => time, :dnf? => dnf)
end
end
describe "#==" do
it "is equal if time and dnf are equal" do
average = average 31
other = average 31
(average == other).should == true
end
end
describe "both dnfs" do
it "neither a < b nor a > b is true" do
(average(12, true) < average(13, true)).should == false
(average(12, true) > average(13, true)).should == false
end
end
describe "#<" do
context "is dnf, other is not a dnf" do
it "is less than even if the times are greater" do
average = average 100
other = average 40, true
(average < other).should ==true
end
end
context "both are no dnfs" do
it "is less than if the time is smaller" do
average = average 100
other = average 110
(average < other).should == true
end
it "is not less than if the time is greater" do
average = average 120
other = average 110
(average < other).should == false
end
end
end
end
end
|
require File.dirname(__FILE__) + '/spec_helper'
describe PrependFile do
context "Dest File is a location" do
before do
@file_name = "sample_files/sample.txt"
@original_contents = File.read(@file_name)
end
after do
File.open(@file_name, 'w') {|f| f.write @original_contents}
end
it "should prepend text to a file given a file name" do
PrependFile.prepend(@file_name, "This is text")
File.read(@file_name).should eq("This is text\n#{@original_contents}")
end
it "should prepend a file from a given file location to a file given a file name" do
PrependFile.prepend(@file_name, "sample_files/prepend_data" )
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given file object to a file given a file name" do
PrependFile.prepend(@file_name, File.new("sample_files/prepend_data"))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given IO object to a file given a file name" do
PrependFile.prepend(@file_name, File.open("sample_files/prepend_data", 'r'))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
end
context "Dest File is a File Object" do
before do
@file_name = "sample_files/sample.txt"
@file = File.new @file_name
@original_contents = @file.read
@file.rewind
end
after do
File.open(@file_name, 'w') {|f| f.write @original_contents}
end
it "should reach the end of the given source file" do
PrependFile.prepend(@file, "This is text")
@file.eof?.should eq(true)
end
it "should prepend text to a file object" do
PrependFile.prepend(@file, "This is text")
File.read(@file_name).should eq("This is text\n#{@original_contents}")
end
it "should prepend a file from a given file location to a file given a file name" do
PrependFile.prepend(@file, "sample_files/prepend_data")
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given file object to a file given a file name" do
PrependFile.prepend(@file, File.new("sample_files/prepend_data"))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given IO object to a file given a file name" do
PrependFile.prepend(@file, File.open("sample_files/prepend_data", 'r'))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
end
context "Dest File is a IO Object" do
before do
@file_name = "sample_files/sample.txt"
@file = File.open @file_name
@original_contents = @file.read
@file.rewind
end
after do
File.open(@file_name, 'w') {|f| f.write @original_contents}
end
it "should reach the end of the given source file" do
PrependFile.prepend(@file, "This is text")
@file.eof?.should eq(true)
end
it "should prepend text to a file object" do
PrependFile.prepend(@file, "This is text")
File.read(@file_name).should eq("This is text\n#{@original_contents}")
end
it "should prepend a file from a given file location to a file given a file name" do
PrependFile.prepend(@file, "sample_files/prepend_data")
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given file object to a file given a file name" do
PrependFile.prepend(@file, File.new("sample_files/prepend_data"))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
it "should prepend a file from a given IO object to a file given a file name" do
PrependFile.prepend(@file, File.open("sample_files/prepend_data", 'r'))
File.read(@file_name).should eq("#{File.read('sample_files/prepend_data')}#{@original_contents}")
end
end
end
|
require_relative 'spec_helper'
require 'pry'
describe "Reservation" do
describe "Initializes an instance of reservation and its instance methods" do
before do
@hotel_ada = Hotel::ReservationManager.new(20)
@new_reservation = @hotel_ada.reserve_room("2018-08-23", "2018-08-25")
@test_reservation = @hotel_ada.reserve_room("2018-09-18", "2018-09-20")
end
it "creates an instance of Reservation" do
expect(@test_reservation).must_be_instance_of Hotel::Reservation
expect(@test_reservation.rooms).must_be_kind_of Array
expect(@test_reservation.check_in).must_be_instance_of Date
expect(@test_reservation.check_in.day).must_equal 18
expect(@test_reservation.date_range.count).must_equal 2
end
it "checks to see if there are any reservations for a given date" do
expect(@test_reservation.find_reservation("2018-09-19")).must_equal true
end
it "calulates total cost for a reservation" do
#binding.pry
expect(@test_reservation.total_cost).must_equal 400
end
end
end
|
require 'nokogiri'
require 'terms'
class CourseWorkCourses
class Course
attr_reader :title, :term, :cid, :cids, :sid, :instructors
def initialize(title:, term:, cid:, cids:, sid:, instructors:)
@title = title
@term = term
@cid = cid
@cids = cids
@sid = sid
@instructors = instructors
end
def key
"#{cid}-#{instructor_sunets.join('-')}"
end
def comp_key
"#{cids.sort.join(',')},#{instructor_sunets.join(',')}"
end
def instructor_sunets
instructors.pluck(:sunet).compact.sort
end
def instructor_names
instructors.pluck(:name).compact.sort
end
def cross_listings
cids.reject { |c| c == cid }.join(", ")
end
end
def initialize(json_file = nil)
if json_file
@json_files = [JSON.parse(json_file)]
else
@json_files = load_from_coursework
end
end
def json_files
@json_files ||= self.json_files
end
def find_by_sunet(sunet)
self.all_courses.select do |course|
course.instructor_sunets.include?(sunet)
end
end
def find_by_class_id(class_id)
self.all_courses.select do |course|
course.cid == class_id
end
end
def find_by_compound_key(key)
self.course_map[key] || []
end
def find_by_class_id_and_section(class_id, section)
self.all_courses.select do |course|
course.cid == class_id && course.sid == section
end
end
def find_by_class_id_and_sunet(class_id, sunet)
self.all_courses.select do |course|
course.cid == class_id && course.instructor_sunets.include?(sunet)
end
end
def find_by_class_id_and_section_and_sunet(class_id, section, sunet)
self.all_courses.select do |course|
course.cid == class_id && course.sid == section && course.instructor_sunets.include?(sunet)
end
end
# We have tests that are highly sensitive to the order of the courses.
# We use the dedup_courses method to preserve the original order while removing duplicates
def all_courses
@all_courses ||= dedup_courses(process_all_courses(self.json_files).to_a)
end
# Given two sections with the same CIDs and instructor sunet ids, preserve only the lower numbered section
# Keep the original order of courses
def dedup_courses(courses)
course_hash = {}
key_order = []
courses.each do |course|
ckey = course.key
sid = course.sid.to_i
key_order << ckey unless course_hash.key?(ckey)
# If we have not encountered this course and instructor set before
# or if the section id that is saved is greater than the one being processed
# save this section as the one to save for this course and instructor set
if !course_hash.key?(ckey) ||
(course_hash.key?(ckey) && course_hash[ckey].sid.to_i > sid)
course_hash[ckey] = course
end
end
key_order.map { |k| course_hash[k] }
end
# Efficient lookup of course data by compound key (which is used in a few places around the app)
def course_map
@course_map ||= all_courses.each_with_object({}) do |course, map|
if map[course.comp_key]
map[course.comp_key] << course
else
map[course.comp_key] = [course]
end
end
end
private
# Adding JSON processing
# Will replace load_xml_from_coursework. Now loads JSON files generated from MAIS course term and course API requests
def load_from_coursework
if Rails.env.test?
return [JSON.parse(File.read("#{Rails.root}/spec/fixtures/course_work.json"))]
else
current = Terms.process_term_for_cw(Terms.current_term)
next_term = Terms.process_term_for_cw(Terms.future_terms.first)
json_files = []
["#{Rails.root}/lib/course_work_content/course_#{current}.json", "#{Rails.root}/lib/course_work_content/course_#{next_term}.json"].each do |url|
json_files << JSON.parse(File.read(url)) if File.exist?(url)
end
return json_files
end
end
# Given JSON representing the information required by a Course object,
# initialize Course objects
def process_all_courses(json_files)
return to_enum(:process_all_courses, json_files) unless block_given?
# This should be an array of json files being read in
# For each JSON file, representing a specific term, read in the information
# and create the objects required by the model
json_files.each do |json_file|
json_file.each do |course|
# Deep transform will also convert the nested instructor hash keys to symbols
# Symbolized keys are required for the hash to map to the keyword arguments for Course
course.deep_transform_keys!(&:to_sym)
yield Course.new(**course) if course[:instructors].present?
end
end
end
end
|
shared_examples 'request method' do
let(:ssoid) { 'vnboeirubvyebvuekrybobvuiberlvbre' }
let(:connection) { BetfairApiNgRails::Api::Connection.new }
let(:http_response) { double(:http_response, code: '200', body: result_hash) }
let(:result) { BetfairApiNgRails::Api::Http::Responser.new(http_response) }
let(:filter) { BetfairApiNgRails::MarketFilter.new }
let(:api_http_requester) { double(:api_http_requester, do_request: result, set_api_req_body: true) }
before(:each) do
expect(BetfairApiNgRails::Api::SessionManager).to receive(:new_ssoid).and_return ssoid
expect(BetfairApiNgRails::Api::Http::Factory).to receive(:provider_requester).with(ssoid).and_return api_http_requester
BetfairApiNgRails.connection = connection
end
subject { TestModule.send(method_name, parameters) }
end |
# Read about factories at https://github.com/thoughtbot/factory_girl
require 'random_helper'
FactoryGirl.define do
factory :shop do
user { create(:shop_owner) }
location
published false
logo "MyString"
address1 { Faker::Address.street_address }
address2 { RandomHelper.bi_rand Faker::Address.secondary_address }
directions { Faker::Lorem.paragraph(sentence_count = 5) }
website1 "MyString"
website2 "MyString"
website3 "MyString"
website4 "MyString"
website5 "MyString"
commission_pct 10
factory :complete_shop do
logo { RandomHelper.rand_shop_logo }
banner { RandomHelper.rand_shop_banner }
published true
location { create(:location) }
after(:create) do |c, evaluator|
language = Language.default
language ||= create(:language)
c.descriptions << create(:description,
describable: c,
language: language
)
RandomHelper.r1(4).times { create(:tagging, taggable: c, tag: Tag::HotelTag.all.sample) }
RandomHelper.r1(10).times { create(:photo, photoable: c) }
end
factory :complete_shop_w_items do
after(:create) do |c, evaluator|
RandomHelper.r1(5).times { create(:complete_item, shop: c) }
end
end
end
end
end
|
require File.dirname(__FILE__) + "/test_helper"
require 'fakeweb'
require 'active_resource/find_as_hashes'
module Resource
class User < ActiveResource::Base
self.site = 'http://api.test.com/'
self.format = :json
end
end
class ActiveResourceTest < ActiveSupport::TestCase
def setup
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:get, "http://api.test.com/users.json", :body => User.all.to_json, :status => ["200", "OK"])
end
def teardown
FakeWeb.allow_net_connect = true
FakeWeb.clean_registry
end
context "#all_as_hashes" do
setup do
@records = Resource::User.all
@hashes = Resource::User.all_as_hashes
end
should "return an array of attribute hashes" do
assert_equal Array, @hashes.class
assert @hashes.all? { |hash| hash.class == Hash }
assert @records.all? { |record| record.class != Hash }
end
end
context "#first_as_hash" do
setup do
@record = Resource::User.first
@hash = Resource::User.first_as_hash
end
should "return a single hash" do
assert_equal Hash, @hash.class
assert_equal Resource::User, @record.class
if ActiveResource::VERSION::MAJOR >= 4
assert_equal @hash["name"], User.first.name
else
assert_equal @hash["user"]["name"], User.first.name
end
end
end
context "#last_as_hash" do
setup do
@record = Resource::User.last
@hash = Resource::User.last_as_hash
end
should "return a single hash" do
assert_equal Hash, @hash.class
assert_equal Resource::User, @record.class
if ActiveResource::VERSION::MAJOR >= 4
assert_equal @hash["name"], User.last.name
else
assert_equal @hash["user"]["name"], User.last.name
end
end
end
end |
module Concerns::Edu::SchoolAdmin
extend ActiveSupport::Concern
included do
has_many :ugroups, class_name: "Edu::Ugroup", foreign_key: :school_id
has_many :enrollments, class_name: "Acn::Enrollment", through: :ugroups
has_many :users, through: :enrollments
belongs_to :level, class_name: "Edu::Level"
counter_culture :level, column_name: "schools_count"
belongs_to :loc, class_name: "Edu::Loc"
counter_culture :loc, column_name: "schools_count"
belongs_to :holder, class_name: "Edu::Holder"
counter_culture :holder, column_name: "schools_count"
end
def alumnus
self.ugroups.where(name: "alumnus").first
end
def add_ugroup name, user
sg = self.ugroups.find_or_create_by(name: name)
sg.enroll user
sg
end
def add_alumnus user
self.add_ugroup "alumnus", user
end
def add_teacher user
sg = self.add_ugroup "teacher", user
user.set_current_group sg
end
def self.bebras_team
find_by(moeid: "0004")
end
end
|
=begin
#In-class printing exercises
puts "Hey, I did a thing!"
print('print: hello world ')
puts('puts: hello world ')
p('p: hello world ')
=end
# 1. Replace every even number with "Mined"
def exercise1(max)
even = false # Whichever number we pick we are starting at one. This will need an adjustment if we are going to start at different numbers
counter = 1 # Start at 1 (not zero)
until counter == (max + 1) # Until we arrive at the specified number (plus 1).
if even == false # "If it's not an even number"
puts(counter) # "Puts" each number. puts not print because we want one number per line.
even = true # Since this increment was not even, change it to change the status to even for the next number
else
puts('even') # Just print the word even.
even = false # Since this increment was not even, change it to change the status to even for the next number
end
counter += 1 # Increment the counter
end # End until loop
end # End function definition
# 2. Replace the first 3 with Mined
def exercise2(max)
1.upto(max).each do |n| # Use builtin integar methods "upto" and then iterate with "each".
line = '' # Declare an empty variable.
line << 'Mined' if n == 3 # If the remainder of n / 3 = 0 (aka its a multiple of 3), append "Mined" to the empty string.
line = n if line.empty? # If there was not text inside the "line" variable, line = the value of n.
p line # Print the line variable
end # Done and...
end
# 3. Replace every multiple of three
def exercise3(max)
1.upto(max).each do |n| # Use builtin integar methods "upto" and then iterate with "each".
line = '' # Declare an empty variable.
line << 'Mined' if n % 3 == 0 # If the remainder of n / 3 = 0 (aka its a multiple of 3), append "Mined" to the empty string.
line = n if line.empty? # If there was not text inside the "line" variable, line = the value of n.
p line # Print the line variable
end # Done and...
end # Done
# 4. Replace every third number with "mined" and every 5th number with minds.
def exercise4(max)
1.upto(max).each do |n| # Use builtin integar methods "upto" and then iterate with "each".
line = '' # Declare an empty variable.
line << 'Mined' if n % 3 == 0 # If the remainder of n / 3 = 0 (aka its a multiple of 3), append "Mined" to the empty string.
line << 'Minds' if n % 5 == 0 # If the remainder of n / 5 = 0 (aka its a multiple of 5), append "Minds" to the string ( could already have "mined" in it).
line = n if line.empty? # If there was not text inside the "line" variable, line = the value of n.
p line # Print the line variable
end # Done and...
end # Done
#-----------------------------------------------------------------------------------------------------------------------#
# Uncomment wichever one you want to see run
#exercise1(100) # Every even number
#exercise2(100) # The first 3
#exercise3(100) # Every third number = "mined"
#exercise4(100) # Every third number = "mined" and every fifth number = "minds"
|
# frozen_string_literal: true
require "kafka/digest"
module Kafka
# Assigns partitions to messages.
class Partitioner
# @param hash_function [Symbol, nil] the algorithm used to compute a messages
# destination partition. Default is :crc32
def initialize(hash_function: nil)
@digest = Digest.find_digest(hash_function || :crc32)
end
# Assigns a partition number based on a partition key. If no explicit
# partition key is provided, the message key will be used instead.
#
# If the key is nil, then a random partition is selected. Otherwise, a digest
# of the key is used to deterministically find a partition. As long as the
# number of partitions doesn't change, the same key will always be assigned
# to the same partition.
#
# @param partition_count [Integer] the number of partitions in the topic.
# @param message [Kafka::PendingMessage] the message that should be assigned
# a partition.
# @return [Integer] the partition number.
def call(partition_count, message)
raise ArgumentError if partition_count == 0
# If no explicit partition key is specified we use the message key instead.
key = message.partition_key || message.key
if key.nil?
rand(partition_count)
else
@digest.hash(key) % partition_count
end
end
end
end
|
require 'chemistry/element'
Chemistry::Element.define "Sodium" do
symbol "Na"
atomic_number 11
atomic_weight 22.98976928
melting_point '371K'
end
|
class CreateRepeats < ActiveRecord::Migration
def change
create_table :repeats do |t|
t.string :repeat_type
t.integer :repeat_daily_flag
t.integer :repeat_weekly_flag
t.integer :repeat_monthly_flag
t.string :week_day
t.string :monthly_day
t.string :create_user
t.datetime :create_date
t.string :update_user
t.datetime :update_date
t.timestamps null: false
end
end
end
|
class Rating < ActiveRecord::Base
# mount_uploaders :image, RatingImageUploader
belongs_to :user
belongs_to :product
validates :header, presence: true
validates :review, presence: true
validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 5 }
end
|
class Experiment < ActiveRecord::Base
attr_accessible :description, :name, :sample_ids
has_and_belongs_to_many :samples
accepts_nested_attributes_for :samples
validates_presence_of :name
end
|
require 'spec_helper'
describe Chapter do
before { @chapter = Chapter.new(title: "Example Chapter", number: 1, scene: "Acte 2", anecdote: "La dispute") }
subject { @chapter }
it { should respond_to(:title) }
it { should respond_to(:number) }
it { should respond_to(:scene) }
it { should respond_to(:anecdote) }
it { should be_valid }
describe "when title is not present" do
before { @chapter.title = " " }
it { should_not be_valid }
end
describe "when number is not present" do
before { @chapter.number = nil }
it { should_not be_valid }
end
describe "when scene is not present" do
before { @chapter.scene = nil }
it { should_not be_valid }
end
describe "when anecdote is not present" do
before { @chapter.anecdote = nil }
it { should_not be_valid }
end
end
|
class ItemsController < ApplicationController
def index
@items = Item.order('slot').page(params[:page]).per(18)
end
def show
@item = Item.find(params[:id])
end
def category_index
@items = Category.find(params[:id]).items.page(params[:page])
render action: :index
end
def new_items_index
@items = Item.where('created_at > ?', Date.yesterday).page(params[:page])
render action: :index
end
def updated_items_index
@items = Item.where('updated_at > ?', Date.yesterday).page(params[:page])
render action: :index
end
def add_to_cart
# add current item to session
session[:cart] << params[:id]
redirect_to action: :view_cart
end
def view_cart
@user = User.new
@items = []
@price = 0
session[:cart].each do |item|
@price += (Item.find(item).price.to_f / 100)
@items << Item.find(item)
end
session[:price] = @price
@items = Kaminari.paginate_array(@items).page(params[:page])
# show all items in session
end
def search_results # displays search
keywords = params[:user_keywords]
category = params[:my_options]
if category == 'All'
@items = Item.where('name LIKE ?', "%#{keywords}%").page(params[:page])
else
@items = Item.where('name LIKE ? AND slot LIKE ?',
"%#{keywords}%", "%#{category}%").page(params[:page])
end
render action: :index
end
def create_order
@user = User.new(user_params)
if (!@user.save)
redirect_to :view_cart, notice: 'You must insert additional details.'
else
@order = Order.new(user_id: @user.id, price: session[:price])
@order.save
session[:cart].each do |item|
@line_item = LineItem.new(order_id: @order.id, item_id: item)
@line_item.save
end
session.destroy
redirect_to :index, notice: 'Order Received.'
end
end
def page
@page = Page.where('name LIKE ?', params[:name]).first
render 'shared/page'
end
private
def user_params
params.require(:user).permit(:name,
:address,
:city,
:country,
:postal_code)
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ultron/version'
Gem::Specification.new do |spec|
spec.name = 'ultron'
spec.version = Ultron::VERSION
spec.authors = ["Sérgio Rodrigues"]
spec.email = ['sergioaugrod@gmail.com']
spec.summary = %q{Communicates with arduino and publishes to a MQTT broker.}
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.11'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'pry', '~> 0.10.3'
spec.add_development_dependency 'rspec', '~> 3.4'
spec.add_development_dependency 'rspec-its', '~> 1.2'
spec.add_development_dependency 'concurrent-ruby', '~> 1.0.1'
spec.add_development_dependency 'rubyserial', '~> 0.2.4'
spec.add_development_dependency 'mqtt', '~> 0.3.1'
spec.add_development_dependency 'codeclimate-test-reporter', '~> 0.5'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.