text
stringlengths
10
2.61M
# frozen_string_literal: true Sentry.init do |config| config.dsn = ENV['SENTRY_DSN'] config.breadcrumbs_logger = %i[active_support_logger http_logger] config.traces_sample_rate = 0.5 end
# == Schema Information # # Table name: solutions # # id :integer not null, primary key # user_id :integer # challenge_id :integer # status :integer # created_at :datetime not null # updated_at :datetime not null # attempts :integer # properties :hstore # # Indexes # # index_solutions_on_challenge_id (challenge_id) # index_solutions_on_user_id (user_id) # solutions_gin_properties (properties) USING gin # require 'rails_helper' RSpec.describe Solution, type: :model do let(:user) { create(:user) } let(:challenge) { create(:challenge) } let(:solution) { create(:solution, challenge: challenge, user: user) } before do create(:level) create(:level, required_points: 100) create(:level, required_points: 200) end context 'associations' do it { should belong_to(:user) } it { should belong_to(:challenge) } it { should have_many(:documents) } end describe "challenge completion" do context "when user completes a challenge and creates the correct amount of points" do before do solution.update(status: Solution.statuses[:completed]) end it "creates a challenge_completion after a challenge is completed for the first time" do expect(ChallengeCompletion.find_by_challenge_id(challenge.id)).to_not eq(nil) end it "creates a challenge_completion after a challenge is completed for the second time" do solution.update(status: Solution.statuses[:failed]) solution.update(status: Solution.statuses[:completed]) expect(ChallengeCompletion.where(challenge_id: challenge.id).count).to eq(1) end it "doesn't add points to a user for a challenge that was already completed" do expected_points = user.stats.total_points solution.update(status: Solution.statuses[:failed]) solution.update(status: Solution.statuses[:completed]) expect(user.stats.total_points).to eq(expected_points) end end end describe ".log_activity" do context "when created" do it "logs the activity" do expect { solution }.to change(ActivityLog, :count).by(1) activity_log = ActivityLog.last expect(activity_log.description).to start_with "Inició" end end context "when a user makes an attempt" do it "logs the activity" do solution # we need to trigger the let expect { solution.failed! }.to change(ActivityLog, :count).by(1) activity_log = ActivityLog.last expect(activity_log.description).to start_with "Intentó" end end context "when a user completes the solution the first time" do it "logs the activity" do solution # we need to trigger the let expect { solution.completed! }.to change(ActivityLog, :count).by(1) activity_log = ActivityLog.last expect(activity_log.description).to start_with "Completó" end end context "when a user completes a completed solution" do it "doesn't logs the activity" do solution.completed! expect { solution.completed! }.to_not change(ActivityLog, :count) end end context "when a user attempts a completed solution" do it "doesn't logs the activity" do solution.completed! expect { solution.failed! }.to_not change(ActivityLog, :count) end end end end
class Product < ApplicationRecord belongs_to :user has_many :comments has_many :images has_many :likes, dependent: :destroy has_many :liking_users, through: :likes, source: :user with_options presence: true do validates :name validates :text validates :price validates :condition validates :shipping_charge validates :shipping_place validates :shipping_date validates :image, unless: :image? end mount_uploader :image, ImageUploader def self.search(search) return Product.all unless search Product.where('text LIKE(?)', "%#{search}%") end end
class Resque::WorkerStatusesController < ApplicationController def index @worker_statuses = Resque. workers. map(&:job). group_by { |x| x.present? }. transform_values { |x| x.size }. transform_keys { |x| x ? :working : :idoling } @worker_count = @worker_statuses.values.sum @working_count = @worker_statuses[:working] || 0 respond_to do |format| format.js end end end
require 'forwardable' require "tsv/version" require "tsv/row" require "tsv/table" module TSV extend self def parse(content, opts = {}, &block) TSV::Table.new(content, opts, &block) end def parse_file(filename, opts = {}, &block) TSV::Table.new(File.new(filename, 'r'), opts, &block) end alias :[] :parse_file class ReadOnly < StandardError end end
require "active_model/validations/presence" module Paperclip module Validators class MediaTypeSpoofDetectionValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) adapter = Paperclip.io_adapters.for(value) if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename, value.content_type).spoofed? record.errors.add(attribute, :spoofed_media_type) end adapter.tempfile.close(true) if adapter.tempfile end end module HelperMethods # Places ActiveModel validations on the presence of a file. # Options: # * +if+: A lambda or name of an instance method. Validation will only # be run if this lambda or method returns true. # * +unless+: Same as +if+ but validates if lambda or method returns false. def validates_media_type_spoof_detection(*attr_names) options = _merge_attributes(attr_names) validates_with MediaTypeSpoofDetectionValidator, options.dup validate_before_processing MediaTypeSpoofDetectionValidator, options.dup end end end end
require 'nestling' class Recommender < ActiveRecord::Base def self.recommend_tracks_from_artist(artist=artist, client=Nestling.new) playlist_rec = client.playlist.static( artist: artist, bucket: "id:rdio-us-streaming", type: "artist-radio", limit: true ) parse_response(playlist_rec) end def self.parse_response(rec) rdio_tracks = [] rec.each do |track| track = RdioTrack.new( artist: track[:artist_name], title: track[:title], rdio_id: track[:foreign_ids].first["foreign_id"].split(":").last ) rdio_tracks << track end rdio_tracks end end
require './helpers/test_helper' class APIController < ApplicationController helpers Sinatra::TestHelpers get '/api/v1/testuser' do content_type :json test_user.to_json end get '/api/v1/users' do content_type :json { count: User.count }.to_json end get '/api/v1/follows' do content_type :json { count: Follow.count }.to_json end get '/api/v1/tweets' do content_type :json { count: Tweet.count }.to_json end get '/api/v1/users/:id' do user = User.find_by(id: params[:id]) if user user.to_json else error 404, {:error => "user not found"}.to_json end end get '/api/v1/tweets/:id' do if params[:id] == 'recent' tweet = Tweet.recent(50) else tweet = Tweet.find_by(id: params[:id]) end if tweet tweet.to_json else error 404, {:error => "tweet not found"}.to_json end end get '/api/v1/users/:id/tweets' do user = User.find_by(id: params[:id]) if !user error 404, {:error => 'no user found'}.to_json else user_recent_tweets = Tweet.recent(50, user) if user_recent_tweets user_recent_tweets.to_json else error 404, {:error => "no recent tweets found from user"}.to_json end end end get '/api/v1/users/:id/followers' do user = User.find_by(id: params[:id]) if !user error 404, {:error => 'no user found'}.to_json else followers = Follow.get_followers(user) if followers followers.to_json else error 404, {:error => "no followers found"}.to_json end end end get '/api/v1/users/:id/following' do user = User.find_by(id: params[:id]) if !user error 404, {:error => "no user found"}.to_json else followers = Follow.get_followings(user) if followers followers.to_json else error 404, {:error => "no followers found"}.to_json end end end get '/api/v1/users/:id/retweets' do user = User.find_by(id: params[:id]) if !user error 404, {:error => "no user found"}.to_json else retweets = Retweet.recent(100, user) if retweets retweets.to_json else error 404, {:error => "no retweets found"}.to_json end end end get '/api/v1/users/:id/favorites' do user = User.find_by(id: params[:id]) if !user error 404, {:error => "no user found"}.to_json else favorite = Favorite.recent(50, user) if favorite favorite.to_json else error 404, {:error => "no favorites found"}.to_json end end end end
#!/usr/bin/env ruby require_relative 'table.rb' require_relative 'view.rb' ## #This whole script is just a bunch of AIDA-specific #examples of how to use table and view classes def join_arg_ments_and_kb_id_ents_tables(arg_ments_table, kb_id_ents_table) hash = {:table_a => arg_ments_table, :table_b => kb_id_ents_table, :a_key => "argmention_id", :b_key => "mention_id", :a_cols => ["type", "subtype", "subsubtype", "level", "provenance_type"], :b_cols => ["kb_id"]} table = Table.new(hash) end def split_kb_linking_tab_file(tab) tables = Table::split_input_tab_file(tab, "mention_type", ["entity", "event", "relation"]) end def count_arg_subsubtypes_per_kb_id(table) ids = ["kb_id"] attrbs = ["type", "subtype", "subsubtype"] view = View.new(table, ids, attrbs) end def count_arg_prov_types_per_kb_id(table) ids = ["kb_id"] attrbs = ["provenance_type"] view = View.new(table, ids, attrbs) end def count_arg_levels_per_kb_id(table) ids = ["kb_id"] attrbs = ["level"] view = View.new(table, ids, attrbs) end def join_arg_ments_and_kb_ids_tables(arg_ments_tab_file, kb_tab_file) kb_tables = split_kb_linking_tab_file(kb_tab_file) table = join_arg_ments_and_kb_id_ents_tables(Table.new({:tab => arg_ments_tab_file}), kb_tables[0]) end table = join_arg_ments_and_kb_ids_tables(ARGV[0], ARGV[1]) views = [] views.push(count_arg_subsubtypes_per_kb_id(table)) views.push(count_arg_levels_per_kb_id(table)) views.push(count_arg_prov_types_per_kb_id(table)) views.each do |view| vt = view.to_table #TODO print each table end
class DropCaracteristicasTable < ActiveRecord::Migration[5.0] def change drop_table :caracteristicas end end
cask 'digital-power-station' do version :latest sha256 :no_check url 'http://www.dpsplugin.com/download/BongioviAcousticsDPS.dmg' name 'Digital Power Station' name 'DPS Plugin' homepage 'http://dpsplugin.com/home/' license :closed tags :vendor => 'Bongiovi' pkg 'Digital Power Station Installer.pkg' uninstall :pkgutil => 'com.bongiovi.pkg.DigitalPowerStation.*' end
class ConcertsController < ApplicationController def index @concerts = Concert.all.what_is_happening_today @concerts_last_mont = Concert.all.what_is_happening_last_month end def new @concert = Concert.new end def create @concert = Concert.new(entry_params) if @concert.save redirect_to concert_path(@concert) else render 'new' end end def show @comment = Comment.new render ('concert_not_found') unless (@concert = Concert.find_by id: params[:id]) end def show_most_popular @concerts = Concert.all.where("date>?", Date.today) ids = [] how_many_comments_concerts = [] @concerts.each do |concert| binding.pry how_many_comments = concert.comments.length concert.comments.each do |comment_id| ids << comment_id.id end end @comments = @concerts.comments end private def entry_params params.require(:concert).permit(:band,:venue,:city,:date,:price,:description) end end
module Ricer::Plugins::Poll class Newpollm < NewpollBase trigger_is :'+multiplechoice' has_usage :execute, '<..question|option1|option2|..>' def execute(message) create_poll(message, Question::MULTI) end end end
class MarkersController < ApplicationController before_action :set_marker, only: [:destroy] # POST /markers # POST /markers.json def create @marker = current_user.markers.new(marker_params) respond_to do |format| if @marker.save format.html { redirect_to dashboard_path, notice: 'Marker was successfully created.' } format.js { render :show, locals: { action: true, id: @marker.id, lat: @marker.lat, lng: @marker.lng, title: @marker.title, description: @marker.description } } else format.html { redirect_to dashboard_path, notice: 'Marker was not created.' } format.js { render :show, locals: { action: false } } end end end # DELETE /markers/1 # DELETE /markers/1.json def destroy @marker.destroy markers = current_user.markers.all respond_to do |format| format.html { redirect_to dashboard_path, notice: 'Marker was successfully destroyed.' } format.js { render :destroy, locals: { markers: markers } } end end private # Use callbacks to share common setup or constraints between actions. def set_marker @marker = current_user.markers.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def marker_params params.require(:marker).permit(:lat, :lng, :title, :description, :user_id) end end
class AddImportsGoodsServicesPercentageGdpToYears < ActiveRecord::Migration def change add_column :years, :imports_goods_services_percentage_gdp, :decimal end end
require 'pry' require 'colorize' def init system "clear" puts " ==================================================" puts "| QUICK MATH DOJO |" puts " ==================================================" print "Player 1, enter name: " @first_player_name = gets.chomp.capitalize print "Player 2, enter name: " @second_player_name = gets.chomp.capitalize print "Initializing game ... " show_wait_cursor(1) puts @first_player_score, @second_player_score = 0, 0 @first_player_lives, @second_player_lives = 3, 3 print_game_status end def show_wait_cursor(seconds,fps=15) chars = %w[| / - \\] delay = 1.0/fps (seconds*fps).round.times{ |i| print chars[i % chars.length] sleep delay print "\b" } end def print_game_status puts "[ #{@first_player_name} (Score: #{@first_player_score})(Lives: #{@first_player_lives}) ] vs [ #{@second_player_name} (Score: #{@second_player_score})(Lives: #{@second_player_lives}) ]".colorize(:red) end def generate_question random_generator = Random.new operators_list = ['+','-','*','/'] operator = operators_list[random_generator.rand(0..3)] first_number = random_generator.rand(20).to_s second_number = (random_generator.rand(20)+1).to_s expression = first_number + " " + operator + " " +second_number answer = eval(expression) [expression, answer] end def prompt_player(player_name, question, fg_color, bg_color) print "#{player_name.colorize(fg_color).colorize(:background => bg_color)}: What does #{question} equal? " answer = gets.chomp.to_i end def verify_answer(user_input, answer) user_input == answer ? true : false end def determine_winner if @first_player_score == @second_player_score winner = "none" elsif @first_player_score > @second_player_score winner = @first_player_name else winner = @second_player_name end if winner == "none" puts "\n\n" puts " ================================================================ " puts "| Yikes! Its a tie :/ |" puts " ================================================================ " else puts "\n\n" puts " ================================================================ " puts "| #{winner.colorize(:green).on_blue.underline} has won! |" puts " ================================================================ " end end def play_game turn_counter = 1 while (@first_player_lives > 0 && @second_player_lives > 0) question = generate_question if turn_counter % 2 == 0 player_answer = prompt_player(@first_player_name, question[0], :yellow, :blue) verify_answer(player_answer, question[1]) ? @first_player_score += 1 : ( @first_player_lives -= 1; print_game_status ) else player_answer = prompt_player(@second_player_name, question[0], :green, :light_blue) verify_answer(player_answer, question[1]) ? @second_player_score += 1 : ( @second_player_lives -= 1 ; print_game_status ) end turn_counter+=1 end print "Game over! Calculating scores ..." show_wait_cursor(1) determine_winner print "\nFinal scores: ".colorize(:green) print_game_status end def restart_or_exit puts "\n-> [r]estart game\n->[q]uit game" print "[r] /[q] > " response = gets.chomp.downcase case response when "r" restart_game = true when "q" restart_game = false else restart_game = false end restart_game end def main loop do init play_game restart_or_exit ? next : break end puts "Thank you for playing quick math dojo today! \a \a \a" puts "=====================================================" end # binding.pry main
class Currency < ActiveRecord::Base has_many :countries validates :name, presence: true validates :name, uniqueness: true before_destroy :confirm_presence_of_countries def confirm_presence_of_countries if countries.any? return false end end end
class Course < ActiveRecord::Base extend FriendlyId # Configuration friendly_id :name, use: :slugged # Associations has_many :tutorials, inverse_of: :course, dependent: :destroy has_many :tags, through: :tutorials # Attributes # Validations validates :name, presence: true, uniqueness: {case_sensitive: false} validates_format_of :image_url, with: URI::regexp(%w(http https)) # Scopes # Callbacks end
class SignupMailer < ApplicationMailer def signup_confirmation(to_email) @to_email = to_email mail(to: @to_email, subject: "Localhst Signup") end end
#encoding: utf-8 class WorkOrder < ActiveRecord::Base # Constants # Put here constants for WorkOrder # Relations belongs_to :responsible, class_name: 'User', foreign_key: 'responsible_id' belongs_to :work_order_status belongs_to :organisation has_many :samples, dependent: :restrict_with_error has_many :sample_types, through: :samples has_many :sample_type_versions, through: :samples has_many :specimens, through: :samples has_many :specimen_types, through: :specimens has_many :specimen_type_versions, through: :specimens has_many :lab_tests, through: :specimens has_many :test_types, through: :lab_tests has_many :test_type_versions, through: :lab_tests # Callbacks # Put here custom callback methods for WorkOrder # Validations validates :name, presence: true # validates :description, <validations> # validates :due_date, <validations> validates :responsible, presence: true validates :work_order_status, presence: true validates :organisation, presence: true # Scopes (used for search form) # Put here custom queries for WorkOrder scope :by_name, ->(name) { where("name ILIKE ?", "%#{name}%") } # Scope for search # Instance methods # Override to_s method def to_s (defined? name)? name : ((defined? email)? email : id) # editable end end
module AutoSpecs module ActiveRecord module Associations MAPPINGS = { belongs_to: 'belong_to', has_many: 'have_many', has_one: 'have_one', has_many: 'have_many', has_and_belongs_to_many: 'have_and_belongs_to_many' } end end end
require 'feidee_utils' require "feidee_utils_test" require 'minitest/autorun' require 'pathname' class FeideeUtils::IntegrationTest < MiniTest::Test def setup base_path = Pathname.new(File.dirname(__FILE__)) @sqlite_db = FeideeUtils::Database.open_file(base_path.join("../data/QiQiTest.sqlite")) @complex_android_backup = FeideeUtils::Database.open_file(base_path.join("../data/Daily_20140401.sqlite")) end def do_test_field_coverage sqlite_db # All mapped fields must exist. All fields must either be mapped or # ignored. FeideeUtils::Record.child_classes.each do |klass| row = sqlite_db.query("SELECT * FROM #{klass.table_name} LIMIT 1"); existing_fields = (Set.new row.columns) - # Two fields covered by accessors.rb [klass.id_field_name, "lastUpdateTime"] mapped_fields = Set.new (klass.const_get :FieldMappings).values ignored_fields = Set.new (klass.const_get :IgnoredFields) # Mapped fields are a subset of exising fields. assert mapped_fields.subset?(existing_fields), "Mapped fields #{mapped_fields - existing_fields} does not appear." # Fields other than those mapped must be a subset of ignored fields. non_mapped_fields = existing_fields - mapped_fields assert non_mapped_fields.subset?(ignored_fields), "Fields #{(non_mapped_fields - ignored_fields).to_a} are not covered." end end def test_field_coverage_android do_test_field_coverage @complex_android_backup end def test_field_coverage_ios do_test_field_coverage @sqlite_db end end
class SplitNameToFirstAndLastNameParts < ActiveRecord::Migration def change rename_column :people, :name, :FirstName add_column :people, :LastName, :string end end
class AddBriefToPersonalData < ActiveRecord::Migration def change add_column :personal_data, :brief, :text end end
class Ticket < ActiveRecord::Base belongs_to :user belongs_to :itpro def self.added where(status: 'added') end def self.in_work where(status: 'in_work') end def self.done where(status: 'done') end def self.opened where(status: ['in_work','added']) end def self.last_two_days where('created_at > ?', Date.today - 2.days) end end
require 'rails_helper' RSpec.describe Bookmark, type: :model do let(:url) {Faker::Internet.url} let(:title){Faker::Science.unique.element } let(:topic) { Topic.create!(title: title, user: user) } let(:user){User.create!(username: "BlocmarksUser", email: "user@blocmarks.com", password: "helloworld") } let(:bookmark) { Bookmark.create!(url: url, topic: topic, user: user) } it { is_expected.to belong_to(:topic)} describe "attributes" do it "has a url" do expect(bookmark).to have_attributes(url: url, topic: topic) end end end
require 'spec_helper' describe T::Config do subject do described_class.new end context 'window_automatic_rename' do it 'defaults to nil' do expect( subject.window_automatic_rename ).to be_nil end it 'but it can be set' do subject.window_automatic_rename true expect( subject.window_automatic_rename ).to eq true end end # context 'window_automatic_rename' end # describe T::Config
class ServicesController < ApplicationController skip_before_action :verify_authenticity_token def book_service if current_user BookedService.create(booked_service_params) flash[:success] = "Service Booked successfully" redirect_to root_path else cookies[:service_id] = params[:booked_service][:service_id] cookies[:postal_code] = params[:booked_service][:postal_code] cookies[:preffered_date] = params[:booked_service][:preffered_date] cookies[:preffered_time] = params[:booked_service][:preffered_time] end end def get_rate_per_hour service=Service.find_by_id(params[:id]) render :json => {rate: service.rate_per_hour} end private def booked_service_params params.require(:booked_service).permit(:service_id, :user_id, :preffered_date, :preffered_time, :postal_code, :hours_booked) end end
# frozen_string_literal: true # rubocop:todo all require 'lite_spec_helper' describe Mongo::Crypt::Binary do require_libmongocrypt let(:data) { 'I love Ruby' } let(:binary) { described_class.from_data(data) } describe '#initialize' do context 'with nil data' do let(:binary) { described_class.new } it 'creates a new Mongo::Crypt::Binary object' do expect do binary end.not_to raise_error end end context 'with valid data' do let(:binary) { described_class.new(data: data) } it 'creates a new Mongo::Crypt::Binary object' do expect do binary end.not_to raise_error end end context 'with pointer' do let(:pointer) { Mongo::Crypt::Binding.mongocrypt_binary_new } let(:binary) { described_class.new(pointer: pointer) } after do Mongo::Crypt::Binding.mongocrypt_binary_destroy(pointer) end it 'creates a new Mongo::Crypt::Binary object from pointer' do expect do binary end.not_to raise_error expect(binary.ref).to eq(pointer) end end end describe '#self.from_data' do let(:binary) { described_class.from_data(data) } it 'creates a new Mongo::Crypt::Binary object' do expect do binary end.not_to raise_error end end describe '#self.from_pointer' do let(:pointer) { Mongo::Crypt::Binding.mongocrypt_binary_new } let(:binary) { described_class.from_pointer(pointer) } after do Mongo::Crypt::Binding.mongocrypt_binary_destroy(pointer) end it 'creates a new Mongo::Crypt::Binary object from pointer' do expect do binary end.not_to raise_error expect(binary.ref).to eq(pointer) end end describe '#to_s' do it 'returns the original string' do expect(binary.to_s).to eq(data) end end describe '#write' do # Binary must have enough space pre-allocated let(:binary) { described_class.from_data("\00" * data.length) } it 'writes data to the binary object' do expect(binary.write(data)).to be true expect(binary.to_s).to eq(data) end context 'with no space allocated' do let(:binary) { described_class.new } it 'returns false' do expect do binary.write(data) end.to raise_error(ArgumentError, /Cannot write #{data.length} bytes of data to a Binary object that was initialized with 0 bytes/) end end context 'without enough space allocated' do let(:binary) { described_class.from_data("\00" * (data.length - 1)) } it 'returns false' do expect do binary.write(data) end.to raise_error(ArgumentError, /Cannot write #{data.length} bytes of data to a Binary object that was initialized with #{data.length - 1} bytes/) end end end end
=begin Copyright (c) 2013 ExactTarget, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =end require "fuelsdk/version" require 'rubygems' require 'date' require 'jwt' module FuelSDK require 'fuelsdk/utils' autoload :HTTPRequest, 'fuelsdk/http_request' autoload :Targeting, 'fuelsdk/targeting' autoload :Soap, 'fuelsdk/soap' autoload :Rest, 'fuelsdk/rest' require 'fuelsdk/client' require 'fuelsdk/objects' end # backwards compatability ET_Client = FuelSDK::Client ET_BounceEvent = FuelSDK::BounceEvent ET_ClickEvent = FuelSDK::ClickEvent ET_ContentArea = FuelSDK::ContentArea ET_DataExtension = FuelSDK::DataExtension ET_DataFolder = FuelSDK::DataFolder ET_Folder = FuelSDK::Folder ET_Email = FuelSDK::Email ET_List = FuelSDK::List ET_OpenEvent = FuelSDK::OpenEvent ET_SentEvent = FuelSDK::SentEvent ET_Subscriber = FuelSDK::Subscriber ET_UnsubEvent = FuelSDK::UnsubEvent ET_TriggeredSend = FuelSDK::TriggeredSend ET_Campaign = FuelSDK::Campaign ET_Get = FuelSDK::Get ET_Post = FuelSDK::Post ET_Delete = FuelSDK::Delete ET_Patch = FuelSDK::Patch ET_ProfileAttribute = FuelSDK::ProfileAttribute ET_Import = FuelSDK::Import
module Periplus class Location < BingResponse attr_accessor :latitude attr_accessor :longitude attr_accessor :address attr_accessor :confidence attr_accessor :entity_type attr_accessor :name def parse super() point = @primary_resource["point"] @latitude, @longitude = point["coordinates"] @name = @primary_resource["name"] @address = @primary_resource["address"] @confidence = @primary_resource["confidence"].downcase.to_sym @entity_type = @primary_resource["entityType"].downcase.to_sym end end end
class ItemSerializer < ActiveModel::Serializer attributes :description, :created_at, :completed, :id has_one :list def created_at object.created_at.strftime('%Y-%B-%d') end end
class Public::OrdersController < ApplicationController before_action :authenticate_customer! before_action :order_validation, only: [:new, :confirm] def index @orders = Order.where(customer_id: current_customer.id).page(params[:page]).per(10) end def show @order = Order.find(params[:id]) end def new @order = Order.new @addresses = current_customer.addresses end def create @order = Order.new(order_params) @order.customer_id = current_customer.id if @order.save @cart_products = current_customer.cart_products.all @cart_products.each do |cart_product| @order_products = @order.order_products.new @order_products.product_id = cart_product.product.id @order_products.quantity = cart_product.quantity @order_products.tax_in_price = cart_product.product.tax_included_price.to_i @order_products.save current_customer.cart_products.destroy_all end redirect_to orders_thanks_path else render :confirm end end def confirm @order = Order.new(order_params) @cart_product = current_customer.cart_products @order.postage = 800 @order.total_price = 0 @cart_product.each do |cp| @order.total_price += cp.quantity * cp.product.tax_included_price.to_i end @billing_amount = @order.postage + @order.total_price if params[:order][:address_option] == "0" @order.shipping_postal_code = current_customer.postal_code @order.shipping_address = current_customer.address @order.shipping_name = current_customer.last_name + current_customer.first_name elsif params[:order][:address_option] == "1" @address = Address.find(params[:order][:order_address]) @order.shipping_postal_code = @address.postal_code @order.shipping_address = @address.address @order.shipping_name = @address.address_name elsif params[:order][:address_option] == "2" if (@order.shipping_postal_code.empty?) @order = Order.new @addresses = current_customer.addresses render :new elsif (@order.shipping_address.empty?) @order = Order.new @addresses = current_customer.addresses render :new elsif (@order.shipping_name.empty?) @order = Order.new @addresses = current_customer.addresses render :new end end end def thanks end private def order_params params.require(:order).permit(:shipping_postal_code, :shipping_address, :shipping_name, :payment_method, :total_price, :postage) end def order_validation if current_customer.cart_products.exists? else redirect_to cart_products_path end end end
require 'spec_helper' describe file('/etc/apt/sources.list') do it { should be_file } it { should contain "deb #{property['apt_ubuntu_uri']}" } it { should contain property['apt_ubuntu_components'].join(' ') } it { should be_mode 644 } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } end
module Dieroll class DiceSet attr_reader :last_results #Create DiceSet object def initialize(number_of_dice, sides, sign='+', drop_string=nil) @number_of_dice, @sides, @sign = number_of_dice, sides, sign @drop_string = drop_string @drops = @drop_string.scan(/[l|h]/) if !!@drop_string @dice = [] @number_of_dice.times do @dice << Dieroll::Die.new(@sides) end @last_results = [] @last_total = nil end #Rolls the DiceSet. Returns the result. def roll(save=false) results = [] @dice.each do |die| if save results << die.roll! else results << die.roll end end results.sort! last_non_dropped = results.dup if !!@drops @drops.each do |drop| last_non_dropped.shift if drop == 'l' last_non_dropped.pop if drop == 'h' end end total = last_non_dropped.inject(0){|sum, element| sum + element} total *= -1 if @sign == '-' @last_results = results if save @last_non_dropped = last_non_dropped if save @last_total = total if save total end #Rolls the DiceSet. Returns the result. #Updates @last_total, @last_result, @last_non_dropped def roll! roll(true) end #Returns a string with details of the last roll. def report output = "#{@sign}#{@number_of_dice}d#{@sides}" output += "/#{@drop_string}" if !!@drop_string output += ": " @dice.each do |die| output += die.to_s + " " end output end #Returns the Odds for the DiceSet. Creates Odds if it doesn't exist. def odds calculate_odds unless !!@odds @odds end #Returns @last_total as a string. def to_s @last_total.to_s end private #Creates a new Odds object for the DiceSet. def calculate_odds if !@drops @odds = @dice[0].odds ** @number_of_dice if(@sign == '-') @odds.offset = @sides * @number_of_dice * -1 end else possibilities = [] num_possibilities = @sides ** @number_of_dice current_side = 1 @number_of_dice.times do |dice| possibilities.sort! num_possibilities.times do |possibility| possibilities[possibility] ||= [] possibilities[possibility] << current_side current_side += 1 current_side = 1 if current_side > @sides end end combinations_array = [] possibilities.each do |possibility| possibility.sort! @drops.each do |drop| possibility.shift if drop == 'l' possibility.pop if drop == 'h' end total = possibility.inject(0) {|sum, element| sum + element} combinations_array[total] ||= 0 combinations_array[total] += 1 end offset = @number_of_dice - @drops.size offset.times do combinations_array.shift end @odds = Dieroll::Odds.new(combinations_array, offset) end end end end
require 'homebus' class HomebusOctoprint::Options < Homebus::Options def app_options(op) server_help = 'Server URL, like "https://ummon:5000" or "http://10.0.1.104"' apikey_help = 'API key from Octoprint' op.separator 'homebus-octoprint options:' op.on('-s', '--server-url SERVER-URL', server_help) { |value| options[:server] = value } op.on('-a', '--api-key APIKEY', apikey_help) { |value| options[:api_key] = value } end def server_help end def banner 'HomeBus Octoprint publisher' end def version HomebusOctoprint::VERSION end def name 'homebus-octoprint' end end
class AdminsBackoffice::SubjectsController < AdminsBackofficeController before_action :set_subject, only: [:edit] def index respond_to do |format| format.html { @subjects = Subject.all.order(:description).page(params[:page]).per(5) } format.pdf { @subjects = Subject.all.order(:description) } format.json { (@subjects = Subject.all.order(:description)) } end end def new @subject = Subject.new() end def edit end def create st, resp = AdminsBackoffice::SubjectsService.create(params_subject) case st when :success then redirect_to admins_backoffice_subjects_path, resp else @subject = resp render :new end end def destroy st, resp = AdminsBackoffice::SubjectsService.destroy(params) case st when :success then redirect_to admins_backoffice_subjects_path, resp else @subject = resp redirect_to admins_backoffice_subjects_path end end def update st, resp = AdminsBackoffice::SubjectsService.update(params_subject) case st when :success then redirect_to admins_backoffice_subjects_path, resp else @subject = resp render :edit end end private def set_subject @subject = Subject.find(params[:id]) end def params_subject params.require(:subject).permit(:id, :description) end end
class AddSequenceAndUuidToAllJoke < ActiveRecord::Migration[5.2] def change add_column :all_jokes, :sequence, :integer add_column :all_jokes, :uuid, :integer end end
class AddArticleIdToInputbybudgetanditems < ActiveRecord::Migration def change add_column :inputbybudgetanditems, :article_id, :integer end end
# == Schema Information # # Table name: partner_codes # # id :integer not null, primary key # partner_deal_id :integer not null # code :string(255) not null # user_id :integer # expires_at :datetime # claimed_at :datetime # class PartnerCode < ActiveRecord::Base scope :unclaimed, -> { where(user: nil) } belongs_to :partner_deal belongs_to :user end
require 'test_helper' class PostsControllerTest < ActionController::TestCase test "should get index page" do get :index assert_response :success assert_template "posts/index" assert_select "article h3.title a", Post.all.count end test "should get show page" do get :show, {'id' => posts(:rails_rules).id} assert_response :success assert_template "posts/show" assert_select "article h1.title", {:count => 1, :text => posts(:rails_rules).title} end test "should return not found page" do #should return error in show page, because post not exist get :show, {'id' => 100} assert_response :not_found assert_template "common/not_found" end end
class Glass < ApplicationRecord belongs_to :wine end
require 'helper' require 'fluent/test/driver/output' if ENV['LIVE_TEST'] require "glint" require "tmpdir" system "go", "build", "test/mockserver.go" end class ZabbixOutputTest < Test::Unit::TestCase def setup Fluent::Test.setup if ENV['LIVE_TEST'] $dir = Dir.mktmpdir $server = Glint::Server.new(10051, { timeout: 3 }) do |port| exec "./mockserver", $dir.to_s + "/trapper.log" end $server.start end end CONFIG = %[ zabbix_server 127.0.0.1 host test_host add_key_prefix ${tag} name_keys foo, bar, baz, f1, f2 ] def create_driver(conf = CONFIG) Fluent::Test::Driver::Output.new(Fluent::Plugin::ZabbixOutput).configure(conf) end def test_write d = create_driver if ENV['LIVE_TEST'] d.run(default_tag: 'test') do d.feed({"foo" => "test value of foo"}) d.feed({"bar" => "test value of bar"}) d.feed({"baz" => 123.4567 }) d.feed({"foo" => "yyy", "zabbix_host" => "alternative-hostname"}) d.feed({"f1" => 0.000001}) d.feed({"f2" => 0.01}) sleep 1 end $server.stop assert_equal open($dir + "/trapper.log").read, <<END host:test_host key:test.foo value:test value of foo host:test_host key:test.bar value:test value of bar host:test_host key:test.baz value:123.4567 host:test_host key:test.foo value:yyy host:test_host key:test.f1 value:0.0 host:test_host key:test.f2 value:0.01 END end end CONFIG_HOST_KEY = %[ zabbix_server 127.0.0.1 host test_host host_key host add_key_prefix test name_keys foo, bar, baz ] def create_driver_host_key(conf = CONFIG_HOST_KEY) Fluent::Test::Driver::Output.new(Fluent::Plugin::ZabbixOutput).configure(conf) end CONFIG_PREFIX_KEY = %[ zabbix_server 127.0.0.1 host test_host prefix_key prefix name_keys foo, bar, baz ] def create_driver_prefix_key(conf = CONFIG_PREFIX_KEY) Fluent::Test::Driver::Output.new(Fluent::Plugin::ZabbixOutput).configure(conf) end def test_write_host_key d = create_driver_host_key if ENV['LIVE_TEST'] d.run(default_tag: 'test') do d.feed({"foo" => "AAA" }) d.feed({"foo" => "BBB", "host" => "alternative-hostname"}) sleep 1 end $server.stop assert_equal open($dir + "/trapper.log").read, <<END host:test_host key:test.foo value:AAA host:alternative-hostname key:test.foo value:BBB END end end def test_write_prefix_key d = create_driver_prefix_key if ENV['LIVE_TEST'] d.run(default_tag: 'test') do d.feed({"foo" => "AAA"}) d.feed({"foo" => "BBB", "prefix" => "p"}) sleep 1 end $server.stop assert_equal open($dir + "/trapper.log").read, <<END host:test_host key:foo value:AAA host:test_host key:p.foo value:BBB END end end end
Rails.application.routes.draw do devise_for :users # get '/', to: 'users#form_login' # post '/', to: 'users#login' # get '/users/new', to: 'users#new' get '/users/:id', to: 'users#show', as: :user_show # post '/users', to: 'users#create' # delete '/users/:id', to: 'users#destroy', as: :users_destroy get '/users/:user_id/products', to: 'products#index' get '/users/:user_id/products/new', to: 'products#new', as: :user_products_new get '/users/:user_id/products/:id', to: 'products#show', as: :user_products_show post '/users/:user_id/products', to: 'products#create', as: :user_products delete '/users/:user_id/products/:id', to: 'products#destroy', as: :user_products_destroy post '/products/:product_id/bids', to: 'bids#create' post '/products/:product_id/buynow', to: 'products#buynow' resources :reviews, only: [:create, :edit, :update, :destroy] get '/api/users/:user_id/seller_reviews', to: 'seller_reviews#show' end
class UsersController < ApplicationController before_filter :authenticate_user! authorize_resource def index @s = params[:s] || "type" @r = params[:r] || false @users = User.sorted_by @s @users.reverse! if @r == "true" end def edit @user = User.find params[:id] @shared_jobs = @user.shared_jobs.order("created_at desc") end def update @user = User.find params[:id] @user.type = params[:user][:type] params[:user].delete :type if params[:user][:password].nil? or params[:user][:password].length <= 0 params[:user].delete(:password) end if @user.update_attributes params[:user] redirect_to users_path else render :edit end end def destroy @user = User.find(params[:id]) if @user @user.delete redirect_to users_path end end def batch_shares if(!params[:shared_jobs] || params[:shared_jobs].length < 1) return redirect_to users_path end user = User.find(params[:id]) share_ids = params[:shared_jobs].keys.map(&:to_i) shares = user.shares.where(job_id: share_ids).index_by(&:job_id) ActiveRecord::Base.transaction do begin params[:shared_jobs].each do |job_id, values| if values[:is_shared] permissions_params = values.except(:is_shared).sort.reverse.to_h shares[job_id.to_i].update_attributes!(permissions: permissions_params.values.join.to_i(2)) else shares[job_id.to_i].delete end end flash[:notice] = "Updated shared jobs successfully" rescue => e flash[:error] = e.message end end redirect_to users_path end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable attr_accessor :friend_id # Matches I made for somebody has_many :matchmaker_matches, foreign_key: :matchmaker_id, class_name: "Match" # Matches a matchmaker friend made for me has_many :friend_matches, foreign_key: :friend_id, class_name: "Match" # Matches a matchmaker of another person made for me has_many :matchee_matches, foreign_key: :matchee_id, class_name: "Match" has_many :friendships has_many :friends, through: :friendships has_many :availabilities, dependent: :destroy has_many :friend_dates, through: :friend_matches, source: :match_date has_many :matchee_dates, through: :matchee_matches, source: :match_date def dates friend_dates.or(matchee_dates) end after_create :set_up_friendship, if: :friend_id after_create :create_availabilities def available_matchees_for(friend) self.class.where.not(id: [id, friend.id]). where.not(id: friend.matchee_matches.map {|match| match.friend_id}). where.not(id: friend.friend_matches.map {|match| match.matchee_id}) end def potential_matches # Rename the method and add additional user friend_matches.matchmaker_matched + matchee_matches.friend_accepted end def official_dates friend_matches.matchee_accepted + matchee_matches.matchee_accepted end def available_times_this_week availabilities.map do |availability| days_from_monday = Date::DAYNAMES.index(availability.weekday.capitalize) - 1 availability.times.map do |hour| DateTime.now.next_week.advance(days: days_from_monday, hours: hour.to_i) end end.flatten end private def create_availabilities Availability.create(user: self, weekday: 'thursday') Availability.create(user: self, weekday: 'friday') Availability.create(user: self, weekday: 'saturday') end def set_up_friendship Friendship.create(user_id: self.id, friend_id: friend_id) end end
class CreateJoinTableUserPair < ActiveRecord::Migration[5.0] def change create_join_table :users, :pairs do |t| t.index [:user_id, :pair_id] t.index [:pair_id, :user_id] 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 Europe module Brussels include TimezoneDefinition timezone 'Europe/Brussels' do |tz| tz.offset :o0, 1050, 0, :LMT tz.offset :o1, 1050, 0, :BMT tz.offset :o2, 0, 0, :WET tz.offset :o3, 3600, 0, :CET tz.offset :o4, 3600, 3600, :CEST tz.offset :o5, 0, 3600, :WEST tz.transition 1879, 12, :o1, 1386844121, 576 tz.transition 1892, 5, :o2, 1389438713, 576 tz.transition 1914, 11, :o3, 4840889, 2 tz.transition 1916, 4, :o4, 58103627, 24 tz.transition 1916, 9, :o3, 58107299, 24 tz.transition 1917, 4, :o4, 58112029, 24 tz.transition 1917, 9, :o3, 58115725, 24 tz.transition 1918, 4, :o4, 58120765, 24 tz.transition 1918, 9, :o3, 58124461, 24 tz.transition 1918, 11, :o2, 58125815, 24 tz.transition 1919, 3, :o5, 58128467, 24 tz.transition 1919, 10, :o2, 58133675, 24 tz.transition 1920, 2, :o5, 58136867, 24 tz.transition 1920, 10, :o2, 58142915, 24 tz.transition 1921, 3, :o5, 58146323, 24 tz.transition 1921, 10, :o2, 58151723, 24 tz.transition 1922, 3, :o5, 58155347, 24 tz.transition 1922, 10, :o2, 58160051, 24 tz.transition 1923, 4, :o5, 58164755, 24 tz.transition 1923, 10, :o2, 58168787, 24 tz.transition 1924, 3, :o5, 58172987, 24 tz.transition 1924, 10, :o2, 58177523, 24 tz.transition 1925, 4, :o5, 58181891, 24 tz.transition 1925, 10, :o2, 58186259, 24 tz.transition 1926, 4, :o5, 58190963, 24 tz.transition 1926, 10, :o2, 58194995, 24 tz.transition 1927, 4, :o5, 58199531, 24 tz.transition 1927, 10, :o2, 58203731, 24 tz.transition 1928, 4, :o5, 58208435, 24 tz.transition 1928, 10, :o2, 29106319, 12 tz.transition 1929, 4, :o5, 29108671, 12 tz.transition 1929, 10, :o2, 29110687, 12 tz.transition 1930, 4, :o5, 29112955, 12 tz.transition 1930, 10, :o2, 29115055, 12 tz.transition 1931, 4, :o5, 29117407, 12 tz.transition 1931, 10, :o2, 29119423, 12 tz.transition 1932, 4, :o5, 29121607, 12 tz.transition 1932, 10, :o2, 29123791, 12 tz.transition 1933, 3, :o5, 29125891, 12 tz.transition 1933, 10, :o2, 29128243, 12 tz.transition 1934, 4, :o5, 29130427, 12 tz.transition 1934, 10, :o2, 29132611, 12 tz.transition 1935, 3, :o5, 29134711, 12 tz.transition 1935, 10, :o2, 29136979, 12 tz.transition 1936, 4, :o5, 29139331, 12 tz.transition 1936, 10, :o2, 29141347, 12 tz.transition 1937, 4, :o5, 29143531, 12 tz.transition 1937, 10, :o2, 29145715, 12 tz.transition 1938, 3, :o5, 29147815, 12 tz.transition 1938, 10, :o2, 29150083, 12 tz.transition 1939, 4, :o5, 29152435, 12 tz.transition 1939, 11, :o2, 29155039, 12 tz.transition 1940, 2, :o5, 29156215, 12 tz.transition 1940, 5, :o4, 29157235, 12 tz.transition 1942, 11, :o3, 58335973, 24 tz.transition 1943, 3, :o4, 58339501, 24 tz.transition 1943, 10, :o3, 58344037, 24 tz.transition 1944, 4, :o4, 58348405, 24 tz.transition 1944, 9, :o3, 58352413, 24 tz.transition 1945, 4, :o4, 58357141, 24 tz.transition 1945, 9, :o3, 58361149, 24 tz.transition 1946, 5, :o4, 58367029, 24 tz.transition 1946, 10, :o3, 58370413, 24 tz.transition 1977, 4, :o4, 228877200 tz.transition 1977, 9, :o3, 243997200 tz.transition 1978, 4, :o4, 260326800 tz.transition 1978, 10, :o3, 276051600 tz.transition 1979, 4, :o4, 291776400 tz.transition 1979, 9, :o3, 307501200 tz.transition 1980, 4, :o4, 323830800 tz.transition 1980, 9, :o3, 338950800 tz.transition 1981, 3, :o4, 354675600 tz.transition 1981, 9, :o3, 370400400 tz.transition 1982, 3, :o4, 386125200 tz.transition 1982, 9, :o3, 401850000 tz.transition 1983, 3, :o4, 417574800 tz.transition 1983, 9, :o3, 433299600 tz.transition 1984, 3, :o4, 449024400 tz.transition 1984, 9, :o3, 465354000 tz.transition 1985, 3, :o4, 481078800 tz.transition 1985, 9, :o3, 496803600 tz.transition 1986, 3, :o4, 512528400 tz.transition 1986, 9, :o3, 528253200 tz.transition 1987, 3, :o4, 543978000 tz.transition 1987, 9, :o3, 559702800 tz.transition 1988, 3, :o4, 575427600 tz.transition 1988, 9, :o3, 591152400 tz.transition 1989, 3, :o4, 606877200 tz.transition 1989, 9, :o3, 622602000 tz.transition 1990, 3, :o4, 638326800 tz.transition 1990, 9, :o3, 654656400 tz.transition 1991, 3, :o4, 670381200 tz.transition 1991, 9, :o3, 686106000 tz.transition 1992, 3, :o4, 701830800 tz.transition 1992, 9, :o3, 717555600 tz.transition 1993, 3, :o4, 733280400 tz.transition 1993, 9, :o3, 749005200 tz.transition 1994, 3, :o4, 764730000 tz.transition 1994, 9, :o3, 780454800 tz.transition 1995, 3, :o4, 796179600 tz.transition 1995, 9, :o3, 811904400 tz.transition 1996, 3, :o4, 828234000 tz.transition 1996, 10, :o3, 846378000 tz.transition 1997, 3, :o4, 859683600 tz.transition 1997, 10, :o3, 877827600 tz.transition 1998, 3, :o4, 891133200 tz.transition 1998, 10, :o3, 909277200 tz.transition 1999, 3, :o4, 922582800 tz.transition 1999, 10, :o3, 941331600 tz.transition 2000, 3, :o4, 954032400 tz.transition 2000, 10, :o3, 972781200 tz.transition 2001, 3, :o4, 985482000 tz.transition 2001, 10, :o3, 1004230800 tz.transition 2002, 3, :o4, 1017536400 tz.transition 2002, 10, :o3, 1035680400 tz.transition 2003, 3, :o4, 1048986000 tz.transition 2003, 10, :o3, 1067130000 tz.transition 2004, 3, :o4, 1080435600 tz.transition 2004, 10, :o3, 1099184400 tz.transition 2005, 3, :o4, 1111885200 tz.transition 2005, 10, :o3, 1130634000 tz.transition 2006, 3, :o4, 1143334800 tz.transition 2006, 10, :o3, 1162083600 tz.transition 2007, 3, :o4, 1174784400 tz.transition 2007, 10, :o3, 1193533200 tz.transition 2008, 3, :o4, 1206838800 tz.transition 2008, 10, :o3, 1224982800 tz.transition 2009, 3, :o4, 1238288400 tz.transition 2009, 10, :o3, 1256432400 tz.transition 2010, 3, :o4, 1269738000 tz.transition 2010, 10, :o3, 1288486800 tz.transition 2011, 3, :o4, 1301187600 tz.transition 2011, 10, :o3, 1319936400 tz.transition 2012, 3, :o4, 1332637200 tz.transition 2012, 10, :o3, 1351386000 tz.transition 2013, 3, :o4, 1364691600 tz.transition 2013, 10, :o3, 1382835600 tz.transition 2014, 3, :o4, 1396141200 tz.transition 2014, 10, :o3, 1414285200 tz.transition 2015, 3, :o4, 1427590800 tz.transition 2015, 10, :o3, 1445734800 tz.transition 2016, 3, :o4, 1459040400 tz.transition 2016, 10, :o3, 1477789200 tz.transition 2017, 3, :o4, 1490490000 tz.transition 2017, 10, :o3, 1509238800 tz.transition 2018, 3, :o4, 1521939600 tz.transition 2018, 10, :o3, 1540688400 tz.transition 2019, 3, :o4, 1553994000 tz.transition 2019, 10, :o3, 1572138000 tz.transition 2020, 3, :o4, 1585443600 tz.transition 2020, 10, :o3, 1603587600 tz.transition 2021, 3, :o4, 1616893200 tz.transition 2021, 10, :o3, 1635642000 tz.transition 2022, 3, :o4, 1648342800 tz.transition 2022, 10, :o3, 1667091600 tz.transition 2023, 3, :o4, 1679792400 tz.transition 2023, 10, :o3, 1698541200 tz.transition 2024, 3, :o4, 1711846800 tz.transition 2024, 10, :o3, 1729990800 tz.transition 2025, 3, :o4, 1743296400 tz.transition 2025, 10, :o3, 1761440400 tz.transition 2026, 3, :o4, 1774746000 tz.transition 2026, 10, :o3, 1792890000 tz.transition 2027, 3, :o4, 1806195600 tz.transition 2027, 10, :o3, 1824944400 tz.transition 2028, 3, :o4, 1837645200 tz.transition 2028, 10, :o3, 1856394000 tz.transition 2029, 3, :o4, 1869094800 tz.transition 2029, 10, :o3, 1887843600 tz.transition 2030, 3, :o4, 1901149200 tz.transition 2030, 10, :o3, 1919293200 tz.transition 2031, 3, :o4, 1932598800 tz.transition 2031, 10, :o3, 1950742800 tz.transition 2032, 3, :o4, 1964048400 tz.transition 2032, 10, :o3, 1982797200 tz.transition 2033, 3, :o4, 1995498000 tz.transition 2033, 10, :o3, 2014246800 tz.transition 2034, 3, :o4, 2026947600 tz.transition 2034, 10, :o3, 2045696400 tz.transition 2035, 3, :o4, 2058397200 tz.transition 2035, 10, :o3, 2077146000 tz.transition 2036, 3, :o4, 2090451600 tz.transition 2036, 10, :o3, 2108595600 tz.transition 2037, 3, :o4, 2121901200 tz.transition 2037, 10, :o3, 2140045200 tz.transition 2038, 3, :o4, 59172253, 24 tz.transition 2038, 10, :o3, 59177461, 24 tz.transition 2039, 3, :o4, 59180989, 24 tz.transition 2039, 10, :o3, 59186197, 24 tz.transition 2040, 3, :o4, 59189725, 24 tz.transition 2040, 10, :o3, 59194933, 24 tz.transition 2041, 3, :o4, 59198629, 24 tz.transition 2041, 10, :o3, 59203669, 24 tz.transition 2042, 3, :o4, 59207365, 24 tz.transition 2042, 10, :o3, 59212405, 24 tz.transition 2043, 3, :o4, 59216101, 24 tz.transition 2043, 10, :o3, 59221141, 24 tz.transition 2044, 3, :o4, 59224837, 24 tz.transition 2044, 10, :o3, 59230045, 24 tz.transition 2045, 3, :o4, 59233573, 24 tz.transition 2045, 10, :o3, 59238781, 24 tz.transition 2046, 3, :o4, 59242309, 24 tz.transition 2046, 10, :o3, 59247517, 24 tz.transition 2047, 3, :o4, 59251213, 24 tz.transition 2047, 10, :o3, 59256253, 24 tz.transition 2048, 3, :o4, 59259949, 24 tz.transition 2048, 10, :o3, 59264989, 24 tz.transition 2049, 3, :o4, 59268685, 24 tz.transition 2049, 10, :o3, 59273893, 24 tz.transition 2050, 3, :o4, 59277421, 24 tz.transition 2050, 10, :o3, 59282629, 24 end end end end end
require 'spec_helper' describe SessionsController do describe "routing" do context "when valid" do before { @provider = "facebook" } it ":get '/auth/:provider/callback' should route to sessions#authenticate_user" do { get: "/auth/#{@provider}/callback" }.should route_to("sessions#authenticate_user", provider: "#{@provider}") end it ":post '/auth/:provider/callback' should route to sessions#authenticate_user" do { post: "/auth/#{@provider}/callback" }.should route_to("sessions#authenticate_user", provider: "#{@provider}") end it ":get '/auth/failure' should route to sessions#failure" do { get: "/auth/failure" }.should route_to("sessions#failure") end it ":post '/auth/failure' should route to sessions#failure" do { post: "/auth/failure" }.should route_to("sessions#failure") end it ":get '/sign_out' should route to sessions#destroy" do { get: "/sign_out" }.should route_to("sessions#destroy") end end context "when invalid" do it ":post '/sign_out' should not be routable" do { post: "/sign_out" }.should_not be_routable end context "given a provider other than facebook" do it ":get '/auth/google/callback' should not be routable" do { get: "/auth/google/callback" }.should_not be_routable end end end end end
Rails.application.routes.draw do devise_for :users root 'projects#index' end
#!/usr/bin/env ruby ############################################################################### # # Dvash Defense - SSHd Module # version 1.0 # # Written By: Ari Mizrahi # # Module to simulate sshd server # ############################################################################### def start_sshd() server = TCPServer.new(22) loop do Thread.fork(server.accept) do |client| # send the client junk data client.puts(random_string) # ban the address if validate_ip("#{client.peeraddr[3]}") then block_ip("#{client.peeraddr[3]}") end if @debug then puts "#{client.peeraddr[3]} tried to talk to me!" end client.close end end end
require 'rails_helper' RSpec.describe 'Debit Factory' do describe 'debit_new' do describe 'default' do it('is not valid') { expect(debit_new).not_to be_valid } it 'is requires charge to be valid' do expect(debit_new charge: charge_new).to be_valid end it 'has date' do expect(debit_new.at_time) .to eq Time.zone.local(2013, 3, 25, 10, 0, 0) end it 'has period' do expect(debit_new.period) .to eq Date.new(2013, 3, 25)..Date.new(2013, 6, 30) end it('has amount') { expect(debit_new.amount).to eq(88.08) } end describe 'overrides' do it 'alters amount' do expect(debit_new(amount: 35.50).amount).to eq(35.50) end it('nils date') { expect(debit_new at_time: nil).not_to be_valid } it 'alters date' do expect(debit_new(at_time: '10/6/2014').at_time) .to eq Time.zone.local(2014, 6, 10, 0, 0, 0) end it 'alters period' do period = Date.new(2014, 3, 25)..Date.new(2014, 6, 30) expect(debit_new(period: period).period.to_s) .to eq '2014-03-25..2014-06-30' end end describe 'adds' do it 'assigns charge' do charge = charge_new charge_type: 'Rent' expect(debit_new(charge: charge).charge_type).to eq 'Rent' end end end describe 'create' do let(:charge) { charge_create } describe 'default' do it 'is created if charge_id set' do expect { debit_create charge: charge }.to change(Debit, :count).by(1) end it 'has amount' do expect(debit_create(charge: charge).amount).to eq(88.08) end it 'has date' do expect(debit_create(charge: charge).at_time) .to eq Time.zone.local(2013, 3, 25, 10, 0, 0) end end describe 'override' do it 'alters amount' do expect(debit_create(charge: charge, amount: 35.50).amount).to eq(35.50) end it 'alters date' do expect(debit_create(charge: charge, at_time: '10/6/2014').at_time) .to eq Time.zone.local(2014, 6, 10, 0, 0, 0) end end end end
require 'rails_helper' RSpec.describe 'Address#updates', type: :system, js: true, elasticsearch: true do before { log_in } let(:client) { ClientPage.new } let(:address) { AddressPage.new } describe 'district line' do it 'can show' do client_create id: 1, address: address_new(district: '') client.load id: 1 expect(address).to be_district_invisible address.add line: 'district' expect(address).to be_district_visible end it 'shows if the address already has district' do client_create id: 1, address: address_new(district: 'Edgbaston') client.load id: 1 expect(address).to be_district_visible end it 'can hide' do client_create id: 1, address: address_new(district: 'Edgbaston') client.load id: 1 address.delete line: 'district' expect(address).to be_district_invisible end end describe 'nation line' do it 'can show' do client_create id: 1, address: address_new(nation: '') client.load id: 1 expect(address).to be_nation_invisible address.add line: 'nation' expect(address).to be_nation_visible end it 'shows if the address already has nation' do client_create id: 1, address: address_new(nation: 'Edgbaston') client.load id: 1 expect(address).to be_nation_visible end it 'can hide' do client_create id: 1, address: address_new(nation: 'Edgbaston') client.load id: 1 address.delete line: 'nation' expect(address).to be_nation_invisible end end end
module KrakenClient module Requests class Limiter class RedisStore < Store attr_accessor :redis, :redis_key def initialize(redis, api_key) @redis = redis @redis_key = "ratelimiter:kraken:#{api_key}" end def get_count redis.hget(redis_key, :count).to_f end def set_count(count) redis.hset(redis_key, :count, count.to_f) end def incr_count(increment) redis.hincrbyfloat(redis_key, :count, increment.to_f) end def get_timestamp raw_timestamp = redis.hget(redis_key, :timestamp) if raw_timestamp.nil? now = Time.now set_timestamp now now else Time.at(raw_timestamp.to_f) end end def set_timestamp(timestamp) redis.hset(redis_key, :timestamp, timestamp.to_f) end end end end end
# 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 'faker' # Booking.destroy_all # p "Deteled bookings" # Space.destroy_all # p "Deteled spaces" # User.destroy_all # p "Deteled users" Booking.delete_all if Rails.env.development? Space.delete_all if Rails.env.development? User.delete_all if Rails.env.development? user_1 = User.create!(open_id: 1, username: Faker::FunnyName.name, manager: true) user_2 = User.create!(open_id: 2, username: Faker::FunnyName.name, manager: true) user_3 = User.create!(open_id: 3, username: Faker::FunnyName.name, manager: true) user_4 = User.create!(open_id: 4, username: Faker::FunnyName.name, manager: false) user_5 = User.create!(open_id: 5, username: Faker::FunnyName.name, manager: false) # p "Created #{User.count} users" space_1 = Space.create!(name: 'WeWork Candor Plaza',district: 'Pudong', address_details: '118 Rong Ke Lu', user_id: user_1.id, picture: 'https://cdn.wework.com/locations/image/9c07167a-e9b1-11e8-bae7-1202be33576a/webimage-1459BF4E-C3FD-4456-9B9774704591CB57.jpg', price: "$100", available_spots: rand(1..100)) space_2 = Space.create!(name: 'WeWork Century Plaza',district: 'Huangpu', address_details: '627 Middle Huaihai Road', user_id: user_1.id, picture: 'https://workdesign.com/wp-content/uploads/2012/11/shift_shared3-720x506.jpg', price: "$110", available_spots: rand(1..100)) space_3 = Space.create!(name: 'WeWork Fuhui Building',district: 'Xuhui', address_details: '989 Changle Road', user_id: user_1.id, picture: 'https://www.wework.com/public/images/Web_72DPI-20180612_WeWork_Dalian_Lu_-_Common_Areas_-_Couch_Area-4__1_.jpg', price: "$105", available_spots: rand(1..100)) space_4 = Space.create!(name: 'WeWork Tiantong Road',district: 'Changning', address_details: '328 Tiantong Road', user_id: user_1.id, picture: 'https://cdn-images-1.medium.com/max/1200/1*dK_M76iViHxJwLJO2hSbCA.jpeg', price: "$120", available_spots: rand(1..100)) space_5 = Space.create!(name: 'Xnode Super Space',district: "Jing'an", address_details: '1 South Wuning Road', user_id: user_2.id, picture: 'http://www.yoursnews.in/wp-content/uploads/2016/12/workplace-e1483086769797.jpg', price: "$100", available_spots: rand(1..100)) space_6 = Space.create!(name: 'Xnode Cool Work',district: 'Putuo', address_details: '1155 Fangdian Road', user_id: user_2.id, picture: 'https://cdn.vox-cdn.com/thumbor/jvL7qBzhkKaqhdz_1UM7k1nDneU=/0x0:7360x4912/1200x800/filters:focal(1331x2365:2507x3541)/cdn.vox-cdn.com/uploads/chorus_image/image/60768185/20180321_Chelsea_6th_Floor_1.0.jpg', price: "$90)", available_spots: rand(1..100)) space_7 = Space.create!(name: 'Xnode Fancy Office',district: 'Hongkou', address_details: '818 Shenchang Road', user_id: user_2.id, picture: 'https://cdn.wework.com/locations/image/8e49219a-dc7d-11e8-a0a4-1202be33576a/webimage-AEC23640-1D03-4494-896DF3670A5DF6DB.jpg', price: "$95", available_spots: rand(1..100)) space_8 = Space.create!(name: 'Xnode Center' ,district: 'Yangpu', address_details: '398 Huoshan Road', user_id: user_2.id, picture: 'https://pbs.twimg.com/media/Dw2Q521UUAEKXJk.jpg', price: "$105", available_spots: rand(1..100)) space_9 = Space.create!(name:"Naked Hub Minhang", district: 'Minhang', address_details: '500 Dalian Road', user_id: user_3.id, picture: 'https://thespaces.com/wp-content/uploads/2015/04/Neuehouse.jpg', price: "$80)", available_spots: rand(1..100)) space_10 = Space.create!(name: 'Naked Hub Baoshan',district: 'Baoshan', address_details: '1229 Century Avenue', user_id: user_3.id, picture: 'https://www.homejournal.hk/wp-content/uploads/2017/07/naked-hub.jpg', price: '$85', available_spots: rand(1..100)) # p "Created #{Space.count} spaces" booking_1 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_2 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_3 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_4 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_5 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_6 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_7 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_8 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_9 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_10 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_11 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_12 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_13 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_14 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_15 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_16 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_17 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_18 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_19 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) booking_20 = Booking.create!(space_id: rand(space_1.id..space_10.id), user_id: rand(user_1.id..user_5.id), date: Faker::Date.forward(60)) # p "Created #{Booking.count} bookings" Space.all.each do |s| s.price = rand(20..100) s.wifi = [true, false].sample s.sofa_area = [true, false].sample s.coffee = [true, false].sample s.beer = [true, false].sample s.purified_air = [true, false].sample s.full_address = "#{s.address_details}, #{s.district}, Shanghai" s.save end p "Created #{User.count} users" p "Created #{Booking.count} bookings" p "Created #{Space.count} spaces"
class Command def self.perform raise NotImplementedError.new("You must implement 'perform' method.") end def self.for(params) self.perform(params) end end
require_relative './travel' require_relative '../../measure' module Hermes class Middleware def initialize(app) @app = app end def call(env) travel = measure(Travel.new(env)) travel.possible? or return missing_collection @app.(env) end private def missing_collection Rack::Response.new \ [{ errors: ['Collection could not be found'] }.to_json], 404, { 'Content-Type' => 'application/json' } end def measure(travel) Measure.new travel, { :possible? => 'Hermes is checking the routing' } end end end
# == Schema Information # Schema version: 20110115032915 # # Table name: orders # # id :integer not null, primary key # user_id :integer # ip_address :string(255) # first_name :string(255) # last_name :string(255) # card_type :string(255) # card_expires_on :date # created_at :datetime # updated_at :datetime # class Order < ActiveRecord::Base belongs_to :user has_many :order_transactions attr_accessor :card_number, :card_verification validate(:validate_card, :on => :create) def purchase price = todays_deal.price response = GATEWAY.purchase(price, credit_card, :ip => ip_address) OrderTransaction.create!(:action => "purchase", :amount => price, :response => response) response.success? end private def validate_card unless credit_card.valid? credit_card.errors.full_messages.each do |message| errors.add_to_base(message) end end end def credit_card @credit_card ||= ActiveMerchant::Billing::CreditCard.new( :type => card_type, :number => card_number, :verification_value => card_verification, :month => card_expires_on.month, :year => card_expires_on.year, :first_name => first_name, :last_name => last_name ) end end
class PagadoresService def self.index(params) pagadores = ::Pagador.buscar(params).map(&:slim_obj) resp = { list: pagadores } resp.merge!(load_module(params)) if params[:with_settings] [:success, resp] end def self.show(params) pagador = Pagador.where(id: params[:id]).first return [:not_found, "Registro não encontrado."] if pagador.blank? resp = {pagador: pagador.to_frontend_obj} [:success, resp] end def self.destroy(params) pagador = Pagador.where(id: params[:id]).first if pagador.blank? errors = "Registro já excluído." return [:not_found, errors] end if pagador.destroy resp = { msg: "Registro excluído com sucesso." } [:success, resp] else errors = pagador.errors.full_messages [:error, errors] end end def self.save(params) params = params[:pagador] if params[:id].present? pagador = Pagador.where(id: params[:id]).first if pagador.blank? errors = "Registro foi excluído" return [:not_found, errors] end else pagador = Pagador.new end params_pag = set_params(params) pagador.assign_attributes(params_pag) novo = pagador.new_record? if pagador.save resp = {novo: novo, pagador: pagador.to_frontend_obj} [:success, resp] else errors = pagador.errors.full_messages [:error, errors] end end # settings def self.load_module(params) resp = {} resp[:settings] = { pagadores: load_settings(params), } # resp[:locales] = load_locales(params) resp end def self.load_settings(params) resp = {} resp[:lista_operacoes] = PerfilPagamento::LISTA_OPERACOES resp[:lista_plano_de_contas] = PerfilPagamento::LISTA_PLANO_DE_CONTAS resp[:lista_fundo] = PerfilPagamento::LISTA_FUNDO resp[:lista_periodos] = Pagador::LISTA_PERIODOS resp[:tipos_conta] = Conta::TIPOS_CONTA resp[:lista_correcao] = ReajusteContratual::LISTA_CORRECAO resp[:lista_opcoes] = Pagador::LISTA_OPCOES resp[:bancos] = Banco.all.map() resp[:filtro] = { q: "", nome: "", telefone: "", email: "", opcoes: [] } resp end private def self.set_params(params) # enderecos params = set_enderecos(params) # perfil para pagamento params = set_perfil_pagamentos(params) # contas params = set_contas(params) # reajuste contratual params = set_reajuste_contratual(params) # bloquear clientes params = set_bloquear_clientes(params) params end private_class_method :set_params def self.set_enderecos(params) enderecos = params.delete(:enderecos) return params if enderecos.blank? params[:enderecos_attributes] = enderecos params end private_class_method :set_enderecos def self.set_perfil_pagamentos(params) perfil_pagamentos = params.delete(:perfil_pagamentos) return params if perfil_pagamentos.blank? params[:perfil_pagamentos_attributes] = perfil_pagamentos params end private_class_method :set_perfil_pagamentos def self.set_contas(params) contas = params.delete(:contas) return params if contas.blank? params[:contas_attributes] = contas params end private_class_method :set_contas def self.set_reajuste_contratual(params) reajuste_contratual = params.delete(:reajuste_contratual) return params if reajuste_contratual.blank? params[:reajuste_contratual_attributes] = reajuste_contratual params end private_class_method :set_reajuste_contratual def self.set_bloquear_clientes(params) bloquear_clientes = params.delete(:bloquear_clientes) return params if bloquear_clientes.blank? params[:bloquear_clientes_attributes] = bloquear_clientes params end private_class_method :set_bloquear_clientes end
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end test "can post a new user" do post users_path, params: { user: { first_name: "Allie", last_name: "Rowan", email: "arowan@wesleyan.edu", password: "password", password_confirmation: "password" } } assert_equal "Allie", User.last.first_name end test "sends back errors if any" do post users_path, params: { user: { last_name: "Rowan", email: "arowan@wesleyan.edu", password: "password", password_confirmation: "password" } } assert_equal ["can't be blank"], response.parsed_body["first_name"] end test "sends error if password different from confirmation" do post users_path, params: { user: { last_name: "Rowan", email: "arowan@wesleyan.edu", password: "passwasdfsdord", password_confirmation: "password" } } assert_equal ["doesn't match Password"], response.parsed_body["password_confirmation"] end test "can update a user" do post session_path, headers: { token: users(:allie).token }, params: { email: "test@gmail.com", password: "password" } my_user = User.find(users(:allie).id) patch user_path(my_user.id), headers: { "Authorization"=> users(:allie).token }, params: { user: { last_name: "Another" } } assert_response :ok assert_equal "Another", User.find(my_user.id).last_name end test "sends back error on update if any" do my_user = User.find(users(:allie).id) post session_path, params: { email: "test@gmail.com", password: "password" } patch user_path(my_user.id), headers: { "Authorization" => users(:allie).token }, params: { user: { password: "password", password_confirmation: "asdlkfj" } } assert_equal ["doesn't match Password"], response.parsed_body["password_confirmation"] end test "can read one user" do my_user = User.find(users(:allie).id) get user_path(my_user.id) assert_response :ok assert_equal "Rowan", response.parsed_body["last_name"] end end
class Suggestion < ApplicationRecord has_many :wynthoughts end
class PostSerializer < ActiveModel::Serializer attributes :id, :title, :body, :version belongs_to :author has_many :comments def version '0.10.0' end end
ActiveAdmin.register Currency do include SpellFixable include Sortable menu priority: 15 permit_params :name, :symbol filter :name index as: :sortable_table do column :id column :name column :symbol column :rate column '# Boats' do |r| r.boats.not_deleted.count end actions end form do |f| f.inputs do f.input :name f.input :symbol end f.actions end end
# encoding: binary # frozen_string_literal: true module RbNaCl module AEAD # Abstract base class for Authenticated Encryption with Additional Data # # This construction encrypts a message, and computes an authentication # tag for the encrypted message and some optional additional data # # RbNaCl provides wrappers for both ChaCha20-Poly1305 AEAD implementations # in libsodium: the original, and the IETF version. class Base # Number of bytes in a valid key KEYBYTES = 0 # Number of bytes in a valid nonce NPUBBYTES = 0 attr_reader :key private :key # Create a new AEAD using the IETF chacha20poly1305 construction # # Sets up AEAD with a secret key for encrypting and decrypting messages. # # @param key [String] The key to encrypt and decrypt with # # @raise [RbNaCl::LengthError] on invalid keys # # @return [RbNaCl::AEAD::Chacha20Poly1305IETF] The new AEAD construct, ready to use def initialize(key) @key = Util.check_string(key, key_bytes, "Secret key") end # Encrypts and authenticates a message with additional authenticated data # # @param nonce [String] An 8-byte string containing the nonce. # @param message [String] The message to be encrypted. # @param additional_data [String] The additional authenticated data # # @raise [RbNaCl::LengthError] If the nonce is not valid # @raise [RbNaCl::CryptoError] If the ciphertext cannot be authenticated. # # @return [String] The encrypted message with the authenticator tag appended def encrypt(nonce, message, additional_data) Util.check_length(nonce, nonce_bytes, "Nonce") ciphertext_len = Util.zeros(1) ciphertext = Util.zeros(data_len(message) + tag_bytes) success = do_encrypt(ciphertext, ciphertext_len, nonce, message, additional_data) raise CryptoError, "Encryption failed" unless success ciphertext end # Decrypts and verifies an encrypted message with additional authenticated data # # @param nonce [String] An 8-byte string containing the nonce. # @param ciphertext [String] The message to be decrypted. # @param additional_data [String] The additional authenticated data # # @raise [RbNaCl::LengthError] If the nonce is not valid # @raise [RbNaCl::CryptoError] If the ciphertext cannot be authenticated. # # @return [String] The decrypted message def decrypt(nonce, ciphertext, additional_data) Util.check_length(nonce, nonce_bytes, "Nonce") message_len = Util.zeros(1) message = Util.zeros(data_len(ciphertext) - tag_bytes) success = do_decrypt(message, message_len, nonce, ciphertext, additional_data) raise CryptoError, "Decryption failed. Ciphertext failed verification." unless success message end # The crypto primitive for this aead instance # # @return [Symbol] The primitive used def primitive self.class.primitive end # The nonce bytes for the AEAD class # # @return [Integer] The number of bytes in a valid nonce def self.nonce_bytes self::NPUBBYTES end # The nonce bytes for the AEAD instance # # @return [Integer] The number of bytes in a valid nonce def nonce_bytes self.class.nonce_bytes end # The key bytes for the AEAD class # # @return [Integer] The number of bytes in a valid key def self.key_bytes self::KEYBYTES end # The key bytes for the AEAD instance # # @return [Integer] The number of bytes in a valid key def key_bytes self.class.key_bytes end # The number bytes in the tag or authenticator from this AEAD class # # @return [Integer] number of tag bytes def self.tag_bytes self::ABYTES end # The number of bytes in the tag or authenticator for this AEAD instance # # @return [Integer] number of tag bytes def tag_bytes self.class.tag_bytes end private def data_len(data) return 0 if data.nil? data.bytesize end def do_encrypt(_ciphertext, _ciphertext_len, _nonce, _message, _additional_data) raise NotImplementedError end def do_decrypt(_message, _message_len, _nonce, _ciphertext, _additional_data) raise NotImplementedError end end end end
require_relative '../lib/cell' class GameOfLife def initialize @live_cells = [] end attr_accessor :live_cells def add_live_cell(cell) @live_cells.push(cell) unless @live_cells.include?(cell) end def tick @kept_alive_cells = @live_cells.select { |c| should_be_kept_alive(c) } @bring_to_life_cells = should_be_brought_to_life @live_cells = @kept_alive_cells.concat(@bring_to_life_cells).uniq end def should_be_kept_alive(cell) number_of_neighbors(cell) == 2 || number_of_neighbors(cell) == 3 end def should_be_brought_to_life all_adjacents_of_live_cells.select {|c| number_of_neighbors(c)==3} end def number_of_neighbors(cell) (@live_cells.select {|c| cell.neighbor?(c)}).size end def all_adjacents_of_live_cells @live_cells.inject([]){|adj, c| adj.concat(c.adjacents)}.uniq end end
class AddUtilizeToPrice < ActiveRecord::Migration def change add_column :prices, :utilize, :boolean end end
require 'tribe' require 'logger' module Logging def root_logger(logger) @logger = logger end def logger @logger or fail 'no logger' end end class ProcessorBase < Tribe::DedicatedActor include Logging def initialize(options) super if options[:logger] root_logger(options[:logger]) elsif options[:parent].respond_to? :logger root_logger(options[:parent].logger) else root_logger(Logger.new(STDERR)) warn 'spawning new logger' end end def connect(processor, command = :data) @processor = processor @command = command end def output(data) fail 'no processor connected' unless @processor and @command if not data debug { "closing output" } else debug { "output: #{data}" } end @processor.deliver_message! @command, data end def debug(&block) logger.debug do "#{name}: #{block.call}" end end def log(msg) logger.info "#{name}: #{msg.to_s}" end def warn(msg) logger.warn "#{name}: #{msg.to_s}" end def name "#{self.class.name}[#{identifier}]" end def to_s name end private def exception_handler(exception) super log "fatal: #{exception.exception}:\n#{exception.backtrace.join("\n")}" end def shutdown_handler(event) super log 'done' end end
class PasswordResetsController < ApplicationController before_action :not_logged_in before_action :user, except: [:new] before_action :authorized, only: [:edit, :update] before_action :check_expiration, only: [:edit, :update] def new end def create @email = params[:email].downcase if @user @user.forgot_password @user.send_password_reset_email redirect_to root_url flash[:info] = "Please check your email for the password reset link." else flash.now[:danger] = "Invalid email address." render "new" end end def edit end def update if params[:user][:password].empty? @user.errors.add :password, :blank render "edit" else new_password = params.require(:user).permit :password, :password_confirmation new_password[:password_reset_sent_at] = nil if @user.update_attributes new_password flash[:success] = "Successfully update new password." redirect_to login_url else render "edit" end end end private # Retrive user from database by email def user @user = User.find_by email: params[:email].downcase end # Only users have valid email and token can reset password def authorized @token = params[:id] return if @user&.authenticated? :password_reset, @token flash[:danger] = "Invalid password reset link." redirect_to root_url end # Check expiration of the password reset token def check_expiration return unless @user.password_reset_expired? message = "This password reset request is expired." message << " Enter your email below to request a new one." flash[:danger] = message redirect_to new_password_reset_url end end
class ArticlesController < ApplicationController http_basic_authenticate_with name: "clayton", password: "secret", except: [:index, :show, :search] before_action :set_article, only: [:edit, :update, :show, :destroy] def index @articles = Article.all end def new @article = Article.new end def show end def edit end def search if params[:search].blank? @articles = Article.all else @articles = Article.search(params) end end def update if @article.update(article_params) redirect_to @article else render 'edit' end end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end def destroy @article.destroy redirect_to articles_path end private def set_article @article=Article.find(params[:id]) end def article_params params.require(:article).permit(:pic,:title,:text) end end
Pod::Spec.new do |s| s.name = "TJActivityViewController" s.version = "1.0.1" s.summary = "TJActivityViewController is a handy subclass of UIActivityViewController for simple customization for the iOS share sheet." s.homepage = "https://github.com/timonus/TJActivityViewController" s.license = { :type => "BSD 3-Clause License", :file => "LICENSE" } s.author = { "Tim Johnsen" => "https://twitter.com/timonus" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/timonus/TJActivityViewController.git", :tag => "1.0.1" } s.source_files = "*.{h,m}" s.public_header_files = "*.h" s.frameworks = "Foundation", "UIKit" s.requires_arc = true end
module OrderSetItemsHelper def include_comments? params[:include_comments] == '1' end end
# frozen_string_literal: true # custom_triggers.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that user-definable triggers for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "yaml" require_relative "../yossarian_plugin" class CustomTriggers < YossarianPlugin include Cinch::Plugin use_blacklist def initialize(*args) super @triggers_file = File.expand_path(File.join(File.dirname(__FILE__), @bot.server_id, "custom_triggers.yml")) if File.file?(@triggers_file) @triggers = YAML.load_file(@triggers_file) @triggers.default_proc = Proc.new { |h, k| h[k] = {} } else FileUtils.mkdir_p File.dirname(@triggers_file) @triggers = Hash.new { |h, k| h[k] = {} } end end def sync_triggers_file File.open(@triggers_file, "w+") do |file| file.write @triggers.to_yaml end end def usage "!trigger <command> - Manage custom triggers. Commands are add, rm, and list. Alias: !reply." end def match?(cmd) cmd =~ /^(!)?(trigger$)|(reply$)/ end match /trigger add (\S.+) -> (.+)/, method: :add_trigger # Note: mandatory " -> " string def add_trigger(m, trigger, response) channel = m.channel.to_s @triggers[channel][trigger] = response m.reply "Added trigger for \'#{trigger}\' -> \'#{response}\'.", true sync_triggers_file end match /trigger rm (\S.+)/, method: :rm_trigger def rm_trigger(m, trigger) channel = m.channel.to_s if @triggers.key?(channel) && @triggers[channel].key?(trigger) @triggers[channel].delete(trigger) m.reply "Deleted the response associated with \'#{trigger}\'.", true sync_triggers_file else m.reply "I don\'t have a response to remove for \'#{trigger}\'.", true end end match /trigger list/, method: :list_triggers def list_triggers(m) if @triggers.empty? m.reply "I don\'t currently have any triggers.", true else m.reply @triggers[m.channel.to_s].keys.join(", "), true end end listen_to :channel def listen(m) channel = m.channel.to_s if @triggers.key?(channel) && @triggers[channel].key?(m.message) m.reply "\u200B#{@triggers[channel][m.message]}" end end end
module ValidatesTimeliness module ORM module ActiveRecord extend ActiveSupport::Concern module ClassMethods public def timeliness_attribute_timezone_aware?(attr_name) create_time_zone_conversion_attribute?(attr_name, timeliness_column_for_attribute(attr_name)) end def timeliness_attribute_type(attr_name) timeliness_column_for_attribute(attr_name).type end if ::ActiveModel.version >= Gem::Version.new('4.2') def timeliness_column_for_attribute(attr_name) columns_hash.fetch(attr_name.to_s) do |key| validation_type = _validators[key.to_sym].find {|v| v.kind == :timeliness }.type.to_s ::ActiveRecord::ConnectionAdapters::Column.new(key, nil, lookup_cast_type(validation_type), validation_type) end end def lookup_cast_type(sql_type) case sql_type when 'datetime' then ::ActiveRecord::Type::DateTime.new when 'date' then ::ActiveRecord::Type::Date.new when 'time' then ::ActiveRecord::Type::Time.new end end else def timeliness_column_for_attribute(attr_name) columns_hash.fetch(attr_name.to_s) do |key| validation_type = _validators[key.to_sym].find {|v| v.kind == :timeliness }.type.to_s ::ActiveRecord::ConnectionAdapters::Column.new(key, nil, validation_type) end end end def define_attribute_methods super.tap { generated_timeliness_methods.synchronize do return if @timeliness_methods_generated define_timeliness_methods true @timeliness_methods_generated = true end } end def undefine_attribute_methods super.tap { generated_timeliness_methods.synchronize do return unless @timeliness_methods_generated undefine_timeliness_attribute_methods @timeliness_methods_generated = false end } end # Override to overwrite methods in ActiveRecord attribute method module because in AR 4+ # there is curious code which calls the method directly from the generated methods module # via bind inside method_missing. This means our method in the formerly custom timeliness # methods module was never reached. def generated_timeliness_methods generated_attribute_methods end end def write_timeliness_attribute(attr_name, value) @timeliness_cache ||= {} @timeliness_cache[attr_name] = value if ValidatesTimeliness.use_plugin_parser type = self.class.timeliness_attribute_type(attr_name) timezone = :current if self.class.timeliness_attribute_timezone_aware?(attr_name) value = Timeliness::Parser.parse(value, type, :zone => timezone) value = value.to_date if value && type == :date end write_attribute(attr_name, value) end def read_timeliness_attribute_before_type_cast(attr_name) @timeliness_cache && @timeliness_cache[attr_name] || read_attribute_before_type_cast(attr_name) end def reload(*args) _clear_timeliness_cache super end end end end class ActiveRecord::Base include ValidatesTimeliness::AttributeMethods include ValidatesTimeliness::ORM::ActiveRecord end
module GapIntelligence class InStoreImage < Record attribute :category_version_id attribute :merchant_id attribute :category_version_name attribute :merchant_name attributes :start_date, :end_date, class: Date attributes :created_at, :updated_at, class: Time def pricing_images @pricing_images ||= begin raw['pricing_images'].map do |pricing_image_attributes| GapIntelligence::PricingImage.new(pricing_image_attributes) end end end end end
class Gossip < ApplicationRecord belongs_to :user has_many :join_gossip_tags has_many :tags, through: :join_gossip_tags validates :title, presence: true validates :content, presence: true validates :user_id, presence: true end
require 'rails_helper' feature 'Log in' do background { create(:category, title: Category::MAIN_GATEGORY) } given(:user) { create(:user) } given(:admin) { create(:admin) } scenario 'log in as persisted user' do visit root_path click_link('Log in', match: :first) fill_in 'Enter your email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' expect(page).to have_content 'Signed in successfully.' expect(page).to have_content 'My account' expect(page).not_to have_content 'Admin panel' expect(page).not_to have_content 'Log in' expect(current_path).to eq root_path end scenario 'log in as admin' do visit new_user_session_path fill_in 'Enter your email', with: admin.email fill_in 'Password', with: admin.password click_button 'Log in' expect(page).to have_content 'Signed in successfully.' expect(page).to have_content 'My account' expect(page).to have_content 'Admin panel' expect(page).not_to have_content 'Log in' end scenario 'invalid data' do visit new_user_session_path click_button 'Log in' expect(page).to have_content 'Invalid Email or password.' expect(page).to have_content 'Log in' expect(page).to have_content 'Sign up' expect(current_path).to eq new_user_session_path end end
source 'https://rubygems.org' git_source(:github) { |repo| 'https://github.com/#{repo}.git' } # CORE ------------------------------------------------------------------------ # Ruby on Rails ruby '3.0.4' gem 'rails', '~> 6.1.7' # Database for Active Record gem 'pg' # App server gem 'puma' # Data cache (required to run Action Cable in production) gem 'redis', '~> 4.0' # Reduce boot times through caching (required in config/boot.rb) gem 'bootsnap', '>= 1.1.0', require: false # Compress responses to speed up page loads gem "rack-brotli" # Write cron jobs gem "whenever", require: false # ASSET PIPELINE -------------------------------------------------------------- # WebPacker asset pipeline gem 'webpacker' # SCSS for stylesheets gem 'sass-rails', '~> 5.0' # CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # Compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # APIs ------------------------------------------------------------------------ # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Fast JSON serialisation gem 'oj' # XML sitemap gem 'sitemap_generator' # FRONTEND FRAMEWORKS --------------------------------------------------------- # Bootstrap CSS framework gem 'bootstrap', '~> 5.1' # Bootstrap forms gem 'bootstrap_form', '~> 5.0' # FontAwesome 4.7 icons gem 'font-awesome-rails' # Hotwire JS framework gem 'turbo-rails' gem 'stimulus-rails' # USERS & PERMISSIONS --------------------------------------------------------- # User management gem 'devise', '>= 4.7.1' # Authorizations management gem 'cancancan' # Oauth2 API gem 'doorkeeper' # Captcha gem 'recaptcha' # MODEL HELPERS --------------------------------------------------------------- # Versioning gem 'paper_trail' # Search gem 'pg_search' # File uploads gem 'carrierwave', '~> 2.0' # ISO-based countries gem 'countries' gem 'country_select' # Geocoding gem 'geocoder' # GBIF Backbone Taxonomy gem 'faraday', '~> 2.5', '>= 2.5.2' gem 'gbifrb' # Bibliographic data gem 'bibtex-ruby' gem 'citeproc-ruby' gem 'csl-styles' # Session store backed by an Active Record class to avoid cookie overflow with # lasso gem 'activerecord-session_store' # VIEW HELPERS ---------------------------------------------------------------- # Pagination gem 'pagy' # Use Postgres COPY for efficient CSV exports gem "postgres-copy" # Breadcrumbs gem 'breadcrumbs' # Markdown rendering gem 'kramdown' # Maps gem 'leaflet-rails' # Charts gem 'vega' # Get posts from blog.xronos.ch gem 'feedjira' gem 'httparty' # DEVELOPMENT ----------------------------------------------------------------- # Syntax checking/linting gem 'rubocop', require: false gem 'rubocop-rails', require: false # Progress bar (for rake tasks etc.) gem 'ruby-progressbar' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger # console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] # Load environment variables gem 'dotenv-rails' end group :development do # Watch for file changes gem 'listen' # Access an interactive console on exception pages or by calling 'console' # anywhere in the code. gem 'web-console', '>= 3.3.0' # Spring speeds up development by keeping your application running in the # background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen' # Annotate models etc. with current schema gem 'annotate' # Watch for N+1 queries and unused eager loading gem 'bullet' end # TESTING --------------------------------------------------------------------- group :development, :test do # RSpec for testing gem 'rspec-rails', '~> 4.0.1' # Generate test data from model specs gem 'factory_bot_rails' gem 'faker' gem 'guard-rspec' end group :test do # Unit testing gem 'minitest' # Schema testing gem 'json-schema' # Acceptance testing gem 'webdrivers' gem 'selenium-webdriver' gem 'capybara' gem 'capybara-selenium' gem 'launchy' # Measure test coverage gem 'simplecov', require: false gem 'simplecov-cobertura' end # COMPATIBILITY --------------------------------------------------------------- # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
class TablesController < ApplicationController before_action :set_table, only: [:show] def index @tables = Table.all.order(:name) end def show @order = Order.new @orders = @table.orders.where.not(status:2) end def set_table @table = Table.find(params[:id]) end end
# AIS-31 Test suite # 2019-10-16 Naoki F., AIT # New BSD License is applied. See COPYING file for details. class Ais31 # All test functions input a bitstring and output an array A # A[0] is array of "PASS" or "FAIL", A[1] is the number of used input bits BIT_PROC_A = 8285728 BIT_TEST_T0 = 3145728 BIT_TEST_A = 20000 BIT_TEST_B = 100000 RUN_MIN = [2267, 1079, 502, 223, 90, 90] RUN_MAX = [2733, 1421, 748, 402, 223, 223] Q_T8 = 2560 K_T8 = 256000 def self.report (text_line, out_file = nil, out_console = STDOUT) @@out_file = out_file if out_file out_console.puts text_line @@out_file.puts text_line end def self.report_error (text_line, out_file = nil) report text_line, out_file, STDERR end def self.procedure_a (bits, out_file) if bits.length < BIT_PROC_A report_error "!! The input bitstring is too short. Stop.", out_file exit 1 end report "[[ AIS-31 Test Procedure A ]]", out_file failure = nil 2.times do |trial| results = Array.new results += self.test_t0(bits, out_file)[0] bits = bits[BIT_TEST_T0..-1] 257.times do |i| report "[Iteration %3d]" % (i + 1) [:test_t1, :test_t2, :test_t3, :test_t4, :test_t5].each do |t| results += self.method(t).call(bits, out_file)[0] end bits = bits[BIT_TEST_A..-1] end failure = results.reduce(0){|s, x| s + ((x == "FAIL") ? 1 : 0) } report "" report "## Number of FAILed Tests (out of 1286): %d" % failure break if failure != 1 || trial != 0 || bits.length < BIT_PROC_A report "## Exactly one test has failed. Retrying..." end if failure == 0 report "## Test Procedure A is PASSED!!!" report "" return [["PASS"], BIT_PROC_A] else report "## Test Procedure A is FAILED..." report "" return [["FAIL"], BIT_PROC_A] end end def self.procedure_b (bits, out_file) report "[[ AIS-31 Test Procedure B ]]", out_file failure = nil total = bits.length 2.times do |trial| results = Array.new [:test_t6, :test_t7a, :test_t7b, :test_t7c, :test_t8].each do |t| result = self.method(t).call(bits, out_file) results += result[0] bits = bits[result[1]..-1] end failure = results.reduce(0){|s, x| s + ((x == "FAIL") ? 1 : 0) } report "" report "## Number of bits used: %d" % (total - bits.length) report "## Number of FAILed Tests (out of 9): %d" % failure break if failure != 1 || trial != 0 report "## Exactly one test has failed. Retrying..." end if failure == 0 report "## Test Procedure B is PASSED!!!" report "" return [["PASS"], total - bits.length] else report "## Test Procedure B is FAILED..." report "" return [["FAIL"], total - bits.length] end end def self.test_t0 (bits, out_file) bits = bits[0..BIT_TEST_T0-1] num_unique = bits.scan(/.{48}/).uniq.size result = (num_unique == 65536) ? "PASS" : "FAIL" report "T0 : %s => # of unique bitstrings = %d (65536)" % [result, num_unique], out_file return [[result], BIT_TEST_T0] end def self.test_t1 (bits, out_file) bits = bits[0..BIT_TEST_A-1] ones = bits.bytes.reduce(0){|s, x| s + (x & 1) } result = (ones >= 9655 && ones <= 10345) ? "PASS" : "FAIL" report "T1 : %s => # of ones = %d (9655-10345)" % [result, ones], out_file return [[result], BIT_TEST_A] end def self.test_t2 (bits, out_file) bits = bits[0..BIT_TEST_A-1] freq = Array.new(16, 0) bits.scan(/..../).each{|x| freq[x.to_i(2)] += 1 } t2 = 16.0 / 5000 * freq.reduce(0){|s, x| s + x * x } - 5000 result = (t2 > 1.03 && t2 < 57.4) ? "PASS" : "FAIL" report "T2 : %s => Test value = %.3f (1.03-57.4)" % [result, t2], out_file return [[result], BIT_TEST_A] end def self.test_t3 (bits, out_file) bits = bits[0..BIT_TEST_A-1].bytes.map{|x| x & 1 } runs = Array.new runs[0] = Array.new 6, 0 runs[1] = Array.new 6, 0 cur = bits[0] len = 0 1.upto(19999) do |i| if cur != bits[i] runs[cur][len] += 1 cur = bits[i] len = 0 else len = (len < 5) ? len + 1 : 5 end end runs[cur][len] += 1 result = "PASS" runs.each do |run| run.each_index {|i| result = "FAIL" if run[i] < RUN_MIN[i] || run[i] > RUN_MAX[i] } end text_line = "T3 : %s => Run |" % result runs[0].each_index{|i| text_line += " %d(%4d-%4d) |" % [i + 1, RUN_MIN[i], RUN_MAX[i]] } report text_line, out_file runs.each_index do |i| text_line = " %ds |" % i runs[i].each{|x| text_line += " %11d |" % x} report text_line end return [[result], BIT_TEST_A] end def self.test_t4 (bits, out_file) bits = bits[0..BIT_TEST_A-1].bytes.map{|x| x & 1 } cur = bits[0] len = 1 longest = 1 1.upto(19999) do |i| if cur != bits[i] cur = bits[i] len = 1 else len = len + 1 longest = len if longest < len end end result = (longest <= 33) ? "PASS" : "FAIL" report "T4 : %s => Longest run = %d (1-33)" % [result, longest], out_file return [[result], BIT_TEST_A] end def self.test_t5 (bits, out_file) bits = bits[0..BIT_TEST_A-1].bytes.map{|x| x & 1 } tau = 0 max_dif = -1 1.upto(5000) do |i| t5 = (0..4999).to_a.reduce(0){|s, x| s + (bits[x] ^ bits[x + i]) } dif = (t5 - 2500).abs if dif > max_dif tau = i max_dif = dif end end t5 = (10000..14999).to_a.reduce(0){|s, x| s + (bits[x] ^ bits[x + tau]) } result = (t5 >= 2327 && t5 <= 2673) ? "PASS" : "FAIL" report "T5 : %s => value of T5(%d) = %d (2327-2673)" % [result, tau, t5], out_file return [[result], BIT_TEST_A] end def self.test_t6 (bits, out_file) bits = bits[0..BIT_TEST_B-1] ones = bits.bytes.reduce(0){|s, x| s + (x & 1) } result = (ones >= 47500 && ones <= 52500) ? "PASS" : "FAIL" report "T6 : %s => # of ones = %d (47500-52500)" % [result, ones], out_file return [[result], BIT_TEST_B] end def self.collect_tuples (bits, len, out_file) num_tf = 2 ** (len - 1) total = 0 rest = BIT_TEST_B * num_tf; occs = Array.new(num_tf, 0) ones = Array.new(num_tf, 0) while rest > 0 if total + len > bits.length report_error "!! The input bitstring ran out. Stop.", out_file exit 1 end tuple = bits[total..total+len-1] tf = tuple[0..-2].to_i(2) if occs[tf] < BIT_TEST_B occs[tf] += 1 ones[tf] += 1 if tuple[-1] == '1' rest -= 1 end total += len end return [ones, total] end def self.test_t7a (bits, out_file) ones, total = collect_tuples(bits, 2, out_file) vemp01 = ones[0].fdiv(BIT_TEST_B) vemp10 = 1.0 - ones[1].fdiv(BIT_TEST_B) result = ((vemp01 + vemp10 - 1).abs < 0.02) ? "PASS" : "FAIL" report "T7a: %s => vemp0(1) = %.5f, vemp1(0) = %.5f, sum = %.5f (0.98-1.02)" % [result, vemp01, vemp10, vemp01 + vemp10], out_file return [[result], total] end def self.test_t7 (bits, out_file, postfix, len) ones, total = collect_tuples(bits, len, out_file) num_cp = ones.size / 2 results = Array.new num_cp.times do |i| f01 = ones[i] f00 = BIT_TEST_B - f01 f11 = ones[i + num_cp] f10 = BIT_TEST_B - f11 np1 = (f01 + f11) / 2.0 np0 = (f00 + f10) / 2.0 chi2 = ((f00 - np0) ** 2 + (f10 - np0) ** 2) / np0 + ((f01 - np1) ** 2 + (f11 - np1) ** 2) / np1 result = (chi2 <= 15.136) ? "PASS" : "FAIL" report "T7%s: %s => vemp%%0%db(1) = %.5f, vemp%%0%db(1) = %.5f, chi-sq = %.3f (0-15.136)" % [postfix, result, len - 1, f01.fdiv(BIT_TEST_B), len - 1, f11.fdiv(BIT_TEST_B), chi2] % [i, i + num_cp], out_file results << result end return [results, total] end def self.test_t7b (bits, out_file) self.test_t7(bits, out_file, 'b', 3) end def self.test_t7c (bits, out_file) self.test_t7(bits, out_file, 'c', 4) end def self.test_t8 (bits, out_file, k = K_T8) bit_test_q8 = (Q_T8 + k) * 8 if bits.length < bit_test_q8 report_error "!! The input bitstring is too short. Stop.", out_file exit 1 end bits = bits[0..bit_test_q8-1].scan(/.{8}/).map{|x| x.to_i(2) } last = Array.new(256, -1) dists = Array.new (Q_T8 + k).times do |i| if i >= Q_T8 dist = i - last[bits[i]] dists[dist] = (dists[dist] || 0) + 1 end last[bits[i]] = i end gi = 0.0 g_sum = 0.0 dists.each_index do |i| gi += 1.0 / (i - 1) if i >= 2 next if ! dists[i] g_sum += gi * dists[i] end entropy = g_sum / k / Math.log(2) / 8 result = (entropy > 0.997) ? "PASS" : "FAIL" report "T8 : %s => estimated entropy per bit = %.6f (0.997-)" % [result, entropy], out_file return [[result], bit_test_q8] end end
class AddColumnToUser < ActiveRecord::Migration def change add_column :users, :name, :string, null: false, default: "" add_column :users, :photo, :binary add_column :users, :birth, :date add_column :users, :year, :integer, null: false, default: "3" add_column :users, :school, :string, null: false, default: "" add_column :users, :lives_in, :string, null: false, default: "" add_column :users, :prefecture, :string add_column :users, :zipcode, :string add_column :users, :school_desire, :string, null: false, default: "" add_column :users, :report_count, :integer, null: false, default: "0" add_column :users, :tutor_id, :integer add_column :users, :tutor_request_exists, :boolean, null: false, default: false add_column :users, :last_tutor_change, :date end end
# rubocop:disable LineLength # # CookBook:: ktc-logging # Recipe:: logstash # chef_gem 'chef-rewind' require 'chef/rewind' include_recipe 'services' include_recipe 'ktc-utils' include_recipe 'logstash::server' ip = KTC::Network.address 'management' patterns_dir = node[:logstash][:basedir] + '/' patterns_dir << node[:logstash][:server][:patterns_dir] es_results = search(:node, node['logging']['elasticsearch_query']) if es_results.empty? es_server_ip = node['logstash']['elasticsearch_ip'] else es_server_ip = es_results[0]['ipaddress'] end cookbook_file "#{patterns_dir}/json" do source 'json' owner node[:logstash][:user] group node[:logstash][:group] mode 0644 end rewind template: "#{node[:logstash][:basedir]}/server/etc/logstash.conf" do source 'logstash.conf.erb' cookbook 'ktc-logging' variables(graphite_server_ip: node[:logstash][:graphite_ip], es_server_ip: es_server_ip, enable_embedded_es: node[:logstash][:server][:enable_embedded_es], es_cluster: node[:logstash][:elasticsearch_cluster], splunk_host: node[:logstash][:splunk_host], splunk_port: node[:logstash][:splunk_port], patterns_dir: patterns_dir ) end # register logstash endpoint # syslog_port = node[:logstash][:server][:syslog_input_port] ruby_block 'register logstash endpoint' do block do member = Services::Member.new node['fqdn'], service: 'logstash-server', port: syslog_port, ip: ip member.save ep = Services::Endpoint.new 'logstash-server', ip: ip, port: syslog_port ep.save end end # process monitoring and sensu-check config processes = node[:logging][:logstash_processes] processes.each do |process| sensu_check "check_process_#{process[:name]}" do command "check-procs.rb -c 10 -w 10 -C 1 -W 1 -p #{process[:name]}" handlers ['default'] standalone true interval 30 end end ktc_collectd_processes 'logstash-processes' do input processes end ################################## # Rewind index-cleaner resources # ################################## include_recipe 'logstash::index_cleaner' base_dir = File.join(node['logstash']['basedir'], 'index_cleaner') index_cleaner_bin = File.join(base_dir, 'logstash_index_cleaner.py') days_to_keep = node['logstash']['index_cleaner']['days_to_keep'] log_file = node['logstash']['index_cleaner']['cron']['log_file'] # Fix UCLOUDNG-1383 rewind cookbook_file: index_cleaner_bin do cookbook_name 'ktc-logging' end # Make it query to remote ES server rewind cron: 'logstash_index_cleaner' do command "#{index_cleaner_bin} --host #{es_server_ip} -d #{days_to_keep} &> #{log_file}" end
RSpec.describe Telegram::Bot::UpdatesController::Session do include_context 'telegram/bot/updates_controller' let(:controller_class) do described_class = self.described_class Class.new(Telegram::Bot::UpdatesController) do include described_class end end describe '.action_methods' do subject { controller_class.action_methods } it { should be_empty } end describe '.dispatch' do subject { ->(*args) { controller_class.dispatch(*args) } } let(:other_bot) { double(username: 'otherBot') } before do controller_class.class_eval do self.session_store = :memory_store def write!(text) session[:text] = text end def read! session[:text] end def action_missing(*) [:action_missing, session[:text]].tap do session[:text] = 'test' end end end end def build_message(text, from) deep_stringify(message: {text: text, from: from}) end it 'stores session between requests' do subject.call(bot, build_message('/write test', id: 1)) expect(subject.call(bot, build_message('/read', id: 1))).to eq 'test' expect(subject.call(bot, build_message('/read', id: 2))).to eq nil expect(subject.call(other_bot, build_message('/read', id: 1))).to eq nil end context 'payload is not supported' do let(:payload_type) { '_unsupported_' } it 'provides empty session' do 2.times { expect(subject.call(bot)).to eq [:action_missing, nil] } expect(subject.call(other_bot)).to eq [:action_missing, nil] end end end describe '.build_session' do subject { controller_class.build_session(key, *args) } let(:key) {} let(:args) { [] } it { expect { subject }.to raise_error(/session_store is not configured/) } shared_examples 'NullSessionHash when key is not present' do |store_proc| it { should be_instance_of(described_class::NullSessionHash) } context 'and key is present' do let(:key) { :test_key } it 'is valid SessionHash' do expect(subject).to be_instance_of(described_class::SessionHash) expect(subject.id).to eq key expect(subject.instance_variable_get(:@store)).to be(instance_exec(&store_proc)) end end end context 'when store configured' do before { controller_class.session_store = nil } include_examples 'NullSessionHash when key is not present', -> { controller_class.session_store } end context 'when store is given' do let(:args) { [double(:store)] } include_examples 'NullSessionHash when key is not present', -> { args[0] } end end describe '.session_store=' do subject { ->(val) { controller_class.session_store = val } } it 'casts to AS::Cache' do expect { subject[:null_store] }.to change(controller_class, :session_store). to(instance_of(ActiveSupport::Cache::NullStore)) expect { subject[nil] }.to change(controller_class, :session_store). to(instance_of(ActiveSupport::Cache::MemoryStore)) end end end
# frozen_string_literal: true module Dynflow module Testing class InThreadWorld < Dynflow::World def self.test_world_config config = Dynflow::Config.new config.persistence_adapter = persistence_adapter config.logger_adapter = logger_adapter config.coordinator_adapter = coordinator_adapter config.delayed_executor = nil config.auto_rescue = false config.auto_validity_check = false config.exit_on_terminate = false config.auto_execute = false config.auto_terminate = false yield config if block_given? return config end def self.persistence_adapter @persistence_adapter ||= begin db_config = ENV['DB_CONN_STRING'] || 'sqlite:/' puts "Using database configuration: #{db_config}" Dynflow::PersistenceAdapters::Sequel.new(db_config) end end def self.logger_adapter @adapter ||= Dynflow::LoggerAdapters::Simple.new $stderr, 4 end def self.coordinator_adapter ->(world, _) { CoordiationAdapterWithLog.new(world) } end # The worlds created by this method are getting terminated after each test run def self.instance(&block) @instance ||= self.new(test_world_config(&block)) end def initialize(*args) super @clock = ManagedClock.new @executor = InThreadExecutor.new(self) end def execute(execution_plan_id, done = Concurrent::Promises.resolvable_future) @executor.execute(execution_plan_id, done) end def terminate(future = Concurrent::Promises.resolvable_future) run_before_termination_hooks @executor.terminate coordinator.delete_world(registered_world) future.fulfill true @terminated.resolve rescue => e future.reject e end def event(execution_plan_id, step_id, event, done = Concurrent::Promises.resolvable_future, optional: false) @executor.event(execution_plan_id, step_id, event, done, optional: optional) end def plan_event(execution_plan_id, step_id, event, time, done = Concurrent::Promises.resolvable_future, optional: false) if time.nil? || time < Time.now event(execution_plan_id, step_id, event, done, optional: optional) else clock.ping(executor, time, Director::Event[SecureRandom.uuid, execution_plan_id, step_id, event, done, optional], :delayed_event) end end end end end
Rails.application.routes.draw do devise_for :users root 'blogs#index' resources :blogs , only:[:create,:destroy,:new,:edit,:update,:index] end
class SubCategoriesController < ApplicationController load_and_authorize_resource def create category = Category.find(params[:category_id]) @sub_category = category.sub_categories.build(sub_category_params) @sub_category.user = current_user notice = @sub_category.save ? "successfully" : "failed" redirect_to category, notice: notice end def update @sub_category = SubCategory.find(params[:id]) respond_to do |format| if @sub_category.update(sub_category_params) format.html { redirect_to @sub_category, notice: 'Category was successfully updated.' } format.json { respond_with_bip(@sub_category) } else format.html { render :action => "edit" } format.json { respond_with_bip(@sub_category) } end end end def destroy sub_category = SubCategory.find(params[:id]) category = sub_category.category sub_category.destroy redirect_to category end private def sub_category_params params.require(:sub_category).permit(:name) end end
require 'spec_helper' describe CasesController do before do @scenario = FactoryGirl.create(:scenario) end let(:valid_attributes) { { "content" => "MyText" } } let(:valid_session) { {} } describe "GET index" do it "assigns all cases as @cases" do test_case = Case.create! valid_attributes @scenario.cases << test_case get :index, {scenario_id: @scenario.id}, valid_session expect(assigns(:cases)).to include(test_case) assigns(:cases).should eq([test_case]) end end describe "GET show" do it "assigns the requested test_case as @case" do test_case = Case.create! valid_attributes @scenario.cases << test_case get :show, {:id => test_case.to_param, scenario_id: @scenario.id}, valid_session assigns(:case).should eq(test_case) end end describe "GET new" do it "assigns a new test_case as @case" do get :new, {scenario_id: @scenario.id}, valid_session assigns(:case).should be_a_new(Case) end end describe "GET edit" do it "assigns the requested test_case as @case" do test_case = Case.create! valid_attributes @scenario.cases << test_case get :edit, {:id => test_case.to_param, scenario_id: @scenario.id}, valid_session assigns(:case).should eq(test_case) end end describe "POST create" do describe "with valid params" do it "creates a new Case" do expect { post :create, {scenario_id: @scenario.id, :case => valid_attributes}, valid_session }.to change(Case, :count).by(1) end it "assigns a newly created test_case as @case" do post :create, {scenario_id: @scenario.id, :case => valid_attributes}, valid_session assigns(:case).should be_a(Case) assigns(:case).should be_persisted assigns(:case).should eq(@scenario.cases.last) end it "redirects to the created case" do post :create, {scenario_id: @scenario.id, :case => valid_attributes}, valid_session response.should redirect_to(scenario_case_path(@scenario, Case.last)) end end describe "with invalid params" do it "assigns a newly created but unsaved test_case as @case" do Case.any_instance.stub(:save).and_return(false) post :create, {scenario_id: @scenario.id, :case => { "content" => "invalid value" }}, valid_session assigns(:case).should be_a_new(Case) end it "re-renders the 'new' template" do Case.any_instance.stub(:save).and_return(false) post :create, {scenario_id: @scenario.id, :case => { "content" => "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 case" do test_case = Case.create! valid_attributes @scenario.cases << test_case Case.any_instance.should_receive(:update_attributes).with({ "content" => "MyText" }) put :update, {scenario_id: @scenario.id, :id => test_case.to_param, :case => { "content" => "MyText" }}, valid_session end it "assigns the requested test_case as @case" do test_case = Case.create! valid_attributes @scenario.cases << test_case put :update, {scenario_id: @scenario.id, :id => test_case.to_param, :case => valid_attributes}, valid_session assigns(:case).should eq(test_case) end it "redirects to the case" do test_case = Case.create! valid_attributes @scenario.cases << test_case put :update, {scenario_id: @scenario.id, :id => test_case.to_param, :case => valid_attributes}, valid_session response.should redirect_to(scenario_case_path(@scenario, test_case)) end end describe "with invalid params" do it "assigns the test_case as @case" do test_case = Case.create! valid_attributes @scenario.cases << test_case Case.any_instance.stub(:save).and_return(false) put :update, {scenario_id: @scenario.id, :id => test_case.to_param, :case => { "content" => "invalid value" }}, valid_session assigns(:case).should eq(test_case) end it "re-renders the 'edit' template" do test_case = Case.create! valid_attributes @scenario.cases << test_case Case.any_instance.stub(:save).and_return(false) put :update, {scenario_id: @scenario.id, :id => test_case.to_param, :case => { "content" => "invalid value" }}, valid_session response.should render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested case" do test_case = Case.create! valid_attributes @scenario.cases << test_case expect { delete :destroy, {scenario_id: @scenario.id, :id => test_case.to_param}, valid_session }.to change(Case, :count).by(-1) end it "redirects to the cases list" do test_case = Case.create! valid_attributes @scenario.cases << test_case delete :destroy, {scenario_id: @scenario.id, :id => test_case.to_param}, valid_session response.should redirect_to(scenario_cases_path(@scenario)) end end end
class VotesManager def initialize(post, redis = nil) @redis = redis ||= Redis.new raise ArgumentError, "VotesManager should be initialied with a post" unless post.is_a?(Post) @post = post end def vote_up!(user) @redis.srem(redis_key(:down_votes), user.id) @redis.sadd(redis_key(:up_votes), user.id) @post.update_rank end def vote_down!(user) @redis.srem(redis_key(:up_votes), user.id) @redis.sadd(redis_key(:down_votes), user.id) @post.update_rank end def up_votes @redis.scard(redis_key(:up_votes)) end def down_votes @redis.scard(redis_key(:down_votes)) end def user_vote(user) return 1 if @redis.sismember(redis_key(:up_votes), user.id) return -1 if @redis.sismember(redis_key(:down_votes), user.id) return nil end private def redis_key(str) "post:#{@post.id}:#{str}" end end
require File.expand_path("../lib/version", __FILE__) Gem::Specification.new do |s| s.name = 'httpotemkin' s.version = Httpotemkin::VERSION s.license = 'MIT' s.platform = Gem::Platform::RUBY s.authors = ['Cornelius Schumacher'] s.email = ['schumacher@kde.org'] s.homepage = 'https://github.com/cornelius/httpotemkin' s.summary = 'Mock HTTP services for system tests' s.description = 'Httpotemkin provides tools to mock HTTP servers for system-level tests.' s.required_rubygems_version = '>= 1.3.6' s.rubyforge_project = 'httpotemkin' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'given_filesystem', '>= 0.1.2' s.add_development_dependency 'cli_tester', '>= 0.0.2' s.add_runtime_dependency 'terminal-table', '~> 1.5' s.files = `git ls-files`.split("\n") s.require_path = 'lib' s.executables = ["httpotemkin"] end
require './test_helper' require './lib/merchant' class MerchantTest < Minitest::Test def test_merchant_stores_id_and_name attributes = {:id => 5, :name => 'Turing School', :created_at => Time.now, :updated_at => Time.now} merchant = Merchant.new(attributes) assert_equal 5, merchant.id assert_equal 'Turing School', merchant.name end end
# Object that deletes all a user's tokens class DeleteAllTokens def initialize(email) @tokens = Token.where(email: email) end def call @tokens.delete_all end end
# Public: Checks which Integer out of four is the lowest. # # num1 - The Integer that will be checked. # num2 - The Integer that will be checked. # num3 - The Integer that will be checked. # num4 - The Integer that will be checked. # # Examples # # min_of_four(7, 1, 1337, 9001) # # => 1 # # Returns the lowest Integer. require_relative "min_of_three.rb" def min_of_four(num1, num2, num3, num4) min = min_of_three(num1, num2, num3) if num4 < min min = num4 end return min end
class CreateServicePricingSchemes < ActiveRecord::Migration def change create_table :service_pricing_schemes do |t| t.integer :user_id t.references :service t.references :service_charging_resource_type t.decimal :unit_cost t.float :charging_unit t.string :duration_unit t.string :pricing_mode t.timestamps end change_table :service_pricing_schemes do |t| t.index :user_id t.index :service_id t.index :service_charging_resource_type_id, :name => 'index_service_pricing_schemes_on_scrt_id' end end end
# frozen_string_literal: true class InvitesController < ApplicationController before_action :project, only: :create def create emails = invite_params[:emails].split(', ') emails.each do |email| @invite = @project.invites.new(email: email) @invite.sender = current_user send_invite_mail(@invite) if @invite.save end redirect_to @project, notice: 'Invitations were sent successfully' end private def project @project ||= current_user.projects.friendly.find(params[:project_id]) end def invite_params params.require(:invite).permit(:emails) end def send_invite_mail(invite) if invite.recipient ProjectInviteMailer.with(invite: invite).existing_user_invite.deliver_later invite.recipient.collaborations.push(invite.project) else ProjectInviteMailer .with(invite: invite, url: new_user_registration_url(invite_token: invite.token)) .new_user_invite .deliver_later end end end
class Course < ActiveRecord::Base has_one :replacement, class_name: "Course", foreign_key: :predecessor_id belongs_to :predecessor, class_name: "Course" end
class Preregistro < ActiveRecord::Base attr_accessible :mail validates :mail, presence: true, uniqueness: true def to_s; mail; end end
require 'spec_helper' RSpec.describe Indocker::Launchers::ConfigurationDeployer do before { setup_indocker(debug: true) } def build_remote_operation thread = Thread.new() {} Indocker::Launchers::DTO::RemoteOperationDTO.new(thread, :external, :indocker_sync) end subject { Indocker::Launchers::ConfigurationDeployer.new( logger: Indocker.logger, global_logger: Indocker.global_logger ) } it "builds and deploys images" do deployment_policy = build_deployment_policy({ containers: [:good_container] }) expect(subject).to receive(:compile_image).once.and_return([build_remote_operation]) expect(subject).to receive(:deploy_container).once.and_return([build_remote_operation]) expect(subject).to receive(:sync_indocker).once.and_return([build_remote_operation]) expect(subject).to receive(:sync_env_files).once.and_return([build_remote_operation]) expect(subject).to receive(:pull_repositories).once.and_return([build_remote_operation]) expect(subject).to receive(:sync_artifacts).once.and_return([build_remote_operation]) subject.run(configuration: Indocker.configuration, deployment_policy: deployment_policy) end end
require 'rails_helper' RSpec.describe "As a user" do context "I am on the dashboard page" do it "when I go to the trackers#new I see a form" do user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit dashboard_path within ".nav-wrapper" do click_on "+" end expect(current_path).to eq(new_tracker_path) expect(page).to have_content('Name') expect(page).to have_content('Purpose') expect(page).to have_button('Create Tracker!') expect(page).to have_content('LOGOUT') end end context "I am on tracker#new" do it "when I click submit I'm sent to show" do user = create(:user) partner = create(:user, email: "other@email.com") tracker = create(:tracker) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit new_tracker_path within ".card-content" do fill_in "tracker[name]", with: "bills" fill_in "tracker[purpose]", with: "hold each other accountable for paying bills" fill_in "tracker[partner_email]", with: partner.email click_on "Create Tracker!" end expect(current_path).to eq(tracker_path(tracker.id + 1)) end it "fails when there is no valid partner" do user = create(:user) tracker = create(:tracker) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit new_tracker_path within ".card-content" do fill_in "tracker[name]", with: "bills" fill_in "tracker[purpose]", with: "hold each other accountable for paying bills" fill_in "tracker[partner_email]", with: "partner@email.com" click_on "Create Tracker!" end expect(page).to have_content("partner@email.com does not exist, please input valid email") end end end
class SellersController < ApplicationController layout 'application' def show @seller = Seller.find(params[:id]) end def new @seller = Seller.new end def create @seller = Seller.new(user_params) begin if @seller.save flash[:notice] = "Usuário cadastrado." redirect_to '/seller-login' else flash[:notice] = "Não foi possível completar o cadastro. Usuário já cadastrado." redirect_to new_seller_path end rescue flash[:notice] = "Não foi possível completar o cadastro. Por favor verificar os dados novamente." redirect_to new_seller_path end end def update @seller = Seller.find(params[:id]) @seller.update_attributes(user_params) if @seller.save flash[:notice] = "Dados atualizados." redirect_to home_index_path else flash[:notice] = "Não foi possível atualizar os dados. Por favor verificar os dados novamente." redirect_to edit_seller_path(@seller) end end private def user_params params.require(:seller).permit(:nome, :email, :cnpj, :apelido, :descricao, :password, :password_confirmation) end end
require 'rails_helper' RSpec.describe 'award wallet settings page' do include_context 'logged in' include AwardWalletMacros let!(:aw_user) { setup_award_wallet_user_from_sample_data(account) } let(:aw_owners) { aw_user.award_wallet_owners } def owner_selector(owner) "#award_wallet_owner_#{owner.id}" end before do account.create_companion!(first_name: 'x') visit integrations_award_wallet_settings_path end example 'updating owner<>person mapping', :js do aw_owner = aw_owners.first person_select = "award_wallet_owner_#{owner.id}_person_id" expect(aw_owner.person).to eq account.owner select account.companion.first_name, from: person_select wait_for_ajax expect(aw_owner.reload.person).to eq account.companion select 'Someone else', from: person_select wait_for_ajax expect(aw_owner.reload.person).to be nil select account.owner.first_name, from: person_select wait_for_ajax expect(aw_owner.reload.person).to eq account.owner end it 'has no recommendation alert' do expect(page).to have_no_content 'Your Card Recommendations' expect(page).to have_no_content 'Abroaders is Working' expect(page).to have_no_content 'Request new card recommendations' end end
require 'benchmark' def main(*arr) edges = create_dag_edges(arr) # create dag from smaller to larger item lis_dp = Hash.new # dynamic programming storage results = [] time = Benchmark.measure { arr.each_index { |i| results << lis(i, edges, lis_dp) } } print_results(results, arr) puts "Time taken: #{time.real}" end def create_dag_edges(arr) edges = Hash.new arr.each_index do |i| edges[i] = [] arr.each_index do |j| break unless j < i edges[i] << j if arr[j] < arr[i] end end edges end def lis(i, edges, lis_dp) return lis_dp[i] unless lis_dp[i].nil? longest_value, longest_index = 0, nil edges[i].each_index do |j| current_longest = lis(j, edges, lis_dp)[0] if current_longest > longest_value longest_value, longest_index = current_longest, j end end lis_dp[i] = [1 + longest_value, longest_index] lis_dp[i] end def print_results(results, arr) value, index = results.map{ |result| result[0] }.each_with_index.max sequences = [index] previous_vertex = results[index][1] while !previous_vertex.nil? sequences << previous_vertex previous_vertex = results[previous_vertex][1] end puts "Longest Sequence: #{value}" puts 'Sequences: ' p sequences.reverse.map { |index| arr[index] } end # Instruction to run: # ruby -r "./longest_increasing_subsequences.rb" -e "main 5,2,8,6,3,6,9,7"