text stringlengths 10 2.61M |
|---|
##
# 05 - Project Euler
#
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def is_divisible(num)
if num % 1 == 0 &&
num % 2 == 0 &&
num % 3 == 0 &&
num % 4 == 0 &&
num % 5 == 0 &&
num % 6 == 0 &&
num % 7 == 0 &&
num % 8 == 0 &&
num % 9 == 0 &&
num % 10 == 0 &&
num % 11 == 0 &&
num % 12 == 0 &&
num % 13 == 0 &&
num % 14 == 0 &&
num % 15 == 0 &&
num % 16 == 0 &&
num % 17 == 0 &&
num % 18 == 0 &&
num % 19 == 0 &&
num % 20 == 0
return true
end
return false
end
# starting at 20 (highest factor), check if
# num is divisible by all factors 1..20.
# If not, add an additional 20 and try again.
num = 20
while is_divisible(num) == false
num += 20
end
# output when is_divisible(num) true
puts num
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :article do
title 'test_title'
body 'test_body'
pv 0
trait :has_comments do
after(:create) do |article, evaluate|
create_list(:comment, 1, article: article)
end
end
end
end
|
require 'server'
require "test_helper"
class ServerTest < MiniTest::Spec
include Rack::Test::Methods
def app
Sinatra::Application.new
end
def setup
@redis = Redis.new
@redis.flushall
@board = Leaderboard.new("game")
1.upto(15) do |i| @board["user#{i}"] = 100-i end
end
describe :index do
it "should return 200 status message" do
get "/"
assert 200, last_response.status
end
it "should return the top10 user with score in json" do
get "/"
iterations = 0
JSON.parse(last_response.body).each do |row|
expected_username = "user#{iterations+1}"
expected_score = 100-(iterations+1)
assert_equal expected_username, row["user"]
assert_equal expected_score, row["score"].to_i
iterations += 1
end
assert_equal 10, iterations
end
end
describe :show do
before { @user = "user11"; @score = 89.0; @rank = 11 }
it "should return 200 status message if user exists" do
get "/#{@user}"
assert 200, last_response.status
end
it "should return 404 status message if user does not exist" do
get "/appletree"
assert 404, last_response.status
end
it "should show the rank of a user" do
get "/user11"
response = JSON.parse(last_response.body)
assert_equal @user, response["user"]
assert_equal @rank, response["rank"]
assert_equal @score, response["score"]
end
end
describe :create do
it "should return 200 status message" do
post "/new_user/111"
assert 404, last_response.status
end
it "should create a user with score" do
post "/new_user/111"
assert_equal 111, @board["new_user"]
end
end
describe :update do
it "update the score of a user" do
assert_equal 99, @board["user1"]
post "/user1/1000"
assert_equal 1000, @board["user1"]
end
end
end |
class Group < ActiveRecord::Base
belongs_to :creator, :class_name => "User", :foreign_key => "creator_id"
has_many :memberships, :class_name => "GroupMembership", :dependent => :destroy
has_many :members, :through => :memberships, :uniq => true
has_many :group_scenarios, :dependent => :destroy
has_many :scenarios, :through => :group_scenarios
has_many :notification_emails, :class_name => "ClassNotificationEmail", :foreign_key => "class_id"
accepts_nested_attributes_for :group_scenarios, :allow_destroy => true
# uniqueness validation for code is useless.
# in lines 18-24, the while code finish after it does
# a query with the random code generated and doesn't find
# a group with that code
validates :code, :presence => true, :length => { :maximum => 200 }#, :uniqueness => true
validates :name, :length => {:maximum => 200 }
validates_uniqueness_of :name, :scope => :creator_id
validates_presence_of :name, :creator, :scenarios
before_validation(:on => :create) do
rcode = secure_rand
while(rcode)
self.code = rcode
rcode = Group.find_by_code(rcode) ? secure_rand : false
end
end
def create_memberships(user)
scenarios.each { |s| memberships.create(:member => user, :scenario => s) }
memberships.where(:member_id => user.id)
end
private
def secure_rand
ActiveSupport::SecureRandom.hex(3)
end
end
|
require_relative '../views/sessions_view'
class SessionsController
def initialize(employee_repository)
@employee_repository = employee_repository
@view = SessionsView.new
end
def sign_in
# Lógica de autenticação
username = @view.ask_for('username')
password = @view.ask_for('password')
employee = @employee_repository.find_by_username(username)
if employee && employee.password == password
@view.welcome_the_user(employee.username)
return employee
else
@view.wrong_credentials
# Chamada recursiva
sign_in
end
end
end
# require_relative '../repositories/employee_repository'
# repo = EmployeeRepository.new('data/employees.csv')
# controller = SessionsController.new(repo)
# controller.sign_in
|
module OutboundMessages
class << self
def welcome_message
"Welcome to Cuphon! Reply with STOP to stop. Reply HELP for help. Msg & data rates may apply. Max 3 msgs/week per brand. Visit Cuphon.com to learn more!"
end
def brand_too_long_message
"Welcome to Cuphon.com. Please make sure merchant names are less than 20 characters. Msg&data rates may apply. Reply with STOP to stop, HELP for help."
end
def subscribed_message(brand)
"You've been subscribed to #{brand}! Soon you'll get offers and deals directly from them, spread the word and keep discovering!"
end
def help_message
"Cuphon.com enables merchants to send offers and deals directly to your phone! Max 3 msgs/week per merchant. Reply STOP to cancel. Msg&data rates may apply."
end
def unsubscribe_all_message
"Your subscriptions have been suspended. To activate your subscriptions, reply with START at any time! Thx, Cuphon.com."
end
def unsubscribe_message(brand)
"Your subscription to #{brand} has been suspended. To activate your subscription, reply with START #{brand} at any time! Thx, Cuphon.com"
end
def not_currently_subscribed_message(brand)
"You are not currently subscribed to #{brand}."
end
def resetstatus_message
"You are now reset to a new user."
end
def sorry_message
"Sorry, we didn't understand your message. Reply HELP for help. Reply STOP to cancel messages."
end
def instant_cuphon_message(brand, description, url)
"Cuphon from #{brand}: #{description} More: #{url}"
end
def already_subscribed_message(brand)
"You are already subscribed to #{brand}."
end
def list_none_message
"You are not subscribed to any brands."
end
def list_cuphons_message(brands)
"You are subscribed to: #{brands.map { |b| b.title }.join(', ')}"
end
def restart_message
"Welcome back! Your subscriptions have been restarted again."
end
end
end |
class Exporter::ComplaintsOfficers < Exporter::Exporter
def column_definitions
column("ia_number") { record.complaint.ia_number }
column("case_number") { record.complaint.case_number }
column("incident_type") { record.complaint.incident_type }
column("received_date") { record.complaint.received_date }
column("occurred_date") { record.complaint.occurred_date }
column("summary") { record.complaint.summary }
column("name") { record.name }
column("title") { record.title }
column("badge") { record.badge }
column("allegation") { record.allegation }
column("finding") { record.finding }
column("finding_date") { record.finding_date }
column("action_taken") { record.action_taken.sort.join(", ") }
prefix("officer", Exporter::Officers) { record.officer }
end
def records
ComplaintOfficer.includes(:complaint, :officer, officer: [:pension, :zip_code, :complaint_officers, :complaints, complaint_officers: [:complaint]])
end
end
|
class SignUp < ActiveRecord::Base
has_secure_password
validates_confirmation_of :password
validates_uniqueness_of :email
has_one :set_lifts
end
|
module Main
class ProductSpecifications < DataObjects
class Type
attr_reader :product_type
def initialize(product_type)
@data = {
paintings: {
attribute_groups_definitions_using_instance_names: {
list: [:artist, :year],
for_visitor: [:artist, :year, :paint, :frames],
for_create: [:artist, :year, :paint, :frames],
for_update: [:id, :artist, :year, :paint, :frames],
},
attribute_names_by_instance_attribute_name: {
id: :id,
year: :smallint_1,
artist: :string_1,
paint: :string_2,
frames: :string_3
}
}
}
unless possible_type_names.include? product_type
raise "Undefined product type."
end
@product_type = product_type
@type_data = @data[@product_type]
end
def possible_type_names
@data.keys
end
def attribute_groups_definitions
definitions = {}
@type_data[:attribute_groups_definitions_using_instance_names]
.each_with_object(definitions) do |(group_name, instance_attribute_names)|
definitions[group_name] = instance_attribute_names.map! do |instance_name|
instance_attribute_name_to_general instance_name
end
end
definitions
end
def instance_attribute_name_to_general(instance_name)
@type_data[:attribute_names_by_instance_attribute_name][instance_name]
end
def instance_attribute_names
@type_data[:attribute_names_by_instance_attribute_name].keys
end
end
def initialize(pipe = nil)
super pipe
end
def load_from_db(needs)
self.type = needs[:type]
super
end
def load_from_params(needs)
self.type = needs[:type]
super
end
def type=(product_type)
@type = Type.new product_type
@attribute_groups = AttributeGroups.new @type.attribute_groups_definitions
end
def class_abbreviation
"PrS"
end
def specification_names
if type_set?
@type.instance_attribute_names
end
end
def attributes_of(attribute_group, options = {})
if type_set?
super
end
end
def create(attributes_or_product_id = nil)
if attributes_or_product_id.is_a? Fixnum
attributes, product_id = nil, attributes_or_product_id
else
attributes, product_id = attributes_or_product_id, nil
end
unless product_id.nil?
@runtime_table.row << {product_id: product_id}
end
super(attributes)
end
def type
@type.product_type
end
private
def type_set?
if @type.nil?
raise "Set #type= first"
end
true
end
end
end
|
require 'test_helper'
module Nls
module FeedInit
class TestInitErrors < NlsTestCommon
def setup
# override setup because this test do not need nls to be started
resetDir
end
def test_syntax_error
cp_import_fixture("package_with_error.json")
exception = assert_raises RuntimeError do
Nls.restart(log: false, daemon: false)
end
assert_exception_has_message "NlsReadImportFile: Json contains error in ligne 1 and column 5", exception
end
def test_package_already_exists
cp_import_fixture("several_same_package_in_file.json")
exception = assert_raises RuntimeError do
Nls.restart(log: false, daemon: false)
end
assert_exception_has_message "NlpCompilePackage: package with id='package_1' already exists" , exception
end
end
end
end
|
require_relative '../tests/test_helper'
require 'calmotron/song'
require 'calmotron/track'
require 'midilib'
class SongTest < MiniTest::Test
def test_attributes
valid_key_song = Song.new('A')
assert_equal(valid_key_song.key, 'A')
#Invalid keys default to C
invalid_key_song = Song.new('Q')
assert_equal(invalid_key_song.key, 'C')
end
def test_to_midi_sequence
song = Song.new('C')
song.add_track(1, 1)
song.add_section((1..5).to_a)
output = song.to_midi_sequence
assert_instance_of(MIDI::Sequence, output)
# first output track is reserved for program changes
assert_equal(1, output.tracks.first.events.count)
# second output track should reflect our created track
output_track_events = output.tracks[1].events
assert_equal(32, output_track_events.count)
assert_instance_of(MIDI::NoteOn, output_track_events.first)
assert_instance_of(MIDI::NoteOff, output_track_events.last)
end
def test_add_track
song = Song.new('C')
song.add_track(1, 2)
bass_track = song.tracks.first
assert_equal(bass_track.octave, 1)
assert_equal(bass_track.duration_multiplier, 2)
end
end
|
# Copyright 2014 Square Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Source mapping information for a JavaScript project. This model stores a
# mapping of generated JavaScript code location and symbol names to
# corresponding location and names in the original code. See the Squash
# JavaScript client library documentation for more information.
#
# Even if your project is not using minified code, this class is also useful for
# mapping the URLs of deployed JavaScript assets to their original source files.
#
# ### Serialization
#
# Mapping data is generated using the "squash_javascript" gem. The gem produces
# a memory representation of the source map. The gem is also included in this
# project to support deserializing the resulting data.
#
# Serialization is accomplished by zlib-encoding the JSON source map, and then
# base-64-encoding the compressed output. This is also how the `map` property is
# transmitted over the wire.
#
# No support is given for modifying these objects after they have been
# deserialized.
#
# ### Source maps in stages
#
# Oftentimes a project's JavaScript code moves through different transformations
# before reaching a final deployed state. For example, the development code
# could be in CoffeeScript, which is then compiled to JavaScript, then
# concatenated, then minified (a three-stage process). The client may generate
# source maps for each of those stages.
#
# In order to convert a stack trace from its original format into one useful in
# the development code, these source maps must be applied in the correct order.
# To facilitate this, SourceMap records have a `from` and `to` field. Stack
# traces are annotated with their production format ("hosted"), and Squash
# searches for source maps that it can apply to that format. It continues to
# search for applicable source maps until the stack trace's format is not
# convertible any further.
#
# Stack traces are searched in a simple linear order and applied as they are
# found applicable. No fancy dependency trees are built.
#
# For example, say the following stack trace was provided:
#
# ````
# 1: foo/bar.js:123 (concatenated)
# 2. foo/baz.js:234 (hosted)
# ````
#
# Squash would first note that line 1 is concatenated, and attempt to locate a
# sourcemap whose `from` field is "concatenated" that has an entry for that file
# and line. It would perhaps find one whose `to` field is "compiled", so it
# would apply that source map, resulting in a different stack trace element
# whose type is "compiled". It would then search again for another source map,
# this time one whose `from` field was "compiled", and finding one, apply it,
# resulting in a new stack trace of type "coffee". Finding no source maps whose
# `from` field is "coffee", Squash would be finished with that line.
#
# Line two would proceed similarly, except Squash might find a source map with
# a `from` of "hosted" and a `to` of "concatenated". From there, the logic would
# proceed as described previously.
#
# The Squash JavaScript client library always adds the type of "hosted" to
# each line of the original backtrace, so your source-mapping journey should
# begin there.
#
# Associations
# ------------
#
# | | |
# |:--------------|:----------------------------------------------|
# | `environment` | The {Environment} this source map pertain to. |
#
# Properties
# ----------
#
# | | |
# |:-------|:---------------------------------------------------------------------------------|
# | `map` | A serialized source map. |
# | `filename` | The name of the file this source map maps from. |
# | `from` | An identifier indicating what kind of JavaScript code this source map maps from. |
# | `to` | An identifier indicating what kind of JavaScript code this source map maps to. |
class SourceMap < ActiveRecord::Base
belongs_to :environment, inverse_of: :source_maps
validates :environment,
presence: true
validates :revision,
presence: true,
known_revision: {repo: ->(map) { RepoProxy.new(map, :environment, :project) }}
validates :from, :to,
presence: true,
length: {maximum: 24}
validates :filename,
presence: true,
strict: true
before_validation :set_filename, on: :create
after_commit(on: :create) do |map|
BackgroundRunner.run SourceMapWorker, map.id
end
attr_readonly :revision
# @private
def map
@map ||= GemSourceMap::Map.from_json(
Zlib::Inflate.inflate(
Base64.decode64(read_attribute(:map))))
end
# @private
def map=(m)
raise TypeError, "expected GemSourceMap::Map, got #{m.class}" unless m.kind_of?(GemSourceMap::Map)
write_attribute :map, Base64.encode64(Zlib::Deflate.deflate(m.as_json.to_json))
end
# @private
def raw_map=(m)
write_attribute :map, m
end
# Given a line of code within a file in the `from` format, attempts to resolve
# it to a line of code within a file in the `to` format.
#
# @param [String] route The URL of the generated JavaScript file.
# @param [Fixnum] line The line of code
# @param [Fixnum] column The character number within the line.
# @return [Hash, nil] If found, a hash consisting of the source file path,
# line number, and method name.
def resolve(route, line, column)
return nil unless column # firefox doesn't support column numbers
return nil unless map.filename == route || begin
uri = URI.parse(route) rescue nil
if uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
uri.path == map.filename
else
false
end
end
mapping = map.bsearch(GemSourceMap::Offset.new(line, column))
return nil unless mapping
{
'file' => mapping.source,
'line' => mapping.original.line,
'column' => mapping.original.column
}
end
private
def set_filename
self.filename = map.filename
end
end
|
module Smtp
class Message < String
DEFAULT_CONTENT_TRANSFER_ENCODING = ContentTransferEncoding.new(
ContentTransferEncoding::EIGHT_BIT
)
def initialize(value, content_type = ContentType.new(ContentType::HTML))
super "#{value}\n"
@content_type = content_type
end
def as_part_of_smtp_message
Headers.new(
@content_type.as_header,
DEFAULT_CONTENT_TRANSFER_ENCODING.as_header,
GenericHeader::NEW_LINE_HEADER
).to_s + self
end
end
end
|
class VideosController < ApplicationController
before_action :ensure_admin!
before_action :set_video, only: [:edit, :update, :destroy]
def new
@video = Video.new
@trail_id = params[:id]
end
def edit
end
def create
@video = Video.new(video_params)
@trail = Trail.find(@video.trail_id)
if @video.save
redirect_to @trail
else
render 'new'
end
end
def update
@video.update(video_params)
redirect_to @trail
end
def destroy
@video.destroy
redirect_to @trail
end
private
def set_video
@video = Video.find(params[:id])
@trail = Trail.find(@video.trail_id)
end
def video_params
params.require(:video).permit(:src,:trail_id)
end
end
|
class User < ActiveRecord::Base
has_secure_password
validates :email, presence: true
scope :for, ->(activity) do
joins(:permissions).where(permissions: { action: "view",
thing_type: "Activity",
thing_id: activity.id })
end
has_many :permissions
def to_s
"#{email} (#{admin? ? "Admin" : "User"})"
end
end
|
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Author: Martin Magr <mmagr@redhat.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Adds OPM CI path to LOAD_PATH
$:.unshift(File.dirname(File.dirname(__FILE__)))
require 'serverspec'
describe file('/etc/sahara/sahara.conf') do
it { should be_file }
it { should be_mode 640 }
it { should be_owned_by 'root' }
it { should be_grouped_into 'sahara' }
its(:content) { should match '^#use_neutron = false$' }
its(:content) { should match '^#use_floating_ips = true$' }
#its(:content) { should match 'host = 0.0.0.0' }
its(:content) { should match '^#port = 8386$' }
its(:content) { should match '^#debug = false$' }
its(:content) { should match '^#verbose = true$' }
its(:content) { should match(/^connection = mysql\+pymysql:\/\/sahara:a_big_secret@127.0.0.1\/sahara\?charset=utf8$/) }
its(:content) { should match '^auth_uri = http://127.0.0.1:5000/v2.0/$' }
its(:content) { should match(/^identity_uri=http:\/\/127.0.0.1:35357\/$/) }
its(:content) { should match '^admin_tenant_name=services$' }
its(:content) { should match '^admin_password=a_big_secret$' }
its(:content) { should match '^admin_user=sahara$' }
its(:content) { should match '^log_dir = /var/log/sahara$' }
its(:content) { should match '^#use_syslog = false$' }
its(:content) { should match '^rabbit_host = 127.0.0.1$' }
its(:content) { should match '^#rabbit_port = 5672$' }
its(:content) { should match '^#rabbit_ha_queues = false$' }
its(:content) { should match '^#rabbit_hosts = \$rabbit_host:\$rabbit_port' }
its(:content) { should match '^rpc_backend = rabbit$' }
its(:content) { should match '^#amqp_durable_queues = false$' }
its(:content) { should match '^#rabbit_use_ssl = false$' }
its(:content) { should match '^rabbit_userid = sahara$' }
its(:content) { should match '^rabbit_password = an_even_bigger_secret$' }
its(:content) { should match '^#rabbit_login_method = AMQPLAIN$' }
its(:content) { should match '^#rabbit_virtual_host = /$' }
its(:content) { should match '^#rabbit_retry_interval = 1$' }
its(:content) { should match '^#rabbit_retry_backoff = 2$' }
its(:content) { should match '^#rabbit_max_retries = 0$' }
its(:content) { should match '^#topics = notifications$' }
its(:content) { should match '^#control_exchange = openstack$' }
its(:content) { should match '^#kombu_reconnect_delay = 1.0$' }
end
|
class FontNotoSans < Formula
head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSans-unhinted.zip", verified: "noto-website-2.storage.googleapis.com/"
desc "Noto Sans"
homepage "https://www.google.com/get/noto/#sans-lgc"
def install
(share/"fonts").install "NotoSans-Black.ttf"
(share/"fonts").install "NotoSans-BlackItalic.ttf"
(share/"fonts").install "NotoSans-Bold.ttf"
(share/"fonts").install "NotoSans-BoldItalic.ttf"
(share/"fonts").install "NotoSans-Condensed.ttf"
(share/"fonts").install "NotoSans-CondensedBlack.ttf"
(share/"fonts").install "NotoSans-CondensedBlackItalic.ttf"
(share/"fonts").install "NotoSans-CondensedBold.ttf"
(share/"fonts").install "NotoSans-CondensedBoldItalic.ttf"
(share/"fonts").install "NotoSans-CondensedExtraBold.ttf"
(share/"fonts").install "NotoSans-CondensedExtraBoldItalic.ttf"
(share/"fonts").install "NotoSans-CondensedExtraLight.ttf"
(share/"fonts").install "NotoSans-CondensedExtraLightItalic.ttf"
(share/"fonts").install "NotoSans-CondensedItalic.ttf"
(share/"fonts").install "NotoSans-CondensedLight.ttf"
(share/"fonts").install "NotoSans-CondensedLightItalic.ttf"
(share/"fonts").install "NotoSans-CondensedMedium.ttf"
(share/"fonts").install "NotoSans-CondensedMediumItalic.ttf"
(share/"fonts").install "NotoSans-CondensedSemiBold.ttf"
(share/"fonts").install "NotoSans-CondensedSemiBoldItalic.ttf"
(share/"fonts").install "NotoSans-CondensedThin.ttf"
(share/"fonts").install "NotoSans-CondensedThinItalic.ttf"
(share/"fonts").install "NotoSans-ExtraBold.ttf"
(share/"fonts").install "NotoSans-ExtraBoldItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensed.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedBlack.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedBlackItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedBold.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedBoldItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedExtraBold.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedExtraBoldItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedExtraLight.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedExtraLightItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedLight.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedLightItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedMedium.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedMediumItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedSemiBold.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedSemiBoldItalic.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedThin.ttf"
(share/"fonts").install "NotoSans-ExtraCondensedThinItalic.ttf"
(share/"fonts").install "NotoSans-ExtraLight.ttf"
(share/"fonts").install "NotoSans-ExtraLightItalic.ttf"
(share/"fonts").install "NotoSans-Italic.ttf"
(share/"fonts").install "NotoSans-Light.ttf"
(share/"fonts").install "NotoSans-LightItalic.ttf"
(share/"fonts").install "NotoSans-Medium.ttf"
(share/"fonts").install "NotoSans-MediumItalic.ttf"
(share/"fonts").install "NotoSans-Regular.ttf"
(share/"fonts").install "NotoSans-SemiBold.ttf"
(share/"fonts").install "NotoSans-SemiBoldItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensed.ttf"
(share/"fonts").install "NotoSans-SemiCondensedBlack.ttf"
(share/"fonts").install "NotoSans-SemiCondensedBlackItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedBold.ttf"
(share/"fonts").install "NotoSans-SemiCondensedBoldItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedExtraBold.ttf"
(share/"fonts").install "NotoSans-SemiCondensedExtraBoldItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedExtraLight.ttf"
(share/"fonts").install "NotoSans-SemiCondensedExtraLightItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedLight.ttf"
(share/"fonts").install "NotoSans-SemiCondensedLightItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedMedium.ttf"
(share/"fonts").install "NotoSans-SemiCondensedMediumItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedSemiBold.ttf"
(share/"fonts").install "NotoSans-SemiCondensedSemiBoldItalic.ttf"
(share/"fonts").install "NotoSans-SemiCondensedThin.ttf"
(share/"fonts").install "NotoSans-SemiCondensedThinItalic.ttf"
(share/"fonts").install "NotoSans-Thin.ttf"
(share/"fonts").install "NotoSans-ThinItalic.ttf"
end
test do
end
end
|
class Review < ActiveRecord::Base
belongs_to :video
belongs_to :user
validates :message, presence: true
validates :rating, presence: true,
inclusion: (0..5).to_a
end
|
require 'test_helper'
class ProfilePicTest < ActiveSupport::TestCase
setup do
@profile = profiles(:dragon_profile_1)
@pic = profile_pics(:dragon_profile_pic_1)
@file_path = File.join(Rails.root, 'test', 'fixtures', 'files', 'Chimera-240.jpg')
end
test "make default" do
image = Rack::Test::UploadedFile.new(@file_path, 'image/jpeg')
new_pic = ProfilePic.create(profile: @profile, image: image)
assert_not new_pic.is_default?
assert @pic.is_default?
new_pic.make_default!
@pic.reload
new_pic.reload
assert new_pic.is_default?,
"new profile pic was not set to default"
assert_not @pic.is_default?,
"old profile pic is still set default"
end
test "after create make default if there are no other pics set default" do
@profile = profiles(:raccoon_profile_1)
image = Rack::Test::UploadedFile.new(@file_path, 'image/jpeg')
@pic = ProfilePic.create(profile: @profile, image: image)
assert @pic.is_default?,
"only profile pic was not set to default"
end
test "after destroy make sure a default gets set if default gets destroyed" do
new_pic = profile_pics(:dragon_profile_pic_2)
assert_not new_pic.is_default?
assert @pic.is_default?
@pic.destroy
new_pic.reload
assert new_pic.is_default?,
"a new default profile pic was not set"
end
test "ensure default pic should still work if no profile pics remain" do
assert_difference 'ProfilePic.count', -1 do
@pic.destroy
end
end
end
|
# frozen_string_literal: true
require 'selenium-webdriver'
require 'rspec'
require 'sauce_whisk'
Before do |scenario|
url = 'https://ondemand.us-west-1.saucelabs.com:443/wd/hub'
SauceWhisk.data_center = :US_WEST
if ENV['PLATFORM_NAME'] == 'linux' # Then Headless
url = 'https://ondemand.us-east-1.saucelabs.com:443/wd/hub'
SauceWhisk.data_center = :US_EAST
end
browser_name = ENV['BROWSER_NAME'] || 'chrome'
options = Selenium::WebDriver::Options.send(browser_name)
options.platform_name = ENV['PLATFORM_NAME'] || 'Windows 10'
options.browser_version = ENV['BROWSER_VERSION'] || 'latest'
sauce_options = {name: "#{scenario.feature.name} - #{scenario.name}",
build: build_name,
username: ENV['SAUCE_USERNAME'],
access_key: ENV['SAUCE_ACCESS_KEY']}
options.add_option('sauce:options', sauce_options)
@driver = Selenium::WebDriver.for(:remote,
url: url,
capabilities: options)
end
After do |scenario|
SauceWhisk::Jobs.change_status(@driver.session_id, scenario.passed?)
@driver.quit
end
#
# Note that this build name is specifically for Circle CI execution
# Most CI tools have ENV variables that can be structured to provide useful build names
#
def build_name
if ENV['CIRCLE_JOB']
"#{ENV['CIRCLE_JOB']}: #{ENV['CIRCLE_BUILD_NUM']}"
elsif ENV['SAUCE_BUILD_NAME']
ENV['SAUCE_BUILD_NAME']
else
"Ruby-Cucumber-Selenium: Local-#{Time.now.to_i}"
end
end
|
FactoryGirl.define do
factory :user do
uid { rand(1...3).to_s }
screen_name { '@' + Faker::Lorem.word }
token { Faker::Crypto.md5 }
secret { Faker::Crypto.md5 }
end
end
|
require 'test_helper'
class CrimeFilesControllerTest < ActionDispatch::IntegrationTest
setup do
@crime_file = crime_files(:one)
end
test "should get index" do
get crime_files_url
assert_response :success
end
test "should get new" do
get new_crime_file_url
assert_response :success
end
test "should create crime_file" do
assert_difference('CrimeFile.count') do
post crime_files_url, params: { crime_file: { } }
end
assert_redirected_to crime_file_url(CrimeFile.last)
end
test "should show crime_file" do
get crime_file_url(@crime_file)
assert_response :success
end
test "should get edit" do
get edit_crime_file_url(@crime_file)
assert_response :success
end
test "should update crime_file" do
patch crime_file_url(@crime_file), params: { crime_file: { } }
assert_redirected_to crime_file_url(@crime_file)
end
test "should destroy crime_file" do
assert_difference('CrimeFile.count', -1) do
delete crime_file_url(@crime_file)
end
assert_redirected_to crime_files_url
end
end
|
# = sckey.rb
#
# Description:: Straddling Checkerboard key
# Author:: Ollivier Robert <roberto@keltia.net>
# Copyright:: © 2001-2013 by Ollivier Robert
#
# $Id: sckey.rb,v 215f60fa1e7f 2013/03/10 17:52:14 roberto $
require 'key/skey'
module Key
# == SCKey
#
# class for straddling checkerboard substitution keys
#
# SC-keys needs to be condensed and rings generated for ciphering/deciphering
#
# See http://en.wikipedia.org/wiki/Straddling_checkerboard
class SCKey < SKey
include Crypto
BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ/-'
attr_reader :full_key, :shortc, :longc
def initialize(key, longc = [ 8, 9 ])
super(key)
@longc = longc
@full_key = keyshuffle(@key, BASE)
gen_rings()
end
# == gen_rings
#
# Assign a code number for each letter. Each code number is
# sequentially allocated from two pools, one with 0..7 and
# the other with 80..99.
#
# Allocation is made on the following criterias
# - if letter is one of ESANTIRU assign a single code number
# - else assign of of the two letters ones
#
# Generate both the encoding and decoding rings.
#
def gen_rings
shortc = (0..9).collect{|i| i unless @longc.include?(i) }.compact
raise DataError if shortc.nil?
long = @longc.collect{|i| (0..9).collect{|j| i*10+j } }.flatten
raise DataError if long.nil?
@shortc = shortc.dup
word = @full_key.dup
word.scan(/./) do |c|
if 'ESANTIRU'.include? c then
ind = shortc.shift
else
ind = long.shift
end
@alpha[c] = ind.to_s
@ralpha[ind.to_s] = c
end
end # -- gen_rings
# === is_long?
#
def is_long?(digit)
return @longc.include?(digit)
end # -- is_long?
end # -- SCKey
end # -- Key
|
class AddSaveToAction < ActiveRecord::Migration
def change
add_column :actions, :save_attr, :string
end
end
|
require "test_helper"
describe Vote do
before do
@new_user = User.create!(username: "Mochi Cat")
@new_work = Work.create!(
category: "book",
title: "Harry Potter",
creator: "JK Rowling",
publication_year: 1990,
description: "great book"
)
@new_vote = Vote.new(work_id: @new_work.id, user_id: @new_user.id)
end
describe "validations" do
it "can instantiate a valid vote" do
expect(@new_vote.save).must_equal true
end
it "will have the required fields" do
@new_vote.save
vote = Vote.last
[:work_id, :user_id].each do |field|
expect(vote).must_respond_to field
end
end
it "will not instantiate a vote without a valid work_id" do
@new_vote.work_id = nil
expect(@new_vote.valid?).must_equal false
expect(@new_vote.errors.messages).must_include :work
expect(@new_vote.errors.messages[:work]).must_equal ["must exist"]
@new_vote.work_id = -1
expect(@new_vote.valid?).must_equal false
expect(@new_vote.errors.messages).must_include :work
expect(@new_vote.errors.messages[:work]).must_equal ["must exist"]
end
it "will not instantiate a vote without a valid user_id" do
@new_vote.user_id = nil
expect(@new_vote.valid?).must_equal false
expect(@new_vote.errors.messages).must_include :user
expect(@new_vote.errors.messages[:user]).must_equal ["must exist"]
@new_vote.user_id = -1
expect(@new_vote.valid?).must_equal false
expect(@new_vote.errors.messages).must_include :user
expect(@new_vote.errors.messages[:user]).must_equal ["must exist"]
end
it "cannot instantiate a vote with the same user and work id combinations" do
@new_vote.save
duplicate_vote = Vote.new(work_id: @new_work.id, user_id: @new_user.id)
expect(duplicate_vote.valid?).must_equal false
expect(duplicate_vote.errors.messages).must_include :user_id
expect(duplicate_vote.errors.messages[:user_id]).must_equal ["has already voted for this work"]
end
end
describe "relationships" do
describe "belongs to a user" do
it "can set the user through user" do
vote = Vote.new(work_id: @new_work.id)
vote.user = @new_user
expect(vote.user_id).must_equal @new_user.id
end
it "can set the user through user_id" do
vote = Vote.new(work_id: @new_work.id)
vote.user_id = @new_user.id
expect(vote.user).must_equal @new_user
end
end
describe "belongs to a work" do
it "can set the work through work" do
vote = Vote.new(user_id: @new_user.id)
vote.work = @new_work
expect(vote.work_id).must_equal @new_work.id
end
it "can set the work through work_id" do
vote = Vote.new(user_id: @new_user.id)
vote.work_id = @new_work.id
expect(vote.work).must_equal @new_work
end
end
end
end
|
class News < ApplicationRecord
belongs_to :admin, optional: true
attr_accessor :body
def read_file(file_path)
self.body = File.open("#{Rails.root}/public/#{file_path}", 'r'){ |f| f.read }
end
end |
module Forem
class Post < ActiveRecord::Base
include Workflow
include Forem::Concerns::NilUser
workflow_column :state
workflow do
state :pending_review do
event :spam, :transitions_to => :spam
event :approve, :transitions_to => :approved
end
state :spam
state :approved do
event :approve, :transitions_to => :approved
end
end
# Used in the moderation tools partial
attr_accessor :moderation_option
belongs_to :topic
belongs_to :forem_user, :class_name => Forem.user_class.to_s, :foreign_key => :user_id
belongs_to :reply_to, :class_name => "Post"
has_many :replies, :class_name => "Post",
:foreign_key => "reply_to_id",
:dependent => :nullify
validates :text, :presence => true
delegate :forum, :to => :topic
after_create :set_topic_last_post_at
after_create :subscribe_replier, :if => :user_auto_subscribe?
after_create :skip_pending_review
class << self
def approved
where(:state => "approved")
end
def approved_or_pending_review_for(user)
if user
where arel_table[:state].eq('approved').or(
arel_table[:state].eq('pending_review').and(arel_table[:user_id].eq(user.id))
)
else
approved
end
end
def by_created_at
order :created_at
end
def pending_review
where :state => 'pending_review'
end
def spam
where :state => 'spam'
end
def visible
joins(:topic).where(:forem_topics => { :hidden => false })
end
def topic_not_pending_review
joins(:topic).where(:forem_topics => { :state => 'approved'})
end
def moderate!(posts)
posts.each do |post_id, moderation|
# We use find_by_id here just in case a post has been deleted.
post = Post.find_by_id(post_id)
post.send("#{moderation[:moderation_option]}!") if post
end
end
end
def user_auto_subscribe?
user && user.respond_to?(:forem_auto_subscribe) && user.forem_auto_subscribe?
end
def owner_or_admin?(other_user)
user == other_user || other_user.forem_admin?
end
protected
def subscribe_replier
if topic && user
topic.subscribe_user(user.id)
end
end
# Called when a post is approved.
def approve
approve_user
return if notified?
email_topic_subscribers
end
def email_topic_subscribers
topic.subscriptions.includes(:subscriber).find_each do |subscription|
subscription.send_notification(id) if subscription.subscriber != user
end
update_column(:notified, true)
end
def set_topic_last_post_at
topic.update_column(:last_post_at, created_at)
end
def skip_pending_review
approve! unless user && user.forem_moderate_posts?
end
def approve_user
user.update_column(:forem_state, "approved") if user && user.forem_state != "approved"
end
def spam
user.update_column(:forem_state, "spam") if user
end
end
end
|
class CompanyAdmin < ApplicationRecord
has_many :projects
has_many :employees
attr_accessor :presence_password
has_secure_password validations: false
validates :password, presence: true , if: :presence_password
has_secure_token
validates :username, presence: true , length: { maximum: 15 }, uniqueness: true
validates_confirmation_of :password
validates :companyname , presence: true
validates :email, presence: true, length: { :maximum => 40 },uniqueness: true,
format: /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i
has_attached_file :logo , styles: { small: "64x64", med: "100x100", large: "200x200" }
validates_attachment :logo , presence: true,
size:{ :in => 0..100.kilobytes },
content_type: { :content_type => "image/jpeg" }
def with_unexpired_token(token, period)
where(token: token).where('token_created_at >= ?', period).first
end
def generate_password_token!
self.reset_password_token = generate_token
self.reset_password_sent_at = Time.now.utc #??
save!
end
def password_token_valid?
(self.reset_password_sent_at + 4.hours) > Time.now.utc
end
def reset_password!(password , password_confirmation)
self.reset_password_token = nil
update_attributes(password: password , password_confirmation: password_confirmation)
end
def send_recover_email
CompanyAdminMailer.recover_password_email(self).deliver_later
end
private
def generate_token
SecureRandom.hex(10)
end
end |
# Create table sections
class CreateSections < ActiveRecord::Migration[5.1]
# Create table
def change
create_table :sections do |t|
t.string :name
t.string :initials
t.integer :status
t.text :observation
t.integer :kind
t.timestamps
end
end
end
|
# -*- encoding : utf-8 -*-
class ChmailsController < ApplicationController
layout 'admin'
before_filter :confirm_logged_in
before_filter :confirm_priveleges_admin
def index
@chmails = Chmail.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @chmails }
end
end
def show
@chmail = Chmail.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @chmail }
end
end
def new
@chmail = Chmail.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @chmail }
end
end
def edit
@chmail = Chmail.find(params[:id])
end
def create
@chmail = Chmail.new(params[:chmail])
respond_to do |format|
if @chmail.save
format.html { redirect_to @chmail, notice: 'Chmail was successfully created.' }
format.json { render json: @chmail, status: :created, location: @chmail }
else
format.html { render action: "new" }
format.json { render json: @chmail.errors, status: :unprocessable_entity }
end
end
end
def update
@chmail = Chmail.find(params[:id])
respond_to do |format|
if @chmail.update_attributes(params[:chmail])
format.html { redirect_to @chmail, notice: 'Chmail was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @chmail.errors, status: :unprocessable_entity }
end
end
end
def destroy
@chmail = Chmail.find(params[:id])
@chmail.destroy
respond_to do |format|
format.html { redirect_to chmails_url }
format.json { head :no_content }
end
end
end
|
class OldRelation < ActiveRecord::Base
include ConsistencyValidations
set_table_name 'relations'
belongs_to :changeset
validates_associated :changeset
def self.from_relation(relation)
old_relation = OldRelation.new
old_relation.visible = relation.visible
old_relation.changeset_id = relation.changeset_id
old_relation.timestamp = relation.timestamp
old_relation.id = relation.id
old_relation.version = relation.version
old_relation.members = relation.members
old_relation.tags = relation.tags
return old_relation
end
def save_with_dependencies!
# see comment in old_way.rb ;-)
save!
clear_aggregation_cache
clear_association_cache
@attributes.update(OldRelation.find(:first, :conditions => ['id = ? AND timestamp = ?', self.id, self.timestamp], :order => "version desc").instance_variable_get('@attributes'))
# ok, you can touch from here on
self.tags.each do |k,v|
tag = OldRelationTag.new
tag.k = k
tag.v = v
tag.id = self.id
tag.version = self.version
tag.save!
end
self.members.each_with_index do |m,i|
member = OldRelationMember.new
member.id = [self.id, self.version, i]
member.member_type = m[0].classify
member.member_id = m[1]
member.member_role = m[2]
member.save!
end
end
def members
unless @members
@members = Array.new
OldRelationMember.find(:all, :conditions => ["id = ? AND version = ?", self.id, self.version], :order => "sequence_id").each do |m|
@members += [[m.type,m.id,m.role]]
end
end
@members
end
def tags
unless @tags
@tags = Hash.new
OldRelationTag.find(:all, :conditions => ["id = ? AND version = ?", self.id, self.version]).each do |tag|
@tags[tag.k] = tag.v
end
end
@tags = Hash.new unless @tags
@tags
end
def members=(s)
@members = s
end
def tags=(t)
@tags = t
end
# has_many :relation_segments, :class_name => 'OldRelationSegment', :foreign_key => 'id'
# has_many :relation_tags, :class_name => 'OldRelationTag', :foreign_key => 'id'
def old_members
OldRelationMember.find(:all, :conditions => ['id = ? AND version = ?', self.id, self.version], :order => "sequence_id")
end
def old_tags
OldRelationTag.find(:all, :conditions => ['id = ? AND version = ?', self.id, self.version])
end
def to_xml
doc = OSM::API.new.get_xml_doc
doc.root << to_xml_node()
return doc
end
def to_xml_node
el1 = XML::Node.new 'relation'
el1['id'] = self.id.to_s
el1['visible'] = self.visible.to_s
el1['timestamp'] = self.timestamp.xmlschema
if self.changeset.user.data_public?
el1['user'] = self.changeset.user.display_name
el1['uid'] = self.changeset.user.id.to_s
end
el1['version'] = self.version.to_s
el1['changeset'] = self.changeset_id.to_s
self.old_members.each do |member|
e = XML::Node.new 'member'
e['type'] = member.member_type.to_s.downcase
e['ref'] = member.member_id.to_s # "id" is considered uncool here as it should be unique in XML
e['role'] = member.member_role.to_s
el1 << e
end
self.old_tags.each do |tag|
e = XML::Node.new 'tag'
e['k'] = tag.k
e['v'] = tag.v
el1 << e
end
return el1
end
# Temporary method to match interface to nodes
def tags_as_hash
return self.tags
end
# Temporary method to match interface to relations
def relation_members
return self.old_members
end
# Pretend we're not in any relations
def containing_relation_members
return []
end
end
|
class FavoritesController < ApplicationController
before_action :set_book
def create
favorite = @book.favorites.new(user_id: current_user.id)
favorite.save
end
def destroy
favorite = current_user.favorites.find_by(book_id: @book.id)
favorite.destroy
end
private
def set_book
@book = Book.find(params[:book_id])
end
end
|
require 'rails_helper'
RSpec.feature 'Changing employee state' do
before do
@admin = create(:admin)
login_as(@admin, scope: :admin)
end
scenario 'by activing him' do
@employee = create(:employee, state: 0)
visit admin_employees_path
expect(page).to have_content(@employee.full_name)
expect(@employee.state).to eq('inactive')
expect(page).to have_link('Activate')
click_link('Activate')
expect(Employee.first.active?).to eq(true)
end
scenario 'by deactivating him' do
@employee = create(:employee)
visit admin_employees_path
expect(page).to have_content(@employee.full_name)
expect(@employee.state).to eq('active')
expect(page).to have_link('Deactivate')
click_link('Deactivate')
expect(Employee.first.inactive?).to eq(true)
end
end
|
class ArtistsController < ApplicationController
before_action :set_artist, only: [:show, :update]
# GET /artists
# GET /artists.json
def index
@artists = Artist.paginate(page: params[:page], per_page:6)
end
# GET /artists/1
# GET /artists/1.json
def show
@concerts = @artist.concerts.paginate(page: params[:page], per_page:6)
end
private
# Use callbacks to share common setup or constraints between actions.
def set_artist
@artist = Artist.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def artist_params
params.require(:artist).permit(:name, :description, :image, :remote_image_url)
end
end
|
class Curso < ActiveRecord::Base
self.primary_key = :id_curso
belongs_to :category, :class_name => 'Category', :foreign_key => :id_categoria
has_many :dispositivos, :class_name => 'Dispositivo', :foreign_key => :id_curso
has_many :facilitador_has_cursos, :class_name => 'FacilitadorHasCurso'
has_many :incidencs, :class_name => 'Incidenc', :foreign_key => :id_curso
has_many :lapso_cursos, :class_name => 'LapsoCurso', :foreign_key => :id_curso
has_many :matriculas, :class_name => 'Matricula', :foreign_key => :id_curso
has_many :modulos, :class_name => 'Modulo', :foreign_key => :id_curso , :dependent => :destroy
has_many :publicidads, :class_name => 'Publicidad', :foreign_key => :id_curso
def self.allCursos
Curso.all
end
def self.crear_Curso(nombre)
@curso = Curso.new( :nombre =>nombre)
@curso.save
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# name :string(255) default(""), not null
# bio :string(255) default(""), not null
# avatar_file_name :string(255)
# avatar_content_type :string(255)
# avatar_file_size :integer
# avatar_updated_at :datetime
# admin :boolean default("f"), not null
# authentication_token :string(255)
#
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :timeoutable,
:omniauthable, :omniauth_providers => [:facebook, :google_oauth2, :github]
before_create :record_first_admin
before_save :ensure_authentication_token
alias_attribute :private_token, :authentication_token
has_attached_file :avatar, :styles => { :medium => "165x165#", :thumb => "100x100#" }, :default_url => "/images/avatar_missing.png"
has_many :identities
has_many :project_members, dependent: :destroy
has_many :project_openings, dependent: :destroy
has_many :projects, through: :project_members
has_many :tasks, :foreign_key => 'assignee_id'
# Scopes
scope :admins, -> { where(admin: true) }
#
# Validations
#
validates :name, presence: true, uniqueness: true
validates :bio, length: { maximum: 500 }, allow_blank: true
validates_attachment_content_type :avatar, :content_type => /\Aimage/
validates_attachment_size :avatar, :in => 0.megabytes..100.kilobytes
def is_admin?
admin
end
def attributes
super.merge({'avatar_url' => avatar_url})
end
def avatar_url
ApplicationController.helpers.avatar_icon(email)
end
def ensure_authentication_token
self.authentication_token ||= generate_authentication_token
end
def work_logged
WorkLog.joins(task: :assignee).select("sum(worked) as work_sum").where(tasks:{assignee_id:id}).take.work_sum || 0
end
def work_week(period_start, period_end)
day_start = period_start.strftime("%Y%m%d")
day_end = period_end.strftime("%Y%m%d")
logs = WorkLog.joins(task: :project).select("project_id, projects.name as name, day, sum(worked) as total_worked").where(day:day_start..day_end).where(tasks:{assignee_id:id}).group("project_id, projects.name, day")
WorkWeek.new(logs)
end
#
# Class methods
#
class << self
def search query
where("lower(name) LIKE :query OR lower(email) LIKE :query", query: "%#{query.downcase}%")
end
def from_omniauth(auth)
user = nil
identity = Identity.where(provider: auth.provider, uid: auth.uid).first
if identity
user = identity.user
else
user = User.find_by(email: auth.info.email) || User.create(email: auth.info.email, password: Devise.friendly_token[0,20], name: (auth.info.name || auth.info.full_name).to_s)
identity = Identity.create(provider: auth.provider, uid: auth.uid, user: user)
end
user
end
end
private
# First user is always super admin
def record_first_admin
if User.count == 0
self.admin = true
end
end
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
end
|
class Listing < ApplicationRecord
belongs_to :product
belongs_to :store, dependent: :destroy
before_validation :format_price_string
validates :price, presence: true
def format_price_string
self.price = price.gsub('$', '').strip #code from my old CSV
end
end
|
xml.urlset(xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9') do
xml.url do
xml.loc root_url
xml.changefreq('hourly')
xml.priority '1.0'
end
end
|
class CreateOrders < ActiveRecord::Migration
def change
create_table :order do |t|
t.integer :total, :precision => 10, :scale => 2
end
end
end
|
module Task::Print
def self.step(text)
puts "#{time_log} " + Rainbow(text).white
end
def self.substep(text)
puts "#{time_log} " + Rainbow(" #{text}").white
end
def self.notice(text)
puts "#{time_log} " + Rainbow(text).yellow
end
def self.warning(text)
puts "#{time_log} " + Rainbow(text).orange
end
def self.error(text)
puts "#{time_log} " + Rainbow(text).red
end
def self.success(text)
puts "#{time_log} " + Rainbow(text).green
end
private
def self.time_log
"[#{DateTime.now.strftime("%FT%T")}]"
end
end
|
class Gossip < ApplicationRecord
belongs_to :user
has_many :taggossips, dependent: :destroy
has_many :tags, through: :taggossips
has_many :coms, dependent: :destroy
has_many :likes, dependent: :destroy
validates :title, :content, presence: true
validates :title, length: { minimum: 3, maximum: 14 }
end
|
class User < ActiveRecord::Base
acts_as_authentic
attr_protected :role
def after_initialize
if self.role.blank?
extend Role::User
else
extend "Role::#{self.role.classify}".constantize
end
end
def to_param
login
end
def self.from_param!(param)
find_by_login!(param)
end
def initial_admin?
false
end
def to_user
self
end
def config
@config ||= User::Configuration.new(self)
end
end
|
# frozen_string_literal: true
module WasteExemptionsShared
module EnrollmentsHelper
def submit_button_text(enrollment)
if enrollment.declaration?
t("global.accept_declaration")
elsif enrollment.choosing_exemption?
t("global.choosing_exemption_continue")
else
t("global.continue")
end
end
def readable_org_type(t)
t.to_s.demodulize.underscore
end
def link_to_reviewing_change_this(enrollment, review_data_row)
url = review_data_row.target(enrollment)
return unless url
klass = WasteExemptionsShared::ReviewingChangeLink
klass.tag default_text: t("enrollments.states.reviewing.link", default: ""), # e.g. 'Change'
link_title: review_data_row.link_title, # e.g. 'Change your name'
url: url,
options: { id: review_link_id(review_data_row), class: "change-link" }
end
# Called from /views/waste_exemptions_shared/enrollments/edit.html.erb which
# appears to be the main view for all WEX journeys. It is used to determine
# whether to display the OS places partial, which contains the OS usage
# notice.
#
# However to make the determination we cannot just rely on :state. For
# example on the choosing_site_address page if you just hit continue you
# don't get :state in the params, instead you get :rendered_state.
#
# Likewise when adding a partner, if you just hit continue you get neither
# :rendered_state or :state, so the fall back is to check the controller.
#
# Hence we pass the whole params object in and have to apply all these
# checks.
def show_os_terms?(params)
state = params[:rendered_state] || params[:state]
controller = params[:controller]
address_states = %w[
partnership
choosing_site_address
organisation_address
address
]
address_controllers = %w[waste_exemptions_shared/organisation_partners]
address_states.include?(state) || address_controllers.include?(controller)
end
end
end
|
require "delegate"
module SpecRunner
class ClojurePath < SimpleDelegator
def exists?
File.exists?(self)
end
def points_to_spec_file?
!!match(/_spec.clj|_test.clj/)
end
def to_implementation
new { gsub(/_spec.clj|_test.clj/, ".clj") }
end
def in_implementation_directory
new { gsub(/\/spec\/|\/test\//, "/src/") }
end
def to_spec
new { gsub(/\.clj/, "_spec.clj") }
end
def in_spec_directory
new { gsub(/\/src\//, "/spec/") }
end
# TODO tests
def to_test
new { gsub(/\.clj/, "_test.clj") }
end
# TODO tests
def in_test_directory
new { gsub(/\/src\//, "/test/") }
end
def file_extension
File.extname(self)
end
def path_segments(n)
new { split(File::SEPARATOR)[-n..-1].join(File::SEPARATOR) }
end
private
def new
self.class.new(yield)
end
end
end
|
json.array!(@guests) do |guest|
json.extract! guest, :id, :last_name, :first_name, :address, :email, :phone_number, :reception, :nijikai
json.url guest_url(guest, format: :json)
end
|
require 'minitest/autorun'
require_relative '../fightergame.rb'
class TestFighterGame < Minitest::Test
def setup
@player = {
name: "player 1",
wins: 0
}
@player_stats = {
type: 0,
health: 0,
strength: 0,
toughness: 0,
speed: 0
}
@opponent = {
name: "player 2",
health: 0,
strength: 0,
toughness: 0,
speed: 0
}
@fighters = [
{
name: "All Rounder",
health: 350,
strength: 50,
toughness: 50,
speed: 4,
},
{
name: "FatMan",
health: 500,
strength: 40,
toughness: 50,
speed: 1,
},
{
name: "Muscle Man",
health: 350,
strength: 70,
toughness: 40,
speed: 3,
},
{
name: "Fast Man",
health: 300,
strength: 50,
toughness: 30,
speed: 5,
},
{
name: "Tough Man",
health: 350,
strength: 50,
toughness: 50,
speed: 4,
},
{
name: "Tough Man",
health: 350,
strength: 50,
toughness: 50,
speed: 4,
}
]
@attacks = {
punch:{
type: :high,
min: 30,
max: 50,
},
elbow:{
type: :high,
min: 10,
max: 90,
},
throw:{
type: :high,
min: 40,
max: 40,
},
kick:{
type: :low,
min: 30,
max: 60,
},
knee:{
type: :low,
min: 10,
max: 80,
},
sweep:{
type: :low,
min: 40,
max: 40,
},
block_high:{
type: :high,
min: 3,
max: 50,
},
block_low:{
type: :low,
min: 0,
max: 0,
},
recover:{
type: :heal,
min: 0,
max: 100,
}}
end
def test_get_player_name()
name = get_player_name("Chris")
assert_equal("player 1", name)
end
def test_update_player_name()
update_player_name("Jack")
assert_equal("Jack",@player[:name])
end
def test_choose_fighter()
choose_fighter(1)
assert_equal(4, @player_stats[:speed])
end
# def test_choose_opponent()
# assert_equal(!"player 2", choose_opponent)
# end
def test_choose_attack()
attack = choose_attack(3)
assert_equal(@attacks[:throw],attack)
end
# def test_opponent_attack()
# attack = opponent_attack(2)
# assert_equal("elbow", attack)
# end
# def test_player_damage()
# damage = player_damage("all_rounder", "punch")
# assert_equal()
# end
# def test_opponent_damage()
# end
# def test_player_dodge()
# end
# def test_opponent_dodge()
# end
# def test_players_health()
# end
# def test_round_outcome()
# end
end |
require 'rails_helper'
RSpec.describe CourseHole, type: :model do
it { should belong_to(:course) }
it { should validate_presence_of(:course) }
it { should validate_presence_of(:hole_number) }
it { should validate_presence_of(:yardage) }
it { should validate_presence_of(:par) }
end
|
# Question 2
# Question 2
# Alan created the following code to keep track of items for a shopping cart application he's writing:
# class InvoiceEntry
# attr_reader :quantity, :product_name
# def initialize(product_name, number_purchased)
# @quantity = number_purchased
# @product_name = product_name
# end
# def update_quantity(updated_count)
# # prevent negative quantities from being set
# quantity = updated_count if updated_count >= 0
# end
# end
# Alyssa looked at the code and spotted a mistake. "This will fail when update_quantity is called", she says.
# Can you spot the mistake and how to address it?
# My answer
# In update_quantity the quantity that is being updated is a local varible.
# it needs to be a instance variable. It should be @quantity.
# Question 3
# In the last question Alan showed Alyssa this code which keeps track of items for a shopping cart application:
# class InvoiceEntry
# attr_reader :quantity, :product_name
# def initialize(product_name, number_purchased)
# @quantity = number_purchased
# @product_name = product_name
# end
# def update_quantity(updated_count)
# quantity = updated_count if updated_count >= 0
# end
# end
# Alyssa noticed that this will fail when update_quantity is called. Since quantity is an instance variable, it must be accessed with the @quantity notation when setting it. One way to fix this is to change attr_reader to attr_accessor and change quantity to self.quantity.
# Is there anything wrong with fixing it this way?
# Yes. Before there wasn't a setter method. Now there is. Now you are allowing
# clients of the class to change the quanitity directly (calling the
# accessor with the instance.quantity = <new value>) rather than by going through
# the update_quantity method.
# Someone could update the quantity even if the update count was less than 0.
# class Greeting
# def greet(string)
# puts string
# end
# end
# class Hello < Greeting
# def hi
# greet("Hello")
# end
# end
# class Goodbye < Greeting
# def bye
# greet("Goodbye")
# end
# end
# person = Hello.new
# person.hi
# Question 5
# class KrispyKreme
# def initialize(filling_type, glazing)
# @filling_type = filling_type
# @glazing = glazing
# end
# def to_s
# if @filling_type == nil && @glazing == nil
# "Plain"
# elsif @filling_type != nil && @glazing == nil
# "#{@filling_type}"
# elsif @filling_type == nil
# "Plain with #{@glazing}"
# else
# "#{@filling_type} with #{@glazing}"
# end
# end
# end
# class KrispyKreme
# def initialize(filling_type, glazing)
# @filling_type = filling_type
# @glazing = glazing
# end
# def to_s
# filling_string = @filling_type ? @filling_type : "Plain"
# glazing_string = @glazing ? " with #{@glazing}" : ''
# filling_string + glazing_string
# end
# end
# donut1 = KrispyKreme.new(nil, nil)
# donut2 = KrispyKreme.new("Vanilla", nil)
# donut3 = KrispyKreme.new(nil, "sugar")
# donut4 = KrispyKreme.new(nil, "chocolate sprinkles")
# donut5 = KrispyKreme.new("Custard", "icing")
# puts donut1
# puts donut2
# puts donut3
# puts donut4
# puts donut5
# Question 6
# If we have these two methods:
# class Computer
# attr_accessor :template
# def create_template
# @template = "template 14231"
# end
# def show_template
# template
# end
# end
# mac = Computer.new
# p mac.create_template
# and
# class Computer
# attr_accessor :template
# def create_template
# self.template = "template 14231"
# end
# def show_template
# self.template
# end
# end
# mac = Computer.new
# p mac.create_template
# What is the difference in the way the code works?
# In the top example "template 13231" is assinged directly to the instance
# variable
# In the bottom example, the setter method is being called through the
# self.template call in order to be assigned. Both result in the instance
# variable being updated, but the bottom example goes through an extra step.
# Its also important to let the computer know that you aren't assigning a variable
# called template in the bottom example and instead you are calling the
# template method on the object.
# For the show_template method the top example is calling the getter method
# created by attr_accessor. The bottom method is calling the getter
# method template on the object. They are essentially the same thing.
# Question 7
# How could you change the method name below so that the method name is more clear and less repetitive?
class Light
attr_accessor :brightness, :color
def initialize(brightness, color)
@brightness = brightness
@color = color
end
def self.light_information
"I want to turn on the light with a brightness level of super high and a colour of green"
end
end
# change the name of self.light_information to just self.information
|
class SaveRoom
prepend SimpleCommand
# Update Room info
# form_object: UpdateRoomInfoForm
def initialize(form_object)
@form_object = form_object
end
def call
save_record(@form_object)
end
private
def save_record(form_object)
raise ArgumentError, 'Invalid RoomId' if form_object.id.nil?
facility = get_facility(form_object.facility_id)
facility.rooms ||= []
room = facility.rooms.detect { |r| r.id.to_s == form_object.id }
if room.nil?
room = facility.rooms.build(id: form_object.id)
end
room.name = form_object.name
room.code = form_object.code
room.full_code = Constants.generate_full_code(facility, room)
room.desc = form_object.desc
room.purpose = form_object.purpose
room.has_sections = form_object.has_sections
if room.has_sections && room.sections.blank?
new_code = NextFacilityCode.call(:section, nil, 1).result
room.sections.build(code: new_code, purpose: room.purpose)
end
# LOGIC#0001 - No rows setup for these types of room
if Constants::ROOM_ONLY_SETUP.include?(room.purpose)
# Mark room as complete since there's no setup requrired
# for these types of room.
room.is_complete = true
end
room.wz_generated = false
facility.save!
room
end
def get_facility(facility_id)
find_cmd = FindFacility.call({id: facility_id})
if find_cmd.success?
find_cmd.result
else
raise ArgumentError, 'Invalid Facility'
nil
end
end
end
|
# encoding: UTF-8
module CDI
module V1
module Users
module AuthProviders
class Facebook
attr_reader :access_token, :options, :auth_provider_data, :errors, :existent_user
PROVIDER_ATTRIBUTES = [:email, :first_name, :last_name, :gender, :birthday, :about]
def initialize(access_token, options = {})
@access_token = access_token
@options = options.to_options!
end
def fetch_user
user_data = memoized_fetch_user_data || {}
find_user(user_data)
end
def find_user(user_data)
@existent_user = find_existent_user(user_data)
if @existent_user.present? and @existent_user.banned?
@existent_user = nil
return
end
@existent_user || ::User.new(user_data)
end
def find_existent_user(provider_data)
oauth_provider_uid = provider_data[:oauth_provider_uid]
return nil if oauth_provider_uid.blank?
::User.where(
"(oauth_provider_uid = ? AND oauth_provider = ?) OR email = ?",
oauth_provider_uid,
provider_name,
provider_data[:email]
).first
end
def memoized_fetch_user_data(scope = 'me')
@users_data ||= {}
@users_data[scope.to_sym] ||= fetch_user_data(scope)
end
def oauth_provider_uid
data = memoized_fetch_user_data
data.is_a?(Hash) ? data[:oauth_provider_uid] : nil
end
def existent_user?
@existent_user.present? && @existent_user.is_a?(User)
end
def fetch_user_data(scope = 'me')
user_data = nil
begin
request = facebook_request(access_token, scope)
request_body = request.body
parsed_body = JSON.parse(request_body)
if request.is_a?(Net::HTTPOK)
@auth_provider_data = parsed_body
user_data = normalized_user_data_from_provider(parsed_body)
else
(@errors ||= []) << (Array.wrap(parsed_body['error'] || parsed_body))
end
rescue => e
(@errors ||= []) << {
message: e.try(:fb_error_message) || e.try(:message),
code: e.try(:fb_error_code) || e.try(:code),
status_code: e.try(:http_status) || 500
}
end
user_data
end
def error?
@errors.present?
end
def success?
!error?
end
def provider_name
:facebook
end
private
def facebook_request(access_token, uuid='me')
uri = URI("https://graph.facebook.com/#{uuid}/?access_token=#{access_token}&fields=#{PROVIDER_ATTRIBUTES.join(',')}")
timeout = (CDI::Config.facebook_api_read_timeout || 10).to_i
Net::HTTP.start(uri.host, uri.port,
:read_timeout => timeout,
:use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
end
def normalized_user_data_from_provider(provider_data)
user_data = provider_data.slice(*PROVIDER_ATTRIBUTES.map(&:to_s))
user_password = SecureRandom.hex
user_data = user_data.merge(
birthday: birthday_date_from_facebook(provider_data['birthday']),
profile_type: User::VALID_PROFILES_TYPES[:student],
password: user_password,
password_confirmation: user_password,
oauth_provider_uid: provider_data['id'],
oauth_provider: provider_name
).deep_symbolize_keys
end
def birthday_date_from_facebook(birthday)
return Date.today if birthday.blank?
date = begin
Date.parse(birthday)
rescue => e
date = birthday.to_s.gsub(/(\d{2})\/(\d{2})\/(\d{4})/, '\\2/\\1/\\3') rescue Date.today
Date.parse(date)
end
end
end
end
end
end
end
|
# frozen_string_literal: true
module Hanamimastery
module CLI
module Commands
class Unshot < Dry::CLI::Command
desc 'Removes shot marks from a given article (i.e. ""[🎬 01] ")'
argument :episode, type: :integer, required: true, desc: "Episodes ID to unshot"
include Deps[
repository: 'repositories.episodes',
transformation: 'hanamimasterytransformations.unshot'
]
attr_reader :transformation, :repository
def call(episode:, **)
content = repository.read(episode)
processed = transformation.call(content, one: false)
repository.replace(episode, processed)
end
end
end
end
end
|
class Employee < ActiveRecord::Base
belongs_to :store
validates :store, presence: true
validates :first_name, :last_name, :hourly_rate, presence: true
validates :hourly_rate, numericality: {:greater_than_or_equal_to => 20, :less_than_or_equal_to => 200}
end
|
require_relative 'CasinoEngine'
require_relative 'PokerHandEvaluator'
class AiRule
RULE_TYPE_JOKER = 0;
RULE_TYPE_HAND_OF_VALUE = 1;
RULE_TYPE_SAME_SUIT = 2;
RULE_TYPE_SAME_VALUE = 3;
RULE_TYPE_RUN_OF_LENGTH = 4;
AI_ACTION_KEEP_AND_CONTINUE = 0;
AI_ACTION_KEEP_AND_STOP = 1;
def initialize(myRuleType, myCount, myAction)
@ruleType = myRuleType
@count = myCount
@action = myAction
end
def ruleType
@ruleType
end
def count
@count
end
def action
@action
end
end
class AiDoubleRule
DOUBLE_RULE_TYPE_WINNINGS_BELOW = 0
DOUBLE_RULE_TYPE_CARD_BELOW = 1
DOUBLE_RULE_TYPE_CARD_ABOVE = 2
DOUBLE_RULE_TYPE_ROUND_BELOW = 3
DOUBLE_AI_ACTION_MANDATORY = 0
DOUBLE_AI_ACTION_GO_IF_TRUE = 1
def initialize(myRuleType, myCount, myAction)
@ruleType = myRuleType
@count = myCount
@action = myAction
end
def ruleType
@ruleType
end
def count
@count
end
def action
@action
end
end
class AiModel
DOUBLE_ACTION_LOWER = 0
DOUBLE_ACTION_HIGHER = 1
def initialize(myRules, myDoubleRules)
@rules = myRules
@doubleRules = myDoubleRules
# testing
# todo: joker won't mesh properly with other rules yet
@rules.push(AiRule.new(AiRule::RULE_TYPE_HAND_OF_VALUE, 1, AiRule::AI_ACTION_KEEP_AND_CONTINUE))
@rules.push(AiRule.new(AiRule::RULE_TYPE_SAME_SUIT, 4, AiRule::AI_ACTION_KEEP_AND_CONTINUE))
@rules.push(AiRule.new(AiRule::RULE_TYPE_SAME_VALUE, 2, AiRule::AI_ACTION_KEEP_AND_CONTINUE))
@rules.push(AiRule.new(AiRule::RULE_TYPE_RUN_OF_LENGTH, 4, AiRule::AI_ACTION_KEEP_AND_CONTINUE))
@rules.push(AiRule.new(AiRule::RULE_TYPE_JOKER, 1, AiRule::AI_ACTION_KEEP_AND_STOP))
@doubleRules.push(AiDoubleRule.new(AiDoubleRule::DOUBLE_RULE_TYPE_WINNINGS_BELOW, 64, AiDoubleRule::DOUBLE_AI_ACTION_GO_IF_TRUE))
@doubleRules.push(AiDoubleRule.new(AiDoubleRule::DOUBLE_RULE_TYPE_ROUND_BELOW, 1, AiDoubleRule::DOUBLE_AI_ACTION_GO_IF_TRUE))
@doubleRules.push(AiDoubleRule.new(AiDoubleRule::DOUBLE_RULE_TYPE_CARD_BELOW, 6, AiDoubleRule::DOUBLE_AI_ACTION_GO_IF_TRUE))
@doubleRules.push(AiDoubleRule.new(AiDoubleRule::DOUBLE_RULE_TYPE_CARD_ABOVE, 9, AiDoubleRule::DOUBLE_AI_ACTION_GO_IF_TRUE))
end
# todo: maybe these can be moved
def cardsInHandOfSuit(hand, suit)
hand.select { |card| card.suit == suit }
end
def cardsInHandOfValue(hand, value)
hand.select { |card| card.value == value }
end
def runOfLengthInHand(hand, length)
result = []
for i in 0..12
startRun = i
endRun = i + (length-1)
# TODO: fix this to only pull one of each card (i.e. 2345, not 23445)
if endRun == 13 # Ace, wraparound
attempt = hand.select { |card| (card.value >= startRun and card.value <= endRun) or (card.value == 0 and !card.isJoker) }
if attempt.length == length
result = attempt
end
elsif endRun < 13
attempt = hand.select { |card| card.value >= startRun and card.value <= endRun }
if attempt.length == length
result = attempt
end
end
end
result
end
def cardsThatMatchRule(hand, rule)
case rule.ruleType
when AiRule::RULE_TYPE_HAND_OF_VALUE
# TODO: pass in casino engine
casinoEngine = CasinoEngine.new
valueOfHand = casinoEngine.betMultiplierForHand(hand)
if valueOfHand >= rule.count
hand
else
[]
end
when AiRule::RULE_TYPE_JOKER
jokerCards = hand.select { |card| card.isJoker == true }
if jokerCards.length >= rule.count
jokerCards
else
[]
end
when AiRule::RULE_TYPE_SAME_SUIT
handEvaluator = PokerHandEvaluator.new
groupedSuits = handEvaluator.cardsGroupedBySuit(hand)
if !groupedSuits[rule.count].nil?
# todo: handle if you have multiple such cases
suit = groupedSuits[rule.count][0]
cardsInHandOfSuit(hand, suit)
else
[]
end
when AiRule::RULE_TYPE_SAME_VALUE
handEvaluator = PokerHandEvaluator.new
groupedValues = handEvaluator.cardsGroupedByValue(hand)
if !groupedValues[rule.count].nil?
# todo: handle if you have multiple such cases
value = groupedValues[rule.count][0]
cardsInHandOfValue(hand, value)
else
[]
end
when AiRule::RULE_TYPE_RUN_OF_LENGTH
handEvaluator = PokerHandEvaluator.new
longestRunLength = handEvaluator.lengthOfLongestRunOfCards(hand)
if longestRunLength == rule.count
runOfLengthInHand(hand, rule.count)
else
[]
end
else
[]
end
end
# returns a subset of hand corresponding to what cards to keep
def getKeptCards(hand)
keptHand = []
@rules.each do |rule|
matchCards = cardsThatMatchRule(hand, rule)
if matchCards.length > 0
# todo: uncomment if you wanna make sure you're saving cards ok
#puts matchCards
#puts
if rule.action == AiRule::AI_ACTION_KEEP_AND_CONTINUE
hand = hand - matchCards
keptHand += matchCards
elsif rule.action == AiRule::AI_ACTION_KEEP_AND_STOP
hand = hand - matchCards
keptHand += matchCards
break
end
end
end
keptHand
end
def shouldDoubleUp(winnings, visibleCard, doubleRound)
mandatoryOk = true
goIfTrue = false
@doubleRules.each do |rule|
ruleSuccess = false
if rule.ruleType == AiDoubleRule::DOUBLE_RULE_TYPE_WINNINGS_BELOW
ruleSuccess = winnings < rule.count
elsif rule.ruleType == AiDoubleRule::DOUBLE_RULE_TYPE_CARD_BELOW
if !visibleCard.nil?
ruleSuccess = visibleCard.value < rule.count
elsif rule.action == AiDoubleRule::DOUBLE_AI_ACTION_MANDATORY
ruleSuccess = true # don't fail mandatory if it's first round
end
elsif rule.ruleType == AiDoubleRule::DOUBLE_RULE_TYPE_CARD_ABOVE
if !visibleCard.nil?
ruleSuccess = visibleCard.value > rule.count
elsif rule.action == AiDoubleRule::DOUBLE_AI_ACTION_MANDATORY
ruleSuccess = true # don't fail mandatory if it's first round
end
elsif rule.ruleType == AiDoubleRule::DOUBLE_RULE_TYPE_ROUND_BELOW
ruleSuccess = doubleRound < rule.count
end
if ruleSuccess and rule.action == AiDoubleRule::DOUBLE_AI_ACTION_GO_IF_TRUE
goIfTrue = true
end
if !ruleSuccess and rule.action == AiDoubleRule::DOUBLE_AI_ACTION_MANDATORY
mandatoryOk = false
end
end
mandatoryOk and goIfTrue
end
def getDoubleUpAction(winnings, visibleCard)
if (visibleCard.value < 8)
DOUBLE_ACTION_HIGHER
else
DOUBLE_ACTION_LOWER
end
# TODO
end
end |
class Admin::PerformancesController < Admin::BaseAdminController
load_and_authorize_resource
skip_load_resource
before_action :set_performance, except: %i[index compare employee_performance]
before_action :set_employee
before_action :ensure_same_employee, only: :employee_performance
before_action :set_performances
before_action :set_performance_topics, except: %i[index destroy]
def new; end
def create
if @performance.save
flash[:notice] = 'Performance has been added.'
redirect_to admin_employee_performances_path(@performance.employee)
else
render :new
end
end
def edit; end
def update
if @performance.update(performance_params)
flash[:notice] = 'Changes has been saved'
redirect_to admin_employee_performances_path(@performance.employee)
else
render :edit
end
end
def index; end
def employee_performance; end
def compare; end
def destroy
return unless @performance.destroy
flash[:notice] = 'Performance was deleted.'
redirect_to admin_employee_performances_path(@performance.employee)
end
private
def performance_params
params.require(:performance).permit(:employee_id, :year, :month, :topic,
:score, :comment, :hr_comment)
end
def set_employee
@employee = Employee.find(params[:employee_id])
end
def set_performance
@performance = if action_name == 'new'
Performance.new
elsif action_name == 'create'
Performance.new(performance_params)
else
Performance.find(params[:id])
end
end
def set_performances
validate_dates if params[:year_from]
if params[:topic]
set_previous_performances
set_last_performances
else
@performances = @employee.performances
end
@total_performances = PerformanceTopic.count * 5
end
def set_previous_performances
@previous_performance = @employee.performances.where(topic: params[:topic],
year: params[:year_from],
month: params[:month_from],
employee_id: params[:employee_id]).first
end
def set_last_performances
@last_performance = @employee.performances.where(topic: params[:topic],
year: params[:year_to],
month: params[:month_to],
employee_id: params[:employee_id]).first
end
def set_performance_topics
@performance_topics = PerformanceTopic.all
end
def validate_dates
parse_dates
ensure_valid_comparison
end
def parse_dates
@previous_date = Date.new(params[:year_from].to_i, params[:month_from].to_i)
@last_date = Date.new(params[:year_to].to_i, params[:month_to].to_i)
end
def ensure_valid_comparison
flash[:notice] = 'Please compare past with future' if @last_date < @previous_date
return redirect_to compare_admin_employee_performances_path(params[:employee_id]) if @last_date < @previous_date
end
def ensure_same_employee
return unless current_employee
redirect_to admin_path if @employee != current_employee
end
end
|
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
#root to: redirect(subdomain: 'transport', path: 'opentransport')
root to: redirect(path: 'opentransport')
#root 'page#index'
get 'opentransport' => 'page#index'
get 'opentransport/map' => 'page#map'
get 'opentransport/ppa/portclusters' => 'page#portClusters'
get 'opentransport/ppa/vesselclusters' => 'page#vesselClusters'
get 'opentransport/ppa/visualization' => 'page#port_visualizer'
get 'opentransport/ppa/shippinglines' => 'page#shipping_line_vis'
devise_for :admins
get 'opentransport/admin' => 'admin#list_ports'
get 'opentransport/admin/exportData', :action => 'export_data', :controller => 'admin', :as => :export_data
get 'opentransport/admin/listPorts', :action => 'list_ports', :controller => 'admin', :as => :list_ports
get 'opentransport/admin/showPort(/:id)', :action => 'show_port', :controller => 'admin', :id => /[0-9]+/i, :as => :show_port
get 'opentransport/admin/showPort/new', :action => 'show_port', :controller => 'admin', :as => :create_new_port
post 'opentransport/admin/savePort', :action => 'save_port', :controller => 'admin', :as => :save_port
post 'opentransport/admin/destroyPort', :action => 'destroy_port', :controller => 'admin', :as => :destroy_port
get 'opentransport/admin/listRoutes', :action => 'list_routes', :controller => 'admin', :as => :list_routes
get 'opentransport/admin/showRoute(/:id)', :action => 'show_route', :controller => 'admin', :id => /[0-9]+/i, :as => :show_route
get 'opentransport/admin/showRoute/new', :action => 'show_route', :controller => 'admin', :as => :create_new_route
post 'opentransport/admin/saveRoute', :action => 'save_route', :controller => 'admin', :as => :save_route
post 'opentransport/admin/destroyRoute', :action => 'destroy_route', :controller => 'admin', :as => :destroy_route
post 'opentransport/admin/saveInfo', :action => 'save_info', :controller => 'admin', :as => :save_info
post 'opentransport/admin/createInfo', :action => 'create_info', :controller => 'admin', :as => :create_info
post 'opentransport/map/getRoutes', :action => 'get_routes', :controller => 'page', :as => :get_routes
get 'opentransport/map/getRoutes' => 'page#get_routes'
get 'opentransport/map/getPorts' => 'page#get_ports'
# resources :page do
# member do
# get 'edit_port'
# get 'list_ports'
# end
# end
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
module Omnimutant
class FileMutator
def initialize(filepath:, verbose:0)
@filepath = filepath
@file_original_data = File.read(@filepath)
@total_lines = @file_original_data.lines.size
@current_line_number = 0
@current_mutation_number = -1
@verbose = verbose
end
def do_next_mutation
reset_to_original()
if has_more_mutations_to_try_on_current_line?
@current_mutation_number += 1
elsif has_more_lines_to_try?
@current_line_number += 1
@current_mutation_number = 0
else
return false
end
line = @file_original_data.lines[get_current_line_number]
if line.chomp.size > 0 && line !~ /^\s*#/
run_current_mutation()
return true
else
return do_next_mutation()
end
end
def report
puts get_current_line_number
puts @current_mutation_number
puts
end
def is_done_mutating?
return false if has_more_mutations_to_try_on_current_line?
return false if has_more_lines_to_try?
reset_to_original()
true
end
private def run_current_mutation
replace_line filepath:@filepath,
line_number:get_current_line_number, new_content:get_mutated_line
end
def reset_to_original
write_file @filepath, @file_original_data
end
def get_original_line
@file_original_data.lines[get_current_line_number]
end
def get_current_line_number
@current_line_number
end
def get_mutated_line
current_line_mutations[@current_mutation_number]
end
private def has_more_mutations_to_try_on_current_line?
mutations = current_line_mutations
if @current_mutation_number < mutations.size - 1
return true
end
false
end
private def current_line_mutations
line = get_original_line()
StringMutator.new(line).get_all_mutations()
end
private def has_more_lines_to_try?
get_current_line_number < @total_lines - 1
end
private def replace_line(filepath:, line_number:, new_content:)
new_file_data = ""
file_data = File.read(filepath)
file_data.lines.each_with_index do |line, index|
if index == line_number
vputs(2, "replace_line - before: " + line)
vputs(2, "replace_line - after : " + new_content)
new_file_data << new_content
else
new_file_data << line
end
end
write_file filepath, new_file_data
end
private def write_file(filepath, data)
File.open(filepath, 'w') { |file| file.write(data) }
end
private def vputs(level, message)
if @verbose >= level
puts message
end
end
end
end
|
class Item
include DataMapper::Resource
include DataMapper::MassAssignmentSecurity
property 'id', Serial
property 'title', String, required: true
property 'url', Text, lazy: false, required: true
property 'image_url', Text, lazy: false
property 'score', Integer, default: 0
property 'notes', Text
timestamps :at
# validates_uniqueness_of :url, :scope => :board_id
belongs_to :board
attr_protected :score
end
|
# U2.W6: Create a Car Class from User Stories
# I worked on this challenge by myself.
# 2. Pseudocode
# => Create an object class Car with model and color attributes, initialize with 0 speed
# => Create a method to set destination distance
# => Create a method to change car speed
# => Create a method to check car speed
# => Create two methods to turn the car (right and left)
# => Create a method to stop the car
# 3. Initial Solution
class Car
def initialize(model, color)
@model = model
@color = color
@speed = 0
@distance_travelled = 0
@direction = "none"
end
def drive(distance, speed = @speed)
@distance_travelled += distance
@speed = speed
end
def stop
@speed = 0
end
def turn_right
@direction = "right"
end
def turn_left
@direction = "left"
end
def check_speed
@speed
end
def set_speed(speed)
@speed = speed
end
def log_distance
@distance_travelled
end
end
# 4. Refactored Solution
# Solution does not need to be refactored. Each method is necessary according to user stories and are concise.
# 1. DRIVER TESTS GO BELOW THIS LINE
def assert
puts "Assertion Failed!" unless yield
end
my_car = Car.new("civic", "red")
my_car.drive(0.25, 25)
my_car.stop
my_car.turn_right
my_car.drive(1.5, 35)
assert { my_car.check_speed == 35 }
my_car.set_speed(15)
my_car.drive(0.25)
my_car.stop
my_car.turn_left
my_car.drive(1.4, 35)
my_car.stop
assert { my_car.log_distance == 3.4 }
# 5. Reflection
# This challenge looked intimidating at first, but once driver tests were written from user stories, the pseudocode was easy to write out and it was easy to figure out what methods were required for the class. One new thing I tried out was using optional parameters for the #drive method. I had never used the convention before, but it was convenient to be able to choose a default value if a parameter was not explicitly set. |
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url , alert: "Sorry mate that's not allowed!"
end
def current_user
begin
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
session.delete(:user_id)
return nil
end
end
def logged_in?
!!current_user
end
end
|
class Post < ApplicationRecord
belongs_to :user
belongs_to :location
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
# def username
# self.user.username
# end
def likes_count
self.likes.length
end
def comments_count
self.comments.length
end
def destination
self.location.country
end
end
|
def caesar_cipher(string, num)
cipher = ""
string.each_char do |ch|
ch = ch.ord
if ch.between?(97, 122) || ch.between?(65, 90)
ch += (num % 26)
elsif ch > 122 || ch.between?(90, 97)
ch -= (num % 26)
end
ch = ch.chr
cipher << ch
end
return cipher
end
# UPCASE = 65-90
# downcase = 97-122
|
# rubocop:disable Style/FrozenStringLiteralComment
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + # rows
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] + # cols
[[1, 5, 9], [3, 5, 7]] # diagonals
# rubocop:enable Style/FrozenStringLiteralComment
INITIAL_MARKER = ' '.freeze
PLAYER_MARKER = 'X'.freeze
COMPUTER_MARKER = 'O'.freeze
def clear_screen
system('clear') || system('cls')
end
def prompt(msg)
puts "=> #{msg}"
end
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def display_board(brd)
puts ''
puts ' | |'
puts " #{brd[1]} | #{brd[2]} | #{brd[3]}"
puts ' | |'
puts '-----+-----+-----'
puts ' | |'
puts " #{brd[4]} | #{brd[5]} | #{brd[6]}"
puts ' | |'
puts '-----+-----+-----'
puts ' | |'
puts " #{brd[7]} | #{brd[8]} | #{brd[9]}"
puts ' | |'
puts ''
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
def initialize_board
new_board = {}
(1..9).each { |num| new_board[num] = INITIAL_MARKER }
new_board
end
def initialize_score
{ player: 0, computer: 0 }
end
def validate_join_array(arr)
!!arr.is_a?(Array)
end
# rubocop:disable Metrics/MethodLength
def join(arr, delimeter = ', ', conjunction = 'or')
if validate_join_array(arr)
string_output = ''
case arr.size
when 0 then string_output << 'Sorry, you have to at least provide an array as an argument.'
when 1 then string_output << arr[0].to_s
when 2
string_output << ("#{arr[0]} #{conjunction} #{arr[1]}")
else
arr.each_with_index do |item, idx|
string_output << if idx < (arr.size - 1)
"#{item} #{delimeter}"
else
"#{conjunction} #{item}"
end
end
end
string_output
else
'Sorry, please provide a valid array as an argument.'
end
end
# rubocop:enable Metrics/MethodLength
def update_score(score, brd)
score[:player] += 1 if detect_winner(brd).include?('Player')
score[:computer] += 1 if detect_winner(brd).include?('Computer')
end
def empty_squares(brd)
brd.keys.select { |num| brd[num] == INITIAL_MARKER }
end
def player_squares(brd)
player_selected_squares = brd.each_with_object([]) do |(key, value), arr|
arr << key if value == PLAYER_MARKER
end
player_selected_squares
end
def potential_win(player_range)
potential_threats = WINNING_LINES.each_with_object([]) do |line, arr|
arr << (line - player_range)
end
potential_threats.keep_if { |arr| arr.size == 1 }
end
def valid_threats(threat_range, valid_squares)
if threat_range.empty? == false
threats = threat_range.flatten
threats.keep_if {|num| valid_squares.include?(num)}
threats if threats.empty? == false
end
end
def detect_threat(brd, valid_squares)
# returns nil if no valid threats
valid_threats(potential_win(player_squares(brd)), valid_squares)
end
def player_places_piece!(brd)
square = ''
loop do
prompt "Choose a square #{join(empty_squares(brd))}"
square = gets.chomp.to_i
break if empty_squares(brd).include?(square)
prompt 'Sorry, that is not a valid choice'
end
brd[square] = PLAYER_MARKER
end
def computer_places_piece!(brd, valid_squares)
if detect_threat(brd, valid_squares) != nil
puts "threat detected! squares #{detect_threat(brd,valid_squares)}"
square = detect_threat(brd, valid_squares).sample
else
puts "no threat detected, choosing a random number."
square = valid_squares.sample
end
brd[square] = COMPUTER_MARKER if square != nil
end
def board_full?(brd)
empty_squares(brd).empty?
end
def someone_won?(brd)
!!detect_winner(brd)
end
def detect_winner(brd)
WINNING_LINES.each do |line|
return 'Player' if brd.values_at(line[0], line[1], line[2]).count(PLAYER_MARKER) == 3
return 'Computer' if brd.values_at(line[0], line[1], line[2]).count(COMPUTER_MARKER) == 3
end
nil
end
def match_winner?(hsh,rounds)
winner = hsh.select do |key, value|
key if value == rounds
end
winner.to_a.flatten[0].to_s.capitalize
end
def display_score(score)
score = <<~MSG
Current Scores:
Player: #{score[:player]}
Computer: #{score[:computer]}
MSG
prompt(score)
end
def round_loop(brd,score)
loop do
clear_screen
display_board(brd)
display_score(score)
player_places_piece!(brd)
break if someone_won?(brd) || board_full?(brd)
computer_places_piece!(brd,empty_squares(brd))
break if someone_won?(brd) || board_full?(brd)
sleep(1)
clear_screen
end
if someone_won?(brd)
clear_screen
display_board(brd)
prompt "#{detect_winner(brd)} won!"
update_score(score, brd)
else
clear_screen
display_board(brd)
prompt "It's a tie!"
end
sleep(3)
end
def welcome_message
welcome_prompt = <<~MSG
Play Tic Tac Toe against the computer!
MSG
prompt(welcome_prompt)
end
def match_rules(rounds = 5)
match_params = <<~MSG
Great! The first player to #{rounds}
wins the match. Preparing the game...
MSG
prompt(match_params)
end
loop do # initiate game
welcome_message
prompt "How many rounds would you like to play?"
match_round = gets.chomp.to_i
match_rules(match_round)
sleep(5)
current_score = initialize_score
loop do # initiate match
board = initialize_board
round_loop(board,current_score)
break if current_score.value?(match_round)
end # end match
prompt "Game over, match win goes to: #{match_winner?(current_score,match_round)}!"
prompt 'Play again?(Y/N)'
reply = gets.chomp.downcase
break if reply == 'n'
end
prompt 'Thanks for playing Tic Tac Toe. Good-bye!'
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'nytimes_congress/version'
Gem::Specification.new do |spec|
spec.name = "nytimes_congress"
spec.version = NytimesCongress::VERSION
spec.authors = ["Eric Candino"]
spec.email = ["ecandino@gmail.com"]
spec.description = "A client for The New York Times Campaign Finance API"
spec.summary = "See who your elected officials are and what they are doing."
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
|
Rails.application.routes.draw do
devise_for :customer,
path: :customers,
:controllers => {
:registrations => "customer/registrations",
:sessions => "customer/sessions",
:passwords => "customer/passwords"
}
devise_for :admin,
path: :admins,
:controllers => {
:sessions => "admin/sessions"
}
get "/" => "customer/items#top", as: "top"
get "/about" => "customer/items#about", as: "about"
get "/customers" => "customer/customers#rule", as: "customer_rule"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :admin, path: :admins do
resources :items, only: [:index, :new, :create, :show, :edit, :update]
resources :genres, only: [:index, :create, :edit, :update]
resources :orders, only: [:index, :show, :update]
resources :item_orders, only: [:update]
resources :customers, only: [:index, :show, :edit, :update]
get "orders/current_user_order/:id" => "orders#current_user_order"
end
namespace :customer, path: :customers do
resources :items, only: [:index, :show]
resources :cart_items, only: [:index, :update, :create, :destroy]
delete "cart_items" => "cart_items#all_destroy", as: "cart_item_all_destroy"
resources :orders, only: [:new, :create, :index, :show] do
collection do
post "confirm"
get "complete"
end
end
resources :deliver_destinations, only: [:index, :create, :destroy, :edit, :update]
get "my_page" => "customers#show", as: "customer"
get "leave" => "customers#leave", as: "customer_leave"
patch "out" => "customers#out", as: "customer_out"
get "edit/my_page" => "customers#edit", as: "customer_edit"
patch "update" => "customers#update", as: "customer_update"
end
end
|
module Datamappify
module Data
module Criteria
module Relational
class FindMultiple < Common
alias_method :entity_class, :entity
attr_reader :primaries, :secondaries, :structured_criteria
def initialize(*args)
super
@primaries = []
@secondaries = []
updated_attributes.each do |attribute|
collector = attribute.primary_attribute? ? @primaries : @secondaries
collector << attribute
end
end
# @return [void]
def perform
records.map do |record|
entity = entity_class.new
update_entity(entity, record)
entity
end
end
private
# @return [Array]
def updated_attributes
unless criteria.keys & attributes.map(&:key) == criteria.keys
raise EntityAttributeInvalid
end
@updated_attributes ||= attributes.select do |attribute|
attribute.value = criteria[attribute.key]
criteria.keys.include?(attribute.key)
end
end
# @param entity [Entity]
#
# @param record [Class]
#
# @return [void]
def update_entity(entity, primary_record)
attributes.each do |attribute|
record = data_record_for(attribute, primary_record)
value = record_value_for(attribute, record)
entity.send("#{attribute.name}=", value)
end
end
# @param attribute [Attribute]
#
# @param primary_record [Class]
# an ORM model object (ActiveRecord or Sequel, etc)
#
# @return [Object]
# an ORM model object (ActiveRecord or Sequel, etc)
def data_record_for(attribute, primary_record)
if attribute.primary_attribute?
primary_record
else
primary_record.send(attribute.source_key)
end
end
# @param attribute [Attribute]
#
# @param record [Class]
# an ORM model object (ActiveRecord or Sequel, etc)
#
# @return [any]
def record_value_for(attribute, record)
record.nil? ? nil : record.send(attribute.source_attribute_name)
end
end
end
end
end
end
|
# frozen_string_literal: true
module ActiveAny
class AssociationRelation < Relation
def initialize(klass, association)
super(klass)
@association = association
end
def proxy_association
@association
end
def ==(other)
other == records
end
private
def exec_queries
super do |r|
@association.set_inverse_instance r
yield r if block_given?
end
end
end
end
|
#!/usr/bin/env ruby
require "rubygems"
###
# http client tools
# Url/fetching/curl like stuff
#
class HttpClient
##
# Stub for future use...
end
##
# Openuri/wget combo version
class SimpleHttpClient < HttpClient
require "open-uri"
def easy_download ( url, path )
system("wget", "-q", "-O", path, url )
return true if (File.exists?(path) && File.size(path) > 0 )
return false
end
def easy_body ( url)
return open(url).read
end
end
###
# Curl based version
class SimpleCurlHttpClient < HttpClient
require "curb"
def easy_download ( url, path )
system("curl", "--output", path, url )
return true if (File.exists?(path) && File.size(path) > 0 )
return false
end
def easy_body ( url)
return Curl::Easy.perform(url).body_str
end
end
##
# Curb based version
class SimpleCurbHttpClient < HttpClient
def easy_download ( url, path )
Curl::Easy.download(url, path)
return true if (File.exists?(path) && File.size(path) > 0 )
return false
end
end
|
class SessionsController < ApplicationController
skip_before_action :require_login, only: [:create]
def create
auth_hash = request.env['omniauth.auth']
merchant = Merchant.find_by(uid: auth_hash[:uid], provider: 'github')
if merchant
# flash[:status] = :success
# flash[:result_text] = "Logged in as returning user #{merchant.name}"
else
merchant = Merchant.build_from_github(auth_hash)
if merchant.save
# flash[:status] = :success
# flash[:result_text] = "Logged in as new user #{merchant.name}"
else
# flash[:status] = :failure
# flash[:result_text] = "Could not create new user account: #{merchant.errors.messages}"
# flash.now[:messages] = merchant.errors.messages
redirect_to root_path
return
end
end
session[:user_id] = merchant.id
redirect_to root_path
end
def destroy
session[:user_id] = nil
# flash[:status] = :success
# flash[:result_text] = "Successfully logged out"
if session[:order_id]
session[:order_id] = nil
end
redirect_to root_path
end
end
|
require 'stk_env'
class Stk_sequence
@@obj_map = {}
def initialize(env,name,id,sequence_type,service_type,options,ref=nil)
if ref == nil
@_seq = Stksequence.stk_create_sequence(env.ref(),name,id,sequence_type,service_type,options);
else
@_seq = ref;
end
@_env = env
@_id = Stksequence.stk_get_sequence_id(@_seq)
@_seqptr = Stksequence.stk_seq_ptr_to_ulong_seq(@_seq)
@@obj_map[@_seqptr] = self
end
def close()
unmap();
Stksequence.stk_destroy_sequence(@_seq)
end
def env()
return @_env
end
def unmap()
@@obj_map[@_seqptr] = nil
end
def hold()
Stksequence.stk_hold_sequence(@_seq)
end
def id()
return Stksequence.stk_get_sequence_id(@_seq);
end
def type()
return Stksequence.stk_get_sequence_type(@_seq);
end
def count()
return stk_number_of_sequence_elements(@_seq)
end
def release()
stk_destroy_sequence(@_seq)
end
def ref()
return @_seq
end
def iterate(clientd)
n = Stksequence.stk_sequence_first_elem(@_seq)
while Stksequence.stk_is_at_list_end(n) == 0 do
dptr = Stksequence.stk_sequence_node_data(n)
yield(self,dptr,Stksequence.stk_sequence_node_type(n),clientd)
n = Stksequence.stk_sequence_next_elem(@_seq,n)
end
end
def each(clientd)
iterate(clientd)
end
def copy_array_to(data,user_type)
v = Stksequence.new_voidDataArray(data.length)
data.each_with_index do |c,i|
Stksequence.voidDataArray_setitem(v,i,c) # Set a value
end
Stksequence.stk_copy_chars_to_sequence(@_seq,v,data.length,user_type)
Stksequence.delete_voidDataArray(v)
end
def copy_string_to(data,user_type)
return Stksequence.stk_copy_string_to_sequence(@_seq,data,user_type)
end
def self.find(seqid)
@@obj_map[seqid]
end
end
|
class CreateAddresses < ActiveRecord::Migration[5.2]
def change
create_table :addresses do |t|
t.integer :user_id, null: false
t.string :first_name, null: false
t.string :last_name, null: false
t.string :first_kana_name, null: false
t.string :last_kana_name, null: false
t.string :tel_number, null: false
t.string :postal_code, null: false
t.string :prefecture, null: false
t.string :city_address, null: false
t.string :building, null: false
t.timestamps
end
end
end
|
# frozen_string_literal: true
class User < ApplicationRecord
class MismatchedPassword < StandardError; end
include PgSearch::Model
include Concerns::Chapterable
include Concerns::Searchable
ALLOWABLE_FLAGS = %w[mod_manager logistics].freeze
attr_accessor :bypass_create_characters_hook
validates :last_name, presence: true
validates :email_address, presence: true, 'valid_email_2/email': true, uniqueness: true
validate :validates_flags
enum membership: { basic: 0, advanced: 1 }
enum role: { regular: 0, admin: 1, branch_owner: 2, guide: 3 }
has_secure_password validations: false
belongs_to :branch
has_many :memberships, dependent: :destroy
has_many :granted_memberships, foreign_key: :grantor_id, class_name: 'Membership', dependent: :restrict_with_error
has_many :characters, dependent: :restrict_with_error
has_many :event_attendees, dependent: :restrict_with_error
has_many :branch_owners, dependent: :destroy
has_many :owned_branches, through: :branch_owners, source: :branch
has_many :user_referrals, dependent: :destroy, foreign_key: :inviter_id
has_many :inviters, foreign_key: :newbie_id, class_name: 'UserReferral'
has_one :inviter, foreign_key: :newbie_id, class_name: 'UserReferral'
has_many :caps, dependent: :restrict_with_error
has_many :granted_caps, foreign_key: :grantor_id, class_name: 'Cap'
has_many :temporary_tokens, dependent: :destroy
has_many :temporary_managers, dependent: :destroy
has_many :external_managed_events, through: :temporary_managers, source: :event
has_many :corrective_actions, dependent: :restrict_with_error
has_many :corrections, dependent: :restrict_with_error, foreign_key: :staff_id, class_name: 'CorrectiveAction'
has_many :branch_transfers, dependent: :restrict_with_error
before_validation :uniquify_flags
before_save :cleanup_role_flags
after_create_commit :create_characters
after_update_commit :record_branch_transfer, if: :saved_change_to_branch_id?
id_searchable!
pg_search_scope(
:id_search,
against: :id,
using: :tsearch
)
pg_search_scope(
:multifield_search,
against: {
first_name: 'A',
last_name: 'A',
email_address: 'B'
},
using: {
trigram: { word_similarity: true },
tsearch: {
prefix: true,
any_word: true
}
},
ranked_by: ':tsearch * 0.5 + :trigram * 0.5'
)
scope :privileged, -> { where(role: %i[admin branch_owner guide]) }
scope :six_months_cutoff, -> { where(event_attendees: { events: { starts_at: 6.months.ago.. } }) }
scope :six_months_outlier, lambda {
where(event_attendees: { events: { starts_at: Date.new(2000, 1, 1)..6.months.ago } })
}
scope :actively_attending, -> { regular.six_months_cutoff.where.not(event_attendees: { id: nil }) }
scope :inactive, -> { regular.where.not(id: actively_attending.ids) }
scope :visitors, ->(branch) { where.not(branch: branch) }
scope :travel_games, lambda { |branch|
includes(event_attendees: :event).visitors(branch).where(event_attendees: { events: { branch: branch } })
}
def self.find_with!(username:)
User.find_by!(
'id = :username_as_id OR email_address ILIKE :username_as_email',
username_as_id: username.to_i,
username_as_email: username.to_s
)
end
def managed_events
Event.where(branch: owned_branches).or(Event.where(id: external_managed_events.ids))
end
def manages_event?(event)
external_managed_events.find_by(id: event.id).present?
end
def full_name
[first_name, last_name].join(' ').strip
end
def genesis_at
(characters.map(&:created_at) + Array.wrap(created_at)).min
end
def owns_branch?(branch)
owned_branches.find_by(id: branch.id).present?
end
def privileged?
admin? || branch_owner?
end
def add_membership!(grantor)
last_effective_date = memberships.active.pluck(:ends_at).max || Time.current
Membership.create!(
user: self,
grantor: grantor,
starts_at: last_effective_date,
bypass_extra_build_callbacks: extra_build_mask && last_effective_date.year == 2020
)
end
def update_password!(params)
raise MismatchedPassword, 'Old Password does not match' unless authenticate(params[:old_password])
update!(password: params[:new_password])
rescue BCrypt::Errors::InvalidHash
raise MismatchedPassword, 'Old Password does not match'
end
def add_referral!(newbie)
user_referrals << UserReferral.create!(inviter: self, newbie: newbie)
end
def remove_referral!(newbie)
user_referrals.find_by(newbie: newbie)&.destroy!
end
def membership_active_during_event?(event)
memberships.where(
'starts_at <= :t_buffered AND ends_at >= :t',
t_buffered: event.starts_at + 3.days,
t: event.starts_at
).present?
end
def suspended_for_event?(event)
corrective_actions.refusal_of_service.present? ||
corrective_actions.suspension.where(ends_at: nil).present? ||
corrective_actions.suspension.where('ends_at > :t', t: event.starts_at).present?
end
def first_event
event_attendees.blank? && characters.map(&:legacy_home_games).max.zero?
end
def last_membership
memberships.order('memberships.ends_at' => :desc).first
end
def extend_membership_by_two_months
return last_membership.extend_by_two_months if last_membership.present?
ActiveRecord::Base.transaction do
Membership.create!(
user: self,
starts_at: Time.current,
ends_at: Time.current + 2.months
)
update!(extra_build_mask: true)
end
end
private
def create_characters
return if bypass_create_characters_hook
3.times do |i|
Character.create!(
name: "Empty Slot #{i + 1}",
user: self,
strain_id: 0,
faith_id: 0,
status: :staged
)
end
end
def record_branch_transfer
BranchTransfer.create!(
user: self,
origin_id: branch_id_before_last_save,
destination_id: branch_id_in_database
)
end
def uniquify_flags
flags.uniq!
end
def cleanup_role_flags
self.flags = [] unless guide?
end
def validates_flags
diff = flags.uniq - ALLOWABLE_FLAGS
return if diff.blank?
errors.add(:base, "Invalid flags: #{diff.join(' ')}")
end
end
|
class Comedian < ApplicationRecord
validates_presence_of :name, :city
validates :age, presence: true, numericality: {
only_integer: true,
}
has_many :specials
def self.average_age
Comedian.average(:age).round(0).to_i
end
def self.cities
Comedian.distinct.pluck(:city)
end
end
|
class Configuration
attr_accessor :api_key, :urlname
end
|
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name, null: false
t.string :subdomain, null: false
t.string :domain, null: false
t.string :logo
t.string :address_1
t.string :address_2
t.string :city
t.string :county
t.string :postcode
t.string :latitude
t.string :longitude
t.string :tel
t.string :alt_tel
t.string :email
t.string :reg_no
t.string :vat_no
t.integer :plan, default: 2
t.timestamps
end
add_index :companies, :name, unique: true
end
end
|
class AddDealtToCards < ActiveRecord::Migration
def change
add_column :cards, :dealt, :boolean
end
end
|
xml.instruct!
xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.channel do
xml.title "Padrino Blog"
xml.description "The fantastic padrino sample blog"
xml.link url_for(:posts, :index)
for post in @posts
xml.item do
xml.title post.title
xml.description post.body
xml.pubDate post.created_at.to_s(:rfc822)
xml.link url_for(:posts, :show, :id => post)
end
end
end
end
|
require "csv"
require "awesome_print"
# class that creates an instance of an order
class Order
# creates methods that will allow reading or writing of specified instance variables
attr_reader :id, :products, :customer, :fulfillment_status
attr_writer :fulfillment_status
# constructor that sets up each instance of an order's id, products, customer, and fulfillment
# status. Raises an ArgumentError if fulfillment entered is not a valid option
def initialize(id, products, customer, fulfillment_status = :pending)
@id = id
@products = products
@customer = customer
@fulfillment_status = fulfillment_status
unless [:pending, :paid, :processing, :shipped, :complete].include?(@fulfillment_status)
raise ArgumentError, "Fulfillment status must be :pending, :paid, :processing, :shipped, :complete!"
end
end
# method that returns a hash containing the id, products, customer, and fulfillment status for an order
def new_order
order_hash = {
id: @id,
products: @products,
customer: @customer,
fulfillment_status: @fulfillment_status,
}
return order_hash
end
# method that returns the total value, plus 7.5% tax of all products in an order
def total
return @products.sum { |product, value| ("%.2f" % (value * 1.075)).to_f }
end
# method that adds a product and price to the existing products hash for an order
def add_product(product_name, price)
if @products.keys.include?(product_name)
raise ArgumentError, "A product with this name has already been added to the order!"
end
@products[product_name] = price
end
# method that removes a product and price from the existing products hash for an order
def remove_product(product_name)
unless @products.keys.include?(product_name)
raise ArgumentError, "A product of this name does not exist in the order!"
end
@products.delete_if { |product, cost| product == product_name }
end
# method that returns an array of all order instances using data pulled from the orders.csv file
def self.all
all_orders = []
CSV.open("data/orders.csv", "r").each do |line|
products_array = line[1].split(/[;:]/)
products_hash = Hash[*products_array]
products_hash.each { |product, price| products_hash[product] = price.to_f }
all_orders << Order.new(line[0].to_i, products_hash, Customer.find(line[2].to_i), line[3].to_sym)
end
return all_orders
end
# method that returns an instance of an order where the value of the id field in the CSV
# matches the passed parameter
def self.find(id)
return Order.all.find { |order| id == order.id }
end
end
|
require 'rails_helper'
describe ContestantPresenter do
let(:target) { double id: 42, name: 'John Doe', avatar_path: '/path/to/avatar' }
let(:contestant) { ContestantPresenter.new target }
describe 'id' do
it 'returns the target id' do
expect(contestant.id).to eq 42
end
end
describe 'name' do
it 'returns the target name' do
expect(contestant.name).to eq 'John Doe'
end
end
describe 'avatar' do
it 'builds the avatar html including the avatar path' do
expect(contestant.avatar).to include '/path/to/avatar'
end
end
describe 'call_for_action' do
it 'builds the call for action message for the target' do
expected = I18n.t 'presenters.contestant.call_for_action_html', contestant: 'John Doe', ext: '042'
expect(contestant.call_for_action).to include expected
end
end
end
|
class ChangeBookings < ActiveRecord::Migration
def change
change_table :bookings do |t|
t.remove :passenger_id
end
change_table :passengers do |t|
t.references :booking_id
end
end
end
|
$lines = IO.readlines('input.txt')
def possible_bin_combinations(length)
combinations = []
for i in 0..2**length - 1 do
combination = i.to_s(2)
if combination.length < length
combination = "#{zeros_string(length - combination.length)}#{combination}"
end
combinations << combination
end
return combinations
end
def apply_mask_p2(mask, target)
result = zeros_string(mask.length - 1)
mask.split('').each_with_index do |bit, i|
if bit == '0'
result[i] = target[i]
elsif bit == '1'
result[i] = '1'
elsif bit == 'X'
result[i] = 'X'
end
end
return result
end
def apply_mask_p1(mask, target)
result = zeros_string(mask.length - 1)
mask.split('').each_with_index do |bit, i|
if bit == 'X'
result[i] = target[i]
else
result[i] = bit
end
end
return result
end
def part_2(mask, mem, mem_pos, mem_val)
mem_pos_bin = mem_binary(mask, mem_pos)
mem_pos_result = apply_mask_p2(mask, mem_pos_bin)
mem_val_bin = mem_binary(mask, mem_val)
mem_pos_bin_comb = possible_bin_combinations(mem_pos_result.count('X'))
mem_pos_bin_comb.each do |comb|
mem_pos_mask = mem_pos_result.dup
comb.split('').each do |num|
x_pos = -1
mem_pos_mask.split('').each_with_index do |bit, i|
if bit == 'X'
x_pos = i
break
end
end
mem_pos_mask[x_pos] = num
end
mem[mem_pos_mask] = mem_val_bin
end
end
def mem_binary(mask, mem_val)
mem_val_bin = mem_val.to_i.to_s(2)
zeros = zeros_string(mask.length - mem_val_bin.length - 1)
return "#{zeros}#{mem_val_bin}"
end
def mem_sum(mem)
sum = 0
mem.each_value do |mem_val|
sum += mem_val.to_i(2)
end
return sum
end
def zeros_string(length)
zeros = ""
for i in 1..length do
zeros += '0'
end
return zeros
end
def part_1(mask, mem, mem_pos, mem_val)
mem_val_bin = mem_binary(mask, mem_val)
mem[mem_pos] = apply_mask_p1(mask, mem_val_bin)
end
def solve_part(part, out)
mem = {}
mask = ""
$lines.each do |line|
if line.start_with?("mask")
mask = line[7..]
else
mem_pos, mem_val = line[4..].split("] = ")
part.call(mask, mem, mem_pos, mem_val)
end
end
puts "#{out}: #{mem_sum(mem)}"
end
solve_part(method(:part_1), "pt.1")
solve_part(method(:part_2), "pt.2")
|
class Api::TaskListsController < Api::BaseController
#before_action :check_owner, only: [:show, :update, :destroy]
def index
# page = params[:page].to_i
# page_size = params[:page_size].to_i
task_lists = TaskList.all
# binding.pry
#task_lists = TaskList.paginate(:page => params[:page], :per_page => 3)
#task_lists_count = task_lists.count
# render json: @users, root: :users, each_serializer: UserSerializer, meta: { total: @users_count }
#render json: current_user.task_lists
render json: task_lists #, meta: { total: task_lists_count }
end
def show
render json: task_list
end
def create
#list = current_user.task_lists.create!(safe_params)
list = TaskList.create!(safe_params)
render json: list
end
def update
task_list.update_attributes(safe_params)
render nothing: true
end
def destroy
task_list.destroy
render nothing: true
end
private
def check_owner
permission_denied if current_user != task_list.owner
end
def task_list
@task_list ||= TaskList.find(params[:id])
end
def safe_params
params.require(:list).permit(:title,:page,:page_size)
end
end
|
class Exectest < ApplicationRecord
belongs_to :qa
belongs_to :suite
belongs_to :teste
end
|
require 'rails_helper'
RSpec.describe "Menus", type: :system do
describe "menus/index" do
let!(:user) { create :user }
let!(:admin) { create :admin }
let!(:menu) { create :menu }
let!(:menu_second) { create :menu_second }
let!(:menu_third) { create :menu_third }
context "user" do
before do
log_in_as user
visit menus_path
end
it "menu_path link test" do
first(".review-right-btn").click
expect(current_path).to eq menu_path(menu.id)
end
it "reservation link test" do
first(".menu_btn").click
expect(current_path).to eq new_reservation_path
end
end
context "admin" do
before do
log_in_as admin
visit menus_path
end
it "new_menu_path link test" do
click_on "メニューを追加する"
expect(current_path).to eq new_menu_path
end
it "menu destroy" do
first(".menu-delete").click
expect(page).to have_content "メニューを削除しました"
end
end
end
end
|
# frozen_string_literal: true
require 'saml/user_attributes/id_me'
require 'saml/user_attributes/mhv'
require 'saml/user_attributes/dslogon'
require 'sentry_logging'
require 'base64'
module SAML
class User
include SentryLogging
attr_reader :saml_response, :saml_attributes, :user_attributes
def initialize(saml_response)
@saml_response = saml_response
@saml_attributes = saml_response.attributes
@user_attributes = user_attributes_class.new(saml_attributes, real_authn_context)
log_warnings_to_sentry!
end
def changing_multifactor?
return false if real_authn_context.nil?
real_authn_context.include?('multifactor')
end
def to_hash
user_attributes.to_hash.merge(Hash[serializable_attributes.map { |k| [k, send(k)] }])
end
private
# we serialize user.rb with this value, in the case of everything other than mhv/dslogon,
# this will only ever be one of 'dslogon, mhv, or nil'
def authn_context
return 'dslogon' if dslogon?
return 'myhealthevet' if mhv?
nil
end
# returns the attributes that are defined below, could be from one of 3 distinct policies, each having different
# saml responses, hence this weird decorating mechanism, needs improved abstraction to be less weird.
def serializable_attributes
%i[authn_context]
end
def dslogon?
saml_attributes.to_h.keys.include?('dslogon_uuid')
end
def mhv?
saml_attributes.to_h.keys.include?('mhv_uuid')
end
# see warnings
# NOTE: The actual exception, if any, should get raised when to_hash is called. Hence "suppress"
def log_warnings_to_sentry!
suppress(Exception) do
if (warnings = warnings_for_sentry).any?
warning_context = {
real_authn_context: real_authn_context,
authn_context: authn_context,
warnings: warnings.join(', '),
loa: user_attributes.loa
}
log_message_to_sentry("Issues in SAML Response - #{real_authn_context}", :warn, warning_context)
end
end
end
# will be one of [loa1, loa3, multifactor, dslogon, mhv]
# this is the real authn-context returned in the response without the use of heuristics
def real_authn_context
REXML::XPath.first(saml_response.decrypted_document, '//saml:AuthnContextClassRef')&.text
# this is to add additional context when we cannot parse for authn_context
rescue NoMethodError
Raven.extra_context(
base64encodedpayload: Base64.encode64(saml_response.response),
attributes: saml_response.attributes.to_h
)
Raven.tags_context(controller_name: 'sessions', sign_in_method: 'not-signed-in:error')
raise
end
# We want to do some logging of when and how the following issues could arise, since loa is
# derived based on combination of these values, it could raise an exception at any time, hence
# why we use try/catch.
def warnings_for_sentry
warnings = []
warnings << 'LOA Current Nil' if user_attributes.loa_current.blank?
warnings << 'LOA Highest Nil' if user_attributes.loa_highest.blank?
warnings
end
# should eventually have a special case for multifactor policy and refactor all of this
# but session controller refactor is premature and can't handle it right now.
def user_attributes_class
case authn_context
when 'myhealthevet'; then SAML::UserAttributes::MHV
when 'dslogon'; then SAML::UserAttributes::DSLogon
else
SAML::UserAttributes::IdMe
end
end
end
end
|
require 'pry'
class Artist
attr_reader :name
@@all = []
def self.all
@@all
end
def initialize(name)
@name = name
@@all << self
end
def new_song(name, genre)
Song.new(name,self,genre)
end
#helper
def songs
Song.all.select do |song_instance|
song_instance.artist == self
end
end
def genres
songs.map do |song_instance|
song_instance.genre
end
end
end # end of class
|
# frozen_string_literal: true
class ImagesController < ActionController::Base
PUBLIC_MOUNTS = {
'User' => :image,
}
def show
http_cache_forever(public: true) do
model_name = params[:model_name]
attribute_name = PUBLIC_MOUNTS[model_name]
head(:not_authorized) and return unless attribute_name
filename = params[:filename]
model_class = model_name.constantize
model = model_class.find(params[:model_id])
url = model.send(attribute_name)
if url.present?
open(url) do |f|
send_data(f.read, filename:, disposition: :inline, content_type: f.content_type)
end
else
Rails.logger.warn("there is no uploaded file for params #{params}")
send_default_image
end
end
rescue
Rails.logger.warn("an error coccured dispatching image with params #{params}: #{$ERROR_INFO}")
send_default_image
end
private
def send_default_image
send_file(Rails.root.join('app/assets/images/logo.gif').to_s, filename: 'default-image.gif', disposition: :inline, content_type: 'image/gif')
end
end
|
class Cache
class << self
###
### Retrieving Information from the Cache
###
# Returns the current patch version
def get_patch
Rails.cache.read(:patch)
end
# @collection_key the plural collection identifier such as champions, items
# Returns a hash of all collection names mapped to their ids
def get_collection(collection_key)
Rails.cache.read(collection_key)
end
# @collection_key the singular collection identifier such as champion, item
# @entry_name the name of the collection entry to lookup in the collection
# Returns the information on the collection entry found by name in the collection
def get_collection_entry(collection_key, entry_name)
search_params = {}
search_params[collection_key] = entry_name
Rails.cache.read(search_params)
end
# @position the metric used to rank the champions such as kills, deaths
# @elo the elo for the rankings such as gold, silver
# @role the role being ranked such as top, mid
# Returns a list of champion names in ranked order
def get_champion_rankings(position, elo, role)
Rails.cache.read({ position: position, elo: elo, role: role })
end
# @name the name of the champion
# @role the role the champion is playing in
# @elo the elo the champion is playing in
# Returns the matchups for the specified champion in that role and elo
def get_champion_matchups(name, role, elo)
Rails.cache.read(matchups: { name: name, role: role, elo: elo })
end
# @name the name of the champion
# @role the role the champion is playing in
# @elo the elo the champion is playing in
# Returns the performance information of the champion in that role and elo
def get_champion_role_performance(name, role, elo)
Rails.cache.read({ name: name, role: role, elo: elo })
end
# @name the name of the summoner
# @region the region the summoner is playing in
# Returns the id of the summoner
def get_summoner_id(name, region)
Rails.cache.read(id: { name: name, region: region })
end
# @name the name of the summoner
# @region the region the summoner is playing in
# Returns the queues for the summoner
def get_summoner_queues(name, region)
Rails.cache.read(queues: { name: name, region: region })
end
###
### Setting Information into the Cache
###
# @patch_number the patch as a string of the form {major}.{minor} version
# Returns success or failure status
def set_patch(patch_number)
Rails.cache.write(:patch, patch_number)
end
# @name the name of the champion
# @role the role the champion is playing in
# @elo the elo the champion is playing in
# matchups the matchup data for how the champion with name @name does against
# other champions
# Returns success or failure status
def set_champion_matchups(name, role, elo, matchups)
Rails.cache.write({ matchups: { name: name, role: role, elo: elo } }, matchups)
end
# @position the metric used to rank the champions such as kills, deaths
# @elo the elo for the rankings such as gold, silver
# @role the role being ranked such as top, mid
# @rankings the rankings for champion performance in @role and @elo
# Returns success or failure status
def set_champion_rankings(position, elo, role, rankings)
Rails.cache.write({ position: position, elo: elo, role: role }, rankings)
end
# @name the name of the champion
# @role the role the champion is playing in
# @elo the elo the champion is playing in
# @performance the performance of the champion with @name in @role and @elo
# Returns success or failure status
def set_champion_role_performance(name, role, elo, performance)
Rails.cache.write({ name: name, role: role, elo: elo }, performance)
end
# @collection_key the plural collection identifier such as champions, items
# @ids_to_names the id to name hash for entries of the collection
# Returns success or failure status
def set_collection(collection_key, ids_to_names)
Rails.cache.write(collection_key, ids_to_names)
end
# @collection_key the singular collection identifier such as champion, item
# @entry_name the name of the collection entry to lookup in the collection
# @entry_info the information on the collection entry found by name in the
# collection
# Returns success or failure status
def set_collection_entry(collection_key, entry_name, entry_info)
search_params = {}
search_params[collection_key] = entry_name
Rails.cache.write(search_params, entry_info)
end
# @name the name of the summoner
# @region the region the summoner is playing in
# @id the summoner id
# Returns success or failure status
def set_summoner_id(name, region, id)
Rails.cache.write({ id: { name: name, region: region } }, id)
end
# @name the name of the summoner
# @region the region the summoner is playing in
# @queues the queues for the summoner
# @expiration the default expiration is 25 minutes, approximate duration of
# one game
# Returns success or failure status
def set_summoner_queues(name, region, queues, expiration = 25.minutes)
Rails.cache.write(
{ queues: { name: name, region: region } },
queues,
expires_in: expiration
)
end
end
# Define a get_or_set method that will retrieve the requested cache entry
# or set it to the value returned from the provided block
methods(false).map(&:to_s).select { |method_name| method_name.start_with?('get_') }
.each do |method_name|
base_method_name = method_name.split('get_').last
define_singleton_method("get_or_set_#{base_method_name}") do |*args, &block|
return_value = send(method_name, *args)
return return_value if return_value
block.call.tap do |rv|
send("set_#{base_method_name}", *(args + [rv]))
end
end
end
end
|
class RenameRequestColumnToJobAdministrations < ActiveRecord::Migration[5.0]
def change
rename_column :blogs, :tweet_id, :user_id
end
end
|
# Command Pattern
class Command
attr_reader :description
def initialize(description)
@description = description
puts @description
end
def execute
end
end
class CreateFile < Command
def initialize(path, contents)
super "Create file: #{path}"
@path = path
@contents = contents
end
def execute
f = File.open(@path, "w")
f.write(@contents)
f.close
end
def unexecute
File.delete(@path)
end
end
class DeleteFile < Command
def initialize(path)
super "Delete file: #{path}"
@path = path
end
def execute
if File.exists?(@path)
@contents = File.read(@path)
end
f = File.delete(@path)
end
def unexecute
if @contents
f = File.open(@path,"w")
f.write(@contents)
f.close
end
end
end
create_command = CreateFile.new('file1.txt', "hello world\n")
create_command.execute
delete_command = DeleteFile.new('file1.txt')
delete_command.execute |
class User < ActiveRecord::Base
has_many :groups
has_many :items, through: :groups
end |
class LogsController < ApplicationController
def new
@ticket = Ticket.find(params[:ticket_id])
@log = @ticket.logs.new
end
def create
@log = Log.create(log_params)
if @log.valid?
@log.save!
flash[:notice] = "New ticket log saved sucessfully"
redirect_to tickets_path
else
render :new
end
end
def index
end
def update
end
private
def log_params
params.permit(:description, :ticket_id)
end
end
|
PointlessFeedback.setup do |config|
# ==> Feedback Configuration
# Configure the topics for the user to choose from on the feedback form
# config.message_topics = ['Error on page', 'Feature Request', 'Praise', 'Other']
# ==> Email Configuration
# Configure feedback email properties (disabled by default)
# Variables needed for emailing feedback
# config.email_feedback = false
# config.send_from_submitter = false
# config.from_email = 'feedback@pointlesscorp.com'
# config.to_emails = ['first@example.com', 'second@example.com']
# ==> Google reCAPTCHA Configuration
# If you'd like to enable Google reCAPTCHA,
# 1. Register your site at: https://www.google.com/recaptcha/admin
# 2. !! Ensure you opt for reCAPTCHA v2. Support for v3 is not here yet.
# 3. Grab the site and secret key and paste them here.
#
# config.google_captcha_site_key = nil
# config.google_captcha_secret_key = nil
# ==> Airtable Configuration
# If you'd like to export feedback submissions to an Airtable database,
# 1. Create an Airtable database with the following columns:
# - Name
# - Email
# - Topic
# - Description
# 2. Generate an API Key: https://airtable.com/account
# 3. Find your app key and table name: https://airtable.com/api
# 4. Fill in all these configs
#
# config.airtable_api_key = "key--------------"
# config.airtable_app_key = "app--------------"
# config.airtable_table_name = "Feedback Tracker"
end
|
require 'spec_helper'
feature 'Deleting activities' do
before do
sign_in_as!(FactoryGirl.create(:admin_user))
end
scenario 'Deleting an activity' do
FactoryGirl.create(:activity, name:'Student Project')
visit '/'
click_link 'Student Project'
click_link 'Delete Activity'
expect(page).to have_content('Activity has been deleted.')
visit '/'
expect(page).to have_no_content('Student Project')
end
end
|
# frozen_string_literal: true
# Road class
class Road
attr_accessor :point_a, :point_b
def initialize(point_a, point_b)
@point_a = point_a
@point_b = point_b
end
end
|
class Status < ActiveRecord::Base
belongs_to :user, inverse_of: :statuses
belongs_to :task, inverse_of: :statuses
default_scope -> { order('created_at DESC') }
validates :content, presence: true
validates :user_id, presence: true
end
|
require './statcollector.rb'
require 'psych'
describe "The StatConfiguration class" do
before(:all) do
@fullconfig = Psych.load('
name: myproject
location: /a/location/for/myproject
max: 10
one_per_day: true
decending: true
output: csv
collect:
command1: "a command"
command2: another command
')
@partialconfig = Psych.load('
name: myproject
location: /a/location/for/myproject
collect:
command1: "a command"
')
@invalidconfig = Psych.load('
name: myproject
collect:
command1: "a command"
')
end
it "should be able to be configured" do
config = StatConfiguration.new(@fullconfig)
config.max.should eq(10)
config.name.should eq("myproject")
config.location.should eq("/a/location/for/myproject")
config.one_per_day.should eq(true)
config.decending.should eq(true)
config.output.should eq("csv")
end
it "should be able to be configured with sensible defaults" do
config = StatConfiguration.new(@partialconfig)
config.max.should eq(0)
config.name.should eq("myproject")
config.location.should eq("/a/location/for/myproject")
config.one_per_day.should eq(false)
config.decending.should eq(false)
config.output.should eq("graph")
end
it "should not be able to be configured without a location" do
expect { StatConfiguration.new(@invalidconfig) }.to raise_error
end
it "should have an hash of collection commands" do
config = StatConfiguration.new(@fullconfig)
config.collect.should eq "command1" => "a command","command2" => "another command"
end
it "should setup a temp directory when created" do
config = StatConfiguration.new(@fullconfig)
config.tmp_repo.should end_with("myproject")
config.tmp_repo.should start_with(config.tmp_root)
end
end
describe "The StatCollector class" do
before(:all) do
@fullconfig = Psych.load('
name: myproject
location: /a/location/for/myproject
max: 0
collect:
command1: "a command"
command2: another command
')
@commits = 'ahash|2012-08-15|
bhash|2012-08-15|
chash|2012-08-14|'
end
before(:each) do
@repo = double("GitRunner")
@repo.stub(:listCommits).and_return(@commits)
@repo.stub(:setupRepo)
@repo.stub(:checkout)
@config = double("StatConfiguration")
@config.stub(:location).and_return("/location")
@config.stub(:collect).and_return({"command1" => "a command","command2" => "another command"})
end
it "should be able to retrieve a list of hashs containing commit information" do
collector = StatCollector.new(StatConfiguration.new(@fullconfig),@repo)
collector.commits.should eq([{:hash => "ahash",:date => "2012-08-15"},{:hash => "bhash",:date => "2012-08-15"},{:hash => "chash",:date => "2012-08-14"}])
end
it "should be able to collect information on each commit" do
@repo.stub(:runCmd).and_return("1","2")
collector = StatCollector.new(StatConfiguration.new(@fullconfig),@repo)
collector.checkout_and_collect({:hash => "ahash", :date => "2012-08-15"}).should eq({:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2})
end
it "should be able to collect information on a number of commits" do
@repo.stub(:runCmd).and_return("1","2","3","4","5","6")
@config.stub(:max).and_return(0) #0 means that we should return an unlimited number of results
@config.stub(:one_per_day).and_return(false)
@config.stub(:decending).and_return(true)
collector = StatCollector.new(@config,@repo)
statistics = collector.get_statistics
statistics.first.should eq({:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2})
statistics.last.should eq({:hash => "chash", :date => "2012-08-14", "command1" => 5, "command2" => 6})
statistics.size.should eq(3)
end
it "should be able to collect information on a number of commits in acending order" do
@repo.stub(:runCmd).and_return("1","2","3","4","5","6")
@config.stub(:max).and_return(0) #0 means that we should return an unlimited number of results
@config.stub(:one_per_day).and_return(false)
@config.stub(:decending).and_return(false)
collector = StatCollector.new(@config,@repo)
statistics = collector.get_statistics
statistics.first.should eq({:hash => "chash", :date => "2012-08-14", "command1" => 5, "command2" => 6})
statistics.last.should eq({:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2})
end
it "should be able to limit collecting to the value of max" do
@repo.stub(:runCmd).and_return("1","2","3","4","5","6")
@config.stub(:max).and_return(1)
@config.stub(:one_per_day).and_return(false)
@config.stub(:decending).and_return(true)
collector = StatCollector.new(@config,@repo)
statistics = collector.get_statistics
#statistics[0].should eq({:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2})
statistics.size.should eq(1)
end
it "should be able to collect information on a maximum of 1 commit a day" do
@repo.stub(:runCmd).and_return("1","2","3","4")
@config.stub(:max).and_return(0) #0 means that we should return an unlimited number of results
@config.stub(:one_per_day).and_return(true)
@config.stub(:decending).and_return(true)
collector = StatCollector.new(@config,@repo)
statistics = collector.get_statistics
statistics.size.should eq(2)
statistics[0].should eq({:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2})
statistics[1].should eq({:hash => "chash", :date => "2012-08-14", "command1" => 3, "command2" => 4})
end
end |
class SlackCommentDecoratorService
attr_accessor :github_comment, :subscription
def initialize(github_comment)
@github_comment = github_comment
@subscription = ''
end
def title
case github_comment.state
when 'approved'
approve_comment
when 'changes_requested'
@subscription = comment_subscription
change_requested_comment
when 'merged'
merged_comment
when 'closed'
closed_comment
when 'reopened'
reopened_comment
when 'assigned'
assigned_action
when 'review_requested'
review_requested_comment
else
@subscription = comment_subscription
normal_comment
end
end
def mention_slack_format(mentions)
mentions.map{ |s| "<#{s}>" }.join(' ')
end
def body
return github_comment.state.gsub('_', ' ').capitalize if github_comment.body.to_s.empty?
result = github_comment.body.to_s
JSON.parse(ENV["USER_MAPPING"]).each do |user_github, user_slack|
result = result.gsub(user_github, "<#{user_slack}>")
end
result
end
def mentions
return '' unless github_comment.body.present?
github_mentions = github_comment.body.split.uniq.select { |word| word.start_with?('@') }
github_mentions
.map { |p| JSON.parse(ENV["USER_MAPPING"])[p.gsub(/[^@a-zA-Z0-9\-]/,"")] }
.compact
.uniq
end
private
def comment_subscription
return '' if !github_comment.first_comment_in_thread? || github_comment.author_of_thread?
subscribe_user = JSON.parse(ENV["USER_MAPPING"])["@#{github_comment.author_name}"]
return "\n\n <#{subscribe_user}> subscribed to this thread" if subscribe_user
''
end
def reopened_comment
"<#{github_comment.html_url}|:unlock: #{github_comment.author_name}>"
end
def assigned_action
"<#{github_comment.html_url}|:bust_in_silhouette: #{github_comment.author_name}>"
end
def closed_comment
"<#{github_comment.html_url}|:closed_lock_with_key: #{github_comment.author_name}>"
end
def merged_comment
"<#{github_comment.html_url}|:lock: #{github_comment.author_name}>"
end
def change_requested_comment
"<#{github_comment.html_url}|:x: #{github_comment.author_name}>"
end
def approve_comment
"<#{github_comment.html_url}|:white_check_mark: #{github_comment.author_name}>"
end
def normal_comment
"<#{github_comment.html_url}|:speech_balloon: #{github_comment.author_name}>"
end
def review_requested_comment
"<#{github_comment.html_url}|:eye-in-speech-bubble: #{github_comment.author_name}>"
end
end
|
module Inventory
class SeedCatalogue
prepend SimpleCommand
def initialize(args = {})
@args = args
end
def call
seed_raw_material_catalogue!
seed_plant_catalogue!
seed_sales_catalogue!
seed_non_sales_catalogue!
nil
end
private
def seed_raw_material_catalogue!
raw_materials_template.each do |raw_material|
Inventory::Catalogue.find_or_create_by!(catalogue_type: 'raw_materials', key: raw_material[:key]) do |c|
c.label = raw_material[:label]
c.category = raw_material[:category]
c.sub_category = raw_material[:sub_category] || ''
c.uom_dimension = raw_material[:uom_dimension]
c.common_uom = raw_material[:common_uom]
c.is_active = true
end
end
end
def seed_plant_catalogue!
Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::PLANTS_KEY, key: Constants::PLANTS_KEY) do |c|
c.label = 'Plants'
c.category = Constants::PLANTS_KEY
c.is_active = true
c.uom_dimension = Constants::UOM_DMS_PIECES
end
# Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::PLANTS_KEY, key: Constants::SEEDS_KEY) do |c|
# c.label = Constants::PLANTS_KEY
# c.category = Constants::PLANTS_KEY
# c.is_active = true
# c.uom_dimension = Constants::UOM_DMS_PIECES
# end
# Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::PLANTS_KEY, key: Constants::PURCHASED_CLONES_KEY) do |c|
# c.label = 'Purchased Clones'
# c.category = Constants::PLANTS_KEY
# c.is_active = true
# c.uom_dimension = Constants::UOM_DMS_PIECES
# end
end
def seed_sales_catalogue!
sales_template.each do |item|
Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::SALES_KEY, key: item[:key]) do |c|
c.label = item[:label]
c.category = item[:category]
c.sub_category = item[:sub_category] || ''
c.uom_dimension = item[:uom_dimension]
c.common_uom = item[:common_uom]
c.is_active = true
end
end
end
def seed_non_sales_catalogue!
Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::NON_SALES_KEY, key: Constants::NON_SALES_KEY) do |c|
c.label = 'Non Sales Product'
c.is_active = true
end
keys = ['vacumn_sealer', 'pos', 'desktop', 'workdesk', 'stationery']
keys.each do |key|
Inventory::Catalogue.find_or_create_by!(catalogue_type: Constants::NON_SALES_KEY, key: key) do |c|
c.label = key.titleize
c.category = Constants::NON_SALES_KEY
c.sub_category = ''
c.uom_dimension = 'piece'
c.common_uom = 'pc'
c.is_active = true
end
end
end
def raw_materials_template
[
# General rule: Only selectable by user has uom_dimension.
# If main parent, category is empty.
# The child must use parent key in category field.
# Child of the child must use its parent key in subcategory field.
# Others and its child
{label: 'Others', category: '', key: Constants::OTHERS_KEY, is_active: true},
{label: 'Antibacterial Soap', category: Constants::OTHERS_KEY, key: 'antibacterial_soap', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Eye drops', category: Constants::OTHERS_KEY, key: 'eye_drops', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Eye Protection', category: Constants::OTHERS_KEY, key: 'eye_protection', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Garbage Bags', category: Constants::OTHERS_KEY, key: 'garbage_bags', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Nitrile Gloves', category: Constants::OTHERS_KEY, key: 'nitrile_gloves', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Rubbing Alcohol', category: Constants::OTHERS_KEY, key: 'rubbing_alcohol', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Scale', category: Constants::OTHERS_KEY, key: 'scale', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Seal Bags', category: Constants::OTHERS_KEY, key: 'seal_bags', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
# {label: 'Supplements', category: Constants::OTHERS_KEY, key: 'supplements', is_active: true, uom_dimension: 'piece'},
{label: 'Trim Station', category: Constants::OTHERS_KEY, key: 'trim_station', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Trim Trays', category: Constants::OTHERS_KEY, key: 'trim_trays', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Trimming Scissors', category: Constants::OTHERS_KEY, key: 'trimming_scissors', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Vacuum Sealer ', category: Constants::OTHERS_KEY, key: 'vacuum_sealer', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Other', category: Constants::OTHERS_KEY, key: 'others_other', is_active: true, uom_dimension: 'piece'},
# Grow light and its child
{label: 'Grow lights', category: '', key: Constants::GROW_LIGHT_KEY, is_active: true},
{label: 'CMH', category: Constants::GROW_LIGHT_KEY, key: 'cmh', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'HID', category: Constants::GROW_LIGHT_KEY, key: 'hid', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'HPS', category: Constants::GROW_LIGHT_KEY, key: 'hps', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'LED', category: Constants::GROW_LIGHT_KEY, key: 'led', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'MS', category: Constants::GROW_LIGHT_KEY, key: 'ms', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
{label: 'T5 Fluorescent', category: Constants::GROW_LIGHT_KEY, key: 't5_fluorescent', is_active: true, uom_dimension: 'piece', common_uom: 'pc'},
# Grow medium and its child
{label: 'Grow medium', category: '', key: Constants::GROW_MEDIUM_KEY, is_active: true},
{label: 'Coco coir', category: Constants::GROW_MEDIUM_KEY, key: 'coco_coir', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Compost soil', category: Constants::GROW_MEDIUM_KEY, key: 'compost_soil', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Hardened Expanded Clay (HEC)', category: Constants::GROW_MEDIUM_KEY, key: 'hec', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Mineral Wool', category: Constants::GROW_MEDIUM_KEY, key: 'mineral_wool', is_active: true, uom_dimension: 'weight', common_uom: 'pc'},
{label: 'Peat', category: Constants::GROW_MEDIUM_KEY, key: 'peat', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Perlite', category: Constants::GROW_MEDIUM_KEY, key: 'perlite', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
{label: 'Soil', category: Constants::GROW_MEDIUM_KEY, key: 'soil', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
{label: 'Sphagnum', category: Constants::GROW_MEDIUM_KEY, key: 'sphagnum', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Vermiculite', category: Constants::GROW_MEDIUM_KEY, key: 'vermiculite', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# Nutrient and its child (2 level)
{label: 'Nutrients', category: '', key: Constants::NUTRIENTS_KEY, is_active: true},
# Blend has no child
# {label: 'Blend', category: '', key: 'blend', sub_category: '', is_active: true},
# {label: 'Blend', category: Constants::NUTRIENTS_KEY, key: 'blend_blend', sub_category: 'blend', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Nitrogen Product', category: Constants::NUTRIENTS_KEY, key: 'nitrogen', sub_category: '', is_active: true, common_uom: 'l'},
# {label: 'Ammonia (NH3)', category: Constants::NUTRIENTS_KEY, key: 'ammonia', sub_category: 'nitrogen', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Blood Meal', category: Constants::NUTRIENTS_KEY, key: 'blood_meal', sub_category: 'nitrogen', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Cottonseed Meal', category: Constants::NUTRIENTS_KEY, key: 'cottonseed_meal', sub_category: 'nitrogen', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Fish Emulsion', category: Constants::NUTRIENTS_KEY, key: 'fish_emulsion', sub_category: 'nitrogen', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
# {label: 'Urea', category: Constants::NUTRIENTS_KEY, key: 'urea', sub_category: 'nitrogen', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Phosphate Product', category: Constants::NUTRIENTS_KEY, key: 'phosphate', sub_category: '', is_active: true},
# {label: 'Bone Meal', category: Constants::NUTRIENTS_KEY, key: 'bone_meal', sub_category: 'phosphate', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Rock Phosphate', category: Constants::NUTRIENTS_KEY, key: 'rock phosphate', sub_category: 'phosphate', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Slag', category: Constants::NUTRIENTS_KEY, key: 'slag', sub_category: 'phosphate', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Super Phosphate', category: Constants::NUTRIENTS_KEY, key: 'super_phosphate', sub_category: 'phosphate', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Potassium Product', category: Constants::NUTRIENTS_KEY, key: 'potassium', sub_category: '', is_active: true},
# {label: 'Seaweed', category: Constants::NUTRIENTS_KEY, key: 'seaweed', sub_category: 'potassium', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Wood ashes', category: Constants::NUTRIENTS_KEY, key: 'wood_ashes', sub_category: 'potassium', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# # Supplement and its child
# {label: 'Supplements', category: '', key: Constants::SUPPLEMENTS_KEY, is_active: true},
# {label: 'Amino Acid', category: Constants::SUPPLEMENTS_KEY, key: 'amino_acid', is_active: true, uom_dimension: 'volume', common_uom: 'l'},
# {label: 'Azomite', category: Constants::SUPPLEMENTS_KEY, key: 'azomite', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Bat Guano', category: Constants::SUPPLEMENTS_KEY, key: 'bat_guano', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
# {label: 'Blood Meal', category: Constants::SUPPLEMENTS_KEY, key: 'blood_meal', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Carbohydrates', category: Constants::SUPPLEMENTS_KEY, key: 'carbohydrates', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
# {label: 'Citric acids', category: Constants::SUPPLEMENTS_KEY, key: 'citric_acids', is_active: true, uom_dimension: 'volume', common_uom: 'kg'},
# {label: 'Compost tea', category: Constants::SUPPLEMENTS_KEY, key: 'compost_tea', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
# {label: 'Dolomite Lime', category: Constants::SUPPLEMENTS_KEY, key: 'dolomite_lime', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Enzymes', category: Constants::SUPPLEMENTS_KEY, key: 'enzymes', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Epsom Salt', category: Constants::SUPPLEMENTS_KEY, key: 'epsom_salt', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Fulvic acid', category: Constants::SUPPLEMENTS_KEY, key: 'fulvic_acid', is_active: true, uom_dimension: 'volume', common_uom: 'kg'},
# {label: 'Gibberellic Acid', category: Constants::SUPPLEMENTS_KEY, key: 'gibberellic_acid', is_active: true, uom_dimension: 'volume', common_uom: 'l'},
# {label: 'Humic Acid', category: Constants::SUPPLEMENTS_KEY, key: 'humic_acid', is_active: true, uom_dimension: 'volume', common_uom: 'l'},
# {label: 'Mycorrhiza', category: Constants::SUPPLEMENTS_KEY, key: 'mycorrhiza', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Silica', category: Constants::SUPPLEMENTS_KEY, key: 'silica', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Sulfur based additives', category: Constants::SUPPLEMENTS_KEY, key: 'sulfur_based_additives', is_active: true, uom_dimension: 'weight', common_uom: 'l'},
# {label: 'Vitamin', category: Constants::SUPPLEMENTS_KEY, key: 'vitamin', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Worm Castings', category: Constants::SUPPLEMENTS_KEY, key: 'worm castings', is_active: true, uom_dimension: 'weight', common_uom: 'kg'},
# Purchased clones and seed
{label: 'Seeds', category: '', key: Constants::SEEDS_KEY, is_active: true, uom_dimension: Constants::PLANTS_KEY, common_uom: 'kg'},
{label: 'Purchased clone', category: '', key: Constants::PURCHASED_CLONES_KEY, is_active: true, uom_dimension: Constants::PLANTS_KEY, common_uom: 'kg'},
]
end
def sales_template
[
{label: 'Capsule/Tablet', category: Constants::CONVERTED_PRODUCT_KEY, key: 'capsule_tablet', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Concentrate (liquid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'concentrate_liquid', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Concentrate (liquid each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'concentrate_liquid_each', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Concentrate (solid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'concentrate_solid', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Concentrate (solid each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'concentrate_solid each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Edible', category: Constants::CONVERTED_PRODUCT_KEY, key: 'edible', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Edible (each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'edible_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Extract (liquid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'extract_liquid', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Extract (liquid-each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'extract_liquid_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Extract (solid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'extract_solid', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Extract (solid-each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'extract_solid_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Liquid', category: Constants::CONVERTED_PRODUCT_KEY, key: 'liquid', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Liquid (each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'liquid_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Pre-Roll Flower', category: Constants::CONVERTED_PRODUCT_KEY, key: 'pre_roll_flower', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Pre-Roll Leaf', category: Constants::CONVERTED_PRODUCT_KEY, key: 'pre_roll_leaf', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Suppository (each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'suppository_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Tincture', category: Constants::CONVERTED_PRODUCT_KEY, key: 'tincture', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Tincture (each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'tincture_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Topical', category: Constants::CONVERTED_PRODUCT_KEY, key: 'topical', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Topical (liquid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'topical_liquid', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Topical (liquid-each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'topical_liquid_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Topical (solid)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'topical_solid', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Topical (solid-each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'topical_solid_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Vape Oil', category: Constants::CONVERTED_PRODUCT_KEY, key: 'vape_oil', uom_dimension: 'volume', common_uom: 'l'},
{label: 'Vape Oil (each)', category: Constants::CONVERTED_PRODUCT_KEY, key: 'vape_oil_each', uom_dimension: 'piece', common_uom: 'pc'},
{label: 'Wax', category: Constants::CONVERTED_PRODUCT_KEY, key: 'wax', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Other', category: Constants::CONVERTED_PRODUCT_KEY, key: 'other', uom_dimension: 'weight', common_uom: 'kg'},
# These are items can be created by grower
# {label: 'Flower', category: 'raw_sales_product', key: 'flower', uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Fresh Cannabis Plant', category: 'raw_sales_product', key: 'fresh_cannabis_plant', uom_dimension: 'piece', common_uom: 'pc'},
# {label: 'Immature Plant', category: 'raw_sales_product', key: 'immature_plant', uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Kief', category: 'raw_sales_product', key: 'kief', uom_dimension: 'weight', common_uom: 'kg'},
# {label: 'Leaf', category: 'raw_sales_product', key: 'leaf', uom_dimension: 'weight', common_uom: 'kg'},
{label: 'Whole plant', category: 'raw_sales_product', key: 'whole_plant', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Flowers (buds)', category: 'raw_sales_product', key: 'flowers_buds', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Kief', category: 'raw_sales_product', key: 'kief', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Shakes', category: 'raw_sales_product', key: 'shakes', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Trims', category: 'raw_sales_product', key: 'trims', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Pre-rolls', category: 'raw_sales_product', key: 'pre_rolls', uom_dimension: 'weight', common_uom: 'g'},
{label: 'Flower', category: 'raw_sales_product', key: 'flower', uom_dimension: 'weight', common_uom: 'kg'},
]
end
end
end
|
require './key'
require 'twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = CONSUMER_KEY
config.consumer_secret = CONSUMER_SECRET
config.access_token = ACCESS_TOKEN
config.access_token_secret = ACCESS_TOKEN_SECRET
end
#ツイートする
client.update("Test tweet from twitter-api with ruby\nby @sammyo_official")
# ユーザー名を指定したユーザー情報をuserに格納する
user = client.user("sammyo_official")
# 上のコードを実行すことにより下記のコマンドが使用できる
p user.id # ユーザのID
p user.screen_name # ユーザ名
p user.protected? # ユーザがプロテクト状態かどうか
p user.tweets_count # ユーザのツイート数を取得
p user.followers_count # フォロワーの数
p user.friends_count # フォローしている数
# ruby app.rb
# ↑これで実行 |
require "rails_helper"
describe Dashboard::BlocksController do
let!(:user) { create(:user) }
let!(:register) { @controller.send(:auto_login, user) }
let!(:block) { create(:block, user: user) }
describe "PUT #set_as_current" do
before { put :set_as_current, id: block.id }
it { is_expected.to redirect_to :blocks }
it "sets block as current block for user" do
expect(user.current_block).to eq(block)
end
end
describe "PUT #reset_as_current" do
before { put :reset_as_current, id: block.id }
it { is_expected.to redirect_to :blocks }
it "reset current block for user" do
expect(user.current_block).to be_nil
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.