text
stringlengths
10
2.61M
# => Contient la classe FenetreNiveau pour la fenêtre de choix de la difficulté # # => Author:: Valentin, DanAurea # => Version:: 0.1 # => Copyright:: © 2016 # => License:: Distributes under the same terms as Ruby ## ## classe FenetreNiveau ## class FenetreNiveau < View # VI box @boxTop @boxBottom # VI bouton @boutonFacile @boutonMoyen @boutonDifficile # VI label @titreLabel ## ## Initialize ## def initialize() # VI box @boxTop = Gtk::Box.new(:vertical,0) @boxBottom = Fenetre::creerBoxBottom() # VI bouton @boutonFacile = Gtk::Button.new(:label => "Facile") @boutonMoyen = Gtk::Button.new(:label => "Moyen") @boutonDifficile = Gtk::Button.new(:label => "Difficile") # VI label @titreLabel = Fenetre::creerLabelType("<u>Choix difficulté</u>", Fenetre::SIZE_TITRE) end ## ## Permet de créer et d'ajouter les box au conteneur principal ## ## def miseEnPlace() creerBoxTop() ajoutCss() Fenetre::box.add(@boxTop) Fenetre::box.add(@boxBottom) end ## ## Créer la box verticale contenant les boutons des choix de la difficulté et le titre ## ## def creerBoxTop() #Action des boutons @boutonFacile.signal_connect('clicked'){ supprimerPartieExistante(@pseudo) Core::changeTo("JeuLibre", "pseudo": @pseudo, :difficulte=>Jeu::FACILE) } @boutonMoyen.signal_connect('clicked'){ supprimerPartieExistante(@pseudo) Core::changeTo("JeuLibre", "pseudo": @pseudo, :difficulte=>Jeu::MOYEN) } @boutonDifficile.signal_connect('clicked'){ supprimerPartieExistante(@pseudo) Core::changeTo("JeuLibre", "pseudo": @pseudo, :difficulte=>Jeu::DIFFICILE) } #add des boutons à la box @boxTop.add(@titreLabel) @boxTop.add(@boutonFacile) @boxTop.add(@boutonMoyen) @boxTop.add(@boutonDifficile) end ## ## Ajoute les classes css au widget ## def ajoutCss() #css label @titreLabel.override_color(:normal, Fenetre::COULEUR_BLANC) @titreLabel.set_margin_top(30) #css bouton @boutonFacile.set_margin_top(70) @boutonFacile.set_margin_bottom(40) @boutonFacile.set_margin_left(100) @boutonFacile.set_margin_right(100) @boutonMoyen.set_margin_bottom(40) @boutonMoyen.set_margin_left(100) @boutonMoyen.set_margin_right(100) @boutonDifficile.set_margin_bottom(40) @boutonDifficile.set_margin_left(100) @boutonDifficile.set_margin_right(100) end ## ## Lance la construction du modèle de la vue. Méthode à définir dans tout les cas ! Autrement pas de rendu de la page. ## ## @return self ## def run() self.miseEnPlace() return self end end
class FontIbmPlexSansCondensed < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/ibmplexsanscondensed" desc "IBM Plex Sans Condensed" homepage "https://fonts.google.com/specimen/IBM+Plex+Sans+Condensed" def install (share/"fonts").install "IBMPlexSansCondensed-Bold.ttf" (share/"fonts").install "IBMPlexSansCondensed-BoldItalic.ttf" (share/"fonts").install "IBMPlexSansCondensed-ExtraLight.ttf" (share/"fonts").install "IBMPlexSansCondensed-ExtraLightItalic.ttf" (share/"fonts").install "IBMPlexSansCondensed-Italic.ttf" (share/"fonts").install "IBMPlexSansCondensed-Light.ttf" (share/"fonts").install "IBMPlexSansCondensed-LightItalic.ttf" (share/"fonts").install "IBMPlexSansCondensed-Medium.ttf" (share/"fonts").install "IBMPlexSansCondensed-MediumItalic.ttf" (share/"fonts").install "IBMPlexSansCondensed-Regular.ttf" (share/"fonts").install "IBMPlexSansCondensed-SemiBold.ttf" (share/"fonts").install "IBMPlexSansCondensed-SemiBoldItalic.ttf" (share/"fonts").install "IBMPlexSansCondensed-Thin.ttf" (share/"fonts").install "IBMPlexSansCondensed-ThinItalic.ttf" end test do end end
FactoryGirl.define do factory :product do name { 'Product A' } price { 30 } description { 'Good Product' } end end
require 'spec_helper' describe Stage do describe 'synchronization' do let!(:remote_attrs) do [ build(:remote_stage, tour_id: '1', eman: 'ignored'), build(:remote_stage, tour_id: '2'), build(:remote_stage, tour_id: '3') ] end describe 'skipping with before_sync hook' do let!(:context) { Stage.sync(remote_attrs, :includes => {}) } it 'skips hashes where name is "ignored"' do expect(Stage.count).to eq(2) expect(Synchronisable::Import.count).to eq(2) end end end end
#!/usr/bin/env ruby require 'optparse' require 'rubygems' require 'aejis_backup' options = {} optparse = OptionParser.new do |opts| opts.banner = "\nUsage: backup [options]\n " opts.on('-c', '--config [PATH]', "Path to backup configuration") do |config| options[:config] = config end opts.on('-b x,y,z', Array, "List of backups to run") do |list| options[:list] = list end opts.on_tail('-s', '--silent', 'Do not print messages to STDOUT') do BACKUP_SILENT = true end end optparse.parse! AejisBackup.config_path = options[:config] AejisBackup.load AejisBackup.run!(options[:list])
module PermitConcern extend ActiveSupport::Concern module ClassMethods private # DSL # Разрешить передачу параметров из params # @param [Hash] attributes def permit(attributes) attributes = attributes.symbolize_keys @permitter = ->(params_scope, controller) do (params_scope.present? ? controller.params.require(params_scope) : controller.params).permit(*attributes[params_scope]) end end # Получает ключи из массива параметров для strong_params # # @return [Array<Symbol>] # def param_keys(model_params) model_params.flat_map{ |i| i.is_a?(Hash) ? i.try(:keys) : i } end end # Возвращает разрешенные параметы # @param [Symbol] params_scope Массив с параметрами, например: :post для params[:post] def permitted_params(params_scope = nil) params = self.class.instance_variable_get(:@permitter).call(params_scope.try(:to_sym), self) # Дополнительная фильтрация параметров на уровне контроллера yield(params) if block_given? params end end
class PosdsController < ApplicationController before_action :set_posd, only: [:show, :edit, :update, :destroy, :upvote] before_filter :authenticate_user!, :only => [:edit, :new, :destroy] # GET /posds # GET /posds.json def index @posds = Posd.order ('publish_date DESC') @posds = @posds.published if current_user.blank? #не залогіненим не показує майбутні пости #@posds = @posds.by_user_id(params[:user]) if params [:user].present? #@posds = @posds.by_category_id(params[:cat]) if params [:cat].present? end # GET /posds/1 # GET /posds/1.json def show end # GET /posds/new def new @posd = Posd.new end # GET /posds/1/edit def edit end # def upvote #likes # @posd.increment!(:votes_count) # #збільшить voutes_count на 1 і save # redirect_to request.referrer #повертається на ту саму сторінку # end # POST /posds # POST /posds.json def create @posd = Posd.new(posd_params) @posd.user_id = current_user.id respond_to do |format| if @posd.save format.html { redirect_to @posd, notice: 'Posd was successfully created.' } format.json { render :show, status: :created, location: @posd } else format.html { render :new } format.json { render json: @posd.errors, status: :unprocessable_entity } end end end # PATCH/PUT /posds/1 # PATCH/PUT /posds/1.json def update respond_to do |format| if @posd.update(posd_params) format.html { redirect_to @posd, notice: 'Posd was successfully updated.' } format.json { render :show, status: :ok, location: @posd } else format.html { render :edit } format.json { render json: @posd.errors, status: :unprocessable_entity } end end end # DELETE /posds/1 # DELETE /posds/1.json def destroy @posd.destroy respond_to do |format| format.html { redirect_to posds_url, notice: 'Posd was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_posd @posd = Posd.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def posd_params params.require(:posd).permit(:title, :body, :publish_date, :user_id) end end
# class Hamming def self.compute(string1, string2) raise ArgumentError if string1.length != string2.length string1.chars.zip(string2.chars).count { |a, b| a != b } end end
# frozen_string_literal: true require "spec_helper" module Decidim module Amendable describe CreateDraft do let!(:component) { create(:opinion_component, :with_amendments_enabled) } let!(:user) { create :user, :confirmed, organization: component.organization } let!(:amendable) { create(:opinion, component: component) } let(:title) { "More sidewalks and less roads!" } let(:body) { "Everything would be better" } let(:params) do { amendable_gid: amendable.to_sgid.to_s, emendation_params: { title: title, body: body } } end let(:context) do { current_user: user, current_organization: component.organization } end let(:form) { Decidim::Amendable::CreateForm.from_params(params).with_context(context) } let(:command) { described_class.new(form) } include_examples "create amendment draft" end end end
class Bill include Virtus.model attribute :name end class SampleInteraction include Faire input :some_string, klass: String input :name, nullify_blank: true input :other, required: false input :bill, klass: Bill def execute bill end end
module SQLiterate module Node module MultiString def value ([single_string.value] + \ t.elements.map do |e| e.single_string.value end ).join end end module Character module Quote def value "'" end end module Text def value text_value end end module ExtEscape def value c.value end end module NotImplemented def value "" end end end module StringConstant def value c.elements.map(&:value).join end end end end
include_recipe 'yumrepo::datadog' package 'datadog-agent' datadog_credentials = Chef::EncryptedDataBagItem.load('credentials', 'datadog') template '/etc/dd-agent/datadog.conf' do owner 'dd-agent' group 'root' mode '0640' variables datadog_apikey: datadog_credentials['api_key'], datadog_hostname: 'home.a-know.me' notifies :restart, 'service[datadog-agent]' end service 'datadog-agent' do action [:enable, :start] supports restart: true end
class CommentsController < ApplicationController def new @topic = Topic.find(params[:topic_id]) @comment = @topic.comments.new @comment.attributes = comment_params if request.post? end def confirm @topic = Topic.find(params[:topic_id]) if request.post? @comment = @topic.comments.new(comment_params) if @comment.valid? render :action => 'confirm' else render :action => 'new' end else @comment = Comment.new render :action => 'new' end end def create @topic = Topic.find(params[:topic_id]) @comment = @topic.comments.create!(comment_params) @topic.touch @topic.updated_at redirect_to topic_path(params[:topic_id]), method: :get end private def comment_params params.require(:comment).permit(:content, :image, :image_cache, :remove_image).merge(user_id: current_user.id, topic_id:params[:topic_id]) end end
module OrientdbBinary module BinDataPrimitives class ProtocolString < BinData::Primitive endian :big int32 :len, value: -> { data.length } string :data, read_length: :len, onlyif: -> {len > -1} def get data end def set(v) self.data = v end end class RecordType < BinData::Primitive endian :big int8 :type def get type.chr end def set(v) self.type = v.ord end end class RecordObject < BinData::Primitive endian :big protocol_string :content def get self.content = OrientdbBinary::Parser::Deserializer.new.deserialize_document(self.content) end def set(v) self.content = v end end end end
require 'spec_helper' describe SrpmDecorator do it 'should return "&ndash;" on Srpm.short_url with empty url' do Srpm.new.decorate.short_url.should eq('&ndash;') end it 'should return "http://example.com" if url length less than 27' do srpm = Srpm.new(url: 'http://example.com').decorate html = srpm.short_url Nokogiri::HTML(html).css('a').attribute('href').value.should eq('http://example.com') Nokogiri::HTML(html).css('a').children.first.text.should eq('http://example.com') end it 'should return short url if url length more than 27' do srpm = Srpm.new(url: 'http://123456789012345678901234567890').decorate html = srpm.short_url Nokogiri::HTML(html).css('a').attribute('href').value.should eq('http://123456789012345678901234567890') Nokogiri::HTML(html).css('a').children.first.text.should eq('http://12345678901234567890...') end it 'should return 1.0-alt1' do srpm = Srpm.new(version: '1.0', release: 'alt1', epoch: nil).decorate srpm.evr.should eq('1.0-alt1') end it 'should return 1:1.0-alt1' do srpm = Srpm.new(version: '1.0', release: 'alt1', epoch: '1').decorate srpm.evr.should eq('1:1.0-alt1') end end
namespace :rates do desc "generate rates for rate-less exchanges" task :generate => :environment do Rails.logger.info "" Rails.logger.info "generate rates process started" Rails.logger.info "" current_rates = Currency.rates currency_updatable = Currency.updatable Exchange.with_no_real_rates.find_each do |exchange| unless exchange.currency.present? Rails.logger.info "Exchange #{exchange.id.to_s} has no currency - no rates generated" next end unless exchange.country.present? Rails.logger.info "Exchange #{exchange.id.to_s} has no country - no rates generated" next end exchange.update(rates_source: 'test', status: nil) exchange.rates.delete_all rates = currency_updatable.include?(exchange.currency) ? current_rates[exchange.currency.to_sym] : Currency.rates(exchange.currency)[exchange.currency.to_sym] markup = Currency.markup_policy(exchange.country) rates.each do |currency, rate| currency = currency.to_s next unless (currency_updatable.include? currency) && rate.present? sell_markup = markup[Currency.category(currency).to_sym][:sell_markup] + markup[Currency.category(currency).to_sym][:sell_spread] * rand(-1.0..1.0) sell_factor = 1 - (sell_markup / 100) sell = rate * sell_factor buy_markup = markup[Currency.category(currency).to_sym][:buy_markup] + markup[Currency.category(currency).to_sym][:buy_spread] * rand(-1.0..1.0) buy_factor = 1 + (buy_markup / 100) buy = rate * buy_factor exchange.rates.create(source: 'test', currency: currency, buy: buy, sell: sell, last_update: Time.now, last_process: 'rates:generate') end end Chain.with_no_real_rates.find_each do |chain| # puts chain.name unless chain.currency.present? Rails.logger.info "Chain #{chain.id.to_s} has no currency - no rates generated" next end unless chain.exchanges.exists? Rails.logger.info "Chain #{chain.id.to_s} has no exchanges - no rates generated" next end chain.update(rates_source: 'test') chain.rates.delete_all rates = currency_updatable.include?(chain.currency) ? current_rates[chain.currency.to_sym] : Currency.rates(chain.currency)[chain.currency.to_sym] markup = Currency.markup_policy(chain.exchanges.first.country) # puts markup.inspect rates.each do |currency, rate| currency = currency.to_s # puts currency next unless (currency_updatable.include? currency) && rate.present? sell_markup = markup[Currency.category(currency).to_sym][:sell_markup] + markup[Currency.category(currency).to_sym][:sell_spread] * rand(-1.0..1.0) sell_factor = 1 - (sell_markup / 100) sell = rate * sell_factor buy_markup = markup[Currency.category(currency).to_sym][:buy_markup] + markup[Currency.category(currency).to_sym][:buy_spread] * rand(-1.0..1.0) buy_factor = 1 + (buy_markup / 100) buy = rate * buy_factor chain.rates.create(source: 'test', currency: currency, buy: buy, sell: sell, last_update: Time.now, last_process: 'rates:generate') end end Rails.logger.info "" Rails.logger.info "generate rates process finished" Rails.logger.info "" end end
require 'spec_helper' describe "Affiliations" do before do mock_geocoding! @affiliation = FactoryGirl.create(:affiliation) end describe "without admin login" do it "should redirect to admin login" do get affiliations_path response.should redirect_to(new_admin_session_path) end end describe "with admin logged in" do before do theAdmin = FactoryGirl.create(:admin) visit new_admin_session_path fill_in "Email", with: theAdmin.email fill_in "Password", with: theAdmin.password click_button "commit" visit affiliations_path end describe "visiting the affiliations index" do it "should show a affiliation" do page.should have_content(@affiliation.name) end end end end
class CourseMeta < ActiveRecord::Base attr_accessible :course_name validates :course_name, :presence => true before_save :update_overall_scores has_many :courses has_many :course_reviews def update_overall_scores overallQualitySum = 0.0 difficultySum = 0.0 numOverallReviews = 0.0 numDifficultyReviews = 0.0 for review in self.course_reviews(true) if(review.average_quality>0) numOverallReviews+=1 end overallQualitySum+=review.average_quality if(review.average_difficulty>0) numDifficultyReviews+=1 end difficultySum+=review.average_difficulty end if numOverallReviews ==0.0 numOverallReviews=1 end if numDifficultyReviews ==0.0 numDifficultyReviews=1 end self.overall_quality=(overallQualitySum/numOverallReviews).to_f self.overall_difficulty=(difficultySum/numDifficultyReviews).to_f end end
class Api::V1::UsersController < ApiController def current if current_user.nil? render json: {user: {}} else render json: current_user, serializer: CurrentUserSerializer end end end
class Tagging < ActiveRecord::Base validates :tag, :taggable, presence: :true validates :tag, uniqueness: { scope: [:taggable_id, :taggable_type] } belongs_to :taggable, polymorphic: true belongs_to :tag end
class GreenhousesController < ApplicationController before_action :set_greenhouse, only: [:show, :edit, :update, :destroy] # GET /greenhouses # GET /greenhouses.json def index @action_entries = ActionEntry.all @greenhouse = Greenhouse.first end end
class DropProductOrders < ActiveRecord::Migration[6.0] def change drop_table :product_orders end end
class CreateArrivalItems < ActiveRecord::Migration[5.2] def change create_table :arrival_items do |t| t.integer :arrival_count, :null => false t.datetime :arrival_time, :null => false t.integer :item_id, :null => false t.boolean :is_deleted, :null => false, :default =>false t.timestamps end add_index :arrival_items, :is_deleted end end
class Genre extend Concerns::Findable attr_accessor :name attr_reader :songs @@all = [] def initialize(name) @name = name @songs = [] end def self.all @@all end def self.destroy_all @@all.clear end def save @@all << self end def self.create(name) genre = Genre.new(name) genre.save genre end def artists songs.collect{|x| x.artist}.uniq end end
require 'spec_helper' module Headjack describe Connection do let(:q1){"RETURN true"} let(:match_rel){ match( "id" => String, "type" => "TYPE", "startNode" => String, "endNode" => String, "properties" => {} ) } let(:match_node){ match( "id" => String, "labels" => ["Test"], "properties" => {} ) } it { is_expected.to be_truthy } describe "#cypher" do it { expect(subject.cypher(query: q1, filter: :all)).to eq "columns"=>["true"], "data"=>[[true]] } end describe "#call" do it { expect(subject.call(query: q1, mode: :cypher, filter: :all)).to eq "columns"=>["true"], "data"=>[[true]] } end describe "#cypher" do it { expect(subject.cypher(query: q1)).to eq [true] } end describe "#call" do it { expect(subject.transaction(query: Object.new.tap{|o| def o.to_s;"RETURN true";end } )).to eq [true] } it { expect(subject.call(query: q1, mode: :cypher)).to eq [true] } it { expect(subject.call(query: q1, mode: :cypher, filter: :all)).to include("columns", "data") } it { expect(subject.call(query: q1, mode: :transaction)).to eq [true] } it { expect(subject.call(query: q1, mode: :transaction, filter: :all)).to include("results", "errors")} it { expect(subject.call(query: q1, filter: :all)).to include("results", "errors")} end describe "#transaction" do let(:dummy_results){ [ {"columns"=>["true"], "data"=>[{"row"=>[true]}]} ] } it { expect(subject.transaction(statements: [statement: q1])).to eq [true] } it { expect(subject.transaction(statements: [statement: q1], filter: :one)).to eq true } it { expect(subject.transaction(statement: q1, filter: :one)).to eq true } it { expect(subject.transaction(query: q1, filter: :one)).to eq true } it { expect(subject.transaction(query: q1, filter: :one)).to eq true } describe "result of transaction" do let(:stats_result){ subject.transaction(query: q1, filter: :stats) } let(:all_result){ subject.transaction(query: q1, filter: :all) } let(:error_result){ subject.transaction(query: "ERROR") } it { expect(stats_result["contains_updates"]).to be false } it { expect(stats_result["contains_updates"]).to be false } it { expect(stats_result["nodes_created"]).to be_zero } it { expect(stats_result["nodes_deleted"]).to be_zero } it { expect(stats_result["properties_set"]).to be_zero } it { expect(stats_result["relationships_created"]).to be_zero } it { expect(stats_result["relationship_deleted"]).to be_zero } it { expect(stats_result["labels_added"]).to be_zero } it { expect(stats_result["labels_removed"]).to be_zero } it { expect(stats_result["indexes_added"]).to be_zero } it { expect(stats_result["indexes_removed"]).to be_zero } it { expect(stats_result["constraints_added"]).to be_zero } it { expect(stats_result["constraints_removed"]).to be_zero } it { expect(all_result["results"].first["columns"]).to eq(["true"]) } it { expect(all_result["results"].first["data"].first["row"]).to eq([true]) } it { expect(all_result["results"].first["data"].first["graph"]["nodes"]).to be_empty } it { expect(all_result["results"].first["data"].first["graph"]["relationships"]).to be_empty } it { expect(all_result["errors"]).to eq([]) } it { expect{error_result}.to raise_error(SyntaxError) } end describe "graph filter" do it{ expect( subject.transaction( statements: [ {statement:"CREATE (a:Test {name: \"A\" }) RETURN a"}, {statement:"ROLLBACK"} ], filter: :graph ) ).to match([ "relationships" => [], "nodes" => [ {"id"=> String, "labels"=> ["Test"], "properties"=> {"name"=>"A"}} ] ] ) } it{ expect( subject.transaction( statements: [ {statement:"CREATE (a:Test)-[r:TYPE]->(b:Test {}) RETURN r"}, {statement:"ROLLBACK"} ], filter: :graph ) ).to match(["nodes"=>[match_node, match_node], "relationships"=>[match_rel]]) } end describe "relationships filter" do it{ expect( subject.transaction( statements: [ {statement:"CREATE (a:Test)-[r:TYPE]->(b:Test {}) RETURN r"}, {statement:"ROLLBACK"} ], filter: :relationships ) ).to match([match_rel]) } end describe "relationship filter" do it{ expect( subject.transaction( statements: [ {statement:"CREATE (a:Test)-[r:TYPE]->(b:Test {}) RETURN r"}, {statement:"ROLLBACK"} ], filter: :relationship ) ).to match_rel } end end end end
class SessionsController < ApplicationController def create # this is what comes back from facebook @omniauth = request.env['omniauth.auth'] # save all our user details to the session session[:provider] = @omniauth[:provider] session[:provider_id] = @omniauth[:uid] session[:name] = @omniauth[:info][:name] session[:photo_url] = @omniauth[:info][:image] Pusher['banter'].trigger("logged_in", { name: session[:name] }) redirect_to root_path end def destroy Pusher['banter'].trigger("logged_out", { name: session[:name] }) reset_session redirect_to root_path end end
class UserCard < ActiveRecord::Base belongs_to :user belongs_to :card scope :with_cards, ->(cards){ where(card_id: cards) } end
class PagesController < ApplicationController def home @testVar = "Ruby" end end
class AddFieldToContractPayments < ActiveRecord::Migration def change add_column :contract_payments, :all_scope, :boolean end end
module Sudoku class Group class InvalidArgumentError < StandardError; end def initialize(cells) validate_input(cells) @cells = cells end def solved? cells.all? &:solved? end private attr_reader :cells def validate_input(cells) raise InvalidArgumentError if cells.nil? || cells.size != 9 end end end
class CreatePurchases < ActiveRecord::Migration[5.0] def change create_table :purchases do |t| t.string :total_amount t.date :valid_since t.date :valid_until t.references :vehicle, foreign_key: true t.references :payment, foreign_key: true t.timestamps end end end
require 'yaml' require_relative '../../tictactoeruby.core/exceptions/nil_reference_error.rb' require_relative '../../tictactoeruby.core/exceptions/invalid_value_error.rb' module TicTacToeRZ module Languages module YAMLReader def self.read_data(file_path, property) raise Exceptions::NilReferenceError, "file_path" if file_path.nil? raise Exceptions::InvalidValueError, "file_path" if file_path == "" file_path = File.dirname(__FILE__) + '/' + file_path raise Exceptions::InvalidValueError, "file_path = #{file_path}" if !(File.exist?(file_path)) raise Exceptions::NilReferenceError, "property" if property.nil? raise Exceptions::InvalidValueError, "property" if property == "" yaml_file = YAML.load_file(file_path) data = yaml_file[property] raise Exceptions::InvalidValueError, property.to_s if data.nil? yaml_content = data end end end end
FactoryBot.define do factory :client_sentiment, class: IGMarkets::ClientSentiment do long_position_percentage 60.0 market_id 'EURUSD' short_position_percentage 40.0 trait :invalid do long_position_percentage 0.0 short_position_percentage 0.0 end end end
require 'optionparser' options = {} printers = Array.new OptionParser.new do |opts| opts.banner = "Usage: dfm [options][path]\nDefaults: dfm -xd ." + File::SEPARATOR opts.on("-f", "--filters FILTERS", Array, "File extension filters") do |filters| options[:filters] = filters end opts.on("-x", "--duplicates-hex", "Prints duplicate files by MD5 hexdigest") do |dh| printers << "dh" end opts.on("-d", "--duplicates-name", "Prints duplicate files by file name") do |dh| printers << "dn" end opts.on("-s", "--singles-hex", "Prints non-duplicate files by MD5 hexdigest") do |dh| printers << "sh" end opts.on("-n", "--singles-name", "Prints non-duplicate files by file name") do |dh| printers << "sn" end end.parse! # # Usage: dfm [options] [path] # Defaults: dfm -xd ./ # -f, --filters FILTERS File extension filters # -x, --duplicates-hex Prints duplicate files by MD5 hexdigest # -d, --duplicates-name Prints duplicate files by file name # -s, --singles-hex Prints non-duplicate files by MD5 hexdigest # -n, --singles-name Prints non-duplicate files by file name # Excerpt from https://github.com/leejarvis/slop opts = Slop.parse do |o| o.string '-h', '--host', 'a hostname' o.integer '--port', 'custom port', default: 80 o.bool '-v', '--verbose', 'enable verbose mode' o.bool '-q', '--quiet', 'suppress output (quiet mode)' o.bool '-c', '--check-ssl-certificate', 'check SSL certificate for host' o.on '--version', 'print the version' do puts Slop::VERSION exit end end ARGV #=> -v --host 192.168.0.1 --check-ssl-certificate opts[:host] #=> 192.168.0.1 opts.verbose? #=> true opts.quiet? #=> false opts.check_ssl_certificate? #=> true opts.to_hash #=> { host: "192.168.0.1", port: 80, verbose: true, quiet: false, check_ssl_certificate: true } x = {"hello" => "world", this: {"apple" => 4, tastes: "delicious"}} require 'json' puts x.to_json # {"hello":"world","this":{"apple":4,"tastes":"delicious"}} puts JSON.pretty_generate( x ) # { # "hello": "world", # "this": { # "apple": 4, # "tastes": "delicious" # } # } require 'yaml' puts x.to_yaml # --- # hello: world # :this: # apple: 4 # :tastes: delicious STDERR.puts "Oops! You broke it!" favorite = "Superman" printf "Who is your favorite hero [Superman]/Batman/Wonder Woman?" input = gets.chomp favorite = input unless input.empty? require 'highline/import' favorite = ask("Who is your favorite hero Superman/Batman/Wonder Woman?") {|question| question.in = ["Superman", "Batman", "Wonder Woman"] question.default = "Superman" } editor = "sublime" # your preferred editor here exec "#{editor} #{RbConfig.method(:ruby).source_location[0]}" require 'mkmf' MakeMakefile::Logging.instance_variable_set(:@log, File.open(File::NULL, 'w')) executable = MakeMakefile.find_executable('clear') # or whatever executable you're looking for
module Gsa18f class EventFields def initialize(event = nil) @event = event end def relevant default end private attr_reader :event def default [ :duty_station, :supervisor_id, :title_of_event, :event_provider, :type_of_event, :cost_per_unit, :start_date, :end_date, :purpose, :justification, :link, :instructions, :free_event, :nfs_form, :travel_required, :estimated_travel_expenses ] end end end
class CreateCartSelections < ActiveRecord::Migration[6.0] def change create_table :cart_selections do |t| t.integer :cart_id t.integer :product_id end end end
class ItunesMusicGrazer extend GrazerBase def self.section_url; 'https://itunes.apple.com/gb/collection/pre-orders/id1?fcId=303241591' end def self.get_platform; 'MP3 Download' end def self.get_product_data(url) page = get_page(url) page.at('li.expected-release-date span.label').remove { title: extract_title(page.at('.title').text), platform: get_platform, creator: page.search('.header-breadcrumb li').last.text, variation: check_variation(page.at('.title').text), image: page.at('div.artwork img').attr('src-swap-high-dpi'), release_date: page.at('li.expected-release-date').text, asin: page.at('div.multi-button button').attr('adam-id'), price: extract_price(page.at('span.price').text), url: url, description: get_track_listing(page) } end def self.get_track_listing(page) rows = page.at('.tracklist-table.content').search('tr.song') output = rows.each_with_object([]) do |row, output| row.at('span.badges').remove if row.at('span.badges') index = row.at('.index').text.strip name = row.at('.name').text.strip output << "#{index}\t#{name}" end output.join("\n") end def self.check_variation(title) 'Deluxe' if title.downcase[/\(deluxe\)/] end def self.get_summary_data(limit=1) agent.user_agent = 'iTunes/10.3.1 (Macintosh; Intel Mac OS X 10.6.8) AppleWebKit/533.21.1' page_url = section_url # Start on the first page summary_data = [] #limit.times do page = get_page(page_url) # Find all product divs and extract their data page.search('div.lockup.small.detailed.option').each do |p| summary_data << extract_summary_data(p) end # Set page_url to the next page before the next iteration of the loop # If no link is found, then we're finished #next_link = page.at('.paging-arrow a') #next_link ? # page_url = URI.join(PLAY_URL, next_link.attr('href')).to_s : # break #end summary_data end def self.extract_summary_data(prod) prod.at('li.expected-release-date span.label').try(:remove) release_date = prod.at('li.expected-release-date') || prod.at('li.release-date') { url: prod.at('a.artwork-link').attr('href'), price: extract_price(prod.at('span.price').text), release_date: release_date.text, asin: prod.attr('adam-id'), title: extract_title(prod.at('li.name').text), image: prod.at('div.artwork img').attr('src-swap-high-dpi'), #artist: p.at('li.artist').text, } end end
# frozen_string_literal: true module Api::V1::Admin::Videos class ShowAction < ::Api::V1::BaseAction step :authorize step :validate, with: 'params.validate' try :find, catch: Sequel::NoMatchingRow private def find(input) ::Video.with_pk!(input.fetch(:id)) end end end
require 'gds_api/test_helpers/content_api' module SpecialistSectorHelper include GdsApi::TestHelpers::ContentApi def stub_specialist_sectors oil_and_gas = { slug: 'oil-and-gas', title: 'Oil and Gas' } sector_tags = [ oil_and_gas, { slug: 'oil-and-gas/wells', title: 'Wells', parent: oil_and_gas }, { slug: 'oil-and-gas/fields', title: 'Fields', parent: oil_and_gas }, { slug: 'oil-and-gas/offshore', title: 'Offshore', parent: oil_and_gas } ] distillation = { slug: 'oil-and-gas/distillation', title: 'Distillation', parent: oil_and_gas } content_api_has_draft_and_live_tags(type: 'specialist_sector', live: sector_tags, draft: [distillation]) end def stub_content_api_tags(document) artefact_slug = RegisterableEdition.new(document).slug tag_slugs = document.specialist_sectors.map(&:tag) # These methods are located in gds_api_adapters stubbed_artefact = artefact_for_slug_with_a_child_tags('specialist_sector', artefact_slug, tag_slugs) content_api_has_an_artefact(artefact_slug, stubbed_artefact) end def select_specialist_sectors_in_form select 'Oil and Gas: Wells', from: 'Primary specialist sector' select 'Oil and Gas: Offshore', from: 'Additional specialist sectors' select 'Oil and Gas: Fields', from: 'Additional specialist sectors' select 'Oil and Gas: Distillation (draft)', from: 'Additional specialist sectors' end def assert_specialist_sectors_were_saved assert has_css?('.flash.notice') click_on 'Edit draft' assert_equal 'oil-and-gas/wells', find_field('Primary specialist sector').value assert_equal ['oil-and-gas/offshore', 'oil-and-gas/fields', 'oil-and-gas/distillation'].to_set, find_field('Additional specialist sectors').value.to_set end def save_document click_button 'Save' end def create_document_tagged_to_a_specialist_sector create(:published_publication, :guidance, primary_specialist_sector_tag: 'oil-and-gas/wells', secondary_specialist_sector_tags: ['oil-and-gas/offshore', 'oil-and-gas/fields'] ) end def check_for_primary_sector_in_heading assert find("article header").has_content?("Oil and gas") end def check_for_sectors_and_subsectors_in_metadata ['Oil and gas', 'Wells', 'Offshore', 'Fields'].each do |sector_name| assert has_css?('dd', text: sector_name, exact: false) end end def check_for_absence_of_draft_sectors_and_subsectors_in_metadata refute has_css?('dd', text: 'Distillation', exact: false) end end World(SpecialistSectorHelper)
class CrimeWitnessesController < ApplicationController before_action :set_crime_witness, only: [:show, :edit, :update, :destroy] # GET /crime_witnesses # GET /crime_witnesses.json def index @crime_witnesses = CrimeWitness.all end # GET /crime_witnesses/1 # GET /crime_witnesses/1.json def show end # GET /crime_witnesses/new def new @crime_witness = CrimeWitness.new end # GET /crime_witnesses/1/edit def edit end # POST /crime_witnesses # POST /crime_witnesses.json def create @crime_witness = CrimeWitness.new(crime_witness_params) puts("start new") puts(params[:crime_id]) puts(@crime_witness.witness_id) @crime_witness.crime_id = params[:crime_id] puts("debug") @crime = Crime.where(id:@crime_witness.crime_id).first respond_to do |format| if @crime_witness.save format.html { redirect_to @crime, notice: 'Testigo añadido con éxito.' } format.json { render :show, status: :created, location: @crime_witness } else format.html { render :new } format.json { render json: @crime_witness.errors, status: :unprocessable_entity } end end end # PATCH/PUT /crime_witnesses/1 # PATCH/PUT /crime_witnesses/1.json def update respond_to do |format| if @crime_witness.update(crime_witness_params) format.html { redirect_to @crime_witness, notice: 'Testigo actualizado con éxito.' } format.json { render :show, status: :ok, location: @crime_witness } else format.html { render :edit } format.json { render json: @crime_witness.errors, status: :unprocessable_entity } end end end # DELETE /crime_witnesses/1 # DELETE /crime_witnesses/1.json def destroy @crime_witness.destroy respond_to do |format| format.html { redirect_to crime_witnesses_url, notice: 'Testigo eliminado con éxito.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_crime_witness @crime_witness = CrimeWitness.find(params[:id]) end # Only allow a list of trusted parameters through. def crime_witness_params params.fetch(:crime_witness, {}).permit(:witness_id,:crime_id, :relato) end end
class User < ActiveRecord::Base include ActiveModel::ForbiddenAttributesProtection has_many :participants has_many :kringles, through: :participants has_many :managed_kringles, class_name: "Kringle", as: :kringlehead rolify # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :role_ids, :as => :admin attr_accessible :name, :email, :password, :password_confirmation, :remember_me end
class WebhookAuthorization pattr_initialize :provided_auth_key def authorize ensure_auth_key_is_defined_in_production return true unless expected_auth_key provided_auth_key == expected_auth_key end private def ensure_auth_key_is_defined_in_production if Rails.env.production? && !expected_auth_key raise "WEBHOOK_KEY must be configured in production. Please see README." end end def expected_auth_key ENV["WEBHOOK_KEY"] end end
class Minimap attr_accessor :position def initialize(map) @map = map @map_data = [] @width = 0 @height = 0 @position = Omega::Vector3.new(0, 0, 10_000) @frame = 0 @block_size = 3 update_map_data([]) end def update(entities) if @frame % 3 == 0 update_map_data(entities) end @frame += 1 end def draw x = 0 y = 0 @position.x = Omega.width - @width * @block_size - 10 @position.y = 10 Gosu.draw_rect(@position.x, @position.y, @width*@block_size, @height*@block_size, Gosu::Color::WHITE, @position.z) @map_data.each do |md| color = ((md == 0) ? nil : Gosu::Color.new(200, 0, 0, 0)) color = ((md == 2) ? Gosu::Color.new(255, 255, 0, 0) : color) color = ((md == 3) ? Gosu::Color.new(255, 0, 255, 0) : color) Gosu.draw_rect(@position.x + x, @position.y + y, @block_size, @block_size, color, @position.z) if color x += @block_size if x/@block_size >= @width x = 0 y += @block_size end end end def update_map_data(entities) @map_data = [] @width = @map.width / @map.tile_size @height = @map.height / @map.tile_size for y in 0...@height for x in 0...@width tile = @map.tile_at("solid", x, y) if tile and tile.type == "solid" @map_data << 1 else @map_data << entities_at(entities, x, y) end end end end def entities_at(entities, x, y) entities.each do |e| tpos = Omega::Vector2.new(((e.x - e.width_scaled*e.origin.x)/@map.tile_size).to_i, (e.y/@map.tile_size - 1).to_i) if tpos.x == x and tpos.y == y if e.is_a? ChaosPenguin return 2 else return 3 end end end return 0 end end
Rails.application.routes.draw do namespace 'auth', defaults: { business: 'auth' } do controller :sign do match :sign, via: [:get, :post] get 'sign/token' => :token post 'sign/mock' => :mock post 'sign/code' => :code post :login get :logout end scope :password, controller: :password, as: 'password' do get 'forget' => :new post 'forget' => :create scope as: 'reset' do get 'reset/:token' => :edit post 'reset/:token' => :update end end scope :auth, controller: :oauths, as: 'oauths' do match ':provider/callback' => :create, via: [:get, :post] match ':provider/failure' => :failure, via: [:get, :post] end resources :users, only: [:index, :show] namespace :admin, defaults: { namespace: 'admin' } do resources :oauth_users resources :user_tags do resources :user_taggeds do collection do delete '' => :destroy get :search end end end end namespace :panel, defaults: { namespace: 'panel' } do resources :users do get :panel, on: :collection member do post :mock get 'user_tags' => :edit_user_tags patch 'user_tags' => :update_user_tags end end resources :accounts resources :oauth_users resources :authorized_tokens end namespace :my, defaults: { namespace: 'my' } do resource :user end namespace :board, defaults: { namespace: 'board' } do resource :user resources :accounts do member do post :token post :confirm put :select end end resources :oauth_users do collection do get :bind end end end end end
# frozen_string_literal: true ActiveAdmin.register CourseCategory do permit_params :name menu parent: 'Corsi' filter :name index do selectable_column id_column column :name actions end show do |_category| attributes_table do row :id row :name end end form do |f| f.inputs t('activeadmin.course_category.panels.details') do f.input :name end f.actions end controller do rescue_from ActiveRecord::DeleteRestrictionError do flash[:error] = t('activeadmin.course_category.destroy.restricted') redirect_to :back end end end
# # Cookbook Name:: newznab # Recipe:: default # # Copyright 2012, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # newznab_download_url = "http://www.newznab.com/newznab-#{ node.newznab.version }.zip" if node.os == 'linux' if node.platform == 'ubuntu' package 'unzip' user node.newznab.user do shell '/bin/bash' manage_home true comment 'newznab' home node.newznab.home system true supports :manage_home => true end remote_file '/tmp/newznab.zip' do source newznab_download_url owner 'root' group 'root' mode '0600' end directory "/tmp/newznab" do action :delete recursive true end execute "unzip /tmp/newznab.zip -d /tmp/newznab" do creates '/tmp/newznab' end execute "mv /tmp/newznab/newznab-#{ node.newznab.version }/* #{ node.newznab.home }" do user node.newznab.user group node.newznab.user creates "#{ node.newznab.home }/www" end end end
# encoding: UTF-8 module API module V1 class UsersMe < API::V1::Base helpers API::Helpers::V1::UsersHelpers helpers API::Helpers::V1::SharedParamsHelpers helpers API::Helpers::V1::SharedServiceActionsHelpers before do authenticate_user end namespace :users do namespace :me do desc 'Flag notification as read' put '/notifications/:id' do notification = current_user.notifications.unread.find_by(id: params[:id]) if notification.try(:mark_as_read) status 204 else status 403 end end params do requires :fb_access_token end desc 'Connect facebook account with current user system account' put :connect_fb do service = execute_service('Users::FacebookLinkService', current_user, params) simple_response_for_service(service) end desc 'Disconnect facebook account from current user system account' put :desconnect_fb do service = execute_service('Users::FacebookUnlinkService', current_user, params) simple_response_for_service(service) end desc 'Update user data' params do requires :user, type: Hash end put do service = execute_service('Users::UpdateService', current_user, current_user, params) options = { serializer: :current_user, # this will use the same representation in cache if nothing changes to render response cache_key: 'current_user.show', cache_replace_data: { user_id: service.user.try(:id) } } response_for_update_service(service, :user, options) end desc 'Updates user profile picture' put :picture do service = execute_service('Users::ProfileImageUpdateService', current_user, current_user, params) response_for_update_service(service, :user) end namespace :learning_cycles do params do use :new_learning_cycle end post do new_learning_cycle_service_response(current_user, params) end route_param :id do params do use :new_learning_track end post :learning_tracks do params[:learning_track].merge!(learning_cycle_id: params[:id]) new_learning_track_service_response(current_user, params) end end end namespace :gallery do desc 'Upload file to slide (and save in user gallery)' params do use :new_file_upload end post :upload do metadata_filter = array_values_from_params(params, :metadata_attributes) || [] options = { meta: { attributes_whitelist: metadata_filter } } user_gallery_new_file_upload_service_response(current_user, params, options) end namespace :assets do route_param :id do delete do album = current_user.default_gallery_album if album asset = album.photos.find_by(id: params[:id]) service = execute_service('UserGalleries::AssetDeleteService', asset, current_user, params) response_for_delete_service(service, :photo, serializer: :simple_user_gallery_asset) else not_found_error_respomse(:gallery_album) end end end end end end end end end end
class Cocktail < ActiveRecord::Base belongs_to :user has_many :comments validates :title, presence: true validates :ingredients, presence: true validates :recipe, presence: true end
require 'elasticsearch' namespace :elasticsearch do es = Elasticsearch::Client.new Tripgraph::Application.config.elasticsearch desc "Delete all elasticsearch indices" task reset: :environment do es.indices.delete index: '_all' end end
require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "invalid signup information" do get signup_path # Not necessary, included for clarity. Also ensures signup form renders properly assert_select 'form[action="/signup"]' # Ensures the url being posted to is correct assert_no_difference "User.count" do post signup_path, params: { user: { name: "", email: "test@invalid", password: "foo", password_confirmation: "bar" } } end assert_template 'users/new' # Checks that failed submission re-renders the new action assert_select 'div#error_explanation' # CSS id for error explanation assert_select 'div.alert' # CSS class for field with error end test "valid signup information" do get signup_path assert_select 'form[action="/signup"]' assert_difference "User.count", 1 do post users_path, params: { user: { name: "Test Tester", email: "ex@example.com", password: "test123", password_confirmation: "test123" } } end follow_redirect! assert_template 'users/show' # Checks that the succesful submission renders the show template assert is_logged_in? # Ensure that the new user is logged in after signup assert_not flash.empty? # Ensures the the flash success message is not empty end end
class Api::V1::MealsController < Api::V1::BaseController skip_before_action :verify_authenticity_token def index @user = current_user @meals = current_user.meals.order(created_at: :desc) end def show @meal = Meal.find(params[:id]) end def create @meal = Meal.new(meal_params) @dish = Dish.find(params[:dish_id]) @user = current_user @meal.user = @user @meal.dish = @dish unless params[:quantity] <= 0 if @meal.save render :index, status: :created else render_error end end end private def meal_params params.require(:meal).permit(:quantity, :user_id, :dish_id) end # params.require(:booking).permit(:user_id, :start_time, :end_time, :total_price) def render_error render json: { errors: @meal.errors.full_messages }, status: :unprocessable_entity end end
# frozen_string_literal: true module ContactsHelper # @param dob [Date] def format_dob(dob) dob&.strftime '%Y %B %e' end def error_list(contact) content_tag :ol, class: 'list-group list-group-numbered' do contact.error_list.split("\n").map do |error| content_tag(:li, error, class: 'list-group-item') end.reduce(&:+) end end end
class SpMarketCap < ActiveRecord::Base def self.get_mkt_caps start_date = SpMarketCap.all.map(&:date).max || Date.new(2006,9,29) # start with end months search_dates = (start_date..(Date.today - 1.day)).map { |date| [(Date.today - 1.day), date.end_of_month].min }.uniq search_dates.each do |d| puts "Getting market cap for #{d.strftime("%F")}..." # process data csv, date = SpMarketCap.get_mc_csv_data(d) mkt_cap = csv.find { |row| row[0] == "Total Net Assets"} # create entry for this month if mkt_cap.blank? puts "Couldn't parse for #{date.strftime("%Y-%m-%d")}..." SpMarketCap.create(date: date, mkt_cap: 0) else # scrub commas out of mkt_cap and save SpMarketCap.create(date: date, mkt_cap: mkt_cap[1].gsub(",","")) end end end def self.get_mc_csv_data(date) require 'open-uri' require 'csv' i = 0 as_of = "" while i < 10 && as_of.blank? # loop back through dates until date includes data (stop at 10 loops to make sure to avoid infinite loops) base_url = "https://www.blackrock.com/us/individual/products/239726/ishares-core-sp-500-etf/1464253357814.ajax?fileType=csv&fileName=IVV_holdings&dataType=fund&asOfDate=" # set url d = date.strftime("%Y%m%d") url = base_url + d # get csv data url_data = open(url).read() csv = CSV.parse(url_data) as_of = csv.find { |row| row[0] == "Fund Holdings as of" }[1] # increment i and date if as_of.blank? date = date - 1.day i += 1 end end return csv, date end def self.get_mkt_caps_date(date) require 'open-uri' require 'csv' url = "https://www.blackrock.com/us/individual/products/239726/ishares-core-sp-500-etf/1464253357814.ajax?fileType=csv&fileName=IVV_holdings&dataType=fund&asOfDate=#{date.strftime("%Y%m%d")}" url_data = open(url).read() csv = CSV.parse(url_data) date_check = csv.find { |row| row[0] == "Fund Holdings as of" }[1].blank? if date_check prev = SpMarketCap.find_by(date: date - 1.day) SpMarketCap.create(date: date, mkt_cap: prev.mkt_cap) else mkt_cap = csv.find { |row| row[0] == "Total Net Assets"} if mkt_cap.blank? puts "Couldn't parse for #{date.strftime("%Y-%m-%d")}" SpMarketCap.create(date: date, mkt_cap: 0) else # scrub commas out of mkt_cap and save SpMarketCap.create(date: date, mkt_cap: mkt_cap[1].gsub(",","")) end end end end
class OrdersController < ApplicationController before_action :move_to_order, except: [:index] before_action :set_item, only: [:index, :new, :create] before_action :authenticate_user!, expect: [:index] before_action :redirect_to_root, only: [:index] def index end def new @Purchase = OrderPurchase.new end def create @Purchase = OrderPurchase.new(order_params) if @Purchase.valid? pay_item @Purchase.save return redirect_to root_path else render 'index' end end private def set_item @item = Item.find(params[:item_id]) end def move_to_order unless user_signed_in? redirect_to action: :index end end def redirect_to_root @item = Item.find(params[:item_id]) if current_user.id == @item.user_id redirect_to root_path end end def order_params params.permit(:price, :token, :post_code, :prefecture_code_id, :city, :house_number, :building_name, :phone_number, :purchase_id, :item_id).merge(user_id: current_user.id) end def pay_item Payjp.api_key = ENV["PAYJP_SECRET_KEY"] # PAY.JPテスト秘密鍵 # binding.pry Payjp::Charge.create( amount: @item.selling_price, # 商品の値段 card: order_params[:token], # カードトークン currency:'jpy' # 通貨の種類(日本円) ) end end
# Deaf Grandma Program SI Homework # Julia Les 5/03/16 # Prompt: Write a Deaf Grandma program. Whatever you say to grandma # (user input) she should respond with HUH?!, SPEAK UP SONNY!, # unless you shout it (type in all CAPS). If you shout, she can hear # you and yells back NO, NOT SINCE 1938! Grandma should shout a different # year each time; random between 1930 to 1980. You can’t stop talking to # grandma until you shout BYE. # Add on to the above. Grandma really loves your company and doesn’t want # you to go unless you shout BYE three times in a row. So if you say BYE # twice and then something else you have to say BYE three times again. def deaf_grandma puts "What do you say to Grandma?" bye_count = 0 while bye_count < 3 you_say = gets.chomp if you_say == "BYE" puts "NO, NOT SINCE #{rand(1930..1980)}!" bye_count += 1 elsif you_say == you_say.upcase puts "NO, NOT SINCE #{rand(1930..1980)}!" bye_count = 0 else puts "HUH?!, SPEAK UP SONNY!" bye_count = 0 end end end
class NotesController < ApplicationController before_action :set_note, only: [:show, :edit, :update, :destroy] # GET /notes # GET /notes.json def index @notes = Note.all end def new_import @note = Note.new end def import begin Note.sanitize_html(Note.import(params[:note][:import_file], current_user)).save redirect_to current_user rescue => exception redirect_to import_new_path, locals: exception end end # GET /notes/1 # GET /notes/1.json def show raise ActionController::RoutingError.new('Not Found') if (@note.is_private && @note.user != current_user) @endorsements = @note.sort_endorsements @buttons_visible = !current_user.blank? @upvote_btn = @note.should_show_upvote_btn(current_user) @vote = Vote.find_by(user_id: current_user.id, note_id: @note.id) unless current_user.blank? end # GET /notes/new def new @note = Note.new @skills = Skill.all.map(&:name) end # GET /notes/1/edit def edit @skills = Skill.all.map(&:name) end # POST /notes # POST /notes.json def create @note = Note.new(note_params) @note.user_id = current_user.id create_skills respond_to do |format| if @note.save format.html { redirect_to current_user } format.json { render :show, status: :created, location: @note } else format.html { render :new } format.json { render json: @note.errors, status: :unprocessable_entity } end end end # PATCH/PUT /notes/1 # PATCH/PUT /notes/1.json def update create_skills respond_to do |format| if @note.update(note_params) format.html { redirect_to @note } format.json { render :show, status: :ok, location: @note } else format.html { render :edit } format.json { render json: @note.errors, status: :unprocessable_entity } end end end # DELETE /notes/1 # DELETE /notes/1.json def destroy @note.destroy respond_to do |format| format.html { redirect_to current_user } format.json { head :no_content } end end def upvote @note = Note.friendly.find(params[:note_id]) Vote.create(note_id: @note.id, is_upvote?: true, user_id: current_user.id) redirect_to @note end private def create_skills skill_names = params[:note][:skills].split(',') return if skill_names == @note.skills.map(&:name) || skill_names.blank? @note.noteskills.destroy_all skill_names.each do |skill_name| ::Noteskill.create(note: @note, skill: Skill.find_by(name: skill_name)) end end def set_note @note = Note.friendly.find(params[:id]) end def note_params params.require(:note).permit(:body, :title, :subtitle, :image_url, :comments_disabled, :is_private) end end
require 'openssl' require 'base64' require File.dirname(__FILE__) + '/version' class SignedParams class NoKey < RuntimeError; end class Tampered < RuntimeError; end DEFAULT_DIGEST_PROC = Proc.new do | signer, payload | raise NoKey, "Please define a salt with SignedParams.salt = something" unless signer.salt digest_type = 'SHA1' OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest_type), signer.salt, payload) end # Options for url_for that will be exempt from affecting the signature CLEAR_OPTIONS = %w(sig controller action only_path) module ControllerInstanceMethods protected # Returns the same result as the one url_for does but also signs the parameters def signed_url_for(options) canonical_options = rewrite_options(options) canonical_options[:controller] ||= controller_path SignedParams.sign!(canonical_options) url_for(canonical_options) end end module ControllerClassMethods # A class call to define a filter that checks for the signed parameters # require_signed_parameters :only => [:send_confidential_email] def require_signed_parameters(*filter_options) before_filter(*filter_options) do | c | begin SignedParams.verify!(c.params) rescue SignedParams::Tampered c.logger.error "Request parameters possibly tampered!" c.send(:render, :status => 404, :text => "No such page") false end end end end ActionController::Base.send(:include, ControllerInstanceMethods) ActionController::Base.send(:extend, ControllerClassMethods) ActionController::Base.send(:helper_method, :signed_url_for) class << self attr_accessor :salt, :digest # Should return the proc used for digest generation def digest @digest ||= DEFAULT_DIGEST_PROC end # Compute the checksum of the hash and save it into the :sig slot. The signature also gets returned. def sign!(ha) ha[:sig] = compute_checksum(ha) end # Check a signed hash for authenticity def verify!(ha) passed_signature = ha[:sig] || ha["sig"] raise Tampered, "No signature given" unless passed_signature raise Tampered, "Checksum differs" unless compute_checksum(ha) == passed_signature.to_s true end private # Compute the cheksum of a hash in such a way that the checksum of it's options # in textual form stays the same independently of where the hash came from. # Considering that the keys in Ruby hashes are unordered this is non-trivial to guarantee def compute_checksum(h) begin signed_h = h.dup.with_indifferent_access CLEAR_OPTIONS.map{|o| signed_h.delete(o) } marshaled = ActionController::Routing::Route.new.build_query_string(signed_h) marshaled = marshaled.gsub(/^\?/, '').split(/&/).sort.join('&') digest.call(self, Base64.encode64(marshaled.to_s.reverse)).to_s ensure end end end # SignedParams end
require 'cgi' class UserMailer < ActionMailer::Base def welcome_email recipients "rajakuraemas@gmail.com" from "[qTiest]Welcome Notification<notifications@example.com>" subject "Welcome to My Awesome Site" sent_on Time.now end end
class PostsController < ApplicationController before_action :logged_in_user, only: [:new, :create] def new @post = Post.new end def create @post = Post.new(user_params) @post.name = @current_user.name @post.user_id = @current_user.id if @post.save flash[:success] = "Post created successfully" redirect_to posts_path else flash.now[:danger] = 'Post failed to save' render :new end end def index @posts = Post.all end private def user_params params.require(:post).permit(:subject,:body, :name) end # Redirects to login_url if not logged in def logged_in_user unless logged_in? flash[:danger] = "Please log in" redirect_to login_url end end end
class FeedbacksController < ApplicationController def index @feedbacks = Feedback.order('id DESC').paginate page: params[:page], per_page: 30 end end
class Itemtag < ApplicationRecord has_many :template_taggings, dependent: :destroy has_many :templates, through: :template_taggings def associate_with(template_id) TemplateTagging.upsert(template_id: template_id, itemtag_id: self.id) end def self.create_from_tag_string(tag_string) p tag_string Itemtag.create( name: tag_string, display_name: Parsers::ItemtagParser.tag_display_name(tag_string), description: "This tag was autogenerated" ) end end
module Bootcamp class TimeFormatter attr_reader :seconds def initialize(seconds) @seconds = seconds end def format_time hours = seconds / 3600 minutes = (seconds - (hours * 3600)) / 60 remaining_seconds = seconds - (hours * 3600) - (minutes * 60) hours_part = '' hours_part = case hours when 0 '' when 1 hours.to_s + ' hour' else hours.to_s + ' hours' end minutes_part = '' minutes_part = case minutes when 0 '' when 1 minutes.to_s + ' minute' else minutes.to_s + ' minutes' end seconds_part = '' seconds_part = case remaining_seconds when 0 '' when 1 remaining_seconds.to_s + ' second' else remaining_seconds.to_s + ' seconds' end hours_part + (hours > 0 && minutes > 0 ? ', ' : '') + minutes_part + (minutes > 0 && remaining_seconds > 0 ? ' and ' : '') + seconds_part end end end
require 'helper_frank' module Rdomino describe 'Session' do it 'raises Exeption when already connected' do assert_raises Error::AlreadyConnected do Rdomino.connect :user => 'Global' end end end end
module BackpackTF # Base class for accessing a BackpackTF API class Interface class << self attr_reader :format, :callback, :appid, :name, :version end @format = 'json' @callback = nil @appid = '440' # @param options [Hash] # @option options [String] :format The format desired. Defaults to 'json'. # @option options [String] :callback JSONP format only, used for function # call. Defaults to `nil`. # @option options [String] :appid The ID of the game. Defaults to '440'. # @return [Hash] default options def self.defaults(options = {}) @format = options[:format] || 'json' @callback = options[:callback] || nil @appid = options[:appid] || '440' end # @return [String] URL fragment, ie: `/IGetPrices/v4/?` def self.url_name_and_version "/#{name}/v#{version}/?" end end end
control "open-development-environment-devbox-script-networking" do title "open-development-environment-devbox-script-networking control" describe file("/etc/network/interfaces") do it { should exist } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } it { should be_readable.by_user('root') } its('mode') { should cmp '0644' } its('content') { should match('pre-up sleep 2') } end end
class IngredientSerializer < ActiveModel::Serializer belongs_to :category has_many :recipes, through: :recipe_ingredients has_many :recipe_ingredients attributes :id, :name, :description, :category_id, :vegan, :image end
# This vagrantfile creates a VM that is capable of running Fabric Workshop sample network Vagrant.require_version ">= 1.7.4" Vagrant.configure('2') do |config| config.vm.box = "bento/ubuntu-20.04" config.vm.hostname = "fabric-workshop" config.vm.synced_folder "..", "/home/vagrant/fabric" config.ssh.forward_agent = true config.vm.provider :virtualbox do |vb| vb.name = "fabric-workshop" vb.cpus = 4 vb.memory = 8192 end config.vm.provision :shell, name: "essentials", path: "essentials.sh" config.vm.provision :shell, name: "docker", path: "docker.sh" config.vm.provision :shell, name: "jdk", path: "java.sh" config.vm.provision :shell, name: "nodeJs", path: "nodeJs.sh" config.vm.provision :shell, name: "fabric", path: "fabric.sh" config.vm.provision :shell, name: "limits", path: "limits.sh" end
class UsersController < ApplicationController layout 'apps' before_filter :admin_required, :except => :waitlist def index respond_to do |format| format.html # index.html.erb (no data required) format.ext_json { pagination_state = update_pagination_state_with_params!(:app) @users = User.find(:all, options_from_pagination_state(pagination_state).merge(options_from_search(:app))) render :json => @users.to_ext_json(:class => :user, :count => User.count, :ar_options => {:only => [:login, :email, :created_at, :id, ], } ) } end end # render new.rhtml def new end # render new.rhtml def edit @user = User.find(params[:id]) end # POST /users def create #cookies.delete :auth_token ## protects against session fixation attacks, wreaks havoc with ## request forgery protection. ## uncomment at your own risk ## reset_session @user = User.new(params[:user]) @user.save if @user.errors.empty? #self.current_user = @user #redirect_back_or_default('/') flash[:notice] = 'User was successfully created.' redirect_to users_path else render :action => 'new' end end # PUT /users/1 def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) flash[:notice] = 'User was successfully updated.' redirect_to users_path else render :action => 'edit' end end # DELETE /users/1 def destroy @user = User.find(params[:id]) @user.destroy respond_to do |format| format.js { head :ok } end rescue respond_to do |format| format.js { head :status => 500 } end end end
# frozen_string_literal: true module Decidim module Opinions # A module with all the gallery common methods for opinions # and collaborative draft commands. # Allows to create several image attachments at once module GalleryMethods include ::Decidim::GalleryMethods private def gallery_allowed? @form.current_component.settings.attachments_allowed? end end end end
class V1::BaseAPI < Grape::API AUTH_HEADER_DESCRIPTION = { 'X-Hoshino-Api-Key' => { description: 'API認証キーを設定', required: true } } rescue_from Grape::Exceptions::ValidationErrors do |e| error_response(message: e.message, status: 400) end end
# from https://gist.github.com/1258681 # # your config.ru # require 'unicorn_killer' # use UnicornKiller::MaxRequests, 1000 # use UnicornKiller::Oom, 400 * 1024 module UnicornKiller module Kill def quit sec = (Time.now - @process_start).to_i warn "#{self.class} send SIGQUIT (pid: #{Process.pid})\talive: #{sec} sec" Process.kill :QUIT, Process.pid end end class Oom include Kill def initialize(app, memory_size= 512 * 1024, check_cycle = 16) @app = app @memory_size = memory_size @check_cycle = check_cycle @check_count = 0 end def rss `ps -o rss= -p #{Process.pid}`.to_i end def call(env) @process_start ||= Time.now if (@check_count += 1) % @check_cycle == 0 @check_count = 0 quit if rss > @memory_size end @app.call env end end class MaxRequests include Kill def initialize(app, max_requests = 1000) @app = app @max_requests = max_requests end def call(env) @process_start ||= Time.now quit if (@max_requests -= 1) == 0 @app.call env end end end
module FacilitiesManagement::Beta::Supplier::SupplierAccountHelper include FacilitiesManagement::Beta::RequirementsHelper def accepted_page ['accepted', 'live', 'not signed', 'withdrawn'] end def warning_title WARNINGS.each { |status, text| return text if @page_data[:procurement_data][:status] == status.to_s } end def warning_message warning_messages = { 'received': "This contract offer expires on #{format_date_time(@page_data[:procurement_data][:expiration_date])}.", 'accepted': 'Awaiting buyer confirmation of signed contract.', 'declined': "You declined this contract offer on #{format_date_time(@page_data[:procurement_data][:date_responded_to_contract])}.", 'live': "Your contract starts on #{format_date(@page_data[:procurement_data][:initial_call_off_start_date])} and ends on #{format_date(@page_data[:procurement_data][:initial_call_off_end_date])}.", 'not responded': "You did not respond to this contract offer within the required timescales,<br/> therefore it was automatically declined with the reason of 'no response'.", 'not signed': "The buyer has recorded this contract as 'not signed' on #{format_date_time(@page_data[:procurement_data][:date_contract_closed])}. <br> The contract offer has therefore been closed.", 'withdrawn': "The buyer withdrew this contract offer and closed this procurement on <br/> #{format_date_time(@page_data[:procurement_data][:date_contract_closed])}." } warning_messages.each { |status, text| return text if @page_data[:procurement_data][:status] == status.to_s } end WARNINGS = { 'received': 'Received contract offer', 'accepted': 'Accepted', 'live': 'Accepted and signed', 'declined': 'Declined', 'not responded': 'Not responded', 'not signed': 'Not signed', 'withdrawn': 'Withdrawn' }.freeze end
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__)) + '/lib/' require 'knife-table/version' Gem::Specification.new do |s| s.name = 'knife-table' s.version = KnifeTable::VERSION.version s.summary = 'Help chef set and serve the table' s.author = 'Chris Roberts' s.email = 'chrisroberts.code@gmail.com' s.homepage = 'http://github.com/heavywater/knife-table' s.description = "Chef's table" s.require_path = 'lib' s.files = Dir.glob('**/*') s.add_dependency 'knife-spork', '>= 0.1.11' s.add_dependency 'hub', '>= 1.10.1' s.add_dependency 'foodcritic', '>= 1.4.0' end
# frozen_string_literal: true require 'savon' client = Savon.client(wsdl: 'http://www.learnwebservices.com/services/hello?WSDL') response = client.call( :say_hello, soap_action: '', message: { 'HelloRequest' => { 'Name' => 'John Doe' } } ) puts response.body[:say_hello_response][:hello_response][:message] # Hello John Doe!
name 'elasticsearch' maintainer 'Thomas Cate' maintainer_email 'tcate@chef.io' license 'MIT license' description 'Installs/Configures elasticsearch' long_description 'Installs/Configures elasticsearch' version '0.0.3' depends 'apt', '~> 4.0.2'
class MobileDevice < ActiveRecord::Base belongs_to :user validates_presence_of :gcm_token validates_uniqueness_of :gcm_token, :scope => :user end
require 'jump_in/authentication' module JumpIn module Strategies module Session def self.included(klass) klass.register_jumpin_callbacks( on_login: [:set_user_session], on_logout: [:remove_user_session], get_current_user: [:current_user_from_session] ) end def set_user_session(user:, by_cookies:) return nil if by_cookies session[:jump_in_class] = user.class.to_s session[:jump_in_id] = user.id end def remove_user_session session.delete :jump_in_class session.delete :jump_in_id end def current_user_from_session return nil unless session[:jump_in_id] && session[:jump_in_class] klass = session[:jump_in_class].constantize klass.find_by(id: session[:jump_in_id]) end end end end
module TroleGroups module Storage autoload :BaseMany, 'trole_groups/storage/base_many' # autoload :BitMany, 'trole_groups/storage/bit_many' autoload :EmbedMany, 'trole_groups/storage/embed_many' autoload :RefMany, 'trole_groups/storage/ref_many' # autoload :StringMany, 'trole_groups/storage/string_many' class BaseMany < Troles::Common::Storage protected # get matching list of Role instances # @param [Array<Symbol>] list of role names to find Roles for # @return [Array<Role>] references to Role instances def find_rolegroups *rolegroups rolegroup_model.where(:name => rolegroups.flatten).all end # get list of embedded Role instances # @param [Array<Symbol>] list of role names # @return [Array<Role>] Role instances generated def rolegroups_to_embed *rolegroups raise "Must be implemented by embed storage to generate a set of rolegroups to embed" end end end end
module Ironwood class MapDisplay attr_reader :map, :fov, :map_memory, :width, :height def initialize map, width, height @map = map @map_memory = MapMemory.new(map) @width = width @height = height end def player map.mobs.player end def viewport_tiles ((player.fov.actor_y - (height / 2))..(player.fov.actor_y + (height / 2) - 1)).each do |y| next if y < 0 or y >= map.height ((player.fov.actor_x - (width / 2))..(player.fov.actor_x + (width / 2))).each do |x| next if x < 0 or x >= map.width col, row = xy_to_colrow x, y yield x, y, col, row end end end def xy_to_colrow x, y d "#{x},#{y}" if x.nil? or y.nil? return (x - player.fov.actor_x) + (width / 2), (y - player.fov.actor_y) + (height / 2) end def view map_memory.add player.fov lines = [] # first pass, lay down the terrain viewport_tiles do |x, y, col, row| #d "#{x},#{y} -> #{col},#{row}" lines[row] ||= ' ' * width if player.fov.visible?(x, y) lines[row][col] = map.tile(x, y) elsif map_memory.remember?(x, y) lines[row][col] = map_memory.tile(x, y) end end # second pass, add sounds map.sounds_heard_by(player).each do |sound| col, row = xy_to_colrow sound.x, sound.y lines[row][col] = '!' end # third pass, add items map.items_seen_by(player).each do |item| #map.items.each do |item| col, row = xy_to_colrow item.x, item.y lines[row][col] = item.tile end # fourth pass, add mobs map.mobs.each do |mob| if player.fov.visible? mob.x, mob.y col, row = xy_to_colrow mob.x, mob.y next if col < 0 or col >= width or row < 0 or row >= height lines[row][col] = mob.tile end end lines end # dear future peter: sorry about this method def style_map style_map = Dispel::StyleMap.new(height) # first pass, highlight the terrain viewport_tiles do |x, y, col, row| if player.fov.visible?(x, y) style_map.add(["#ffffff", "#000000"], row, [col]) elsif map_memory.remember?(x, y) style_map.add(["#666666", "#000000"], row, [col]) else style_map.add(["#000000", "#000000"], row, [col]) end end # second pass, highlight mobvision map.mobs.each do |mob| next if mob.player? next unless player.fov.visible? mob.x, mob.y viewport_tiles do |x, y, col, row| if mob.fov.visible?(x, y) and map_memory.remember?(x, y) style_map.add([mob.color, '#000000'], row, [col]) end end end # third pass, show sounds map.sounds_heard_by(player).each do |sound| col, row = xy_to_colrow sound.x, sound.y style_map.add([SOUND_COLOR, '#000000'], row, [col]) end # fourth pass, mobs items map.items_seen_by(player).each do |item| col, row = xy_to_colrow item.x, item.y style_map.add([item.color, '#000000'], row, [col]) end # last, show mobs map.mobs.each do |mob| next unless player.fov.visible? mob.x, mob.y col, row = xy_to_colrow mob.x, mob.y style_map.add([mob.color, "#000000"], row, [col]) end style_map end end end # Ironwood
require 'liquid' require 'date' module TackleBox module Email class Template module Tags class Date < Liquid::Tag def render(context) ::Date.today.strftime("%b %e") end end end end end end Liquid::Template.register_tag('date', TackleBox::Email::Template::Tags::Date)
require ('pry') require ('pry-byebug') class KaraokeRoom #Get methods for name attr_reader :name def initialize(name)#Constructor method @name = name @clients = [] #@songs = [] end # Get methods # def get_karaoke_name() # @karaoke_name # end # def get_songs # return @songs.map {|@songs| @songs} # end #End get methods #checks the client array for number of clients def client_count() #binding.pry return @clients.length() end #Adds client to karaoke room - passes a client parameter in def add_client(client) @clients.push(client) end #Removes client def remove_client(client) @clients.delete(client) end #Check total number of client in room by checking size of client array def client_count(client) @clients.size() end end
Sequel.migration do up do run "create index series_register_id_year_idx on series(register_id, date_part('year', time))" end down do alter_table(:series) do drop_index name: 'series_register_id_year_idx' end end end
class StudyScheduleController < ApplicationController def change_page @page = params[:page] @arm = Arm.find params[:arm_id] @protocol = @arm.protocol @tab = params[:tab] @visit_groups = @arm.visit_groups.paginate(page: @page) end def change_tab @protocol = Protocol.find(params[:protocol_id]) @arms_and_pages = {} hash = params[:arms_and_pages] hash.each do |arm_id, page| arm = Arm.find(arm_id) @arms_and_pages[arm_id] = {arm: arm, page: page} end @tab = params[:tab] end def check_row qty = params[:check] == 'true' ? 1 : 0 visits = Visit.where(line_item_id: params[:line_item_id]) visits.update_all(research_billing_qty: qty, insurance_billing_qty: 0, effort_billing_qty: 0) visits.each do |visit| visit.update_procedures qty.to_i, 'research_billing_qty' visit.update_procedures 0, 'insurance_billing_qty' end end def check_column qty = params[:check] == 'true' ? 1 : 0 visits = Visit.where(visit_group_id: params[:visit_group_id]) visits.update_all(research_billing_qty: qty, insurance_billing_qty: 0, effort_billing_qty: 0) visits.each do |visit| visit.update_procedures qty.to_i, 'research_billing_qty' visit.update_procedures 0, 'insurance_billing_qty' end end end
class Encounter < ActiveRecord::Base belongs_to :monster has_many :levels has_many :dungeons, through: :levels def display "#{monster.name} x #{num_enemies} (id::#{id})" end # def self.get_encounter_id_from_display_string(option) option.split("::")[1].gsub(")", "") end # def self.find_by_display_string(display_string) find(get_encounter_id_from_display_string(display_string)) end # def get_difficulty 0.2 + 0.005 * (monster.challenge + 0.5) * num_enemies end end
class Trip < ActiveRecord::Base before_create :generate_code before_validation :geocode_everything belongs_to :owner, class_name: 'User' has_many :users, through: :trip_memberships has_many :trip_memberships, dependent: :destroy has_many :categories, through: :trip_categories has_many :trip_categories, dependent: :destroy has_many :completed_trip_tasks validates_presence_of :title, :description, :start_address, :end_address, :contributors_limit, :start_time, :end_time scope :find_by_code, ->(trip_code) { where(trip_code: trip_code) } scope :upcoming, -> { where('start_time > ?', Time.now) } scope :in_progress, -> { where('? BETWEEN start_time AND end_time ', Time.now) } scope :past, -> { where('start_time < ?', Time.now) } validate :validate_max_members validate :correct_datetime validate :dates_chronological accepts_nested_attributes_for :categories def from_past? start_time < Time.now ? true : false end def without_id self.dup end def self.search(category_ids) if category_ids.present? joins(:trip_categories).where(trip_categories: { category_id: category_ids }) else order("start_time ASC") end end def generate_code begin self.trip_code = SecureRandom.hex(10) end while Trip.exists?(trip_code: trip_code) end private def geocode_everything self.start_latitude, self.start_longitude = Geocoder.coordinates(self.start_address) self.end_latitude, self.end_longitude = Geocoder.coordinates(self.end_address) end def correct_datetime errors.add(:start_time, 'must be a valid datetime') if ((DateTime.parse(start_time.to_s) rescue ArgumentError) == ArgumentError) errors.add(:end_time, 'must be a valid datetime') if ((DateTime.parse(end_time.to_s) rescue ArgumentError) == ArgumentError) end def dates_chronological return if !start_time.present? || !end_time.present? errors.add(:end_time, 'must be later than start date') if (start_time > end_time) end def validate_max_members return unless contributors_limit.present? if self.contributors_limit <= self.trip_memberships.accepted.size errors.add(:contributors_limit, 'Max limit reached!') end end end
# FIXME HACK extension to ActiveRecord::Errors to allow error attributes to be renamed. This is # because otherwise we'll end up producing very confusing error messages complaining about :secret, # :encrypted_secret, and so forth when all the user really cares about is :password. class ActiveRecord::Errors def rename_attribute(original_name, new_name) original_name, new_name = original_name.to_s, new_name.to_s return if original_name == new_name hash = @errors.to_hash.dup hash.each do |attribute, old_errors| if attribute.to_s == original_name original_name = attribute # because some are strings, some are symbols. old_errors.each do |error| new_error = error.dup new_error.attribute = new_name unless @errors[new_name] && @errors[new_name].include?(new_error) @errors[new_name] ||= [] @errors[new_name] << new_error end end @errors.delete(original_name) end end end end class ActiveRecord::Error def ==(other) other.kind_of?(ActiveRecord::Error) && attribute.to_s == other.attribute.to_s && message == other.message end end
class User < ActiveRecord::Base has_many :dogs belongs_to :park has_many :walks, through: :dogs end
class RenameWrongFieldInAddresses < ActiveRecord::Migration def up rename_column :member_addresses, :langitude, :latitude end def down end end
module Oauth class Weibo < Provider def follow(uid) api_access('friendships/create', {'uid' => uid}, 'post') end def publish(content) api_access('statuses/update', {'status'=>content}, 'post') end def fetch_info api_access('users/show',{'uid' => uid}) end def basic_info info && { "name" => info.data["name"], "avatar" => info.data["avatar_hd"] || info.data["avatar_large"], "gender" => info.data["gender"], "location" => info.data["location"], "description" => info.data["description"] } end def api_access(api, http_params, http_method = 'get') return nil if expired? # expired url = 'https://api.weibo.com/2/' + api + '.json' http_params.merge!({"access_token" => access_token}) Oauth::Weibo.request(url, http_params, http_method, 'json') end def refresh info = Oauth::Weibo.postJSON('https://api.weibo.com/oauth2/get_token_info', {access_token: access_token}) if info self.created_at = info["create_at"] user.save! end end class << self def self.authenticate?(access_token, uid) result = postJSON('https://api.weibo.com/oauth2/get_token_info', {access_token: access_token}) if result.try(:[], 'uid').to_i == uid.to_i uid.to_i > 0 else false end end def authorize_url(params = {}) get_params = { 'client_id' => Configure['weibo']['appid'], 'redirect_uri' => Configure['weibo']['callback'], 'response_type' => 'code', 'display' => 'default' # for different divice, default|mobile|wap|client|apponweibo }.merge(params) "https://api.weibo.com/oauth2/authorize?#{URI.encode_www_form(get_params)}"; end def detail_of_code(code) url = 'https://api.weibo.com/oauth2/access_token' post_params = { 'client_id' => Configure['weibo']['appid'], 'client_secret' => Configure['weibo']['secret'], 'grant_type' => 'authorization_code', 'code' => code, 'redirect_uri' => Configure['weibo']['callback'] } response = postJSON(url,post_params) response.delete('remind_in') if response response end end end class WeiboMobile < Weibo; end end
#!/usr/bin/ruby -w require 'mechanize' require 'fileutils' require 'uri' require 'thwait' class SiteDump def initialize(url=nil, use_threads=true) @agent = Mechanize.new unless url.nil? @sitemap = @agent.get(url) end if use_threads @dump_fn = self.method(:dump_t) else @dump_fn = self.method(:dump_n) end end def dump @dump_fn.call end def dump_n urls.each do |url| dump_url(url) end end def dump_t threads = [] urls.each do |url| threads << Thread.new{dump_url(url)} end ThreadsWait.all_waits(*threads) end protected def dump_url(url) dpath = make_dir(url.host, url.path) fpath = File.join(dpath, "index.html") File.open(fpath, 'w') do |file| begin file.write(@agent.get(url).content) puts "url [#{url}] saved to [#{fpath}]" rescue Mechanize::ResponseCodeError => e puts e.inspect FileUtils.rm_rf(dpath) end end end def urls raise "#{__method__} not implemented" end def make_dir(base, path) dpath = File.join(Dir.getwd, "#{base}", path) FileUtils.mkpath(dpath) return dpath end end
# frozen_string_literal: true require 'mondial_relay/translatable' require 'mondial_relay/formattable' require 'mondial_relay/has_defaults' require 'interactor/initializer' module MondialRelay class Operation include MondialRelay::Translatable include MondialRelay::Formattable include MondialRelay::HasDefaults include Interactor::Initializer DEFAULT_SERVICE = :generic class << self attr_reader :operation, :service def configure(operation:, service: nil) @operation = operation @service = service || DEFAULT_SERVICE end end initialize_with :account, :params def run adjusted_response end private def adjusted_params params_with_defaults = add_defaults_to_params(params) formatted_params = format_params(params_with_defaults) translate_params(formatted_params) end def adjusted_response translated_response = translate_response(response) format_response(translated_response) end def response MondialRelay::Query.run(service, operation, account, adjusted_params) end def operation self.class.operation end def service_name self.class.service end def service MondialRelay.services.resolve(service_name) end end end
class Adduniqtodictionary < ActiveRecord::Migration def change change_column :dictionaries,:word,:string,:unique =>true end end
## # Load required libraries require 'soap/wsdlDriver' ## # Monkey patch WSDL parser to stop it moaning module WSDL class Parser def warn(msg) end end end ## # Provide interface to Quova geolocation service module Quova ## # Access details for WSDL description WSDL_URL="https://webservices.quova.com/OnDemand/GeoPoint/v1/default.asmx?WSDL" WSDL_USER = APP_CONFIG['quova_username'] WSDL_PASS = APP_CONFIG['quova_password'] ## # Status codes Success = 0 IPV6NoSupport = 1 InvalidCredentials = 2 NotMapped = 3 InvalidIPFormat = 4 IPAddressNull = 5 AccessDenied = 6 QueryLimit = 7 OutOfService = 10 ## # Create SOAP endpoint @@soap = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver @@soap.options["protocol.http.basic_auth"] << [WSDL_URL, WSDL_USER, WSDL_PASS] ## # Accessor for SOAP endpoint def self.soap @@soap end ## # Class representing geolocation details for an IP address class IpInfo def initialize(ip_address) @ipinfo = Quova::soap.GetIpInfo(:ipAddress => ip_address) end def status @ipinfo["GetIpInfoResult"]["Response"]["Status"].to_i end def country_code @ipinfo["GetIpInfoResult"]["Location"]["Country"]["Name"] end def country_confidence @ipinfo["GetIpInfoResult"]["Location"]["Country"]["Confidence"] end end end
class Review < ApplicationRecord belongs_to :brewery end
########################################################################### ## ## stream_consumer ## ## Multi-threaded HTTP stream consumer, with asynchronous spooling ## and multi-threaded production. ## ## David Tompkins -- 05/30/2013 ## tompkins@adobe_dot_com ## ########################################################################### ## ## Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ########################################################################### require 'http_streaming_client' module StreamConsumer class Consumer include Loggable class InterruptRequest < StandardError; end def initialize(config) HttpStreamingClient.logger = logger @config = config @production_queue = Queue.new end def halt(halt_consumers = true) if halt_consumers then @consumer_threads.each { |thread| thread[:client].interrupt } @consumer_threads.each { |thread| thread.raise InterruptRequest.new "Interrupt Request" } @consumer_threads.each { |thread| thread.join } end @producer_threads.each { |thread| thread.raise InterruptRequest.new "Interrupt Request"} @producer_threads.each { |thread| thread.join } @stats.halt @debug_thread.raise InterruptRequest.new "Interrupt Request" if defined? @debug_thread @debug_thread.join if defined? @debug_thread logger.info "Shutdown (halt) complete: #{Time.new.to_s}" end def produce_messages(thread_id) begin startTime = Time.new logger.info "starting producer #{thread_id} for id #{@run_id}: #{startTime.to_s}" while true job = @production_queue.pop logger.info "producer #{thread_id}:production job accepted: job id #{job.id}, run id #{job.run_id}" now = Time.new @config[:data_producer].produce(thread_id, job.messages) unless @config[:data_producer].nil? @stats.add_produced(job.messages.size) msg = "producer #{thread_id}:#{job.messages.size} messages produced to run id #{job.run_id}, job id #{job.id}" job.clear job = nil elapsed_time = Time.new - now logger.info "#{msg}, production elapsed time: #{elapsed_time} seconds" end logger.info "producer #{thread_id}:shut down complete: #{Time.new.to_s}" logger.info "producer #{thread_id}:total elapsed time: #{(Time.new - startTime).round(2).to_s} seconds" rescue InterruptRequest logger.info "producer #{thread_id}:interrupt requested" logger.info "producer #{thread_id}:shut down complete: #{Time.new.to_s}" logger.info "producer #{thread_id}:total elapsed time: #{(Time.new - startTime).round(2).to_s} seconds" rescue Exception => e logger.error "Production job thread #{thread_id}:Exception:#{e}" end end def debug_threads(interval = 30) begin while true sleep interval logger.info "--debug thread backtrace-----------" @consumer_threads.each do |thread| logger.info "----consumer #{thread[:thread_id]}:" thread.backtrace.each { |line| logger.info line } end @producer_threads.each do |thread| logger.info "----producer #{thread[:thread_id]}:" thread.backtrace.each { |line| logger.info line } end logger.info "----stats thread" @stats.backtrace.each { |line| logger.info line } logger.info "-----------------------------------" end rescue InterruptRequest logger.info "debug_threads:interrupt requested" logger.info "debug_threads:shut down complete: #{Time.new.to_s}" end end def run(&block) @run_id = @config[:run_id] @records_per_batch = @config[:records_per_batch] @min_batch_seconds = @config[:min_batch_seconds] logger.info "-----------------------------------------------------------------" logger.info "url: #{@config.stream_url}" logger.info "run_id: #{@run_id}" logger.info "consumer threads: #{@config[:num_consumer_threads]}" logger.info "producer threads: #{@config[:num_producer_threads]}" logger.info "-----------------------------------------------------------------" @stats = Stats.new(@run_id) @stats.start { |checkpoint| @config[:stats_updater].update(checkpoint) unless @config[:stats_updater].nil? } @producer_threads = (1..@config[:num_producer_threads]).map { |i| Thread.new(i) { |thread_id| Thread.current[:thread_id] = thread_id; produce_messages(thread_id) } } @consumer_threads = (1..@config[:num_consumer_threads]).map { |i| Thread.new(i) { |thread_id| Thread.current[:thread_id] = thread_id; consume_messages(thread_id, &block) } } @debug_thread = Thread.new { debug_threads(config[:debug_threads]) } if @config[:debug_threads] @consumer_threads.each { |thread| thread.join } # initiate full shutdown if all consumer threads have stopped halt(false) logger.info "Shutdown (all consumers exited) complete: #{Time.new.to_s}" end def consume_messages(thread_id, &block) begin logger.info "starting consumer #{thread_id} for id #{@run_id}: #{Time.new.to_s}" # Prepare for batch run totalCount = 0 intervalCount = 0 intervalSize = 0 startTime = nil lastTime = nil messages = [] if @config[:reconnect] then client = HttpStreamingClient::Client.new(compression: true, reconnect: true, reconnect_interval: @config[:reconnect_interval], reconnect_attempts: @config[:reconnect_attempts]) else client = HttpStreamingClient::Client.new(compression: true) end Thread.current[:client] = client startTime = lastTime = Time.new logger.info "client.get:#{@config.stream_url}, #{@config[:options_factory].get_options}" response = client.get(@config.stream_url, { :options_factory => @config[:options_factory] }) { |line| if line.nil? then logger.info "consumer #{thread_id}:error:nil line received for id: #{@run_id}" next end if line.size == 0 then logger.info "consumer #{thread_id}:error:zero length line received for id: #{@run_id}" next end if line.eql? "\r\n" then logger.info "consumer #{thread_id}:Server ping received for id: #{@run_id}" next end if !@config[:signal_prefix_array].nil? then signal_message_received = false @config[:signal_prefix_array].each do |prefix| if line.start_with? prefix then logger.info "consumer #{thread_id}:Stream signal message received for id:#{@run_id}:#{line}" signal_message_received = true break end end next if signal_message_received end logger.debug "consumer #{thread_id}:line: #{line}" messages << @config[:data_producer].format(line) unless @config[:data_producer].nil? totalCount = totalCount + 1 intervalCount = intervalCount + 1 intervalSize = intervalSize + line.size if (totalCount % @records_per_batch) == 0 then now = Time.new if (now - lastTime) < @min_batch_seconds then logger.debug "consumer #{thread_id}:next because < @min_batch_seconds" next end lag = -1 # lag unknown if block_given? then # block is code to detect lag lag = block.call(line, now) logger.debug "consumer #{thread_id}:lag handler called, calculated lag: #{lag}" end @stats.add_consumed(intervalCount, intervalSize, lag) intervalElapsedTime = now - lastTime message_set_params = { num_records: intervalCount, size_bytes: intervalSize, time_sec: intervalElapsedTime.round(2).to_s, records_per_sec: (intervalCount / intervalElapsedTime).round(2).to_s, kbytes_per_sec: (intervalSize / intervalElapsedTime / 1024).round(2).to_s, message_lag: lag } production_job = ProductionJob.new(@run_id, messages, message_set_params) logger.info "consumer #{thread_id}:enqueuing production job, #{messages.size} messages for #{@run_id}, job id #{production_job.id}, queue length #{@production_queue.length}" @production_queue << production_job production_job = nil messages = [] lastTime = Time.new intervalSize = 0 intervalCount = 0 end } logger.info "consumer #{thread_id}:shut down complete: #{Time.new.to_s}" logger.info "consumer #{thread_id}:total elapsed time: #{(Time.new - startTime).round(2).to_s} seconds" rescue InterruptRequest logger.info "consumer #{thread_id}:interrupt requested" #client.interrupt logger.info "consumer #{thread_id}:shut down complete: #{Time.new.to_s}" rescue Exception => e logger.error "Consumer thread #{thread_id}:Exception:#{e}" logger.error "Backtrace:\n\t#{e.backtrace.join("\n\t")}" end end end end
class Category < ActiveRecord::Base has_many :catrted_products has_many :products, through: :categorized_products end
module ConsoleUtils class ReplState IVAR = :"@__console_utils__" EMPTY_CONTEXT_ALERT = "Trying to setup with empty context".freeze ALREADY_EXTENDED_ALERT = "Trying to setup again on fully extended context".freeze CONTEXT_DEBUG_MSG = "Console instance: %p".freeze MODULE_EXTENDS_MSG = "extending context...".freeze def self.setup(context) state = (context.instance_variable_defined?(IVAR) ? context.instance_variable_get(IVAR) : nil) || ReplState.new return true if state.frozen? logger.tagged("console_utils-#{VERSION}") do if context.nil? logger.warn { EMPTY_CONTEXT_ALERT } return end unless state.persisted? logger.level = Logger::WARN if ENV["CONSOLE_UTILS_DEBUG"] logger.level = Logger::DEBUG logger.debug { CONTEXT_DEBUG_MSG % context } end end if state.fully_extended? logger.warn { ALREADY_EXTENDED_ALERT } else ConsoleUtils.enabled_modules do |mod| state.extending(mod.to_s) do logger.debug { MODULE_EXTENDS_MSG } context.extend(mod) end end end end context.instance_variable_set(IVAR, state.persist!) end def self.logger ConsoleUtils.logger end def initialize @version = VERSION @extensions = [] @persisted = false end def persisted? @persisted end def persist! @persisted = true fully_extended? ? freeze : self end def fully_extended? @persisted && @extensions.size == ConsoleUtils.enabled_modules.size end def extending(mod_name) if include?(mod_name) true else ConsoleUtils.logger.tagged(mod_name) { yield } @extensions << mod_name end end def include?(mod) @extensions.include?(mod.to_s) end alias_method :extended_with?, :include? end end
class PagesController < ApplicationController before_action :must_login, only: [:dashboard, :pricing, :documents, :vflex, :flexforward, :mycert, :learning, :labs, :upload, :upload_file, :pinpoint] before_action :can_see_pricing, only: [:pricing] before_action :can_print_cert, only: [:mycert] before_action :require_admin, only: [:uploads, :reports] def new_dl @download = Download.new(user_id: current_user.id) if @download.save flash[:success] = "Your Download should have started. If you have issues, please contact us." redirect_back(fallback_location:"/") #download user email actions here current_user.send_download_ext_notice current_user.send_download_int_notice current_user.send_download_zap #zap to workflow for download else flash[:danger] = "There seems to have been a problem with the download. Feel free to contact us." redirect_back(fallback_location:"/") end end def new_calc @calculator = Calculator.new(user_id: current_user.id) if @calculator.save flash[:success] = "Your ROI Calculator download should have initiated. If you have issues, please contact us." redirect_to root_path else flash[:danger] = "There seems to have been a problem with the download. Feel free to contact us." redirect_to root_path end end def dashboard @user = current_user @badge = UserBadge.where(user_id: @user.id).take @license = License.where(user_id: current_user.id).first @listing = Listing.where(user_id: current_user.id).first @postal_code = (@user.zip).to_s respond_to do |format| format.html { render "dashboard" } end end def tmc @url = request.original_url if @url.include? "hardware" @bg = 'hardware' elsif @url.include? "tmc" @bg = 'tmc' elsif @url.include? "features" @bg = 'features' else @bg = 'peripheral' end end def learning @user = current_user @quizzes = Quiz.joins(:categories).where.not(categories: { name: "Certification" }) @prodquizzes = @quizzes.where(categories: { name: "Productivity" }) @visquizzes = @quizzes.where(categories: { name: "Visualization" }) @secquizzes = @quizzes.where(categories: { name: "Security" }) @mobquizzes = @quizzes.where(categories: { name: "Mobility" }) @configquizzes = @quizzes.where(categories: { name: "Configuration" }) @advancedquizzes = @quizzes.where(categories: { name: "Advanced" }) @badge = UserBadge.where(user_id: @user.id).take #### Configuration Badge #### @config_q_passed = 0 @configquizzes.each do |quiz| @uqquery = UserQuiz.where(user_id: @user.id, quiz_id: quiz.id) if @uqquery != [] @config_q_passed += 1 end end if (@config_q_passed == @configquizzes.count) && @configquizzes.count > 0 if @badge == nil @newconfigbadge = UserBadge.new(user_id: @user.id, configuration: true) if @newconfigbadge.save flash[:success] = "You earned your CONFIGURATION badge!" redirect_to learning_path end elsif @badge != nil && !@badge.configuration if @badge.update(configuration: true) flash[:success] = "You earned your CONFIGURATION badge!" redirect_to learning_path else flash[:danger] = "There was a problem awarding your badge." redirect_to learning_path end end end #### END Configuration Badge #### #### Productivity Badge #### @prod_q_passed = 0 @prodquizzes.each do |quiz| @uqquery = UserQuiz.where(user_id: @user.id, quiz_id: quiz.id) if @uqquery != [] @prod_q_passed += 1 end end if (@prod_q_passed == @prodquizzes.count) && @prodquizzes.count > 0 if @badge == nil @newprodbadge = UserBadge.new(user_id: @user.id, productivity: true) if @newprodbadge.save flash[:success] = "You earned your PRODUCTIVITY badge!" redirect_to learning_path end elsif @badge != nil && !@badge.productivity if @badge.update(productivity: true) flash[:success] = "You earned your PRODUCTIVITY badge!" redirect_to learning_path else flash[:danger] = "There was a problem awarding your badge." redirect_to learning_path end end end #### END Productivity Badge #### #### Visualization Badge #### @vis_q_passed = 0 @visquizzes.each do |quiz| @uqquery = UserQuiz.where(user_id: @user.id, quiz_id: quiz.id) if @uqquery != [] @vis_q_passed += 1 end end if (@vis_q_passed == @visquizzes.count) && @visquizzes.count > 0 if @badge == nil @newvisbadge = UserBadge.new(user_id: @user.id, visualization: true) if @newvisbadge.save flash[:success] = "You earned your VISUALIZATION badge!" redirect_to learning_path end elsif @badge != nil && !@badge.visualization if @badge.update(visualization: true) flash[:success] = "You earned your VISUALIZATION badge!" redirect_to learning_path else flash[:danger] = "There was a problem awarding your badge." redirect_to learning_path end end end #### END Visualization Badge #### #### Security Badge #### @sec_q_passed = 0 @secquizzes.each do |quiz| @uqquery = UserQuiz.where(user_id: @user.id, quiz_id: quiz.id) if @uqquery != [] @sec_q_passed += 1 end end if (@sec_q_passed == @secquizzes.count) && @secquizzes.count > 0 if @badge == nil @newsecbadge = UserBadge.new(user_id: @user.id, security: true) if @newsecbadge.save flash[:success] = "You earned your SECURITY badge!" redirect_to learning_path end elsif @badge != nil && !@badge.security if @badge.update(security: true) flash[:success] = "You earned your SECURITY badge!" redirect_to learning_path else flash[:danger] = "There was a problem awarding your badge." redirect_to learning_path end end end #### END Security Badge #### #### Mobility Badge #### @mob_q_passed = 0 @mobquizzes.each do |quiz| @uqquery = UserQuiz.where(user_id: @user.id, quiz_id: quiz.id) if @uqquery != [] @mob_q_passed += 1 end end if (@mob_q_passed == @mobquizzes.count) && @mobquizzes.count > 0 if @badge == nil @newmobbadge = UserBadge.new(user_id: @user.id, mobility: true) if @newmobbadge.save flash[:success] = "You earned your MOBILITY badge!" redirect_to learning_path end elsif @badge != nil && !@badge.mobility if @badge.update(mobility: true) flash[:success] = "You earned your MOBILITY badge!" redirect_to learning_path else flash[:danger] = "There was a problem awarding your badge." redirect_to learning_path end end end #### END Mobility Badge #### end def pinpoint end def reports @users = User.all @allquizzed = UserQuiz.all @configbadges = UserBadge.where(configuration: true) @prodbadges = UserBadge.where(productivity: true) @visbadges = UserBadge.where(visualization: true) @secbadges = UserBadge.where(security: true) @mobbadges = UserBadge.where(mobility: true) @allbadgesearned = UserBadge.where(configuration: true, productivity: true, visualization: true, security: true, mobility: true) @badgesearned = @configbadges.count + @prodbadges.count + @visbadges.count + @secbadges.count + @mobbadges.count #@userslastmonth = User.where(created_at: 1.month.ago..Date.tomorrow) @distributors = User.where(prttype: "Distributor") @integrators = User.where(prttype: "Integrator") @oems = User.where(prttype: "OEM") @endusers = User.where(prttype: "End User") @baseusers = User.where(needs_review: true) @usersthisweek = User.where(created_at: 1.week.ago..Date.tomorrow) @quizthisweek = UserQuiz.where(created_at: 1.week.ago..Date.tomorrow) @usersthismonth = User.where(created_at: 1.month.ago..Date.tomorrow) @quizthismonth = UserQuiz.where(created_at: 1.month.ago..Date.tomorrow) #@loggedlastmonth = User.where(lastlogin: Date.today.beginning_last_month..Date.today.end_of_last_month) @loggedthismonth = User.where(lastlogin: Date.today.beginning_of_month..Date.today.end_of_month) @usersthisquarter = User.where(created_at: 3.months.ago..Date.tomorrow) @quizthisquarter = UserQuiz.where(created_at: 3.months.ago..Date.tomorrow) @loggedthisquarter = User.where(lastlogin: Date.today.beginning_of_quarter..Date.today.end_of_quarter) @usersthisyear = User.where(created_at: 12.months.ago..Date.tomorrow) @quizthisyear = UserQuiz.where(created_at: 12.months.ago..Date.tomorrow) @loggedthisyear = User.where(lastlogin: Date.today.beginning_of_year..Date.today.end_of_year) @certified = User.where.not(certexpire: nil).where("certexpire >= ?", Date.today) @certexpired = User.where.not(certexpire: nil).where("certexpire < ?", Date.today) @certsi = User.where.not(certexpire: nil).where("certexpire >= ?", Date.today).where(prttype: "Integrator") @certoem = User.where.not(certexpire: nil).where("certexpire >= ?", Date.today).where(prttype: "OEM") @certsignedup = User.where(cert_signup: true) @inprogress = User.where(cert_signup: true, needs_review: true) @wrongs = Wrong.all if @wrongs.count >= 1 @wrongs_month = Wrong.where(created_at: 1.month.ago..Date.tomorrow) @mostmissed = Wrong.group(:question_id).select(:question_id).order(Arel.sql('COUNT(*) DESC')).first.question_id if @wrongs_month.any? @mostmissed_month = @wrongs_month.group(:question_id).select(:question_id).order(Arel.sql('COUNT(*) DESC')).first.question_id else @mostmissed_month = nil end @most_missed_quiz = Question.find(@mostmissed).quizzes.last if @mostmissed_month != nil @most_missed_quiz_month = Question.find(@mostmissed_month).quizzes.last @question_missed_most_month = Question.find(@mostmissed_month).question else @most_missed_quiz_month = nil @question_missed_most_month = nil end @question_missed_most = Question.find(@mostmissed).question else @wrongs_month = nil @mostmissed = nil @mostmissed_month = nil @most_missed_quiz = nil @most_missed_quiz_month = nil @question_missed_most = nil @question_missed_most_month = nil end @flexes = Flexforward.all @flexmonth = Flexforward.where(created_at: 1.month.ago..Date.tomorrow) @flexred = Flexforward.where(red_exchange: true) @qrs = Qrcode.all @qrmonth = Qrcode.where(created_at: 1.month.ago..Date.tomorrow) if @qrmonth.count > 0 @qr_most_user_month = @qrmonth.group(:user_id).select(:user_id).order(Arel.sql('COUNT(*) DESC')).first.user_id else @qr_most_user_month = nil end @qr_most_user = Qrcode.group(:user_id).select(:user_id).order(Arel.sql('COUNT(*) DESC')).first.user_id @qr_best_user = User.find(@qr_most_user) if @qr_most_user_month != nil @qr_best_user_month = User.find(@qr_most_user_month) else @qr_best_user_month = nil end @evt_users = User.where(referred_by: "Events") @evt_registrations = EventAttendee.where(:canceled => false) @evt_reg_cancels = EventAttendee.where(:canceled => true) @event_attended = EventAttendee.where(:canceled => false).where(:checkedin => true) @pastevts = Event.where("endtime < ?", Date.today) @pastregistered = EventAttendee.joins(:event).where("endtime < ?", Date.today) @pastattended = @pastregistered.where(:checkedin => true) @evt_average_attend = ((@pastattended.count).to_f / (@pastregistered.count).to_f) * 100 @learn_users = User.where(referred_by: "Video Learning") end def labs @user = current_user end def upload #file selection and upload @user = current_user end def uploads #index of uploads require 'aws-sdk-s3' ######################## aws calls and checks ############################ def bucket_exists?(s3_client, bucket_name) response = s3_client.list_buckets response.buckets.each do |bucket| return true if bucket.name == bucket_name end return false rescue StandardError => e puts "Error listing buckets: #{e.message}" return false end @user = current_user @s3 = Aws::S3::Client.new @bucket_name = 'rails-partners-bucket' @message if bucket_exists?(@s3, @bucket_name) @message = true else @message = false end @objects = @s3.list_objects_v2( bucket: @bucket_name, max_keys: 1000 ).contents #@objects = @objects.order("last_modified desc") end def download_lab #download file from AWS require 'aws-sdk-s3' @s3 = Aws::S3::Client.new #@s3 = Aws::S3::Presigner.new @bucket_name = 'rails-partners-bucket' @object_key = params[:object_key] #@local_path = "./#{@object_key}" @message_log = "" #@url = @s3.presigned_url(:get_object, bucket: "bucket", key: "key") def download_db(key:, bucket:) # @s3.get_object( # #response_target: to, # bucket: bucket, # key: key # ) # File.open(key, 'wb') do |file| # @s3.get_object( bucket: bucket, key: key) do |chunk| # file.write(chunk) # end # end File.open(key, 'wb') do |file| resp = @s3.get_object({ bucket: bucket, key: key }, target: file) end @message_log = response.message end begin download_db(key: @object_key, bucket: @bucket_name) rescue StandardError => e @message_log = e.message flash[:danger] = "#{@message_log} - Object '#{@object_key}' in bucket '#{@bucket_name}' was not downloaded." redirect_to uploads_path else flash[:success] = "AWS Message about Download - \"#{@message_log}\"" redirect_to uploads_path end end def upload_file #upload action require 'aws-sdk-s3' @user = current_user @s3 = Aws::S3::Resource.new @bucket_name = 'rails-partners-bucket' @message_log = "" @file = params[:user][:cert_lab] @object_key = @file.original_filename begin if @file.content_type != "application/octet-stream" flash[:danger] = "Sorry, you can only upload .db files" redirect_to upload_path elsif @file.original_filename.include? ".db" @s3.bucket(@bucket_name).object(@object_key).upload_file(@file.tempfile) @user.lab_file = @object_key @user.save ## send email confirming file upload to certification@thinmanager.com @user.send_lab_upload_notice ## send email integrating Hubspot via Zapier to lab submission @user.send_zap_lab_upload flash[:success] = "Your file named \"#{@object_key}\" has been uploaded. We will review it for grading and contact you after." redirect_to root_path else flash[:danger] = "Sorry, you can only upload .db files" redirect_to upload_path end rescue StandardError => e @message_log = e.message flash[:danger] = "#{@message_log}" redirect_to upload_path end end def destroy_labfile require 'aws-sdk-s3' @s3 = Aws::S3::Resource.new @key = params[:key] @bucket_name = 'rails-partners-bucket' # @bucket = @s3.buckets[@bucket_name] # @object = @bucket.objects[@key] # @object.delete # @s3.delete_object({ # bucket: @bucket_name, # key: @key, # }) @s3.bucket(@bucket_name).object(@key).delete # @obj.delete # @s3.delete_object(bucket: @bucket_name, key: @key) #flash[:warning] = "this action is not functional. You have to do it through the AWS Console for now." flash[:success] = "#{@key} was successfully deleted." redirect_back(fallback_location:"/") end def pricing @channel = @current_user.channel respond_to do |format| format.html { render "pricing" } end end def documents respond_to do |format| format.html { render "documents" } end end def vflex @user = @current_user respond_to do |format| format.html { render "vflex" } end end def flexforward @user = @current_user respond_to do |format| format.html { render "flexforward" } end end def mycert @user = @current_user respond_to do |format| format.html { render "mycert" } end end private def must_login if !logged_in? redirect_to login_path end end def can_see_pricing if @current_user.admin? || (@current_user.prttype == "Distributor" && (@current_user.continent == "North America" || @current_user.continent == "NA")) else flash[:danger] = "You do not have permission to view this page." redirect_to root_path end end def can_print_cert if @current_user.admin? || (@current_user.certifications.any? && @current_user.certifications.last.exp_date > Date.today) || (@current_user.certexpire != nil && @current_user.certexpire > Date.today) else flash[:danger] = "You do not have permission to view this page." redirect_to root_path end end def require_admin if (logged_in? and !current_user.admin?) || !logged_in? flash[:danger] = "Only admin users can perform that action" redirect_to root_path end end end
# -*- encoding: utf-8 -*- class DeliveryMailsController < ApplicationController # GET /delivery_mails # GET /delivery_mails.json def index if params[:bp_pic_group_id] #グループメール @bp_pic_group = BpPicGroup.find(params[:bp_pic_group_id]) cond = ["bp_pic_group_id = ? and deleted = 0", @bp_pic_group] else #即席メール cond = ["delivery_mail_type = ? and deleted = 0", "instant"] end @delivery_mails = DeliveryMail.where(cond).order("id desc").page(params[:page]).per(50) respond_to do |format| format.html # index.html.erb format.json { render json: @delivery_mails } end end # GET /delivery_mails/1 # GET /delivery_mails/1.json def show @delivery_mail = DeliveryMail.find(params[:id]).get_informations @delivery_mail_targets = @delivery_mail.delivery_mail_targets @delivery_mail_targets.sort_by! do |delivery_mail_target| delivery_mail_target.reply_mails.empty? ? 0 : - delivery_mail_target.id end @attachment_files = AttachmentFile.get_attachment_files("delivery_mails", @delivery_mail.id) respond_to do |format| format.html # show.html.erb format.json { render json: @delivery_mail } end end def show_all @delivery_mail = DeliveryMail.find(params[:id]).get_informations @delivery_mail_targets = @delivery_mail.delivery_mail_targets @delivery_mail_targets.sort_by! do |delivery_mail_target| delivery_mail_target.reply_mails.empty? ? 0 : - delivery_mail_target.id end respond_to do |format| format.html { render layout: false } # show.html.erb format.json { render json: @delivery_mail } end end def copynew @src_mail_id = params[:id] src_mail = DeliveryMail.find(@src_mail_id) src_mail.setup_planned_setting_at(current_user.zone_at(src_mail.planned_setting_at)) @attachment_files = AttachmentFile.get_attachment_files("delivery_mails", src_mail.id) @delivery_mail = DeliveryMail.new @delivery_mail.attributes = src_mail.attributes.reject{|x| ["created_at", "updated_at", "created_user", "updated_user", "deleted_at", "deleted"].include?(x)} new_proc respond_to do |format| format.html { render action: "new" } end end # GET /delivery_mails/new # GET /delivery_mails/new.json def new @delivery_mail = DeliveryMail.new @delivery_mail.bp_pic_group_id = params[:bp_pic_group_id] if (target_mail_template = get_target_mail_template) @delivery_mail.content = target_mail_template.content @delivery_mail.subject = target_mail_template.subject @delivery_mail.mail_cc = target_mail_template.mail_cc @delivery_mail.mail_bcc = target_mail_template.mail_bcc else @delivery_mail.content = <<EOS %%business_partner_name%% %%bp_pic_name%% 様 EOS end @delivery_mail.add_signature(current_user) new_proc respond_to do |format| format.html # new.html.erb format.json { render json: @delivery_mail } end end # GET /delivery_mails/1/edit def edit @delivery_mail = DeliveryMail.find(params[:id]) @delivery_mail.setup_planned_setting_at(current_user.zone_at(@delivery_mail.planned_setting_at)) @attachment_files = @delivery_mail.attachment_files respond_to do |format| format.html # edit.html.erb format.json { render json: @delivery_mail } end end # POST /delivery_mails # POST /delivery_mails.json def create if params[:bp_pic_ids].present? return contact_mail_create(params[:bp_pic_ids].split.uniq) end if params[:source_bp_pic_id].present? return reply_mail_create end @delivery_mail = DeliveryMail.new(params[:delivery_mail]) @delivery_mail.matching_way_type = @delivery_mail.bp_pic_group.matching_way_type @delivery_mail.delivery_mail_type = "group" @delivery_mail.perse_planned_setting_at(current_user) # zone set_user_column @delivery_mail respond_to do |format| begin ActiveRecord::Base.transaction do @delivery_mail.save! @delivery_mail.tag_analyze! # 添付ファイルの保存 store_upload_files(@delivery_mail.id) # 添付ファイルのコピー copy_upload_files(params[:src_mail_id], @delivery_mail.id) end if params[:testmail] DeliveryMail.send_test_mail(@delivery_mail.get_informations) format.html { redirect_to({ :controller => 'delivery_mails', :action => 'edit', :id => @delivery_mail, :back_to => back_to }, notice: 'Delivery mail was successfully created.') } end format.html { redirect_to url_for( :controller => 'bp_pic_groups', :action => 'show', :id => @delivery_mail.bp_pic_group_id, :delivery_mail_id => @delivery_mail.id, :back_to => back_to ), notice: 'Delivery mail was successfully created.' } format.json { render json: @delivery_mail, status: :created, location: @delivery_mail } rescue ActiveRecord::RecordInvalid format.html { render action: "new" } format.json { render json: @delivery_mail.errors, status: :unprocessable_entity } end end end # PUT /delivery_mails/1 # PUT /delivery_mails/1.json def update @delivery_mail = DeliveryMail.find(params[:id]) @delivery_mail.mail_status_type = 'editing' respond_to do |format| begin @delivery_mail.attributes = params[:delivery_mail] @delivery_mail.perse_planned_setting_at(current_user) # zone set_user_column(@delivery_mail) ActiveRecord::Base.transaction do @delivery_mail.save! @delivery_mail.tag_analyze! # 添付ファイルの保存 store_upload_files(@delivery_mail.id) end if params[:testmail] DeliveryMail.send_test_mail(@delivery_mail.get_informations) format.html { redirect_to({ :controller => 'delivery_mails', :action => 'edit', :id => @delivery_mail, :back_to => back_to }, notice: 'Delivery mail was successfully created.') } end format.html { redirect_to url_for( :controller => 'bp_pic_groups', :action => 'show', :id => @delivery_mail.bp_pic_group_id, :delivery_mail_id => @delivery_mail.id, :back_to => back_to ), notice: 'Delivery mail was successfully updated.' } format.json { head :no_content } rescue ActiveRecord::RecordInvalid format.html { render action: "edit" } format.json { render json: @delivery_mail.errors, status: :unprocessable_entity } end end end # POST /delivery_mails/add_details # POST /delivery_mails/add_details.json def add_details if params[:bp_pic_ids].blank? redirect_to back_to, notice: 'メール対象者が0人でなので、登録できません。' return end delivery_mail = DeliveryMail.find(params[:delivery_mail_id]).get_informations ActiveRecord::Base.transaction do delivery_mail.mail_status_type = 'unsend' set_user_column delivery_mail delivery_mail.save! add_targets(params[:delivery_mail_id], params[:bp_pic_ids]) end if delivery_mail.planned_setting_at < Time.now.to_s DeliveryMail.send_mails error_count = DeliveryError.where(:delivery_mail_id => delivery_mail.id).size if error_count > 0 flash.now[:warn] = "送信に失敗した宛先が存在します。<br>送信に失敗した宛先は配信メール詳細画面から確認できます。" end end SystemNotifier.send_info_mail("[GoldRush] 配信メールがセットされました ID:#{delivery_mail.id}", <<EOS).deliver #{SysConfig.get_system_notifier_url_prefix}/delivery_mails/#{delivery_mail.id} 件名: #{delivery_mail.subject} #{delivery_mail.content} EOS respond_to do |format| format.html { redirect_to url_for(:action => :index, :bp_pic_group_id => params[:bp_pic_group_id]), notice: 'Delivery mail targets were successfully created.' } # format.json { render json: @delivery_mail_target, status: :created, location: @delivery_mail_target } end end def add_targets(delivery_mail_id, bp_pic_ids) bp_pic_ids.each do |bp_pic_id| next if DeliveryMailTarget.where(:delivery_mail_id => delivery_mail_id, :bp_pic_id => bp_pic_id.to_i, :deleted => 0).first delivery_mail_target = DeliveryMailTarget.new delivery_mail_target.delivery_mail_id = delivery_mail_id delivery_mail_target.bp_pic_id = bp_pic_id.to_i set_user_column(delivery_mail_target) delivery_mail_target.save! end end # PUT /delivery_mails/cancel/1 # PUT /delivery_mails/cancel/1.json def cancel @delevery_mail = DeliveryMail.find(params[:id]) @delevery_mail.mail_status_type = 'canceled' set_user_column @delevery_mail @delevery_mail.save! respond_to do |format| format.html { redirect_to back_to, notice: 'Delivery mail was successfully canceled.' } end end # DELETE /delivery_mails/1 # DELETE /delivery_mails/1.json def destroy # @delivery_mail = DeliveryMail.find(params[:id]) # @delivery_mail.destroy respond_to do |format| format.html { redirect_to delivery_mails_url } format.json { head :no_content } end end def reply_mail_new @bp_pics = [] source_subject, source_content, @source_bp_pic_id, @source_message_id = if params[:import_mail_id] source_im = ImportMail.find(params[:import_mail_id]) [source_im.mail_subject, source_im.mail_body, source_im.bp_pic_id, source_im.message_id] elsif params[:delivery_mail_id] source_dm = DeliveryMail.find(params[:delivery_mail_id]) # こちらから送った配信メールに返信する形で配信するのは、現状、自動マッチングからのみの機能なので、 # 配信メールの持つ配信メール対象は一つしかない想定 source_dmt = source_dm.delivery_mail_targets.first [source_dm.subject, source_dm.content, source_dmt.bp_pic_id, source_dmt.message_id] end @delivery_mail = DeliveryMail.new @delivery_mail.mail_bcc = current_user.email new_proc @delivery_mail.subject = "Re: #{source_subject}" @delivery_mail.content = <<EOS + "\n\n\n" + source_content.lines.map{|x| "> " + x}.join %%business_partner_name%% %%bp_pic_name%% 様 EOS @delivery_mail.add_signature(current_user) respond_to do |format| format.html { render action: "new" } end end def reply_mail_create @delivery_mail = DeliveryMail.new(params[:delivery_mail]) @delivery_mail.delivery_mail_type = "instant" @delivery_mail.setup_planned_setting_at(current_user.zone_now) @delivery_mail.mail_status_type = 'unsend' set_user_column @delivery_mail respond_to do |format| begin ActiveRecord::Base.transaction do @delivery_mail.save! # 添付ファイルの保存 store_upload_files(@delivery_mail.id) #配信メール対象作成 delivery_mail_target = DeliveryMailTarget.new delivery_mail_target.delivery_mail_id = @delivery_mail.id delivery_mail_target.bp_pic_id = params[:source_bp_pic_id] delivery_mail_target.in_reply_to = params[:source_message_id] set_user_column(delivery_mail_target) delivery_mail_target.save! end #transaction # メール送信 DeliveryMail.send_mails error_count = DeliveryError.where(:delivery_mail_id => @delivery_mail.id).size if error_count > 0 flash.now[:warn] = "送信に失敗した宛先が存在します。<br>送信に失敗した宛先は配信メール詳細画面から確認できます。" end format.html { redirect_to url_for( :controller => 'delivery_mails', :action => 'show', :id => @delivery_mail.id, :back_to => back_to ), notice: 'Delivery mail was successfully sent.' # redirect_to(back_to , notice: 'Delivery mail was successfully created.') } rescue ActiveRecord::RecordInvalid format.html { render action: "new" } end end end def contact_mail_new @bp_pics = BpPic.find(params[:bp_pic_ids]) @delivery_mail = DeliveryMail.new #@delivery_mail.bp_pic_group_id = params[:id] unless sales_pic = BpPic.find(params[:bp_pic_ids][0]).sales_pic sales_pic = current_user end @delivery_mail.content = "" if t = sales_pic.contact_mail_template @delivery_mail.mail_cc = t.mail_cc @delivery_mail.mail_bcc = t.mail_bcc @delivery_mail.subject = t.subject @delivery_mail.content = t.content end @delivery_mail.add_signature(sales_pic) @delivery_mail.mail_bcc = @delivery_mail.mail_bcc.to_s.split(",").push(sales_pic.email).join(",") @delivery_mail.mail_from = sales_pic.email @delivery_mail.mail_from_name =sales_pic.employee.employee_name @delivery_mail.setup_planned_setting_at(sales_pic.zone_now) respond_to do |format| format.html { render action: "new" } end rescue ValidationAbort respond_to do |format| format.html { flash[:warning] = '営業担当が設定されていません。' redirect_to(back_to) } end end def contact_mail_create(bp_pic_ids) @bp_pics = BpPic.find(bp_pic_ids) @delivery_mail = DeliveryMail.new(params[:delivery_mail]) @delivery_mail.delivery_mail_type = "instant" @delivery_mail.setup_planned_setting_at(@bp_pics[0].sales_pic.zone_now) @delivery_mail.mail_status_type = 'unsend' set_user_column @delivery_mail respond_to do |format| begin ActiveRecord::Base.transaction do @delivery_mail.save! #あいさつメールフラグの更新 @bp_pics.each do |bp_pic| bp_pic.contact_mail_flg = 1 set_user_column bp_pic bp_pic.save! end # 添付ファイルの保存 store_upload_files(@delivery_mail.id) #配信メール対象作成 add_targets(@delivery_mail.id, bp_pic_ids) end #transaction # メール送信 DeliveryMail.send_mails error_count = DeliveryError.where(:delivery_mail_id => @delivery_mail.id).size if error_count > 0 flash.now[:warn] = "送信に失敗した宛先が存在します。<br>送信に失敗した宛先は配信メール詳細画面から確認できます。" end format.html { redirect_to url_for( :controller => 'delivery_mails', :action => 'show', :id => @delivery_mail.id, :back_to => back_to ), notice: 'Delivery mail was successfully sent.' # redirect_to(back_to , notice: 'Delivery mail was successfully created.') } rescue ActiveRecord::RecordInvalid format.html { render action: "new" } end end end def start_matching m = DeliveryMail.find(params[:id]) session[:mail_match_target_id] = m.id redirect_to :controller => :import_mail, :action => :list end def fix_matching session.delete(:mail_match_target_id) render :text => "OK", :layout => false end def add_matching ActiveRecord::Base.transaction do dm = DeliveryMail.find(session[:mail_match_target_id]) im = ImportMail.find(params[:id]) dmm = DeliveryMailMatch.new dmm.delivery_mail = dm dmm.import_mail = im dmm.delivery_mail_match_type = 'auto' dmm.matching_user_id = current_user.id dmm.memo= params[:msg] set_user_column dmm dmm.save! ScoreJournal.update_score!(current_user.id, 1, 'add_matching', dmm.id) SystemNotifier.send_info_mail("[GoldRush] マッチング候補が提案されました ID:#{dm.id}", <<EOS).deliver #{SysConfig.get_system_notifier_url_prefix}/delivery_mails/#{dm.id} コメント: #{dmm.memo} 対象メール: #{dm.subject} 提案メール: #{im.mail_subject} #{im.mail_body} EOS end _redirect_or_back_to({:controller => :import_mails, :action => :show , :id => params[:id]}, notice: "マッチング候補に追加しました!") end def unlink_matching ActiveRecord::Base.transaction do dmm = DeliveryMailMatch.match(params[:delivery_mail_id], params[:import_mail_id]) dmm.deleted = 9 dmm.deleted_at = Time.now set_user_column dmm dmm.save! ScoreJournal.update_score!(dmm.matching_user_id, -1, 'unlink_matching', dmm.id) end redirect_to(back_to, notice: "マッチング候補から外しました。") end private def new_proc @delivery_mail.mail_from = SysConfig.get_value(:delivery_mails, :default_from) @delivery_mail.mail_from_name = SysConfig.get_value(:delivery_mails, :default_from_name) @delivery_mail.setup_planned_setting_at(current_user.zone_now) end def store_upload_files(parent_id) [1,2,3,4,5].each do |i| unless (upfile = params['attachment' + i.to_s]).blank? af = AttachmentFile.new af.create_and_store!(upfile, parent_id, upfile.original_filename, "delivery_mails", current_user.login) end end end def copy_upload_files(src_mail_id, parent_id) unless params[:src_mail_id].blank? AttachmentFile.get_attachment_files("delivery_mails", params[:src_mail_id]).each do |src| af = AttachmentFile.new af.parent_table_name = src.parent_table_name af.parent_id = parent_id af.file_name = src.file_name af.extention = src.extention af.file_path = src.file_path set_user_column af af.save! end end end def get_target_mail_template if @delivery_mail.bp_pic_group != nil && @delivery_mail.bp_pic_group.mail_template_id MailTemplate.find(@delivery_mail.bp_pic_group.mail_template_id) end end end
# frozen_string_literal: true require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end def setup @email = 'hoge@email.com' @user = User.new(name: 'hoge', nickname: 'hogechan', email: @email, password: 'hogefuga') @user.save end test 'should be valid' do assert @user.valid? end test 'password should be present (nonblank)' do assert_not @user.update_password(' ' * 6) end test 'password should have a minimum length' do assert_not @user.update_password('a' * 5) end test 'id should be present' do assert @user.id end test 'password_digest should be match digest' do assert @user.password_digest == User.digest(@user.password) end test 'should not be activated' do assert_not @user.activated? end test 'should be activated' do @user.activate assert @user.activated? end end