text stringlengths 10 2.61M |
|---|
def roman(n)
result = ""
{"L" => 50,"X" => 10,"V" => 5,"I" => 1}.each do |letter, number|
result += letter * (n/number)
n = n%number
end
result
end
require "minitest/spec"
require "minitest/autorun"
describe "roman" do
it "converts the number 1 to the string I" do
roman(1).must_equal "I"
end
it "converts the number 2 to the string II" do
roman(2).must_equal "II"
end
it "convert the number 3 to the string III" do
roman(3).must_equal "III"
end
it "convert the number 4 to the string IIII" do
roman(4).must_equal "IIII"
end
it "converts the number 5 to the string V" do
roman(5).must_equal "V"
end
it "converts the number 6 to the string VI" do
roman(6).must_equal "VI"
end
it "converts the number 10 to the string X" do
roman(10).must_equal "X"
end
it "converts the number 9 to the string IX" do
roman(9).must_equal "VIIII"
end
it "converts the number 37 to the string XXXVII" do
roman(37).must_equal "XXXVII"
end
it "converts the number 50 to the string L" do
roman(50).must_equal "L"
end
end
|
require 'rails_helper'
require 'api/products_controller'
=begin
describe Api, type: :controller do
describe ProductsController, type: :controller do
render_views
context 'GET index' do
let!(:products) { create_list(:product, 10) }
let(:index_request) { get 'index', format: :json }
let(:response_json) { JSON.parse response.body }
before do
index_request
end
it do
binding.pry
expect(response_json['current_page']).to eq 1
end
end
end
end
=end
describe Api::ProductsController, type: :controller do
render_views
context 'GET index' do
let!(:products) { create_list(:product, 10) }
let(:index_request) { get 'index', format: :json}
let(:response_json) { JSON.parse response.body }
before do
index_request
end
context 'without token' do
it do
expect(response_json['error']).to eq 'Invalid token'
end
end
context 'with token' do
let!(:current_user) { create(:user) }
let(:index_request) { get 'index', format: :json,params:{ auth_token: current_user.auth_token} }
it do
expect(response_json['current_page']).to eq 1
expect(response_json['products'].count).to eq 5
end
end
context 'with token in header' do
let!(:current_user) { create(:user) }
let(:index_request) do
request.headers['X-Auth-Token'] = current_user.auth_token
get :index, format: :json,params:{per: 5}
end
it do
expect(response_json['current_page']).to eq 1
expect(response_json['products'].count).to eq 5
end
end
end
end
|
def uncommon_from_sentences(s1, s2)
counts = {}
arr = [s1 + " " + s2]
arr.each do |word|
all_words = word.split(" ")
all_words.each do |single_word|
counts[single_word] = counts[single_word] ? counts[single_word] + 1 : 1
end
final_value = counts.select {|key, value| value == 1 }
return final_value.keys
end
end
# A sentence is a string of single-space separated words where each word consists only of lowercase letters.
# A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
# Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.
# Example 1:
# Input: s1 = "this apple is sweet", s2 = "this apple is sour"
# Output: ["sweet","sour"]
# Example 2:
# Input: s1 = "apple apple", s2 = "banana"
# Output: ["banana"]
# Runtime: 52 ms, faster than 60.00% of Ruby online submissions for Uncommon Words from Two Sentences.
# Memory Usage: 210.1 MB, less than 30.00% of Ruby online submissions for Uncommon Words from Two Sentences.
# Next challenges
|
require 'spec_helper'
describe Task do
it { should belong_to(:category) }
it { should have_many(:entries).through(:entry_tasks) }
it { should have_many(:entry_tasks) }
it { should validate_uniqueness_of(:name) }
[:name ].each do |m|
it { should validate_presence_of(m) }
end
end
|
def reverse(arr)
reversed = Array.new(arr.count(arr))
index = arr.count(arr) - 1
arr.each_char do |char|
reversed[index] = char
index -= 1
end
reversed.join()
end
phrase = "This is part 4 of our live session series on “Beginning Ruby”."
p reverse(phrase) |
class SidekiqPlansController < ApplicationController
before_action :set_sidekiq_plan, only: [:show, :edit, :update, :destroy]
# GET /sidekiq_plans
def index
@sidekiq_plans = SidekiqPlan.all
end
# GET /sidekiq_plans/1
def show
end
# GET /sidekiq_plans/new
def new
@sidekiq_plan = SidekiqPlan.new
end
# GET /sidekiq_plans/1/edit
def edit
end
# POST /sidekiq_plans
def create
@sidekiq_plan = SidekiqPlan.new(sidekiq_plan_params)
@sidekiq_plan.jid = 0
@sidekiq_plan.status = :initial
if @sidekiq_plan.save
@sidekiq_plan.enqueue
redirect_to @sidekiq_plan, notice: 'Sidekiq plan was successfully created.'
else
render :new
end
end
# PATCH/PUT /sidekiq_plans/1
def update
if @sidekiq_plan.update(sidekiq_plan_params)
redirect_to @sidekiq_plan, notice: 'Sidekiq plan was successfully updated.'
else
render :edit
end
end
# DELETE /sidekiq_plans/1
def destroy
@sidekiq_plan.destroy
redirect_to sidekiq_plans_url, notice: 'Sidekiq plan was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_sidekiq_plan
@sidekiq_plan = SidekiqPlan.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def sidekiq_plan_params
params.require(:sidekiq_plan).permit(:label, :worker_name, :perform_at)
end
end
|
#collecting user information: the client's name, age, number of children, decor theme,
puts "Enter client information"
puts
puts "client first name"
name1 = gets.chomp
puts "client last name"
name2 = gets.chomp
puts "client age"
age = gets.chomp
puts "number of children"
children = gets.chomp
puts "Would you like a decor theme?"
decore = gets.chomp
# will update hash with user input
if decore == "no"
puts
elsif decore == "yes"
puts "Ok what would you like"
answer = gets.chomp
elsif
puts "huh?"
end
# will add these items to hash
p client = {client_first_name: name1,
client_last_name: name2,
client_age: age,
number_of_children: children,
decor_theme: answer}
puts
puts "Please review your information"
puts
puts client [:client_first_name]
puts client [:client_last_name]
puts client [:client_age]
puts client [:number_of_children]
puts client [:decor_theme]
|
# frozen_string_literal: true
class CardKeysController < ApplicationController
before_action :admin_required
before_action :set_card_key, only: %i[show edit update destroy]
def index
@card_keys = CardKey.all.sort_by { |ck| [ck.user&.name || '', ck.label] }
end
def show
edit
end
def new
@card_key ||= CardKey.new
load_form_data
render :new
end
def edit
load_form_data
render :edit
end
def create
@card_key = CardKey.new(card_key_params)
if @card_key.save
redirect_to card_keys_path, notice: 'Card key was successfully created.'
else
new
end
end
def update
if @card_key.update(card_key_params)
redirect_to card_keys_path, notice: 'Nøkkelkortet ble oppdatert.'
else
edit
end
end
def destroy
@card_key.destroy
respond_to do |format|
format.html { redirect_to card_keys_url, notice: 'Nøkkelkortet ble slettet.' }
format.json { head :no_content }
end
end
private
def load_form_data
@users = Member.active.includes(:user).map(&:user).sort_by(&:name)
end
# Use callbacks to share common setup or constraints between actions.
def set_card_key
@card_key = CardKey.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def card_key_params
params.require(:card_key).permit(:label, :office_key, :user_id, :comment)
end
end
|
require 'json'
require 'net/http'
class XKCDReceiver
def initialize(args)
@tweet_object = args[:object]
@twitter_client = Jarvis::API::Addons.client(:twitter)
match? @tweet_object.text
end
def match?(text)
case text
when (/(xkcd)\s*(help)/i)
answer("xkcd = latest / xkcd NUM = grab this comic / xkcd random = grab random comic")
when (/xkcd\s*latest/i)
latest
when (/xkcd\s*(\d+)/i)
grab($1)
when (/xkcd\s*random/i)
grab()
end
end
def latest
url = "http://xkcd.com/info.0.json"
resp = Net::HTTP.get_response(URI.parse(url))
infos = JSON.load(resp.body)
answer("#{infos['img']} #{infos['safe_title']} - #{infos['alt']}" )
end
def grab(number=nil)
if number.nil?
max = JSON.load(Net::HTTP.get_response(URI.parse("http://xkcd.com/info.0.json")).body)['num']
url = "http://xkcd.com/#{rand(1..max)}/info.0.json"
resp = Net::HTTP.get_response(URI.parse(url))
infos = JSON.load(resp.body)
else
url = "http://xkcd.com/#{number}/info.0.json"
resp = Net::HTTP.get_response(URI.parse(url))
infos = JSON.load(resp.body)
end
answer("#{infos['img']} #{infos['safe_title']} - #{infos['alt']}" )
end
def answer(message)
unique = Digest::MD5.hexdigest(@tweet_object.to_s)[0..3]
message = "#{message} ##{unique}"
if @tweet_object.is_a? Twitter::Tweet
options = { in_reply_to_status: @tweet_object }
@twitter_client.update("@#{@tweet_object.user.screen_name} #{message}"[0...139], options)
elsif @tweet_object.is_a? Twitter::DirectMessage
user = @tweet_object.sender.id
@twitter_client.create_direct_message(user, message[0...139])
end
end
end
|
#!/usr/bin/env ruby
class Calc
def evaluate_expression(expression)
expression = expression.strip().delete(' ')
until expression.match(/\A\d+\z/)
if expression.include?("(")
open, close = matching_parens(expression)
paren_value = evaluate_expression(expression[open+1..close-1])
expression = expression.gsub(expression[open..close], paren_value)
else
expression = evaluate_simple_expression(expression)
end
end
expression
end
protected
def matching_parens(expression)
open = expression.rindex('(')
close = open + expression[open...].index(')')
[open, close]
end
def evaluate_simple_expression(expression)
value = expression.match(/\A(\d+)/)[1]
expression = expression[value.length...]
value = value.to_i
until expression.empty?
operator, operand = expression.match(/\A([+*])(\d+)/).captures
expression = expression[operand.length+1...]
case operator
when '+'
value += operand.to_i
when '*'
value *= operand.to_i
end
end
value.to_s
end
end
calc = Calc.new
result = File.open('data_math_hw.txt').sum do |line|
calc.evaluate_expression(line).to_i
end
puts result
|
class ChangeDurationToFlot < ActiveRecord::Migration[5.2]
def change
add_column :services, :duration_float, :float
end
end
|
#https://github.com/fredwu/ruby_decorators
module MethodDecorator
def self.extended(klass)
define_method(klass.name) do
raise "foo"
end
end
end
|
module Domotics::Core
class Element
@@data = DataHash.new
attr_reader :name, :type, :room, :device
def initialize(args = {})
@room = args[:room]
@device = args[:device]
@room.register_element self, @name = args[:name]
@type ||= :element
set_state(self.state || :off)
end
def load_driver(args = {})
return unless args[:device_type]
device_space = args[:device_type].to_s.split("_").map{ |x| x.capitalize }.join
self.class.class_eval(%(include Domotics::#{device_space}::#{args[:driver]}), __FILE__, __LINE__)
end
def state
@@data[self].state
end
def verbose_state
{ @room.name =>
{ :elements =>
{ @name =>
{ :state => state,
:info => info,
:img => image,
}
}
}
}
end
def info
nil
end
def image
nil
end
def set_state(value)
@@data[self].state = value
@room.notify({ event: :state_set, element: self }) unless @type == :dimmer
end
def state_changed(value)
@@data[self].state = value
@room.notify event: :state_changed, element: self
end
def self.data=(value)
@@data = value
end
def to_s
"#{@room.name}@#{@name}(id:#{__id__})"
end
end
end
|
require 'spec_helper'
describe Group do
before(:all) do
@group = FactoryGirl.create(:group)
end
context "initialize params" do
it "contain an id" do
expect(@group.id).to_not be_nil
expect(@group.id).to be_a(Integer)
end
it "contains a name" do
expect(@group.name).to_not be_nil
expect(@group.name).to be_a(String)
end
end
context "find by category id" do
context "with valid id" do
it "returns an Array of Groups" do
expect(Group.find_by_category_id(9)).to_not be_nil
expect(Group.find_by_category_id(9)).to be_a(Array)
expect(Group.find_by_category_id(9)).to_not be_empty
Group.find_by_category_id(9).each do |group|
expect(group).to be_a(Group)
end
end
end
context "with invalid id" do
it "returns an empty Array" do
expect(Group.find_by_category_id(0)).to_not be_nil
expect(Group.find_by_category_id(0)).to be_a(Array)
expect(Group.find_by_category_id(0)).to be_empty
end
end
end
context "select all members" do
it "returns an Array of Blueprints" do
expect(@group.members).to_not be_nil
expect(@group.members).to be_a(Array)
expect(@group.members).to_not be_empty
@group.members.each do |member|
expect(member).to be_a(Blueprint)
end
end
end
context "members" do
it "must have the groups id" do
@group.members.each do |member|
expect(member.group["id"].to_i).to be == @group.id
end
end
end
end
|
class Contact
include ActiveModel::Model
attr_accessor :name, :phone, :email, :message
validates :email, :message, :name, :phone, presence: true
validates :message, length: {maximum: 300}
validates :phone, length: {maximum: 12}
validates :email, format: {with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/}
def notify
AdminMailer.contact_us(self).deliver
end
end
|
# Static database for small installations. To use it, write:
# Golem.configure do |cfg|
# cfg.db = 'static'
# Golem::DB.setup do |db|
# db.add_user 'test_user'
# db.add_repository 'test_repository', 'test_user'
# db.add_key 'test_user', 'test_key'
# end
# end
class Golem::DB::Static
# Create database, initialize users, repositories and ssh_keys to [].
def initialize
@users, @repositories, @ssh_keys = [], [], []
end
# Retrieve users.
# @param [Hash] opts options, see {Golem::DB}.
# @return [Array] list of users.
def users(opts = {})
opts[:return] == :array ? @users.collect {|u| u[:name]} : @users
end
# Retrieve repositories.
# @param [Hash] opts options, see {Golem::DB}.
# @return [Array] list of repotitories.
def repositories(opts = {})
opts[:return] == :array ? @repositories.collect {|r| r[:name]} : @repositories
end
# Retrieve ssh keys.
# @param [Hash] opts options, see {Golem::DB}.
# @return [Array] list of keys.
def ssh_keys(opts = {})
opts[:return] == :array ? @ssh_keys.collect {|k| [k[:user_name], k[:key]]} : @ssh_keys
end
# Add user to database.
# @param [String] name username,
# @return [Array] list of users.
def add_user(name)
@users << {:name => name}
end
# Add repository to database.
# @param [String] name repository name,
# @param [String] user_name username.
# @return [Array] list of repositories.
def add_repository(name, user_name)
abort "Cannot add repository, user not found!" unless users(:return => :array).include?(user_name)
@repositories << {:name => name, :user_name => user_name}
end
# Add key to database.
# @param [String] user_name username,
# @param [String] key ssh key (e.g. +cat id_rsa.pub+).
# @return [Array] list of keys.
def add_key(user_name, key)
abort "Cannot add key, user not found!" unless users(:return => :array).include?(user_name)
@ssh_keys << {:user_name => user_name, :key => key}
end
# Setup database.
def setup(&block)
yield self
end
end
|
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def github
auth = request.env["omniauth.auth"]
token = UserOauthToken.find_by_provider_and_uid(auth["provider"], auth["uid"].to_s)
if token
Rails.logger.info "user has persisted"
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Github"
sign_in_and_redirect(:user, token.user)
elsif current_user
Rails.logger.info "associated the current user and the github account"
current_user.user_oauth_tokens.create!(:provider => auth["provider"], :uid => auth["uid"].to_s, :access_token => auth["credentials"]["token"] )
current_user.nickname = auth["user_info"]["nickname"]
current_user.save!
flash[:notice] = "Successfully associated your Github account"
redirect_to dashboard_path()
else
user = User.new
user.apply_omniauth(auth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session["devise.github_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
def passthru
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
end |
class AddTagsCountToTagText < ActiveRecord::Migration
def change
TagText.reset_column_information
add_column(:tag_texts, :tags_count, :integer, default: 0) unless TagText.column_names.include?('tags_count')
end
end
|
require 'rltk/cg/llvm'
require 'rltk/cg/module'
# tells LLVM we are using x86 arch
RLTK::CG::LLVM.init(:X86)
module JS
class JIT
attr_reader :module
def initialize
@module = RLTK::CG::Module.new('JS JIT')
@builder = RLTK::CG::Builder.new
@st = Hash.new
end
def add(ast)
case ast
when Expression then translate_function(Function.new(Prototype.new('',[]), ast))
when Function then translate_function(ast)
when Prototype then translate_prototype(ast)
else raise 'Attempting to add an unhandled node type to the JIT.'
end
end
def translate_expression(node)
case node
when Assign
right = translate_expression(node.right)
alloca = if @st.has_key?(node.name)
@st[node.name]
else
@st[node.name] = @builder.alloca(RLTK::CG::DoubleType, node.name)
end
@builder.store(right, alloca)
when Binary
left = translate_expression(node.left)
right = translate_expression(node.right)
case node
when Add
@builder.fadd(left, right, 'addtemp')
when Sub
@builder.fadd(left, right, 'subtemp')
when Mul
@builder.fadd(left, right, 'multmp')
when Div
@builder.fadd(left, right, 'divtmp')
end
when Call
callee = @module.functions[node.name]
if not callee
raise 'Unknown function'
end
if callee.params.size != node.args.length
raise 'Function argument does not match'
end
args = node.args.map { |arg| translate_expression(arg)}
@builder.call(callee, *args.push('calltmp'))
when Variable
if @st.key?(node.name)
@st[node.name]
else
raise "Uninitialized variable"
end
when Number
RLTK::CG:Double.new(node.value)
when Str
RLTK::CG::Double.new(1.to_s)
end
end
def translate_function(node)
# Reset the symbol table.
@st.clear
# Translate the function's prototype.
fun = translate_prototype(node.proto)
# Create a new basic block to insert into, translate the
# expression, and set its value as the return value.
fun.blocks.append('entry', @builder, nil, self) do |jit|
ret jit.translate_expression(node.body)
end
# Verify the function and return it.
returning(fun) { fun.verify }
end
def translate_prototype(node)
if fun = @module.functions[node.name]
if fun.blocks.size != 0
raise "Redefinition of function #{node.name}."
elsif fun.params.size != node.arg_names.length
raise "Redefinition of function #{node.name} with different number of arguments."
end
else
fun = @module.functions.add(node.name, RLTK::CG::DoubleType, Array.new(node.arg_names.length, RLTK::CG::DoubleType))
end
# Name each of the function paramaters.
returning(fun) do
node.arg_names.each_with_index do |name, i|
(@st[name] = fun.params[i]).name = name
end
end
end
end
end
|
# Helper functions used throughout the Gallery
module GalleryLib
class << self
# Is the string a uuid?
def uuid?(str)
/^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/.match(str)
end
# Does the string look like a valid email address?
def valid_email?(str)
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.match(str)
end
# Build list of extensions
def extensions
entries = {}
GalleryConfig.directories.extensions.each do |dir|
Dir["#{dir}/*"].each do |extension_dir|
next unless File.directory?(extension_dir)
# Must be a .rb file matching the directory name
name = File.basename(extension_dir)
rb_file = File.join(extension_dir, "#{name}.rb")
next unless File.exist?(rb_file)
# Must not be disabled
if GalleryConfig.dig(:extensions, :disable, name)
if defined?(Rails.logger) && Rails.logger
Rails.logger.debug("Extension #{name} is disabled")
else
puts "Extension #{name} is disabled" # rubocop: disable Rails/Output
end
next
end
# Do we need to load extensions in a certain order?
order = GalleryConfig.dig(:extensions, :order, name)
entries[name] = {
name: name,
dir: extension_dir,
file: rb_file,
order: order ? order : 100
}
# Does it include a config file?
config = File.join(extension_dir, "#{name}.yml")
entries[name][:config] = config if File.exist?(config)
end
end
entries.sort_by {|a,b| b[:order]}
end
# Fill and sort chart data - single series
def chart_prep_single(data, keys, value)
data = data.to_h
keys.each {|k| data[k] ||= value}
data.to_a.sort_by(&:first).to_h
end
# Fill and sort chart data - multiple series
def chart_prep_multi(data, keys, value)
# Union all series keys
data.each do |series|
keys.merge(series[:data].to_a.map(&:first))
end
# Fill values for each series
data.each do |series|
series[:data] = chart_prep_single(series[:data], keys, value)
end
data
end
# Fill and sort chart data
def chart_prep(data, options={})
keys = Set.new(options[:keys] || [])
value = options[:value] || 0.0
if data.is_a?(Array) && data.first&.is_a?(Hash)
chart_prep_multi(data, keys, value)
else
chart_prep_single(data, keys, value)
end
end
# Last N days
def last_n_days(n=30)
(0...n).map {|i| i.day.ago}.sort
end
# Escape the highlight snippet returned by Solr
def escape_highlight(s)
return s if s.blank?
# Escape HTML but then unescape tags that Solr added
CGI.escapeHTML(s)
.gsub('<b>', '<b>')
.gsub('</b>', '</b>')
.gsub('<i>', '<i>')
.gsub('</i>', '</i>')
.gsub('<em>', '<em>')
.gsub('</em>', '</em>')
.gsub('<br>', '<br>')
end
end
# Helper functions for notebook diffs
module Diff
# Stylesheet for diffs
def self.css
"<style type='text/css'>\n#{Diffy::CSS}\n</style>"
end
# Inline diff (like running diff -u)
def self.inline(before, after)
Diffy::Diff.new(before, after).to_s(:html)
end
# Side-by-side diff
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/BlockLength
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def self.split(before, after)
diff = Diffy::SplitDiff.new(before, after, format: :html)
# The diffs don't line up. Walk the two sides and insert
# blank lines to make them line up.
begin
left_in = diff.left.split("\n")
right_in = diff.right.split("\n")
left_out = []
right_out = []
left_pos = 0
right_pos = 0
loop do
break if left_pos >= left_in.size or right_pos >= right_in.size
#puts
#puts "left=#{left_pos}/#{left_in.size} #{left_in[left_pos]}"
#puts "right=#{right_pos}/#{right_in.size} #{right_in[right_pos]}"
# First, regex to see if this is unchanged/insert/delete.
# We should only get 'nil' at the same time when scanning
# the header and trailer rows.
left = /^ +<li class="([^"]+)">/.match left_in[left_pos]
if left.nil?
left_out.push left_in[left_pos]
left_pos += 1
end
right = /^ +<li class="([^"]+)">/.match right_in[right_pos]
if right.nil?
right_out.push right_in[right_pos]
right_pos += 1
end
next if left.nil? and right.nil?
# Second, add blank lines if necessary
#p [left[1], right[1]]
case [left[1], right[1]]
when %w[unchanged unchanged], %w[del ins], %w[ins del]
# pass through and advance both sides
left_out.push left_in[left_pos]
left_pos += 1
right_out.push right_in[right_pos]
right_pos += 1
when %w[unchanged del], %w[unchanged ins]
# insert a blank on the left; advance the right
left_out.push ' <li class="unchanged"><span> </span></li>'
right_out.push right_in[right_pos]
right_pos += 1
when %w[del unchanged], %w[ins unchanged]
# insert a blank on the right; advance the left
left_out.push left_in[left_pos]
left_pos += 1
right_out.push ' <li class="unchanged"><span> </span></li>'
else
# shouldn't happen, but break to prevent infinite loop
break
end
end
# We should hit the end of both sides at the same time, but
# if not, add the remainder back in.
left_out += left_in[left_pos..-1] if left_pos != left_in.size
right_out += right_in[right_pos..-1] if right_pos != right_in.size
# Empty spans don't have the same height, so insert spaces.
[left_out, right_out].each do |arr|
arr.map! do |str|
str.sub('<ins></ins>', '<ins> </ins>')
.sub('<del></del>', '<del> </del>')
.sub('<span></span>', '<span> </span>')
end
end
[left_out.join("\n"), right_out.join("\n")]
rescue StandardError #=> ex
# If there's an error, just return the raw diff.
#p ex
[diff.left, diff.right]
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/BlockLength
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# All the diff types together
def self.all_the_diffs(before, after)
diff = Diffy::Diff.new(before, after)
{
different: diff.count.positive?,
css: css,
inline: diff.to_s(:html),
split: split(before, after)
}
end
end
end
|
class CompanyDecorator < RKit::Decorator::Base
def count_badges
self.badges.flatten.group_by{ |elem| elem }.map{ |k,v| [k, v.count] }
end
def total_badges
self.badges.count
end
end
|
module OSMLib
module Element
# OpenStreetMap Relation.
#
# To create a new OSMLib::Element::Relation object:
# relation = OSMLib::Element::Relation.new(331, 'user', '2007-10-31T23:51:53Z')
#
# To get a relation from the API:
# relation = OSMLib::Element::Relation.from_api(17)
#
class Relation < OSMLib::Element::Object
# Array of Member objects
attr_reader :members
# Create new Relation object.
#
# If +id+ is +nil+ a new unique negative ID will be allocated.
def initialize(id=nil, user=nil, timestamp=nil, members=[], uid=-1, version=1, visible=nil)
@members = members
super(id, user, timestamp, uid, version, visible)
end
def type
'relation'
end
# Add one or more tags or members to this relation.
#
# The argument can be one of the following:
#
# * If the argument is a Hash or an OSMLib::Element::Tags object, those tags are added.
# * If the argument is an OSMLib::Element::Member object, it is added to the relation
# * If the argument is an Array the function is called recursively, i.e. all items in the Array are added.
#
# Returns the relation to allow chaining.
#
# call-seq: relation << something -> Relation
#
def <<(stuff)
case stuff
when Array # call this method recursively
stuff.each do |item|
self << item
end
when OSMLib::Element::Member
members << stuff
else
tags.merge!(stuff)
end
self # return self to allow chaining
end
# Raises a NoGeometryError.
#
# Future versions of this library may recognize certain relations
# that do have a geometry (such as Multipolygon relations) and do
# the right thing.
def geometry
raise OSMLib::Error::NoGeometryError.new("Relations don't have a geometry")
end
# Returns a polygon made up of all the ways in this relation. This
# works only if it is tagged with 'polygon' or 'multipolygon'.
def polygon
raise OSMLib::Error::NoDatabaseError.new("can't create Polygon from relation if it is not in a OSMLib::Database") if @db.nil?
raise OSMLib::Error::NoDatabaseError.new("can't create Polygon from relation if it does not represent a polygon") if self['type'] != 'multipolygon' and self['type'] != 'polygon'
c = []
member_objects.each do |way|
raise TypeError.new("member is not a way so it can't be represented as Polygon") unless way.kind_of? OSMLib::Element::Way
raise OSMLib::Error::NotClosedError.new("way is not closed so it can't be represented as Polygon") unless way.is_closed?
raise OSMLib::Error::GeometryError.new("way with less then three nodes can't be turned into a polygon") if way.nodes.size < 3
c << way.node_objects.collect{ |node| [node.lon.to_f, node.lat.to_f] }
end
GeoRuby::SimpleFeatures::Polygon.from_coordinates(c)
end
# Return all the member objects of this relation.
def member_objects
members.collect do |member|
obj = case member.type
when :node, 'node' then @db.get_node(member.ref)
when :way, 'way' then @db.get_way(member.ref)
when :relation, 'relation' then @db.get_relation(member.ref)
end
raise OSMLib::Error::NotFoundError.new("not in database: #{member.type} #{member.ref}") unless obj
obj
end
end
# Return string version of this Relation object.
#
# call-seq: to_s -> String
#
def to_s
if @visible == nil
"#<OSMLib::Element::Relation id=\"#{@id}\" user=\"#{@user}\" timestamp=\"#{@timestamp}\">"
else
"#<OSMLib::Element::Relation id=\"#{@id}\" user=\"#{@user}\" timestamp=\"#{@timestamp}\" visible=\"#{@visible}\">"
end
end
# Return the member with a specified type and id. Returns nil
# if not found.
#
# call-seq: member(type, id) -> OSMLib::Element::Member
#
def member(type, id)
members.select{ |member| member.type == type && member.ref == id }[0]
end
# Return XML for this relation. This method uses the Builder library.
# The only parameter ist the builder object.
def to_xml(xml)
xml.relation(attributes) do
members.each do |member|
member.to_xml(xml)
end
tags.to_xml(xml)
end
end
end
# A member of an OpenStreetMap Relation.
class Member
# Role this member has in the relationship
attr_accessor :role
# Type of referenced object (can be 'node', 'way', or 'relation')
attr_reader :type
# ID of referenced object
attr_reader :ref
# Create a new Member object. Type can be one of 'node', 'way' or
# 'relation'. Ref is the ID of the corresponding Node, Way, or
# Relation. Role is a freeform string and can be empty.
def initialize(type, ref, role='')
if type !~ /^(node|way|relation)$/
raise ArgumentError.new("type must be 'node', 'way', or 'relation'")
end
if ref.to_s !~ /^[0-9]+$/
raise ArgumentError
end
@type = type
@ref = ref.to_i
@role = role
end
# Return XML for this way. This method uses the Builder library.
# The only parameter ist the builder object.
def to_xml(xml)
xml.member(:type => type, :ref => ref, :role => role)
end
end
end
end |
require 'graphviz'
require 'bloomit'
module Kantox
module Refactory
module Model
class Telescope
COLORS = [0xFF, 0xCC, 0x88, 0x44, 0].repeated_permutation(3).to_a.shuffle
attr_reader :tree, :yielded
# @param [String|Symbol|::ActiveRecord::Reflection] model
def initialize model, levels = 20, count_through = true
@model = model
@count_through = count_through
@levels = levels
@yielded = [PinceNez.new(model)]
(@tree = {})[@yielded.first] = crawl_level @yielded.first, @levels
end
def to_graph reuse_nodes = true, filename = nil
g = GraphViz.new(:G, :type => :digraph)
@tree.each do |_, v|
root = g.add_nodes v[:model].name, { shape: :box, style: :filled, color: yield_color(v[:model].name) }
level_to_graph g, root, v[:children], { v[:model].name => root }, [], @levels, reuse_nodes
end
puts "Will write doc/#{@tree.keys.map(&:name).join('+')}_#{@count_through ? 'thru' : 'direct'}_#{reuse_nodes ? 'uniq' : 'all'}_#{@levels}.png"
g.output(png: filename || "doc/#{@tree.keys.map(&:name).join('+')}_#{@count_through ? 'thru' : 'direct'}_#{reuse_nodes ? 'uniq' : 'all'}_#{@levels}.png")
end
def to_plant_uml filename = nil
plantuml = "@startuml\n" # scale 8000 width\n"
@tree.each do |_, v|
plantuml << level_to_plant_uml(v)
end
plantuml << "\n@enduml"
filename ||= "doc/#{@tree.keys.map(&:name).join('+')}.plantuml"
File.open(filename, 'w') do |f|
f.puts plantuml
end
end
private
def yielded tree = @tree
tree.keys | tree.values.inject([]) do |memo, v|
memo << yielded(v) if v.is_a?(Hash)
memo
end
end
def crawl_level model, levels
{
model: model,
children: levels <= 0 ? {} : model.crawl(@count_through).map do |name, r|
ar = r[:reflection].model_class
[
name,
@yielded.include?(ar) ? { model: r[:pince_nez], type: r[:reflection].macro, children: {} } :
begin
@yielded << ar
crawl_level r[:pince_nez], levels - 1
end
]
end.to_h
}
end
def yield_color model_name
@colors ||= {}
@colors[model_name] ||= model_name.to_color # COLORS[@colors.size % COLORS.size]
# "##{@colors[model_name].map { |c| "%02x" % c }.join}"
end
def graph_node_params model, reuse_nodes, levels
# reuse_nodes ?
# [model.name, "grey#{30 + (@levels - levels) * 70 / @levels}"] :
# ["#{model.name}:#{model.__id__}", yield_color(model.name)]
[reuse_nodes ? model.name : "#{model.name}:#{model.__id__}", yield_color(model.name)]
end
def level_to_graph g, root, children, nodes, edges, levels, reuse_nodes
return if levels.zero?
children.each do |k, v|
node_name, node_color = graph_node_params(v[:model], reuse_nodes, levels)
opts = { style: :filled, color: node_color }
subroot = nodes[node_name] || g.add_nodes(node_name, opts).tap { |n| nodes[node_name] = n }
next if edges.include? [root, subroot, k]
g.add_edges(root, subroot, { label: k })
edges << [root, subroot, k]
level_to_graph g, subroot, v[:children], nodes, edges, levels - 1, reuse_nodes
end
end
def level_to_plant_uml model
model[:children].inject([]) do |memo, (k, v)|
# FIXME different types of connectors
memo << "#{model[:model].name} #{'o' if v[:type] == :belongs_to}-- #{v[:model].name} : #{k} >" \
<< level_to_plant_uml(v)
end.join("\n")
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe '#asset_url' do
it 'returns the absolute path of an asset' do
expect(helper.asset_url('quasars_logo.svg'))
.to match(%r{http://test.host/assets/quasars_logo})
end
end
end
|
FactoryGirl.define do
sequence :email do |n|
"cfajitas@gmail.com"
end
end
FactoryGirl.define do
factory :user, :class => 'User' do
email 'cfajitas@gmail.com'
password 'password1'
password_confirmation 'password1'
factory :admin do
admin true
end
end
end
FactoryGirl.define do
factory :apparel do
Apparel_ID '1'
Sex 'Male'
Article 'Suit'
Size '32'
Status 'In'
end
end
FactoryGirl.define do
factory :rental do
Rental_ID '1'
UIN '123456789'
Apparel_ID '12'
Checkout_Date '04-12-2016'
Expected_Return_Date '04-16-2016'
Return_Date '04-14-2016'
end
end
FactoryGirl.define do
factory :student do
UIN '123456789'
First_Name 'John'
Last_Name 'Smith'
Email 'Smith@tamu.edu'
Phone_Number '1234567890'
end
end |
class Preference < ApplicationRecord
# Direct associations
has_many :restaurants,
:dependent => :destroy
has_many :shops,
:dependent => :destroy
has_many :routes,
:dependent => :destroy
has_many :users,
:dependent => :destroy
# Indirect associations
# Validations
validates :taste, presence: true
validates :style, presence: true
validates :gender, presence: true
validates :taste, uniqueness: {scope: [:style, :gender], message: ", Style, and Gender combination already exists!"}
end
|
class V1::StoragesController < ApplicationController
before_action :authentication
def create
return head :bad_request if params[:bucket].blank?
render json: UpYun.token(params[:bucket], current_user), status: :created
end
end
|
class TrendingGroup < ActiveRecord::Base
self.table_name = 'trending_groups'
after_initialize :readonly!
belongs_to :group
default_scope ->{ order('score DESC').includes(:group) }
def self.not_joined_by_user(user)
user = user.id if user.is_a?(User)
TrendingGroup.where.not(
group: GroupMember.where(user_id: user).select(:group_id)
)
end
def self.groups
select(:group_id).map { |x| x.group }
end
end
|
=begin
TODO :
- handle walls better : playing with visibility, but also w, l, x, and z related to other walls
=end
require 'json'
class TiledMap
def initialize(filename)
infos = JSON.parse(File.read(filename))
@width = infos['width']
@height = infos['height']
infos['layers'].each do |layer|
case layer['name']
when 'floors'
@tiles = layer["data"].map {|e| e - 1}
when 'walls'
@walls = layer["data"].map {|e| e - 1}
end
end
@tile_size = 16
@tileset = GLTexture.load_tiles('gfx/tileset.png', @tile_size, @tile_size)
@wallset = GLTexture.load_tiles('gfx/wallset.png', @tile_size, @tile_size * 3)
remove_below_walls_tiles
@tiles_rects = auto_rectangles(@tiles)
@walls_rects = auto_rectangles(@walls)
end
def remove_below_walls_tiles
@walls.each_with_index do |wall, id|
if wall != -1
@tiles[id] = -1
end
end
end
def auto_rectangles(data)
@reserved = []
rects = {}
@height.times do |y|
@width.times do |x|
next if defined?(@reserved) && @reserved.include?([x, y])
rect = get_rectangle(data, x, y)
unless rect.nil?
tile, x, z, w, l = rect
rects[tile] = [] unless rects.has_key?(tile)
rects[tile].push [x, z, w, l]
end
end
end
return rects
end
def get_tile(data, x, y)
data[y * @width + x]
end
def get_rectangle(data, x, y)
return nil if @reserved.include?([x, y])
tile = get_tile(data, x, y)
return nil if tile == -1
min_x = x
try_x = x
while try_x >= 0
if !@reserved.include?([try_x, y]) && get_tile(data, try_x, y) == tile
min_x = try_x
try_x -= 1
else
break
end
end
max_x = x
for try_x in x...@width
if !@reserved.include?([try_x, y]) && get_tile(data, try_x, y) == tile
max_x = try_x
else
break
end
end
min_y = y
try_y = y - 1
while try_y >= 0
tile_ok = true
for try_x in min_x..max_x
tile_ok = false if @reserved.include?([try_x, try_y]) || get_tile(data, try_x, try_y) != tile
end
if tile_ok
min_y = try_y
try_y -= 1
else
break
end
end
max_y = y
for try_y in (y + 1)...@height
tile_ok = true
for try_x in min_x..max_x
tile_ok = false if @reserved.include?([try_x, try_y]) || get_tile(data, try_x, try_y) != tile
end
if tile_ok
max_y = try_y
else
break
end
end
for y in min_y..max_y
for x in min_x..max_x
@reserved.push [x, y]
end
end
return [tile, min_x, min_y, max_x - min_x + 1, max_y - min_y + 1]
end
def draw
@tiles_rects.each do |tile_id, quads|
glBindTexture(GL_TEXTURE_2D, @tileset[tile_id].get_id)
glPushMatrix
glScalef(@tile_size, @tile_size, @tile_size)
glBegin(GL_QUADS)
quads.each do |quad|
x, z, w, l = quad
glTexCoord2d(0, 0); glVertex3i(x, 0, z)
glTexCoord2d(0, l); glVertex3i(x, 0, z+l)
glTexCoord2d(w, l); glVertex3i(x+w, 0, z+l)
glTexCoord2d(w, 0); glVertex3i(x+w, 0, z)
end
glEnd
glPopMatrix
end
# walls tops
@walls_rects.each_value do |quads|
glBindTexture(GL_TEXTURE_2D, @tileset[0].get_id)
glPushMatrix
glScalef(@tile_size, @tile_size, @tile_size)
glBegin(GL_QUADS)
quads.each do |quad|
x, z, w, l = quad
glTexCoord2d(0, 0); glVertex3i(x, 3, z)
glTexCoord2d(0, l); glVertex3i(x, 3, z+l)
glTexCoord2d(w, l); glVertex3i(x+w, 3, z+l)
glTexCoord2d(w, 0); glVertex3i(x+w, 3, z)
end
glEnd
glPopMatrix
end
@walls_rects.each do |tile_id, quads|
glBindTexture(GL_TEXTURE_2D, @wallset[tile_id].get_id)
glPushMatrix
glScalef(@tile_size, @tile_size * 3, @tile_size)
glBegin(GL_QUADS)
quads.each do |quad|
x, z, w, l = quad
# back wall
glColor3ub(255, 255, 255)
glTexCoord2d(0, 0); glVertex3i(x, 1, z)
glTexCoord2d(0, 1); glVertex3i(x, 0, z)
glTexCoord2d(w, 1); glVertex3i(x+w, 0, z)
glTexCoord2d(w, 0); glVertex3i(x+w, 1, z)
# front wall
glColor3ub(255, 255, 255)
glTexCoord2d(0, 0); glVertex3i(x, 1, z+l)
glTexCoord2d(0, 1); glVertex3i(x, 0, z+l)
glTexCoord2d(w, 1); glVertex3i(x+w, 0, z+l)
glTexCoord2d(w, 0); glVertex3i(x+w, 1, z+l)
# left wall
glColor3ub(128, 128, 128)
glTexCoord2d(0, 0); glVertex3i(x, 1, z)
glTexCoord2d(0, 1); glVertex3i(x, 0, z)
glTexCoord2d(l, 1); glVertex3i(x, 0, z+l)
glTexCoord2d(l, 0); glVertex3i(x, 1, z+l)
# right wall
glColor3ub(128, 128, 128)
glTexCoord2d(0, 0); glVertex3i(x+w, 1, z)
glTexCoord2d(0, 1); glVertex3i(x+w, 0, z)
glTexCoord2d(l, 1); glVertex3i(x+w, 0, z+l)
glTexCoord2d(l, 0); glVertex3i(x+w, 1, z+l)
end
glEnd
glPopMatrix
glColor3ub(255, 255, 255)
end
end
end
|
class Outfit < ActiveRecord::Base
has_many :OutfitItems
has_many :items, through: :OutfitItems
belongs_to :user
attr_accessible :name, :user_id
end
|
json.array!(@biomes) do |biome|
json.extract! biome, :id, :map_mat, :description, :name, :functions
json.url biome_url(biome, format: :json)
end
|
class AddSideDealEndDate < ActiveRecord::Migration
def self.up
add_column :deal_histories,:side_deal_completed_at, :datetime
add_column :deal_histories, :side_deal_started_at, :datetime
end
def self.down
remove_column :deal_histories, :side_deal_completed_at
remove_column :deal_histories, :side_deal_started_at
end
end |
class Character < ActiveRecord::Base
belongs_to :party
has_one :mount
belongs_to :character_class
has_many :abilities, through: :character_class
end
|
module ProMotion
class MapScreenAnnotation < RMAnnotation
attr_reader :params
def initialize(params = {},map_view)
@params = params
@map_view = map_view
set_defaults
if @params[:coordinate]
@params[:latitude] = @params[:coordinate].latitude
@params[:longitude] = @params[:coordinate].longitude
@coordinate = @params[:coordinate]
initWithMapView(map_view, coordinate: @coordinate, andTitle: @params[:title])
elsif @params[:latitude] && @params[:longitude]
@coordinate = CLLocationCoordinate2D.new(@params[:latitude], @params[:longitude])
initWithMapView(map_view, coordinate: @coordinate, andTitle: @params[:title])
else
PM.logger.error("You are required to specify :latitude and :longitude or :coordinate for annotations.")
nil
end
self.userInfo = @params
end
def set_defaults
if @params.class == Hash
@params = {
title: "Title",
pin_color: :red,
identifier: "Annotation-#{@params[:pin_color]}-#{@params[:image]}",
show_callout: true,
animates_drop: false,
maki_icon: nil,
}.merge(@params)
elsif @params.class == RMQuadTreeNode # Clustered pins
@params = {
title: @params.annotations.count,
coordinate: @params.clusterAnnotation.coordinate,
pin_color: :purple,
identifier: "Annotation-cluster",
show_callout: true,
animates_drop: false,
maki_icon: nil,
}
end
end
def title
@params[:title]
end
def subtitle
@params[:subtitle] ||= nil
end
def coordinate
@coordinate
end
def pin_color
@params[:pin_color]
end
def cllocation
CLLocation.alloc.initWithLatitude(@params[:latitude], longitude:@params[:longitude])
end
def setCoordinate(new_coordinate)
super
if new_coordinate.is_a? Hash
@coordinate = CLLocationCoordinate2D.new(new_coordinate[:latitude], new_coordinate[:longitude])
else
@coordinate = new_coordinate
end
end
def self.new_with_rmannotation(rmannotation,map_view)
annotation = self.new(rmannotation.userInfo, map_view)
%w(coordinate title subtitle userInfo annotationType annotationIcon
position layer clusteringEnabled
isClusterAnnotation isUserLocationAnnotation).each do |meth|
annotation.send("#{meth}=", rmannotation.send(meth))
end
annotation
end
def method_missing(meth, *args)
if @params[meth.to_sym]
@params[meth.to_sym]
else
PM.logger.warn "The annotation parameter \"#{meth}\" does not exist on this pin."
nil
end
end
end
end
|
#!/usr/bin/env ruby
#####################################################################################
# Copyright 2015 Kenneth Evensen <kenneth.evensen@redhat.com>
#
# 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.
#
#####################################################################################
#
# Contact Info: <kenneth.evensen@redhat.com> and <lester@redhat.com>
#
#####################################################################################
load 'base/v1/api/Api.rb'
load 'base/v1/api/ResourceQuotaSpec.rb'
load 'base/v1/core/ObjectMeta.rb'
require 'json'
class ResourceQuota < Api
def initialize(namespace=nil)
super("resourcequotas", namespace)
@namespace = namespace
end
def list_resource_quotas
return list
end
def create_resource_quota(name, pods=nil, replicationcontrollers=nil, services=nil,
secrets=nil, persistentvolumeclaims=nil)
rqspec = ResourceQuotaSpec.new
rqspec.pods = pods
rqspec.replicationcontrollers = replicationcontrollers
rqspec.services = services
rqspec.secrets = secrets
rqspec.persistentvolumeclaims = persistentvolumeclaims
objectmeta = ObjectMeta.new
objectmeta.name = name
objectmeta.namespace = @namespace
body = {'spec' => rqspec.get_hash, 'metadata' => objectmeta.get_hash}
data = create(body)
return data
end
def delete_resource_quota(name)
data = delete(name)
return data
end
end
|
# frozen_string_literal: true
class Route
attr_reader :stations
include InstanceCounter
include Valid
@@list = []
def initialize(first_station, last_station)
@stations = [first_station, last_station]
validate!
@@list << self
register_instance
end
def validate!
raise StandardError, 'Начальная и конечная станции маршрута должны различаться' if stations[0] == stations[1]
end
def to_s
"Маршрут '#{stations.first.name} -> #{stations.last.name}'"
end
def self.list
@@list
end
def add_station(station)
raise StandardError, "Маршрут уже содержит станцию:'#{station.name}'" if stations.include? (station)
stations.insert(-2, station)
end
def delete_station(station)
raise StandardError, 'Конечные точки маршрута удалить нельзя' if station == stations.first || station == stations.last
raise StandardError, "Маршрут не содержит станцию'#{station.name}'" if !stations.include?(station)
stations.delete(station)
end
end
|
class RemovePriceFromEvent < ActiveRecord::Migration
def change
remove_column :events, :price, :decimal
end
end
|
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
def init_db
@db = SQLite3::Database.new 'blog.db'
@db.results_as_hash = true
end
configure do
init_db
@db.execute 'create table if not exists "comments"
("id" integer primary key autoincrement,
"comments" text,
"date" date,
"post_id" integer)'
@db.execute 'create table if not exists "posts"
("id" integer primary key autoincrement,
"posts" text,
"date" date)'
end
before do
init_db
@username = "Stranger"
end
get '/' do
erb "Hi #{@username}"
end
get '/posts' do
@posts = @db.execute 'select * from posts order by id'
erb :posts
end
get '/new post' do
erb :new_post
end
post '/new post' do
post = params[:post]
if post.length < 1
@error = "Write a message please!"
erb :new_post
else
@db.execute 'insert into posts (posts, date) values(?, datetime())', [post]
@error = "Your request sent successfuly!"
erb :new_post
end
end
get '/posts/:id_post' do
@id_post = params[:id_post]
@posts = @db.execute 'select * from posts where id = ?', [@id_post]
@comments = @db.execute 'select * from comments where post_id = ?', [@id_post]
erb :comment
end
post '/comment/:id_post' do
id_post = params[:id_post]
post = params[:post]
if post.length < 1
redirect to '/posts/' + id_post
else
@db.execute 'insert into comments (comments, date, post_id) values (?, datetime(), ?)', [post, id_post]
redirect to '/posts/' + id_post
end
end
|
# class EventJob < ActiveJob::Base
# queue_as :lagottino
# rescue_from ActiveJob::DeserializationError, ActiveRecord::ConnectionTimeoutError do
# retry_job wait: 5.minutes, queue: :lagottino
# end
# def perform(event)
# ActiveRecord::Base.connection_pool.with_connection do
# event.process_data
# end
# end
# end |
class CreateMeetings < ActiveRecord::Migration[5.0]
def change
enable_extension 'citext'
create_table :meetings do |t|
t.references :user, index: true, foreign_key: true
t.string :meeting_id
t.timestamp :starts_at
t.timestamp :ends_at
t.jsonb :info, null: false, default: '{}'
t.timestamps
end
add_index :meetings, :info, using: :gin
add_index :meetings, :meeting_id, unique: true
end
end
|
module Connection
class Request
require 'net/http'
attr_accessor :url, :port, :method, :response, :uri, :net, :parser, :options, :http
def initialize(method, url, options = {}, ssl=false, port=8080)
@url = url
@port = uri.port.nil?? port : uri.port
@method = method.to_s
@use_ssl = Rails.env.development?? false : ssl
@options = options
@header = @options.delete(:header)
@authentication = @options.delete(:authentication)
@net = ::Net::HTTP
@parser = ::JSON
end
def invoke
begin
@response = http.request(net_request)
rescue => e
puts e.message
end
end
def success?
if @response.present?
@response.kind_of? Net::HTTPSuccess
end
end
def response
if @response.present?
return parser.parse @response.response.body
end
end
def header
@header = @header.nil?? {'Content-Type' =>'application/json'} : @header
end
protected
def uri
::URI.parse(url)
end
def http
http = net.new uri.host, port
http.use_ssl = use_ssl
http
end
def net_http
"::Net::HTTP::#{method.capitalize}".constantize
end
def net_request
request = net_http.new(uri, header)
request["Authorization"] = authentication if @authentication
request.body = options[:params].to_json if options[:params].present?
request
end
def use_ssl
@use_ssl
end
def authentication
if @authentication
case @authentication[:type]
when "HTTP Authentication Base64"
return "Basic " + Base64::encode64("#{@authentication[:credential][:username]}:#{@authentication[:credential][:password]}").gsub("\n", "")
end
end
end
end
end |
# Copyright (c) 2008 Peter Houghton
#
# 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.
require 'rubygems'
require 'errfix'
# Example Test Driver
# This pretends to be a test driver, to support unit tests
#
class EgTestDriver
def initialize(use_symbols=false)
@transitions_list=Array.new
@states_list=Array.new
@symbols=use_symbols
end # end initialize
def push_states(state_sym,state_str)
if @symbols
@states_list.push state_sym
else
@states_list.push state_str
end # end if
end # end emthod
# Test state methods, record that they were touched...
def test_STATEA
push_states(:STATEA , "STATEA")
end # end test state
def test_STATEB
push_states(:STATEB , "STATEB")
end # end test state
def test_STATEC
push_states(:STATEC , "STATEC")
end # end test state
def test_STATED
push_states(:STATED , "STATED")
end # end test state
def test_STATEE
push_states(:STATEE , "STATEE")
end # end test state
# Actions, record that they were touched...
def action1
if @symbols
@transitions_list.push TransitionHolder.new(:STATEA,:action1,:STATEB)
else
@transitions_list.push TransitionHolder.new("STATEA","action1","STATEB")
end # end if
end # end action1
def action2
if @symbols
@transitions_list.push TransitionHolder.new(:STATEB,:action2,:STATEC)
else
@transitions_list.push TransitionHolder.new("STATEB","action2","STATEC")
end # end
end # end action2
def action3
if @symbols
@transitions_list.push TransitionHolder.new(:STATEC,:action3,:STATED)
else
@transitions_list.push TransitionHolder.new("STATEC","action3","STATED")
end # end
end # end action3
def action4
if @symbols
@transitions_list.push TransitionHolder.new(:STATEC,:action4,:STATEE)
else
@transitions_list.push TransitionHolder.new("STATEC","action4","STATEE")
end # end
end # end action4
def states_tested
return @states_list
end # end states travelled
def transitions_travelled
return @transitions_list
end # end transitions travelled
end # end class
|
class Quiz
include Mongoid::Document
include Mongoid::Timestamps
# relations
belongs_to :user
belongs_to :course
belongs_to :user_course
has_one :quiz_answer
embeds_many :words
# callbacks
before_create :set_words
private
def set_words
self.words = self.course.words.where(:id.nin => self.user_course.finish_word_ids).page(1)
end
end
|
class CreateCards < ActiveRecord::Migration[5.1]
def change
create_table :cards do |t|
t.string :api_rf
t.string :name
t.string :mana_cost
t.string :card_type
t.string :image_url
t.timestamps
end
end
end
|
#!/usr/bin/env ruby
puts "*** Hey #{ENV['USER']} I'll try to generate Swagger definitions for you.."
require 'yaml'
# Helpers
def decimal(hex_string)
hex_string.to_i(16)
end
def ieee(hex_string)
[hex_string.gsub('0x', '')].pack('H16').unpack('g').first
end
def ieeeDouble(hex_string)
[hex_string.gsub('0x', '').gsub(', ', '')].pack('H16').unpack('G').first
end
def hex_to_s(hex_string)
[hex_string.gsub('0x', '').gsub(', ', '')].pack('H*')
end
def swagger_name(name)
name.split('_').map { |w| w.capitalize }.join
end
def swagger_prop_name(spec)
return spec['title_case_name'] if spec['title_case_name']
spec['name'].split('_').map.with_index { |w, i|
i == 0 ? w : w.capitalize
}.join
end
# Create header
defs = Hash.new
defs['definitions'] = Hash.new
# Load exceptions spec
exceptions = YAML.load_file('exceptions.yaml')
# All capabilities
Dir.glob('../*.yml') do |yml_file|
# Capability
spec = YAML.load_file(yml_file)
if exceptions['rejections'].include?(spec['name'])
puts "Skipping #{spec['name']} as it should be rejected.."
next
elsif not spec['properties']
puts "Skipping #{spec['name']} as there's no properties.."
next
end
cap = Hash.new
cap['type'] = 'object'
cap['properties'] = Hash.new
cap_name = nil
example = YAML.load_file("../examples/#{spec['name']}.yml")
# - Get Swagger formatted model name
spec['message_types'].each do |msg|
if msg['id'] == 0x01
cap_name = swagger_name(msg['name'])
break
end
end
puts "Starting with #{cap_name}.."
# - Capability properties
spec['properties'].each do |prop_spec|
puts "Now property #{prop_spec['name']}.."
prop = Hash.new
# --- Check for swagger exception
if ex_item = exceptions['exceptions'][prop_spec['name']]
puts "Found an exception for exception #{ex_item}.."
prop = ex_item.dup
else
example_val = example[prop_spec['name']] ?
example[prop_spec['name']].first['item'].first['value'] : String.new
case prop_spec['type']
when 'string'
prop['type'] = 'string'
# -- Handling string format
prop['example'] = hex_to_s(example_val)
prop['description'] = prop_spec['description']
when 'integer'
prop['type'] = 'number'
prop['format'] = 'integer'
# -- Handling decimal format
prop['example'] = decimal(example_val)
prop['description'] = prop_spec['description']
when 'float'
prop['type'] = 'number'
prop['format'] = 'float'
# -- Handling IEE 754 format
prop['example'] = ieee(example_val)
prop['description'] = prop_spec['description']
when 'double'
prop['type'] = 'number'
prop['format'] = 'double'
# -- Handling IEE 754 double format
prop['example'] = ieeeDouble(example_val)
prop['description'] = prop_spec['description']
when 'enum'
prop['type'] = 'string'
prop['enum'] = prop_spec['values'].map { |val| val['name'] }
prop['example'] = prop_spec['values'].first['name']
when 'capability_state'
prop['type'] = 'array'
prop['items'] = {
'description' => 'A state of the vehicle',
'type' => "object"
}
else
# -- Handling object
if prop_spec['items']
# --- Creating a new model to be referenced
prop_model = Hash.new
prop_model['type'] = 'object'
prop_model['properties'] = Hash.new
prop_spec['items'].each_with_index do |prop_item_spec, idx|
item = Hash.new
item_example = example[prop_spec['name']].first['item']
case prop_item_spec['type']
when 'string'
item['type'] = 'string'
# --- Handling string format
item['example'] = hex_to_s(item_example[idx]['value'])
item['description'] = prop_item_spec['description']
when 'integer'
item['type'] = 'number'
item['format'] = 'integer'
# --- Handling decimal format
item['example'] = decimal(item_example[idx]['value'])
item['description'] = prop_item_spec['description']
when 'float'
item['type'] = 'number'
item['format'] = 'float'
# --- Handling IEE 754 format
item['example'] = ieee(item_example[idx]['value'])
item['description'] = prop_item_spec['description']
when 'double'
item['type'] = 'number'
item['format'] = 'double'
# --- Handling IEE 754 double format
item['example'] = ieeeDouble(item_example[idx]['value'])
item['description'] = prop_item_spec['description']
when 'enum'
item['type'] = 'string'
item['enum'] = prop_item_spec['values'].map { |val| val['name'] }
item['example'] = prop_item_spec['values'].first['name']
when 'capability_enum'
item['type'] = 'string'
# --- Handling enum of all capabilities
item['enum'] = Dir.glob('../*.yml').map do |val|
base_name = File.basename(val, '.yml')
base_name unless exceptions['rejections'].include?(base_name)
end.compact
item['example'] = 'charging'
when 'message_types_enum'
item['type'] = 'array'
item['items'] = {
'description' => prop_item_spec['description'],
'type' => 'enum',
'enum' => []
}
# --- Handling enum of all message types
item['items']['enum'] = []
Dir.glob('../*.yml').map do |val|
meta_cap = YAML.load_file(val)
unless exceptions['rejections'].include?(meta_cap['name'])
item['items']['enum'] = item['items']['enum'] + meta_cap['message_types'].map do |msg|
# Ignore state resonses for clarity
msg['name'] unless msg['id'] == 0x01
end.compact
end
end
item['items']['example'] = 'get_charge_state'
else
puts "Found a property item with type #{prop_item_spec['type']} - skipping that.."
end
# --- Adding item to property
prop_model['properties'][swagger_prop_name(prop_item_spec)] = item
end
prop_swagger_name = swagger_name(prop_spec['name'])
# -- Referencing to model
if exceptions['arrays'].include?(prop_spec['name'])
prop['type'] = 'array'
prop['items'] = {
'description' => prop_swagger_name,
'$ref' => "#/definitions/#{prop_swagger_name}"
}
else
prop['description'] = prop_swagger_name
prop['$ref'] = "#/definitions/#{prop_swagger_name}"
end
# -- Push model to definitions
defs['definitions'][prop_swagger_name] = prop_model
else
puts "Found a property with type #{prop_spec['type']} - skipping that.."
next
end
end
end
# -- Add property
cap['properties'][swagger_prop_name(prop_spec)] = prop
end
# - Push capability
defs['definitions'][cap_name] = cap
end
# Add additional models from exceptions conf
exceptions['definitions'].each do |model|
# key, object
defs['definitions'][model.first] = model.last
end
# Add permission scopes
owner_auth = Hash.new
owner_auth['type'] = 'oauth2'
# -- TODO: the URL should be added in the UI, as it's unique
owner_auth['authorizationUrl'] = 'https://developers.high-mobility.com/hm_cloud/o/{org_oem}/oauth'
owner_auth['flow'] = 'implicit'
scopes = Hash.new
permissions_spec = YAML.load_file('../permissions/auto_api.yml')
permissions_spec['bytes'].each do |byte|
# Skip certificate permissions (idx 1)
if byte['idx'] != 1
byte['bits'].each do |bit|
scopes[bit['name']] = bit['description']
end
end
end
owner_auth['scopes'] = scopes
defs['securityDefinitions'] = Hash.new
defs['securityDefinitions']['owner_auth'] = owner_auth
# Store definitions
open("definitions.yaml", 'w') { |f| f.write(defs.to_yaml) }
# All done
puts "*** I think I made it.." |
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
protected
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys:
[:username, :contact, :role, :city, :school_name, :matricule, :school_code, :level_id, :slug])
end
# If you have extra params to permit, append them to the sanitizer.
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys:
[:email, :username, :contact, :school_code, :city, :role, :school_name, :level_id, :memo, :slug])
end
end
|
class Running < ApplicationRecord
belongs_to :contact
validates_presence_of :text
end
|
class AddGeneratedScoreToAssessmentItemEvent < ActiveRecord::Migration[5.0]
def change
add_column :assessment_item_events, :generated_score, :float
end
end
|
class Api::V1::AdminSerializer < Api::V1::BaseSerializer
attributes :id, :email, :created_at, :updated_at, :chapters
end
|
class CourseProfessor < ActiveRecord::Base
#associations
belongs_to :professor
belongs_to :course
has_many :course_professor_users
#validations
validates :professor_id, :course_id, presence: true
validates :course_id, numericality: { only_integer: true }
validates :professor_id, numericality: { only_integer: true }, uniqueness: { scope: :course_id }
#selects
scope :base, ->{ select('course_professors.id, course_professors.professor_id, course_professors.course_id, course_professors.updated_at, course_professors.created_at') }
#wheres
scope :filter_by_id, ->(id){ where('course_professors.id = ?', id) }
end
|
require_relative './spec_helpers/violation_checker'
require_relative './test_classes/class_with_pre_post_conditions'
describe 'Pre and post' do
include ViolationChecker
let(:an_instance) { ClassWithPreAndPostConditions.new }
it 'should not throw an exception if a method does not violate a pre condition' do
expect_fulfillment {an_instance.some_method_with_pre}
end
it 'should not throw an exception if a pre condition is fulfilled with an accessor' do
expect_fulfillment {an_instance.method_with_accessor_pre}
end
it 'should explode if the pre condition is not fulfilled' do
expect_pre_condition_error {an_instance.method_with_accessor_pre_violation}
end
it 'should return as the method if there is no contract violation' do
expect(an_instance.method_with_normal_return).to eq 8
end
it 'should not explode if the post is fulfilled' do
expect_fulfillment {an_instance.method_with_post_ok}
end
it 'should not explode if both pre and post are fulfilled' do
expect_fulfillment {an_instance.method_with_pre_and_post_ok}
end
it 'should not explode if the post with the method result is fulfilled' do
expect_fulfillment {an_instance.method_with_post_method_result}
end
it 'should not explode if the post is emptyd' do
expect_fulfillment {an_instance.method_with_empty_post}
end
it 'should return the parameter if the method does that and the pre condition is fulfilled. also the instance should not have the parameter accessor' do
expect(an_instance.method_with_arg("hello")).to eq "hello"
expect(an_instance.respond_to?(:an_arg)).to eq false
end
it 'should explode if the pre validation is violated and the post doesnt' do
expect_pre_condition_error {an_instance.method_with_pre_violation}
end
it 'if one method is defined twice in the class, it should return as the second when called' do
class ClassWithPreAndPostConditions
def method_with_post_ok
'redefined method'
end
end
expect(ClassWithPreAndPostConditions.new.method_with_post_ok).to eq 'redefined method'
end
it 'if one method is defined twice in the class with a validation, it should explode if the validation is not fulfilled' do
class ClassWithPreAndPostConditions
post { pp 'executing post'; 1 < 0 }
def method_with_post_ok
'redefined method'
end
end
expect_post_condition_error {ClassWithPreAndPostConditions.new.method_with_post_ok}
end
it 'should be able to pass a block to a method' do
another_instance = ClassWithPreAndPostConditions.new
expect_fulfillment { another_instance.method_with_block {1} }
end
end |
#Family Tree is a tool for observing the history of a Genetic Algorithm
#When itialized with an Individual with a parents method which returns
#an array of two Individuals a Tree of breeding events can be calculated
class FamilyTree
def initialize individual
@individual = individual
end
def make_tree
@tree = []
indivs = [@individual] #This is the job stack
print "Generating Family Tree"
until indivs.uniq == ["no_data"]
print "."
gen = [] #The current layer of the family tree
next_gen = [] #defines the jobs for next loop
indivs.each do |ind|
gen << ind #put current individual into current layer of tree
unless ind == "no_data"
#set the parents of individual to be processed next pass
#unless there are no parents in which case TWO placeholders stored.
next_gen << ind.parents unless ind.parents.nil?
next_gen << ["no_data","no_data"] if ind.parents.nil?
else
next_gen << ["no_data","no_data"]
#if there is no individual then there will be no parents
end
end
@tree.push gen #add current layer to the tree
indivs = next_gen.flatten #add the next jobs to the stack
end
puts "done"
end
def puts_tree
puts "tree"
c = 0
for level in @tree
c+=1
puts level.size
o = []
level.each do |memb|
o << "\{#{memb.name}, #{memb.fitness}\}" unless memb == "no_data"
o << "\{#{memb}\}" if memb == "no_data"
end
puts "gen: #{c}\t #{o.join(",")}"
end
end
def pp_tree
gap = "\t"
n = 5
if n == 4
js = [7,3,1,0]
jg = [0,7,3,1]
elsif n == 5
js = [15,7,3,1,0]
jg = [0,15,7,3,1]
end
#n defines how many passes to make, while js and jg define number of spaces
n.times do |i|
gen = @tree[i]
o = [] #will contrain the current line of the tree to write
gen.each do |memb|
o << "\{#{memb.name},#{memb.dob ? memb.dob : "orig"} #{memb.fitness}\}#{memb.mutant? ? "<-M" : ""}" unless memb == "no_data"
o << "\{#{memb}\}" if memb == "no_data"
end
sp = "--------"
msg, s, g, s_n, sp_n, g_n = "", "", "", "", "", ""
js[i].times {s << gap}
jg[i].times {g << gap}
#s is the space at the start of each line, g is the size of gap between items on the line
#s_n is the space for the next line, g_p is the gap spacing for the next line. Next line knowledge
#is needed in order to draw the branches on the tree
#add the down lines
unless jg[i] == 0
msg << "#{s}"
gen.size.times do
msg << "\t|#{g}"
end
end
#add information under down lines
msg << "\n#{s}#{o.join(g) }"
#add horizonital lines for the next row
unless i == n-1
js[i+1].times {s_n << gap}
(jg[i+1]+1).times {sp_n << sp}
(jg[i+1]).times {g_n << gap}
msg << "\n#{s_n}"
gen.size.times do
msg << "\t#{sp_n}#{g_n}"
end
end
puts msg
end
end
end
|
require 'logger'
require 'twitter'
require 'redis-objects'
require 'redis-namespace'
require 'twing/version'
require 'twing/modules'
require 'twing/receivers'
require 'twing/cli'
require 'twing/operating_mode'
require 'twing/queue'
require 'twing/cursor'
class Twing
include Modules
include OperatingMode
LOGGER_FORMAT = '%Y-%m-%d %H:%M:%S.%L '
REDIS_KEY = 'home_timeline_streamer'
attr_accessor :logger
attr_reader :receivers, :cli, :setting, :rest_client, :stream_client
def initialize
@receivers = Receivers.new
@cli = Cli.new(self)
@setting = @cli.parse
@logger = generate_logger
@receivers.init(self)
@logger.debug("load plugins: #{@receivers.receivers}")
@rest_client = Twitter::REST::Client.new(setting.twitter.api_key)
@stream_client = Twitter::Streaming::Client.new(setting.twitter.api_key)
unless setting.standalone
Redis.current = Redis::Namespace.new(
setting.redis.namespace,
:redis => Redis.new(setting.redis.config)
)
@redis = Redis.current
@queue = Queue.new('queue', setting.redis.namespace)
end
@cursor = Cursor.new(REDIS_KEY, !setting.standalone)
after_init
end
def start
raise ArgumentError, 'mode is empty' if mode.nil?
logger.info("start mode=#{mode} standalone=#{setting.standalone}")
send(mode)
rescue Interrupt, SignalException
# do nothing
rescue Exception => ex
backtrace = ex.backtrace.dup
logger.error(<<~EOF)
#{backtrace.shift}: #{ex.message} (#{ex.class})
#{backtrace.join("\n")}
EOF
end
def pouring(tweet_id)
obj = rest_client.status(tweet_id)
delivery(obj)
end
private
def generate_logger
logdev = setting.log_dir ? File.join(setting.log_dir, "#{mode}.log") : STDOUT
logger = Logger.new(logdev, datetime_format: LOGGER_FORMAT)
logger.level = setting.debug ? Logger::DEBUG : Logger::INFO
logger
end
def publish(data)
logger.debug("Message publish #{data}")
if setting.standalone
delivery(data)
else
body =
case data
when Twitter::Streaming::Event
{
event: object.name,
source: object.source.to_h,
target: object.target.to_h,
target_object: object.target_object.to_h
}.to_json
when Twitter::Streaming::FriendList
data.to_json
else
data.to_h.to_json
end
@queue.push({
class: data.class.to_s,
body: body
}.to_json)
end
end
def delivery(data)
logger.debug("Message delivery #{data}")
@receivers.run do |receiver|
receiver.on_message(data)
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Feed do
def create_feed params = {}
feed = Factory.build(:feed, params)
feed.stub!(:update_feed_info)
feed
end
before(:each) do
@feed = create_feed
end
it "#url が空の時は、保存に失敗するべき" do
@feed.url = ""
@feed.save
@feed.should have(1).errors_on(:url)
end
it "#url がhttp://で始まらない時、保存に失敗するべき" do
@feed.url = "ftp://ftp.example.com"
@feed.save
@feed.should have(1).errors_on(:url)
end
it "#url はhttp://で始まるURLの形式であるとき、保存に成功する" do
@feed.url = "http://www.example.com/"
@feed.save
@feed.should have(0).errors_on(:url)
end
it "#url は他のレコードと重複していた場合、保存に失敗する" do
@feed.save
same_feed = create_feed
same_feed.save
same_feed.should have(1).errors_on(:url)
end
end
|
# frozen_string_literal: true
module LeaderboardEntry::Concerns
module Ranked
extend ActiveSupport::Concern
included do
before_save :drop_leaderboard_cache
end
module ClassMethods
# kvokka it returns Hash, so it is not right to use ::scope here
def ranked(leaderboard)
Rails.cache.fetch("rank_#{leaderboard.id}") do
where(leaderboard: leaderboard).group(:username).order("sum_score desc").sum(:score)
end
end
end
def save_with_rank(*args)
rank_before = self.class.ranked leaderboard
return false unless save(*args)
rank_after = self.class.ranked leaderboard
(rank_before.keys.index(username) || rank_after.size) - rank_after.keys.index(username)
end
private
def drop_leaderboard_cache
Rails.cache.delete("rank_#{leaderboard.id}")
end
end
end
|
class CreateForteManagerSettlements < ActiveRecord::Migration[5.0]
def change
create_table :forte_manager_settlements do |t|
t.string :settle_id, index: { unique: true } # stl_0dde9c0d-a816-4ed1-9eb1-490207a87c35
t.string :organization_id, index: true # org_300005
t.string :location_id, index: true # loc_115161
t.string :customer_token, index: true # cst_11017799
t.string :transaction_id, index: true # trn_8bb0c376-8ab9-4351-af7d-991452d21429
t.string :customer_id, index: true # 45687545
t.string :order_number, index: true # 000001
t.string :reference_id, index: true # 0002315
t.datetime :settle_date # 2014-02-09T00:00:00
t.string :settle_type, index: true # deposit
t.string :settle_response_code, index: true # S01
t.decimal :settle_amount, precision: 8, scale: 2 # 5.4
t.string :method, index: true # echeck
t.timestamps
end
end
end
|
require "net/http"
require "uri"
require "date"
require "rubygems"
require "httparty"
require "digest"
#DIRNAME = "E:/Squadro/Demo"
#OUTPUTDIRNAME = "E:/Squadro/DailyOutput"
today = Date.today
#from = Time.gm(today.year, today.month, today.day) #.to_s[0..-5]
from = (Time.now() - 7200).getgm.to_s[0..-5]
tomo = today + 1
to = Time.gm(tomo.year, tomo.month, tomo.day).to_s[0..-5]
puts from
puts to
# random string
nonce = (0...8).map { (65 + rand(26)).chr }.join
############################
##### DIRECTORIES ##########
############################
parent_dir = File.expand_path("..",Dir.pwd)
# The directory where all the required input files, the executable files located
assets_dir = parent_dir + "/assets"
# Folder to be named for the time duration for which the
folder_name = folder_name = from + "__" + to
# Create a new folder to output the contents
output_dir = parent_dir + '/' + folder_name
Dir.mkdir(output_dir)
###################################
#### GETTING JSON FROM SERVER #####
###################################
base_uri = "http://squadro.in/restapi/order/range"
auth = Digest::MD5.hexdigest(from + nonce + to)
params = {:from => from, :to => to, :nonce => nonce}
auth_header = {"x-auth-key" => auth}
response = HTTParty.get(base_uri, :query => params, :headers => auth_header)
json = JSON.parse(response.body) # json contains the hash to parse
puts json
####################################
##### PARSING ######################
####################################
orders_array = json["orders"]
filenames = []
orders_array.each do |order|
products_hash = order["products"]
products_hash.each_pair do |product_code, quantity|
model_code, variant_code = product_code.split('-')
filenames += Array.new(quantity, variant_code)
end
end
#filenames = ["BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005","BC3.1_P021", "BC3.1_P020", "BC2.1_P024", "BC1.1_P005"]
#filenames = ["BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004","BC1.1_P004"]
######################################################################
##### FIND ALL SKP FILES RELAVANT IN THIS ORDER ######################
######################################################################
pathnames = []
filenames.each do |file|
pathnames += Dir.glob("#{assets_dir}/**/#{file}.skp")
end
####################################################################
########## CREATE THE MERGED SKP FILE ##############################
####################################################################
t = Time.now()
date = t.strftime("%d%m%Y_%H%M%S")
outputfilename = "#{output_dir}/#{date}.skp"
# cmd is the params to the add_entities.exe C++ program with all
# the files to merge as the first parameters and the last param is the output file name
cmd = ""
pathnames.each do |path|
cmd += " #{path}"
end
cmd += " #{outputfilename}"
value = %x["#{assets_dir}/add_entities.exe" #{cmd}]
####################################################################
########## RUN THE SKP FILE FOR ###################################
####################################################################
value1 = %x["C:/Program Files (x86)/SketchUp/SketchUp 2013/SketchUp.exe" #{outputfilename}] |
# Pine suggests adapting the program
# - to our computer
# - with added safety features, inlcuding...
# > ensuring we don't overwrite a file (File.exist?)
# > using 'exit' to quit in the event of an error
Dir.chdir '~/Pictures/moved_test_pics'
pic_names = Dir['~/Pictures/test_pics'] # First we find all of the pictures to be moved.
puts 'What would you like to call this batch?'
batch_name = gets.chomp
puts "That file already exists." if batch_name.exist == true
puts
print "Downloading #{pic_names.length} files: "
# This will be our counter. We'll start at 1 today, though normally I like to count from 0.
pic_number = 1
pic_names.each do |name|
print '.' # This is our "progress bar".
new_name = if pic_number < 10
"#{batch_name}0#{pic_number}.jpg"
else
"#{batch_name}#{pic_number}.jpg"
end
File.rename name, new_name
# Finally, we increment the counter.
pic_number = pic_number + 1
end
puts # This is so we aren't on progress bar line.
puts 'Done!'
|
class ChangeColumnRequestsLocationId < ActiveRecord::Migration
def change
change_column :requests, :location_id, :integer
end
end
|
class CategoriesController < ApplicationController
def index
respond_with app.categories
end
def show
respond_with app.categories.find(params[:id])
end
def create
category = app.categories.create(category_params)
respond_with app, category
end
def update
category = app.categories.find(params[:id])
category.update(category_params)
respond_with app, category
end
def destroy
category = app.categories.destroy(params[:id])
respond_with app, category
end
private
def app
@app ||= App.find(params[:app_id])
end
def category_params
params.permit(:name, :position)
end
end
|
class Spree::Allegro::Theme < ActiveRecord::Base
belongs_to :store, class_name: 'Spree::Store'
has_many :store_products
end
|
class UsersController < ApplicationController
before_action :set_hospital
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@users = if current_user.admin?
@hospital.users.where(role: "manager")
elsif current_user.manager?
@hospital.users.where(role: "nurse")
end
authorize @users
end
def new
@user = @hospital.users.new
authorize @user
end
def create
@user = @hospital.users.new(user_params)
@user.role = if current_user.admin?
"manager"
elsif current_user.manager?
"nurse"
end
authorize @user
if @user.save
flash[:success] = "created successfully."
redirect_to hospital_users_path
else
flash[:alert] = "Please fill required field."
render 'new'
end
end
def show
end
def edit
end
def update
if @user.update(user_params)
flash[:success] = "Update Successfully."
redirect_to hospital_users_path
else
flash[:alert] = @user.errors.full_messages.join(' ,')
render 'edit'
end
end
def destroy
flash[:alert] = "Destroy Successfully." if @user.destroy
redirect_to hospital_users_path
end
private
def set_user
@user = @hospital.users.find(params[:id])
authorize @user
end
def set_hospital
@hospital = if current_user.admin?
current_user.hospitals.find(params[:hospital_id])
else
Hospital.find(params[:hospital_id])
end
end
def user_params
params.require(:user).permit(:hospital_id, :first_name, :last_name, :email, :password)
end
end |
class ListsController < ApplicationController
#require 'zip/zip'
def new
@list = List.new
@problems= Problem.all
end
#Show report details and only show selescted problem in gmap
def show
@list = List.find(params[:id])
@problems = Problem.paginate(page: params[:page])
#Respond to will create a call to csv and prepare the list for .xls exporting
#See lists/show.xls.erb for table formatting details
respond_to do |format|
format.html # index.html.erb
format.xlsx{
render :xlsx => "show", :filename => "#{@list.id}-#{@list.name}-#{@list.created_at.strftime("%b.%d %Y")}.xlsx"
}
end
end
#Show list of reports and show all of them in gmap
def index
@lists = List.paginate(page: params[:page])
end
def create
@list = List.new(params[:list])
#Para obtener el usuario actual que esta creando el reporte solo funciona
#por webapp. Su motivo aplicar relación belongs_to de "problems"
@list.user_id = current_user.id
#Activate the list when it is created, enabling it for use
#If list is closed it will only be browsable, not editable
@list.active = true
if @list.save
flash[:success] = "List saved"
redirect_to @list
else
flash[:error] = 'Incomplete information, list not created'
redirect_to lists_path
end
end
def destroy
# Unassign all contained reports unless already resolved
@list = List.find(params[:id])
@list.problems.each do |problem|
if problem.status!=3
problem.status = 1
problem.save
end
end
@list.destroy
flash[:success] = "List deleted."
redirect_to lists_url
end
def edit
@list = List.find(params[:id])
end
def update
@list = List.find(params[:id])
if @list.update_attributes(params[:list])
flash[:success] = "List updated"
redirect_to @list
else
flash[:error] = "List update error"
redirect_to @list
end
end
def add_problem
@list = List.find(params[:id])
@problem = Problem.find(params[:problem_id])
if !@list.problems.include?(@problem)
@list.problems << @problem # This appends and saves the problem selected
#Change the report status, it is now assigned to the owner of the list
@problem.status = 2
@problem.assigned_at = Time.now
@problem.save
flash[:notice] = "Report added"
redirect_to @list
else
flash[:notice] = "Report is already on the list"
redirect_to @list
end
end
def remove_problem
@list = List.find(params[:id])
@problem = Problem.find(params[:problem_id])
#Change the report status back to being unassigned
if @problem.status!= 3
@problem.status = 1
@problem.save
end
@list.problems.destroy(@problem) # This removes the problem selected
flash[:notice] = "Report removed"
redirect_to @list
end
# def validates_role(role)
# raise ActiveRecord::Rollback if self.roles.include? role
# end
# def show_problems
# @list = List.find(params[:id])
# end
# def save
# @list = List.find(params[:id])
# @problem = Problem.find(params[:problem])
# if params[:show] == "true"
# @list.problems << @problem
# else
# @list.problems.delete(@problem)
# end
# @list.save!
# render :nothing => true
# end
end
|
require 'rails_helper'
RSpec.shared_examples 'domain mailer registrar info' do
let(:registrar) { instance_spy(RegistrarPresenter) }
before :example do
without_partial_double_verification do
allow(view).to receive(:registrar).and_return(registrar)
end
end
attributes = %i(
name
email
phone
website
)
attributes.each do |attr_name|
it "has #{attr_name}" do
expect(registrar).to receive(attr_name).and_return("test #{attr_name}")
render
expect(rendered).to have_text("test #{attr_name}")
end
end
end
|
# frozen_string_literal: true
require 'test_helper'
class ReminderTest < ActiveSupport::TestCase
test 'valid reminder' do
ticket = create(:ticket, :with_due_date)
reminder = Reminder.new(
attributes_for(:reminder).merge(
reminderable_id: ticket.id,
reminderable_type: ticket.class.name
)
)
assert reminder.valid?
end
end
|
class Cli
attr_reader :user
def initialize(user)
@user = user
end
def welcome_menu
puts "Welcome #{user.name}"
puts "Would you like to build a new grocery list?"
end
end |
class AddStartDaysToTreatments < ActiveRecord::Migration
def change
add_column :treatments, :start_days, :integer
end
end
|
class RefreshTaxNumbersJob
include Sidekiq::Worker
def perform
TaxNumber.refresh
end
end
|
class AddForeignKeyToMeters < ActiveRecord::Migration[5.0]
def change
add_foreign_key :meters, :mpoints
end
end
|
module SqlMigrations
class Seed < SqlScript
def self.find(db_name)
super(db_name, :seed)
end
def to_s
"Seed data #{@name}, datetime: #{@date + @time}"
end
end
end
|
# frozen_string_literal: true
class Meeting < ApplicationRecord
validate :normal_date?
belongs_to :user
has_many :comments, dependent: :destroy
private
def normal_date?
if start_time > end_time
errors.add(:end_time, 'start time must be before end time')
errors.add(:start_time, 'start time must be before end time')
end
errors.add(:start_time, 'start time must be after now') if start_time < Time.now
end
end
|
class ChangeFriendlyFireType < ActiveRecord::Migration
def change
change_column :spells, :friendly_fire, :string
end
end
|
class AddCollectionUuidToProjects < ActiveRecord::Migration[5.2]
def change
add_column :projects, :collection_uuid, :string
add_index :projects, :collection_uuid
Project.all.each do |project|
project.collection_uuid = project.collection.uuid
project.save!
end
end
end
|
class CreateDoctorProfiles < ActiveRecord::Migration
def change
create_table :doctor_profiles do |t|
t.date "birthday", null: false
t.string "gender", limit: 20, null: false
t.string "specialty", limit: 100, null: false
t.string "license_number", limit: 100, null: false
t.string "street", limit: 100, null: false
t.string "suburb", limit: 100, null: false
t.string "city", limit: 100, null: false
t.string "state", limit: 100, null: false
t.string "zip", limit: 10, null: false
t.references :user
t.foreign_key :users, dependent: :delete
t.timestamps
end
end
end
|
class AirportFinder < BaseStruct
attribute :filter_params, Types::Hash
def call
Airport.filter(filter_params).order("passenger_volume DESC NULLS LAST")
end
end
|
class CreateShares < ActiveRecord::Migration
def self.up
create_table :shares, :force => true do |t|
t.belongs_to :content, :polymorphic => true
t.string :identifier
t.integer :attempts, :default => 0
t.text :last_error
t.timestamp :shared_at, :last_error_at
t.timestamps
end
add_index :shares, [:content_id, :content_type]
end
def self.down
drop_table :shares
end
end
|
#!/usr/bin/env ruby
begin
require 'benchmark'
require 'rubygems'
require 'activesupport'
require 'socket'
require 'optparse'
require 'ostruct'
end
begin
$options = {
:concurrency => 1,
:count => 100,
:host => "0.0.0.0"
}
OptionParser.new do |opts|
opts.on('-n', "--number COUNT", Integer) { |count| $options[:count] = count }
opts.on('-c', "--concurrency CONCURRENCY", Integer) { |concurrency| $options[:concurrency] = concurrency }
opts.on('-p', "--port PORT", Integer) { |port| $options[:port] = port }
end.parse!
end
count_per_worker = $options[:count] / $options[:concurrency]
requests = (1..10).to_a
benchmark = Benchmark.measure do
threads = []
$options[:concurrency].times do
threads << Thread.new do
socket = TCPSocket.new($options[:host], $options[:port])
count_per_worker.times do
socket.print("#{requests.rand}\n")
socket.readline
end
end
end
threads.each(&:join)
end
mean = $options[:count] / benchmark.real
puts "Requests per second (throughput):\t%2f [#/sec] (mean)" % mean |
require 'rails_helper'
RSpec.describe Movie, :type => :model do
it "find correct movies with the same director" do
movies_list = [{id: 1,title: "Titanic",director: "James Cameroon"},{id: 2,title: "Avatar",director: "James Cameroon"},{id: 3,title: "Avengers", director: "Joe Russo"}]
movies_list.each do |new_movie|
Movie.create(new_movie)
end
movies = Movie.list_same_director_movies("James Cameroon")
expect(movies.length()).to eq(2)
expect(movies.pluck(:director)).to eq(["James Cameroon", "James Cameroon"])
end
it "find no movies with different director" do
movies_list = [{id: 1,title: "Titanic",director: "James Cameroon"},{id: 2,title: "Avatar",director: "James Cameroon"},{id: 3,title: "Avengers", director: "Joe Russo"}]
movies_list.each do |new_movie|
Movie.create(new_movie)
end
movies = Movie.list_same_director_movies("Joe Russo")
expect(movies.length()).to eq(1)
expect(movies.pluck(:director)).not_to eq("James Cameroon")
end
end |
require_relative '../lib/mtmd/core/path_helper'
require_relative '../lib/mtmd/core/config_loader'
module MTMD
module FamilyCookBook
class Database
def self.config
base_config = MTMD::Core::ConfigLoader.new(::Utils::PathHelper.project_root('config/database.yml'), RACK_ENV).load_config
base_config['database']
end
def self.host
config['host']
end
def self.credentials
"#{config['user']}:#{config['password']}" if config['user']
end
def self.db
config['name']
end
def self.port
config['port'] || "5432"
end
def self.options
config['pg_options'] || {}
end
def self.handler
"postgres://#{credentials}@#{host}:#{port}/#{db}"
end
end
end
end
Sequel::Model.plugin(:schema)
Sequel::Model.raise_on_save_failure = true # Do not throw exceptions on failure
Sequel::Model.plugin :update_or_create
Sequel.extension :core_extensions, :pg_range_ops, :pg_array_ops, :pg_json_ops
loggers = RACK_ENV == 'test' ? [] : [logger]
default_options = {:loggers => loggers}
Sequel::Model.db = Sequel.connect(
MTMD::FamilyCookBook::Database.handler,
default_options.merge(MTMD::FamilyCookBook::Database.options)
)
Sequel::Model.db.extension :pagination, :pg_array, :pg_json, :pg_range, :schema_dumper
|
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# project_id :integer
# user_id :integer
# checkin_id :integer
# title :string not null
# url :string not null
# current_state :string
# estimate :integer default(0)
# current :boolean not null
# created_at :datetime not null
# updated_at :datetime not null
# task_type :string default("feature"), not null
# message_timestamp :string
# task_id :integer
#
class Task < ApplicationRecord
belongs_to :user
belongs_to :project
belongs_to :checkin
has_many :task_blockers
scope :current, -> { where :current => true }
scope :previous, -> { where :current => false }
scope :current_tasks_1month_ago,
-> { current.where('tasks.created_at BETWEEN ? AND ?', 1.month.ago.beginning_of_day, Date.today.end_of_day) }
def week
self.created_at.strftime '%W'
end
def self.week_dates week_num
year = Time.now.year
week_start = Date.commercial year, week_num.to_i, 1
week_end = Date.commercial year, week_num.to_i, 7
week_start.strftime('%m/%d/%y') + ' - ' + week_end.strftime('%m/%d/%y')
end
def times_checked_in_current user_id
count = Task.where(
:task_id => self.task_id,
:current => true,
:user_id => user_id
).count
count == 0 ? 1 : count
end
end
|
module Groups
class UsersController < ApplicationController
before_action :set_group
def show
@user = @group.users.find(params[:id])
end
def index
@users = @group.users.all
@email = params[:email]
@user = current_user
@group = Group.friendly.find(params[:group])
if @email
if @email.include?(@group.email_domain_name.downcase)
UserMailer.invitation(@email, @user).deliver_now
flash[:notice] = "Invitation envoyée"
redirect_to :back
else
flash[:alert] = "Erreur, vérifiez l'adresse email"
redirect_to :back
end
end
end
def autocomplete
render json: User.search(params[:query], autocomplete: true, limit: 10).map(&:name)
end
private
def set_group
@group = Group.friendly.find(params[:group])
end
end
end
|
class AddDealercompanyToTruck < ActiveRecord::Migration[4.2]
def change
add_reference :trucks, :dealercompany, index: true, foreign_key: true
end
end
|
# rubocop:disable Style/CyclomaticComplexity, Style/AbcSize:
module Rounders
module Generators
class Base < Thor::Group
include Thor::Actions
include Rounders::Plugins::Pluggable
argument :name, type: :string
protected
def class_name
Util.infrect(name).classify
end
def feature_path
Pathname("#{Rounders::APP_PATH}/#{self.class.directory_name}")
end
def empty_directory_with_keep_file(destination, config = {})
empty_directory(destination, config)
keep_file(destination)
end
def keep_file(destination)
create_file("#{destination}/.keep")
end
def underscored_name
@underscored_name ||= Util.infrect(name).underscore
end
def namespaced_name
@namespaced_name ||= Util.infrect(name.tr('-', '/')).classify
end
class << self
def inherited(klass)
klass.define_singleton_method(:source_root) do
default_source_root
end
klass.define_singleton_method(:generator_name) do
@generator_name ||= feature_name.split('_').first
end
klass.define_singleton_method(:default_source_root) do
return unless base_name && generator_name
return unless default_generator_root
path = Pathname.new(default_generator_root).join('templates')
path if path.exist?
end
klass.define_singleton_method(:base_name) do
@base_name ||= begin
base = name.to_s.split('::').first
Rounders::Util.infrect(base).underscore unless base.nil?
end
end
klass.define_singleton_method(:default_generator_root) do
path = Pathname(__FILE__).dirname.join(generator_name).expand_path
path if path.exist?
end
end
end
end
end
end
|
# == Schema Information
#
# Table name: democ_detail_records
#
# id :integer not null, primary key
# average_weekly_wage :float
# business_sequence_number :integer
# claim_activity_status :string
# claim_activity_status_effective_date :date
# claim_combined :string
# claim_handicap_percent :string
# claim_handicap_percent_effective_date :date
# claim_indicator :string
# claim_injury_date :date
# claim_manual_number :integer
# claim_medical_paid :integer
# claim_mira_indemnity_reserve_amount :integer
# claim_mira_medical_reserve_amount :integer
# claim_mira_ncci_injury_type :string
# claim_mira_non_reducible_indemnity_paid :integer
# claim_mira_non_reducible_indemnity_paid_2 :integer
# claim_mira_reducible_indemnity_paid :integer
# claim_number :string
# claim_rating_plan_indicator :string
# claim_status :string
# claim_status_effective_date :date
# claim_sub_manual_number :string
# claim_total_subrogation_collected :integer
# claim_type :string
# claimant_date_of_birth :date
# claimant_date_of_death :date
# claimant_name :string
# combined_into_claim_number :string
# current_policy_status :string
# current_policy_status_effective_date :date
# enhanced_care_program_indicator :string
# enhanced_care_program_indicator_effective_date :date
# full_weekly_wage :float
# indemnity_settlement_date :date
# industrial_commission_appeal_indicator :string
# last_paid_indemnity_date :date
# last_paid_medical_date :date
# maximum_medical_improvement_date :date
# medical_settlement_date :date
# non_at_fault :string
# policy_number :integer
# policy_type :string
# policy_year :integer
# policy_year_rating_plan :string
# record_type :integer
# representative_number :integer
# representative_type :integer
# requestor_number :integer
# settled_claim :string
# settlement_type :string
# valid_policy_number :string
# created_at :datetime
# updated_at :datetime
#
require 'test_helper'
class DemocDetailRecordTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
require 'feed'
namespace :teams do
desc 'Notify teams to update their status log'
task notify_missing_log_updates: :environment do
# we do not send annoying emails on weekends:
if !(Date.today.saturday? || Date.today.sunday?)
TeamPerformance.teams_to_remind.each do |team|
ReminderMailer.update_log(team).deliver_later
end
end
end
end |
class EvaluationsController < ApplicationController
load_and_authorize_resource
def index
@evaluations = current_user.evaluations
end
def new
@evaluation = Evaluation.new
end
def create
@evaluation = current_user.evaluations.build(evaluation_params)
if @evaluation.save
@evaluation.submit
Notifier.notify(@evaluation, @evaluation.reviewer, "#{@evaluation.user.name} submit an evaluation").deliver_now
redirect_to @evaluation
else
render 'new'
end
end
def destroy
Evaluation.find_by(id: params[:id]).destroy rescue nil
redirect_to evaluations_path
end
def edit
@evaluation = Evaluation.find_by(id: params[:id])
end
def update
@evaluation = Evaluation.find_by(id: params[:id])
if @evaluation.update(evaluation_params)
@evaluation.submit
Notifier.notify(@evaluation, @evaluation.reviewer, "#{@evaluation.user.name} edit evaluation").deliver_now
redirect_to evaluations_path
else
render 'edit'
end
end
def show
@evaluation = Evaluation.find_by(id: params[:id])
@evaluation.read if current_user == @evaluation.user
redirect_to evaluations_path if @evaluation.nil?
end
def recall
@evaluation = Evaluation.find_by(id: params[:id])
if @evaluation
@evaluation.recall
Notifier.notify(@evaluation, @evaluation.reviewer, "#{@evaluation.user.name} recall evaluation").deliver_now
redirect_to evaluations_path
else
redirect_to evaluations_path
end
end
def reviewer
@evaluation = Evaluation.find_by(id: params[:id])
return redirect_to evaluations_path if @evaluation.nil?
reviewer_params = params.require(:evaluation).permit(
:attitude_rating, :accountability_rating, :problem_solving_rating, :delivering_rating,
:relationship_rating, :feedback_rating, :developing_rating, :professionalism_rating,
:strengths, :improvements)
if params[:commit] == 'Reviewer approve'
reviewer_params.merge!(state: "reviewer_approved")
elsif params[:commit] == 'Reviewer deny'
reviewer_params.merge!(state: "reviewer_denied")
end
if @evaluation.update(reviewer_params)
if @evaluation.state == "reviewer_approved"
Notifier.notify(@evaluation, @evaluation.manager, "#{@evaluation.user.name} submit an evaluation").deliver_now
Notifier.notify(@evaluation, @evaluation.user, "#{@evaluation.reviewer.name} approve your evaluation").deliver_now
elsif @evaluation.state == "reviewer_denied"
Notifier.notify(@evaluation, @evaluation.user, "#{@evaluation.reviewer.name} deny your evaluation").deliver_now
end
else
@evaluation.state = "submitted"
return render 'show'
end
return redirect_to @evaluation
end
def manager
@evaluation = Evaluation.find_by(id: params[:id])
return redirect_to evaluations_path if @evaluation.nil?
state = "manager_approved" if params[:commit] == "Manager approve"
state = "manager_denied" if params[:commit] == "Manager deny"
if @evaluation.update(params.require(:evaluation).permit(:manager_comments).merge(state: state))
if @evaluation.state == "manager_approved"
Notifier.notify(@evaluation, @evaluation.user, "#{@evaluation.manager.name} approve your evaluation").deliver_now
elsif @evaluation.state == "manager_denied"
Notifier.notify(@evaluation, @evaluation.user, "#{@evaluation.manager.name} deny your evaluation").deliver_now
end
else
@evaluation.state = "reviewer_approved"
return render 'show'
end
return redirect_to @evaluation
end
def managed
@evaluations = Evaluation.where(reviewer_id: current_user.id, state: ["submitted", "manager_denied"]) + Evaluation.where(manager_id: current_user.id, state: "reviewer_approved")
render 'index'
end
def evaluation_all
@q = Evaluation.search(@q)
@evaluations = @q.result
end
def export
# from 2017/8 to 2018/7
@users = User.where(status: "Employed", department: ["Outsourcing", "Consulting", "outsourcing", "consulting"])
@from_date = Date.new(2017, 8, 1)
filename = 'attachment; filename=' + "Review (#{@from_date.year} 8--#{@from_date.year + 1} 7)#{Time.now.strftime("%Y%m%d%H%M%S")}.xlsx"
respond_to do |format|
format.xlsx {
response.headers['Content-Disposition'] = filename
}
end
end
private
def evaluation_params
params.require(:evaluation).permit(:project_id, :times, :complexity, :role, :description, :reviewer_id, :manager_id)
end
end
|
# frozen_string_literal: true
module Pitzi
module V1
class UsersAPI < Grape::API
helpers do
def user_params
declared(params, include_missing: false)[:user]
end
end
get '/users' do
result = ::Users::List.result
present :list, result.list
end
params do
requires :user, type: Hash do
requires :name, type: String
requires :email, type: String
requires :cpf, type: String
end
end
post '/users' do
result = ::Users::Create.result(attributes: user_params)
present :user, result.user
end
params do
requires :id, type: String
requires :user, type: Hash do
optional :name, type: String
optional :email, type: String
optional :cpf, type: String
end
end
put '/users/:id' do
result = ::Users::Update.result(id: params[:id], attributes: user_params)
present :user, result.user
end
params do
requires :id, type: String
end
delete '/users/:id' do
::Users::Destroy.result(id: params[:id])
status :no_content
end
end
end
end
|
# author: Adrián García
# program under the license GPL v3
def clear
# Función que limpia la pantalla
printf "\e[H\e[2J"
end
def time
# Función que devuelve la fecha actual en formato string
return Time.new.strftime '%d/%m/%y'
end
def printall(lista)
col_negrita="\e[1m"
col_magenta="\e[35m"
col_green="\e[32m"
col_red="\e[31m"
col_normal="\e[0m"
#Imprime la pantalla básica con la cuenta de frases y el menú
clear
printf col_negrita
puts "#{$title} #{$version}"
"#{$title} #{$version}".size.times{printf "-"} #imprime una linea de guiones
puts "\n\n#{col_normal}"
i=1
lista.keys.each do |key|
printf "#{col_negrita+col_magenta}#{i}#{col_normal} #{key} ->"
puts "#{col_negrita+col_green}#{lista.getval(key)}#{col_normal}"
i+=1
end
if lista.getcombob
printf "\nC-C-C-COMBO BREAKER!!! >> "
puts "#{col_negrita+col_red}#{lista.getcombob}#{col_normal}"
end
puts "TOTAL: #{col_negrita+col_red}#{lista.gettotal}#{col_normal}"
printf "\nq=salir / a=añadir / d=eliminar / c=cambiar_frase /"
printf " p=gráfica_de_estadísticas / ps=guardar_gráfica_.svg /"
printf " pe=guardar_gráfica_.eps / 1..n=incrementar_frase_n\n>> "
end
def marshalload(filename)
f=File.open(filename,'r')
objeto=Marshal.load f.read
f.close
return objeto
end
def marshalsave(filename,objeto)
f=File.open(filename,'w')
f.write Marshal.dump objeto
f.close
end
|
#!/usr/bin/env ruby
#require "rubygems"
#require "bundler/setup"
SNO_ROOT = File.expand_path("../../", __FILE__)
require "sno"
require 'optparse'
require "json"
include Sno
options = {
:notebook_name => nil,
:web_server => false,
:force => false
}
OptionParser.new do |opts|
opts.banner = "Usage: sno.rb input_dir [output_dir] [options]"
opts.on("-n", "--project-name NAME", String, "Specify a name to persist throughout the pages") do |n|
options[:notebook_name] = n
end
opts.on("-w", "--web-server [WEBROOT]", "Build site that is hostable on a web server with optional base web root") do |web_root|
options[:web_server] = true
if web_root
web_root.chomp!("/")
web_root = "/" + web_root unless web_root[0] == "/"
end
options[:web_root] = web_root || ""
end
opts.on("-f", "--force", "Force updates to .sno assets directory") do
options[:force] = true
end
opts.on("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
input_dir = ARGV[0] or raise "You must specify a input directory!"
options[:output_dir] = ARGV[1] if ARGV[1]
sno = Sno::Sno.new input_dir, options
sno.generate_notebook |
class SnapsController < ApplicationController
before_action :reset_unanswered_content_pushes, only: :fetched
def fetched
unviewed_usernames = split_param(:unviewed_usernames)
viewed_sent_usernames = split_param(:viewed_sent_usernames)
viewed_received_usernames = split_param(:viewed_received_usernames)
params[:trigger] = 'periodic_check' if params[:trigger].blank?
unless current_user.mobile_notifier.pushes_enabled?
unviewed_usernames.each do |username|
current_user.email_notifier.notify_new_snap(username)
end
current_user.email_notifier.notify_missed_sent_snaps if viewed_sent_usernames.present?
current_user.email_notifier.notify_missed_received_snaps if viewed_received_usernames.present?
end
increment_stories_metrics
increment_content_push_metrics
render_success
end
private
def increment_stories_metrics
count = params[:new_stories_count].to_i
trigger = params[:trigger]
StatsD.increment("stories.fetched.by_trigger.#{trigger}", count) if count > 0 && %w(periodic_check content_push).include?(trigger)
end
def increment_content_push_metrics
return unless params[:trigger] == 'content_push'
StatsD.increment('content_available_pushes.client_received')
StatsD.increment("content_available_pushes.#{current_user.content_frequency_cohort}.client_received")
mixpanel.received_daily_content_push
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
sequence :code do |n|
(21321 + n).to_s
end
factory :course do
code 21321
number 300
title %w(CIS 300 - Ruby on Rails)
instructor "David Huang"
status "open"
available_seats 30
term
department
end
end
|
require "puppet/provider/package"
require "fileutils"
Puppet::Type.type(:package).provide(:ruby_build, :parent => Puppet::Provider::Package) do
desc "Package management using ruby-build."
commands :rbenv => "rbenv"
has_feature :installable, :uninstallable
def self.installed
rbenv(:versions).split("\n").map { |v| v.split[1] }
end
def self.instances
installed.map { |a| new(:name => a, :ensure => :present, :provider => :ruby_build) }
end
def install
rbenv(:install, resource[:name])
end
def query
if self.class.installed.include?(resource[:name])
{ :name => resource[:name], :ensure => :present, :provider => :ruby_build }
end
end
def uninstall
installation = "#{ENV['HOME']}/.rbenv/versions/#{resource[:name]}"
if File.directory?(installation)
FileUtils.remove_entry_secure(installation)
end
end
end
|
require 'rails_helper'
RSpec.describe "interviews/new", type: :view do
before(:each) do
assign(:interview, Interview.new(
:study => nil,
:interviewer => nil,
:interviewee => nil,
:locale => nil
))
end
it "renders new interview form" do
render
assert_select "form[action=?][method=?]", interviews_path, "post" do
assert_select "input#interview_study_id[name=?]"
assert_select "input#interview_interviewer_id[name=?]"
assert_select "input#interview_interviewee_id[name=?]"
assert_select "input#interview_locale_id[name=?]"
end
end
end
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../player.rb')
require_relative('../deck.rb')
class PlayerTest < MiniTest::Test
def setup
@player1 = Player.new("Chris", 30, [])
@deck1 = Deck.new([])
end
def test_player_name
assert_equal("Chris", @player1.player_name)
end
def test_player_health
assert_equal(30, @player1.player_health)
end
def test_player_decks
assert_equal([], @player1.player_decks)
end
def test_player_loses_health
assert_equal(25, @player1.player_lose_health(5))
end
def test_player_gains_health
assert_equal(32, @player1.player_gain_health(2))
end
def test_player_deck_count
assert_equal(0, @player1.player_deck_count)
end
def test_player_add_deck
@player1.player_add_deck(@deck1)
assert_equal(1, @player1.player_deck_count)
end
def test_player_remove_deck
@player1.player_add_deck(@deck1)
@player1.player_remove_deck(@deck1)
assert_equal(0, @player1.player_deck_count)
end
end
|
include DataMagic
Given(/^user logged into COS with a single IHG cobranded account and navigates to transactions and details page$/) do
DataMagic.load("canada.yml")
visit LoginPage
on(LoginPage) do |page|
logindata = page.data_for(:can_singlecard_IHG)
username = logindata['username']
password = logindata['password']
ssoid = logindata['ssoid']
page.login(username, password, ssoid)
end
visit(TransactionsDetailsPage)
end
Given(/^user logged into COS with a multicard Delta cobranded account and navigates to transactions and details page$/) do
DataMagic.load("canada.yml")
visit LoginPage
on(LoginPage) do |page|
logindata = page.data_for(:can_multicard_Delta)
username = logindata['username']
password = logindata['password']
ssoid = logindata['ssoid']
page.login(username, password, ssoid)
end
visit(TransactionsDetailsPage)
end
When(/^the user clicks on the IHG rewards link in the Account Brick$/) do
visit(TransactionsDetailsPage)
on(TransactionsDetailsPage).rewards_amount
end
Given(/^user logged into COS with a multicard IHG cobranded account and navigates to transactions and details page$/) do
DataMagic.load("canada.yml")
visit LoginPage
on(LoginPage) do |page|
logindata = page.data_for(:can_multicard_IHG)
username = logindata['username']
password = logindata['password']
ssoid = logindata['ssoid']
page.login(username, password, ssoid)
end
visit(TransactionsDetailsPage)
end
Given(/^user logged into COS for multicard with both Delta and IHG co\-branded accounts and navigates to transactions and details page$/) do
DataMagic.load("canada.yml")
visit LoginPage
on(LoginPage) do |page|
logindata = page.data_for(:can_multicard_IHG_Delta)
username = logindata['username']
password = logindata['password']
ssoid = logindata['ssoid']
page.login(username, password, ssoid)
end
visit(TransactionsDetailsPage)
end
And(/^an interstitial page should show$/) do
visit(IHGRewardsInterstitial)
on(IHGrewardsinterstitial).attach_to_window(:url => 'redirect/ihg')
end
And(/^an interstitial page for Delta cobranded account should show$/) do
visit(DeltaRewardsInterstitial)
on(DeltaRewardsInterstitial).attach_to_window(:url => '/redirect/delta')
end
And(/^And an interstitial page for Delta cobranded account displays with content should advise the customer they are leaving Capital One and going to the Delta Rewards Site$/) do
on(DeltaRewardsInterstitial) do |page|
page.attach_to_window(:url => 'redirect/delta')
page.expect(interstitial_bodytext_delta).include? data_for(:interstial_messaging)['delta_redirect_message']
end
And(/^on the transaction and details page the user selects another Delta cobranded account from the dropdown$/) do
visit(TransactionsDetailsPage)
sleep 5
@browser.select_list(:id => 'account_name', :value => 1)
end
And(/^an interstitial page for IHG should show$/) do
visit(IHGRewardsInterstitial)
on(IHGRewardsInterstitial).attach_to_window(:url => 'redirect/ihg')
end
Then(/^an interstitial page displays with with content advising the customer they are leaving Capital One site and going to the IHG Rewards Site$/) do
visit(IHGRewardsInterstitial)
on(IHGRewardsInterstitial) do |page|
page.attach_to_window(:url => 'redirect/ihg')
page.expect(interstitial_bodytext_ihg).include? data_for(:interstial_messaging)['ihg_redirect_message']
end
end
end
Then(/^an interstitial page for Delta cobranded account displays with content should advise the customer they are leaving Capital One and going to the Delta Rewards Site$/) do
visit(DeltaRewardsInterstitial)
on(DeltaRewardsInterstitial) do |page|
page.attach_to_window(:url => 'redirect/Delta')
page.expect(interstitial_bodytext_delta).include? data_for(:interstitial_messaging)['delta_redirect_message']
end
end
When(/^the user clicks on the Delta rewards link in the Account Brick$/) do
on(TransactionsDetailsPage) do |page|
page.rewards_amount
end
end
Then(/^the user should be transfered to Delta rewards site$/) do
expect(@browser.url).to eq "https://cosqa3.kdc.capitalone.com/ui/#/accounts/rewards/redirect/delta"
end
Then(/^the user will be transferred to IHG rewards site$/) do
visit(IHGRewardsWebsite)
on(IHGRewardsWebsite) do |page|
page.wait_for_ihg_website
expect(@browser.url).to eq "http://www.ihg.com/rewardsclub/us/en/home?cm_mmc=domains-_-MM-_-1213-_-priorityclub.ca"
end
end
Then(/^an IHG interstitial page displays with with content advising the customer they are leaving Capital One site and going to the IHG Rewards Site$/) do
visit(IHGRewardsInterstitial)
on(IHGRewardsInterstitial) do |page|
page.attach_to_window(:url => 'redirect/ihg')
page.interstitial_bodytext_ihg.include? data_for(:interstitial_messaging)['ihg_redirect_message']
end
end
Given(/^user logged into COS with a single Delta cobranded account and navigates to transactions and details page$/) do
DataMagic.load("canada.yml")
visit LoginPage
on(LoginPage) do |page|
logindata = page.data_for(:can_singlecard_Delta)
username = logindata['username']
password = logindata['password']
ssoid = logindata['ssoid']
page.login(username, password, ssoid)
end
visit(TransactionsDetailsPage)
end
Then(/^the user will be transferred to Delta rewards site$/) do
visit(DeltaRewardsWebsite)
on(DeltaRewardsWebsite) do |page|
page.wait_for_delta_website
expect(@browser.url).to eq "http://www.delta.com/"
end
end
Then(/^an Delta interstitial page for Delta cobranded account displays with content should advise the customer they are leaving Capital One and going to the Delta Rewards Site$/) do
on(DeltaRewardsInterstitial) do |page|
page.attach_to_window(:url => 'redirect/delta')
page.interstitial_bodytext_delta.include? data_for(:interstitial_messaging)['delta_redirect_message']
end
end
And(/^on the transaction and details page the user selects an Delta cobranded account from the dropdown$/) do
on(TransactionsDetailsPage) do |page|
page.multi_card_names_element.visible?
page.multi_card_names = data_for(:can_trans_and_details_acct_selection)['delta_card']
end
end
And(/^the user closes the tab$/) do
@browser.execute_script("window.close()")
@browser.windows.first.use
end
When(/^the user clicks on the IHG rewards card art$/) do
on(TransactionsDetailsPage) do |page|
page.card_art_link
end
end
When(/^the user clicks on the Delta rewards card art$/) do
on(TransactionsDetailsPage) do |page|
page.card_art_link
end
end
And(/^the user clicks the Delta rewards card art$/) do
on(TransactionsDetailsPage) do |page|
page.card_art_link_1
end
end |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Component rendering', type: :component_template do
describe 'with attribute' do
before do
set_component_template(<<~eos)
some content
<%= an_attribute %>
more content
eos
end
it 'works' do
view_template = "template <%= #{component_class_name}(an_attribute: 'val') %>"
expect(render_view_template(view_template)).to eq(<<~eos)
template some content
val
more content
eos
end
describe 'setting defaults' do
before { component_class.defaults = {an_attribute: 'default value'} }
context 'with attribute' do
it 'uses the value' do
view_template = "template <%= #{component_class_name}(an_attribute: 'given val') %>"
expect(render_view_template(view_template)).to eq(<<~eos)
template some content
given val
more content
eos
end
end
context 'without attribute' do
it 'uses the default value' do
view_template = "template <%= #{component_class_name} %>"
expect(render_view_template(view_template)).to eq(<<~eos)
template some content
default value
more content
eos
end
end
end
end
describe 'with block' do
before do
set_component_template(<<~eos)
some content
<%= block_content %>
more content
eos
component_class.send(:redefine_method, :cache_key) do
[attributes[:an_attribute], block_content]
end
end
it 'works' do
view_template = "template <%= #{component_class_name}(an_attribute: 'value') do %>content from block<% end %>"
expect(render_view_template(view_template)).to eq(<<~eos)
template some content
content from block
more content
eos
end
describe 'block_content in #cache_key' do
subject do
component_class.new(nil, ActionView::Base.new, :show, an_attribute: :value, block: proc { 'the block' })
end
it 'works' do
expect(subject.cache_key).to eq([:value, 'the block'])
end
end
end
end
|
class UserPolicy < ApplicationPolicy
attr_reader :user, :record
def show?
@user.id == @record.id || @user.admin?
end
end
|
require 'pry'
class Owner
@@all = []
attr_accessor :owner, :pets, :name
attr_reader :species
def initialize(owner, species="human")
@pets = {fishes: [], cats: [], dogs: []}
@owner = owner
@species = species
@@all << self
# binding.pry
end
#CLASS OPERATORS
def self.reset_all
@@all.clear
end
def self.count
@@all.length
end
def self.all
@@all
end
#===================
# def name=(name)
# @name = name
# end
def say_species
return "I am a #{@species}."
end
def buy_fish(fish_name)
name = Fish.new(fish_name)
@pets[:fishes] << name
@pets[:fishes].count
end
def buy_cat(cat_name)
name = Cat.new(cat_name)
@pets[:cats] << name
@pets[:cats].count
end
def buy_dog(dog_name)
name = Dog.new(dog_name)
@pets[:dogs] << name
@pets[:dogs].count
end
def play_with_cats
@pets[:cats].collect do |x|
x.mood = "happy"
end
end
def feed_fish
@pets[:fishes].collect do |x|
x.mood = "happy"
end
end
def walk_dogs
@pets[:dogs].collect do |x|
x.mood = "happy"
end
end
def sell_pets
@pets.each do |type,pets_hash|
pets_hash.map do |x|
x.mood = "nervous"
end
end
@pets.clear
end
def list_pets
x = @pets[:fishes].length
y = @pets[:dogs].length
z = @pets[:cats].length
"I have #{x} fish, #{y} dog(s), and #{z} cat(s)."
end
end
|
require 'spec_helper'
describe Request::Rack, '#port' do
subject { object.port }
it_should_behave_like 'a rack env accessor' do
let(:object) { described_class.new(env) }
let(:rack_key) { 'SERVER_PORT' }
let(:rack_key_value) { '80' }
let(:expected_value) { 80 }
end
end
|
Rails.application.routes.draw do
root 'static_pages#home'
devise_for :users
resources :venues do
resources :events do
resources :tickets, only: [:index, :show]
resources :ticket_options
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.