text stringlengths 10 2.61M |
|---|
### loop_example.rb code Start #####
#loop do
# puts "This will keep printing until you hit Ctrl + c"
#end
### loop_example.rb code End #####
=begin
x = gets.chomp.to_i
until x < 0
puts x
x -= 1
end
puts "Done!"
=end
#loop do
# puts "Do you want to do that again?"
# answer = gets.chomp
# if answer != 'Y'
# break
# end
#end
#x = gets.chomp.to_i
#for i in 1..x do
# puts i
#end
#puts "Done!"
### fibonacci.rb Start ####
#def fibonacci(num)
# if num < 2
# num
# else
# fibonacci(num - 1) + fibonacci(num - 2)
# end
#end
#puts fibonacci(6)
### fibonacci.rb End ####
### Ex 1 Start ####
#The each method will return the x array.
### Ex 1 End ####
### Ex 2 Start ####
puts "Type any action.....type 'stop' to quit :-)"
x = gets.chomp.to_s
x.upcase!
while x
if x == "STOP"
break
else
puts "Your requested action is #{x}"
puts "Type any action.....type 'stop' to quit :-)"
x = gets.chomp.to_s
x.upcase!
end
end
### Ex 2 End ####
### Ex 3 Start ####
arr = [1,2,3,4,5,6,7,8,9,10]
arr.each_with_index{|item, index| puts "This is the item #{item} and it's index is #{index}"}
### Ex 3 End ####
### Ex 4 Start ####
def count_down(x)
if x >= 0
puts x
count_down(x-1)
end
end
puts count_down(10)
### Ex 4 End ####
|
NycCollegeLine::Application.routes.draw do
devise_for :users,
controllers: {
confirmations: :confirmations,
registrations: :registrations,
passwords: :passwords,
},
path_names: {
password: 'forgot',
registration: 'register',
sign_up: 'signup'
},
skip: [:sessions]
match '/ask-an-adviser' => 'guest_questions#redirect'
match '/blog-user-registration' => "blog_posts#blog_user"
match '/global-search' => 'search#global_search' , as: 'global_search'
get 'feed' => 'blog_posts#feed'
as :user do
get 'login' => 'sessions#new', as: :new_user_session
post 'login' => 'sessions#create', as: :user_session
delete 'signout' => 'sessions#destroy' #API user logout
delete 'logout' => 'devise/sessions#destroy', as: :destroy_user_session
match 'registrations/success/:step' => 'registrations#success',
as: :registration_success
end
namespace :api, constraints: { format: 'json' } do
namespace :v1 do
match 'faq' => 'masters#faq',via: [:get]
match 'guest-question' => 'masters#ask_an_adviser_guest',via: [:post]
match 'user-question' => 'masters#ask_an_adviser_user',via: [:post]
match 'facebook-login' => 'masters#facebook_login',via: [:post]
match 'about-contact' => 'masters#about_us',via: [:get]
match 'terms-of-use' => 'masters#terms_policy',via: [:get]
match 'apply-data' => 'masters#apply_data',via: [:get]
match 'scholarships' => 'masters#scholarships',via: [:get]
match 'scholarship-form' => 'masters#scholarship_form',via: [:post]
match 'events' => 'masters#events',via: [:get]
match 'event-show' => 'masters#event_show',via: [:post]
match 'event-comment' => 'masters#event_comment',via: [:post]
match 'reply_to_question' => "masters#reply_to_question", via: [:get, :post]
match 'get_question' => "masters#get_question", via: [:get, :post]
match 'get-data-sync' => 'masters#offline_data',via: [:get, :post]
match "user-profile" => "masters#user_profile", via: [:post]
match 'user-scholarships' => "masters#user_scholarships", via: [:post]
match 'edit-profile' => "masters#edit_profile", via: [:get, :post]
match 'upload-photo' => "masters#upload_photo", via: [:post]
match 'user-setting' => "masters#user_setting", via: [:get, :post]
match 'bookmark-event' => "masters#bookmark_event", via: [:get, :post, :delete]
match 'bookmark-faq' => "masters#bookmark_faq", via: [:get, :post, :delete]
match 'user-asked-questions' => "masters#user_asked_questions", via: [:post]
match 'delete-user-account' => "masters#delete_user_account", via: [:post]
end
end
#
# Public folders
#
resources :survey_answers
resources :folders, only: [:index]
match '/folders/:id/:slug' => 'folders#show', :as => :folder
namespace 'admissions', as: 'admin' do
resources :blog_posts do
get 'confirm_destroy', on: :member
end
resources :campaign_ppcs do
get 'confirm_destroy', on: :member
end
resources :tags
resources :assets, except: [:show,] do
get 'browse', on: :collection
get 'confirm_destroy', on: :member
post 'details', on: :member
get 'search', on: :collection
end
resources :audiences, :events, :faqs, :forums, :glossary_terms,
:organizations, :phases, :promo_instances, :scholarships,
:scholarship_submissions,
:system_avatars, except: [:show,] do
get 'confirm_destroy', on: :member
end
resources :comments, except: [:show, :new, :create,] do
get 'confirm_destroy', on: :member
end
resources :contact_submissions, only: [:index, :show, :destroy]
resources :contests do
get 'confirm_destroy', on: :member
end
resources :folders, only: [:index, :show, :update]
resources :folder_recommendations, only: [:index, :show, :destroy], path: 'recommendations'
resources :galleries, except: [:show,] do
get 'browse', on: :collection
get 'confirm_destroy', on: :member
end
resources :glossary_imports, only: [:create, :new,]
resources :pages, except: [:show,] do
get 'confirm_destroy', on: :member
post 'update_order', on: :collection
end
resources :questions, except: [:show, :new, :create] do
get 'confirm_destroy', on: :member
end
resources :guest_questions, except: [:show, :new, :create] do
get 'confirm_destroy', on: :member
end
resources :referral_codes, only: [:create]
resources :resource_imports, only: [:create, :new,]
resources :resources, except: [:show,] do
get 'confirm_destroy', on: :member
get 'search', on: :collection
end
resources :resource_suggestions, except: [:show, :new, :create,] do
get 'confirm_destroy', on: :member
end
resources :site_settings, only: [:edit, :update,]
resources :blog_users do
get 'confirm_destroy', on: :member
get 'export_csv', on: :collection
end
resources :users, except: [:show,] do
get 'confirm_destroy', on: :member
get 'search', on: :collection
get 'export_partial', on: :collection
get "blog_users", on: :collection
end
resources :survey_templates do
get 'confirm_destroy', on: :member
match 'assign_ques', on: :member
end
resources :survey_questions do
get 'confirm_destroy', on: :member
end
resources :survey_reports, path: "survey-template-report" do
get 'confirm_destroy', on: :member
get 'report', on: :member, path: "template"
get 'show', on: :member, path: "template-response"
delete :delete, on: :member
end
root to: 'admissions#index'
end
namespace 'guest-profile', as: :guest_profile do
resources :guest_questions, path: 'guest-ask-an-adviser', only: [:new, :create, :show] do
post 'build', on: :collection
get 'success', on: :collection
end
root to: 'guest_questions#index'
end
namespace 'profile', as: :profile do
resources :advisers, only: [:index, :show]
resources :contests, only: [:index] do
resources :referral_emails, only: [:new, :create]
end
resources :folder_recommendations, only: [:new, :create]
resources :folders, except: [:new] do
resources :folder_emails, only: [:new, :create]
member do
get 'clone'
end
end
resources :forum_threads, path: 'forums', only: [:index]
resources :questions, path: 'ask-an-adviser', only: [:new, :create, :show] do
get 'success', on: :collection
end
resources :resource_suggestions, path: 'suggest-resource',
only: [:new, :create]
resources :resources, only: [:index, :new, :create, :edit, :update]
resources :settings, only: [:index] do
put :update_avatar, on: :collection
put :update, on: :collection
get :confirm_destroy, on: :collection
delete :destroy, on: :collection
end
match 'settings/audience' => 'settings#audience'
match 'settings/newsletter' => 'settings#newsletter'
root to: 'folders#index'
end
resources :avatars, only: [:create, :destroy]
resources :comments, only: [:destroy]
resources :conditions_of_use, path: 'conditions-of-use', only: [:index]
resources :contact_submissions, path: 'contact-us',
only: [:index, :new, :create]
resources :events, only: [:index, :show] do
resources :bookmarks, only: [:create, :update] do
match 'move', on: :collection
match 'toggle', on: :collection
match 'sort', on: :collection
end
resources :comments, only: [:create]
end
match 'events/:year/:month/:day' => 'events#date'
match 'events/:year/:month' => 'events#monthdate'
resources :faqs, path: 'faq', only: [:index]
resources :forums, only: [:index, :show] do
match 'search', on: :collection
resources :forum_threads, path: 'threads', only: [:index, :show]
end
resources :forum_threads, path: 'threads', only: [:new, :create, :destroy] do
resources :comments, only: [:create]
end
resources :glossary, only: [:index]
match 'newsletter-hooks' => 'newsletter_hooks#index'
resources :organizations, only: [:show]
resources :questions, only: [:index] do
resources :comments, only: [:create]
end
resources :guest_questions, only: [:index] do
resources :comments, only: [:create]
resources :guest_comments, only: [:create]
end
resources :resources, only: [:show] do
post 'helpful', on: :member
resources :bookmarks, only: [:create, :update] do
match 'move', on: :collection
match 'toggle', on: :collection
match 'sort', on: :collection
end
resources :comments, only: [:create]
end
match 'blog/date/:date' => 'blog_posts#by_date', as: :blog_date
match 'blog/category/:category' => 'blog_posts#by_category', as: :blog_category
resources :blog_posts, only: [:index, :show], path: 'blog' do
resources :bookmarks, only: [:create, :update] do
match 'move', on: :collection
match 'toggle', on: :collection
match 'sort', on: :collection
end
resources :comments, only: [:create]
end
resources :scholarships, only: [:index, :show] do
resources :scholarship_submissions, only: [:create, :show] do
resources :user_submission_votes, only: [:create, :destroy]
end
end
resources :campaign_ppcs do
post 'question', on: :member
end
resources :survey_templates do
get 'template', on: :member
match 'survey_answer', on: :member
end
resources :contacts, only: [:new, :create]
match 'search' => 'search#index', as: :search
get '*id' => 'application#show', as: :page
root to: 'home#index'
end
|
require 'spec_helper'
describe AsanaAPI::Workspace do
let(:subject) { AsanaAPI::Workspace.new }
let(:workspaces) { AsanaAPI::Workspace.index! }
it 'returns 200 for index', vcr: true do
expect(subject.index.code).to eq(200)
end
it 'returns 200 for show', vcr: true do
subject.index
expect(subject.show(id: subject.parsed.first['id']).code).to eq(200)
end
end
|
# typed: true
require 'vndb/command'
require 'vndb/response'
require 'pry-byebug'
require 'socket'
require 'json'
module Vndb
class Client
extend T::Sig
sig { returns(T.nilable(IO)) }
attr_reader :socket
sig { params(username: T.nilable(String), password: T.nilable(String)).void }
def initialize(username: nil, password: nil)
@username = T.let(username, T.nilable(String))
@password = T.let(password, T.nilable(String))
@socket = T.let(TCPSocket.open(Vndb::Constants::URL, Vndb::Constants::PORT), T.nilable(IO))
payload = T.let({
protocol: 1,
client: "vndb-ruby",
clientver: Vndb::Constants::VERSION
}, Hash)
payload = merge_credentials(payload, @username, @password) if @username && @password
command = Vndb::Command.new(command: "login", payload: payload)
@socket.puts(command.to_s)
data = T.must(@socket).read(1024)
response = Vndb::Response.new(raw_body: T.must(data))
raise(Vndb::Error, T.must(response.body)) unless response.success?
end
sig { returns(Hash) }
def dbstats
command = Vndb::Command.new(command: "dbstats")
@socket.puts(command.to_s)
data = T.must(@socket).read(1024)
Vndb::Response.new(raw_body: T.must(data))
.then { |response| JSON.parse(response.body) }
end
private
sig { params(payload: Hash, username: String, password: String).returns(Hash) }
def merge_credentials(payload, username, password)
payload.merge(
username: username,
password: password
)
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Welcome to Vagrant.
# Change your project name here
PROJECT_NAME = "demo"
PROJECT_IP = "192.168.123.123"
Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.2"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
end
# Private network which allows host-only access to the machine on a specific IP.
config.vm.network :private_network, ip: PROJECT_IP
# Vagrant v1.1+ (http://jeremykendall.net/2013/08/09/vagrant-synced-folders-permissions/)
config.vm.synced_folder "./public", "/public", id: "vagrant-root",
owner: "vagrant",
group: "www-data",
mount_options: ["dmode=775,fmode=664"]
config.vm.provision :shell, :path => "./provision/CentOS_php5/_start.sh", :args => [PROJECT_NAME, PROJECT_IP]
end
|
class RecommendationFormsController < ApplicationController
layout 'embedded_app'
#Function to create or find recommendation form
def new
redirect_to recommend_form_customization
end
#Function to build new recommendation form
def edit
@recommendation = Recommendation.new
@css = encode_css(parse_layout)
end
#Function to save CSS for new recommendationf form
def update
@recommend_form.update(form_params)
redirect_to recommend_form_customization
end
#Function to reset form
def reset_form
@recommend_form.reset
redirect_to recommend_form_customization
end
private
#Function to limit the create params
def form_params
params.require(:recommendation_form).permit(:field_width,
:border_color,
:border_size,
:text_color,
:background_color,
:text_font_family,
:button_font_family,
:button_font_color,
:button_color)
end
#Function to build path for edit
def recommend_form_customization
edit_recommendation_form_path(@recommend_form)
end
#function to parse layout
def parse_layout
render_to_string(partial: "form_dynamic_css", layout: false)
end
#Function to encode CSS
def encode_css(layout)
layout.gsub!("<", "<").gsub!(">", ">")
end
end
|
class AddFields2ToWorkOrder < ActiveRecord::Migration
def change
add_column :work_orders, :address, :string
add_column :work_orders, :city, :string
add_column :work_orders, :state, :string
add_column :work_orders, :zip, :integer
add_column :work_orders, :country, :string
add_column :work_orders, :phone, :string
add_column :work_orders, :description, :text
add_column :work_orders, :type, :string
add_column :work_orders, :comments, :text
end
end
|
# encoding: utf-8
#
# TODO make me an attrib - use the same one from V-71919,V-71921 etc.
control "V-71923" do
title "User and group account administration utilities must be configured to
store only encrypted representations of passwords."
desc "Passwords need to be protected at all times, and encryption is the
standard method for protecting passwords. If passwords are not encrypted, they
can be plainly read (i.e., clear text) and easily compromised. Passwords
encrypted with a weak algorithm are no more protected than if they are kept in
plain text."
impact 0.5
tag "check": "Verify the user and group account administration utilities are
configured to store only encrypted representations of passwords. The strength
of encryption that must be used to hash passwords for all accounts is
\"SHA512\".
Check that the system is configured to create \"SHA512\" hashed passwords with
the following command:
# cat /etc/libuser.conf | grep -i sha512
crypt_style = sha512
If the \"crypt_style\" variable is not set to \"sha512\", is not in the
defaults section, or does not exist, this is a finding."
tag "fix": "Configure the operating system to store only SHA512 encrypted
representations of passwords.
Add or update the following line in \"/etc/libuser.conf\" in the [defaults]
section:
crypt_style = sha512"
describe command("cat /etc/libuser.conf | grep -i sha512") do
its('stdout.strip') { should match %r(^crypt_style = sha512$) }
end
end
|
name 'wrapper_vnc'
maintainer 'Serguei Kouzmine'
maintainer_email 'koumine_serguei@yahoo.com'
description 'Installs/configures vnc to run under specific user'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.0.1'
# https://supermarket.chef.io/cookbooks/vnc
# depends 'vnc' ,'>= 0.1.0'
# depends 'vnc' ,'>= 1.0.0'
depends 'vnc'
|
class RenameColumnOfHistoriesFromTransactionHistoryToBalance < ActiveRecord::Migration[5.2]
def change
rename_column :histories, :transaction_history, :balance
end
end
|
json.array!(@supplies) do |supply|
json.extract! supply, :id, :client_id, :residue_id, :supplied_monthly_quantity, :stock, :state
json.url supply_url(supply, format: :json)
end
|
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'posts#index'
# Example of regular route:
# ---------------------User plans-------------------------
get 'plan' => 'plan#index'
get 'new' => 'plan#new'
get 'login' => 'plan#login'
post 'create' => 'plan#create'
post 'edit' => 'plan#edit'
post 'update' => 'plan#update'
post 'delete' => 'plan#delete'
post 'sort' => 'plan#sort'
post 'uplevel' => 'plan#uplevel'
# ---------------------Posts-------------------------
get 'posts/new' => 'posts#new'
post 'posts/create', :to =>'posts#create', :as => :posts
get 'posts/show' => 'posts#show', :as => :post
get 'posts/index' => 'posts#index'
post 'posts/search' => 'posts#search'
# ---------------------Users-------------------------
get 'users/login'=>'users#login'
get 'users/registration'=>'users#registration'
post 'users/create', :to => 'users#create', :as => :users
post 'users/login' => 'users#lgn', :as => :loguser
get 'users/logout'=>'users#destroy'
post 'users/rlogin' => 'users#rlogin'
# ---------------------Comments-------------------------
post 'comments/new' => 'comments#new'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
require 'rails_helper'
require 'byebug'
RSpec.describe KepplerFrontend::Views::CssHandler, type: :services do
before(:each) do
@view = create(:keppler_frontend_views, method: "GET")
@css = KepplerFrontend::Views::CssHandler.new(@view)
end
let(:css_file) do
assets = KepplerFrontend::Urls::Assets.new
assets = assets.core_assets('stylesheets', 'app')
"#{assets}/views/#{@view.name}.scss"
end
let(:css_installed) { @css.install }
let(:css_uninstalled) { @css.uninstall }
let(:css_content) { File.read(css_file) }
context 'install' do
it { expect(css_installed).to eq(true) }
it { expect(File.exist?(css_file)).to eq(true) }
it { expect(css_content).to eq("/* Keppler - test_index.scss file */\n") }
end
context 'uninstall' do
it { expect(css_uninstalled).to eq(true) }
it { expect(File.exist?(css_file)).to eq(false) }
end
end |
require 'spec_helper'
describe Boxzooka::ReturnsNotificationRequest do
let(:return_notification_item) {
Boxzooka::ReturnNotificationItem.new(
sku: 'ABC123',
quantity: 1,
reason: 'Didnt fit',
directive: 'Return to inventory'
)
}
let(:return_notification) {
Boxzooka::ReturnNotification.new(
order_id: 'TKTEST00001',
return_date: DateTime.new(2016, 02, 20),
rma: 'TKTEST00001-R',
return_tracking: 'ABZ0123456',
return_carrier: 'Fedex',
notes: 'Didnt fit',
items: [return_notification_item]
)
}
let(:instance) {
described_class.new(
customer_access: Boxzooka::CustomerAccess.new(customer_id: 123, customer_key: 'abc'),
returns: [return_notification]
)
}
describe 'XML serialization' do
let(:xml) { Boxzooka::Xml.serialize(instance) }
it { puts Ox.dump(Ox.parse(xml)) }
end
end
|
# encoding: UTF-8
require 'spec_helper'
describe CrazyHarry::Truncate do
let(:harry){ CrazyHarry }
it "truncate by number of words" do
harry.fragment('<p>text goes here</p>').truncate!(2).to_s.should == '<p>text goes…</p>'
end
it "closes html tags properly" do
harry.fragment('<p>text <b>goes here</b></p>').truncate!(2).to_s.should == '<p>text <b>goes</b>…</p>'
end
it "passes extra options to HTML_Truncator" do
harry.fragment('<p>text goes here</p>').truncate!(10, length_in_chars: true, ellipsis: ' (...)').to_s
.should == '<p>text goes (...)</p>'
end
end
|
class Team < ActiveRecord::Base
unloadable
include Redmine::SafeAttributes
safe_attributes 'name'
has_many :team_sprints, :inverse_of => :team
has_and_belongs_to_many :issues
validates_presence_of :name
validates_uniqueness_of :name
after_save :add_team_backlog
def add_team_backlog
return if backlog
TeamSprint.create(:name => "Backlog", :team => self, :backlog => true)
end
def backlog
team_sprints.where(:backlog => true).first
end
def to_s
name
end
end
|
Puppet::DataTypes.create_type("Choria::TaskResults") do
interface <<-PUPPET
attributes => {
"results" => Array[Choria::TaskResult, 0],
"exception" => Optional[Error],
},
functions => {
count => Callable[[], Integer],
empty => Callable[[], Boolean],
error_set => Callable[[], Choria::TaskResults],
find => Callable[[String[1]], Optional[Choria::TaskResult]],
first => Callable[[], Optional[Choria::TaskResult]],
ok => Callable[[], Boolean],
ok_set => Callable[[], Choria::TaskResults],
fail_ok => Callable[[], Boolean],
hosts => Callable[[], Choria::Nodes],
message => Callable[[], String],
}
PUPPET
require_relative "../../_load_choria"
implementation_class MCollective::Util::BoltSupport::TaskResults
end
|
# frozen_string_literal: true
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user,:logged_in?,:current_user, :logged_in_user, :logout,:get_likes_for, :following, :current_post
before_action :set_cache_buster
def log_in(user)
session[:user_id] = user.id
end
def current_user
@current_user ||= User.where("auth_token =?", cookies[:auth_token]).first if cookies[:auth_token]
end
def logged_in?
!current_user.nil?
end
def logged_in_user
unless logged_in?
flash[:danger] = "Please log in."
redirect_to new_sessions_path and return
end
end
def logout
cookies[:auth_token] = nil
end
def current_user?(user)
user == current_user
end
def liked?
Like.where(post_id: @post.id,user_id: current_user.id).exists?
end
def get_likes_for(pid)
users = []
Like.where(post_id: pid).each do |l|
users << User.find_by(id: l.user_id).name
end
users = users.join(' ')
end
# def following(follower_id)
# following = []
# Follow.where(follower_id: follower_id).each do |f|
# following << User.find_by(id: f.followable_id).name
# end
# following = following.join(' ')
# end
def current_post
@p = Post.find(params[:id])
end
private
def set_cache_buster
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
end
|
class AddOriginalBodyToDecidimParticipationsParticipations < ActiveRecord::Migration[5.1]
def change
add_column :decidim_participations_participations, :original_body, :text
end
end
|
class AddMissingIndexes < ActiveRecord::Migration
def up
add_index :bookmarks, [:resource_id]
add_index :comments, [:commentable_id, :commentable_type]
add_index :questions, [:last_commenter_id]
end
def down
remove_index :bookmarks, [:resource_id]
remove_index :comments, [:commentable_id, :commentable_type]
remove_index :questions, [:last_commenter_id]
end
end
|
require_relative 'Animal'
require_relative 'mammal'
require_relative 'Flight'
class Bat < Mammal
include Flight
def initialize(name)
super(name)
@num_legs = 2
@can_fly = true
end
def method_missing(method_name)
puts "Bats don't #{method_name}, really"
"(they do drink blood ;) )"
end
def drink_blood
puts "*slurp *slurp"
end
end |
###
# Page options, layouts, aliases and proxies
###
###
# Site Settings
###
# Set site setting, used in helpers / sitemap.xml / feed.xml.
set :protocol, "https://"
set :host, "www.vejerisimo.com/"
set :port, 80
set :site_url, 'https://www.vejerísimo.com'
set :site_author, 'Wim & Marie'
set :site_title, 'VEJERÍSIMO'
set :site_description, 'Vejerísimo'
set :site_keywords, 'Vejer, Andalusia, Spain, Hotel, Bed & Breakfast, Casa, Tiene, Patio, Planta'
# Select the theme from bootswatch.com.
# If false, you can get plain bootstrap style.
# set :theme_name, 'flatly'
set :theme_name, false
# set @analytics_account, like "XX-12345678-9"
@analytics_account = "UA-63217615-1"
# Slim settings
Slim::Engine.set_options :pretty => true
# shortcut
Slim::Engine.set_options :shortcut => {
'#' => {:tag => 'div', :attr => 'id'},
'.' => {:tag => 'div', :attr => 'class'},
'&' => {:tag => 'input', :attr => 'type'}
}
# Markdown settings
set :markdown, :tables => true, :autolink => true, :gh_blockcode => true, :fenced_code_blocks => true, :with_toc_data => true
set :markdown_engine, :redcarpet
# Per-page layout changes:
#
# With no layout
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false
# With alternative layout
# page "/path/to/file.html", layout: :otherlayout
# Proxy pages (http://middlemanapp.com/basics/dynamic-pages/)
# proxy "/this-page-has-no-template.html", "/template-file.html", locals: {
# which_fake_page: "Rendering a fake page with a local variable" }
# General configuration
activate :directory_indexes
activate :i18n, :langs => [:en, :es, :fr, :nl, :de], :mount_at_root => false
activate :middleman_simple_thumbnailer
# activate :bower
# Use relative URLs
# activate :relative_assets
# sprockets for bower components
activate :sprockets
sprockets.append_path File.join(root, 'bower_components')
if defined? RailsAssets
RailsAssets.load_paths.each do |path|
sprockets.append_path path
end
end
# Reload the browser automatically whenever files change
configure :development do
set :port, 4567
activate :livereload
# Used for generating absolute URLs # middleman 3
# set :host, Middleman::PreviewServer.host
# set :port, Middleman::PreviewServer.port
end
# Build-specific configuration
configure :build do
# Minify CSS on build
activate :minify_css
# Minify Javascript on build
activate :minify_javascript
# minify html
activate :minify_html
# create gzip variants
# activate :gzip
# Enable cache buster
# activate :asset_hash
# activate :imageoptim do |options|
# # Use a build manifest to prevent re-compressing images between builds
# options.manifest = true
# # Silence problematic image_optim workers
# options.skip_missing_workers = true
# # Cause image_optim to be in shouty-mode
# options.verbose = false
# # Setting these to true or nil will let options determine them (recommended)
# options.nice = true
# options.threads = true
# # Image extensions to attempt to compress
# options.image_extensions = %w(.png .jpg .gif .svg)
# # Compressor worker options, individual optimisers can be disabled by passing
# # false instead of a hash
# options.pngcrush = { :chunks => ['alla'], :fix => false, :brute => false }
# options.pngout = { :copy_chunks => false, :strategy => 0 }
# options.pngout = false
# options.svgo = {}
# options.svgo = false
# options.advpng = { :level => 4 }
# options.gifsicle = { :interlace => false }
# options.jpegoptim = { :allow_lossy => true, :strip => ['all'], :max_quality => 80 }
# options.jpegtran = { :copy_chunks => false, :progressive => true, :jpegrescan => true }
# options.optipng = { :level => 6, :interlace => false }
# end
end
|
# == Schema Information
#
# Table name: attribution_holdings
#
# id :integer not null, primary key
# quantity :float
# ticker :string
# cusip :string
# security :string
# unit_cost :float
# total_cost :float
# price :float
# market_value :float
# pct_assets :float
# yield :float
# company_id :integer
# code_id :integer
# type_id :integer
# day_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Attribution::Holding < ActiveRecord::Base
PRINT_SETTINGS = {
:quantity => 12,
:ticker => 6,
:cusip => 10,
:date => 10,
:security => 15,
:market_value => 14,
:price => 7,
:code_name => 15,
:type_name => 10
}
belongs_to :day, class_name: "Attribution::Day"
belongs_to :company, class_name: "Attribution::Company"
belongs_to :type, class_name: "Attribution::HoldingType"
belongs_to :code, class_name: "Attribution::HoldingCode"
attr_accessor :name
before_save :associate_company
def associate_company
c = Attribution::Company.where( name: self.name, ticker: self.ticker, cusip: self.cusip, code_id: self.code_id ).first_or_create!
self.company_id = c.id
end
def portfolio_weight
self.market_value / day.total_market_value
end
def print
str_parts = PRINT_SETTINGS.map do |attrib, len|
self.send(attrib).to_s[0,len].rjust( len )
end
str = str_parts.join( " | " )
puts str
end
def date
self.day.date
end
def type_name
type and type.name
end
def usable?
return true if code.nil?
code.usable?
end
def code_name
code and code.name
end
def tag
company.id
# cusip || code.name
end
def cash_type?
type_name.upcase == "CASH"
end
def intacc?
company.tag == "intacc"
end
def audit
puts "*** AUDIT FOR #{company.tag} on #{day.date}***"
puts "----------------------------------------------"
calculator = Attribution::SecurityPerformanceCalculator.new day: day
calculator.audit_eop_weight( self )
calculator.audit_performance( self )
puts "=============================================="
end
def sd_on( day )
Attribution::SecurityDay.where( day_id: day.id, company_id: self.company.id ).first
end
end
|
class AnswersController < ApplicationController
before_action :find_answer, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user #, except: [:index, :show]
# don't need that since there are only these actions in the first place...
before_action :authorize_user, only: [:edit, :update, :destroy]
def create
@question = Question.find(params[:question_id])
@answer = Answer.new(answer_params)
@answer.question = @question
# current_user here requires the `if` statement in ApplicationController since it could raise an exception if there was no user?
@answer.user = current_user
# @answer = @question.answers.new(answer_params)
# special rails method respond_to takes a variable called format and a corresponding block
respond_to do |format|
if @answer.save
AnswersMailer.notify_question_owner(@answer).deliver_later
# execute code as html, passing in block of code to be executed.
format.html { redirect_to question_path((@question), flash: { success: "Answer created!" }) }
format.js { render :create_success }
else
# rendering into another controller, hardcode
format.html { render "questions/show" }
# respond to javascript, execute inner block as JS on client
# format.js { render js: "alert('error happened');" }
format.js { render :create_failure }
end
end
end
def edit
end
def update
if @answer.update(answer_params)
redirect_to question_path(@answer.question_id), notice: "Question Updated"
else
flash[:alert] = "Not updated.."
render :edit
end
end
def destroy
# to ensure that both question and answer id matches
# question = Question.find(params[:question_id])
# answer = question.find(params[:id])
@answer = Answer.find(params[:id])
@answer.destroy
respond_to do |format|
format.html { redirect_to question_path(params[:question_id]), flash: { danger: "Answer Deleted!" } }
format.js { render }
# this renders app/views/answers/destroy.js.erb}
end
end
private
def answer_params
params.require(:answer).permit([:body])
end
def find_answer
@answer = Answer.find(params[:id])
end
def authorize_user
unless (can? :manage, @answer) || (can? :destroy, @answer)
redirect_to root_path, alert: "access denied"
end
end
end
|
class ModelService < ApplicationService
extend ApplicationHelper
def self.update_from_webservice_by_make make
json = get_json_from_uri('http://www.webmotors.com.br/carro/modelos', { marca: make.webmotors_id })
json.each do |make_param|
model = Model.new make: make , name: make_param['Nome']
unless model.save
puts "Model: The #{make_param['Nome']} fail to save because:"
model.errors.each &$print_errors
end
end
end
end |
# encoding: utf-8
# frozen_string_literal: true
require 'rubygems'
require 'bundler'
require 'bundler/gem_tasks'
require 'rake/testtask'
require 'rspec/core/rake_task'
require 'cucumber'
require 'cucumber/rake/task'
require 'rdoc/task'
require 'rake/clean'
RSpec::Core::RakeTask.new(:spec) do |t|
t.rspec_opts = '--format documentation'
end
Rake::RDocTask.new do |rd|
rd.main = 'README.rdoc'
rd.rdoc_files.include('README.rdoc', 'lib/**/*.rb', 'bin/**/*')
rd.title = 'Autosign'
end
CUKE_RESULTS = 'results.html'.freeze
CLEAN << CUKE_RESULTS
desc 'Run features'
Cucumber::Rake::Task.new(:features) do |t|
t.cucumber_opts = 'features --format pretty'
end
desc 'Run features tagged as work-in-progress (@wip)'
Cucumber::Rake::Task.new('features:wip') do |t|
tag_opts = ' --tags ~@pending'
tag_opts = ' --tags @wip'
t.cucumber_opts = "features --format html -o #{CUKE_RESULTS} --format pretty -x -s#{tag_opts}"
t.fork = false
end
task 'cucumber:wip' => 'features:wip'
task :wip => 'features:wip'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/*_test.rb']
end
task :ci => [:spec, :features]
task :default => [:test, :features]
|
=begin
Write a program that prints out the numbers from 1 to
100, but for multiples of three print "Fizz" instead of
the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five
print "FizzBuzz"
=end
def fizzbuzz
(1..100).each do |num|
if (num % 3).zero? && (num % 5).zero?
puts 'FizzBuzz'
elsif (num % 3).zero?
puts 'Fizz'
elsif (num % 5).zero?
puts 'Buzz'
else
puts num
end
end
end
fizzbuzz
=begin
Problem
- How will I print out the number 1-100?
- lets use a range (1..100)
- lets then use the Range#each method to
iterate over each number
- How will I isolate numbers that are both
multiples of 3 and 5?
- I will check each number in the following
sequence.
First - is the current iteration number
divisable by both 3 and 5 with no remainders?
current_num % 3 == 0 && current_num % 5 == 0
If this statement returns true then print
"FizzBuzz"
Then check for 3
then check for 5
else
print number
Examples
Data-structures
Algorithm
Create range 1-100
iterate over each number
check if number if evenly divisable by 3 & 5
check if number if evenly divisable by 3
check if number if evenly divisable by 5
If not then return number
Code
=end
|
require File.expand_path('simple', File.dirname(__FILE__))
# This test currently passes, but only because Errno.constants is stubbed
# to return []...
errnosWithBadSuperclass = Errno.constants.find_all do |n|
Errno.const_get(n).superclass != SystemCallError unless n == "ERRNO_TO_EXCEPTION"
end
test(errnosWithBadSuperclass.size, 0, "Errnos with bad superclass: #{errnosWithBadSuperclass}")
test(Errno::EBADF.superclass, SystemCallError, 'Errno::EBADF should be a SystemCallError')
test(Errno::EBADF::Errno, 9, 'Errno::EBADF::Errno != 9')
report
true
|
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_owner!, except: %i[top about]
def after_sign_in_path_for(_resources)
pet_path(current_owner.pet)
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up,
keys: [:name, :image,
{ pet_attributes: %i[id name image birthday gender type introduction _destroy] }])
devise_parameter_sanitizer.permit(:sign_in, keys: [:email])
devise_parameter_sanitizer.permit(:account_update, keys: %i[name image])
end
end
|
shared_examples_for 'globus::service' do |facts|
it do
is_expected.to contain_service('globus-gridftp-server').with(ensure: 'running',
enable: 'true',
hasstatus: 'true',
hasrestart: 'true')
end
context 'when manage_service => false' do
let(:params) { { manage_service: false } }
it { is_expected.not_to contain_service('globus-gridftp-server') }
end
context 'version => 5', if: support_v5(facts) do
let(:params) { { version: '5' } }
it { is_expected.to contain_service('globus-gridftp-server') }
end
end
|
module IControl::LocalLB
##
# The Class interface enables you to manipulate a local load balancer's Class attributes.
# There are 3 different Class types: Address, String, and Value.
class Klass < IControl::Base
set_id_name "class_members"
class AddressClass < IControl::Base::Struct; end
class AddressEntry < IControl::Base::Struct; end
class MetaInformation < IControl::Base::Struct; end
class StringClass < IControl::Base::Struct; end
class ValueClass < IControl::Base::Struct; end
class AddressClassSequence < IControl::Base::Sequence ; end
class AddressEntrySequence < IControl::Base::Sequence ; end
class AddressEntrySequenceSequence < IControl::Base::SequenceSequence ; end
class ClassTypeSequence < IControl::Base::Sequence ; end
class FileFormatTypeSequence < IControl::Base::Sequence ; end
class FileModeTypeSequence < IControl::Base::Sequence ; end
class MetaInformationSequence < IControl::Base::Sequence ; end
class StringClassSequence < IControl::Base::Sequence ; end
class ValueClassSequence < IControl::Base::Sequence ; end
# A list of different class types.
class ClassType < IControl::Base::Enumeration; end
# A list of different file format types.
class FileFormatType < IControl::Base::Enumeration; end
# A list of different file mode types.
class FileModeType < IControl::Base::Enumeration; end ##
# Incrementally adds address class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def add_address_class_member
super
end
##
# Incrementally adds string class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def add_string_class_member
super
end
##
# Incrementally adds value class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def add_value_class_member
super
end
##
# Creates address classes. The specified classes must not already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::AddressClass] :classes The class names and the class members.
def create_address_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Creates external classes. Note: As of v9.6.0, the validation on the file_name field
# in external_classes was improved to ensure the class file exists on pain of Common::OperationFailed
# exception.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::MetaInformation] :external_classes The sequence of external classes to create.
def create_external_class(opts)
opts = check_params(opts,[:external_classes])
super(opts)
end
##
# Creates string classes. The specified classes must not already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::StringClass] :classes The class names and the class members.
def create_string_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Creates value classes. The specified classes must not already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::ValueClass] :classes The class names and the class members.
def create_value_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Incrementally deletes address class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_address_class_member
super
end
##
# Deletes all address classes.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_all_address_classes
super
end
##
# Deletes all string classes.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_all_string_classes
super
end
##
# Deletes all value classes.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_all_value_classes
super
end
##
# Deletes this classes. The specified classes can be of any class type, even external
# classes.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :classes The classes to delete.
def delete_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Incrementally deletes string class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_string_class_member
super
end
##
# Incrementally deletes value class member.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_value_class_member
super
end
##
# Checks to see if this class member are in this class names.
# @rspec_example
# @return [boolean[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def find_address_class_member
super
end
##
# Checks to see if this class member are in this class names.
# @rspec_example
# @return [boolean[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def find_string_class_member
super
end
##
# Checks to see if this class member are in this class names.
# @rspec_example
# @return [boolean[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def find_value_class_member
super
end
##
# Gets this address classes.
# @rspec_example
# @return [AddressClass]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names.
def address_class(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the list of available address classes.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def address_class_list
super
end
##
# Gets the data values associated with a set of address class member. This method is
# effectively the lookup method for using the class as a value map.
# @rspec_example
# @return [String[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def address_class_member_data_value
super
end
##
# Gets the meta data information for this classes. For external classes, the meta information
# will indicate the external file and other relevant information. For non-external
# classes, only applicable information such as class name/type will be of importance.
# @rspec_example
# @return [MetaInformation]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to retrieve class meta information from.
def class_meta_information(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the class types for this classes.
# @rspec_example
# @return [ClassType]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to retrieve class types.
def class_type(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the strings used to separate a class member value from its optional associated
# data value for a set of classes.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names Names of the requested classes
def data_separator(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the file format for this classes. This should only be called for external classes,
# since it does not make sense for non-external classes.
# @rspec_example
# @return [FileFormatType]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to retrieve file formats.
def external_class_file_format(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the file modes for this classes. This should only be called for external classes,
# since it does not make sense for non-external classes.
# @rspec_example
# @return [FileModeType]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to retrieve file modes.
def external_class_file_mode(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the file names for this classes. This should only be called for external classes,
# since it does not make sense for non-external classes.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to retrieve file names.
def external_class_file_name(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the list of all available external classes.
# @rspec_example
# @return [MetaInformation]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def external_class_list
super
end
##
# Gets this string classes.
# @rspec_example
# @return [StringClass]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names.
def string_class(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the list of available string classes.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def string_class_list
super
end
##
# Gets the data values associated with a set of string class member. This method is
# effectively the lookup method for using the class as a value map.
# @rspec_example
# @return [String[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def string_class_member_data_value
super
end
##
# Gets this value classes.
# @rspec_example
# @return [ValueClass]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names.
def value_class(opts)
opts = check_params(opts,[:class_names])
super(opts)
end
##
# Gets the list of available value classes.
# @rspec_example
# @return [String]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def value_class_list
super
end
##
# Gets the data values associated with a set of value class member. This method is
# effectively the lookup method for using the class as a value map.
# @rspec_example
# @return [String[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def value_class_member_data_value
super
end
##
# Gets the version information for this interface.
# @rspec_example
# @return [String]
def version
super
end
##
# Modifies address classes. The specified classes must already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::AddressClass] :classes The class names and the class members. The result is that the class now has the members specified in the class_members, regardless of what the class has before.
def modify_address_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Modifies string classes. The specified classes must already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::StringClass] :classes The class names and the class members. The result is that the class now has the members specified in the class_members, regardless of what the class has before.
def modify_string_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Modifies value classes. The specified classes must already exist.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [IControl::LocalLB::Class::ValueClass] :classes The class names and the class members. The result is that the class now has the members specified in the class_members, regardless of what the class has before.
def modify_value_class(opts)
opts = check_params(opts,[:classes])
super(opts)
end
##
# Sets the data values associated with a set of address class member. This data value
# is an optional arbitrary string, which can be retrieved given the class member information,
# allowing the class to be used as a value map.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :values Data values to associate with each class member, organized in the same manner as the class member IP addresses (default: "" (i.e., no value))
def set_address_class_member_data_value(opts)
opts = check_params(opts,[:values])
super(opts)
end
##
# Sets the strings used to separate a class member value from its optional associated
# data value for a set of classes. This is used for listing and storing both external
# and internal classes.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names Names of the requested classes
# @option opts [String] :separators String separator for each class (default: ":=")
def set_data_separator(opts)
opts = check_params(opts,[:class_names,:separators])
super(opts)
end
##
# Sets the file format for this classes. This should only be called for external classes,
# since it does not make sense for non-external classes. If called for non-external
# classes, it will silently accept it, but nothing will be done.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to set the file formats.
# @option opts [IControl::LocalLB::Class::FileFormatType] :file_formats A list of file formats to set for the specified classes.
def set_external_class_file_format(opts)
opts = check_params(opts,[:class_names,:file_formats])
super(opts)
end
##
# Sets the file mode for this classes. This should only be called for external classes,
# since it does not make sense for non-external classes. If called for non-external
# classes, it will silently accept it, but nothing will be done.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to set the file modes.
# @option opts [IControl::LocalLB::Class::FileModeType] :file_modes A list of file modes to set for the specified classes.
def set_external_class_file_mode(opts)
opts = check_params(opts,[:class_names,:file_modes])
super(opts)
end
##
# Sets the file names for this external classes. This should only be called for external
# classes, since it does not make sense for non-external classes. If called for non-external
# classes, it will silently accept it, but nothing will be done.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String] :class_names The class names to set the file names.
# @option opts [String] :file_names A list of file names to set for the specified classes.
def set_external_class_file_name(opts)
opts = check_params(opts,[:class_names,:file_names])
super(opts)
end
##
# Sets the data values associated with a set of string class member. This data value
# is an optional arbitrary string, which can be retrieved given the class member information,
# allowing the class to be used as a value map.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :values Data values to associate with each class member, organized in the same manner as the class member string values (default: "" (i.e., no value))
def set_string_class_member_data_value(opts)
opts = check_params(opts,[:values])
super(opts)
end
##
# Sets the data values associated with a set of value class member. This data value
# is an arbitrary optional string, which can be retrieved given the class member information,
# allowing the class to be used as a value map.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :values Data values to associate with each class member, organized in the same manner as the class member integer values (default: "" (i.e., no value))
def set_value_class_member_data_value(opts)
opts = check_params(opts,[:values])
super(opts)
end
##
# A struct that describes an Address class.
# @attr [String] name The Address class name.
# @attr [IControl::LocalLB::Klass::AddressEntrySequence] members The Address class member list.
class AddressClass < IControl::Base::Struct
icontrol_attribute :name, String
icontrol_attribute :members, IControl::LocalLB::Klass::AddressEntrySequence
end
##
# A struct that describes an Address class member.
# @attr [String] address The IP address of the Address class member.
# @attr [String] netmask The netmask of the Address class member.
class AddressEntry < IControl::Base::Struct
icontrol_attribute :address, String
icontrol_attribute :netmask, String
end
##
# A struct that describes the meta information of a class.
# @attr [String] class_name The name of the external class.
# @attr [IControl::LocalLB::Klass::ClassType] class_type The type of the external class.
# @attr [String] file_name The name of the file holding the data. If file_name is not empty, it indicates an external class.
# @attr [IControl::LocalLB::Klass::FileModeType] file_mode The mode determines whether the external data is updated by a save operation. Default is "READ". Only applicable for external classes.
# @attr [IControl::LocalLB::Klass::FileFormatType] file_format The file format of an external class. Only applicable for external classes.
class MetaInformation < IControl::Base::Struct
icontrol_attribute :class_name, String
icontrol_attribute :class_type, IControl::LocalLB::Klass::ClassType
icontrol_attribute :file_name, String
icontrol_attribute :file_mode, IControl::LocalLB::Klass::FileModeType
icontrol_attribute :file_format, IControl::LocalLB::Klass::FileFormatType
end
##
# A struct that describes a String class.
# @attr [String] name The String class name.
# @attr [StringSequence] members The String class member list.
class StringClass < IControl::Base::Struct
icontrol_attribute :name, String
icontrol_attribute :members, StringSequence
end
##
# A struct that describes a Value class.
# @attr [String] name The Value class name.
# @attr [LongSequence] members The Value class member list.
class ValueClass < IControl::Base::Struct
icontrol_attribute :name, String
icontrol_attribute :members, LongSequence
end
## A sequence of Address classes.
class AddressClassSequence < IControl::Base::Sequence ; end
## A sequence of Address class members.
class AddressEntrySequence < IControl::Base::Sequence ; end
## A sequence of Address class entry sequences.
class AddressEntrySequenceSequence < IControl::Base::SequenceSequence ; end
## A sequence of class types.
class ClassTypeSequence < IControl::Base::Sequence ; end
## A sequence of file format types.
class FileFormatTypeSequence < IControl::Base::Sequence ; end
## A sequence of file mode types.
class FileModeTypeSequence < IControl::Base::Sequence ; end
## A sequence of external class properties.
class MetaInformationSequence < IControl::Base::Sequence ; end
## A sequence of String classes.
class StringClassSequence < IControl::Base::Sequence ; end
## A sequence of Value classes.
class ValueClassSequence < IControl::Base::Sequence ; end
# A list of different class types.
class ClassType < IControl::Base::Enumeration
# Class type is undefined.
CLASS_TYPE_UNDEFINED = :CLASS_TYPE_UNDEFINED
# Address class.
CLASS_TYPE_ADDRESS = :CLASS_TYPE_ADDRESS
# String class.
CLASS_TYPE_STRING = :CLASS_TYPE_STRING
# Value class.
CLASS_TYPE_VALUE = :CLASS_TYPE_VALUE
end
# A list of different file format types.
class FileFormatType < IControl::Base::Enumeration
# File format is unknown.
FILE_FORMAT_UNKNOWN = :FILE_FORMAT_UNKNOWN
# File format is comma-separated values.
FILE_FORMAT_CSV = :FILE_FORMAT_CSV
end
# A list of different file mode types.
class FileModeType < IControl::Base::Enumeration
# File mode type is unknown.
FILE_MODE_UNKNOWN = :FILE_MODE_UNKNOWN
# File mode type is READ.
FILE_MODE_TYPE_READ = :FILE_MODE_TYPE_READ
# File mode type is READ/WRITE.
FILE_MODE_TYPE_READ_WRITE = :FILE_MODE_TYPE_READ_WRITE
end
end
end
|
## Simple adding
# Have the function SimpleAdding(num) add up all the
# numbers from 1 to num. Parameter num will be a postive
# integer.
def SimpleAdding(num)
num.downto(1).reduce(&:+)
end
|
class RemovePathFromPageAndPageFolder < ActiveRecord::Migration
def change
remove_column :pages, :path, :string
remove_column :page_folders, :path, :string
add_column :page_folders, :name, :string
add_column :page_folders, :title, :string
rename_column :pages, :slug, :name
end
end
|
require "rails_helper"
RSpec.describe "Pet Show Page" do
before :each do
@shelter_1 = Shelter.create(
name: "Paws For You",
address: "1234 W Elf Ave",
city: "Denver",
state: "Colorado",
zip: "90210",
)
@pet_1 = Pet.create(
image: 'https://www.petful.com/wp-content/uploads/2014/01/maltese-1.jpg',
name: "Lucy",
approximate_age: "4",
sex: "female",
name_of_shelter_where_pet_is_currently_located: "Paws For You",
shelter_id: @shelter_1.id
)
@pet_2 = Pet.create(
image: 'https://www.petful.com/wp-content/uploads/2014/01/maltese-1.jpg',
name: "MoMo",
approximate_age: "4",
sex: "male",
name_of_shelter_where_pet_is_currently_located: "Paws For You",
shelter_id: @shelter_1.id
)
end
it "I can delete the pet" do
visit "/pets/#{@pet_1.id}"
click_link "Delete Pet"
expect(current_path).to eq("/pets")
expect(page).to have_content("MoMo")
expect(page).to_not have_content("Lucy")
end
end
|
require 'windows/directory'
require 'windows/shell'
require 'windows/file'
require 'windows/error'
require 'windows/device_io'
require 'windows/unicode'
require 'windows/directory'
require 'windows/handle'
require 'windows/path'
class Dir
include Windows::Directory
include Windows::Shell
include Windows::Error
include Windows::File
include Windows::DeviceIO
extend Windows::Directory
extend Windows::Shell
extend Windows::File
extend Windows::Error
extend Windows::DeviceIO
extend Windows::Unicode
extend Windows::Handle
extend Windows::Path
VERSION = '0.3.1'
# Dynamically set each of the CSIDL_ constants
constants.grep(/CSIDL/).each{ |constant|
path = 0.chr * 260
nconst = constant.split('CSIDL_').last
if SHGetFolderPath(0, const_get(constant), 0, 1, path) != 0
path = nil
else
path.strip!
end
Dir.const_set(nconst, path)
}
# Creates the symlink +to+, linked to the existing directory +from+. If the
# +to+ directory already exists, it must be empty or an error is raised.
#
def self.create_junction(to, from)
# Normalize the paths
to.tr!('/', "\\")
from.tr!('/', "\\")
to_path = 0.chr * 260
from_path = 0.chr * 260
buf_target = 0.chr * 260
if GetFullPathName(from, from_path.size, from_path, 0) == 0
raise StandardError, 'GetFullPathName() failed: ' + get_last_error
end
if GetFullPathName(to, to_path.size, to_path, 0) == 0
raise StandardError, 'GetFullPathName() failed: ' + get_last_error
end
to_path = to_path.split(0.chr).first
from_path = from_path.split(0.chr).first
# You can create a junction to a directory that already exists, so
# long as it's empty.
rv = CreateDirectory(to_path, 0)
if rv == 0 && rv != ERROR_ALREADY_EXISTS
raise StandardError, 'CreateDirectory() failed: ' + get_last_error
end
handle = CreateFile(
to_path,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
0
)
if handle == INVALID_HANDLE_VALUE
raise StandardError, 'CreateFile() failed: ' + get_last_error
end
buf_target = buf_target.split(0.chr).first
buf_target = "\\??\\" << from_path
length = buf_target.size * 2 # sizeof(WCHAR)
wide_string = multi_to_wide(buf_target)
# REPARSE_JDATA_BUFFER
rdb = [
"0xA0000003L".hex, # ReparseTag (IO_REPARSE_TAG_MOUNT_POINT)
wide_string.size + 12, # ReparseDataLength
0, # Reserved
0, # SubstituteNameOffset
wide_string.size, # SubstituteNameLength
wide_string.size + 2, # PrintNameOffset
0, # PrintNameLength
wide_string # PathBuffer
].pack('LSSSSSSa' + (wide_string.size + 4).to_s)
bytes = [0].pack('L')
bool = DeviceIoControl(
handle,
CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),
rdb,
rdb.size,
0,
0,
bytes,
0
)
unless bool
error = 'DeviceIoControl() failed: ' + get_last_error
RemoveDirectory(to)
CloseHandle(handle)
raise error
end
CloseHandle(handle)
self
end
# Returns whether or not +path+ is empty. Returns false if +path+ is not
# a directory, or contains any files other than '.' or '..'.
#
def self.empty?(path)
PathIsDirectoryEmpty(path)
end
# Returns whether or not +path+ is a junction.
#
def self.junction?(path)
bool = true
attrib = GetFileAttributes(path)
bool = false if attrib == INVALID_FILE_ATTRIBUTES
bool = false if attrib & FILE_ATTRIBUTE_DIRECTORY == 0
bool = false if attrib & FILE_ATTRIBUTE_REPARSE_POINT == 0
bool
end
# Class level aliases
#
class << self
alias reparse_dir? junction?
end
end |
class ReadingAssignment < ActiveRecord::Migration
def change
create_table :reading_assignments do |t|
t.integer :user_id
t.date :future_scheduled
t.string :route_number
t.datetime :synchronization_date
end
add_index :reading_assignments, :user_id
add_index :reading_assignments, :synchronization_date
end
end
|
class PlacesController < ApplicationController
def index
end
def search
@places = BeermappingApi.places_in(params[:city])
if @places.empty?
redirect_to places_path, notice: "No locations in #{params[:city]}"
else
render :index
end
end
def show
city = Rails.cache.read params[:from_search]
if city.nil?
# TODO: load from beermapping api.
redirect_to places_path, notice: "Something went wrong."
return
end
@bar = city[city.find_index{|c| c.id == params[:id].to_s}]
end
end |
class CampaignResult < ActiveRecord::Base
belongs_to :user
serialize :cobrands, Array
serialize :categories, Array
serialize :excluded_affiliate_programs, Array
validates_presence_of :cobrands, :start_date, :end_date, :name
# define getter and setter methods for arrays of integers
[:categories, :cobrands, :excluded_affiliate_programs].each do |attribute|
define_method attribute do
array = read_attribute(attribute)
array.blank? ? [] : array
end
define_method "#{attribute}=".to_sym do |object|
write_attribute(attribute, [*object].map!(&:to_i))
end
end
def path_to_file
filename ? File.join(Rails.root, 'tmp', 'reports', filename) : nil
end
def run
results = { :reviews => 0, :users => 0, :data => [
['display_id', 'screen name', 'email', 'number of reviews', 'registration date', 'affiliate program id']
]
}
conditions = [<<-SQL, start_date, end_date, cobrands]
reviews.status = 'active' AND (reviews.published_at BETWEEN ? AND ?) AND reviews.cobrand_id IN (?) AND
products.status = 'active' AND
users.account_status = 'active' AND users.auth_email NOT LIKE '%@viewpoints.com'
SQL
unless categories.blank?
conditions[0] << " AND products.category_id in (?)"
conditions << categories.map { |cat| [cat, Category.find(cat).find_all_descendents.map(&:id)] }.flatten.uniq
end
unless excluded_affiliate_programs.blank?
conditions[0] << " AND (affiliate_users.affiliate_program_id IS NULL OR affiliate_users.affiliate_program_id NOT IN (?))"
conditions << excluded_affiliate_programs
end
users = Hash.new(0)
Review.all(:conditions => conditions, :include => { :user => :affiliate_user }, :joins => :product).each do |review|
if character_count.zero? or review.raw_character_count(:content) >= character_count
results[:reviews] += 1
users[review.user] += 1
end
end
qualified_users = review_count.zero? ? users : users.select { |user, num| num >= review_count }
results[:users] = qualified_users.size
qualified_users.each do |user, num|
results[:data] << [
user.display_id, user.screen_name, user.auth_email, num, user.created_at.to_s(:exact_target_date),
(user.affiliate_user ? user.affiliate_user.affiliate_program_id : '')
]
end
results
end
end
|
class ConfigurationOption < ActiveRecord::Base
belongs_to :device
belongs_to :group
end
|
describe "links DSL" do
it "runs" do
sql = I_Dig_Sql.new
sql << <<-EOF
link AS DEFAULT
asker_id | giver_id
----------------------
screen_name
id, owner_id, screen_name
----------------------
----------------------
block
blocked | victim
screen_name | screen_name
----------------------
# BLOCK_SCREEN_TYPE_ID
# ----------------------
post
pinner | pub
screen_name, computer | screen_name
ORDER BY created_at DESC
follow
fan | star
screen_name | screen_name
feed
FROM
follow, post
OF
:audience_id
GROUP BY follow.star
SELECT
follow.star_screen_name
post.*
max(post.computer_created_at)
EOF
actual = sql.to_sql(:feed)
asql actual
fail
sql(actual).should == "a"
end # === it
end # === describe "links DSL"
|
require 'spec_helper'
describe User do
context '#user_initialization' do
it { should have_db_column(:name) }
it { should have_db_column(:email) }
it { should have_db_column(:uid) }
it { should have_db_column(:provider) }
end
context "#user_relationships" do
it { should have_many(:favorites) }
end
end
|
# == Schema Information
#
# Table name: favorites
#
# id :bigint(8) not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# article_id :bigint(8)
# user_id :bigint(8)
#
# Indexes
#
# index_favorites_on_article_id (article_id)
# index_favorites_on_user_id (user_id)
# index_favorites_on_user_id_and_article_id (user_id,article_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (article_id => articles.id)
# fk_rails_... (user_id => users.id)
#
FactoryBot.define do
factory :favorite do
user { nil }
article { nil }
end
end
|
module Services
NOTIFIERS = Dry::AutoInject(Containers::NotifierContainer)
class BranchManagerObserver
include NOTIFIERS['osx_notifier']
ACTOR_TITLE = 'BranchManager'
SUCCESS_MESSAGE = "Good job with %{step_name}!"
FAILURE_MESSAGE = "You must do better than that!"
def on_step_succeeded(event)
osx_notifier.notify(message: SUCCESS_MESSAGE % event, title: ACTOR_TITLE)
end
def on_step_failed(event)
msg = if event[:step_name] == :pack_pizza
"OK. My Bad, i am sorry. Will order more boxes;"
else
FAILURE_MESSAGE
end
osx_notifier.notify(message: msg, title: ACTOR_TITLE)
end
end
end
|
require 'carrierwave/mongoid'
class Photo
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :photo, type: String
mount_uploader :photo, PhotoUploader
end
|
class DiplomasController < ApplicationController
def new
@html_content = render_to_string :partial => "/diplomas/new.haml"
respond_to do |format|
format.js { render :template => "/common/new.rjs"}
end
end
def create
begin
ActiveRecord::Base.transaction do
@diploma = Diploma.new(params[:diploma])
@diploma.user_id = current_user.id
@diploma.save!
step = AchievementStep.find(3)
current_user.steps << step unless current_user.steps.include?(step)
end
render :json => {:url => person_path(current_user)}.to_json, :status => 201
rescue
render :json => collect_errors_for(@diploma, @diploma.degree, @diploma.degree.organization).to_json, :status => 406
end
end
def edit
@diploma = Diploma.find(params[:id])
@html_content = render_to_string :partial => "/diplomas/edit.haml"
respond_to do |format|
format.js { render :template => "/common/edit.rjs"}
end
end
def update
begin
ActiveRecord::Base.transaction do
@diploma = Diploma.find(params[:id])
@diploma.update_attributes(params[:diploma])
@diploma.save!
end
render :json => {:url => person_path(current_user)}.to_json, :status => 201
rescue
render :json => collect_errors_for(@diploma, @diploma.degree, @diploma.degree.organization).to_json, :status => 406
end
end
def destroy
current_user.diplomas.find(params[:id]).destroy
redirect_to person_path(current_user)
end
end |
json.set! :user do
json.extract! user, :id, :name, :created_at, :updated_at
json.url user_url(user, format: :json)
json.set! :flights do
json.array! @user.reservations do |res|
json.id res.flight.id
json.flight_num res.flight.flight_num
json.date res.flight.date
json.from res.flight.from
json.to res.flight.to
json.airplane_id res.flight.airplane_id
json.reservation_row res.seat_row
json.reservation_column res.seat_column
end
end
end
|
class TrackingsController < ApplicationController
before_filter :load_imperatives, except: [:destroy]
def create
@title = params[:show_title]
@show = Show.find_by_title(@title.titleize)
if @show
@tracking = Tracking.create(:user_id => @user.id, :show_id => @show.id)
render 'success'
elsif Show.show_available?(@title)
@canonical_title = Show.show_available?(@title)
@show = Show.find_or_initialize_by_title(@canonical_title)
@show.save if @show.new_record?
Show.create_show_data(@title, @canonical_title, @show.id) if @show.status.nil?
@tracking = Tracking.create(:user_id => @user.id, :show_id => @show.id)
if @tracking.valid?
render 'success'
else
render 'error'
end
else
render 'error'
end
end
def destroy
@id = params[:id]
Tracking.find(@id).destroy
render 'destroy_success'
end
private
def load_imperatives
# Creates a guest user
current_user ? @user = User.find(current_user.id) : @user = User.new_guest
if @user.guest?
@user.save
session[:user_id] = @user.id
end
@trackings = @user.trackings.includes(:show)
end
end |
class Job::Report::Producer < Job::Base
belongs_to :user
belongs_to :producer, class_name: '::Producer'
def self.create_for(params = {})
job = self.create!(params)
job.enqueue_job
end
def queue
Settings.delayed_job.short_queue
end
def perform
csv = ::Report::Producer.new(producer).csv
ProducerMailer.report(self, csv).deliver_now
end
end |
module OHOLFamilyTrees
class LogValueYXT
attr_reader :filesystem
attr_reader :output_path
attr_reader :zoom
def initialize(filesystem, output_path, zoom)
@output_path = output_path
@filesystem = filesystem
@zoom = zoom
end
def write(tile, timestamp)
path = "#{output_path}/#{timestamp}/ml/#{zoom}/#{tile.tilex}/#{tile.tiley}.txt"
#p path
filesystem.write(path) do |out|
last_x = 0
last_y = 0
last_time = 0
current_v = nil
current_y = nil
current_x = nil
tile.placements.sort {|a,b|
(a.object <=> b.object)*8 +
(a.y <=> b.y)*4 +
(a.x <=> b.x)*2 +
(a.ms_time <=> b.ms_time)
}.each do |logline|
if logline.object != current_v
if current_v
out << "\n"
end
current_v = logline.object
current_y = nil
current_x = nil
out << "v#{logline.object}"
end
if logline.y != current_y
current_y = logline.y
current_x = nil
out << "\ny#{logline.y - last_y}"
end
if logline.x != current_x
current_x = logline.x
out << "\n#{logline.x - last_x}"
end
out << " #{(logline.ms_time - last_time)/10}"
last_time = logline.ms_time
last_x = logline.x
last_y = logline.y
end
end
end
end
end
|
class ApplicantDetailsJobTypes < ActiveRecord::Migration
def change
create_table :applicant_details_job_types, id: false do |t|
t.belongs_to :applicant_detail
t.belongs_to :job_type
end
add_index :applicant_details_job_types, [:applicant_detail_id, :job_type_id], unique: true, name: "applicant_and_job"
end
end
|
require './lib/blackjack/player'
# Blackjack separates the game into two classes: Game and Player.
module Blackjack
# Game contains all the game and card logic.
class Game
DECK = { suits: %w[C S D H],
cards: [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] }.freeze
SPECIAL_VALUES = { 'A' => 11,
'J' => 10,
'Q' => 10,
'K' => 10 }.freeze
# generate_deck returns an Array of strings with 52 elements.
def generate_deck
@deck = []
DECK[:suits].each do |suit|
DECK[:cards].each do |card|
@deck << "#{suit}#{card}"
end
end
# shuffle! is a built-in Ruby method
@deck.shuffle!
end
# load_deck takes an optional path to file and returns an Array of strings.
def load_deck(path = nil)
return generate_deck if path.nil?
raise "the card file doesn't exist" unless File.file?(path)
deck = File.read(path).split(', ')
deck.last.strip! # to remove the newline from the last element
deck
end
# card_value takes a string and returns an integer
def card_value(card)
value = card[1..2]
if SPECIAL_VALUES[value].nil?
value.to_i
else
SPECIAL_VALUES[value]
end
end
# player_plays takes a Blackjack::Player object and an array. We don't care
# about its return value.
def player_plays(player, deck)
card = draw_card(deck)
raise 'there are no cards left' if card.nil?
player.cards << card
player.score += card_value(card)
end
# draw_card takes an array and returns its first element, removing it
# from the array.
def draw_card(deck)
deck.shift
end
# first_round takes two Blackjack::Player objects and an Array object.
# We don't care about its return value.
def first_round(sam, dealer, deck)
player_plays(sam, deck)
player_plays(dealer, deck)
player_plays(sam, deck)
player_plays(dealer, deck)
end
# early_winner takes two Blackjack::Player objects and determines a winner
# after the first round of the game.
def early_winner(sam, dealer)
case sam.score
when 21 # Sam wins regardless if the dealer has 21.
return sam.name
when 22 # dealer wins regardless if he has 22.
return dealer.name
end
case dealer.score
when 21
return dealer.name
end
end
# play takes two Blackjack::Player objects and a deck of cards (an Array
# object), and returns a string with the name of the winner.
def play(sam, dealer, deck)
first_round(sam, dealer, deck)
return early_winner(sam, dealer) unless early_winner(sam, dealer).nil?
loop do
return sam.name if sam.score == 21
return dealer.name if sam.score > 21
break if sam.score >= 17
player_plays(sam, deck)
end
loop do
return sam.name if dealer.score > 21
break if dealer.score > sam.score
return dealer.name if dealer.score == 21
player_plays(dealer, deck)
end
determine_winner(sam, dealer)
end
# determine_winner takes two Blackjack::Player objects and returns a string.
def determine_winner(sam, dealer)
# I assumed that the dealer wins on a tie
if 21 - sam.score >= 21 - dealer.score
dealer.name
else
sam.name
end
end
# print_outcome takes two Blackjack::Player objects and an Array object,
# and prints the whole game.
def print_outcome(sam, dealer, deck)
puts play(sam, dealer, deck).to_s
puts "sam: #{sam.cards.join(', ')}"
puts "dealer: #{dealer.cards.join(', ')}"
end
end
end
|
require "data_structures/linked_list.rb"
require "digest/murmurhash"
module DataStructures
# I'll use the same hash function that Ruby uses internally for
# its Hash class (MurmurHash). As cryptographic hash functions is out of
# scope for this exercise, I've borrowed an already made implementation from
# someone over the interwebz (https://github.com/ksss/digest-murmurhash)
class MurmurHasher
def hash(key)
return Digest::MurmurHash1.rawdigest(key)
end
end
class HashTable
# For simplicity sake, we'll create a constraint regarding the table
# size for the hashtable.
def initialize(hasher, table_size = 97)
@table = []
@table_size = table_size
@hasher = hasher
end
def put(key, val)
table_idx = key_index(key)
@table[table_idx] = Bucket.new if @table[table_idx].nil?
@table[table_idx].put(key, val)
end
def get(key)
table_idx = key_index(key)
if @table[table_idx].nil?
value = nil
else
value = @table[table_idx].get(key)
end
return value
end
def key_index(key)
key_hash = @hasher.hash(key)
return key_hash % @table_size
end
class BucketValue
def initialize(key, value)
@key = key
@value = value
end
def ==(bucket_value)
return bucket_value.key == @key
end
attr_accessor :key, :value
end
class Bucket
def initialize
@size = 1
@values = LinkedList.new
end
def put(key, value)
bucket_value = BucketValue.new(key, value)
@values.delete(bucket_value)
node = LinkedList::Node.new(bucket_value)
@values.add node
end
def get(key)
@values.each do |node|
# ugly API is ugly...
if node.value.key == key
return node.value.value
end
end
return nil
end
end
end
end
|
Apipie.configure do |config|
config.app_name = "DocUBuild - API"
config.api_base_url = "/api"
config.doc_base_url = "/apidocs"
# where is your API defined?
config.api_controllers_matcher = "#{Rails.root}/app/controllers/api/**/*.rb"
config.default_version = "1"
config.app_info = "The DocUBuild API will allow you to access documents, as well as perform queries in compliance with the HL7 Infobutton standard"
config.translate = false
config.default_locale = nil
end
|
module ApiBase
def current_user
context[:current_user]
end
end
|
class Item < ActiveRecord::Base
belongs_to :beacon
has_many :staff_items
has_many :staff, through: :staff_items
has_many :item_tags
has_many :tags, through: :item_tags
end
|
require 'csv'
module S3MPI
module Converters
module CSV
extend self
class HeaderError < StandardError; end
# Convert CSV string data to an array of hashes
#
# @param [String] csv_data
# String of CSV data
#
# @param [Hash] options
# Passed to CSV.parse
#
# @return [Array]
def parse(csv_data, options = Hash.new)
options = options.merge({
headers: true,
converters: :all
})
::CSV.parse(csv_data, options).map(&:to_hash)
end
# Convert an array of hashes to CSV string data
#
# @param [Array] array_of_hashes
# An Array of Hashes
#
# @param [Hash] options
# Passed to CSV.generate
#
# @return [String]
def generate(array_of_hashes, options = Hash.new)
return "" if array_of_hashes.empty?
headers = inspect_headers(array_of_hashes)
::CSV.generate(options) do |csv|
csv << headers
array_of_hashes.each do |hash|
csv << hash.values_at(*headers)
end
end
end
private
def inspect_headers(data)
data.first.keys.tap do |headers|
sorted = headers.sort
error = data.any?{ |hash| hash.keys.sort != sorted }
raise HeaderError, "the rows have inconsistent headers!" if error
end
end
end
end
end
|
# frozen_string_literal: true
class User < ApplicationRecord
# Include default users modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
validates :email, presence: true, length: {maximum: 256},
uniqueness: {case_sensitive: false}
end
|
Rails.application.routes.draw do
root 'homes#about'
get '/top' => 'homes#top', as: :top
get '/manage' => 'homes#manage', as: :manage
devise_for :admins, controllers: {
sessions: 'admins/sessions',
passwords: 'admins/passwords',
registrations: 'admins/registrations'
}
devise_for :users, controllers: {
sessions: 'users/sessions',
passwords: 'users/passwords',
registrations: 'users/registrations'
}
resources :users, only: [:edit, :update, :show] do
member do
get :followings
get :followers
end
collection do
get :search
end
end
resources :admins
resources :categories, only: [:create, :destroy, :update, :edit, :index]
resources :items, only: [:create, :destroy, :update, :show, :index, :edit, :new] do
member do
get :like
end
collection do
get :search
post :confirm
end
end
resources :logs, only: [:create, :destroy, :update, :edit]
resources :likes, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
resources :comments, only: [:create, :destroy]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end |
class LoginValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, :bad_login) unless value =~ /\A\w+\Z/
end
end
|
module Elasticsearch
module Search
module Pagination
def setup_pagination
@page = params.fetch(:page, default_page).to_i
@page = default_page if page < default_page
@per_page = params.fetch(:per_page, nil).to_i
@per_page = default_per_page unless per_page.in?(minimum_per_page..maximum_per_page)
end
private
attr_reader :page, :per_page
def default_page
Settings.pagination.page.default
end
def default_per_page
Settings.pagination.per_page.default
end
def minimum_per_page
Settings.pagination.per_page.minimum
end
def maximum_per_page
Settings.pagination.per_page.maximum
end
end
end
end
|
class Bus
attr_accessor :route_number, :destination, :passengers
def initialize(route_number, destination)
@route_number = route_number
@destination = destination
@passengers = []
end
def drive
return "Brum brum"
end
def pickup(*passenger)
@passengers.concat(passenger)
end
def drop_off(*passenger)
passenger.each do |pas|
@passengers.delete(pas) if @passengers.include? pas
end
end
def empty
@passengers = []
end
def pick_up_from_stop(bus_stop)
@passengers.concat(bus_stop.queue)
bus_stop.queue = []
end
end
|
class Invite < ApplicationRecord
class Policy < BasePolicy
def index?
current_user.can_administer_groups?
end
def show?
current_user.admin_groups.map(&:id).include?(model.group_id)
end
def create?
current_user.can_administer_groups?
end
def revoke?
current_user.admin_groups.map(&:id).include?(model.group_id)
end
def accept?
true
end
def accepted?
model.accepted_by == current_user.remote_user
end
end
end
|
# encoding: utf-8
class SessionsController < ApplicationController
skip_before_filter :require_signin, :only => [:new, :create, :destroy]
layout "sessions"
def new
end
def create
#redirect_to user_menus_path
reset_session #anti session fixation. must before assign session values
user = User.authenticate(params[:login], params[:password]) #here email is pointing to login in User.authenticate
session[:user_ip] = request.env['HTTP_X_FORWARDED_FOR'].nil? ? request.env['REMOTE_ADDR'] : request.env['HTTP_X_FORWARDED_FOR']
#good for client behind proxy or load balancer
if user.nil?
#log
sys_logger('登录名/密码错误')
flash.now[:error] = "登录名/密码错误!"
render 'new'
elsif user.status == 'active'
#assign session vars
session[:user_id] = user.id
session[:user_name] = user.name
session[:last_seen] = Time.now.utc #db uses UTC time for timestamp
sign_in(user)
#log
sys_logger('登录')
redirect_to user_menus_path
else
#log
sys_logger('登录失败')
flash.now[:error] = "登录名/密码错误!"
render 'new'
end
end
def destroy
sys_logger('退出')
sign_out
redirect_to signin_path, :notice => "退出了!"
end
end
|
def display_board(board)
puts row1 = " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts row2 = " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts row3 = " #{board[6]} | #{board[7]} | #{board[8]} "
end
def move(board, index, position)
board[index] = position
end
def valid_move?(board, index)
if index>= 0 && index <=8
if position_taken?(board, index) == false
return true
else return false
end
else return false
end
end
def turn(board)
puts "Please enter 1-9:"
goodInput = false
while goodInput == false
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index) == true && position_taken?(board, index) == false
move(board, index, current_player(board))
goodInput = true
display_board(board)
else
puts "Not a valid move! Try again"
end
end
end
def input_to_index(input)
index = input.to_i
if !index
return -1
else
return index -= 1
end
end
def turn_count(board)
xTurnsTaken = 0
oTurnsTaken = 0
board.each do |space|
if space == "X"
xTurnsTaken += 1
elsif space == "O"
oTurnsTaken += 1
end
end
turnsTaken = xTurnsTaken + oTurnsTaken
end
def current_player(board)
turnToGo = turn_count(board)
if turnToGo%2 == 0
return "X"
else
return "O"
end
end
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
def won?(board)
WIN_COMBINATIONS.each do |win_combo|
index0 = win_combo[0]
index1 = win_combo[1]
index2 = win_combo[2]
if board[index0] == "X" && board[index1] == "X" && board[index2] == "X"
return win_combo
elsif board[index0] == "O" && board[index1] == "O" && board[index2] == "O"
return win_combo
end
end
return false
end
def full?(board)
count = -1
check = board.all? do |i|
count += 1
position_taken?(board, count)
end
check
end
def draw?(board)
if won?(board)
return false
elsif full?(board)
return true
else
return false
end
end
def over?(board)
if full?(board) || draw?(board) || won?(board) != false
return true
else return false
end
end
def winner(board)
if won?(board) != false
winningCombo = won?(board)
teamWin = board[winningCombo[0]]
return teamWin
else return nil
end
end
def play(board)
while !(over?(board))
turn(board)
won?(board)
end
if won?(board) != false
winnerTeam = winner(board)
puts "Congratulations #{winnerTeam}!"
elsif draw?(board)
puts "Cat's Game!"
end
end |
# frozen_string_literal: true
module Jet
module Core
module InstanceRegistry
def self.extended(base)
super
base.instance_variable_set(:@registry, {})
end
def [](obj)
@registry[obj]
end
def []=(key, obj)
raise "no `type` for registry has been set yet" unless @type
@registry[Jet.type_check!("`key`", key, Symbol)] = Jet.type_check!("`obj`", obj, @type)
end
def fetch(*args)
@registry.fetch(*args)
end
def freeze
@registry.freeze
super
end
def register(hash)
hash.each { |key, obj| self[key] = obj }
self
end
def to_h
@registry.dup
end
def type(type = nil)
return @type unless type
raise "`type` cannot be changed once set" if @type
Jet.type_check!("`type`", type, Class, Module)
@type = type
end
end
end
end
|
require 'byebug'
class Minesweeper
CHECK = [[-1,0], [-1,-1], [-1,1], [0,1], [0,-1], [1,-1], [1,0], [1,1]]
attr_accessor :height, :width, :bombs, :grid
def initialize(diff)
@diff = diff
@bombs = 0
@height = 0
@width = 0
case diff
when "easy"
@height = 9
@width = 9
@bombs = 10
when "intermediate"
@height = 16
@width = 16
@bombs = 40
when "hard"
@height = 16
@width = 30
@bombs = 99
end
@grid = Array.new(width) { Array.new(height) { Tile.new } }
populate
end
def reveal(pos)
x, y = pos
raise "Game Over!" if grid[x][y].bomb
grid[x][y].revealed = true unless grid[x][y].flagged
end
def flag(pos)
grid[x][y].flagged = true
end
def populate
bombs.times do
x,y = [rand(width), rand(height)]
tile = grid[x][y]
tile.bomb = true
end
grid.each_index do |row|
grid[row].each_index do |col|
grid[row][col].position = [row,col]
end
end
end
def display
grid.each_index do |row|
grid[row].each_index do |tile|
if grid[row][tile].revealed
if grid[row][tile].bomb
print "*"
elsif grid[row][tile].flagged
print "P"
else
print adjacent_bombs(grid[row][tile].position)
end
else
print "o"
end
end
puts
end
end
def adjacent_bombs(pos)
num_bombs = 0
CHECK.each do |el|
num_bombs += 1 if grid[pos[0] + el[0]] [pos[1] + el[1]].bomb
end
num_bombs
end
def click(pos)
reveal(pos)
if adjacent_bombs(pos) == 0
cands = [self]
until cands.empty?
CHECK.each do |el|
cands.shift
tile = grid[pos[0 + el[0]]][1 + el[1]]
cands.push(tile) unless tile.bomb
reveal(tile.position) unless tile.flagged
end
end
end
end
end
class Tile
attr_accessor :bomb, :revealed, :flagged, :adj_bombs, :position
def initialize(bomb = false, revealed = false, flagged = false, adj_bombs = 0, position = [0,0])
@bomb = bomb
@revealed = revealed
@flagged = flagged
@adj_bombs = adj_bombs
@position = position
end
end
|
# == Schema Information
#
# Table name: track_charges
#
# id :integer not null, primary key
# track_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# state :string
# track_sku :string
# payment :json
# amount_cents :integer default(0), not null
#
# Indexes
#
# index_track_charges_on_track_id (track_id)
# index_track_charges_on_user_id (user_id)
#
class TrackCharge < ActiveRecord::Base
belongs_to :track
belongs_to :user
monetize :amount_cents
validates :track, presence: true
validates :amount, presence: true
validates :user, presence: true
end
|
class AppointmentsController < ApplicationController
def new
@appointment = Appointment.new
end
def create
@appointment = Appointment.new(appointment_params)
if @appointment.save
redirect_to root_path, notice: "Appointment added."
else
render :new
end
end
private
def appointment_params
params.require(:appointment).permit(:description,
:"appointment_schedule(1i)",
:"appointment_schedule(2i)",
:"appointment_schedule(3i)",
:"appointment_schedule(4i)",
:"appointment_schedule(5i)"
)
end
end
|
class Cake < ActiveRecord::Base
#has_attached_file :photo, :styles => { :medium => "650x250>", :thumb => "500x100>" }, :default_url => "/images/:style/missing.png"
has_attached_file :photo,
:styles => { :medium => "650x250", :thumb => "500x100"},
:default_url => "/images/:style/missing.png",
:storage => :s3,
:s3_host_name => 's3-us-west-2.amazonaws.com',
:s3_credentials => Proc.new{|a| a.instance.s3_credentials }
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :line_item
before_destroy :ensure_not_referenced_by_any_line_item
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_item.count.zero?
return true
else
errors[:base] << "Line Items present"
eturn false
end
end
def s3_credentials
{:bucket => "vuong", :access_key_id => "AKIAIXITLBP44VVID6UQ", :secret_access_key => "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"}
end
end
|
module Spree::Chimpy
module Interface
class Lists
delegate :log, to: Spree::Chimpy
def self.delegate_each(*methods)
options = methods.pop
unless options.is_a?(Hash) && to = options[:to]
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
end
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
if prefix == true && to =~ /^[^a-z_]/
raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
end
method_prefix = \
if prefix
"#{prefix == true ? to : prefix}_"
else
''
end
file, line = caller.first.split(':', 2)
line = line.to_i
to = to.to_s
to = 'self.class' if to == 'class'
methods.each do |method|
# Attribute writer methods only accept one argument. Makes sure []=
# methods still accept two arguments.
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
# The following generated methods call the target exactly once, storing
# the returned value in a dummy variable.
#
# Reason is twofold: On one hand doing less calls is in general better.
# On the other hand it could be that the target has side-effects,
# whereas conceptualy, from the user point of view, the delegator should
# be doing one call.
if allow_nil
module_eval(<<-EOS, file, line - 3)
def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
#{to}.map do |_| # client.each do |_|
if !_.nil? || nil.respond_to?(:#{method}) # if !_.nil? || nil.respond_to?(:name)
_.#{method}(#{definition}) # _.name(*args, &block)
end # end
end # end
end # end
EOS
else
exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
module_eval(<<-EOS, file, line - 2)
def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
#{to}.map do |_| # client.each do |_|
begin # begin
_.#{method}(#{definition}) # _.name(*args, &block)
rescue NoMethodError => e # rescue NoMethodError => e
location = "%s:%d:in `%s'" % [__FILE__, __LINE__ - 2, '#{method_prefix}#{method}'] # location = "%s:%d:in `%s'" % [__FILE__, __LINE__ - 2, 'customer_name']
if _.nil? && e.backtrace.first == location # if _.nil? && e.backtrace.first == location
#{exception} # # add helpful message to the exception
else # else
raise # raise
end # end
end # end
end # end
end # end
EOS
end
end
end
attr_accessor :lists
def initialize(lists)
@lists = lists
end
delegate_each :subscribe, to: :lists
delegate_each :unsubscribe, to: :lists
delegate_each :update_subscriber, to: :lists
delegate_each :add_merge_var, to: :lists
delegate_each :create_segment, to: :lists
delegate_each :sync_merge_vars, to: :lists
delegate_each :segment, to: :lists
delegate_each :ensure_list, to: :lists
delegate_each :ensure_segment, to: :lists
def info(email_or_id)
## return info from the first list which returns non-nil result
## TODO: only call subsequent lists if first list returns nil/empty
lists.map { |list| list.info(email_or_id) }.reject(&:nil?).reject(&:empty?).first || {}
end
end
end
end
|
# == Schema Information
#
# Table name: wishes
#
# id :integer not null, primary key
# name :string(255)
# description :text
# url :string(255)
# created_at :datetime
# updated_at :datetime
#
require 'rails_helper'
RSpec.describe Wish, :type => :model do
subject {FactoryGirl.build(:wish)}
it "has a valid factory" do
expect(subject).to be_valid
end
describe '#name' do
it "is required" do
subject.name = nil
expect(subject).to_not be_valid
end
end
describe '#description' do
it "is required" do
subject.description = nil
expect(subject).to_not be_valid
end
end
describe '#url' do
it "is required" do
subject.url = nil
expect(subject).to_not be_valid
end
end
end
|
def prompt(message)
puts "=> #{message}"
end
def join_and(array, delimiter1 = ', ', delimiter2 = 'and')
if array.length > 2
string1 = array.first(array.length - 1).join(delimiter1)
string2 = array.pop.to_s
string1 + "#{delimiter1}#{delimiter2} " + string2
else
array.join(" #{delimiter2} ")
end
end
def initialize_deck
suits = ['hearts', 'spades', 'diamonds', 'clubs']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10'] +
['jack', 'queen', 'king', 'ace']
new_deck = []
suits.each do |suit|
ranks.each do |rank|
new_deck << [suit, rank]
end
end
new_deck
end
def deal_cards(deck, hand)
hand << deck.delete_at(rand(deck.length - 1))
end
def calculate_value(hand)
sum = 0
hand.each do |card|
if card[1] == 'ace'
sum += 11
elsif card[1].to_i == 0
sum += 10
else
sum += card[1].to_i
end
if sum > 21
hand.each do |crd|
if sum > 21 && crd[1] == 'ace'
sum -= 10
end
end
end
end
sum
end
def display_dlrhand(dlr_hand)
prompt("Dealer has: #{dlr_hand[0][1]} and a hidden card.")
end
def display_plrhand(plr_hand)
just_ranks = plr_hand.map do |card|
card[1]
end
prompt("You have #{join_and(just_ranks)}.")
end
def display_totals(plr_hand, dlr_hand)
prompt("You have a total of #{calculate_value(plr_hand)}.")
prompt("Dealer has a total of #{calculate_value(dlr_hand)}.")
end
def busted?(hand)
hand_value = calculate_value(hand)
hand_value > 21
end
def twenty_one?(hand)
hand_value = calculate_value(hand)
hand_value == 21
end
def find_winner(plr_hand, dlr_hand)
total_player = calculate_value(plr_hand)
total_dealer = calculate_value(dlr_hand)
if total_player == total_dealer
:tie
elsif total_player > total_dealer
:player
else
:dealer
end
end
def display_winner(plr_hand, dlr_hand)
winner = find_winner(plr_hand, dlr_hand)
case winner
when :tie
prompt("It's a tie!")
when :player
prompt("You won the game!")
when :dealer
prompt("The dealer won the game!")
end
end
loop do
# initialize deck
main_deck = initialize_deck
player_hand = []
dealer_hand = []
# deal cards to player (2 cards) and to dealer (2 cards)
2.times { deal_cards(main_deck, player_hand) }
2.times { deal_cards(main_deck, dealer_hand) }
# 'Welcome to game' prompt
system 'clear'
prompt("Welcome to 21!")
system 'sleep 2'
# loop to deal cards to player until busted or 'stay'
loop do
display_dlrhand(dealer_hand)
display_plrhand(player_hand)
break if busted?(player_hand)
break if twenty_one?(player_hand)
answer = ''
loop do
prompt("Would you like to hit or stay? (Enter 'hit' or 'stay')")
answer = gets.chomp
break if answer == 'stay' || answer == 'hit'
prompt("That's not a valid answer, please try again.")
end
break if answer == 'stay'
deal_cards(main_deck, player_hand)
end
if busted?(player_hand)
prompt("You are busted, dealer won the game!")
system 'sleep 2'
elsif twenty_one?(player_hand) && !twenty_one?(dealer_hand)
prompt("You are the first to have reached 21, you won the game!")
system 'sleep 2'
else
# deal cards to dealer until total_dealer >= 17 or 'busted'
loop do
display_dlrhand(dealer_hand)
display_plrhand(player_hand)
system 'sleep 2'
total_dealer = calculate_value(dealer_hand)
break_dealer_loop = nil
if total_dealer < 17
prompt("Dealer chooses to hit")
system 'sleep 2'
deal_cards(main_deck, dealer_hand)
elsif total_dealer == 21
prompt("Dealer has 21! Dealer won the game.")
system 'sleep 2'
break_dealer_loop = true
elsif total_dealer >= 17
prompt("Dealer chooses to stay")
system 'sleep 2'
prompt("")
display_totals(player_hand, dealer_hand)
display_winner(player_hand, dealer_hand)
break_dealer_loop = true
end
# why does it not work when I put the above in a case statement?
break if break_dealer_loop
end
end
play_again = ''
loop do
prompt("Would you like to play again? Enter 'yes' or 'no': ")
play_again = gets.chomp.downcase
break if play_again == 'yes' || play_again == 'no'
prompt("That is not a valid answer, please try again.")
end
break if play_again == 'no'
end
prompt("Thank you for playing, bye!")
|
module Presenter
module Table
class Vertical < Presenter::Table::Base
def render
render_tty.join(VERTICAL_DELIMETER)
end
def render_tty
lines
end
end
end
end
|
require 'rails_helper'
describe Comment do
it { should belong_to :story }
it { should validate_presence_of :comment }
it { should validate_length_of :comment }
end
|
class Api::V1::AuthenticationController < ApplicationController
skip_before_action :authenticate_request, only: [:authenticate]
include ActiveModel::Serialization
def authenticate
command = AuthenticateUser.call(params[:email], params[:password])
if command.success?
render json: { auth_token: command.result }
else
render json: { error: command.errors }, status: :unauthorized
end
end
def return_user
render json: current_user, only: [:name, :email, :admin]
end
end
|
# Feed
# RSSフィード
class Feed
# @!attribute [rw] title
# @!attribute [rw] description
# @!attribute [rw] link
# @!attribute [rw] entries
attr_accessor :title, :description, :link, :entries
# インスタンスの作成
# @param [String] title
# @param [String] description
# @param [String] link
# @param [String] entries
# @return [Feed] Feedクラスのインスタンス
def initialize(title, description, link, entries)
@title = title
@description = description
@link = link
@entries = entries
end
end
|
class CreateProperties < ActiveRecord::Migration
def change
create_table :properties do |t|
t.references :thing, index: true, :null => :false
t.references :parent_control, index: true
t.string :name, :null => :false
t.string :type, :null => :false, :default => "StringProperty"
t.integer :position, :default => 0
t.boolean :many, :default => false
t.boolean :required, :default => false
t.string :matches
t.string :restricted
t.decimal :minimum
t.decimal :maximum
t.text :view
t.timestamps
end
end
end
|
require 'test_helper'
class DomainTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "Creates address and user" do
d1 = Domain.new(:domain => "@example.net")
assert d1.valid?, d1.errors.to_s
assert d1.save
assert d1.user
assert d1.address
assert d1.address.domain == d1
end
test "Won't save if duplicate" do
Domain.new(:domain => "@example.net").save
d1 = Domain.new(:domain => "@example.net")
assert !d1.valid?, d1.errors.to_s
end
end
|
songs = [
"Phoenix - 1901",
"Tokyo Police Club - Wait Up",
"Sufjan Stevens - Too Much",
"The Naked and the Famous - Young Blood",
"(Far From) Home - Tiga",
"The Cults - Abducted",
"Phoenix - Consolation Prizes",
"Harry Chapin - Cats in the Cradle",
"Amos Lee - Keep It Loose, Keep It Tight"
]
def list(songs)
arr = {}
songs.each_with_index do |song, i|
# arr << {i+1: song}
puts "#{i+1}. #{song}"
end
end
def help
puts "I accept the following commands:
- help : displays this help message
- list : displays a list of songs you can play
- play : lets you choose a song to play
- exit : exits this program"
end
def exit_jukebox
puts "Goodbye"
end
def play
puts "What's your song's number or name"
num = gets.chomp
arr.each do |number, song|
if number == num
puts song
elsif num == song
puts song
else
puts "Invalid input, please try again"
end
end
end |
module Arcane
class Finder
attr_reader :object
def initialize(object)
@object = object
end
def refinery
klass = find
klass = klass.constantize if klass.is_a?(String)
klass
rescue NameError
Arcane::Refinery
end
def self.object_name(object)
klass = if object.respond_to?(:model_name)
object.model_name
elsif object.class.respond_to?(:model_name)
object.class.model_name
elsif object.is_a?(Class)
object
else
object.class
end
klass.to_s
end
private
def find
if object.respond_to?(:arcane_class)
object.refinery_class
elsif object.class.respond_to?(:arcane_class)
object.class.refinery_class
else
klass = self.class.object_name(object)
"#{klass}Refinery"
end
end
end
end |
class DeliveryOrder < ActiveRecord::Base
has_many :state_per_order_details
has_many :delivery_order_details
belongs_to :cost_center
belongs_to :user
accepts_nested_attributes_for :delivery_order_details, :allow_destroy => true
state_machine :state, :initial => :pre_issued do
event :issue do
transition [:pre_issued, :revised] => :issued
end
event :observe do
transition :issued => :pre_issued
end
event :revise do
transition [:issued, :approved] => :revised
end
event :approve do
transition :revised => :approved
end
event :cancel do
transition [:pre_issued, :issued, :revised, :approved] => :canceled
end
end
def self.getOwnArticles(word, name)
mysql_result = ActiveRecord::Base.connection.execute("
SELECT a.id, a.code, a.name, a.unit_of_measurement_id, u.symbol
FROM articles_from_cost_center_" + name.to_s + " a, unit_of_measurements u
WHERE (a.code LIKE '04%' || a.code LIKE '03%' || a.code LIKE '02%')
AND ( a.name LIKE '%#{word}%' OR a.code LIKE '%#{word}%' )
AND a.unit_of_measurement_id = u.id
GROUP BY a.code
")
return mysql_result
end
def self.inspect_have_data(id)
flag = false
DeliveryOrder.find(id).delivery_order_details.each do |dod|
purchase_order = dod.purchase_order_details
if purchase_order.count > 0
flag = true
break
end
end
return flag
end
end |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
#now using devise
#unless ENV['RAILS_ENV'] == 'test' || ENV['RAILS_ENV'] == 'development'
# http_basic_authenticate_with name: ENV['BASIC_AUTH_USER'], password: ENV['BASIC_AUTH_PASS']
#end
helper_method :is_admin?, :check_admin
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
def is_admin?
current_user.present? && current_user.admin? #signed_in? && current_user.admin?
end
def check_admin
if !current_user.admin?
flash['error'] = "The action you've requested requires admin privileges. "
redirect_to root_path
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :admin])
end
end
|
# -*- encoding: utf-8 -*-
# stub: qless 0.10.5 ruby lib
Gem::Specification.new do |s|
s.name = "qless".freeze
s.version = "0.10.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Dan Lecocq".freeze, "Myron Marston".freeze]
s.bindir = "exe".freeze
s.date = "2016-11-29"
s.description = "\n`qless` is meant to be a performant alternative to other queueing\nsystems, with statistics collection, a browser interface, and\nstrong guarantees about job losses.\n\nIt's written as a collection of Lua scipts that are loaded into the\nRedis instance to be used, and then executed by the client library.\nAs such, it's intended to be extremely easy to port to other languages,\nwithout sacrificing performance and not requiring a lot of logic\nreplication between clients. Keep the Lua scripts updated, and your\nlanguage-specific extension will also remain up to date.\n ".freeze
s.email = ["dan@moz.com".freeze, "myron@moz.com".freeze]
s.executables = ["qless-web".freeze, "qless-config".freeze, "qless-stats".freeze]
s.files = ["exe/qless-config".freeze, "exe/qless-stats".freeze, "exe/qless-web".freeze]
s.homepage = "http://github.com/seomoz/qless".freeze
s.rubyforge_project = "qless".freeze
s.rubygems_version = "2.5.2.1".freeze
s.summary = "A Redis-Based Queueing System".freeze
s.installed_by_version = "2.5.2.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<metriks>.freeze, ["~> 0.9"])
s.add_runtime_dependency(%q<redis>.freeze, ["< 4.0.0.rc1", ">= 2.2"])
s.add_runtime_dependency(%q<rusage>.freeze, ["~> 0.2.0"])
s.add_runtime_dependency(%q<sentry-raven>.freeze, ["~> 0.4"])
s.add_runtime_dependency(%q<sinatra>.freeze, ["~> 1.3"])
s.add_runtime_dependency(%q<statsd-ruby>.freeze, ["~> 1.3"])
s.add_runtime_dependency(%q<thin>.freeze, ["~> 1.6.4"])
s.add_runtime_dependency(%q<thor>.freeze, ["~> 0.19.1"])
s.add_runtime_dependency(%q<vegas>.freeze, ["~> 0.1.11"])
else
s.add_dependency(%q<metriks>.freeze, ["~> 0.9"])
s.add_dependency(%q<redis>.freeze, ["< 4.0.0.rc1", ">= 2.2"])
s.add_dependency(%q<rusage>.freeze, ["~> 0.2.0"])
s.add_dependency(%q<sentry-raven>.freeze, ["~> 0.4"])
s.add_dependency(%q<sinatra>.freeze, ["~> 1.3"])
s.add_dependency(%q<statsd-ruby>.freeze, ["~> 1.3"])
s.add_dependency(%q<thin>.freeze, ["~> 1.6.4"])
s.add_dependency(%q<thor>.freeze, ["~> 0.19.1"])
s.add_dependency(%q<vegas>.freeze, ["~> 0.1.11"])
end
else
s.add_dependency(%q<metriks>.freeze, ["~> 0.9"])
s.add_dependency(%q<redis>.freeze, ["< 4.0.0.rc1", ">= 2.2"])
s.add_dependency(%q<rusage>.freeze, ["~> 0.2.0"])
s.add_dependency(%q<sentry-raven>.freeze, ["~> 0.4"])
s.add_dependency(%q<sinatra>.freeze, ["~> 1.3"])
s.add_dependency(%q<statsd-ruby>.freeze, ["~> 1.3"])
s.add_dependency(%q<thin>.freeze, ["~> 1.6.4"])
s.add_dependency(%q<thor>.freeze, ["~> 0.19.1"])
s.add_dependency(%q<vegas>.freeze, ["~> 0.1.11"])
end
end
|
class Sears::CommentsController < ApplicationController
before_filter :require_session_user, :only => :create
before_filter :load_article, :only => [:blog, :qa]
before_filter :load_ratable_entity, :only => :media
before_filter :load_article_category, :only => :slice
ssl_allowed :create
[:blog, :media, :qa].each do |action|
define_method action do
render :json => {
:comments => @entity.messages.map { |comment|
{ :id => comment.id,
:date => comment.created_at.strftime("%m/%d/%Y"),
:poster => {
:id => comment.from_user.id,
:screen_name => comment.from_user.screen_name
},
:content => comment.text,
:rating => Review.convert_points_to_stars(comment.rating)
}
}
}
end
end
def slice
hash = { :comment_summary => {} }
@entity.children.each do |trend|
trend.articles.of_type(:qa).published.each do |article|
hash[:comment_summary][article.id] = { :num_comments => article.messages.active.count }
end
end
render :json => hash
end
def create
if 'media' == params[:kind]
load_ratable_entity
# RatableEntities originate outside our system, create a new instance if resource not found
# RatableEntity(id, source_id, partner_type, partner_key, messages_count, average_rating, created_at, updated_at)
@entity ||= RatableEntity.create! :partner_key => params[:id], :source_id => params[:source_id]
else
load_article # QA and Blog Articles originate in our system, reject comments if resource not found
end
return (redirect_to_widget_if(params[:redirect_to_failure]) || handle_resource_not_found) unless @entity
# TODO who do we use for RatableEntities ???
message = Message.new(
:from_user => session_user,
:to_user => (@entity.is_a?(Article) ? @entity.user : User.first(:conditions => { :proxy_user => true })),
:about => @entity,
:text => params[:text],
:rating => params[:rating].blank? ? nil : Review.convert_stars_to_points(params[:rating].to_i)
)
if message.save
redirect_to_widget_if(params[:redirect_to]) || render(:text => 'Created', :status => 201)
else
redirect_to_widget_if(params[:redirect_to_error], message.errors) || render(:text => message.errors.map{|k,v| "#{k} #{v}"}.join("\n"), :status => 400)
end
end
private
def require_session_user
return if session_user
redirect_to_widget_if(params[:redirect_to_unauthenticated])
end
def load_article
@entity = Article.first :conditions => { :id => params[:id] }
end
def load_article_category
@entity = ArticleCategory.first :conditions => { :partner_key => params[:id] }
end
def load_ratable_entity
@entity = RatableEntity.first :conditions => { :partner_key => params[:id] }
end
end
|
require 'active_record/connection_adapters/abstract_adapter'
module ActiveRecord
class Base
##
# Establishes a connection to the database that's used by all Active Record objects
##
def self.vertica_connection(config)
unless defined? Vertica
begin
require 'vertica'
rescue LoadError
raise "Vertica Gem not installed"
end
end
config = config.symbolize_keys
host = config[:host]
port = config[:port] || 5433
username = config[:username].to_s if config[:username]
password = config[:password].to_s if config[:password]
schema = config[:schema].to_s if config[:schema]
if config.has_key?(:database)
database = config[:database]
else
raise ArgumentError, "No database specified. Missing argument: database."
end
# if config.has_key?(:schema)
# schema = config[:schema]
# else
# raise ArgumentError, "Vertica Schema must be specified."
# end
conn = Vertica.connect({ :user => username,
:password => password,
:host => host,
:port => port,
:database => database,
:schema => schema })
options = [host, username, password, database, port,schema]
ConnectionAdapters::VerticaAdapter.new(conn, options, config)
end
# def self.instantiate(record)
# record.stringify_keys!
# model = find_sti_class(record[inheritance_column]).allocate
# model.init_with('attributes' => record)
# # if ActiveRecord::IdentityMap.enabled? && record_id
# # if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
# # record_id = record_id.to_i
# # end
# # if instance = IdentityMap.get(sti_class, record_id)
# # instance.reinit_with('attributes' => record)
# # else
# # instance = sti_class.allocate.init_with('attributes' => record)
# # IdentityMap.add(instance)
# # end
# # else
# # Kernel.p record
# # end
# model
# end
end
module ConnectionAdapters
class VerticaColumn < Column
end
class VerticaAdapter < AbstractAdapter
ADAPTER_NAME = 'Vertica'.freeze
def adapter_name #:nodoc:
ADAPTER_NAME
end
def initialize(connection, connection_options, config)
super(connection)
@connection_options, @config = connection_options, config
@quoted_column_names, @quoted_table_names = {}, {}
# connect
end
def active?
@connection.opened?
end
# Disconnects from the database if already connected, and establishes a
# new connection with the database.
def reconnect!
@connection.reset_connection
end
def reset
reconnect!
end
# Close the connection.
def disconnect!
@connection.close rescue nil
end
# return raw object
def execute(sql, name=nil)
log(sql,name) do
if block_given?
@connection = ::Vertica.connect(@connection.options)
@connection.query(sql) {|row| yield row }
@connection.close
else
@connection = ::Vertica.connect(@connection.options)
results = @connection.query(sql)
@connection.close
results
end
end
end
def schema_name
@schema ||= @connection.options[:schema]
end
def tables(name = nil) #:nodoc:
sql = "SELECT * FROM tables WHERE table_schema = #{quote_column_name(schema_name)}"
tables = []
execute(sql, name) { |field| tables << field[:table_name] }
tables
end
def columns(table_name, name = nil)#:nodoc:
sql = "SELECT * FROM columns WHERE table_name = #{quote_column_name(table_name)}"
columns = []
execute(sql, name){ |field| columns << VerticaColumn.new(field[:column_name],field[:column_default],field[:data_type],field[:is_nullable])}
columns
end
def select(sql, name = nil, binds = [])
rows = []
@connection = ::Vertica.connect(@connection.options)
@connection.query(sql) {|row| rows << row }
@connection.close
rows
end
def primary_key(table)
''
end
## QUOTING
def quote_column_name(name) #:nodoc:
"'#{name}'"
end
def quote_table_name(name) #:nodoc:
if schema_name.blank?
name
else
"#{schema_name}.#{name}"
end
end
end
end
end
|
require_relative 'spec_helper'
describe Robut::Plugin::Quiz do
subject {
connection = double("connection")
connection.stub_chain(:config, :nick) { "quizmaster" }
connection.stub(:store).and_return(store)
connection.stub(:reply).and_return(nil)
Robut::Plugin::Quiz.new connection
}
let!(:store) { {} }
let(:time) { Time.now }
[
"ask 'Should I continue the presentation?'",
"ask for 3 minutes 'Should I continue the presentation?'",
"ask polar for 3 minutes 'Should I continue the presentation?'",
"ask choice 1 minute 'What do you want for lunch?', 'pizza', 'sandwich', 'salad'",
"ask scale question for 10 minutes 'how much did you like the presentation?', '1..5'"
].each do |question|
it "should match the question: '#{question}'" do
subject.is_a_valid_question?(question).should be_true
end
end
describe "#handle" do
context "when a question is asked" do
it "should be enqueued to be asked" do
subject.should_receive(:enqueue_the_question).with('person',"ask polar 'Should I continue the presentation?' for 3 minutes")
subject.handle time,'person',"@quizmaster ask polar 'Should I continue the presentation?' for 3 minutes"
end
end
context "when currently asking a question" do
context "when the response is not an answer to the question" do
it "should not process response for the question" do
subject.stub(:currently_asking_a_question?).and_return(true)
subject.stub(:is_a_valid_response?).and_return(false)
subject.should_not_receive(:process_response_for_active_question)
subject.handle time,'person',"@quizmaster ask polar for 3 minutes 'Should I continue the presentation?'"
end
end
context "when the response is an answer to the question" do
it "should process response for the question" do
subject.stub(:sent_to_me?).and_return(true)
subject.stub(:currently_asking_a_question?).and_return(true)
subject.stub(:is_a_valid_response?).and_return(true)
subject.should_receive(:process_response_for_active_question)
subject.handle time,'person',"@quizmaster ask polar for 3 minutes 'Should I continue the presentation?'"
end
end
end
end
describe "#process_the_question" do
context "when a polar question is asked" do
it "should find all the components of the question" do
expected_question = Robut::Plugin::Quiz::Polar.new 'person',"ask polar 'Should I continue the presentation?' for 3 minutes"
subject.should_receive(:create_the_question_based_on_type).and_return(expected_question)
subject.should_receive(:set_current_question).with(expected_question,'3')
subject.process_the_question 'person',"ask polar for 3 minutes 'Should I continue the presentation?'"
end
end
end
describe "#set_current_question" do
before :each do
subject.stub(:sleep)
end
let(:question) do
Robut::Plugin::Quiz::Polar.new 'person',"'Should I continue the presentation?'"
end
it "should place robut in the mode where it is asking a question" do
subject.should_receive(:start_accepting_responses_for_this_question)
subject.set_current_question(question,'3')
end
it "should ask the question" do
question.should_receive(:ask)
subject.set_current_question(question,'3')
end
it "should wait until the question time is done" do
subject.should_receive(:sleep).with(180)
subject.set_current_question(question,'3')
end
context "when it is done waiting" do
it "should take robut out of the mdoe where it is asking a question" do
subject.should_receive(:stop_accepting_responses_for_this_question)
subject.set_current_question(question,'3')
end
it "should process the results for the question" do
question.should_receive(:results)
subject.set_current_question(question,'3')
end
end
end
end |
unless String.respond_to?(:underscore)
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
end
unless Hash.respond_to?(:deep_merge)
class ::Hash
def deep_merge(second)
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
self.merge(second, &merger)
end
def deep_merge!(second)
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
self.merge!(second, &merger)
end
end
end
|
json.array!(@matrix_entries) do |matrix_entry|
json.extract! matrix_entry, :id, :browser_reader_id, :renderer_id, :format_id, :platform_id, :assistive_technology_id
json.url matrix_entry_url(matrix_entry, format: :json)
end
|
require "spec_helper"
#TODO -> rspecs missing
describe Spree::Payment do
before(:each) do
@payment = create(:payment_with_loyalty_points)
end
describe 'notify_paid_order' do
context "all payments completed" do
before :each do
@payment.stub(:all_payments_completed?).and_return(true)
end
it "should change paid_at in order" do
expect {
@payment.notify_paid_order
}.to change{ @payment.order.paid_at }
end
end
context "all payments not completed" do
before :each do
@payment.stub(:all_payments_completed?).and_return(false)
end
it "should change paid_at in order" do
expect {
@payment.notify_paid_order
}.to_not change{ @payment.order.paid_at }
end
end
end
#TODO -> Test state_not scope separately.
describe 'all_payments_completed?' do
let (:payments) { create_list(:payment_with_loyalty_points, 5, state: "completed") }
context "all payments complete" do
before :each do
order = create(:order_with_loyalty_points)
@payment.order = order
order.payments = payments
end
it "should return true" do
@payment.all_payments_completed?.should eq(true)
end
end
context "one of the payments incomplete" do
before :each do
order = create(:order_with_loyalty_points)
@payment.order = order
payments.first.state = "void"
order.payments = payments
end
it "should return true" do
@payment.all_payments_completed?.should eq(false)
end
end
end
end
|
require 'active_support/concern'
require 'active_support/core_ext/module/delegation'
module SpecHelpers
module LoggerHelpers
extend ActiveSupport::Concern
included do
attr_reader :default_logger, :use_logger
around :each do |example|
@default_logger = Circuit.logger
if clean_logger?
Circuit.logger = nil
elsif !default_logger?
@logger_sio = StringIO.new
Circuit.logger = Logger.new(@logger_sio)
end
example.run
if clean_logger?
clean_logger!(false)
elsif !default_logger?
@logger_sio.close
@logger_sio = nil
end
Circuit.logger = @default_logger
end
end
def use_logger!(key)
@use_logger = (key ? key.to_sym : nil)
end
def use_logger?(key)
@use_logger == key.to_sym
end
def clean_logger!(val=true)
use_logger!(val ? :clean : false)
end
def clean_logger?() use_logger?(:clean); end
def default_logger!(val=true)
use_logger!(val ? :default : false)
end
def default_logger?() use_logger?(:default); end
def logger_output
raise "Clean logger used" if clean_logger?
raise "Default logger used" if default_logger?
@logger_sio.string
end
end
end
|
#!/run/current-system/sw/bin/vpsadmin-api-ruby
# Export all payments that took place in selected years, or affected memberships
# in those years.
#
# Usage: $0 <year...>
#
require 'vpsadmin'
require 'csv'
require 'time'
if ARGV.length < 1
warn "Usage: #{$0} <year...>"
exit(false)
end
# Necessary to load plugins
VpsAdmin::API.default
years = ARGV.map(&:to_i)
csv = CSV.new(
STDOUT,
col_sep: ';',
headers: %w(payment_id user_id amount currency from_date to_date accounted_at),
write_headers: true,
)
::UserPayment.includes(:incoming_payment).where(
"YEAR(#{UserPayment.table_name}.created_at) IN (?) "+
"OR YEAR(#{UserPayment.table_name}.from_date) IN (?) "+
"OR YEAR(#{UserPayment.table_name}.to_date) IN (?)",
years, years, years
).order("#{UserPayment.table_name}.created_at").each do |payment|
if payment.incoming_payment
amount = payment.incoming_payment.amount
currency = payment.incoming_payment.currency
else
amount = payment.amount
currency = 'CZK'
end
csv << [
payment.id,
payment.user_id,
amount,
currency,
payment.from_date.iso8601,
payment.to_date.iso8601,
payment.created_at.iso8601,
]
end
|
module GTK
class Printer
attr_accessor :tempfile
def initialize
@tempfile = Tempfile.new(Time.now.to_s)
end
def pdf_content; File.read(tempfile); end
def export(base_url, name)
File.open(File.join(base_url, name), 'w+'){ |f| f.write pdf_content }
end
def temp_path; tempfile.path; end
def delete_pdf; tempfile.delete; end
end
end
|
class User::BaseController < ApplicationController
before_action :authenticate_user!
layout 'user/layouts/application'
end
|
require 'dotenv'
require 'slop'
require 'pry'
require 'aws-sdk'
class DeathToLcs
VERSION='0.1'
def self.run
load_env
opts = parse_args
puts '-------------------------------------'
puts 'Launch Configurations deleted'
puts '-------------------------------------'
puts lc_deleter.delete_unused_lcs
end
def self.lc_deleter
LcDeleter.new
end
def self.parse_args
Slop.parse do |o|
o.on '--dry', 'dry run' do
puts '-------------------------------------'
puts 'Launch Configurations to be deleted'
puts '-------------------------------------'
puts lc_deleter.unused_lc_names
exit
end
o.on '--version', 'print the version' do
puts DeathToLcs::VERSION
exit
end
end
end
def self.load_env
Dotenv.load
end
end
class LcDeleter
def unused_lc_names
inactive_lcs.collect do |lc|
lc.launch_configuration_name
end
end
def delete_unused_lcs
inactive_lcs.collect do |lc|
aws_asg_wrapper.delete_lc lc.launch_configuration_name
lc.launch_configuration_name
end
end
def active_lc_names
lc_names_associated_with_asg_instances + lc_names_associated_with_asgs
end
def lc_names_associated_with_asg_instances
aws_asg_wrapper.all_asg_instances.collect do |instance|
instance.launch_configuration_name
end
end
def lc_names_associated_with_asgs
aws_asg_wrapper.all_asgs.collect do |asg|
asg.launch_configuration_name
end
end
def inactive_lcs
all_lcs.collect do |lc|
lc unless active_lc_names.include?(lc.launch_configuration_name)
end.compact
end
def all_lcs
aws_asg_wrapper.all_lcs
end
def aws_asg_wrapper
AwsAutoScalingWrapper.new
end
end
class AwsAutoScalingWrapper
def delete_lc lc_name
client.delete_launch_configuration({
launch_configuration_name: lc_name,
})
end
def all_lcs
results = []
while true
result = client.describe_launch_configurations
results = results + result.launch_configurations
if result.last_page?
break
else
result.next_page
end
end
results
end
def all_asg_instances
results = []
while true
result = client.describe_auto_scaling_instances
results = results + result.auto_scaling_instances
if result.last_page?
break
else
result.next_page
end
end
results
end
def all_asgs
results = []
while true
result = client.describe_auto_scaling_groups
results = results + result.auto_scaling_groups
if result.last_page?
break
else
result.next_page
end
end
results
end
private
def client
Aws::AutoScaling::Client.new
end
end
DeathToLcs.run |
require 'rails_helper'
RSpec.describe 'Merchant Item Index', type: :feature do
before :each do
@merchant = create(:merchant)
@items = create_list(:item,2, user: @merchant)
@inactive_item = create(:inactive_item, user: @merchant)
@new_item = attributes_for(:item)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@merchant)
end
it 'can add a new item' do
visit dashboard_items_path
click_link "Add Item"
expect(current_path).to eq(new_dashboard_item_path)
fill_in "Name", with:@new_item[:name]
fill_in "Description", with:@new_item[:description]
fill_in "Image URL", with:@new_item[:image_url]
fill_in "Price", with:@new_item[:current_price]
fill_in "Inventory", with:@new_item[:quantity]
click_button "Create Item"
item = Item.last
expect(page).to have_content("#{item.name} Saved")
expect(item.name).to eq(@new_item[:name])
expect(item.description).to eq(@new_item[:description])
expect(item.image_url).to eq(@new_item[:image_url])
expect(item.current_price).to eq(@new_item[:current_price])
expect(item.quantity).to eq(@new_item[:quantity])
expect(item.enabled).to eq(true)
expect(item.merchant_id).to eq(@merchant.id)
end
describe 'validates information for new items, returning to form with message if incorrect' do
it 'can leave the url blank' do
visit new_dashboard_item_path
fill_in "Name", with:@new_item[:name]
fill_in "Description", with:@new_item[:description]
fill_in "Price", with:@new_item[:current_price]
fill_in "Inventory", with:@new_item[:quantity]
click_button "Create Item"
item = Item.last
expect(item.image_url).to eq('http://www.spore.com/static/image/500/404/515/500404515704_lrg.png')
expect(page).to have_xpath("//img[@src='http://www.spore.com/static/image/500/404/515/500404515704_lrg.png']")
end
it 'cannot have a quantity of less than 0' do
visit new_dashboard_item_path
fill_in "Name", with:@new_item[:name]
fill_in "Description", with:@new_item[:description]
fill_in "Image URL", with:@new_item[:image_url]
fill_in "Price", with:@new_item[:current_price]
click_button "Create Item"
expect(page).to have_content("Quantity can't be blank")
fill_in "Inventory", with:-10
click_button "Create Item"
expect(page).to have_content("Quantity must be greater than or equal to 0")
# Below, this is a kludge-y test, form does not allow input of floats
# So this is very sad-path of a forced input
fill_in "Inventory", with:1.5
expect(page).to have_content("Quantity must be greater than or equal to 0")
fill_in "Inventory", with: 5
click_button "Create Item"
expect(current_path).to eq(dashboard_items_path)
end
it 'must have a price greater than 0.00' do
visit new_dashboard_item_path
fill_in "Name", with:@new_item[:name]
fill_in "Description", with:@new_item[:description]
fill_in "Image URL", with:@new_item[:image_url]
fill_in "Inventory", with:@new_item[:quantity]
click_button "Create Item"
expect(page).to have_content("Price can't be blank")
fill_in "Price", with:0.00
click_button "Create Item"
expect(page).to have_content("Price must be greater than 0")
fill_in "Price", with: -1.00
expect(page).to have_content("Price must be greater than 0")
click_button "Create Item"
fill_in "Price", with: 1.00
expect(current_path).to eq(dashboard_items_path)
end
it 'must have name' do
visit new_dashboard_item_path
fill_in "Description", with:@new_item[:description]
fill_in "Image URL", with:@new_item[:image_url]
fill_in "Price", with:@new_item[:current_price]
fill_in "Inventory", with:@new_item[:quantity]
click_button "Create Item"
expect(page).to have_content("Name can't be blank")
end
it 'must have description' do
visit new_dashboard_item_path
fill_in "Name", with:@new_item[:name]
fill_in "Image URL", with:@new_item[:image_url]
fill_in "Price", with:@new_item[:current_price]
fill_in "Inventory", with:@new_item[:quantity]
click_button "Create Item"
expect(page).to have_content("Description can't be blank")
end
end
end
|
class AddOnionstyleOnioncountToBurgers < ActiveRecord::Migration
def change
add_column :burgers, :onionstyle, :text
add_column :burgers, :onioncount, :text
end
end
|
class Customer < ActiveRecord::Base
attr_accessible :address, :first_name, :last_name, :phone
has_many :sales
def name
first_name + ' ' + last_name
end
end
|
class MainController < ApplicationController
def index
json = CollectionJSON.generate_for(Routes['main#index']) do |builder|
builder.add_link(Routes['tasks#index'], 'tasks')
end.to_json
respond_to do |format|
format.json { render :json => json }
format.html { render :json => json }
end
end
end
|
class MedicalQuestion < ActiveRecord::Base
validates :question, :disease, presence: true
validates :question, :disease, length: { maximum: 100 }
has_many :user_medical_questions
end
|
class CreatePermissions < ActiveRecord::Migration[5.2]
def change
create_table :permissions, id: :uuid do |t|
t.uuid :granted_to
t.uuid :given_by
t.hstore :permissions
t.timestamps
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.