text
stringlengths
10
2.61M
class User < ApplicationRecord mount_uploader :photo, ImageUploader # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :lists has_many :skills, through: :lists, as: :skills has_many :wishlists has_many :skills, through: :wishlists, as: :wishlists def self.random(user_id) User.where('id != ?', user_id).order("random()").limit(1).first end end
class GamesController < ApplicationController filter_access_to :all before_filter :require_user, :except => :index before_filter :find_game, :only => [:show, :edit, :update, :destroy] helper_method :get_count, :get_percent_rated # GET /games # GET /games.xml def index @games = Game.paginate :page => params[:page], :order => 'title', :per_page => 10 respond_to do |format| format.html # index.html.erb format.xml { render :xml => @games } end end # GET /games/1 # GET /games/1.xml def show respond_to do |format| format.html # show.html.erb format.xml { render :xml => @game } end end # GET /games/new # GET /games/new.xml def new @game = Game.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @game } end end # GET /games/1/edit def edit end # POST /games # POST /games.xml def create @game = Game.new(params[:game]) respond_to do |format| if @game.save flash[:notice] = 'Game was successfully created.' format.html { redirect_to(@game) } format.xml { render :xml => @game, :status => :created, :location => @game } else format.html { render :action => "new" } format.xml { render :xml => @game.errors, :status => :unprocessable_entity } end end end # PUT /games/1 # PUT /games/1.xml def update respond_to do |format| if @game.update_attributes(params[:game]) flash[:notice] = 'Game was successfully updated.' format.html { redirect_to(@game) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @game.errors, :status => :unprocessable_entity } end end end # DELETE /games/1 # DELETE /games/1.xml def destroy @game.destroy respond_to do |format| format.html { redirect_to(games_url) } format.xml { head :ok } end end # Return the number of games owned by the # specified user def get_count( user_id ) return Game.count(:conditions => ["user_id = ?", user_id]) end # Return the number of games owned by the # specified user that are rated def get_rated_count( user_id ) return Game.count(:conditions => ["user_id = ? AND rating != '' AND rating IS NOT NULL", user_id]) end # Return the percent of games owned by the # specified user where the rating is not null def get_percent_rated( user_id ) return 100.0 * get_rated_count(user_id) / get_count( user_id ) end private def find_game @game = Game.find(params[:id]) end end
class MeditationsHaveEmbed < ActiveRecord::Migration def change add_column :meditations, :embed, :text end end
class CreateMinputs < ActiveRecord::Migration[5.0] def change create_table :minputs do |t| t.decimal :tlosses, precision: 10, scale: 2 t.decimal :llosses, precision: 10, scale: 2 t.decimal :ct, precision: 10, scale: 2 t.boolean :f, default: true t.date :mdate, null: false t.text :comment end end end
class Game < ActiveRecord::Base has_many :rounds validates :president, :name, presence: true after_save :prepare_for_game def prepare_for_game gamemaker = Gamemaker.new(self) # gamemaker.some_method end end
module GoodnightWorld def self.handler(event:, context:) "Good Night World!" end end
class AddMainCharactersToShow < ActiveRecord::Migration def change add_column :shows, :main_characters, :text, array: true, default: [] end end
class AddSectionIdToItems < ActiveRecord::Migration def change add_reference :items, :section, index: true, foreign_key: true end end
class StringBuffer attr_accessor :buffer def initialize @buffer = [] end def append word buffer.push word end def to_s buffer.inject("", :<<) end end
require File.expand_path('../helper', __FILE__) require 'citrus/file' class CitrusFileTest < Test::Unit::TestCase # A shortcut for creating a grammar that includes Citrus::File but uses a # different root. def file(root_rule) Grammar.new do include Citrus::File root root_rule end end ## File tests def run_file_test(file, root) grammar = file(root) code = F.read(file) match = grammar.parse(code) assert(match) end %w< rule grammar >.each do |type| Dir[F.dirname(__FILE__) + "/_files/#{type}*.citrus"].each do |path| module_eval(<<-RUBY.gsub(/^ /, ''), __FILE__, __LINE__ + 1) def test_#{F.basename(path, '.citrus')} run_file_test("#{path}", :#{type}) end RUBY end end ## Hierarchical syntax def test_rule_body_alias grammar = file(:rule_body) match = grammar.parse('rule_name') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Alias, match.value) end def test_rule_body_terminal grammar = file(:rule_body) match = grammar.parse('.') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) match = grammar.parse('[a-z]') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) match = grammar.parse('/./') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) match = grammar.parse("[0-9] {\n def value\n text.to_i\n end\n}\n") assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) end def test_rule_body_string_terminal grammar = file(:rule_body) match = grammar.parse('""') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) match = grammar.parse('"a"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) match = grammar.parse('"" {}') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) end def test_rule_body_repeat grammar = file(:rule_body) match = grammar.parse('"a"*') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) assert_equal(0, match.value.min) assert_equal(Infinity, match.value.max) match = grammar.parse('""* {}') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" "b")*') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" | "b")*') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" "b")* {}') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" | "b")* {}') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" "b")* <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('( "a" "b" )* <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('("a" | "b")* <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse("[0-9]+ {\n def value\n text.to_i\n end\n}\n") assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) end def test_rule_body_choice grammar = file(:rule_body) match = grammar.parse('"a" | "b"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Choice, match.value) match = grammar.parse('/./ | /./') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Choice, match.value) assert_equal(1, match.find(:bar).length) assert_equal(2, match.find(:regular_expression).length) assert_equal(0, match.find(:dot).length) match = grammar.parse('("a" | /./)') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Choice, match.value) match = grammar.parse('("a" | "b") <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Choice, match.value) end def test_rule_body_sequence grammar = file(:rule_body) match = grammar.parse('"a" "b"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) match = grammar.parse('/./ /./') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) assert_equal(2, match.find(:regular_expression).length) match = grammar.parse('( "a" "b" ) <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) match = grammar.parse('"a" ("b" | /./)* <Module>') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) match = grammar.parse('"a" ("b" | /./)* {}') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) end def test_precedence grammar = file(:rule_body) # Sequence should bind more tightly than Choice. match = grammar.parse('"a" "b" | "c"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Choice, match.value) # Parentheses should change binding precedence. match = grammar.parse('"a" ("b" | "c")') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Sequence, match.value) # Repeat should bind more tightly than AndPredicate. match = grammar.parse("&'a'+") assert(match) assert_kind_of(Rule, match.value) assert_instance_of(AndPredicate, match.value) end def test_empty grammar = file(:rule_body) match = grammar.parse('') assert(match) end def test_choice grammar = file(:choice) match = grammar.parse('"a" | "b"') assert(match) assert_equal(2, match.rules.length) assert_instance_of(Choice, match.value) match = grammar.parse('"a" | ("b" "c")') assert(match) assert_equal(2, match.rules.length) assert_instance_of(Choice, match.value) end def test_sequence grammar = file(:sequence) match = grammar.parse('"" ""') assert(match) assert_equal(2, match.rules.length) assert_instance_of(Sequence, match.value) match = grammar.parse('"a" "b" "c"') assert(match) assert_equal(3, match.rules.length) assert_instance_of(Sequence, match.value) end def test_expression grammar = file(:expression) match = grammar.parse('"" <Module>') assert(match) assert_kind_of(Rule, match.value) assert_kind_of(Module, match.value.extension) match = grammar.parse('"" {}') assert(match) assert_kind_of(Rule, match.value) assert_kind_of(Module, match.value.extension) match = grammar.parse('"" {} ') assert(match) assert_kind_of(Rule, match.value) assert_kind_of(Module, match.value.extension) end def test_prefix grammar = file(:prefix) match = grammar.parse('&""') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(AndPredicate, match.value) match = grammar.parse('!""') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(NotPredicate, match.value) match = grammar.parse('label:""') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Label, match.value) match = grammar.parse('label :"" ') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Label, match.value) end def test_suffix grammar = file(:suffix) match = grammar.parse('""+') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('""? ') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) match = grammar.parse('""1* ') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Repeat, match.value) end def test_primary grammar = file(:primary) match = grammar.parse('rule_name') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Alias, match.value) match = grammar.parse('"a"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) end ## Lexical syntax def test_require grammar = file(:require) match = grammar.parse('require "some/file"') assert(match) assert_equal('some/file', match.value) match = grammar.parse('require"some/file"') assert(match) assert_equal('some/file', match.value) match = grammar.parse("require 'some/file'") assert(match) assert_equal('some/file', match.value) end def test_include grammar = file(:include) match = grammar.parse('include Module') assert(match) assert_equal(Module, match.value) match = grammar.parse('include ::Module') assert(match) assert_equal(Module, match.value) end def test_root grammar = file(:root) match = grammar.parse('root some_rule') assert(match) assert_equal('some_rule', match.value) assert_raise ParseError do match = grammar.parse('root :a_root') end end def test_rule_name grammar = file(:rule_name) match = grammar.parse('some_rule') assert(match) assert('some_rule', match.value) match = grammar.parse('some_rule ') assert(match) assert('some_rule', match.value) end def test_terminal grammar = file(:terminal) match = grammar.parse('[a-z]') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) match = grammar.parse('.') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) match = grammar.parse('/./') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(Terminal, match.value) end def test_string_terminal grammar = file(:string_terminal) match = grammar.parse("'a'") assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) match = grammar.parse('"a"') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) match = grammar.parse('`a`') assert(match) assert_kind_of(Rule, match.value) assert_instance_of(StringTerminal, match.value) end def test_single_quoted_string grammar = file(:quoted_string) match = grammar.parse("'test'") assert(match) assert_equal('test', match.value) match = grammar.parse("'te\\'st'") assert(match) assert_equal("te'st", match.value) match = grammar.parse("'te\"st'") assert(match) assert_equal('te"st', match.value) end def test_double_quoted_string grammar = file(:quoted_string) match = grammar.parse('"test"') assert(match) assert_equal('test', match.value) match = grammar.parse('"te\\"st"') assert(match) assert_equal('te"st', match.value) match = grammar.parse('"te\'st"') assert(match) assert_equal("te'st", match.value) match = grammar.parse('"\\x26"') assert(match) assert_equal('&', match.value) end def test_case_insensitive_string grammar = file(:case_insensitive_string) match = grammar.parse('`test`') assert(match) assert_equal('test', match.value) match = grammar.parse('`te\\"st`') assert(match) assert_equal('te"st', match.value) match = grammar.parse('`te\`st`') assert(match) assert_equal("te`st", match.value) match = grammar.parse('`\\x26`') assert(match) assert_equal('&', match.value) end def test_character_class grammar = file(:character_class) match = grammar.parse('[_]') assert(match) assert_equal(/\A[_]/, match.value) match = grammar.parse('[a-z]') assert(match) assert_equal(/\A[a-z]/, match.value) match = grammar.parse('[a-z0-9]') assert(match) assert_equal(/\A[a-z0-9]/, match.value) match = grammar.parse('[\[-\]]') assert(match) assert_equal(/\A[\[-\]]/, match.value) match = grammar.parse('[\\x26-\\x29]') assert(match) assert_equal(/\A[\x26-\x29]/, match.value) end def test_dot grammar = file(:dot) match = grammar.parse('.') assert(match) assert_equal(DOT, match.value) end def test_regular_expression grammar = file(:regular_expression) match = grammar.parse('/./') assert(match) assert_equal(/./, match.value) match = grammar.parse('/\\//') assert(match) assert_equal(/\//, match.value) match = grammar.parse('/\\\\/') assert(match) assert_equal(/\\/, match.value) match = grammar.parse('/\\x26/') assert(match) assert_equal(/\x26/, match.value) match = grammar.parse('/a/i') assert(match) assert_equal(/a/i, match.value) end def test_predicate grammar = file(:predicate) match = grammar.parse('&') assert(match) assert_kind_of(Rule, match.value('')) match = grammar.parse('!') assert(match) assert_kind_of(Rule, match.value('')) end def test_and grammar = file(:and) match = grammar.parse('&') assert(match) assert_instance_of(AndPredicate, match.value('')) match = grammar.parse('& ') assert(match) assert_instance_of(AndPredicate, match.value('')) end def test_not grammar = file(:not) match = grammar.parse('!') assert(match) assert_instance_of(NotPredicate, match.value('')) match = grammar.parse('! ') assert(match) assert_instance_of(NotPredicate, match.value('')) end def test_label grammar = file(:label) match = grammar.parse('label:') assert(match) v = match.value('') assert_instance_of(Label, v) assert_equal(:label, v.label) match = grammar.parse('a_label : ') assert(match) v = match.value('') assert_instance_of(Label, v) assert_equal(:a_label, v.label) end def test_tag grammar = file(:tag) match = grammar.parse('<Module>') assert(match) assert_equal(Module, match.value) match = grammar.parse('< Module >') assert(match) assert_equal(Module, match.value) match = grammar.parse('<Module> ') assert(match) assert_equal(Module, match.value) end def test_block grammar = file(:block) match = grammar.parse('{}') assert(match) assert(match.value) match = grammar.parse("{} \n") assert(match) assert(match.value) match = grammar.parse('{ 2 }') assert(match) assert(match.value) assert_equal(2, match.value.call) match = grammar.parse("{ {:a => :b}\n}") assert(match) assert(match.value) assert_equal({:a => :b}, match.value.call) match = grammar.parse("{|b|\n Proc.new(&b)\n}") assert(match) assert(match.value) b = match.value.call(Proc.new { :hi }) assert(b) assert_equal(:hi, b.call) match = grammar.parse("{\n def value\n 'a'\n end\n} ") assert(match) assert(match.value) end def test_block_with_interpolation grammar = file(:block) match = grammar.parse('{ "#{number}" }') assert(match) assert(match.value) end def test_repeat grammar = file(:repeat) match = grammar.parse('?') assert(match) assert_instance_of(Repeat, match.wrap('')) match = grammar.parse('+') assert(match) assert_instance_of(Repeat, match.wrap('')) match = grammar.parse('*') assert(match) assert_instance_of(Repeat, match.wrap('')) end def test_question grammar = file(:question) match = grammar.parse('?') assert(match) assert_equal(0, match.min) assert_equal(1, match.max) match = grammar.parse('? ') assert(match) assert_equal(0, match.min) assert_equal(1, match.max) end def test_plus grammar = file(:plus) match = grammar.parse('+') assert(match) assert_equal(1, match.min) assert_equal(Infinity, match.max) match = grammar.parse('+ ') assert(match) assert_equal(1, match.min) assert_equal(Infinity, match.max) end def test_repeat grammar = file(:repeat) match = grammar.parse('*') assert(match) assert_equal(0, match.min) assert_equal(Infinity, match.max) match = grammar.parse('1*') assert(match) assert_equal(1, match.min) assert_equal(Infinity, match.max) match = grammar.parse('*2') assert(match) assert_equal(0, match.min) assert_equal(2, match.max) match = grammar.parse('1*2') assert(match) assert_equal(1, match.min) assert_equal(2, match.max) match = grammar.parse('1*2 ') assert(match) assert_equal(1, match.min) assert_equal(2, match.max) end def test_module_name grammar = file(:module_name) match = grammar.parse('Module') assert(match) match = grammar.parse('::Proc') assert(match) end def test_constant grammar = file(:constant) match = grammar.parse('Math') assert(match) assert_raise ParseError do match = grammar.parse('math') end end def test_comment grammar = file(:comment) match = grammar.parse('# A comment.') assert(match) assert_equal('# A comment.', match) end end
require 'spec_helper' describe PlayerHand do let(:player) { Player.new } let(:table) { GameTable.new } context '#hand_rank' do context 'given a straight flush' do context 'when there is not any ace' do it 'should return a proper hand rank' do hand = PlayerHand.new('straight_flush') %w(2 3 4 5 6).each do |face| hand.add_card Card.new('H', face) end expect(hand.hand_rank).to eq 20 end end context 'when an ace as a high card in straight' do it 'should return a proper hand rank' do hand = PlayerHand.new('straight_flush') %w(T J Q K A).each do |face| hand.add_card Card.new('H', face) end expect(hand.hand_rank).to eq 60 end end context 'when an ace as a low card in straight' do it 'should return a proper hand rank' do hand = PlayerHand.new('straight_flush') %w(A 2 3 4 5).each do |face| hand.add_card Card.new('H', face) end expect(hand.hand_rank).to eq 15 end end end end end
require 'spec_helper' describe Request::Rack, '#protocol' do subject { object.protocol } Request::Protocol::ALL.each do |protocol| it_should_behave_like 'a rack env accessor' do let(:object) { described_class.new(env) } let(:rack_key) { 'rack.url_scheme' } let(:rack_key_value) { protocol.name } let(:expected_value) { protocol } end end end
def substrings(sentence, dict) result = Hash.new(0) sentence.split.each do |word| dict.reduce(result) do |acc, val| if word.upcase.include? val.upcase acc[val] += 1 end acc end end result end # TESTS # dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"] # p substrings("below", dictionary) # p substrings("Howdy partner, sit down! How's it going?", dictionary)
class Oystercard attr_reader :balance def initialize @balance = 0 end def top_up (money) @balance += money return @balance end end
ActiveAdmin.register Reservation do permit_params :date_from, :date_to, :total_price, :client, :room, :message actions :show, :index, :destroy index do selectable_column column :date_from do |r| r.date_from.strftime("%d-%m-%y %A") end column :date_to do |r| r.date_to.strftime("%d-%m-%y %A") end column :client column :room column :message column :prepayment column :prepayment_status do |reservation| link_to("#{ reservation.prepaid ? "Оплачено" : "Не оплачено" }", reservations_prepaid1_admin_reservation_url(reservation.id), method: :post) end column :total_price column :payment_status do |reservation| link_to("#{ reservation.paid ? "Оплачено" : "Не оплачено" }", reservations_paid1_admin_reservation_url(reservation.id), method: :post) end column :created_at actions end show do attributes_table do row :date_from do |r| r.date_from.strftime("%d-%m-%y %A") end row :date_to do |r| r.date_to.strftime("%d-%m-%y %A") end row :total_price row :client row :room row :message end panel :dates do table_for(reservation.room_dates.order(:date)) do column :date do |room_date| if room_date.date.strftime("%A") == "Saturday" || room_date.date.strftime("%A") == "Sunday" strong do link_to(room_date.date.strftime("%d-%m-%y %A"), admin_room_date_url(room_date.id)) end else link_to(room_date.date.strftime("%d-%m-%y %A"), admin_room_date_url(room_date.id)) end end end end end member_action :reservations_paid, method: :post do begin ActiveRecord::Base.transaction do if !resource.prepaid resource.update!(prepaid: !resource.prepaid) end resource.update!(paid: !resource.paid) end rescue end redirect_to admin_client_url(resource.client.id) end member_action :reservations_prepaid, method: :post do begin ActiveRecord::Base.transaction do resource.update!(prepaid: !resource.prepaid) end rescue end redirect_to admin_client_url(resource.client.id) end member_action :reservations_paid1, method: :post do begin ActiveRecord::Base.transaction do if !resource.prepaid resource.update!(prepaid: !resource.prepaid) end resource.update!(paid: !resource.paid) end rescue end redirect_to admin_reservations_url end member_action :reservations_prepaid1, method: :post do begin ActiveRecord::Base.transaction do resource.update!(prepaid: !resource.prepaid) end rescue end redirect_to admin_reservations_url end end
require File.join(File.dirname(__FILE__), "../spec_helper.rb") describe Milksteak::Fragment do it "should use the fragments/ folder" do Milksteak::Fragment.folder.should == "fragments" end it "should allow sub-dir fragments" do f = File.open(File.join(File.dirname(__FILE__), "../fixtures/objs/sample_obj.yml"), "r") f.stub(:save).and_return true File.should_receive(:new).with("/tmp/milk_site/fragments/section/sub-folder/fragment-name.yml", "r").and_return f c = Milksteak::Fragment.load("section/sub-folder/fragment-name") end it "should render a fragment with params" do f = File.open(File.join(File.dirname(__FILE__), "../fixtures/objs/sample_obj_with_params.yml"), "r") f.stub(:save).and_return true File.should_receive(:new).with("/tmp/milk_site/fragments/section/sub-folder/fragment-name.yml", "r").and_return f c = Milksteak::Fragment.render("section/sub-folder/fragment-name", {:foo => "Testing"}) c.should == "This is a Test Object. Testing\n" end end
class CreateShipments < ActiveRecord::Migration[5.0] def change create_table :shipments do |t| t.references :company, foreign_key: true t.string :destination_country t.string :origin_country t.string :tracking_number t.string :slug t.timestamps end end end
module CurrentCart private def set_cart Rails.logger.debug 'set_cart looking for cart:' + session[:cart_id].to_s @cart = Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound @cart = Cart.create session[:cart_id] = @cart.id Rails.logger.debug 'set_cart created cart cart:' + @cart.id.to_s end end
class UpvoteIndex < ActiveRecord::Migration[5.2] def change add_index :upvotes, [:upvoteable_id, :upvoteable_type, :user_id], unique: true end end
class CreateShipments < ActiveRecord::Migration def change create_table :shipments do |t| t.integer :order_id, null: false t.string :external_id, null: false t.date :ship_date, null: false t.integer :quantity, null: false t.decimal :weight t.decimal :freight_charge t.decimal :handling_charge t.boolean :collect_freight, null: false, default: false t.string :freight_responsibility t.string :cancel_code t.string :cancel_reason t.timestamps null: false t.index :order_id t.index :external_id t.index :ship_date end end end
class AdminAuthController < AdminController skip_before_action :require_sysop, only: [:login, :logout, :forgot_password, :send_reset_password_email] def login if request.post? || request.put? @sysop = Sysop.find_by_name(params[:name]).try(:authenticate, params[:password]) if @sysop @sysop.set_token @sysop.save cookies[:admin_token] = @sysop.token end end # Either we just logged in or someone is doing a GET on login when already # logged in. if @sysop redirect_to_default elsif params[:name].present? flash.now[:alert] = 'Incorrect name or password' end end def logout cookies[:admin_token] = nil redirect_to :admin_login end def forgot_password end def send_reset_password_email login = params[:login] sysop = Sysop.find_by_name(login) || Sysop.find_by_email(login) if sysop.try(:email) AdminMailer.password_reset(sysop).deliver! else flash.now[:alert] = "Account either was not found or does not have an email address associated. Please contact an admin." render 'forgot_password' end end def reset_password end def update_password current_sysop.password = current_sysop.password_confirmation = params[:password] if current_sysop.password.blank? flash.now[:alert] = "Password must not be blank." render 'reset_password' return end if current_sysop.save flash[:notice] = "Password updated." redirect_to_default else flash.now[:alert] = current_sysop.errors.full_messages render 'reset_password' end end private def redirect_to_default if @sysop.superuser? redirect_to :admin elsif @sysop.permissions.members.any? redirect_to "admin_#{@sysop.permissions.members.first}".to_sym end end end
class CreateSectionSteps < ActiveRecord::Migration def change create_table :section_steps do |t| t.references :section, index: true t.references :question, index: true t.integer :row_order t.string :type t.string :headline t.text :description t.string :template t.timestamps end end end
class CreateStockproductfotos < ActiveRecord::Migration def change create_table :stockproductfotos do |t| t.references :stockproduct, index: true t.timestamps null: false end add_foreign_key :stockproductfotos, :stockproducts end end
Given(/^I am on the home page$/) do visit "/" end Given(/^I am on "(.*?)"$/) do |path| visit path end Given(/I am not logged in$/) do page.should have_content "Login" end When(/^I fill in "(.*?)" with "(.*?)"$/) do |field, value| fill_in field.underscore, with: value end When(/^I confirm "(.*?)" with "(.*?)"$/) do |field, value| fill_in "#{field.underscore}_confirmation", with: value end When(/^I press "(.*?)"$/) do |label| click_on label end When(/^I press on the "(.*?)" button$/) do |title| find("button[title=\"#{title}\"]").click end Then(/^I should see "(.*?)"$/) do |text| page.should have_content text end Then(/^I should be redirected to "(.*?)"$/) do |path| expect(page.current_path).to eq(path) end
class Invoice < ActiveRecord::Base attr_accessor :new_state include AASM STATUS_NAME = %w(active draft closed) CURRENCIES = %w(CLP UF USD) DTE_TYPES = {taxed_invoice: 33, untaxed_invoice: 34, credit_note: 61} TAX_RATE = 19.0 self.per_page = 10 # Asociatons belongs_to :account belongs_to :company has_many :invoice_items, dependent: :destroy has_one :reminder, as: :remindable, dependent: :destroy has_many :attachments, as: :attachable, dependent: :destroy has_many :comments, as: :commentable, dependent: :destroy has_many :dtes, dependent: :destroy belongs_to :contact accepts_nested_attributes_for :invoice_items, :allow_destroy => true accepts_nested_attributes_for :reminder, :allow_destroy => true accepts_nested_attributes_for :attachments, :allow_destroy => true accepts_nested_attributes_for :dtes, :allow_destroy => true #Callbacks before_validation :set_due_date_and_reminder, if: :draft? before_validation :perform_calculations, if: :amounts_changed? before_update :close_invoice_if_total_payed_match_total after_save :update_items_number after_save :generate_dte, if: :may_generate_dte? # Solo borramos si esta en Draft before_destroy {|record| return false unless record.draft? } # Validations validates_presence_of :company_id, :subject, :active_date, :due_days, :currency, :currency_convertion_rate # validates_numericality_of :contact_id, :greater_than => 0, message: "no existe" validates_numericality_of :due_days validates_numericality_of :total, :greater_than => 0 validates_numericality_of :currency_convertion_rate, :greater_than => 0 validates_numericality_of :net_total, :greater_than => 0 validates_numericality_of :total_payed, :on => :update, less_than_or_equal_to: ->(invoice) { invoice.total } validates :invoice_items, length: {minimum: 1, message: "Debe tener al menos un Item"} #validate :invoice_ready_for_payment validates_presence_of :number, unless: :draft? validates_numericality_of :number, unless: :draft? validate :number_uniqueness validates :contact, presence: true, unless: :draft? #Scopes #default_scope { where(account_id: Account.current_id) } scope :for_account, ->(account_id) {where(:id => account_id)} scope :active, ->() {where("aasm_state = ? and due_date >= ?", "active", Date.today )} scope :due, ->() {where("aasm_state = ? and due_date < ?", "active", Date.today )} scope :open, ->() {where("aasm_state = ?", "active")} scope :draft, ->() {where(aasm_state: "draft")} scope :not_draft, ->() {where.not(aasm_state: "draft")} scope :closed, ->() {where(aasm_state: "closed")} scope :cancelled, ->() {where(aasm_state: "cancelled")} scope :taxed, ->() {where(taxed: true)} scope :not_taxed, ->() {where(taxed: false)} scope :all_invoices, ->() {all} # States aasm :create_scopes => false, :whiny_transitions => false do state :draft, initial: true state :active state :closed state :cancelled event :active, after: Proc.new { run_activation_jobs } do transitions from: :draft, to: :active, guard: :ready_for_activation? end event :cancel do transitions from: :active, to: :cancelled end event :close do transitions from: :active, to: :closed, guard: :is_really_payed? close_date = Date.today end end def all_attachments [attachments + all_comments_attachments].flatten end def all_comments_attachments comments.includes(:attachments).map {|c| c.attachments.flatten if c.attachments.any? }.compact.flatten end def last_comment comments.last end def cond_pago "#{due_days} días" end def run_activation_jobs update_active_date update_due_date # schedule_reminder # activation_notification_email end def run_cancelation_jobs generate_dte(DTE_TYPES[:credit_note]) end def update_due_date self.due_date = active_date + due_days end def update_active_date self.active_date = Date.today end def schedule_reminder reminder = update_reminder reminder.schedule! end def activation_notification_email InvoiceMailer.delay.activation_notification(self) end def change_status(params) new_state = params.delete :new_state return false unless STATUS_NAME.include? new_state.downcase unless send("may_#{new_state}?") update_attributes(params) end self.send(new_state) save end def clone! source_invoice = self.reset_for_cloning new_invoice = source_invoice.dup new_invoice.invoice_items << source_invoice.clone_items new_invoice end def clone_items invoice_items_tmp = Array.new return false if invoice_items.size < 0 invoice_items.each_with_index do |line, index| line.invoice_id = nil invoice_items_tmp << line.dup end invoice_items_tmp end def reset_for_cloning self.active_date = Date.today self.aasm_state = "draft" self.total_payed = 0 self.number = nil self end def company_name= end def company_rut company.rut end def company_name return "" if company_id.nil? company.name end def company_address company.address end def company_province company.province end def company_industry company.industry end def company_contacts return [] unless company_has_contact? company.contacts end def company_has_contact? return false if company.nil? company.has_contacts? end def has_valid_number? account.check_invoice_number_availability(number,taxed) end def has_dte? dtes.any? end def has_payment? total_payed > 0 end def has_dte_invoice? !dte_invoice.nil? end def notification_date return reminder.notification_date unless (reminder.nil? || reminder.notification_date.nil?) Date.today + 30 end def has_contact? !contact.nil? && (contact.company_id == company_id) end def has_number? !number.nil? end def has_invoice_attachment? attachments.where(category: "invoice").any? end def in_clp? currency.downcase == "clp" end def price_precision return 0 if in_clp? 3 end def dte_attachment attachments.where(category: "invoice").first end def dte_attachment_url dte_attachment.resource.url end def has_debt? total_payed.to_i > 0 && total_payed.to_i < total.to_i end def debt total - total_payed end def contact_name return "" unless has_contact? contact.full_name end def contact_name_titleize contact_name.titleize end def is_really_payed? return total_payed.to_i >= total.to_i end def invoices_for_account begin account.invoices rescue Exception => e raise "The invoice must belong to an account" end end def last_used_number account.invoice_last_used_number taxed? end def may_edit? draft? || active? end def may_generate_dte? return false unless account.e_invoice_enabled? return false if draft? return false if closed? return false if (cancelled? && dte_invoice.nil?) # Si no tiene un dte factura true end def status return "draft" if new_record? return "due" if is_due? return "processing_dte" if has_any_processing_dte? aasm_state end # Esta vencida si se pasó la fecha y está activa def is_due? due_date < Date.today && active? end def dte_invoice dtes.e_invoice.first end def has_any_processing_dte? return false unless has_dte? dtes.not_processed.any? end def late_days (Date.today - due_date).to_i end def self.currencies CURRENCIES end def suggested_number return last_used_number + 1 end def update_invoice(params) update_attributes(params) end def default_reminder_subject number_string = number.to_s || "NA" "Recordatorio vencimiento Factura #{self.number}" end # def reminder # reminders.first # end def pay(amount) return false unless active? self.total_payed = amount.to_s.gsub(/[^\d]/,"").to_i + total_payed.to_i self.save end def payment_days (close_date - due_date).to_i end def record_dte_result(dte) dte = dtes.reload.find(dte) process_dte_comment(dte) process_dte_pdf(dte) end def process_dte_comment(dte) message = dte.result_message comment = comments.new_from_system({message: message, account_users_ids: account_users_ids, private: true}) comment.save end def process_dte_pdf(dte) return unless dte.ok? dte_pdf = attachments.new_from_dte({file: dte.pdf_file, name: "#{dte.folio} #{dte.dte_type}"}) dte_pdf.save end def set_due_date_and_reminder date = active_date || Date.today self.due_date = date + due_days self.update_reminder end def update_reminder self.reminder ||= build_reminder(due_date: due_date) self.reminder.subject = default_reminder_subject self.reminder.notification_date = nil self.reminder.due_date = due_date self.set_reminder_contacts reminder end def set_reminder_contacts reminder.account_users_ids = account_users_ids reminder.company_users_ids = company_users_ids end def account_users_ids account.users.map {|u| u.id} end def amounts_changed? return true if draft? # Es diferente la nueva suma de items que el total guardado? return original_currency_total.to_i != calculate_original_currency_total_from_invoice_items.to_i # Hubo en cambio en los montos si cambio el total en moneda original !changes["original_currency_total"].nil? end %w(rut name industry industry_code address city province).each do |m| define_method("account_#{m}".to_sym) { account.send(m) } end def company_users_ids return [] if contact.nil? [contact.id] end def calculate_tax self.total = net_total return unless self.taxed? self.tax_rate = TAX_RATE self.total = (net_total * (1 + TAX_RATE/100)).round self.tax_total = total - net_total end def calculate_net_total_from_currency_total self.net_total = original_currency_total * currency_convertion_rate end def calculate_original_currency_total_from_invoice_items self.invoice_items = invoice_items_round_price if currency.downcase == "clp" items_sum = invoice_items.reject(&:marked_for_destruction?).map(&:calculate_total).sum self.original_currency_total = items_sum end def invoice_items_round_price invoice_items.each do |invoice_item| invoice_item.price = invoice_item.price.round end invoice_items end # Cerrar la factura si el monto de pago calza con el total de la factura def close_invoice_if_total_payed_match_total return unless total_payed_changed? return unless is_really_payed? self.close_date = Date.today self.close end # Solo se debería poder abonar si la factura esta activa def invoice_ready_for_payment return if self.active? return if total_payed == 0 errors.add(:total_payed, "Sólo se puede pagar cuando la venta está activa") end # Búsqueda simple def self.search(params) params = Hash.new(nil) if params.nil? query_items = params["query_items"].nil? ? {} : params["query_items"].delete_if {|k,v| v.empty?} start_date = Date.parse(query_items.delete("start_date")) unless query_items["start_date"].nil? end_date = Date.parse(query_items.delete("end_date")) unless query_items["end_date"].nil? status = params["status"].nil? ? "all_invoices" : params["status"] total = params["total"].to_i sorted_by = (params["sorted_by"].nil? || params["sorted_by"].empty?) ? "active_date" : params["sorted_by"] sorted_direction = (params["sorted_direction"].nil? || params["sorted_direction"].empty?) ? "DESC" : params["sorted_direction"] results = send(status).where(query_items) if start_date && end_date.nil? results = results.where("active_date >= ?", start_date) elsif start_date.nil? && end_date results = results.where("active_date <= ?", end_date) elsif start_date && end_date results = results.where(active_date: start_date..end_date) end unless total < 1 results = results.where(total: (total.to_i - 1)..(total.to_i + 1)) end results.order("#{sorted_by} #{sorted_direction}").includes(:company) end # Return the sum of the totals def self.total_due due.to_a.sum(&:total).to_i end def self.total_active active.to_a.sum(&:total).to_i end def self.total_closed closed.to_a.sum(&:total).to_i end def self.total_draft draft.to_a.sum(&:total).to_i end def perform_calculations set_currency_convertion_rate(currency.downcase) calculate_original_currency_total_from_invoice_items calculate_net_total_from_currency_total calculate_tax end def ready_for_activation? errors.add(:number, "El número ya está usado") unless has_valid_number? errors.add(:contact, "Debe asignar un contacto") unless has_contact? return (has_contact? && has_valid_number? && valid?) end def set_currency_convertion_rate(indicador) indicador = "dolar" if indicador == "usd" self.currency_convertion_rate ||= 1 indicadores = Indicadores::Chile.new begin self.currency_convertion_rate = indicadores.send(indicador) rescue Exception => e end end def update_items_number invoice_items.each_with_index do |item,index| item.number = index + 1 item.save end end def number_uniqueness result = account.invoices.not_draft.where(taxed: self.taxed, number: self.number) return unless result.any? return if result.first.id == id errors.add(:number, "El número ya está usado") end def generate_dte tipo_dte = dte_to_generate dte = Dte.prepare_from_invoice(self, tipo_dte) dte.save end def dte_to_generate return DTE_TYPES[:credit_note] if cancelled? # Esta nota de credito por correccion de monto return DTE_TYPES[:credit_note] if (active? && has_dte_invoice?) # Solo nos interesa si es NC nil end end
require './lib/random_variable' require './lib/word_tokeniser' require 'facets' class Ngram attr_accessor :n, :tokeniser def initialize(n) @tokeniser = WordTokeniser.new @n = n @frequencies_stale = true end def length ngrams.length end def ngrams @ngrams ||= [] end def frequency(ngram) frequencies[ngram] end def frequencies if @frequencies_stale @frequencies_stale = false @frequencies = ngrams.frequency else @frequencies end end def add_ngrams(more_ngrams) @ngrams = ngrams + more_ngrams @frequencies_stale = true end def add(sentence) add_ngrams(sliding(n, tokeniser.tokenise(sentence))) end def successors(ngram) frequencies.select do |potential_successor, freq| overlap(ngram, potential_successor) end end def random_ngram ngrams.sample end def successor(ngram) transition = RandomVariable.new(successors(ngram).map { |succ, freq| [freq / length , succ ]}) transition.get end def get(k) ngram_sequence = [random_ngram] token_sequence = random_ngram (k-1).times do succ = successor(ngram_sequence.last) succ ||= random_ngram ngram_sequence.push(succ) token_sequence.push(succ.last) end token_sequence end private def overlap(ngram_a, ngram_b) ngram_a.drop(1) == ngram_b.take(n - 1) end def sliding(n, array) windows = array.length - n + 1 (0 .. windows - 1).map do |i| array.drop(i).take(n) end end end
require "vipera/config" require "vipera/sources/sources" def main if ARGV.count < 1 then raise "Invalid arguments!" end module_name = ARGV[0] config = read_config xcodeproj = read_xcodeproj config source_map = Sources::create_sources_map module_name Sources::generate_sources module_name, xcodeproj, read_config, source_map xcodeproj.save puts "Module #{module_name} generated!" end def run_main begin main rescue StandardError => e puts e.message end end
class DogsController < ApplicationController def new @dog = Dog.new end def show @dogs = Dog.all end def create @dog = Dog.new(dog_params) if @dog.save redirect_to @dog, notice: 'You let the dogz out' else render new_dog_path end # respond_to do |format| # if @dog.save # format.html { redirect_to action: 'new', notice: 'Cform was successfully created.' } # format.json { render action: 'new', status: :created, location: @cform } # else # format.html { render action: 'new' } # format.json { render json: @dog.errors, status: :unprocessable_entity } # end # end end private def dog_params params.require(:dog).permit(:email, :dog_name, :first_name, :last_name) end end
require 'uri' require 'net/http' class Boggle NEIGHBORS_DATA = [ [-1,-1, "↖"], [-1, 0, "↑"], [-1, 1, "↗"], [0, -1, "←"], [0, 1, "→"], [1, -1, "↙"], [1, 0, "↓"], [1, 1, "↘"], ] def initialize(args = {}) @result = [] @boggle = args[:boggle] @lengthc = @boggle[0].size @lengthr = @boggle.size puts("Given board") puts @boggle.to_a.map(&:inspect) # Initialize trie datastructure @trie_node = {'valid'=> false, 'next'=> {}} end def check_word word @english_word = [] @english_word << word trie_node = build_trie(@english_word, @trie_node) (0..@lengthr-1).each_with_index do |r, ri| (0..@lengthc-1).each_with_index do |c, ci| letter = @boggle[ri][ci] dfs(ri, ci, [], trie_node, '', "directions from #{letter} go") end end return @result end def gen_trie(word, node) return unless word if !node.key?(word[0]) node[word[0]] = {'valid' => word.length == 1, 'next' => {}} end return if word[1..-1] == "" gen_trie(word[1..-1], node[word[0]]) end def build_trie(words, trie) # puts "Builds trie data structure from the list of words given" words.each do |word| gen_trie(word, trie) end return trie end def get_neighbors(r, c) # puts "Returns the neighbors for a given co-ordinates" n = [] NEIGHBORS_DATA.each do |neigh| new_r = r + neigh[0] new_c = c + neigh[1] next if (new_r >= @lengthr) || (new_c >= @lengthc) || (new_r < 0) || (new_c < 0) n.append [new_r, new_c, neigh[2]] end return n end def dfs(r, c, visited, trie, now_word, direction) # "Scan the graph using DFS" if visited.include?([r, c]) return end letter = @boggle[r][c] visited.append [r, c] if trie.key?(letter) now_word += letter if trie[letter]['valid'] puts "Found #{now_word} #{direction}" @result << "Found #{now_word} #{direction}" end neighbors = get_neighbors(r, c) neighbors.each do |n| dfs(n[0], n[1], visited[0..], trie[letter], now_word, direction + " " + n[2]) end end end end
class Game def initialize(display, screen_manager, input) raise 'Unable to initialize game when display is nil' unless display raise 'Unable to initialize game when screen manager is nil' unless screen_manager raise 'Unable to initalize game when input is nil' unless input @display = display @screen_manager = screen_manager @input = input end def start raise 'Unable to start game when screen_manager is empty' if @screen_manager.empty? quit = false while !quit @screen_manager.render @display @display.render quit = @screen_manager.update @input end end end
Pod::Spec.new do |ff| ff.name = "ff-ios-client-sdk" ff.version = "1.1.0" ff.summary = "iOS SDK for Harness Feature Flags Management" ff.description = <<-DESC Feature Flag Management platform from Harness. iOS SDK can be used to integrate with the platform in your iOS applications. DESC ff.homepage = "https://github.com/drone/ff-ios-client-sdk" ff.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" } ff.author = "Harness Inc" ff.platform = :ios, "10.0" ff.ios.deployment_target = "10.0" ff.source = { :git => ff.homepage + '.git', :tag => ff.version } ff.source_files = "Sources", "Sources/ff-ios-client-sdk/**/*.{h,m,swift}" ff.public_header_files = "Sources/ff-ios-client-sdk/**/*.{h}" ff.requires_arc = true ff.swift_versions = ['5.0', '5.1', '5.2', '5.3'] end
class Forum < ActiveRecord::Base attr_accessible :description, :title, :topic_id, :user_id #association belongs_to :topic belongs_to :user has_many :posts #validation validates :topic_id, :presence => true validates :user_id, :presence => true validates :title, :presence => true, :uniqueness => true validates :description, :presence => true validates_associated :posts #callback before_validation :validate_user, :validate_topic # validate_user is a function it's generete the error if User is not present in user table def validate_user errors.add(:user_id, 'user not presence') if User.find_by_id( self[:user_id] ) == nil end # validate_topic is a function it's generate the error if chapter topic in not present in the topic table def validate_topic errors.add(:topic_id, 'Topic not presence') if Topic.find_by_id( self[:topic_id] ) == nil end end
require 'spec_helper' describe Puppet::Type.type(:firewalld_direct_chain) do before do Puppet::Provider::Firewalld.any_instance.stubs(:state).returns(:true) # rubocop:disable RSpec/AnyInstance end context 'with no params' do describe 'when validating attributes' do [:name, :inet_protocol, :table].each do |param| it "should have a #{param} parameter" do expect(described_class.attrtype(param)).to eq(:param) end end end describe 'namevar validation' do it 'has :name, :inet_protocol and :table as its namevars' do expect(described_class.key_attributes).to eq([:name, :inet_protocol, :table]) end it 'uses the title as the name when non-delimited' do resource = described_class.new(title: 'LOG_DROPS', table: 'filter') expect(resource.name).to eq('LOG_DROPS') end context 'colon delimited title pattern' do let(:resource) { described_class.new(title: 'ipv4:filter:LOG_DROPS') } it 'sets resource `name` correctly' do expect(resource.name).to eq('LOG_DROPS') end it 'sets resource `table` parameter correctly' do expect(resource[:table]).to eq('filter') end it 'sets resource `inet_protocol` parameter correctly' do expect(resource[:inet_protocol]).to eq('ipv4') end end it 'defaults inet_protocol to ipv4' do resource = described_class.new(title: 'LOG_DROPS', table: 'filter') expect(resource[:inet_protocol]).to eq('ipv4') end it 'raises an error if given malformed inet protocol' do expect { described_class.new(title: '4vpi:filter:LOG_DROPS') }.to raise_error(Puppet::Error) end end end end
# Output represents one of the outputs of an operation in the graph. Has a # DataType (and eventually a Shape). May be passed as an input argument to a # function for adding operations to a graph, or to a Session's Run() method to # fetch that output as a tensor. class Tensorflow::Output attr_accessor :index, :operation # @!attribute index # Index specifies the index of the output within the Operation. # @!attribute operation # Operation is the Operation that produces this Output. def c Tensorflow.input(operation.c, index) end # DataType returns the type of elements in the tensor produced by p. def dataType Tensorflow::TF_OperationOutputType(c) end # Shape returns the (possibly incomplete) shape of the tensor produced p. def shape status = Tensorflow::Status.new port = c ndims = Tensorflow::TF_GraphGetTensorNumDims(operation.g.c, port, status.c) raise 'Operation improperly specified.' if status.code != 0 # This should not be possible since an error only occurs if # the operation does not belong to the graph. It should not # be possible to construct such an Operation object. return nil if ndims < 0 return [] if ndims == 0 c_array = Tensorflow::Long_long.new(ndims) Tensorflow::TF_GraphGetTensorShape(operation.g.c, port, c_array, ndims, status.c) dimension_array = [] (0..ndims - 1).each do |i| dimension_array.push(c_array[i]) end dimension_array end end # Operation that has been added to the graph. class Tensorflow::Operation attr_accessor :c, :g # @!attribute c # contains the graph representation. # @!attribute g # A reference to the Graph to prevent it from being GCed while the Operation is still alive. def initialize(c_representation, graph) self.c = c_representation self.g = graph end # Name returns the name of the operation. def name Tensorflow::TF_OperationName(c) end # Type returns the name of the operator used by this operation. def type Tensorflow::TF_OperationOpType(c) end # NumOutputs returns the number of outputs of op. def num_outputs Tensorflow::TF_OperationNumOutputs(c) end # OutputListSize returns the size of the list of Outputs that is produced by a # named output of op. # # An Operation has multiple named outputs, each of which produces either # a single tensor or a list of tensors. This method returns the size of # the list of tensors for a specific output of the operation, identified # by its name. def output_list_size(output) cname = CString(output) status = Tensorflow::Status.new Tensorflow::TF_OperationOutputListLength(c, cname, status.c) end # Output returns the i-th output of op. def output(i) out = Tensorflow::Output.new out.operation = self out.index = i out end end # Input is the interface for specifying inputs to an operation being added to # a Graph. # # Operations can have multiple inputs, each of which could be either a tensor # produced by another operation (an Output object), or a list of tensors # produced by other operations (an OutputList). Thus, this interface is # implemented by both Output and OutputList. # # See OpSpec.Input for more information. class Tensorflow::Input attr_accessor :Index, :Operations def initialize end end
class Stockphoto < ActiveRecord::Base belongs_to :stockproduct has_attached_file :photo, :styles => { :medium => "600x600>", :thumb => "100x100>", :large => "1000x1000" }, :storage => :s3, :s3_protocol => :https, :s3_credentials => { :bucket => ENV['S3_BUCKET'], :access_key_id => ENV['AWS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'] } validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/ end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? before_action :count_unread, except: [:create] # before_action :set_locale protect_from_forgery with: :exception rescue_from CanCan::AccessDenied do |exception| redirect_to main_app.root_url, :alert => exception.message end def set_locale I18n.locale = request.compatible_language_from ["uk", "ru", "de", "en","pt"] end def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name,:organization,:gender,:user_type,:about_me,:profile_picture]) end def count_unread @count = [] if current_user user_chats = current_user.chats.includes(:messages) user_chats.each do |chat| @count << chat.messages.where.not(user_id: current_user.id,read: true).count end @count = @count.sum end end end
class TopsController < ApplicationController def index @most_viewed = Recipe.order('impressions_count DESC').take(3) end end
require 'eb_ruby_client/resource/venue' RSpec.describe EbRubyClient::Resource::Venue do let(:address_data) {{ "address_1" => "1 Hyde Park", "city" => "London" }} let(:data) {{ "name" => "Betty's house", "address" => address_data, "resource_uri" => "https://athing", "id" => "12345", "latitude" => "54.4", "longitude" => "-54.4" }} subject(:venue) { EbRubyClient::Resource::Venue.new(data) } describe "initialize" do it "sets the name" do expect(venue.name).to eq("Betty's house") end it "sets the resource_uri" do expect(venue.resource_uri).to eq("https://athing") end it "sets the id" do expect(venue.id).to eq("12345") end it "sets the latitude" do expect(venue.latitude).to eq("54.4") end it "sets the longitude" do expect(venue.longitude).to eq("-54.4") end end describe "address" do it "creates an address resource" do address = double(EbRubyClient::Resource::Address) expect(EbRubyClient::Resource::Address).to receive(:new). with(address_data).and_return(address) expect(venue.address).to be(address) end end describe "#to_data" do subject(:venue_data) { venue.to_data } it "includes the name" do expect(venue_data["venue.name"]).to eq("Betty's house") end it "includes the address" do expect(venue_data["venue.address.address_1"]).to eq(venue.address.address_1) expect(venue_data["venue.address.city"]).to eq(venue.address.city) end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'tzinfo/timezone_definition' module TZInfo module Definitions module America module Caracas include TimezoneDefinition timezone 'America/Caracas' do |tz| tz.offset :o0, -16064, 0, :LMT tz.offset :o1, -16060, 0, :CMT tz.offset :o2, -16200, 0, :VET tz.offset :o3, -14400, 0, :VET tz.transition 1890, 1, :o1, 1627673863, 675 tz.transition 1912, 2, :o2, 10452001043, 4320 tz.transition 1965, 1, :o3, 39020187, 16 tz.transition 2007, 12, :o2, 1197183600 end end end end end
$:.push File.expand_path("../lib", __FILE__) description = <<TEXT Sinatra app that drives the delcom indicator light TEXT Gem::Specification.new do |s| s.name = "indicator_delcom" s.summary = %q{Sinatra app that drives the delcom indicator light} s.description = description s.homepage = "http://github.com/playup/indicator" s.authors = ["PlayUp Devops"] s.email = ["devops@playup.com"] s.version = '0.0.4' s.platform = Gem::Platform::RUBY s.add_runtime_dependency 'sinatra' , '1.0' s.add_runtime_dependency 'haml' , '2.2.23' s.add_runtime_dependency 'ruby-usb' , '0.1.3' s.add_runtime_dependency 'json' s.add_development_dependency 'rake', '~> 0.9.2' s.require_paths = ["lib"] s.files = Dir["lib/*", "init.d", "README.md", "LICENSE"] s.executables = ["indicatord", "jenkins_light"] end
class Video < ActiveRecord::Base belongs_to :category has_many :reviews, -> { order("created_at DESC") } delegate :label, to: :category, prefix: true validates_presence_of :title, :description def average_rating ratings = reviews.map { |review| review.rating } (ratings.sum / ratings.count.to_f).round rescue 0 end def self.search_by_title(search_term) return [] if search_term.blank? where('title like ?', "%#{search_term}%").order("created_at DESC") end end
class Types::ArticleAttributes < Types::BaseInputObject description 'Attributes for article' argument :title, String, 'Title for the post article', required: true argument :body, String, 'Body for the post article', required: true end
# encoding: utf-8 # rubocop:disable SymbolName module Rubocop module Cop module Style # Checks that block braces have or don't have surrounding space depending # on configuration. For blocks taking parameters, it checks that the left # brace has or doesn't have trailing space depending on configuration. class SpaceAroundBlockBraces < Cop include SurroundingSpace def investigate(processed_source) return unless processed_source.ast @processed_source = processed_source processed_source.tokens.each_cons(2) do |t1, t2| next if ([t1.pos, t2.pos] - positions_not_to_check).size < 2 type1, type2 = t1.type, t2.type if [:tLCURLY, :tRCURLY].include?(type2) check(t1, t2) elsif type1 == :tLCURLY if type2 == :tPIPE check_pipe(t1, t2) else check(t1, t2) end end end end def positions_not_to_check @positions_not_to_check ||= begin positions = [] ast = @processed_source.ast tokens = @processed_source.tokens on_node(:hash, ast) do |hash| b_ix = index_of_first_token(hash) e_ix = index_of_last_token(hash) positions << tokens[b_ix].pos << tokens[e_ix].pos end # TODO: Check braces inside string/symbol/regexp/xstr # interpolation. on_node([:dstr, :dsym, :regexp, :xstr], ast) do |s| b_ix = index_of_first_token(s) e_ix = index_of_last_token(s) tokens[b_ix..e_ix].each do |t| positions << t.pos if t.type == :tRCURLY end end positions end end def check(t1, t2) if t2.text == '{' check_space_outside_left_brace(t1, t2) elsif t1.text == '{' && t2.text == '}' check_empty_braces(t1, t2) elsif cop_config['EnforcedStyle'] == 'space_inside_braces' check_space_inside_braces(t1, t2) else check_no_space_inside_braces(t1, t2) end end def check_empty_braces(t1, t2) if cop_config['EnforcedStyleForEmptyBraces'] == 'space' check_space_inside_braces(t1, t2) else check_no_space_inside_braces(t1, t2) end end def check_space_inside_braces(t1, t2) unless space_between?(t1, t2) token, what = problem_details(t1, t2) convention(token.pos, token.pos, "Space missing inside #{what}.") end end def check_no_space_inside_braces(t1, t2) if space_between?(t1, t2) token, what = problem_details(t1, t2) s = space_range(token) convention(s, s, "Space inside #{what} detected.") end end def problem_details(t1, t2) if t1.text == '{' token = t1 what = t2.text == '}' ? 'empty braces' : '{' else token = t2 what = '}' end [token, what] end def check_space_outside_left_brace(t1, t2) if t2.text == '{' && !space_between?(t1, t2) convention(t1.pos, t2.pos, 'Space missing to the left of {.') end end def check_pipe(t1, t2) if cop_config['SpaceBeforeBlockParameters'] unless space_between?(t1, t2) convention(t2.pos, t1.pos, 'Space between { and | missing.') end elsif space_between?(t1, t2) s = space_range(t1) convention(s, s, 'Space between { and | detected.') end end def space_range(token) src = @processed_source.buffer.source if token.text == '{' b = token.pos.begin_pos + 1 e = b + 1 e += 1 while src[e] =~ /\s/ else e = token.pos.begin_pos b = e - 1 b -= 1 while src[b - 1] =~ /\s/ end Parser::Source::Range.new(@processed_source.buffer, b, e) end def autocorrect(range) @corrections << lambda do |corrector| case range.source when '}', '|' then corrector.insert_before(range, ' ') when ' ' then corrector.remove(range) else corrector.insert_after(range, ' ') end end end end end end end
module Helpers module SessionHelper def current_user @current_user ||= if session[:user_id] User.find(session[:user_id]) end error_unauthorized! if @current_user.nil? @current_user end end end
Pod::Spec.new do |s| s.name = "AFMActionSheet" s.version = "2.0.1" s.summary = "Easily adaptable action sheet supporting custom views and transitions." s.description = <<-DESC Easily adaptable action sheet supporting custom views and transitions. AFMActionSheet provides a AFMActionSheetController that can be used in places where one would use a UIAlertController, but a customized apperance or custom presentation/dismissal animation is needed. Seeing as how AFMActionSheetController was inspired by UIAlertController, it too supports ActionSheet and Alert styles to make your life even easier. DESC s.homepage = "https://github.com/ask-fm/AFMActionSheet" s.screenshots = "https://raw.githubusercontent.com/ask-fm/AFMActionSheet/master/res/action_sheet.gif", "https://raw.githubusercontent.com/ask-fm/AFMActionSheet/master/res/alert.gif" s.license = 'MIT' s.author = { "Ilya Alesker" => "ilya.alesker@ask.fm" } s.source = { :git => "https://github.com/ask-fm/AFMActionSheet.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/evil_cormorant' s.platform = :ios, '8.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.frameworks = 'UIKit' end
class ChangeDiscountFormatInReservations < ActiveRecord::Migration def up change_column :reservations, :discount, :float end def down change_column :reservations, :discount, :integer end end
Time.class_eval do def ceil(seconds = 60) self.class.at((self.to_f / seconds).ceil * seconds) end alias round ceil def floor(seconds = 60) self.class.at((self.to_f / seconds).floor * seconds) end end module ApplicationController::CachingHelpers private def expires_at(time, options = {}) options.assert_valid_keys(:public) if time > 1.year.from_now logger.warn "HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in the future." end if options[:public] cache_control = response.headers["Cache-Control"].split(",").map { |k| k.strip } cache_control.delete("private") cache_control.delete("no-cache") cache_control << "public" response.headers["Cache-Control"] = cache_control.join(', ') end response.headers["Expires"] = time.httpdate end def expires_every(seconds, options = {}) options.assert_valid_keys(:offset, :public) offset = options.delete(:offset).to_i expires_at Time.now.ceil(seconds) + offset, options end end
class Note < ApplicationRecord belongs_to :user has_many :taggings has_many :tags, through: :taggings, dependent: :destroy before_destroy :prevent_destroying_unarchived after_save :create_tags scope :unarchived, -> { where(is_archived: false) } scope :archived, -> { where(is_archived: true) } private def prevent_destroying_unarchived throw(:abort) unless is_archived end def create_tags if is_archived tags.destroy_all else hashtags = (extract_hashtags(title) + extract_hashtags(body)).uniq mentions = (extract_mentions(title) + extract_mentions(body)).uniq existing_tag_names = tags.map { |t| t.name } hashtags = hashtags.reject { |t| existing_tag_names.include?(t) } mentions = mentions.reject { |t| existing_tag_names.include?(t) } hashtags.each do |name| tag = user.tags.find_by(name: name, mention: false) tag ? tags << tag : tags.create(name: name, mention: false, user_id: user.id) end mentions.each do |name| tag = user.tags.find_by(name: name, mention: true) tag ? tags << tag : tags.create(name: name, mention: true, user_id: user.id) end end end def extract_hashtags(str) str ? str.scan(/#\S+/).map {|tag| tag[1..-1]}.uniq : [] end def extract_mentions(str) str ? str.scan(/@\S+/).map {|tag| tag[1..-1]}.uniq : [] end end
module LocalCache @hash = {} DEFAULT_TIMEOUT = 30 # seconds def self.[] key unwrap(@hash[key], key) end def self.[]= key, value @hash[key] = wrap(value) end def self.get key unwrap(@hash[key], key) end def self.set key, value, timeout=DEFAULT_TIMEOUT @hash[key] = wrap(value, timeout) end def self.clear key @hash.delete key end private def self.wrap value, timeout=DEFAULT_TIMEOUT {value: value, timestamp: Time.now.utc, timeout: timeout} end def self.unwrap item, key if item if Time.now.utc - item[:timestamp] > item[:timeout] @hash.delete key return nil end item[:timestamp] = Time.now.utc return item[:value] end item end end
require 'spec_helper' describe Appilf::DomainTrait do include Appilf::TestData describe '.new' do let(:domain_trait) do Appilf::DomainTrait.new(load_test_json_data(mocked_response_file_path('client/domain_trait/domain_trait.json'))) end it 'should respond to id' do domain_trait.id.should == 'verified' end end end
class AddColumnsNew < ActiveRecord::Migration def change remove_column :advocates, :practicing_at, :string remove_column :client_cases, :case_status, :boolean add_column :client_cases, :case_status, :string add_column :client_cases, :nature_of_case, :text add_column :fees, :fee_comment, :text end end
# Courses model class Course < ActiveRecord::Base has_many :user_courses has_many :users, through: :user_courses, dependent: :destroy belongs_to :category belongs_to :user, :class_name => :User, :foreign_key => 'creator_id' has_many :topics, dependent: :destroy creator_message = 'creator id/category id must be a positive integer' title_message = 'Title must be 5-100 characters and alphanumeric.' description_message = 'Description must be 50-1000 characters long.' validates :creator_id, :category_id, :presence => { message: 'Id Required' }, :numericality => { only_integer: true, greater_than: 0, message: creator_message } validates :title, :presence =>{ message: 'Title required' }, :length => { in: 5..100, message: title_message } validates :description, :presence => { message: 'description required '}, :length => { in: 50..1000, message: description_message } def as_json(options = {}) super.tap do |hash| if options[:include] if options[:include].include? :'user' fname, lname, id = hash['user'].values_at 'fname', 'lname', 'id' hash[:creator] = { name: "#{fname} #{lname}", id: id } hash.delete 'user' end end end end end
class Rankeable::InstallGenerator < Rails::Generators::Base #:nodoc: require 'rails/generators/migration' source_root File.expand_path("../templates", __FILE__) def copy_rankeable_gem_migrations migration_number = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i unless migration_already_exists? copy_file "create_rankings.rb", "db/migrate/#{migration_number}_create_rankings.rb" end end def add_ranking_rules_to_project destination_path = "app/rankings/rankings_rules.rb" if Dir.glob(destination_path).empty? copy_file "ranking_rules.rb", destination_path end end private def migration_already_exists? Dir.glob("#{File.join(destination_root, File.join("db", "migrate"))}/[0-9]*_*.rb").grep(/\d+_create_rankings.rb$/).first end end
## -*- Ruby -*- ## Sample XMLEncoding class for Japanese (EUC-JP, Shift_JIS) ## 1998 by yoshidam ## ## Usage: ## require 'xml/encoding-ja' ## include XML::Encoding_ja module XML module Encoding_ja require 'xml/parser' require 'uconv' class EUCHandler<XML::Encoding def map(i) return i if i < 128 return -1 if i < 160 or i == 255 return -2 end def convert(s) Uconv.euctou2(s) end end class SJISHandler<XML::Encoding def map(i) return i if i < 128 return -2 end def convert(s) Uconv.sjistou2(s) end end def unknownEncoding(name) return EUCHandler.new if name =~ /^euc-jp$/i return SJISHandler.new if name =~ /^shift_jis$/i nil end end end
class Api::PlaylistsController < ApplicationController def index @followed_playlist_ids = current_user.followed_playlist_ids @playlists = current_user.followed_playlists if params[:fetchType] == 'collection' @playlists = current_user.playlists if params[:fetchType] == 'addsong' if params[:fetchType] == 'browse' @playlists = Playlist.all.reject { |playlist| @followed_playlist_ids.include?(playlist.id) } end render :index end def create @followed_playlist_ids = current_user.followed_playlist_ids @playlist = Playlist.new(playlist_params) @playlist.user_id = current_user.id @playlist.image_url = 'https://sparkifyimages.s3.amazonaws.com/blank.jpg' if @playlist.save current_user.followed_playlists << @playlist render :show else render json: ["Unable to create playlist"], status: 401 end end def show @followed_playlist_ids = current_user.followed_playlist_ids @followed_song_ids = current_user.followed_song_ids @playlist = Playlist.includes(:songs).find(params[:id]) render :show end def update @playlist = current_user.playlists.find(params[:id]) if @playlist.update(playlist_params) @followed_playlist_ids = current_user.followed_playlist_ids @followed_song_ids = current_user.followed_song_ids render :show end end def follow @playlist = Playlist.find(params[:id]) current_user.followed_playlists << @playlist unless current_user.followed_playlists.include?(@playlist) render status: 200 end def unfollow @playlist = Playlist.find(params[:id]) @follow = Follow.find_by(followable_id: @playlist.id, followable_type: 'Playlist', user_id: current_user.id) @follow.destroy render status: 200 end def destroy playlist = current_user.playlists.find(params[:id]) playlist.destroy render :json => {}, status: 200 end private def playlist_params params.require(:playlist).permit(:title, :description) end end
json.array!(@looms) do |loom| json.extract! loom, :id, :reference, :workshop_id json.url loom_url(loom, format: :json) end
# Exercises: Easy 1 # Question 1. Which of the following are objects in Ruby? If they are objects, # how can you find out what class they belong to? # true # "hello" # [1, 2, 3, "happy days"] # 142 # all are objects. You can find out what class they belong to by adding .class # to the object. # Question 2. If we have a Car class and a Truck class and we want to be able # to go_fast, how can we add the ability for them to go_fast using the # module Speed? How can you check if your Car or Truck can now go fast? module Speed def go_fast puts "I am a #{self.class} and going super fast!" end end class Car include Speed def go_slow puts "I am safe and driving slow." end end class Truck include Speed def go_very_slow puts "I am a heavy truck and like going very slow." end end # just need to include the module Speed to both Truck and Car classes. # Question 3. In the last question we had a module called Speed which contained # a go_fast method. We included this module in the Car class as shown below. module Speed def go_fast puts "I am a #{self.class} and going super fast!" end end class Car include Speed def go_slow puts "I am safe and driving slow." end end # When we called the go_fast method from an instance of the Car class # (as shown below) you might have noticed that the string printed when # we go fast includes the name of the type of vehicle we are using. # How is this done? >> small_car = Car.new >> small_car.go_fast # I am a Car and going super fast! # we are calling go_fast from the class car, so self.class tells us were a Car object. # Question 4. If we have a class AngryCat how do we create a new instance # of this class? # The AngryCat class might look something like this: class AngryCat def hiss puts "Hisssss!!!" end end trinity = AngryCat.new # Question 5. Which of these two classes has an instance variable and # how do you know? class Fruit def initialize(name) name = name end end class Pizza def initialize(name) @name = name end end # class Pizza has an instance variable, you can tell because of the @ in front # of a variable. # Question 6. What could we add to the class below to access the # instance variable @volume? class Cube attr_reader :volume def initialize(volume) @volume = volume end end # Question 7. What is the default thing that Ruby will print to the screen # if you call to_s on an object? Where could you go to find out if you # want to be sure? # it prints the objects id or memory in space. If you weren't sure you can # check the ruby docs. # Question 8. If we have a class such as the one below: class Cat attr_accessor :type, :age def initialize(type) @type = type @age = 0 end def make_one_year_older self.age += 1 end end # You can see in the make_one_year_older method we have used self. # What does self refer to here? # self refers to the instance(object) of Cat # Question 9. If we have a class such as the one below: class Cat @@cats_count = 0 def initialize(type) @type = type @age = 0 @@cats_count += 1 end def self.cats_count @@cats_count end end # In the name of the cats_count method we have used self. # What does self refer to in this context? # self.cats_counts is a class method. self is referring to the class Cat # Question 10. If we have the class below, what would you need to call to # create a new instance of this class. class Bag def initialize(color, material) @color = color @material = material end end my_bag = Bag.new('blue', 'leather')
class Room < ApplicationRecord belongs_to :master, class_name: "User", foreign_key: "master_id" belongs_to :joiner, class_name: "User", foreign_key: "joiner_id" has_many :messages, dependent: :destroy has_attachment :photo def self.exist?(current_user, user) Room.exist_with_master?(current_user, user) || Room.exist_with_joiner?(current_user, user) end def self.exist_with_master?(current_user, user) if Room.where(master: current_user, joiner: user).first != nil true else false end end def self.exist_with_joiner?(current_user, user) if Room.where(master: user, joiner: current_user).first != nil true else false end end end
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. describe RemessasController do # This should return the minimal set of attributes required to create a valid # Remessa. As you add validations to Remessa, be sure to # adjust the attributes here as well. let(:valid_attributes) { { "codigorastreio" => "MyString" } } # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # RemessasController. Be sure to keep this updated too. let(:valid_session) { {} } describe "GET index" do it "assigns all remessas as @remessas" do remessa = Remessa.create! valid_attributes get :index, {}, valid_session assigns(:remessas).should eq([remessa]) end end describe "GET show" do it "assigns the requested remessa as @remessa" do remessa = Remessa.create! valid_attributes get :show, {:id => remessa.to_param}, valid_session assigns(:remessa).should eq(remessa) end end describe "GET new" do it "assigns a new remessa as @remessa" do get :new, {}, valid_session assigns(:remessa).should be_a_new(Remessa) end end describe "GET edit" do it "assigns the requested remessa as @remessa" do remessa = Remessa.create! valid_attributes get :edit, {:id => remessa.to_param}, valid_session assigns(:remessa).should eq(remessa) end end describe "POST create" do describe "with valid params" do it "creates a new Remessa" do expect { post :create, {:remessa => valid_attributes}, valid_session }.to change(Remessa, :count).by(1) end it "assigns a newly created remessa as @remessa" do post :create, {:remessa => valid_attributes}, valid_session assigns(:remessa).should be_a(Remessa) assigns(:remessa).should be_persisted end it "redirects to the created remessa" do post :create, {:remessa => valid_attributes}, valid_session response.should redirect_to(Remessa.last) end end describe "with invalid params" do it "assigns a newly created but unsaved remessa as @remessa" do # Trigger the behavior that occurs when invalid params are submitted Remessa.any_instance.stub(:save).and_return(false) post :create, {:remessa => { "codigorastreio" => "invalid value" }}, valid_session assigns(:remessa).should be_a_new(Remessa) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted Remessa.any_instance.stub(:save).and_return(false) post :create, {:remessa => { "codigorastreio" => "invalid value" }}, valid_session response.should render_template("new") end end end describe "PUT update" do describe "with valid params" do it "updates the requested remessa" do remessa = Remessa.create! valid_attributes # Assuming there are no other remessas in the database, this # specifies that the Remessa created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. Remessa.any_instance.should_receive(:update).with({ "codigorastreio" => "MyString" }) put :update, {:id => remessa.to_param, :remessa => { "codigorastreio" => "MyString" }}, valid_session end it "assigns the requested remessa as @remessa" do remessa = Remessa.create! valid_attributes put :update, {:id => remessa.to_param, :remessa => valid_attributes}, valid_session assigns(:remessa).should eq(remessa) end it "redirects to the remessa" do remessa = Remessa.create! valid_attributes put :update, {:id => remessa.to_param, :remessa => valid_attributes}, valid_session response.should redirect_to(remessa) end end describe "with invalid params" do it "assigns the remessa as @remessa" do remessa = Remessa.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Remessa.any_instance.stub(:save).and_return(false) put :update, {:id => remessa.to_param, :remessa => { "codigorastreio" => "invalid value" }}, valid_session assigns(:remessa).should eq(remessa) end it "re-renders the 'edit' template" do remessa = Remessa.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Remessa.any_instance.stub(:save).and_return(false) put :update, {:id => remessa.to_param, :remessa => { "codigorastreio" => "invalid value" }}, valid_session response.should render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested remessa" do remessa = Remessa.create! valid_attributes expect { delete :destroy, {:id => remessa.to_param}, valid_session }.to change(Remessa, :count).by(-1) end it "redirects to the remessas list" do remessa = Remessa.create! valid_attributes delete :destroy, {:id => remessa.to_param}, valid_session response.should redirect_to(remessas_url) end end end
class Game attr_accessor :win def initialize end end class Board < Game attr_accessor :board, :show_board def initialize @board = [1,2,3,4,5,6,7,8,9] end def show_board p board[0..2].join(" ") p board[3..5].join(" ") p board[6..8].join(" ") end end class Player < Game attr_reader :made_moves def initialize(mark,game) @mark = mark @game = game @made_moves = [] end def ask_move begin puts "Pick a spot on the board:" pick = Integer(gets.chomp) make_move(pick) rescue puts "Please enter an integer" retry end end def make_move(spot) if @game.board[spot-1].is_a? Numeric @made_moves.push(spot) @game.board[spot-1] = @mark check_win else puts "Invalid pick!" ask_move end end def check_win winning_combinations = [123,456,789,147,258,369,159,357] winning_combinations.each do |i| combi = i.to_s.split(//).map{|chr| chr.to_i} if (combi - @made_moves.sort).empty? $win = true break end end end end b = Board.new player_x = Player.new("X",b) player_y = Player.new("O",b) $win = false while $win == false while $win == false player_x.ask_move b.show_board break end while $win == false player_y.ask_move b.show_board break end end puts "YOU WON!"
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'open-uri' Movie.destroy_all Genre.destroy_all User.destroy_all genres = [ "Action", "Adventure", "Animation", "Comedy", "Crime", "Documentary", "Drama", "Family", "Fantasy", "History", "Horror", "Music", "Mystery", "Romance", "Science Fiction", "TV Movie", "Thriller", "War", "Western" ] puts "Creating #{genres.length} genres" genres.each do |g| Genre.create(name: g) end puts "Creating marvelous movies" movie1 = Movie.create( title: "Aladdin", description: "A kind-hearted street urchin Aladdin vies for the love of the beautiful princess Jasmine, the princess of Agrabah. When he finds a magic lamp, he uses the genie's magic power to make himself a prince in order to marry her. He's also on a mission to stop the powerful Jafar who plots to steal the magic lamp that could make his deepest wishes come true.", rating: 6.9, year: "2019", duration: "2h 8min", director: "Guy Ritchie", genres: Genre.where(name: ["Adventure", "Family", "Fantasy", "Music", "Romance"]) ) file1 = URI.open('https://m.media-amazon.com/images/M/MV5BMjQ2ODIyMjY4MF5BMl5BanBnXkFtZTgwNzY4ODI2NzM@._V1_UX182_CR0,0,182,268_AL_.jpg') movie1.photo.attach(io: file1, filename: 'aladin.jpg', content_type: 'image/jpg') movie2 = Movie.create( title: "Lion King", description: "In Africa, the lion cub Simba is the pride and joy of his parents King Mufasa and Queen Sarabi. Mufasa prepares Simba to be the next king of the jungle. However, the naive Simba believes in his envious uncle Scar that wants to kill Mufasa and Simba to become the next king. He lures Simba and his friend Nala to go to a forbidden place and they are attacked by hyenas but they are rescued by Mufasa. Then Scar plots another scheme to kill Mufasa and Simba but the cub escapes alive and leaves the kingdom believing he was responsible for the death of his father. Now Scar becomes the king supported by the evil hyenas while Simba grows in a distant land. Sometime later, Nala meets Simba and tells that the kingdom has become a creepy wasteland. What will Simba do?", rating: 6.9, year: "2019", duration: "1h 58min", director: "Jon Favreau", genres: Genre.where(name: ["Animation", "Adventure", "Drama", "Family", "Music"]) ) file2 = URI.open('https://m.media-amazon.com/images/M/MV5BMjIwMjE1Nzc4NV5BMl5BanBnXkFtZTgwNDg4OTA1NzM@._V1_UX182_CR0,0,182,268_AL_.jpg') movie2.photo.attach(io: file2, filename: 'lion_king.jpg', content_type: 'image/jpg') movie3 = Movie.create( title: "Despicable Me", description: "In a happy suburban neighborhood surrounded by white picket fences with flowering rose bushes, sits a black house with a dead lawn. Unbeknownst to the neighbors, hidden beneath this house is a vast secret hideout. Surrounded by a small army of minions, we discover Gru (Steve Carell), planning the biggest heist in the history of the world. He is going to steal the moon. Gru delights in all things wicked. Armed with his arsenal of shrink rays, freeze rays, and battle-ready vehicles for land and air, he vanquishes all who stand in his way. Until the day he encounters the immense will of three little orphaned girls who look at him and see something that no one else has ever seen: a potential Dad. The world's greatest villain has just met his greatest challenge: three little girls named Margo (Miranda Cosgrove), Edith (Dana Gaier), and Agnes (Elsie Fisher).", rating: 7.6, year: "2010", duration: "1h 35min", director: "Pierre Coffin, Chris Renaud", genres: Genre.where(name: ["Animation", "Comedy", "Crime", "Family", "Fantasy"]) ) file3 = URI.open('https://m.media-amazon.com/images/M/MV5BMTY3NjY0MTQ0Nl5BMl5BanBnXkFtZTcwMzQ2MTc0Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg') movie3.photo.attach(io: file3, filename: 'despicable_me.jpg', content_type: 'image/jpg') movie4 = Movie.create( title: "Bruce Almighty", description: "Bruce Nolan, a television reporter in Buffalo, N.Y., is discontented with almost everything in life despite his popularity and the love of his girlfriend Grace . At the end of the worst day of his life, Bruce angrily ridicules and rages against God and God responds. God appears in human form and, endowing Bruce with divine powers, challenges Bruce to take on the big job to see if he can do it any better.", rating: 6.8, year: "2003", duration: "1h 41min", director: "Tom Shadyac", genres: Genre.where(name: ["Comedy", "Fantasy"]) ) file4 = URI.open('https://m.media-amazon.com/images/M/MV5BNzMyZDhiZDUtYWUyMi00ZDQxLWE4NDQtMWFlMjI1YjVjMjZiXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_UX182_CR0,0,182,268_AL_.jpg') movie4.photo.attach(io: file4, filename: 'bruce_almighty.jpg', content_type: 'image/jpg') puts "Creating fake userssss" user1 = User.create( first_name: "Avalon", last_name: "Horst", email: "avalon@gmail.com", password: "password" ) user2 = User.create( first_name: "Puk", last_name: "Horstje", email: "puk@gmail.com", password: "password" ) puts "Finished!"
require 'bigdecimal' require 'bigdecimal/util' class Integer def ordinal cardinal = self.abs digit = cardinal%10 if (1..3).include?(digit) and not (11..13).include?(cardinal%100) self.to_s << %w{st nd rd}[digit-1] else self.to_s << 'th' end end end module InvoicePrintForShoppingCart def invoice invoice_message, grid, @prices = '', '+' + ('-' * 48) + '+' + ('-' * 10) + '+', [] invoice_message += grid + sprintf("\n| Name%-39sqty | price |\n#{grid}", '') invoice_message += invoice_add_products_to_string invoice_message += invoice_coupon_to_string( @prices.reduce { |current, next_one| current + next_one }, grid) invoice_message += sprintf("\n#{grid}\n| TOTAL%41s |", '') + \ ('%.2f' % @prices.reduce { |prices_sum, next_price| prices_sum += next_price }) .rjust(9) + " |\n#{grid}\n" end def invoice_add_products_check_promo(promo_data, product_price, product_count, product_name) @prices << (product_price * product_count).to_f product_message = sprintf( "\n| %-40s#{product_count.to_s.rjust(6)} |%9.2f |", product_name, @prices.last) unless promo_data.nil? promo_name = promo_data.keys[0] @prices << - (product_price * product_count - calculate_promotion( product_name, product_count, product_price, promo_data)).to_f product_message += "\n| #{invoice_promo_to_string(promo_name, @prices.last, product_name, promo_data[promo_name])}" end product_message end def invoice_add_products_to_string products_message = '' @products_in_cart.each do |product_name, product_count| promo_data, product_price = @promo[product_name], @products[product_name] products_message += invoice_add_products_check_promo(promo_data, product_price, product_count, product_name) end products_message end def invoice_promo_to_string(promo_type, promo_sum, product_name, promo_value) case promo_type when :get_one_free then sprintf("%-45s", "(buy #{promo_value - 1}, get 1 free)") when :package sprintf("%-45s", "(get #{promo_value.values[0]}% off for every #{promo_value.keys[0]})") else sprintf("%-45s", "(#{promo_value.values[0]}% off of every after the #{promo_value.keys[0].ordinal})") end + \ sprintf("| %8s |", ('%.2f' % promo_sum.to_f)) end def invoice_coupon_to_string(total_price_without_coupons, grid) unless @coupon_name.nil? coupon_message = "\n| Coupon #{@coupon_name} - " if @coupons[@coupon_name].has_key? :percent coupon_message += ("#{@coupons[@coupon_name][:percent]}% off").ljust(37 - @coupon_name.length) elsif @coupons[@coupon_name].has_key? :amount coupon_message += sprintf("%.2f off %19s", @coupons[@coupon_name][:amount].to_f, '') end @prices << - (total_price_without_coupons.to_f - use_coupon(total_price_without_coupons)).to_f coupon_message += sprintf("|%4s%.2f |", '', @prices.last) end.to_s end end class Inventory def initialize @products = {} @promo = {} @coupons = {} end def register(product_name, product_price, get_one_free: nil, package: nil, threshold: nil) if product_name.length > 40 or @products.has_key? product_name or not BigDecimal(product_price).between? BigDecimal('0.01') , BigDecimal('999.99') raise 'Invalid parameters passed.' else @products[product_name] = BigDecimal(product_price) end @promo[product_name] = { get_one_free: get_one_free } unless get_one_free.nil? @promo[product_name] = { package: package } unless package.nil? @promo[product_name] = { threshold: threshold } unless threshold.nil? end def register_coupon(coupon_name, coupon_hash) @coupons[coupon_name] = coupon_hash end def new_cart new_cart = Cart.new(@products, @promo, @coupons) end end class Cart include InvoicePrintForShoppingCart def initialize(products, promo, coupons) @products_in_cart = {} @products = products @promo = promo @coupons = coupons @coupon_name = nil end def add(product_name, product_quantity = 1) if not @products.include? product_name or not product_quantity.between? 1, 99 raise 'Invalid parameters passed.' elsif not @products_in_cart.has_key? product_name @products_in_cart[product_name] = product_quantity else @products_in_cart[product_name] += product_quantity end end def calculate_promotion(product_name, product_quantity, product_price, promo_data) return product_price * product_quantity if @promo.size.zero? case promo_type = promo_data.keys[0] when :get_one_free (product_quantity - (product_quantity.to_i / promo_data.values[0].to_i)) else promo_value = 1 - promo_data[promo_type].values[0] / 100.to_d package_or_threshold_promo(product_price, product_quantity, promo_value, promo_data) end \ * product_price end def package_or_threshold_promo(product_price, product_quantity, promo_value, promo_data) promo_quantity = promo_data[promo_data.keys[0]].keys[0] case promo_type = promo_data.keys[0] when :package (product_quantity % promo_quantity.to_d + promo_value * promo_quantity * (product_quantity / promo_quantity).to_i) when :threshold ([product_quantity, promo_quantity].min + promo_value * [0, (product_quantity - promo_quantity).to_i].max) end end def use(coupon_name) @coupon_name = coupon_name end def use_coupon(total_price) return total_price if @coupon_name.nil? coupon_type = @coupons[@coupon_name].keys[0] coupon_value = @coupons[@coupon_name].values[0] if coupon_type == :percent total_price * (1 - coupon_value / 100.to_d) elsif coupon_type == :amount [0, total_price - coupon_value.to_d].max end end def total @products_in_cart.map do |product| product_name = product[0] product_quantity = @products_in_cart[product_name].to_d product_price = @products[product_name] promo_data = @promo[product_name] use_coupon( calculate_promotion(product_name, product_quantity, product_price, promo_data) ) end .reduce { |sum, product_quantity| sum + product_quantity } end end
class AddSummaryOverrideToCalendarUsers < ActiveRecord::Migration def change add_column :calendar_users, :summary_override, :string end end
require 'spec_helper' describe Pardner::Team do let(:team) { described_class.create(name: 'Super', members: ['jill@example.com', 'bill@example.com']) } describe '#member?' do it 'is true if the given email is a member of the team' do expect(team.member?('jill@example.com')).to eql true end it 'is false if the given email is not a member of the team' do expect(team.member?('illj@example.com')).to eql false end end describe "validations" do it "is invalid without name" do t = described_class.new t.valid? expect(t).not_to be_valid expect(t.errors[:name]).to be_present end it "is invalid without a unique name" do team t = described_class.new(name: team.name) t.valid? expect(t).not_to be_valid expect(t.errors[:name]).to be_present end it "is valid with a name" do expect(described_class.new(name: 'my team')).to be_valid end end end
require "spec_helper" describe "routing" do it "routes a bunch of stuff" do expect(get: '/').to route_to("departments#home") expect(get: 'courses/1/teachers/doej/assignments/new').to route_to( controller: 'assignments', action: 'new', course_id: "1", teacher_id: 'doej' ) expect(get: 'sections/1/assignments_pane').to route_to( controller: 'sections', action: 'assignments_pane', id: "1" ) expect(get: 'departments/1/edit_dept_doc/2').to route_to( controller: 'department_documents', action: 'edit', dept_id: "1", id: "2" ) expect(put: 'departments/1/update_dept_doc/2').to route_to( controller: 'department_documents', action: 'update', dept_id: "1", id: "2" ) expect(get: 'courses/1/home/2').to route_to( controller: 'courses', action: 'home', id: "1", section_id: "2" ) expect(get: 'courses/1/pane/sections').to route_to( controller: "courses", action: 'get_pane', kind: "sections", id: "1" ) end # it "retrieves sections in a variety of ways" do # expect(get: "sections/retrieve/321/davidsonl/B/2013").to route_to( # controller: 'sections', # action: 'retrieve', # course_id: "321", # teacher_id: "davidsonl", # block: "B", # year: "2013" # ) # expect(get: "sections/retrieve").to route_to( # controller: "sections", # action: "retrieve" # ) # expect(get: "/sections/retrieve/231/foobar").to route_to( # controller: 'sections', # action: 'retrieve', # course_id: "231", # teacher_id: "foobar" # ) # end end
class Payment < ActiveRecord::Base ## PAGAMENTI ## Validazioni validates :date, presence:true validates :amount, presence:true ## Scopes def self.real where.not(movement_id:nil) end def self.only_real where(importation_table_id:nil).where.not(movement_id:nil) end def self.virtual where.not(importation_table_id:nil) end def self.only_virtual where(movement_id:nil).where.not(importation_table_id:nil) end def self.matched where.not(movement_id:nil, importation_table_id:nil) end def self.orphan where(movement_id:nil, importation_table_id: nil) end def self.ordinary where(withheld_payment:false) end def self.withheld where(withheld_payment:true) end def self.income where('amount < 0.00') end def self.outcome where('amount >= 0.00') end ## Chiavi Primarie belongs_to :movement, optional: true belongs_to :importation_table, optional: true belongs_to :building belongs_to :tenant, optional: true belongs_to :supplier, optional: true ## Chiavi Esterne has_many :partial_payments, :dependent => :destroy has_many :invoices, through: :partial_payments has_many :tenants, through: :partial_payments has_many :traces, :dependent => :destroy ## Esporta tabella su file CSV def self.to_csv(options = {:col_sep => "|"}) CSV.generate(options) do |csv| all.each do |object| csv << object.attributes.values_at(*column_names) end end end ## Ricerche include PgSearch pg_search_scope :payments_search, against: [:description, :amount, :date, :iban, :tax_code, :vat_code], using: {tsearch:{ prefix:true}}, associated_against: {movement: [:number, :description]} end
module MTMD module FamilyCookBook module Search class RecipeByTag < ::MTMD::FamilyCookBook::Search::Recipe def query(phrase) MTMD::FamilyCookBook::Recipe. where( :id => MTMD::FamilyCookBook::Tag. association_join(:recipes). where(:tags__id => phrase). select_map(:recipe_id) ). order(:title). all end def transform_phrase(phrase) MTMD::FamilyCookBook::Tag.where(:id => phrase).select_map(:name).first end end end end end
class CreateAttacks < ActiveRecord::Migration def change create_table :attacks do |t| t.string :Name t.string :Capsule t.string :Type t.integer :Power t.integer :Accuracy t.timestamps null: false end add_index :attacks, :Name end end
# frozen_string_literal: true require 'controller_test' class BoardMeetingsControllerTest < ActionController::TestCase setup do @board_meeting = board_meetings(:one) login(:uwe) end test 'should get index' do get :index assert_response :success end test 'should get new' do get :new assert_response :success end test 'should create board_meeting' do assert_difference('BoardMeeting.count') do post :create, params: { board_meeting: { start_at: @board_meeting.start_at } } end assert_redirected_to board_meetings_path end test 'should show board_meeting' do get :show, params: { id: @board_meeting } assert_response :success end test 'should get edit' do get :edit, params: { id: @board_meeting } assert_response :success end test 'should update board_meeting' do put :update, params: { id: @board_meeting, board_meeting: { start_at: @board_meeting.start_at } } assert_redirected_to board_meetings_path end test 'should destroy board_meeting' do assert_difference('BoardMeeting.count', -1) do delete :destroy, params: { id: @board_meeting } end assert_redirected_to board_meetings_path end end
# frozen_string_literal: true class Api::V1::UsersController < Api::V1::BaseController def index render json: current_api_v1_user end def show user = User.find(params[:id]) render json: user end def update current_api_v1_user.update(user_params) render json: current_api_v1_user end private def user_params user_params = params.permit( :name, :email, :image, :sport_id ) user_params[:image] = parse_image_data(user_params[:image]) if user_params[:image] user_params end def parse_image_data(base64_image) filename = 'profile-image' in_content_type, _, string = base64_image.split(/[:;,]/)[1..3] @tempfile = Tempfile.new(filename) @tempfile.binmode @tempfile.write Base64.decode64(string) @tempfile.rewind ActionDispatch::Http::UploadedFile.new( tempfile: @tempfile, content_type: in_content_type, filename: filename ) end end
class Pnameforms::Piece12sController < ApplicationController before_action :set_piece12, only: [:show, :edit, :update, :destroy] # GET /piece12s # GET /piece12s.json def index @pnameform = Pnameform.find(params[:pnameform_id]) @piece12s = @pnameform.piece12s end # GET /piece12s/12 # GET /piece12s/12.json def show @pnameform = Pnameform.find(params[:pnameform_id]) @piece12s = Piece12.all end # GET /piece12s/new def new @pnameform = Pnameform.find(params[:pnameform_id]) @piece12 = current_user.piece12s.build end # GET /piece12s/12/edit def edit @pnameform = Pnameform.find(params[:pnameform_id]) @piece12.pnameform = @pnameform end # POST /piece12s # POST /piece12s.json def create @pnameform = Pnameform.find(params[:pnameform_id]) @piece12 = current_user.piece12s.build(piece12_params) @piece12.pnameform = @pnameform respond_to do |format| if @piece12.save format.html { redirect_to pnameform_piece12s_path(@pnameform), notice: 'Piece12 was successfully created.' } format.json { render :show, status: :created, location: @piece12 } else format.html { render :new } format.json { render json: @piece12.errors, status: :unprocessable_entity } end end end # PATCH/PUT /piece12s/12 # PATCH/PUT /piece12s/12.json def update @pnameform = Pnameform.find(params[:pnameform_id]) @piece12.pnameform = @pnameform respond_to do |format| if @piece12.update(piece12_params) format.html { redirect_to pnameform_piece12s_path(@pnameform), notice: 'Piece12 was successfully updated.' } format.json { render :show, status: :ok, location: @piece12 } else format.html { render :edit } format.json { render json: @piece12.errors, status: :unprocessable_entity } end end end # DELETE /piece12s/12 # DELETE /piece12s/12.json def destroy @pnameform = Pnameform.find(params[:pnameform_id]) @piece12 = Piece12.find(params[:id]) title = @piece12.name if @piece12.destroy flash[:notice] = "\"#{title}\" was deleted successfully." redirect_to pnameform_piece12s_path(@pnameform) else flash[:error] = "There was an error deleting." render :show end end private # Use callbacks to share common setup or constraints between actions. def set_piece12 @piece12 = Piece12.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def piece12_params params.require(:piece12).permit(:name, :user_id) end end
class Boat < ActiveRecord::Base belongs_to :captain has_many :boat_classifications has_many :classifications, through: :boat_classifications def self.first_five select(:name).limit(5)#Model.select(:field)# => [#<Model field:value>]https://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/select end def self.dinghy where("length <= ?", 20)#Now what if that number could vary, say as an argument from somewhere,http://guides.rubyonrails.org/active_record_querying.html#conditions end def self.ship where("length >= ?", 20)#Now what if that number could vary, say as an argument from somewhere,http://guides.rubyonrails.org/active_record_querying.html#conditions end def self.last_three_alphabetically select(:name).order(name: :desc).limit(3) #https://apidock.com/rails/ActiveRecord/QueryMethods/order #binding.pry end def self.without_a_captain where("captain_id IS ?",nil) end def self.sailboats #binding.pry joins(:classifications).where(classifications: { name: 'Sailboat' }) end def self.with_three_classifications joins(:classifications).group("boats.id").having('count(classification_id) = 3') #return a Boat object for all boats with classifications by joins call #return collection of boats_id by group call #return boats with specified expression Having (count(classification_id = 3)) on the GROUP BY fields #binding.pry end def self.longest order('length DESC').first end end
require_relative './order_item' module Schema class Order < Base BASE_REQUEST_REGEX = /\A\d+\s[A-Z0-9]+\z/ attribute :quantity, Integer attribute :base_request, String attribute :product_code, String attribute :order_items, Array[Schema::OrderItem] attribute :total_amount, Decimal, default: 0.0 attribute :currency, String, default: "$" validates :base_request, presence: true validates :base_request, format: { with: BASE_REQUEST_REGEX } def parse_request self.quantity, self.product_code = self.base_request.split(' ') if valid? end def compute order_items.sum{ |x| x.amount } end def render_details puts "---------------" order_items.each_with_index do |oi, index| puts "#{index + 1}. #{oi.quantity} x #{oi.pack.quantity} - #{oi.currency}#{oi.amount}" end puts "---------------" puts "Total: #{currency} #{compute}" end end end
class Project < ActiveRecord::Base mount_uploader :image, ProjectUploader validates_presence_of :name, :image, :description end
require 'rubygems' require 'date' require 'mixpanel_client' #appsIDs is an array def get_live_page_count(appsIDs, eventName) config = { api_key: 'dc026b4b9413dcce8e3ac0374ef906e5', api_secret: 'd144302ca4443c49420569d07d1c9e15' } client = Mixpanel::Client.new(config) data = client.request('events/properties', { event: eventName, name: 'Landing Page ID', values: appsIDs, type: 'unique', unit: 'day', interval: 1, }) current_date = data["data"]["series"][0] values = data["data"]["values"] results = Hash.new appsIDs.each do |id| if values[id].nil? value = 0 else value = values[id][current_date] end results[id] = {"date"=>current_date,"clicks"=>value} end return results end #appsIDs is an array def get_mixpanel_data(appsIDs) config = { api_key: 'dc026b4b9413dcce8e3ac0374ef906e5', api_secret: 'd144302ca4443c49420569d07d1c9e15' } client = Mixpanel::Client.new(config) pageViewdata = client.request('events/properties', { event: 'App LandingPage Viewed', name: 'Landing Page ID', values: appsIDs, type: 'unique', unit: 'day', interval: 1, }) itunesClicks = client.request('events/properties', { event: 'Click Apps iTunes', name: 'Landing Page ID', values: appsIDs, type: 'unique', unit: 'day', interval: 1, }) current_date = pageViewdata["data"]["series"][0] values = pageViewdata["data"]["values"] iTunesClick_values = itunesClicks["data"]["values"] results = Hash.new appsIDs.each do |id| if values[id].nil? value = 0 else value = values[id][current_date] end if iTunesClick_values[id].nil? iTunes_Click = 0 else iTunes_Click = iTunesClick_values[id][current_date] end results[id] = {"date"=>current_date,"pageView"=>value, "itunesClick"=>iTunes_Click} end return results end #fuck = get_live_page_count(["13","14","15","16"], 'App LandingPage Viewed') # fuck = get_mixpanel_data(["13","14","15","16"]) # puts fuck # fuck.each do |f,v| # puts "Page View: "+v["pageView"].to_s + " iTunes Clicks " + v["itunesClick"].to_s # end
# == Schema Information # # Table name: badges # # id :integer not null, primary key # name :string # description :text # required_points :integer # image_url :string # subject_id :integer # created_at :datetime not null # updated_at :datetime not null # giving_method :integer # FactoryGirl.define do factory :badge do subject { create(:subject) } name { Faker::Commerce.product_name } description { Faker::Lorem.paragraph } image_url "/test.png" giving_method "manually" factory :points_badge do giving_method "points" required_points 100 end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'inhouse_events/version' Gem::Specification.new do |spec| spec.name = 'inhouse_events' spec.version = InhouseEvents::VERSION spec.authors = ['lefs'] spec.summary = 'Web analytics for Rails applications.' spec.description = 'Web analytics for Rails applications.' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.9.0' spec.add_development_dependency 'combustion', '~> 1.3' spec.add_development_dependency 'rspec-rails', '~> 3.9.1' spec.add_development_dependency 'capybara', '~> 2.18' spec.add_development_dependency 'ammeter', '~> 1.1.2' spec.add_development_dependency 'sucker_punch', '~> 1.3.2' spec.add_development_dependency 'teaspoon', '~> 1.1.5' spec.add_development_dependency 'teaspoon-jasmine', '~> 2.3.4' spec.add_development_dependency 'factory_girl', '~> 4.8.0' spec.add_development_dependency 'sidekiq', '~> 3.3.1' spec.add_development_dependency 'webmock', '~> 3.8.3' spec.add_development_dependency 'appraisal', '~> 2.3' spec.add_development_dependency 'poltergeist', '~> 1.6.0' spec.add_dependency 'rails', '>= 4.2' end
# frozen_string_literal: true class ApplicationController < ActionController::Base include DeviseTokenAuth::Concerns::SetUserByToken before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname]) end def application_pack_name case framework = params[:framework] when 'react', 'vue' "application_#{framework}" else 'application_vue' end end helper_method :application_pack_name end
class Bootcamp def initialize(name, slogan, student_capacity) @name = name @slogan = slogan @student_capacity = student_capacity @teachers = [] @students = [] @grades = Hash.new { |h, k| h[k] = [] } end attr_reader :name, :slogan, :teachers, :students def hire(tea) @teachers << tea end def enroll(stu) if @students.length < @student_capacity @students << stu true else false end end def enrolled?(stu) @students.include?(stu) end def student_to_teacher_ratio @students.length / @teachers.length end def add_grade(stu, grade) if enrolled?(stu) @grades[stu] << grade true else false end end def num_grades(stu) @grades[stu].length end def average_grade(stu) return nil if num_grades(stu) == 0 || !enrolled?(stu) sum = @grades[stu].sum / num_grades(stu) end end
require "fog/core/model" module Fog module Google class Monitoring ## # A monitoredResourceDescriptor defines a metric type and its schema. # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.monitoredResourceDescriptors#MonitoredResourceDescriptor class MonitoredResourceDescriptor < Fog::Model identity :name attribute :description attribute :display_name, :aliases => "displayName" attribute :type attribute :labels end end end end
class Appointment < ApplicationRecord belongs_to :country, optional: true belongs_to :company, optional: true end
require_relative '../test_helper' class SkillTest < Minitest::Test def test_it_assigns_attributes_correctly data = { "name" => "Skill One", "description" => "Description One", "id" => 1} skill = Skill.new(data) assert_equal "Skill One", skill.name assert_equal "Description One", skill.description assert_equal 1, skill.id end end
require "piece" require "byebug" describe Piece do let(:board) {double("board", valid_pos?: true)} subject(:piece) {Piece.new(:white, board, [0,0])} describe "#initialize" do context "with valid arguments" do it "instantiates a piece correctly" do #this runs the test # piece = Piece.new(:white, board, [0, 0]) # "be" checks for object id expect(piece.color).to be(:white) # eq checks for equality expect(piece.pos).to eq([0, 0]) end end context "with invalid arguments" do it "raises an error when provided an invalid color" do # need block {} for checking errors expect { Piece.new(:blue, board, [0, 0]) }.to raise_error("Invalid color") end it "raises an error when provided an invalid position" do allow(board).to receive(:valid_pos?).and_return(false) expect { Piece.new(:white, board, [9, 9]) }.to raise_error("Invalid position") end it "delegates to the board to ensure the passed position is valid" do expect(board).to receive(:valid_pos?) Piece.new(:white, board, [0,0]) end end end describe "#pos=" do before(:each) { piece.pos = [1,1] } #will run before each it block it "correctly assigns a piece's position" do # piece = Piece.new(:white, board, [0, 0]) # piece.pos = [1, 1] expect(piece.pos).to eq([1, 1]) end end describe "#symbol" do it "raises an error" do expect { piece.symbol }.to raise_error(NotImplementedError) end end describe "#to_s" do it "returns a formatted string" do allow(piece).to receive(:symbol).and_return("♜") expect(piece.to_s).to eq(" ♜ ") end end describe "#empty?" do it "returns false" do expect(piece.empty?).to be_falsey end end end
class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.string :eventName t.string :password t.integer :admin_id t.integer :participants t.integer :spendingLimit t.text :match, :array => true t.date :expire t.timestamps end end end
require 'spec_helper' describe Oplop::V1 do describe ".password" do context "tests from testdata.json (see Python implementation at http://code.google.com/p/oplop/)" do # loop around each "case" in testdata.yml Yajl::Parser.new.parse(File.new(File.dirname(__FILE__) + "/testdata/v1.json", 'r')).each do |testdata| specify testdata["why"] do password = Oplop::V1.password(:master => testdata["master"], :label => "*" + testdata["label"]) expect(password).to eq testdata["password"] password = Oplop::V1.password(:master => testdata["master"], :length => 8, :label => testdata["label"]) expect(password).to eq testdata["password"] end end end end end
class ChangeModuleValueTypeToString2 < ActiveRecord::Migration def up change_column :module_values, :value, :text end def down change_column :module_values, :value, :string end end
# == Schema Information # # Table name: locations # # id :integer not null, primary key # name :string(255) # country :string(255) # airport :string(255) # address :text(65535) # zipcode :string(255) # town :string(255) # additional_details :text(65535) # created_at :datetime not null # updated_at :datetime not null # class Location < ActiveRecord::Base # Validations for storing filtered data validates_presence_of :name, :country, :airport, :address, :zipcode, :town # Relations/Associations with other models has_many :audits #, dependent: :destroy end
class Customer attr_accessor :first_name, :last_name, :reviews @@all = [] def initialize(first_name, last_name) @first_name = first_name @last_name = last_name @@all << self end def self.all @@all end def restaurants self.reviews.map {|review| review.restaurant} end def reviews Review.all.select {|review| review.customer == self} end def create_review(restaurant, content) puts self Review.new(restaurant, content, self) end def full_name "#{first_name} #{last_name}" end def self.find_by_name(full_name) self.all.find {|cust| cust.full_name == full_name} end def self.find_all_by_first_name(first_name) self.all.find_all {|cust| cust.first_name == first_name} end end class Review attr_accessor :content attr_reader :restaurant, :customer @@all = [] def initialize(restaurant, content, customer) @customer = customer @restaurant = restaurant @content = content @@all << self end def self.all @@all end end class Restaurant attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.find_by_name(name) self.all.find {|restaurant| restaurant.name == name} end def customers # return customer --> success! self.reviews.map {|review| review.customer} end def reviews # return all reviews associated with this restaurant Review.all.select {|review| review.restaurant == self} end def self.all @@all end end
module PryParsecom class Setting DOT_DIRNAME = "#{Dir.home}/.pry-parsecom" SETTINGS_FILENAME = "settings" IGNORES_FILENAME = "ignores" KEYS_FILENAME = "keys" SCHEMAS_FILENAME = "schemas" USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' LOGIN_URL = 'https://parse.com/apps' LOGIN_SUCCESS_FILENAME= 'apps.html' LOGIN_ERROR_FILENAME = 'user_session.html' APPS_XPATH = '/html/body/div[4]/div[2]/div/div/div/div[3]/ul/li/ul/li/a' APP_NAME_XPATH = '//*[@id="parse_app_name"]' APP_KEYS_CSS = 'div.app_keys.window' APP_ID_XPATH = 'div[2]/div[1]/div[2]/div/input' API_KEY_XPATH = 'div[2]/div[5]/div[2]/div/input' MASTER_KEY_XPATH = 'div[2]/div[6]/div[2]/div/input' @@agent = Mechanize.new @@agent.user_agent = USER_AGENT @@current_app = nil @@apps = {} class <<self def current_app @@current_app end def current_app= app @@current_app = app store_setting app end def current_setting @@apps[@@current_app] end def setup_if_needed if @@apps.empty? unless restore login *PryParsecom.ask_email_and_password end end end def read_setting_file name begin File.read "#{DOT_DIRNAME}/#{name}" rescue '' end end def write_setting_file name, hash Dir.mkdir DOT_DIRNAME unless File.exist? DOT_DIRNAME File.open "#{DOT_DIRNAME}/#{name}", 'w' do |file| file.write YAML.dump(hash) end end def restore if File.exist? DOT_DIRNAME settings = read_setting_file SETTINGS_FILENAME ignores = read_setting_file IGNORES_FILENAME keys = read_setting_file KEYS_FILENAME schemas = read_setting_file SCHEMAS_FILENAME if !keys.empty? && !schemas.empty? ignores = ignores.split "\n" keys = YAML.load keys schemas = YAML.load schemas keys.each do |app_name, key| @@apps[app_name] = Setting.new app_name, key['app_id'], key['api_key'], key['master_key'], schemas[app_name] end unless settings.empty? settings = YAML.load settings self.current_app = settings['current_app'] end return true end end false end def store_cache keys = {} schemas = {} @@apps.each do |app_name, setting| keys[app_name] = { 'app_id' => setting.app_id, 'api_key' => setting.api_key, 'master_key' => setting.master_key } schemas[app_name] = setting.schemas end write_setting_file KEYS_FILENAME, keys write_setting_file SCHEMAS_FILENAME, schemas end def store_setting if @@current_app write_setting_file SETTINGS_FILENAME, 'current_app' => @@current_app end end def login email, password @@apps = {} login_page = @@agent.get LOGIN_URL apps_page = login_page.form_with :id => 'new_user_session' do |form| form['user_session[email]'] = email form['user_session[password]'] = password end.submit if apps_page.filename == LOGIN_ERROR_FILENAME puts 'login error' return end apps_page.search(APPS_XPATH).each do |a| href = a.attributes['href'].to_s count_page = @@agent.get "#{href}/collections/count" schema = JSON.parse count_page.content edit_page = @@agent.get "#{href}/edit" app_name = edit_page.search(APP_NAME_XPATH).first.attributes['value'].to_s app_keys = edit_page.search('div.app_keys.window') app_id = app_keys.search(APP_ID_XPATH).first.attributes['value'].to_s api_key = app_keys.search(API_KEY_XPATH).first.attributes['value'].to_s master_key = app_keys.search(MASTER_KEY_XPATH).first.attributes['value'].to_s next if read_setting_file(IGNORES_FILENAME).split("\n").include? app_name @@apps[app_name] = Setting.new app_name, app_id, api_key, master_key, schema end store_cache end def logout FileUtils.rm "#{DOT_DIRNAME}/#{KEYS_FILENAME}" FileUtils.rm "#{DOT_DIRNAME}/#{SCHEMAS_FILENAME}" @@apps.clear @@current_app = nil end def cache_time if File.exist? DOT_DIRNAME File.mtime "#{DOT_DIRNAME}/#{SCHEMAS_FILENAME}" else nil end end def app_names @@apps.keys end def has_app? app_name @@apps.has_key? app_name.to_s end def by_name app_name @@apps[app_name.to_s] end alias [] by_name def each &block @@apps.each &block end end attr_accessor :app_name, :app_id, :api_key, :master_key, :schemas def initialize app_name, app_id, api_key, master_key, schemas @app_name, @app_id, @api_key, @master_key, @schemas = app_name, app_id, api_key, master_key, schemas end def apply Parse.credentials :application_id => @app_id, :api_key => @api_key, :master_key => @master_key Parse::Client.default.application_id = @app_id Parse::Client.default.api_key = @api_key Parse::Client.default.master_key = @master_key schemas['collection'].each do |e| class_name = e['id'] next if class_name[0] == '_' if Object.const_defined? class_name puts "#{class_name.to_s} has already exist." next end Parse::Object class_name end end def reset schemas['collection'].each do |e| class_name = e['id'] next if class_name[0] == '_' if Object.const_defined? class_name klass = Object.const_get class_name if klass < Parse::Object Object.class_eval do remove_const class_name end end end end Parse.credentials :application_id => '', :api_key => '', :mater_key => '' Parse::Client.default.application_id = nil Parse::Client.default.api_key = nil Parse::Client.default.master_key = nil Parse::Client.default end def classes schemas['collection'].map{|e| e['id']}.sort end def schema class_name schms = schemas['collection'].select do |e| e['id'] == class_name || e['display_name'] == class_name end schms.empty? ? [] : schms.first['schema'] end end end
require 'mina/bundler' require 'mina/rails' require 'mina/git' # require 'mina/rbenv' # for rbenv support. (http://rbenv.org) # require 'mina/rvm' # for rvm support. (http://rvm.io) # Basic settings: # domain - The hostname to SSH to. # deploy_to - Path to deploy into. # repository - Git repo to clone from. (needed by mina/git) # branch - Branch name to deploy. (needed by mina/git) set :app, 'mirafloris' set :domain, '54.232.210.178' set :identity_file, File.join(ENV["HOME"], ".ec2", "mirafloris.pem") set :user, 'ubuntu' set :deploy_to, "/var/www/#{app}" set :repository, "https://github.com/candidosales/#{app}.git" set :branch, 'master' # Manually create these paths in shared/ (eg: shared/config/database.yml) in your server. # They will be linked in the 'deploy:link_shared_paths' step. set :shared_paths, ['config/database.yml', 'log'] # Optional settings: # set :user, 'foobar' # Username in the server to SSH to. # set :port, '30000' # SSH port number. # This task is the environment that is loaded for most commands, such as # `mina deploy` or `mina rake`. task :environment do # If you're using rbenv, use this to load the rbenv environment. # Be sure to commit your .rbenv-version to your repository. # invoke :'rbenv:load' # For those using RVM, use this to load an RVM version@gemset. # invoke :'rvm:use[ruby-1.9.3-p125@default]' end # Put any custom mkdir's in here for when `mina setup` is ran. # For Rails apps, we'll make some of the shared paths that are shared between # all releases. task :setup => :environment do queue! %[mkdir -p "#{deploy_to}/shared/log"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/log"] queue! %[mkdir -p "#{deploy_to}/shared/config"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/config"] queue! %[touch "#{deploy_to}/shared/config/database.yml"] queue %[-----> Be sure to edit 'shared/config/database.yml'.] end desc "Deploys the current version to the server." task :deploy => :environment do deploy do # Put things that will set up an empty directory into a fully set-up # instance of your project. invoke :'git:clone' invoke :'deploy:link_shared_paths' invoke :'bundle:install' invoke :'rails:db_migrate' invoke :'rails:assets_precompile' to :launch do queue 'touch tmp/restart.txt' end task :start do %w(config/database.yml).each do |path| from = "#{deploy_to}/#{path}" to = "#{current}/#{path}" run "if [ -f '#{to}' ]; then rm '#{to}'; fi; ln -s #{from} #{to}" end run "cd #{current} && RAILS_ENV=production && GEM_HOME=/opt/local/ruby/gems && bundle exec unicorn_rails -c #{deploy_to}/config/unicorn.rb -D" end task :stop do run "if [ -f #{deploy_to}/shared/pids/unicorn.pid ]; then kill `cat #{deploy_to}/shared/pids/unicorn.pid`; fi" end task :restart do stop start end end end namespace :rails do task :db_create do queue 'RAILS_ENV="production" bundle exec rake db:create' end end task :install_enviroment do invoke :dev_tools invoke :git invoke :ruby invoke :update_gem invoke :bundler end desc "Atualizar Ubuntu" namespace :ubuntu do task :update do print_str "-----> Atualizando Ubuntu" queue "sudo apt-get -y update" queue "sudo apt-get -y upgrade" queue "sudo apt-get -y dist-upgrade" queue "sudo apt-get -y autoremove" queue "sudo reboot" end end task :dev_tools do print_str "-----> Instalar Development Tools" queue "sudo apt-get install dialog build-essential openssl libreadline6 libreadline6-dev curl zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion nodejs -y" end task :git do print_str "-----> Instalar Git" queue "sudo apt-get install git-core git-svn git gitk ssh libssh-dev -y" print_str "-----> Git version" queue "git --version" end task :imagemagick do print_str "-----> Instalar ImageMagick" queue "sudo apt-get install imagemagick libmagickwand-dev -y" end namespace :mysql do task :install do print_str "-----> Instalar MySQL" queue "sudo apt-get install mysql-server libmysql-ruby mysql-client libmysqlclient-dev -y" end task :restart do print_str "-----> Restart Mysql server." queue "sudo restart mysql" end end task :ruby do print_str "-----> Instalar Ruby Stable" queue "sudo apt-get install libyaml-dev libssl-dev libreadline-dev libxml2-dev libxslt1-dev libffi-dev -y" queue "sudo mkdir -p /opt/local/src" queue "cd /opt/local/src" queue "sudo wget http://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p195.tar.bz2" queue "sudo tar xvf ruby-2.0.0-p195.tar.bz2" queue "cd /opt/local/src/ruby-2.0.0-p195" print_str "-----> Instalando Ruby" queue "sudo ./configure --prefix=/opt/local/ruby/2.0.0" queue "sudo make && sudo make install" queue "sudo ln -s /opt/local/ruby/2.0.0 /opt/local/ruby/current" queue "sudo ln -s /opt/local/src/ruby-2.0.0-p195 /opt/local/ruby/current" print_str "-----> Aplicacoes ficarao centralizadas em suas pastas, mas terao um link simbolico para a pasta bin e sbin" queue "sudo mkdir -p /opt/local/bin" queue "sudo mkdir -p /opt/local/sbin" print_str "-----> Criando links simbolicos para a pasta bin" queue "sudo ln -s /opt/local/ruby/current/bin/erb /opt/local/bin/erb" queue "sudo ln -s /opt/local/ruby/current/bin/gem /opt/local/bin/gem" queue "sudo ln -s /opt/local/ruby/current/bin/irb /opt/local/bin/irb" queue "sudo ln -s /opt/local/ruby/current/bin/rake /opt/local/bin/rake" queue "sudo ln -s /opt/local/ruby/current/bin/rdoc /opt/local/bin/rdoc" queue "sudo ln -s /opt/local/ruby/current/bin/ri /opt/local/bin/ri" queue "sudo ln -s /opt/local/ruby/current/bin/ruby /opt/local/bin/ruby" queue "sudo ln -s /opt/local/ruby/current/bin/testrb /opt/local/bin/testrb" print_str "-----> Criando links simbolicos para a pasta sbin" queue "sudo ln -s /opt/local/ruby/current/sbin/erb /opt/local/sbin/erb" queue "sudo ln -s /opt/local/ruby/current/sbin/gem /opt/local/sbin/gem" queue "sudo ln -s /opt/local/ruby/current/sbin/irb /opt/local/sbin/irb" queue "sudo ln -s /opt/local/ruby/current/sbin/rake /opt/local/sbin/rake" queue "sudo ln -s /opt/local/ruby/current/sbin/rdoc /opt/local/sbin/rdoc" queue "sudo ln -s /opt/local/ruby/current/sbin/ri /opt/local/sbin/ri" queue "sudo ln -s /opt/local/ruby/current/sbin/ruby /opt/local/sbin/ruby" queue "sudo ln -s /opt/local/ruby/current/sbin/testrb /opt/local/sbin/testrb" print_str "-----> Ruby version" queue "ruby -v" end task :update_gem do print_str "-----> Atualizar todas as gems" queue "sudo gem update --system" print_str "-----> Gem version" queue "gem -v" end task :bundler do print_str "-----> Instalar bundle" queue "sudo gem install bundler" end desc "Instalar Nginx" namespace :nginx do task :install do print_str "-----> Instalar nginx" queue "sudo apt-get install libpcre3-dev libssl-dev -y" queue "sudo wget http://nginx.org/download/nginx-1.4.1.tar.gz" queue "sudo tar xvf nginx-1.4.1.tar.gz" queue "cd nginx-1.4.1" queue "sudo ./configure --prefix=/opt/local/nginx/1.4.1 --with-http_ssl_module --with-http_realip_module --with-http_gzip_static_module --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/body --http-proxy-temp-path=/var/lib/nginx/proxy --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --with-debug --with-ipv6" queue "sudo make && sudo make install" queue "sudo ln -s /opt/local/nginx/1.4.1 /opt/local/nginx/current" print_str "-----> Criando links simbolicos para a pasta bin e sbin" queue "sudo ln -s /opt/local/nginx/current/bin/nginx /opt/local/bin/nginx" queue "sudo ln -s /opt/local/nginx/current/sbin/nginx /opt/local/sbin/nginx" print_str "-----> Nginx version" queue "nginx -v" end task :conf do print_str "-----> Configurando nginx" queue "sudo mkdir /var/www" queue "sudo chown ubuntu:ubuntu /var/www" queue "sudo chmod 774 /var/www" queue "sudo mkdir -p /var/lib/nginx/body" queue "sudo mkdir -p /var/lib/nginx/proxy" queue "sudo mkdir -p /var/lib/nginx/fastcgi" queue "sudo chown -R ubuntu:ubuntu /var/lib/nginx" queue "sudo mkdir -p /var/log/nginx/" queue "sudo chown ubuntu:ubuntu /var/log/nginx" queue "sudo mkdir /etc/nginx/ssl" queue "sudo mkdir /etc/nginx/sites-enabled" end end
# $Id$ module SlideshowsHelper def link_to_slideshow(contents, info={}) unless contents.empty? render :partial => 'shared/slideshow', :locals => {:contents => contents, :info=>info} end end # Create link with Lightview settings for Lightview slideshow. # Some content types like videos require additional div for inline display def link_to_slideshow_slide(content, options={}) # some content types need associated divs in order to be displayed # properly by Lightview. if content.playable? link_to_playable_slide(content, options) else link_to_slide(content, content.url, options) end end def link_to_playable_slide(content, options) options.merge!({ :duration => content.duration_seconds }) case content when WebVideo # Only use flash player if flash format capture show_video_link(content, options) do |p| link_to_slide(content, "##{dom_id(content)}", options) + p end when Audio, Music capture link_to_audio(content, options.merge(:hidden=>true)) do |p| link_to_slide(content, "##{dom_id(content)}", options) + p end else link_to_slide content, content.url, options end end def link_to_slide(content, target, options) opts = {:id => "slide_#{dom_id(content)}", :rel => options[:set], :title => "#{content.title} :: #{content.description}"}.merge(options) if content.width opts[:title] += " :: width: #{content.width}, height: #{content.height}" opts[:width] = content.width opts[:height] = content.height end opts[:class] = 'lightview' if options[:play_link] opts[:class] += ' play_slideshow' name = 'Play slideshow' else name = '' end text = with_options opts do |slide| slide.link_to name, target end end end
require_relative 'executable_source_code' require_relative 'source_code_reader' class ProcSourceCode < ExecutableSourceCode private def find_source_code_node(parsed_node) if parsed_node.type == :block block_node = parsed_node else block_node = parsed_node.children.find do |child| child.is_a?(Parser::AST::Node) && child.type == :block end unless block_node raise "Could not find definition for #{@obj}" end end # block_node children array: # [0] (send # (const nil :Proc) :new) # [1] (args) # [2] THE_BODY_NODE (can be any type if single-line, or ':begin' if multi-line) block_node.children[2] end end
class AddWonRoundsAgainstTiedRostersCountToLeagueRosters < ActiveRecord::Migration[5.0] def change add_column :league_rosters, :won_rounds_against_tied_rosters_count, :integer, default: 0, null: false League::Roster.all.each do |roster| roster.update_match_counters_tied! end end end
class User < ActiveRecord::Base has_one :login validates :name, :surname, :email, :birthdate, presence: true validates :email, uniqueness: { case_sensitive: false } end
class HumanReport < HumanBaseService # Faz a consulta dos status de uma lista de mensagens ao gateway de SMS. # @param [String] msg_ids Lista de identificadores das mensagens separados por ponto-e-vírgula. # @return [String] Resposta do gateway em formato de texto sendo que cada linha representa o status de cada mensagem na mesma ordem de consulta. def report_multiple(msg_ids) params = { :dispatch => 'checkMultiple', :account => @account, :code => @password, :idList => msg_ids, } send params end # Faz a consulta do status de uma unica mensagem ao gateway de SMS. # @param [String] msg_id Identificador da mensagem no gateway de SMS. # @return [String] Resposta do gateway com o status da mensagem. def report_single(msg_id) params = { :dispatch => 'check', :account => @account, :code => @password, :id => msg_id, } send params end end
Rails.application.routes.draw do mount OmniTag::Engine => "/omni_tag" end
class Florist < ActiveRecord::Base has_many :FloristDates, dependent: :destroy belongs_to :Vendor end
require 'rails_helper' RSpec.describe Shooter, type: :model do it 'can fire only at valid coordinates' do user_1 = create(:user) user_2 = create(:user2) game = Game.create(player_1_board: Board.new(4), player_2_board: Board.new(4), player_1_turns: 0, player_2_turns: 0, current_turn: "player 1", player_1_id: user_1.id, player_2_id: user_2.id ) coordinates = "A1" board_1 = game.player_1_board board_2 = game.player_2_board # binding.pry #ATTEMPT AT ALLOW_ANY_INSTANCE_OF # allow_any_instance_of(Board).to receive(:space_names).and_return("Hit") space = board_1.locate_space(coordinates) shooter = Shooter.new(board: board_1, target: "A1") # binding.pry shooter.fire! expect(space.status).to eq("Miss") coordinates_2 = "F9" space_2 = board_2.locate_space(coordinates_2) shooter_2 = Shooter.new(board: board_2, target: space_2) expect { shooter_2.fire! }.to raise_error(InvalidAttack) end end
class QueueCallResponse def initialize(call:) @call = call @response = Twilio::TwiML::VoiceResponse.new end def to_s call.greeting(response) response.enqueue( name: "queue", wait_url: RouteHelper.enqueued_call_wait_url, wait_url_method: "GET", action: RouteHelper.queue_call_url(call) ) response.to_s end private attr_reader :call, :response end
class AnswersController < ApplicationController # ------------------------- ROUTES --------------------------------- # party_quiz_answers # POST /party_quizzes/:party_quiz_id/answers(.:format) # answers#create # new_party_quiz_answer # GET /party_quizzes/:party_quiz_id/answers/new(.:format) # answers#new # ---------------------------------------------------------------------- def new # Récupération de la partie en cours @party_quiz = PartyQuiz.find_by(id: params[:party_quiz_id]) if @party_quiz.nil? redirect_to root_path, alert: "quiz not found." end # Récupération de la question en cours @question = @party_quiz.quiz.questions[@party_quiz.position_in_quiz] # Récupération des valeurs des options possibles @options = [[@question.options.first.id, @question.options.first.title], [@question.options.last.id, @question.options.last.title]] # Récupération de l'option qui est la bonne réponse @good_option = (@question.options.first.is_right) ? @question.options.first.id : @question.options.last.id # Initialisation de la nouvelle réponse @answer = Answer.new end def create # Récupération de la partie en cours @party_quiz = PartyQuiz.find_by(id: params[:party_quiz_id]) @quiz = Quiz.find_by(id: @party_quiz.quiz_id) # version pessimiste on vérifie la cohérence entre party_quiz et quiz if !@quiz.nil? # Verrou au cas ou qu'il y ai un clic sur les flèche retour du navigateur if @party_quiz.position_in_quiz > @quiz.questions.count redirect_to root_path end else redirect_to root_path end if !@party_quiz.nil? # Sauvegarde de la réponse fournit par l'utilisateur answer = Answer.new(answer_params) answer.party_quiz = @party_quiz answer.user = current_user if answer.save if Option.find(answer.option_id).is_right # Si l'option choisie est la bonne réponse alors on incrémente les scores @party_quiz.party_points += @quiz.points_by_question current_user.total_point += @quiz.points_by_question current_user.save end # On incrémente le numéro de la question et on sauvegarde le tout @party_quiz.position_in_quiz += 1 @party_quiz.save if @quiz.questions.count == @party_quiz.position_in_quiz # une fois toutes les questions répondues, on update la party_quiz @party_quiz.done =true @party_quiz.save # on va ensuite sur la show de quiz. # pour obtenir le résulat de la party_quiz redirect_to quiz_path @quiz.id else # Sinon on passe à la question suivante redirect_to new_party_quiz_answer_path end end end end private def answer_params params.require(:answer).permit(:option_id, :party_quiz_id) end end