text stringlengths 10 2.61M |
|---|
#!/usr/bin/env ruby
# @param {String} str
# @return {Integer}
def my_atoi(str)
ret = str.to_i
if ret > 2147483647
ret = 2147483647
end
if ret < -2147483648
ret = -2147483648
end
ret
end |
module Antelope
module Generator
class CHeader < Base
register_as "c-header", "c_header"
has_directive "union", Array[String, String]
has_directive "api.prefix", String
has_directive "api.push-pull", String
has_directive "api.value.type", String
has_directive "api.token.prefix", String
has_directive "parse-param", Array
has_directive "lex-param", Array
has_directive "param", Array
def push?
directives.api.push_pull == "push"
end
def define_stype?
!!directives.union[0] && !directives.api.value.type
end
def lex_params
params = [directives.lex_param, directives.param].compact.
flatten
if params.any?
", " << params.join(", ")
else
""
end
end
def parse_params
[directives.parse_param, directives.param].compact.flatten.
join(", ")
end
def params
if directives.param
directives.param.join(", ")
else
""
end
end
def stype
prefix.upcase << if directives.api.value.type
directives.api.value.type
elsif directives.union.size > 1
directives.union[0]
else
"STYPE"
end
end
def union_body
directives.union.last
end
def terminal_type
"int" # for now
end
def token_prefix
if directives.api.token.prefix
directives.api.token.prefix
elsif directives.api.prefix
prefix.upcase
else
""
end
end
def prefix
if directives.api.prefix
directives.api.prefix
else
"yy"
end
end
def upper_prefix
prefix.upcase
end
def symbols
@_symbols ||= begin
sym = grammar.terminals.map(&:name) + grammar.nonterminals
nums = sym.each_with_index.map { |v, i| [v, i + 257] }
Hash[nums]
end
end
def guard_name
"#{prefix.upcase}#{file.gsub(/[\W]/, "_").upcase}"
end
def generate
template "c_header", "#{file}.h"
end
end
end
end
|
class RecipesController < ApplicationController
impressionist :actions=> [:show]
def index
@recipes = Recipe.all.order(created_at: "DESC").limit(8)
@tsukurepos = Tsukurepo.all.order(created_at: "DESC").limit(8)
end
def new
@recipe = Recipe.new
@recipe.flows.build
@recipe.ingredients.build
end
def create
@recipe = Recipe.create(recipe_params)
redirect_to root_path
end
def edit
@recipe = Recipe.find(params[:id])
end
def update
@recipe = Recipe.find(params[:id])
if @recipe.update(recipe_params)
redirect_to root_path, notice: "レシピを編集しました"
else
render :edit
end
end
def show
@recipe = Recipe.find(params[:id])
@recipes = Recipe.all
@ingredients = @recipe.ingredients.includes(:recipe)
@flows = @recipe.flows.order(order: "ASC").includes(:recipe)
@comment = Comment.new
@comments = @recipe.comments.includes(:user)
@tsukurepos = @recipe.tsukurepos.includes(:user)
impressionist(@recipe, nil, unique: [:session_hash])
@pv = @recipe.impressionist_count
@today = @recipe.impressionist_count(start_date: Date.today)
@history = @recipe.register_to_history(current_user)
respond_to do |format|
format.html
format.json
end
end
def list
@user = User.find(params[:id])
@recipes = @user.recipes.includes(:ingredients)
if params[:keyword].present?
@recipes = Recipe.find(Recipe.select_target_recipe_id(params[:keyword],@user.id))
end
respond_to do |format|
format.html
format.json{@recipes}
end
end
def destroy
@recipe = Recipe.find(params[:id])
if @recipe.destroy
redirect_to action: "list", id: current_user.id
else
flash.now[:error] = "レシピの削除に失敗しました"
render action: "list", id: current_user.id
end
end
def recipe_rankings
end
def save
end
private
def recipe_params
params.require(:recipe).permit(
:title,
:catch_copy,
:image,
:tips,
:background,
:user_id,
{ ingredients_attributes: [:id, :recipe_id, :name , :amount, :_destroy ] },
{ flows_attributes: [:id, :recipe_id, :image, :text, :order, :_destroy ] }
).merge(user_id: current_user.id)
end
end
|
require 'yaml'
require 'fileutils'
require 'sprawl/service_definition'
module Sprawl
class MultiGitLoader
def self.load(options)
puts 'Using Multi Git Loader' if options[:verbose]
begin
# Make temp directory
Dir.mkdir('.sprawl')
pull_repos(options[:group])
service_definitions = []
Dir.glob('.sprawl/**/SPRAWL').each do |def_file|
puts "Loading definition #{def_file}" if options[:verbose]
begin
service_definitions << Sprawl::ServiceDefinition.from(YAML.load_file(File.join(def_file)))
rescue
puts "Failed to load #{def_file}. Trying the rest."
end
end
ensure
FileUtils.rm_rf('.sprawl')
end
service_definitions
end
def pull_repos(urls)
urls.each do |url|
puts "Pulling git repository of definitions from #{url}" if options[:verbose]
Dir.chdir('.servitude') do
`git clone #{url}`
end
end
end
end
end
|
# added in release 1.7.0
module GroupDocs
class Document::TemplateEditorFields < Api::Entity
# @attr [Integer] page
attr_accessor :page
# @attr [String] name
attr_accessor :name
# @attr [String] type
attr_accessor :type
# @attr [GroupDocs::Document::Rectangle] rect
attr_accessor :rect
# @attr [String] fieldtype
attr_accessor :fieldtype
# @attr [Array] acceptableValues
attr_accessor :acceptableValues
# @attr [Int] selectionPosition
attr_accessor :selectionPosition
# @attr [Int] selectionLength
attr_accessor :selectionLength
# @attr [GroupDocs::Document::Style] style
attr_accessor :style
# @attr [Boolean] isTableMarker
attr_accessor :isTableMarker
# changed in release 2.0.0
# @attr [GroupDocs::Document::FieldOption] options
attr_accessor :options
# added in release 2.0.0
# @attr [Int] tableNumber
attr_accessor :tableNumber
# @attr [Int] tableRow
attr_accessor :tableRow
# @attr [Int] tableColumn
attr_accessor :tableColumn
# @attr [Int] tableCell
attr_accessor :tableCell
#
# Converts passed hash to GroupDocs::Document::Rectangle object.
# @param [Hash] options
#
def rect=(rectangle)
if rectangle.is_a?(Hash)
rectangle = GroupDocs::Document::Rectangle.new(rectangle)
end
@rect = rectangle
end
#
# Converts passed hash to GroupDocs::Document::TemplateEditorFieldStyle object.
# @param [Hash] options
#
def style=(style)
if style.is_a?(Hash)
style = GroupDocs::Document::TemplateEditorFieldStyle.new(style)
end
@style = style
end
# Human-readable accessors
alias_accessor :rectangle, :rect
end # Document::TemplateEditorFields
end # GroupDocs
|
require 'rails_helper'
describe 'token middleware', :type => :request do
let(:token) { FactoryGirl.create(:token) }
context 'with a valid key' do
let(:key) { token.key }
context 'with a reference' do
let!(:reference) { FactoryGirl.create(:reference) }
it 'shows contact information' do
get '/', {token: key}
expect(response.body).to include(reference.telephone)
end
end
end
context 'when incorrect key' do
let(:key) { token.key + 'foo' }
context 'with a reference' do
let!(:reference) { FactoryGirl.create(:reference) }
it 'does not show contact information' do
get '/'
expect(response.body).to_not include(reference.telephone)
end
end
end
context 'when no key' do
context 'with a reference' do
let!(:reference) { FactoryGirl.create(:reference) }
it 'does not show contact information' do
get '/'
expect(response.body).to_not include(reference.telephone)
end
end
end
end
|
class MovieRetriever
def initialize movie_db
@movie_db = movie_db
end
def posters
@movie_db.posters.compact
end
end
describe "Movie database" do
before :each do
@movie_db = double("MovieDB")
@retriever = MovieRetriever.new @movie_db
end
it "retrieves one poster if there is one" do
@movie_db.stub(:posters).and_return(['poster'])
expect(@retriever.posters).not_to eq(nil)
end
it "retrieves two posters if there are two" do
@movie_db.stub(:posters).and_return(['poster','poster'])
expect(@retriever.posters).to eq(['poster','poster'])
end
it "with N films, only returns the one with posters" do
@movie_db.stub(:posters).and_return(['poster' ,nil, nil, 'poster', nil, 'poster'])
expect(@retriever.posters).to eq(['poster', 'poster', 'poster'])
end
end
|
require 'spec_helper'
describe Rack::DevMark::Utils do
subject { Class.new{ include Rack::DevMark::Utils }.new }
describe "#camelize" do
it "camelizes" do
expect(subject.camelize("test_test_test")).to eq("TestTestTest")
end
end
end
|
class Item < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :prefecture
belongs_to_active_hash :condition
belongs_to_active_hash :delivery_fee
belongs_to_active_hash :days_until_shipping
belongs_to :category, optional: true
belongs_to :buyer, class_name: "User", foreign_key: "buyer_id", optional: true
belongs_to :seller, class_name: "User", foreign_key: "seller_id", optional: true
has_many :images, dependent: :destroy
accepts_nested_attributes_for :images, allow_destroy: true
validates :name, :explanation, :category_id, :condition_id, :delivery_fee_id, :prefecture_id, :days_until_shipping_id, :price, presence: true
validates :name, length: { maximum: 40 }
validates :price, numericality: { only_integer: true , greater_than_or_equal_to: 300, less_than_or_equal_to: 9999999 }
validates :images, presence: true
end
|
Rails.application.configure do
config.webpack.dev_server.host = 'client' if Rails.env.test?
config.webpack.dev_server.manifest_host = 'client'
config.webpack.dev_server.manifest_port = 3808
config.webpack.dev_server.enabled = !Rails.env.production? && ENV['CI'].blank?
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
$:.unshift(File.expand_path('../lib', __dir__))
require 'rblint'
def run_tests(constant, contents)
contents.each do |content|
parser = RbLint::Parser.new(content)
parser.singleton_class.prepend(RbLint::Rules.const_get(constant))
parser.parse
if parser.error?
raise "Could not parse: #{content}"
elsif parser.violations.empty?
raise "Expected an #{constant} violation for #{content}"
end
end
end
current = []
File.readlines(File.expand_path('../lib/rblint/rules.rb', __dir__)).each do |line|
if line.start_with?(' #') .. line.start_with?(' module')
case line
when /\#\s*\z/
current << []
when /\#\s{5}(.+)/
current[-1] << $1
when /\A\s{4}module (.+)\s*\z/
run_tests($1, current.tap(&:pop).map { |lines| lines.join("\n") })
current = []
end
end
end
puts 'All tests passed.'
|
require 'bacon'
require 'tilt'
describe Tilt::StringTemplate do
it "is registered for '.str' files" do
Tilt['test.str'].should.equal Tilt::StringTemplate
end
it "compiles and evaluates the template on #render" do
template = Tilt::StringTemplate.new { |t| "Hello World!" }
template.render.should.equal "Hello World!"
end
it "supports locals" do
template = Tilt::StringTemplate.new { 'Hey #{name}!' }
template.render(Object.new, :name => 'Joe').should.equal "Hey Joe!"
end
it "is evaluated in the object scope provided" do
template = Tilt::StringTemplate.new { 'Hey #{@name}!' }
scope = Object.new
scope.instance_variable_set :@name, 'Joe'
template.render(scope).should.equal "Hey Joe!"
end
it "evaluates template_source with yield support" do
template = Tilt::StringTemplate.new { 'Hey #{yield}!' }
template.render { 'Joe' }.should.equal "Hey Joe!"
end
it "renders multiline templates" do
template = Tilt::StringTemplate.new { "Hello\nWorld!\n" }
template.render.should.equal "Hello\nWorld!\n"
end
it "reports the file and line properly in backtraces without locals" do
data = File.read(__FILE__).split("\n__END__\n").last
fail unless data[0] == ?<
template = Tilt::StringTemplate.new('test.str', 11) { data }
begin
template.render
flunk 'should have raised an exception'
rescue => boom
boom.should.be.kind_of NameError
line = boom.backtrace.first
file, line, meth = line.split(":")
file.should.equal 'test.str'
line.should.equal '13'
end
end
it "reports the file and line properly in backtraces with locals" do
data = File.read(__FILE__).split("\n__END__\n").last
fail unless data[0] == ?<
template = Tilt::StringTemplate.new('test.str', 1) { data }
begin
template.render(nil, :name => 'Joe', :foo => 'bar')
flunk 'should have raised an exception'
rescue => boom
boom.should.be.kind_of RuntimeError
line = boom.backtrace.first
file, line, meth = line.split(":")
file.should.equal 'test.str'
line.should.equal '6'
end
end
end
__END__
<html>
<body>
<h1>Hey #{name}!</h1>
<p>#{fail}</p>
</body>
</html>
|
class MaterialCategoryPolicy < Struct.new(:user, :m_c)
def show?
m_c.course.users.include? user
end
def create?
m_c.course.admins.include? user
end
def update?
create?
end
def destroy?
create?
end
def new?
create?
end
end
|
class CreateClocks < ActiveRecord::Migration
def change
create_table :clocks do |t|
t.string :department
t.integer :name
t.integer :number
t.datetime :time
t.integer :machine_number
t.integer :code
t.string :way
t.integer :card_number
t.timestamps null: false
end
end
end
|
require_relative 'bike'
class DockingStation
attr_reader :bike
# def initialize #(@bike)
# end #@bike
def release_bike
raise "No bikes available" unless @bike
@bike
end
def dock_bike(bike)
#need to return bike which is being docked
#use instance var to store the bike - in the 'state' of this instance
@bike = bike
end
end
|
class Api::V1::MerchantsController < Api::V1::BaseController
def object_type
Merchant
end
def items
respond_with Item.where(merchant_id: params[:id]).order(:id)
end
def invoices
respond_with Invoice.where(merchant_id: params[:id]).order(:id)
end
def most_revenue
respond_with Merchant.most_revenue(params[:quantity].to_i)
end
def most_items
respond_with Merchant.most_items_sold(params[:quantity].to_i)
end
def revenue
respond_with Merchant.revenue_by_date(params[:date])
end
def single_merchant_revenue
respond_with Merchant.single_merchant_revenue(params[:id], params[:date])
end
def favorite_customer
respond_with Merchant.favorite_customer(params[:id])
end
def customers_with_pending_invoices
respond_with Merchant.customers_with_pending_invoices(params[:id])
end
private
def finder_params
params.permit(:id,
:name,
:created_at,
:updated_at)
end
end
|
class AddShopTierToUsers < ActiveRecord::Migration
def change
add_column :users, :shopTier, :integer, default:1
end
end
|
require 'spec_helper'
describe EnumerableObserver do
let(:array) { Array.new }
let(:caller) { Object.new }
describe 'items added' do
it 'should observe items added' do
items_to_add = [1, 2, 3]
expect(caller).to receive(:items_added).with(items_to_add)
EnumerableObserver.observe(array).added do |items|
caller.items_added(items)
end
array.concat(items_to_add)
end
end
describe 'items removed' do
it 'should observe items removed' do
items_to_remove = [1, 2, 3]
array.concat(items_to_remove)
expect(caller).to receive(:items_removed).with(items_to_remove)
EnumerableObserver.observe(array).removed do |items|
caller.items_removed(items)
end
array.delete_if { |i| items_to_remove.include? i }
end
end
describe 'unobserve' do
it 'should observe items removed' do
items_to_remove = [1, 2, 3]
array.concat(items_to_remove)
expect(caller).to_not receive(:items_removed)
EnumerableObserver.observe(array).removed do |items|
caller.items_removed(items)
end
array.observers.first.unobserve
array.delete_if { |i| items_to_remove.include? i }
end
end
end
|
class Geoipupdate < Formula
desc "Automatic updates of GeoIP2 and GeoIP Legacy databases"
homepage "https://github.com/maxmind/geoipupdate"
url "https://github.com/maxmind/geoipupdate/releases/download/v2.4.0/geoipupdate-2.4.0.tar.gz"
sha256 "8b4e88ce8d84e9c75bc681704d19ec5c63c54f01e945f7669f97fb0df7e13952"
revision 1
bottle do
sha256 "323ae245cabc43f6dfc5dd95625eb4aa8fd87cf33dfc3c0ad75f043f48ffff88" => :high_sierra
sha256 "ecc561b023e6ae9c57c4dcbe248407bfbf8b6f73e28da9e9a0395759b1fdb931" => :sierra
sha256 "5a56005484abf3771b79707fc79a669803e683f1573c12a854c23f4b92d78ee0" => :el_capitan
sha256 "e984990bc05d7f13585e6b19f309dbd56c181f15f09faa08333ba8020fb1876a" => :yosemite
end
head do
url "https://github.com/maxmind/geoipupdate.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
def install
# Configure for free GeoLite2 and GeoLite Legacy Databases
# See https://dev.maxmind.com/geoip/geoipupdate/
inreplace "conf/GeoIP.conf.default" do |s|
s.gsub! /^UserId 0$/, "UserId 999999"
s.gsub! /^# (ProductIds 506 517 533 GeoLite.*$)/, "\\1"
end
system "./bootstrap" if build.head?
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--datadir=#{var}",
"--prefix=#{prefix}",
"--sysconfdir=#{etc}"
system "make", "install"
end
def post_install
(var/"GeoIP").mkpath
system bin/"geoipupdate", "-v"
end
test do
system "#{bin}/geoipupdate", "-V"
end
end
|
Dynamic.class_eval do
# How a field should be RENDERED ON A SEARCH FORM of a given team
def self.field_search_json_schema_type_language(team = nil)
languages = team.get_languages || []
keys = languages.flatten.uniq
include_other = true
if keys.empty?
include_other = false
joins = "INNER JOIN annotations a ON a.id = dynamic_annotation_fields.annotation_id INNER JOIN project_medias pm ON a.annotated_type = 'ProjectMedia' AND pm.id = a.annotated_id"
values = DynamicAnnotation::Field.group('dynamic_annotation_fields.value').where(annotation_type: 'language').joins(joins).where('pm.team_id' => team.id).count.keys
values.each do |yaml_code|
code = YAML.load(yaml_code)
keys << code
end
end
keys = keys.sort
labels = []
keys.each{ |code| labels << CheckCldr.language_code_to_name(code) }
if include_other
keys << "not:#{keys.join(',')}"
labels << I18n.t(:other_language)
end
keys << "und"
labels << I18n.t(:unidentified_language)
{ type: 'array', title: I18n.t(:annotation_type_language_label), items: { type: 'string', enum: keys, enumNames: labels } }
end
def self.field_search_json_schema_type_flag(_team = nil)
keys = []
labels = []
DynamicAnnotation::AnnotationType.where(annotation_type: 'flag').last&.json_schema&.dig('properties', 'flags', 'required').to_a.each do |flag|
keys << flag
labels << I18n.t("flag_#{flag}")
end
values = (0..5).to_a.map(&:to_s)
[
{ id: 'flag_name', type: 'array', title: I18n.t(:annotation_type_flag_name_label), items: { type: 'string', enum: keys, enumNames: labels } },
{ id: 'flag_value', type: 'array', title: I18n.t(:annotation_type_flag_value_label), items: { type: 'string', enum: values, enumNames: values.collect{ |v| I18n.t("flag_likelihood_#{v}") } } }
]
end
end
ProjectMedia.class_eval do
def self.field_search_query_type_range(field, range, tzinfo, _options = nil)
timezone = ActiveSupport::TimeZone[tzinfo] if tzinfo
timezone = timezone ? timezone.formatted_offset : '+00:00'
output = {
range: {
"#{field}": {
lte: range[1].strftime("%Y-%m-%d %H:%M"),
format: "yyyy-MM-dd' 'HH:mm",
time_zone: timezone
}
}
}
output[:range][:"#{field}"][:gte] = range[0].strftime("%Y-%m-%d %H:%M") if range[0].strftime("%Y").to_i > 0
output
end
def self.field_search_query_type_range_long(field, range)
{
range: {
"#{field}": {
gte: range[0].to_i,
lte: range[1].to_i
}
}
}
end
def self.field_search_query_type_range_created_at(range, timezone, _options = nil)
self.field_search_query_type_range(:created_at, range, timezone)
end
def self.field_search_query_type_range_updated_at(range, timezone, _options = nil)
self.field_search_query_type_range(:updated_at, range, timezone)
end
def self.field_search_query_type_range_report_published_at(range, _timezone, _options = nil)
self.field_search_query_type_range_long(:report_published_at, range)
end
def self.field_search_query_type_range_media_published_at(range, _timezone, _options = nil)
self.field_search_query_type_range_long(:media_published_at, range)
end
def self.field_search_query_type_range_last_seen(range, _timezone, _options = nil)
self.field_search_query_type_range_long(:last_seen, range)
end
end
|
class ChangeMsgColumnName < ActiveRecord::Migration
def change
rename_column :user_messages, :recipient_id, :user_id
end
end
|
class DocsController < ApplicationController
before_action :_check_admin_rights,
only: [:new, :edit, :create, :update, :destroy]
before_action :require_user, only: [:download]
before_action :_set_doc, only: [:show, :edit, :update, :destroy]
helper_method :download, :layout
layout :layout
#TODO: selectable docs to be displayed in client section
# GET /docs
def index
@docs = Doc.all
end
# GET /docs/1
def show
end
# GET /docs/new
def new
@doc = Doc.new
end
# GET /docs/1/edit
def edit
end
# POST /docs
def create
@doc = Doc.new(_doc_params)
if @doc.save
redirect_to @doc, notice: 'Document was successfully created.'
else
render action: 'new'
end
end
# PATCH/PUT /docs/1
def update
if @doc.update(_doc_params)
redirect_to @doc, notice: 'Document was successfully updated.'
else
render action: 'edit'
end
end
# DELETE /docs/1
def destroy
@doc.destroy
redirect_to docs_url, notice: 'Document was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def _set_doc
@doc = Doc.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def _doc_params
params.require(:doc).permit(:document_file,
:filename,
:description,
:binary_content,
:content_type)
end
def download(filename, filetype)
send_file filename, type: filetype
end
end
|
class AddIdentifiableIdToStudentUsers < ActiveRecord::Migration
def change
add_column :student_users, :identifiable_id, :integer
end
end
|
module ProductCustomizations
# given params[:customizations], return a non-persisted array of ProductCustomization objects
def product_customizations
customizations = []
# do we have any customizations?
params[:product_customizations].to_unsafe_h.each do |customization_type_id, customization_pair_value| # customization_type_id =>
# {customized_product_option_id => <user input>, etc.}
next if customization_pair_value.empty? || customization_pair_value.values.all? {|value| value.empty?}
# create a product_customization based on customization_type_id
product_customization = Spree::ProductCustomization.new(product_customization_type_id: customization_type_id)
customization_pair_value.each_pair do |customized_option_id, user_input|
# create a customized_product_option based on customized_option_id
customized_product_option = Spree::CustomizedProductOption.new
# attach to its 'type'
customized_product_option.customizable_product_option_id = customized_option_id
if user_input.is_a? String
customized_product_option.value = user_input
else
customized_product_option.value = "" # TODO revisit. What should be here
customized_product_option.customization_image = user_input["customization_image"]
end
# attach to its customization
product_customization.customized_product_options << customized_product_option
end
customizations << product_customization
end if params[:product_customizations]
customizations
end
end
|
namespace :rpush_app do
desc 'create rpush app'
task create: :environment do
app = Rpush::Gcm::App.new
app.name = "android_app"
app.auth_key = Rails.application.credentials.FIREBASE_SERVER_KEY
app.connections = 1
app.save!
end
end
|
require './Lib/Airport'
describe Airport do
let(:plane) { double :plane, land: nil, take_off: nil }
let(:gate) { double :gate }
let(:available_gate) { double :gate, available?: true }
let(:unavailable_gate) { double :gate, available?: false}
let(:two_gate_airport) { Airport.new [available_gate, unavailable_gate] }
context 'Airport and gates' do
it 'should be initialized with a number of gates' do
airport = Airport.new [gate]
expect(airport.gates).to eq([gate])
end
it 'should be able to return all avilable gates' do
expect(two_gate_airport.available_gates).to eq([available_gate])
end
it 'should be able to return first available gate' do
expect(two_gate_airport.next_gate).to eq(available_gate)
end
it 'should be able to test if gates available' do
expect(two_gate_airport).not_to be_full
end
it 'should be full if no gates available' do
airport = Airport.new [double(:gate, available?: false)]
expect(airport).to be_full
end
it 'should be initialized with an empty holding pattern' do
airport = Airport.new
expect(airport.holding_pattern).to eq([])
end
end
context 'traffic control' do
let(:airport) { Airport.new }
it 'should be able to land a plane' do
expect(plane).to receive(:land)
airport.clear_to_land(plane)
end
it 'should be able to clear a plane to take off' do
expect(plane).to receive(:take_off)
airport.clear_to_take_off(plane)
end
it 'should be able to hold a plane' do
airport.hold_plane(plane)
expect(airport.holding_pattern).to eq([plane])
end
it 'should be able to remove a plane from holding pattern' do
airport.hold_plane(plane)
airport.unhold_plane(plane)
expect(airport.holding_pattern).to be_empty
end
it 'should return any plane removed from holding' do
airport.hold_plane(plane)
expect(airport.unhold_plane(plane)).to eq(plane)
end
end
context 'traffic control in good weather' do
let(:available_gate) { double :gate, available?: true, dock: :plane }
let(:airport) { Airport.new [available_gate]}
let(:unavailable_gate) { double :gate, available?: false, undock: plane}
let(:full_airport) { Airport.new [unavailable_gate]}
before do
Airport.any_instance.stub(:current_conditions) { "Clear"}
end
it 'should land an approaching plane if gate available' do
expect(plane).to receive(:land)
airport.approach(plane)
end
it 'should not land a plane if airport full' do
expect(plane).not_to receive(:land)
full_airport.approach(plane)
end
it 'should hold a plane if airport full' do
full_airport.approach(plane)
expect(full_airport.holding_pattern).to eq([plane])
end
it 'should place a landed plane in gate' do
expect(available_gate).to receive(:dock)
airport.approach(plane)
end
it 'should be able to undock a plane from gate' do
expect(unavailable_gate).to receive(:undock)
full_airport.depart(unavailable_gate)
end
it 'should launch a plane from gate' do
expect(plane).to receive(:take_off)
full_airport.depart(unavailable_gate)
end
end
context 'traffic control in bad weather' do
let(:unavailable_gate) { double :gate, available?: false, undock: plane}
let(:full_airport) { Airport.new [unavailable_gate]}
before do
Airport.any_instance.stub(:current_conditions) { "Stormy"}
end
it 'should not be able to undock a plane from gate' do
expect(unavailable_gate).not_to receive(:undock)
full_airport.depart(unavailable_gate)
end
it 'should not launch a plane from gate' do
expect(plane).not_to receive(:take_off)
full_airport.depart(unavailable_gate)
end
end
end |
require 'spec_helper'
describe NoPerc do
before(:each) do
@attr = { :composer_name => "Example Composer", :work_name => "Example Work name" }
end
it "should require a composer name" do
no_name_composer_name = NoPerc.new(@attr.merge(:composer_name => ""))
no_name_composer_name.should_not be_valid
end
it "should require a work name" do
no_name_work_name = NoPerc.new(@attr.merge(:work_name => ""))
no_name_work_name.should_not be_valid
end
end |
class Move < ActiveRecord::Base
attr_accessible :game_id, :square, :player_number, :current_user
belongs_to :game
validates :game_id, :square, :player_number, presence: true
validate :right_player
validate :square_free
validate :game_active
validate :player_allowed
def right_player
unless self.right_player?
errors.add(:number, "Sorry, it is not your turn.")
end
end
def right_player?
return true if self.game.moves.empty? && self.player_number == 1
return true if self.game.moves.count.even? && self.player_number == 1
return true if self.game.moves.count.odd? && self.player_number == 2
return false
end
def square_free
unless self.game.free_squares.include?(self.square)
errors.add(:square, "Sorry, that square has already been taken.")
end
end
def game_active
unless self.game.result == 'active' || self.game.result == 'expanding'
errors.add(:result, "Sorry, that game is no longer active.")
end
end
def player_allowed
unless self.game.next_player == current_user
errors.add(:allowed, "Sorry, it is not your turn.")
end
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :reviews, dependent: :destroy
validates :first_name, :last_name, presence: true
end
|
#
# Be sure to run `pod lib lint CardIOSDKBridge.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'CardIOSDKBridge'
s.version = '0.2.0'
s.license = { type: 'MIT', file: 'LICENSE' }
s.homepage = 'https://www.card.io'
s.summary = 'Credit card scanning for mobile apps'
s.social_media_url = 'https://twitter.com/cardio'
s.author = { 'Jesse Xu' => 'jessexu.mail@qq.com' }
s.source = { :git => 'https://github.com/jessecoding/CardIOSDKBridge.git', :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.static_framework = true
s.source_files = 'CardIOSDKBridge/Classes/**/*'
s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.dependency 'CardIO', '5.4.1'
end
|
class Patient::RatingsController < ApplicationController
layout 'patient_layout'
skip_before_action :verify_authenticity_token
before_filter :require_patient_signin
def create
puts "Rating params"
puts params
@consult = Consult.find(params[:consult_id])
@rating = Rating.create(rating_params)
@consult.rating = @rating
respond_to do |format|
format.json { head :ok }
end
end
private
def rating_params
params.require(:rating).permit(:score, :reason, :comments)
end
end
|
require 'spec_helper'
describe GnipInstanceImportsController do
let(:user) { users(:owner) }
let(:gnip_csv_result_mock) { GnipCsvResult.new("a,b,c\n1,2,3") }
let(:gnip_instance) { gnip_instances(:default) }
let(:workspace) { workspaces(:public) }
let(:gnip_instance_import_params) { {
:gnip_instance_id => gnip_instance.id,
:import => {
:to_table => 'foobar',
:workspace_id => workspace.id
}
} }
describe "#create" do
before do
log_in user
end
context "table name doesn't exist already" do
before do
mock(QC.default_queue).enqueue("GnipImporter.import_to_table", 'foobar',
gnip_instance.id, workspace.id, user.id, anything)
any_instance_of(CsvFile) do |file|
stub(file).table_already_exists(anything) { false }
end
end
it "uses authentication" do
mock(subject).authorize! :can_edit_sub_objects, workspace
post :create, gnip_instance_import_params
response.code.should == '200'
end
it "leaves the job to handle the CSVFile" do
expect {
post :create, gnip_instance_import_params
}.to change(CsvFile, :count).by(0)
end
it "creates an event before it is run" do
expect {
post :create, gnip_instance_import_params
}.to change(Events::GnipStreamImportCreated, :count).by(1)
created_event = Events::GnipStreamImportCreated.last
created_event.destination_table.should == 'foobar'
created_event.dataset.should_not be_present
end
end
context "table name already exists" do
before do
any_instance_of(CsvFile) do |file|
stub(file).table_already_exists(anything) { true }
end
end
it "checks for the table name being taken before downloading data" do
dont_allow(ChorusGnip).from_stream
post :create, gnip_instance_import_params
response.code.should == "422"
response.body.should include "TABLE_EXISTS"
end
end
context "workspace doesn't have a sandbox" do
let(:workspace) { workspaces(:private) }
it "should check and return an error" do
workspace.sandbox.should be_nil
dont_allow(ChorusGnip).from_stream
post :create, gnip_instance_import_params
response.code.should == "422"
response.body.should include "must have a sandbox"
end
end
end
end
|
require 'test_helper'
class MessagesControllerTest < ActionDispatch::IntegrationTest
setup do
@message = messages(:one)
end
test "should get list posted and public" do
get messages_url, as: :json
assert_response :success
body = JSON.parse(@response.body)
assert_equal 1, body.length
end
test "should get list with user: draft from" do
get messages_url({user: 'B_User'}), as: :json
assert_response :success
body = JSON.parse(@response.body)
assert_equal 4, body.length
end
test "should get list with user: posted private" do
get messages_url({user: 'A_User'}), as: :json
assert_response :success
body = JSON.parse(@response.body)
assert_equal 3, body.length
end
test "should create message" do
assert_difference('Message.count') do
post messages_url, params: { message: { body: @message.body, from: @message.from, private: @message.private, to: @message.to } }, as: :json
end
assert_response 201
end
test "should publish message" do
publish_message = messages(:three)
#check not posted
assert_nil publish_message.posted
#post it and check answer
put message_url(publish_message.id)
assert_response 200
#reload and validate it has been posted
publish_message.reload
assert_not_nil publish_message.posted
end
test "should not change message already published" do
published_message = messages(:six)
#check posted and save it
assert_not_nil published_message.posted
init = published_message.posted.dup
#repost it and check answer
put message_url(published_message.id)
assert_response 200
#reload and validate it hasn't change
published_message.reload
assert_equal init, published_message.posted
end
# test "should not publish unknown message" do
# id = 1111
#post fake id and check answer
# put message_url(id)
# rescue_from ActiveRecord::RecordNotFound, :with => { assert_response 404 }
# end
end
|
# Ignoring Case
# Using the following code, compare the value of name with the string 'RoGeR' while ignoring
# the case of both strings. Print true if the values are the same; print false if they aren't.
# Then, perform the same case-insensitive comparison, except compare the value of name with the
# string 'DAVE' instead of 'RoGeR'.
# name = 'Roger'
# Expected output:
# true
# false
name = "Mohammed"
puts name.casecmp("MoHammed").zero?
puts name.casecmp("DAVE") == 0
Dynamic String
Modify the following code so that the value of name is printed within "Hello, !".
name = 'Elizabeth'
puts "Hello, #{name}!"
puts "Hello, !"
Expected output:
Hello, Elizabeth!
Combining Names
Using the following code, combine the two names together to form a full name and assign that
value to a variable named full_name. Then, print the value of full_name.
first_name = 'John'
last_name = 'Doe'
full_name = "#{first_name} #{last_name}"
puts full_name
or
full_name = first_name + " " + last_name
puts full_name
ricky Formatting
Using the following code, capitalize the value of state then print the modified value. Note that state should have the modified value both before and after you print it.
state = 'tExAs'
state.capitalize
put state
Expected output:
Texas
|
module TeamStats
def team_info(team_id)
info = {}
info["team_id"] = @teams[team_id].team_id
info["franchiseId"] = @teams[team_id].franchiseId
info["teamName"] = @teams[team_id].teamName
info["abbreviation"] = @teams[team_id].abbreviation
info["link"] = @teams[team_id].link
info
end
def best_season(team_id)
worst_and_best_season(team_id)[1]
end
def worst_season(team_id)
worst_and_best_season(team_id)[0]
end
def average_win_percentage(team_id)
(calculate_percents[2][team_id]/100).round(2)
end
def most_goals_scored(team_id)
@game_teams[team_id].max_by{ |object| object.goals }.goals
end
def fewest_goals_scored(team_id)
@game_teams[team_id].min_by{ |object| object.goals }.goals
end
def favorite_opponent(team_id)
generate_percent(team_id)[0]
end
def rival(team_id)
generate_percent(team_id)[1]
end
def biggest_team_blowout(team_id)
generate_goals_difference(team_id)[0]
end
def worst_loss(team_id)
generate_goals_difference(team_id)[1].abs
end
def head_to_head(team_id)
opponents_and_win_percentage = {}
generate_percent(team_id)[3].each do |opponent, percent|
opponents_and_win_percentage[@teams[opponent].teamName] = (percent/100).round(2)
end
opponents_and_win_percentage
end
def seasonal_summary(team_id)
generate_inner_hash_for_summary(team_id)
end
# helper methods
def generate_post_and_regular(team_id)
game_ids = []
post_and_reg = {}
seasons = []
@games.each do |game_id, game|
seasons << game.season
end
seasons.each do |season|
post_and_reg[season] = {}
post_and_reg[season][:postseason] = []
post_and_reg[season][:regular_season] = []
end
@game_teams[team_id].each {|game| game_ids << game.game_id}
game_ids.each do |game_id|
if @games[game_id].type == "Postseason" && (post_and_reg[@games[game_id].season][:postseason] == nil)
post_and_reg[@games[game_id].season][:postseason] = [game_id]
elsif @games[game_id].type == "Postseason" && !(post_and_reg[@games[game_id].season][:postseason] == nil)
post_and_reg[@games[game_id].season][:postseason] << game_id
elsif @games[game_id].type == "Regular Season" && (post_and_reg[@games[game_id].season][:regular_season] == nil)
post_and_reg[@games[game_id].season][:regular_season] = [game_id]
elsif @games[game_id].type == "Regular Season" && !(post_and_reg[@games[game_id].season][:regular_season] == nil)
post_and_reg[@games[game_id].season][:regular_season] << game_id
end
end
post_and_reg
end
def generate_inner_hash_for_summary(team_id)
summary_hash = {}
post_and_reg = generate_post_and_regular(team_id)
post_and_reg.each do |season, hash|
summary_hash[season] = {} unless summary_hash.key? season
hash.each do |reg_or_post, game_ids|
summary_hash[season][reg_or_post] = {} unless summary_hash[season].key? reg_or_post
game_teams = []
@game_teams.each do |team, array|
array.each do |game|
if game_ids.include?(game.game_id) && game.team_id == team_id
game_teams << game
end
end
end
games = @games.select {|game_id, game| game_ids.include?(game_id) }
summary_hash[season][reg_or_post][:win_percentage] = win_percent(game_teams)
summary_hash[season][reg_or_post][:total_goals_scored] = goals(game_teams)
summary_hash[season][reg_or_post][:total_goals_against] = allowed_goals(team_id,games)
summary_hash[season][reg_or_post][:average_goals_scored] = generate_average(goals(game_teams), game_num(game_teams))
summary_hash[season][reg_or_post][:average_goals_against] = generate_average(allowed_goals(team_id, games),game_num(game_teams))
end
end
summary_hash
end
def win_percent(game_teams)
if game_num(game_teams) == 0
return 0.0
else
(wins(game_teams).to_f/game_num(game_teams)).round(2)
end
end
def wins(game_teams)
results = []
game_teams.each do |game|
results << game.result
end
results.count("WIN")
end
def game_num(game_teams)
game_num = 0
game_teams.each do |game|
game_num += 1
end
game_num
end
def goals(game_teams)
goals = 0
game_teams.each do |game|
goals += game.goals
end
goals
end
def allowed_goals(team_id, games)
allowed = 0
games.each do |game_id, game|
if game.home_team_id == team_id
allowed += game.away_goals
elsif game.away_team_id == team_id
allowed += game.home_goals
end
end
allowed
end
def generate_average(num,divisor)
if divisor == 0
return 0.0
else
(num/divisor.to_f).round(2)
end
end
def generate_goals_difference(team_id)
game_teams = @game_teams[team_id]
games = []
game_teams.each { |game| games << @games[game.game_id] }
goals = {}
games.each do |game|
goals[game.game_id] = {
:team_goals => 0,
:opponent_goals => 0 }
end
games.each do |game|
if team_id == game.home_team_id
goals[game.game_id][:team_goals] = game.home_goals
goals[game.game_id][:opponent_goals] = game.away_goals
elsif team_id == game.away_team_id
goals[game.game_id][:team_goals] = game.away_goals
goals[game.game_id][:opponent_goals] = game.home_goals
end
end
differences = {}
goals.each do |game_id, goals_hash|
differences[game_id] = goals[game_id][:team_goals] - goals[game_id][:opponent_goals]
end
max = differences.max_by {|game_id, difference| difference}[1]
min = differences.min_by {|game_id, difference| difference}[1]
[max,min]
end
def generate_opponents_wins_and_games(team_id)
opponent_games = Hash.new(0)
opponent_wins = Hash.new(0)
team_wins = Hash.new(0)
@games.each do |game_id, game|
if team_id == game.home_team_id && game.away_goals > game.home_goals
opponent_games[game.away_team_id] += 1
opponent_wins[game.away_team_id] += 1
team_wins[game.away_team_id] += 0
elsif team_id == game.home_team_id && game.away_goals < game.home_goals
opponent_games[game.away_team_id] += 1
opponent_wins[game.away_team_id] += 0
team_wins[game.away_team_id] += 1
elsif team_id == game.home_team_id && game.away_goals == game.home_goals
opponent_games[game.away_team_id] += 1
opponent_wins[game.away_team_id] += 0
team_wins[game.away_team_id] += 0
end
if team_id == game.away_team_id && game.home_goals > game.away_goals
opponent_games[game.home_team_id] += 1
opponent_wins[game.home_team_id] += 1
team_wins[game.home_team_id] += 0
elsif team_id == game.away_team_id && game.home_goals < game.away_goals
opponent_games[game.home_team_id] += 1
opponent_wins[game.home_team_id] += 0
team_wins[game.home_team_id] += 1
elsif team_id == game.away_team_id && game.home_goals == game.away_goals
opponent_games[game.home_team_id] += 1
opponent_wins[game.home_team_id] += 0
team_wins[game.home_team_id] += 0
end
end
[opponent_wins, opponent_games,team_wins]
end
def generate_percent(team_id)
opponent_wins = generate_opponents_wins_and_games(team_id)[0]
opponent_games = generate_opponents_wins_and_games(team_id)[1]
team_wins = generate_opponents_wins_and_games(team_id)[2]
opponent_percent = {}
team_percent = {}
opponent_wins.each {|opponent, wins| opponent_percent[opponent] = ((wins.to_f / opponent_games[opponent]) * 100).round(2) }
opponent_wins.each {|opponent, wins| opponent_percent[opponent] = ((wins.to_f / opponent_games[opponent]) * 100).round(2) }
opponent_games.each {|opponent, games| team_percent[opponent] = ((team_wins[opponent].to_f / games) * 100).round(2) }
min = opponent_percent.min_by{ |opp, percent| percent }[0]
max = opponent_percent.max_by{ |opp, percent| percent }[0]
min_team = @teams[min].teamName
max_team = @teams[max].teamName
[min_team, max_team, opponent_percent,team_percent]
end
def worst_and_best_season(team_id)
seasons = Hash.new(0)
game_ids = []
@game_teams[team_id].each {|game| game_ids << game.game_id}
@game_count_by_season = Hash.new(0)
game_ids.each do |game_id|
if @games[game_id].home_team_id == team_id
@game_count_by_season[@games[game_id].season] += 1
if @games[game_id].home_goals > @games[game_id].away_goals
seasons[@games[game_id].season] += 1
end
elsif @games[game_id].away_team_id == team_id
@game_count_by_season[@games[game_id].season] += 1
if @games[game_id].away_goals > @games[game_id].home_goals
seasons[@games[game_id].season] += 1
end
end
end
seasons = seasons.each do |season, wins|
seasons[season] = ((wins.to_f / @game_count_by_season[season]) * 100).round(2)
end
max = seasons.max_by {|id, count| count}[0]
min = seasons.min_by {|id, count| count}[0]
@min_max = [min, max, seasons]
end
end
|
class Level < ApplicationRecord
has_many :courses
validates :name, :presence => true
end
|
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# title :string(255)
# content :string(255)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Post < ActiveRecord::Base
# solo content e title sono accessibili, per evitare eventuali associaz user-post manuali o sbagliate
attr_accessible :content, :title
# ogni post è associato a uno specifico utente
belongs_to :user
# ordine decrescente della data di creaz per il get dei posts
default_scope order: 'posts.created_at DESC'
# user_id sempre presente
validates :user_id, presence: true
# title sempre presente e minimo 5 caratteri
validates :title, presence: true, length: {minimum: 5}
# content sempre presente e massimo 500 caratteri
validates :content, presence: true, length: {maximum: 500}
# prendo i post dell'utente più quelli scritti dagli utenti che segue
def self.from_users_followed_by(user)
followed_user_ids = 'SELECT followed_id FROM relationships WHERE follower_id = :user_id'
where("user_id IN (#{followed_user_ids}) OR user_id = :user_id", user_id: user.id)
end
end
|
class CreateResearchSequence < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
CREATE SEQUENCE research_seq;
SQL
end
def down
execute <<-SQL
DROP SEQUENCE research_seq;
SQL
end
end |
namespace :dev do
namespace :composer do
desc "Runs composer install on the VM."
task :install do
run "vagrant ssh -- -t 'cd #{REMOTE_APP_FOLDER}; composer install'"
end
desc "Runs composer update on the VM."
task :update do
run "vagrant ssh -- -t 'cd #{REMOTE_APP_FOLDER}; composer update'"
end
end
end
|
class Like < ActiveRecord::Base
belongs_to :video
belongs_to :liked_by, class_name: "User"
end
|
class VendorsController < ApplicationController
before_filter :authenticate_vendor!, :only=> [:usersearch,:addmember, :createmember, :memberlist, :addmywwmember,:edit, :update]
####################### Vendor Search #######################################
def search
if !params[:searchtype].nil?
if params[:filterQuery].nil?
params[:filterQuery]=""
end
if params[:searchtype]=="all"
@data=Vendor.where("city like '%"+params[:filterQuery]+"%' or state like '%"+params[:filterQuery]+"%' or zipcode like '%"+params[:filterQuery]+"%'").page(params[:page] || 1).per(30)
@cols="all"
else
@data=Vendor.where("vendor_type ='"+params[:searchtype]+"' and (city like '%"+params[:filterQuery]+"%' or state like '%"+params[:filterQuery]+"%' or zipcode like '%"+params[:filterQuery]+"%')").page(params[:page] || 1).per(30)
@cols="other"
end
end
@meta=Meta.where("controller= 'Vendors' and page='Vendor Search'").last
if !@meta.blank?
@meta_title=@meta.metatitle
@meta_keywords=@meta.keywords
@meta_description=@meta.description
end
end
################################# Vendor Info Page ####################
def show
@vendor=Vendor.find(params[:id])
@meta=Meta.where("controller= 'Vendors' and page='Vendor Info'").last
if !@meta.blank?
@meta_title=@vendor.business_name
@meta_keywords=@meta.keywords
@meta_description=@meta.description+", "+"#{@vendor.business_name}"+","+"#{@vendor.vendor_type}".split('_').join(' ')
end
end
#end show
######################### Vendor Profile Page ############################
def profile
@vendor=Vendor.find(params[:id])
render :layout=>'vendorprofile'
end
########################## Vendor Signup Second Step ###################
def second_step
render :layout => 'signup'
end
######################### Vendor Signup Second Step ###################
def final
if current_vendor.update_attributes(params[:vendor])
current_vendor.save # TODO: needed?
redirect_to profile_vendors_path(current_vendor)
else
render :action => :second_step, :layout => 'signup'
end
end
###################################################################
def captchatest
elements=Hash.new
elements={:recaptcha_response_field => params[:xxx], :recaptcha_challenge_field => params[:vvv]}
check=verify_recaptcha(request.remote_ip, elements)
if check[:status] == 'false'
render :text=> "false"
return
else
render :text=> "true"
return
end
end
############################### Vendor Edit ############################################
def edit
@vendor=Vendor.find(params[:id])
end
############################### Vendor Update #########################################
def update
@vendor=Vendor.find(params[:id])
respond_to do |format|
if @vendor.update_attributes(params[:vendor])
#format.html { redirect_to(vendorInfo_path(@vendor.id)+"/#{session[:vendor].vendor_type}") }
format.html { redirect_to profile_vendors_path(current_vendor) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @vendor.errors, :status => :unprocessable_entity }
end
end
end
############################### Business Claim #########################################
def businessclaim
params[:businessclaim]
@cfname= params[:businessclaim][:claimfname]
@clname= params[:businessclaim][:claimlname]
@cemail= params[:businessclaim][:claimemail]
@contact= params[:businessclaim][:claimcontact]
@vendor_id= params[:businessclaim][:vendor_id]
@btype= params[:businessclaim][:business_type]
@stat= params[:businessclaim][:status]
check=verify_recaptcha(request.remote_ip, params)
if check[:status] == 'false'
@captchastatus="false"
render 'search'
#redirect_to(vendor_path)
else
@claim=Businessclaim.new(params[:businessclaim])
@business=Vendor.find(params[:businessclaim][:vendor_id])
if @claim.save
@business.update_attributes(:status=>"Pending approval") # devise not updating it if email is blank........
@admin =User.where("admin=1")
@admin.each do |admin|
@admin=admin
BusinessclaimMailer.businessclaim(@admin, @claim, @business).deliver
end
redirect_to(vendor_path, :notice => 'Successfully claimed.')
else
render :action => "new"
end
end
end
####################### Auto Ajax Search in Vendor Signup and Edit ##########################
def auto_search
@city=ActiveRecord::Base.connection.execute("select c.id, c.name,co.name from City c, Country co where c.name like '%"+params[:search]+"%' and c.countrycode=co.code")
render :json =>@city
return
end
def auto_search1
@colleges=ActiveRecord::Base.connection.execute("select c.id, c.colleges from colleges c where c.colleges like '%"+params[:search]+"%'")
render :json =>@colleges
return
end
def auto_search2
@degrees=ActiveRecord::Base.connection.execute("select c.id, c.degrees from degrees c where c.degrees like '%"+params[:search]+"%'")
render :json =>@degrees
return
end
#################################### Vendor User Search #########################
def usersearch
if !params[:filterQuery].nil?
@data=User.where("first_name like '%"+params[:filterQuery]+"%' or last_name like '%"+params[:filterQuery]+"%' or email like '%"+params[:filterQuery]+"%'").page(params[:page] || 1).per(15)
end
end
######################### Add Vendor member Weight ##########################
def userweight
@weight=Weight.create(:weight=>params[:weight],:user_id=>params[:user_id])
@user=User.find(params[:user_id])
respond_to do |format|
if @weight.save
format.html { render :json => "weight saved." }
format.js { render :json => "weight saved." }
end
end
end
###############################Add Myweight World Users #######################
def addmywwmember
@vendor=Vendor.find(current_vendor.id)
@membership=Vendormember.find_by_user_id_and_vendor_id(params[:user_id], current_vendor.id)
if @membership.nil?
@member=Vendormember.create(:user_id=>params[:user_id], :vendor_id=>current_vendor.id, :userApproved=>false, :status=>"waiting")
@user=User.find(params[:user_id])
respond_to do |format|
if @member.save
@notification=@vendor.notifications.create(:notificationTo=>"User",:notificationToId=>params[:user_id], :message=> params[:message])
BusinessclaimMailer.delay.mywwmembership(@user, @vendor)
format.html { render :json => "Successfully sent a notification to user. Please wait for the approval." }
format.js { render :json => "Successfully sent a notification to user. Please wait for the approval." }
else
format.html { render :json => @member.errors.full_messages.first }
format.js { render :json => @member.errors.full_messages.first }
end
end
else
if @membership.status=="waiting"
respond_to do |format|
format.html { render :json => "Already Waiting approval." }
format.js { render :json => "Already Waiting approval." }
end
end
end
end
################################## Add new User by Vendor ###############################
def addmember
@member=User.new
end
def createmember
@member=User.create(params[:user])
@vendor=Vendor.find(current_vendor.id)
if @member.save
@weight=Weight.create(:weight=>params[:user][:weight],:user_id=>@member.id)
@membership=Vendormember.create(:user_id=>@member.id, :vendor_id=>current_vendor.id, :userApproved=>true,:status=>"approved")
BusinessclaimMailer.newaddedmywwuser(@member, @vendor,params[:user][:password]).deliver
redirect_to(memberlist_vendors_path, :notice => 'User created.')
else
render 'addmember'
end
end
################################## Remove user for membership ################################
def removemember
@member=Vendormember.find_by_user_id_and_vendor_id(params[:user_id],params[:vendor_id])
@member.destroy
respond_to do |format|
format.html { render :json => "Successfully removed." }
format.js { render :json => "Successfully removed." }
end
end
############################### Member List ###########################################
def memberlist
#@members=Vendormember.find(:all,:conditions=>["userApproved=? and vendor_id=?",true,session[:vendor].id])
@vendor=Vendor.find(current_vendor.id)
@members=@vendor.users.where("userApproved=1").order('first_name ASC').page(params[:page] || 1).per(30)
end
################################# Member details ######################################
def memberdetails
@user=Vendormember.find_by_user_id_and_vendor_id_and_userApproved(params[:token], current_vendor.id,true)
if @user!=nil
@user=User.find(params[:id])
@vendor=current_vendor
@weights=@user.weights.limit(50).order('created_at ASC')
@bodyfats=@user.bodyfats.limit(50).order('created_at ASC')
@measuremets=@user.measurements.limit(50).order('created_at DESC')
@ratings=Rating.find_by_ratingFor_and_ratingForid_and_ratingable_type_and_ratingable_id("user",@user.id,"Vendor",current_vendor.id)
if @ratings.nil?
@rating=1
else
@rating=@ratings.rating
end
else
render :file => "#{Rails.root}/public/404.html", :status => :not_found
end
end
############################### Create Member Bodyfat by Vendor ##################
def userbodyfat
@user=User.find(params[:id])
@fat=@user.bodyfats.new
end
def userbodyfatcreate
@user=User.find(params[:id])
@fat=@user.bodyfats.create(params[:bodyfat])
if @fat.save
redirect_to(memberdetails_vendors_path(@user)+"?token=#{@user.id}", :notice => 'Bodyfat successfully saved.')
else
render "userbodyfat"
end
end
############################### Create Member Measurements by Vendor ##################
def usermeasurementnew
@user=User.find(params[:id])
@meas=@user.measurements.new
end
def usermeasurementcreate
@user=User.find(params[:id])
@meas=@user.measurements.create(params[:measurement])
if @meas.save
redirect_to(memberdetails_vendors_path(@user)+"?token=#{@user.id}", :notice => 'Measurement successfully saved.')
else
render "usermeasurement"
end
end
############################### Create Vendor Notifications to Members ##################
def vendorNotificationsNew
@vendor=current_vendor
@notification = Notification.new
@members=current_vendor.users.where("userApproved=1").order('first_name ASC')
render :layout=>'vendorprofile'
end
def vendorNotificationsCreate
params[:notification][:notificationToId]=params[:notificationToId].collect{|a| a.split(",") }.join(",").to_s
if params[:notificationFrequency]=="first"
if params[:notificationFrequency1].to_s=="day"
params[:notification][:notificationFrequency]="#{(24/params[:times].to_f).round(2)}"+".hours"
elsif params[:notificationFrequency1].to_s=="week"
params[:notification][:notificationFrequency]="#{24*7/params[:times].to_f}"+".hours"
elsif params[:notificationFrequency1].to_s=="month"
params[:notification][:notificationFrequency]="#{24*30/params[:times].to_f}"+".hours"
else
params[:notification][:notificationFrequency]="#{(24*30*12/params[:times].to_f).round(2)}"+".hours"
end
params[:notification][:frequency_type]="first"
else
params[:notification][:notificationFrequency]=params[:notificationFrequency2].split(",").sort.collect{|a| a.to_s.strip+".days" }.join(",").to_s
params[:notification][:frequency_type]="second"
end
if params[:notification][:notification_type]=="food"
params[:notification][:mealslist]=params[:meals1].collect{|a| a.split(",") }.join(",").to_s
end
if params[:notification][:notification_type]=="food_type"
params[:notification][:food_category]=params[:food_category].collect{|a| a.split(",") }.join(",").to_s
end
if params[:notification][:notification_type]=="activity"
params[:notification][:exerciseslist]=params[:exercise1].collect{|a| a.split(",") }.join(",").to_s
params[:notification][:workoutduration]=params[:workoutduration]
end
if params[:notificationPeriodUnit]=="days"
params[:notification][:notificationDuration]=params[:notificationPeriod].to_i.days.from_now
elsif params[:notificationPeriodUnit]=="weeks"
params[:notification][:notificationDuration]=params[:notificationPeriod].to_i.weeks.from_now
elsif params[:notificationPeriodUnit]=="months"
params[:notification][:notificationDuration]=params[:notificationPeriod].to_i.months.from_now
else
params[:notification][:notificationDuration]=params[:notificationPeriod].to_i.years.from_now
end
@notification = Notification.create(params[:notification])
if @notification.save
#writing schedule and rake task file
Notification.updateCronTab
redirect_to( profile_vendors_path(current_vendor), :notice => 'Notification was successfully created.')
else
render :action => "vendorNotificationsNew"
end
end
############################## Notification to users ######################################
=begin
def notifications
@user=User.find(params[:notificatonToId])
@vendor=current_vendor
@notification=@vendor.notifications.create(:notificationTo=>"User",:notificationToId=>params[:notificatonToId], :message=> params[:message])
respond_to do |format|
if @notification.save
format.html { render :json => "Message sent." }
format.js { render :json => "Message sent." }
end
end
end
=end
############################# Star Rating to User (create and update) ##########################
def ratings
@vendor=Vendor.find(current_vendor.id)
@rating=Rating.find_by_ratingable_id_and_ratingable_type_and_ratingForid(current_vendor.id,"Vendor",params[:userid])
if @rating==nil
@rating=@vendor.ratings.create(:ratingForid=>params[:userid], :rating=>params[:rating], :ratingFor=>"user")
respond_to do |format|
if @rating.save
format.html { render :json => "Rating created." }
end
end
else
@rating.update_attributes(:rating=>params[:rating])
respond_to do |format|
if @rating.save
format.html { render :json => "Rating updated." }
end
end
end
end
########################### Member Workout and meal diary ##################################
def userdiary
@user=User.find(params[:id])
if params[:date_on] && params[:date_on].downcase!="today"
@start_date = Time.zone.parse(params[:date_on]).strftime("%Y-%m-%d")
else
@start_date = Time.zone.now.strftime("%Y-%m-%d")
end
@workouts=Workout.find_by_sql("SELECT wi.exercise_id,w.id,e.description,wi.calories,w.time_from,w.note,w.trained_on FROM exercises e ,workout_items wi, workouts w WHERE w.user_id="+@user.id.to_s+" and trained_on='"+@start_date+"' and wi.exercise_id=e.id and w.id=wi.workout_id")
@meals = Meal.find_by_sql("SELECT mi.food_id,m.id,f.name,m.meal_type,m.note,ifnull(mi.calories,0) as calories,ifnull(f.lipid_tot,0) as fat,ifnull(f.carbohydrt,0) as carbohydrt,ifnull(f.protein,0) as protein,m.ate_on from meals m,meal_items mi,foods f where f.id=mi.food_id and m.id = mi.meal_id and m.user_id=" + @user.id.to_s + " and m.ate_on='"+ @start_date.to_s+"'")
@meals.each do |f|
if(f.food_id!=8443)
f.fat= calculate_calories(f.food_id,f.calories,"fat")
f.carbohydrt=calculate_calories(f.food_id,f.calories,"carbohydrt")
f.protein=calculate_calories(f.food_id,f.calories,"protein")
end
end
end
private
############################## Calculating fat carb etc. in meals #########################################
def calculate_calories(fid, calories, type)
@food=Food.find(fid)
times=calories/@food.energ_kcal
if !@food.custom
case type
when 'fat'
calories = (@food.lipid_tot.to_f * times)
when 'carbohydrt'
calories = (@food.carbohydrt.to_f * times)
when 'protein'
calories = (@food.protein.to_f * times)
end
else
times=calories/@food.energ_kcal
case type
when 'calorie'
calories = @food.energ_kcal.to_f* times
when 'fat'
calories = @food.total_fat.to_f * times
when 'carbohydrt'
calories = @food.carbohydrt.to_f * times
when 'protein'
calories = @food.protein.to_f * times
when 'fiber_td'
calories = @food.fiber_td.to_f * times
end
end
return calories.round(2) unless calories.nil?
end
#######################################################################################
end
|
class User < ActiveRecord::Base
belongs_to :credit_company
has_many :credit_companies, foreign_key: "executive_id"
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_validation { self.role ||= :company_user }
validates :credit_company, :role, presence: :true
#before_save :temp_authorized, if: :new_record?
default_scope { order(:name) }
scope :find_all_by_approved, ->(status) { where approved: status }
scope :executives, -> { where role: [:analytic_executive, :executive, :admin] }
def to_s
name
end
def active_for_authentication?
super && (approved? || email == Rails.application.config.superadmin)
end
def inactive_message
if !approved?
:not_approved
else
super # Use whatever other message
end
end
def is_at_least? minimum_role
Rails.application.config.user_roles[role.to_sym][:privilege] >= Rails.application.config.user_roles[minimum_role.to_sym][:privilege]
end
def has_more_privileges_than? minor_role
Rails.application.config.user_roles[role.to_sym][:privilege] > Rails.application.config.user_roles[minor_role.to_sym][:privilege]
end
def is_at_most? maximum_role
Rails.application.config.user_roles[role.to_sym][:privilege] <= Rails.application.config.user_roles[maximum_role.to_sym][:privilege]
end
def is? specific_role
Rails.application.config.user_roles[role.to_sym][:privilege] == Rails.application.config.user_roles[specific_role.to_sym][:privilege]
end
def is_not? specific_role
Rails.application.config.user_roles[role.to_sym][:privilege] != Rails.application.config.user_roles[specific_role.to_sym][:privilege]
end
def temp_authorized
self.approved = true
self.role = :company_user
end
end
|
require 'rubygems'
require 'json'
require 'httparty'
require 'pp'
class Issues < Linkbot::Plugin
@@config = Linkbot::Config["plugins"]["activecollab"]
if @@config
include HTTParty
base_uri @@config["url"]
debug_output $stderr
Linkbot::Plugin.register('issues', self, {
:message => {:regex => Regexp.new('!issue (.*)'),
:handler => :on_message, :help => :help
}
})
end
def self.issue_search(needle)
res = get("/projects/1/tickets?format=json&token=#{@@config['token']}")
issues = JSON.load(res.body)
issues_found = []
issues.each do |issue|
haystack = issue["name"] + issue["body"]
if haystack.match /#{needle}/i
issues_found << issue
end
end
issues_found
end
def self.on_message(message, matches)
query = matches[0]
msg = []
issues = self.issue_search(query)
for issue in issues
msg << "#{issue['permalink']}: #{issue['name']}"
end
#self.api_send(msg)
msg
end
def self.help
"!issue <query> - search for open issues that match your query"
end
end
|
bp_require 'json/json'
bp_require 'machsend'
bp_require 'machsend/utils'
bp_require 'machsend/logging'
bp_require 'machsend/observable'
bp_require 'machsend/base'
bp_require 'machsend/asset'
bp_require 'machsend/client'
bp_require 'machsend/rpc'
bp_require 'machsend/rpc/message'
bp_require 'machsend/rpc/client_to_client'
bp_require 'machsend/rpc/client_to_server'
require 'uri'
module Machsend
class BrowserPlus
include Logging
ALLOWED_DOMAINS = [
'untitled.heroku.com',
'localhost'
]
def initialize(args)
Machsend::Logging.trace = true
@uri = args['uri']
@base = Machsend::Base.new
@allowed = false
end
def startup(trans, args)
uri = URI.parse(@uri) rescue nil
if !uri || uri.scheme != "http" ||
!ALLOWED_DOMAINS.include?(uri.host)
trans.error('securityError', "Wrong domain")
return
end
@allowed = true
@callback = args['callback']
@base.startup(args['guid'])
@base.on_change {
trace('on_change')
invoke(:sync, remote_assets)
}
@base.observable.append(:conn_failed) {
trace('conn_failed')
invoke(:conn_failed)
}
# trans.complete(true)
# Don't call trans.complete
# otherwise the callback won't work
rescue Errno::ECONNREFUSED
trans.error('connectionError', 'refused')
end
def syncAssets(trans, args)
if !@allowed
trans.error('securityError', "Wrong domain")
return
end
@base.assets = args['assets'].map {|a|
Asset.fromPath(a)
}
throttle {
trans.complete(true)
}
end
def refresh(trans, args)
if !@allowed
trans.error('securityError', "Wrong domain")
return
end
@base.refresh {
trans.complete(remote_assets)
}
end
def download(trans, args)
if !@allowed
trans.error('securityError', "Wrong domain")
return
end
asset = @base.remote_asset_by_guid(args['guid'])
return unless asset
progress = proc {|size, total|
throttle(true) {
args['progress'].invoke({
:size => size,
:total => total
}.stringify_keys)
}
}
asset.download(args['path'], progress) {|tmp|
throttle {
trans.complete(true)
}
}
end
def defaultDir(trans, args)
if !@allowed
trans.error('securityError', "Wrong domain")
return
end
trans.complete(default_dir)
end
def shutdown(trans, args)
if !@allowed
trans.error('securityError', "Wrong domain")
return
end
@base.shutdown
trans.complete(true)
end
private
def default_dir
home = Pathname.new(
ENV['HOME'] ||
ENV['HOMEDRIVE'] + ENV['HOMEPATH'] ||
ENV['USERPROFILE']
)
return unless home
downloads = home.join('Downloads')
return downloads if downloads.directory?
desktop = home.join('Desktop')
return desktop if desktop.directory?
nil
end
def remote_assets
@base.remote_assets.map {|a|
a.to_hash.stringify_keys
}
end
def invoke(type, value = nil)
throttle {
@callback.invoke({
:type => type.to_s,
:value => value
}.stringify_keys)
}
end
def throttle(discard = false)
@sem ||= Mutex.new
@sem.synchronize {
if @last_called
diff = Time.now.to_f - @last_called
if diff < 0.5
return if discard
sleep(0.51 - diff)
end
end
@last_called = Time.now.to_f
yield
}
end
end
end
rubyCoreletDefinition = {
'class' => "Machsend::BrowserPlus",
'name' => "Untitled",
'major_version' => 0,
'minor_version' => 0,
'micro_version' => 1,
'documentation' => 'Efficiently transfer files on machsend.com (provided by Lead Thinking, LLC)',
'functions' =>
[
{
'name' => 'startup',
'documentation' => "startup",
'arguments' =>
[
{
'name' => 'guid',
'type' => 'string',
'required' => true,
'documentation' => 'guid'
},
{
'name' => 'callback',
'type' => 'callback',
'required' => true,
'documentation' => 'callback'
}
]
},
{
'name' => 'syncAssets',
'documentation' => "syncAssets",
'arguments' =>
[
{
'name' => 'assets',
'type' => 'list',
'required' => true,
'documentation' => 'asset'
}
]
},
{
'name' => 'refresh',
'documentation' => "refresh",
'arguments' => []
},
{
'name' => 'download',
'documentation' => "download",
'arguments' =>
[
{
'name' => 'guid',
'type' => 'string',
'required' => true,
'documentation' => 'guid'
},
{
'name' => 'path',
'type' => 'path',
'required' => true,
'documentation' => 'path'
},
{
'name' => 'progress',
'type' => 'callback',
'required' => true,
'documentation' => 'callback'
}
]
},
{
'name' => 'defaultDir',
'documentation' => "defaultDir",
'arguments' => []
},
{
'name' => 'shutdown',
'documentation' => "shutdown",
'arguments' => []
}
]
}
|
class Post < ApplicationRecord
belongs_to :user
validates :text, length: { maximum: 200 }
end
|
# encoding: utf-8
class DocumentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"#{Rails.root}/private/documents/#{model.id}"
end
end
|
module Api
module V1
class BookSuggestionController < ApiController
def create
render json: BookSuggestion.create!(book_suggestion_params), status: :created
end
def book_suggestion_params
params.require(:book_suggestion).permit(:author, :title, :link,
:publisher, :year, :user_id)
end
end
end
end
|
requirements = [
{ name: "add the paper to the page",
spec: "$frame.find('svg').length > 0",
position: 1,
success: "You just made an HTML canvas to draw on.",
step: 1,
kit: "whackamole"
},
{ name: "set the background color",
spec: '
colored_rects = 0
_.each($frame.find("svg rect"), (rect) ->
if $(rect).attr("fill").match(/#/i) &&
$(rect).attr("width") >= 399 && $(rect).attr("height") >= 399
colored_rects += 1
)
if colored_rects > 1
return true
else
return false
',
position: 1,
success: "Great, now you have a nice color in your background",
step: 2,
kit: "whackamole"
},
{ name: "add the first mole hole",
spec: '
colored_circles = 0
_.each($frame.find("svg circle"), (circle) ->
if $(circle).attr("fill").match(/#/i) &&
$(circle).attr("stroke-width") == "0" &&
$(circle).attr("r") == "30"
colored_circles += 1
)
colored_circles > 0
',
position: 1,
step: 3,
kit: "whackamole"
},
{ name: "add 16 mole holes",
spec: '
colored_circles = 0
_.each($frame.find("svg circle"), (circle) ->
if $(circle).attr("fill").match(/#/i) &&
$(circle).attr("stroke-width") == "0" &&
$(circle).attr("r") == "30"
colored_circles += 1
)
colored_circles > 15
',
position: 1,
step: 4,
kit: "whackamole"
},
{ name: "add the mole image",
spec: '$frame.find("svg image").length > 0',
position: 1,
step: 5,
kit: "whackamole"
},
{ name: "add the sound file to the page",
spec: '$("#sound").length > 0',
position: 1,
step: 6,
kit: 'whackamole'
},
{ name: "add a random function",
spec: 'editor.getSession().getValue().match(///
\r\nrandom*.+=*.+->
///)',
position: 1,
step: 7,
kit: 'whackamole'
},
{ name: "add the showMole function",
spec: 'editor.getSession().getValue().match(///
\r\nshowMole*.+=*.+->
///)',
position: 2,
step: 7,
kit: 'whackamole'
},
{ name: "animate the mole",
spec: 'editor.getSession().getValue().match(///
\r\n\s\smole\.animate
///)',
position: 3,
step: 7,
kit: 'whackamole'
},
{ name: "call the showMole function",
spec: 'editor.getSession().getValue().match(/\r\nshowMole\(\)/)',
position: 4,
step: 7,
kit: 'whackamole'
},
{ name: "Add a count",
spec: '
editor.getSession().getValue().match(///
\r\ncount*.+=*.+0
///)
',
position: 1,
step: 8,
kit: "whackamole"
},
{ name: "create the hide and show function",
spec: '
editor.getSession().getValue().match(///
\r\n\s{6}setTimeout\(*.+\(*.+->*.+
\r\n\s{8}mole.hide\(\)*.+
\r\n\s{8}count\+\+*.+
\r\n\s{8}if\scount\<*.+\d*.+
\r\n\s{10}showMole\(\)
///)
',
position: 2,
step: 8,
kit: 'whackamole'
},
{ name: "Add a button",
spec: '
buttonText = false
_.each($frame.find("svg rect"), (rect) ->
$rect = $(rect)
if $rect.attr("stroke-width") == "3" && $rect.attr("width") < 200 && $rect.attr("height") < 100
if $frame.find("svg text").length > 6
buttonText = true
)
buttonText
',
position: 1,
step: 9,
kit: 'whackamole'
},
{ name: "Delay starting the mole",
spec: '
match = editor.getSession().getValue().match(/\r\nshowMole\(\)/)
if match
false
else
true
',
position: 2,
step: 9,
kit: 'whackamole'
},
{ name: "attach the click to the button",
spec: '
editor.getSession().getValue().match(///
\r\nbutton\.click\(*.+->[^]+
\r\n\s{2}button\.hide\(\)[^]+
\r\n\s{2}showMole\(\)
///)
',
step: 10,
position: 1,
kit: "whackamole"
},
{ name: "attach the click to the text",
spec: '
editor.getSession().getValue().match(///
\r\ntext\.click\(*.+->[^]+
\r\n\s{2}text\.hide\(\)[^]+
\r\n\s{2}showMole\(\)
///)
',
step: 10,
position: 2,
kit: 'whackamole'
},
{ name: "tally the score",
step: 11,
position: 1,
kit: 'whackamole',
spec: '
match1 = editor.getSession().getValue().match(///
\r\nscore*.+=*.+\d
///)
match2 = editor.getSession().getValue().match(///
\r\n\s{2}score*.+\+
///)
if match1 && match2
true
else
false
'
},
{ name: "show the score",
step: 11,
position: 2,
kit: "whackamole",
spec: '
editor.getSession().getValue().match(///
\r\n\s{10}text\.attr\(*.+text*.+Score:\s*.+score*.+\)
///)
'
},
{ name: "add the paper to the page",
spec: "$frame.find('svg').length > 0",
position: 1,
success: "You just made an HTML canvas to draw on.",
step: 1,
kit: "quiz"
},
{ name: "assign a variable to the paper",
spec: 'editor.getSession().getValue().match(/\=/)',
position: 1,
step: 2,
kit: "quiz"
},
{ name: "set the background color",
spec: '
colored_rects = 0
_.each($frame.find("svg rect"), (rect) ->
if $(rect).attr("fill").match(/#/i) &&
$(rect).attr("width") >= 399 && $(rect).attr("height") >= 399
colored_rects += 1
)
if colored_rects > 1
return true
else
return false
',
position: 1,
success: "Great, now you have a nice color in your background",
step: 3,
kit: "quiz"
},
{
name: "add a question",
step: 4,
kit: "quiz",
position: 1,
spec: "
$frame.find('svg text').length > 6
"
},
{
name: "add at least 3 answers",
step: 5,
kit: "quiz",
position: 1,
spec: "
$frame.find('svg text').length > 9
"
},
{
step: 6,
position: 1,
kit: 'quiz',
name: 'Add an alert to the page',
spec: 'editor.getSession().getValue().match(/alert/)'
},
{
step: 7,
position: 1,
kit: 'quiz',
name: 'Add a click to one of the answers',
spec: '
editor.getSession().getValue().match(///
answer\d.click\(*.+->*.+
\r\n .+alert\(*.+\)
[^]*\)
///)
'
},
{
step: 8,
position: 1,
kit: 'quiz',
name: 'Add a new background to the click',
spec: '
editor.getSession().getValue().match(///
answer\d.click\(*.+->*.+
\r\n\s+alert\(*.+\)
\r\n\s+.+paper.rect\(*.+\)
[^]+attr*.+fill*.+\)
[^]*\)
///)
'
},
{
step: 9,
position: 1,
kit: 'quiz',
name: 'Add a new question on the click',
spec: '
editor.getSession().getValue().match(///
answer\d.click\(*.+->*.+
\r\n\s+alert\(*.+\)
\r\n\s+.+paper.rect\(*.+\)[^]+attr*.+fill*.+\)*.+
[^]+\r\n\s+.+paper.text\(*.+\)[^]*\)
///)
'
},
{
step: 9,
position: 2,
kit: 'quiz',
name: 'Add at least 1 new answer on the click',
spec: '
editor.getSession().getValue().match(///
answer\d.click\(*.+->*.+
\r\n\s+alert\(*.+\)
\r\n\s+.+paper.rect\(*.+\)[^]+attr*.+fill*.+\)*.+
[^]+\r\n\s+.+paper.text
[^]+\r\n\s+.+paper.text
[^]*\)
///)
'
},
{
step: 10,
position: 1,
kit: 'quiz',
name: 'Add a click to the correct answer',
spec: '
editor.getSession().getValue().match(///
answer\d.click\(*.+->*.+
[^]+paper.text\(*.+\)
[^]+.click\(*.+->*.+
\r\n\s+alert\(*.+\)*.+\)
[^]*\)
///)
'
},
{ name: "add the paper to the page",
spec: "$frame.find('svg').length > 0",
step: 1,
kit: "puppy",
position: 1,
success: "You just made an HTML canvas to draw on."
},
{
position: 1,
name: 'add an ellipse for the face',
spec: '$frame.find("svg ellipse").length > 0',
step: 3,
kit: "puppy",
success: "You just drew an ellipse for the face."
},
{
position: 1,
name: 'create a variable named paper',
spec: 'editor.getSession().getValue().match(///
paper*.+=*.+makeWorkspace\(\)
///)',
step: 2,
kit: 'puppy',
},
{
position: 2,
spec: '
face = false
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("rx") == "60"
face = true
)
return face
',
name: "make the width 60",
step: 3,
kit: "puppy",
success: "the third number that you added to ellipse set the width"
},
{
position: 3,
spec: '
face = false
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("ry") == "80"
face = true
)
return face
',
name: "make the height 80",
step: 3,
kit: "puppy",
success: "and the last number set the height."
},
{
position: 1,
step: 4,
kit: 'puppy',
name: "set the face color to saddlebrown",
spec: '_.find($frame.find("svg ellipse"),((e)-> $(e).attr("fill").match(/#/i)))',
success: "try changing the fill color with <a href='http://www.w3schools.com/html/html_colornames.asp' target='_blank'>this!</a>"
},
{
position: 1,
step: 5,
kit: "puppy",
name: "add 2 new ellipses for the ears",
spec: '$frame.find("svg ellipse").length > 2',
success: "an ellipse is like a circle, only more stretched."
},
{
position: 2,
step: 5,
kit: "puppy",
name: "make sure the x-coordinate (first number in the ellipse method) is different for each ear",
spec: '$frame.find("svg ellipse[cx=150]").length != 2',
success: "when both ears were on top of each other you couldn't tell them apart.'"
},
{
position: 3,
step: 5,
kit: "puppy",
name: "give both ears x-radius (the third number in the ellipse method) of approximately 40",
spec: '
ellipses = 0
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("rx") > 35 && $(ellipse).attr("rx") < 45
ellipses += 1
)
if ellipses < 2
return false
else
return true
',
success: "the x radius controls how wide the ellipse is."
},
{
position: 4,
step: 5,
kit: "puppy",
name: "give both ears y-radius (the fourth number in the ellipse method) of approximately 80",
spec: '
ellipses = 0
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("ry") > 75 && $(ellipse).attr("ry") < 85
ellipses += 1
)
if ellipses < 3
return false
else
return true
',
success: "the y radius controls how tall the ellipse is."
},
{
position: 1,
name: "color both ears saddlebrown",
step: 6,
kit: "puppy",
spec: '
brownEllipses = 0
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("fill").match(/#/i)
brownEllipses += 1
)
if brownEllipses < 3
return false
else
return true
',
success: "again, here are the <a href='http://www.w3schools.com/html/html_colornames.asp' target='_blank'>colors</a>."
},
{
position: 1,
step: 7,
kit: "puppy",
name: "rotate both ears",
spec: '
rotatedEllipses = 0
_.each($frame.find("svg ellipse"), (ellipse)->
if $(ellipse).attr("transform")
rotatedEllipses += 1
)
if rotatedEllipses < 2
return false
else
return true
',
success: "When you use \"R20\" you rotate the ear 20° clockwise. \"R-20\" will rotate it counterclockwise."
},
{
position: 1,
step: 8,
kit: "puppy",
name: "make the outer left eye",
spec: '
eye = false
_.each($frame.find("svg ellipse"), (ellipse)->
if ($(ellipse).attr("fill").match(/#/i) &&
$(ellipse).attr("cx") >= 170 && $(ellipse).attr("cx") <= 185 &&
$(ellipse).attr("cy") >= 170 && $(ellipse).attr("cy") <= 185 &&
$(ellipse).attr("rx") < 15 && $(ellipse).attr("ry") < 18)
eye = true
)
return eye
'
},
{
position: 2,
step: 8,
kit: "puppy",
name: "make the left pupil (smaller than 11px)",
spec: '
eye = false
_.each($frame.find("svg ellipse"), (ellipse)->
if ($(ellipse).attr("fill").match(/#/i) &&
$(ellipse).attr("cx") >= 170 && $(ellipse).attr("cx") <= 185 &&
$(ellipse).attr("cy") >= 165 && $(ellipse).attr("cy") <= 180 &&
$(ellipse).attr("rx") < 11 && $(ellipse).attr("ry") < 11)
eye = true
)
_.each($frame.find("svg circle"), (circle) ->
if ($(circle).attr("fill").match(/#/i) &&
$(circle).attr("cx") >= 170 && $(circle).attr("cx") <= 185 &&
$(circle).attr("cy") >= 165 && $(circle).attr("cy") <= 180 &&
$(circle).attr("r") < 11)
eye = true
)
return eye
'
},
{
position: 3,
step: 8,
kit: "puppy",
name: "make the outer right eye",
spec: '
eye = false
_.each($frame.find("svg ellipse"), (ellipse)->
if ($(ellipse).attr("fill").match(/#/i) &&
$(ellipse).attr("cx") >= 220 && $(ellipse).attr("cx") <= 235 &&
$(ellipse).attr("cy") >= 170 && $(ellipse).attr("cy") <= 185 &&
$(ellipse).attr("rx") < 15 && $(ellipse).attr("ry") < 18)
eye = true
)
return eye
'
},
{
position: 4,
step: 8,
kit: "puppy",
name: "make the right pupil (smaller than 11px)",
spec: '
eye = false
_.each($frame.find("svg ellipse"), (ellipse)->
if ($(ellipse).attr("fill").match(/#/i) &&
$(ellipse).attr("cx") >= 220 && $(ellipse).attr("cx") <= 235 &&
$(ellipse).attr("cy") >= 165 && $(ellipse).attr("cy") <= 180 &&
$(ellipse).attr("rx") < 11 && $(ellipse).attr("ry") < 11)
eye = true
)
_.each($frame.find("svg circle"), (circle) ->
if ($(circle).attr("fill").match(/#/i) &&
$(circle).attr("cx") >= 220 && $(circle).attr("cx") <= 235 &&
$(circle).attr("cy") >= 165 && $(circle).attr("cy") <= 180 &&
$(circle).attr("r") < 11)
eye = true
)
return eye
'
},
{
position: 1,
step: 9,
kit: "puppy",
name: "make a nose that is wider than it is long",
spec: '
nose = false
_.each($frame.find("svg ellipse"), (ellipse)->
if parseInt($(ellipse).attr("rx"), 10) > parseInt($(ellipse).attr("ry"), 10)
nose = true
)
return nose
'
},
{
position: 2,
step: 9,
kit: "puppy",
name: "center the nose",
spec: '
nose = false
_.each($frame.find("svg ellipse"), (ellipse)->
if parseInt($(ellipse).attr("rx"),10) > parseInt($(ellipse).attr("ry"), 10)
x = parseInt($(ellipse).attr("cx"), 10)
if x >= 180 && x <= 220
nose = true
)
return nose
'
},
{
position: 3,
step: 9,
kit: "puppy",
name: "put the nose at the bottom of the face",
spec: '
nose = false
_.each($frame.find("svg ellipse"), (ellipse)->
if parseInt($(ellipse).attr("rx"),10) > parseInt($(ellipse).attr("ry"), 10)
y = parseInt($(ellipse).attr("cy"), 10)
if y <= 280
nose = true
)
if nose == true
nose = false
_.each($frame.find("svg ellipse"), (ellipse)->
y = parseInt($(ellipse).attr("cy"), 10)
if y >= 270
nose = true
)
return nose
else
return false
'
},
{
position: 4,
step: 9,
kit: "puppy",
name: 'give the nose a color',
spec: '
nose = false
_.each($frame.find("svg ellipse"), (ellipse)->
if parseInt($(ellipse).attr("rx"),10) > parseInt($(ellipse).attr("ry"), 10)
if $(ellipse).attr("fill").match(/#/i)
nose = true
)
return nose
'
}
]
Requirement.destroy_all
requirements.each do |req|
kit = Kit.find_by_slug(req.delete(:kit))
step = Step.where(kit_id: kit.id).where(position: req.delete(:step)).first
req[:step_id] = step.id
Requirement.create!(req)
end
|
require 'vizier/arguments/base'
module Vizier
#Input must match the regular expression passed to create this Argument
class RegexpArgument < Argument
register "regexp", Regexp
register "regex"
def complete(terms, prefix, subject)
return [prefix]
end
def validate(term, subject)
return basis(subject) =~ term
end
end
end
|
# This is a working file until I split these up
require 'spec_helper'
describe MSFLVisitors::Parsers::MSFLParser do
let(:expected_node) { ->(wrapped_node) { MSFLVisitors::Nodes::Filter.new [ wrapped_node ] } }
let(:left) { MSFLVisitors::Nodes::Field.new :value }
let(:right) { MSFLVisitors::Nodes::Number.new one_thousand }
let(:one_thousand) { 1000 }
describe "parsing a trivial filter" do
subject { described_class.new.parse msfl }
let(:msfl) { { value: one_thousand } }
it "is the expected node" do
expect(subject).to eq expected_node.call(MSFLVisitors::Nodes::Equal.new(left, right))
end
end
describe "#parse" do
context "when parsing a filter" do
subject { described_class.new.parse(filter) }
let(:set_of_values) { MSFL::Types::Set.new [50, 250, 20000] }
let(:set_of_nodes) { set_of_values.map { |value| MSFLVisitors::Nodes::Number.new value } }
let(:set_node) { MSFLVisitors::Nodes::Set.new set_of_nodes }
describe "parsing implicit equality" do
let(:filter) { { value: one_thousand } }
it "is the expected Equal node" do
expect(subject).to eq expected_node.call(MSFLVisitors::Nodes::Equal.new(left, right))
end
end
describe "parsing explict comparisons" do
describe "parsing a gt filter" do
let(:filter) { { value: { gt: one_thousand } } }
let(:gt_node) { MSFLVisitors::Nodes::GreaterThan.new left, right }
it "is the expected GreaterThan node" do
expect(subject).to eq expected_node.call(gt_node)
end
end
describe "parsing a gte filter" do
let(:filter) { { value: { gte: one_thousand } } }
let(:gte_node) { MSFLVisitors::Nodes::GreaterThanEqual.new left, right }
it "is the expected GreaterThanEqual node" do
expect(subject).to eq expected_node.call(gte_node)
end
end
describe "parsing a eq filter" do
let(:filter) { { value: { eq: one_thousand } } }
let(:eq_node) { MSFLVisitors::Nodes::Equal.new left, right }
it "is the expected Equal node" do
expect(subject).to eq expected_node.call(eq_node)
end
end
describe "parsing a lt filter" do
let(:filter) { { value: { lt: one_thousand } } }
let(:lt_node) { MSFLVisitors::Nodes::LessThan.new left, right }
it "is the expected LessThan node" do
expect(subject).to eq expected_node.call(lt_node)
end
end
describe "parsing a lte filter" do
let(:filter) { { value: { lte: one_thousand } } }
let(:lte_node) { MSFLVisitors::Nodes::LessThanEqual.new left, right }
it "is the expected LessThanEqual node" do
expect(subject).to eq expected_node.call(lte_node)
end
end
end
describe "parsing containment" do
let(:filter) { { value: { in: set_of_values } } }
let(:containment_node) { MSFLVisitors::Nodes::Containment.new left, set_node }
it "is the expected Containment node" do
expect(subject).to eq expected_node.call(containment_node)
end
end
describe "parsing filters that contain explicit filters" do
let(:explicit_filter_node) { MSFLVisitors::Nodes::ExplicitFilter.new [equal_node] }
let(:equal_node) { MSFLVisitors::Nodes::Equal.new field_node, value_node }
describe "parsing a foreign filter" do
let(:filter) { { foreign: { dataset: "person", filter: { age: 25 } } } }
let(:foreign_node) { MSFLVisitors::Nodes::Foreign.new dataset_node, explicit_filter_node }
let(:field_node) { MSFLVisitors::Nodes::Field.new :age }
let(:value_node) { MSFLVisitors::Nodes::Number.new 25 }
let(:dataset_node) { MSFLVisitors::Nodes::Dataset.new "person" }
subject { described_class.new(MSFL::Datasets::Car.new).parse(filter) }
it "is the expected Foreign node" do
expect(subject).to eq expected_node.call(foreign_node)
end
end
describe "parsing a partial" do
let(:filter) { { partial: { given: given_filter, filter: { avg_age: 10 } } } }
let(:given_filter) { { make: "Toyota" } }
let(:partial_node) { MSFLVisitors::Nodes::Partial.new given_node, named_value }
let(:given_node) { MSFLVisitors::Nodes::Given.new [given_equal_node] }
let(:given_equal_node) { MSFLVisitors::Nodes::Equal.new given_field_node, given_value_node }
let(:given_field_node) { MSFLVisitors::Nodes::Field.new :make }
let(:given_value_node) { MSFLVisitors::Nodes::Word.new "Toyota" }
let(:named_value) { MSFLVisitors::Nodes::NamedValue.new MSFLVisitors::Nodes::Word.new("partial"), explicit_filter_node }
# explicit_filter_node already defined
# equal_node already defined
let(:field_node) { MSFLVisitors::Nodes::Field.new :avg_age }
let(:value_node) { MSFLVisitors::Nodes::Number.new 10 }
it "is the expected Partial node" do
expect(subject).to eq expected_node.call(partial_node)
end
context "when the partial's given clause is a foreign" do
let(:given_filter) { { foreign: { dataset: "person", filter: { gender: 'male' } } } }
let(:given_node) { MSFLVisitors::Nodes::Given.new [foreign_node] }
let(:foreign_node) { MSFLVisitors::Nodes::Foreign.new dataset_node, given_explicit_filter_node }
let(:dataset_node) { MSFLVisitors::Nodes::Dataset.new "person" }
let(:given_explicit_filter_node) { MSFLVisitors::Nodes::ExplicitFilter.new [given_exp_fil_equal_node] }
let(:given_exp_fil_equal_node) { MSFLVisitors::Nodes::Equal.new given_exp_fil_field_node, given_exp_fil_value_node }
let(:given_exp_fil_field_node) { MSFLVisitors::Nodes::Field.new :gender }
let(:given_exp_fil_value_node) { MSFLVisitors::Nodes::Word.new 'male' }
it "is the expected Partial node with a Foreign node under the Given node" do
expect(subject).to eq expected_node.call(partial_node)
end
end
end
end
describe "parsing an and filter" do
let(:filter) { { and: MSFL::Types::Set.new([{ value: 1000 }]) } }
let(:and_node) { MSFLVisitors::Nodes::And.new set_node }
let(:set_node) { MSFLVisitors::Nodes::Set.new filter_node }
let(:filter_node) { MSFLVisitors::Nodes::Filter.new(MSFLVisitors::Nodes::Equal.new left, right) }
it "is the expected And node" do
expect(subject).to eq expected_node.call(and_node)
end
context "when it contains a containment filter" do
let(:makes) { MSFL::Types::Set.new(["Honda", "Chevy", "Volvo"]) }
let(:containment_filter) { { make: { in: makes } } }
let(:gte_filter) { { value: { gte: one_thousand } } }
let(:and_set) { MSFL::Types::Set.new([containment_filter, gte_filter]) }
let(:filter) { { and: and_set } }
let(:and_node) do
MSFLVisitors::Nodes::And.new(
MSFLVisitors::Nodes::Set.new(
[
MSFLVisitors::Nodes::Filter.new(
[
MSFLVisitors::Nodes::Containment.new(
MSFLVisitors::Nodes::Field.new(:make),
MSFLVisitors::Nodes::Set.new(
[
MSFLVisitors::Nodes::Word.new("Honda"),
MSFLVisitors::Nodes::Word.new("Chevy"),
MSFLVisitors::Nodes::Word.new("Volvo")
]
)
)
]
),
MSFLVisitors::Nodes::Filter.new(
[
MSFLVisitors::Nodes::GreaterThanEqual.new(
MSFLVisitors::Nodes::Field.new(:value),
MSFLVisitors::Nodes::Number.new(one_thousand)
)
]
)
]
)
)
end
it "is the expected And node" do
expect(subject).to eq expected_node.call(and_node)
end
end
end
context "when the filter contains an unsupported type" do
let(:filter) { { foo: Object.new } }
it "raises an ArgumentError" do
expect { subject }.to raise_error ArgumentError
end
end
end
end
end |
module Gloat
class Slide
VALID_EXTENSIONS = %w{ slide textile md haml erb html }
attr_reader :template_name
def initialize content, extension, template_name='default'
@extension = extension
@template_name = template_name
parse_slide(content)
end
def self.slide_file_valid? filename
file = Pathname.new(filename)
file.exist? && VALID_EXTENSIONS.include?(file.extname.gsub(/^\./, ''))
end
def options
@options ||= begin
Hashie::Mash.new(
@raw_options.scan(/\s*([^=]+)="([^"]+)"/).inject({}) { |hash, item| hash[item[0]] = item[1]; hash }
)
end
end
def markup
@markup ||= begin
if @extension == 'slide' || language != config.default_language
lang = language
else
lang = @extension
end
markup = case lang
when 'textile' then Tilt::RedClothTemplate.new { @raw_markup }.render
when 'haml' then Tilt::HamlTemplate.new { @raw_markup }.render
when 'erb' then Tilt::ErubisTemplate.new { @raw_markup.gsub(/<.+>\n* */) { |m| m.gsub(/>\n* *$/, '>') } }.render
when 'html' then @raw_markup
when /markdown|md/ then Tilt::RDiscountTemplate.new { @raw_markup }.render
else raise 'Unknown language'
end
Nokogiri::HTML::fragment(emojify(markup))
end
end
def for_json
{
options: options,
html: render.to_s
}
end
def render
@render ||= begin
Nokogiri::HTML::fragment(template.render(self))
end
end
private
def config
Config.instance
end
def parse_slide content
if match = content.match(/^!SLIDE\s?(?<raw_options>[^\n]*)\n\n(?<raw_markup>[^\n].*)$/m)
@raw_options = match['raw_options']
@raw_markup = match['raw_markup']
self
else
raise "Unable to create Gloat::Slide from '#{content}'"
end
end
def language
options.fetch('language', config.default_language)
end
def template
@template ||= Tilt::ERBTemplate.new(template_file)
end
def template_file
File.expand_path(File.join('..', '..', '..', 'views', 'templates', "#{template_name}.erb"), __FILE__)
end
def emojify markup=''
markup.gsub(/\s*:([a-z0-9\+\-_]+):\s*/) do |match|
if is_emoji?($1)
%Q{<img alt="#{$1}" src="/assets/emoji/#{$1}.png" class="emoji" />}
else
match
end
end
end
def is_emoji? file
available_emojis.include? file
end
def available_emojis
@available_emojis ||= Dir["#{config.images_path}/emoji/*.png"].sort.map { |f| File.basename(f, '.png') }
end
end
end
|
TeamType = GraphqlCrudOperations.define_default_type do
name 'Team'
description 'Team type'
interfaces [NodeIdentification.interface]
field :archived, types.Boolean
field :private, types.Boolean
field :avatar, types.String
field :name, !types.String
field :slug, !types.String
field :description, types.String
field :dbid, types.Int
field :members_count, types.Int
field :projects_count, types.Int
field :permissions, types.String
field :get_slack_notifications_enabled, types.String
field :get_slack_webhook, types.String
field :get_slack_channel, types.String
field :get_embed_whitelist, types.String
field :get_report_design_image_template, types.String
field :get_status_target_turnaround, types.String
field :pusher_channel, types.String
field :search_id, types.String
field :search, CheckSearchType
field :check_search_trash, CheckSearchType
field :trash_size, JsonStringType
field :public_team_id, types.String
field :permissions_info, JsonStringType
field :invited_mails, JsonStringType
field :dynamic_search_fields_json_schema, JsonStringType
field :get_rules, JsonStringType
field :rules_json_schema, types.String
field :rules_search_fields_json_schema, JsonStringType
field :medias_count, types.Int
field :trash_count, types.Int
field :get_languages, types.String
field :get_language, types.String
field :get_report, JsonStringType
field :get_fieldsets, JsonStringType
field :public_team do
type PublicTeamType
resolve -> (team, _args, _ctx) do
team
end
end
field :verification_statuses do
type JsonStringType
argument :items_count, types.Boolean
argument :published_reports_count, types.Boolean
resolve -> (team, args, _ctx) do
team.reload.send('verification_statuses', 'media', nil, args['items_count'], args['published_reports_count'])
end
end
connection :team_users, -> { TeamUserType.connection_type } do
resolve -> (team, _args, _ctx) {
team.team_users.where({ status: 'member' }).order('id ASC')
}
end
connection :join_requests, -> { TeamUserType.connection_type } do
resolve -> (team, _args, _ctx) {
team.team_users.where({ status: 'requested' })
}
end
connection :users, -> { UserType.connection_type } do
resolve -> (team, _args, _ctx) {
team.users
}
end
connection :contacts, -> { ContactType.connection_type } do
resolve -> (team, _args, _ctx) {
team.contacts
}
end
connection :projects, -> { ProjectType.connection_type } do
resolve ->(team, _args, _ctx) {
team.recent_projects
}
end
connection :sources, -> { SourceType.connection_type } do
resolve ->(team, _args, _ctx) {
team.sources
}
end
connection :team_bots, -> { BotUserType.connection_type } do
resolve ->(team, _args, _ctx) {
team.team_bots
}
end
connection :team_bot_installations, -> { TeamBotInstallationType.connection_type } do
resolve ->(team, _args, _ctx) {
team.team_bot_installations
}
end
connection :tag_texts, -> { TagTextType.connection_type } do
resolve ->(team, _args, _ctx) {
team.tag_texts
}
end
connection :team_tasks, -> { TeamTaskType.connection_type } do
argument :fieldset, types.String
resolve ->(team, args, _ctx) {
tasks = team.team_tasks.order(order: :asc, id: :asc)
tasks = tasks.where(fieldset: args['fieldset']) unless args['fieldset'].blank?
tasks
}
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
devise_for :customers
root to: 'homes#top'
get 'about' => 'homes#about'
get 'customers/unsubscribe' => "customers#unsubscribe"
patch 'customers/status' => "customers#status"
resources :customers, only: [:show, :edit, :update, :unsubscribe, :status]
resources :items, only: [:new, :index, :show]
resources :cart_items, only: [:index, :update, :create]
delete 'cart_items/:id' => "cart_items#one"
delete 'cart_items' => "cart_items#all"
get 'orders/complete' => "orders#complete"
resources :orders, only: [:new, :create, :index, :show]
post 'orders/confirm' => "orders#confirm"
resources :addresses, only: [:index, :edit, :create, :update, :destroy]
devise_for :admins, path: :admin, views: {
:registrations => 'admins/registrations',
:sessions => 'admins/sessions'
}
namespace :admin do
resources :genres, only: [:index, :new, :create, :edit, :update]
resources :items, only: [:index, :new, :create, :show, :edit, :update]
resources :customers, only: [:index, :show, :edit, :update]
resources :orders, only: [:show, :update, :makes]
root to: 'homes#top'
end
end
|
class Collection < ApplicationRecord
belongs_to :box
belongs_to :recipe
end
|
class User::TopController < User::Base
include SmartYoyakuApi::User
before_action :set_categories
before_action :not_found, only: :details
def index
end
def shop
if params[:category_id].present?
@category = Category.find(params[:category_id])
@all_store = Store.categorized(params[:category_id]).active
else
@all_store = Store.active
end
end
def details
@reserve_app_url = reserve_app_url
@plans = @store.plans
@masseurs = @store.masseurs
# 閲覧中のstoreが持っている出張範囲(各マッサージ師が持っている出張範囲)を全て取得
ranges = @masseurs.map { |masseur| masseur.business_trip_ranges.pluck(:city_id).map {|id| City.find_by(id: id) }}
# 取得した出張範囲で被っている出張範囲を一つにする。 それぞれのIDを取得
@prefecture_ids = ranges.flatten.uniq.map {|city| city.prefecture_id}
@city_ids = ranges.flatten.uniq.map {|city| city.id}
@store_images = @store.store_images.first
unless @store_images.nil?
@count_store_image = @store_images.store_image.count
end
end
private
# ヘッダーとトップページのカテゴリ一覧表示用
def set_categories
@categories = Category.all
end
# @storeのstore_managerが無料プラン契約中の場合404エラーを表示
def not_found
@store = Store.find(params[:id])
if @store.store_manager.order_plan.nil?
raise ActiveRecord::RecordNotFound, "こちらのページは現在表示することができません。"
end
end
end
|
module Acronym
# @param [String]
# @return [String]
def self.abbreviate(string)
# letter after word boundary
string.scan(/\b[a-zA-Z]/).join.upcase
end
end |
require 'test_helper'
class MovieReactionsControllerTest < ActionDispatch::IntegrationTest
setup do
@movie_reaction = movie_reactions(:one)
end
test "should get index" do
get movie_reactions_url
assert_response :success
end
test "should get new" do
get new_movie_reaction_url
assert_response :success
end
test "should create movie_reaction" do
assert_difference('MovieReaction.count') do
post movie_reactions_url, params: { movie_reaction: { liked: @movie_reaction.liked, movie_id: @movie_reaction.movie_id, user_id: @movie_reaction.user_id } }
end
assert_redirected_to movie_reaction_url(MovieReaction.last)
end
test "should show movie_reaction" do
get movie_reaction_url(@movie_reaction)
assert_response :success
end
test "should get edit" do
get edit_movie_reaction_url(@movie_reaction)
assert_response :success
end
test "should update movie_reaction" do
patch movie_reaction_url(@movie_reaction), params: { movie_reaction: { liked: @movie_reaction.liked, movie_id: @movie_reaction.movie_id, user_id: @movie_reaction.user_id } }
assert_redirected_to movie_reaction_url(@movie_reaction)
end
test "should destroy movie_reaction" do
assert_difference('MovieReaction.count', -1) do
delete movie_reaction_url(@movie_reaction)
end
assert_redirected_to movie_reactions_url
end
end
|
# # Binary Secret Handshake
# > There are 10 types of people in the world: Those who understand binary, and those who don't.
# You and your fellow flatirons are of those in the "know" when it comes to binary decide to come up with a secret "handshake".
# ```
# 1 = wink
# 10 = double blink
# 100 = close your eyes
# 1000 = jump
# 10000 = Reverse the order of the operations in the secret handshake.
# ```
# Write a program that will convert a binary number, represented as a string (i.e. "101010"), and convert it to the appropriate sequence of events for a secret handshake.
# ```
# handshake = SecretHandshake.new "1001"
# handshake.commands # => ["wink","jump"]
# handshake = SecretHandshake.new "11001"
# handshake.commands # => ["jump","wink"]
# ```
# The program should consider strings specifying an invalid binary as the value 0.
#1 = "wink"
#10 = "double blink"
#100 = "close your eyes"
#1000 = "jump"
#10000 = "Reverse the order of the operations in the secret handshake"
class SecretHandshake
attr_accessor :num
#secretHandshake = { 1 => "wink", 10 => "double blink", 100 => "close your eyes", 1000 => "jump", 1000 => "reverse" }
def initialize (num)
@num = num
end
def commands
new_array = []
secretHandshake = { 1 => "wink", 10 => "double blink", 100 => "close your eyes", 1000 => "jump", 10000 => "reverse" }
if num[-1] == "1"
new_array << secretHandshake[1]
end
if num[-2] == "1"
new_array << secretHandshake[10]
end
if num[-3] == "1"
new_array << secretHandshake[100]
end
if num[-4] == "1"
new_array << secretHandshake[1000]
end
if num[-5] == "1"
new_array.reverse!
end
new_array
end
end
handshake = SecretHandshake.new(10111)
handshake.commands
#=> ["wink", "jump"]
#if there is a 1 in the -1 postion (that is the last digit in the number is 1) = you get wink |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure('2') do |config|
config.vm.box = "precise32"
config.vm.box_url = "http://files.vagrantup.com/precise32.box"
config.vm.hostname = 'stm32-dev-box'
config.vm.synced_folder ".", "/home/vagrant/files"
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "1024"]
vb.customize ["modifyvm", :id, "--cpus", "1"]
vb.customize ["modifyvm", :id, "--ioapic", "on"]
vb.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/cross-compiler", "1"]
vb.customize ['modifyvm', :id, '--usb', 'on']
vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'STLink', '--vendorid', '0x0483', '--productid', '0x3748']
end
end |
module AdminArea
class RecommendationRequestsController < AdminController
def index
# accounts with unresolved recs:
accounts = Account\
.joins(:unresolved_recommendation_requests)\
.includes(
:unresolved_recommendation_requests,
owner: :unresolved_recommendation_request,
companion: :unresolved_recommendation_request,
).sort_by do |a|
[
a.owner.unresolved_recommendation_request&.created_at,
a.companion&.unresolved_recommendation_request&.created_at,
].compact.max
end
render cell(RecommendationRequests::Cell::Index, accounts)
end
end
end
|
# pic-mover.rb
$LOAD_PATH << File.dirname(__FILE__)
require 'logger'
require 'settings'
require 'remote'
require 'fileutils'
class Server
def initialize
@conf = Settings.new
log_path = File.join(@conf['local_root'], 'log', @conf['local_log_file'])
@log = Logger.new(log_path)
@log.level = Logger.const_get(@conf['local_log_level'])
end
def local_pics
path = @conf['local_pic_dir']
pics = Dir.glob("#{path}/*.jpg")
short_pics = pics.map{|pic| File.basename(pic) }
end
def remote_pics
pics = Remote.ls(
@conf['hostname'],
@conf['username'],
@conf['password'],
File.join(@conf['remote_root'], @conf['remote_glob']))
short_pics = pics.map{|pic| File.basename(pic) }
end
def pics_to_move?
@my_local_pics.size > 0
end
def run
@log.info "Running..."
n = 0
loop do
n += 1
@log.debug "Starting loop #{n}."
@my_local_pics = local_pics
if pics_to_move?
@log.info "Found pics to move: #{@my_local_pics}"
@my_remote_pics = remote_pics
@log.info "remote_pics: #{@my_remote_pics}"
@my_local_pics.each do |pic|
unless @my_remote_pics.include?(pic)
Remote.scp(
@conf['hostname'],
@conf['username'],
@conf['password'],
File.join(@conf['local_pic_dir'], pic),
File.join(@conf['remote_root'], pic))
@log.info "Copied local #{pic} to remote."
else
@log.info "Found local #{pic} already at remote."
FileUtils.rm File.join(@conf['local_pic_dir'], pic)
@log.info "Deleted local #{pic}."
end
end
end
sleep(@conf['scan_interval'])
end
end
end
server = Server.new
server.run
|
class CreateClientOrganizations < ActiveRecord::Migration[5.2]
def change
create_table :client_organizations do |t|
t.bigint :client_id
t.bigint :organization_id
end
add_index :client_organizations, [:client_id, :organization_id], unique: true
end
end
|
class DocumentationLink < ActiveRecord::Base
belongs_to :documentation
validates_presence_of :path
end |
class Users::UsersController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
end |
class SessionsController < ApplicationController
skip_before_action :require_user, only: [:new, :create]
# login page
def new
@login_form = LoginForm.new
end
# login form POST
def create
@login_form = LoginForm.new(login_params)
user = @login_form.authenticate
if @login_form.valid? && login(user)
redirect_to root_path
flash[:success] = 'Logged in successfully'
else
render action: 'new'
end
end
def destroy
reset_session
flash[:danger] = 'You have been logged out.'
redirect_to root_path
end
private
def login_params
params.require(:login_form).permit(:email, :password)
end
end |
require 'spec_helper'
require 'simplecov'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'rails/all'
require 'rspec/rails'
require 'devise'
# include Rack::Test::Methods
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.include ActionController::RespondWith, type: :controller
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include FactoryBot::Syntax::Methods
SimpleCov.start
config.include Devise::Test::IntegrationHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :controller
config.mock_with :rspec do |mocks|
mocks.verify_doubled_constant_names = true
end
end
|
class Restaurant < ActiveRecord::Base
has_many :reviews, dependent: :destroy
validates :name, presence: true, uniqueness: true
def average_rating
return 'N/A' if reviews.none?
reviews.inject(0) do |sum, review|
@total = sum+review.rating
end
@total/reviews.count
end
end
|
class ApplicationController < ActionController::API
private
# mongodb saves everything, remove any non-class defined attributes
def private_params(_class)
params.permit(_class.column_names)
end
end
|
# модель товара
# по большему счету тут все наглядно:
# - картинки, зависимости, валидации и переводы
# - алиас для категорий
# - расчет минимальной цены из вариантов
# - проверка наличия вариантов с картинкой материала
class Good < ActiveRecord::Base
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::TagHelper
include MultilingualModel
include SluggableModel
include AutotitleableModel
default_scope { order('weight, name') }
translates :price, :title, :heading, :keywords, :description, :announce, :content, :additional, :material_type_text
has_and_belongs_to_many :good_category
has_and_belongs_to_many :designer
has_and_belongs_to_many :material
has_and_belongs_to_many :property_type
has_and_belongs_to_many :tags
has_and_belongs_to_many :goods, foreign_key: 'parent_id'
has_one :video
has_one :category_good
delegate :weight, to: :category_good, prefix: true, allow_nil: true
has_many :files, dependent: :destroy, class_name: 'GoodFile'
has_many :dwgs, dependent: :destroy, class_name: 'GoodFile::Dwg'
has_many :pdfs, dependent: :destroy, class_name: 'GoodFile::Pdf'
has_many :variants, dependent: :destroy
has_many :three60s, -> { where media_file_id: nil}, dependent: :destroy
validates :name, presence: true
validates :article, presence: true
# validates :designer, presence: true
attr_accessor :thumb
attr_accessor :logo
attr_accessor :logo_desc
attr_accessor :picture
attr_accessor :portrait
attr_accessor :landscape
attr_accessor :panorama
attr_accessor :panorama_ipad
has_attached_file :logo,
styles: {preview: "300x300#"},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/logo/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/logo/:style/:basename.:extension"
has_attached_file :logo_desc,
styles: {preview: "400x30>"},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/logo_desc/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/logo_desc/:style/:basename.:extension"
has_attached_file :thumb,
styles: {preview: "300x300#", cart: "400x400#", additional: '90x90#', admin: "30x30#"},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/thumb/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/thumb/:style/:basename.:extension"
has_attached_file :portrait,
styles: {
picture: "3000x3000>",
normal: "768x1024#",
admin: "30x30#",
preview: '100x100#'
},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/portrait/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/portrait/:style/:basename.:extension",
convert_options: { picture: "-quality 79" }
has_attached_file :landscape,
styles: {
picture: "3000x3000>",
normal: "1024x768#",
admin: "30x30#",
preview: '100x100#'
},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/landscape/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/landscape/:style/:basename.:extension",
convert_options: { picture: "-quality 79" }
has_attached_file :picture,
styles: {
picture: "3000x3000>",
preview: "300x300#"
},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/picture/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/picture/:style/:basename.:extension",
convert_options: { picture: "-quality 79" }
has_attached_file :panorama,
styles: {
picture: "3000x3000>",
preview: "300x300#"
},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/panorama/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/panorama/:style/:basename.:extension",
convert_options: { picture: "-quality 79" }
has_attached_file :panorama_ipad,
styles: {
picture: "3000x3000>",
preview: "300x300#"
},
default_url: "/images/:style/missing.png",
url: "/uploads/goods/:id/panorama/ipad/:style/:basename.:extension",
path: ":rails_root/public/uploads/goods/:id/panorama/ipad/:style/:basename.:extension",
convert_options: { picture: "-quality 79" }
validates_attachment_content_type :panorama, :content_type => ['image/jpeg', 'image/png','image/gif']
validates_attachment_content_type :panorama_ipad, :content_type => ['image/jpeg', 'image/png','image/gif']
validates :logo, :attachment_presence => true
validates_attachment_content_type :logo, :content_type => ['image/jpeg', 'image/png','image/gif']
#validates :logo_desc, :attachment_presence => true
validates_attachment_content_type :logo_desc, :content_type => ['image/jpeg', 'image/png','image/gif']
validates :thumb, :attachment_presence => true
validates_attachment_content_type :thumb, :content_type => ['image/jpeg', 'image/png','image/gif']
validates :picture, :attachment_presence => true
validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/png','image/gif']
# validates :portrait, :attachment_presence => true
validates_attachment_content_type :portrait, :content_type => ['image/jpeg', 'image/png','image/gif']
# validates :landscape, :attachment_presence => true
validates_attachment_content_type :landscape, :content_type => ['image/jpeg', 'image/png','image/gif']
def categories
good_category
end
def best_price
best_price = price
unless variants.empty?
prices = variants.map{|v| v.price }
best_price = variants.min_by {|v| v.price}.price
((content_tag(:small, 'от') + ' ') unless (prices.uniq.size == 1)).to_s + number_to_currency(best_price, precision: 0, unit: 'р.').to_s
else
number_to_currency(best_price, precision: 0, unit: 'р.')
end
end
def pictures
{
preload: {
desktop: picture.url(:picture)
},
images: {
retina_portrait: portrait.url(:picture),
retina_landscape: landscape.url(:picture),
portrait: portrait.url(:normal),
landscape: landscape.url(:normal)
}
}
end
def material_types
self.variants.select{|v| v.material.present? && v.is_material }
end
def has_any_material_type?
self.material_types.size > 0
end
end
|
require 'rails_helper'
describe "find an item with params" do
context "search using valid params" do
before :each do
@item = create(:item)
end
it "can find an item with id params" do
get '/api/v1/items/find', params: {id: @item.id}
end
it "can find an item with name params" do
get '/api/v1/items/find', params: {name: @item.name}
end
it "can find an item with description params" do
get '/api/v1/items/find', params: {description: @item.description}
end
it "can find an item with unit price param" do
price = @item.format_unit_price
get '/api/v1/items/find', params: {unit_price: price}
end
it "can find an item with created_at param" do
@item.update(created_at: "2012-03-27T14:54:03.000Z")
get '/api/v1/items/find', params: {created_at: @item.created_at}
end
it "can find an item with updated_at param" do
@item.update(updated_at: "2012-03-27T14:54:03.000Z")
get '/api/v1/items/find', params: {updated_at: @item.updated_at}
end
after :each do
expect(response).to be_success
item = JSON.parse(response.body)
expect(item["id"]).to eq(@item.id)
expect(item["name"]).to eq(@item.name)
expect(item["description"]).to eq(@item.description)
expect(item["unit_price"]).to eq(@item.unit_price)
end
end
end
|
#GET request
get '/sample-41-how-to-set-callback-for-annotation-and-manage-user-rights' do
haml :sample41
end
#POST request
post '/sample41/callback' do
begin
#Get callback request
data = JSON.parse(request.body.read)
serialized_data = JSON.parse(data['SerializedData'])
raise 'Empty params!' if data.empty?
file_guid = serialized_data['DocumentGuid']
collaborator_guid = serialized_data['UserGuid']
client_id = nil
private_key = nil
#Get private key and client_id from file user_info.txt
if File.exist?("#{File.dirname(__FILE__)}/../public/user_info.txt")
contents = File.read("#{File.dirname(__FILE__)}/../public/user_info.txt")
contents = contents.split(' ')
client_id = contents.first
private_key = contents.last
end
status = nil
if file_guid != '' and collaborator_guid != ''
document = GroupDocs::Storage::File.new(:guid => file_guid).to_document
#Get all collaborators for the document
get_collaborator = document.collaborators!
get_collaborator.each do |reviewer|
#Set reviewer rights to view only
reviewer.access_rights = %w(view)
end
#Make request to API to update reviewer rights
status = document.set_reviewers! get_collaborator
end
#Create new file callback_info.txt and write the guid document
out_file = File.new("#{File.dirname(__FILE__)}/../public/callback_info.txt", 'w')
#White space is required
out_file.write(status.nil? ? "Error" : "User rights was set to view only")
out_file.close
rescue Exception => e
err = e.message
end
end
#POST request
post '/sample41/check_guid' do
pp 'test'
begin
result = nil
i = 0
for i in 1..10
i +=1
#Check is downloads folder exist
if File.exist?("#{File.dirname(__FILE__)}/../public/callback_info.txt")
result = File.read("#{File.dirname(__FILE__)}/../public/callback_info.txt")
if result != ''
break
end
end
sleep(3)
end
#Check result
if result == 'Error'
result = "File was not found. Looks like something went wrong."
else
result
end
rescue Exception => e
err = e.message
end
end
#POST request
post '/sample-41-how-to-set-callback-for-annotation-and-manage-user-rights' do
#Set variables
set :client_id, params[:clientId]
set :private_key, params[:privateKey]
set :email, params[:email]
set :source, params[:source]
set :file_id, params[:fileId]
set :url, params[:url]
set :base_path, params[:basePath]
set :callback, params[:callbackUrl]
#Set download path
downloads_path = "#{File.dirname(__FILE__)}/../public/downloads"
#Remove all files from download directory or create folder if it not there
if File.directory?(downloads_path)
Dir.foreach(downloads_path) { |f| fn = File.join(downloads_path, f); File.delete(fn) if f != '.' && f != '..' }
if File.exist?("#{File.dirname(__FILE__)}/../public/callback_info.txt")
File.delete("#{File.dirname(__FILE__)}/../public/callback_info.txt")
end
else
Dir::mkdir(downloads_path)
end
begin
#Check required variables
raise 'Please enter all required parameters' if settings.client_id.empty? or settings.private_key.empty? or settings.email.empty?
#Prepare base path
if settings.base_path.empty?
base_path = 'https://api.groupdocs.com'
elsif settings.base_path.match('/v2.0')
base_path = settings.base_path.split('/v2.0')[0]
else
base_path = settings.base_path
end
#Configure your access to API server
GroupDocs.configure do |groupdocs|
groupdocs.client_id = settings.client_id
groupdocs.private_key = settings.private_key
#Optionally specify API server and version
groupdocs.api_server = base_path # default is 'https://api.groupdocs.com'
end
#Write client and private key to the file for callback job
if settings.callback
out_file = File.new("#{File.dirname(__FILE__)}/../public/user_info.txt", 'w')
#White space is required
out_file.write("#{settings.client_id} ")
out_file.write("#{settings.private_key}")
out_file.close
end
#Get document by file GUID
case settings.source
when 'guid'
#Create instance of File
file = GroupDocs::Storage::File.new({:guid => settings.file_id})
when 'local'
#Construct path
file_path = "#{Dir.tmpdir}/#{params[:file][:filename]}"
#Open file
File.open(file_path, 'wb') { |f| f.write(params[:file][:tempfile].read) }
#Make a request to API using client_id and private_key
file = GroupDocs::Storage::File.upload!(file_path, {})
when 'url'
#Upload file from defined url
file = GroupDocs::Storage::File.upload_web!(settings.url)
else
raise 'Wrong GUID source.'
end
guid = file.guid
#Create document object
document = file.to_document
#Set file sesion callback - will be trigered when user add, remove or edit commit for annotation
session = document.set_session_callback! settings.callback
#Get all users from accaunt
users = GroupDocs::User.new.users!
user_guid = nil
# Number of collaborators
number = Array.new
if users
#Pass of each email
settings.email.each do |email|
#Pass of each user and get user GUID if user with same email already exist
users.map do |user|
if user.primary_email == email
#Get user GUID
user_guid = user.guid
break
end
end
#Check is user with entered email was founded in GroupDocs account, if not user will be created
if user_guid.nil?
#Create new User object
userNew = GroupDocs::User.new
#Set email as entered email
userNew.primary_email = settings.email
#Set first name as entered first name
userNew.firstname = settings.email
#Set last name as entered last name
userNew.lastname = settings.email
#Set roles
userNew.roles = [{:id => '3', :name => 'User'}]
#Update account
new_user = GroupDocs::User.update_account!(userNew)
#Get user GUID
user_guid = new_user.guid
end
#Get all collaborators for current document
collaborators = document.collaborators!
if collaborators
#Pass of each collaborator
collaborators.map do |collaborator|
#Check is user with entered email already in collaborators
if collaborator.primary_email == email
number << collaborator.guid
end
end
end
end
#Delete empty email
if settings.email[1].empty? then settings.email.delete("") end
#Add user as collaborators for the document
document.set_collaborators! settings.email if number.size < 2
#Add user GUID as "uid" parameter to the iframe URL
iframe = "/document-annotation2/embed/#{file.guid}?uid=#{user_guid}"
# Construct result string
url = GroupDocs::Api::Request.new(:path => iframe).prepare_and_sign_url
#Generate iframe URL
case base_path
when 'https://stage-api-groupdocs.dynabic.com'
iframe = "https://stage-api-groupdocs.dynabic.com#{url}"
when 'https://dev-api-groupdocs.dynabic.com'
iframe = "https://dev-apps.groupdocs.com#{url}"
else
iframe = "https://apps.groupdocs.com#{url}"
end
iframe = "<iframe src='#{iframe}' id='downloadframe' width='800' height='1000'></iframe>"
end
rescue Exception => e
err = e.message
end
#Set variables for template
haml :sample41, :locals => {:userId => settings.client_id, :fileId => settings.file_id, :privateKey => settings.private_key, :iframe => iframe, :callbackUrl => settings.callback, :err => err}
end
|
class Bullhorn
module Plugin
class << self
attr_accessor :options
attr :ignored_exceptions
end
def self.ignored_exceptions
[].tap do |ex|
ex << ActiveRecord::RecordNotFound if defined? ActiveRecord
if defined? ActionController
ex << ActionController::UnknownController
ex << ActionController::UnknownAction
ex << ActionController::RoutingError if ActionController.const_defined?(:RoutingError)
end
end
end
protected
def rescue_action_in_public(exception)
notify_with_bullhorn!(exception)
super
end
def notify_with_bullhorn!(exception)
unless Bullhorn::Plugin.ignored_exceptions.include?(exception.class)
bullhorn = Bullhorn.new(self, Bullhorn::Plugin.options)
bullhorn.notify(exception, request.env)
end
end
end
end |
class Project < ActiveRecord::Base
validates :title, :presence => true, :uniqueness => true
has_many :project_weeks
has_many :weeks, :through => :project_weeks, :uniq => true
def num_weeks_scheduled weeks
num = 0
weeks.each do |week|
if self.weeks.include?(week)
num += 1
end
end
num
end
end
|
class RemoveManuallyEnteredForeignKeys < ActiveRecord::Migration
def change
remove_column :answers, :question_id
remove_column :questions, :quiz_id
end
end
|
class UpdateMatches < ActiveRecord::Migration[5.2]
def change
remove_column :matches, :forfeit, :integer
remove_column :matches, :league_play, :boolean
remove_column :matches, :teams_id, :integer
add_reference :matches, :division
end
end
|
class AddDatetimeStatusesToConsultant < ActiveRecord::Migration
def change
add_column :consultants, :date_on_hold, :datetime
add_column :consultants, :date_pending_approval, :datetime
add_column :consultants, :date_approved, :datetime
add_column :consultants, :date_rejected, :datetime
end
def data
Consultant.find_each do |c|
if c.pending_approval?
c.date_pending_approval = DateTime.now
end
if c.on_hold?
c.date_on_hold = DateTime.now
end
if c.approved?
c.date_approved = DateTime.now
c.date_pending_approval = DateTime.now
end
if c.rejected?
c.date_rejected = DateTime.now
c.date_pending_approval = DateTime.now
end
c.save
end
end
end
|
class Proc
def to_route(opts = {})
based_on = opts[:based_on]
if opts[:unwrap] or based_on and based_on.extensions and based_on.graph
source = proc { self.call.map { |e| e.element } }
else
source = self
end
if based_on
Pacer::RouteBuilder.current.chain(source, :element_type => :mixed, :graph => based_on.graph, :extensions => based_on.extensions, :info => based_on.info)
else
graph = opts[:graph] if opts[:graph]
Pacer::RouteBuilder.current.chain(source, :element_type => (opts[:element_type] || :object), :graph => graph, :extensions => opts[:extensions], :info => opts[:info])
end
end
end
|
class Api::V1::InvitationsController < Devise::InvitationsController
skip_before_action :resource_from_invitation_token, :only => [:edit]
def edit
invitation_token = params[:invitation_token]
slug = params[:slug]
resource = User.accept_team_invitation(invitation_token, slug)
path = if resource.errors.empty?
user = User.find_by_id(resource.id)
if user.nil?
url = "/?invitation_response=success&msg=no"
else
sign_in user
url = "/#{slug}"
end
url
else
error_key = resource.errors.messages.keys[0].to_s
error_key == 'invitation_accepted' ? "/#{slug}" : "/?invitation_response=#{error_key}"
end
redirect_to CheckConfig.get('checkdesk_client') + path
end
end
|
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
describe 'the dns_aaaa function' do
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
it 'should exist' do
expect(Puppet::Parser::Functions.function('dns_aaaa')).to eq('function_dns_aaaa')
end
it 'should raise a ArgumentError if there is less than 1 arguments' do
expect { scope.function_dns_aaaa([]) }.to raise_error(ArgumentError)
end
it 'should return a list of IPv6 addresses when doing a lookup' do
results = scope.function_dns_aaaa(['google.com'])
expect(results).to be_a Array
results.each do |res|
expect(res).to match(/([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])/)
end
end
it 'should raise an error on empty reply' do
expect { scope.function_dns_aaaa(['foo.example.com']) }.to raise_error(Resolv::ResolvError)
end
end
|
class Hand
attr_reader :held_cards
def initialize
@held_cards = []
end
def size
held_cards.count
end
def new_card!(deck_to_draw)
held_cards << deck_to_draw.draw!
end
def view
if size == 0
"No cards!"
else
cards_info = []
held_cards.each do |card|
cards_info << card.info
end
cards_info
end
end
end
|
class Dragon
def initialize name
@name = name
@asleep = false
@stuff_in_belly = 10 # He's full.
@stuff_in_intestine = 0 # He doesn't need to go.
puts "#{@name} just hatched from the mystical egg."
end
def feed
puts "You feed #{@name} the bodies of your enemies."
@stuff_in_belly = 10
passage_of_time
end
def walk
puts "You take a walk through the village with #{@name} balanced on your shoulder."
@stuff_in_intestine = 0
passage_of_time
end
def put_to_bed
puts "You put #{@name} to bed."
@asleep = true
3.times do
if @asleep
passage_of_time
end
if @asleep
puts "#{@name} snores, and you question whether he has sleep apnoea."
end
end
if @asleep
@asleep = false
puts "#{@name} wakes up slowly."
end
end
def toss
puts "You toss #{@name} up into the air."
puts 'Some of his slobber lands in your mouth. Ew.'
passage_of_time
end
def rock
puts "You rock #{@name} gently."
@asleep = true
puts 'He briefly dozes off...'
passage_of_time
if @asleep
@asleep = false
puts '...but wakes when you stop.'
end
end
private
def hungry?
@stuff_in_belly <= 2
end
def poopy?
@stuff_in_intestine >= 8
end
def passage_of_time
if @stuff_in_belly > 0
@stuff_in_belly = @stuff_in_belly - 1
@stuff_in_intestine = @stuff_in_intestine + 1
else # Our dragon is starving!
if @asleep
@asleep = false
puts 'He wakes up suddenly!'
end
puts "#{@name} is starving! In desperation, he fly's off to McDonals for a fillet o' fish. What a weirdo."
exit # This quits the program.
end
if @stuff_in_intestine >= 10
@stuff_in_intestine = 0
puts "Oh betty! #{@name}'s done a whoopsy on the carpet.'"
end
if hungry?
if @asleep
@asleep = false
puts 'He wakes up suddenly!'
end
puts "#{@name}'s stomach grumbles..."
end
if poopy?
if @asleep
@asleep = false
puts 'He wakes up suddenly!'
end
puts "#{@name} does the potty dance..."
end
end
end
pet = Dragon.new 'Toothless'
pet.feed
pet.toss
pet.walk
pet.put_to_bed
pet.rock
pet.put_to_bed
pet.put_to_bed
pet.put_to_bed
pet.put_to_bed
|
class CreateBookmarks < ActiveRecord::Migration[5.0]
def change
create_table :bookmarks do |t|
t.string :title
t.string :url
t.text :description
t.text :image
t.boolean :favorite
t.belongs_to :user
t.timestamps
end
end
end
|
User.class_eval do
after_commit -> { PipelineService::V2.publish self }
# Submissions must be excused upfront else once the first requirement check happens
# the all_met condition will fail on submissions not being excused yet
#
# content_tag - where we want to place them
# context_module - module of the place we want to place them
def custom_placement_at(content_tag)
context_module = content_tag.context_module
course = context_module.context
new_placement_position = content_tag.position - 1
# get 'lower' module units in Course
bypass_modules = course.context_modules
.where('position < ?', context_module.position)
.order(position: :asc)
# get 'lower' content tags within same context_module as where we're dropping user
bypass_tags = context_module.content_tags
.active
.where('position <= ?', new_placement_position)
.order(position: :asc)
# exclude any submissions requirements
bypass_modules.each do |bypass_module|
bypass_module.content_tags
.active
.order(position: :asc).each do |tag|
exclude_submissions(tag)
bypass_module.touch
end
end
# exclude any submissions requirements
bypass_tags.each do |tag|
exclude_submissions(tag)
end
# force progression requirements of lower modules
bypass_modules.each do |bypass_module|
progression = bypass_module.find_or_create_progression(self) # self is user
progression.update_columns requirements_met: bypass_module.completion_requirements,
evaluated_at: (bypass_module.updated_at - 1.second),
current: false # mark as outdated # TODO change back to false
progression.reload.evaluate!
bypass_module.touch
sleep(Rails.env.production? ? 5 : 1)
end
# force progression requirements of lower tags in new placements context_module
bypass_tags_context_module = context_module
return if bypass_tags_context_module.nil?
requirements_of_bypass_tags = bypass_tags.map do |tag|
bypass_tags_context_module.completion_requirements.find do |req|
req[:id] == tag.id
end
end.compact
# puts '*** requirements_of_bypass_tags ***'
# puts requirements_of_bypass_tags
progression = bypass_tags_context_module.find_or_create_progression(self) # self is user
progression.update_columns requirements_met: requirements_of_bypass_tags,
evaluated_at: (bypass_tags_context_module.updated_at - 1.second),
current: false # mark as outdated
progression.reload.evaluate!
bypass_tags_context_module.touch
AssignmentOverrideStudent.where(user_id: self.id, assignment_id: course.assignment_ids).each(&:destroy!) # run through each as we want callbacks to fire
sleep(Rails.env.production? ? 5 : 1)
end
def exclude_submissions(tag)
tag.context_module.completion_requirements.each do |req|
next unless req[:id] == tag.id
subs = []
# Things that can have assignments, i.e. Quiz, Discussion Topic, etc?
if tag&.content&.respond_to? :assignment
subs = tag&.content&.assignment&.submissions&.where(user_id: self.id) || []
elsif tag&.content&.respond_to? :submissions # Assignment
subs = tag&.content&.submissions&.where(user_id: self.id) || []
end
subs.each do |sub|
sub.update_column :excused, true
end
end
end
def get_teacher_unread_discussion_topics(course)
topic_microservice_endpoint = ENV['TOPIC_MICROSERVICE_ENDPOINT']
api_key = ENV['TOPIC_MICROSERVICE_API_KEY']
return {} unless topic_microservice_endpoint && api_key
return {} if self.enrollments.where(type: 'TeacherEnrollment').empty?
endpoint = "#{topic_microservice_endpoint}/teachers/#{ENV['CANVAS_DOMAIN']}:#{self.id}/topics/"
ret = HTTParty.get(endpoint, headers: { "x-api-key": api_key })
return {} unless ret.code == 200
ids = JSON.parse(ret.body).map(&:to_i)
Assignment.joins(:discussion_topic).where('discussion_topics.id' => ids).where('context_id' => course.id)
end
def recent_feedback_with_wrap(opts={})
filter_feedback(recent_feedback_without_wrap(opts))
end
alias_method :recent_feedback_without_wrap, :recent_feedback
alias_method :recent_feedback, :recent_feedback_with_wrap
private
def filter_feedback(submissions)
submissions.select { |sub| sub.submission_comments.any? || (sub.grader_id && sub.grader_id > GradesService::Account.account_admin.try(:id)) }
end
end
|
# encoding: utf-8
Gem::Specification.new do |s|
s.name = 'hibot'
s.version = '0.0.4'
s.date = '2015-07-28'
s.summary = "IRC bot supporting multiple services."
s.description = "IRC bot supporting multiple services like spotify, giphy and so on."
s.authors = ["Nicolas Collard"]
s.email = 'niko@hito.be'
s.files = ["lib/hibot.rb"]
s.homepage = 'https://github.com/Hito01/Hibot'
s.license = 'MIT'
s.add_dependency "cinch", "~> 2.2"
s.add_dependency "httparty", "~> 0.13"
s.add_dependency "rainbow", "~> 2.0"
s.add_development_dependency "bundler", "~> 1.9"
s.add_development_dependency "rake", "~> 10.4"
s.files = `git ls-files`.split($\)
s.test_files = s.files.grep(/^spec/)
s.executables << "hibot"
end
|
class AddLocalToGames < ActiveRecord::Migration
def change
add_column :games, :local, :integer, :default => 0
add_column :games, :local_miss, :integer, :default => 0
end
end
|
class SkillsController < ApplicationController
before_filter :authenticate_admin!
def new
@skill = Skill.new
@post = Post.find(params[:post_id])
render :partial => 'form', :locals => {:skill => @skill, :post => @post}
end
def create
@post = Post.find(params[:post_id])
@skill = @post.skills.build(params[:skill])
respond_to do |format|
if @skill.save
format.html
format.js
else
redirect_to root_path
end
end
end
def edit
@skill = Skill.new
@post = Post.find(params[:post_id])
render :partial => 'form', :locals => {:skill => @skill, :post => @post}
end
def update
@post = Post.find(params[:post_id])
@skill = Skill.find(params[:id])
if @skill.update_attributes(params[:skill])
redirect_to edit_post_path(@post)
end
end
def destroy
@skill = Skill.find(params[:id])
respond_to do |format|
if @skill.destroy
format.js
else
end
end
end
end
|
require 'edge'
describe Edge do
context '#initialize' do
edge = Edge.new('A','B', 5)
it 'has a start node' do
expect(edge.start).to eq 'A'
end
it 'has an end node' do
expect(edge.finish). to eq 'B'
end
it 'has a weight' do
expect(edge.weight). to eq 5
end
end
end
|
module UserHelper
def classes(contribution)
return case contribution.contribution_type
when :image, :video, :suggestion
"#{contribution.contribution_type.to_s} dnld"
when 'attached_file'
"document dnld"
when 'link'
"#{contribution.contribution_type} dnld"
else
''
end
end
end
|
class Preferences < ActiveRecord::Base
belongs_to :user
def self.create_for_user user
user.create_preferences if user.preferences.nil?
end
end
|
require "rails_helper"
describe Subscription do
it "belongs to user" do
Subscription.reflect_on_association(:user).macro.should eq(:belongs_to)
end
it "belongs to plan" do
Subscription.reflect_on_association(:plan).macro.should eq(:belongs_to)
end
it "has many to transactions" do
Subscription.reflect_on_association(:transactions).macro.should eq(:has_many)
end
end |
# listpkg.rb - This script will extract the package information
# from a Conary database and list the installed packages and their
# version numbers on the console.
#
# Author: Steven Oliphant
# Stonecap Enterprises
#
# This software is copyrighted 2007 All rights reserved
# ManageIQ
# 1 International Boulevard
# Mahwah, NJ 07495
#
# This version requires the sqlite 3 ruby interface library
#
begin
require 'sqlite3'
rescue LoadError
puts "sqlite3 library not found"
exit
end
if ARGV.length == 0
puts "No database name given"
exit
end
begin
fn = ARGV[0]
fh = File.open fn
fh.close
rescue
puts fn + " cannot be opened"
exit
end
begin
db = SQLite3::Database.open fn
columns = nil
count = 0
select = "select Instances.troveName, Instances.versionID,\
Versions.version from Instances,Versions where\
Instances.versionID = Versions.versionID and Instances.troveName\
not like '%:%' and Instances.isPresent=1 order by Instances.troveName"
db.execute2(select) do |row|
# skip first row - always the select name header
if columns.nil?
columns = row
else
count += 1
# process row
cnt = count.to_s
print cnt, " Pkg: ", row[0], " Version ID: ", row[1], " Version: ", row[2], "\n"
end
end
rescue SQLite3::SQLException
puts "SQL Query failed for database: " + fn
exit
end
|
# encoding: utf-8
require "spec_helper"
describe Refinery do
describe "LandingPages" do
describe "Admin" do
describe "landing_pages" do
refinery_login_with :refinery_user
describe "landing_pages list" do
before do
FactoryGirl.create(:landing_page, :Homepage_Headline => "UniqueTitleOne")
FactoryGirl.create(:landing_page, :Homepage_Headline => "UniqueTitleTwo")
end
it "shows two items" do
visit refinery.landing_pages_admin_landing_pages_path
page.should have_content("UniqueTitleOne")
page.should have_content("UniqueTitleTwo")
end
end
describe "create" do
before do
visit refinery.landing_pages_admin_landing_pages_path
click_link "Add New Landing Page"
end
context "valid data" do
it "should succeed" do
fill_in "Homepage Headline", :with => "This is a test of the first string field"
click_button "Save"
page.should have_content("'This is a test of the first string field' was successfully added.")
Refinery::LandingPages::LandingPage.count.should == 1
end
end
context "invalid data" do
it "should fail" do
click_button "Save"
page.should have_content("Homepage Headline can't be blank")
Refinery::LandingPages::LandingPage.count.should == 0
end
end
context "duplicate" do
before { FactoryGirl.create(:landing_page, :Homepage_Headline => "UniqueTitle") }
it "should fail" do
visit refinery.landing_pages_admin_landing_pages_path
click_link "Add New Landing Page"
fill_in "Homepage Headline", :with => "UniqueTitle"
click_button "Save"
page.should have_content("There were problems")
Refinery::LandingPages::LandingPage.count.should == 1
end
end
end
describe "edit" do
before { FactoryGirl.create(:landing_page, :Homepage_Headline => "A Homepage_Headline") }
it "should succeed" do
visit refinery.landing_pages_admin_landing_pages_path
within ".actions" do
click_link "Edit this landing page"
end
fill_in "Homepage Headline", :with => "A different Homepage_Headline"
click_button "Save"
page.should have_content("'A different Homepage_Headline' was successfully updated.")
page.should have_no_content("A Homepage_Headline")
end
end
describe "destroy" do
before { FactoryGirl.create(:landing_page, :Homepage_Headline => "UniqueTitleOne") }
it "should succeed" do
visit refinery.landing_pages_admin_landing_pages_path
click_link "Remove this landing page forever"
page.should have_content("'UniqueTitleOne' was successfully removed.")
Refinery::LandingPages::LandingPage.count.should == 0
end
end
end
end
end
end
|
# Public: Uses the meal cost and tip amount to calculate the cost per person of a meal shared.
class CheckSplitter
attr_reader :tip_amount
# Public: Initializes a new Checksplitter.
def initialize(meal_cost:, group:, tip_percentage: 0.18)
@meal_cost = meal_cost.to_f
@group = group.to_f
self.get_tip_amount(tip_percentage, meal_cost)
end
# Public: Calculates the tip amount.
#
# tip_perctange - percentage amount given as a whole number
# meal_cost - cost of meal
#
# Returns a float for the tip amount to be added to meal cost.
def get_tip_amount(tip_percentage, meal_cost)
@tip_amount = meal_cost*(tip_percentage/100.0)
end
# Public: Calculates the total cost of the meal.
#
# meal_cost - cost of meal
# tip_amount - amount of tip
#
# Returns a float for the total cost of meal
def total_cost
@meal_cost + @tip_amount
end
# Public: Calculates the cost per person.
#
# total_cost - total cost of meal
# group - number of people at the meal
#
# Returns the cost per person attending the meal.
def cost_per_person
self.total_cost / @group
end
end |
FactoryGirl.define do
factory :history do
symbol "MyString"
date "2016-03-04"
open "9.99"
high "9.99"
low "9.99"
close "9.99"
volume 1
adj_close "9.99"
end
end
|
class CitiesController < ApplicationController
def index
@cities = City.all
end
def show
@city = City.find(params[:id])
@neighborhoods = Neighborhoods.all
end
private
def set_city
@city = City.find(params[:id])
end
end
|
# frozen_string_literal: true
#
# Author:: Chef Partner Engineering (<partnereng@chef.io>)
# Copyright:: Copyright (c) 2022 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'spec_helper'
describe Vra::Catalog do
let(:client) do
Vra::Client.new(
username: 'user@corp.local',
password: 'password',
tenant: 'tenant',
base_url: 'https://vra.corp.local'
)
end
let(:catalog_item) do
JSON.parse(File.read('spec/fixtures/resource/sample_catalog_item.json'))
end
let(:entitled_catalog_item) do
JSON.parse(File.read('spec/fixtures/resource/sample_catalog_item_2.json'))
end
before(:each) do
allow(client).to receive(:authorized?).and_return(true)
end
describe '#all_items' do
it 'calls the catalogItems endpoint' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/admin/items', nil)
.and_return([catalog_item])
client.catalog.all_items
end
it 'returns a Vra::CatalogItem object' do
allow(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/admin/items', nil)
.and_return([catalog_item])
items = client.catalog.all_items
expect(items.first).to be_an_instance_of(Vra::CatalogItem)
end
end
describe '#entitled_items' do
it 'calls the entitledCatalogItems endpoint' do
expect(client).to receive(:get_parsed)
.with('/catalog/api/admin/entitlements?projectId=pro-123456')
.and_return(JSON.parse(File.read('spec/fixtures/resource/sample_entitlements.json')))
client.catalog.entitled_items('pro-123456')
end
it 'returns a Vra::CatalogItem object' do
allow(client).to receive(:get_parsed)
.with('/catalog/api/admin/entitlements?projectId=pro-123456')
.and_return(JSON.parse(File.read('spec/fixtures/resource/sample_entitlements.json')))
items = client.catalog.entitled_items('pro-123456')
expect(items.first).to be_an_instance_of(Vra::CatalogItem)
end
it 'return a Vra::CatalogSource object on source entitlements' do
allow(client).to receive(:get_parsed)
.with('/catalog/api/admin/entitlements?projectId=pro-123456')
.and_return(JSON.parse(File.read('spec/fixtures/resource/sample_entitlements.json')))
items = client.catalog.entitled_sources('pro-123456')
expect(items.first).to be_an_instance_of(Vra::CatalogSource)
end
end
describe '#request' do
it 'returns a new Vra::CatalogRequest object' do
allow(Vra::CatalogItem).to receive(:new)
request = client.catalog.request('blueprint-1', cpus: 2)
expect(request).to be_an_instance_of(Vra::DeploymentRequest)
end
end
describe '#sources' do
let(:source_data) do
JSON.parse(File.read('spec/fixtures/resource/sample_catalog_source.json'))
end
it 'should call the api to fetch the sources' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/admin/sources', nil)
.and_return([source_data])
client.catalog.all_sources
end
it 'should return the Vra::CatalogSource object' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/admin/sources', nil)
.and_return([source_data])
source = client.catalog.all_sources.first
expect(source).to be_a(Vra::CatalogSource)
end
end
describe '#types' do
let(:type_data) do
JSON.parse(File.read('spec/fixtures/resource/sample_catalog_type.json'))
end
it 'should call the api to fetch the types' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/types', nil)
.and_return([type_data])
client.catalog.all_types
end
it 'should return the Vra::CatalogType object' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/types', nil)
.and_return([type_data])
source = client.catalog.all_types.first
expect(source).to be_a(Vra::CatalogType)
end
end
describe '#fetch_catalog_by_name' do
let(:catalog_item) do
JSON.parse(File.read('spec/fixtures/resource/sample_catalog_item.json'))
end
it 'returns the catalogs by name' do
expect(client).to receive(:http_get_paginated_array!)
.with('/catalog/api/admin/items', 'search=centos')
.and_return([catalog_item])
cat = client.catalog.fetch_catalog_items('centos').first
expect(cat).to be_an_instance_of(Vra::CatalogItem)
end
end
end
|
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
token = request.params[:token]
payload = JWT.decode(token, ENV['JWT_SECRET_KEY'], true, {algorithm: 'HS256'})[0]
if verified_user = User.find(payload["user_id"])
verified_user
else
reject_unauthorized_connection
end
end
end
end
|
class UsersController < ApplicationController
def index
@users = User.joins(:professions).where(professions: { id: params[:profession]})
@profession = Profession.find(params[:profession])
@enquiry = Enquiry.new()
end
def new
User.new()
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
@user.become_contractor if params[:contractor]
end
def update
@user = User.find(params[:id])
if params[:user][:profession_ids]
@user.update_professions(params[:user][:profession_ids])
end
@user.update(user_params)
if @user.update(user_params)
redirect_to profile_path
else
render :edit
end
end
private
def user_params
params.require(:user).permit(:contractor_name, :bio, :logo)
end
end
|
class AddEmailAndPasswordToUser < ActiveRecord::Migration
def self.up
add_column :users, :email, :string
add_column :users, :password, :string
add_column :users, :status, :string,:default=>User::STATUS[:reg_step_1]
add_column :users,:last_position_x,:double,:default=>0
add_column :users,:last_position_y,:double,:default=>0
end
def self.down
remove_column :users, :password
remove_column :users, :email
remove_column :users, :status
remove_column :users,:last_position_x
remove_column :users,:last_position_y
end
end
|
class State < ActiveRecord::Base
has_many :petitions
has_many :state_word_counts
validates :name, presence: true, uniqueness:true
def to_param
name
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.