text stringlengths 10 2.61M |
|---|
# Decide what objects/models you want to use, I used pirates and ships, you can use this or anything else.
# Make a nested form (this should probably have labels so it makes sense to a user).
# After a user clicks submit they should be taken to a page that displays all the information we just posted from the form. In my example I'd have a page that showed the pirate I created along with his ships and all the details about the pirate and his ships.
# I'm intentionally being vague about exactly what routes you need or how to set this all up. We can all review together how you structured your routes and talk about the postives and negatives. Do what you think makes the most sense. Follow REST conventions. Use the internet to figure it out if need be.
# Note: YOU DO NOT NEED A DATABASE, we just need to keep track of the forms input long enough to display it, not persist it. I don't expect the pirate to be there the next time I come to his URL, but it'd be cool if he was.
# This is an excercise in REST conventions, HTML forms and params. Please use the debugger and/or puts to see how changing the type of HTML you use changes the params. Spend some time thinking about your routes.
# PS DO NOT COPY EXACTLY WHAT I HAVE HERE. THIS IS THE ONLY WAY TO FAIL FLATIRON SCHOOL
# get ...pirate thing
# end
# post '/pirate' do
# @pirate = Pirate.new
# @pirate.name = params[:pirate][:name]
# @pirate.weight = params[:pirate][:weight]
# @pirate.height = params[:pirate][:height]
# @pirate.save
# end
class PirateParams < Sinatra::Base
require 'sinatra'
get '/hi' do
"Hello World!"
end
end |
Given(/^a valid client id and a valid secret$/) do
ENV['PERSONA_OAUTH_CLIENT'] = 'primate'
ENV['PERSONA_OAUTH_SECRET'] = 'bananas'
end
Given(/^an invalid client id and an invalid secret$/) do
ENV['PERSONA_OAUTH_CLIENT'] = 'complete'
ENV['PERSONA_OAUTH_SECRET'] = 'rubbish'
end
Given(/^I am authenticated as a superuser client$/) do
steps 'Given a valid client id and a valid secret'
steps 'When I attempt to authenticate'
end
# rubocop:disable Metrics/LineLength
Given(/^I am authenticated as a client with the scopes of "([^"]*)"$/) do |scopes|
@required_scopes = scopes.split(', ')
end
When(/^I attempt to authenticate$/) do
begin
@talis = Talis.new(host: 'http://persona')
@authenticated = true
rescue Talis::AuthenticationFailedError
fail_with 'authentication failed'
end
end
When(/^I retrieve my scopes$/) do
steps 'When I attempt to authenticate'
end
When(/^I try to add the scope of "([^"]*)" to my client$/) do |scope|
@talis.add_scope(scope)
end
Then(/^I should have the scope of "([^"]*)"$/) do |scope|
expect(@talis.scopes).to include(scope)
end
Then(/^I should have the scopes "([^"]*)"$/) do |scopes|
scopes.split(', ').each do |scope|
expect(@talis.scopes).to include(scope)
end
end
Then(/^I should be authenticated$/) do
expect(@authenticated).to be_truthy
end
Then(/^I should not be authenticated$/) do
expect(@authenticated).to be_falsey
end
|
class AddLinkedUserIdToEntries < ActiveRecord::Migration[5.1]
def change
add_column :entries, :linked_user_id, :id
end
end
|
require 'cld_native'
module CLD
class Language
attr_accessor :code, :name
end
class PossibleLanguage
attr_accessor :name, :score
end
class LanguageResult
attr_accessor :probable_language, :reliable, :possible_languages
end
class Detector
def initialize
@native = CLDNative.new
end
def detect_language(text, options = {})
@native.detect_language(text, options)
end
end
end |
# Write a method that takes two strings as arguments, determines the longest of the two strings,
# and then returns the result of concatenating the shorter string, the longer string, and the
# shorter string once again. You may assume that the strings are of different lengths.
# Understand the problem:
# Pass two string arguments
# Compare string lengths
# Concat shorter string + longer string + shorter string
# Return concat string
# Inputs: strings
# Outputs: string
# Data Structures
# string: input, output
# Algorithm
# START
# SET string1 string2
# IF string1.length > string2.length
# #{string1}#{string2}#{string1}
# ELSE
# #{string2}#{string1}#{string2}
# END
# END
def string_concat string1, string2
if string1.length >= string2.length
string1 + string2 + string1
else
string2 + string1 + string2
end
end
puts string_concat "Its me","Its you"
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
d = Dog.create(name: "Sylvain")
puts "Bienvenue chez les Sims. Un chien a été crée. Il a pour nom #{d.name}"
ds = Dogsitter.create(name: "Thibault")
puts "Mais c'est un chien de Super_héros. Suuuuuuuper-#{ds.name}"
s = Stroll.create(dog: d, dogsitter: ds)
puts "#{s.dog.name} et #{s.dogsitter.name} vont se balader au parc ensemble"
arrayd = [d.strolls[1]]
arrayds = [ds.strolls[1]]
puts "Voici tout les strolls dans lequel #{d.name} a participé #{arrayd}"
puts "Voici tout les strolls dans lequel #{ds.name} a participé #{arrayds}"
c = City.create(city:"Paris")
puts "Ils se baladent à #{c} tous ensemble"
c.dog
s.dog
s.dogsitter
d.strolls
ds.strolls
|
class ApplicationController < ActionController::API
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from ActiveRecord::RecordNotUnique, with: :record_not_unique
def render_jsonapi_response(resource)
if resource.errors.empty?
render jsonapi: resource
else
render jsonapi_errors: resource.errors, status: 400
end
end
def record_not_unique(message)
render json: {
'errors': [
{
'status': '400',
'title': message
}
]
}, status: 400
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:firstname, :lastname, :age, :role, :email, :password])
devise_parameter_sanitizer.permit(:account_update, keys: [:firstname, :lastname, :age, :email, :password])
end
end
|
class Yajl < DebianFormula
homepage 'http://lloyd.github.com/yajl/'
url 'http://github.com/lloyd/yajl/tarball/1.0.12'
md5 '70d2291638233d0ab3f5fd3239d5ed12'
name 'yajl'
section 'libs'
version '1.0.12'
description 'Yet Another JSON Library - A Portable JSON parsing and serialization library in ANSI C'
provides 'libyajl-dev', 'libyajl1', 'yajl-tools'
conflicts 'libyajl-dev', 'libyajl1', 'yajl-tools'
replaces 'libyajl-dev', 'libyajl1', 'yajl-tools'
build_depends 'cmake'
end
|
class ProgrammesController < ApplicationController
include IndexPager
before_filter :programmes_enabled?
before_filter :find_requested_item, :only=>[:show,:admin, :edit,:update, :destroy,:initiate_spawn_project,:spawn_project]
before_filter :find_assets, :only=>[:index]
before_filter :is_user_admin_auth,:except=>[:show,:index]
include Seek::BreadCrumbs
respond_to :html
def create
@programme = Programme.new(params[:programme])
flash[:notice] = "The #{t('programme').capitalize} was successfully created." if @programme.save
respond_with(@programme)
end
def update
avatar_id = params[:programme].delete(:avatar_id).to_i
@programme.avatar_id = ((avatar_id.kind_of?(Numeric) && avatar_id > 0) ? avatar_id : nil)
flash[:notice] = "The #{t('programme').capitalize} was successfully updated." if @programme.update_attributes(params[:programme])
respond_with(@programme)
end
def edit
respond_with(@programme)
end
def new
@programme=Programme.new
respond_with(@programme)
end
def show
respond_with(@programme)
end
def initiate_spawn_project
@available_projects = Project.where('programme_id != ? OR programme_id IS NULL',@programme.id)
respond_with(@programme,@available_projects)
end
def spawn_project
proj_params=params[:project]
@ancestor_project = Project.find(proj_params[:ancestor_id])
@project = @ancestor_project.spawn({:title=>proj_params[:title],:description=>proj_params[:description],:web_page=>proj_params[:web_page],:programme=>@programme})
if @project.save
flash[:notice]="The #{t('project')} '#{@ancestor_project.title}' was successfully spawned for the '#{t('programme')}' #{@programme.title}"
redirect_to project_path(@project)
else
@available_projects = Project.where('programme_id != ? OR programme_id IS NULL',@programme.id)
render :action=>:initiate_spawn_project
end
end
end
|
FactoryBot.define do
factory :accessory do
name { Faker::Device.unique.model_name }
cost { Faker::Commerce.price(range: 0..100.0) }
qty { 10 }
status_label
company
model { association :model, company: company }
vendor { association :vendor, company: company }
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :users, only: %i[new create show]
resources :sessions
resources :posts
resources :comments, only: %i[create destroy]
get "logout" => "sessions#destroy", :as => "logout"
get "signin" => "sessions#new", :as => "sign_in"
root 'posts#index'
end
|
class CalculateDeliveryDate
attr_reader :event_date
BANK_HOLIDAYS = [
Date.new(2017, 1, 2), Date.new(2017, 1, 16), Date.new(2017, 2, 20), Date.new(2017, 5, 29),
Date.new(2017, 7, 4), Date.new(2017, 9, 4), Date.new(2017, 10, 9), Date.new(2017, 11, 11),
Date.new(2017, 11, 23), Date.new(2017, 12, 25), Date.new(2018, 1, 1), Date.new(2018, 1, 15),
Date.new(2018, 2, 19), Date.new(2018, 5, 28), Date.new(2018, 7, 4), Date.new(2018, 9, 3),
Date.new(2018, 10, 8), Date.new(2018, 11, 12), Date.new(2018, 11, 22), Date.new(2018, 12, 25)
]
def initialize(event_date)
@event_date = event_date
end
def get_future_delivery_date
delivery = adjust_if_weekend(event_date)
adjust_if_bank_holiday(delivery)
end
private
def adjust_if_weekend(delivery_date)
if delivery_date.saturday?
delivery_date - 1.day
elsif delivery_date.sunday?
delivery_date - 2.days
else
delivery_date
end
end
def adjust_if_bank_holiday(delivery_date)
if BANK_HOLIDAYS.include?(delivery_date)
delivery = delivery_date - 1.day
adjust_if_weekend(delivery)
else
delivery_date
end
end
end |
# encoding: UTF-8
module Unicafe
class Restaurant
LIST_OF_RESTAURANTS = {
1 => {name: "Metsätalo", latitude: "60.172577", longitude: "24.948878"},
2 => {name: "Olivia", latitude: "60.175077", longitude: "24.952979"},
3 => {name: "Porthania", latitude: "60.169878", longitude: "24.948669"},
4 => {name: "Päärakennus", latitude: "60.169178", longitude: "24.949297"},
5 => {name: "Rotunda", latitude: "60.170332", longitude: "24.950791"},
6 => {name: "Topelias", latitude: "60.171806", longitude: "24.95067"},
7 => {name: "Valtiotiede", latitude: "60.173897", longitude: "24.953095"},
8 => {name: "Ylioppilasaukio", latitude: "60.169092", longitude: "24.93992"},
10 => {name: "Chemicum", latitude: "60.205108", longitude: "24.963357"},
11 => {name: "Exactum", latitude: "60.20509", longitude: "24.961209"},
12 => {name: "Physicum"},
13 => {name: "Meilahti", latitude: "60.190212", longitude: "24.908911"},
14 => {name: "Ruskeasuo", latitude: "60.206341", longitude: "24.895871"},
15 => {name: "Soc & kom", latitude: "60.173054", longitude: "24.95049"},
16 => {name: "Kookos", latitude: "60.181034", longitude: "24.958652"},
18 => {name: "Biokeskus", latitude: "60.226922", longitude: "25.013707"},
19 => {name: "Korona", latitude: "60.226922", longitude: "25.013707"},
21 => {name: "Viikuna", latitude: "60.23049", longitude: "25.020544"}
}
def initialize id
@id = id
end
def name
@name ||= LIST_OF_RESTAURANTS[@id][:name]
end
def latitude
@latitude ||= LIST_OF_RESTAURANTS[@id][:latitude]
end
def longitude
@longitude ||= LIST_OF_RESTAURANTS[@id][:longitude]
end
def lunches
::Unicafe::Lunch.lunches_for_restaurant(@id)
end
def self.find_by_id id
self.new id
end
def self.find_by_name name
self.find_by_id self.name_to_id(name)
end
def self.name_to_id name
LIST_OF_RESTAURANTS.select{|key, hash| hash[:name] == name}.map{|key, hash| key}.first || raise(NotFound)
end
class NotFound < Exception
end
end
end
|
module HBase
module Response
class RowResponse < BasicResponse
def parse_content(raw_data)
doc = REXML::Document.new(raw_data)
row = doc.elements["row"]
columns = []
count = 0
row.elements["columns"].each do |col|
name = col.elements["name"].text.strip.unpack("m").first
value = col.elements["value"].text.strip.unpack("m").first rescue nil
timestamp = col.elements["timestamp"].text.strip.to_i
columns << Model::Column.new(:name => name,
:value => value,
:timestamp => timestamp)
count += 1
end
Model::Row.new(:total_count => count, :columns => columns)
end
end
end
end
|
# https://leetcode-cn.com/problems/add-two-numbers/
# 2. 两数相加
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
result = []
carry = 0
while(l1 || l2) do
num1 = l1.nil? ? 0 : l1.val
num2 = l2.nil? ? 0 : l2.val
tmp = num1 + num2 + carry
carry = tmp / 10
result.push(tmp % 10)
l1 = l1.next unless l1.nil?
l2 = l2.next unless l2.nil?
end
result.push(1) if carry == 1
result
end
|
#
# BEGIN COMPLIANCE_PROFILE
#
def catalog_to_map(catalog)
catalog_map = Hash.new()
catalog_map['compliance_map::percent_sign'] = '%'
catalog_map['compliance_map'] = {
'version' => @api_version,
'generated_via_function' => Hash.new()
}
catalog.resources.each do |resource|
# Ignore our own nonsense
next if resource.name == 'Compliance_markup'
if resource.name.is_a?(String) && (resource.name[0] =~ /[A-Z]/) && resource.parameters
resource.parameters.each do |param_array|
param = param_array.last
param_name = %{#{resource.name}::#{param.name}}.downcase
# We only want things with values
next if param.value.nil?
catalog_map['compliance_map']['generated_via_function'][param_name] = {
'identifiers' => ['GENERATED'],
'value' => param.value
}
end
end
end
return catalog_map.to_yaml
end
# There is no way to silence the global warnings on looking up a qualified
# variable, so we're going to hack around it here.
def lookup_global_silent(param)
@context.find_global_scope.to_hash[param]
end
def process_options(args)
config = {
:custom_call => false,
:report_types => [
'non_compliant',
'unknown_parameters',
'custom_entries'
],
:format => 'json',
:client_report => false,
:client_report_timestamp => false,
:server_report => true,
:server_report_dir => File.join(Puppet[:vardir], 'simp', 'compliance_reports'),
:default_map => {},
:catalog_to_compliance_map => false
}
# What profile are we using?
if args && !args.empty?
unless (args.first.is_a?(String) || args.first.is_a?(Hash))
raise Puppet::ParseError, "compliance_map(): First parameter must be a String or Hash"
end
# This is used during the main call
if args.first.is_a?(Hash)
# Convert whatever was passed in to a symbol so that the Hash merge
# works properly.
user_config = Hash[args.first.map{|k,v| [k.to_sym, v] }]
if user_config[:report_types]
user_config[:report_types] = Array(user_config[:report_types])
end
# Takes care of things that have been set to 'undef' in Puppet
user_config.delete_if{|k,v|
v.nil? || v.is_a?(Symbol)
}
config.merge!(user_config)
# This is used for custom content
else
config[:custom_call] = true
config[:custom] = {
:profile => args.shift,
:identifier => args.shift,
:notes => args.shift
}
if config[:custom][:profile] && !config[:custom][:identifier]
raise Puppet::ParseError, "compliance_map(): You must pass at least two parameters"
end
unless config[:custom][:identifier].is_a?(String)
raise Puppet::ParseError, "compliance_map(): Second parameter must be a compliance identifier String"
end
if config[:custom][:notes]
unless config[:custom][:notes].is_a?(String)
raise Puppet::ParseError, "compliance_map(): Third parameter must be a compliance notes String"
end
end
end
end
valid_formats = [
'json',
'yaml'
]
unless valid_formats.include?(config[:format])
raise Puppet::ParseError, "compliance_map(): 'valid_formats' must be one of: '#{valid_formats.join(', ')}'"
end
valid_report_types = [
'full',
'non_compliant',
'compliant',
'unknown_resources',
'unknown_parameters',
'custom_entries'
]
unless (config[:report_types] - valid_report_types).empty?
raise Puppet::ParseError, "compliance_map(): 'report_type' must include '#{valid_report_types.join(', ')}'"
end
config[:extra_data] = {
# Add the rest of the useful information to the map
'fqdn' => @context.lookupvar('fqdn'),
'hostname' => @context.lookupvar('hostname'),
'ipaddress' => @context.lookupvar('ipaddress'),
'puppetserver_info' => 'local_compile'
}
puppetserver_facts = lookup_global_silent('server_facts')
if puppetserver_facts && !puppetserver_facts.empty?
config[:extra_data]['puppetserver_info'] = puppetserver_facts
end
if config[:site_data]
unless config[:site_data].is_a?(Hash)
raise Puppet::ParseError, %(compliance_map(): 'site_data' must be a Hash)
end
end
return config
end
def get_compliance_profiles
# Global lookup for the legacy stack
compliance_profiles = lookup_global_silent('compliance_profile')
# ENC compatible lookup
compliance_profiles ||= lookup_global_silent('compliance_markup::validate_profiles')
# Module-level lookup
compliance_class_resource = @context.catalog.resource('Class[compliance_markup]')
compliance_profiles ||= compliance_class_resource[:validate_profiles] if compliance_class_resource
return compliance_profiles
end
def add_file_to_client(config, compliance_map)
if config[:client_report]
client_vardir = @context.lookupvar('puppet_vardir')
unless client_vardir
raise(Puppet::ParseError, "compliance_map(): Cannot find fact `puppet_vardir`. Ensure `puppetlabs/stdlib` is installed")
else
compliance_report_target = %(#{client_vardir}/compliance_report.#{config[:format]})
end
# Retrieve the catalog resource if it already exists, create one if it
# does not
compliance_resource = @context.catalog.resources.find{ |res|
res.type == 'File' && res.name == compliance_report_target
}
if compliance_resource
# This is a massive hack that should be removed in the future. Some
# versions of Puppet, including the latest 3.X, do not check to see if
# a resource has the 'remove' capability defined before calling it. We
# patch in the method here to work around this issue.
unless compliance_resource.respond_to?(:remove)
# Using this instead of define_singleton_method for Ruby 1.8 compatibility.
class << compliance_resource
self
end.send(:define_method, :remove) do nil end
end
@context.catalog.remove_resource(compliance_resource)
else
compliance_resource = Puppet::Parser::Resource.new(
'file',
compliance_report_target,
:scope => @context,
:source => @context.source
)
compliance_resource.set_parameter('owner',Process.uid)
compliance_resource.set_parameter('group',Process.gid)
compliance_resource.set_parameter('mode','0600')
end
unless (config[:client_report_timestamp].nil? || config[:client_report_timestamp])
compliance_map.delete('timestamp') if compliance_map['timestamp']
end
if config[:format] == 'json'
compliance_resource.set_parameter('content',%(#{(compliance_map.to_json)}\n))
elsif config[:format] == 'yaml'
compliance_resource.set_parameter('content',%(#{compliance_map.to_yaml}\n))
end
# Inject new information into the catalog
@context.catalog.add_resource(compliance_resource)
end
end
def write_server_report(config, report)
report_dir = File.join(config[:server_report_dir], @context.lookupvar('fqdn'))
FileUtils.mkdir_p(report_dir)
if config[:server_report]
File.open(File.join(report_dir,"compliance_report.#{config[:format]}"),'w') do |fh|
if config[:format] == 'json'
fh.puts(report.to_json)
elsif config[:format] == 'yaml'
fh.puts(report.to_yaml)
end
end
end
if config[:catalog_to_compliance_map]
File.open(File.join(report_dir,'catalog_compliance_map.yaml'),'w') do |fh|
fh.puts(catalog_to_map(@context.resource.scope.catalog))
end
end
end
def compliance_map(args, context)
require 'set'
@context = context
if (@custom_entries == nil)
@custom_entries = {}
end
@catalog = @context.resource.scope.catalog
profile_compiler = compiler_class.new(self)
profile_compiler.load do |key, default|
@context.call_function('lookup', [key, {"default_value" => default}])
end
main_config = process_options(args)
report_types = main_config[:report_types]
if report_types.include?('full')
report_types << 'unknown_resources'
report_types << 'unknown_parameters'
report_types << 'compliant'
report_types << 'non_compliant'
report_types << 'custom_entries'
end
report = main_config[:extra_data].dup
report['version'] = '1.0.1';
report['timestamp'] = Time.now.to_s
report['compliance_profiles'] = {}
profile_list = get_compliance_profiles
Array(profile_list).each do |profile|
num_compliant = 0
num_non_compliant = 0
profile_report = {}
if main_config[:custom_call]
add_custom_entries(main_config)
else
unknown_parameters = Set.new
unknown_resources = Set.new
profile_compiler.list_puppet_params([profile]).each do |fully_qualified_parameter, profile_settings|
resource_parts = fully_qualified_parameter.split('::')
param = resource_parts.pop
unless resource_parts.empty?
base_resource = resource_parts.join('::')
res = @catalog.resource("Class[#{base_resource}]")
unless res
define_resource_name = resource_parts.map { |x| x.capitalize }.join('::')
# This only finds the first instance but this limits the amount of
# work done every time this runs. Will probably need to figure out
# a better way to do this in the future.
res = @catalog.resources.find{|r| r.to_s =~ /#{define_resource_name}/}
end
end
if res.nil? && base_resource
unknown_resources << base_resource
elsif res.has_key?(param.to_sym)
current_value = res[param]
# XXX ToDo This should be improved to allow for validators to be specified
# instead of forcing regexes to be in values (as it breaks enforcement)
# ie, functions or built ins.
if profile_settings.key?('value')
expected_value = profile_settings['value']
# Allow for escaping knockout prefixes that we want to preserve in strings
# NOTE: This is horrible but less horrible than traversing all manner of
# data structures recursively.
expected_value = JSON.load(expected_value.to_json.gsub('\\--', '--'))
result = {
'compliant_value' => expected_value,
'system_value' => current_value,
}
if profile_settings.key?('identifiers')
result['identifiers'] = profile_settings['identifiers']
end
classkey = "#{res.type}[#{res.title}]"
if expected_value =~ /^re:(.+)/
section = (current_value =~ Regexp.new($1)) ? 'compliant' : 'non_compliant'
else
section = (current_value == expected_value) ? 'compliant' : 'non_compliant'
end
if section == 'compliant'
num_compliant += 1
else
num_non_compliant += 1
end
if report_types.include?(section) && !result.nil?
profile_report[section] ||= {}
profile_report[section][classkey] ||= {}
profile_report[section][classkey]['parameters'] ||= {}
profile_report[section][classkey]['parameters'][param] = result
end
end
else
unknown_parameters << fully_qualified_parameter
end
if report_types.include?('unknown_parameters') && !unknown_parameters.empty?
profile_report['documented_missing_parameters'] = unknown_parameters.to_a
end
if report_types.include?('unknown_resources') && !unknown_resources.empty?
profile_report['documented_missing_resources'] = unknown_resources.to_a
end
end
end
profile_report['custom_entries'] = @custom_entries[profile] if @custom_entries[profile]
profile_report['summary'] = summary(profile_report, num_compliant, num_non_compliant)
report['compliance_profiles'][profile] = profile_report
end
write_server_report(main_config, report)
add_file_to_client(main_config, report)
end
#
# Create a summary from a profile report.
#
def summary(profile_report, num_compliant, num_non_compliant)
report = {
'compliant' => num_compliant,
'non_compliant' => num_non_compliant
}
if profile_report['documented_missing_parameters']
report['documented_missing_parameters'] = profile_report['documented_missing_parameters'].count
end
if profile_report['documented_missing_resources']
report['documented_missing_resources'] = profile_report['documented_missing_resources'].count
end
total_checks = num_non_compliant + num_compliant
report['percent_compliant'] = total_checks == 0 ? 0 : ((num_compliant.to_f/total_checks) * 100).round(0)
return report
end
def add_custom_entries(main_config)
# XXX ToDo
# We need to decide if this is actually necessary. If the compliance profiles are authoritative
# then having to evaluate a catalog to get all values makes no sense
file_info = custom_call_file_info
value = {
"identifiers" => main_config[:custom][:identifier],
"location" => %(#{file_info[:file]}:#{file_info[:line]})
}
if main_config[:custom][:notes]
value['notes'] = main_config[:custom][:notes]
end
profile = main_config[:custom][:profile]
resource_name = %(#{@context.resource.type}::#{@context.resource.title})
unless (@custom_entries.key?(profile))
@custom_entries[profile] = {}
end
unless (@custom_entries[profile].key?(resource_name))
@custom_entries[profile][resource_name] = []
end
unless @custom_entries[profile][resource_name].include?(value)
@custom_entries[profile][resource_name] << value
end
end
def custom_call_file_info
file_info = {
:file => @context.source.file,
# We may not know the line number if this is at Top Scope
:line => @context.source.line || '<unknown>',
}
# If we don't know the filename, guess....
# This is probably because we're running in Puppet 4
if @context.is_topscope?
# Cast this to a string because it could potentially be a symbol from
# the bowels of Puppet, or 'nil', or whatever and is purely
# informative.
env_manifest = "#{@context.environment.manifest}"
if env_manifest =~ /\.pp$/
file = env_manifest
else
file = File.join(env_manifest,'site.pp')
end
else
filename = @context.source.name.split('::')
filename[-1] = filename[-1] + '.pp'
file = File.join(
'<estimate>',
"#{@context.environment.modulepath.first}",
filename
)
end
return file_info
end
def debug(message)
return
end
def codebase
"compliance_map"
end
def environment
@context.environment.name.to_s
end
def lookup_fact(fact)
begin
@context.call_function('dig', [@context.lookupvar('facts'), *fact.split('.')])
rescue ArgumentError
nil
end
end
def module_list
@context.environment.modules.map { |obj| { "name" => obj.metadata["name"], "version" => obj.metadata["version"] } }
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Users', type: :request do
describe 'UserCreateAPI' do
it 'ユーザー作成できる' do
post '/api/v1/signup', params: { user: { name: 'user', email: 'test@example.com', password: 'password', password_confirmation: 'password' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'user作成しました'
end
it 'password と password_confirmation 不一致で作成できない' do
post '/api/v1/signup', params: { user: { name: 'user', email: 'test@example.com', password: 'password', password_confirmation: 'pass' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['err_msg'][0]).to eq "Password confirmation doesn't match Password"
end
end
describe 'UserShowAPI' do
before do
@users = create_list(:user, 2)
end
it 'ユーザ1取得できる' do
get "/api/v1/users/#{@users[0].id}"
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['user']['name']).to eq @users[0].name
expect(json['user']['email']).to eq @users[0].email
end
it 'ユーザ2取得できる' do
get "/api/v1/users/#{@users[1].id}"
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['user']['name']).to eq @users[1].name
expect(json['user']['email']).to eq @users[1].email
end
it '全ユーザー所得できる' do
get '/api/v1/users'
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json.length).to eq 2
end
end
describe 'UserUpdateAPI' do
let(:user) { create(:user) }
it 'ユーザの name 変更できる' do
put "/api/v1/users/#{user.id}", params: { user: { name: 'update' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['user']['name']).to eq 'update'
end
it 'ユーザの email 変更できる' do
put "/api/v1/users/#{user.id}", params: { user: { email: 'update@example.com' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['user']['email']).to eq 'update@example.com'
end
it 'ユーザの password 変更できる' do
put "/api/v1/users/#{user.id}", params: { user: { password: 'testtest', password_confirmation: 'testtest' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'updateしました'
end
it 'ユーザの password confirmation不一致で変更できない' do
put "/api/v1/users/#{user.id}", params: { user: { password: 'testtest', password_confirmation: 'test' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['err_msg'][0]).to eq "Password confirmation doesn't match Password"
end
end
describe 'UserSessionAPI' do
let(:user) { create(:user) }
it 'ログインできる' do
get '/api/v1/login', params: { user: { email: user.email, password: user.password } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'ログインしました'
expect(json['token'].empty?).to eq false
end
it 'email が間違ってログインできない' do
get '/api/v1/login', params: { user: { email: 'test', password: user.password } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'メールアドレス or パスワードが間違っています'
end
it 'password が間違ってログインできない' do
get '/api/v1/login', params: { user: { email: user.email, password: 'test' } }
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'メールアドレス or パスワードが間違っています'
end
end
describe 'UserDeleteAPI' do
let(:user) { create(:user) }
it 'ユーザ削除できる' do
delete "/api/v1/users/#{user.id}"
json = JSON.parse(response.body)
expect(response.status).to eq 200
expect(json['msg']).to eq 'user削除しました'
end
end
end
|
class ChangeLadyDoctor < ActiveRecord::Migration
def change
change_column :lady_doctors, :name, :string, :null => false
change_column :lady_doctors, :doctor_number, :integer, :null => false
end
end
|
class Band < ActiveRecord::Base
attr_accessible :name, :artist_ids
validates :name, presence: true
has_many :albums
has_many :tracks, through: :albums
has_many :songs, through: :tracks
has_many :memberships
has_many :artists, :through => :memberships
end |
class Spawner
attr_accessor :inputs, :random, :shape, :previous_nodes
def initialize(inputs, shape, random)
@random = random
@shape = shape
@inputs = inputs
end
def spawn
@previous_nodes = inputs
shape.map do |layer_nodes|
layer = build_layer(layer_nodes)
@previous_nodes += layer_nodes
layer
end
end
private
def build_layer(layer_nodes)
layer = []
layer_nodes.times do
layer << build_node_weights
end
layer
end
def build_node_weights
weights = []
previous_nodes.times do
weights << random.rand
end
weights
end
end
class WeightRandomizer
attr_accessor :random
def initialize(seed = nil)
@random = seed ? Random.new(seed) : Random.new
end
def rand
(random.rand - 0.5) * 10
end
end
|
class CreateRaids < ActiveRecord::Migration[5.2]
def change
create_table :raids do |t|
t.references :gym, foreign_key: true
t.string :boss
t.datetime :time
t.integer :remaining_time, default: 44
t.boolean :expired, default: false
t.timestamps
end
end
end
|
class CoursesController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response
def index
courses = Course.all
render json: courses, include: ['chapters', 'quiz_questions', 'quiz_questions.quiz_answers']
end
def show
course = find_course
render json: course
end
private
def find_course
Course.find(params[:id])
end
def render_not_found_response
render json: { error: "Course not found" }, status: :not_found
end
end
|
class Subject < ActiveRecord::Base
attr_accessible :abbr, :name, :alias
#alias for this subject, i.e. "cs" for computer science
validates :abbr, presence:true, uniqueness: { case_sensitive: false}
has_many :sessions, :through => :courses
has_many :courses
def toString
self.abbr + " - " + self.name
end
def instructors_by_count
retarray = []
instructorHash = {}
for course in self.courses
for section in course.sections
for instructor in section.instructors
if instructorHash.has_key? instructor
instructorHash[instructor] += 1
else
instructorHash[instructor] = 1
end
end
end
end
instructorHash.sort_by{|k,v| v}
instructorHash.each_key {|key| retarray << key }
return retarray
end
searchable do
text :name, :boost => 2
text :abbr, :boost => 2
text :course_names do
courses.map(&:name)
end
text :instructor_names do
instructors_by_count.map(&:name)
end
end
end
|
=begin
#===============================================================================
Title: Shared EXP
Author: Hime
Date: May 17, 2013
--------------------------------------------------------------------------------
** Change log
May 17, 2013
- removed unnecessary type casting
May 13, 2013
- Initial release
--------------------------------------------------------------------------------
** Terms of Use
* Free to use in non-commercial projects
* Contact me for commercial use
* No real support. The script is provided as-is
* Will do bug fixes, but no compatibility patches
* Features may be requested but no guarantees, especially if it is non-trivial
* Credits to Hime Works in your project
* Preserve this header
--------------------------------------------------------------------------------
** Description
This script changes exp gain after battle to distribute the total exp
based on the number of alive battle members in the party.
One actor in the battle will receive all of the exp, whereas if there are
four actors in the battle they will each receive a quarter.
--------------------------------------------------------------------------------
** Installation
Place this script below Materials and above Main
--------------------------------------------------------------------------------
** Usage
Plug and play
#===============================================================================
=end
$imported = {} if $imported.nil?
$imported["TH_SharedExp"] = true
#===============================================================================
# ** Configuration
#===============================================================================
module TH
module Shared_Exp
end
end
#===============================================================================
# ** Rest of script
#===============================================================================
class Game_Troop < Game_Unit
alias :th_shared_exp_exp_total :exp_total
def exp_total
total = th_shared_exp_exp_total
return apply_exp_modifiers(total)
end
def apply_exp_modifiers(total)
return total / $game_party.alive_members.size
end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: yh_photo_fr_ynas
#
# id :bigint(8) not null, primary key
# action :string
# service_type :string
# content_id :string
# date :date
# time :time
# urgency :string
# category :string
# class_code :string
# attriubute_code :string
# source :string
# credit :string
# region :string
# title :string
# comment :string
# body :string
# picture :string
# taken_by :string
# created_at :datetime not null
# updated_at :datetime not null
#
class YhPhotoFrYna < ApplicationRecord
validates_uniqueness_of :content_id
def source_path
require 'date'
today = Date.today
today_string = today.strftime('%Y%m%d')
@filename_date = content_id.split('/').last.scan(/\d{8}/).first
"/wire_source/205_PHOTO_FR_YNA/#{@filename_date}"
# "/Volumes/211.115.91.190/101_KOR/#{Issue.last.date_string}"
# "/Volumes/211.115.91.190/203_GRAPHIC/#{Issue.last.date_string}"
end
def full_size_path
return unless picture
full_size = picture.split(' ').first
source_path + "/#{full_size}"
end
def preview_path
return unless picture
preview = picture.split(' ')[1]
source_path + "/#{preview}"
end
def thumb_path
return unless picture
thumb = picture.split(' ').last
source_path + "/#{thumb}"
end
def taken(user)
self.taken_by = user.name
save
end
def self.delete_week_old(today)
one_week_old = today.days_ago(3)
YhPhotoFrYna.all.each do |photo_fr_yna|
photo_fr_yna.destroy if photo_fr_yna.created_at < one_week_old
end
end
end
|
class AddEmailbodyToRedeemable < ActiveRecord::Migration
def change
add_column :redeemables, :email_body, :text
add_column :redeemables, :go_to_link, :string
end
end
|
class ImagesController < AttachmentsController
skip_before_filter :verify_authenticity_token
before_action :set_image, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# POST /attachments
# POST /attachments.json
def create
unless params[:id].present?
@image = Image.new(image_params)
@image.save
else
@image = Image.find_or_initialize_by(id: params[:id])
@image.update(image_params)
end
authorize! :edit, @image.attachable
respond_to do |format|
if !@image.errors.present?
format.html { redirect_to @image, notice: 'Image was successfully created.' }
format.json { render :show, status: :created, location: @image }
format.js { }
else
format.html { render :new }
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /attachments/1
# PATCH/PUT /attachments/1.json
def update
respond_to do |format|
if @image.update(image_params)
format.html { redirect_to @image, notice: 'Attachment was successfully updated.' }
format.json { render :show, status: :ok, location: @image }
format.js { }
else
format.html { render :edit }
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
# DELETE /attachments/1
# DELETE /attachments/1.json
def destroy
@image.destroy
respond_to do |format|
format.html { redirect_to attachments_url, notice: 'Image was successfully destroyed.' }
format.json { head :no_content }
format.js { }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_image
@image = Image.find(params[:id])
end
def image_params
params.permit(:asset, :type, :attachable_id, :attachable_type, :attachable, :name, :about, :link, :position, :link_text)
end
end
|
module Api
module V1
class CarsController < ApiController
before_action :set_car, only: [:show, :edit, :update, :destroy]
before_action do
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
# GET /cars
def index
page_size = params[:page_size]
@q = Car.all.ransack(params[:q])
@q.sorts = 'created_at DESC' if @q.sorts.empty?
@cars = @q.result
@cars = @cars.page(params[:page])
@cars = @cars.per(page_size) if !page_size.blank?
render_success(:index, :ok,nil,@cars)
end
# GET /cars/:id
def show
end
# GET /cars/new
def new
@car = Car.new
end
# GET /cars/:id/edit
def edit
end
# POST /cars
def create
@car = Car.new(car_params)
@car_type = CarsType.find (params[:car][:cars_type_id])
@car.cars_type = @car_type
if @car.valid? && @car.save
render_success(:show, :created)
else
render_validation_error(:show, t('text.car_can_not_be_created'), 204)
end
end
# PATCH/PUT /cars/:id
def update
if @car.update(car_params)
render_success(:show, :updated)
else
render_validation_error(:show, t('text.car_can_not_be_updated'), 3000)
end
end
# DELETE /cars/:id
def destroy
if @car.destroy
render_success(:show, :deleted)
else
render_validation_error(:show, t('text.car_can_not_be_deleted'),3000)
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_car
@car = Car.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def car_params
params.require(:car).permit(:name, :horsepower, :price, :cars_type_id)
end
end
end
end
|
class CreateSearches < ActiveRecord::Migration[5.2]
def change
create_table :searches do |t|
t.string :keywords
t.string :student_name
t.integer :result_min
t.integer :result_max
t.string :comment
t.string :assignment
t.timestamps
end
end
end
|
Pod::Spec.new do |s|
s.name = "DDTCPClient"
s.version = "0.0.7"
s.summary = "A client of socket"
s.homepage = "https://github.com/longxdragon/DDTCPClient"
s.license = "MIT"
s.author = { "longxdragon" => "longxdragon@163.com" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/longxdragon/DDTCPClient.git", :tag => "#{s.version}" }
s.source_files = "Source/DDTCPClient/*.{h,m}"
s.framework = "Foundation"
s.requires_arc = true
s.dependency 'CocoaAsyncSocket', '~> 7.6.2'
# s.static_framework = true
end
|
require 'test_helper'
class CollaborationTest < ActiveSupport::TestCase
setup do
setup_default_profiles
@owner = @dragon
@collaborator = @lion
@submission = submissions(:dragon_lion_collaboration_image_1)
end
test "cannot have duplicate profiles for the same submission" do
assert_no_difference 'Collaboration.count' do
Collaboration.create(profile: @collaborator, submission: @submission)
assert_raises ActiveRecord::RecordInvalid do
@submission.collaborators << @collaborator
end
end
end
test "notifications should be sent to collaborators after creation" do
submission = submissions(:dragon_image_1)
assert_difference 'Notification.count', 2 do
submission.collaborators << @donkey
submission.collaborators << @lion
end
end
test "notifications should not be sent to the submission creator after creation" do
assert_no_difference 'Notification.count' do
submission = Submission.create(profile: @owner)
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'associations' do
it { is_expected.to respond_to(:galleries) }
end
describe 'validations' do
context 'should be valid' do
it { expect(create(:user)).to be_valid }
end
context 'shouldn\'t be valid' do
it 'should not allow spaces in the email' do
expect { create :user, email: 'any user@example.com' }
.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
end
|
class Cart < ApplicationRecord
has_many :cart_items, dependent: :destroy
validates_associated :cart_items
def add_product(dish)
current_item = cart_items.find_by(dish_id: dish.id)
if (current_item)
current_item.quantity += 1
else
current_item = cart_items.build(dish_id: dish.id)
current_item.price = dish.price
end
current_item
end
def total_price
cart_items.to_a.sum{ |item|
item.total_price
}
end
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Resources
class Importer
DEFAULT_ENGINE = :mri
class << self
def requirement(name, *args)
const_name = "#{name.to_s.capitalize}Requirement".to_sym
requirements[name] = Requirements.const_get(const_name).new(*args)
end
def ruby_engine(engine)
@ruby_engine = engine
end
def output_path(path)
@output_path = if path.start_with?('/')
path
else
File.join(TwitterCldr::RESOURCES_DIR, path)
end
end
def locales(locs)
@locales = locs
end
def parameter(key, value)
parameters[key] = value
end
def default_params
parameters.merge(
output_path: @output_path,
locales: get_locales,
ruby_engine: @ruby_engine || DEFAULT_ENGINE
)
end
def requirements
@requirements ||= {}
end
def parameters
@parameters ||= {}
end
private
def get_locales
if ENV.include?('LOCALES')
ENV['LOCALES'].split(',').map { |loc| loc.strip.to_sym }
else
@locales
end
end
end
attr_reader :params, :requirements
def initialize(options = {})
@params = self.class.default_params.merge(options)
@requirements = self.class.requirements
end
def can_import?
importability_errors.empty?
end
def import
if can_import?
puts "Importing #{name}..."
prepare
execute
else
raise "Can't import #{name}: #{importability_errors.first}"
end
end
def prepare
before_prepare
requirements.each { |_, req| req.prepare }
after_prepare
end
private
def name
@name ||= self.class.name
.split('::').last
.chomp('Importer')
.gsub(/([A-Z])([a-z])/) { " #{$1.downcase}#{$2}" }
.strip
.tap { |n| n << 's' unless n.end_with?('s') }
end
def importability_errors
@importability_errors ||= [].tap do |errors|
errors << 'incompatible RUBY_ENGINE' unless compatible_engine?
end
end
def compatible_engine?
case params.fetch(:ruby_engine)
when :mri
RUBY_ENGINE == 'ruby'
when :jruby
RUBY_ENGINE == 'jruby'
else
false
end
end
def before_prepare
end
def after_prepare
end
end
end
end
|
FactoryGirl.define do
factory :contestant do
sequence :email do |n|
"valid#{n}@example.com"
end
password 'supersecret'
first_name 'Jenny'
last_name 'Smith'
public_name 'jenny from the block'
phone '5558675309'
end
factory :admin, class: Contestant do
sequence :email do |n|
"admin#{n}@example.com"
end
password "iwilljudgeyou"
first_name "Judge"
sequence :last_name do |n|
"the #{ActiveSupport::Inflector.ordinalize(n)}"
end
sequence :public_name do |n|
"Judge the #{ActiveSupport::Inflector.ordinalize(n)}"
end
admin true
end
end |
# Ride >- Driver ✅
# Ride >- Passenger ✅
# Driver -< Ride >- Passenger
class Ride
attr_reader :driver, :passenger
@@all = []
def initialize(pick_up, destination, cost, driver, passenger)
@pick_up = pick_up
@destination = destination
@cost = cost
# ⭐️ a ride belongs to a driver
@driver = driver
# ⭐️ a ride belongs to a passenger
@passenger = passenger
# ⭐️ Single Source of Truth for Rides
@@all << self
end
def self.all
@@all
end
end # Ride class
|
class MessagesController < ApplicationController
def index
@groups = current_user.groups
@group = Group.find(params[:group_id])
@message = Message.new
@messages = current_user.messages
respond_to do |format|
format.html
format.json {
@new_messages = @group.messages.where('id > ?', params[:message][:id].to_i)
}
end
end
def new
end
def create
@group = Group.find(params[:group_id])
@message = Message.new(message_params)
if @message.save
respond_to do |format|
format.html { redirect_to group_messages_path(@group), notice: "メッセージを作成しました" }
format.json
end
else
flash[:alert] = "テキストまたは画像を入力してください"
render :index
end
end
private
def message_params
params.require(:message).permit(:body, :image).merge(user_id: current_user.id, group_id: params[:group_id])
end
end
|
class User < ApplicationRecord
has_secure_password
has_many :answers
has_many :questions
end
|
class AddBatchWiseStudentReportIdInGeneratedReportBatches < ActiveRecord::Migration
def self.up
add_column :generated_report_batches, :batch_wise_student_report_id, :integer
add_index :generated_report_batches, :batch_wise_student_report_id, :name => "index_on_report"
end
def self.down
remove_column :generated_report_batches, :batch_wise_student_report_id
remove_index :generated_report_batches, :batch_wise_student_report_id, :name => "index_on_report"
end
end
|
class CreateCovers < ActiveRecord::Migration
def change
create_table :covers do |t|
t.integer :offset_x
t.integer :offset_y
t.text :source
t.integer :facebook_id
t.belongs_to :event, index: true
t.timestamps
end
end
end
|
# To take advantage of Heroku’s realtime logging, you will need to disable this buffering to have log messages sent straight to Logplex.
$stdout.sync = true
# The latest changesets to Ruby 1.9.2 no longer make the current directory . part of your LOAD_PATH
#
# http://stackoverflow.com/questions/2900370/why-does-ruby-1-9-2-remove-from-load-path-and-whats-the-alternative
#
require './main'
## There is no need to set directories here anymore;
## Just run the application
run Sinatra::Application
|
require 'tempfile'
class Emulation
def initialize(emulator, assembly)
self.emulator = emulator
self.assembly = assembly
end
def run(ram, output_addresses, cycle_count)
Tempfile.open('output') do |output_file|
Tempfile.open(['assembly', '.asm']) do |assembly_file|
assembly_file.write assembly
assembly_file.flush
Tempfile.open('script') do |script_file|
script = generate_script(File.basename(assembly_file), File.basename(output_file), ram, output_addresses, cycle_count)
script_file.write script
script_file.flush
error, status = emulator.run(script_file.path)
raise error unless error.empty? && status.success?
end
end
parse_output output_file.read
end
end
private
attr_accessor :emulator, :assembly
def generate_script(assembly_path, output_path, ram, output_addresses, cycle_count)
<<-eos
load #{assembly_path},
output-file #{output_path},
output-list #{generate_output_list(output_addresses)};
#{generate_assignments(ram)}
repeat #{cycle_count} { ticktock; }
output;
eos
end
def generate_output_list(output_addresses)
output_addresses.map { |address| "RAM[#{address}]%D2.6.2" }.join(' ')
end
def generate_assignments(ram)
ram.map { |address, value| "set RAM[#{address}] #{value}," }.join(' ')
end
def parse_output(output)
Hash[output.each_line.map(&method(:parse_output_line)).transpose]
end
def parse_output_line(line)
line.split(/\s+/).map { |field| field.slice(/-?\d+/) }.compact.map(&:to_i)
end
end
|
require 'spec_helper'
describe ContestsController do
# TODO
# check time
describe 'GET /index' do
it 'should respond failure' do
get :index
expect(response).not_to be_success
end
describe 'when contestant logged in' do
include_examples 'login contestant'
it 'should respond success' do
get :index
expect(response).to be_success
end
end
end
describe 'GET /show/:wupc' do
before do
@contest = build(:contest)
@contest.save!
end
after do
@contest.destroy
end
it 'should respond failure' do
get :show, id: @contest
expect(response).not_to be_success
end
describe 'when contestant logged in and attended the contest' do
include_examples 'login contestant'
before do
contestant.attend(@contest)
end
it 'should respond success' do
get :show, id: @contest
expect(response).to be_success
end
end
end
end
|
# Represents application's configuration
class Config < ApplicationRecord
EUR_KOEF = 70
USD_KOEF = 60
validates :koef_eur, :koef_usd, presence: true
class << self
def koef_eur
Config.last.try(:koef_eur) || EUR_KOEF
end
def koef_usd
Config.last.try(:koef_usd) || USD_KOEF
end
end
end
|
class ChangePushNumber < ActiveRecord::Migration[5.2]
def change
rename_column :pushers, :pusher_number, :pusher_id
end
end
|
def word_sizes(input)
array = input.split
hash = {}
array.each do |word|
if hash.keys.include?(word.length)
hash[word.length] += 1
else
hash[word.length] = 1
end
end
hash
end
puts word_sizes('Four score and seven.') == { 3 => 1, 4 => 1, 5 => 1, 6 => 1 }
puts word_sizes('Hey diddle diddle, the cat and the fiddle!') == { 3 => 5, 6 => 1, 7 => 2 }
puts word_sizes("What's up doc?") == { 6 => 1, 2 => 1, 4 => 1 }
puts word_sizes('') == {}
|
require "jani/from_json/movie"
FactoryGirl.define do
factory :movie, class: Jani::FromJson::Movie do
uuid "cfcce0c6-e046-429f-89c0-8a24202ecf89"
frame_height 360
frame_width 640
fps 13
pixel_ratio 2
loading_banner nil
postroll_banner nil
strips []
tracking_events []
conversion_status Jani::FromJson::Movie::CONVERTED_STATUS
end
end
|
class ChangeWorkOrderPrimary < ActiveRecord::Migration
def self.up
rename_column :work_orders, :primary, :level
end
def self.down
rename_column :work_orders, :level, :primary
end
end
|
#
# Z - public procurements in Ukraine, (cc) dvrnd for texty.org.ua, 2012
#
require 'rubygems'
require 'json'
require 'sinatra'
require 'data_mapper'
require 'pony'
require 'nokogiri'
require 'open-uri'
load 'settings.rb'
load "models.rb"
load "lib/helpers.rb"
def construct_query query_conditions, params
if params[:market]
s_t = params[:market].to_i
s_t_symbol = Transaction.service_type.options[:flags][s_t]
query_conditions[:service_type] = s_t_symbol
end
if params[:buyer]
buyer_id = params[:buyer].to_i
query_conditions[:buyer_id] = buyer_id
end
if params[:seller]
seller_id = params[:seller].to_i
query_conditions[:seller_id] = seller_id
end
if params[:sum]
treshould = params[:sum].to_i * 1000000
query_conditions[:volume.gt] = treshould # search for bigger then treshould
end
# eof constructing query
query_conditions
end
def interval m
m = m.to_i
n = (m-1) * 30 + Time.now.day # days
end
def search params, limit
#make query
if limit > 0
query_conditions = {:limit => limit}
else
query_conditions = {}
end
if params[:date_from] =~ /^\d\d\/\d\d\/\d\d\d\d$/ && params[:date_to] =~ /^\d\d\/\d\d\/\d\d\d\d$/
query_conditions[:deal_date.gt] = Date.strptime( params[:date_from], '%d/%m/%Y')
query_conditions[:deal_date.lt] = Date.strptime( params[:date_to], '%d/%m/%Y')
end
if params[:service_type] && params[:service_type] != "all" && $service_types.include?(params[:service_type].to_sym)
query_conditions[:service_type] = params[:service_type]
end
if params[:volume_from] && params[:volume_to] && params[:volume_to].to_i > params[:volume_from].to_i
query_conditions[:volume.gt] = params[:volume_from]
query_conditions[:volume.lt] = params[:volume_to]
end
if params[:key_word] && params[:key_word].split.empty? == false
key_word = "%#{params[:key_word].split}%"
query_conditions1 = query_conditions.merge({Transaction.seller.name.like => key_word })
query_conditions2 = query_conditions.merge({Transaction.buyer.name.like => key_word })
query_conditions3 = query_conditions.merge({Transaction.procurement_notice.subject.like => key_word })
tenders = Transaction.all(query_conditions1) + Transaction.all(query_conditions2) + Transaction.all(query_conditions3)
else
tenders = Transaction.all(query_conditions)
end
if params[:sort] && params[:order]
sort_param = DataMapper::Query::Operator.new(params[:sort], params[:order])
else
sort_param = :deal_date.desc
end
tenders.all(:order => [sort_param])
end
def get_news(n = 3)
rss = Nokogiri::XML(open("http://texty.org.ua/mod/news/?view=rss"))
news = rss.xpath('//xmlns:item').map do |i|
{:title => i.xpath('xmlns:title').text, :url => i.xpath('xmlns:link').text}
end
news.first(n)
end
################# routes for main pages ######################
configure do
# set cache timelife for static files
# set :static_cache_control, [:public, {:max_age => 300}]
end
# main page going ...
get '/' do
@title = 'Головна сторінка: пошук по базі даних тендерів, 2008-2014 рік'
@url = $api_url
@page_js = partial :"_main_js"
# make array with short description of all service types (see models.rb)
@service_types = Transaction.service_type.options[:flags].map do |flag|
next if flag == :unknown
$service_types[flag][1]
end
@news = get_news
erb :container_main
end
#page for entity
get '/buyer/:id' do
halt 500 unless id = params[:id].to_i
b = Buyer.get(id)
name = b.name
role = 'buyer'
p_role = 'seller'
@url = $api_url
# obj vars - for templates
@title = "Замовник: #{name} - Пошук по базі даних тендерів, 2008-2012 рік"
@header1 = 'кому платила ця установа?'
@header2 = 'за що платила?'
# find data for charts
@page_js = partial(:"_firm_js", { :url => @url, :chart_title2 => "ЩОРІЧНІ ОБ'ЄМИ",
:chart_title3 => "НАЙБІЛЬШІ ОТРИМУВАЧІ КОШТІВ",
:role => role, :id => id})
result = []
# get total for all deals
sum, count = Transaction.all(:buyer_id => id).aggregate(:volume.sum, :all.count)
# , but limit number of returned deals to 100
# TODO: add possibility to download all deals in zipped, csv - format
deals = Transaction.all(:buyer_id => id, :limit => 100, :order => [:deal_date.desc])
#sum, count = deals.aggregate(:volume.sum, :all.count)
deals.each do |deal|
pn = deal.procurement_notice
result << { :seller => {:name => deal.seller.name.limit_words(32), :id=> deal.seller_id },
# cut long words, after some treshold
:subject => pn.subject.limit_words(64),
:id => deal.id,
:date => deal.deal_date,
# volume - in thousands
:volume => "%.1f" % (deal.volume / 1000) }
end
erb :container_firm, :locals => {:name => name.limit_words(22),
# total in millions
:volume => "%.2f" % (sum / 1000000),
:dnum => count ,
:deals => result,
:role => p_role }
end
# TODO: DRY for get /buyer and get /seller
#page for entity
get '/seller/:id' do
halt 500 unless id = params[:id].to_i
b = Seller.get(id)
name = b.name
role = 'seller'
p_role = 'buyer'
@url = $api_url
# obj vars - for templates
@title = "Отримувач коштів: #{name} - Пошук по базі даних тендерів, 2008-2012 рік"
@header1 = 'Хто заплатив цій установі?'
@header2 = 'за що отримала кошти?'
# find data for charts
@page_js = partial(:"_firm_js", { :url => @url, :chart_title2 => "ЩОРІЧНІ ОБ'ЄМИ",
:chart_title3 => "НАЙБІЛЬШІ ПЛАТНИКИ",
:role => role, :id => id})
result = []
# get total for all deals
sum, count = Transaction.all(:seller_id => id).aggregate(:volume.sum, :all.count)
# , but limit number of returned deals to 100
# TODO: add possibility to download all deals in zipped, csv - format
deals = Transaction.all(:seller_id => id, :limit => 100, :order => [:deal_date.desc])
deals.each do |deal|
pn = deal.procurement_notice
result << { :seller => {:name => deal.buyer.name.limit_words(32), :id=> deal.buyer_id },
# cut long words, after some treshold
:subject => pn.subject.limit_words(64),
:id => deal.id,
:date => deal.deal_date,
:volume => "%.1f" % (deal.volume / 1000) }
end
erb :container_firm, :locals => {:name => name.limit_words(22),
:volume => "%.2f" % (sum / 1000000),
:dnum => count ,
:deals => result,
:role => p_role }
end
get '/deal/:id' do
halt 500 unless id = params[:id].to_i
@url = $api_url
@tenders_url = 'https://tender.me.gov.ua'
deal = Transaction.get(id)
proc_notice = deal.procurement_notice
buyer = { :name => deal.buyer.name, :id => deal.buyer.id }
seller = { :name => deal.seller.name, :id => deal.seller.id }
dresult = $deal_results[proc_notice.result]
dtype = $deal_types[proc_notice.type]
dmarket = $service_types[deal.service_type][0]
@title = proc_notice.subject
erb :container_deal, :locals => { :buyer => buyer, :seller => seller,
:volume => "%.1f" % (deal.volume / 1000),
:deal_date => deal.deal_date,
:deal_result => dresult,
:deal_type => dtype,
:deal_subj => proc_notice.subject,#.limit_words(64),
:deal_market => dmarket, :deal_issue => proc_notice.issue,
:deal_url => @tenders_url + proc_notice.url }
end
# web form for search
get '/search' do
@title = 'Пошук по базі даних тендерів, 2008-2012 рік'
tenders = search(params, 0)
sum, count = tenders.aggregate(:volume.sum, :all.count)
result = tenders.all( :limit => 100 )
sum ||= 0
@page_js = partial(:"_search_js", {
:url => $api_url,
:posts_start => 100,
:tenders_per_request => 100,
:number_of_tenders => count,
:params => params})
erb :container_search, :locals => {
:tenders => result,
:volume => "%.2f" % (sum / 1000000),
:dnum => count ,
:service_types => $service_types,
:date_from => params[:date_from] || Time.local(2008, 1, 1).strftime('%d/%m/%Y'),
:date_to => params[:date_to] || Time.now.strftime('%d/%m/%Y'),
:volume_from => params[:volume_from],
:volume_to => params[:volume_to],
:key_word => params[:key_word],
:service_type => params[:service_type] || "all",
:sort => params[:sort] || "deal_date",
:order => params[:order] || "desc"
}
end
get "/search.csv" do
tenders = search(params, 1000)
headers "Content-Disposition" => "attachment;filename=search_result_#{Time.now.strftime("%Y%m%d%H%M%S")}.csv",
"Content-Type" => "application/octet-stream"
result = CSV.generate do |csv|
csv << ['Замовник', 'Виконавець', 'Предмет', 'Дата', 'Сума']
tenders.each do |tender|
csv << [tender.buyer.name, tender.seller.name, tender.procurement_notice.subject, tender.deal_date, tender.volume]
end
end
end
# form for subscribe
get "/subscribe" do
@title = 'XYZ - Підписка на оновлення за ключевим словом по базі даних тендерів'
@subscribers = Subscriber.all
erb :container_subscriber
end
post "/subscribe" do
@title = 'XYZ - Підписка на оновлення за ключевим словом по базі даних тендерів'
subscriber = Subscriber.new(:email => params[:email], :key_words => params[:key_words], :last_date => Transaction.first(:order => [:deal_date.desc]).deal_date)
if subscriber.save
@message = "Ваша заявку на підписку прийнята. В найближчий час Вам прийде повідомлення на email з підтвердженням."
Pony.mail(:to => subscriber.email , :from => 'no-reply@ztexty.org.ua', :subject => 'hi', :body => 'Hello there.')
else
@errors = subscriber.errors.full_messages
end
erb :container_subscriber
end
# page with top-100 sellers and top-100 buyers
get "/statistics" do
@title = 'XYZ - Топ-100 замовників та виконавців'
@page_js = partial :"_statistics_js"
@top_buyers = repository(:default).adapter.select("SELECT buyers.id, buyers.name, sum(transactions.volume) AS total_volume FROM transactions INNER JOIN buyers ON transactions.buyer_id = buyers.id GROUP BY buyers.id ORDER BY total_volume DESC LIMIT 100" )
@max_buyer_value = (@top_buyers.first)[:total_volume]
@top_sellers = repository(:default).adapter.select("SELECT sellers.id, sellers.name, sum(transactions.volume) AS total_volume FROM transactions INNER JOIN sellers ON transactions.seller_id = sellers.id GROUP BY sellers.id ORDER BY total_volume DESC LIMIT 100" )
@max_seller_value = (@top_sellers.first)[:total_volume]
erb :container_statistics
end
get "/test_send_mail" do
Pony.mail(:to => "0979029562@mail.ru" , :from => 'no-reply@ztexty.org.ua', :subject => 'hi', :body => 'Hello there.')
erb "Send mail"
end
# ######################### API start
# TODO: rewrite mess with query conditions below in 'post '/''
# main query
post '/query' do
#n = params[:monthes].to_i * 30 # days
#m = params[:monthes].to_i
#n = (m-1) * 30 + Time.now.day # days
n = interval params[:monthes]
# start constructing query
query_conditions = { :deal_date.gt => Date.today - n,
:deal_date.lt => Date.today }
query_conditions = construct_query(query_conditions, params)
sum, count = Transaction.all( query_conditions ).aggregate(:volume.sum,
:all.count)
#send JSON with total volume and number of deals for query
{:volume => sum, :number => count }.to_json
end
# send data to fill top table on first page
post '/table' do
limit = 50
#n = params[:monthes].to_i * 30 # days
n = interval params[:monthes]
# start constructing query
query_conditions = { :deal_date.gt => Date.today - n,
:deal_date.lt => Date.today,
:order => [:volume.desc], :offset => params[:start].to_i, :limit => limit }
query_conditions = construct_query(query_conditions, params)
ts = Transaction.all( query_conditions )
result = []
ts.each do |deal|
buyer = deal.buyer.name
seller = deal.seller.name
result << [[buyer, deal.buyer_id], [seller, deal.seller_id ],
[deal.deal_date, nil], [deal.volume, deal.id]]
end
#send JSON with table result
result.to_json
end
# route for interactive autocomplete form
post '/actor' do
if params[:buyer]
clas = Buyer
name = params[:buyer]
elsif params[:seller]
clas = Seller
name = params[:seller]
else
return [].to_json # cant find meaningful var in post request
end
if name and name.length < 512 and name.length > 5
bs = clas.all(:name.like => "%#{name}%", :limit => 100)
# limit_words: cuts a names in result which is above some length
bs.map{|b| [b.id, b.name.limit_words(22)]}.to_json
end
end
# produce data for little charts on firm's page
# to optimise, i broke it down to raw SQL
post '/chart' do
player = params[:player].gsub(/[']/, '')
id = params[:id].to_i
rez = []
if params[:type].to_s == 'time'
# find volumes for each years from 2008 to 2011
volumes = repository(:default).adapter.select("SELECT SUM(`volume`),
YEAR(`deal_date`) as y FROM `transactions`
WHERE `#{player}_id` = #{id} GROUP BY y")
# make last year automatic
2008.step(Time.new.year, 1) do |year|
if e = volumes.detect{|e| e['y'] == year}
rez << [year, e['sum(`volume`)']]
else
rez << [year, 0]
end
end
elsif params[:type].to_s == 'diagramm'
# find 5 most successfull partners
other_role = player == "buyer" ? "seller" : "buyer"
table_name = other_role + 's'
r = repository(:default).adapter.select("SELECT #{table_name}.name, sum(transactions.volume) AS total_volume, #{table_name}.id FROM transactions INNER JOIN #{table_name} ON transactions.#{other_role}_id = #{table_name}.id and transactions.#{player}_id = ? GROUP BY #{table_name}.id ORDER BY total_volume DESC LIMIT 5", id )
rez = r.map{|e| [e['name'], e['total_volume'], e['id']] }
end
rez.to_json
end
# return result of the search
post '/search' do
tenders = search(params, 0)
result = tenders.all( :offset => params[:start].to_i, :limit => 100 )
erb :"_search_result", :layout => false, :locals => { :tenders => result }
end
# ############# API end #######################
|
Sequel.migration do
change do
create_table :work_queue do
primary_key :id
String :task
String :data
end
end
end
|
class HostsController < ApplicationController
before_action :authenticate_user!
def update
@host = current_user.host
if @host.update(host_params)
flash[:success] = "Host updated!"
end
redirect_to root_path
end
private
def host_params
params.require(:host).permit(:address_1, :state, :zipcode, :name)
end
end
|
class CreatePinPads < ActiveRecord::Migration
# 密码键盘 password_pad
#接口 interface
#语音 voice
#防窥罩 anti_peep_cover
def self.up
create_table :pin_pads do |t|
t.string "interface"
t.string "voice"
t.string "anti_peep_cover"
t.text "memo"
t.timestamps
end
end
def self.down
drop_table :pin_pads
end
end
|
require 'rails_helper'
RSpec.describe ProposalSituation, type: :model do
it 'has a valid factory' do
expect(create :proposal_situation).to be_valid
end
it { should validate_presence_of :name }
it { should have_many :proposals }
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# VM ONE ==============================================================
config.vm.define "one" do |one|
one.vm.box = "ubuntu/bionic64"
one.vm.hostname = "one"
one.vm.provision "shell", path: "prov-one.sh"
one.vm.network "private_network", ip: "192.168.10.10"
end
# VM TWO ==============================================================
config.vm.define "two" do |two|
two.vm.box = "ubuntu/bionic64"
two.vm.hostname = "two"
two.vm.provision "shell", path: "prov-two.sh"
two.vm.network "private_network", ip: "192.168.10.20"
end
# COMMON OPTIONS
config.vm.provider "virtualbox" do |vb|
# Display the VirtualBox GUI when booting the machine
vb.gui = false
# # Customize the amount of memory on the VM:
vb.memory = "1024"
end
end
|
# bubble sort works by swapping value pairs
# we make a number of passes through the array we want to sort
# at each pass, the following happens:
# for every index (starting with 0):
# compary array[index] and array[index + 1]
# if the first is larger than the second, swap them.
# we do as many passes as needed to reach a stable state.
def bubble_sort(array)
swapped = nil
loop do
swapped = false
for i in (1...array.size)
if array[i] < array[i - 1]
swap_values_at_indices(i, i - 1, array)
swapped = true
end
end
break if swapped == false
end
array
end
def swap_values_at_indices(index1, index2, array)
stored_value = array[index1]
array[index1] = array[index2]
array[index2] = stored_value
end
array = [10, 5, 3, 1, 2, 10]
p bubble_sort(array) # [1, 2, 3, 5, 10, 10]
|
class Test1
# Example:
# Test1.new.add(1, 2)
# => 3
# Test1.new.add(1, "something")
# => TypeError: String can't be coerced into Fixnum
def add(num1, num2)
num1 + num2
end
end |
json.shops do
json.array! @shops do |shop|
json.id shop.id
json.name shop.name
json.books_sold_count shop.shop_items.with_state(:sold).joins(book: :publisher).where("publishers.id = ?", @publisher_id).count
json.books_in_stock count_available_books_in_store(shop)
end
end |
class AddArticleReferenceToEntry < ActiveRecord::Migration[4.2]
def change
add_reference :entries, :article, index: true, foreign_key: true
end
end
|
module Mongoid::TaggableWithContext::AggregationStrategy
module RealTime
extend ActiveSupport::Concern
included do
set_callback :create, :after, :increment_tags_agregation
set_callback :save, :after, :update_tags_aggregation
set_callback :destroy, :before, :store_reference_to_tag_counter
set_callback :destroy, :after, :decrement_tags_aggregation
end
module ClassMethods
# Collection name for storing results of tag count aggregation
def aggregation_collection_for(context)
"#{collection_name}_#{context}_aggregation"
end
def tags_for(context, conditions={})
conditions = {:sort => '_id'}.merge(conditions)
db.collection(aggregation_collection_for(context)).find({:value => {"$gt" => 0 }}, conditions).to_a.map{ |t| t["_id"] }
end
# retrieve the list of tag with weight(count), this is useful for
# creating tag clouds
def tags_with_weight_for(context, conditions={})
conditions = {:sort => '_id'}.merge(conditions)
db.collection(aggregation_collection_for(context)).find({:value => {"$gt" => 0 }}, conditions).to_a.map{ |t| [t["_id"], t["value"]] }
end
end
private
def need_update_tags_aggregation?
!changed_contexts.empty?
end
def changed_contexts
tag_contexts & changes.keys.map(&:to_sym)
end
def increment_tags_agregation
# if document is created by using MyDocument.new
# and attributes are individually assigned
# #changes won't be empty and aggregation
# is updated in after_save, so we simply skip it.
return unless changes.empty?
# if the document is created by using MyDocument.create(:tags => "tag1 tag2")
# #changes hash is empty and we have to update aggregation here
tag_contexts.each do |context|
coll = self.class.db.collection(self.class.aggregation_collection_for(context))
field_name = self.class.tag_options_for(context)[:array_field]
tags = self.send field_name || []
tags.each do |t|
coll.update({:_id => t}, {'$inc' => {:value => 1}}, :upsert => true)
update_tag_counter(t, context, 1)
end
end
end
def decrement_tags_aggregation
tag_contexts.each do |context|
coll = self.class.db.collection(self.class.aggregation_collection_for(context))
field_name = self.class.tag_options_for(context)[:array_field]
tags = self.send field_name || []
tags.each do |t|
coll.update({:_id => t}, {'$inc' => {:value => -1}}, :upsert => true)
update_tag_counter(t, context, -1)
end
end
end
def update_tags_aggregation
return unless need_update_tags_aggregation?
changed_contexts.each do |context|
coll = self.class.db.collection(self.class.aggregation_collection_for(context))
field_name = self.class.tag_options_for(context)[:array_field]
old_tags, new_tags = changes["#{field_name}"]
old_tags ||= []
new_tags ||= []
unchanged_tags = old_tags & new_tags
tags_removed = old_tags - unchanged_tags
tags_added = new_tags - unchanged_tags
tags_removed.each do |t|
coll.update({:_id => t}, {'$inc' => {:value => -1}}, :upsert => true)
update_tag_counter(t, context, -1)
end
tags_added.each do |t|
coll.update({:_id => t}, {'$inc' => {:value => 1}}, :upsert => true)
update_tag_counter(t, context, 1)
end
end
end
def store_reference_to_tag_counter
@after_destroy_operatation = true
tag_contexts.each do |context|
counter_model_name = self.class.tag_options_for(context)[:counter_in]
@tag_counter = self.send(counter_model_name) if counter_model_name
end
end
def update_tag_counter(tag, context, val)
return if @after_destroy_operation && !@tag_counter
return if tag.blank?
counter_model_name = self.class.tag_options_for(context)[:counter_in]
return unless counter_model_name
counter_model = @tag_counter
counter_model = self.send(counter_model_name) unless counter_model
return unless counter_model
counter_hash = counter_model.send(context)
return unless counter_hash
unless counter_hash[tag]
val == -1 ? false : (counter_hash[tag] = {:count => val})
else
counter_hash[tag][:count] += val
counter_hash.delete(tag) if counter_hash[tag][:counter] == 0 #this should perhaps be optional?
end
counter_model.send("#{context}=", counter_hash)
mdl = (self.send(counter_model_name).class).find(counter_model.id) #hack to avoid the Frozen Hash error
mdl.send("#{context}=", counter_hash)
mdl.save
end
end
end |
class Kcov < Formula
desc "Code coverage tool for compiled programs, Python and Bash"
homepage "http://simonkagstrom.github.com/kcov/index.html"
url "https://github.com/SimonKagstrom/kcov/archive/v36.tar.gz"
sha256 "29ccdde3bd44f14e0d7c88d709e1e5ff9b448e735538ae45ee08b73c19a2ea0b"
depends_on "cmake" => :build
depends_on "binutils"
depends_on "pkg-config"
def install
ENV.append "CXXFLAGS", "-O2"
ENV.append "CXXFLAGS", "-I#{Formula["binutils"].opt_include}"
ENV.append "LDFLAGS", "-L#{Formula["binutils"].opt_lib}"
system "cmake", ".", *std_cmake_args
system "make", "install"
end
end
|
require 'rspec'
require './lib/ingredient'
require './lib/recipe'
describe Recipe do
before do
@cheese = Ingredient.new("Cheese", "oz", 50)
@mac = Ingredient.new("Macaroni", "oz", 200)
@mac_and_cheese = Recipe.new("Mac and Cheese")
end
it "exists" do
expect(@mac_and_cheese).to be_a(Recipe)
end
it "has a name" do
expect(@mac_and_cheese.name).to eq("Mac and Cheese")
end
it "can add ingredients" do
expect(@mac_and_cheese.ingredients).to eq({})
@mac_and_cheese.add_ingredient(@cheese, 2)
@mac_and_cheese.add_ingredient(@mac, 8)
expect(@mac_and_cheese.ingredients).to eq({
@cheese => 2,
@mac => 8
})
end
it "can check needed amounts" do
@mac_and_cheese.add_ingredient(@cheese, 2)
expect(@mac_and_cheese.check_amount(@cheese)).to eq("2 oz")
@mac_and_cheese.add_ingredient(@mac, 8)
expect(@mac_and_cheese.check_amount(@mac)).to eq("8 oz")
expect(@mac_and_cheese.check_amount("steak")).to eq(nil)
end
it "can find total calories" do
expect(@mac_and_cheese.total_calories).to eq(0)
@mac_and_cheese.add_ingredient(@cheese, 2)
@mac_and_cheese.add_ingredient(@mac, 8)
expect(@mac_and_cheese.total_calories).to eq(1700)
end
end
|
class Bid < ActiveRecord::Base
validates_presence_of :item_id, :color, :amount, :timestamp
belongs_to :item
def self.external_exists?(external_id)
Bid.exists? external_id: external_id
end
end
|
# frozen_string_literal: true
require 'selenium-webdriver'
RSpec.configure do |config|
config.before do |example|
options = Selenium::WebDriver::Options.chrome(browser_version: '94',
platform_name: 'Windows 10',
timeouts: {script: 90})
options.add_option("sauce:options",
{name: example.full_description,
build: "Ruby-Visual-#{Time.now.to_i}",
username: ENV['SAUCE_USERNAME'],
accessKey: ENV['SAUCE_ACCESS_KEY']})
options.add_option("sauce:visual",
{apiKey: ENV['SCREENER_API_KEY'],
projectName: 'Sauce Demo Ruby',
viewportSize: '1280x1024'})
# On complex websites and browsers like internet explorer 11, you might need to increase
# scripts and connection timeout in order for visual to be able to capture UI snapshot
http_client = Selenium::WebDriver::Remote::Http::Default.new
http_client.read_timeout = 90 # seconds
skip('currently does not support Selenium 4')
@driver = Selenium::WebDriver.for :remote,
url: 'https://hub.screener.io/wd/hub',
capabilities: options,
http_client: http_client
end
config.after do
unless @driver.nil?
@driver.execute_script '/*@visual.end*/'
@driver.quit
end
end
end
|
class PurchasesController < ApplicationController
before_action :authenticate_user!, only: :create
before_action :its_admin?, only: [ :update, :dashboard, :destroy ]
def create
product = Product.find(params[:product_id])
purchase = Purchase.new
purchase.product = product
purchase.user = current_user
purchase.status = :pending
purchase.price = product.price
if product.available? && purchase.save
balance = Purchase.balance(current_user)
PurchaseNotifierMailer.notify_account_balance(current_user, balance).deliver_now if balance > 10_000
product.update_stock
flash[:notice] = 'Tu compra ha sido realizada con éxito'
else
flash[:alert] = 'No ha sido posible agregar este producto a tus compras, intenta de nuevo'
end
redirect_to root_path(category_id: product.category_id)
end
def update
purchase = Purchase.find(params[:id])
if purchase.update(status: :paid)
flash[:notice] = 'Tu compra ha sido pagada con éxito'
else
flash[:alert] = 'No ha sido posible pagar esta compra, intenta de nuevo'
end
redirect_to profile_path(id: params[:user_id])
end
def dashboard
@users = User.all
end
def destroy
@purchase = Purchase.find(params[:id])
@purchase.destroy
flash[:notice] = 'La compra fue elminada con éxito'
redirect_to profile_path(id: params[:user_id])
end
private
def its_admin?
unless current_user.admin?
redirect_to root_path, alert: "Acceso denegado, no posee permisos como administrador"
end
end
end
|
require 'json'
require "net/http"
require "uri"
MAX_ATTEMPTS=50
TIMESTAMP = Time.now.strftime('%FT%T').gsub(/:|-/,'')
PARAMETERS = {SSHKeyName: ENV['SSHKEYNAME']}
def get_expanded_params
expanded_params = '--parameters '
PARAMETERS.each_pair { |key, value| expanded_params << "ParameterKey=#{key},ParameterValue=#{value} " }
expanded_params
end
def get_stack_name(template_file)
template_file.split('.').first.gsub('_','') + TIMESTAMP
end
def get_stack_attributes(stack_name)
state_output = `aws cloudformation describe-stacks --stack-name #{stack_name} 2>&1`
if state_output.match /does not exist/
{'StackStatus' => 'ENOENT'}
else
JSON.parse(state_output)['Stacks'].first
end
end
def get_stack_state(stack_name)
get_stack_attributes(stack_name)['StackStatus'].inspect
end
def wait_for_stack(stack_name)
while get_stack_state(stack_name) == '"CREATE_IN_PROGRESS"'
get_stack_state(stack_name)
puts "Waiting for stack #{stack_name} ..."
sleep 10
end
end
def delete_stack(stack_name)
sh "aws cloudformation delete-stack --stack-name #{stack_name}"
while get_stack_state(stack_name) != '"ENOENT"'
get_stack_state(stack_name)
puts "Deleting stack #{stack_name} ..."
sleep 10
end
end
def ready?(response)
puts response.inspect
begin
puts response['location']
rescue
end
if response.nil?
return false
elsif response.class == Net::HTTPServiceUnavailable
return false
elsif response.class == Net::HTTPForbidden
return true
else
return false
end
end
def connect_to_neo(url,username, pass)
response = nil
attempts = 0
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("neo4j", "neo4j")
until ready?(response)|| attempts == MAX_ATTEMPTS
attempts += 1
sleep 10
begin
response = http.request(request)
echo response
rescue
end
end
response.body
end
def test_for_ssh_key
raise "Set the SSHKEYNAME var first" unless ENV['SSHKEYNAME']
end
desc "Publish to S3"
task :publish => [:validate, :test] do
sh "s3cmd put --acl-public *.json s3://cf-templates.neo4j.org"
end
task :validate do
Dir.glob('*.json').each do |template|
sh "aws cloudformation validate-template --template-body file:///#{Dir.pwd}/#{template}"
end
end
task :test => :validate do
test_for_ssh_key
expanded_params = get_expanded_params
Dir.glob('*.json').each do |template|
stack_name = get_stack_name(template)
sh "aws cloudformation create-stack --template-body file:///#{Dir.pwd}/#{template} --stack-name #{stack_name} --parameters #{expanded_params}"
wait_for_stack(stack_name)
begin
stack_attrs = get_stack_attributes(stack_name)
puts stack_attrs.inspect
neo4j_endpoint = stack_attrs['Outputs'].select {|output| output['OutputKey'] == 'Neo4jEndPoint' }.first['OutputValue']
db_output = connect_to_neo(neo4j_endpoint, PARAMETERS[:DBUsername], PARAMETERS[:DBPassword])
rescue Exception => e
puts "Error: #{e}"
db_output = "Something went wrong: #{e}"
end
delete_stack(stack_name)
raise "Couldn't connect to Neo4j!" unless db_output.match(/password_change/)
end
end
task :spawn do
test_for_ssh_key
template_file = 'ubuntu.json'
expanded_params = get_expanded_params
stack_name = get_stack_name(template_file)
sh "aws cloudformation create-stack --template-body file:///#{Dir.pwd}/#{template_file} --stack-name #{stack_name} --parameters #{expanded_params}"
end
|
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe "出品商品登録" do
context "出品登録できるパターン" do
it "全て条件通りの入力をすると新規登録できる" do
expect(@item).to be_valid
end
end
context "出品登録できないパターン" do
it "商品名がないと登録できない" do
@item.item_name = ""
@item.valid?
expect(@item.errors.full_messages).to include("Item name can't be blank")
end
it "商品画像がないと登録できない" do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
it "商品詳細がないと登録できない" do
@item.text = ""
@item.valid?
expect(@item.errors.full_messages).to include("Text can't be blank")
end
it"カテゴリーを選ばないと登録できない" do
@item.category_id = "1"
@item.valid?
expect(@item.errors.full_messages).to include("Category must be other than 1")
end
it "商品の状態を選ばないと登録できない" do
@item.item_status_id = "1"
@item.valid?
expect(@item.errors.full_messages).to include("Item status must be other than 1")
end
it "配送料の負担を選ばないと登録できない" do
@item.ship_cost_id = "1"
@item.valid?
expect(@item.errors.full_messages).to include("Ship cost must be other than 1")
end
it "発送元の地域を選ばないと登録できない" do
@item.prefecture_id = "1"
@item.valid?
expect(@item.errors.full_messages).to include("Prefecture must be other than 1")
end
it "発送までの日数を選ばないと登録できない" do
@item.days_to_ship_id = "1"
@item.valid?
expect(@item.errors.full_messages).to include("Days to ship must be other than 1")
end
it "販売価格がないと登録できない" do
@item.price = ""
@item.valid?
expect(@item.errors.full_messages).to include("Price can't be blank")
end
it "販売価格が全角数字だと登録できない" do
@item.price = "500"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が半角英字だと登録できない" do
@item.price = "yoshida"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が半角カタカナだと登録できない" do
@item.price = "ヨシダ"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が全角ひらがなだと登録できない" do
@item.price = "よしだ"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が全角カタカナだと登録できない" do
@item.price = "ヨシダ"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が全角漢字だと登録できない" do
@item.price = "吉田"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "販売価格が299円より小さいと登録できない" do
@item.price = "299"
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300")
end
it "販売価格が9,999,999円を超えると登録できない" do
@item.price = "10000000"
@item.valid?
expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999")
end
end
end
end |
require 'spec_helper'
module Naf
describe QueuedJob do
# Mass-assignment
[:application_id,
:application_schedule_id,
:application_type_id,
:command,
:application_run_group_restriction_id,
:application_run_group_name,
:application_run_group_limit,
:priority].each do |a|
it { should allow_mass_assignment_of(a) }
end
[:id,
:created_at,
:updated_at].each do |a|
it { should_not allow_mass_assignment_of(a) }
end
#---------------------
# *** Associations ***
#+++++++++++++++++++++
it { should belong_to(:historical_job) }
it { should belong_to(:application) }
it { should belong_to(:application_schedule) }
it { should belong_to(:application_type) }
it { should belong_to(:application_run_group_restriction) }
#--------------------
# *** Validations ***
#++++++++++++++++++++
it { should validate_presence_of(:application_type_id) }
it { should validate_presence_of(:command) }
it { should validate_presence_of(:application_run_group_restriction_id) }
it { should validate_presence_of(:priority) }
#----------------------
# *** Class Methods ***
#++++++++++++++++++++++
describe "#order_by_priority" do
let!(:high_priority_job) { FactoryGirl.create(:queued_job, priority: 1) }
let!(:low_priority_job) { FactoryGirl.create(:queued_job, priority: 2) }
let!(:low_priority_job2) { FactoryGirl.create(:queued_job, priority: 2) }
it "return records in correct order" do
Naf::QueuedJob.order_by_priority.
should == [high_priority_job, low_priority_job, low_priority_job2]
end
end
describe "#exclude_run_group_names" do
let!(:included_job) { FactoryGirl.create(:queued_job, application_run_group_name: 'test 1') }
let!(:excluded_job) { FactoryGirl.create(:queued_job, application_run_group_name: 'test 2') }
it "return queued jobs not included in the run group names" do
Naf::QueuedJob.exclude_run_group_names(['test 2']).
should == [included_job]
end
it "return all queued jobs when run group names are not specified" do
Naf::QueuedJob.exclude_run_group_names([]).
should == [included_job, excluded_job]
end
end
describe "#runnable_by_machine" do
let!(:included_job) { FactoryGirl.create(:queued_job, application_run_group_name: 'test 1') }
let!(:excluded_job) { FactoryGirl.create(:queued_job, application_run_group_name: 'test 2') }
it "return queued jobs not included in the run group names" do
Naf::QueuedJob.exclude_run_group_names(['test 2']).
should == [included_job]
end
it "return all queued jobs when run group names are not specified" do
Naf::QueuedJob.exclude_run_group_names([]).
should == [included_job, excluded_job]
end
end
describe "#prerequisites_finished" do
let!(:prerequesite_needed_historical_job) { FactoryGirl.create(:job, finished_at: nil) }
let!(:prerequesite_historical_job) { FactoryGirl.create(:job) }
let!(:historical_job) { FactoryGirl.create(:job) }
let!(:prerequesite_needed_queued_job) {
FactoryGirl.create(:queued_job, id: prerequesite_needed_historical_job.id,
historical_job: prerequesite_needed_historical_job)
}
let!(:queued_job) {
FactoryGirl.create(:queued_job, id: historical_job.id,
historical_job: historical_job)
}
let!(:prerequesite) {
FactoryGirl.create(:historical_job_prerequesite, prerequisite_historical_job: prerequesite_historical_job,
historical_job: prerequesite_needed_historical_job)
}
it "return queued jobs not included in the run group names" do
Naf::QueuedJob.prerequisites_finished.
should == [queued_job]
end
end
describe "#weight_available_on_machine" do
let!(:machine) { mock_model(Machine) }
let!(:cpu_affinity_slot) { mock_model(MachineAffinitySlot, affinity_id: 4, affinity_parameter: 5.0) }
let!(:memory_affinity_slot) { mock_model(MachineAffinitySlot, affinity_id: 5, affinity_parameter: 5.0) }
let!(:queued_job) { FactoryGirl.create(:queued_job) }
before do
::Naf::RunningJob.any_instance.stub(:affinity_weights).
and_return(1 => 0.0, 2 => 0.0, 3 => 0.0, 4 => 1.0, 5 => 1.0)
end
it "return queued job when machine has cpus left" do
memory_affinity_slot = mock_model(MachineAffinitySlot, affinity_id: 5, affinity_parameter: 0.0)
machine.stub(:machine_affinity_slots).and_return([cpu_affinity_slot, memory_affinity_slot])
::Naf::QueuedJob.stub(:check_weight_sum).
and_return([])
::Naf::QueuedJob.weight_available_on_machine(machine).
should == [queued_job]
end
it "return queued job when machine has cpus and memory left" do
machine.stub(:machine_affinity_slots).and_return([cpu_affinity_slot, memory_affinity_slot])
::Naf::QueuedJob.stub(:check_weight_sum).
and_return([])
::Naf::QueuedJob.weight_available_on_machine(machine).
should == [queued_job]
end
it "return queued job when machine does not have cpu/memory restriction" do
machine.stub(:machine_affinity_slots).and_return([])
::Naf::QueuedJob.weight_available_on_machine(machine).
should == [queued_job]
end
end
describe "#check_weight_sum" do
let!(:queued_job) { FactoryGirl.create(:queued_job) }
let!(:affinity) { FactoryGirl.create(:affinity, id: 4, affinity_name: 'cpus') }
let!(:affinity_tab) { FactoryGirl.create(:job_affinity_tab_base,
historical_job: queued_job.historical_job,
affinity_id: affinity.id,
affinity_parameter: 1)}
it "does not return queued job when machine has cpus left" do
::Naf::QueuedJob.check_weight_sum(4, 1, 3).
should == []
end
it "does not return queued job when job does not have cpu affinity" do
affinity_tab.delete
::Naf::QueuedJob.check_weight_sum(4, 1, 3).
should == []
end
it "return jobs when machine does not have cpus left" do
::Naf::QueuedJob.check_weight_sum(4, 3, 3).
should == [queued_job]
end
end
end
end
|
module Rubicus::Layers
class Base
protected
def convert_options(obj)
case obj
when String
obj.gsub("\n", "\\n")
when Array
if obj[0].kind_of? Array
obj.map { |row| row.join(" ") }.join
else
obj.join(" ")
end
when Hash
obj.map { |k,v| "#{k}=#{convert_options(v)}" }.join(" ")
when true
'yes'
when false
'no'
else
obj.to_s
end
end
def convert(obj)
case obj
when String
obj.gsub("\n", "\\n") + "\n"
when Array
if obj[0].kind_of? Array
obj.map {|row| row.join(" ") + "\n"}.join
else
obj.join(" ")
end
when Hash
obj.map {|k,v| "#{ k }=#{ convert(v) }" }.join(" ")
when true
'yes'
when false
'no'
else
obj.to_s
end
end
end
end |
module Dotpkgbuilder
class Scripts < Stage
delegate :working_dir, :scripts_dir, :pkg_dir, to: :context
PREINSTALL_FILE = "preinstall".freeze
POSTINSTALL_FILE = "postinstall".freeze
SCRIPTS_FILE = "Scripts".freeze
def preinstall_file
PREINSTALL_FILE
end
def preinstall?
File.exists?(File.join(scripts_dir, preinstall_file))
end
def postinstall_file
POSTINSTALL_FILE
end
def postinstall?
File.exists?(File.join(scripts_dir, postinstall_file))
end
def run
mkscripts
provide :preinstall, preinstall?
provide :preinstall_file, preinstall_file
provide :postinstall, postinstall?
provide :postinstall_file, postinstall_file
end
def mkscripts
sh "find #{scripts_dir}/*install | cpio -o --format odc | gzip -c > #{pkg_dir}/#{SCRIPTS_FILE}"
end
end
end
|
# based on:
# BustRailsCookie.rb by Corey Benninger
require 'cgi'
require 'base64'
require 'openssl'
require 'active_record'
require 'optparse'
banner = "Usage: #{$0} [-h HASHTYPE] [-w WORDLIST_FILE] <cookie value--hash>"
##########################
### Set Default Values ###
##########################
hashtype = 'SHA1'
wordlist = ''
opts = OptionParser.new do |opts|
opts.banner = banner
opts.on("-h", "--hash HASH") do |h|
hashtype = h
end
opts.on("-w", "--wordlist [FILE]") do |w|
wordlist = w
end
end
begin
opts.parse!(ARGV)
rescue Exception => e
puts e, "", opts
exit
end
cookie = ARGV.shift
if cookie == nil || cookie.length < 2
print banner
exit
end
####################################
### Print out the Session info ###
####################################
data, digest = CGI.unescape(cookie).split('--')
puts "\n***Dumping session value***"
puts Base64.decode64(data)
####################################
### Check Hash and set Hash Type ###
####################################
if digest == nil
print "\nNo hash found. Cookie should be 'CookieValue--HashValue'\n"
exit
end
if digest.length != 40 && hashtype == 'SHA1'
if digest.length == 64
print "\nUsing SHA256\n"
hashtype = 'SHA256'
elseif digest.length == 128
print "\nUsing SHA512\n"
hashtype = 'SHA512'
elseif digest.length == 32
print "\nUsing MD5\n"
hashtype = 'MD5'
else
print "\nWARNING: Default hash should be 40 characters long. This cookie hash is: #{digest.length}\nCracking will most likely fail. Try setting the proper hash type.\n"
end
end
data = CGI.unescape(data)
if wordlist != ''
puts "\n\n***Beginning Word List Attack***\n"
File.open(wordlist, "r").each_line do |line|
keygen = ActiveSupport::KeyGenerator.new(line.chomp, iterations: 1000)
key = keygen.generate_key('signed encrypted cookie')
key = keygen.generate_key('signed cookie')
dig = OpenSSL::HMAC.hexdigest(hashtype, key, data)
if digest == dig
puts "\n\n***PASSWORD FOUND***\nPassword is: #{line}"
exit
end
end
puts "\nSorry. Password not found in wordlist.\n"
end
|
# Add a declarative step here for populating the DB with movies.
Given /the following movies exist/ do |movies_table|
movies_table.hashes.each do |movie|
# each returned element will be a hash whose key is the table header.
# you should arrange to add that movie to the database here.
Movie.create! movie unless Movie.find :first, :conditions => movie
end
end
# Make sure that one string (regexp) occurs before or after another one
# on the same page
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# ensure that that e1 occurs before e2.
# page.content is the entire content of the page as a string.
regexp = /#{e1}.*#{e2}/m
assert page.body =~ regexp, "#{e1} should be before #{e2}"
end
# Make it easier to express checking or unchecking several boxes at once
# "When I uncheck the following ratings: PG, G, R"
# "When I check the following ratings: G"
When /I (un)?check the following ratings: (.*)/ do |uncheck, rating_list|
rating_list.split(/,\s*/).each do |rating|
steps %Q{
When I #{'un' if uncheck}check "ratings[#{rating}]"
}
end
end
Then /I should see all of the movies/ do
assert find('#movielist').all('tr').count == Movie.count, 'Expected all movies'
end
Then /I should( not)? see the following movies/ do |unseen, movies_table|
movies_table.hashes.each do |movie|
steps %Q{ Then I should#{" not" if unseen} see "#{movie[:title]}" }
end
end
When /I filter by the following ratings: (.*)/ do |rating_list|
steps %Q{
When I check the following ratings: #{rating_list}
And I press "Refresh"
}
end |
require 'snmp2mkr/oid'
module Snmp2mkr
class Metric
def initialize(vhost, name, oid, mib: nil, transformations: [])
@vhost_name = vhost.name
@name = name
@oid = oid.kind_of?(Oid) ? oid : Oid.new(oid, mib: mib)
@transformations = transformations
end
attr_reader :vhost_name, :name, :oid, :transformations
def inspect
"#<#{self.class}:#{'%x' % __id__} #{name.inspect} => #{oid.inspect} (#{transformations.inspect})>"
end
def safe_name
name.gsub(/[^a-zA-Z0-9._-]/, '-')
end
def evaluate(varbind, state_holder: nil, time: Time.now)
if varbind == SNMP::NoSuchObject || varbind == SNMP::NoSuchInstance
return nil
end
if state_holder
state = state_holder.fetch(self)
end
raw = val = varbind.value.to_i
transformations.each do |xfrm|
val = transform(xfrm, val, state, time)
end
if state_holder
state_holder.set(self, state.merge(last: val, last_raw: raw, last_at: time))
end
return val
end
private
def transform(xfrm, value, state, time)
case xfrm.type
when 'persec'
unless state[:last_raw] && state[:last_at]
return nil
end
delta = value - state[:last_raw]
return nil if delta < 0
return delta/(time-state[:last_at])
end
end
end
end
|
class CreateSnippetsTagsTable < ActiveRecord::Migration
def change
create_join_table :snippets, :tags
end
end
|
class AddFuelLpgToReport < ActiveRecord::Migration
def change
add_column :reports, :fuel_cost_lpg, :integer, after: :fuel_cost, null: false, default: 0
end
end
|
class UserDecorator < Draper::Decorator
delegate_all
def full_address
"#{object.street_address}, #{object.city}, #{object.state} #{object.zip}"
end
def created_at
object.created_at.strftime("%m-%d-%Y")
end
def trial_expiration
(object.created_at + 30.days).strftime("%m-%d-%Y")
end
end
|
require 'rails_helper'
RSpec.describe "admin/topics/index", type: :view do
before(:each) do
assign(:admin_topics, [
Admin::Topic.create!(),
Admin::Topic.create!()
])
end
it "renders a list of admin/topics" do
render
end
end
|
require 'axlsx'
class LegalServices::SupplierSpreadsheetCreator
def initialize(suppliers, params)
@suppliers = suppliers
@params = params
end
def build
Axlsx::Package.new do |p|
p.workbook.add_worksheet(name: 'Supplier shortlist') do |sheet|
sheet.add_row ['Supplier name', 'Phone number', 'Email']
add_supplier_details(sheet)
end
p.workbook.add_worksheet(name: 'Shortlist audit') do |sheet|
sheet.add_row ['Central Government user?', @params['central_government']]
sheet.add_row ['Fees under £20 000 per matter?', 'yes'] if @params['central_government'] == 'yes'
lot = LegalServices::Lot.find_by(number: @params['lot'])
sheet.add_row ['Lot', "#{lot.number} - #{lot.description}"] unless @params['central_government'] == 'yes'
add_audit_trail(sheet)
end
end
end
private
def add_supplier_details(sheet)
@suppliers.each do |supplier|
sheet.add_row(
[
supplier.name,
supplier.phone_number,
supplier.email
]
)
end
end
def add_audit_trail(sheet)
add_jurisdiction(sheet) if @params['lot'] == '2'
add_services(sheet) if ['1', '2'].include? @params['lot']
add_regions(sheet) if @params['lot'] == '1'
end
def add_regions(sheet)
regions = []
@params['region_codes'].each do |region_code|
region_name = if region_code == 'UK'
'Full national coverage'
else
Nuts1Region.find_by(code: region_code).name
end
regions << region_name
end
sheet.add_row ['Regions', regions.join(', ')]
end
def add_jurisdiction(sheet)
jurisdictions = { 'a' => 'England & Wales', 'b' => 'Scotland', 'c' => 'Northern Ireland' }
sheet.add_row ['Jurisdiction', jurisdictions[@params['jurisdiction']]]
end
def add_services(sheet)
services = []
@params['services'].each { |service| services << LegalServices::Service.find_by(code: service).name }
sheet.add_row ['Services', services.join(', ')]
end
end
|
ActiveAdmin.register Bar do
index do
column "Logo" do |bar|
image_tag bar.logo.thumb('100x100').url
end
column :name
column :city
column :freebeer
column "Visits" do |bar|
bar.visits.count
end
default_actions
end
filter :name
filter :city
form html: { multipart: true } do |f|
f.inputs "Bar Details" do
f.input :name
f.input :logo, as: :file, hint: ((logo = f.object.logo) && f.template.image_tag(logo.thumb('100x100').url))
f.input :street
f.input :zipcode
f.input :city
f.input :country
f.input :freebeer
end
f.actions
end
show do |bar|
attributes_table do
row :name
row :logo do
image_tag bar.logo.thumb('100x100').url
end
row :street
row :zipcode
row :city
row :country
row :freebeer
row :latitude
row :longitude
end
active_admin_comments
end
end
|
require "seasons_of_love/version"
require 'active_support/core_ext'
module SeasonsOfLove
#date trick taken from http://stackoverflow.com/questions/925905/is-it-possible-to-create-a-list-of-months-between-two-dates-in-rails
# -Dylan
def self.split_dates_into_ranges(start_date, end_date, opts={})
months = []
if start_date.blank? || end_date.blank?
if opts[:allow_nil]
[]
else
raise "Range of #{start_date} - #{end_date} is missing one endpoint."
end
else
if opts[:format] == 'weeks'
weeks = []
beginning_of_week = opts[:beginning_of_week] || :sunday
week_start = start_date
while week_start <= end_date
weeks << { :start_date => week_start, :end_date => [week_start.end_of_week(beginning_of_week), end_date].min}
week_start = week_start.end_of_week(beginning_of_week) + 1.day
end
weeks
else
(start_date.year..end_date.year).each do |y|
mo_start = (start_date.year == y) ? start_date.month : 1
mo_end = (end_date.year == y) ? end_date.month : 12
(mo_start..mo_end).each do |m|
if (start_date.year == y && start_date.month == m)
#first month in range
start_of_month = start_date
else
start_of_month = Date.strptime("#{sprintf '%02d', m}/01/#{y}", "%m/%d/%Y")
end
if (end_date.year == y && end_date.month == m)
#last month in range
end_of_month = end_date
else
end_of_month = start_of_month.end_of_month
end
month_entry = {}
month_entry[:start_date] = start_of_month
month_entry[:end_date] = end_of_month
month_entry[:month] = Date::MONTHNAMES[m]
months << month_entry
end
end
months
end
end
end
end
|
class Song
attr_accessor :name, :artist, :genre
def initialize(name, genre)
@name= name
@genre = genre
end
def artist_name
self.artist.name
end
end
|
class Review < ApplicationRecord
belongs_to :user
belongs_to :menu
validates :content, presence: true, length: { maximum: 300 }
default_scope -> { order(created_at: :desc) }
end |
class Special
def initialize
@should_resume = false
end
def execute_from_game(game, player, events)
puts "Special executing for #{player.name}"
execute(game, player, events)
if @should_resume
puts "After execution, resuming card play"
game.continue_card(events)
else
puts "Yield execution of card for special"
end
end
def execute(game, player, events)
end
def process_response(game, player, dialog, data, events)
end
def react_to_attack(game, card, player, events)
return true
end
def allow_reactions_from_player(game, player, events)
puts "Checking whether #{player.name} will be attacked"
should_attack = true
player.revealed.cards.each do |card|
card.card_attributes.each do |attr|
if (attr.key =~ /^special_/)
class_name = attr.key
class_name.slice!('special_')
special = class_name.constantize.new()
should_attack &= special.react_to_attack(game, card, player, events)
puts "After checking #{card.name}, #{player.name} should be attacked if #{should_attack}"
end
end
end
puts "#{player.name} will be attacked if #{should_attack}"
return should_attack
end
end
class GainCard < Special
def gain_card(game, player, special_type, condition, events)
puts "Building dialog for gaining a card"
cards = []
game.supplies.each do |supply|
candidate_card = supply.card_pile.top_card
if candidate_card == nil
next
end
puts "Testing #{candidate_card.name}"
if candidate_card != nil and condition.call(candidate_card)
puts "#{candidate_card.name} is gainable"
view = candidate_card.view
view[:id] = supply.id
cards << view
else
puts "#{candidate_card.name} cannot be gained"
end
end
if cards.any?
state = {
dialog_type: 'cardset_options',
prompt: 'Choose a card to gain',
cardsets: [
{
name: 'Options',
id: 0,
cards: cards,
card_count_type: 'exactly',
card_count_value: 1,
options: {
gain: "Gain",
},
option_count_type: 'exactly',
option_count_value: 1
}
]
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: special_type, state: state.to_s)
game.dialogs << dialog
events << {
type: 'dialog',
logs_by_id: [{
owner_id: player.id,
id: dialog.id
}.merge(state)]
}
@should_resume = false
else
@should_resume = true
end
end
end
class Feast < GainCard
def execute(game, player, events)
puts "Executing Feast card"
feast = game.current_state.card
player.move_card_explicit_public(feast, player.name, 'play_area', player.play_area, '<system>', 'trash', game.trash, events)
gain_card(game, player, 'Feast', Proc.new { |card| next card.cost <= 5 }, events)
end
def process_response(game, player, dialog, data, events)
puts "Processing response for Feast. Data: #{data}"
data['cardsets'].each do |cardset|
supply = Supply.find(cardset['cards'][0])
puts "Chose to gain from #{supply.name}"
player.move_card_explicit_public(supply.card_pile.top_card, '<system>', supply.name, supply.card_pile, player.name, 'discard', player.discard, events)
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
class Chancellor < Special
def execute(game, player, events)
puts "Executing Chancellor card"
state = {
dialog_type: 'options',
prompt: 'Chancellor - put deck into discard?',
optionset: {
option_count_type: 'exactly',
option_count_value: 1,
options: {
yes: "Yes",
no: "No"
}
}
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'Chancellor', state: state.to_s)
game.dialogs << dialog
events << {
type: 'dialog',
logs_by_id: [{
owner_id: player.id,
id: dialog.id
}.merge(state)]
}
@should_resume = false
end
def process_response(game, player, dialog, data, events)
puts "Processing response for Chancellor. Data: #{data}"
data['optionset'].each do |decision|
if decision == 'yes'
puts "Decided to activate chancellor ability"
player.deck.cards.each do |card|
player.move_card_public(card, 'deck', 'discard', events)
end
else
puts "Decided not to activate chancellor ability"
end
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
class Library < Special
def execute(game, player, events)
puts "#{player.name} is executing Library"
@should_resume = true
while player.hand.cards.count < 7
next_card = player.reveal_from_deck(events)
if next_card.is_true?('is_action')
puts "Action was drawn (#{next_card.name}). Sending dialog"
state = {
dialog_type: 'cardset_options',
prompt: 'Library - action revealed',
cardsets: [
{
name: next_card.name,
id: next_card.id,
cards: [next_card.view],
card_count_type: 'exactly',
card_count_value: 1,
options: {
draw: "Draw",
set_aside: "Set aside"
},
option_count_type: 'exactly',
option_count_value: 1
}
]
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'Library', state: state.to_s)
game.dialogs << dialog
events << {
type: 'dialog',
logs_by_id: [{
owner_id: player.id,
id: dialog.id
}.merge(state)]
}
@should_resume = false
break
else
puts "Non-Action was drawn (#{next_card.name}). Moving to hand"
player.move_card_public(next_card, 'revealed', 'hand', events)
end
end
if @should_resume
player.revealed.cards.each do |card|
player.move_card_public(card, 'revealed', 'discard', events)
end
end
end
def process_response(game, player, dialog, data, events)
data['cardsets'].each do |cardset|
card = Card.find(cardset['id'])
option = cardset['options'][0]
if option == 'draw'
puts "Chose to draw action"
player.move_card_from_source_public(card, 'hand', events)
elsif option == 'set_aside'
puts "Chose to set action aside. Leaving in revealed pile."
end
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
execute_from_game(game, player, events)
end
end
class Spy < Special
def execute(game, player, events)
puts "Execute spy for #{player.name}"
cardsets = []
game.players.each do |opponent|
unless allow_reactions_from_player(game, opponent, events)
next
end
revealed_card = opponent.reveal_from_deck(events)
if revealed_card != nil
puts "#{opponent.name} has revealed #{revealed_card.name} for Spy"
cardsets << {
name: opponent.name,
id: opponent.id,
cards: [revealed_card.view],
card_count_type: 'exactly',
card_count_value: 1,
options: {
discard: "Discard",
deck: "Return to deck",
},
option_count_type: 'exactly',
option_count_value: 1
}
else
puts "#{opponent.name} has no card to reveal for Spy"
end
end
if cardsets.any?
puts "Sending Spy dialog"
state = {
dialog_type: 'cardset_options',
prompt: 'Choose actions for spy attacks',
cardsets: cardsets
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'Spy', state: state.to_s)
game << dialog
events << {
type: 'dialog',
logs_by_id: [{
owner_id: player.id,
id: dialog.id
}.merge(state)]
}
else
puts "No dialog for spy - resuming card play"
@should_resume = true
end
end
def process_response(game, player, dialog, data, events)
puts "Process response spy #{player.name} with data #{data}"
data['cardsets'].each do |cardset|
opponent = Player.find(cardset['id'])
card = Card.find(cardset['cards'][0])
option = cardset['options'][0]
if option == 'discard'
opponent.move_card_from_source_public(card, 'discard', events)
elsif option == 'deck'
opponent.move_card_explicit_public(card, opponent.name, 'revealed', opponent.revealed, opponent.name, 'deck', opponent.deck, events)
end
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
class Thief < Special
def execute(game, player, events)
puts "Execute thief for #{player.name}"
cardsets = []
game.players.select{|opponent| opponent.id != player.id}.each do |opponent|
unless allow_reactions_from_player(game, opponent, events)
next
end
revealed_cards = [opponent.reveal_from_deck(events), opponent.reveal_from_deck(events)]
revealed_treasure_cards = revealed_cards.select{|card| card.is_true?('is_treasure')}.map{|card| card.view}
if revealed_treasure_cards.any?
cardsets << {
name: opponent.name,
id: opponent.id,
cards: revealed_treasure_cards,
card_count_type: 'exactly',
card_count_value: 1,
options: {
discard: "Discard",
trash: "Trash",
gain: "Trash and gain"
},
option_count_type: 'exactly',
option_count_value: 1
}
end
end
if cardsets.any?
puts "Sending dialog for Thief"
state = {
dialog_type: 'cardset_options',
prompt: 'Choose actions for thief attacks',
cardsets: cardsets
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'Thief', state: state.to_s)
game << dialog
events << {
type: 'dialog',
logs_by_id: [{
owner_id: player.id,
id: dialog.id
}.merge(state)]
}
else
puts "Nothing to thieve - continue card play"
game.players.each do |opponent|
opponent.revealed.cards.each do |card|
opponent.move_card_public(card, 'revealed', 'discard', events)
end
end
@should_resume = true
end
end
def process_response(game, player, dialog, data, events)
data['cardsets'].each do |cardset|
opponent = Player.find(cardset['id'])
card = Card.find(cardset['cards'][0])
option = cardset['options'][0]
if option == 'discard'
opponent.move_card_from_source_public(card, 'discard', events)
elsif option == 'trash'
opponent.move_card_explicit_public(card, opponent.name, 'revealed', opponent.revealed, '<system>', 'trash', game.trash, events)
elsif option == 'gain'
opponent.move_card_explicit_public(card, opponent.name, 'revealed', opponent.revealed, '<system>', 'trash', game.trash, events)
player.move_card_explicit_public(card, '<system>', 'trash', game.trash, player.name, 'discard', player.discard, events)
end
end
game.players.each do |opponent|
opponent.revealed.cards.each do |card|
opponent.move_card_public(card, 'revealed', 'discard', events)
end
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
class Bureaucrat < Special
def execute(game, player, events)
logs_by_id = []
game.players.select{|opponent| opponent.id != player.id}.each do |opponent|
should_attack = allow_reactions_from_player(game, opponent, events)
unless should_attack
next
end
unless opponent.hand.has_card_boolean?('is_victory')
next
end
state = {
dialog_type: 'choose_cards',
source: 'hand',
count_type: 'exactly',
count_value: 1,
prompt: "Choose a victory to place on top of your deck"
}
dialog = Dialog.create(game: game, active_player: opponent, stage: 1, special_type: 'Bureaucrat', state: state.to_s)
game.dialogs << dialog
logs_by_id << {
owner_id: opponent.id,
id: dialog.id
}.merge!(state)
end
events << {
type: 'dialog',
logs_by_id: logs_by_id
}
supply = game.supplies.joins(:card_pile).where('card_piles.name' => 'Silver').take
unless supply.card_pile.is_empty
candidate_card = supply.card_pile.top_card
player.deck.add_card(candidate_card)
newTop = supply.card_pile.top_card
events << {
type: "move_card",
all_log: {
from_player: "<system>",
from_zone: "supply:#{supply.id}",
from_size: supply.card_pile.cards.count,
from_card: candidate_card.view,
revealed: newTop && newTop.view,
to_player: player.name,
to_zone: "deck",
to_size: player.deck.cards.count,
to_card: candidate_card.view
}
}
else
@should_resume = true
end
end
def process_response(game, player, dialog, data, events)
data['cards'].each do |card_id|
card = Card.find(card_id)
if player.hand.cards.where(id: card.id).count == 0
return
end
player.deck.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "hand",
from_size: player.hand.cards.count,
to_player: player.name,
to_zone: "deck",
to_size: player.discard.cards.count,
to_card: card.view
},
player_log: { from_card: card.view }
}
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
if !game.has_dialog
game.continue_card(events)
end
end
end
class AvoidAttack < Special
def execute(game, player, events)
@should_resume = true
end
def process_response(game, player, dialog, data, events)
puts "Processing #{player.name}'s dialog response: #{data}"
card_count = 0
data['cards'].each do |card_id|
card = Card.find(card_id)
if player.hand.cards.where(id: card.id).count == 0
return
end
card_count += 1
player.revealed.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "hand",
from_size: player.hand.cards.count,
to_player: player.name,
to_zone: "revealed",
to_size: player.revealed.cards.count,
to_card: card.view
},
player_log: { from_card: card.view }
}
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
if !game.has_dialog
game.continue_card(events)
end
end
def react_to_attack(game, card, player, events)
player.hand.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "reavealed",
from_size: player.revealed.cards.count,
from_card: card.view,
to_player: player.name,
to_zone: "hand",
to_size: player.hand.cards.count,
to_card: card.view
}
}
return false
end
end
class Adventurer < Special
def execute(game, player, events)
count = 0
while count < 2
player.predraw(events)
if player.deck.is_empty
break
end
next_card = player.deck.top_card
if next_card.has_attr("is_treasure") and next_card.is_treasure == 1
player.hand.add_card(next_card)
new_top = player.deck.top_card
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "deck",
from_size: player.deck.cards.count,
from_card: next_card.view,
revealed: new_top && new_top.view,
to_player: player.name,
to_zone: "hand",
to_size: player.hand.cards.count,
to_card: next_card.view
}
}
count += 1
else
player.revealed.add_card(next_card)
new_top = player.deck.top_card
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "deck",
from_size: player.deck.cards.count,
from_card: next_card.view,
revealed: new_top && new_top.view,
to_player: player.name,
to_zone: "revealed",
to_size: player.revealed.cards.count,
to_card: next_card.view
}
}
end
end
player.revealed.cards.each do |card|
player.discard.add_card(card)
new_top = player.revealed.top_card
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "revealed",
from_size: player.revealed.cards.count,
from_card: card.view,
revealed: new_top && new_top.view,
to_player: player.name,
to_zone: "discard",
to_size: player.discard.cards.count,
to_card: card.view
}
}
end
@should_resume = true
end
end
class Curse < Special
def execute(game, player, events)
game.supplies.map{|x| x}
game.players.each do |opponent|
if opponent.id != player.id
should_attack = allow_reactions_from_player(game, opponent, events)
unless should_attack
next
end
curse = curse_pile.card_pile.top_card
opponent.discard.add_card(curse)
newTop = curse_pile.card_pile.top_card
events << {
type: "move_card",
all_log: {
from_player: "<system>",
from_zone: "supply:#{curse_pile.id}",
from_size: curse_pile.card_pile.cards.count,
from_card: curse.view,
revealed: newTop && newTop.view,
to_player: opponent.name,
to_zone: "discard",
to_size: opponent.discard.cards.count,
to_card: curse.view
}
}
end
end
@should_resume = true
end
end
class CouncilRoom < Special
def execute(game, player, events)
game.players.each do |opponent|
if opponent.id != player.id
opponent.draw(1, events)
end
end
@should_resume = true
end
end
class YouMayTrash < Special
def execute(game, player, events)
state = {
dialog_type: 'choose_cards',
source: 'hand',
count_type: 'at_most',
count_value: 4,
prompt: "Trash up to 4 cards"
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'YouMayTrash', state: state.to_s)
game.dialogs << dialog
events << {
type: 'dialog',
player_log: {
id: dialog.id
}.merge!(state)
}
end
def process_response(game, player, dialog, data, events)
if data['cards'].count > 4
return
end
data['cards'].each do |card_id|
card = Card.find(card_id)
if player.hand.cards.where(id: card.id).count == 0
return
end
game.trash.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "hand",
from_size: player.hand.cards.count,
to_player: "<system>",
to_zone: "trash",
to_size: game.trash.cards.count,
to_card: card.view
},
player_log: { from_card: card.view }
}
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
class AttackDiscardTo < Special
def execute(game, player, events)
logs_by_id = []
game.players.select{|opponent| opponent.id != player.id}.each do |opponent|
should_attack = allow_reactions_from_player(game, opponent, events)
unless should_attack
next
end
total_cards = opponent.hand.cards.count()
to_discard = total_cards - 3
if to_discard <= 0
next
end
state = {
dialog_type: 'choose_cards',
source: 'hand',
count_type: 'exactly',
count_value: to_discard,
prompt: "Discard down to 3 cards"
}
dialog = Dialog.create(game: game, active_player: opponent, stage: 1, special_type: 'AttackDiscardTo', state: state.to_s)
game.dialogs << dialog
logs_by_id << {
owner_id: opponent.id,
id: dialog.id
}.merge!(state)
end
if logs_by_id.any?
events << {
type: 'dialog',
logs_by_id: logs_by_id
}
else
@should_resume = true
end
end
def process_response(game, player, dialog, data, events)
data['cards'].each do |card_id|
card = Card.find(card_id)
if player.hand.cards.where(id: card.id).count == 0
return
end
player.discard.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "hand",
from_size: player.hand.cards.count,
to_player: player.name,
to_zone: "discard",
to_size: player.discard.cards.count,
to_card: card.view
},
player_log: { from_card: card.view }
}
end
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
if !game.has_dialog
game.continue_card(events)
end
end
end
class Cellar < Special
def execute(game, player, events)
state = {
dialog_type: 'choose_cards',
source: 'hand',
count_type: 'at_least',
count_value: 0,
prompt: "Discard any number of cards"
}
dialog = Dialog.create(game: game, active_player: player, stage: 1, special_type: 'Cellar', state: state.to_s)
game.dialogs << dialog
events << {
type: 'dialog',
player_log: {
id: dialog.id
}.merge!(state)
}
end
def process_response(game, player, dialog, data, events)
card_count = 0
data['cards'].each do |card_id|
card = Card.find(card_id)
if player.hand.cards.where(id: card.id).count == 0
return
end
card_count += 1
player.discard.add_card(card)
events << {
type: "move_card",
all_log: {
from_player: player.name,
from_zone: "hand",
from_size: player.hand.cards.count,
to_player: player.name,
to_zone: "discard",
to_size: player.discard.cards.count,
to_card: card.view
},
player_log: { from_card: card.view }
}
end
player.draw(card_count, events)
events << {
type: 'dialog',
player_log: {
id: dialog.id,
dialog_type: 'complete'
}
}
dialog.stage = 0
dialog.save
game.continue_card(events)
end
end
|
class SubscriptionsController < ApplicationController
include EventSource
before_action :authenticate
def new
@subscription = CreateSubscriptionCommand.new topic_id: params[:topic_id]
end
def edit
@subscription = UpdateSubscriptionCommand.new Subscription.find(id_param).updatable_attributes
end
def create
@subscription = CreateSubscriptionCommand.new subscription_params
if store_event_id Domain.run_command(@subscription)
redirect_to userpage_users_path, notice: 'Topic wurde abonniert.'
else
render 'new'
end
end
def update
@subscription = UpdateSubscriptionCommand.new subscription_params.merge(id: id_param)
if store_event_id Domain.run_command(@subscription)
redirect_to userpage_users_path, notice: 'Die Einstellungen wurden gespeichert.'
else
render 'edit'
end
end
def destroy
delete_subscription = DeleteSubscriptionCommand.new(id: id_param)
if store_event_id Domain.run_command(delete_subscription)
redirect_to userpage_users_path, notice: 'Das Abonnement wurde entfernt.'
else
redirect_to userpage_users_path, alert: 'Das Abonnerment konnte nicht gelöscht werdenn!'
end
end
private
def subscription_params
params.require(:subscription).permit(:email, :topic_id).merge(user_id: session[:user])
end
def id_param
params.require(:id).to_i
end
end
|
Rails.application.routes.draw do
resources :questions
resources :members
root to: 'members#index'
get '/incoming' => 'answers#incoming'
end
|
require 'optparse'
require 'highline/import'
module Chat
class Client
class CLI
def self.execute(args)
host = Chat::DEFAULT_HOST
port = Chat::DEFAULT_PORT
# parse command-line arguments
parser = OptionParser.new do |opts|
opts.on("-h", "--host=HOST", "Host to connect to.") do |arg|
host = arg
end
opts.on("-p", "--port=PORT", "Port to connect to.") do |arg|
port = arg.to_i
end
end
parser.parse!(args)
# execute client
client = Chat::Client.new(host, port)
client.run
end
end
end
end
|
require "test_helper"
require "minitest/stub/const"
class StopwatchTest < Minitest::Test
def test_benchmark_is_used_to_time_execution
# Create a mock BenchmarkTms object to be returned from Benchmark#measure
benchmark_timing_mock = Minitest::Mock.new
benchmark_timing_mock.expect(:real, 1.23)
# Create a mock Benchmark to return a mock BenchmarkTms objet
benchmark_mock = Minitest::Mock.new
benchmark_mock.expect(:measure, benchmark_timing_mock)
# Stub Benchmark with our mock
Object.stub_const :Benchmark, benchmark_mock do
# Assert we get the expected value back from Benchmark#measure
assert_equal(
1.23,
SCC::Stopwatch.call { nil }
)
end
# Assert our mock expectations were satisifed
assert_mock benchmark_timing_mock
assert_mock benchmark_mock
end
end
|
name 'motd-tail'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache-2.0'
description 'Updates motd.tail with Chef Roles'
version '5.1.0'
%w(debian ubuntu).each do |os|
supports os
end
source_url 'https://github.com/chef-cookbooks/motd-tail'
issues_url 'https://github.com/chef-cookbooks/motd-tail/issues'
chef_version '>= 12.15'
|
require "test_helper"
class AddEventsControllerTest < ActionDispatch::IntegrationTest
setup do
@add_event = add_events(:one)
end
test "should get index" do
get add_events_url, as: :json
assert_response :success
end
test "should create add_event" do
assert_difference('AddEvent.count') do
post add_events_url, params: { add_event: { event_id: @add_event.event_id, job_seeker_id: @add_event.job_seeker_id } }, as: :json
end
assert_response 201
end
test "should show add_event" do
get add_event_url(@add_event), as: :json
assert_response :success
end
test "should update add_event" do
patch add_event_url(@add_event), params: { add_event: { event_id: @add_event.event_id, job_seeker_id: @add_event.job_seeker_id } }, as: :json
assert_response 200
end
test "should destroy add_event" do
assert_difference('AddEvent.count', -1) do
delete add_event_url(@add_event), as: :json
end
assert_response 204
end
end
|
module Mailbox
class DaemonThreadFactory
def newThread(r)
thread = java.lang.Thread.new r;
thread.set_daemon true;
return thread;
end
end
end
|
# encrypt method
# move forward every letter of a string
# "abc" and want to get "bcd"
# assume lowercase input and output
# reverse that!
# "bcd" back to "abc"
def encrypt (secret_string)
# loop over the string
# for every index take that character and move forward one
counter = 0
while counter < secret_string.length
if secret_string[counter] == "z"
secret_string[counter] = "a"
elsif secret_string[counter] == " "
secret_string[counter] == " "
else
secret_string[counter] = secret_string[counter].next
# anytime the program z delete the letter that follows the letter, because z becomes aa which becomes ab
# index z, once it is encrypted you have delete the index next to it.
end
counter += 1
end
p secret_string
end
def decrypt (secret_string)
#go back one letter
alphabet = "abcdefghijklmnopqrstuvwxyz"
counter = 0
while counter < secret_string.length
if secret_string[counter] == " "
secret_string[counter] = " "
else
index_number = alphabet.index(secret_string[counter]) - 1
secret_string[counter] = alphabet[index_number]
end
counter += 1
end
p secret_string
end
# ask a sercet agent whether they would like to decrypt or encrypt a password and then what is that password
puts "What is your secret agent code name?"
codename = gets.chomp
puts "Welcome Agent #{codename}, do you wish to decrypt or encrypt your secret password?"
puts "Type decrypt or encrypt to proceed"
decrypt_encrypt = gets.chomp
puts "What is the password?"
password = gets.chomp
# run the decrypt method when decrypt is typed or the encrypt method when encrypt is typed
# conduct the requested operation, prints the result to the screen and exits
if decrypt_encrypt == "decrypt"
decrypt(password)
else
encrypt(password)
end
encrypt("abc")
encrypt("zed")
decrypt("bcd")
decrypt("afe")
decrypt(encrypt("swordfish"))
#this works because it passes swordfish to encrypt first then passes results to decrypt, so it encypts then decyrpts
|
require 'test_helper'
class ResponsesControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
def setup
@email = 'hoge@email.com'
@user = User.new(name: 'hoge',
nickname: 'hogechan',
email: @email,
password: 'hogefuga')
@user.save
@user.activate
@post = @user.posts.create(title: 'test', body: 'test', code: 'test', source_url: 'test')
@review = Review.generate_record(body: 'review', user: @user, post: @post)
@review.save
@master, @onetime = create_sessions
end
def get_body
@body = JSON.parse(response.body)
end
test 'should be created' do
m, o = create_sessions
text = 'awesome review'
post "/api/v1/posts/#{@post.id}/reviews/#{@review.id}", params: { value: { body: text }, token: { onetime: o.token } }
get_body
assert @body['status'] == 'SUCCESS'
end
test 'closed post should reject to post response' do
@post.close
m, o = create_sessions
text = 'awesome review'
post "/api/v1/posts/#{@post.id}/reviews/#{@review.id}", params: { value: { body: text }, token: { onetime: o.token } }
get_body
assert @body['status'] == 'FAILED'
assert @body['errors'].first['key'] == 'closed'
end
test 'can not response to response' do
response = @review.reply(user: @user, body: 'body')
m, o = create_sessions
text = 'awesome review'
post "/api/v1/posts/#{@post.id}/reviews/#{response.id}", params: { value: { body: text }, token: { onetime: o.token } }
get_body
assert @body['status'] == 'FAILED'
assert @body['errors'].first['key'] == 'response'
end
# reviewにレスポンスをしたときユーザーが消せなかったため、そのテスト
test 'user should be deleted' do
master, onetime = create_sessions
text = 'awesome review'
post "/api/v1/posts/#{@post.id}/reviews/#{@review.id}", params: { value: { body: text }, token: { onetime: onetime.token } }
assert response.status == 200
delete "/api/v1/users/#{@user.name}", params: { token: onetime.token }
assert response.status == 200
get "/api/v1/users/#{@user.name}"
assert response.status == 404
end
end
|
class PhotosController < ApplicationController
before_action :require_current_user, except: [:show, :search]
def index
render text: "Coming soon!"
end
def show
@photo = Photo.find(params[:id])
end
def new
@photo = Photo.new
end
def create
@photo = Photo.new(photo_params)
@photo.user = @current_user
@photo.save
redirect_to photo_path(@photo)
end
def search
@results = Photo.search_for params[:query]
end
private
def photo_params
params.require(:photo).permit(:title, :description, :upload)
end
end
|
# require 'spec_helper'
#
# describe HeatsController do
#
# def mock_heat(stubs={})
# @mock_heat ||= mock_model(Heat, stubs).as_null_object
# end
#
# describe "GET index" do
# it "assigns all heats as @heats" do
# Heat.stub(:all) { [mock_heat] }
# get :index
# assigns(:heats).should eq([mock_heat])
# end
# end
#
# describe "GET show" do
# it "assigns the requested heat as @heat" do
# Heat.stub(:find).with("37") { mock_heat }
# get :show, :id => "37"
# assigns(:heat).should be(mock_heat)
# end
# end
#
# describe "GET new" do
# it "assigns a new heat as @heat" do
# Heat.stub(:new) { mock_heat }
# get :new
# assigns(:heat).should be(mock_heat)
# end
# end
#
# describe "GET edit" do
# it "assigns the requested heat as @heat" do
# Heat.stub(:find).with("37") { mock_heat }
# get :edit, :id => "37"
# assigns(:heat).should be(mock_heat)
# end
# end
#
# describe "POST create" do
#
# describe "with valid params" do
# it "assigns a newly created heat as @heat" do
# Heat.stub(:new).with({'these' => 'params'}) { mock_heat(:save => true) }
# post :create, :heat => {'these' => 'params'}
# assigns(:heat).should be(mock_heat)
# end
#
# it "redirects to the created heat" do
# Heat.stub(:new) { mock_heat(:save => true) }
# post :create, :heat => {}
# response.should redirect_to(heat_url(mock_heat))
# end
# end
#
# describe "with invalid params" do
# it "assigns a newly created but unsaved heat as @heat" do
# Heat.stub(:new).with({'these' => 'params'}) { mock_heat(:save => false) }
# post :create, :heat => {'these' => 'params'}
# assigns(:heat).should be(mock_heat)
# end
#
# it "re-renders the 'new' template" do
# Heat.stub(:new) { mock_heat(:save => false) }
# post :create, :heat => {}
# response.should render_template("new")
# end
# end
#
# end
#
# describe "PUT update" do
#
# describe "with valid params" do
# it "updates the requested heat" do
# Heat.should_receive(:find).with("37") { mock_heat }
# mock_heat.should_receive(:update_attributes).with({'these' => 'params'})
# put :update, :id => "37", :heat => {'these' => 'params'}
# end
#
# it "assigns the requested heat as @heat" do
# Heat.stub(:find) { mock_heat(:update_attributes => true) }
# put :update, :id => "1"
# assigns(:heat).should be(mock_heat)
# end
#
# it "redirects to the heat" do
# Heat.stub(:find) { mock_heat(:update_attributes => true) }
# put :update, :id => "1"
# response.should redirect_to(heat_url(mock_heat))
# end
# end
#
# describe "with invalid params" do
# it "assigns the heat as @heat" do
# Heat.stub(:find) { mock_heat(:update_attributes => false) }
# put :update, :id => "1"
# assigns(:heat).should be(mock_heat)
# end
#
# it "re-renders the 'edit' template" do
# Heat.stub(:find) { mock_heat(:update_attributes => false) }
# put :update, :id => "1"
# response.should render_template("edit")
# end
# end
#
# end
#
# describe "DELETE destroy" do
# it "destroys the requested heat" do
# Heat.should_receive(:find).with("37") { mock_heat }
# mock_heat.should_receive(:destroy)
# delete :destroy, :id => "37"
# end
#
# it "redirects to the heats list" do
# Heat.stub(:find) { mock_heat }
# delete :destroy, :id => "1"
# response.should redirect_to(heats_url)
# end
# end
#
# end
|
# frozen_string_literal: true
require 'json'
require 'open-uri'
require 'net/https'
require './lib/models.rb'
def get_sticker_data(stkver, stkopt, stkid, stkpkgid)
base_uri = "https://dl.stickershop.line.naver.jp/products/0/0/#{stkver}/#{stkpkgid}"
info_uri = base_uri + '/iphone/productInfo.meta'
sticker_uri = base_uri + "/iphone/stickers/#{stkid}@2x.png"
animation_uri = base_uri + "/iphone/animation/#{stkid}@2x.png"
sound_uri = base_uri + "/iphone/sound/#{stkid}.m4a"
data = {}
begin
data['sticker'] = URI.open(sticker_uri, 'rb', ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
info = JSON.load(URI.open(info_uri, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read)
if info['hasAnimation']
data['animation'] = URI.open(animation_uri, 'rb', ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
end
if info['hasSound']
data['sound'] = URI.open(sound_uri, 'rb', ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
end
rescue
end
return data # {'sticker': png or nil, 'animation': apng or nil, 'sound': m4a or nil}
end
|
class UserMoodsController < ApplicationController
before_action :set_user_mood, only: [:show, :destroy, :update]
before_action :greeting, only: [:show, :index]
def index
@usermoods = @current_user.user_moods
end
def show
end
def new
@usermood = UserMood.new
end
def create
mood = Mood.find(params[:user_mood][:mood_id])
@usermood = UserMood.create(
user_id: @current_user.id,
mood_id: mood.id,
quote_id: random_quote_id(mood),
art_id: random_art_id(mood),
music_id: random_music_id(mood)
)
redirect_to user_mood_path(@usermood)
end
def random_quote_id(mood)
Quote.all.select {|quote| quote.mood.id == mood.id}.sample.id
end
def random_art_id(mood)
Art.all.select {|art| art.mood.id == mood.id}.sample.id
end
def random_music_id(mood)
Music.all.select {|music| music.mood.id == mood.id}.sample.id
end
def update
end
def improve_user_mood
@usermood = UserMood.find(params[:id])
mood = @usermood.mood
if mood.id == 1
redirect_to user_mood_path(@usermood), notice: "You're already happy, we wouldn't want to change that."
elsif mood.id == 4
redirect_to user_mood_path(@usermood), notice: "You're inspired, we wouldn't want to change that."
else
new_mood = improve_mood(mood)
@usermood.update(
user_id: @current_user.id,
mood_id: new_mood.id,
quote_id: random_quote_id(new_mood),
art_id: random_art_id(new_mood),
music_id: random_music_id(new_mood)
)
redirect_to user_mood_path(@usermood)
end
end
def destroy
@usermood.destroy
redirect_to user_moods_path
end
private
def user_mood_params
params.require(:user_mood).permit(:user_id, :mood_id, :quote_id, :music_id, :art_id)
end
def set_user_mood
@usermood = UserMood.find(params[:id])
end
def improve_mood(mood)
if mood.id == 1
return mood
elsif mood.id == 2
return Mood.find(1)
elsif mood.id == 3
return Mood.find(1)
else mood.id == 5
return Mood.find(4)
end
end
end
|
class User < ActiveRecord::Base
ROLES = %w[user admin root]
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :avatar, :styles => { retina_medium: "400x800>", medium: "200x400>", thumb: "50x50#", retina_thumb: "100x200>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
#validates_attachment_file_name :avatar, matches: [/png\Z/, /jpe?g\Z/, /gif\Z/]
validates_attachment :avatar, size: { in: 0..1500.kilobytes}
validates :name, presence: true
has_many :likes, as: :author, dependent: :delete_all
has_many :user_answers, dependent: :delete_all
has_many :passed_tests, through: :user_answers, source: :test
has_many :touched_publishers,through: :passed_tests, source: :author, source_type: 'Publisher'
has_many :comments, as: :author, dependent: :delete_all
has_many :ratings, dependent: :delete_all
has_and_belongs_to_many :publishers, class_name: 'Publisher'
has_and_belongs_to_many :voted_tests, class_name: "Test"
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end
def roles
ROLES.reject do |r|
((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
end
end
def is?(role)
roles.include?(role.to_s)
end
end
|
class RenameLeagueField < ActiveRecord::Migration
def change
rename_column :matches, :league, :league_id
end
end
|
# Create license mappings
class CreateLicenseMappings < ActiveRecord::Migration
def change
create_table :license_mappings do |t|
t.references :mappable, polymorphic: true, index: true
t.references :license, index: true, foreign_key: true
end
end
end
|
# coding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
include SimilarityEngineSimilarity
describe SimilarityEngine do
context 'uninitialized' do
describe '#initialize' do
context 'when call' do
it 'CosineSimilarity' do
engine = SimilarityEngine.new
engine.instance_eval('@similarity').instance_of?(CosineSimilarity).should be_truthy
end
end
end
end
context 'initialized' do
before(:each) do
@engine = SimilarityEngine.new
end
describe '#analyze' do
context '2 nil vector input' do
it 'should raise error' do
expect {
@engine.analyze(nil, nil)
}.to raise_error
end
end
context '1 nil vector input' do
it 'should raise error' do
vec_x = nil
vec_y = [1, 2, 3]
expect {
@engine.analyze(vec_x, vec_y)
}.to raise_error
end
it 'should raise error' do
vec_x = [1, 2, 3]
vec_y = nil
expect {
@engine.analyze(vec_x, vec_y)
}.to raise_error
end
end
context 'null vector input' do
it 'should raise error' do
vec_x = []
vec_y = []
expect {
@engine.analyze(vec_x, vec_y)
}.to raise_error
end
end
context 'defferent demension vector input' do
it 'should raise error' do
vec_x = [1, 2, 3]
vec_y = [1, 2]
expect {
@engine.analyze(vec_x, vec_y)
}.to raise_error
end
end
context 'valid vector input' do
it 'should not raise error' do
vec_x = [1, 2, 3]
vec_y = [4, 5, 6]
expect {
@engine.analyze(vec_x, vec_y)
}.to_not raise_error
end
end
end
describe '#to_cosine' do
context 'when call' do
it 'CosineSimilarity' do
@engine.to_cosine
@engine.instance_eval('@similarity').instance_of?(CosineSimilarity).should be_truthy
end
end
end
describe '#to_pearson' do
context 'when call' do
it 'PearsonSimilarity' do
@engine.to_pearson
@engine.instance_eval('@similarity').instance_of?(PearsonSimilarity).should be_truthy
end
end
end
describe '#to_tanimoto' do
context 'when call' do
it 'PearsonSimilarity' do
@engine.to_tanimoto
@engine.instance_eval('@similarity').instance_of?(TanimotoSimilarity).should be_truthy
end
end
end
describe '#to_euclid' do
context 'when call' do
it 'EuclidSimilarity' do
@engine.to_euclid
@engine.instance_eval('@similarity').instance_of?(EuclidSimilarity).should be_truthy
end
end
end
end
end
|
class Student
attr_accessor :first_name
@@all = []
def initialize(first_name)
@first_name = first_name
@@all << self
end
def self.all
@@all
end
def tests_taken
BoatingTest.all.select do |test|
test.student == self
end
end
def instructors_taken
tests_taken.map do |test|
test.instructor
end
end
def add_boating_test(test_name, test_status, instructor)
BoatingTest.new(self, test_name, test_status, instructor)
end
def self.find_student(name)
self.all.select do |student|
student.first_name == name
end
end
def grade_percentage
student_test = BoatingTest.all.find_all { |test| test.student.first_name == self.first_name}
total = student_test.length.to_f
passed_total = student_test.find_all { |test| test.test_status == "passed" }
passed_num = passed_total.length.to_f
percent = (passed_num / total) * 100
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.