text
stringlengths
10
2.61M
class KnotesController < ApplicationController before_filter :require_user, :except => [:show, :easier, :harder, :restore] before_filter :require_valid_user, :except => [:show, :easier, :harder, :restore] # before_filter { |c| @knotebook = Knotebook.find(c.params[:knotebook_id]) if c.params[:knotebook_id] } # # def index # @knotes = params[:id] ? Knote.by_concept(params[:id]).paginate(:page => params[:page]) : Knote.paginate(:page => params[:page]) # @knote = @knotes.first or raise ActiveRecord::RecordNotFound # @position = 1 # end # # def show # @media_type = params[:media_type] || "any" # @knote = Knote.find(params[:id]) # end def new @knotebook = current_user.knotebooks.find(params[:knotebook_id]) @knote = @knotebook.knotes.build(:user => current_user) # @knote = Knote.new(params[:knote] || nil) # @concept = @knote.concepts.empty? ? @knote.concepts.build(:name => "untitled") : @knote.concepts.first # @concept = params[:concept] ? @knote.concepts.build(params[:concept]) : @knote.concepts.build(:name => "untitled") respond_to do |format| format.html { render :new } format.js { render :new } end end def edit @knotebook = current_user.knotebooks.find(params[:knotebook_id]) @knote = @knotebook.knotes.find(params[:id]) # @knote = Knote.find(params[:id]) respond_to do |format| format.html format.json { render :new } end end def create @knotebook = current_user.knotebooks.find(params[:knotebook_id]) @knote = Knote.build(params[:knote]) @knote.source = "#{current_user.name}, Knotebooks \"#{@knote.title}\", #{knotebook_url @knotebook}" if params[:knote][:references] == "auto" respond_to do |format| render :action => 'new' and return if params[:commit] == "Change Knote Type" if @knote.save @knotebook.knotes << @knote flash.now[:notice] = "Knote was successfully created." format.html { redirect_to edit_knotebook_path(@knotebook) } else format.html { render :action => "new" } end end end # TODO: create a new knote if knote.user != current_user def update @knotebook = current_user.knotebooks.find(params[:knotebook_id]) @knote = @knotebook.knotes.find(params[:id]) respond_to do |format| if @knote.update_attributes(params[:knote]) flash.now[:notice] = 'Knote was successfully updated.' format.html { redirect_to edit_knotebook_path(@knotebook) } else format.html { render :action => :edit } end end end def destroy @knotebook = current_user.knotebooks.find(params[:knotebook_id]) @knote = @knotebook.knotes.find(params[:id]) if @knote.user == current_user @knote.destroy if @knote.knotings.size == 1 flash[:notice] = 'Knote was removed completely and no longer exists.' else @knotebook.knotes.delete(@knote) flash[:notice] = 'Knote was removed from this knotebook, but still exists in other knotebooks.' end respond_to do |format| format.html { redirect_to edit_knotebook_path(@knotebook) } end end def restore @knotebook = Knotebook.find(params[:knotebook_id]) @position = params[:position].to_i @knote = @knotebook.knotes[@position] render :show end def easier @knotebook = Knotebook.everyone(params[:knotebook_id]) @knote = Knote.find_easier(params) @position = params[:position] if @knote.nil? set_knote_flash("easier") @knote = Knote.find(params[:id]) end render :show end def harder @knotebook = Knotebook.everyone(params[:knotebook_id]) @knote = Knote.find_harder(params) @position = params[:position] if @knote.nil? set_knote_flash("harder") @knote = Knote.find(params[:id]) end render :show end # # def easier # @media_type = params[:media_type] || "any" # @concept_ids = params[:concepts] || [] # @knote = Knote.find(params[:id], :include => :concepts).easier!(@concept_ids, @media_type) or raise ActiveRecord::RecordNotFound # @position = params[:position] # @restore = params[:restore] # # respond_to do |format| # # format.html { redirect_to @knote, :status => 303 } # # format.json { redirect_to knote_url(@knote, :format => :json), :status => 303 } # format.json { render :show } # end # end # # def harder # @media_type = params[:media_type] || "any" # @concept_ids = params[:concepts] || [] # @knote = Knote.find(params[:id], :include => :concepts).harder!(@concept_ids, @media_type) or raise ActiveRecord::RecordNotFound # @position = params[:position] # @knotebook = Knotebook.find(params[:knotebook_id]) # @restore = params[:restore] # # respond_to do |format| # # format.html { redirect_to @knote, :status => 303 } # # format.json { redirect_to knote_url(@knote, :format => :json), :status => 303 } # format.json { render :show } # end # end # def search_index # @knote = Knote.new # # respond_to do |format| # format.html # format.json # end # end def search @knotebook = current_user.knotebooks.find(params[:knotebook_id]) if params[:knote_search] @search = Knote.search do |query| query.keywords params[:knote_search] query.paginate(:page => params[:page], :per_page => 1) end @knotes = @search.results @knote = @knotes.first end @knotes ||= [] respond_to do |format| flash.now[:notice] = 'No knotes found. Please try a different search!' if @knotes.empty? format.html { render :search } format.js { render :search } end end def add @knotebook = current_user.knotebooks.find(params[:knotebook_id]) respond_to do |format| if @knotebook.knotes << Knote.find(params[:id]) flash.now[:notice] = "Knote was successfully added." format.html { redirect_to edit_knotebook_path(@knotebook) } else flash.now[:error] = "That knote couldn't be added. Maybe it was deleted?" format.html { redirect_to edit_knotebook_path(@knotebook) } end end end # def search # @concept = Concept.find_by_name(params[:id]) # # @knotes = @concept.knotes.sort_by(&:difficulty) # # @knotes = Knote.by_concept([@concept.id]).all(:order => "difficulty ASC, knotes.created_at DESC") # # @knote = @knotes.first or raise ActiveRecord::RecordNotFound # # # @media_type = params[:media_type] || "any" # # # params[:concept_id] = @concept.id # # difficulty = params[:difficulty] || 0 # # media_type = params[:media_type] || "any" # # concepts = params[:concepts] || [] # # # # @knote = Knote.related(@concept).similar(media_type).except(concepts).first or raise ActiveRecord::RecordNotFound # # # respond_to do |format| # format.html # # format.html { redirect_to concept_knote_url, :status => 303 } # # format.json { redirect_to concept_knote_url(:format => :json), :status => 303 } # end # end # def search_easier # @concepts = Concept.all(:conditions => { :name => params[:id].split(', ') }, :include => :knotes) # @concept = Concept.find_by_name(params[:id], :include => :knotes) # # difficulty = params[:difficulty] || 0 # media_type = params[:media_type] || "any" # concepts = params[:concepts] || [] # # @knote = Knote.related(@concept).similar(media_type).except(concepts).first or raise ActiveRecord::RecordNotFound # # respond_to do |format| # format.html { render :search } # format.json { render :search } # end # end # # def search_harder # # @concepts = Concept.all(:conditions => { :name => params[:id].split(', ') }, :include => :knotes) # @concept = Concept.find_by_name(params[:id], :include => :knotes) # # difficulty = params[:difficulty] || 0 # media_type = params[:media_type] || "any" # concepts = params[:concepts] || [] # # @knote = Knote.related(@concept).similar(media_type).except(concepts).first or raise ActiveRecord::RecordNotFound # # respond_to do |format| # format.html { render :search } # format.json { render :search } # end # end private def set_knote_flash(kind) flash.now[:notice] = "We couldn't find #{kind == 'harder' ? 'a harder' : 'an easier'} #{'video ' if params[:knote_type] == 'Video'}knote. Sorry!" end end
class Poll < ApplicationRecord belongs_to :candidate def self.to_csv attributes = %w(id source date value candidate_id) CSV.generate(headers: true) do |csv| csv << attributes all.each do |candidate| csv << attributes.map{ |attr| candidate.send(attr) } end end end end
require 'hpricot/htmlinfo' def Hpricot(input, opts = {}) Hpricot.parse(input, opts) end module Hpricot # Hpricot.parse parses <i>input</i> and return a document tree. # represented by Hpricot::Doc. def Hpricot.parse(input, opts = {}) Doc.new(make(input, opts)) end # :stopdoc: def Hpricot.make(input, opts = {}) opts = {:fixup_tags => false}.merge(opts) stack = [[nil, nil, [], [], [], []]] Hpricot.scan(input) do |token| if stack.last[5] == :CDATA and !(token[0] == :etag and token[1].downcase == stack.last[0]) token[0] = :text token[1] = token[3] if token[3] end case token[0] when :stag stagname = token[0] = token[1].downcase if ElementContent[stagname] == :EMPTY token[0] = :emptytag stack.last[2] << token else if opts[:fixup_tags] # obey the tag rules set up by the current element if ElementContent.has_key? stagname trans = nil (stack.length-1).downto(0) do |i| untags = stack[i][5] break unless untags.include? stagname # puts "** ILLEGAL #{stagname} IN #{stack[i][0]}" trans = i end if trans.to_i > 1 eles = stack.slice!(trans..-1) stack.last[2] += eles # puts "** TRANSPLANTED #{stagname} TO #{stack.last[0]}" end end end # setup tag rules for inside this element if ElementContent[stagname] == :CDATA uncontainable_tags = :CDATA elsif opts[:fixup_tags] possible_tags = ElementContent[stagname] excluded_tags, included_tags = stack.last[3..4] if possible_tags excluded_tags = excluded_tags | (ElementExclusions[stagname] || []) included_tags = included_tags | (ElementInclusions[stagname] || []) containable_tags = (possible_tags | included_tags) - excluded_tags uncontainable_tags = ElementContent.keys - containable_tags else # If the tagname is unknown, it is assumed that any element # except excluded can be contained. uncontainable_tags = excluded_tags end end stack << [stagname, token, [], excluded_tags, included_tags, uncontainable_tags] end when :etag etagname = token[0] = token[1].downcase matched_elem = nil (stack.length-1).downto(0) do |i| stagname, = stack[i] if stagname == etagname matched_elem = stack[i] stack[i][1] += token eles = stack.slice!((i+1)..-1) stack.last[2] += eles break end end unless matched_elem stack.last[2] << [:bogus_etag, token] else ele = stack.pop stack.last[2] << ele end when :text l = stack.last[2].last if l and l[0] == :text l[1] += token[1] else stack.last[2] << token end else stack.last[2] << token end end while 1 < stack.length ele = stack.pop stack.last[2] << ele end structure_list = stack[0][2] structure_list.map {|s| build_node(s) } end def Hpricot.fix_element(elem, excluded_tags, included_tags) tagname, _, attrs, sraw, _, _, _, eraw = elem[1] children = elem[2] if eraw elem[2] = fix_structure_list(children) return elem, [] else if ElementContent[tagname] == :EMPTY elem[2] = [] return elem, children else if ElementContent[tagname] == :CDATA possible_tags = [] else possible_tags = ElementContent[tagname] end if possible_tags excluded_tags2 = ElementExclusions[tagname] included_tags2 = ElementInclusions[tagname] excluded_tags |= excluded_tags2 if excluded_tags2 included_tags |= included_tags2 if included_tags2 containable_tags = (possible_tags | included_tags) - excluded_tags uncontainable_tags = ElementContent.keys - containable_tags else # If the tagname is unknown, it is assumed that any element # except excluded can be contained. uncontainable_tags = excluded_tags end fixed_children = [] rest = children until rest.empty? if String === rest[0][0] elem = rest.shift elem_tagname = elem[0] elem_tagname = elem_tagname.downcase if uncontainable_tags.include? elem_tagname rest.unshift elem break else fixed_elem, rest2 = fix_element(elem, excluded_tags, included_tags) fixed_children << fixed_elem rest = rest2 + rest end else fixed_children << rest.shift end end elem[2] = fixed_children return elem, rest end end end def Hpricot.build_node(structure) case structure[0] when String tagname, _, attrs, sraw, _, _, _, eraw = structure[1] children = structure[2] etag = eraw && ETag.parse(tagname, eraw) stag = STag.parse(tagname, attrs, sraw, true) if !children.empty? || etag Elem.new(stag, children.map {|c| build_node(c) }, etag) else Elem.new(stag) end when :text Text.parse_pcdata(structure[1]) when :emptytag Elem.new(STag.parse(structure[1], structure[2], structure[3], false)) when :bogus_etag BogusETag.parse(structure[1], structure[2]) when :xmldecl XMLDecl.parse(structure[2], structure[3]) when :doctype DocType.parse(structure[1], structure[2], structure[3]) when :procins ProcIns.parse(structure[1], structure[2], structure[3]) when :comment Comment.parse(structure[1]) when :cdata_content Text.parse_cdata_content(structure[1]) when :cdata Text.parse_cdata_section(structure[1]) else raise Exception, "[bug] unknown structure: #{structure.inspect}" end end def STag.parse(qname, attrs, raw_string, is_stag) result = STag.new(qname, attrs) result.raw_string = raw_string result end def ETag.parse(qname, raw_string) result = self.new(qname) result.raw_string = raw_string result end def BogusETag.parse(qname, raw_string) result = self.new(qname) result.raw_string = raw_string result end def Text.parse_pcdata(raw_string) result = Text.new(raw_string) result.raw_string = raw_string result end def Text.parse_cdata_content(raw_string) result = Text.new(raw_string) result.raw_string = raw_string result.instance_variable_set( "@cdata", true ) result end def Text.parse_cdata_section(content) result = Text.new(content) result.raw_string = "<![CDATA[" + content + "]]>" result end def XMLDecl.parse(attrs, raw_string) attrs ||= {} version = attrs['version'] encoding = attrs['encoding'] case attrs['standalone'] when 'yes' standalone = true when 'no' standalone = false else standalone = nil end result = XMLDecl.new(version, encoding, standalone) result.raw_string = raw_string result end def DocType.parse(root_element_name, attrs, raw_string) if attrs public_identifier = attrs['public_id'] system_identifier = attrs['system_id'] end root_element_name = root_element_name.downcase result = DocType.new(root_element_name, public_identifier, system_identifier) result.raw_string = raw_string result end def ProcIns.parse(target, content, raw_string) result = ProcIns.new(target, content) result.raw_string = raw_string result end def Comment.parse(content) result = Comment.new(content) result.raw_string = "<!--" + content + "-->" result end module Pat NameChar = /[-A-Za-z0-9._:]/ Name = /[A-Za-z_:]#{NameChar}*/ Nmtoken = /#{NameChar}+/ end # :startdoc: end
ActiveAdmin.register Expert do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # Uncomment all parameters which should be permitted for assignment # permit_params :full_name, :description, :experience, :additional_education, :procedure, :address, :medical_center, :email, :phone, :image, :hw_start_monday, :hw_end_monday, :hw_start_tuesday, :hw_end_tuesday, :hw_start_wednesday, :hw_end_wednesday, :hw_start_thursday, :hw_end_thursday, :hw_start_friday, :hw_end_friday, :hw_start_saturday, :hw_end_saturday, :hw_start_sunday, :hw_end_sunday, :category_id, :education, :level_id # # or # # permit_params do # permitted = [:full_name, :description, :experience, :additional_education, :procedure, :address, :medical_center, :email, :phone, :image, :hw_start_monday, :hw_end_monday, :hw_start_tuesday, :hw_end_tuesday, :hw_start_wednesday, :hw_end_wednesday, :hw_start_thursday, :hw_end_thursday, :hw_start_friday, :hw_end_friday, :hw_start_saturday, :hw_end_saturday, :hw_start_sunday, :hw_end_sunday, :category_id, :education, :level_id] # permitted << :other if params[:action] == 'create' && current_user.admin? # permitted # end end
require 'deepstruct' module Pebblebed module RSpecHelper def god!(options = {}) options.delete(:god) stub_current_identity({:id => 1, :god => true}.merge(options)) end def user!(options = {}) options.delete(:god) stub_current_identity({:id => 1, :god => false}.merge(options)) end def guest! stub_current_identity end def current_identity @current_identity end def another_identity id = current_identity ? (current_identity.id + 1) : 1 DeepStruct.wrap(deep_stringify_keys({:id => id, :god => false}.merge(default_identity_options))) end private def stub_current_identity(options = {}) guest = options.empty? identity = nil unless guest identity = default_identity_options.merge(options) end @current_identity = DeepStruct.wrap(deep_stringify_keys(identity)) checkpoint = double(:get => DeepStruct.wrap(:identity => identity), :service_url => 'http://example.com') Pebblebed::Connector.any_instance.stub(:checkpoint => checkpoint) unless guest session = options.fetch(:session) { 'validsession' } stub_current_session session end end def default_identity_options {:realm => 'testrealm'} end def stub_current_session(session) app.any_instance.stub(:current_session).and_return session end def deep_stringify_keys(hash) if hash and hash.is_a?(Hash) hash.keys.each do |key| val = hash.delete(key) hash[key.to_s] = val.is_a?(Hash) ? deep_stringify_keys(val) : val end end hash end end end
json.data do json.proposal do json.id @proposal.id json.customer_id @proposal.customer_id json.artist_id @proposal.artist_id json.status @proposal.status json.proposal_items @proposal.proposal_items do |proposal_item| json.id proposal_item.id json.title proposal_item.title json.description proposal_item.description json.service_id proposal_item.service_id end end end
class Beer < ActiveRecord::Base include RatingAverage validates :name, presence: true belongs_to :brewery belongs_to :style has_many :ratings, :dependent => :destroy has_many :raters, -> { uniq }, through: :ratings, source: :user def to_s "#{name} (" + brewery.name + ")" end end
class SessionsController < ApplicationController def create if @user = User.authenticate(session_params[:username], session_params[:password]) session[:user_id] = @user.id render_jsonapi_from(serializer_for: :session, object: @user, status: :created) else render_error_from(message: "Invalid credentials", code: "unauthorized", status: :unauthorized) end end def destroy session[:user_id] = nil head :ok end private def session_params params.require(:session).permit(:username, :password) end end
def starts_with_a_vowel?(word) if word.match(/\b[aieouAEIOU]\w/) then true else false end end def words_starting_with_un_and_ending_with_ing(text) text.scan(/\bun\w+ing/) end def words_five_letters_long(text) text.scan(/\b\w{5}\b/) end def first_word_capitalized_and_ends_with_punctuation?(text) #capitalization and punctuation if text.match(/^\b[A-Z]/) && text.match(/[.?!]$/) then true #no capitalization but punctuation elsif text.match(/^\b[A-Z]/) && text.match(/[^.?!]$/) then false #elsif #capitalization but no punctuation #false else false end end def valid_phone_number?(phone) if phone.match(/\(?\d{3}\)?\-?\ ?\d{3}\-?\ ?\d{4}$/) then true elsif phone.match(/\s\d{8}$/) then false elsif phone.match(/\(\d{3}\)\d{3}\-\d{5}/) then false elsif phone.match(/\d{3}\ \d{2}\ \d{4}/) then false elsif phone.match(/\(\d{3}\)[a-zA-Z]/) then false else false 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' puts 'Cleaning database...' Flat.destroy_all puts 'Populating database...' 100.times do Flat.create!( name: Faker::Superhero.name, address: Faker::Address.full_address, description: Faker::Company.buzzword, price_per_night: rand(100..2000), number_of_guests: rand(1..10), picture: "https://picsum.photos/350/225/?random" ) end puts 'All done!'
# encoding: utf-8 class ListaReport < Prawn::Document # ширина колонок Widths = [20, 100, 70, 50, 50, 50, 50, 50, 50, 50] # заглавия колонок Headers = ["№", "RRE,SE si liniilor", "Punctul de evidenta", "", "№ contor.", "Indicatii", "Indicatii", "Diferenta indicat.", "Coeficient contor.", "Energie kWh"] def row(d1, d2, d3, d4, d5, d6, d7, d8, d9, d10) row = [d1, d2, d3, d4, d5, d6, d7, d8, d9, d10] make_table([row]) do |t| t.column_widths = Widths t.cells.style :borders => [:left, :right], :padding => 2 end end def to_pdf(cp,report,luna,ddate,luna_e,luna_b) # привязываем шрифты if RUBY_PLATFORM == "i386-mingw32" then font_families.update( "OpenSans" => { :bold => "./app/assets/fonts/OpenSans-Bold.ttf", :italic => "./app/assets/fonts/OpenSans-Italic.ttf", :normal => "./app/assets/fonts/OpenSans-Light.ttf" }) font "OpenSans", :size => 10 else font_families.update( "OpenSans" => { :bold => "./app/assets/fonts/OpenSans-Bold.ttf", :italic => "./app/assets/fonts/OpenSans-Italic.ttf", :normal => "./app/assets/fonts/OpenSans-Light.ttf" }) font "OpenSans", :size => 10 end # добавим время создания вверху страницы creation_date = Time.now.strftime("Отчет сгенерирован %e %b %Y в %H:%M") move_down(0) text creation_date, :align => :right, :style => :italic, :size => 9 move_down(1) text "LISTA", :size => 15, :style => :bold, :align => :center text "de calcul a intrarii energiei electrice la #{cp.name}", :size => 14, :style => :bold, :align => :center text "pentru luna #{luna} anul #{ddate.year}", :size => 15, :style => :bold, :align => :center move_down(18) text "#{flr.name}", :size => 12, :style => :bold, :align => :left move_down(10) # выборка записей data = [] if !report.nil? then items = report.each do |item| data << row(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8], item[9]) end end Headers[5] = "Indicatii \n #{luna_e}" Headers[6] = "Indicatii \n #{luna_b}" head = make_table([Headers], :column_widths => Widths) table([[head], *(data.map{|d| [d]})], :header => true, :row_colors => %w[cccccc ffffff]) do row(0).style(:background_color => 'ffffff', :text_color => '000000', :font_style => :bold, :align => :center) cells.style :borders => [:left, :right] row(0).borders = [:top, :bottom, :left, :right] # row(1..50).borders = [:left, :right] row(-1).borders = [:bottom, :left, :right] end render end end
class CampaignMonitor @@campaign = nil def self.add_subscriber(user, list, custom_fields = nil) load list_id = self.get_list_id(list) CreateSend::Subscriber.add(list_id, user.email, user.username, custom_fields, true) end def self.remove_subscriber(user, list) load list_id = self.get_list_id(list) if already_subscribed_to?(user, list) list = CreateSend::Subscriber.new(list_id, user.email) list.unsubscribe end end def self.already_subscribed_to?(user, list) load list_id = self.get_list_id(list) begin CreateSend::Subscriber.get(list_id, user.email) rescue CreateSend::BadRequest => err # Code 203: Subscriber not in list or has already been removed. if err.data.Code == 203 false else raise err end end end def self.get_subscribed_list(list) load list_id = self.get_list_id(list) list = CreateSend::List.new(list_id) list.active('2010-01-01') end private def self.load unless @@campaign puts "Initializing Campaign Monitor....." CreateSend.api_key APP_CONFIG['campaign_monitor']['key'] @@campaign = CreateSend::CreateSend.new end @@campaign end def self.get_list_id(list) APP_CONFIG['campaign_monitor']['lists'][list] end end
require 'rails_helper' RSpec.describe "Generating a client report", type: :feature do before do @client = FactoryGirl.create(:client, name: "DMU Leicester Castle Business School") @client_channel = FactoryGirl.create(:client_channel, type: "Facebook", uid: "1376049629358567", client: @client) @campaign = FactoryGirl.create(:campaign, name: "2017_interview_remarketing_promoted_posts", client: @client) @campaign_channel = FactoryGirl.create(:campaign_channel, campaign: @campaign, client_channel: @client_channel, uid: "6065738876478") end context "should" do # it "summarise the search terms" do # search_url = datasets_path(client: @client.id, channel: ['ClientChannels::Facebook'], date_from: '2017-03-01', date_to: '2017-03-01') # visit search_url # expect(current_path).to eq reports_path # expect(page).to have_content "All reports" # end # it "display some data" do # search_url = reports_path(client: @client.id, campaign: @campaign.id, channel: ['ClientChannels::Facebook'], date_from: '2017-02-13', date_to: '2017-02-20') # visit search_url # expect(page.all('table#metrics-table tr').count).to eq 2 # end end end
class MasterUpdateTradingInfoWorker include Sidekiq::Worker def perform(*args) # Do something count_crypto = cryptocurrencies.count total_pages = (count_crypto / 10) + 1 total_pages.times do |i| offset = i * 10 UpdateCryptoTradingInfoWorker.perform_in(offset.minutes.from_now, offset) end end end
class CreateEvents < ActiveRecord::Migration[5.0] def change create_table :events do |t| t.string :name t.string :headline t.text :abstract t.string :location t.datetime :start_time t.string :speaker t.string :company t.timestamps end end end
cask 'android-sdk-custom' do version "4333796" sha256 'ecb29358bc0f13d7c2fa0f9290135a5b608e38434aad9bf7067d0252c160853e' # dl.google.com/android/repository/ was verified as official when first introduced to the cask url "http://artifactory.generagames.com:8081/artifactory/generic-local/macos/programming/android-sdk/4333796/android-sdk-4333796.zip.dmg" name 'android-sdk' homepage 'https://developer.android.com/studio/releases/sdk-tools' binary "#{staged_path}/tools/android" binary "#{staged_path}/tools/bin/archquery" binary "#{staged_path}/tools/bin/avdmanager" binary "#{staged_path}/tools/bin/jobb" binary "#{staged_path}/tools/bin/lint" binary "#{staged_path}/tools/bin/monkeyrunner" binary "#{staged_path}/tools/bin/screenshot2" binary "#{staged_path}/tools/bin/sdkmanager" binary "#{staged_path}/tools/bin/uiautomatorviewer" binary "#{staged_path}/tools/emulator" binary "#{staged_path}/tools/emulator-check" binary "#{staged_path}/tools/mksdcard" binary "#{staged_path}/tools/monitor" postflight do FileUtils.ln_sf(staged_path.to_s, "#{HOMEBREW_PREFIX}/share/android-sdk") end uninstall_postflight do FileUtils.rm_f("#{HOMEBREW_PREFIX}/share/android-sdk") end caveats do depends_on_java '8' discontinued end end
RSpec.shared_context "Messages" do let (:messages) do [Twitter::DirectMessage.new({id: 1}), Twitter::DirectMessage.new({id: 2}), Twitter::DirectMessage.new({id: 3}), Twitter::DirectMessage.new({id: 4})] end end
class Review < ApplicationRecord belongs_to :product belongs_to :user validates :content_body, length: { in: 50..250 } validates :rating, inclusion: { in: 1..5 } validates_presence_of :content_body, :rating end
class Vote < ActiveRecord::Base belongs_to :user belongs_to :steam_app validates :steam_app, uniqueness: { scope: :user } validate :validate_weight private def validate_weight if weight < 0 errors.add(:weight, 'must be > 0') elsif Vote.where(user_id: user_id).sum(:weight) + weight > 100 errors.add(:weight, 'is too high!') end end end
require 'active_merchant' module PaymentService class << self def purchase_order(order, credit_card_params) gateway = ActiveMerchant::Billing::TrustCommerceGateway.new( :login => 'TestMerchant', :password => 'password', ) credit_card = ActiveMerchant::Billing::CreditCard.new(credit_card_params) if credit_card.validate.empty? response = gateway.purchase(order.total_amount * 100, credit_card) if response.success? order.update(paid_at: Time.now) else raise Error::PaymentError, response.message end else raise Error::InvalidCreditCardError, credit_card.validate end end end end
require "test_helper" describe User do let (:text_user) { User.new(name: 'SpongeBob') } describe "initilaiztaion" do it "can be instantiated" do expect(text_user.valid?).must_equal true end end describe "validations" do it "must have a name" do text_user.name = nil expect(text_user.valid?).must_equal false expect(text_user.errors.messages).must_include :name expect(text_user.errors.messages[:name]).must_equal ["can't be blank"] end end describe "relationships" do it "can have many votes" do user = User.find_by(name: 'Banana') vote_1 = Vote.create(user_id: user.id, work_id: Work.first.id) vote_2 = Vote.create(user_id: user.id, work_id: Work.last.id) expect(user.votes.count).must_be :>, 0 user.votes.each do |vote| expect(vote).must_be_instance_of Vote end end end end
# Downloads a URL to a local file on the worker module VelocitasCore class GpxDownloader include Interactor delegate :url, :filename, :attachment, to: :context attr_accessor :response #attr_accessor :url, :response, :filename # @param [String] url The URL to the GPX file. # @param [String] filename (Optional) The desired filename of the desired file. # Otherwise, it gets the name of the MD5 sum of its file contents. #def initialize(url, filename: filename) # @url = url # @filename = filename # @response = nil #end def call @response = connection.get(url) if status == 200 context.file = save! else context.fail! message: "Download failed" end end delegate :success?, to: :context def status response.try(:status) end private def contents @response.body end # Returns the handle to the File object that this file is downloaded to def save! path = File.join(basedir, computed_filename) Rails.logger.info "Saved GPX file as #{path}" file = File.new(path, 'wb') file.write contents file.close file end def basedir Rails.root.join("tmp") end def computed_filename filename || "#{SecureRandom.hex(12)}.gpx" end def connection @connnection ||= Faraday.new do |faraday| faraday.request :url_encoded # form-encode POST params faraday.response :logger # log requests to STDOUT faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end end end end
helpers do def pre_filled_input(name, value) erb( :"partials/pre_filled_input", :layout => false, :locals => {:name => name, :value => value} ) end end
require 'spec_helper' require 'yt/models/statistics_set' describe Yt::StatisticsSet do subject(:statistics_set) { Yt::StatisticsSet.new data: data } describe '#data' do let(:data) { {"key"=>"value"} } specify 'returns the data the statistics set was initialized with' do expect(statistics_set.data).to eq data end end end
class HomeController < ApplicationController def dashboard @insurance_types = InsuranceType.roots.decorate end def contact_us @contact_us_by_phone = @contact_us_by_email = ContactUs.new end def save_contact contact_us = ContactUs.new(permit_contact) if contact_us.save UserMailer.send_contact_email(contact_us).deliver flash[:notice] = "Thank you for contacting us. We will get back to you soon." redirect_to root_path else @contact_us_by_phone = contact_us.contact_type == "By Phone" ? contact_us : ContactUs.new @contact_us_by_email = contact_us.contact_type == "By Email" ? contact_us : ContactUs.new flash[:contact_errors] = contact_us.errors.full_messages.to_sentence(last_word_connector: " and ",words_connector: " , ") render "contact_us" end end private def permit_contact params.require(:contact_us).permit(:name,:phone,:type_of_insurance,:prefer_call_time, :email, :comments,:contact_type) end end
class Rsvp < ApplicationRecord belongs_to :user belongs_to :event # def set_total_price # self.price = event.price # total_days = (ends_at.to_date - starts_at.to_date).to_i # self.total = price * total_days # end before_save :set_price def set_price price = self.event.price end def event_available? event.available? starts_at. ends_at end end
# frozen_string_literal: true RSpec.describe SC::Billing::Stripe::Webhooks::Customers::CreateOperation, :stripe do subject(:call) do described_class.new.call(event) end let(:event) { StripeMock.mock_webhook_event('customer.created') } let(:customer) { event.data.object } context 'when user does not exist' do it 'creates user and company', :aggregate_failures do expect { call }.to( change(SC::Billing.user_model, :count).by(1) ) expect( SC::Billing.user_model.first[SC::Billing.registration_source.field_name] ).to eq(SC::Billing::Constants::USERS_CREATED_IN_STRIPE_TYPE) end end context 'when user already exists' do let!(:user) { create(:user, email: event.data.object.email) } it 'updates user' do expect { call }.to change { user.reload.stripe_customer_id }.to(customer.id) end end end
class Director < ActiveRecord::Base # A director has many movies has_many :movies end
# encoding: utf-8 # frozen_string_literal: true require_relative '../../test_helper' require 'pagy/extras/support' require 'pagy/countless' SingleCov.covered! unless ENV['SKIP_SINGLECOV'] describe Pagy::Frontend do let(:frontend) { TestView.new } describe "#pagy_prev_url" do it 'returns the prev url for page 1' do pagy = Pagy.new count: 1000, page: 1 pagy_countless = Pagy::Countless.new(page: 1).finalize(21) frontend.pagy_prev_url(pagy).must_be_nil frontend.pagy_prev_url(pagy_countless).must_be_nil end it 'returns the prev url for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_prev_url(pagy).must_equal '/foo?page=2' frontend.pagy_prev_url(pagy_countless).must_equal '/foo?page=2' end it 'returns the prev url for page 6' do pagy = Pagy.new count: 1000, page: 6 pagy_countless = Pagy::Countless.new(page: 6).finalize(21) frontend.pagy_prev_url(pagy).must_equal '/foo?page=5' frontend.pagy_prev_url(pagy_countless).must_equal '/foo?page=5' end it 'returns the prev url for last page' do pagy = Pagy.new count: 1000, page: 50 pagy_countless = Pagy::Countless.new(page: 50).finalize(20) frontend.pagy_prev_url(pagy).must_equal '/foo?page=49' frontend.pagy_prev_url(pagy_countless).must_equal '/foo?page=49' end end describe "#pagy_next_url" do it 'returns the next url for page 1' do pagy = Pagy.new count: 1000, page: 1 pagy_countless = Pagy::Countless.new(page: 1).finalize(21) frontend.pagy_next_url(pagy).must_equal '/foo?page=2' frontend.pagy_next_url(pagy_countless).must_equal '/foo?page=2' end it 'returns the next url for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_next_url(pagy).must_equal '/foo?page=4' frontend.pagy_next_url(pagy_countless).must_equal '/foo?page=4' end it 'returns the url next for page 6' do pagy = Pagy.new count: 1000, page: 6 pagy_countless = Pagy::Countless.new(page: 6).finalize(21) frontend.pagy_next_url(pagy).must_equal '/foo?page=7' frontend.pagy_next_url(pagy_countless).must_equal '/foo?page=7' end it 'returns the url next for last page' do pagy = Pagy.new count: 1000, page: 50 pagy_countless = Pagy::Countless.new(page: 50).finalize(20) frontend.pagy_next_url(pagy).must_be_nil frontend.pagy_next_url(pagy_countless).must_be_nil end end describe "#pagy_prev_link" do it 'renders the prev link for page 1' do pagy = Pagy.new count: 1000, page: 1 pagy_countless = Pagy::Countless.new(page: 1).finalize(21) frontend.pagy_prev_link(pagy).must_equal "<span class=\"page prev disabled\">&lsaquo;&nbsp;Prev</span>" frontend.pagy_prev_link(pagy_countless).must_equal "<span class=\"page prev disabled\">&lsaquo;&nbsp;Prev</span>" end it 'renders the prev link for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_prev_link(pagy).must_equal "<span class=\"page prev\"><a href=\"/foo?page=2\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" frontend.pagy_prev_link(pagy_countless).must_equal "<span class=\"page prev\"><a href=\"/foo?page=2\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" end it 'renders the prev link for page 6' do pagy = Pagy.new count: 1000, page: 6 pagy_countless = Pagy::Countless.new(page: 6).finalize(21) frontend.pagy_prev_link(pagy).must_equal "<span class=\"page prev\"><a href=\"/foo?page=5\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" frontend.pagy_prev_link(pagy_countless).must_equal "<span class=\"page prev\"><a href=\"/foo?page=5\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" end it 'renders the prev link for last page' do pagy = Pagy.new count: 1000, page: 50 pagy_countless = Pagy::Countless.new(page: 50).finalize(20) frontend.pagy_prev_link(pagy).must_equal "<span class=\"page prev\"><a href=\"/foo?page=49\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" frontend.pagy_prev_link(pagy_countless).must_equal "<span class=\"page prev\"><a href=\"/foo?page=49\" rel=\"next\" aria-label=\"next\" >&lsaquo;&nbsp;Prev</a></span>" end end describe "#pagy_next_link" do it 'renders the next link for page 1' do pagy = Pagy.new count: 1000, page: 1 pagy_countless = Pagy::Countless.new(page: 1).finalize(21) frontend.pagy_next_link(pagy).must_equal "<span class=\"page next\"><a href=\"/foo?page=2\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" frontend.pagy_next_link(pagy_countless).must_equal "<span class=\"page next\"><a href=\"/foo?page=2\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" end it 'renders the next link for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_next_link(pagy).must_equal "<span class=\"page next\"><a href=\"/foo?page=4\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" frontend.pagy_next_link(pagy_countless).must_equal "<span class=\"page next\"><a href=\"/foo?page=4\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" end it 'renders the next link for page 6' do pagy = Pagy.new count: 1000, page: 6 pagy_countless = Pagy::Countless.new(page: 6).finalize(21) frontend.pagy_next_link(pagy).must_equal "<span class=\"page next\"><a href=\"/foo?page=7\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" frontend.pagy_next_link(pagy_countless).must_equal "<span class=\"page next\"><a href=\"/foo?page=7\" rel=\"next\" aria-label=\"next\" >Next&nbsp;&rsaquo;</a></span>" end it 'renders the next link for last page' do pagy = Pagy.new count: 1000, page: 50 pagy_countless = Pagy::Countless.new(page: 50).finalize(20) frontend.pagy_next_link(pagy).must_equal "<span class=\"page next disabled\">Next&nbsp;&rsaquo;</span>" frontend.pagy_next_link(pagy_countless).must_equal "<span class=\"page next disabled\">Next&nbsp;&rsaquo;</span>" end end describe "#pagy_serialized" do it 'returns the serialized object for page 1' do pagy = Pagy.new count: 1000, page: 1 pagy_countless = Pagy::Countless.new(page: 1).finalize(21) frontend.pagy_serialized(pagy).must_equal({:count=>1000, :page=>1, :items=>20, :pages=>50, :last=>50, :offset=>0, :from=>1, :to=>20, :prev=>nil, :next=>2, :vars=>{:page=>1, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}, :count=>1000}, :series=>["1", 2, 3, 4, 5, :gap, 50], :prev_url=>nil, :next_url=>"/foo?page=2"}) frontend.pagy_serialized(pagy_countless).must_equal({:count=>nil, :page=>1, :items=>20, :pages=>2, :last=>2, :offset=>0, :from=>1, :to=>20, :prev=>nil, :next=>2, :vars=>{:page=>1, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}}, :series=>["1", 2], :prev_url=>nil, :next_url=>"/foo?page=2"}) end it 'returns the serialized object for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_serialized(pagy).must_equal({:count=>1000, :page=>3, :items=>20, :pages=>50, :last=>50, :offset=>40, :from=>41, :to=>60, :prev=>2, :next=>4, :vars=>{:page=>3, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}, :count=>1000}, :series=>[1, 2, "3", 4, 5, 6, 7, :gap, 50], :prev_url=>"/foo?page=2", :next_url=>"/foo?page=4"}) frontend.pagy_serialized(pagy_countless).must_equal({:count=>nil, :page=>3, :items=>20, :pages=>4, :last=>4, :offset=>40, :from=>41, :to=>60, :prev=>2, :next=>4, :vars=>{:page=>3, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}}, :series=>[1, 2, "3", 4], :prev_url=>"/foo?page=2", :next_url=>"/foo?page=4"}) end it 'returns the serialized object for page 6' do pagy = Pagy.new count: 1000, page: 6 pagy_countless = Pagy::Countless.new(page: 6).finalize(21) frontend.pagy_serialized(pagy).must_equal({:count=>1000, :page=>6, :items=>20, :pages=>50, :last=>50, :offset=>100, :from=>101, :to=>120, :prev=>5, :next=>7, :vars=>{:page=>6, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}, :count=>1000}, :series=>[1, 2, 3, 4, 5, "6", 7, 8, 9, 10, :gap, 50], :prev_url=>"/foo?page=5", :next_url=>"/foo?page=7"}) frontend.pagy_serialized(pagy_countless).must_equal({:count=>nil, :page=>6, :items=>20, :pages=>7, :last=>7, :offset=>100, :from=>101, :to=>120, :prev=>5, :next=>7, :vars=>{:page=>6, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}}, :series=>[1, 2, 3, 4, 5, "6", 7], :prev_url=>"/foo?page=5", :next_url=>"/foo?page=7"}) end it 'returns the serialized object for last page' do pagy = Pagy.new count: 1000, page: 50 pagy_countless = Pagy::Countless.new(page: 50).finalize(20) frontend.pagy_serialized(pagy).must_equal({:count=>1000, :page=>50, :items=>20, :pages=>50, :last=>50, :offset=>980, :from=>981, :to=>1000, :prev=>49, :next=>nil, :vars=>{:page=>50, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}, :count=>1000}, :series=>[1, :gap, 46, 47, 48, 49, "50"], :prev_url=>"/foo?page=49", :next_url=>nil}) frontend.pagy_serialized(pagy_countless).must_equal({:count=>nil, :page=>50, :items=>20, :pages=>50, :last=>50, :offset=>980, :from=>981, :to=>1000, :prev=>49, :next=>nil, :vars=>{:page=>50, :items=>20, :outset=>0, :size=>[1, 4, 4, 1], :page_param=>:page, :params=>{}, :anchor=>"", :link_extra=>"", :item_path=>"pagy.info.item_name", :cycle=>false, :breakpoints=>{0=>[1, 4, 4, 1]}}, :series=>[1, :gap, 46, 47, 48, 49, "50"], :prev_url=>"/foo?page=49", :next_url=>nil}) end end describe "#pagy_apply_init_tag" do it 'renders the default apply-init tag for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_apply_init_tag(pagy, :testFunction).must_equal "<script type=\"application/json\" class=\"pagy-json\">[\"applyInit\",\"testFunction\",{\"count\":1000,\"page\":3,\"items\":20,\"pages\":50,\"last\":50,\"offset\":40,\"from\":41,\"to\":60,\"prev\":2,\"next\":4,\"vars\":{\"page\":3,\"items\":20,\"outset\":0,\"size\":[1,4,4,1],\"page_param\":\"page\",\"params\":{},\"anchor\":\"\",\"link_extra\":\"\",\"item_path\":\"pagy.info.item_name\",\"cycle\":false,\"breakpoints\":{\"0\":[1,4,4,1]},\"count\":1000},\"series\":[1,2,\"3\",4,5,6,7,\"gap\",50],\"prev_url\":\"/foo?page=2\",\"next_url\":\"/foo?page=4\"}]</script>" frontend.pagy_apply_init_tag(pagy_countless, :testFunction).must_equal "<script type=\"application/json\" class=\"pagy-json\">[\"applyInit\",\"testFunction\",{\"count\":null,\"page\":3,\"items\":20,\"pages\":4,\"last\":4,\"offset\":40,\"from\":41,\"to\":60,\"prev\":2,\"next\":4,\"vars\":{\"page\":3,\"items\":20,\"outset\":0,\"size\":[1,4,4,1],\"page_param\":\"page\",\"params\":{},\"anchor\":\"\",\"link_extra\":\"\",\"item_path\":\"pagy.info.item_name\",\"cycle\":false,\"breakpoints\":{\"0\":[1,4,4,1]}},\"series\":[1,2,\"3\",4],\"prev_url\":\"/foo?page=2\",\"next_url\":\"/foo?page=4\"}]</script>" end it 'renders the apply-init tag for page 3' do pagy = Pagy.new count: 1000, page: 3 pagy_countless = Pagy::Countless.new(page: 3).finalize(21) frontend.pagy_apply_init_tag(pagy, :testFunction, {a: 1}).must_equal "<script type=\"application/json\" class=\"pagy-json\">[\"applyInit\",\"testFunction\",{\"a\":1}]</script>" frontend.pagy_apply_init_tag(pagy_countless, :testFunction, {a: 1}).must_equal "<script type=\"application/json\" class=\"pagy-json\">[\"applyInit\",\"testFunction\",{\"a\":1}]</script>" end end end
# frozen_string_literal: true # Name. When("I set the name to {string}") do |name| step %(I fill in "taxon_name_string" with "#{name}") end # Protonym name. When("I set the protonym name to {string}") do |name| step %(I fill in "protonym_name_string" with "#{name}") end # Misc. Then("{string} should be of the rank of {string}") do |name, rank| taxon = Taxon.find_by!(name_cache: name) expect(taxon.rank).to eq rank end Then("the {string} of {string} should be {string}") do |association, taxon_name, other_taxon_name| taxon = Taxon.find_by!(name_cache: taxon_name) other_taxon = Taxon.find_by!(name_cache: other_taxon_name) expect(taxon.public_send(association)).to eq other_taxon end
class Post < ActiveRecord::Base attr_accessible :author_id, :receiver_id, :body, :album_id, :photo belongs_to :receivers, class_name: "User", foreign_key: "receiver_id" belongs_to :author, class_name: "User", foreign_key: "author_id" belongs_to :album has_many :likes, as: :likeable has_many :likers, through: :likes has_many :comments, as: :commentable has_attached_file :photo, styles: {thumbnail: "100x100>"} validates :author_id, :receiver_id, presence: true validate :body_or_photo def author User.find(self.author_id) end def receiver User.find(self.receiver_id) end def body_or_photo if self.body.blank? && !self.photo.blank? true elsif !self.body.blank? && self.photo.blank? true elsif !self.body.blank? && !self.photo.blank? true else false end end def photo? !self.photo_file_name.nil? end def num_likes self.likes.count end end
class AddHasWozToArm < ActiveRecord::Migration def change add_column :arms, :has_woz, :boolean, default: false end end
class Process < ActiveRecord::Base has_many :processable_processes has_many :processesables, through: :processable_processes end
require 'date' require_relative 'app_spec_helper' describe "Put Request" do describe "Invalid ID" do put('/venues/someInvalidID', updated_name_json.to_json, standard_header) response = last_response it "should respond with status 404" do expect(response.status).to eql(404) end it "should respond with body 404" do expect(response.body).to eql(not_found_with_id_error("someInvalidID")) end end describe "Invalid Paramater" do put('/venues/56e40252133859f813000027', updated_invalid_name_json.to_json, standard_header) response = last_response it "should respond with status 400" do expect(response.status).to eql(400) end it "should respond with correct error body" do expect(response.body).to eql(empty_param_error("name")) end end describe "Valid ID" do get '/venues/56e40252133859f813000027' old_response_body = JSON.parse(last_response.body) old_updated_at_string = old_response_body["records"].first["updated_at"] old_updated_at = Time.at(Time.parse(old_updated_at_string)) put('/venues/56e40252133859f813000027', updated_name_json.to_json, standard_header) response = last_response it "should update paramater updated_at" do get '/venues/56e40252133859f813000027' new_response_body = JSON.parse(last_response.body) new_updated_at_string = new_response_body["records"].first["updated_at"] new_updated_at = Time.at(Time.parse(new_updated_at_string)) expect(new_updated_at).to be > old_updated_at end it "should update the param" do get '/venues/56e40252133859f813000027' updated_param_body = JSON.parse(last_response.body) expect(updated_param_body["records"].first["name"]).to eql("Rspec Test") end it "should respond with status 204" do expect(response.status).to eql(204) end it "should respond with duration in the header" do expect(response.header["x-duration"].to_s).to match(/(\d)/) end end end
class AddEmailOptions < ActiveRecord::Migration def self.up add_column :accounts, :email_info, :boolean, :default => false add_column :accounts, :email_errors, :boolean, :default => false end def self.down remove_column :accounts, :email_info remove_column :accounts, :email_errors end end
# frozen_string_literal: true class LiteralToken < Token EXPRESSION = /\"(.*)\"/ def initialize(value) @value = value end def to_s "Literal(#{value})" end def debug_print(level) pad = "\t" * level "#{pad}#{to_s}" end def self.from(token_match) new(token_match[1]) end end
require 'keyutils/key' require 'keyutils/key_types' module Keyutils class Keyring < Key include Enumerable # Clear the contents of the keyring. # # The caller must have write permission on a keyring to be able clear it. # @return [Keyring] self # @raise [Errno::ENOKEY] the keyring is invalid # @raise [Errno::EKEYEXPIRED] the keyring has expired # @raise [Errno::EKEYREVOKED] the keyring had been revoked # @raise [Errno::EACCES] the keyring is not writable by the calling process def clear Lib.keyctl_clear id self end # Link a key to the keyring. # # Creates a link from this keyring to +key+, displacing any link to another # key of the same type and description in this keyring if one exists. # # The caller must have write permission on a keyring to be able to create # links in it. # # The caller must have link permission on a key to be able to create a # link to it. # # @param key [Key] the key to link to this keyring # @return [Keyring] self # @raise [Errno::ENOKEY] the key or the keyring specified are invalid # @raise [Errno::EKEYEXPIRED] the key or the keyring specified have expired # @raise [Errno::EKEYREVOKED] the key or the keyring specified have been # revoked # @raise [Errno::EACCES] the keyring exists, but is not writable by the # calling process # @raise [Errno::ENOMEM] insufficient memory to expand the keyring # @raise [Errno::EDQUOT] expanding the keyring would exceed the keyring # owner's quota # @raise [Errno::EACCES] the key exists, but is not linkable by the # calling process # @see #unlink def link key Lib.keyctl_link key.id, id self end alias << link # Unlink a key from the keyring. # # Removes a link from this keyring to +key+ if it exists. # # The caller must have write permission on a keyring to be able to remove # links in it. # @param key [Key] the key to unlink from this keyring # @return [Keyring] self # @raise [Errno::ENOKEY] the key or the keyring specified are invalid # @raise [Errno::EKEYEXPIRED] the key or the keyring specified have expired # @raise [Errno::EKEYREVOKED] the key or the keyring specified have been # revoked # @raise [Errno::EACCES] the keyring exists, but is not writable by the # calling process # @see #link def unlink key Lib.keyctl_unlink key.id, id self rescue Errno::ENOENT # there was no link self end # Search the keyring for a key # # Recursively searches the keyring for a key of the specified +type+ and # +description+. # # If found, the key will be attached to the +destination+ keyring (if # given), and returned. # # The source keyring must grant search permission to the caller, and for a # key to be found, it must also grant search permission to the caller. # Child keyrings will be only be recursively searched if they grant search # permission to the caller as well. # # If the +destination+ keyring is given, then the link may only be formed # if the found key grants the caller link permission and the destination # keyring grants the caller write permission. # # If the search is successful, and if the destination keyring already # contains a link to a key that matches the specified type and description, # then that link will be replaced by a link to the found key. # # @param type [Symbol] the type of the key to find # @param description [String] the description of the key to find # @param destination [Keyring, nil] the keyring to attach the key if found # @return [Key, nil] the key, if found # @raise [Errno::EKEYEXPIRED] one of the keyrings has expired, or the only # key found was expired # @raise [Errno::EKEYREVOKED] one of the keyrings has been revoked, or the # only key found was revoked # @raise [Errno::ENOMEM] insufficient memory to expand the destination # keyring # @raise [Errno::EDQUOT] the key quota for this user would be exceeded by # creating a link to the found key in the destination keyring # @raise [Errno::EACCES] the source keyring didn't grant search permission, # the destination keyring didn't grant write permission or the found key # didn't grant link permission to the caller # @see #request def search type, description, destination = nil serial = Lib.keyctl_search id, type.to_s, description, destination.to_i Key.send :new_dispatch, serial, type.intern, description rescue Errno::ENOKEY nil end # Read the keyring. # # Reads the list of keys in this keyring. # # The caller must have read permission on a key to be able to read it. # # @return [<Key>] the keyring members # @raise [Errno::ENOKEY] the keyring is invalid # @raise [Errno::EKEYEXPIRED] the keyring has expired # @raise [Errno::EKEYREVOKED] the keyring had been revoked # @raise [Errno::EACCES] the keyring is not readable by the calling process # @see #each def read super.unpack('L*').map do |serial| # try to map to the correct class key = Key.send :new, serial, nil, nil Key.send(:new_dispatch, serial, key.type, key.description) rescue key end end alias to_a read undef to_s rescue nil # Iterate over linked keys # # @return [Enumerator, Keyring] self if block given, else an Enumerator # @yieldparam key [Key] member of the keyring # @see #read def each &b read.each &b end # Iterate over keys recursively # # Performs a depth-first recursive scan of the keyring tree and yields for # every link found in the accessible keyrings in that tree. # # Errors are ignored. Inaccessible keyrings are not scanned, but links to # them are still yielded. If key attributes (and hence ype) cannot be # retrieved, a generic {Key} object is yielded and an error that prevented # it is indicated. # # This method yields for each link found in all the keyrings in the tree # and so may be called multiple times for a particular key if that key has # multiple links to it. # # @yieldparam key [Key] the key to which the link points # @yieldparam parent [Keyring, nil] the keyring containing the link or nil # for the initial key. # @yieldparam attributes [Hash] key attributes, as returned by # {Key#describe} # @yieldparam error [SystemCallError, nil] error that prevented retrieving # key attributes # # @return [Enumerator, Keyring] self if block given, else an Enumerator def each_recursive return enum_for __method__ unless block_given? Lib.recursive_key_scan serial, ->(parent, key, desc, desc_len, _) do parent = parent == 0 ? nil : Keyring.send(:new, parent, nil) if desc_len > 0 attributes = Key.send :parse_describe, desc.read_string(desc_len) key = Key.send :new_dispatch, key, attributes[:type], attributes[:desc] error = nil else attributes = nil key = Key.send :new, key, nil, nil error = SystemCallError.new FFI.errno end yield key, parent, attributes, error 0 end, nil self end # @return [Fixnum] number of keys linked to this keyring def length read.length end # Add a key to the kernel's key management facility. # # Asks the kernel to create or update a key of the given +type+ and # +description+, instantiate it with the +payload+, and to attach it to # this keyring. # # The key type may reject the data if it's in the wrong format or in # some other way invalid. # # Keys of the user-defined key type ("user") may contain a blob of # arbitrary data, and the description may be any valid string, though it # is preferred that the description be prefixed with a string # representing the service to which the key is of interest and a colon # (for instance "afs:mykey"). # # If this keyring already contains a key that matches the specified type # and description then, if the key type supports it, that key will be # updated rather than a new key being created; if not, a new key will be # created and it will displace the link to the extant key from the keyring. # # @param type [Symbol] key type # @param description [String] key description # @param payload [#to_s, nil] payload # @return [Key] the key created or updated # @raise [Errno::ENOKEY] the keyring doesn't exist # @raise [Errno::EKEYEXPIRED] the keyring has expired # @raise [Errno::EKEYREVOKED] the keyring has been revoked # @raise [Errno::EINVAL] the payload data was invalid # @raise [Errno::ENODEV] the key type was invalid # @raise [Errno::ENOMEM] insufficient memory to create a key # @raise [Errno::EDQUOT] the key quota for this user would be exceeded by # creating this key or linking it to the keyring # @raise [Errno::EACCES] the keyring wasn't available for modification by # the user def add type, description, payload serial = Lib.add_key \ type.to_s, description, payload && payload.to_s, payload && payload.to_s.length || 0, to_i Key.send :new_dispatch, serial, type.intern, description end # Request a key from the kernel's key management facility. # # Asks the kernel to find a key of the given +type+ that matches the # specified +description+ and, if successful, to attach it this keyring. # # {#request} first recursively searches all the keyrings attached to the # calling process in the order thread-specific keyring, process-specific # keyring and then session keyring for a matching key. # # If {#request} is called from a program invoked by request_key(2) on # behalf of some other process to generate a key, then the keyrings of # that other process will be searched next, using that other process's # UID, GID, groups and security context to control access. # # The keys in each keyring searched are checked for a match before any # child keyrings are recursed into. Only keys that are searchable for # the caller may be found, and only searchable keyrings may be searched. # # If the key is not found then, if +callout_info+ is not nil, this # function will attempt to look further afield. In such a case, the # +callout_info+ is passed to a user-space service such as # +/sbin/request-key+ to generate the key. # # If that is unsuccessful also, then an error will be raised, and a # temporary negative key will be installed in the keyring. This # will expire after a few seconds, but will cause subsequent calls to # {#request} to fail until it does. # # If a key is created, no matter whether it's a valid key or a negative # key, it will displace any other key of the same type and description # from the keyring. # @param type [Symbol] key type # @param description [String] key description # @param callout_info [String, nil] additional parameters for the # request-key(8) facility # @return [Key, nil] the key, if found # @raise [Errno::EACCES] the keyring wasn't available for modification by the user # @raise [Errno::EINTR] the request was interrupted by a signal # @raise [Errno::EDQUOT] the key quota for this user would be exceeded by creating this key or linking it to the keyring # @raise [Errno::EKEYEXPIRED] an expired key was found, but no replacement could be obtained # @raise [Errno::EKEYREJECTED] the attempt to generate a new key was rejected # @raise [Errno::EKEYREVOKED] a revoked key was found, but no replacement could be obtained # @raise [Errno::ENOMEM] insufficient memory to create a key # @see Keyring#search # @see http://man7.org/linux/man-pages/man2/request_key.2.html request_key(2) # @see #assume_authority def request type, description, callout_info = '' serial = Lib.request_key \ type.to_s, description, callout_info, to_i new_dispatch serial, type.intern, description rescue Errno::ENOKEY nil end # Get a member "user" key # # Searches the members of the keyring for a :user type key with the # given +description+ # # @param description [String] description of the key to find # @return [Key, nil] the key, if found def [] description find do |key| key.type == :user && key.description == description rescue false end end # Set a member "user" key # # Updates or creates a member key of type "user" and given description # # @param description [String] the description of the key to update or # create # @param payload [String] the new key payload # @return [String] +payload+ def []= description, payload add :user, description, payload end # Return all "user" subkeys # # Keys that cannot be read are ommited. # # @return [{String => String}] user keys' descriptions and their payloads def to_h keys = find_all { |k| k.type == :user rescue false } pairs = keys.map { |k| [k.description, k.to_s] rescue nil } Hash[*pairs.compact.flatten] end class << self # Set the implicit destination keyring # # Sets the default destination for implicit key requests for the current # thread. # # After this operation has been issued, keys acquired by implicit key # requests, such as might be performed by open() on an AFS or NFS # filesystem, will be linked by default to the specified keyring by this # function. # # Only one of the special keyrings can be set as default: # - {Thread} # - {Process} # - {Session} # - {User} # - {UserSession} # - {Group} # # If +keyring+ is nil, the default behaviour is selected, which is to # use the thread-specific keyring if there is one, otherwise the # process-specific keyring if there is one, otherwise the session # keyring if there is one, otherwise the UID-specific session keyring. # # @param keyring [Keyring, nil] the new default keyring # @return [Keyring, nil] +keyring+ # @see .default def default= keyring = nil id = keyring.to_i raise ArgumentError, 'only special keyrings can be default' \ if id > 0 Lib.keyctl_set_reqkey_keyring -id end # Get the implicit destination keyring # # Gets the default destination for implicit key requests for the current # thread. # # Keys acquired by implicit key requests, such as might be performed # by open() on an AFS or NFS filesystem, will be linked by default to # that keyring. # # Only one of the special keyrings can be returned: # - {Thread} # - {Process} # - {Session} # - {User} # - {UserSession} # - {Group} # # If nil is returned, the default behaviour is selected, which is to # use the thread-specific keyring if there is one, otherwise the # process-specific keyring if there is one, otherwise the session # keyring if there is one, otherwise the UID-specific session keyring. # # @return [Keyring, nil] the default keyring # @see .default= def default [nil, Thread, Process, Session, User, UserSession, Group]\ [Lib.keyctl_set_reqkey_keyring -1] end # Get the persistent keyring for a user. # # @note Not every system supports persistent keyrings. # # Unlike the session and user keyrings, this keyring will persist once # all login sessions have been deleted and can thus be used to carry # authentication tokens for processes that run without user interaction, # such as programs started by cron. # # The persistent keyring will be created by the kernel if it does not # yet exist. Each time this function is called, the persistent keyring # will have its expiration timeout reset to the value in # +/proc/sys/kernel/keys/persistent_keyring_expiry+ (by default three # days). Should the timeout be reached, the persistent keyring will be # removed and everything it pins can then be garbage collected. # # If UID is nil then the calling process's real user ID will be used. If # UID is not nil then {Errno::EPERM} will be raised if the user ID # requested does not match either the caller's real or effective user # IDs or if the calling process does not have _SetUid_ capability. # # If successful, a link to the persistent keyring will be added into # +destination+. # # @param uid [Fixnum, nil] UID of the user for which the persistent # keyring is requested # @param destination [Keyring, nil] keyring to add the persistent keyring # to # @return [Keyring] the persistent keyring # @raise [Errno::EPERM] not permitted to access the persistent keyring # for the requested UID. # @raise [Errno::ENOMEM] insufficient memory to create the persistent # keyring or to extend +destination+. # @raise [Errno::ENOKEY] +destination+ does not exist. # @raise [Errno::EKEYEXPIRED] +destination+ has expired. # @raise [Errno::EKEYREVOKED] +destination+ has been revoked. # @raise [Errno::EDQUOT] the user does not have sufficient quota to # extend +destination+. # @raise [Errno::EACCES] +destination+ exists, but does not grant write # permission to the calling process. # @raise [Errno::EOPNOTSUPP] persistent keyrings are not supported by this # system def persistent uid = nil, destination = nil Keyring.send \ :new, Lib.keyctl_get_persistent(uid || -1, destination.to_i), nil, nil end end end # This module contains the additional methods included in {Keyutils::Keyring::Session}. module SessionKeyring # Join a different session keyring # # Change the session keyring to which a process is subscribed. # # If +name+ is nil then a new anonymous keyring will be created, and the # process will be subscribed to that. # # If +name+ is provided, then if a keyring of that name is available, # the process will attempt to subscribe to that keyring, raising an # error if that is not permitted; otherwise a new keyring of that name # is created and attached as the session keyring. # # To attach to an extant named keyring, the keyring must have search # permission available to the calling process. # @param name [String, nil] name of the keyring to join # @return [Keyring] the keyring found or created # @raise [Errno::ENOMEM] insufficient memory to create a key # @raise [Errno::EDQUOT] the key quota for this user would be exceeded # by creating this key or linking it to the keyring # @raise [Errno::EACCES] the named keyring exists, but is not searchable # by the calling process def join name = nil Keyring.send :new, Lib.keyctl_join_session_keyring(name), name end # Set the parent process's session keyring. # # Changes the session keyring to which the calling process's parent # subscribes to be the that of the calling process. # # The keyring must have link permission available to the calling process, # the parent process must have the same UIDs/GIDs as the calling process, # and the LSM must not reject the replacement. Furthermore, this may not # be used to affect init or a kernel thread. # # Note that the replacement will not take immediate effect upon the parent # process, but will rather be deferred to the next time it returns to # userspace from kernel space. # # @return [Keyring] self # @raise [Errno::ENOMEM] insufficient memory to create a key. # @raise [Errno::EPERM] the credentials of the parent don't match those of # the caller. # @raise [Errno::EACCES] the named keyring exists, but is not linkable by # the calling process. def to_parent Lib.keyctl_session_to_parent self end end KeyTypes[:keyring] = Keyring class Keyring # thread-specific keyring Thread = Keyring.new Lib::KEY_SPEC[:THREAD_KEYRING], nil # process-specific keyring Process = Keyring.new Lib::KEY_SPEC[:PROCESS_KEYRING], nil # session-specific keyring # @see Keyutils::SessionKeyring Session = Keyring.new(Lib::KEY_SPEC[:SESSION_KEYRING], nil). extend SessionKeyring # UID-specific keyring User = Keyring.new Lib::KEY_SPEC[:USER_KEYRING], nil # UID-session keyring UserSession = Keyring.new Lib::KEY_SPEC[:USER_SESSION_KEYRING], nil # GID-specific keyring Group = Keyring.new Lib::KEY_SPEC[:GROUP_KEYRING], nil end end
class RemoveFollowersColumnFromUsers < ActiveRecord::Migration[5.0] def change remove_column :users, :followers remove_column :users, :following end end
module Nationality module Cell class Survey < Abroaders::Cell::Base def title 'Are You Eligible?' end private def buttons cell(Buttons, model) end class Buttons < Abroaders::Cell::Base include Escaped property :companion_first_name property :couples? property :owner_first_name private def couples_h { both: "Both #{owner_first_name} and #{companion_first_name} are U.S. citizens or permanent residents.", owner: "Only #{owner_first_name} is a U.S. citizen or permanent resident.", companion: "Only #{companion_first_name} is a U.S. citizen or permanent resident.", neither: "Neither of us is a U.S. citizen or permanent resident.", } end end end end end
class VoteItemsController < ApplicationController before_filter :authenticate, :only => [:index, :show, :new, :edit, :create, :update, :destroy] before_filter :correct_user, :only => [:edit, :update, :destroy, :show] # GET /vote_items # GET /vote_items.xml def index @vote_items = current_user.rsvp_event.vote_items.all(:order => "rank") respond_to do |format| format.html # index.html.erb format.xml { render :xml => @vote_items } end end # GET /vote_items/1 # GET /vote_items/1.xml def show respond_to do |format| format.html # show.html.erb format.xml { render :xml => @vote_item } end end # GET /vote_items/new # GET /vote_items/new.xml def new @vote_item = VoteItem.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @vote_item } end end # GET /vote_items/1/edit def edit end # POST /vote_items # POST /vote_items.xml def create @vote_item = VoteItem.new(params[:vote_item]) @vote_item.rsvp_event = current_user.rsvp_event respond_to do |format| if @vote_item.save format.html { redirect_to(vote_items_path, :notice => 'The food option was successfully created.') } format.xml { render :xml => @vote_item, :status => :created, :location => @vote_item } else format.html { render :action => "new" } format.xml { render :xml => @vote_item.errors, :status => :unprocessable_entity } end end end # PUT /vote_items/1 # PUT /vote_items/1.xml def update @vote_item.rsvp_event = current_user.rsvp_event respond_to do |format| if @vote_item.update_attributes(params[:vote_item]) format.html { redirect_to(vote_items_path, :notice => 'The food option was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @vote_item.errors, :status => :unprocessable_entity } end end end # DELETE /vote_items/1 # DELETE /vote_items/1.xml def destroy @vote_item.destroy respond_to do |format| format.html { redirect_to(vote_items_url) } format.xml { head :ok } end end private #HTML Before Filters def authenticate deny_access unless signed_in? end def correct_user @vote_item = VoteItem.find(params[:id]) redirect_to(root_path) if @vote_item.rsvp_event.nil? redirect_to(root_path) unless current_user?(@vote_item.rsvp_event.user) end def admin_user redirect_to(root_path) unless current_user.admin? end end
FactoryGirl.define do factory :world, :class => Refinery::Worlds::World do sequence(:Main_headline) { |n| "refinery#{n}" } end end
require "rails_helper" RSpec.feature "edit space redirects to previous page" do context "logged in as owner space" do scenario "returned to space show" do user = create(:user) space = create(:space, approved: true) user.spaces << space allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit space_path(space) click_on "Edit Space" fill_in "Occupancy", with: 90 fill_in "Name", with: "The best name" click_on "Update Space" expect(current_path).to eq space_path(space) end end context "logged in as platform admin" do scenario "returned to all spaces" do admin = create(:user, role: 1) space = create(:space, approved: true) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit admin_spaces_path click_on "Edit" fill_in "Occupancy", with: 90 fill_in "Name", with: "The best name" click_on "Update Space" expect(current_path).to eq admin_spaces_path end end end
require 'rails_helper' RSpec.describe ArticlesController, type: :controller do describe '#index' do it 'renders the index template' do get :index expect(response).to render_template(:index) end end describe '#show' do let(:article) { FactoryBot.create(:article) } it 'renders the index template' do get :show, params: { uid: article.uid } expect(response).to render_template(:show) end end describe '#new' do context 'when signed in' do before { sign_in user } let(:user) { FactoryBot.create(:user) } it 'renders the new template' do get :new expect(response).to render_template(:new) end end context 'when not signed in' do it 'redirects to sign in page' do get :new expect(response).to redirect_to('/users/sign_in') end end end describe '#edit' do let(:associated_user) { FactoryBot.create(:user) } let(:unassociated_user) { FactoryBot.create(:user) } let(:moderator_user) { FactoryBot.create(:user, :moderator) } let(:article) { FactoryBot.create(:article, user: associated_user) } context 'when associated user is signed in' do before { sign_in associated_user } it 'renders the edit template' do get :edit, params: { uid: article.uid } expect(response).to render_template(:edit) end end context 'when moderator user is signed in' do before { sign_in moderator_user } it 'renders the edit template' do get :edit, params: { uid: article.uid } expect(response).to render_template(:edit) end end context 'when unassociated user is signed in' do before { sign_in unassociated_user } it 'is forbidden' do get :edit, params: { uid: article.uid } expect(response).to be_forbidden end end context 'when not signed in' do it 'redirects to sign in page' do get :edit, params: { uid: article.uid } expect(response).to redirect_to('/users/sign_in') end end end describe '#create' do let(:user) { FactoryBot.create(:user) } let(:article_params) do FactoryBot.attributes_for(:article).merge(user_id: user.id) end context 'when signed in' do before { sign_in user } it 'renders the show template' do post :create, params: { article: article_params } article = Article.find_by(user: user) expect(response).to redirect_to(article_path(article.uid)) end end context 'when not signed in' do it 'redirects to sign in page' do post :create, params: { article: article_params } expect(response).to redirect_to('/users/sign_in') end end end describe '#update' do let(:user) { FactoryBot.create(:user) } let(:moderator) { FactoryBot.create(:user, :moderator) } let(:article) { FactoryBot.create(:article, user: user) } let(:params) do { uid: article.uid, article: { description: 'New description' } } end context 'when associated user is signed in' do before { sign_in user } it 'renders the show template' do patch :update, params: params expect(response).to redirect_to(article_path(article.uid)) end it 'updates the article' do patch :update, params: params expect(article.reload.description).to eq(params[:article][:description]) end end context 'when moderator is signed in' do before { sign_in moderator } it 'renders the show template' do patch :update, params: params expect(response).to redirect_to(article_path(article.uid)) end end context 'when not signed in' do it 'redirects to sign in page' do patch :update, params: params expect(response).to redirect_to('/users/sign_in') end end end describe '#destroy' do let(:associated_user) { FactoryBot.create(:user) } let(:unassociated_user) { FactoryBot.create(:user) } let(:moderator_user) { FactoryBot.create(:user, :moderator) } let(:article) { FactoryBot.create(:article, user: associated_user) } context 'when associated user is signed in' do before { sign_in associated_user } it 'redirects to the index' do delete :destroy, params: { uid: article.uid } expect(response).to redirect_to('/') end it 'destroys the article' do delete :destroy, params: { uid: article.uid } expect(Article.where(id: article.id)).to be_empty end end context 'when moderator user is signed in' do before { sign_in moderator_user } it 'destroys the article' do delete :destroy, params: { uid: article.uid } expect(Article.where(id: article.id)).to be_empty end end context 'when unassociated user is signed in' do before { sign_in unassociated_user } it 'is forbidden' do delete :destroy, params: { uid: article.uid } expect(response).to be_forbidden end end context 'when not signed in' do it 'redirects to sign in page' do delete :destroy, params: { uid: article.uid } expect(response).to redirect_to('/users/sign_in') end end end end
namespace :sync do desc "Sync the counter caches" task :comments => :environment do posts = OldTextFile.all posts.each do |post| OldTextFile.update_counters post.id, :comments_count => post.comments.count end end end
require 'spec_helper' feature 'User Registration' do before do DatabaseCleaner.clean end scenario 'User can create an account, a welcome email is sent and they are logged in' do visit '/' emails_sent = ActionMailer::Base.deliveries.length click_link 'Register' fill_in 'user[email]', with: 'bob@example.com' fill_in 'user[password]', with: 'password1' fill_in 'user[password_confirmation]', with: 'password1' click_button 'Register' expect(page).to have_content 'Welcome, bob@example.com' expect(ActionMailer::Base.deliveries.length).to eq (emails_sent + 1) expect(page).to_not have_content 'Login' expect(page).to_not have_content 'Register' end scenario 'Users see an error message if they register with an invalid email' do visit '/' click_link 'Register' fill_in 'user[email]', with: 'invaliduserexample,com' fill_in 'user[password]', with: 'password1' fill_in 'user[password_confirmation]', with: 'password1' click_button 'Register' expect(current_path).to eq '/users' expect(page).to have_content 'Email is invalid' end context 'user logs in' do before do visit '/' click_link 'Register' fill_in 'user[email]', with: 'user@example.com' fill_in 'user[password]', with: 'password1' fill_in 'user[password_confirmation]', with: 'password1' click_button 'Register' end scenario 'User email shows to indicate logged in status after navigating away from login page' do visit '/' expect(page).to have_content 'Welcome, user@example.com' click_link 'Logout' expect(current_url).to eq 'http://www.example.com/' expect(page).to have_no_content 'Welcome, user@example.com' end scenario 'Registered user can login without password confirmation' do click_link 'Logout' click_link 'Login' fill_in 'session[email]', with: 'user@example.com' fill_in 'session[password]', with: 'password1' click_button 'Login' expect(page).to have_content 'Welcome, user@example.com' end end scenario 'App sends password reset email' do visit '/' click_link 'Register' fill_in 'user[email]', with: 'user@example.com' fill_in 'user[password]', with: 'password1' fill_in 'user[password_confirmation]', with: 'password1' click_button 'Register' click_link 'Logout' emails_sent = ActionMailer::Base.deliveries.length click_link 'Login' click_link 'Forgot password?' fill_in 'email', with: 'user@example.com' click_button 'Reset my password' expect(ActionMailer::Base.deliveries.length).to eq (emails_sent + 1) expect(page).to have_content 'Please check your email to reset your password.' found_user = User.find_by(email: "user@example.com") expect(found_user.reset_token).to_not be_nil email_message = ActionMailer::Base.deliveries.last.body.raw_source @doc = Nokogiri::HTML(email_message) result = @doc.xpath("//html//body//p//a//@href")[0].value visit result fill_in 'user[password]', with: 'foo' fill_in 'user[password]', with: 'foo' click_button 'Update password' expect(page).to have_content("Password must be at least 8-12 characters with 1 number") fill_in 'user[password]', with: 'foo' fill_in 'user[password]', with: 'foo' click_button 'Update password' expect(page).to have_content("Password must be at least 8-12 characters with 1 number") fill_in 'user[password]', with: 'password2' fill_in 'user[password_confirmation]', with: 'password2' click_button 'Update password' expect(page).to have_content("Please use your new password to login.") fill_in 'session[email]', with: 'user@example.com' fill_in 'session[password]', with: 'password2' click_button 'Login' expect(page).to have_content 'Welcome, user@example.com' end end
# == Schema Information # # Table name: deposits # # id :integer not null, primary key # brokers_lead_id :integer # amount :integer # currency :string # created_at :datetime # updated_at :datetime # class Deposit <ActiveRecord::Base validates_presence_of :brokers_lead_id, :amount, :currency belongs_to :brokers_lead end
module ApplicationHelper # Render the user profile picture depending on the gravatar configuration. def user_image_tag(email) if APP_CONFIG.enabled?("gravatar") && !email.nil? && !email.empty? gravatar_image_tag(email) else image_tag "user.svg", class: "user-picture" end end # Render the image tag that is suitable for activities. def activity_time_tag(ct) time_tag ct, time_ago_in_words(ct), title: ct end end
# frozen_string_literal: true class HousePresenter < ApplicationPresenter def statuses Enums.house_statuses end def street_names House.all.collect(&:street).uniq end def for_select House.all.each_with_object({}) do |house, acc| acc[house.street] ||= [] acc[house.street] << [house.number, house.id] end end def select_list House.all.map { |h| [addr(h), h.id] } end def house_address addr(__getobj__) end def linked_lot_addresses return '' unless lots lots .map { |lot| HousePresenter.new(lot, nil).house_address } .join('; ') end def err_msgs errors.full_messages end def contributions(year: Date.current.year) contribs = Contributions::GetForHouseAndYear.call(house_id, year) contribs.reduce(0) { |sum, c| sum + c.amount_cents } end def occupants Person.where('house_id = ?', id) end private def addr(house) "#{house.number} #{house.street}" end def house_id id end end
class AddUnitPriceDiscountsColumnToInvoiceItems < ActiveRecord::Migration[5.2] def change add_column :invoice_items, :unit_price_discounted, :integer end end
class RegistrationsController < ApplicationController prepend_before_action :require_no_authentication, only: [:new, :create] layout 'basic' include Abroaders::Controller::Onboarding include Auth::Controllers::SignInOut def new run Registration::New render cell(Registration::Cell::New, @model, form: @form) end def create run Registration::Create do flash[:notice] = I18n.t('devise.registrations.signed_up') sign_in(:account, @model) return redirect_to onboarding_survey_path end @form.clean_up_passwords render cell(Registration::Cell::New, @model, form: @form) end protected # Helper for use in before_actions where no authentication is required. # # Example: # before_action :require_no_authentication, only: :new def require_no_authentication if warden.authenticated?(:account) && warden.user(:account) flash[:alert] = I18n.t("devise.failure.already_authenticated") redirect_to root_path end end end
class Language < ActiveRecord::Base attr_accessible :description,:spanishname, :language_sid validates :description, :language_sid, :presence => true, :uniqueness => true end
class Question < ApplicationRecord validates :title, presence: true, length: { minimum: 20 } validates :description, presence: true, length: { minimum: 50 }, if: 'markdown.blank?' validates :markdown, presence: true, length: { minimum: 50 }, if: 'description.blank?' validates :user_id, presence: true has_many :answers end
class CreateRules < ActiveRecord::Migration def change create_table :rules do |t| t.integer :user_id t.integer :pattern_id t.string :rule_type t.string :year t.string :month t.string :day t.string :hour t.string :variation t.decimal :value, :precision => 30, :scale => 10 t.timestamps end change_table :rules do |t| t.index :user_id t.index :pattern_id end end end
class Post include DataMapper::Resource property :id, Serial # An auto-increment integer key property :user_id, Integer # An integer key property :title, String # A varchar type string, for short strings property :body, Text # A text block, for longer string data. property :created_at, DateTime # A DateTime, for any date you might like. property :updated_at, DateTime # A DateTime, for any date you might like. # relationship with user model belongs_to :user def created_at=date super Date.strptime(date, '%m/%d/%Y') end def updated_at=date super Date.strptime(date, '%m/%d/%Y') end # DataMapper.auto_upgrade! # DataMapper.finalize end
class ServiceAreaCode < ApplicationRecord has_many :ticket_service_area_codes, dependent: :destroy has_many :tickets, through: :ticket_service_area_codes end
class CreateBlocks < ActiveRecord::Migration[5.0] def change create_table :blocks do |t| t.string :name, :limit => 150, :null => false t.integer :weight, :null => false, :default => 0 t.references :block_subgroup, foreign_key: true, :null => false # auto / conditional t.integer :include_type, :null => false, :default => 0 # what is this??? -> cont type have fields #t.integer :content_type, :null => false, :default => 0 #nullable ref to field if! block block is conditional ( BOOLEAN field ) t.references :block_field, foreign_key: true, null: true t.timestamps end end end
# Imagine a robot sitting on the upper left corner of a grid with r rows and c # columns. The robot can only move in two directions, right and down, but certain # cells are "off limits" such that the robot cannot step on them. Design an # algorithm to find a path for the robot from the top left to the bottom right. # # Runtime: O(2^r+c) or O(rc) w/ caching class RobotGrid attr_reader :rows, :columns, :off_limits def initialize(rows: rows, columns: columns, off_limits: []) @rows = rows @columns = columns @off_limits = off_limits end def go row = rows-1 col = columns-1 if get_path(row, col, path = [], cache = []) return draw(path) end return nil end private def get_path(row, col, path, cache) if row < 0 || col < 0 || off_limits?(row, col) return false end if already_visited?(cache, row, col) return false end found = row == 0 && col == 0 if found || get_path(row-1, col, path, cache) || get_path(row, col-1, path, cache) path << { row: row, col: col } return true end cache << { row: row, col: col } return false end def already_visited?(cache, row, col) cache.find { |point| point[:row] == row && point[:col] == col } end def off_limits?(row, col) off_limits.each do |cell| if cell[0] == row && cell[1] == col return true end end return false end def draw(path) (0...rows).each_with_index do |_, row| (0...columns).each_with_index do |_, col| if path.find { |point| point[:row] == row && point[:col] == col } print "* " elsif off_limits?(row, col) print "x " else print " " end end print "\n" end end end RobotGrid.new( rows: 15, columns: 15, off_limits: [[0, 1], [2, 2], [3, 2], [2, 4]], ).go
cask "mounty-legacy" do version "1.9" sha256 :no_check url "https://mounty.app/releases/Mounty-1.9.dmg" name "Mounty for NTFS" desc "Re-mounts write-protected NTFS volumes" homepage "https://mounty.app/" app "Mounty.app" end
require 'elm/compiler/exceptions' require 'elm/compiler/io' require 'open3' require 'tempfile' module Elm class Compiler class << self def compile(elm_files, output_path: nil, elm_make_path: "elm-make") raise ExecutableNotFound unless elm_executable_exists?(elm_make_path) if output_path elm_make(elm_make_path, elm_files, output_path) else compile_to_string(elm_make_path, elm_files) end end # private def elm_executable_exists?(elm_make_path) Open3.popen2(elm_make_path){}.nil? rescue Errno::ENOENT, Errno::EACCES false end def compile_to_string(elm_make_path, elm_files) Tempfile.open(['elm', '.js']) do |tempfile| elm_make(elm_make_path, elm_files, tempfile.path) return File.read tempfile.path end end def elm_make(elm_make_path, elm_files, output_path) output_path_abs = File.absolute_path(output_path) Elm::IO.with_project_copy(*elm_files) do |tmp_elm_files| Open3.popen3({"LANG" => "en_US.UTF8" }, elm_make_path, *tmp_elm_files, '--yes', '--output', output_path_abs) do |_stdin, _stdout, stderr, wait_thr| fail CompileError, stderr.gets(nil) if wait_thr.value.exitstatus != 0 end end end end end end
module Queries class ShowUserPortfolio < Queries::BaseQuery type Types::UserPortfolio, null: true description "Get the user portfolio" def resolve return unless current_user current_user.user_portfolio end end end
# Gitlab::Git::Commit is a wrapper around native Grit::Repository object # We dont want to use grit objects inside app/ # It helps us easily migrate to rugged in future require_relative 'encoding_helper' require_relative 'ref' require 'open3' module Gitlab module Git class Repository include Gitlab::Git::Popen class NoRepository < StandardError; end PARKING_BRANCH = "__parking_branch" # Default branch in the repository attr_accessor :root_ref # Full path to repo attr_reader :path # Directory name of repo attr_reader :name # Grit repo object attr_reader :grit # Rugged repo object attr_reader :rugged def initialize(path) @path = path @name = path.split("/").last @root_ref = discover_default_branch end def self.clone!(url, path, key) authorize_hostname(url) execute_repo_command(key) do |private_key_file| `ssh-agent bash -c "ssh-add #{private_key_file.path} && git clone #{url} #{path}"` end Repository.new(path) end def pull!(key) self.class.execute_repo_command(key) do |private_key_file| git_dir = File.join(path, ".git") cmd = "ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} reset --hard origin/#{current_branch} && git --git-dir=#{git_dir} --work-tree=#{path} pull origin #{current_branch}" `ssh-agent bash -c "#{cmd}"` end end def commit!(params = {}) if params.include?(:current_user) && params.include?(:project) && params.include?(:ref) && params.include?(:path) && params.include?(:content) && params.include?(:commit_message) && params.include?(:key) begin prepare_repo!(params[:current_user], params[:key]) # create target branch in satellite at the corresponding commit from bare repo grit.git.checkout({raise: true, timeout: true, b: true}, params[:ref], "origin/#{params[:ref]}") # update the file in the satellite's working dir file_path_in_repo = File.join(grit.working_dir, params[:path]) # Prevent relative links unless safe_path?(file_path_in_repo) Gitlab::GitLogger.error("FileAction: Relative path not allowed") return false end self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") stdin, stdout, stderr = Open3.popen3("ssh-agent bash -c \"ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} push --dry-run origin #{params[:ref]}\"") raise "Could not commit the changes." unless(stderr.read.include?("Everything up-to-date")) end # Write file write_file(file_path_in_repo, params[:content], params[:encoding]) grit.add(file_path_in_repo) # commit the changes # will raise CommandFailed when commit fails grit.git.commit(raise: true, timeout: true, a: true, m: params[:commit_message]) # push commit back to bare repo # will raise CommandFailed when push fails self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") `ssh-agent bash -c "ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} push origin #{params[:ref]}"` end true rescue Grit::Git::CommandFailed => ex self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") `git --git-dir=#{git_dir} --work-tree=#{path} checkout #{params[:ref]} && git --git-dir=#{git_dir} --work-tree=#{path} reset --hard` end Gitlab::GitLogger.error(ex.message) false rescue => e self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") `git --git-dir=#{git_dir} --work-tree=#{path} checkout #{params[:ref]} && git --git-dir=#{git_dir} --work-tree=#{path} reset --hard` end Gitlab::GitLogger.error(e.message) false end else false end end def delete!(params = {}) if params.include?(:current_user) && params.include?(:project) && params.include?(:ref) && params.include?(:path) && params.include?(:commit_message) && params.include?(:key) begin prepare_repo!(params[:current_user], params[:key]) # create target branch in satellite at the corresponding commit from bare repo grit.git.checkout({raise: true, timeout: true, b: true}, params[:ref], "origin/#{params[:ref]}") # update the file in the satellite's working dir file_path_in_repo = File.join(grit.working_dir, params[:path]) # Prevent relative links unless safe_path?(file_path_in_repo) Gitlab::GitLogger.error("FileAction: Relative path not allowed") return false end self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") stdin, stdout, stderr = Open3.popen3("ssh-agent bash -c \"ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} push --dry-run origin #{params[:ref]}\"") raise "Could not commit the changes." unless(stderr.read.include?("Everything up-to-date")) end # Write file File.delete(file_path_in_repo) grit.remove(file_path_in_repo) # commit the changes # will raise CommandFailed when commit fails grit.git.commit(raise: true, timeout: true, a: true, m: params[:commit_message]) # push commit back to bare repo # will raise CommandFailed when push fails self.class.execute_repo_command(params[:key]) do |private_key_file| git_dir = File.join(path, ".git") `ssh-agent bash -c "ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} push origin #{params[:ref]}"` end true rescue Grit::Git::CommandFailed => ex Gitlab::GitLogger.error(ex.message) false rescue => e Gitlab::GitLogger.error(e.message) false end else false end end def current_branch git_dir = File.join(path, ".git") b = `git --git-dir=#{git_dir} --work-tree=#{path} rev-parse --abbrev-ref HEAD` if(b.empty?) "master" else b.gsub("\n", "") end end def grit @grit ||= Grit::Repo.new(path) rescue Grit::NoSuchPathError raise NoRepository.new('no repository for such path') end # Alias to old method for compatibility def raw grit end def rugged @rugged ||= Rugged::Repository.new(path) rescue Rugged::RepositoryError, Rugged::OSError raise NoRepository.new('no repository for such path') end # Returns an Array of branch names # sorted by name ASC def branch_names branches.map(&:name) end # Returns an Array of Branches def branches rugged.refs.select do |ref| ref.name =~ /\Arefs\/remotes\/origin/ end.map do |rugged_ref| Branch.new(rugged_ref.name, rugged_ref.target) end.sort_by(&:name) end # Returns an Array of tag names def tag_names tags.map(&:name) end # Returns an Array of Tags def tags rugged.refs.select do |ref| ref.name =~ /\Arefs\/tags/ end.map do |rugged_ref| Tag.new(rugged_ref.name, rugged_ref.target) end.sort_by(&:name) end # Returns an Array of branch and tag names def ref_names branch_names + tag_names end # Deprecated. Will be removed in 5.2 def heads @heads ||= grit.heads.sort_by(&:name) end def has_commits? !empty? end def empty? rugged.empty? end def repo_exists? !!rugged end # Discovers the default branch based on the repository's available branches # # - If no branches are present, returns nil # - If one branch is present, returns its name # - If two or more branches are present, returns current HEAD or master or first branch def discover_default_branch if branch_names.length == 0 nil elsif branch_names.length == 1 branch_names.first elsif branch_names.include?("master") "master" elsif rugged.head Ref.extract_branch_name(rugged.head.name) elsif branch_names.first end end # Archive Project to .tar.gz # # Already packed repo archives stored at # app_root/tmp/repositories/project_name/project_name-commit-id.tag.gz # def archive_repo(ref, storage_path, format = "tar.gz") ref = ref || self.root_ref commit = Gitlab::Git::Commit.find(self, ref) return nil unless commit extension = nil git_archive_format = nil pipe_cmd = nil case format when "tar.bz2", "tbz", "tbz2", "tb2", "bz2" extension = ".tar.bz2" pipe_cmd = "bzip" when "tar" extension = ".tar" pipe_cmd = "cat" when "zip" extension = ".zip" git_archive_format = "zip" pipe_cmd = "cat" else # everything else should fall back to tar.gz extension = ".tar.gz" git_archive_format = nil pipe_cmd = "gzip" end # Build file path file_name = self.name.gsub("\.git", "") + "-" + commit.id.to_s + extension file_path = File.join(storage_path, self.name, file_name) # Put files into a directory before archiving prefix = File.basename(self.name) + "/" # Create file if not exists unless File.exists?(file_path) FileUtils.mkdir_p File.dirname(file_path) file = self.grit.archive_to_file(ref, prefix, file_path, git_archive_format, pipe_cmd) end file_path end # Return repo size in megabytes def size size = popen('du -s', path).first.strip.to_i (size.to_f / 1024).round(2) end def search_files(query, ref = nil) if ref.nil? || ref == "" ref = root_ref end greps = grit.grep(query, 3, ref) greps.map do |grep| Gitlab::Git::BlobSnippet.new(ref, grep.content, grep.startline, grep.filename) end end # Delegate log to Grit method # # Usage. # repo.log( # ref: 'master', # path: 'app/models', # limit: 10, # offset: 5, # ) # def log(options) default_options = { limit: 10, offset: 0, path: nil, ref: root_ref, follow: false } options = default_options.merge(options) commits = grit.log( options[:ref] || root_ref, options[:path], max_count: options[:limit].to_i, skip: options[:offset].to_i, follow: options[:follow] ) if commits.empty? if options[:ref].is_a?(String) ref = ref_list.find { |ref| ref[:id] =~ /.*\/#{options[:ref]}/ }[:md5] else ref = options[:ref].oid end commits = grit.commits(ref, options[:limit].to_i, options[:offset].to_i) end commits end # Delegate commits_between to Grit method # def commits_between(from, to) grit.commits_between(from, to) end def merge_base_commit(from, to) grit.git.native(:merge_base, {}, [to, from]).strip end def diff(from, to, *paths) grit.diff(from, to, *paths) end # Returns commits collection # # Ex. # repo.find_commits( # ref: 'master', # max_count: 10, # skip: 5, # order: :date # ) # # +options+ is a Hash of optional arguments to git # :ref is the ref from which to begin (SHA1 or name) # :contains is the commit contained by the refs from which to begin (SHA1 or name) # :max_count is the maximum number of commits to fetch # :skip is the number of commits to skip # :order is the commits order and allowed value is :date(default) or :topo # def find_commits(options = {}) actual_options = options.dup allowed_options = [:ref, :max_count, :skip, :contains, :order] actual_options.keep_if do |key, value| allowed_options.include?(key) end default_options = {pretty: 'raw', order: :date} actual_options = default_options.merge(actual_options) order = actual_options.delete(:order) case order when :date actual_options[:date_order] = true when :topo actual_options[:topo_order] = true end ref = actual_options.delete(:ref) containing_commit = actual_options.delete(:contains) args = [] if ref args.push(ref) elsif containing_commit args.push(*branch_names_contains(containing_commit)) else actual_options[:all] = true end output = grit.git.native(:rev_list, actual_options, *args) Grit::Commit.list_from_string(grit, output).map do |commit| Gitlab::Git::Commit.decorate(commit) end rescue Grit::GitRuby::Repository::NoSuchShaFound [] end # Returns branch names collection that contains the special commit(SHA1 or name) # # Ex. # repo.branch_names_contains('master') # def branch_names_contains(commit) output = grit.git.native(:branch, {contains: true}, commit) # Fix encoding issue output = EncodingHelper::encode!(output) # The output is expected as follow # fix-aaa # fix-bbb # * master output.scan(/[^* \n]+/) end # Get refs hash which key is SHA1 # and value is ref object(Grit::Head or Grit::Remote or Grit::Tag) def refs_hash # Initialize only when first call if @refs_hash.nil? @refs_hash = Hash.new { |h, k| h[k] = [] } grit.refs.each do |r| @refs_hash[r.commit.id] << r end end @refs_hash end # Lookup for rugged object by oid def lookup(oid) commit = rugged.lookup(oid) commit = commit.target if commit.is_a?(Rugged::Tag::Annotation) commit end # Return hash with submodules info for this repository # # Ex. # { # "rack" => { # "id" => "c67be4624545b4263184c4a0e8f887efd0a66320", # "path" => "rack", # "url" => "git://github.com/chneukirchen/rack.git" # }, # "encoding" => { # "id" => .... # } # } # def submodules(ref) Grit::Submodule.config(grit, ref) end private def ref_list grit.refs_list.map do |ref| { id: ref[0], md5: ref[1], type: ref[2] } end end def self.authorize_hostname(url) begin u = URI(url) hostname = u.host rescue URI::InvalidURIError m = url.match(/.*?@(.*)?:/) hostname = m[1] end unless hostname.nil? || hostname.empty? Ssh.add_host(hostname) else raise ArgumentError.new("Could not find hostname in url '#{url}'") end end def self.execute_repo_command(key) private_key_file = create_private_key_file(key) yield private_key_file private_key_file.close private_key_file.unlink end def self.create_private_key_file(key) file = Tempfile.new("#{key.user_id}.private_key") file.write(key.private_key) file.rewind file end def write_file(abs_file_path, content, file_encoding = 'text') dir_path = File.dirname(abs_file_path) FileUtils.mkdir_p(dir_path) if file_encoding == 'base64' File.open(abs_file_path, 'wb') { |f| f.write(Base64.decode64(content)) } else File.open(abs_file_path, 'w') { |f| f.write(content) } end end def safe_path?(path) File.absolute_path(path) == path end def prepare_repo!(user, key) clear_and_update!(key) grit.config['user.name'] = user.name grit.config['user.email'] = user.email end def clear_and_update!(key) clear_working_dir! delete_heads! remove_remotes! update_from_source!(key) end # Clear the working directory def clear_working_dir! grit.git.reset(hard: true) end # Deletes all branches except the parking branch # # This ensures we have no name clashes or issues updating branches def delete_heads! heads = grit.heads.map(&:name) # update or create the parking branch if heads.include? PARKING_BRANCH grit.git.checkout({}, PARKING_BRANCH) else grit.git.checkout(default_options({b: true}), PARKING_BRANCH) end # remove the parking branch from the list of heads ... heads.delete(PARKING_BRANCH) # ... and delete all others heads.each { |head| grit.git.branch(default_options({D: true}), head) } end # Deletes all remotes except origin # # This ensures we have no remote name clashes or issues updating branches def remove_remotes! remotes = grit.git.remote.split(' ') remotes.delete('origin') remotes.each { |name| grit.git.remote(default_options,'rm', name)} end # Updates the satellite from bare repo def update_from_source!(key) self.class.execute_repo_command(key) do |private_key_file| git_dir = File.join(path, ".git") `ssh-agent bash -c "ssh-add #{private_key_file.path} && git --git-dir=#{git_dir} --work-tree=#{path} fetch origin"` end end def default_options(options = {}) {raise: true, timeout: true}.merge(options) end end end end
json.credit_item do json.extract! @credit_item, :id, :stripe_charge_id, :stripe_receipt_url, :memo, :quantity, :user_id end
FactoryBot.define do factory :buy do point { Faker::Number.within(range: 1..100) } association :user association :item end end
class WorkoutsController < ApplicationController get '/log' do not_logged_in? current_user all_workouts = Workout.all.find_all {|workout| workout.user_id == session[:user_id]} @workouts = all_workouts.sort_by { |workout| workout.date}.reverse erb :'workouts/logs' end get '/log/new' do current_user if logged_in? erb :'workouts/new' else redirect to "/login" end end get '/log/:id' do current_user find_log if @workout && @workout.user == current_user erb :'workouts/show' else redirect to "/users/#{current_user.slug}" end end get '/log/:id/edit' do current_user if logged_in? find_log @exercises = @workout.exercises erb :'workouts/edit' else redirect to "/users/#{current_user.slug}" end end post '/log' do if logged_in? if all_integer? @workout = Workout.create(:date => params[:workout][:date], :user_id => session["user_id"]) workouts_exercises if !@exercises.empty? && !@workout.date.empty? create_exercise redirect to "/log/#{@workout.id}" else flash[:message] = "Date cannot be empty and at least one exercise must be filled out." redirect to "/log/new" end else flash[:message] = "Weight field only accepts whole numbers." redirect to "/log/new" end else redirect to "/login" end end patch '/log/:id' do if logged_in? find_log if all_integer? if @workout && @workout.user == current_user unless params[:workout][:date].empty? @workout.update(:date => params[:workout][:date]) end names = params[:workout][:exercise][:exists][:name] weights = params[:workout][:exercise][:exists][:weight] exercises = @workout.exercises.zip(names, weights) exercises.each do |exercise| if exercise.include?("") exercise[0].destroy else exercise[0].update(:name => exercise[1], :weight => exercise[2]) end end unless exercise_names.empty? || exercise_weights.empty? workouts_exercises create_exercise end redirect to "/log/#{@workout.id}" else redirect to "/users/#{current_user.slug}" end else flash[:message] = "Weight field only accepts whole numbers." redirect to "/log/#{@workout.id}/edit" end else redirect to '/login' end end delete '/log/:id' do if logged_in? find_log if @workout && @workout.user == current_user @workout.destroy end redirect to '/log' else redirect to '/login' end end private def find_log @workout = Workout.find_by(:id => params[:id]) end def exercise_names params[:workout][:exercise][:name] end def exercise_weights params[:workout][:exercise][:weight] end def all_integer? weights = exercise_weights.reject{|weight| weight == ""} weights.all? {|w| !!(w=~/\A[-+]?[0-9]+\z/) == true} end def workouts_exercises @exercises = exercise_names.zip(exercise_weights).reject{ |exercise| exercise.include?("")} end def create_exercise @exercises.each do |exercise| @workout.exercises << Exercise.create(:workout_id => @workout.id, :name => exercise[0], :weight => exercise[1]) end end def not_logged_in? unless logged_in? redirect to "/login" end end end
class Organizer < ApplicationRecord belongs_to :microcosm belongs_to :user end
require 'roby/test/self' require 'roby/test/aruba_minitest' module Roby module CLI describe 'roby gen' do include Test::ArubaMinitest def validate_app_valid(*args) roby_run = run_roby ["run", *args].join(" ") run_roby_and_stop "quit --retry" roby_run.stop assert_command_finished_successfully roby_run end describe "creation of a new app in the current directory" do it "generates a new valid app" do run_roby_and_stop "gen app" validate_app_valid end it "generates a default robot configuration" do run_roby_and_stop "gen app" assert file?('config/robots/default.rb') end it "is accessible through the deprecated 'init' subcommand" do run_roby_and_stop "init" validate_app_valid end end describe "within an existing app" do before do run_roby_and_stop "gen app" end describe "gen robot" do it "generates a new valid robot configuration" do run_roby_and_stop "gen robot test" validate_app_valid "-rtest" end end end end end end
require "formula" class Htop < Formula homepage "http://hisham.hm/htop/" url "http://hisham.hm/htop/releases/1.0.3/htop-1.0.3.tar.gz" sha1 "261492274ff4e741e72db1ae904af5766fc14ef4" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/htop --version" end end
# frozen_string_literal: true module PaymentGateways class OgoneCrypt < PaymentGatewayCrypt DEFAULT_EXPIRATION_DATE = Date.new(2099, 12, 1) DEFAULT_EXPIRATION_DATE_PARAM = DEFAULT_EXPIRATION_DATE.strftime("%m%y") # "1299" attr_reader :url attr_accessor :fields, :field_names, :payment_gateway_options def initialize(user) super @payment_gateway_options = @provider.payment_gateway_options @url = "https://secure.ogone.com/ncol/#{test? ? 'test' : 'prod'}/orderstandard.asp" end def fill_fields(return_url) @fields = {} @fields['PSPID'] = payment_gateway_options[:login] @fields['orderID'] = "#{user.first_name}_#{Time.now.to_i}" @fields['amount'] = '1' @fields['alias'] = buyer_reference @fields['aliasusage'] = "Your data will be used for future chargements" @fields['currency'] = provider.currency @fields['language'] = 'en_US' @fields['operation'] = 'RES' @fields['accepturl'] = return_url @fields['cancelurl'] = return_url @fields['declineurl'] = return_url @fields['exceptionurl'] = return_url @fields['SHASign'] = SHASign(@fields, payment_gateway_options[:signature]) end def success?(params) parameters_to_sign = params.dup %w[action controller SHASIGN].each {|excluded| parameters_to_sign.delete excluded} params.upcase_keys['STATUS'] == '5' && SHASign(parameters_to_sign, payment_gateway_options[:signature_out]) == params["SHASIGN"] end def upcase_keys(hash) upcase_keys!(hash.dup) end def upcase_keys!(params) params.keys.each do |key| self[(begin key.upcase rescue StandardError key end) || key] = params.delete(key) end self end def update_user(params) expiration_date = params.upcase_keys['ED'] expiration_date = DEFAULT_EXPIRATION_DATE_PARAM if expiration_date.blank? account.credit_card_expires_on_month = expiration_date[0..1] account.credit_card_expires_on_year = "20#{expiration_date[2..3]}" account.credit_card_partial_number = params.upcase_keys['CARDNO'][-4..-1] account.credit_card_auth_code = buyer_reference account.save! end def SHASign(fields, signature) f = fields.delete_if {|k, v| v.blank? } capitalized_hash = {} fields.each do |k, v| capitalized_hash[k.upcase]=v end datastring = capitalized_hash.keys.sort.collect do |key| "#{key}=#{capitalized_hash[key]}" end.join(signature) Digest::SHA1.hexdigest("#{datastring}#{signature}").upcase end end end
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録できるとき' do it 'nickname,email,password,password_confirmation,姓,名,姓カナ,名カナ,生年月日が存在すれば登録できる' do expect(@user).to be_valid end it 'emailに@が含まれていると登録できる' do @user.email = 'aaaa@aaaa' expect(@user).to be_valid end it 'passwordが6文字以上で半角英数字のとき登録できる' do @user.password = 'abc123' @user.password_confirmation = 'abc123' expect(@user).to be_valid end it '姓が全角(漢字・ひらがな・カタカナ)であれば登録できる' do @user.last_name = '佐藤' expect(@user).to be_valid end it '名が全角(漢字・ひらがな・カタカナ)であれば登録できる' do @user.first_name = 'ユウキ' expect(@user).to be_valid end it 'last_name_katakanaは全角(カタカナ)であれば登録できる' do @user.last_name_katakana = 'サトウ' expect(@user).to be_valid end it 'first_name_katakanaは全角(カタカナ)であれば登録できる' do @user.first_name_katakana = 'ユウキ' expect(@user).to be_valid end end context '新規登録できないとき' do it 'nicknameが空では登録できない' do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include "Nickname can't be blank" end it 'emailが空では登録できない' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include "Email can't be blank" end it 'emailは@が含まれていないと登録できない' do @user.email = 'aaaaaaaa' @user.valid? expect(@user.errors.full_messages).to include "Email is invalid" end it '同じemailは登録できない' do @user.save another = FactoryBot.build(:user) another.email = @user.email another.valid? expect(another.errors.full_messages).to include('Email has already been taken') end it 'passwordが空では登録できない' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include "Password can't be blank" end it 'passwordが半角数字のみの場合は登録できない' do @user.password = 'aaaaaaa' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password", "Password is invalid") end it 'passwordが半角英字のみの場合は登録できない' do @user.password = '1111111' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password", "Password is invalid") end it 'passwordが全角の場合は登録できない' do @user.password = 'ABC123' @user.password_confirmation = 'ABC123' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password", "Password confirmation is invalid", "Password is invalid") end it '姓が空では登録できない' do @user.last_name = '' @user.valid? expect(@user.errors.full_messages).to include "Last name can't be blank" end it '姓は全角(漢字・ひらがな・カタカナ)でなければ登録できない' do @user.last_name = 'aaaaAAAA' @user.valid? expect(@user.errors.full_messages).to include "Last name 全角文字を使用してください" end it '名が空では登録できない' do @user.first_name = '' @user.valid? expect(@user.errors.full_messages).to include "First name can't be blank" end it 'first_nameは全角(漢字・ひらがな・カタカナ)でなければ登録できない' do @user.first_name = 'aaaaAAAA' @user.valid? expect(@user.errors.full_messages).to include "First name 全角文字を使用してください" end it '姓(カナ)が空では登録できない' do @user.last_name_katakana = '' @user.valid? expect(@user.errors.full_messages).to include "Last name katakana can't be blank" end it 'last_name_katakanaは全角(カタカナ)でなければ登録できない' do @user.last_name_katakana = 'あfdgs@' @user.valid? expect(@user.errors.full_messages).to include "Last name katakana 全角カタカナのみで入力して下さい" end it '名(カナ)が空では登録できない' do @user.first_name_katakana = '' @user.valid? expect(@user.errors.full_messages).to include "First name katakana can't be blank" end it 'first_name_katakanaは全角(カタカナ)でなければ登録できない' do @user.first_name_katakana = 'あfdgs@' @user.valid? expect(@user.errors.full_messages).to include "First name katakana 全角カタカナのみで入力して下さい" end it '生年月日が空では登録できない' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include "Birthday can't be blank" end end end end
class Book attr_accessor :title def title _title = [] _exceptions = ['and', 'the', 'a', 'an', 'in', 'of'] @title.split(' ').map.with_index { |word, idx| if idx == 0 or !_exceptions.include?(word) _title << word.capitalize else _title << word end } _title.join(' ') end end
module SlackbotPingity module Commands class Ping < SlackRubyBot::Commands::Base command 'ping' do |client, data, match| request = self.process_input(match['expression']) client.say( channel: data.channel, text: "I'm attempting to ping \"#{request}\". Just a moment, please..." ) report = Pingity::Report.new( request, eager: true ) status = report.status client.say( channel: data.channel, text: "... The Pingity status for \"#{request}\" is \"#{status}\"." ) end def self.process_input(input) input = input.split[0].downcase case input when /\|(?<uri>.+)\>$/ # When slack recognizes a potential URI, it pre-formats it before the # data can be extracted with match['expression'], resulting in a # characteristic string, "http://<<guessed uri>|<human-readable uri>>". # This approach identifies strings that have characters between | and > # and extracts them. $LAST_MATCH_INFO['uri'][0..-1] else input end end end end end
class KeepController < ApplicationController def index render component: 'Keep' end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def index @tracked_trainees = Trainee.all.where(tracking_status: 1) @submissions = Submission.all end end
require 'nokogiri' require 'nokogiri-styles' class SVGMapper ORIGINAL_MAP = 'assets/us_map.svg' XPATH_FOR_COUNTY = "//svg:path[@inkscape:label='%{county}']" XPATH_NAMESPACES = {'svg': "http://www.w3.org/2000/svg", 'inkscape': "http://www.inkscape.org/namespaces/inkscape"} def initialize(output_file_name, opts = {}) @output_file_name = output_file_name parser = opts[:parser] || Nokogiri::XML @doc = parser.parse(File.read(ORIGINAL_MAP)).dup end def color_county!(county, color) node = @doc.at_xpath(XPATH_FOR_COUNTY % {county: county}, XPATH_NAMESPACES) unless node.nil? style = node.styles style['fill'] = color node.styles = style else puts "ERROR! Cannot find county: #{county}" end end def close File.write(@output_file_name, @doc.to_xml) @output_file_name end end
class Droid < ActiveRecord::Base alias_method :orig_as_json, :as_json def as_json(options = {}) base = orig_as_json if options[:version] == 2 base = {'name' => self.name} end base end end
class Article < ApplicationRecord mount_uploader :cover, CoverUploader validates :title, presence: true, length: { minimum: 5 } has_many :comments, dependent: :destroy belongs_to :user has_many :likes has_many :users, through: :likes scope :published, -> { where(published: true) } scope :most_commented, -> { order(comments_count: :desc).first } def tags=(tag_list) tag_list = sanitize_tags(tag_list) if tag_list.is_a?(String) super(tag_list) end def css_class if published? 'normal' else 'unpublished' end end private def sanitize_tags(text) text.downcase.split.uniq end end
# geocoder gem configuration file Geocoder.configure do |config| config.lookup = :yahoo end
# frozen_string_literal: true # Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru> require_relative 'base_client' module Valera class MonolithosClient < BaseClient URL = 'https://price.monolithos.pro/v1/setzer/price/list' # [{"first_currency"=>"ETH", "second_currency"=>"RUB", "price"=>"226330.4259100000", "date"=>1632213940.111}, # {"first_currency"=>"ETH", "second_currency"=>"USD", "price"=>"3085.7596841298", "date"=>1632213944.215}, # {"first_currency"=>"ETH", "second_currency"=>"MDT", "price"=>"1697.3498621156", "date"=>1632213944.273}, # {"first_currency"=>"MDT", "second_currency"=>"MCR", "price"=>"133.3434143200", "date"=>1632213944.378}, # {"first_currency"=>"USD", "second_currency"=>"MDT", "price"=>"0.5500589922", "date"=>1632213944.491}, # {"first_currency"=>"USD", "second_currency"=>"RUB", "price"=>"73.3315000000", "date"=>1632213944.562}, # {"first_currency"=>"BTC", "second_currency"=>"MDT", "price"=>"23875.9027171788", "date"=>1632213874.489}, # {"first_currency"=>"BTC", "second_currency"=>"RUB", "price"=>"3179876.7677600000", "date"=>1632213876.008}, # {"first_currency"=>"MDT", "second_currency"=>"UAH", "price"=>"47.5744160173", "date"=>1632213876.534}, # {"first_currency"=>"MDT", "second_currency"=>"USD", "price"=>"1.8172406254", "date"=>1632213876.632}, # {"first_currency"=>"UAH", "second_currency"=>"RUB", "price"=>"2.8016964285", "date"=>1632213876.921}, # {"first_currency"=>"BTC", "second_currency"=>"USD", "price"=>"43375.0000000000", "date"=>1632213876.955}, # {"first_currency"=>"USD", "second_currency"=>"UAH", "price"=>"26.5762061902", "date"=>1632213877.315}], def fetch JSON.parse(URI.parse(URL).open.read).fetch('result') end end end
ActionController::Routing::Routes.draw do |map| map.resources :statuses, :collection => { :friends_timeline => :get, :user_timeline => :get, :public_timeline => :get, :replies => :get, :friends => :get, :followers => :get } map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resources :users, :has_many => [:statuses] map.resource :session # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' map.root :controller => "statuses", :action => "friends_timeline" end
require 'spec_helper' require 'harvest/domain' # Because the aggregate roots store EventTypes in Harvest::Domain::Events require 'harvest/event_handlers/read_models/fishing_grounds_available_to_join' module Harvest module EventHandlers module ReadModels describe FishingGroundsAvailableToJoin do let(:database) { double( "ReadModelDatabase", save: nil, delete: nil, update: nil, records: [ :record_1, :record_2 ], count: 3 ) } let(:event_bus) { Realm::Messaging::Bus::SimpleMessageBus.new } subject(:view) { FishingGroundsAvailableToJoin.new(database) } before(:each) do event_bus.register(:unhandled_event, Realm::Messaging::Bus::UnhandledMessageSentinel.new) end describe "#handle_fishing_ground_opened" do before(:each) do event_bus.register(:fishing_ground_opened, view) end it "saves the view info" do event_bus.publish( Domain::Events.build( :fishing_ground_opened, uuid: :uuid_1, name: "Fishing ground 1", starting_year: 2012, lifetime: 10, starting_population: 40, carrying_capacity: 50, order_fulfilment: :sequential ) ) expect(database).to have_received(:save).with( uuid: :uuid_1, name: "Fishing ground 1", starting_year: 2012, current_year: 2012 ) end end describe "#handle_year_advanced" do before(:each) do event_bus.register(:year_advanced, view) end before(:each) do database.stub( records: [ { uuid: :uuid_1, name: "Fishing ground 1", starting_year: 2012, current_year: 2012 } ] ) end it "updates the view info" do event_bus.publish( Domain::Events.build(:year_advanced, years_passed: 1, new_year: 2013, uuid: :uuid_1) ) # Hack to wait for messages to process view.to_s expect(database).to have_received(:update).with( [ :uuid ], uuid: :uuid_1, name: "Fishing ground 1", starting_year: 2012, current_year: 2013 ) end end describe "#handle_fishing_ground_closed" do before(:each) do event_bus.register(:fishing_ground_closed, view) end it "saves the view info" do event_bus.publish( Domain::Events.build( :fishing_ground_closed, uuid: :uuid_1, version: 1, timestamp: Time.now ) ) # Hack to wait for messages to process view.to_s expect(database).to have_received(:delete).with(uuid: :uuid_1) end end describe "#record_for" do before(:each) do database.stub( records: [ { uuid: :uuid_1, data: "data a", extra: "extra data" }, { uuid: :uuid_1, data: "data b", extra: "extra data" }, { uuid: :uuid_2, data: "data b", extra: "extra data" } ] ) end it "returns the record for the query" do record = view.record_for(uuid: :uuid_1, data: "data b") expect(record).to be == { uuid: :uuid_1, data: "data b", extra: "extra data" } end end describe "#count" do it "is the number of records in the database" do expect(view.count).to be == 3 end end describe "#records" do it "is the database records" do expect(view.records).to be == [ :record_1, :record_2 ] end end end end end end
module ApplicationHelper def today Date.today.strftime "%d/%m/%Y" end def human_date(date) date.strftime '%d/%m/%y' end def label_and_content(label, content, options = nil) opt = options.to_h col_md = BootstrapColDecorator.new(opt.fetch :col_md, 0) col_offset = BootstrapColDecorator.new(opt.fetch :col_offset, 0) padding_space = BootstrapColDecorator.padding_class(col_md, col_offset) content_tag :div, class: 'row' do concat(content_tag(:div, class: "#{col_offset.to_offset_class} #{col_md.to_class}") do concat(content_tag :strong, "#{label}:") concat(content_tag :em, content, class: 'pull-right') end) concat(content_tag :div, nil, class: padding_space) unless padding_space.blank? end end end
require 'discordrb' require 'colorize' require 'websocket' module EasyDiscordrb class NameBot attr_accessor :var, :prefixe, :tok def initialize(variable, token, pref) @var = variable @tok = token @prefixe = pref end def Namebot @var = Discordrb::Commands::CommandBot.new token: tok, prefix: prefixe end def BotStart var.run end end class Ready attr_accessor :variable def initialize(var) @variable = var end def ready puts "+=================[ My bot ]==================+".blue puts "Bot is ready".green puts "This bot has been dev with EasyDiscordRb".blue puts "==============================================+".blue end end class Commandss def help(var, name_command, content) var.command name_command do |commands| commands.respond(content) end end def pmMention(var, content) var.mention do |pm_mention| pm_mention.user.pm(content) end end end end
require 'spec_helper' describe DealService do it 'generates a request uri per centre' do expect(DealService.request_uri(centre: 'burwood').to_s).to eq "http://deal-service.#{Rails.env}.dbg.westfield.com/api/deal/master/deals.json?centre=burwood" end context "Build" do describe "When we've only asked for one deal" do it "return deal objects" do mock_response = double(:body => [{"title" => "Deal 1"},{"title" => "Deal 2"}]) deals = DealService.build(mock_response) expect(deals.size).to eql(2) expect(deals[0].title).to eql("Deal 1") expect(deals[1].title).to eql("Deal 2") end end describe "When we've asked for many deals" do it "return a deal object" do mock_response = double(:body => {"title" => "Deal 1"}) deal = DealService.build(mock_response) expect(deal.title).to eql("Deal 1") end end end end
require 'digest/md5' require 'cgi' module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Alipay module Sign def verify_sign sign_type = @params.delete("sign_type") sign = @params.delete("sign") email = @params["seller_email"] if email == EMAIL_NEW alipay_key = KEY_NEW elsif email == EMAIL alipay_key = KEY else return false end md5_string = @params.sort.collect do |s| unless s[0] == "notify_id" s[0]+"="+CGI.unescape(s[1]) else s[0]+"="+s[1] end end Digest::MD5.hexdigest(md5_string.join("&")+alipay_key) == sign.downcase end end end end end end
# frozen_string_literal: true module Telegram module Bot module Tasks extend self def set_webhook routes = Rails.application.routes.url_helpers cert_file = ENV['CERT'] cert = File.open(cert_file) if cert_file each_bot do |key, bot| route_name = RoutesHelper.route_name_for_bot(bot) url = routes.send("#{route_name}_url") say("Setting webhook for #{key}...") bot.set_webhook( url: url, certificate: cert, ip_address: ENV['IP_ADDRESS'], drop_pending_updates: drop_pending_updates, ) end end def delete_webhook each_bot do |key, bot| say("Deleting webhook for #{key}...") bot.delete_webhook(drop_pending_updates: drop_pending_updates) end end def log_out each_bot do |key, bot| say("Logging out #{key}...") bot.log_out end end def close each_bot do |key, bot| say("Closing #{key}...") bot.close end end private def say(text) puts(text) unless Rails.env.test? # rubocop:disable Rails/Output end def each_bot(&block) id = ENV['BOT'].try!(:to_sym) bots = id ? {id => Client.by_id(id)} : Telegram.bots bots.each { |key, bot| bot.async(false) { block[key, bot] } } end def drop_pending_updates ENV['DROP_PENDING_UPDATES'].try!(:downcase) == 'true' end end end end
#This class is a rather experimental class designed to gather information #about the populations evolution during the running of the algorithm class PopulationMonitor attr_accessor :stats, :history, :best, :mutations def initialize *args @args = *args.join(" ") @history = [] end #=--------------Code Called During GA Run-Time--------------=# def process current_population @history << current_population.get_pop.clone end def record_mutation @mutations ||= 0 @mutations += 1 end #=--------------Code Called After GA Run-Time--------------=# # ##=--------------Statistic Generating code----------------=# def make @stats = [] @history.each {|generation| make_stats(generation) } when_best self end def make_stats population running_score = 0 for individual in population f = individual.fitness running_score += f best ||= {:individual => individual, :fitness => f} best = {:individual => individual, :fitness => f} if f > best[:fitness] end @stats << { :gen_no => @stats.size + 1, :best_individual => best[:individual], :mean_fit => (running_score / population.size) } end def when_best @best = @stats.first[:best_individual] @stats.each do |generation| if generation[:best_individual].fitness > @best.fitness @best = generation[:best_individual] @earliest_occurance = generation[:gen_no] end end end def calculate_genetic_convergence gene_length = @history.first.first.genome.sequence.size # Not gonna work with variable gene lengths genome_std = [] @history.each do |generation| gene_score = [] gene_length.times do |i| gene_score[i] = standard_deviation( generation.map {|indiv| indiv.genome.sequence[i] } ) end genome_std << gene_score end genome_std.map {|gen| i=0; gen.each {|g| i+=g}; i/gen.size} end ##=--------------Data return functions----------------=# def results results ={:stats => @stats, :best => @best} results.merge!({:mutations => @mutations}) if @mutations results.merge!({:offspring_wins => @offspring_wins}) if @off_spring_wins results end def best_individual @best end alias best best_individual def mean_fitness results[:stats].map{|s| s[:mean_fit] } end def genetic_convergence calculate_genetic_convergence end def converged_at g_conv = calculate_genetic_convergence i = g_conv.last until i != g_conv.last i = g_conv.pop end g_conv.size end #=--------------Code which outputs to screen----------------=# def display_results make display_best display_mutations unless @mutations end def display_best when_best unless @earliest_occurance msg = "\n\nWinning Genome\nGenome: #{@best.genome.sequence.join(", ")}" msg << "\nName:\t\t#{@best.name}" msg << "\nPhenotype:\t#{@best.phenotype.class == Array ? @best.phenotype.join(", ") : @best.phenotype}" msg << "\nFitness:\t#{@best.fitness}" msg << "\nGeneration:\t#{@earliest_occurance}" msg << "\n#{Array.new(20){"-"}.to_s}\n" puts msg end def show_genetic_convergence puts "population was geneticaly identical at generation #{converged_at}" end def display_mutations puts "Number of Mutations: #{@mutations}" end #=-----------------------------------------------------------=# def array_sum arr sum = 0 arr.each {|a| sum+= a} sum end def variance(population) n = 0 mean = 0.0 s = 0.0 population.each { |x| n = n + 1 delta = x - mean mean = mean + (delta / n) s = s + delta * (x - mean) } # if you want to calculate std deviation # of a sample change this to "s / (n-1)" return s / n end # calculate the standard deviation of a population # accepts: an array, the population # returns: the standard deviation def standard_deviation(population) Math.sqrt(variance(population)) end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :jobs, dependent: :destroy has_many :applications has_many :worker_relationships, class_name: "Shimekiri", foreign_key: "worker_id", dependent: :destroy has_many :owner_users, through: :worker_relationships, source: :owner has_many :owner_relationships, class_name: "Shimekiri", foreign_key: "owner_id", dependent: :destroy has_many :worker_users, through: :owner_relationships, source: :worker def oubo(other_user) worker_relationships.find_or_create_by(owner_id: other_user.id) end # oubo -> not def unoubo(other_user) worker_relationship = worker_relationships.find_by(worker_id: other_user.id) worker_relationship.destroy if worker_relationship end # あるユーザーをフォローしているかどうか? def oubo?(other_user) worker_users.include?(other_user) end end
class Project < ActiveRecord::Base acts_as_superclass attr_accessible :name, :uid, :description, :scm, :private, :public belongs_to :owner, class_name: User validates :name, length: {minimum: 5}, presence: true, uniqueness: true validates :uid, format: {with: /\A[a-z0-9-]+\z/}, length: {minimum: 5}, presence: true, uniqueness: true def self.real_class(scm) case scm when :git then GitProject when :svn then SvnProject end end def public=(public) self.private = !public end def public? !self.private? end end
class CategoriesController < ApplicationController before_action :authorize before_action :check_admin before_action :find_category, except: [:index, :new, :create] def index @categories = Category.all end def create @category = Category.new(category_params) if @category.save redirect_to categories_path else render 'new' end end def new @category = Category.new end def edit end def update if @category.update(category_params) redirect_to categories_path else render 'edit', alert: "Update Unsuccesful!!" end end def destroy @category.destroy redirect_to categories_path, alert: "Category Deleted!" end private def category_params params.require(:category).permit(:name) end def check_admin if current_user.admin != true redirect_to root_path, alert: "Access Denied!" end end def find_category @category = Category.find(params[:id]) end end
class Application < ApplicationRecord validates :name, presence: true validates :address, presence: true validates :city, presence: true validates :state, presence: true validates :zip, presence: true has_many :pet_applications has_many :pets, through: :pet_applications def self.pending Application.select('applications.id, pets.shelter_id').joins(:pets).where(:status => "Pending") end def pet_count self.pets.count end def approved_declined if (status == "Approved") status = "Approved" elsif (status == "Rejected") status = "Rejected" else (status == "Approved" && status == "Rejected") status = "Rejected" end end end
# frozen_string_literal: true require 'gilded_rose' def enter_item(name, sell_in, quality) @items = [Item.new(name, sell_in, quality)] GildedRose.new(@items).update_quality end describe GildedRose do describe '#update_quality' do it 'does not change the name' do enter_item('foo', 0, 0) expect(@items[0].name).to eq 'foo' end context 'normal items' do context 'postive sell_in value' do it 'decreases quality by 1' do enter_item('foo', 10, 20) expect(@items[0].quality).to eq 19 end end context 'negative sell_in value' do it 'decreases quality by 2' do enter_item('foo', 0, 6) expect(@items[0].quality).to eq 4 end end it 'quality of item is never negative' do enter_item('foo', 1, 0) expect(@items[0].quality).to eq 0 end end context 'Aged Brie' do context 'postive sell_in value' do it 'increases quality by 1' do enter_item('Aged Brie', 1, 6) expect(@items[0].quality).to eq 7 end end context 'negative sell_in value' do it 'increases quality by 2' do enter_item('Aged Brie', 0, 6) expect(@items[0].quality).to eq 8 end end it 'quality is never more than 50' do enter_item('Aged Brie', 1, 49) expect(@items[0].quality).to eq 50 end end context 'Bakstage Passes' do it 'quality is never more than 50' do enter_item('Backstage passes to a TAFKAL80ETC concert', 1, 50) expect(@items[0].quality).to eq 50 end it 'quality increases by 1 if sell_in value is 15' do enter_item('Backstage passes to a TAFKAL80ETC concert', 15, 10) expect(@items[0].quality).to eq 11 end it 'quality increases by 2 if sell_in value is 10' do enter_item('Backstage passes to a TAFKAL80ETC concert', 10, 10) expect(@items[0].quality).to eq 12 end it 'quality increases by 3 if sell_in value is 5' do enter_item('Backstage passes to a TAFKAL80ETC concert', 5, 10) expect(@items[0].quality).to eq 13 end it 'quality decreases to 0 if sell_in value is 0' do enter_item('Backstage passes to a TAFKAL80ETC concert', 0, 10) expect(@items[0].quality).to eq 0 end end context 'Legendary items' do it 'sell_in and quanity do not change if sell_in value is positive' do enter_item('Sulfuras, Hand of Ragnaros', 10, 80) expect(@items[0].sell_in).to eq 10 expect(@items[0].quality).to eq 80 end it 'sell_in and quanity do not change if sell_in value is negative' do enter_item('Sulfuras, Hand of Ragnaros', -1, 80) expect(@items[0].sell_in).to eq(-1) expect(@items[0].quality).to eq 80 end end context 'Conjured items' do context 'postive sell_in value' do it 'decreases quality by 2' do enter_item('Conjured', 10, 20) expect(@items[0].quality).to eq 18 end end context 'negative sell_in value' do it 'decreases quality by 4' do enter_item('Conjured', 0, 6) expect(@items[0].quality).to eq 2 end end it 'quality of item is never negative' do enter_item('Conjured', 1, 0) expect(@items[0].quality).to eq 0 end end end end
class CreateCrawlers < ActiveRecord::Migration def change create_table :crawlers do |t| t.string :ip_address t.string :referral t.string :browser_type t.boolean :is_it_a_bot t.date :created_at t.timestamps null: false end end end
require 'spec_helper' require 'rakuten_web_service/ichiba/ranking' describe RakutenWebService::Ichiba::RankingItem do let(:endpoint) { 'https://app.rakuten.co.jp/services/api/IchibaItem/Ranking/20170628' } let(:affiliate_id) { 'affiliate_id' } let(:application_id) { 'application_id' } let(:expected_query) do { affiliateId: affiliate_id, applicationId: application_id, formatVersion: '2' } end before do response = JSON.parse(fixture('ichiba/ranking_search.json')) @expected_request = stub_request(:get, endpoint). with(query: expected_query).to_return(body: response.to_json) RakutenWebService.configure do |c| c.affiliate_id = affiliate_id c.application_id = application_id end end describe '.search' do let(:expected_json) do response = JSON.parse(fixture('ichiba/ranking_search.json')) response['Items'][0] end before do @ranking_item = RakutenWebService::Ichiba::RankingItem.search({}).first end subject { @ranking_item } specify 'should call the endpoint once' do expect(@expected_request).to have_been_made.once end specify 'should be access by key' do expect(subject['itemName']).to eq(expected_json['itemName']) expect(subject['item_name']).to eq(expected_json['itemName']) end describe '#rank' do subject { super().rank } it { is_expected.to eq(1) } end describe '#name' do subject { super().name } it { is_expected.to eq(expected_json['itemName']) } end end end
#!/usr/bin/env ruby require 'rubygems' require 'rubygame' #require 'pubnub' require 'matrix' #require 'pp' include Rubygame resolution = [640, 480] #pn = Pubnub.new(:publish_key => 'pub-dad6a0ed-bc25-4a22-be4d-d4695a6a2b4a', :subscribe_key => 'sub-a391c3ba-08f1-11e2-98f5-8d7cd55b77a3') @screen = Screen.open resolution, 0, [HWSURFACE, DOUBLEBUF] @screen.title = "JumpJump" #@screen.show_cursor = false TTF.setup point_size = 20 $font = TTF.new "Verdana.ttf", point_size YELLOW = [ 0xee, 0xee, 0x33] PLAYER1 = [ 0x00, 0x00, 0xff] PLAYER2 = [ 0x00, 0xff, 0x00] LIFE = 5000 unless @screen.respond_to? :draw_box puts "Don't have SDL_gfx available, can't use draw_box" puts "Exiting..." exit 1 end class Player include Sprites::Sprite def initialize color super() @image = Surface.new [30,30] @image.draw_box_s [0,0], [30,30], color @rect = @image.make_rect @velocity = [0, 2] #gravity end def vel_add vel @velocity[0] += vel[0] @velocity[1] += vel[1] end def update seconds_passed, walls old_velocity = @velocity x, y = @velocity factor = 500 * seconds_passed x *= factor y *= factor @rect.move! x,y # undo x and y separately so you can move without jumping @rect.move! 0, -1.0 * y if collides? walls # undo gravity @rect.move! -1.0 * x, 0 if collides? walls # undo sideways movement end def draw on_surface @rect.clamp! on_surface.make_rect @image.blit on_surface, @rect end def collides? group collide_group(group) != [] end end class Health include Sprites::Sprite def initialize color super() @image = Surface.new [30,30] @image.fill color @rect = @image.make_rect end def draw on_surface @image.blit on_surface, @rect end end class Wall include Sprites::Sprite def initialize pos super() color = [ 0xc0, 0x10, 0x10] @image = Surface.new [80,10] @image.draw_box_s [0,0], [80,10], color @rect = @image.make_rect @rect.topleft = pos end def draw on_surface @image.blit on_surface, @rect end end @black = Surface.new resolution @black.blit @screen,[0,0] @background = Surface.new resolution @background.blit @screen,[0,0] @score = Surface.new [640,30] @clock = Clock.new @clock.target_framerate = 120 @clock.enable_tick_events @players=Sprites::Group.new @walls=Sprites::Group.new Sprites::UpdateGroup.extend_object @players Sprites::UpdateGroup.extend_object @walls @player1 = Player.new PLAYER1 @player2 = Player.new PLAYER2 @players << @player1 @players << @player2 @walls << Wall.new([400,400]) @walls << Wall.new([300,300]) @walls << Wall.new([200,200]) @walls << Wall.new([100,100]) @walls.draw @screen @event_queue = EventQueue.new @event_queue.enable_new_style_events #enables rubygame 3.0 @player1_is_it_text = $font.render_utf8 "Player 1 is it!", true, PLAYER1 @player2_is_it_text = $font.render_utf8 "Player 2 is it!", true, PLAYER2 @player1_wins_text = $font.render_utf8 "Player 1 wins!", true, YELLOW @player2_wins_text = $font.render_utf8 "Player 2 wins!", true, YELLOW @player1_score = LIFE @player2_score = LIFE @got_message = lambda { |message| puts message return false } #pn.subscribe(:channel => :jumpjump, :callback => @got_message) should_run = true @player1_is_it = true @colliding = false while should_run seconds_passed = @clock.tick().seconds @event_queue.each do |event| case event when Events::QuitRequested should_run = false when Events::KeyPressed case event.key when :left @player1.vel_add [-1,0] when :right @player1.vel_add [ 1,0] when :up @player1.vel_add [0,-4] when :a @player2.vel_add [-1,0] when :d @player2.vel_add [ 1,0] when :w @player2.vel_add [0,-4] end when Events::KeyReleased @player1.vel_add [ 1,0] if event.key == :left @player1.vel_add [-1,0] if event.key == :right @player1.vel_add [0,4] if event.key == :up @player2.vel_add [ 1,0] if event.key == :a @player2.vel_add [-1,0] if event.key == :d @player2.vel_add [0,4] if event.key == :w end end tmp = @player1.collide(@player2) != [] if tmp and !@colliding @player1_is_it = !@player1_is_it @colliding = true @black.blit @background, [0,0] @walls.draw @background if @player1_is_it @player1_is_it_text.blit @background, [10,40] else @player2_is_it_text.blit @background, [320,40] end @background.blit @screen, [0,0] elsif !tmp and @colliding @colliding = false end @black.blit @score, [0,0] player1_score_text = $font.render_utf8 @player1_score.to_s, true, YELLOW player2_score_text = $font.render_utf8 @player2_score.to_s, true, YELLOW player1_score_text.blit @score, [0,0] player2_score_text.blit @score, [320,0] @score.blit @screen, [0,0] if @player1_is_it if @player1_score > 0 @player1_score -= 1 end else if @player2_score > 0 @player2_score -= 1 end end @players.undraw @screen, @background @players.update seconds_passed, @walls @players.draw @screen if @player1_score or @player2_score == 0 if @player1_score == 0 @player2_wins_text.blit @screen, [220,250] elsif @player2_score == 0 @player1_wins_text.blit @screen, [220,250] end end @screen.flip end
class PusherController < ActionController::Base def pusher webhook = Pusher.webhook(request) if webhook.valid? webhook.events.each do |event| case event["name"] when 'channel_occupied' device = Device.find_or_create_by_channel_name event["channel"] unless device.unassigned? device.active! Pusher.trigger(event["channel"], 'close_registration', {}) else Pusher.trigger(event["channel"], 'unregistered', {:code => device.access_token}) end when 'channel_vacated' device = Device.find_by_channel_name event["channel"] device.inactive! if device.active? end end render text: 'ok' else render text: 'invalid', status: 401 end end end
class ModifySerialFloat < ActiveRecord::Migration[5.2] def change change_column :flows_steps, :serial, :float, index: true end end
require_relative './test_helper' require './lib/invoice' require 'time' require 'bigdecimal' require 'mocha/minitest' class InvoiceTest < Minitest::Test def test_it_exists_and_has_attributes repo = mock i = Invoice.new({ :id => 6, :customer_id => 7, :merchant_id => 8, :status => "pending", :created_at => Time.now, :updated_at => Time.now, }, repo) invoice_test_created_at = i.created_at.strftime("%d/%m/%Y") invoice_test_updated_at = i.updated_at.strftime("%d/%m/%Y") assert_instance_of Invoice, i assert_equal 6, i.id assert_equal 7, i.customer_id assert_equal 8, i.merchant_id assert_equal :pending, i.status assert_equal Time.now.strftime("%d/%m/%Y"), invoice_test_created_at assert_equal Time.now.strftime("%d/%m/%Y"), invoice_test_updated_at end end
require 'rails_helper' RSpec.describe "FriendlyForwardings", type: :request do describe "perform a friendly forwarding" do describe "for non-signed-in users" do it "should forward to the requested page after signin" do user = create(:user) visit edit_user_path(user) fill_in "session_email", :with => user.email fill_in "session_password", :with => user.password click_button "Sign in" expect(current_path).to eq edit_user_path(user) visit signout_path visit signin_path fill_in "session_email", :with => user.email fill_in "session_password", :with => user.password click_button "Sign in" expect(current_path).to eq user_path(user) end end end end
class RemoveCategoryRequiredConstraintOnArticles < ActiveRecord::Migration def self.up change_column :articles, :article_category_id, :integer, :null => true end def self.down end end
class MateriaCarrerasController < ApplicationController before_action :set_materia_carrera, only: [:show, :edit, :update, :destroy] # GET /materia_carreras # GET /materia_carreras.json def index @materia_carreras = MateriaCarrera.all end # GET /materia_carreras/1 # GET /materia_carreras/1.json def show end # GET /materia_carreras/new def new @materia_carrera = MateriaCarrera.new end # GET /materia_carreras/1/edit def edit end # POST /materia_carreras # POST /materia_carreras.json def create @materia_carrera = MateriaCarrera.new(materia_carrera_params) respond_to do |format| if @materia_carrera.save format.html { redirect_to @materia_carrera, notice: 'Materia carrera was successfully created.' } format.json { render :show, status: :created, location: @materia_carrera } else format.html { render :new } format.json { render json: @materia_carrera.errors, status: :unprocessable_entity } end end end # PATCH/PUT /materia_carreras/1 # PATCH/PUT /materia_carreras/1.json def update respond_to do |format| if @materia_carrera.update(materia_carrera_params) format.html { redirect_to @materia_carrera, notice: 'Materia carrera was successfully updated.' } format.json { render :show, status: :ok, location: @materia_carrera } else format.html { render :edit } format.json { render json: @materia_carrera.errors, status: :unprocessable_entity } end end end # DELETE /materia_carreras/1 # DELETE /materia_carreras/1.json def destroy @materia_carrera.destroy respond_to do |format| format.html { redirect_to materia_carreras_url, notice: 'Materia carrera was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_materia_carrera @materia_carrera = MateriaCarrera.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def materia_carrera_params params.require(:materia_carrera).permit(:materia_id, :carrera_id, :semestre) end end