text stringlengths 10 2.61M |
|---|
class CleanupUsersTable < ActiveRecord::Migration
def change
remove_column :users, :full_address
remove_column :users, :city
remove_column :users, :state
remove_column :users, :zip
remove_column :users, :latitude
remove_column :users, :longitude
remove_column :users, :suspicion
remove_column :users, :login_count
remove_column :users, :user_type
remove_column :users, :public
end
end
|
class OrderLineItem < ApplicationRecord
belongs_to :inventory_item, required: false
belongs_to :order, required: false
before_save :save_total_price
#accepts_nested_attributes_for :order
#validates :order_item_qty, presence: true, numericality: { only_integer: true, greater_than: 0 }
def total_fixed_price
fixed_item_price.to_i * order_item_qty.to_i
end
private
def updated_total_price
inventory_item.price.to_i * order_item_qty.to_i
end
def save_total_price
self.total_price = inventory_item.price.to_f * order_item_qty.to_f
end
end
|
require 'rails_helper'
RSpec.describe 'Comp Card Types API' do
let!(:comp_card_type) { create(:comp_card_type)}
describe 'GET /comp_card_types' do
before { get '/comp_card_types'}
it 'return status code 200' do
expect(response).to have_http_status(200)
end
it 'return comp card types' do
expect(json).not_to be_empty
expect(json.size).to eq(1)
end
end
end
|
require "rails_helper"
RSpec.feature 'View a dasboard', :type => 'feature' do
before :each do
end
scenario "User acess the dashboards index" do
visit "dashboards"
expect(page).to have_text("Pipefy Recruitment Test")
expect(page).to have_text("Back-end Test")
expect(page).to have_text("Something is not working")
expect(page).to have_text("Missing translation on reports")
end
scenario "User clicks the 'fecht new data button'" do
visit "dashboards"
click_button "Fecht new data"
expect(page).to have_text("All data is up to date!")
end
end |
# == Schema Information
#
# Table name: events
#
# id :integer(4) not null, primary key
# user_id :integer(4) not null
# surfspot_id :integer(4)
# report_id :integer(4)
# thirdparty_account_id :integer(4)
# type :string(255)
# action :integer(4)
# created_at :datetime
# updated_at :datetime
# surf_session_id :integer(4)
# friend_id :integer(4)
# comment_id :integer(4)
# gear_id :integer(4)
# surfboard_id :integer(4)
# post_id :integer(4)
#
class GearEvent < Event
GEAR_ADDED = 0
GEAR_EDITED = 1
GEAR_DELETED = 2
validates_presence_of :gear_id, :action
end
|
class FlickrService
def initialize(location)
@location = location
end
def forecast
Forecast.new(@location)
end
def latitude
forecast.latitude
end
def longitude
forecast.longitude
end
def all_photos
Flickr.configure do |config|
config.api_key = ENV['flickr_key']
config.shared_secret = ENV['flickr_secret']
end
Flickr.photos.search(lat: latitude, lon: longitude, tags: "city")
end
end
|
class DispatcherSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :username, :email, :destination
attribute :formatted_destination do |object|
uri = object.destination.gsub(/ /, '+')
"https://www.google.com/maps/embed/v1/place?key=#{ENV['GOOGLE_MAPS_API_KEY']}&q=#{uri}"
end
end
|
# frozen_string_literal: true
# TODO: add tests
module Ringu
module Injector
extend self
def create(deps)
Module.new do
define_method(:deps) { deps }
def self.included(klass)
klass.extend ClassMethods
klass.send :include, InstanceMethods
end
end
end
module ClassMethods
def inject(name, klass = nil)
attr_accessor name
injector[name] = {
klass: klass
}
end
def injector
@injector ||= {}
end
end
module InstanceMethods
def initialize(**kwargs)
self.class.injector.each do |name, options|
term = kwargs[name] || options[:klass]
resource = deps.resolve(name, term)
instance_variable_set("@#{name}", resource)
end
end
end
end
end
|
require 'vanagon/component/dsl'
require 'vanagon/component/rules'
require 'vanagon/component/source'
require 'vanagon/component/source/rewrite'
require 'vanagon/logger'
class Vanagon
class Component
include Vanagon::Utilities
# @!attribute [r] files
# @return [Set] the list of files marked for installation
# 30 accessors is too many. These have got to be refactored.
# - Ryan McKern, 2017-01-27
# The name, version, primary source, supplementary sources,
# associated patches, upstream URL (for fetching the source),
# homepage, and license of a given component
attr_accessor :name
attr_accessor :version
attr_accessor :source
attr_accessor :sources
attr_accessor :patches
attr_accessor :url
attr_accessor :mirrors
attr_accessor :license
attr_accessor :homepage
# holds an OpenStruct describing all of the particular details about
# how any services associated with a given component should be defined.
attr_accessor :service
# holds the expected directory name of a given component, once it's
# been unpacked/decompressed. For git repos, it's usually the directory
# that they were cloned to. For the outlying flat files, it'll
# end up being defined explicitly as the string './'
attr_accessor :dirname
# The specific tools or command line invocations that
# should be used to extract a given component's sources
attr_accessor :extract_with
# how should this component be configured?
attr_accessor :configure
# the optional name of a directory to build a component in; most
# likely to be used for cmake projects, which do not like to be
# configured or compiled in their own top-level directories.
attr_accessor :build_dir
# build will hold an Array of the commands required to build
# a given component
attr_accessor :build
# check will hold an Array of the commands required to validate/test
# a given component
attr_accessor :check
# install will hold an Array of the commands required to install
# a given component
attr_accessor :install
# holds a Vanagon::Environment object, to map out any desired
# environment variables that should be rendered into the Makefile
attr_accessor :environment
# holds a OpenStruct, or an Array, or maybe it's a Hash? It's often
# overloaded as a freeform key-value lookup for platforms that require
# additional configuration beyond the "basic" component attributes.
# it's pretty heavily overloaded and should maybe be refactored before
# Vanagon 1.0.0 is tagged.
attr_accessor :settings
# used to hold the checksum settings or other weirdo metadata related
# to building a given component (git ref, sha, etc.). Probably conflicts
# or collides with #settings to some degree.
attr_accessor :options
# the platform that a given component will be built for -- due to the
# fact that Ruby is pass-by-reference, it's usually just a reference
# to the same Platform object that the overall Project object also
# contains. This is a definite code smell, and should be slated
# for refactoring ASAP because it's going to have weird side-effects
# if the underlying pass-by-reference assumptions change.
attr_accessor :platform
# directories holds an Array with a list of expected directories that will
# be packed into the resulting artifact's bill of materials.
attr_accessor :directories
# build_requires holds an Array with a list of the dependencies that a given
# component needs satisfied before it can be built.
attr_accessor :build_requires
# requires holds an Array with a list of all dependencies that a given
# component needs satisfied before it can be installed.
attr_accessor :requires
# replaces holds an Array of OpenStructs that describe a package that a given
# component will replace on installation.
attr_accessor :replaces
# provides holds an Array of OpenStructs that describe any capabilities that
# a given component will provide beyond the its filesystem payload.
attr_accessor :provides
# conflicts holds an Array of OpenStructs that describe a package that a
# given component will replace on installation.
attr_accessor :conflicts
# preinstall_actions is a two-dimensional Array, describing scripts that
# should be executed before a given component is installed.
attr_accessor :preinstall_actions
# install_triggers is a one-dimensional Array of OpenStructs, describing scripts that
# should be executed when a package is installed or upgraded
attr_accessor :install_triggers
# interest_triggers is a one-dimensional Array of OpenStructs, describing scripts that
# should be executed when a package identifies an interest trigger
attr_accessor :interest_triggers
# activate_triggers is a one-dimentional Array of Strings, describing scripts that
# should be executed when a package identifies an activate trigger
attr_accessor :activate_triggers
# postinstall_actions is a two-dimensional Array, describing scripts that
# should be executed after a given component is installed.
attr_accessor :postinstall_actions
# preremove_actions is a two-dimensional Array, describing scripts that
# should be executed before a given component is uninstalled.
attr_accessor :preremove_actions
# preinstall_actions is a two-dimensional Array, describing scripts that
# should be executed after a given component is uninstalled.
attr_accessor :postremove_actions
# cleanup_source contains whatever value a given component's Source has
# specified as instructions for cleaning up after a build is completed.
# usually a String, but not required to be.
attr_accessor :cleanup_source
# When dealing with compiled artifacts generated by setting
# `project.generate_archives true`, you only need to install the component.
# By setting install_only to true the component 'build' will exclude the
# unpack, patch, configure, build, and check steps.
attr_accessor :install_only
# Loads a given component from the configdir
#
# @param name [String] the name of the component
# @param configdir [String] the path to the component config file
# @param settings [Hash] the settings to be used in the component
# @param platform [Vanagon::Platform] the platform to build the component for
# @return [Vanagon::Component] the component as specified in the component config
# @raise if the instance_eval on Component fails, the exception is reraised
def self.load_component(name, configdir, settings, platform)
compfile = File.join(configdir, "#{name}.rb")
dsl = Vanagon::Component::DSL.new(name, settings, platform)
dsl.instance_eval(File.read(compfile), compfile, 1)
dsl._component
rescue StandardError => e
VanagonLogger.error "Error loading project '#{name}' using '#{compfile}':"
VanagonLogger.error e
VanagonLogger.error e.backtrace.join("\n")
raise e
end
# Component constructor.
#
# @param name [String] the name of the component
# @param settings [Hash] the settings to be used in the component
# @param platform [Vanagon::Platform] the platform to build the component for
# @return [Vanagon::Component] the component with the given settings and platform
def initialize(name, settings, platform) # rubocop:disable Metrics/AbcSize
@name = name
@settings = settings
@platform = platform
@options = {}
@build_requires = []
@requires = []
@configure = []
@install = []
@build = []
@check = []
@patches = []
@files = Set.new
@ghost_files = Set.new
@directories = []
@replaces = []
@provides = []
@conflicts = []
@environment = Vanagon::Environment.new
@sources = []
@preinstall_actions = []
@install_triggers = []
@interest_triggers = []
@activate_triggers = []
@postinstall_actions = []
@preremove_actions = []
@postremove_actions = []
@install_only = false
@service = []
end
# Adds the given file to the list of files and returns @files.
#
# @param file [Vanagon::Common::Pathname] file to add to a component's list of files
# @return [Set, nil] Returns @files if file is successfully added to @files
# or nil if file already exists
def add_file(file)
@files.add file
end
# Adds the given file to the list of %ghost files to be added to an
# rpm spec's %files.
#
# @param file [Vanagon::Common::Pathname] file to add to the ghost file set.
# @return [Set, nil] Returns @ghost_files if the file is successfully added
# to @ghost_files or nil if the file already exists.
def add_rpm_ghost_file(file)
@ghost_files.add file
end
# Deletes the given file from the list of files and returns @files.
#
# @param file [String] path of file to delete from a component's list of files
# @return [Set, nil] Returns @files if file is successfully deleted
# from @files or nil if file doesn't exist; this matches strictly on
# the path of a given file, and ignores other attributes like :mode,
# :owner, or :group.
def delete_file(file)
@files.delete_if { |this_file| this_file.path == file }
end
# Retrieve all items from @files not marked as configuration files
#
# @return [Set] all files not marked as configuration files
def files
@files.reject(&:configfile?)
end
# Retrieve all items from @files explicitly marked as configuration files
#
# @return [Set] all files explicitly marked as configuration files
def configfiles
@files.select(&:configfile?)
end
# Retrieve all the files intended as %ghost entries for an rpm spec
# %files section.
#
# @return [Array] of all the rpm %ghost files.
def rpm_ghost_files
@ghost_files.to_a
end
# @return [Set] a list of unique mirror URIs that should be used to
# retrieve the upstream source before attempting to retrieve from
# whatever URI was defined for #uri. If no mirrors are set and the
# deprecated rewrite system has been configured, this will return
# rewritten URIs
def mirrors # rubocop:disable Lint/DuplicateMethods
@mirrors ||= Set.new [deprecated_rewrite_url].compact
end
# Retrieve upstream source file from a mirror, by randomly iterating
# through #mirrors until there's no more mirrors left. Will #warn
# if the mirror's URI cannot be resolved or if the URI cannot
# be retrieved. Does not suppress any errors from
# Vanagon::Component::Source.
#
# @return [Boolean] return True if the source can be retrieved,
# or False otherwise. This is because because each subclass of
# Vanagon::Component::Source returns an inconsistent value
# if #fetch is successful.
def fetch_mirrors(options)
mirrors.to_a.shuffle.each do |mirror|
begin
VanagonLogger.info %(Attempting to fetch from mirror URL "#{mirror}")
@source = Vanagon::Component::Source.source(mirror, **options)
return true if source.fetch
rescue Vanagon::InvalidSource
# This means that the URL was not a git repo or a valid downloadable file,
# which means either the URL is incorrect, or we don't have access to that
# resource. Return false, so that the pkg.url value can be used instead.
VanagonLogger.error %(Invalid source "#{mirror}")
rescue SocketError
# SocketError means that there was no DNS/name resolution
# for whatever remote protocol the mirror tried to use.
VanagonLogger.error %(Unable to resolve mirror URL "#{mirror}")
rescue StandardError
# Source retrieval does not consistently return a meaningful
# namespaced error message, which means we're brute-force rescuing
# StandardError. Also, we want to handle other unexpected things when
# we try reaching out to the URL, so that we can gracefully return
# false and fall back to fetching the pkg.url value instead.
VanagonLogger.error %(Unable to retrieve mirror URL "#{mirror}")
end
end
false
end
# Retrieve upstream source file from the canonical URL.
# Does not suppress any errors from Vanagon::Component::Source.
#
# @return [Boolean] return True if the source can be retrieved,
# or False otherwise
def fetch_url(options)
VanagonLogger.info %(Attempting to fetch from canonical URL "#{url}")
@source = Vanagon::Component::Source.source(url, **options)
# Explicitly coerce the return value of #source.fetch,
# because each subclass of Vanagon::Component::Source returns
# an inconsistent value if #fetch is successful.
!!source.fetch
end
# This method is deprecated and private. It will return
# a rewritten URL if there's any value for #url and a
# rewrite rule for that URL has been set
def deprecated_rewrite_url
return nil unless url
rewritten_url = Vanagon::Component::Source::Rewrite.parse_and_rewrite(url)
url == rewritten_url ? nil : rewritten_url
end
private :deprecated_rewrite_url
# Fetches the primary source for the component. As a side effect, also sets
# @extract_with, @dirname and @version for the component for use in the
# makefile template
#
# @param workdir [String] working directory to put the source into
def get_source(workdir) # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
opts = options.merge({ workdir: workdir, dirname: dirname })
if url || !mirrors.empty?
if ENV['VANAGON_USE_MIRRORS'] == 'n' or ENV['VANAGON_USE_MIRRORS'] == 'false'
fetch_url(opts)
else
fetch_mirrors(opts) || fetch_url(opts)
end
source.verify
extract_with << source.extract(platform.tar) if source.respond_to? :extract
@cleanup_source = source.cleanup if source.respond_to?(:cleanup)
@dirname ||= source.dirname
# Git based sources probably won't set the version, so we load it if it hasn't been already set
if source.respond_to?(:version)
@version ||= source.version
end
else
VanagonLogger.info "No source given for component '#{@name}'"
# If there is no source, we don't want to try to change directories, so we just change to the current directory.
@dirname = './'
# If there is no source, there is nothing to do to extract
extract_with << ': no source, so nothing to extract'
end
end
# Expands the build directory
def get_build_dir
if @build_dir
File.join(@dirname, @build_dir)
else
@dirname
end
end
def get_dependency_hash
{ name => { 'version' => version, 'url' => url, 'ref' => options[:ref] }.delete_if { |_, v| !v } }
end
# Fetches secondary sources for the component. These are just dumped into the workdir currently.
#
# @param workdir [String] working directory to put the source into
def get_sources(workdir) # rubocop:disable Metrics/AbcSize
sources.each do |source|
src = Vanagon::Component::Source.source(
source.url, workdir: workdir, ref: source.ref, sum: source.sum
)
src.fetch
src.verify
if source.erb
erb_file(src.file, File.join(File.dirname(src.file), File.basename(src.file, ".erb")), true)
end
# set src.file to only be populated with the basename instead of entire file path
src.file = File.basename(src.url)
extract_with << src.extract(platform.tar) if src.respond_to? :extract
end
end
# @return [Array] the specific tool or command line invocations that
# should be used to extract a given component's primary source
def extract_with # rubocop:disable Lint/DuplicateMethods
@extract_with ||= []
end
# Fetches patches if any are provided for the project.
#
# @param patch_root [String] working directory to put the patches into
def get_patches(patch_root)
return if @patches.empty?
@patches.each do |patch|
patch_assembly_path = File.join(patch_root, patch.assembly_path)
if File.exist?(patch_assembly_path)
raise Vanagon::Error, "Duplicate patch files detected, '#{patch.origin_path}' would have overwritten '#{patch.assembly_path}'. Ensure all patch file names within a component are unique."
end
patch_target_directory = File.dirname(patch_assembly_path)
FileUtils.mkdir_p(patch_target_directory)
FileUtils.cp(patch.origin_path, patch_assembly_path)
end
end
# Force version determination for components
#
# If the component doesn't already have a version set (which normally happens for git sources),
# the source will be fetched into a temporary directory to attempt to figure out the version if the
# source type supports :version. This directory will be cleaned once the get_sources method returns
#
# @raise Vanagon::Error raises a vanagon error if we're unable to determine the version
def force_version
if @version.nil?
Dir.mktmpdir do |dir|
get_source(dir)
end
end
raise Vanagon::Error, "Unable to determine source version for component #{@name}!" if @version.nil?
@version
end
# Prints the environment in a way suitable for use in a Makefile
# or shell script. This is deprecated, because all Env. Vars. are
# moving directly into the Makefile (and out of recipe subshells).
#
# @return [String] environment suitable for inclusion in a Makefile
# @deprecated
def get_environment
VanagonLogger.info <<-WARNING.undent
#get_environment is deprecated; environment variables have been moved
into the Makefile, and should not be used within a Makefile's recipe.
The #get_environment method will be removed by Vanagon 1.0.0.
WARNING
if environment.empty?
": no environment variables defined"
else
environment_variables
end
end
def environment_variables
environment.map { |key, value| %(export #{key}="#{value}") }
end
def rules(project, platform)
Vanagon::Component::Rules.new(self, project, platform)
end
end
end
|
class OrdersController < ApplicationController
before_filter :activate_tab, :shop_navigation, :set_current_item
before_filter :show_menu, :except => [:new]
# GET /orders
# GET /orders.xml
def index
@orders = (logged_in? ) ? Order.buyer(current_member).purchased : []
respond_to do |format|
format.html # index.rhtml
format.xml { render :xml => @orders.to_xml }
end
end
# GET /orders/1
# GET /orders/1.xml
def show
begin
if @cart.id == params[:id].to_i
render :action => "checkout"
else
session[:foo] # lazy loading session patch. see: http://bit.ly/1pvTLv
@order = (logged_in?) ? current_member.orders.find(params[:id]) : Order.find_by_session_id(request.session_options[:id])
end
rescue
flash[:notice] = "This order is not yours or cannot be found."
end
end
def complete
begin
session[:foo] # lazy loading session patch. see: http://bit.ly/1pvTLv
@order = (logged_in?) ? current_member.orders.find(params[:id]) : Order.find_by_session_id(request.session_options[:id])
rescue
nil
end
unless @order.nil?
if !@order.paid?
PaymentNotification.create!(:params => params, :order_id => params[:invoice],
:status => params[:payment_status], :transaction_id => params[:txn_id])
end
redirect_to order_path(@order)
else
flash[:notice] = "There was a problem completing this order. Please contact customer service at support@homeschoolapple.com"
redirect_to home_path
end
end
def cancel
@cart.cancel!
redirect_to home_path
end
# GET /orders/new
# def new
# @current_item = nil
# if @cart.empty?
# redirect_to_index("Your cart is empty" )
# elsif !logged_in?
# flash[:notice] = "Please log in or create an account to continue."
# store_location
# redirect_to login_path
# else
# @cart = Order.new
# @cart.email = self.current_member.email
# @last_order = Order.find(:first, :conditions => ["member_id = ?", current_member], :order => "id DESC")
# @cart = prepopulate_order(@cart, @last_order) unless @last_order.nil?
#
# end
# end
def destroy
@cart.empty_cart
flash[:notice] = "Your cart is now empty"
end
private
def ship_to_billing (order)
order.ship_address_line_1 = order.address_line_1
order.ship_address_line_2 = order.address_line_2
order.ship_city = order.city
order.ship_state = order.state
order.ship_zip = order.zip
order.ship_country = order.country
return order
end
def prepopulate_order (order, last_order)
order.name = last_order.name
order.email = last_order.email
order.address_line_1 = last_order.address_line_1
order.address_line_2 = last_order.address_line_2
order.city = last_order.city
order.state = last_order.state
order.zip = last_order.zip
order.country = last_order.country
order.ship_address_line_1 = last_order.ship_address_line_1
order.ship_address_line_2 = last_order.ship_address_line_2
order.ship_city = last_order.ship_city
order.ship_state = last_order.ship_state
order.ship_zip = last_order.ship_zip
order.ship_country = last_order.ship_country
order.pay_info = last_order.pay_info
order.pay_type = last_order.pay_type
order.ship_to = last_order.ship_to
return order
end
def activate_tab
@active_tab = "shop_tab"
end
def set_current_item
@current_item = "my_purchases"
end
end |
class CreateStudentEmails < ActiveRecord::Migration
def change
create_table :student_emails do |t|
t.string :email
t.integer :course_id
t.string :random_url
t.datetime :created_at
t.datetime :updated_at
end
end
end
|
class Entry<ActiveRecord::Base
validates_presence_of :title
validates_presence_of :description
belongs_to :category,
inverse_of: :entries
default_scope order('updated_at DESC')
def rendered_category_name
if category == nil
""
else
category.name
end
end
def ordered_by_date
end
end |
describe IGMarkets::DealingPlatform::SprintMarketPositionMethods do
let(:session) { IGMarkets::Session.new }
let(:platform) do
IGMarkets::DealingPlatform.new.tap do |platform|
platform.instance_variable_set :@session, session
end
end
it 'can retrieve the current sprint market positions' do
positions = [build(:sprint_market_position)]
expect(session).to receive(:get)
.with('positions/sprintmarkets', IGMarkets::API_V1)
.and_return(sprint_market_positions: positions)
expect(platform.sprint_market_positions.all).to eq(positions)
end
it 'can create a sprint market position' do
attributes = {
direction: :buy,
epic: 'CS.D.EURUSD.CFD.IP',
expiry_period: :five_minutes,
size: 2.0
}
payload = {
direction: 'BUY',
epic: 'CS.D.EURUSD.CFD.IP',
expiryPeriod: 'FIVE_MINUTES',
size: 2.0
}
result = { deal_reference: 'reference' }
expect(session).to receive(:post).with('positions/sprintmarkets', payload, IGMarkets::API_V1).and_return(result)
expect(platform.sprint_market_positions.create(attributes)).to eq(result.fetch(:deal_reference))
end
end
|
#coding : utf-8
#
# 系统任务
#
namespace :system do
#
# 系统维护后给用户发消息并进行补偿
# 执行命令 /opt/ruby/bin/ruby /opt/ruby/bin/rake system:send_system_message
#
desc '发送系统消息'
task(:send_system_message => :environment) do
system_message = '今天服务器维护,送叫花鸡3个,100000白银,祝愿大家玩的开心'
reward_type = '1001' # 例子
User.find_each(batch_size: 1000) do |user|
if user.npc_or_not == 0 # 不是npc的用户会收到奖励
system_reward_record = SystemRewardRecorder.new
system_reward_record.system_message = system_message
system_reward_record.reward_type = reward_type
system_reward_record.user_id = user.id
system_reward_record.receive_or_not = SystemRewardRecorder::NOT_RECEIVED
system_reward_record.save
end
end
end
#
# 初始化系统后,根据npc_config.json进行npc数据初始化,存入数据库
# 执行命令 /opt/ruby/bin/ruby /opt/ruby/bin/rake system:init_npc
#
desc '初始化npc'
task(:init_npc => :environment) do
# 解析npc配置
npc_config_path = "#{Rails.root}/config/configurations/npc_config.json"
npc_config_content = ''
File.open(npc_config_path, 'r'){|f| npc_config_content = f.read }
npc_config_array = JSON.parse(npc_config_content)
puts ("npc配置信息: \n#{JSON.pretty_generate(npc_config_array).to_s}")
lunjian_rank = 1 # 论剑排位从1开始
npc_config_array.each() do |npc|
puts "position:#{lunjian_rank}"
# 导入npc基本信息
user = User.new
user.name = npc['name'].to_s
user.level = npc['level'].to_i
user.username = npc['id'].to_s
user.password = npc['id'].to_s
# 区分npc和普通用户
user.npc_or_not = 1
if user.save
puts 'user save success'
else
puts 'user save failed'
end
puts ("user信息: \n#{user.to_s}")
team_position = 0 # 布阵排位从0开始
# 导入阵容信息
team_array = npc['team']
team_array.each() do |member|
# 记录弟子信息
disciple = Disciple.new
disciple.d_type = member['id']
disciple.level = member['level']
disciple.user_id = user.id
disciple.save
# 记录弟子阵容排位信息
team_member = TeamMember.new
team_member.user_id = user.id
team_member.disciple_id = disciple.id
team_member.position = team_position
team_member.save
team_position = team_position + 1
end
# 添加论剑排名记录
lunjian_position = LunjianPosition.new
lunjian_position.user_id = user.id
lunjian_position.position = lunjian_rank
lunjian_position.left_time = 0
lunjian_position.score = 0
lunjian_position.save
lunjian_rank = lunjian_rank + 1
end
end
end
|
class Api::V1::EventResource < Api::V1::EntriesBaseResource
model_name 'Event'
attributes *(ATTRIBUTES + [:date_start, :date_end])
attribute :has_time_start, delegate: :time_start
attribute :has_time_end, delegate: :time_end
# not for now:
# :public_speaker, :location_type, :support_wanted,
# actual not needed (wait for ui)
# has_one :parent_event, class_name: 'Event', foreign_key: 'parent_id'
# has_many :sub_events, class_name: 'Event', foreign_key: 'children_ids'
# has_many :ownables, class_name: 'Ownable'
has_one :orga
before_create do
@model.creator_id = context[:current_user].id
end
before_save do
@model.last_editor_id = context[:current_user].id
end
end
|
require 'pry'
class String
def sentence?
if self.end_with?(".")
return true
else
false
end
end
def question?
if self.end_with?("?")
true
else
false
end
end
def exclamation?
if self.end_with?("!")
true
else
false
end
end
def count_sentences
fresh_array = self.split(/[.?!]/)
fresh_array.delete_if{|sentence| sentence.empty?}
fresh_array.length
end
end |
class Veiculo
attr_accessor :nome, :marca, :modelo
def initialize(nome, marca, modelo)
self.nome = nome
self.marca = marca
self.modelo = modelo
end
def ligar
puts "#{nome} esta pronto para iniciar o trajeto."
end
def buzinar
puts "Beep! Beep!"
end
end
class Carro < Veiculo
def dirigir
puts "#{nome} iniciando o trajeto..."
end
end
class Moto < Veiculo
def pilotar
puts "#{nome} iniciando o trajeto..."
end
end
up = Carro.new('Up', 'VW', 'TSI')
up.ligar
up.buzinar
up.dirigir
hilux = Carro.new('Hilux', 'Toyota', 'Model')
hilux.ligar
hilux.dirigir
fazer = Moto.new('Fazer', 'yamaha', '250x')
fazer.ligar
fazer.buzinar
fazer.pilotar |
class VotesController < ApplicationController
before_action :authorize!
def create
vote = Vote.create(user_id: current_user.id, episode_id: params[:episode_id])
flash[:warning] = "You already upvoted this episode." if vote.invalid?
redirect_to episodes_path
end
end
|
class EnrollmentsController < ApplicationController
# GET /enrollments
# GET /enrollments.json
def index
@enrollments = Enrollment.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @enrollments }
end
end
def view_enrollments_for
#render :text => "ddd"
@enrollments = Enrollment.where(:studentID => session[:account].netid)
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @enrollments }
end
end
# GET /enrollments/new
# GET /enrollments/new.json
def new
@enrollment = Enrollment.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @enrollment }
end
end
# GET /enrollments/1/edit
def edit
@enrollment = Enrollment.find(params[:id])
end
# POST /enrollments
# POST /enrollments.json
def create
@enrollment = Enrollment.new(params[:enrollment])
respond_to do |format|
if @enrollment.save
format.js { render :js => "redirect('"+enrollments_url+"', '"+"Enrollment Was Successfully Created"+"');"}
format.html { redirect_to @enrollment, :notice => 'Enrollment was successfully created.' }
format.json { render :json => @enrollment, :status => :created, :location => @enrollment }
else
format.html { render :action => "new" }
format.json { render :json => @enrollment.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /enrollments/1
# DELETE /enrollments/1.json
def destroy
@enrollment = Enrollment.find(params[:id])
@enrollment.destroy
respond_to do |format|
format.js { render :js => "redirect('"+enrollments_url+"', '"+"Enrollment Was Successfully Deleted"+"');"}
format.html { redirect_to enrollments_url }
format.json { head :no_content }
end
end
end
|
require_relative "Scheduler_QualificationPanel"
require_relative "Scheduler_CertificateDialog"
class CreateListItem < Wx::ListItem
def initialize
super
super.set_background_colour(changingColor())
end
end
class CertificatePanel < Wx::Panel
attr_accessor :ids, :descriptions, :selected, :qualificationPanel
@listCtrl = nil
@hooverItem = -1
@qualificationPanel = nil
@selected = -1
def initialize(parent, mainQuery, bottomButtons = true)
@ids = []
@certificateNames = []
@descriptions = []
super(parent, -1)
set_background_colour($BGCOLOR)
topSizer = Wx::HBoxSizer.new()
listCtrlSizer = Wx::VBoxSizer.new()
listCtrlPanel = Wx::Panel.new(self,-1)
listCtrlPanel.set_background_colour($BGCOLOR)
@listCtrl = Wx::ListCtrl.new(listCtrlPanel, -1 , {style:Wx::LC_REPORT | Wx::RA_SPECIFY_COLS | Wx::LC_SINGLE_SEL, size:Wx::Size.new(154, 150)})
@listCtrl.insert_column(0, "Certificate")
query = execQuery(mainQuery)
$colorIndex = 1
query.each_hash { |h|
index = @listCtrl.get_item_count()
@ids[index] = h['id'].to_i
@descriptions[index] = h['description']
@certificateNames[index] = h['certificate']
listItem = CreateListItem.new()
listItem.set_id(index)
listItem.set_text(@certificateNames[index])
@listCtrl.insert_item(listItem)
}
@listCtrl.set_column_width(0, 150)
@listCtrl.evt_left_dclick(){|event| on_list_item_dClick()}
@listCtrl.evt_leave_window(){|event| on_leave_window(event)}
@listCtrl.evt_motion(){|event| mouse_over(event)}
evt_list_item_selected(@listCtrl.get_id()){|event| on_list_item_selected()}
evt_list_item_deselected(@listCtrl.get_id()){|event| }
@descriptionStaticText = Wx::TextCtrl.new(listCtrlPanel, -1, "", {style:Wx::NO_BORDER|Wx::TE_MULTILINE|Wx::TE_NO_VSCROLL, size:Wx::Size.new(254, 50)})
@descriptionStaticText.set_background_colour($BGCOLOR)
listCtrlSizer.add(@listCtrl, 0, Wx::ALL, 5)
listCtrlSizer.add_spacer(5)
listCtrlSizer.add(@descriptionStaticText, 0, Wx::LEFT, 10)
listCtrlPanel.set_sizer(listCtrlSizer)
listCtrlSizer.fit(listCtrlPanel)
buttonSizer = Wx::VBoxSizer.new()
buttonPanel = Wx::Panel.new(self, Wx::ID_ANY, {size:Wx::Size.new(100,200)})
buttonPanel.set_background_colour($BGCOLOR)
addButton = Wx::Button.new(buttonPanel, Wx::ID_ANY, "add certificate", {size:Wx::Size.new(100, 20)})
editButton = Wx::Button.new(buttonPanel, Wx::ID_ANY, "edit certificate", {size:Wx::Size.new(100, 20)})
removeButton = Wx::Button.new(buttonPanel, Wx::ID_ANY, "remove certificate", {size:Wx::Size.new(100, 20)})
evt_button(addButton) { clicked( 'add') }
evt_button(editButton) { clicked('edit') }
evt_button(removeButton) { clicked('remove') }
buttonSizer.add_spacer(5)
buttonSizer.add(addButton, 1, Wx::ALL, 5)
buttonSizer.add(editButton, 1, Wx::ALL, 5)
buttonSizer.add(removeButton, 1, Wx::ALL, 5)
buttonPanel.set_sizer(buttonSizer)
buttonSizer.fit(buttonPanel)
qualificationQuery = "SELECT * FROM qualifications"
topSizer.add(listCtrlPanel, 0, Wx::ALL, 5);
@qualificationPanel = (QualificationPanel.new(self, qualificationQuery, false))
@qualificationPanel.clearList()
topSizer.add(@qualificationPanel, 0, Wx::ALL, 0);
if bottomButtons == false
topSizer.add(buttonPanel, 0, Wx::ALL, 5);
buttonPanel.show(false)
else
topSizer.add(buttonPanel, 0, Wx::ALL, 5);
end
set_sizer(topSizer)
topSizer.fit(self)
end
def clicked(label)
if @selected == -1
return
end
if label == "add"
dialog = CertificateDialog.new(self, @listCtrl, "Add Certificate", "Add")
dialog.show()
elsif label == "edit"
if @selected != nil
dialog = CertificateDialog.new(self, @listCtrl,"Edit Certificate", "Edit")
dialog.show()
end
elsif label == "remove"
query = "DELETE FROM shifts WHERE id = #{@ids[@selected]}"
execQuery(query)
@listCtrl.delete_item(@selected)
@ids[@selected] = nil
@ids = @ids.compact()
@descriptions[@selected] = nil
@descriptions = @descriptions.compact()
$colorIndex = 1
for i in 0..@listCtrl.get_item_count() - 1
@listCtrl.set_item_background_colour(i, changingColor())
end
end
end
def on_list_item_selected()
@selected = @listCtrl.get_selections()[0]
@qualificationPanel.refillList("SELECT * FROM qualifications WHERE id IN (SELECT qualification_id FROM certificates_qualifications WHERE certificate_id = #{@ids[@selected]})")
@listCtrl.set_item_background_colour(@selected, Wx::Colour.new("#7DAFFF"))
@listCtrl.get_item(1)
end
def on_list_item_dClick()
dialog = dialog.new(self, @listCtrl, "Edit Time Slot", "Edit")
dialog.show()
end
def on_leave_window(evt)
@descriptionStaticText.set_value("")
end
def mouse_over(evt)
mousePosition = evt.get_position()
item, flags = @listCtrl.hit_test(mousePosition)
p @ids, item
if item == -1
@descriptionStaticText.set_value("")
@hooverItem = item
elsif @hooverItem != item
@descriptionStaticText.set_value(@descriptions[item])
@hooverItem = item
end
end
end
|
require_relative 'dom'
require_relative 'exceptions'
module Dom
# Node can be seen as an **aspect** or feature of another Object. Therefore it can be mixed in to
# add node-functionality to a class.
# Such functionality is used by {CodeObject::Base code-objects} and {Document::Document documents}.
#
# Instance Variables
# ------------------
# The following instance-variables will be set while including Dom::Node into your class:
#
# - `@name` (should be already set in your including class)
# - `@parent`
# - `@children`
#
# @example
# class MyObject
# include Dom::Node
#
# # The contructor of MyObject should call init_node
# def initialize(name)
# super
# @name = name
# end
# end
#
# # MyObject can now be used as a node within our Domtree
# @baz = MyObject.new 'Baz'
# @baz.add_node(MyObject.new 'foo')
# @baz.add_node(MyObject.new 'bar')
#
# # These Nodes get inserted into Dom, so it looks like
# Dom.print_tree
# #=>
# #-Baz
# # -foo
# # -bar
#
# @note including Class should set instance-variable @name
# @see CodeObject::Base
# @see Document::Document
# @see Dom
module Node
NS_SEP_STRING = '.'
NS_SEP = /#{Regexp.escape(NS_SEP_STRING)}/
NODENAME = /[0-9a-zA-Z$_]+/
LEAF = /^#{NS_SEP}(?<name>#{NODENAME})$/
ABSOLUTE = /^(?<first>#{NODENAME})(?<rest>(#{NS_SEP}#{NODENAME})*)$/
RELATIVE = /^#{NS_SEP}(?<first>#{NODENAME})(?<rest>(#{NS_SEP}#{NODENAME})*)$/
# @group Initialization
# The 'constructor' of {Dom::Node}. It initializes all required instance-variables.
# (see {Dom::Node above}).
def initialize
super
@children, @parent = {}, nil
@name ||= "" # should be written by including class
end
# @group Traversing
# `node.parent` returns the parent {Dom::Node node}, if there is one. If no parent exists `nil`
# is returned. In this case `node` can be considered either as loose leave or root of the {Dom}.
#
# @return [Dom::Node] the parent node, if one exists
def parent
@parent
end
# searches all parents recursivly and returns an array, starting with the highest order parent
# (excluding the {Dom.root}) and ending with the immediate parent.
#
# @example
# o1 = CodeObject::Base.new :foo
# o2 = CodeObject::Base.new :bar, o1
# o3 = CodeObject::Base.new :baz, o2
#
# # no parents
# o1.parents #=> []
#
# # all parents
# o3.parents #=> [#<CodeObject::Base:foo>, #<CodeObject::Base:bar>]
#
# @return [Array<Dom::Node>] the associated parents
def parents
return [] if @parent.nil? or @parent.parent.nil?
@parent.parents << @parent
end
# Returns all immediately associated children of this `node`
#
# @return [Hash<Symbol, Dom::Node>]
def children
@children
end
# Get's the child of this node, which is identified by `path`. Returns `nil? , if no matching
# child was found.
#
# @example childname
# Dom[:Core] #=> #<CodeObject::Object:Core @parent=__ROOT__ …>
# Dom['Core'] #=> #<CodeObject::Object:Core @parent=__ROOT__ …>
#
# @example path
# Dom['Core.logger.log'] #=> #<CodeObject::Function:log @parent=logger …>
#
# @overload [](childname)
# @param [String, Symbol] childname
# @return [Dom::Node, nil]
#
# @overload [](path)
# @param [String] path The path to the desired node
# @return [Dom::Node, nil]
def [](path)
return @children[path] if path.is_a? Symbol
return @children[path.to_sym] if path.split(NS_SEP_STRING).size == 1
path = path.split(NS_SEP_STRING)
child = @children[path.shift.to_sym]
return nil if child.nil?
# decend recursive
child[path.join(NS_SEP_STRING)]
end
# Alias for bracket-access
# @see #[]
def find(path)
self[path]
end
# Returns if the current node is a leaf or not.
#
# @return [Boolean]
def has_children?
not (@children.nil? or @children.size == 0)
end
# Finds all siblings of the current node. If there is no parent, it will return `nil`.
#
# @return [Array<Dom::Node>, nil]
def siblings
return nil if parent.nil?
@parent.children
end
# Resolves `nodename` in the current context and tries to find a matching
# {Dom::Node}. If `nodename` is not the current name and further cannot be found in the list of
# **children** the parent will be asked for resolution.
#
# Given the following example, each query (except `.log`) can be resolved without ambiguity.
#
# # -Core
# # -extend
# # -extensions
# # -logger
# # -log
# # -properties
# # -log
#
# Dom[:Core][:logger].resolve '.log'
# #=> #<CodeObject::Function:log @parent=logger @children=[]>
#
# Dom[:Core][:logger][:log].resolve '.log'
# #=> #<CodeObject::Function:log @parent=logger @children=[]>
#
# Dom[:Core][:logger][:log].resolve '.logger'
# #=> #<CodeObject::Object:logger @parent=Core @children=[]>
#
# Dom[:Core].resolve '.log'
# #=> #<CodeObject::Function:log @parent=Core @children=[]>
#
# Dom[:Core][:properties].resolve '.log'
# #=> #<CodeObject::Function:extend @parent=Core @children=[]>
#
# Dom[:Core][:logger].resolve 'foo'
# #=> nil
#
# @param [String] nodename
#
# @return [Dom::Node, nil]
def resolve(nodename)
return self if nodename == @name
return nil if @children.nil? and @parent.nil?
path = RELATIVE.match(nodename)
if path
first, rest = path.captures
# we did find the first part in our list of children
if not @children.nil? and @children.has_key? first.to_sym
# we have to continue our search
if rest != ""
@children[first.to_sym].resolve rest
# Finish
else
@children[first.to_sym]
end
else
@parent.resolve nodename unless @parent.nil?
end
# It's absolute?
elsif ABSOLUTE.match nodename
Dom.root.find nodename
end
end
# Iterates recursivly over all children of this node and applies `block` to them
#
# @param [Block] block
def each_child(&block)
@children.values.each do |child|
yield(child)
child.each_child(&block)
end
end
# @group Manipulation
# There are three different cases
#
# 1. Last Childnode i.e. ".foo"
# -> Append node as child
# 2. absolute path i.e. "Foo"
# -> delegate path resolution to Dom.root
# 3. relative path i.e. ".bar.foo"
# a. if there is a matching child for first element, delegate
# adding to this node
# b. create NoDoc node and delegate rest to this NoDoc
#
#
# @overload add_node(path, node)
# @param [String] path
# @param [Dom::Node] node
#
# @overload add_node(node)
# @param [Dom::Node] node
#
def add_node(*args)
# Grabbing right overload
if args.count == 2
node = args[1]
path = args[0]
elsif args.count == 1
node = args[0]
path = '.'+node.name
raise NoPathGiven.new("#{node} has no path.") if path.nil?
else
raise ArgumentError.new "Wrong number of arguments #{args.count} for 1 or 2"
end
leaf = LEAF.match path
if leaf
# node found, lets insert it
add_child(leaf[:name], node)
else
matches = RELATIVE.match path
if matches
name = matches[:first].to_s
# node not found, what to do?
add_child(name, NoDoc.new(name)) if self[name].nil?
# everything fixed, continue with rest
self[name].add_node(matches[:rest], node)
else
# has to be an absolute path or something totally strange
raise WrongPath.new(path) unless ABSOLUTE.match path
# begin at top, if absolute
Dom.add_node '.' + path, node
end
end
end
# @group Name- and Path-Handling
# Like {#qualified_name} it finds the absolute path.
# But in contrast to qualified_name it will not include the current node.
#
# @example
# my_node.qualified_name #=> "Core.logger.log"
# my_node.namespace #=> "Core.logger"
#
# @see #qualified_name
# @return [String]
def namespace
parents.map{|p| p.name}.join NS_SEP_STRING
end
# The **Qualified Name** equals the **Absolute Path** starting from the
# root-node of the Dom.
#
# @example
# my_node.qualified_name #=> "Core.logger.log"
#
# @return [String]
def qualified_name
parents.push(self).map{|p| p.name}.join NS_SEP_STRING
end
# Generates a text-output on console, representing the **subtree-structure**
# of the current node. The current node is **not** being printed.
#
# @example example output
# -Core
# -extend
# -extensions
# -logger
# -log
# -properties
#
# @return [nil]
def print_tree
# Because parent = nil and parent = Dom.root are handled the same at #parents
# we need to make a difference here
if @parent.nil?
level = 0
else
level = parents.count + 1
end
@children.each do |name, child|
puts "#{" " * level}-#{name.to_s}#{' (NoDoc)' if child.is_a? NoDoc}"
child.print_tree
end
nil
end
protected
def add_child(name, node)
name = name.to_sym
if self[name].nil?
self[name] = node
# If child is a NoDoc: replace NoDoc with node and move all children from
# NoDoc to node using node.add_child
elsif self[name].is_a? NoDoc
self[name].children.each do |name, childnode|
node.add_child(name, childnode)
end
self[name] = node
else
raise NodeAlreadyExists.new(name)
end
self[name].parent = self
end
# @note unimplemented
def remove_child(name) end
def parent=(node)
@parent = node
end
# setting a children of this node
def []=(name, value)
@children[name.to_sym] = value
end
# path can be absolute like `Foo.bar`, `Foo` or it can be relative like
# `.foo`, `.foo.bar`.
# in both cases we need to extract the name from the string and save it
# as name. After doing this we can use the path to save to dom.
#
# @example absolute path
# Node.extract_name_from("Foo.bar.baz") #=> 'baz'
# Node.extract_name_from("Foo.bar.baz") #=> 'baz'
#
# @param [String] path relative or absolute path of node
# @return [String] the extracted name
def extract_name_from(path)
name = path.split(NS_SEP_STRING).last
raise NoNameInPath.new(path) if name.nil?
return name
end
end
end
|
class Category < ApplicationRecord
# t.integer "tag_id", null: false
# t.integer "business_id", null: false
belongs_to :businesses,
foreign_key: :business_id,
class_name: :Business
belongs_to :tags,
foreign_key: :tag_id,
class_name: :Tag
end
|
Gem::Specification.new do |s|
s.name = 'consolehelp'
s.version = '0.0.0'
s.summary = "For all of your console needs!"
s.description = "A simple hello world test gem"
s.authors = ["darkdarcool30"]
s.email = 'darkdarcool@gmail.com'
s.files = ["lib/main.rb"]
s.homepage =
'https://rubygems.org/gems/hola'
s.license = 'MIT'
end
# gem install ./consolehelp-0.0.0.gem |
class CreateUpdates < ActiveRecord::Migration
def self.up
create_table :updates do |t|
t.integer :project_id
t.string :value
t.timestamp :created_at
end
end
def self.down
drop_table :updates
end
end
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/prawn_charts/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Dave McNelis"]
gem.email = ["davemcnelis@market76.com"]
gem.description = %q{Prawn::Charts, Chart module for Prawn
(adapted from Scruffy by Brasten Sager)}
gem.summary = %q{PrawnCharts, Chart module for Prawn
(adapted from Scruffy by Brasten Sager)}
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "prawn_charts"
gem.require_paths = ["lib"]
gem.version = PrawnCharts::VERSION
end
|
class Language < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :lists
end
|
# == Schema Information
# Schema version: 0
#
# Table name: users
#require 'bcrypt'
class User < ActiveRecord::Base
#include BCrypt
attr_accessor :password
#attr_accessible :email, :name, :encrypted_password, :salt, :admin
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
#if self.status.nil?
def destroy
#@user =
end
def has_password?(submitted_password)
encrypted_password == encrypt_pass(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
logger.debug('-- login --')
logger.debug(user.inspect)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
private
def user_params
#params.require(:email).permit!
end
def encrypt_password
logger.debug('--test--')
#abort password.inspect
#self.salt = '1'
#self.encrypted_password = '2'
self.salt = BCrypt::Engine.generate_salt
#self.encrypted_password = BCrypt::Engine.hash_secret(password, salt)
self.encrypted_password = encrypt_pass(password)
#BCrypt::Password.create
#self.encrypted_password.inspect
#self.salt = Digest::SHA2.hexdigest("#{Time.now.utc}--#{password}")
#self.encrypted_password = Digest::SHA2.hexdigest("#{self.salt}--#{password}")
end
def encrypt_password2
return if password.blank?
if new_record?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")
end
self.crypted_password = encrypt_pass(password)
end
def encrypt_pass(password)
BCrypt::Engine.hash_secret(password, self.salt)
end
def clear_password
self.password = nil
end
end |
class StudentClass < ActiveRecord::Base
attr_accessible :name, :batch_id
belongs_to :batch
has_many :students
has_many :batch_counselor_advisors
has_many :batch_leadership_leaders
def student_section
"#{self.name}".to_s
end
end
|
Given(/^the user "([^\"]*)" exists$/) do |user_alias|
user = User.new
@test_world.add_user(user_alias, user)
end
When(/^I search for user "([^"]*)"$/) do |user_alias|
user = @test_world.get_user user_alias
@home.search user.name
end
Then(/^I should be on the search results for user "([^"]*)"$/) do |user_alias|
name = @test_world.get_user(user_alias).name
expect(@results.current_url).to include name.tr(' ', '+')
end |
require 'spec_helper'
describe Reading do
it { should belong_to :user }
it { should belong_to :book }
end |
class Dealvalue < ActiveRecord::Base
attr_accessible :comment, :deal_id, :user_id, :value
validates :comment, :deal_id, :user_id, :value, :presence => true
belongs_to :deal
end
|
require_relative 'globals'
require_relative 'logger_mixin'
module TextlabNLP
class TreeTaggerConfig
include Logging
attr_reader :enc_conv, :type
# @option opts [Symbol] lang ISO-639-2 language code (:fra or :swe).
# @option opts [String] encoding Input encoding (utf-8 or latin1).
def initialize(opts={})
@config = opts[:config] || nil
@type = opts[:type]
if @config
@config = @config.deep_merge(TextlabNLP.config[:treetagger])
else
@config = TextlabNLP.config[:treetagger]
end
# inject these values for testing only
#noinspection RubyResolve
@config = opts[:replace_config] || @config
@encoding = opts[:encoding] || "utf-8"
@lang = opts[:lang] || nil
@model_fn = opts[:model_fn] || nil
unless @model_fn or @config[:languages].has_key?(@lang)
raise ArgumentError
end
# See if treetagger is available in the requested encoding.
# If not we set up an EncodingConverter which will be passed to the shell command runner.
unless @model_fn
if @config[:languages][@lang][:encoding].include?(@encoding.to_s)
@enc_conv = nil
@tool_encoding = @encoding
else
@tool_encoding = prefered_encoding
@enc_conv = EncodingConverter.new(@encoding, @tool_encoding)
end
end
end
# @private
# @return [Symbol]
def prefered_encoding
encodings = @config[:languages][@lang][:encoding]
if encodings.include?("utf-8")
# if possible use UTF-8
"utf-8"
else
# otherwise use the first encoding for this language in the default config
encodings.first
end
end
# @private
def tokenize_cmd
path = @config[:path]
lang_config = @config[:languages][@lang]
tokenize_bin =
case @encoding
when "latin1"
@config[:tokenize_latin1_cmd]
when "utf-8"
@config[:tokenize_utf8_cmd]
else
raise NotImplementedError
end
tokenize_path = File.join(@config[:cmd_dir], tokenize_bin)
tokenize_path = File.join(path, tokenize_path) if path
args = [tokenize_path]
abbrev_path =
case @encoding
when "latin1"
lang_config[:abbreviations_latin1_file] if lang_config
when "utf-8"
lang_config[:abbreviations_utf8_file] if lang_config
else
raise NotImplementedError
end
abbrev_path = File.join(@config[:lib_dir], abbrev_path) if abbrev_path
args << "-a #{File.join(path, abbrev_path)}" if path and abbrev_path
#noinspection RubyCaseWithoutElseBlockInspection
case @lang
when :fra
args << '-f'
when :ita
args << '-i'
when :eng
args << '-e'
end
args.join(' ')
end
# @private
def pipeline_cmd
path = @config[:path]
lang_config = @config[:languages][@lang]
raise NotImplementedError unless lang_config
cmd =
case @tool_encoding
when "utf-8"
lang_config[:pipeline_utf8_cmd]
when "latin1"
lang_config[:pipeline_latin1_cmd]
else
raise NotImplementedError
end
if path
File.join(path, @config[:cmd_dir], cmd) if path
else
cmd
end
end
# @private
def tag_cmd
if @config[:path]
bin = File.join(@config[:path], @config[:bin_dir], @config[:tag_bin])
else
bin = @config[:tag_bin]
end
"#{bin} -token -lemma -sgml #{@model_fn}"
end
# @private
def self.train_cmd(config, encoding)
if config[:path]
cmd = File.join(config[:path], config[:bin_dir], config[:train_bin])
else
cmd = config[:train_bin]
end
if encoding == 'utf-8'
cmd += " -utf8"
end
cmd
end
# @private
def sent_tag
lang_config = @config[:languages][@lang]
if lang_config and lang_config.has_key?(:sent_tag)
lang_config[:sent_tag]
else
'SENT'
end
end
# @private
def encoding
case @encoding
when "utf-8"
Encoding.find("utf-8")
when "latin1"
Encoding.find("ascii-8bit")
else
raise RuntimeError
end
end
# Treetagger configuration for specified language.
# @see #initialize for full list of options.
#
# @param [Object] lang ISO-639-2 language code (:fra or :swe).
# @return [TreeTaggerConfig]
def self.for_lang(lang, opts={})
opts[:lang] = lang
opts[:type] = :lang_pipeline
TreeTaggerConfig.new(opts)
end
def self.lang_available?(lang, opts={})
opts[:lang] = lang
config = TreeTaggerConfig.new(opts)
TextlabNLP.runnable?(config.pipeline_cmd) # and TextlabNLP.runnable?(config.tokenize_cmd)
end
# Train a TreeTagger model from training data files and return a TreeTaggerConfig instance
# for running the model.
#
# @param [Object] train Treetagger formatted training file/IO like.
# @param [Object] open Treetagger open class file/IO like.
# @param [Object] lexicon Treetagger lexicon file/IO like.
# @param [Object] model_fn File to write the TreeTagger model to.
# @option opts [String] encoding Training data/model encoding
# @option opts [Hash] config
# @option opts [Symbol] lang
#
# @return [TreeTaggerConfig]
def self.train(train, open, lexicon, model_fn, opts={})
encoding = opts[:encoding] || 'utf-8'
config = opts[:config] || {}
lang = opts[:lang] || nil
config = config.deep_merge(TextlabNLP.config[:treetagger])
if [train, open, lexicon].detect { |f| TextlabNLP.io_like?(f) }
Dir.mktmpdir('textlabnlp') do |dir|
if TextlabNLP.io_like?(train)
train = TextlabNLP.copy(train, File.join(dir, 'train'))
end
if TextlabNLP.io_like?(open)
open = TextlabNLP.copy(open, File.join(dir, 'open'))
end
if TextlabNLP.io_like?(lexicon)
lexicon = TextlabNLP.copy(lexicon, File.join(dir, 'lexicon'))
end
self.train(train, open, lexicon, model_fn, opts)
end
else
cmd = "#{train_cmd(config, encoding)} #{lexicon} #{open} #{train} #{model_fn}"
Logging.logger.info("Training TreeTagger model with command #{cmd}")
TextlabNLP.run_shell_command(cmd)
TreeTaggerConfig.new(config: config, model_fn: model_fn,
lang: lang, encoding: encoding, type: :param_file)
end
end
end
end
|
require 'thread'
module LRU_RB
class LruCache
attr_reader :max_size, :current_size
def initialize(max_size=100)
@max_size = max_size
@current_size = 0
@cache_h = Hash.new
@cache_lru = LinkedList.new
@mutex = Mutex.new
end
def add(key,val)
@mutex.synchronize do
if @cache_h.has_key? key
@cache_lru.push(@cache_lru.remove([key,val]))
else
@cache_lru.push [key,val]
end
@cache_h[key] = val
ret = nil
if @cache_lru.size > max_size
val = @cache_lru.remove_tail
@cache_h.delete(val[0])
ret = val
end
ret
end
end
def get(key)
@mutex.synchronize do
val = nil
if @cache_h.has_key? key
val = @cache_h[key]
@cache_lru.push(@cache_lru.remove([key,val]))
end
val
end
end
def print
@mutex.synchronize do
@cache_lru.print
end
end
end
end
|
require "linguist"
class Jekyll::Tags::LinguistColors < Liquid::Tag
def initialize tag_name, markup, tokens
@attributes = {
:selector => ".language-{language}",
:property => "background"
}
markup.scan(Liquid::TagAttributes) { |key, value| @attributes[key.to_sym] = value }
super
end
def render context
Linguist::Language.all.select{ |language| language.color }.map do |language|
slug = language.name.gsub(/\s+/, "-").gsub(/([#+])/, "\\\\\\\\\\1").downcase
"#{@attributes[:selector].gsub "{language}", slug} { #{@attributes[:property]}: #{language.color} }"
end * "\n"
end
end
Liquid::Template.register_tag "linguist_colors", Jekyll::Tags::LinguistColors |
require 'rails_helper'
require 'givdo/facebook'
RSpec.describe FriendsSerializer, :type => :serializer do
let(:friend_user) { build(:user, :uid => 'user-1234')}
let(:user) { build(:user, :uid => 'user-1234')}
let(:friends) { Givdo::Facebook::Friends.new(nil, {}) }
before { allow(friends).to receive(:next_page_params).and_return({page: 2}) }
before { allow(friends).to receive(:users).and_return([friend_user]) }
subject { serialize(friends, FriendsSerializer, :scope => user, :include => 'users') }
it { is_expected.to serialize_link(:next).with(api_v1_friends_url({page: 2})) }
it { is_expected.to serialize_id_and_type('user-1234', 'friends') }
it { is_expected.to serialize_included(friend_user).with(FriendUserSerializer) }
end
|
require 'test_helper'
class PhoneBookEntriesControllerTest < ActionController::TestCase
setup do
@user1 = FactoryGirl.create(:user)
pb = @user1.phone_books.first
@user1_phone_book_entry = FactoryGirl.create(
:phone_book_entry,
:phone_book_id => pb.id
)
@expected_status_if_not_authorized = :redirect
end
test "should not get index (not logged in)" do
get :index
assert_response @expected_status_if_not_authorized
end
test "should get index" do
session[:user_id] = @user1.id
get :index
assert_response :success
assert_not_nil assigns(:phone_book_entries)
end
# test "should get new" do
# get :new
# assert_response :success
# end
test "should not have a route for new" do
assert_raises(ActionController::RoutingError) {
get :new
}
end
#
# test "should create phone_book_entry" do
# assert_difference('PhoneBookEntry.count') do
# post :create, phone_book_entry: @user1_phone_book_entry.attributes
# end
#
# assert_redirected_to phone_book_entry_path(assigns(:phone_book_entry))
# end
#
test "should not show phone_book_entry (not logged in)" do
get :show, id: @user1_phone_book_entry.to_param
assert_response @expected_status_if_not_authorized
end
test "should show phone_book_entry without nesting" do
session[:user_id] = @user1.id
get :show, id: @user1_phone_book_entry.to_param
assert_response :success
end
test "should show phone_book_entry nested in phone_book" do
session[:user_id] = @user1.id
get :show, phone_book_id: @user1_phone_book_entry.phone_book.id, id: @user1_phone_book_entry.to_param
assert_response :success
end
#
# test "should get edit" do
# get :edit, id: @user1_phone_book_entry.to_param
# assert_response :success
# end
test "should not have a route for edit" do
assert_raises(ActionController::RoutingError) {
get :edit, id: @user1_phone_book_entry.to_param
}
end
#
# test "should update phone_book_entry" do
# put :update, id: @user1_phone_book_entry.to_param, phone_book_entry: @user1_phone_book_entry.attributes
# assert_redirected_to phone_book_entry_path(assigns(:phone_book_entry))
# end
test "should not have a route for update" do
assert_raises(ActionController::RoutingError) {
put :update, id: @user1_phone_book_entry.to_param, phone_book_entry: @user1_phone_book_entry.attributes
}
end
#
# test "should destroy phone_book_entry" do
# assert_difference('PhoneBookEntry.count', -1) do
# delete :destroy, id: @user1_phone_book_entry.to_param
# end
# assert_redirected_to phone_book_entries_path
# end
test "should not have a route for destroy" do
assert_raises(ActionController::RoutingError) {
delete :destroy, id: @user1_phone_book_entry.to_param
}
end
end
|
require 'aws-sdk'
require 'tempfile'
require 'json'
require 'active_support/core_ext/date/calculations'
module ReportsHelper
REPORT_TABLE = 'test_management_cucumber_report'
def self.bucket(project)
ApplicationHelper.report_params(project)['bucket']
end
def self.get_all_reports(project)
cut_time = (Date.tomorrow - ApplicationHelper.report_params(project)['days_to_keep']).to_time.to_i
criteria = {project: {comparison_operator: 'EQ', attribute_value_list: [project]}}
criteria['update_time'] = {comparison_operator: 'GE', attribute_value_list: [cut_time]}
ApplicationHelper.dynamodb_get_items(REPORT_TABLE, criteria)
end
def self.get_all_file_paths(project)
criteria = {project: {comparison_operator: 'EQ', attribute_value_list: [project]}}
ApplicationHelper.dynamodb_distinct_column(REPORT_TABLE, 'report_file', criteria)
end
def self.get_report_detail(project, report_name)
criteria = {project: {comparison_operator: 'EQ', attribute_value_list: [project]}}
criteria['report_file'] = {comparison_operator: 'EQ', attribute_value_list: [report_name]}
result = ApplicationHelper.dynamodb_get_items(REPORT_TABLE, criteria)
if result.size == 1
result[0]
else
{}
end
end
def self.get_report_content(project, report_name)
dir = "#{File.dirname(__FILE__)}/../../test-reports/#{report_name}"
puts "dir for report folder"+ dir
File.read(dir)
# ApplicationHelper.s3_file_read(bucket(project), report_name)
end
def self.keep_report?(project, date)
return true if date==''
date_obj = Date.strptime(date, '%m-%d-%y')
Date.today - date_obj <= ApplicationHelper.report_params(project)['days_to_keep']
end
def self.update(params)
project = params['project']
date = params['date']
repo = params['trigger_repo'].present? ? params['trigger_repo'] : 'N/A'
commit = params['trigger_commit'].present? ? params['trigger_commit'] : 'N/A'
bkt = bucket(project)
ApplicationHelper.s3_file_list(bkt, date, 'html').each do |file|
slash_parts = file.split('/')
next unless slash_parts.size == 2
at_parts = slash_parts[1].split('@')
next unless at_parts.size == 2
tag = at_parts[1].gsub('.html', '')
next unless tag == params['tag']
level = at_parts[0]
time = ApplicationHelper.s3_file_modify_time(bkt, file).to_i
file_content = ApplicationHelper.s3_file_read(bkt, file)
passed = file_content.split('Passed: ')[1].split('<')[0]
failed = file_content.split('Failed: ')[1].split('<')[0]
record = {
project: project,
date: date,
tag: tag,
trigger_author: params['trigger_author'].strip, #the author value might have ending whitespace
trigger_repo: repo,
trigger_commit: commit,
travis_url: params['travis_url'],
passed: passed,
failed: failed,
update_time: time,
s3_bucket: bkt,
report_file: file,
report_level: level,
latest: 'true'
}
previous = get_latest_report(project, date, tag, level)
unless previous.empty?
previous[0]['latest']='false'
ApplicationHelper.dynamodb_put_item(REPORT_TABLE, previous[0])
end
ApplicationHelper.dynamodb_put_item(REPORT_TABLE, record)
end
end
def self.get_latest_report(project, date, service, level='all')
filter = {project: {comparison_operator: 'EQ', attribute_value_list: [project]}}
filter['date'] = {comparison_operator: 'EQ', attribute_value_list: [date]}
filter['tag'] = {comparison_operator: 'EQ', attribute_value_list: [service]}
filter['latest'] = {comparison_operator: 'EQ', attribute_value_list: ['true']}
filter['report_level'] = {comparison_operator: 'EQ', attribute_value_list: [level]} unless level == 'all'
ApplicationHelper.dynamodb_get_items(REPORT_TABLE, filter)
end
def self.notify_user(project, date, service, report_link)
record = get_latest_report(project, date, service)
return "There is no report for #{project}/#{date}/#{service}!" if record.size < 1
author = record[0]['trigger_author']
unless author.present?
return "Report #{project}/#{date}/#{service} doesn't contain trigger_author information!"
end
message = "\nPlease check: <#{record[0]['travis_url']}|Travis Log>"
place_holder = 'xxLEVELxx'
bdd_report_link = "#{report_link}/reports/#{project}/#{date}/#{service}/#{place_holder}"
bdd_report_link = "<#{bdd_report_link}|Test Report (#{place_holder})>"
record.each do |r|
link = bdd_report_link.gsub(place_holder, r['report_level'])
message += "\n #{r['report_level']} Test: #{r['passed']} Passed | #{r['failed']} Failed. #{link}"
end
message += "\nTrigger Repo: #{record[0]['trigger_repo']} (#{record[0]['trigger_commit']})"
criticals = record.select {|r| r['report_level']!='non-critical'}
failed = criticals[0]['failed'].to_i
#need to consider both critical and rerun, take the less failed value
criticals.each {|c| failed = c['failed'].to_i if c['failed'].to_i < failed}
theme = failed > 0 ? 'danger' : 'good'
time = Time.at(record[0]['update_time']).strftime("%Y-%m-%d %H:%M:%S")
title = failed > 0 ? "#{project} #{service} BDD Test Failed @#{time} :sob:" : "#{project} #{service} BDD Test Passed @#{time} :tada:"
msg = SlackSender.new.send_message(theme, title, message, author)
msg
end
def self.zero_if_nil(val)
val.nil? ? '0' : val
end
def self.getStats(report_type)
retVal = Hash.new()
retVal.default = 0
if report_type
retVal = {
passed: ReportsHelper.zero_if_nil(report_type['passed']),
failed: ReportsHelper.zero_if_nil(report_type['failed'])
}
end
retVal
end
def self.build_travis_details(details)
# Here I am getting all the (critical or non-critical or rerun) hash that has a travis_url
available = details.select {|_run, data| !(data['travis_url'].nil?)}
# Here I am taking travis url in the first hash
url = available[available.keys.first]['travis_url']
{
text: url.split('/').last,
url: url
}
end
end |
require 'poke'
require 'game'
describe "Game" do
# 黑桃 spade, 红桃 heard, 梅花 club, 方块 diamond
it "return 0 if Royal Flush" do
royal_flush = [["spade", "A"], ["spade","K"], ["spade", "Q"], ["spade", "J"], ["spade", "10"]]
royal_flash_cards = convert_to_cards(royal_flush)
expect(game(royal_flash_cards)).to eq 0
end
it "return 1 if Straight Flush" do
straight_flush = [["club", "Q"], ["club","J"], ["club", "10"], ["club", "9"], ["club", "8"]]
straight_flash_cards = convert_to_cards(straight_flush)
expect(game(straight_flash_cards)).to eq 1
end
it "return 2 if Four of a Kind" do
cards_array = [["heard", "A"], ["club","A"], ["diamond", "A"], ["club", "A"], ["spade", "10"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 2
end
it "return 3 if Full House" do
cards_array = [["diamond", "10"], ["spade","10"], ["heard", "10"], ["club", "7"], ["spade", "7"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 3
end
it "return 4 if Flush" do
cards_array = [["heard", "A"], ["heard","Q"], ["heard", "8"], ["heard", "7"], ["heard", "5"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 4
end
it "return 5 if Straight" do
cards_array = [["spade", "J"], ["heard","10"], ["diamond", "9"], ["heard", "8"], ["club", "7"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 5
end
it "return 6 if Three of a Kind" do
cards_array = [["diamond", "7"], ["heard","7"], ["club", "7"], ["diamond", "A"], ["club", "J"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 6
end
it "return 7 if Two Pairs" do
cards_array = [["diamond", "10"], ["spade","10"], ["heard", "A"], ["club", "A"], ["diamond", "J"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 7
end
it "return 8 if One Pair" do
cards_array = [["club", "K"], ["heard","K"], ["heard", "J"], ["heard", "10"], ["diamond", "5"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 8
end
it "return 9 if Single" do
cards_array = [["diamond", "A"], ["heard","Q"], ["spade", "10"], ["spade", "8"], ["heard", "5"]]
cards = convert_to_cards(cards_array)
expect(game(cards)).to eq 9
end
it "return 0 if Royal Flush exists in 7 cards" do
royal_flush = [["spade", "A"], ["spade","K"], ["spade", "Q"], ["spade", "J"], ["spade", "10"], ["diamond", "J"], ["club", "10"]]
royal_flash_cards = convert_to_cards(royal_flush)
expect(game(royal_flash_cards)).to eq 0
end
end
def convert_to_cards(cards_array)
cards_object = []
cards_array.each do |card|
cards_object << Poke.new(card.first, card.last)
end
cards_object
end
|
require 'strava/api/v3'
require 'logger'
module StravaArchiver
class StravaArchiver
@@logger = Logger.new(STDOUT)
@@logger.level = Logger::INFO
def initialize(output_dir: "#{ENV['HOME']}/strava-archive",
existing_data_file: nil,
access_token: nil,
client: Strava::Api::V3::Client.new(:access_token => access_token, :logger => @@logger))
@output_dir = output_dir || "#{ENV['HOME']}/strava-archive"
@client = client
@existing_data_file = existing_data_file
end
def archive(current_athlete = @client.retrieve_current_athlete)
@@logger.info "archiving strava activities for id #{current_athlete['id']} (#{current_athlete['username']}) to directory #{@output_dir}"
totals = @client.totals_and_stats(current_athlete['id'])
path = "#{@output_dir}/#{current_athlete['id']}"
FileUtils.mkdir_p("#{path}/activities") unless File.exists?("#{path}/activities")
if(@existing_data_file && File.exists?(@existing_data_file))
summaries = load_activity_summaries(@existing_data_file)
else
summaries = fetch_activity_summaries(totals)
end
File.open("#{path}/athlete.json", "w") {|f| f.write(current_athlete.to_json)}
File.open("#{path}/totals.json", "w") {|f| f.write(totals.to_json)}
File.open("#{path}/summaries.json", "w") {|f| f.write(summaries.to_json)}
write_activities(summaries, path)
end
private
def load_activity_summaries(existing_data_file)
JSON.parse(File.read(existing_data_file))
end
def fetch_activity_summaries(totals)
total_ride_count = totals['all_ride_totals']['count']
total_run_count = totals['all_run_totals']['count']
total_swim_count = totals['all_swim_totals']['count']
page_count = ((total_ride_count + total_run_count + total_swim_count) / 30) + 2
activities = []
(1..page_count).each {|p|
@@logger.info "getting page #{p} of #{page_count} activity summaries"
@client.list_athlete_activities(page: p, page_size: 30).each {|a|
activities << a
}
}
activities
end
def get_activity(id, filename, manual = false)
@@logger.info "getting activity #{filename}"
activity = @client.retrieve_an_activity(id)
activity['activity_streams'] = @client.retrieve_activity_streams(id, 'time,latlng,distance,altitude,heartrate,cadence,watts,temp') unless manual
File.open(filename, "w") {|f| f.write(activity.to_json)}
end
def write_activities(summaries, path)
summaries.each {|r|
id = r['id']
type = r['type'].downcase
filename = "#{path}/activities/#{type}-#{id}.json"
if !File.exists?(filename)
get_activity(id, filename, r['manual'])
sleep(1)
else
@@logger.info "#{filename} already collected, skipping "
end
}
end
end
end
|
# simplified version of https://github.com/girishso/pluck_to_hash
module PluckH
extend ActiveSupport::Concern
module ClassMethods
def pluck_h(*keys)
pluck(*keys).map do |values|
if keys.one?
{keys.first => values}
else
Hash[keys.zip(values)]
end
end
end
end
end
ActiveRecord::Base.send(:include, PluckH)
|
module I18n
module Counter
class Summary
DEFAULT_LOCALE = 'en'
attr :redis, :used, :unused
def initialize
@redis = I18nRedis.connection
@_redis_keys = {}
@used = []
@unused = []
@_count_by_locale = {}
@_sum_by_locale = {}
end
module RedisCounts
def accessed_keys locale
@_redis_keys[locale] ||= redis.keys("#{locale}.*")
end
def accessed_keys_global
I18n.available_locales.each do |locale|
accessed_keys(locale).each do |k|
key = strip_locale_from_key locale, k
accessed_keys('global') << "global.#{key}" unless accessed_key?('global', key)
end
end
accessed_keys('global')
end
def accessed_key? locale, key
k = add_locale_to_key(locale, key)
accessed_keys(locale).include?(k)
end
def count_by_locale locale
@_count_by_locale[locale] ||= accessed_keys(locale).size
end
def list_counts_by_locale
I18n.available_locales.each.reduce({}) do |result, locale|
result[locale] = count_by_locale(locale)
result
end
end
def count_all
accessed_keys_global.size
end
def sum_all
I18n.available_locales.each.reduce(0) { |sum, locale| sum += sum_by_locale(locale) }
end
def sum_by_locale locale
@_sum_by_locale[locale] ||= accessed_keys(locale).reduce(0) {|sum, key| sum += redis.get(key).to_i }
end
end
include RedisCounts
module NativeKeys
def translation_used?(k)
I18n.available_locales.detect do |locale|
accessed_key?(locale, "#{locale}.#{k}")
end
end
DEFAULT_LOCALE
def native_keys locale = DEFAULT_LOCALE
local_locale(locale).select_keys do |k,v|
yield k
end
end
def list_native_keys locale = DEFAULT_LOCALE
keys = []
native_keys(locale) { |k| keys << k}
keys
end
def local_locale locale
load_locales.data[locale]
end
def load_locales
@_locales ||= I18n::Tasks::BaseTask.new
end
end
include NativeKeys
def call locale = DEFAULT_LOCALE
native_keys(locale) do |k|
key = strip_locale_from_key locale, k
if translation_used?(key)
@used << key
else
@unused << key
end
end
self
end
private
def strip_locale_from_key locale, key
key.sub("#{locale}.", '')
end
def add_locale_to_key locale, key
key =~ /^#{locale}\.*/ ? key : "#{locale}.#{key}"
end
end
end
end
|
class LikeType < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '優柔不断' },
{ id: 3, name: 'プライドが高い' },
{ id: 4, name: '協調性がない' },
{ id: 5, name: '飽きっぽい' },
{ id: 6, name: '傷つきやすい' },
{ id: 7, name: 'やや非常識' },
{ id: 8, name: '向上心がない' },
{ id: 9, name: '精神的に自立していない' },
{ id: 10, name: '共感能力が低い' }
]
include ActiveHash::Associations
has_many :questions
end |
# frozen-string-literal: true
#
# The pg_extended_date_support extension allows support
# for BC dates/timestamps by default, and infinite
# dates/timestamps if configured. Without this extension,
# BC and infinite dates/timestamps will be handled incorrectly
# or raise an error. This behavior isn't the default because
# it can hurt performance, and few users need support for BC
# and infinite dates/timestamps.
#
# To load the extension into the database:
#
# DB.extension :pg_extended_date_support
#
# To enable support for infinite dates/timestamps:
#
# DB.convert_infinite_timestamps = 'string' # or 'nil' or 'float'
#
# Related module: Sequel::Postgres::ExtendedDateSupport
#
module Sequel
module Postgres
module ExtendedDateSupport
DATETIME_YEAR_1 = DateTime.new(1)
TIME_YEAR_1 = Time.at(-62135596800).utc
INFINITE_TIMESTAMP_STRINGS = ['infinity'.freeze, '-infinity'.freeze].freeze
INFINITE_DATETIME_VALUES = ([PLUS_INFINITY, MINUS_INFINITY] + INFINITE_TIMESTAMP_STRINGS).freeze
PLUS_DATE_INFINITY = Date::Infinity.new
MINUS_DATE_INFINITY = -PLUS_DATE_INFINITY
RATIONAL_60 = Rational(60)
TIME_CAN_PARSE_BC = RUBY_VERSION >= '2.5'
# Add dataset methods and update the conversion proces for dates and timestamps.
def self.extended(db)
db.extend_datasets(DatasetMethods)
procs = db.conversion_procs
procs[1082] = ::Sequel.method(:string_to_date)
procs[1184] = procs[1114] = db.method(:to_application_timestamp)
if ocps = db.instance_variable_get(:@oid_convertor_map)
# Clear the oid convertor map entries for timestamps if they
# exist, so it will regenerate new ones that use this extension.
# This is only taken when using the jdbc adapter.
Sequel.synchronize do
ocps.delete(1184)
ocps.delete(1114)
end
end
end
# Handle BC dates and times in bound variables. This is necessary for Date values
# when using both the postgres and jdbc adapters, but also necessary for Time values
# on jdbc.
def bound_variable_arg(arg, conn)
case arg
when Date, Time
literal(arg)
else
super
end
end
# Whether infinite timestamps/dates should be converted on retrieval. By default, no
# conversion is done, so an error is raised if you attempt to retrieve an infinite
# timestamp/date. You can set this to :nil to convert to nil, :string to leave
# as a string, or :float to convert to an infinite float.
attr_reader :convert_infinite_timestamps
# Set whether to allow infinite timestamps/dates. Make sure the
# conversion proc for date reflects that setting.
def convert_infinite_timestamps=(v)
@convert_infinite_timestamps = case v
when Symbol
v
when 'nil'
:nil
when 'string'
:string
when 'date'
:date
when 'float'
:float
when String, true
typecast_value_boolean(v)
else
false
end
pr = old_pr = Sequel.method(:string_to_date)
if @convert_infinite_timestamps
pr = lambda do |val|
case val
when *INFINITE_TIMESTAMP_STRINGS
infinite_timestamp_value(val)
else
old_pr.call(val)
end
end
end
add_conversion_proc(1082, pr)
end
# Handle BC dates in timestamps by moving the BC from after the time to
# after the date, to appease ruby's date parser.
# If convert_infinite_timestamps is true and the value is infinite, return an appropriate
# value based on the convert_infinite_timestamps setting.
def to_application_timestamp(value)
if value.is_a?(String) && (m = /((?:[-+]\d\d:\d\d)(:\d\d)?)?( BC)?\z/.match(value)) && (m[2] || m[3])
if m[3]
value = value.sub(' BC', '').sub(' ', ' BC ')
end
if m[2]
dt = if Sequel.datetime_class == DateTime
DateTime.parse(value)
elsif TIME_CAN_PARSE_BC
Time.parse(value)
# :nocov:
else
DateTime.parse(value).to_time
# :nocov:
end
Sequel.convert_output_timestamp(dt, Sequel.application_timezone)
else
super(value)
end
elsif convert_infinite_timestamps
case value
when *INFINITE_TIMESTAMP_STRINGS
infinite_timestamp_value(value)
else
super
end
else
super
end
end
private
# Return an appropriate value for the given infinite timestamp string.
def infinite_timestamp_value(value)
case convert_infinite_timestamps
when :nil
nil
when :string
value
when :date
value == 'infinity' ? PLUS_DATE_INFINITY : MINUS_DATE_INFINITY
else
value == 'infinity' ? PLUS_INFINITY : MINUS_INFINITY
end
end
# If the value is an infinite value (either an infinite float or a string returned by
# by PostgreSQL for an infinite date), return it without converting it if
# convert_infinite_timestamps is set.
def typecast_value_date(value)
if convert_infinite_timestamps
case value
when *INFINITE_DATETIME_VALUES
value
else
super
end
else
super
end
end
# If the value is an infinite value (either an infinite float or a string returned by
# by PostgreSQL for an infinite timestamp), return it without converting it if
# convert_infinite_timestamps is set.
def typecast_value_datetime(value)
if convert_infinite_timestamps
case value
when *INFINITE_DATETIME_VALUES
value
else
super
end
else
super
end
end
module DatasetMethods
private
# Handle BC Date objects.
def literal_date(date)
if date.year < 1
date <<= ((date.year) * 24 - 12)
date.strftime("'%Y-%m-%d BC'")
else
super
end
end
# Handle BC DateTime objects.
def literal_datetime(date)
if date < DATETIME_YEAR_1
date <<= ((date.year) * 24 - 12)
date = db.from_application_timestamp(date)
minutes = (date.offset * 1440).to_i
date.strftime("'%Y-%m-%d %H:%M:%S.%N#{format_timestamp_offset(*minutes.divmod(60))} BC'")
else
super
end
end
# Handle Date::Infinity values
def literal_other_append(sql, v)
if v.is_a?(Date::Infinity)
sql << (v > 0 ? "'infinity'" : "'-infinity'")
else
super
end
end
if RUBY_ENGINE == 'jruby'
# :nocov:
ExtendedDateSupport::CONVERT_TYPES = [Java::JavaSQL::Types::DATE, Java::JavaSQL::Types::TIMESTAMP]
# Use non-JDBC parsing as JDBC parsing doesn't work for BC dates/timestamps.
def type_convertor(map, meta, type, i)
case type
when *CONVERT_TYPES
db.oid_convertor_proc(meta.getField(i).getOID)
else
super
end
end
# Work around JRuby bug #4822 in Time#to_datetime for times before date of calendar reform
def literal_time(time)
if time < TIME_YEAR_1
literal_datetime(DateTime.parse(super))
else
super
end
end
# :nocov:
else
# Handle BC Time objects.
def literal_time(time)
if time < TIME_YEAR_1
time = db.from_application_timestamp(time)
time.strftime("'#{sprintf('%04i', time.year.abs+1)}-%m-%d %H:%M:%S.%N#{format_timestamp_offset(*(time.utc_offset/RATIONAL_60).divmod(60))} BC'")
else
super
end
end
end
end
end
end
Database.register_extension(:pg_extended_date_support, Postgres::ExtendedDateSupport)
end
|
require 'colorize'
module PageInmetrics
module Funcionario
class Funcionario < SitePrism::Page
set_url '/'
element :div_form, '[class*="validate-form"]'
element :div_table, '[id="tabela_wrapper"]'
element :btn_enviar, '[class*="cadastrar"]'
element :btn_novo_funcionario, 'li:nth-child(2)'
element :input_cpf, '#cpf'
element :input_nome, '#inputNome'
element :input_cargo, '#inputCargo'
element :input_search, '[type="search"]'
element :input_salario, '#dinheiro'
element :input_admissao, '#inputAdmissao'
elements :select_sexo, '[id="slctSexo"] option'
elements :select_contrato, '[type="radio"]'
elements :btn_exclusao, '#delete-btn'
elements :btn_edicao, '[class*="warning"]'
elements :tbody_registros, 'tbody [role="row"]'
def cadastrar_funcionario
insert = Factory.funcionario
btn_novo_funcionario.click
wait_until_div_form_visible
input_nome.set insert[:nome]
input_cargo.set insert[:cargo]
input_cpf.send_keys insert[:cpf]
input_salario.set insert[:salario]
select_sexo[2].click
select_contrato[rand(select_contrato.length)].click
input_admissao.set insert[:admissao]
btn_enviar.click
puts "\n Funcionário(a) #{insert[:nome]} cadastrado(a)".green if has_no_btn_enviar?
end
def editar_funcionario
edit = Factory.funcionario
if has_tbody_registros?
nome = edit[:nome]
btn_edicao.find { |editar| editar.click }
wait_until_div_form_visible
input_nome.set ''
input_nome.set edit[:nome]
input_cargo.set ''
input_cargo.set edit[:cargo]
input_salario.set ''
input_salario.set edit[:salario]
input_admissao.set ''
input_admissao.set edit[:admissao]
btn_enviar.click
puts "\n Funcionário(a) #{nome} editado(a)".green if has_div_table?
else
raise Exception.new "PÁGINA DE EDIÇÃO NÃO CARREGADA"
end
end
def excluir_funcionario
btn_exclusao.find { |excluir| excluir.click } if has_tbody_registros?
end
end
end
end
|
ENV['RACK_ENV'] = 'test'
require "test/unit"
require "domotics/core"
class DomoticsElementsTestCase < Test::Unit::TestCase
def test_dimmer
dimmer = Domotics::Core::Room[:test].dimmer
# Should turn on max and convert state to int
dimmer.set_state :on
assert_equal 255, dimmer.state
# Should turn off and convert state to int
dimmer.set_state :off
assert_equal 0, dimmer.state
# Dim
[0,3,24,127,237,255].each do |val|
dimmer.set_state val
assert_equal val, dimmer.state
end
# Off
dimmer.off
assert_equal 0, dimmer.state
# Fade to
dimmer.fade_to 255
sleep 1.6
assert_equal 255, dimmer.state
dimmer.fade_to 127
sleep 0.8
assert_equal 127, dimmer.state
dimmer.fade_to 0
sleep 0.8
assert_equal 0, dimmer.state
end
def test_rgb_strip
rgb = Domotics::Core::Room[:test].rgb
rgb.on
sleep 1.6
assert_equal 255, rgb.red.state
rgb.off
assert_equal 0, rgb.red.state
assert_equal :dimmer, rgb.red.type
assert_equal :dimmer, rgb.green.type
assert_equal :dimmer, rgb.blue.type
end
def test_button
room = Domotics::Core::Room[:test]
btn = room.button
$emul.set_internal_state 6, 1
$emul.toggle_pin 6
sleep 0.1
$emul.toggle_pin 6
sleep 0.05
assert_equal room.last_event(btn.name), :state_changed => :tap
$emul.toggle_pin 6
sleep 0.6
$emul.toggle_pin 6
sleep 0.01
assert_equal room.last_event(btn.name), :state_changed => :long_tap
end
def test_camera_motion_sensor
room = Domotics::Core::Room[:test]
cam_mt = room.cam_motion
saved_mode = cam_el.device.mode
%x{echo "[test foto content]" > /tmp/test_foto.jpg}
sleep 0.5
assert_equal room.last_event(cam_mt.name), :state_changed => :motion_detection
assert_equal cam_el.device.mode, saved_mode
end
end |
class AddIncomingIpToCspReportCspReports < ActiveRecord::Migration
def change
add_column :csp_report_csp_reports, :incoming_ip, :string, null: true
CspReport::CspReport.all.each do |report|
report.incoming_ip = 'Unknown (captured prior to v0.2.0)'
report.save!
end
# Removes the default value
change_column :csp_report_csp_reports, :incoming_ip, :string, null: false
end
end
|
# frozen_string_literal: true
module PopulatePokemon
# Service to populate all pokemon
class Service
attr_reader :starting_number, :ending_number, :region
def initialize(starting_number, ending_number, region)
@starting_number = starting_number
@ending_number = ending_number
@region = region
end
def populate
delete_all_mons
(starting_number..ending_number)
.each { |number| populate_pokemon(number) }
end
private
def populate_pokemon(pokedex_number)
puts "Trying to populate pokemon number: #{pokedex_number}"
PopulatePokemon::Populate.new(pokedex_number, region).populate
puts "--------------------------------------------------------------------------"
rescue StandardError => e
Rails.logger.error "Service Error: #{e}"
end
def delete_all_mons
puts "Deleting all pokemon from #{region}."
Pokemon.where(pokedex_number: starting_number..ending_number).destroy_all
end
end
end
|
require "boxing/kata/version"
require "boxing/kata/box_scheduler"
require "boxing/kata/family"
require 'csv'
module Boxing
module Kata
def self.report
unless has_input_file?
puts "Usage: ruby ./bin/boxing-kata <spec/fixtures/family_preferences.csv"
end
cmd_line = STDIN.gets
cmd_line = "spec/fixtures/family_preferences.csv"
scheduler = BoxScheduler.new
starWarsFamily = Family.new
print starWarsFamily.load_family_preferences(cmd_line)
print scheduler.ship_starter_box(starWarsFamily)
print scheduler.ship_refill_boxes(starWarsFamily)
end
def self.has_input_file?
!STDIN.tty?
end
end
end
|
class CreateUserWorkspaceRequests < ActiveRecord::Migration[6.0]
def change
create_table :user_workspace_requests do |t|
t.integer :user
t.integer :workspace
t.integer :status
t.timestamps
end
end
end
|
require 'pry'
class MusicLibraryController
attr_accessor :path
def initialize(path = "./db/mp3s")
@path = MusicImporter.new(path).import
end
def call
puts "Welcome to your music library!"
puts "To list all of your songs, enter 'list songs'."
puts "To list all of the artists in your library, enter 'list artists'."
puts "To list all of the genres in your library, enter 'list genres'."
puts "To list all of the songs by a particular artist, enter 'list artist'."
puts "To list all of the songs of a particular genre, enter 'list genre'."
puts "To play a song, enter 'play song'."
puts "To quit, type 'exit'."
puts "What would you like to do?"
i = 0
loop do
input = gets.strip
i += 1
if i == 4 || input == "exit"
break
elsif input == "list songs"
list_songs
elsif input == "list artists"
list_artists
elsif input == "list genres"
list_genres
elsif input == "list artist"
list_songs_by_artist
elsif input == "list genre"
list_songs_by_genre
elsif input == "play song"
play_song
end
end
end
def list_songs
list = Song.all.sort_by! do |songA|
songA.name
end
list.each.with_index(1) do |song, i|
puts "#{i}. #{song.artist.name} - #{song.name} - #{song.genre.name}"
end
# binding.pry
end
def list_artists
list = Artist.all.sort_by! do |artist|
artist.name
end
list.each.with_index(1) do |artist, i|
puts "#{i}. #{artist.name}"
end
end
def list_genres
list = Genre.all.sort_by! do |genre|
genre.name
end
list.each.with_index(1) do |genre, i|
puts "#{i}. #{genre.name}"
end
end
def list_songs_by_artist
puts "Please enter the name of an artist:"
input = gets.chomp
song_list = []
Song.all.each do |song|
if song.artist.name == input
song_list << song
end
end
song_list = song_list.sort_by{|song| song.name}
song_list.each {|song| puts "#{song_list.index(song) + 1}. #{song.name} - #{song.genre.name}" }
end
def list_songs_by_genre
puts "Please enter the name of a genre:"
input = gets.chomp
songs_genre = []
Song.all.each do |song|
if song.genre.name == input
songs_genre << song
end
end
songs_genre = songs_genre.sort_by{|song| song.genre}
songs_genre.each {|song| puts "#{songs_genre.index(song) + 1}. #{song.artist.name} - #{song.name}" }
end
def play_song
puts "Which song number would you like to play?"
input = gets.chomp.to_i
if Song.all.length + 1 >= input && input > 0
song = Song.all.sort_by! { |songA| songA.name}[input - 1]
puts "Playing #{song.name} by #{song.artist.name}" if song
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
layout :layout_by_resource
before_action :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
protected
def layout_by_resource
if devise_controller? && resource_name == :user && action_name == "new"
"login"
end
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :city_id, :email, :password, :password_confirmation, :user_id, :suscribed, :remember_me])
devise_parameter_sanitizer.permit(:sign_in, keys: [:login, :email, :password, :remember_me])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :city_id, :email, :password, :password_confirmation, :suscribed]) if devise_controller? && resource_name == :user && action_name == "edit"
end
end
|
class AddDumpVariablesParameter < ActiveRecord::Migration
def up
GsParameter.create(:entity => 'dialplan', :section => 'parameters', :name => 'dump_variables', :value => 'false', :class_type => 'Boolean', :description => 'Log dialplan variables.')
end
def down
GsParameter.where(:entity => 'dialplan', :section => 'parameters', :name => 'dump_variables').destroy_all
end
end
|
# frozen_string_literal: true
module AsciiDetector
VERSION = '0.1.0'
end
|
class Api::V1::ReviewsController < ApplicationController
before_action :authenticate_user!
before_action :authorize_destruction, :only => [:destroy]
skip_before_action :verify_authenticity_token, :only => [:create, :destroy]
def index
render json: Review.all
end
def create
@review = Review.new
@restaurant = Restaurant.find(params[:restaurant_id])
@review.restaurant = @restaurant
@review.title = params[:review][:title]
@review.body = params[:review][:body]
@review.rating = params[:review][:rating]
@review.user = current_user
if @review.save
render status: 201, json: @review
else
render status: 422, json: {
message: "ERROR: UNPROCESSABLE ENTITY",
errorList: @review.errors.full_messages
}.to_json
end
end
def destroy
@review = Review.find(params[:id])
if @review.destroy
@reviews = @review.restaurant.reviews
render json: {reviews: @reviews}
else
@reviews = review.restaurant.reviews
render json: {reviews: @reviews}
end
end
protected
def authorize_destruction
if !current_user || !current_user.admin?
render status: 401
return false
end
end
end
|
#!/usr/bin/env ruby
require 'sippy_cup'
require 'getoptlong'
def usage
puts "#{$0} [OPTS] </path/to/sippy_cup_definition.yml>"
puts
puts "--compile, -c Compile the given scenario manifest to XML and PCAP"
puts "--run, -r Run the scenario"
puts "--help, -h Print this usage information"
puts "--version, -V Print SippyCup version"
end
opts = GetoptLong.new(
['--compile', '-c', GetoptLong::NO_ARGUMENT],
['--run', '-r', GetoptLong::NO_ARGUMENT],
['--help', '-h', GetoptLong::NO_ARGUMENT],
['--version', '-V', GetoptLong::NO_ARGUMENT]
)
compile = false
run = false
opts.each do |opt, arg|
case opt
when '--compile'
compile = true
when '--run'
run = true
when '--help'
usage
exit 0
when '--version'
require 'sippy_cup/version'
puts "SippyCup version #{SippyCup::VERSION}"
exit 0
end
end
unless ARGV.count == 1
puts "ERROR: Must supply the SippyCup manifest file"
puts
usage
exit 1
end
manifest_path = ARGV.shift
unless File.readable? manifest_path
puts "ERROR: Unable to read manifest file"
puts
usage
exit 1
end
unless compile || run
puts "No action (compile or run) specified. Exiting."
usage
exit 1
end
scenario = SippyCup::Scenario.from_manifest File.read(manifest_path), input_filename: manifest_path
if scenario.valid?
scenario.compile! if compile
else
$stderr.puts "Errors encountered while building the scenario!"
puts "Step\tError Message"
scenario.errors.each do |error|
puts "#{error[:step]}\t#{error[:message]}"
end
end
if run
runner = SippyCup::Runner.new scenario
runner.run
end
|
#write your code here
def echo(input)
return input
end
def shout(input)
return input.upcase
end
def repeat(input, q=2)
return ([input]*q).join(' ')
end
def start_of_word(input, q)
return input[0..q-1]
end
def first_word(input)
return input.split.first
end
def titleize(input)
little_words = %w{and the or over on}
return input.split.map.with_index {|word, i| ((little_words.include? word)&&i>0) ? word : word.capitalize}.join(' ')
end
|
class ThingsController < ApplicationController
def index
@things = Thing.rank(:row_order).all
end
def new
@thing = Thing.new
end
def show
@thing = Thing.find(params[:id])
end
def create
@thing = Thing.create(thing_params)
if @thing.save
redirect_to things_path
else
render :new
end
end
def update_row_order
@thing = Thing.find(thing_params[:thing_id])
@thing.row_order_position = thing_params[:row_order_position]
@thing.save
render nothing: true
end
private
def set_thing
@thing = Thing.find(params[:id])
end
def thing_params
params.require(:thing).permit(:thing_id, :title, :description, :row_order_position)
end
end
|
module Squall
# OnApp IpAddress
class IpAddress < Base
# Returns a list of ip addresses for a network
#
# ==== Params
#
# * +network_id+ - ID of the network
def list(network_id)
response = request(:get, "/settings/networks/#{network_id}/ip_addresses.json")
response.collect { |ip| ip['ip_address'] }
end
# Updates an existing ip address
#
# ==== Params
#
# * +network_id+ - ID of the network
# * +id+ - ID of the ip address
# * +options+ - Params for updating the ip address
#
# ==== Options
#
# See #create
def edit(network_id, id, options = {})
response = request(:put, "/settings/networks/#{network_id}/ip_addresses/#{id}.json", default_params(options))
end
# Creates a new IpAddress
#
# ==== Params
#
# * +network_id+ - ID of the network
# * +options+ - Params for the new ip address
#
# ==== Options
#
# * +address*+ - IP address
# * +netmask*+ - Network mask
# * +broadcast*+ - A logical address at which all devices connected to a multiple-access communications network are enabled to receive datagrams
# * +network_address*+ - IP address of network
# * +gateway*+ - Gateway address
# * +disallowed_primary+ - Set to '1' to prevent this address being used as primary
def create(network_id, options = {})
response = request(:post, "/settings/networks/#{network_id}/ip_addresses.json", default_params(options))
end
# Deletes an existing ip address
#
# ==== Params
#
# * +network_id+ - ID of the network
# * +id+ - ID of the ip address
def delete(network_id, id)
request(:delete, "/settings/networks/#{network_id}/ip_addresses/#{id}.json")
end
end
end
|
class AddPostDateToWeeklyApps < ActiveRecord::Migration[5.2]
def change
add_column :weekly_apps, :post_date, :date
end
end
|
log "
*****************************************
* *
* Recipe:#{recipe_name} *
* *
*****************************************
"
thisdir = node[:clone12_2][:ebsprep][:workingdir]
rootusr = 'root'
rootgrp = node[:root_group]
#######################################################################
# Doc Id: 1330703.1
#
# Attention: By default, the OPMN service of the Application
# Server technology stack listens on port 6000 when started up
# during Rapid Install. This can conflict with the X11 port
# used for the graphics console on AIX servers or other processes
# and prevent Rapid Install from completing.
#
# Note: we decided not to automate this at this time. We havent
# found it on a newly installed system, and therefore dont
# believe we will ever see this. So Instead, we check and fail
# if it ever gets triggered
#
fname="chk_opmn_port"
execute "check_if_port_6000_in_use" do
user rootusr
group rootgrp
command "netstat -an | grep 6000 | fgrep LISTEN"
returns 1
end
|
require 'spec_helper'
require 'rails_helper'
include Warden::Test::Helpers
Warden.test_mode!
describe 'New address' do
before :each do
user = FactoryGirl.create(:user)
login_as(user)
end
it 'creates new address' do
visit new_address_path
fill_in('address_name', with:'Tom Jones')
fill_in('address_phone', with:'0501234567')
click_button('Save address')
expect(page).to have_content 'Address was successfully created.'
end
it 'doesn´t add address if title empty' do
visit new_address_path
fill_in('address_name', with:'')
fill_in('address_phone', with:'0501234567')
click_button('Save address')
expect(page).to have_content 'Name can\'t be blank'
end
end |
require 'test_helper'
class TempusersControllerTest < ActionController::TestCase
setup do
@tempuser = tempusers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:tempusers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create tempuser" do
assert_difference('Tempuser.count') do
post :create, tempuser: { pku_id: @tempuser.pku_id }
end
assert_redirected_to tempuser_path(assigns(:tempuser))
end
test "should show tempuser" do
get :show, id: @tempuser
assert_response :success
end
test "should get edit" do
get :edit, id: @tempuser
assert_response :success
end
test "should update tempuser" do
patch :update, id: @tempuser, tempuser: { pku_id: @tempuser.pku_id }
assert_redirected_to tempuser_path(assigns(:tempuser))
end
test "should destroy tempuser" do
assert_difference('Tempuser.count', -1) do
delete :destroy, id: @tempuser
end
assert_redirected_to tempusers_path
end
end
|
require "test_helper"
describe DashboardController do
Given(:user) { FactoryGirl.create(:user) }
describe "#show for" do
describe "authenticated user" do
Given { sign_in user }
Given { get dashboard_show_url }
Then { value(response).must_be :success? }
end
describe "logged out user" do
Given { get dashboard_show_url }
Then { assert_redirected_to new_user_session_path }
end
end
end
|
require 'rails_helper'
describe Transaction do
context 'attributes' do
it { is_expected.to respond_to(:invoice_id) }
it { is_expected.to respond_to(:credit_card_number) }
it { is_expected.to respond_to(:credit_card_expiration_date) }
it { is_expected.to respond_to(:result) }
it { is_expected.to respond_to(:created_at) }
it { is_expected.to respond_to(:updated_at) }
end
context 'relationships' do
it { is_expected.to belong_to(:invoice) }
end
end
|
JSONAPI.configure do |config|
config.json_key_format = :camelized_key
config.route_format = :dasherized_route
config.default_paginator = :none
config.default_page_size = 10
config.maximum_page_size = 100
config.top_level_meta_include_record_count = true
config.top_level_meta_record_count_key = :record_count
end
|
class DocumentosController < ApplicationController
before_action :set_documento, only: [:show, :edit, :update, :destroy]
# GET /documentos
# GET /documentos.json
def index
@documentos = Documento.all
end
# GET /documentos/1
# GET /documentos/1.json
def show
respond_to do |format|
format.html
format.pdf do
render pdf: "file_name", # Excluding ".pdf" extension.
layout: 'layouts/application.pdf.haml', # layout used
show_as_html: params[:debug].present?
end
end
end
# GET /documentos/new
def new
@documento = Documento.new
end
# GET /documentos/1/edit
def edit
end
# POST /documentos
# POST /documentos.json
def create
@documento = Documento.new(documento_params)
@documento.fecha_ingreso = Date.current.to_s
@estudiante = Estudiante.find(@documento.estudiante_id)
@documentos = Documento.all
contador = 1
@documentos.each do |doc|
if doc.estudiante_id == @documento.estudiante_id && doc.tipo_documento == "Boletin"
contador = contador + 1
else
if doc.estudiante_id == @documento.estudiante_id && doc.tipo_documento == "Documento de identidad"
contador = contador + 1
else
if doc.estudiante_id == @documento.estudiante_id && doc.tipo_documento == "Constancia EPS"
contador = contador + 1
else
if doc.estudiante_id == @documento.estudiante_id && doc.tipo_documento == "Foto tamaño 3x4"
contador = contador + 1
end
end
end
end
end
@fecha = Horario.random
fecha_hora = "#{@fecha.fecha} #{@fecha.hora_inicio} - #{@fecha.hora_fin}"
if contador==4
@estudiante.update_attributes({
:estado => "Pendiente por examen",
:f_examen => fecha_hora
});
end
respond_to do |format|
if @documento.save
format.html { redirect_to "http://localhost:3000/estudiantes", notice: 'Documento creado exitosamente' }
format.json { render :show, status: :created, location: @documento }
else
format.html { render :new }
format.json { render json: @documento.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /documentos/1
# PATCH/PUT /documentos/1.json
def update
respond_to do |format|
if @documento.update(documento_params)
format.html { redirect_to "http://localhost:3000/estudiantes", notice: 'Documento actualizado exitosamente' }
format.json { render :show, status: :ok, location: @documento }
else
format.html { render :edit }
format.json { render json: @documento.errors, status: :unprocessable_entity }
end
end
end
# DELETE /documentos/1
# DELETE /documentos/1.json
def destroy
@documento.destroy
respond_to do |format|
format.html { redirect_to "http://localhost:3000/estudiantes", notice: 'Documento eliminado exitosamente' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_documento
@documento = Documento.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def documento_params
params.require(:documento).permit(:tipo_documento, :fecha_ingreso, :observacion, :estudiante_id, :adjunto)
end
end
|
class Admin::CheckoutsController < Admin::BaseController
resource_controller :singleton
belongs_to :order
before_filter :load_data
ssl_required
edit.before :edit_before
update.before :update_before
update.wants.html do
if @order.in_progress?
redirect_to edit_admin_order_shipment_url(@order, @order.shipment)
else
redirect_to admin_order_checkout_url(@order)
end
end
private
def load_data
@countries = Country.find(:all).sort
if params[:checkout] && params[:checkout][:bill_address_attributes]
default_country = Country.find params[:checkout][:bill_address_attributes][:country_id]
elsif params[:checkout] && params[:checkout][:ship_address_attributes]
default_country = Country.find params[:checkout][:ship_address_attributes][:country_id]
elsif object.bill_address && object.bill_address.country
default_country = object.bill_address.country
elsif current_user && current_user.bill_address
default_country = current_user.bill_address.country
else
default_country = Country.find Spree::Config[:default_country_id]
end
@states = default_country.states.sort
end
def edit_before
@checkout.build_bill_address(:country_id => Spree::Config[:default_country_id]) if @checkout.bill_address.nil?
@checkout.build_ship_address(:country_id => Spree::Config[:default_country_id]) if @checkout.ship_address.nil?
end
def update_before
@checkout.enable_validation_group(:address)
end
end
|
Spree::BaseController.class_eval do
before_filter :set_pages
private
def set_pages
@header_pages = Spree::Page.header_links.top_level.visible
@footer_pages = Spree::Page.footer_links.top_level.visible
end
end
|
Rails.application.routes.draw do
root to: 'pages#home'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :projects, only: [:index, :show]
get '/contact', to: 'contacts#new', as: 'new_message'
post 'contacs', to: 'contacs#create', as: 'create_message'
end
|
class Backend::AdminsController < Backend::ApplicationController
def update
if current_admin.update admin_params
response_json current_admin
else
raise LogicError, '更新失败'
end
end
private
def admin_params
params.require(:admin).permit(:name, :avatar, :password, :password_confirmation)
end
end
|
require "test_helper"
describe OrgsUser do
subject { OrgsUser }
describe "db" do
specify "columns & types" do
must_have_column(:org_id, :integer)
must_have_column(:user_id, :integer)
end
end
specify "associations" do
must_belong_to(:org)
must_belong_to(:user)
end
end
|
module IControl::ASM
##
# The WebApplicationGroup interface enables you to manipulate a group of ASM Web Applications.
class WebApplicationGroup < IControl::Base
set_id_name "group_names"
##
# Adds web applications to this web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :webapp_names The names of the web applications to add to the specified groups.
def add_webapp(opts)
opts = check_params(opts,[:webapp_names])
super(opts)
end
##
# Creates a new web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def create
super
end
##
# Deletes all web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_all_groups
super
end
##
# Deletes this web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def delete_group
super
end
##
# Gets a list of all web application group.
# @rspec_example
# @return [WebApplicationGroupDefinition]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def list
super
end
##
# Gets the version information for this interface.
# @rspec_example
# @return [String]
def version
super
end
##
# Returns a list of the web applications associated with this web application group.
# @rspec_example
# @return [String[]]
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def webapp_list
super
end
##
# Removes all web applications from this web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
def remove_all_webapps
super
end
##
# Removes web applications from this web application group.
# @rspec_example
# @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid.
# @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid.
# @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs.
# @param [Hash] opts
# @option opts [String[]] :webapp_names The names of the web applications to remove from the specified groups.
def remove_webapp(opts)
opts = check_params(opts,[:webapp_names])
super(opts)
end
end
end
|
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network :private_network, ip: "192.168.19.20"
config.vm.network "forwarded_port", guest: 80, host: 8990
config.ssh.forward_agent = true
config.vm.synced_folder "~/Workspace/go-project", "/home/vagrant/go/project"
config.vm.provision "ansible" do |ansible|
ansible.playbook = "provisioning/playbook.yml"
ansible.verbose = "vvv"
end
end
|
class TaskSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :external_id, :accepted, :paid, :review_requested, :links, :budget, :resolver, :expenses, :orders, :potential_resolvers
private
def budget
object.budget.to_f
end
def potential_resolvers # TODO - make request more smart for roles
data = []
if object.orders.present?
object.orders.first.team.users.all_active.each do |user|
data << {id: user.id, login: user.login, name: user.name}
end
else
User.all_active.each do |user|
data << {id: user.id, login: user.login, name: user.name}
end
end
data
end
def orders
data = []
object.task_orders.each do |order|
data << {id: order.order_id, budget: order.budget}
end
data
end
def resolver
user = object.user
data = {}
if user.present?
data[:name] = user.name
data[:href] = user_path(user)
data[:id] = user.id
end
data
end
def links
data = []
link_to_self = {}
link_to_self[:href] = task_path(object)
link_to_self[:rel] = 'self'
data << link_to_self
link_to_external = {}
link_to_external[:href] = object.external_url
link_to_external[:rel] = 'external'
data << link_to_external
end
end
|
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username, presence: true, uniqueness: true #, format: { with: /[a-zA-Z0-9]{4,20}/ }
# attr_accessible :email, :password, :password_confirmation, :remember_me, :username
end
|
require 'socket'
module OTerm
class Server
attr_accessor :acceptThread
attr_accessor :stop
attr_accessor :listeners
attr_accessor :debug
def initialize(executor, port=6060, debug=false)
@debug = debug
@stop = false
@listeners = []
@acceptThread = Thread.start() do
server = TCPServer.new(port)
while !stop do
Thread.start(server.accept()) do |con|
@listeners << Listener.new(self, con, executor)
end
end
end
end
def shutdown()
@acceptThread.exit()
end
def remove_listener(listener)
@listeners.delete(listener)
end
def join()
@acceptThread.join()
end
end # Server
end # OTerm
|
# == Schema Information
#
# Table name: host_lists
#
# id :integer not null, primary key
# token :string
# user_id :integer
# policy :string
# created_at :datetime not null
# updated_at :datetime not null
#
class HostList < ApplicationRecord
enumerize :policy, in: [ :black, :white, :speed ], scope: true
belongs_to :user
before_save :ensure_token
def ensure_token
self.token = SecureRandom.hex
end
def to_param
token
end
end
|
require 'rails_helper'
describe UserInfo do
describe '#create' do
it " すべてのデータがあり正常に登録できる" do
userinfo = build(:user)
expect(userinfo).to be_valid
end
it "first_nameなしでは保存不可" do
userinfo = build(:user_info, first_name: nil)
userinfo.valid?
expect(userinfo.errors[:first_name]).to include("can't be blank")
end
it "first_nameが36文字以上だと保存不可 " do
userinfo = build(:user_info, first_name: "a"*36)
userinfo.valid?
expect(userinfo.errors[:first_name][0]).to include("is too long")
end
it "first_nameが35文字以下だと保存可能" do
userinfo = build(:user_info, first_name: "a"*35)
expect(userinfo).to be_valid
end
it "last_nameが空だと保存不可" do
userinfo = build(:user_info, last_name: nil)
userinfo.valid?
expect(userinfo.errors[:last_name]).to include("can't be blank")
end
it "last_nameが36文字以上だと保存不可" do
userinfo = build(:user_info, last_name: "a"*36)
userinfo.valid?
expect(userinfo.errors[:last_name][0]).to include("is too long")
end
it "last_nameが35文字以下だと保存可能" do
userinfo = build(:user_info, last_name: "a"*35)
expect(userinfo).to be_valid
end
it "kana_first_nameが空だと保存不可" do
userinfo = build(:user_info, kana_first_name: nil)
userinfo.valid?
expect(userinfo.errors[:kana_first_name]).to include("can't be blank")
end
it "kana_first_nameが36文字以上だと保存不可" do
userinfo = build(:user_info, kana_first_name: "a"*36)
userinfo.valid?
expect(userinfo.errors[:kana_first_name][0]).to include("is too long")
end
it "ana_first_nameが35文字以下だと保存可能" do
userinfo = build(:user_info, kana_first_name: "a"*35)
expect(userinfo).to be_valid
end
it "kana_last_nameが空だと保存不可" do
userinfo = build(:user_info, kana_last_name: nil)
userinfo.valid?
expect(userinfo.errors[:kana_last_name]).to include("can't be blank")
end
it "kana_last_nameが36文字以上だと保存不可" do
userinfo = build(:user_info, kana_last_name: "a"*36)
userinfo.valid?
expect(userinfo.errors[:kana_last_name][0]).to include("is too long")
end
it "kana_last_nameが35文字以下だと保存可能" do
userinfo = build(:user_info, kana_last_name: "a"*35)
expect(userinfo).to be_valid
end
it "birth_yearが空だと保存不可" do
userinfo = build(:user_info, birth_year: nil)
userinfo.valid?
expect(userinfo.errors[:birth_year]).to include("can't be blank")
end
it "birth_monthが空だと保存不可" do
userinfo = build(:user_info, birth_month: nil)
userinfo.valid?
expect(userinfo.errors[:birth_month]).to include("can't be blank")
end
it "birth_dayが空だと保存不可" do
userinfo = build(:user_info, birth_day: nil)
userinfo.valid?
expect(userinfo.errors[:birth_day]).to include("can't be blank")
end
end
end
|
class SessionsController < ApplicationController
def create
auth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id
do_redirect
end
def destroy
session[:user_id] = nil
do_redirect
end
def twitter
session[:redirect_target] = request.referer unless session[:redirect_target]
redirect_to :controller => :auth, :action => :twitter
end
private
def do_redirect
if session[:redirect_target]
redirect_to session[:redirect_target]
session[:redirect_target] = nil
else
redirect_to root_url
end
end
end
|
class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.integer :score, :null => false, :default=>0
t.references :user, :null => false
t.references :votable, :polymorphic => true
t.timestamps
end
add_index :votes, [:user_id, :votable_id, :votable_type], :name=> :one_vote_per, :unique=>true
add_index :votes, :user_id
add_index :votes, :votable_id
end
end
|
require "rails_helper"
def create_duplicate_patients
facility_blue = create(:facility, name: "Facility Blue")
user = create(:user, registration_facility: facility_blue)
patient_blue = create_patient_with_visits(registration_time: 6.month.ago, facility: facility_blue, user: user)
facility_red = create(:facility, facility_group: facility_blue.facility_group, name: "Facility Red")
patient_red = create_patient_with_visits(registration_time: 1.month.ago, facility: facility_red, user: user)
{blue: patient_blue, red: patient_red}
end
def with_comparable_attributes(related_entities)
related_entities.map do |entity|
entity.attributes.with_indifferent_access.with_int_timestamps.except(:id, :patient_id, :created_at, :updated_at, :deleted_at)
end
end
def duplicate_records(deduped_record_ids)
DeduplicationLog.where(deduped_record_id: Array(deduped_record_ids)).flat_map(&:duplicate_records).uniq
end
describe PatientDeduplication::Deduplicator do
context "#merge" do
it "creates a new patient with the right associated facilities and users" do
patient_blue, patient_red = create_duplicate_patients.values_at(:blue, :red)
new_patient = described_class.new([patient_blue, patient_red], user: patient_blue.registration_user).merge
expect(new_patient.recorded_at.to_i).to eq(patient_blue.recorded_at.to_i)
expect(new_patient.registration_facility).to eq(patient_blue.registration_facility)
expect(new_patient.registration_user).to eq(patient_blue.registration_user)
expect(new_patient.assigned_facility).to eq(patient_red.assigned_facility)
expect(new_patient.device_created_at.to_i).to eq(patient_blue.device_created_at.to_i)
expect(new_patient.device_updated_at.to_i).to eq(patient_blue.device_updated_at.to_i)
expect(duplicate_records(new_patient.id)).to match_array([patient_blue, patient_red])
end
it "Uses the latest available name, gender, status, address,and reminder consent" do
patient_earliest = create(:patient, recorded_at: 2.months.ago, full_name: "patient earliest", gender: :male, reminder_consent: "granted")
patient_not_latest = create(:patient, recorded_at: 2.months.ago, full_name: "patient not latest", gender: :male, reminder_consent: "granted")
patient_latest = create(:patient, recorded_at: 1.month.ago, full_name: "patient latest", gender: :female, reminder_consent: "denied", address: nil)
patients = [patient_earliest, patient_not_latest, patient_latest]
new_patient = described_class.new(patients).merge
expect(new_patient.full_name).to eq(patient_latest.full_name)
expect(new_patient.gender).to eq(patient_latest.gender)
expect(new_patient.status).to eq(patient_latest.status)
expect(new_patient.reminder_consent).to eq(patient_latest.reminder_consent)
expect(new_patient.address.street_address).to eq(patient_not_latest.address.street_address)
expect(duplicate_records(new_patient.address)).to match_array(patients.map(&:address).compact)
end
context "age and dob" do
it "Uses the latest available DoB" do
patient_earliest = create(:patient, recorded_at: 3.months.ago, age: 42, date_of_birth: Date.parse("1 January 1945"))
patient_not_latest = create(:patient, recorded_at: 2.month.ago, age: 42, date_of_birth: Date.parse("10 January 1945"))
patient_latest = create(:patient, recorded_at: 1.month.ago, age: 42, date_of_birth: nil)
new_patient = described_class.new([patient_earliest, patient_not_latest, patient_latest]).merge
expect(new_patient.date_of_birth).to eq(patient_not_latest.date_of_birth)
expect(new_patient.age).to eq(nil)
expect(new_patient.age_updated_at).to eq(nil)
expect(new_patient.current_age).to eq(patient_not_latest.current_age)
end
it "If there is no DoB, it uses the latest available age" do
patient_earliest = create(:patient, recorded_at: 3.months.ago, age: 88, date_of_birth: nil, age_updated_at: 2.months.ago)
patient_not_latest = create(:patient, recorded_at: 2.month.ago, age: 42, date_of_birth: nil, age_updated_at: 1.month.ago)
patient_latest = create(:patient, recorded_at: 1.month.ago, age: nil, date_of_birth: nil, age_updated_at: 1.month.ago)
new_patient = described_class.new([patient_earliest, patient_not_latest, patient_latest]).merge
expect(new_patient.date_of_birth).to eq(nil)
expect(new_patient.age).to eq(42)
expect(new_patient.age_updated_at.to_i).to eq(patient_not_latest.age_updated_at.to_i)
expect(new_patient.current_age).to eq(patient_not_latest.current_age)
end
end
it "Uses full set of prescription drugs from latest visit, and ensures history is kept" do
patient_blue, patient_red = create_duplicate_patients.values_at(:blue, :red)
new_patient = described_class.new([patient_blue, patient_red]).merge
expect(new_patient.prescription_drugs.count).to eq(patient_blue.prescription_drugs.with_discarded.count + patient_red.prescription_drugs.with_discarded.count)
expect(with_comparable_attributes(new_patient.prescribed_drugs)).to match_array(with_comparable_attributes(patient_red.prescribed_drugs.with_discarded))
expect(duplicate_records(new_patient.prescription_drugs.map(&:id))).to match_array([patient_blue, patient_red].flat_map { |p| p.prescription_drugs.with_discarded })
end
it "merges phone numbers uniqued by the number" do
patient_blue = create(:patient, phone_numbers: [])
patient_red = create(:patient, phone_numbers: [])
_phone_number_1 = create(:patient_phone_number, number: "111111111", dnd_status: true, device_updated_at: 2.months.ago, patient: patient_blue)
phone_number_2 = create(:patient_phone_number, number: "111111111", dnd_status: false, device_updated_at: 1.month.ago, patient: patient_red)
phone_number_3 = create(:patient_phone_number, number: "3333333333", patient: patient_red)
new_patient = described_class.new([patient_blue, patient_red]).merge
expect(with_comparable_attributes(new_patient.phone_numbers)).to match_array(with_comparable_attributes([phone_number_2, phone_number_3]))
expect(duplicate_records(new_patient.phone_numbers.map(&:id))).to match_array([phone_number_2, phone_number_3])
end
it "merges patient business identifiers uniqued by the identifier" do
patient_blue = create(:patient, business_identifiers: [])
patient_red = create(:patient, business_identifiers: [])
identifier_id = SecureRandom.uuid
_business_identifier_1 = create(:patient_business_identifier, identifier: identifier_id, device_updated_at: 2.months.ago, patient: patient_blue)
business_identifier_2 = create(:patient_business_identifier, identifier: identifier_id, device_updated_at: 1.month.ago, patient: patient_red)
business_identifier_3 = create(:patient_business_identifier, identifier: SecureRandom.uuid, patient: patient_red)
new_patient = described_class.new([patient_blue, patient_red]).merge
expect(with_comparable_attributes(new_patient.business_identifiers)).to match_array(with_comparable_attributes([business_identifier_2, business_identifier_3]))
expect(duplicate_records(new_patient.business_identifiers.map(&:id))).to match_array([business_identifier_2, business_identifier_3])
end
it "merges medical histories" do
earlier_medical_history = create(:medical_history,
prior_heart_attack_boolean: true,
prior_stroke_boolean: false,
chronic_kidney_disease_boolean: nil,
receiving_treatment_for_hypertension_boolean: nil,
diabetes_boolean: nil,
diagnosed_with_hypertension_boolean: nil,
prior_heart_attack: "yes",
prior_stroke: "no",
chronic_kidney_disease: "unknown",
receiving_treatment_for_hypertension: "no",
diabetes: "no",
diagnosed_with_hypertension: "no",
hypertension: "no",
device_created_at: 1.month.ago,
device_updated_at: 1.month.ago,
created_at: 1.month.ago,
updated_at: 1.month.ago)
later_medical_history = create(:medical_history,
prior_heart_attack_boolean: true,
prior_stroke_boolean: nil,
chronic_kidney_disease_boolean: nil,
receiving_treatment_for_hypertension_boolean: nil,
diabetes_boolean: false,
device_created_at: 1.month.ago,
device_updated_at: 1.month.ago,
created_at: 1.month.ago,
updated_at: 1.month.ago,
diagnosed_with_hypertension_boolean: nil,
prior_heart_attack: "no",
prior_stroke: "no",
chronic_kidney_disease: "no",
receiving_treatment_for_hypertension: "no",
diabetes: "yes",
diagnosed_with_hypertension: "no",
hypertension: "no")
new_patient = described_class.new([earlier_medical_history.patient, later_medical_history.patient]).merge
expect(new_patient.medical_history.attributes.with_indifferent_access.with_int_timestamps).to include({
prior_heart_attack_boolean: true,
prior_stroke_boolean: false,
chronic_kidney_disease_boolean: nil,
receiving_treatment_for_hypertension_boolean: nil,
diabetes_boolean: false,
diagnosed_with_hypertension_boolean: nil,
prior_heart_attack: "yes",
prior_stroke: "no",
chronic_kidney_disease: "no",
receiving_treatment_for_hypertension: "no",
diabetes: "yes",
diagnosed_with_hypertension: "no",
hypertension: "no",
user_id: later_medical_history.user.id,
device_created_at: later_medical_history.device_created_at,
device_updated_at: later_medical_history.device_updated_at
}.with_indifferent_access.with_int_timestamps)
expect(duplicate_records(new_patient.medical_history.id)).to match_array([earlier_medical_history, later_medical_history])
end
it "copies over encounters, observations and all observables" do
patient_blue, patient_red = create_duplicate_patients.values_at(:blue, :red)
patients = [patient_blue, patient_red]
visit = create_visit(patient_blue, facility: patient_red.registration_facility, visited_at: patient_red.latest_blood_pressure.recorded_at)
encounters = Encounter.where(patient_id: patients).load - [visit[:blood_pressure].encounter]
blood_pressures = BloodPressure.where(patient_id: patients).load
blood_sugars = BloodSugar.where(patient_id: patients).load
observables = patients.flat_map(&:observations).map(&:observable)
soft_deleted_bp = blood_pressures.first
soft_deleted_sugar = blood_sugars.first
soft_deleted_bp.discard
soft_deleted_sugar.discard
new_patient = described_class.new(patients).merge
expect(with_comparable_attributes(new_patient.encounters)).to eq with_comparable_attributes(encounters)
expect(duplicate_records(new_patient.encounters.map(&:id))).to match_array(encounters)
expect(with_comparable_attributes(new_patient.blood_pressures)).to match_array with_comparable_attributes(blood_pressures - [soft_deleted_bp])
expect(duplicate_records(new_patient.blood_pressures.map(&:id))).to match_array(blood_pressures - [soft_deleted_bp])
expect(with_comparable_attributes(new_patient.blood_sugars)).to match_array with_comparable_attributes(blood_sugars - [soft_deleted_sugar])
expect(duplicate_records(new_patient.blood_sugars.map(&:id))).to match_array(blood_sugars - [soft_deleted_sugar])
expect(with_comparable_attributes(new_patient.observations.map(&:observable))).to match_array with_comparable_attributes(observables - [soft_deleted_bp, soft_deleted_sugar])
expect(duplicate_records(new_patient.observations.map(&:observable))).to match_array(observables - [soft_deleted_bp, soft_deleted_sugar])
end
it "copies over appointments, keeps only one scheduled appointment and marks the rest as cancelled" do
patient_blue, patient_red = create_duplicate_patients.values_at(:blue, :red)
scheduled_appointments = Appointment.where(patient_id: [patient_red, patient_blue]).status_scheduled.order(device_created_at: :desc).load
new_patient = described_class.new([patient_blue, patient_red]).merge
patient_blue.appointments.with_discarded.status_scheduled.update_all(status: :cancelled)
expect(with_comparable_attributes(new_patient.appointments.status_scheduled)).to eq with_comparable_attributes(scheduled_appointments.take(1))
expected_appointments = Appointment.with_discarded.where(patient_id: [patient_red, patient_blue])
expect(with_comparable_attributes(new_patient.appointments)).to match_array with_comparable_attributes(expected_appointments)
expect(duplicate_records(new_patient.appointments.map(&:id))).to match_array(expected_appointments)
end
it "copies over teleconsultations" do
patients = create_duplicate_patients.values
teleconsultations = Teleconsultation.where(patient_id: patients).load
new_patient = described_class.new(patients).merge
expect(with_comparable_attributes(new_patient.teleconsultations)).to match_array with_comparable_attributes(teleconsultations)
expect(duplicate_records(new_patient.teleconsultations.map(&:id))).to match_array(teleconsultations)
end
context "marks patients as merged" do
it "soft deletes the merged patients" do
patients = create_duplicate_patients.values
expect(patients.first).to receive(:discard_data).and_call_original
expect(patients.last).to receive(:discard_data).and_call_original
described_class.new(patients).merge
expect(patients.map(&:discarded?)).to all be true
end
end
context "handles errors" do
it "less than 2 patients cannot be merged" do
patients = [create(:patient)]
instance = described_class.new(patients, user: patients.first.registration_user)
expect(instance.errors).to eq ["Select at least 2 patients to be merged."]
expect(instance.merge).to eq nil
end
it "catches any error that happens during merge, and adds it to the list of errors" do
patients = create_duplicate_patients.values
patients.map(&:medical_history).each(&:discard)
instance = described_class.new(patients, user: patients.first.registration_user)
expect(instance.merge).to eq nil
expect(instance.errors.first[:exception]).to be_present
expect(instance.errors.first[:patient_ids]).to eq(patients.pluck(:id))
end
end
end
end
|
class GmailImporter
attr_reader :email, :password
def initialize(email, password)
@email = email
@password = password
end
def import(number_of_messages)
@imap = Net::IMAP::Gmail.new('imap.gmail.com', ssl: true)
@imap.login(email, password)
@imap.examine(folder)
fetch(number_of_messages)
each_message do |message, labels|
puts message
end
end
private
def fetch(number_of_messages)
exists = @imap.responses["EXISTS"].first
message_range = (exists - number_of_messages)..exists
columns = ["UID", "FLAGS", "X-GM-LABELS", "BODY.PEEK[]"]
@messages = @imap.fetch(message_range, columns).map do |data|
[data.attr["BODY[]"], data.attr["X-GM_LABELS"]]
end
end
def each_message(&block)
@messages.each(&block)
end
def folder
@folder ||= @imap.list("", "*").find {|x| x.attr.include? :All}.name
end
end
|
require "test_helper"
describe Api::V1::AreasController do
before do
@plains = Area.create(:name => "Plains", :width => 640, :height => 512)
@desert = Area.create(:name => "Desert", :width => 640, :height => 512)
@night_elf = Player.create(:name => "Night Elf", :direction => "down",
:x => 0, :y => 0)
@barbarian = Player.create(:name => "Barbarian", :direction => "down",
:x => 0, :y => 0 )
end
describe "#index" do
it "must respond with JSON containing all Areas" do
get "index"
response.status.must_equal 200
json.length.must_equal 2
end
end
describe "#update" do
it "must add players when IDs are provided" do
@plains.players.length.must_equal 0
payload = {
:id => @plains.id,
:area => {
:players => [@night_elf.id, @barbarian.id]
}
}
post("update", payload)
@plains.reload
@plains.players.length.must_equal 2
end
it "must remove players when IDs are not provided" do
@plains.players.length.must_equal 0
payload = {
:id => @plains.id,
:area => {
:players => []
}
}
post("update", payload)
@plains.reload
@plains.players.length.must_equal 0
end
it "must remove the players when their IDs are not provided" do
@plains.players.length.must_equal 0
payload = {
:id => @plains.id,
:area => {
:players => [@night_elf.id, @barbarian.id]
}
}
post("update", payload)
@plains.reload
@plains.players.length.must_equal 2
payload = {
:id => @plains.id,
:area => {
:players => [@night_elf.id]
}
}
post("update", payload)
@plains.reload
@night_elf.reload
@plains.players.length.must_equal 1
@plains.players[0].must_equal @night_elf
@plains.players[1].must_be_nil
end
end
end
|
# == Schema Information
#
# Table name: addresses
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# addressable_id :integer not null
# addressable_type :string(255) not null
# tag_for_address :string(255)
# country :string(255)
# address_line_1 :string(255)
# address_line_2 :string(255)
# locality :string(255)
# admin_area :string(255)
# postal_code :string(255)
#
require 'spec_helper'
describe Address do
it "should create" do
@address = Address.new( :tag_for_address => 'My Address',
:country => 'USA',
:address_line_1 => '123 Main St',
:address_line_2 => 'Apt 3B',
:locality => 'Derwood',
:admin_area => 'MD',
:postal_code => '22102',
:addressable_id => 0,
:addressable_type => 'User'
)
@address.save!.should eq true
@address.should be_valid
@address.address_line_1.should eq '123 Main St'
@address.address_line_2.should eq 'Apt 3B'
end
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require "kbsecret"
require "tty-prompt"
include KBSecret
$VERBOSE = nil # tty-prompt blasts us with irrelevant warnings on 2.4
cmd = CLI.create do |c|
c.slop do |o|
o.banner = <<~HELP
Usage:
kbsecret rm [options] <record>
HELP
o.string "-s", "--session", "the session containing the record", default: :default
o.bool "-i", "--interactive", "ask for confirmation before deleting"
end
c.dreck do
string :label
end
c.ensure_session!
end
label = cmd.args[:label]
cmd.die "Can't delete a nonexistent record." unless cmd.session.record? label
tty = TTY::Prompt.new
confirm = if cmd.opts.interactive?
tty.yes?("Delete '#{label}' from the #{cmd.session.label} session?")
else true
end
cmd.session.delete_record(label) if confirm
|
class AuthlogService
def initialize(params, message, status)
@params = params
@message = message
@status = status
end
def warn
auth_logger.warn(data_attributes)
end
def info
auth_logger.info(data_attributes)
end
def fatal
auth_logger.fatal(data_attributes)
end
def debug
auth_logger.debug(data_attributes)
end
private
attr_reader :params, :message, :status
def auth_logger
AUTH_LOGGER
end
def data_attributes
{
params: params,
message: message,
status: status
}
end
end |
json.data do
json.proposal_image do
json.id @proposal_image.id
json.image url_for(@proposal_image.image)
json.proposal_item_id @proposal_image.proposal_item_id
end
end |
####
#
# LiteralSearch
#
# Responsible for exact match searches for the application.
#
# Used by search Controller - returns results as LiteralResults
#
#
####
#
class LiteralSearch
attr_reader :referrer, :query
# referrer: the model and action of the query being executed - one of Client,
# Payment, Property, Arrear or Invoice and any of the actions.
# query: the search terms being queried on the model
#
def self.search(referrer:, query:)
new(referrer: referrer, query: query)
end
# go
# Executes the query
# returns LiteralResult - a wrapper for the search results
#
def go
return query_by_referrer if query_by_referrer.found?
default_ordered_query
end
private
def initialize(referrer:, query:)
@referrer = referrer
@query = query
end
# query_by_referrer
# - cache method
#
def query_by_referrer
@query_by_referrer ||= get_query_by_referrer
end
# get_query_by_referrer
# - search depending on the request's original controller
#
def get_query_by_referrer
case referrer.controller
when 'clients' then client_search
when 'payments', 'payments_by_dates' then payment_search
when 'properties' then property_search
when 'arrears', 'cycles', 'users', 'invoice_texts', 'invoicings', 'invoices'
results records: []
else
raise NotImplementedError, "Missing: #{referrer}"
end
end
def client_search
results action: 'show',
controller: 'clients',
records: Client.match_by_human_ref(query)
end
def payment_search
results action: 'index',
controller: 'payments',
records: Payment.includes(account: [property: [:entities]])
.match_by_human_ref(query)
.by_booked_at.to_a
end
def property_search
results action: 'show',
controller: 'properties',
records: Property.match_by_human_ref(query)
end
# default_ordered_query
# - when we don't find anything under the initial controller we check if
# it would have matched literal searches in other important controllers
# before giving up.
#
# returns literal search matches for the query
#
def default_ordered_query
return property_search if property_search.found?
return client_search if client_search.found?
results records: []
end
def results(action: '', controller: '', records:)
LiteralResult.new action: action, controller: controller, records: records
end
end
|
require "coolxbrl/edinet/document_information"
require "coolxbrl/edinet/xbrl"
require "coolxbrl/edinet/presentation"
require "coolxbrl/edinet/xsd"
require "coolxbrl/edinet/label"
module CoolXBRL
module EDINET
extend XSD
class << self
def parse(dir, language=Label::DEFAULT_LANGUAGE)
get_taxonomy dir, language
Presentation.parse presentation
end
def parse_table(dir, consolidated, table, language=Label::DEFAULT_LANGUAGE)
get_taxonomy dir, language
Presentation.parse_table(presentation, consolidated, table)
end
private
def read(doc)
end
def get_xbrl(path)
end
end
end
end |
module Jekyll
module OctopodFilters
# Escapes some text for CDATA
def cdata_escape(input)
input.gsub(/<!\[CDATA\[/, '<![CDATA[').gsub(/\]\]>/, ']]>')
end
# Replaces relative urls with full urls
#
# {{ "about.html" | expand_urls }} => "/about.html"
# {{ "about.html" | expand_urls:site.url }} => "http://example.com/about.html"
def expand_urls(input, url='')
url ||= '/'
input.gsub /(\s+(href|src)\s*=\s*["|']{1})(\/[^\"'>]*)/ do
$1+url+$3
end
end
end
end
Liquid::Template.register_filter(Jekyll::OctopodFilters)
|
class Api::LessonsController < Api::ApplicationController
def index
lessons = Subject.find_by!(slug: params[:slug]).lessons
render json: lessons.map{ |lesson|
{
id: lesson.id,
name: lesson.name,
}
}
end
def show
subject = Subject.find_by(slug: params[:slug])
lesson = subject.lessons.find_by(order: params[:lesson_order])
chapter = lesson.chapters.find_by(order: params[:chapter_order])
slides = chapter.slides
instruction = chapter.instruction
answer_columns = chapter.answer_columns.as_json(include: [:answer_spaces])
answer_choices = chapter.answer_choices
render json: {
slides: slides,
instruction: instruction,
answer_columns: answer_columns,
answer_choices: answer_choices,
}
end
end
|
feature 'diaries' do
scenario 'return a list of diary entries' do
visit '/'
expect(page).to have_content 'Dear Diary'
end
end
|
require 'spec_helper'
describe "Session", :vcr, :record => :new_episodes, :type => :request do
context "successful login" do
before { setup_for_github_login }
it "enforces opensesame login" do
visit root_path
within("#opensesame-session") do
page.should have_content("Login")
click_link "github"
end
page.should have_content "Welcome Home"
end
describe "auto login" do
before { OpenSesame.stub!(:auto_access_provider).and_return('github') }
it "allows auto login" do
visit root_path
page.should have_content "Welcome Home"
end
it "skips auto login if just logged out" do
visit root_path
click_link "Logout"
page.should_not have_content "Welcome Home"
page.should have_content "Login"
visit root_path # auto login now works on refresh
page.should have_content "Welcome Home"
page.should_not have_content "Login"
end
end
end
it "tries auto login and ends up on opensesame page after failure" do
setup_for_github_login(mock('NonUser', :id => "123"))
visit root_path
page.should have_content "Login"
page.should_not have_content "Welcome Home"
end
end |
class Bomb
attr_reader :x, :y, :power
EXPLODE_TIME = 1500 #ms
def initialize(x, y, power=3)
@x, @y = x, y
@sprite = Gosu::Image.new('bomb.png', :tileable => true)
@timer = Gosu.milliseconds
@power = power
end
def draw
@sprite.draw(@x, @y, ZOrder::BOMB)
end
def update
explode! if timer_expired?
end
def apply_explosion(map)
self.power.times do |i|
object = object_hit(map, @x + (i * Constants::TILE_SIZE), @y)
break unless object == :ground
end
self.power.times do |i|
object = object_hit(map, @x - (i * Constants::TILE_SIZE), @y)
break unless object == :ground
end
self.power.times do |i|
object = object_hit(map, @x, @y + (i * Constants::TILE_SIZE))
break unless object == :ground
end
self.power.times do |i|
object = object_hit(map, @x, @y - (i * Constants::TILE_SIZE))
break unless object == :ground
end
end
private
def object_hit(map, x, y)
players = $window.get_hit_player(x, y)
players.each do |player|
player.kill
end
return :player unless players.empty?
if map.is_ground?(x, y)
return :ground
end
if map.is_wall?(x, y)
return :wall
end
if map.is_box?(x, y)
map.destroy_box(x, y)
return :box
end
end
def timer_expired?
@timer + EXPLODE_TIME < Gosu.milliseconds
end
def explode!
$window.bomb_explode(self)
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu1404"
config.vm.define :viff do |master|
master.vm.network "forwarded_port", guest: 80, host: 8088
master.vm.network "forwarded_port", guest: 27017, host: 27017
master.vm.network "forwarded_port", guest: 9999, host: 9999
master.vm.network "forwarded_port", guest: 6379, host: 6379
master.vm.network "forwarded_port", guest: 3000, host: 30000
master.vm.network "forwarded_port", guest: 3001, host: 30001
master.vm.hostname = "viff"
master.vm.network "private_network", ip: "10.1.1.2"
end
config.vm.provision "ansible" do |ansible|
ansible.playbook = "./ansible-tasks/playbook.yml"
ansible.verbose = "vvv"
end
end
|
module Adminpanel
class UsersController < Adminpanel::ApplicationController
private
def user_params
params.require(:user).permit(
:email,
:name,
:password,
:password_confirmation,
:role_id
)
end
end
end
|
class AddEmbedLinkToPost < ActiveRecord::Migration
def self.up
add_column :posts, :embed_link, :text, :default => nil
end
def self.down
remove_column :posts, :embed_link
end
end
|
require 'spec_helper'
describe Group do
subject(:group) { Group.new(vmt_userid, vmt_password, vmt_url) }
let(:vmt_userid) { VMT_USERID }
let(:vmt_password) { VMT_PASSWORD}
let(:vmt_url) { VMT_BASE_URL }
describe "Should be a valid VMT Object" do
it_behaves_like 'a VMT API object'
end
describe "#get_group_list" do
let(:data_result) {group.get_group_list(group_ID)}
let(:group_ID) { nil }
context "will return a list of groups" do
it_behaves_like 'return entity'
end
context "will return a single group by name" do
let(:group_ID) {'domain-c72'}
it_behaves_like 'return entity'
end
context "will return a single group by UUID" do
let(:group_ID) {'d7c70eb353932647263031225d6084bfa8210460'}
it_behaves_like 'return entity'
end
end
describe "#get_group_members" do
let(:data_result) {group.get_group_members(group_ID)}
let(:group_ID) { nil }
context "will return members of a group by name" do
let(:group_ID) {'domain-c72'}
it_behaves_like 'return entity'
end
context "will return members of a group by UUID" do
let(:group_ID) {'d7c70eb353932647263031225d6084bfa8210460'}
it_behaves_like 'return entity'
end
context "will throw exception when no group ID is passed" do
let(:group_ID) { nil }
it_behaves_like 'Errors'
end
end
end |
class Authentication
def initialize(user_object)
email = user_object[:email]
@password = user_object[:password]
@user = User.find_by(email: email)
end
def authenticate
true if @user && @user.authenticate(@password)
end
def generate_token
JwtWebToken.encode(user_id: @user.id)
end
end |
class QuestionScore < ActiveRecord::Base
#Relationships
belongs_to :game_record
#Scopes
scope :for_game_record, ->(game_record_id) { where('game_record_id = ?', game_record_id) }
scope :for_landmark, ->(landmark_id) { where('landmark_id = ?', landmark_id) }
scope :for_question, ->(question_id) { where('question_id = ?', question_id) }
scope :by_landmark_id, -> { order("landmark_id") }
scope :by_question_id, -> { order("question_id") }
#Validations
validates_presence_of :landmark_id
validates_presence_of :question_id
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.