text stringlengths 10 2.61M |
|---|
class PollsController < ApplicationController
before_action :set_poll, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:index, :show, :create, :new, :edit, :update]
#before_action :logged_in_user
# GET /polls
# GET /polls.json
def index
@polls = Poll.paginate(page: params[:page], :per_page => 10)
end
# GET /polls/1
# GET /polls/1.json
def show
end
# GET /polls/new
def new
@poll = Poll.new
@poll.questions.build.answerchoices.build
end
# GET /polls/1/edit
def edit
end
# POST /polls
# POST /polls.json
def create
puts "polls_create START"
@poll = Poll.new(poll_params)
puts @poll.inspect
puts @poll.questions.inspect
respond_to do |format|
if @poll.save
format.html { redirect_to @poll, notice: 'Poll was successfully created.' }
format.json { render :show, status: :created, location: @poll }
else
format.html { render :new }
format.json { render json: @poll.errors, status: :unprocessable_entity }
end
end
puts "polls_create END"
end
# PATCH/PUT /polls/1
# PATCH/PUT /polls/1.json
def update
respond_to do |format|
if @poll.update(poll_params)
format.html { redirect_to @poll, notice: 'Poll was successfully updated.' }
format.json { render :show, status: :ok, location: @poll }
else
format.html { render :edit }
format.json { render json: @poll.errors, status: :unprocessable_entity }
end
end
end
# DELETE /polls/1
# DELETE /polls/1.json
def destroy
@poll.destroy
respond_to do |format|
format.html { redirect_to polls_url, notice: 'Poll was successfully destroyed.' }
format.json { head :no_content }
end
end
def pvote
puts "pvote START"
puts params
puts params[:poll][:user_id]
@poll = Poll.find(params[:id])
if params[:choices]
params[:choices].each do |key, value|
puts "creating userchoice with user_id #{params[:poll][:user_id]} and answerchoice_id #{value}"
@userchoice = Userchoice.new({"answerchoice_id"=>value, "user_id"=>params[:poll][:user_id]})
if @userchoice.save
puts "success!"
#format.json { render :show, status: :ok, location: @poll }
end
end
redirect_to @poll, notice: 'Thank you for voting!'
else
redirect_to @poll, notice: "You didn't select any choices!"
end
puts "pvote END"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_poll
@poll = Poll.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def poll_params
params.require(:poll).permit(:id, :title, :user_id, :questions_attributes => [:id, :text, :_destroy, :answerchoices_attributes => [:id, :content, :_destroy]])
end
end
|
module Antlr4::Runtime
class CharStreams
DEFAULT_BUFFER_SIZE = 4096
def self.from_string(s, source_name)
CodePointCharStream.new(0, s.length, source_name, s.codepoints)
end
end
end
|
module Paysafe
class Configuration
API_TEST = 'https://api.test.paysafe.com'
API_LIVE = 'https://api.paysafe.com'
attr_reader :account_number, :api_base, :api_key, :api_secret, :test_mode, :timeout
def initialize(**options)
@test_mode = true
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
@api_base = test_mode ? API_TEST : API_LIVE
end
end
end
|
require_relative 'tic_tac_toe'
class TicTacToeNode
attr_reader :board, :next_mover_mark, :prev_move_pos, :children
def initialize(board, next_mover_mark, prev_move_pos = nil)
@board = board
@next_mover_mark = next_mover_mark
@prev_move_pos = prev_move_pos
end
def losing_node?(evaluator)
p board.won?
return false if evaluator != @next_mover_mark && @board.won?
true
end
def winning_node?(evaluator)
end
# This method generates an array of all moves that can be made after
# the current move.
def children
@children = []
checked_spaces = []
@board.rows.each_with_index do |row, i|
row.each_with_index do |space, j|
dup_board = board.dup
mark = :x
if @next_mover_mark == :x
mark = :o
end
if space.nil? && !checked_spaces.include?([i,j])
checked_spaces << [i,j]
dup_board.rows[i][j] = mark
@prev_move_pos = [i,j]
child = TicTacToeNode.new(dup_board, mark, @prev_move_pos)
@children << child
end
end
end
@children
end
end
|
ActiveAdmin.register PollutionReport do
actions :index
filter :status, as: :select, collection: PollutionReport.statuses
preserve_default_filters!
member_action :archive, method: :put do
status = PollutionReport.statuses[:archived]
resource.update(status: status)
redirect_to admin_pollution_reports_path, notice: "Archived!"
end
member_action :restore, method: :put do
status = PollutionReport.statuses[:active]
resource.update(status: status)
redirect_to admin_pollution_reports_path, notice: "Restored!"
end
index do
PollutionReport.column_names.each do |c|
column c.to_sym
end
column :actions do |pollution_report|
if pollution_report.active?
link_to "archive", archive_admin_pollution_report_path(pollution_report), method: :put
else
link_to "restore", restore_admin_pollution_report_path(pollution_report), method: :put
end
end
end
end
|
class List < Hyperloop::Router::Component
render do
SECTION(class: 'main') do
INPUT(id: "toggle-all", class:"toggle-all", type:"checkbox")
LABEL(htmlFor: "toggle-all") { 'Mark all as complete' }
UL(class: 'todo-list') do
scope = match.params[:scope]
scope = :all if scope.blank?
Todo.send(scope).each do |item|
ListItem(item: item)
end
end
end
end
end |
require 'spec_helper'
describe HomeController do
describe 'GET homepage' do
render_views
let(:slideshow_post) { create :post, post_type: Post::POST_TYPES[:slideshow] }
let(:image_post) { create :post, post_type: Post::POST_TYPES[:image] }
let(:mobile_post) { create :post, post_type: Post::POST_TYPES[:gallery] }
let(:video_post) { create :post, post_type: Post::POST_TYPES[:video] }
it "gets the most recently published billboard" do
billboard1 = create :billboard, published_at: 1.day.ago
billboard2 = create :billboard, published_at: 1.day.from_now
billboard3 = create :billboard, status: Billboard::STATUS[:draft], published_at: 5.days.from_now
get :homepage
assigns(:billboard).should eq billboard2
end
it "renders some recent posts" do
published_posts = create_list :post, 1
unpublished_posts = create_list :post, 1, status: Post::STATUS[:draft]
get :homepage
assigns(:recent_posts).to_a.should eq published_posts
end
it "doesn't include any posts from the billboard in the recent posts" do
billboard = create :billboard
billboard_post = create :post
other_posts = create_list :post, 2
get :homepage
recent_posts = assigns(:recent_posts).to_a
recent_posts.should include billboard_post
recent_posts.size.should eq 3
billboard.posts << billboard_post
get :homepage
recent_posts = assigns(:recent_posts).to_a
recent_posts.should_not include billboard_post
recent_posts.size.should eq 2
end
it "assigns the buckets matching the requested keys" do
midway_bucket = create :bucket, key: HomeController::MIDWAY_BUCKET_KEY
right_bar_bucket = create :bucket, key: HomeController::RIGHT_BAR_BUCKET_KEY
get :homepage
assigns(:midway_bucket).should eq midway_bucket
assigns(:right_bar_bucket).should eq right_bar_bucket
end
context 'with layout_1' do
it "renders properly" do
billboard = create :billboard, layout: 1
billboard.posts = [slideshow_post, video_post, mobile_post]
get :homepage
response.should render_template(partial: "billboards/_layout_1")
response.should render_template(partial: "billboards/components/_slideshow")
response.should render_template(partial: "billboards/components/_video")
response.should render_template(partial: "billboards/components/_mobile")
end
end
context 'with layout_2' do
it "renders properly" do
billboard = create :billboard, layout: 2
billboard.posts = [slideshow_post, image_post, image_post, image_post]
get :homepage
response.should render_template(partial: "billboards/_layout_2")
response.should render_template(partial: "billboards/components/_slideshow")
response.should render_template(partial: "billboards/components/_image")
end
end
context 'with layout_3' do
it "renders properly" do
billboard = create :billboard, layout: 3
billboard.posts = [slideshow_post, video_post, video_post]
get :homepage
response.should render_template(partial: "billboards/_layout_3")
response.should render_template(partial: "billboards/components/_slideshow")
response.should render_template(partial: "billboards/components/_video")
end
end
context 'with layout_4' do
it "renders properly" do
billboard = create :billboard, layout: 4
billboard.posts = [video_post, mobile_post, image_post]
get :homepage
response.should render_template(partial: "billboards/_layout_4")
response.should render_template(partial: "billboards/components/_video")
response.should render_template(partial: "billboards/components/_mobile")
response.should render_template(partial: "billboards/components/_image")
end
end
context 'with layout_5' do
it "renders properly" do
billboard = create :billboard, layout: 5
billboard.posts = [mobile_post, video_post, image_post, image_post, image_post]
get :homepage
response.should render_template(partial: "billboards/_layout_5")
response.should render_template(partial: "billboards/components/_video")
response.should render_template(partial: "billboards/components/_mobile")
response.should render_template(partial: "billboards/components/_image")
end
end
context 'with layout_6' do
it "renders properly" do
billboard = create :billboard, layout: 6
billboard.posts = [mobile_post, image_post, video_post, video_post]
get :homepage
response.should render_template(partial: "billboards/_layout_6")
response.should render_template(partial: "billboards/components/_mobile")
response.should render_template(partial: "billboards/components/_image")
response.should render_template(partial: "billboards/components/_video")
end
end
context 'with layout_7' do
it "renders properly" do
billboard = create :billboard, layout: 7
billboard.posts = [image_post, mobile_post, video_post, video_post]
get :homepage
response.should render_template(partial: "billboards/_layout_7")
response.should render_template(partial: "billboards/components/_image")
response.should render_template(partial: "billboards/components/_mobile")
response.should render_template(partial: "billboards/components/_video")
end
end
context 'with layout_8' do
it "renders properly" do
billboard = create :billboard, layout: 8
billboard.posts = [video_post]
get :homepage
response.should render_template(partial: "billboards/_layout_8")
response.should render_template(partial: "billboards/components/_episode")
end
end
end
end
|
Pod::Spec.new do |s|
s.name = 'TencentOpenAPI'
s.version = '2.3'
s.summary = 'Tencent Open API'
s.homepage = 'http://wiki.open.qq.com/wiki/IOS_API%E8%B0%83%E7%94%A8%E8%AF%B4%E6%98%8E"
s.ios.deployment_target = '3.0'
s.source = { :git => "https://github.com/amoblin/easyPods.git", :branch => "master" }
s.ios.vendored_frameworks = 'TencentOpenAPI/TencentOpenAPI.framework'
s.resource = "TencentOpenAPI/TencentOpenApi_IOS_Bundle.bundle"
s.frameworks = 'TencentOpenAPI', 'Security', 'SystemConfiguration', 'CoreGraphics', 'CoreTelephony'
s.libraries = 'iconv', 'sqlite3', 'stdc++', 'z'
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/TencentOpenAPI/TencentOpenAPI"' }
end
|
require "sinatra/gyazo/version"
require "sinatra"
require 'fileutils'
require 'pathname'
require 'digest/md5'
require 'sdbm'
module Sinatra
module Gyazo
module Helpers
def image_path(image_dir, data, ext)
hash = Digest::MD5.hexdigest(data + Time.now.to_s).to_s
year = Date.today.year
Pathname.new("#{image_dir}/#{year}/#{section(hash)}/#{hash}#{ext}")
end
private
def section(hash)
hash[0..1]
end
end
class << self
def registered(app)
app.helpers Gyazo::Helpers
app.set :dbm_path, 'db/id'
app.set :image_dir, 'images'
app.post '/gyazo' do
data = params[:imagedata][:tempfile].read
ext = params[:imagedata][:type] == 'image/gif' ? '.gif' : '.png'
begin
image_path = image_path(settings.image_dir, data, ext)
end while File.exists?("#{settings.public_folder}/#{image_path}")
directory = "#{settings.public_folder}/#{image_path.dirname}"
FileUtils.mkdir_p(directory, mode: 0755)
File.open("#{settings.public_folder}/#{image_path}", 'w'){|f| f.write(data)}
id = params[:id]
unless id && id != ""
id = Digest::MD5.hexdigest(request.ip + Time.now.to_s)
headers "X-Gyazo-Id" => id
end
dbm = SDBM.open("#{settings.root}/#{settings.dbm_path}", 0644)
dbm[image_path.to_s] = id
dbm.close
"#{request.scheme}://#{request.host_with_port}/#{image_path}"
end
end
end
end
end
|
require 'mongoid'
require 'json'
require 'sinatra/reloader' if development?
## TODO : Develop a valid token algorithm
VALID_KEY = "KH6R643B72V085P2TRK0"
class ExceptionResource < Sinatra::Base
set :methodoverride, true
# Loading mongodb with yaml configuration
Mongoid.load!("mongoid.yml", :development)
# Models
class Project
include Mongoid::Document
field :project_code, type: String
field :name, type: String
field :description, type: String
field :logo, type: String
field :external_order, type: Integer
end
class Exception
include Mongoid::Document
field :project_code, type: String
field :friendly, type: String
field :thrown_date, type: DateTime
field :message, type: String
field :class_name, type: String
field :backtrace, type: String
end
helpers do
# Checks the query string or
# post params for valid key
def valid_key? key
key == VALID_KEY
end
# Returns a JSON object with status
# code and explanation in it
def json_status code, reason
{
:status => code,
:reason => reason
}.to_json
end
# Returns a JSON object with status
# code and data in it
def json_result code, result
{
:status => code,
:data => result
}.to_json
end
# Helper method for setting the
# sent form attributes
def accept_params params, *fields
ps = { }
fields.each do |name|
ps[name] = params[name] if params[name]
end
ps
end
end
# Check the key before every route
before do
error 401 unless valid_key?(params[:token])
end
## GET : '/'
get '/' do
json_status 404, "No such route has been found."
end
## POST : '/projects'
post '/projects' do
content_type :json
exceptions = Project.all
json_result 200, exceptions
end
## Post a new project
## POST : '/projects/new'
post '/projects/new' do
content_type :json
create_params = accept_params(params, :project_code, :name, :description, :logo, :external_order)
project = Project.new(create_params)
if project.save
json_result 200, project
else
json_result 400, project.errors.to_hash
end
end
## Return a project detail
## POST : '/projects/detail'
post '/projects/detail' do
content_type :json
project = Project.find(params[:id])
json_result 200, project
end
## Return all exceptions
## POST : '/exceptions?token=123'
post '/exceptions' do
content_type :json
exceptions = Exception.all.desc(:thrown_date)
json_result 200, exceptions
end
## Return a exception detail
## POST : '/exceptions/detail'
post '/exceptions/detail' do
content_type :json
exception = Exception.find(params[:id])
json_result 200, exception
end
## Return all the exceptions limited
## POST : '/exceptions/{limit}?token=123'
post '/exceptions/:limit' do
content_type :json
exceptions = Exception.all.desc(:thrown_date)
.limit(params[:limit])
json_result 200, exceptions
end
## Return all exceptions by project
## POST : '/exceptions/{project-code}?token=123'
post '/exceptions/:pcode' do
content_type :json
exceptions = Exception.where(project_code: params[:pcode])
.desc(:thrown_date)
json_result 200, exceptions
end
## Return all exceptions by project
## POST : '/exceptions/{project-code}/{limit}?token=123'
post '/exceptions/:pcode/:limit' do
content_type :json
exceptions = Exception.where(project_code: params[:pcode])
.desc(:thrown_date)
.limit(params[:limit])
json_result 200, exceptions
end
## Post a new exception
## POST : '/exception/new'
post '/exception/new' do
content_type :json
create_params = accept_params(params, :project_code, :friendly, :thrown_date, :message, :class_name, :backtrace)
exception = Exception.new(create_params)
if exception.save
json_result 200, exception
else
json_result 400, exception.errors.to_hash
end
end
get '*' do
status 404
end
post '*' do
status 404
end
put '*' do
status 404
end
delete '*' do
status 404
end
not_found do
json_status 404, "No such route has been found."
end
error do
json_status 500, "Internal Server Error : #{env['sinatra.error'].message}"
end
end
|
# frozen_string_literal: true
class Api::V1::AccountActivationsController < ApplicationController
include ErrorMessageHelper
include ResponseHelper
include ResponseStatus
include ErrorKeys
def update
user = User.find_by(email: user_params[:email])
if user && !user.activated? && user.authenticated?(:activation, user_params[:token])
user.activate
render json: generate_response(SUCCESS, message: 'activated')
else
message = 'invalid activation link'
key = ErrorKeys::LINK
error_response(key: key, message: message)
end
end
private
def user_params
return {} unless params[:value]
params.require(:value).permit(:email, :token)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
ActiveRecord::Base.transaction do
#Level Generator
def level_generator(order, grid_width, grid_height, cookies = 0)
lvl = Level.create!(level_order: order,
title: "Level #{order}",
grid_width: grid_width,
grid_height: grid_height,
cookies: cookies )
s_board = ScoreBoard.create!(level_id: lvl.id)
3.times do |n|
Score.create!(score_board_id: s_board.id, time: (n + 1 * 60))
end
end
#Level 1
level_generator(1, 1, 1)
#Level 2
level_generator(2, 10, 1)
#Level 3
level_generator(3, 10, 10)
#Level 4
level_generator(4, 10, 10, 5)
end |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module HP
module Cloud
class CLI < Thor
map %w(containers:rm containers:delete containers:del) => 'containers:remove'
desc "containers:remove name [name ...]", "Remove a containers."
long_desc <<-DESC
Remove one or more containers. By default this command removes a container if it is empty, but you may use the `--force` flag to delete non-empty containers. Be careful with this flag or you could have a really bad day.
Examples:
hpcloud containers:remove :my_container # Delete 'my_container' (if empty)
hpcloud containers:remove :tainer1 :tainer2 # Delete 'tainer1' and 'tainer2' (if empty)
hpcloud containers:remove :my_container --force # Delete `my container` (regardless of contents)
hpcloud containers:remove :my_container -z region-a.geo-1 # Delete the container `my_container` for availability zone 'region-a.geo-1`
Aliases: containers:rm, containers:delete, containers:del
DESC
method_option :force, :default => false,
:type => :boolean, :aliases => '-f',
:desc => 'Force removal of non-empty containers.'
CLI.add_common_options
define_method "containers:remove" do |name, *names|
cli_command(options) {
names = [name] + names
names.each { |name|
resource = ResourceFactory.create(Connection.instance.storage, name)
if resource.is_container?
if resource.remove(options.force)
@log.display "Removed container '#{name}'."
else
@log.error resource.cstatus
end
else
@log.error "The specified object is not a container: #{name}", :incorrect_usage
end
}
}
end
end
end
end
|
class Section < ApplicationRecord
attr_accessor :add_field
belongs_to :application_form, optional: true
belongs_to :recommender_form, optional: true
has_many :fields, -> { order(:order) }, dependent: :destroy, autosave: true
validates :title, uniqueness: { scope: :application_form_id }
accepts_nested_attributes_for :fields, allow_destroy: true
def handle_add_field
return if Field::TYPES.values.exclude?(add_field)
order = (self.fields.to_a.map(&:order).max || 0) + 1
klass = add_field.constantize
field = klass.new(order: order)
self.fields << field
end
def title_key
title.downcase.tr(' ', '_')
end
def fields_json_config
fields.each_with_object({}) do |field, hash|
hash.merge!(field.json_config)
end
end
def required_fields
fields.each_with_object([]) do |field, array|
array << field.title_key if field.required
end
end
def build_json_schema
{
title_key => {
title: title,
type: :object,
required: required_fields,
properties: fields_json_config
}.reject { |_k, v| v.blank? }
}
end
def build_ui_schema
fields.each_with_object({}) do |field, hash|
hash.merge!(field.ui_config)
end
end
end
|
class HashGenerator
def initialize(string_to_hash)
@string_to_hash = string_to_hash
end
def hash_md5
Digest::MD5.hexdigest @string_to_hash
end
def hash_sha1
Digest::SHA1.hexdigest @string_to_hash
end
end |
# encoding: utf-8
require 'cgi'
require "open3"
require 'fileutils'
require 'ap'
require 'digest/md5'
require 'string_cleaner'
include Open3
class CURL
AGENT_ALIASES = {
'Windows IE 6' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Windows IE 7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Windows Mozilla' => 'Mozilla/5.0 Windows; U; Windows NT 5.0; en-US; rv:1.4b Gecko/20030516 Mozilla Firebird/0.6',
'Windows Mozilla 2' => 'Mozilla/5.0 Windows; U; Windows NT 5.0; ru-US; rv:1.4b Gecko/20030516',
'Windows Mozilla 3' => 'Mozilla/5.0 Windows; U; Windows NT 5.0; en-UK; rv:1.4b Gecko/20060516',
'Mac Safari' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.3',
'Mac FireFox' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3',
'Mac Mozilla' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401',
'Linux Mozilla' => 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624',
'Linux Konqueror' => 'Mozilla/5.0 (compatible; Konqueror/3; Linux)',
'IPhone' => 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3',
'IPhone Vkontakt' => 'VKontakte/1.1.8 CFNetwork/342.1 Darwin/9.4.1',
'Google'=>"Googlebot/2.1 (+http://www.google.com/bot.html)",
"Yahoo-Slurp"=>"Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)"
}
attr_accessor :user_agent
def initialize(keys={})
@socks_hostname = keys[:socks_hostname] ||= false
@cache = ( keys[:cache] ? keys[:cache] : false )
@cache_time = ( keys[:cache_time] ? keys[:cache_time] : 3600*24*1 ) # 1 day cache life
@connect_timeout = keys[:connect_timeout] || 6
@max_time = keys[:max_time] || 8
@retry = keys[:retry] || 1
@cookies_enable = ( keys[:cookies_disable] ? false : true )
@user_agent = AGENT_ALIASES["Google"]#AGENT_ALIASES[AGENT_ALIASES.keys[rand(6)]]
FileUtils.makedirs("/tmp/curl/")
@cookies_file = keys[:cookies] || "/tmp/curl/curl_#{rand}_#{rand}.jar"
# @cookies_file = "/home/ruslan/curl.jar"
#--header "Accept-Encoding: deflate"
# @setup_params = ' --header "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" --header "Accept-Language: en-us,en;q=0.5" --header "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" '
@setup_params = " --connect-timeout #{@connect_timeout} --max-time #{@max_time} --retry #{@retry} --location --compressed --silent -k "
# @setup_params = ' --location --silent '
yield self if block_given?
end
def user_agent_alias=(al)
self.user_agent = AGENT_ALIASES[al] || raise("unknown agent alias")
end
def cookies
@cookies_file
end
def proxy(proxy_uri)
File.open("/tmp/aaaaaaaa.aaa","w"){|file| file.puts "#{Time.now}---"+proxy_uri}
proxy = ( proxy_uri.is_a?(URI) ? proxy_uri : URI.parse("http://#{proxy_uri}") )
@setup_params = "#{@setup_params} --proxy \"#{proxy.host}:#{proxy.port}\" "
@setup_params = "#{@setup_params} --proxy-user \"#{proxy.user}:#{proxy.password}\" " if proxy.user
end
def socks(socks_uri)
socks = ( socks_uri.is_a?(URI) ? socks_uri : URI.parse("http://#{socks_uri}") )
s = @socks_hostname ? "--socks5-hostname" : "--socks5"
@setup_params = "#{@setup_params} #{s} \"#{socks.host}:#{socks.port}\" "
@setup_params = "#{@setup_params} --proxy-user \"#{socks.user}:#{socks.password}\" " if socks.user
@setup_params
end
def self.check(proxy)
out = false
catch_errors(5){
result = `curl --connect-timeout 6 --max-time 8 --silent --socks5 \"#{proxy}\" \"yahoo.com\" `
out = true if result.scan("yahoo").size>0
}
out
end
def debug=(debug=false)
@debug=debug
end
def debug?
@debug
end
def cache_path(url)
"#{@cache}/#{Digest::MD5.hexdigest(url)[0..1]}/#{Digest::MD5.hexdigest(url)[2..3]}/#{Digest::MD5.hexdigest(url)[4..5]}/#{Digest::MD5.hexdigest(url)[6..7]}"
end
def cache_file(url)
cache_path(url)+"/#{Digest::MD5.hexdigest(url)}.html"
end
def get(url, keys={})
ref = keys[:ref] ||= nil
count = keys[:count] ||= 3
encoding = keys[:encoding] ||= "utf-8"
raw = ( keys[:raw]==nil ? false : keys[:raw] )
if @cache
filename = cache_file(url)
unless File.exists?(filename) && (File.exists?(filename) && File.ctime(filename) > Time.now-@cache_time)
FileUtils.mkdir_p(cache_path(url))
result = get_raw(url, {:count=>count, :ref=>ref, :encoding=>encoding} ) #+" --output \"#{filename}\" ")
puts "cache to file '#{filename}'" if @debug
File.open(filename,"w"){|f| f.puts result}
return result
else
puts "read from cache file '#{filename}'" if @debug
return open(filename).read
end
else
return get_raw(url, {:count=>count , :ref=>ref, :encoding=>encoding, :raw=>raw})
end
end
def get_raw(url, keys={})
ref = keys[:ref] ||= nil
count = keys[:count] ||= 3
encoding = keys[:encoding] ||= "utf-8"
raw = ( keys[:raw]==nil ? false : keys[:raw] )
cmd = "curl #{cookies_store} #{browser_type} #{@setup_params} #{ref} \"#{url}\" "
if @debug
puts cmd.red
end
result = open_pipe(cmd)
if result.to_s.strip.size == 0
puts "empty result, left #{count} try".yellow if @debug
count -= 1
result = self.get(url,count) if count > 0
end
# result.force_encoding(encoding)
if raw
return result
else
return ( encoding=="utf-8" ? result.clean : Iconv.new("UTF-8", "WINDOWS-1251").iconv(result) )
end
end
# формат данных для поста
# data = { "subm"=>"1",
# "sid"=>cap.split("=").last,
# "country"=>"1"
# }
def post(url,post_data, ref = nil,count=5, header = " --header \"Content-Type: application/x-www-form-urlencoded\" " )
#header = " --header \"Content-Type: application/x-www-form-urlencoded\" "
post_q = '--data "'
post_data.each do |key,val|
if key
post_q += "#{key}=#{URI.escape(CGI.escape(val.to_s),'.')}&" unless key == 'IDontAgreeBtn'
end
end
post_q += '"'
post_q.gsub!('&"','"')
cmd = "curl #{cookies_store} #{browser_type} #{post_q} #{header} #{@setup_params} #{ref} \"#{url}\" "
puts cmd.red if @debug
result = open_pipe(cmd)
if result.to_s.strip.size == 0
puts "empty result, left #{count} try".yellow if @debug
count -= 1
result = self.post(url,post_data,nil,count) if count > 0
end
result
end
# формат данных для поста
# data = { "subm"=>"1",
# "sid"=>cap.split("=").last,
# "country"=>"1"
# }
def send(url,post_data, ref = nil,count=5 )
post_q = '' # " -F \"method\"=\"post\" "
post_data.each do |key,val|
pre = ""
if key
key = key.to_s
pre = "@" if key.scan("file").size>0 or key.scan("photo").size>0 or key.scan("@").size>0
key = key.to_s.gsub("@",'')
val = val.to_s
val = val.gsub('"','\"')
post_q += " -F \"#{key}\"=#{pre}\"#{val}\" "
end
end
cmd = "curl #{cookies_store} #{browser_type} #{post_q} #{@setup_params} #{ref} \"#{url}\" "
puts cmd.red if @debug
result = open_pipe(cmd)
#if result.to_s.strip.size == 0
# puts "empty result, left #{count} try".yellow if @debug
# count -= 1
# result = self.send(url,post_data,nil,count) if count > 0
#end
result
end
def get_header(url, location=false)
cmd = "curl #{cookies_store} #{browser_type} #{@setup_params} \"#{url}\" -i "
cmd.gsub!(/\-\-location/,' ') unless location
puts cmd.red if @debug
open_pipe(cmd)
end
def save(url,path="/tmp/curl/curl_#{rand}_#{rand}.jpg")
FileUtils.mkdir_p(File.dirname(path))
cmd = "curl #{cookies_store} #{browser_type} #{@setup_params} \"#{url}\" --output \"#{path}\" "
puts cmd.red if @debug
system(cmd)
path
end
def save!(url,path="/tmp/curl/curl_#{rand}_#{rand}.jpg")
FileUtils.mkdir_p(File.dirname(path))
cmd = "curl #{browser_type} --location --compressed --silent \"#{url}\" --output \"#{path}\" "
puts cmd.red if @debug
system(cmd)
path
end
def clear
File.delete(@cookies_file) if File.exists?(@cookies_file)
end
def init_cook(hash,site='')
file = "# Netscape HTTP Cookie File\n# http://curl.haxx.se/rfc/cookie_spec.html\n# This file was generated by libcurl! Edit at your own risk.\n\n"
hash.each do |key,val|
file += "#{site}\tTRUE\t/\tFALSE\t0\t#{key}\t#{val}\n"
end
File.open(cookies_store.scan(/\"(.+?)\"/).first.first,"w") {|f| f.puts file+"\n" }
file+"\n"
end
private
def open_pipe_old(cmd,kills=true)
result = ''
tmp_path="/tmp/curl/curl_#{rand}_#{rand}.html.tmp"
#cmd += " --output \"#{tmp_path}\" "
system(cmd)
stdin, stdout, stderr = popen3(cmd)
result = stdout
#File.open(tmp_path,"r") { |f| result = f.read }
#File.delete(tmp_path)
result
end
def open_pipe(cmd,kills=true)
result, current_process = '', 0
IO.popen(cmd,"r+") { |pipe|
current_process = pipe.object_id # Saving the PID
result = pipe.read
pipe.close
}
while result.to_s.size==0
sleep 0.5
end
#Process.wait
#Process.kill("KILL", current_process) if kills and current_process.to_i>0
result
end
def browser_type
browser = " --user-agent \"#{@user_agent}\" "
end
def cookies_store
if @cookies_enable
return " --cookie \"#{@cookies_file}\" --cookie-jar \"#{@cookies_file}\" "
else
return " "
end
end
end
|
class GateType < ApplicationRecord
belongs_to :material
validates_presence_of :gate_price
end
|
class AddColumnToPersonalcharge < ActiveRecord::Migration
def self.up
add_column :personalcharges, :charge_date, :date
end
def self.down
end
end
|
# Unlucky Days
=begin
(Understand the Problem)
Problem:
Write a method that returns the number of Friday the 13ths in the year given by an argument.
Inputs: Integer (year)
Outputs: Integer (# of Friday the 13ths in given year)
Questions:
1.
Explicit Rules:
1. You may assume that the year is greater than 1752
2.
Implicit Rules:
1.
2.
Mental Model:
- Create a method that determines and returns the # of Friday the 13ths in the input year
-
(Examples/Test Cases)
friday_13th(2015) == 3
friday_13th(1986) == 1
friday_13th(2019) == 2
(Data Structure)
Integer
(Algorithm)
- Initialize local variable `count` and assign it to 0
-
-
(Code)
=end
require 'date'
def friday_13th(year)
Date.new(year).step(Date.new(year, -1, -1)).select{ |day| day.friday?}.select{ |date| date.mday == 13 }.size
end
p friday_13th(2015) == 3
p friday_13th(1986) == 1
p friday_13th(2019) == 2 |
require 'spec_helper'
describe Spree::User do
before(:each) do
shipping_category = Spree::ShippingCategory.new
shipping_category.save(validate: false)
@user = Spree::User.create! email: 'test@example.com', :password => 'spree123'
@product1 = Spree::Product.create! name: 'product1', price: 100, shipping_category_id: shipping_category.id
@product2 = Spree::Product.create! name: 'product2', price: 100, shipping_category_id: shipping_category.id
favorite = Spree::Favorite.new
favorite.product_id = @product1.id
favorite.user_id = @user.id
favorite.save!
end
it { should have_many(:favorites).dependent(:destroy) }
it { should have_many(:favorite_products).through(:favorites).class_name('Spree::Product') }
describe "has_favorite_product?" do
context "when product in user's favorite products" do
it { @user.has_favorite_product?(@product1.id).should be true }
end
context 'when product is not in users favorite products' do
it { @user.has_favorite_product?(@product2.id).should be false }
end
end
end
|
class Users::RegistrationsController < Devise::RegistrationsController
def success
@email = params[:email].presence || "you"
end
protected
def after_inactive_sign_up_path_for(resource)
flash[:notice] = nil
users_registrations_success_path :email => resource.email
end
end
|
class DownloadsController < ApplicationController
include Sufia::DownloadsControllerBehavior
def show
if datastream.external?
send_file datastream.filename, content_options.merge(disposition: 'attachment')
else
super
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
pizza = Food.create(name: "Pizza", calories: 600, rating: "A")
ice_cream = Food.create(name: "Ice Cream", calories: 190, rating: "A")
tacos = Food.create(name: "Tacos", calories: 300, rating: "A+")
ceviche = Food.create(name: "Ceviche", calories: 10, rating: "A+") |
FactoryGirl.define do
factory :soat do
start_date Date.today
end_date Date.today
premium_value { Faker::Number.number(5) }
fosyga { Faker::Number.number(5) }
runt { Faker::Number.number(3) }
total_value { Faker::Number.number(5) }
pay true
association :user
association :vehicle
end
end
|
# == Schema Information
#
# Table name: workouts
#
# id :integer not null, primary key
# date :string(255)
# duration :integer
# activity :string(255)
# intensity :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Workout < ActiveRecord::Base
attr_accessible :activity, :date, :duration, :intensity
belongs_to :user
validates :user_id, presence: true
validates :date, presence: true
validates :duration, presence: true, :numericality => { :only_integer => true }
validates :activity, presence: true
validates :intensity, presence: true
default_scope order: 'workouts.date ASC'
end
|
def begins_with_r(array)
array.each do |it|
if !it.to_s.start_with?("r")
return false
end
end
return true
end
def contain_a(array)
a_array = []
array.each do |thing|
if thing.include?("a"||"A")
a_array << thing
end
end
a_array
end
def first_wa(array)
first_wa_word = ""
array.find do |it|
if it[0..1] == "wa"
first_wa_word = it
end
end
first_wa_word
end
def remove_non_strings(array)
new_array = []
array.each do |thing|
if thing.is_a?(String)
new_array << thing
end
end
new_array
end
def count_elements(data)
new_hash = {}
data.each do |thing|
if new_hash.has_key?(thing[:name])
new_hash[thing[:name]] += 1
else
new_hash[thing[:name]] = 1
end
end
new_hash.map { |key, value| {:name => key , :count => value} }
end
def merge_data(keys, data)
new_array = []
keys.each do |thing|
thing.each do |lable, value|
data.each do |nested_thing|
nested_thing.each do |key,hash|
if value == key
new_array << thing.merge(hash)
end
end
end
end
end
new_array
end
def find_cool(array)
new_array = []
array.each do |thing|
if thing[:temperature] == "cool"
new_array << thing
end
end
new_array
end
def organize_schools(array)
schools_org = {}
array.each do |name, details|
location = details[:location]
if !schools_org[location]
schools_org[location] = []
end
if !schools_org[location].include?(name)
schools_org[location]<< name
end
end
schools_org
end
|
module Contactable
extend ActiveSupport::Concern
included do
has_one :contact, as: :contactable, dependent: :destroy
has_many :addresses, through: :contact
has_many :phones, through: :contact
has_many :emails, through: :contact
has_many :websites, through: :contact
accepts_nested_attributes_for :contact, :addresses, :phones, :emails, :websites
validates_presence_of :contact
before_validation :ensure_associated_contact
def ensure_associated_contact
build_contact unless contact
end
end
end
|
require_relative '../test_case'
module RackRabbit
class TestSubscriber < TestCase
#--------------------------------------------------------------------------
def test_subscribe_lifecycle
subscriber = build_subscriber
rabbit = subscriber.rabbit
assert_equal(false, rabbit.started?)
assert_equal(false, rabbit.connected?)
subscriber.subscribe
assert_equal(true, rabbit.started?)
assert_equal(true, rabbit.connected?)
subscriber.unsubscribe
assert_equal(false, rabbit.started?)
assert_equal(false, rabbit.connected?)
end
#--------------------------------------------------------------------------
def test_subscribe_options
subscriber = build_subscriber({
queue: QUEUE,
exchange: EXCHANGE,
exchange_type: :fanout,
routing_key: ROUTE,
ack: true
})
rabbit = subscriber.rabbit
subscriber.subscribe
assert_equal({
queue: QUEUE,
exchange: EXCHANGE,
exchange_type: :fanout,
routing_key: ROUTE,
manual_ack: true
}, rabbit.subscribe_options)
end
#--------------------------------------------------------------------------
def test_subscribe_handles_message
subscriber = build_subscriber(:app_id => APP_ID)
message = build_message
rabbit = subscriber.rabbit
prime(subscriber, message)
assert_equal([], rabbit.subscribed_messages, "preconditions")
subscriber.subscribe
assert_equal([message], rabbit.subscribed_messages)
assert_equal([], rabbit.published_messages)
assert_equal([], rabbit.acked_messages)
assert_equal([], rabbit.rejected_messages)
end
#--------------------------------------------------------------------------
def test_handle_message_that_expects_a_reply
subscriber = build_subscriber(:app_id => APP_ID)
message = build_message(:delivery_tag => DELIVERY_TAG, :reply_to => REPLY_TO, :correlation_id => CORRELATION_ID)
rabbit = subscriber.rabbit
prime(subscriber, message)
subscriber.subscribe
assert_equal([message], rabbit.subscribed_messages)
assert_equal([], rabbit.acked_messages)
assert_equal([], rabbit.rejected_messages)
assert_equal(1, rabbit.published_messages.length)
assert_equal(APP_ID, rabbit.published_messages[0][:app_id])
assert_equal(REPLY_TO, rabbit.published_messages[0][:routing_key])
assert_equal(CORRELATION_ID, rabbit.published_messages[0][:correlation_id])
assert_equal(200, rabbit.published_messages[0][:headers][RackRabbit::HEADER::STATUS])
assert_equal("ok", rabbit.published_messages[0][:body])
end
#--------------------------------------------------------------------------
def test_successful_message_is_acked
rabbit = build_rabbit
subscriber = build_subscriber(:ack => true, :rabbit => rabbit)
message = build_message(:delivery_tag => DELIVERY_TAG, :rabbit => rabbit)
prime(subscriber, message)
subscriber.subscribe
assert_equal([message], rabbit.subscribed_messages)
assert_equal([], rabbit.published_messages)
assert_equal([DELIVERY_TAG], rabbit.acked_messages)
assert_equal([], rabbit.rejected_messages)
end
#--------------------------------------------------------------------------
def test_failed_message_is_rejected
rabbit = build_rabbit
subscriber = build_subscriber(:rack_file => ERROR_RACK_APP, :ack => true, :rabbit => rabbit)
message = build_message(:delivery_tag => DELIVERY_TAG, :rabbit => rabbit)
response = build_response(500, "uh oh")
prime(subscriber, [message, response])
subscriber.subscribe
assert_equal([message], rabbit.subscribed_messages)
assert_equal([], rabbit.published_messages)
assert_equal([], rabbit.acked_messages)
assert_equal([DELIVERY_TAG], rabbit.rejected_messages)
end
#==========================================================================
# PRIVATE IMPLEMTATION HELPERS
#==========================================================================
private
def prime(subscriber, *messages)
messages.each do |m|
m, r = m if m.is_a?(Array)
r ||= build_response(200, "ok")
subscriber.rabbit.prime(m)
subscriber.handler.expects(:handle).with(m).returns(r)
end
end
#--------------------------------------------------------------------------
end # class TestSubscriber
end # module RackRabbit
|
require 'irods4r'
module IRODS4r
# This module interfaces directly with the IRODS system
#
module ICommands
class ICommandException < IRODS4rException; end
# Return the list of files found at 'path'.
def self.ls(path, ticket = nil)
r = `ils #{"-t #{ticket}" if ticket} #{path}`
#raise ICommandException.new($?) unless $?.exitstatus == 0
if r.empty?
raise NotFoundException.new("Can't find resource '#{path}'")
end
r.lines
end
# Return content of resource at 'path'
#
def self.read(path, ticket = nil)
f = Tempfile.new('irods4r')
`iget -f #{"-t #{ticket}" if ticket} #{path} #{f.path}`
raise ICommandException.new($?) unless $?.exitstatus == 0
content = f.read
f.close
f.unlink
content
end
# Return content of resource at 'path'
#
def self.write(path, content, ticket = nil)
f = Tempfile.new('irods4r')
f.write(content)
f.close
`iput -f #{"-t #{ticket}" if ticket} #{f.path} #{path}`
raise ICommandException.new($?) unless $?.exitstatus == 0
f.unlink
end
def self.mkpath(dirname)
cmd_out = `imkdir -p #{dirname} 2>&1`
raise ICommandException.new(cmd_out) unless $?.exitstatus == 0
end
def self.exist?(path, ticket = nil)
`ils #{"-t #{ticket}" if ticket} #{path}`
$?.exitstatus == 0
end
# Copy the resource at 'path' in iRODS to 'file_path'
# in the local file system.
#
def self.export(path, file_path, create_parent_path = true, ticket = nil)
#puts ">>>> #{path} -> #{file_path}"
if create_parent_path
require 'fileutils'
FileUtils.mkpath ::File.dirname(file_path)
end
`iget -f #{"-t #{ticket}" if ticket} #{path} #{file_path}`
raise ICommandException.new($?) unless $?.exitstatus == 0
end
end #module
end # module
|
require "spec_helper"
require "linked_list"
RSpec.describe LinkedList, "#push" do
let(:list) { described_class.new }
it "pushs one value" do
list.push("foo")
expect(list[0]).to eq("foo")
end
it "pushs two values" do
list.push("bar")
list.push("qux")
expect(list[0]).to eq("bar")
expect(list[1]).to eq("qux")
end
end
RSpec.describe LinkedList, "#pop" do
let(:list) { described_class.new }
before do
list.push("foo")
list.push("bar")
list.push("qux")
end
it "pops the last value off" do
expect(list.pop).to eq("qux")
expect(list.pop).to eq("bar")
expect(list.pop).to eq("foo")
expect(list.pop).to be_nil
end
end
RSpec.describe LinkedList, "#delete" do
let(:list) { described_class.new }
before do
list.push("foo")
list.push("bar")
list.push("qux")
end
it "deletes foo" do
list.delete(0)
expect(list[0]).to eq("bar")
expect(list[1]).to eq("qux")
expect(list[2]).to be_nil
end
it "deletes bar" do
list.delete(1)
expect(list[0]).to eq("foo")
expect(list[1]).to eq("qux")
expect(list[2]).to be_nil
end
it "deletes qux" do
list.delete(2)
expect(list[0]).to eq("foo")
expect(list[1]).to eq("bar")
expect(list[2]).to be_nil
end
it "raises an argument error for a negative value" do
expect { list.delete(-1) }.to raise_error(ArgumentError)
end
it "deletes nothing for out of bounds" do
expect(list.delete(20)).to be_nil
expect(list[0]).to eq("foo")
expect(list[1]).to eq("bar")
expect(list[2]).to eq("qux")
end
end
RSpec.describe LinkedList, "#each" do
let(:list) { described_class.new }
pending "implement me"
end
RSpec.describe LinkedList, "#reverse_each" do
let(:list) { described_class.new }
pending "implement me"
end
RSpec.describe LinkedList, "#get" do
let(:list) { described_class.new }
pending "implement me"
end
RSpec.describe LinkedList, "#set" do
let(:list) { described_class.new }
pending "implement me"
end
|
json.array!(@mailings) do |mailing|
json.extract! mailing, :id, :first_name, :last_name, :email, :mobile_num, :phone_num, :sms_optIn, :email_optIn
json.url mailing_url(mailing, format: :json)
end
|
json.array!(@recording_sessions) do |recording_session|
json.extract! recording_session, :id, :start_time, :end_time, :description
json.url recording_session_url(recording_session, format: :json)
end
|
class User < ActiveRecord::Base
validates :email, :spotify_access_token, :spotify_refresh_token,
:user_name, presence: true
validates :email, uniqueness: true
has_many :slack_tokens, dependent: :destroy
def to_param
"#{id}-#{user_name}"
end
def signed_into_slack?
slack_tokens.count > 0
end
def latest_slack_token
slack_tokens.order("updated_at DESC").first
end
# Returns a hash of Slack team IDs and team names, excluding the given
# SlackToken ID.
def other_slacks(slack_token_id)
slack_tokens.where('id <> ?', slack_token_id).
order(:team_name).select(:team_id, :team_name).
map { |slack_token| [slack_token.team_id, slack_token.team_name] }.
to_h
end
end
|
require 'typhoeus'
# https://github.com/typhoeus/typhoeus
Typhoeus::Hydra.new(max_concurrency: 20) # default limit is 200
Typhoeus::Config.verbose = true
# we will get some improvements using a single hydra run to process each request but it would be even faster to have have a pool of hydra requests as ready as possible
#
url_1 = 'https://api.github.com/users/eoinkelly'
url_2 = 'https://api.github.com/repos/eoinkelly/angular-bootcamp'
# typhoeus wraps libcurl and defaults to infinite timeout
hydra_options = {
timeout: 30, # seconds
connecttimeout: 10 # seconds
}
hydra = Typhoeus::Hydra.hydra
first_request = Typhoeus::Request.new(url_1)
first_request.on_complete do |response|
puts 'first request finished'
# p response
# third_url = response.body
# third_request = Typhoeus::Request.new(third_url)
# hydra.queue third_request
end
second_request = Typhoeus::Request.new(url_2)
second_request.on_complete do |response|
puts 'second request finished'
# p response
end
hydra.queue first_request
hydra.queue second_request
puts Time.now
hydra.run # this is a blocking call that returns once all requests are complete
puts Time.now
|
require_relative '../karel.rb'
describe Karel do
describe '#initialize' do
it 'accepts coordinates and direction' do
expect{ Karel.new }.to raise_error ArgumentError
end
end
describe '#current_location' do
let(:rover) { Karel.new(4, 1,'N') }
it 'returns current coordinates and direction' do
expect(rover.current_location).to eq '(4,1) N'
end
end
describe '#move' do
it 'does not change direction' do
rover = Karel.new(4, 1, 'N')
expect(rover.current_location).to include 'N'
rover.move
expect(rover.current_location).to include 'N'
end
context 'facing North' do
let(:rover) { Karel.new(4, 1,'N') }
it 'decreases the Y position' do
expect(rover.current_location).to eq '(4,1) N'
rover.move
expect(rover.current_location).to eq '(4,0) N'
end
end
context 'facing South' do
let(:rover) { Karel.new(4, 1,'S') }
it 'increases the Y position' do
expect(rover.current_location).to eq '(4,1) S'
rover.move
expect(rover.current_location).to eq '(4,2) S'
end
end
context 'facing West' do
let(:rover) { Karel.new(4, 1,'W') }
it 'decreases the X position' do
expect(rover.current_location).to eq '(4,1) W'
rover.move
expect(rover.current_location).to eq '(3,1) W'
end
end
context 'facing East' do
let(:rover) { Karel.new(4, 1,'E') }
it 'increases the X position with' do
expect(rover.current_location).to eq '(4,1) E'
rover.move
expect(rover.current_location).to eq '(5,1) E'
end
end
end
describe '#left' do
context 'given North' do
let(:rover) { Karel.new(4, 1,'N') }
it 'turns West' do
expect(rover.current_location).to include 'N'
rover.left
expect(rover.current_location).to include 'W'
end
end
context 'given South' do
let(:rover) { Karel.new(4, 1,'S') }
it 'turns East' do
expect(rover.current_location).to include 'S'
rover.left
expect(rover.current_location).to include 'E'
end
end
end
describe '#right' do
context 'given North' do
let(:rover) { Karel.new(4, 1,'N') }
it 'turns East' do
expect(rover.current_location).to include 'N'
rover.right
expect(rover.current_location).to include 'E'
end
end
context 'given East' do
let(:rover) { Karel.new(4, 1,'E') }
it 'turns South' do
expect(rover.current_location).to include 'E'
rover.right
expect(rover.current_location).to include 'S'
end
end
end
describe '#follow' do
let(:rover) { Karel.new(4, 1,'E') }
let(:command) { 'MMMLMMRMMML' }
it 'follows the sequence of commands and makes appropriate moves' do
expect(rover.current_location).to eq '(4,1) E'
rover.follow(command)
expect(rover.current_location).to eq '(7,1) N'
end
end
end
|
class CreatePlaybacks < ActiveRecord::Migration
def self.up
create_table :playbacks do |t|
t.column :user_id, :integer, :null => false
t.column :media_file_id, :integer, :null => false
t.column :created_at, :datetime
end
add_index :playbacks, [:user_id, :media_file_id]
end
def self.down
drop_table :playbacks
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Game do
it "should have many teams" do
should have_many(:teams)
end
it "should require a number of rounds" do
should validate_presence_of(:rounds)
end
it "should require a number of questions per round" do
should validate_presence_of(:questions_per_round)
end
it "should have many questions" do
should have_many(:questions)
end
end |
class Solution
# find the longest sub string out of `s` containing at most `k` distinct characters
def self.longest_substring(s: '', k: 0)
# loop through starting from index = 0
# and then grow the end pointer we look at until we see at most `k` unique characters, once we do, stop
substring = ''
# shouldn't be an endless loop
0.upto(s.length - 1) do |start_index|
# go upto the end of the string
start_index.upto(s.length - start_index) do |end_index|
candidate = s[start_index..end_index]
if candidate.chars.uniq.size <= k && candidate.length > substring.length
substring = candidate
end
return substring if start_index + substring.length > s.length
end
end
substring
end
end
|
class FontMyricam < Formula
version "2.006.20150301"
sha256 "a90eb9b79885f02ad9e0e752a0b979b699847be7de13dc3b6113658f006d12bd"
url "https://github.com/tomokuni/Myrica/archive/refs/tags/#{version}.tar.gz", verified: "github.com/tomokuni/Myrica/"
desc "MyricaM"
desc "Programming font"
homepage "https://myrica.estable.jp/"
def install
parent = File.dirname(Dir.pwd) != (ENV['HOMEBREW_TEMP'] || '/tmp') ? '../' : ''
(share/"fonts").install "#{parent}Myrica-#{version}/MyricaM.TTC"
end
test do
end
end
|
require 'spec_helper'
require 'poms/api/response'
module Poms
module Api
RSpec.describe Response do
subject { described_class.new('200', nil, nil) }
it 'converts code to integer' do
expect(subject.code).to be(200)
end
it 'converts body to string' do
expect(subject.body).to eql('')
end
it 'converts headers to hash' do
expect(subject.headers).to eql({})
end
it 'considers two respones with equal properties equal' do
expect(subject).to eql(described_class.new('200', nil, nil))
end
end
end
end
|
class Users::PasswordsController < Devise::PasswordsController
ssl_required :new, :create
layout "bootstrap/application"
def new
@title = "Reset password :: #{t("site.title")}"
super
end
end
|
# Our CLI Controller
class DailyDeal::CLI
def call
puts "Today's Daily Deals:"
list_deals
menu
end
def list_deals
# here doc http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html
puts <<-DOC.gsub /^\s*/, ''
1. PCH Digital Massager - $27 - Still available!
2. Lenovo ThinkPad 11E 11.6 - $199.99 - Still available!
DOC
end
def menu
puts "Enter the number of the deal you'd like more info on:"
end
end
|
#
# Author:: Jörgen Brandt <joergen.brandt@onlinehome.de>
# Cookbook:: chef-cuneiform
# Recipe:: cf_worker
#
# Copyright:: 2015-2018 Jörgen Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
cf_worker_version = node['cuneiform']['cf_worker']['version']
cf_worker_dir = "/tmp/cf_worker-#{cf_worker_version}"
cf_worker_github = 'https://github.com/joergen7/cf_worker.git'
git 'git_clone_cf_worker' do
repository cf_worker_github
destination cf_worker_dir
revision cf_worker_version
end
bash 'compile_cf_worker' do
code 'rebar3 escriptize'
cwd cf_worker_dir
environment 'PATH' => "/usr/local/bin:#{ENV['PATH']}"
creates "#{cf_worker_dir}/_build/default/bin/cf_worker"
end
bash 'install_cf_worker' do
code "cp #{cf_worker_dir}/_build/default/bin/cf_worker /usr/local/bin"
creates "/usr/local/bin/cf_worker"
end
|
class Blas < Formula
desc "Basic Linear Algebra Subprograms"
homepage "http://www.netlib.org/blas/"
url "http://www.netlib.org/blas/blas.tgz"
version "2011-04-19"
sha256 "55df2a24966c2928d3d2ab4a20e9856d9914b856cf4742ebd4f7a4507c8e44e8"
depends_on "gcc" => :build
def install
# makefiles do not work in parallel mode
ENV.deparallelize
inreplace "make.inc" do |s|
s.change_make_var! "PLAT", "_DARWIN"
end
system "make"
(lib + name).install "blas_DARWIN.a" => "libblas.a"
end
end
|
require "java"
require "json"
require "bundler/setup"
$:.unshift "uri:classloader:/lib"
require "blogs/deploy"
java_import "java.util.Map"
java_package "uk.org.blogs.deploy"
class LambdaHandler
java_signature "Object call(Map event)"
def call(event)
puts "Received #{event.to_string}"
return unless actionable?(event)
BLOGS::Deploy::Deployment.new.deploy
end
private def actionable?(event)
return true if event["detail-type"] == "Scheduled Event"
puts "Not a scheduled event"
event["Records"]&.any? do |record|
data = JSON.parse(record.dig("Sns", "Message") || "{}")
branch = data["ref"].split("/").last
default_branch = data.dig("repository", "default_branch")
puts "Received push to #{branch} (default: #{default_branch})"
branch && branch == default_branch
end
end
end
|
class Message < ActiveRecord::Base
validates_presence_of :subject, :email, :body
validates_length_of :body, minimum: 15
validates_length_of :subject, minimum: 5
end
|
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
config.vm.hostname = 'salt-test-box'
# Give the machine 2048MB of RAM.
# This assumes you're using the virtualbox provider, see
# https://www.vagrantup.com/docs/providers/ for information on the
# other providers.
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
config.vm.synced_folder "salt", "/srv/salt"
config.vm.synced_folder "pillar", "/srv/pillar"
config.vm.provision :salt do |salt|
salt.install_type = "stable"
salt.masterless = true
salt.minion_config = "salt/minion"
salt.run_highstate = true
end
end
|
class User < ApplicationRecord
before_validation :normalize_fields
has_secure_password
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i # rubocop:disable Style/MutableConstant
validates :username, :email_address, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 255 }
validates :email_address, format: { with: VALID_EMAIL_REGEX }
validates :password, presence: true, length: { minimum: 6 }
private
def normalize_fields
self.email_address = email_address.to_s.downcase.strip
self.username = username.to_s.downcase.strip
end
end
|
class SetParkingSpotsToFree < ActiveRecord::Migration[5.2]
def up
reversible do |dir|
dir.up do
ParkingSpot.where(status: nil).update_all(status: 'free')
end
end
change_column_default :parking_spots, :status, 'free'
end
end
|
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def p(obj, field)
if obj.class == User && field.to_s == 'name'
private_user_name(obj)
end
if Privacy.visible?(obj, field)
obj.send(field)
else
"Hidden"
end
end
def fl
render :partial => 'shared/flash', :object => flash if flash.present?
end
private
def private_user_name(obj)
name_parts = []
name_parts << p(obj, :first_name)
name_parts << p(obj, :last_name)
name_parts.join(' ')
end
end
|
#!/usr/bin/env ruby
require 'emoji'
require 'trollop'
opts = Trollop::options do
version "#{Emoji::VERSION} (c) 2014 David Wu"
banner <<-EOS
Emoji Power
EOS
opt :random, "Select a Random Emoji"
opt :list, "Select from all Emoji"
# --random
# --recent (default)
end
menu = Emoji::Menu.new(opts)
menu.run
|
module TaxCloud
class TICGroup
attr_accessor :group_id, :description
def initialize(attrs = {})
attrs.each do |sym, val|
self.send "#{sym}=", val
end
end
end
end
|
require './runtime.rb'
class ProgramNode
def initialize(statements)
@statements = statements
end
def evaluate(scope_frame)
@statements.each { |s| s.evaluate(scope_frame) }
end
end
class ConstantNode
def initialize(n)
@n = n
end
def evaluate(scope_frame)
@n
end
end
class PrintNode
def initialize(statement)
@statement = statement
end
def evaluate(scope_frame)
pr_print(object_value(@statement, scope_frame), scope_frame)
end
end
class BinaryOperatorNode
def initialize(a, b, op)
@a, @b, @op = a, b, op
end
def evaluate(scope_frame)
end
end
class ArithmeticOperatorNode < BinaryOperatorNode
# Used for syntactic sugar of certain operators
@@method_map = {
:+ => :add,
:- => :subtract,
:* => :multiply,
:/ => :divide,
:% => :modulus,
:^ => :pow
}
def evaluate(scope_frame)
method_name = @@method_map[@op]
target = object_value(@a, scope_frame)
arg = object_value(@b, scope_frame)
method_signature = PRMethodSignatureForObject(target, method_name)
if not target.implements_method?(method_signature) then
raise "Invalid type (#{target.class}) of left operand for '#{@op}'!"
end
msg_send(target, method_signature, arg)
end
end
class LogicalANDNode
def initialize(left, right)
@left_operand, @right_operand = left, right
end
def evaluate(scope_frame)
left_value = boolean_value(object_value(@left_operand, scope_frame))
right_value = boolean_value(object_value(@right_operand, scope_frame))
result = left_value._value && right_value._value
PRBool.new(result)
end
end
class LogicalORNode
def initialize(left, right)
@left_operand, @right_operand = left, right
end
def evaluate(scope_frame)
left_value = boolean_value(object_value(@left_operand, scope_frame))
right_value = boolean_value(object_value(@right_operand, scope_frame))
result = left_value._value || right_value._value
PRBool.new(result)
end
end
class LogicalNOTNode
def initialize(operand)
@operand = operand
end
def evaluate(scope_frame)
value = boolean_value(object_value(@operand, scope_frame))
result = value._value == false
PRBool.new(result)
end
end
class EqualityNode
def initialize(left, right)
@left_operand, @right_operand = left, right
end
def evaluate(scope_frame)
left_value = object_value(@left_operand, scope_frame)
right_value = object_value(@right_operand, scope_frame)
return left_value.eql(right_value)
end
end
class UnaryPreIncrementNode
def initialize(operand)
@operand = operand
end
def evaluate(scope_frame)
object = @operand.evaluate(scope_frame)
if object.is_a?(NAVariable) then
value = object.value
assert_type(value, PRNumber)
object.assign(value.add(PRInteger.new(1)))
return object.value
end
assert_type(object, PRNumber)
return object.add(PRInteger.new(1))
end
end
class UnaryPostIncrementNode
def initialize(operand)
@operand = operand
end
def evaluate(scope_frame)
object = @operand.evaluate(scope_frame)
if object.is_a?(NAVariable) then
original_value = object.value
assert_type(original_value, PRNumber)
object.assign(original_value.add(PRInteger.new(1)))
return original_value
end
assert_type(object, PRNumber)
return object
end
end
class UnaryPreDecrementNode
def initialize(operand)
@operand = operand
end
def evaluate(scope_frame)
object = @operand.evaluate(scope_frame)
if object.is_a?(NAVariable) then
value = object.value
assert_type(value, PRNumber)
object.assign(value.subtract(PRInteger.new(1)))
return object.value
end
assert_type(object, PRNumber)
return object.subtract(PRInteger.new(1))
end
end
class UnaryPostDecrementNode
def initialize(operand)
@operand = operand
end
def evaluate(scope_frame)
object = @operand.evaluate(scope_frame)
if object.is_a?(NAVariable) then
original_value = object.value
assert_type(original_value, PRNumber)
object.assign(original_value.subtract(PRInteger.new(1)))
return original_value
end
assert_type(object, PRNumber)
return object
end
end
class ComparisonNode
def initialize(left_operand, op, right_operand)
@left_operand, @operator, @right_operand = left_operand, op, right_operand
end
def evaluate(scope_frame)
left_value = object_value(@left_operand, scope_frame)
right_value = object_value(@right_operand, scope_frame)
assert_type(left_value, PRNumber)
assert_type(right_value, PRNumber)
method_signature = PRMethodSignatureForObject(left_value, :compare)
comparison_result = msg_send(left_value, method_signature, right_value)
case @operator
when "<"
return PRBool.new(comparison_result._value == -1)
when "<="
return PRBool.new(comparison_result._value <= 0)
when ">"
return PRBool.new(comparison_result._value == 1)
when ">="
return PRBool.new(comparison_result._value >= 0)
end
end
end
class MethodCallNode
def initialize(target, method_name, *args)
@target, @method_name, @args = target, method_name, args
end
def evaluate(scope_frame)
assert_method(@target, @method_name)
end
end
class FunctionCallNode
def initialize(target, args=[])
@target, @args = target, args
end
def evaluate(scope_frame)
arg_values = []
@args.each { |arg_node| arg_values << object_value(arg_node, scope_frame) }
function = object_value(@target, scope_frame)
#puts "Calling function #{function} with arguments #{arg_values}"
result = function.call(arg_values, scope_frame)
return result
end
end
class VariableDeclarationNode
def initialize(type, name, value=nil)
#puts "Variable declaration: #{name} = #{value}"
@type, @name, @value = type, name, value
if @value == nil then
@value = ConstantNode.new(native_class_for_string(type).new)
end
end
def evaluate(scope_frame)
new_var = NAVariable.new(@name, @type, @value.evaluate(scope_frame))
scope_frame.add(new_var)
#puts "Declared a variable '#{@name}' of type #{@type} with the value #{new_var.value}: #{new_var}"
end
end
class FunctionDeclarationNode
def initialize(type, name, parameters, body)
@type, @name, @parameter_nodes, @body = type, name, parameters, body
end
def evaluate(scope_frame)
native_type = native_class_for_string(@type)
params = []
@parameter_nodes.each { |node| params << node.evaluate(scope_frame) }
function = NAFunction.new(@name, native_type, params, @body)
assert_return(function)
#puts "Declared a function: #{function.body}"
scope_frame.add(function)
end
end
class ParameterDeclarationNode
def initialize(type, name)
@type, @name = type, name
end
def evaluate(scope_frame)
return NAParameter.new(native_class_for_string(@type), @name)
end
end
class ReturnStatementNode
attr_reader :statement
def initialize(statement = nil)
@statement = statement
end
def evaluate(scope_frame)
@statement.evaluate(scope_frame) if @statement != nil
end
end
class ScopeLookupNode
def initialize(variable_name)
#puts "Variable reference: #{variable_name.class}"
@variable_name = variable_name
end
def evaluate(scope_frame)
scope_frame.fetch(@variable_name)
end
end
class MethodLookupNode
def initialize(receiver, method_name)
@receiver_node, @method_name = receiver, method_name
end
def evaluate(scope_frame)
receiver_object = object_value(@receiver_node, scope_frame)
signature = PRMethodSignatureForObject(receiver_object, @method_name)
return NAMethodInvocation.new(receiver_object, signature) if signature != nil
raise "No function '#{@method_name}' found for object #{receiver_object}"
end
end
# Needs to be updated to support other types of
# assignment than direct variable assignment (such as subscript assignment).
class AssignmentNode
def initialize(variable_node, value_node)
@variable_node, @value_node = variable_node, value_node
end
def evaluate(scope_frame)
variable = @variable_node.evaluate(scope_frame)
value = object_value(@value_node, scope_frame)
variable.assign(value)
end
end
class CompoundStatementNode
attr_reader :statements
def initialize(statements = nil)
@statements = statements
end
def evaluate(scope_frame)
return if @statements == nil
@statements.each { |s| s.evaluate(scope_frame) }
end
end
class ArrayLiteralNode
def initialize(element_nodes)
@element_nodes = element_nodes
end
def evaluate(scope_frame)
elements = @element_nodes.map { |e| object_value(e, scope_frame) }
return PRArray.new(elements)
end
end
class DictLiteralNode
def initialize(pair_nodes)
@pair_nodes = pair_nodes
end
def evaluate(scope_frame)
pairs = @pair_nodes.map { |p| object_value(p, scope_frame) }
return PRDict.new(pairs)
end
end
class KeyValuePairNode
def initialize(key, value)
@key, @value = key, value
end
def evaluate(scope_frame)
key_object = object_value(@key, scope_frame)
value_object = object_value(@value, scope_frame)
return NAKeyValuePair.new(key_object, value_object)
end
end
class IfStatementNode
def initialize(condition, stat)
@condition, @stat = condition, stat
end
def evaluate(scope_frame)
new_scope = NAScopeFrame.new("if", scope_frame)
value = boolean_value(object_value(@condition, new_scope))
if value._value then
@stat.evaluate(new_scope)
end
end
end
class IfElseStatementNode
def initialize(condition, stat, else_stat)
@condition, @stat, @else_stat = condition, stat, else_stat
end
def evaluate(scope_frame)
new_scope = NAScopeFrame.new("if", scope_frame)
value = boolean_value(object_value(@condition, new_scope))
if value._value then
@stat.evaluate(new_scope)
else
@else_stat.evaluate(new_scope)
end
end
end
class WhileLoopNode
def initialize(condition, stat)
@condition, @stat = condition, stat
end
def evaluate(scope_frame)
new_scope = NAScopeFrame.new("while", scope_frame)
while boolean_value(object_value(@condition, new_scope))._value do
@stat.evaluate(new_scope)
end
end
end
class ForLoopNode
def initialize(decl, cond, control, stat)
@declaration, @condition, @control, @stat = decl, cond, control, stat
end
def evaluate(scope_frame)
new_scope = NAScopeFrame.new("for", scope_frame)
@declaration.evaluate(new_scope) if @declaration != nil
while @condition == nil or boolean_value(object_value(@condition, new_scope))._value do
@stat.evaluate(new_scope) if @stat != nil
@control.evaluate(new_scope) if @control != nil
end
end
end
class SubscriptNode
def initialize(target_node, index_node)
@target_node, @index_node = target_node, index_node
end
def evaluate(scope_frame)
object = object_value(@target_node, scope_frame)
index = object_value(@index_node, scope_frame)
if not object.is_a?(PRArray) and not object.is_a?(PRDict)
raise "#{object} does not support subscripting."
end
if object.is_a?(PRArray) then
assert_type(index, PRInteger)
method_sig = PRMethodSignatureForObject(object, :at)
return msg_send(object, method_sig, index)
else
method_sig = PRMethodSignatureForObject(object, :fetch)
return msg_send(object, method_sig, index)
end
end
end
|
=begin
#===============================================================================
Title: Message Skip
Author: Hime
Date: Jul 21, 2013
--------------------------------------------------------------------------------
** Change log
Jul 21, 2013
- Initial release
--------------------------------------------------------------------------------
** Terms of Use
* Free to use in non-commercial projects
* Contact me for commercial use
* No real support. The script is provided as-is
* Will do bug fixes, but no compatibility patches
* Features may be requested but no guarantees, especially if it is non-trivial
* Credits to Hime Works in your project
* Preserve this header
--------------------------------------------------------------------------------
** Description
This script allows you to skip messages (fast-forward) by holding down the
CTRL key.
--------------------------------------------------------------------------------
** Installation
Place this script below Materials and above Main
--------------------------------------------------------------------------------
** Usage
You can choose which key will be used as the skip key.
You can enable or disable message skipping by assigning a disable switch.
When the disable switch is ON, players cannot skip messages.
--------------------------------------------------------------------------------
** Compatibility
This script overwrites the following methods
Window_Message
input_pause
#===============================================================================
=end
$imported = {} if $imported.nil?
$imported["TH_MessageSkip"] = true
#===============================================================================
# ** Configuration
#===============================================================================
module TH
module Message_Skip
# Switch to use to prevent message skipping
Disable_Switch = 0
# Key to hold to skip messages
Skip_Key = :CTRL
# Use "auto skip" mode. When the skip mode is OFF, you need to hold the
# skip key to fast-forward messages. When the skip mode is ON, you just
# need to press it once to begin skipping, and press it again to stop
# skipping
Auto_Skip = false
# Ignore delays when skipping.
Skip_Delays = false
# Ignore pauses when skipping
end
end
#===============================================================================
# ** Rest of script
#===============================================================================
class Window_Message < Window_Base
def skip_key
TH::Message_Skip::Skip_Key
end
def skip_key_pressed?
!$game_switches[TH::Message_Skip::Disable_Switch] && Input.press?(skip_key)
end
#-----------------------------------------------------------------------------
# Overwrite. Actually all you really need is that extra line of code to tell
# the fiber to resume
#-----------------------------------------------------------------------------
def input_pause
self.pause = true
wait(10)
Fiber.yield until Input.trigger?(:B) || Input.trigger?(:C) || skip_key_pressed?
Input.update
self.pause = false
end
alias :th_skip_message_wait :wait
def wait(duration)
return if TH::Message_Skip::Skip_Delays && skip_key_pressed?
th_skip_message_wait(duration)
end
end |
class AddCodeIdToDatabrowsers < ActiveRecord::Migration
def change
add_reference :databrowsers, :code, index: true, foreign_key: true
add_reference :dataincludes, :code, index: true, foreign_key: true
add_reference :datasubcategories, :code, index: true, foreign_key: true
add_reference :datacompatibles, :code, index: true, foreign_key: true
add_reference :taggings, :code, index: true, foreign_key: true
add_reference :screenshots, :code, index: true, foreign_key: true
add_reference :brokes, :code, index: true, foreign_key: true
end
end
|
module PrintQuoteDetail
extend ActiveSupport::Concern
include PrintDocumentStyle
def quote_details(quote, pdf)
pdf.bounding_box([175.mm, 231.mm], :width => 20.mm) do
pdf.text quote.project.ref, customer_style unless quote.project.ref.blank?
pdf.text quote.ref, customer_style unless quote.ref.blank?
pdf.text quote.customer_ref, customer_style unless quote.customer_ref.blank?
pdf.text quote.date.strftime("%d/%m/%y"), customer_style unless quote.date.blank?
end
end
end |
require 'rails_helper'
feature 'User edit customer' do
scenario 'successfully' do
customer = create(:customer)
user = create(:user)
login_as(user, scope: :user)
visit root_path
click_on 'Lista de Clientes'
click_on customer.name
click_on 'Editar'
fill_in 'Nome', with: 'George R R Martin'
fill_in 'E-mail', with: 'george@martin.com'
fill_in 'Telefone', with: '0800-V4L4R'
click_on 'Salvar'
expect(page).to have_content('George R R Martin')
expect(page).to_not have_content(customer.name)
end
scenario 'Duplicated fields' do
user = create(:user)
customer = create(:customer)
other_customer = create(:customer, name: 'Jon', phone: '(11) 96782-4553',
email: 'douglas@gmail.com')
login_as(user, scope: :user)
visit root_path
click_on 'Lista de Clientes'
click_on customer.name
click_on 'Editar'
fill_in 'Nome', with: ''
fill_in 'E-mail', with: 'douglas@gmail.com'
fill_in 'Telefone', with: '(11) 96782-4553'
click_on 'Salvar'
expect(page).to have_content("Name can't be blank")
expect(page).to have_content('Email has already been taken')
expect(page).to have_content('Phone has already been taken')
end
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
clear_db = -> () {
Task.destroy_all
Category.destroy_all
Comment.destroy_all
}
create_task = -> (status) do
category = rand(2) != 0 ? Category.all.sample : Category.first
rand_date = rand(3) == 0 ? Date.today - 7 : Date.today + 7
category.tasks.create(
title: Faker::Name.name_with_middle,
description: Faker::Lorem.paragraph(sentence_count: 7),
status: status,
deadline: rand_date
)
end
create_comments = -> (task) do
number = rand(3)
number.times do |i|
task.comments.create(text: Faker::Lorem.sentences)
end
end
clear_db.call
Category.create(name: "General")
6.times do |i|
Category.create(name: Faker::Name.name_with_middle)
end
10.times do |i|
create_task.call(:to_do)
end
10.times do |i|
create_task.call(:done)
end
Task.all.each do |task|
create_comments.call(task)
end
|
class AddFieldsToBlogs < ActiveRecord::Migration
def change
add_column :blog_posts, :uid, :string, :after => :url
add_column :blog_posts, :preview, :text, :after => :body
add_column :blog_posts, :published_at, :datetime, :after => :user_id
end
end
|
require 'hpricot'
##
# The BodyMatcher is the module which makes it all happen. To
# enable body matching, just include this module in your TestCase class:
#
# class Test::Unit::TestCase
# include BodyMatcher
#
# self.use_transactional_fixtures = true
# self.use_instantiated_fixtures = false
# end
#
module BodyMatcher
class Matcher
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
def initialize(body) #:nodoc:
@body = body
@doc = Hpricot(body)
end
##
# Finds a specific element:
# body['#login']
#
# Raises an exception if that element is not found.
def [](*args)
return @body[*args] if args.size > 1
elements = @doc.search(args.first)
raise "Element(s) matching #{search} not found." if elements.empty?
elements.map! { |e| Element.new(e) }
elements.size == 1 ? elements.first : elements
end
def method_missing(*args, &block)
@body.send(*args, &block)
end
end
class Element
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
def initialize(element) #:nodoc:
@element = element
@text = element.inner_text
end
##
# Accesses an attribute of an element:
# body['#name_field']['value']
def [](attribute)
@element[attribute]
end
##
# Returns a hash of the element's attributes.
# body['#name_field'].attributes
def attributes
@element.attributes
end
def method_missing(*args, &block) #:nodoc:
@text.send(*args, &block)
end
end
def self.included(base) #:nodoc:
require 'hpricot'
alias_body = proc do
alias_method :real_rails_body, :body
def body
Matcher.new(real_rails_body)
end
end
ActionController::TestResponse.class_eval &alias_body
Test::Unit::TestCase.class_eval &alias_body
alias_match = lambda do
alias_method :test_spec_match, :match
def match(target)
test_spec_match target.is_a?(Regexp) ? target : %r(#{target})
end
end
if defined? Test::Spec
Test::Spec::ShouldNot.class_eval &alias_match
Test::Spec::Should.class_eval &alias_match
end
end
end
|
require "spec_helper"
describe PostsController do
describe "routing" do
it "routes to #index" do
get("/tailgates/1/posts").should route_to("posts#index", tailgate_id:"1")
end
it "routes to #new" do
get("/tailgates/1/posts/new").should route_to("posts#new", tailgate_id:"1")
end
it "routes to #show" do
get("/tailgates/2/posts/1").should route_to("posts#show", :id => "1", tailgate_id:"2")
end
it "routes to #edit" do
get("/tailgates/2/posts/1/edit").should route_to("posts#edit", :id => "1", tailgate_id:"2")
end
it "routes to #create" do
post("/tailgates/2/posts").should route_to("posts#create", tailgate_id:"2")
end
it "routes to #update" do
put("/tailgates/2/posts/1").should route_to("posts#update", :id => "1", tailgate_id:"2")
end
it "routes to #destroy" do
delete("/tailgates/2/posts/1").should route_to("posts#destroy", :id => "1", tailgate_id:"2")
end
end
end
|
# encoding: UTF-8
module CDI
module V1
module Posts
class PostToSubscribersService < BaseService
def initialize post, options={}
super options
@post = post
end
def execute
if can_execute?
users.each { |user| create_subscriber_post(user) }
create_subscriber_post @post.user
end
end
def can_execute?
!@post.nil?
end
def users
all_users = []
@post.visibilities.each { |v| all_users += users_by_visibilities(v) }
all_users - [@post.user]
end
def users_by_visibilities visibility
if visibility.students?
@post.user.subscribers_users.student
elsif visibility.multipliers?
@post.user.subscribers_users.multiplier
elsif visibility.all?
@post.user.subscribers_users
else
obj = visibility.visibility_object
@post.user.subscribers_users.reduce_by_visibility(obj)
end
end
def create_subscriber_post user
subscription = user.user_subscriptions.find_by(publisher: @post.publisher)
@post.subscriber_posts.build(user_subscription: subscription).save
notify_user user
end
def notify_user user
unless user == @post.user
create_system_notification_async(
sender_user: @post.user,
receiver_user: user,
notification_type: :new_post,
notificable: @post
)
end
end
end
end
end
end
|
class EvaluationQuestion < ActiveRecord::Base
#belongs_to :course
belongs_to :course_class
has_many :registration_evaluation_answers
attr_accessible :heading, :position, :question, :course_id, :answer_type, :course_class_id, :old_id
acts_as_list scope: :course
HEADINGS = ["Objective", "Instruction", "Content", "Teaching Methods", "Relevancy", "Open-Ended"]
validates_presence_of :question, :answer_type
#:heading,
def object_title
"#{self.heading} // #{self.question}"
end
RailsAdmin.config do |config|
config.model EvaluationQuestion do
object_label_method :object_title
visible false
edit do
# field :course
field :heading, :enum do
enum do
EvaluationQuestion::HEADINGS
end
end
field :question
field :answer_type, :enum do
enum do
["poor-excellent", "little-great", "open-ended"]
end
end
end
end
end
protected
after_initialize do
if new_record?
self.answer_type ||= 'poor-excellent' # be VERY careful with ||= and False values
end
end
end
|
# Campaign Model
class Campaign < ApplicationRecord
has_many :choices
has_many :votes, through: :choices
validates_presence_of :name
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates_confirmation_of :password
attr_accessor :password_confirmation
validates :nickname,
presence: true, # 必須
uniqueness: true, # 一意性
length: { maximum: 20 } # あんまり長いのも
validates :email,
presence: true,
uniqueness: true,
format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i } # メールアドレスの正規表現
validates :password,
presence: true, # 必須
length: { minimum: 7 }, # 7文字以上
format: { with: /\A[a-z0-9]+\z/i } # 半角英数字のみ
has_one :profile
has_one :shipping_address
accepts_nested_attributes_for :profile
has_many :creditcards
has_many :items
# 購入未・済などを区別して取り出せるようにするアソシエーション
# has_many :buyed_items, foreign_key: "buyer_id", class_name: "Item"
# has_many :saling_items, -> { where("buyer_id is NULL") }, foreign_key: "saler_id", class_name: "Item"
# has_many :sold_items, -> { where("buyer_id is not NULL") }, foreign_key: "saler_id", class_name: "Item"
end
|
# frozen_string_literal: true
require 'json'
require 'net/http'
POKE_RANGE = (1..151).freeze
PARTICIPANTS = 8
def gen_ids
# Generate eight ids in the range 1..151,
# making sure they are different.
last_poke_ids = []
poke_id = 0
Array.new(PARTICIPANTS) do
last_poke_ids.push poke_id
# generate a new, different id
poke_id = rand(POKE_RANGE) while last_poke_ids.include? poke_id
poke_id
end
end
def parse_dmg_rel(dmg_rel)
# Cleans damage relation hash,
# removing clutter urls
dmg_rel.each do |k, v|
clean_array = []
v.each do |h|
clean_array.push h['name']
end
dmg_rel[k] = clean_array
end
end
def get_pokes(ids)
all_pokes = []
ids.each do |id|
poke_uri = URI("https://pokeapi.co/api/v2/pokemon/#{id}")
poke_str = Net::HTTP.get(poke_uri)
poke_hash = JSON.parse(poke_str)
base_stat = poke_hash['stats'][0]['base_stat']
type_name = poke_hash['types'][0]['type']['name']
name = poke_hash['name']
type_uri = URI("https://pokeapi.co/api/v2/type/#{type_name}")
type_str = Net::HTTP.get(type_uri)
type_hash = JSON.parse(type_str)
dmg_rel = type_hash['damage_relations']
clean_dmg_rel = parse_dmg_rel(dmg_rel)
all_pokes.push({
name: name, base_stat: base_stat,
type: type_name, dmg_rel: clean_dmg_rel
})
end
all_pokes
end
|
class CreateGames < ActiveRecord::Migration
def change
create_table :games do |t|
t.integer :player1_id
t.integer :player2_id
t.datetime :gamed_at
t.integer :final_points_1
t.integer :final_points_2
t.timestamps null: false
end
end
end
|
require 'rails_helper'
describe Article do
it { should have_many :comments }
it { should validate_presence_of :content }
end
|
class ApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
respond_to :json
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from ActiveRecord::RecordNotFound do
respond_to do |type|
type.all { render :nothing => true, :status => 404 }
end
end
protected
def check_access (user)
if current_user != user and not current_user.admin?
render :json => {errors: 'The resource is not owned by you.'}, status: :forbidden
end
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:account_update) << :name
end
end
|
# frozen_string_literal: true
module Tikkie
module Api
module V1
module Types
module PlatformUsage
FOR_MYSELF = "PAYMENT_REQUEST_FOR_MYSELF"
FOR_OTHERS = "PAYMENT_REQUEST_FOR_OTHERS"
end
end
end
end
end
|
class ShopsController < ApplicationController
def index
@shops = current_user.shops
end
def new
@shop = current_user.shops.new
end
def create
@shop = current_user.shops.create shop_params
if @shop.persisted?
flash[:success] = t ".success"
redirect_to shops_path
else
flash[:alert] = t ".error"
render :new
end
end
def set_current_shop
cookies["current_shop_user_#{current_user.id}"] = params[:shop_id]
redirect_to request.referer
end
def connect_to_facebook_page
update_facebook_page_info_to_current_shop
redirect_to facebook_chat_path
end
def disconnect_facebook_page
current_shop.update_attributes facebook_page_id: nil,
facebook_page_access_token: nil
redirect_to facebook_pages_path
end
private
def shop_params
params.require(:shop).permit :name
end
def update_facebook_page_info_to_current_shop
current_shop.update_attributes facebook_page_id: facebook_page.id,
facebook_page_access_token: facebook_page.access_token
end
def facebook_page
user_graph_api = Facebook::GraphApiService.call current_user.facebook_access_token
facebook_page_id = params[:facebook_page_id]
access_token = user_graph_api.get_page_access_token facebook_page_id
FacebookPage.new id: facebook_page_id, access_token: access_token
end
end
|
# encoding: utf-8
module Pakman
class Runner
include LogUtils::Logging
def initialize
@opts = Opts.new
end
attr_reader :opts
def run( args )
opt=OptionParser.new do |cmd|
cmd.banner = "Usage: pakman [options]"
cmd.on( '-f', '--fetch URI', 'Fetch Templates' ) do |uri|
opts.fetch_uri = uri
end
cmd.on( '-t', '--template MANIFEST', 'Generate Templates' ) do |manifest|
opts.generate = true
opts.manifest = manifest
end
cmd.on( '-l', '--list', "List Installed Templates" ) { opts.list = true }
cmd.on( '-c', '--config PATH', "Configuration Path (default is #{opts.config_path})" ) do |path|
opts.config_path = path
end
cmd.on( '-o', '--output PATH', "Output Path (default is #{opts.output_path})" ) { |path| opts.output_path = path }
cmd.on( '-v', '--version', "Show version" ) do
puts Pakman.banner
exit
end
cmd.on( "--verbose", "Show debug trace" ) do
## logger.datetime_format = "%H:%H:%S"
## logger.level = Logger::DEBUG
# fix: use logutils - set to debug
end
cmd.on_tail( "-h", "--help", "Show this message" ) do
puts <<EOS
pakman - Lets you manage template packs.
#{cmd.help}
Examples:
pakman -f URI # to be done
pakman -f URI -c ~/.slideshow/templates
pakman -l # to be done
pakman -l -c ~/.slideshow/templates
pakman -t s6
pakman -t s6 ruby19.yml
pakman -t s6 ruby19.yml tagging.yml
pakman -t s6 -o o
pakman -t s6 -c ~/.slideshow/templates
Further information:
http://geraldb.github.com/pakman
EOS
exit
end
end
opt.parse!( args )
puts Pakman.banner
if opts.list?
List.new( opts ).run
elsif opts.generate?
Gen.new( opts ).run( args )
elsif opts.fetch?
Fetch.new( opts ).run
else
puts "-- No command do nothing for now. --" ## run help??
puts "Done."
end
end # method run
end # class Runner
end # module Pakman
|
# Symfony environment
set :symfony_env, "prod"
# Symfony application path
set :app_path, "app"
# Symfony web path
set :web_path, "web"
# Symfony log path
set :log_path, fetch(:app_path) + "/logs"
# Symfony cache path
set :cache_path, fetch(:app_path) + "/cache"
# Symfony config file path
set :app_config_path, fetch(:app_path) + "/config"
# Controllers to clear
set :controllers_to_clear, ["app_*.php"]
# Files that need to remain the same between deploys
set :linked_files, []
# Dirs that need to remain the same between deploys (shared dirs)
set :linked_dirs, [fetch(:log_path), fetch(:web_path) + "/uploads"]
# Dirs that need to be writable by the HTTP Server (i.e. cache, log dirs)
set :file_permissions_paths, [fetch(:log_path), fetch(:cache_path)]
# Name used by the Web Server (i.e. www-data for Apache)
set :webserver_user, "www-data"
# Method used to set permissions (:chmod, :acl, or :chown)
set :permission_method, false
# Execute set permissions
set :use_set_permissions, false
# Symfony console path
set :symfony_console_path, fetch(:app_path) + "/console"
# Symfony console flags
set :symfony_console_flags, "--no-debug"
# Assets install path
set :assets_install_path, fetch(:web_path)
# Assets install flags
set :assets_install_flags, '--symlink'
# Assetic dump flags
set :assetic_dump_flags, ''
|
class SolarSystem
def initialize(star_name)
@star_name = star_name
@planets = []
end
attr_reader :star_name, :planets
def add_planet(planet_info)
@planets << planet_info
end
def check_planet_found(planet)
return @planets.map { |plant| plant.name.downcase }.include?(planet)
end
def list_planets
list = ["Planets orbiting #{@star_name}\n"]
@planets.each_with_index { |plant, index| list += ["#{index + 1}. #{plant.name.downcase}\n"] }
return list
end
def find_planet_by_name(planet_name)
# what to do if more than one planet with the given name?
# what to do it user wants to add name for planet that already exists?
return @planets.find { |obj| obj.name.downcase == planet_name.downcase }
end
def distance_between(planet1, planet2)
dist1 = @planets.find { |obj| obj.name.downcase == planet1.downcase }
dist2 = @planets.find { |obj| obj.name.downcase == planet2.downcase }
return (dist1.distance_from_sun_km - dist2.distance_from_sun_km).abs
end
end
|
require 'spec_helper'
describe Topic do
let(:topic) {FactoryGirl.create(:topic)}
it {(topic.slug).should_not be_nil}
it { should belong_to(:user) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:content) }
end
|
# frozen_string_literal: true
Warden::Manager.after_set_user except: :fetch do |user, auth, opts|
password = auth.request.params.fetch(opts[:scope], {}).fetch(:password, nil)
password && auth.authenticated?(opts[:scope]) && user.respond_to?(:password_pwned?) && user.password_pwned?(password)
end
|
require 'rails_helper'
require 'sidekiq/testing'
Sidekiq::Testing.inline!
def parse_body(body)
JSON.parse(body, symbolize_names: true)
end
describe "Convert Office Open XML to HTML using OxGarage" do
before do
Fog.mock!
connection = Fog::Storage.new({
provider: "AWS",
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
})
directory = connection.directories.create key: ENV['S3_BUCKET']
end
let(:response_body) { TahiEpub::JSONParser.parse response.body }
it "converts to HTML containing the title and body from the .docx file" do
allow_any_instance_of(Job).to receive(:notify!)
VCR.use_cassette("oxgarage") do
post '/jobs', format: :json, epub: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'turtles.epub'), 'application/epub+zip'), callback_url: "blah"
expect(response_body[:job][:id]).to_not be_blank
end
end
end
|
class OrderMap < ApplicationRecord
after_create :create_check_info, :create_doctor_check_info
belongs_to :customer_record
belongs_to :service
has_one :check_info, dependent: :destroy
has_one :doctor_check_info, dependent: :destroy
class << self
def statistic start_date, end_date, station_id
sql = "CALL order_map_stat('#{start_date}', '#{end_date}', #{station_id})"
result = OrderMap.connection.select_all sql
stat = []
id = 1
result.rows.each do |row|
data = {}
data[:id] = id
data[:date] = row[2].to_s
data[:s_id] = row[3]
data[:s_name] = row[4]
data[:income] = row[0]
data[:count] = row[1]
stat << data
id += 1
end
stat
end
def total_sale start_date, end_date, station_id
sql = "CALL services_sale('#{start_date}', '#{end_date}', #{station_id})"
result = OrderMap.connection.select_all sql
stat = []
id = 1
result.rows.each do |row|
data = {}
data[:id] = id
data[:date] = row[0].to_s
data[:t_sale] = row[1]
stat << data
id += 1
end
stat
end
end
private
def create_check_info
station = Station.find_by(id: self.station_id)
if station
@checkinfo = CheckInfo.new(status: 1, order_map_id: self.id,
c_id: self.customer_record.id,
c_name: self.customer_record.cname, station_id: station.id)
if @checkinfo.valid?
@checkinfo.save
end
end
end
def create_doctor_check_info
station = Station.find_by(id: self.station_id)
if station
@checkinfo = DoctorCheckInfo.new(order_map_id: self.id,
c_id: self.customer_record.id,
c_name: self.customer_record.cname, station_id: station.id)
if @checkinfo.valid?
@checkinfo.save
end
end
end
end
|
require('spec_helper')
describe Tag do
it "will check if the tables are setup right" do
new_tag = Tag.create({:name => 'Snack'})
expect(Tag.all).to eq [new_tag]
end
it "will check to see the tags has a recipe" do
new_recipe = Recipe.create({:name => 'Cookies', :ingredients => 'Flour sugar milk', :instructions => "cook", :ratings => 4})
new_tag = Tag.create({:name => "Snack"})
new_tag2 = Tag.create({:name => "Cookie"})
new_tag3 = Tag.create({:name => "Desert"})
expect(new_tag.recipes.push(new_recipe)).to(eq(new_tag.recipes))
expect(Tag.all).to eq [new_tag, new_tag2, new_tag3]
end
it("validates presence of name field in tag") do
tag = Tag.new({:name => ""})
expect(tag.save()).to(eq(false))
end
it("converts the name to Capitalized") do
tag = Tag.new({:name => "french"})
tag.save()
expect(tag.name()).to(eq("French"))
end
end
|
class Run < ActiveRecord::Base
belongs_to :user
def time_minutes
return nil if time_in_seconds.nil?
(time_in_seconds / 1.minute) % 1.minute
end
def time_hours
return nil if time_in_seconds.nil?
(time_in_seconds / 1.hour)
end
def time_minutes=(minutes)
self.time_in_seconds ||= 0
self.time_in_seconds += minutes.to_i.minutes
end
def time_hours=(hours)
self.time_in_seconds ||= 0
self.time_in_seconds += hours.to_i.hours
end
def self.find_for_friends(friends_facebook_ids)
Run.find(:all,
:conditions=>["users.facebook_id in (?)",friends_facebook_ids],
:include=>[:user],
:limit=>20,
:order=>"ran_on desc")
end
end
|
class TictactoeGamesController < ApplicationController
before_action :set_tictactoe_game, only: [:show, :edit, :update, :destroy]
def index
@tictactoe_games = TictactoeGame.all
end
def new
@tictactoe_game = TictactoeGame.new
end
def create
@tictactoe_game = TictactoeGame.new(tictactoe_game_params)
respond_to do |format|
if current_user.tictactoe_games.create(tictactoe_game_params)
format.html { redirect_to tictactoe_game_path TictactoeGame.find(current_user.tictactoe_games.last.id), notice: 'Game was successfully created.' }
format.json { render :show, status: :created, location: @tictactoe_game }
else
format.html { render :new }
format.json { render json: @tictactoe_game.errors, status: :unprocessable_entity }
end
end
end
def show
end
def edit
end
def update
end
def destroy
end
private
def tictactoe_game_params
params.require(:tictactoe_game).permit(:player_1_id, :player_2_id, :current_turn_user_id, :mode, :moves, :status, :winner_user_id)
end
def set_tictactoe_game
@article = Article.find_by_name(params[:id])
end
end
resources :tictactoe_game
# player_1_id
# player_2_id
# mode:string
# current_turn_user_id
# moves:string
# status:string
# winner_user_id |
class BondValue
attr_accessor :buy, :sale
def initialize(buy, sale)
@buy = buy
@sale = sale
end
end
|
class CreateRecords < ActiveRecord::Migration
def change
create_table :records do |t|
t.integer :user_id
t.string :checked_boxes, array: true, default: []
t.timestamps
end
end
end
|
require 'test_helper'
class GclassesControllerTest < ActionController::TestCase
setup do
@gclass = gclasses(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:gclasses)
end
test "should get new" do
get :new
assert_response :success
end
test "should create gclass" do
assert_difference('Gclass.count') do
post :create, gclass: @gclass.attributes
end
assert_redirected_to gclass_path(assigns(:gclass))
end
test "should show gclass" do
get :show, id: @gclass.to_param
assert_response :success
end
test "should get edit" do
get :edit, id: @gclass.to_param
assert_response :success
end
test "should update gclass" do
put :update, id: @gclass.to_param, gclass: @gclass.attributes
assert_redirected_to gclass_path(assigns(:gclass))
end
test "should destroy gclass" do
assert_difference('Gclass.count', -1) do
delete :destroy, id: @gclass.to_param
end
assert_redirected_to gclasses_path
end
end
|
class Copyright
include Dragonfly::Configurable
include Dragonfly::ImageMagick::Utils
def copyright(source_image, notice = "(c)")
# opts = defaults.merge(opts)
# #TODO proper tempfile name
# tempfile =Tempfile.new('caststone')
# command = "convert -fill white -pointsize 40 -annotate 0 'Hello Sailor' #{source_image.path} #{tempfile.path}"
# result = `#{command}`
# tempfile
end
def defaults
{ opacity: 60,
pointSize: 24,
fontFamily: 'Baskerville',
fontWeight: 'bold',
gravity: 'southwest',
stroke: 'transparent',
fill: 'white',
text: "\"(c) Caststone #{Time.now.year}\""
}
end
end
|
class AddTournamntIdToStakes < ActiveRecord::Migration
def change
add_column :stakes, :tournament_id_4, :integer
end
end
|
class Student < ApplicationRecord
validates :name, :student_number, :gpa, presence: true
validates :name, uniqueness: true
validates :student_number, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 10000}
belongs_to :school
end
|
module Responders
class Setupgame < ApplicationResponder
respond_to "scan-data", "text", "link", "picture", "video", "sticker"
def can_handle?
Game.find(user.game_id).category.nil?
end
def handle
if match_message('Kids') || match_message('Teens') || match_message('College') || match_message('Family')
g = Game.find(user.game_id)
g.category = message['body']
g.save!
text_response("Enter first player's name")
else
text_response("#{Game.last.id}, #{user.game_id} Choose type of game",["Kids", "Teens", "College", "Family"])
end
end
end
end
|
class Student::PreviewImport
include ActiveModel::Model
attr_accessor :file, :course_id, :headers
def initialize(attributes = {})
@file = attributes[:file]
@course_id = attributes[:course_id]
@headers = attributes[:headers] == "1"
end
def read
nested_array = CSV.read(@file)
result = @headers ? nested_array.slice!(1..) : nested_array
return result
end
end |
class FontKatibeh < Formula
head "https://github.com/google/fonts/raw/main/ofl/katibeh/Katibeh-Regular.ttf", verified: "github.com/google/fonts/"
desc "Katibeh"
homepage "https://fonts.google.com/specimen/Katibeh"
def install
(share/"fonts").install "Katibeh-Regular.ttf"
end
test do
end
end
|
class StaticPagesController < ApplicationController
# NOTE: I moved the root logic to the posts controller.
# staticpages#home no longer matters
# unless the user is not logged in at all (which I'm also going to change)
# I'll keep this stuff in tact in case I need to revert later for some reason.
def home
if signed_in?
@post = current_user.posts.build
@feed_items = Post.paginate(page: params[:page], :per_page => 20)
end
end
def about
end
def rules
end
end
|
class Projects::TimesheetsController < Projects::ItemsController
# Start editing timesheet
def edit
add_project_breadcrumb
add_breadcrumb "My Timesheet", :edit_project_timesheet_path
today = Date.today
@period_start = today.beginning_of_week
@period_end = @period_start + 4
gon.user_id = current_user.id
gon.period_start = @period_start.strftime("%Y%m%d")
gon.period_end = @period_end.strftime("%Y%m%d")
gon.can_update_members_task_work = can?(current_user, :update_members_task_work, @project)
end
end
|
require 'rails_helper'
describe 'admin invoice show page (/admin/invoices/:id)' do
include ActionView::Helpers::NumberHelper
let!(:customer1) { create(:customer) }
let!(:customer2) { create(:customer) }
let!(:invoice1) { create(:invoice, customer: customer1, status: 2) }
let!(:invoice2) { create(:invoice, customer: customer2) }
let!(:item1a) { create(:item) }
let!(:item1b) { create(:item) }
let!(:item2a) { create(:item) }
let!(:item2b) { create(:item) }
let!(:item2c) { create(:item) }
let!(:invoice_item1a) { create(:invoice_item, item: item1a, invoice: invoice1) }
let!(:invoice_item1b) { create(:invoice_item, item: item1b, invoice: invoice1) }
let!(:invoice_item2a) { create(:invoice_item, item: item2a, invoice: invoice2) }
let!(:invoice_item2b) { create(:invoice_item, item: item2b, invoice: invoice2) }
let!(:invoice_item2c) { create(:invoice_item, item: item2c, invoice: invoice2) }
let!(:bulk_discount1) { create(:bulk_discount, merchant: item1a.merchant, quantity_threshold: 5) }
let!(:bulk_discount2) { create(:bulk_discount, merchant: item2a.merchant, quantity_threshold: 10) }
describe 'as an admin' do
context 'when I visit an admin invoice show page' do
before { visit admin_invoice_path(invoice1) }
it { expect(page).to have_no_content('Success!') }
it { expect(page).to have_no_content('Error!') }
it 'displays the invoice detials: id, status, and created_at' do
expect(page).to have_current_path(admin_invoice_path(invoice1))
expect(page).to have_content("Invoice ##{invoice1.id}")
expect(page).to have_content("Created on: #{invoice1.formatted_date}")
expect(page).to have_no_content("Invoice ##{invoice2.id}")
end
it 'displays the customer details: name and address' do
expect(page).to have_content("#{customer1.first_name} #{customer1.last_name}")
expect(page).to have_content(customer1.address)
expect(page).to have_content("#{customer1.city}, #{customer1.state} #{customer1.zip}")
expect(page).to have_no_content("#{customer2.first_name} #{customer2.last_name}")
end
it 'displays all the items on the invoice and the item details: name, quantity, price, and status' do
within '#invoice-items' do
invoice1.invoice_items.each do |invoice_item|
expect(page).to have_content(invoice_item.item.name)
expect(page).to have_content(invoice_item.quantity)
expect(page).to have_content(number_to_currency(invoice_item.unit_price / 100.00))
expect(page).to have_content(number_to_currency(invoice_item.revenue / 100.00))
unless invoice_item.max_discount.nil?
expect(page).to have_content(number_to_currency(invoice_item.revenue_discount / 100.00))
expect(page).to have_content(number_to_currency(invoice_item.discounted_revenue / 100.00))
end
expect(page).to have_content(invoice_item.status.titleize)
end
expect(page).to have_no_content(item2a.name)
expect(page).to have_no_content(item2b.name)
expect(page).to have_no_content(item2c.name)
end
end
it 'displays the total revenue' do
expect(page).to have_content("Total Revenue: #{number_to_currency(invoice1.total_revenue / 100.00)}")
expect(page).to have_no_content(number_to_currency(invoice2.total_revenue / 100.00))
end
it 'displays the total discounts' do
expect(page).to have_content("Discounts: #{number_to_currency(-invoice1.revenue_discount / 100.00)}")
expect(page).to have_no_content(number_to_currency(invoice2.revenue_discount / 100.00))
end
it 'displays the total discounted revenue' do
expect(page).to have_content("Total Discounted Revenue: #{number_to_currency(invoice1.total_discounted_revenue / 100.00)}")
expect(page).to have_no_content(number_to_currency(invoice2.total_discounted_revenue / 100.00))
end
it 'has a status select field that updates the invoices status' do
within "#status-update-#{invoice1.id}" do
expect(invoice1.status).to eq('completed')
expect(page).to have_select('invoice[status]', selected: 'Completed')
expect(page).to have_button('Update')
select 'Cancelled', from: :invoice_status
click_button 'Update'
expect(page).to have_current_path(admin_invoice_path(invoice1))
expect(page).to have_select('invoice[status]', selected: 'Cancelled')
expect(invoice1.reload.status).to eq('cancelled')
end
expect(page).to have_content('Success! The invoice was updated.')
end
end
end
end
|
class DanceClass < ActiveRecord::Base
belongs_to :instructor
belongs_to :studio
validates :name, :instructor_id, :studio_id, :when, :time, :cost, :presence => true
validates :name, :uniqueness => true
end
|
# 4. Write a method that counts down to zero using recursion.
def count_down(start)
if start <= 0
puts start
else
puts start
count_down(start - 1)
end
end
count_down(10)
# Time to practice with the LS method.
def count_to_zero(number)
if number <= 0
puts number
else
puts number
count_to_zero(number-1)
end
end
count_to_zero(10)
count_to_zero(20)
count_to_zero(-3)
|
# frozen_string_literal: true
class ActivityChannel < ApplicationCable::Channel
def subscribed
ActionCable.server.broadcast('activity',
{ action: 'status_update', id: current_user.id, status: 'online' })
stream_from 'activity'
end
def unsubscribed
ActionCable.server.broadcast('activity',
{ action: 'status_update', id: current_user.id, status: 'offline' })
end
end
|
class Api::V1::EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :update, :destroy]
def index
json_response(Employee.all.paginate(page: params[:page], per_page: 20))
end
def show
json_response(@employee)
end
def create
employee = Employee.create!(employee_params)
json_response(employee, :created)
end
def update
@employee.update(employee_params)
head :no_content
end
def destroy
@employee.destroy
head :no_content
end
private
def employee_params
params.permit(:id, :name, :middle_name, :surname, :nationality, :gender,
:start_dt, :end_dt, :status, :job_title, :payment_method, :payment_per_hour,
:overtime_per_hour, :reason_for_leaving, :email_address, :landline_phone,
:mobile_phone, :address_street_1, :address_street_2, :postcode, :city,
:comment, :user_id, :dormant, :created_at, :updated_at, :created_by, :updated_by)
end
def set_employee
@employee = Employee.find(params[:id])
end
end
|
require "test_helper"
feature "
As a user,
I want to sign out when I'm done
so that my session is closed.
" do
scenario "sign out current user" do
# Given a current user
visit new_user_session_path
fill_in "Email", with: users(:eli).email
fill_in "Password", with: "password"
click_on "Sign in"
page.must_have_content "Signed in successfully"
page.must_have_content "Sign Out"
# When the sign out link is clicked
click_on "Sign Out"
# Then the session should be destroyed
page.must_have_content "Signed out successfully"
page.wont_have_content "Sign Out"
end
end
|
class InvoicesController < ApplicationController
before_action :set_invoice, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :set_user
def index
if current_user.role === "administrator"
@producer_invoices = []
@client_invoices = []
Invoice.all.each do |i|
unless i.users == []
if i.users.first.role == "producer"
@producer_invoices << i
elsif i.users.first.role == "client"
@client_invoices << i
end
end
end
else
@invoices = []
Invoice.all.each do |invoice|
if invoice.users.include?(current_user)
@invoices << invoice
end
end
@invoices
end
end
def show
@amount_due_from_client = 0
@invoice.episodes.each do |episode|
@amount_due_from_client += episode.client_cost
end
@amount_due_from_client.round(2)
@amount_due_to_producer = (@amount_due_from_client * 0.66).round(2)
@producer = fetch_producer(@invoice.users)
end
def new
@invoice = Invoice.new
end
def edit
end
def create
@invoice = Invoice.new(invoice_params)
respond_to do |format|
if @invoice.save
format.html { redirect_to @invoice, notice: 'Invoice was successfully created.' }
format.json { render :show, status: :created, location: @invoice }
else
format.html { render :new }
format.json { render json: @invoice.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @invoice.update(invoice_params)
format.html { redirect_to @invoice, notice: 'Invoice was successfully updated.' }
format.json { render :show, status: :ok, location: @invoice }
else
format.html { render :edit }
format.json { render json: @invoice.errors, status: :unprocessable_entity }
end
end
end
def destroy
@invoice.destroy
respond_to do |format|
format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
@user = User.find(current_user[:id])
end
def set_invoice
@invoice = Invoice.find(params[:id])
end
def invoice_params
params.require(:invoice).permit(
:amount_due_from_client, :status, :invoice_number, :invoice_date,
:payment_due, :users_id, :notes
)
end
def fetch_producer(users_array)
users_array.to_a.each do |user|
if user.role == "producer"
return user
end
end
end
end
|
namespace :reviews do
desc 'Syncs reviews with Google Sheet'
task sync: :environment do
Archiver::TweetArchiver.archive
puts 'Start syncing to sheet'
SheetSync::Download::SheetReader.download
puts 'Finshed syncing sheet successfully'
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.