text
stringlengths
10
2.61M
class User < ActiveRecord::Base after_create :send_notification devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :name, presence: true, length: {maximum: 25} has_many :charges has_many :memberships has_many :courses, through: :memberships has_many :sessions, through: :courses def subscribed? stripe_subscription_id? end def admin? role == "admin" end def regular? role == "regular" end private def send_notification MyMailer.new_user(self).deliver end end
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don"t touch unless you know what you"re doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ffuenf/debian-8.2.0-amd64" config.vm.hostname = ENV["VM_HOSTNAME"] || "rubylive-builder" # apt-cacher-ng #config.vm.network "forwarded_port", guest: 3142, host: 3142 config.vm.provider "virtualbox" do |vb| # Don"t boot with headless mode vb.gui = true if ENV["VM_GUI"] # Use VBoxManage to customize the VM. For example to change memory: vb.customize ["modifyvm", :id, "--memory", ENV["VM_MEMORY"] || "1024"] end config.vm.provision :shell do |shell| shell.path = "provision.sh" end end
require 'net/http' require 'uri' require 'digest/sha2' require 'erb' def formula(git_tag, sha256) erb_string = File.read('formula.erb') ERB.new(erb_string).result(binding.tap{|b| b.local_variable_set(:git_tag, git_tag) b.local_variable_set(:sha256, sha256) }) end def fetch(url, depth = 0) res = Net::HTTP.get_response(URI.parse(url)) if depth > 0 && res.is_a?(Net::HTTPRedirection) fetch(res['location'], depth - 1) else res.body end end def main() latest_url = "https://github.com/YusukeIwaki/appetize-cli/releases/latest" res = Net::HTTP.get_response(URI.parse(latest_url)) return -1 unless res.is_a?(Net::HTTPRedirection) redirect_url = res['location'] return -1 unless m = /https:\/\/github\.com\/YusukeIwaki\/appetize-cli\/releases\/tag\/(v[0-9]+(\..*)?)/.match(redirect_url) git_tag = m[1] url = "https://github.com/YusukeIwaki/appetize-cli/releases/download/#{git_tag}/appetize_darwin_amd64" sha256 = Digest::SHA256.hexdigest fetch(url, 5) puts formula(git_tag, sha256) end main()
class Enquit < ActiveRecord::Base belongs_to :user has_many :votes validates :title, presence: true validates :option1, presence: true validates :option2, presence: true validates :option3, presence: true validates :option4, presence: true end
class Comment < ActiveRecord::Base belongs_to :user belongs_to :post validates_presence_of :title, message: "The title cannot be blank." validates_presence_of :body, message: "Your comment cannot be blank." end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :use_mobile_view helper_method :better_time $markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => false) $admin = %w(1423101 F0000Q1207 F0000L0011) def is_admin? if $admin.include?session[:cas_user].upcase session[:admin] = true else session[:admin] = false end end def better_time(time) t = time.to_s p = /(....)-(..)-(..)/ p.match(t) year = $1.to_i month = $2.to_i day = $3.to_i "#{year}年#{month}月#{day}日" end private def use_mobile_view request.variant = :phone if request.user_agent =~ /iPhone/ request.variant = :phone if request.user_agent =~ /Android/ end #def logout # reset_session # CASClient::Frameworks::Rails::Filter.logout(self) #end end
# *******************************_lucky_sevens?_******************************* # Write a function lucky_sevens?(numbers), which takes in an array of integers and returns true if any three consecutive elements sum to 7. # lucky_sevens?([2,1,5,1,0]) == true # => 1 + 5 + 1 == 7# lucky_sevens?([0,-2,1,8]) == true # => -2 + 1 + 8 == 7 # lucky_sevens?([7,7,7,7]) == false # lucky_sevens?([3,4,3,4]) == false # Make sure your code currectly checks for edge cases (i.e. the first and last elements of the array). # # def lucky_seven?(numbers) # numbers.each_cons(3).any? { |sum| sum.reduce(:+)== 7} # # end # # # puts lucky_seven?([1,2,4,4,5]) # Enumerable#reduce takes a collection and reduces it down to a single element. It applies an operation to each element, maintaining a running “total.” # For example, #reduce can be used to sum a collection: e.g. [1,2,3].reduce(:+) prints 6 # great link to explain each_cons : http:/ # # /www.sitepoint.com/guide-ruby-collections-iii-enumerable-enumerator/ # # i = 20 # loop do # i -= 1 # puts i # break if i <= 0 # # for i in 1..50 # if i % 7 == 0 # puts i # end # end # for row_num in 1..9 line = '' for col_num in 1..9 line = line + "#{row_num * col_num}\t" end puts line end
require 'chemistry/element' Chemistry::Element.define "Lead" do symbol "Pb" atomic_number 82 atomic_weight 207.2 melting_point '600.75K' end
class Api::PhotosController < ApplicationController before_action :require_logged_in! def index @photos = current_user.fetch_photos(fetch_params) .includes(:user) .includes(:likes) .includes(:comments) if @photos render :index else render json: {} end end def create @photo = Photo.new(photo_params) @photo.user_id = current_user.id if @photo.save render :show else render json: @photo.errors.full_messages, status: 422 end end def show @photo = Photo .includes(:user) .includes(:likes) .includes(:comments) .find(params[:id]) end def destroy @photo = current_user.photos.find(params[:id]) if @photo.destroy render :show else render json: @photo.errors.full_messages, status: 422 end end def user @photos = User.find(params[:user_id]) .fetch_photos(fetch_params(user_only: true)) .includes(:user) .includes(:likes) .includes(:comments) if @photos render :user else render json: @photos.errors.full_messages, status: 422 end end private def photo_params params.require(:photo).permit(:caption, :image) end def fetch_params(options = {}) params.require(:query).permit(:limit, :max_created_at) .merge(options) end end
# frozen_string_literal: true class Rogare::Commands::QuickCheck extend Rogare::Command command Rogare.prefix usage '`!%` - Quick check of things' handle_help match_empty :execute def execute(m, _param) if defined? Rogare::Commands::Project pro = Rogare::Commands::Project.new pro.show_current m, novels end if defined? Rogare::Commands::Wordwar ww = Rogare::Commands::Wordwar.new War.all_current.each do |war| war[:end] = war[:start] + war[:seconds] ww.say_war_info m, war end ww.ex_war_stats(m) end print '' end end
class Task # : signifies symbol, one location in memory entire time attr_accessor :title attr_accessor :priority attr_accessor :completed def initialize(title, priority = 10) self.title = title self.priority = priority self.completed = false end def complete?() completed end def complete self.completed = true; end end
Rails.application.routes.draw do # CLIENT SITE scope module: :client do root to: 'welcome#index' match 'auth/:provider/callback', to: 'sessions#create', via: [:get, :post] match 'auth/failure', to: redirect('/'), via: [:get, :post] match 'signout', to: 'sessions#destroy', as: 'signout', via: [:get, :post] resources :artisans resources :posts do get 'page/:page', action: :index, on: :collection end resources :masterpieces do get 'page/:page', action: :index, on: :collection end match 'contact', to: 'contact#index', via: :get end # ADMIN SITE namespace :admin do # root to: 'dashboard#index' root to: 'posts#index' resources :sliders do member do put :toggle end collection do post :sort get :list end end resources :artisans do member do put :toggle end end resources :testimonials do member do put :toggle end end resources :posts do member do put :toggle get :put_wall get :delete_wall post :img_sort get :img_list end collection do post :sort get :list get :search end end resources :experiences do member do put :toggle end collection do post :sort get :list end end resources :masterpieces do member do put :toggle end collection do get :upload post :sort get :list end end resources :images resources :tags end end
require_relative "./shared/intcode" TILES = [".", "|", "#", "_", "o"].freeze def render(tiles) screen = Hash.new(0) score = 0 tiles.each_slice(3) do |x, y, value| if x == -1 && y == 0 score = value else screen[[x, y]] = value end end [screen, score] end cabinet = Computer.new(INTCODE) screen, = render(cabinet.run) solve!("The total number of blocks is:", screen.values.count { |tile| tile == TILES.index("#") }) playable = INTCODE.dup playable[0] = 2 cabinet = Computer.new(playable) final_score = loop do ball, = screen.detect { |_coords, tile| tile == TILES.index("o") } paddle, = screen.detect { |_coords, tile| tile == TILES.index("_") } joystick = ball[0] <=> paddle[0] updates, score = render(cabinet.run(inputs: [joystick])) screen.merge!(updates) break score if screen.values.none? { |tile| tile == TILES.index("#") } end solve!("The score after breaking all blocks is:", final_score)
class Artists::QuotationsController < ApplicationController include SlugRedirectable before_action :authenticate_user!, except: [:index] before_action :set_artist, only: [:new, :create, :index, :edit, :update] before_action :set_quotation, only: [:edit, :update, :destroy, :publish, :unpublish] def index @quotations = QuotationPolicy::Scope.new(current_user, @artist.quotations_as_artist).resolve_for_artist .order(:created_at) .includes({ :proposal => [ :delay ] }, :commissioner, :assets) .filter(params.permit(:state)) .page(page) .per(per) authorize @quotations end def new @quotation = Quotation.new(commissioner: current_user, artist: @artist) authorize @quotation end def create @quotation = Quotation.new(strong_params(Quotation.new)) authorize @quotation if @quotation.save if params[:publish] publish! flash[:notice] = I18n.t("artists.quotations.publish.success") else flash[:notice] = I18n.t("artists.quotations.create.success") end redirect_to commissioner_quotations_url(commissioner_id: @quotation.commissioner.slug) else render 'new' end end def update @quotation.assign_attributes(strong_params(@quotation)) authorize @quotation if @quotation.save if params[:publish] publish! flash[:notice] = I18n.t("artists.quotations.publish.success") else flash[:notice] = I18n.t("artists.quotations.create.success") end redirect_to commissioner_quotations_path(commissioner_id: @quotation.commissioner.slug) else render 'edit' end end def destroy authorize @quotation @quotation.destroy flash[:notice] = I18n.t("quotations.destroy.success") redirect_to commissioner_quotations_path(commissioner_id: @quotation.commissioner.slug) end def publish authorize @quotation, :publish_for_artist? @quotation.update(public_for_artist: true) head :no_content end def unpublish authorize @quotation, :unpublish_for_artist? @quotation.update(public_for_artist: false) head :no_content end protected def publish! @quotation.publish! @quotation.create_activity key: "quotation.publish", owner: current_user, recipient: @quotation.artist if @quotation.artist.allow_quotation_created_notification NotificationMailer.quotation_created(@quotation).deliver_later end end def set_artist @artist = User.find(params[:artist_id]) redirect_if_new_slug_for(@artist, :artist_id) end def set_quotation @quotation = Quotation.find(params[:id] || params[:quotation_id]) end end
# frozen_string_literal: true class Queries::SeriesQuery < Queries::BaseQuery type Types::SeriesType.connection_type, null: false argument :ids, [ID], required: false, default_value: nil argument :resource_type, String, required: false, default_value: nil def resolve(ids:, resource_type:) scope(ids, resource_type).all.uniq end protected def scope(ids, resource_type) scope = ::Series.joins(:resources).where.not(resources: { published_at: nil }).order('resources.published_at desc') scope = filter_by_ids(scope, ids) scope.where(resources: { type: Resource::TYPES[resource_type.to_sym] }) if resource_type.present? scope end def filter_by_ids(scope, ids) ids.present? ? scope.where(id: ids) : scope end end
class Visit include Mongoid::Document include Mongoid::Timestamps field :referral_link, :type => String field :ip_address, :type => String embedded_in :url validates_presence_of :url validates_associated :url end
class Prey < Cask url 'http://preyproject.com/releases/current/prey-0.6.2-mac-batch.mpkg.zip' homepage 'https://preyproject.com' version '0.6.2' sha1 'c6c8de5adeb813ecfd517aab36dc2b7391ce8498' install 'prey-0.6.2-mac-batch.mpkg' uninstall :pkgutil => 'com.forkhq.prey' def caveats; <<-EOS.undent Prey requires an API key to be installed. If None is found, installation will fail. To set up your API key, set it as an environment variable during installation like this: brew cask uninstall prey API_KEY="abcdef123456" brew cask install prey EOS end end
class StatisticsIndexTestTemplate < StatisticsIndexTemplate def initialize super @state = 'active' @index_name = "#{@configuration['index_patterns'][0..-3].gsub(/^stats-/, 'tests-')}" @configuration.delete('aliases') @configuration['index_patterns'] = "#{@index_name}-*" end end
FactoryBot.define do factory :user do nickname { Faker::Internet.username(specifier: 40) } email { Faker::Internet.unique.free_email } password = Faker::Lorem.characters(number: 6, min_alpha: 1, min_numeric: 1) password { password } password_confirmation { password } familyname { Gimei.last.kanji } firstname { Gimei.first.kanji } familyname_furigana { Gimei.last.katakana } firstname_furigana { Gimei.first.katakana } birthday { Faker::Date.between(from: '1930-09-23', to: 5.year.from_now) } end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception private def current_usr @current_usr ||= if session[:usr_id] Usr.find_by_id(session[:usr_id]) end end helper_method :current_usr end
require 'test_helper' class OAuth2::TokenControllerTest < ActionDispatch::IntegrationTest test 'should fail /oauth2/token with invalid Content-Type' do post(oauth2_token_path(ServiceProvider.first.id), headers: { 'CONTENT_TYPE': 'text/plain' }) assert_response(:bad_request) json = JSON.parse(response.body) assert_equal('invalid_request', json['error']) assert_equal('Request header validation failed.', json['error_description']) assert_equal('text/plain is invalid, must be application/x-www-form-urlencoded', json['error_details']['content_type']) assert_equal('error', json['status']) end test 'should fail /oauth2/token with invalid_grant' do sp = ServiceProvider.all.max{ |a, b| a.scopes.size <=> b.scopes.size } consumer = sp.consumers.first params = { client_id: consumer.client_id_key, client_secret: consumer.client_secret, state: 'abcABC' } post(oauth2_token_path(sp), params: params) assert_response(:bad_request) json = JSON.parse(response.body) assert_equal('invalid_grant', json['error']) assert_equal('grant_type is invalid', json['error_description']) end test 'should get /oauth2/token with client_credentials' do sp = ServiceProvider.all.max{ |a, b| a.scopes.size <=> b.scopes.size } consumer = sp.consumers.first params = { grant_type: 'client_credentials', client_id: consumer.client_id_key, client_secret: consumer.client_secret, state: 'abcABC' } post(oauth2_token_path(sp), params: params) assert_response(:success) json = JSON.parse(response.body) assert_equal('success', json['status']) assert_not_nil(json['access_token']) assert_equal('Bearer', json['token_type']) assert_kind_of(Integer, json['expires_in']) assert_equal('abcABC', json['state']) end test 'should get /oauth2/token with authorization_code' do ldap_user = sign_in_as(:great_user) sp = ServiceProvider.all.max{ |a, b| a.scopes.size <=> b.scopes.size } consumer = sp.consumers.first user = User.find_by(uid: ldap_user.uid) token = consumer.tokens.create!(grant: 'authorization_code', user: user) redirect_uri = consumer.redirect_uris.first.uri state = 'abcABC' token.set_as_authorization_code(sp.scopes.map(&:name), state, redirect_uri) params = { grant_type: 'authorization_code', client_id: consumer.client_id_key, client_secret: consumer.client_secret, redirect_uri: redirect_uri, code: token.code, scope: sp.scopes.map{ |s| s.name }.join(' '), state: state } post(oauth2_token_path(sp.id), params: params) assert_response(:success) json = JSON.parse(response.body) assert_equal('success', json['status']) assert_not_nil(json['access_token']) assert_not_nil(json['refresh_token']) assert_equal('Bearer', json['token_type']) assert_kind_of(Integer, json['expires_in']) assert_equal(sp.scopes.map{ |s| s.name }.join(' '), json['scope']) assert_equal('abcABC', json['state']) end test 'should fail /oauth2/token with authorization_code' do ldap_user = sign_in_as(:great_user) sp = ServiceProvider.all.max{ |a, b| a.scopes.size <=> b.scopes.size } consumer = sp.consumers.first user = User.find_by(uid: ldap_user.uid) token = consumer.tokens.create!(grant: 'authorization_code', user: user) redirect_uri = consumer.redirect_uris.first.uri state = 'abcABC' token.set_as_authorization_code(sp.scopes.map(&:name), state, redirect_uri) params = { grant_type: 'authorization_code', client_id: consumer.client_id_key, client_secret: consumer.client_secret, redirect_uri: redirect_uri, code: token.code + 'invalid', scope: sp.scopes.map{ |s| s.name }.join(' '), state: state } post(oauth2_token_path(sp.id), params: params) assert_response(:bad_request) json = JSON.parse(response.body) assert_equal('invalid_request', json['error']) assert_equal('code is invalid', json['error_description']) assert_equal('abcABC', json['state']) end end
class Queue def initialize @queue = [] end def enqueue(el) queue << el end def dequeue queue.shift end def show queue end private attr_accessor :queue end queue = Queue.new queue.enqueue("i") queue.enqueue("love") queue.enqueue("ruby") p queue.show queue.dequeue p queue.show
class UserSerializer < ActiveModel::Serializer attributes :id, :first_name, :last_name, :username, :expenses, :income has_many :debts has_one :plan end
module Parser class PageView def initialize(log_path) @log_path = log_path end def all sort end def uniq sort(uniq: true) end private def sort(uniq: false) scope = logs scope.uniq! if uniq scope. group_by(&:path). map { |path, views| OpenStruct.new(path: path, views_count: views.count) }. sort_by(&:views_count). reverse end def logs @lines ||= ::File.readlines(@log_path).map do |line| path, ip_address = line.split OpenStruct.new(path: path, ip_address: ip_address) end end end end
#!/usr/bin/env ruby require_relative '../lib/move.rb' # Code your CLI Here #Lines 8 and 9-13 Display opening message and begininng board state puts "Welcome to Tic Tac Toe!" board = [" "," "," "," "," "," "," "," "," "] puts display_board(board) puts "Where would you like to go?" puts "Please enter a number 1-9:" # Takes user input and removes extra whitespace input = gets.strip # Passes input to #input_to_index and assigns as variabel index index = input_to_index(input) # Calls #move with board state and index to generate move move(board, index) # Display new board display_board(board)
require 'spec_helper' describe ResourcesController do let(:user) { create :member_user } let(:book) { create :book } let(:resource) { create :resource, :user => user, :book => book } describe "GET#new" do describe "unauthenticated" do it "should not allow anonymous access" do get :new response.should_not be_success end end describe "authenticated" do it "should allow access from authenticated user" do sign_in user get :new response.should be_success end end end describe "POST#create" do context "when user has signed in" do before(:each) do sign_in user end context 'with valid attributes' do let(:book) { create :book } let(:valid_attributes) { attributes_for(:resource).merge(:book_id => book.id) } it 'creates the resource' do expect { post 'create', :resource => valid_attributes }.to change{Resource.count}.by(1) response.should redirect_to(resource.book) end end context "with invalid attributes" do let(:invalid_attributes) { attributes_for(:invalid_resource) } it "does not save the new resource" do expect{ post :create, resource: invalid_attributes }.to_not change(Resource, :count) end it "re-renders the new method" do post :create, resource: invalid_attributes response.should render_template :new end end end context 'when user has not signed in' do it "should be redirect" do post 'create' response.should be_redirect end end end describe "DELETE#destroy" do context 'when user has not signed in' do it "should be redirect" do delete :destroy, id: resource.id response.should redirect_to root_path flash[:alert].should eql(I18n.t('unauthorized.default')) end end context 'when user has signed in' do before(:each) do sign_in user end it 'can destroy the resource blongs to him' do resource = create :resource, :user => user expect { delete :destroy, id: resource.id }.to change{Resource.count}.by(-1) end it 'can not destroy the resource blongs to other' do resource1 = create :resource delete :destroy, id: resource1.id response.should redirect_to root_path flash[:alert].should eql(I18n.t('unauthorized.default')) end end end describe "GET#read" do it "should have an read action" do get :read, :id => resource response.should be_success assigns(:resource).should eq(resource) end end describe "PUT#pdf2html" do let(:admin) { create :admin_user } it "can not pdf2html" do expect { put :pdf2html, id: resource }.to_not change{resource.transformed}.from(false).to(true) end it "can pdf2html" do #sign_in admin #request.env['HTTP_REFERER'] = 'http://test.com/sessions/new' #expect { #put :pdf2html, id: resource #}.to change{resource.transformed}.from(false).to(true) end end end
require 'spec_helper' feature "Viewing activities" do let!(:user) { FactoryGirl.create(:user) } let!(:activity) { FactoryGirl.create(:activity) } before do sign_in_as!(user) define_permission!(user, :view, activity) end scenario "Listing all activities" do FactoryGirl.create(:activity, name: "Hidden") visit '/' expect(page).to_not have_content("Hidden") click_link activity.name expect(page.current_url).to eql(activity_url(activity)) end end
require 'test_helper' class BruteForceTest < Minitest::Test def test_has_a_version_number refute_nil ::BruteForce::VERSION end def test_starts_with_option generator = ::BruteForce::Generator.new(starts_from: 'abcdef') assert_equal(generator.next, 'abcdef') end def test_letters_option generator = ::BruteForce::Generator.new(letters: BruteForce::UPPERCASE) generator.next #skip empty string (\0) assert_equal(generator.next, 'A') end def test_regex_filter_option pattern = /\A.*?B\Z/ generator = ::BruteForce::Generator.new(filter: pattern) assert_match(pattern, generator.next) end def test_lambda_filter_option generator = ::BruteForce::Generator.new(filter: ->(word){ word.start_with?('B') }) assert_equal(generator.next, 'B') end end
# ------------------------------------------------------------------ # Der Twitter-User. # # In der Tabelle werden nur wenige Kernattribute gehalten. # # Attribute: # t.string "name" # t.string "tw_id_str" # t.string "screen_name" # t.integer "followers_count" # t.integer "friends_count" # t.string "lang" # t.string "profile_image_url" # t.datetime "processed_at" # t.datetime "created_at" # t.datetime "updated_at" # t.text "json_data" # ------------------------------------------------------------------ class TwitterUser < ActiveRecord::Base validates_presence_of :name validates_presence_of :tw_id_str validates_uniqueness_of :tw_id_str validates_presence_of :screen_name validates_presence_of :followers_count validates_presence_of :friends_count validates_presence_of :lang validates_presence_of :profile_image_url has_many :twitter_friends has_many :friends, :through => :twitter_friends has_many :twitter_followers has_many :followers, :through => :twitter_followers has_many :tweets # ------------------------------------------------------------------ # DEPRECATED: Erzeugt und speichert TwitterUser mit den im Mashie gespeicherten Daten # # Parameter: # user_mashie Mashie die Attribute # ------------------------------------------------------------------ def self.build(user_mashie) tw = TwitterUser.new() tw.refresh(user_mashie) tw end # ------------------------------------------------------------------ # Erzeugt und speichert oder aktualisiert einen TwitterUser mit den # im Mashie gespeicherten Daten # # Parameter: # user_mashie Mashie die Attribute # ------------------------------------------------------------------ def self.create_or_update(user_mashie) unless (user_mashie.nil?) tw = TwitterUser.find_by_screen_name(user_mashie.screen_name) || TwitterUser.new() tw.refresh!(user_mashie) tw end end # ------------------------------------------------------------------ # Aktualisiert die Attributwerte # # Parameter: # user_mashie Mashie die Attribute # ------------------------------------------------------------------ def refresh!(user_mashie) self.name = user_mashie.name self.tw_id_str = user_mashie.id_str self.screen_name = user_mashie.screen_name self.followers_count = user_mashie.followers_count self.friends_count = user_mashie.friends_count self.lang = user_mashie.lang self.profile_image_url = user_mashie.profile_image_url self.json_data = user_mashie.to_json() self.updated_at = Time.now() # self.processed_at wird nicht gesetzt unless (user_mashie.status.nil?) last_tweet = user_mashie.status #t = Tweet.find_by_tw_id_str(last_tweet.id) t = Tweet.where("tw_id_str = ?", last_tweet.id_str) if (screen_name == "der_mensch_max") then logger.debug("[refresh!] last_tweet.id: #{last_tweet.id}") logger.debug("[refresh!] t.count(): #{t.count()}") # logger.debug("[refresh!] Tweet.count(): #{Tweet.count()}") # logger.debug("[refresh!] tweets.count()(): #{tweets.count()}") # # logger.debug("[refresh!] dumping tweets ") # Tweet.all.each() do |tw| # logger.debug("[refresh!] saved tweet #{tw.id} -> #{tw.tw_id_str} - #{tw.text}") # end end if (t.nil? || t.count() == 0) then logger.debug("[refresh!] create tweet for tw_id_str #{last_tweet.id_str} -> #{last_tweet.text}") if (screen_name == "der_mensch_max") tw = Tweet.create_from_twitter_status(last_tweet) tw.save! logger.debug("[refresh!] created tweed id: #{tw.id}, tw_id_str: #{tw.tw_id_str}") if (screen_name == "der_mensch_max") self.tweets << tw end end end # ------------------------------------------------------------------ # Liefert den letzten Tweet des Users. Convenience Methode # # Parameter: # # ------------------------------------------------------------------ def last_tweet tweets.order("updated_at desc").first unless (tweets.nil? || tweets.size == 0) end end
class Cour < ApplicationRecord validates :title, presence: true, length: { minimum: 5 } has_many :lecons, dependent: :destroy end
control 'redis-server-0' do impact 1.0 title 'ensure redis-server presence' describe port(6379) do it { is_expected.to be_listening } end describe service('redis-server') do it { should be_enabled } it { should be_running } end end control 'postgresql-0' do title 'ensure postgresql presence' describe port(5432) do it { should be_listening } end describe service('postgresql') do it { should be_enabled } it { should be_running } end end control 'rvm-0' do title 'ensure rvm presence' impact 1.0 describe command('. /home/vagrant/.rvm/scripts/rvm && rvm version') do its(:exit_status) { is_expected.to be 0 } end describe command('. /home/vagrant/.rvm/scripts/rvm && ruby --version') do its(:exit_status) { is_expected.to be 0 } its(:stdout) { is_expected.to include 'ruby 2.3.1' } end end control 'app-0' do impact 1.0 title 'ensure db:setup populated 4 users' describe command("cd /vagrant/pivorak-web-app && . /home/vagrant/.rvm/scripts/rvm && DISABLE_SPRING=1 rvm ruby-2.3.1 do bundle exec rails runner 'puts User.count'") do its(:stdout) { is_expected.to be == "4\n" } end end
# ref: https://en.wikipedia.org/wiki/Pet#Domesticated PET_SPECIES = %w(alpaca camel cat cow dog donkey ferret goat hedgehog horse llama pig rabbit fox rodent sheep buffalo yak bird fish).freeze
class X8664ElfBinutils < Formula desc "GNU binutils for i386 & x86_64 (ELF/EFI PE)" homepage "http://www.gnu.org/software/binutils/" url "http://ftpmirror.gnu.org/binutils/binutils-2.26.tar.bz2" sha256 "c2ace41809542f5237afc7e3b8f32bb92bc7bc53c6232a84463c423b0714ecd9" def install args = [] args << "--program-prefix=x86_64-elf-" args << "--enable-targets=x86_64-elf,i386-elf" args << "--target=x86_64-elf" args << "--prefix=#{prefix}" args << "--infodir=#{info}" args << "--mandir=#{man}" args << "--disable-nls" args << "--disable-debug" args << "--disable-dependency-tracking" args << "--disable-werror" args << "--enable-64-bit-bfd" mkdir "build" do system "../configure", *args system "make" system "make", "install" end info.rmtree end end
require 'rails_helper' describe 'GET /v1/users' do let(:path) { '/v1/users' } it 'should get index' do get_user path expect(response).to be_success expect(response.status).to eq 200 end end
class User # attr_accessor :username attr_reader :username attr_writer :username @@all = [] def initialize(username) @username = username @@all << self end def post_tweet(message) @tweet = Tweet.new(self, message) end def self.all @@all end def tweets Tweet.all.select do |tweet| tweet.user == self end end def like_tweet(tweet) # Store this in the like class # Show that they liked a specific message # if it exists. Like.new(self, tweet) # Like.all[tweet.include?()] end def liked_tweets likes = Like.all.find_all do |like| # binding.pry like.user == self end liked_tweets = likes.map do |like| like.tweet end # self.tweet end end
require 'concurrent/executor/ruby_thread_pool_executor' module Concurrent # @!macro cached_thread_pool class RubyCachedThreadPool < RubyThreadPoolExecutor # Create a new thread pool. # # @param [Hash] opts the options defining pool behavior. # number of seconds a thread may be idle before it is reclaimed # # @raise [ArgumentError] if `overflow_policy` is not a known policy def initialize(opts = {}) overflow_policy = opts.fetch(:overflow_policy, :abort) raise ArgumentError.new("#{overflow_policy} is not a valid overflow policy") unless OVERFLOW_POLICIES.include?(overflow_policy) opts = opts.merge( min_threads: 0, max_threads: DEFAULT_MAX_POOL_SIZE, overflow_policy: overflow_policy, max_queue: DEFAULT_MAX_QUEUE_SIZE, idletime: DEFAULT_THREAD_IDLETIMEOUT ) super(opts) end end end
# frozen_string_literal: true version = File.read(File.expand_path('../VERSION', __dir__)).strip lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = 'problem_details-rails' spec.version = version spec.authors = ['Nobuhiro Nikushi'] spec.email = ['deneb.ge@gmail.com'] spec.summary = 'Add a :problem renderer that renponds with RFC 7807 Problem Details format' spec.description = spec.summary spec.homepage = 'https://github.com/nikushi/problem_details' spec.license = 'MIT' spec.files = Dir['lib/**/*.rb'] + %w[ LICENSE.txt README.md Rakefile problem_details-rails.gemspec ] spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.0.0' spec.add_runtime_dependency 'problem_details', version spec.add_dependency 'actionpack', '>= 4.0' spec.add_dependency 'activesupport', '>= 4.0' spec.add_development_dependency 'bundler', '>= 1.16' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' end
# frozen_string_literal: true class FakeBroker def initialize @messages = {} @partition_errors = {} end def messages messages = [] @messages.each do |topic, messages_for_topic| messages_for_topic.each do |partition, messages_for_partition| messages_for_partition.each do |message| messages << message end end end messages end def produce(messages_for_topics:, required_acks:, timeout:, transactional_id: nil, compressor: nil) messages_for_topics.each do |topic, messages_for_topic| messages_for_topic.each do |partition, record_batch| @messages[topic] ||= {} @messages[topic][partition] ||= [] @messages[topic][partition].concat(record_batch.records) end end topics = messages_for_topics.map {|topic, messages_for_topic| Kafka::Protocol::ProduceResponse::TopicInfo.new( topic: topic, partitions: messages_for_topic.map {|partition, record_batch| Kafka::Protocol::ProduceResponse::PartitionInfo.new( partition: partition, error_code: error_code_for_partition(topic, partition), offset: record_batch.records.size, timestamp: (Time.now.to_f * 1000).to_i, ) } ) } if required_acks != 0 Kafka::Protocol::ProduceResponse.new(topics: topics) else nil end end def mark_partition_with_error(topic:, partition:, error_code:) @partition_errors[topic] ||= Hash.new { 0 } @partition_errors[topic][partition] = error_code end private def error_code_for_partition(topic, partition) @partition_errors[topic] ||= Hash.new { 0 } @partition_errors[topic][partition] end end
FactoryBot.define do factory :user do name { "sample" } email { "sample@123.com"} password {"sample123"} password_confirmation {"sample123"} end # FactoryBot.create(:user_with_tasks) do # transient do # tasks_count 3 # end # after(:create) do |user, evaluator| # create_list(:tasks, evaluator.tasks_count, user: user) # end # end end # FactoryBot.create(:user, :with_3_tasks) # trait(:with_3_tasks) do # name { "with_3" } # end # after(:create) do |user| # 3.times { create(:task, user: user) } # end # end # end
require File.join(File.dirname(__FILE__), '..', 'test_helper') # index # ----- class IQ::Crud::Actions::Index::IndexTest < Test::Unit::TestCase def setup ['', 'admin_'].each do |prefix| send(prefix + 'crudified_instance').stubs(:find_collection).with().returns(valid_collection) end end def test_should_respond assert_respond_to(crudified_instance, :index) end def test_should_call_response_for_and_return crudified_instance.stubs(:response_for).with(:index).returns('the response') assert_equal 'the response', crudified_instance.index end def test_should_render_html request_with_both_shiny_product_routes(:get, :index) do |prefix| assert_response :success end end def test_should_render_xml setup_xml_request_header valid_collection.stubs(:to_xml).returns('the xml') request_with_shiny_products_route(:get, :index) { assert_equal('the xml', @response.body) } end def test_should_populate_current_collection_from_find_collection request_with_both_shiny_product_routes(:get, :index) do |prefix| assert_equal(valid_collection, send(prefix + 'crudified_view').current_collection) end end def test_should_have_header request_with_both_shiny_product_routes(:get, :index) { assert_select('h1', 'Shiny products') } end def test_should_have_new_link request_with_both_shiny_product_routes(:get, :index) do |prefix| assert_select(['p a[href=?]', send("new_#{prefix}shiny_product_path")], 'New shiny product', :count => 2) end end def test_should_have_table_of_records request_with_both_shiny_product_routes(:get, :index) do |prefix| assert_select('table[cellspacing="0"]') do assert_select('thead') do assert_select('tr th:nth-child(1)', 'Name') assert_select('tr th:nth-child(2)', 'Brand name') assert_select('tr th:last-child', 'Action') end assert_select('tbody') do assert_select('tr:nth-child(1).alt') do assert_select('td:nth-child(1)', 'Foo') assert_select('td:nth-child(2)', 'Footech') assert_select('td:last-child') do assert_select(['a[href=?]', send("edit_#{prefix}shiny_product_path", '21')], 'Edit') assert_select(['a[href=?]', send("delete_#{prefix}shiny_product_path", '21')], 'Delete') end end assert_select('tr:nth-child(2):not(.alt)') do assert_select('td:nth-child(1)', 'Bar') assert_select('td:nth-child(2)', '&nbsp;') assert_select('td:last-child') do assert_select(['a[href=?]', send("edit_#{prefix}shiny_product_path", '35')], 'Edit') assert_select(['a[href=?]', send("delete_#{prefix}shiny_product_path", '35')], 'Delete') end end assert_select('tr:nth-child(3).alt') do assert_select('td:nth-child(1)', 'Yum &amp; Baz') assert_select('td:nth-child(2)', 'YumBaz Inc.') assert_select('td:last-child') do assert_select(['a[href=?]', send("edit_#{prefix}shiny_product_path", '46')], 'Edit') assert_select(['a[href=?]', send("delete_#{prefix}shiny_product_path", '46')], 'Delete') end end end end end end end
require "spec_helper" describe ReuniaosController do describe "routing" do it "routes to #index" do get("/reuniaos").should route_to("reuniaos#index") end it "routes to #new" do get("/reuniaos/new").should route_to("reuniaos#new") end it "routes to #show" do get("/reuniaos/1").should route_to("reuniaos#show", :id => "1") end it "routes to #edit" do get("/reuniaos/1/edit").should route_to("reuniaos#edit", :id => "1") end it "routes to #create" do post("/reuniaos").should route_to("reuniaos#create") end it "routes to #update" do put("/reuniaos/1").should route_to("reuniaos#update", :id => "1") end it "routes to #destroy" do delete("/reuniaos/1").should route_to("reuniaos#destroy", :id => "1") end end end
module Cabinet class AdminController < ApplicationController before_action :authenticate_user! before_action :authorize_user! layout "admin" def authorize_user! return render_not_authorized if current_user.customer? end end end
module HTTPalooza # Request presents a standard interface for describing an HTTP request that Players can translate into the underlying library's representation. class Request STANDARD_METHODS = [:get, :post, :put, :patch, :delete, :options, :head] attr_reader :url, :method, :params, :payload, :headers # @!attribute [r] url # @return [String] the URL to request # @!attribute [r] method # @return [Symbol] the HTTP method # @!attribute [r] params # @return [Hash] the URL parameters # @!attribute [r] payload # @return [String] the request body # @!attribute [r] headers # @return [Hash] the request headers # Instantiate a Request. # # @param [String] url the URL to request # @param [Symbol] method the HTTP method # @param [Hash] options additional options # @option options [Hash] :params the URL parameters # @option options [Hash] :headers the request headers # @option options [String] :payload the request payload def initialize(url, method, options = {}) @url = url @method = method @params = options[:params] || {} @payload = options[:payload] @headers = Rack::Utils::HeaderHash.new(options[:headers] || {}) normalize_url! end # @return [Boolean] whether or not the URL is SSL def ssl? !!(url.to_s =~ /^https/) end STANDARD_METHODS.each do |verb| define_method(:"#{verb}?") do method == verb end end private def normalize_url! raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http/ @url = url.kind_of?(Addressable::URI) ? url : Addressable::URI.parse(url) @url.query_values = (@url.query_values || {}).merge(params) @url.normalize! end end end
module BackpackTF module Price # Process reponses from IGetPrices class Response < BackpackTF::Response @response = nil @items = nil def self.raw_usd_value @response['raw_usd_value'] end def self.usd_currency @response['usd_currency'] end def self.usd_currency_index @response['usd_currency_index'] end def self.items @items ||= generate_items end def self.generate_items @response['items'].each_with_object({}) do |(name), items| defindex = @response['items'][name]['defindex'][0] if defindex.nil? || defindex < 0 # ignore this item else items[name] = Item.new(name, @response['items'][name]) end items end end end end end
RedisAdmin::Application.routes.draw do root :to => 'keys#index' end
#TODO # create second array for user input # merge those two arrays #Add the arrays # create second array for user input # add the arrays # reset = clear the second array require 'colorize' require 'pry' class Answers attr_accessor :response, :combo, :user_arr #comment def initialize @response_easter_egg = "Responses" @view_easter_egg = "View" @settings_easter_egg = "Settings" @user_arr = [] @default_response = [ "It is certain", "It is decidedly so", "Without a doubt", "You may rely on it", "Reply hazy try again", "I Cannot predict now", "Don't count on it", "My sources say no","Outlook not so good" ] @combo = [] @combo = @default_response + @user_arr end def question_input puts "I am the spooky Magic Eight Ball".colorize(:red) puts "ASK YOUR QUESTION, PEASANT".colorize(:red) question_input = gets.strip if question_input == @response_easter_egg puts "Oooooo You have unlocked a new ability...".colorize(:red) puts "You may now add your own Costom responses.".colorize(:red) add_answer elsif question_input == @view_easter_egg puts "Oooooo You have unlocked a new ability...".colorize(:red) puts "You may now view the Magic Responses.".colorize(:red) `say "You may now view the Magic Responses."` responses elsif question_input == @settings_easter_egg puts "Oooooo You have unlocked a new ability...".colorize(:red) puts "You may now view the Magic Eight Ball Settings.".colorize(:red) settings else question_out end end def question_out randomize = @combo.sample puts "#{randomize}".colorize(:red) end def add_answer puts "What response would you like to add?" user_input = gets.strip @user_arr << user_input add_another end def add_another puts "Would you like to add another? (y/n)" choice = gets.strip.downcase if choice == 'y' add_answer elsif choice == 'n' else puts "Invalid option." add_answer end end def settings puts "===========================".colorize(:red) print "========".colorize(:red) print " Settings ".colorize(:white) puts "========".colorize(:red) puts "===========================".colorize(:red) puts "1) Add Custom Response" puts "2) View Respoonses" puts "3) Reset Magic Eight Ball" puts "4) Main Menu" choice = gets.to_i case choice when 1 add_answer when 2 responses when 3 puts "The Magic Eight Ball has been reset" reset when 4 main_escape else puts "Invalid response, please try again." settings end end def responses puts "===========================".colorize(:red) print "=====".colorize(:red) print " View Responses ".colorize(:white) puts "======".colorize(:red) puts "===========================".colorize(:red) puts "Which resonses would you like to view?" puts "1) My custom responses" puts "2) Default responses" puts "3) All responses" puts "4) Settings" puts "5) Main Menu" choice = gets.strip.to_i case choice when 1 puts "Here are your custom responses:" puts @user_arr.each {|n| "n"} responses when 2 puts "Here are the default responses:" puts @default_reponse puts @default_response.each {|n| "n"} responses when 3 puts "Here are all of the responses:" puts @combo puts @combo.each {|n| "n"} responses when 4 settings when 5 main_escape else puts "Invalid response" responses end end def main_escape end def reset @user_arr = [] end end
require 'spec_helper' describe OpenAssets::Protocol::AssetDefinitionLoader, :network => :testnet do describe 'initialize' do context 'http or https' do subject{ OpenAssets::Protocol::AssetDefinitionLoader.new('http://goo.gl/fS4mEj').loader } it do expect(subject).to be_a(OpenAssets::Protocol::HttpAssetDefinitionLoader) end end context 'invalid scheme' do subject{ OpenAssets::Protocol::AssetDefinitionLoader.new('<http://www.caiselian.com>') } it do expect(subject.load_definition).to be_nil end end end describe 'create_pointer_redeem_script' do subject { OpenAssets::Protocol::AssetDefinitionLoader.create_pointer_redeem_script('https://goo.gl/bmVEuw', 'bWwvzRQ6Lux9rWgeqTe91XwbxvFuxzK56cx') } it do expect(subject.chunks[0]).to eq('u=https://goo.gl/bmVEuw') expect(subject.chunks[1]).to eq(Bitcoin::Script::OP_DROP) expect(subject.chunks[2]).to eq(Bitcoin::Script::OP_DUP) expect(subject.chunks[3]).to eq(Bitcoin::Script::OP_HASH160) expect(subject.chunks[4]).to eq('46c2fbfbecc99a63148fa076de58cf29b0bcf0b0'.htb) # bWwvzRQ6Lux9rWgeqTe91XwbxvFuxzK56cx のBitcoinアドレスのhash160 expect(subject.chunks[5]).to eq(Bitcoin::Script::OP_EQUALVERIFY) expect(subject.chunks[6]).to eq(Bitcoin::Script::OP_CHECKSIG) end end describe 'create_pointer_p2sh' do subject { OpenAssets::Protocol::AssetDefinitionLoader.create_pointer_p2sh('https://goo.gl/bmVEuw', 'bWwvzRQ6Lux9rWgeqTe91XwbxvFuxzK56cx') } it do expect(subject.is_p2sh?).to be true redeem_script = OpenAssets::Protocol::AssetDefinitionLoader.create_pointer_redeem_script('https://goo.gl/bmVEuw', 'bWwvzRQ6Lux9rWgeqTe91XwbxvFuxzK56cx') expect(subject.chunks[1]).to eq(Bitcoin.hash160(redeem_script.to_payload.bth).htb) end end describe 'redeem pointer p2sh' do it do issuance_tx = Bitcoin::Protocol::Tx.new('01000000010ae08e10dad8548a6e5eef11c5ff76f77ba865f186f6247d3d9502a59c37b588020000006b483045022100fc0d5caa16f3c21939a87b7724dca14c54b1be6a27b253bd1087009ec3873000022062a9b9e40028797526668cb07f91001f3d098461f0a610bd05db7888caac378a01210292ee82d9add0512294723f2c363aee24efdeb3f258cdaf5118a4fcf5263e92c9ffffffff03580200000000000017a914c590a1c93975aec75157e33ad904a74d2934e9d58700000000000000000b6a094f41010001d0860300f8d90000000000001976a91446c2fbfbecc99a63148fa076de58cf29b0bcf0b088ac00000000'.htb) tx = Bitcoin::Protocol::Tx.new tx.add_in(Bitcoin::Protocol::TxIn.from_hex_hash(issuance_tx.hash, 0)) tx.add_out(Bitcoin::Protocol::TxOut.value_to_address(100, 'mmy7BEH1SUGAeSVUR22pt5hPaejo2645F1')) def_url = 'https://goo.gl/bmVEuw' to = 'bWwvzRQ6Lux9rWgeqTe91XwbxvFuxzK56cx' redeem_script = OpenAssets::Protocol::AssetDefinitionLoader.create_pointer_redeem_script(def_url, to) sigunature = '3045022100a48fedcab731c5cbd583a5aa482f3efdf73e855105f8c66e44a5852c4f7a54a802202fb7c9ecf223bf072f97c90cd21bcfc9600f4b51fcd08ab3080ff0ebdd39678d' pubkey = '0292ee82d9add0512294723f2c363aee24efdeb3f258cdaf5118a4fcf5263e92c9' sig = Bitcoin::Script.to_pubkey_script_sig(sigunature.htb, pubkey.htb) script_sig = Bitcoin::Script.new(sig + Bitcoin::Script.pack_pushdata(redeem_script.to_payload)) tx.in[0].script_sig = script_sig.to_payload expect(tx.verify_input_signature(0, issuance_tx)).to be true end end end
# frozen_string_literal: true FactoryBot.define do factory :item do name { Faker::Lorem.words(3).join } end end
class OrdersController < ApplicationController before_action :authenticate_user! # TODO: talvez possa fazer tudo com o edit e o update def answer @order = Order.find(params[:id]) end def index @status = params[:status] unless @status.nil? @orders = Order.where(status: @status).order(created_at: :desc) else @orders = Order.all.order(created_at: :desc) end end def new @order = Order.new # puts current_user.employee.name # @order.order_items.build # @order.order_items.new @order.status = OrderStatus::REGISTERED @order.order_items.build @order.employee = current_user.employee end def edit @order = Order.find(params[:id]) end def create @order = Order.new(order_params) # @order.order_items.new(order_params) if @order.save redirect_to orders_path else render 'new' end end def update @order = Order.find(params[:id]) @answer = params[:answer] unless @answer.nil? @order.update_column(:status, OrderStatus::PREPARING) params.delete :answer flash[:success] = "Pedido atendido com sucesso. Acompanhe o preparo." redirect_to @order end if @order.update(order_params) redirect_to @order else render 'edit' end end def show @order = Order.find(params[:id]) if !params[:answer].nil? or params[:answer] === true @answer = true end end def destroy @order = Order.find(params[:id]) @order.destroy redirect_to orders_path end private def order_params params.require(:order).permit(:client_id, :employee_id, :value, :status, :order_item_ids, order_items_attributes: [:quantity, :pizza_id, :id]) end end
class Article < ApplicationRecord #association has_many :carousels, as: :carouselable, dependent: :destroy accepts_nested_attributes_for :carousels, allow_destroy: true #carrierwave uploader mount_uploader :image, ImageUploader mount_uploader :og_image, ImageUploader #tagging acts_as_taggable_on :tags #search include PgSearch pg_search_scope :search, against: {:title => 'A', :content => 'B', :author => 'c'}, :using => {:tsearch => {:prefix => true, :dictionary => "english"}} #number of articles from this month scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) } #group by month def self.by_month(month) where('extract(month from created_at) = ?', month) end # or use scope # scope :by_month, -> (month) {where('extract(month from created_at) = ?', month)} # or # scope :by_month, -> { |month| {:conditions => ["MONTH(created_at) = ?", month]}} ## defined in Application Controller?? def og_image? og_image.present? ? og_image.url : image.url end end
class RenameColumnInRectangles < ActiveRecord::Migration def change rename_column :rectangles, :fillColor, :fill_color end end
require "spec_helper" describe Destructive do context "when the user creates 5 destructive reports on 2012" do before { Timecop.freeze Time.new.change(year: 2012, month: 1, day: 1) } before do 5.times do r = Report.new dt = Destructive.new dt.report = r if not dt.save raise "Error creating the reports: "+dt.report.errors.full_messages.join(", ") end Timecop.freeze Time.now.advance(seconds: 1) end end it "starts with DT-12-5" do Report.first.uid.should == "DT-12-5" end it "ends with DT-12-1" do Report.last.uid.should == "DT-12-1" end context "when the user edits and saves a report" do let(:dt) { Destructive.first } let(:old_uid) { dt.report.uid } before do dt.project_title = "project 1" dt.save end it "uid should not change" do dt.report.uid.should == old_uid end end context "and then the user creates 5 more reports on 2013" do before { Timecop.freeze Time.new.change(year: 2013, month: 1, day: 1) } before do 5.times do r = Report.new dt = Destructive.new dt.report = r if not dt.save raise "Error creating the reports: "+dt.report.errors.full_messages.join(", ") end Timecop.freeze Time.now.advance(seconds: 1) end end it "starts with DT-13-5" do Report.first.uid.should == "DT-13-5" end it "ends with DT-12-1" do Report.last.uid.should == "DT-12-1" end end end after(:each) { Timecop.return } end
require "net/http" require "json" require "openssl" # Interface for connecting with M2X API service. # # This class provides convenience methods to access M2X most common resources. # It can also be used to access any endpoint directly like this: # # m2x = M2X::Client.new("<YOUR-API-KEY>") # m2x.get("/some_path") class M2X::Client DEFAULT_API_BASE = "https://api-m2x.att.com".freeze DEFAULT_API_VERSION = "v2".freeze CA_FILE = File.expand_path("../cacert.pem", __FILE__) USER_AGENT = "M2X-Ruby/#{M2X::Client::VERSION} #{RUBY_ENGINE}/#{RUBY_VERSION} (#{RUBY_PLATFORM})".freeze attr_accessor :api_key attr_accessor :api_base attr_accessor :api_version attr_reader :last_response def initialize(api_key=nil, api_base=nil) @api_key = api_key @api_base = api_base @api_version = api_version end # Returns the status of the M2X system. # # The response to this endpoint is an object in which each of its attributes # represents an M2X subsystem and its current status. # # @return {Response} the API Status def status get("/status") end # Obtain a Collection from M2X # # This method instantiates an instance of Collection and calls `Collection#view` # method, returning the collection instance with all its attributes initialized def collection(id) M2X::Client::Collection.new(self, "id" => id).tap(&:view) end # Creates a new collection on M2X with the specified parameters # # See {M2X::Client::Collection.create!} for more details def create_collection(params) M2X::Client::Collection.create!(self, params) end # Retrieve the list of collections accessible by the authenticated API key # # See {M2X::Client::Collection.list} for more details def collections(params={}) M2X::Client::Collection.list(self, params) end # List Sent Commands # # See {M2X::Client::Command.list} for more details def commands(params={}) M2X::Client::Command.list(self, params) end # View Command Details # # This method instantiates an instance of Command and calls `Command#view` # method, returning the command instance with all its attributes initialized def command(id) M2X::Client::Command.new(self, "id" => id).tap(&:view) end # Send command # # See {M2X::Client::Command.send!} for more details def send_command(params) M2X::Client::Command.send!(self, params) end # Obtain a Device from M2X # # This method instantiates an instance of Device and calls `Device#view` # method, returning the device instance with all its attributes initialized def device(id) M2X::Client::Device.new(self, "id" => id).tap(&:view) end # Creates a new device on M2X with the specified parameters # # See {M2X::Client::Device.create!} for more details def create_device(params) M2X::Client::Device.create!(self, params) end # Retrieve the list of devices accessible by the authenticated API key # # See {M2X::Client::Device.list} for more details def devices(params={}) M2X::Client::Device.list(self, params) end # Retrieve the list of devices accessible by the authenticated API key that # meet the search criteria. # # See {M2X::Client::Device.search} for more details def search_devices(params={}) M2X::Client::Device.list(self, params) end # Search the catalog of public Devices. # # This allows unauthenticated users to search Devices from other users that # have been marked as public, allowing them to read public Device metadata, # locations, streams list, and view each Devices' stream metadata and its # values. # # See {M2X::Client::Device.catalog} for more details def device_catalog(params={}) M2X::Client::Device.catalog(self, params) end # Obtain a Distribution from M2X # # This method instantiates an instance of Distribution and calls # `Distribution#view` method, returning the device instance with all # its attributes initialized def distribution(id) M2X::Client::Distribution.new(self, "id" => id).tap(&:view) end # Creates a new device distribution on M2X with the specified parameters # # See {M2X::Client::Distribution.create!} for more details. def create_distribution(params) M2X::Client::Distribution.create!(self, params) end # Retrieve list of device distributions accessible by the authenticated # API key. # # See {M2X::Client::Distribution.list} for more details def distributions(params={}) M2X::Client::Distribution.list(self, params) end # Obtain a Job from M2X # # This method instantiates an instance of Job and calls `Job#view` # method, returning the job instance with all its attributes initialized def job(id) M2X::Client::Job.new(self, "id" => id).tap(&:view) end # Obtain an API Key from M2X # # This method instantiates an instance of Key and calls # `Key#view` method, returning the key instance with all # its attributes initialized def key(key) M2X::Client::Key.new(self, "key" => key).tap(&:view) end # Create a new API Key # # Note that, according to the parameters sent, you can create a # Master API Key or a Device/Stream API Key. # # See {M2X::Client::Key.create!} for more details def create_key(params) M2X::Client::Key.create!(self, params) end # Retrieve list of keys associated with the user account. # # See {M2X::Client::Key.list} for more details def keys M2X::Client::Key.list(self) end # Obtain an Integration from M2X # # This method instantiates an instance of Integration and calls # `Integration#view` method, returning the integration instance with all its # attributes initialized def integration(id) M2X::Client::Integration.new(self, "id" => id).tap(&:view) end # Creates a new integration on M2X with the specified parameters # # See {M2X::Client::Integration.create!} for more details def create_integration(params) M2X::Client::Integration.create!(self, params) end # Retrieve list of integrations associated with the user account. # # See {M2X::Client::Integration.list} for more details def integrations M2X::Client::Integration.list(self) end # Method for {https://m2x.att.com/developer/documentation/v2/time Time} API # # @return (Response) text/plain response of the server time in all three formats def time get("/time").json end # Method for {https://m2x.att.com/developer/documentation/v2/time Time} API # # @return (Response) text/plain response of the server time in seconds def time_seconds get("/time/seconds").raw end # Method for {https://m2x.att.com/developer/documentation/v2/time Time} API # # @return (Response) text/plain response of the server time in millis def time_millis get("/time/millis").raw end # Method for {https://m2x.att.com/developer/documentation/v2/time Time} API # # @return (Response) text/plain response of the server time in ISO 8601 Format def time_iso8601 get("/time/iso8601").raw end # Define methods for accessing M2X REST API [:get, :post, :put, :delete, :head, :options, :patch].each do |verb| define_method verb do |path, qs=nil, params=nil, headers=nil| request(verb, path, qs, params, headers) end end private def request(verb, path, qs=nil, params=nil, headers=nil) url = URI.parse(File.join(api_base, versioned(path))) url.query = URI.encode_www_form(qs) unless qs.nil? || qs.empty? headers = default_headers.merge(headers || {}) body = if params headers["Content-Type"] ||= "application/x-www-form-urlencoded" case headers["Content-Type"] when "application/json" then JSON.dump(params) when "application/x-www-form-urlencoded" then URI.encode_www_form(params) else raise ArgumentError, "Unrecognized Content-Type `#{headers["Content-Type"]}`" end end options = {} options.merge!(use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_PEER, ca_file: CA_FILE) if url.scheme == "https" path = url.path path << "?#{url.query}" if url.query res = Net::HTTP.start(url.host, url.port, options) do |http| http.send_request(verb.to_s.upcase, path, body, headers) end @last_response = Response.new(res) end def api_base @api_base ||= DEFAULT_API_BASE end def api_version @api_version ||= DEFAULT_API_VERSION end def versioned(path) versioned?(path) ? path : "/#{api_version}#{path}" end def versioned?(path) path =~ /^\/v\d+\// end def default_headers @headers ||= { "User-Agent" => USER_AGENT }.tap do |headers| headers["X-M2X-KEY"] = @api_key if @api_key end end end
# # Copyright 2013, Seth Vargo <sethvargo@gmail.com> # Copyright 2013, Opscode, Inc. # # 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. # module CommunityZero # @author Seth Vargo <sethvargo@gmail.com> class Store # The number of cookbooks in the store. # # @return [Fixnum] # the number of cookbooks in the store def size _cookbooks.keys.size end # The full array of cookbooks. # # @example # [ # #<CommunityZero::Cookbook apache2>, # #<CommunityZero::Cookbook apt> # ] # # @return [Array<CommunityZero::Cookbook>] # the list of cookbooks def cookbooks _cookbooks.map { |_,v| v[v.keys.first] } end # Query the installed cookbooks, returning those who's name matches the # given query. # # @param [String] query # the query parameter # # @return [Array<CommunityZero::Cookbook>] # the list of cookbooks that match the given query def search(query) regex = Regexp.new(query, 'i') _cookbooks.collect do |_, v| v[v.keys.first] if regex.match(v[v.keys.first].name) end.compact end # Delete all cookbooks in the store. def destroy_all @_cookbooks = nil end # Add the given cookbook to the cookbook store. This method's # implementation prohibits duplicate cookbooks from entering the store. # # @param [CommunityZero::Cookbook] cookbook # the cookbook to add def add(cookbook) cookbook = cookbook.dup cookbook.created_at = Time.now cookbook.updated_at = Time.now entry = _cookbooks[cookbook.name] ||= {} entry[cookbook.version] = cookbook end alias_method :update, :add # Remove the cookbook from the store. # # @param [CommunityZero::Cookbook] cookbook # the cookbook to remove def remove(cookbook) return unless has_cookbook?(cookbook.name, cookbook.version) _cookbooks[cookbook.name].delete(cookbook.version) end # Determine if the cookbook store contains a cookbook. # # @see {find} for the method signature and parameters def has_cookbook?(name, version = nil) !find(name, version).nil? end # Determine if the cookbook store contains a cookbook. If the version # attribute is nil, this method will return the latest cookbook version by # that name that exists. If the version is specified, this method will only # return that specific version, or nil if that cookbook at that version # exists. # # @param [String] name # the name of the cookbook to find # @param [String, nil] version # the version of the cookbook to search # # @return [CommunityZero::Cookbook, nil] # the cookbook in the store, or nil if one does not exist def find(name, version = nil) possibles = _cookbooks[name] return nil if possibles.nil? version ||= possibles.keys.sort.last possibles[version] end # Return a list of all versions for the given cookbook. # # @param [String, CommunityZero::Cookbook] name # the cookbook or name of the cookbook to get versions for def versions(name) name = name.respond_to?(:name) ? name.name : name (_cookbooks[name] && _cookbooks[name].keys.sort) || [] end # Return the latest version of the given cookbook. # # @param [String, CommunityZero::Cookbook] name # the cookbook or name of the cookbook to get versions for def latest_version(name) versions(name).last end private # All the cookbooks in the store. # # @example # { # 'apache2' => { # '1.0.0' => { # 'license' => 'Apache 2.0', # 'version' => '1.0.0', # 'tarball_file_size' => 20949, # 'file' => 'http://s3.amazonaws.com...', # 'cookbook' => 'http://localhost:4000/apache2', # 'average_rating' => nil # } # } # } # # @return [Hash<String, Hash<String, CommunityZero::Cookbook>>] def _cookbooks @_cookbooks ||= {} end end end
module Ai class Tile attr_accessor :x, :y, :value, :merged def initialize x, y, value = 2, merged = false @x = x; @y = y; @value = value; @merged = false end end end
class AddColumnsToTasks < ActiveRecord::Migration def change # modify column change_column :tasks, :description, :text # adding new columns add_column :tasks, :category, :string add_column :tasks, :sub_category, :string add_column :tasks, :created_by, :string add_column :tasks, :assigned_to, :string add_column :tasks, :estimated_hours, :decimal add_column :tasks, :actual_hours, :decimal add_column :tasks, :completion_date, :datetime add_column :tasks, :delivery_date, :datetime add_column :tasks, :notes, :text end end
class AnswersController < ApplicationController before_action :authenticate_user! before_action :load_question before_action :load_answer, except: :create def create @answer = @question.answers.create(answer_params.merge(user: current_user)) end def update @answer.update(answer_params) if current_user.author_of?(@answer) end def destroy @answer.destroy if current_user.author_of?(@answer) end def accept @answer.accept! if current_user.author_of?(@question) end private def answer_params params.require(:answer).permit(:body) end def load_question @question = Question.find(params[:question_id]) end def load_answer @answer = Answer.find(params[:id]) end end
class CreateTalks < ActiveRecord::Migration def change create_table :talks do |t| t.integer :sender_user_id t.integer :sender_car_id t.integer :receiver_user_id t.integer :receiver_car_id t.boolean :received t.timestamps end add_index :talks, :sender_user_id add_index :talks, :sender_car_id add_index :talks, :receiver_user_id add_index :talks, :receiver_car_id end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string # email :string # login :string # created_at :datetime not null # updated_at :datetime not null # password_digest :string # remember_digest :string # roles :string(2) default("U") # # Indexes # # index_users_on_login (login) UNIQUE # class User < ApplicationRecord include Adauth::Rails::ModelBridge VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i Roles = { "U" => "user", "A" => "admin" } attr_accessor :remember_token before_save { login.downcase! } validates :name, presence: true, length: {maximum: 50} validates :email, presence: true, length: {maximum: 255}, format: {with: VALID_EMAIL_REGEX} validates :login, presence: true, length: {maximum: 255}, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6 }, allow_nil: true has_secure_password AdauthMappings = { :login => :login, :email => :email } AdauthSearchField = [:login, :login] # Returns boolean if user is admin def admin? roles.match(/A/) end # Returns list of roles as string def roles_to_s roles.split("").map {|ch| Roles[ch]}.join(",") end # Remembers a user in the database for use in persistent sessions. def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # Forgets a user. def forget update_attribute(:remember_digest, nil) end # Returns true if the given token matches the digest. def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end class << self # Returns the hash digest of the given string. def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token. def new_token SecureRandom.urlsafe_base64 end # Checks both authentication methods (local and AD) def authenticate(login,password) user = User.find_by(login: login.downcase) update_adauth_cfg(login,password) # first try local authentication, nil password means AD account if (user && !user.password_digest.nil? && user.authenticate(password)) user # then AD authentication elsif auser = Adauth.authenticate(login,password) User.return_and_create_from_adauth(auser) else false end end # Override Adauth finder to allow some further actions def return_and_create_from_adauth(ad_model) user = super(ad_model) # some AD are emailless, create dummy as our app requires it if user.email.blank? user.email = "unknown@unknown.com" end # create name begin user.name = "#{ad_model.first_name} #{ad_model.last_name}" rescue NoMethodError user.name=ad_model.login end user.save(validate: false) user end end end class User class << self private def update_adauth_cfg(login,password) Adauth.configure do |c| c.domain = AppConfig.get("ad_domain") if !AppConfig.get("ad_domain").nil? c.server = AppConfig.get("ad_controller") if !AppConfig.get("ad_controller").nil? c.base = AppConfig.get("ad_ldap_base") if !AppConfig.get("ad_ldap_base").nil? c.allowed_groups = AppConfig.get("ad_allowed_groups").split(",") if !AppConfig.get("ad_allowed_groups").nil? c.query_user=login c.query_password=password end end end end
class CategoryPage < SitePrism::Page element :parent_category_dropdown, :xpath, ".//form[@id='commentReplyForm']//div/select" element :title_field, :xpath, "//*[@id='commentReplyForm']//input[@name='title']" element :summary_field, :xpath, "//*[@id='commentReplyForm']//input[@name='desc']" element :tags_field, :xpath, "//*[@id='commentReplyForm']//input[@name='spigit_tags']" element :order_field, :xpath, "//*[@id='commentReplyForm']//input[@name='display_order']" element :moderate_idea_checkbox, :xpath, "//*[@id='commentReplyForm']//input[@name='moderate_ideas']" element :moderate_thread_checkbox, :xpath, "//*[@id='commentReplyForm']//input[@name='moderate_threads']" element :publish_button, :xpath, ".//*[@id='submit']" element :displayorder_field, :xpath, ".//*[@id='display_order']" element :savedraft_button, :xpath, ".//a[@title='Save Draft']" element :subscribe_checkbox, :xpath, ".//input[@type='checkbox'][@name='subscribe']" element :viewsectorwidget_container, '#view_sector_widget_fresh' element :categorystatswidget_container, '#panel308_1' element :control_panel_header, :xpath, ".//div[@class='widget']//div[div[contains(@style,'none;')]]//h2[a[text()='Category Control']]" element :edit_category_link, :xpath, ".//a[@title='Edit this Category']" element :post_an_idea_link, :xpath, ".//a/span[text()='Post an idea']" element :post_sub_category_link, :xpath, ".//a[@title='Create a sub category']" element :subscribe_link, :xpath, ".//span[text()='Subscribe']" element :unsubscribe_link, :xpath, ".//span[text()='Unsubscribe']" element :managespam_link, :xpath, ".//a[contains(@title,'Manage Spam')]" element :be_an_expert_link, :xpath, ".//a[span[text()='Be an Expert']]" #Be an Expert page element :edit_become_an_expert_button, :xpath, ".//span[text()='Edit']" element :submit_become_an_expert, :xpath, ".//span[text()='Submit']" element :message_editor_textarea, :xpath, ".//td[div[contains(@class,'mce-tinymce')]]" @@categoryContent = Hash.new { |h,k| h[k] = {} } #to save a category's field content def fillValue(field, value) case field when 'Title' then @mainpage = MainPage.new title_field.set @mainpage.addCategoryTitle(value) when 'Summary' then summary_field.set(value) when 'Description' then fillInTinyMCE(field,value) when 'Custom Title' then title_field.set(value) when 'Custom Description' then fillInTinyMCE('Description',value) when 'Tags' then tags_field.set(value) when 'Display Order' then order_field.set(value) when 'Display Order' then displayorder_field.set value else fail(ArgumentError.new("'#{field}' field doesn't exist.")) end sleep 1 end def fillInTinyMCE(tinymce, content) iframe = case tinymce when 'Description' then 'content_ifr' else fail(ArgumentError.new("'#{tinymce}' text area is not listed!")) end within_frame(iframe) do editor = page.find_by_id('tinymce') editor.click editor.native.clear editor.native.send_keys(content) end sleep 3 end def getTextFromTinyMCE(tinymce) iframe = case tinymce when 'Description' then 'content_ifr' else fail(ArgumentError.new("'#{tinymce}' text area doesn't exist.")) end within_frame(iframe) do editor = page.find_by_id('tinymce') editor.native.text end end def clickButton(button) case button when 'Publish' then publish_button.click sleep 2 when 'Save Draft' then savedraft_button.click sleep 2 when 'Submit Become an Expert' then submit_become_an_expert.click else fail(ArgumentError.new("'#{button}' button is not listed!")) end end def verifyCheckbox(checkbox) case checkbox when 'Subscribe' then return subscribe_checkbox.checked? else fail(ArgumentError.new("'#{checkbox}' checkbox is not listed!")) end end def setCheckbox(field, value) case field when 'Moderate Idea' then moderate_idea_checkbox.set value when 'Moderate Threads' then moderate_thread_checkbox.set value when 'Subscribe' then subscribe_checkbox.set value else fail(ArgumentError.new("'#{field}' field doesn't exist.")) end end def verifyLinkRedirection(category) @mainpage = MainPage.new categoryDisplayed = has_xpath?(".//*[@id='view_sector_widget_fresh']//h1[text()='#{@mainpage.getCategoryTitle(category)}']") return (current_url.include?('/Page/ViewSector?sectorid=') && categoryDisplayed) end def selectOptionByName(list, option_name) case list when 'Parent Category' then parent_category_dropdown.find('option', :text => option_name).select_option else fail(ArgumentError.new("'#{list}' list is not found.")) end end def verifyElementExists(element) wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds begin wait.until { case element when 'Parent Category' then has_parent_category_dropdown? when 'Title' then has_title_field? when 'Summary' then has_summary_field? when 'Tags' then has_tags_field? when 'Order' then has_order_field? when 'Moderate Idea' then has_moderate_idea_checkbox? when 'Moderate Threads' then has_moderate_thread_checkbox? when 'Publish' then has_publish_button? when 'Save Draft' then has_savedraft_button? when 'Subscribe' then has_subscribe_checkbox? when 'Unsubscribe' then has_unsubscribe_link? when 'Edit Become an Expert' then has_edit_become_an_expert_button? when 'Submit Become an Expert' then has_submit_become_an_expert? when 'Editor Message Become an Expert' then has_message_editor_textarea? end } rescue fail(ArgumentError.new("The element: '#{element}' was not displayed in 10 seconds.")) end end def expandWidget(widget) case widget when 'Category Control' then if has_control_panel_header? control_panel_header.click end else fail(ArgumentError.new("'#{widget}' widget is not listed.")) end end def clickLink(link) case link when 'Edit Category' then edit_category_link.click sleep 2 when 'Post an idea' then post_an_idea_link.click sleep 2 when 'Post Sub Category' then post_sub_category_link.click sleep 2 when 'Subscribe' then subscribe_link.click sleep 2 when 'Unsubscribe' then unsubscribe_link.click sleep 2 when 'Manage Spam' then managespam_link.click sleep 2 when 'Be an Expert' then be_an_expert_link.click else fail(ArgumentError.new("Link: #{link} is not listed.")) end end def getCategoryContent(category, data) @@categoryContent[category][data] end def addCategoryContent(category, data, categoryContent) @@categoryContent[category][data] = categoryContent end def verifyElementExistsWithText(element, text) @mainpage = MainPage.new @users = Users.new case element when 'Spam Title' then @mainpage.setCurrentIdea(text) return has_xpath?(".//tr/td/b[text()='#{@mainpage.getIdeaTitle(text)}']") when 'Description' then descriptionText = find(:xpath,".//tbody[tr[td[b[text()='#{@mainpage.getIdeaTitle(@mainpage.getCurrentIdea)}']]]]//p").text descriptionText.include?text when 'Idea Owner' then ownerName = @users.getUser(text,'firstname') + " " + @users.getUser(text,'lastname') return has_xpath?(".//td[b[text()='#{@mainpage.getIdeaTitle(@mainpage.getCurrentIdea)}']]/span/a[text()='#{ownerName}']") when 'Date/Time' then dateInfo = find(:xpath,".//td[b[text()='#{@mainpage.getIdeaTitle(@mainpage.getCurrentIdea)}']]/span").text datetime = DateTime.strptime(dateInfo[/By .* at (.*) ...\z/,1],'%m/%d/%Y %H:%M %p') return !datetime.nil? when 'Title' then return has_xpath?("//*[@id='commentReplyForm']//input[@value='#{@mainpage.getCategoryTitle(text)}']") when 'Description*' then return getTextFromTinyMCE('Description').include?text when 'Tags' then return has_xpath?(".//input[@id='spigit_tags'][@value='#{text}']") else fail(ArgumentError.new("ELEMENT #{element} WAS NOT FOUND!")) end end def approveDeletePendingIdea(type, action, idea_title) case type when 'Spam' then case action when 'Approve' then find(:xpath, ".//tr[td[b[text()='#{idea_title}']]]/td/a[@title='approve']").click when 'Delete' then find(:xpath, ".//tr[td[b[text()='#{idea_title}']]]/td/a[@title='Delete']").click end end end end
json.array!(@prodcutos) do |prodcuto| json.extract! prodcuto, :id, :codigo, :nombre, :fecha_vencimiento, :cantidad json.url prodcuto_url(prodcuto, format: :json) end
require 'rails_helper' describe 'Comment' do it 'is valid with a user' do expect(create_comment).to be_valid end it 'should have an associated user' do user = create_user comment = create_comment(user_id: user.id) expect(comment.user_id).to eq(user.id) end end
class Book < ActiveRecord::Base attr_accessible :title has_many :pictures, :dependent => :destroy belongs_to :user end
# frozen_string_literal: true class UsersController < ApplicationController # POST /users def create form = Account::SignUpForm.new(user_params) if form.save render(json: SimpleResponse.call(200, 'ok')) else render(json: SimpleError.call(400, form.errors)) end end # GET /users def index users = Account::User.all render(json: users) end private def user_params params.require(:user).permit(:email, :password) end end
class PurchasesController < ApplicationController before_action :logged_in_user, only: [:create] def create secure_post = params.require(:purchase).permit(:guitarid, :delivery, :address, :country) @purchase = current_user.purchases.build(secure_post) if @purchase.save flash[:success] = "Purchase placed" redirect_to current_user else redirect_to :back flash[:error] = "Purchase failed" end end def correct_user @purchase = current_user.purchases.find_by(id: params[:id]) redirect_to root_url if @purchase.nil? end end
# frozen_string_literal: true require 'datadog/lambda' require 'yake' module Yake module Datadog class MockContext < Struct.new( :clock_diff, :deadline_ms, :aws_request_id, :invoked_function_arn, :log_group_name, :log_stream_name, :function_name, :memory_limit_in_mb, :function_version) def invoked_function_arn @invoked_function_arn ||= begin region = ENV['AWS_REGION'] || ENV['AWS_DEFAULT_REGION'] || 'us-east-1' "arn:aws:lambda:#{region}:123456789012:function-name" end end end module DSL include Yake::DSL ## # Datadog handler wrapper def datadog(name, &block) define_method(name) do |event:nil, context:nil| context ||= MockContext.new ::Datadog::Lambda.wrap(event, context) do Yake.wrap(event, context, &block) end end end end end end extend Yake::Datadog::DSL
require 'rails_helper' RSpec.describe UsersHelper, type: :helper do describe '#super_admin?' do context 'when user is super admin' do let(:user) { double(email: 'admin@arsenal.com.br') } it 'returns true' do expect(helper.super_admin?(user)).to be_truthy end end context 'when user is not super admin' do let(:user) { double(email: 'user@arsenal.com.br') } it 'returns false' do expect(helper.super_admin?(user)).to be_falsy end end end end
load 'deploy' if respond_to?(:namespace) # cap2 differentiator require 'rubygems' require 'rexml/document' #require 'bells/recipes/apache' # This one requires the Bells gem set :application, "musicbox" set :domain, "stg.mobile" role :app, "stg.mobile" # Set the Unix user and group that will actually perform each task # on the remote server. The defaults are set to 'deploy' set :user, "www-data" set :group, "www-data" # Deployment Settings set :repository_base, 'git@git.intra.sapo.pt' set :app_repository, 'musicbox' set :repository, "#{repository_base}:#{app_repository}" set :deploy_app_to, "/fasmounts/sapo/mobile/#{application}" # This is where your project will be deployed. #other directories set :tmp_dir, "/var/tmp/#{application}" ssh_options[:username] = 'www-data' #before :deploy, :choose_tag #after :deploy, :create_svn_release_tag namespace :deploy do # Overwritten to provide flexibility for people who aren't using Rails. task :setup do # create release dir dirs = [deploy_app_to, "#{deploy_app_to}/releases/"] #, "/var/www/#{application}" run "umask 02 && mkdir -p #{dirs.join(' ')}" run "umask 02 && mkdir -p #{tmp_dir}" run "umask 02 && mkdir -p #{tmp_dir}/smarty_cache/" run "umask 02 && mkdir -p #{tmp_dir}/smarty_templates/" run "umask 02 && mkdir -p #{tmp_dir}/mtemplates/" end # Also overwritten to remove Rails-specific code. task :finalize_update do end task :update_code do exportApp() runRemote "cd #{deploy_app_to}/releases && chown -R www-data:www-data #{$app_export_dirname}" runRemote "cd #{deploy_app_to}/releases/#{$app_export_dirname} && cp bootstrap.lab.php bootstrap.php" runRemote "cd #{deploy_app_to}/ && rm -f current && ln -s releases/#{$app_export_dirname} current" runRemote "rm -f /var/www/#{application} && ln -s #{deploy_app_to}/current/web /var/www/#{application}" end # Each of the following tasks are Rails specific. They're removed. task :migrate do end task :migrations do end task :cold do end task :start do end task :stop do end task :symlink do end # Do nothing in apache (To restart apache, run 'cap deploy:apache:restart') task :restart do #recreate soft link end task :create_symlink do end end def getCurrentTime() if (!$currtime) then $currtime=`date +%Y%m%d%H%M%S` $currtime.strip! end return $currtime end def runLocal(cmd) printf("\n - Running Locally: %s\n", cmd); system cmd end def runRemote(cmd) printf("\n @ Running remotely: %s\n", cmd); run cmd end def exportApp() getCurrentTime() $app_export_dirname="#{$currtime}" runLocal "git archive --remote=#{repository} lab | gzip > /tmp/#{$app_export_dirname}.tar.gz" runLocal "scp /tmp/#{$app_export_dirname}.tar.gz #{user}@#{domain}:/tmp/" runRemote "mkdir #{deploy_app_to}/releases/#{$app_export_dirname} && tar xzf /tmp/#{$app_export_dirname}.tar.gz -C #{deploy_app_to}/releases/#{$app_export_dirname} && rm /tmp/#{$app_export_dirname}.tar.gz" end
class ReplaceSharedStringAst attr_accessor :shared_strings def initialize(shared_strings) @shared_strings = shared_strings.map do |s| s[/^(.*?)\n$/,1] end end def map(ast) if ast.is_a?(Array) operator = ast.shift if respond_to?(operator) send(operator,*ast) else [operator,*ast.map {|a| map(a) }] end else return ast end end def shared_string(string_id) [:string,shared_strings[string_id.to_i]] end end class ReplaceSharedStrings def self.replace(values,shared_strings,output) self.new.replace(values,shared_strings,output) end # Rewrites ast with shared strings to strings def replace(values,shared_strings,output) rewriter = ReplaceSharedStringAst.new(shared_strings.readlines) values.each_line do |line| # Looks to match shared string lines if line =~ /\[:shared_string/ ref, ast = line.split("\t") output.puts "#{ref}\t#{rewriter.map(eval(ast)).inspect}" else output.puts line end end end end
class SubtaskSerializer include FastJsonapi::ObjectSerializer attributes :title, :estimated_duration end
require 'test_helper' class AllDelegatesControllerTest < ActionController::TestCase setup do @all_delegate = all_delegates(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:all_delegates) end test "should get new" do get :new assert_response :success end test "should create all_delegate" do assert_difference('AllDelegate.count') do post :create, all_delegate: @all_delegate.attributes end assert_redirected_to all_delegate_path(assigns(:all_delegate)) end test "should show all_delegate" do get :show, id: @all_delegate.to_param assert_response :success end test "should get edit" do get :edit, id: @all_delegate.to_param assert_response :success end test "should update all_delegate" do put :update, id: @all_delegate.to_param, all_delegate: @all_delegate.attributes assert_redirected_to all_delegate_path(assigns(:all_delegate)) end test "should destroy all_delegate" do assert_difference('AllDelegate.count', -1) do delete :destroy, id: @all_delegate.to_param end assert_redirected_to all_delegates_path end end
class Site < ActiveRecord::Base extend DeleteableModel has_and_belongs_to_many :users, join_table: "site_users" attr_accessible :description @@gridColumns = {:id => "Id", :name => "Name", :description => "Description", :created_at => "Created At"} @@gridRenderers = {:created_at => 'dateRenderer'} @@columnOrder = {:created_at => "desc"} def self.gridColumns @@gridColumns end def self.gridRenderers @@gridRenderers end def self.columnOrder @@columnOrder end def self.find_site_by_name(site_name) return Site.find_by_name site_name.upcase end end
# Install StreamMachine include_recipe "nodejs" include_recipe "git" if node.streammachine.install_ffmpeg include_recipe "streammachine::ffmpeg" end if node.streammachine.install_redis include_recipe "streammachine::install_redis" end # -- Create our User -- # user node.streammachine.user do action :create system true shell "/bin/bash" supports :manage_home => false end # -- Create our Log Directory -- # directory "/var/log/streammachine" do action :create mode 0755 owner node.streammachine.user recursive true end # -- Install the code -- # # Install StreamMachine, unless we already have the version requested source = (node.streammachine.version.to_sym == :master) ? "StreamMachine/StreamMachine" : "streammachine@#{node.streammachine.version}" execute "npm install -g #{source}" do #environment({ # "PATH" => "/usr/bin:/usr/local/bin" #}) not_if do if node.streammachine.version.to_sym == :master false else json = `npm list -g streammachine --json` begin obj = JSON.parse json if obj["dependencies"] && obj["dependencies"]["streammachine"]["version"] == node.streammachine.version true else false end rescue false end end end end # -- Write our config file -- # # Look for the databag log "Looking for StreamMachine config in databag #{node.streammachine.databag}/#{node.streammachine.config}" item = data_bag_item( node.streammachine.databag, node.streammachine.config ) if item && item.has_key?("config") # convert config to JSON config_json = JSON.pretty_generate item["config"] # replace our directory #config_json.gsub! "!DIR!", node.streammachine.dir file "/etc/streammachine.json" do action :create content config_json user node.streammachine.user end else log "Failed to find StreamMachine config at #{node.streammachine.databag}/#{node.streammachine.config}" end # -- Create and start our service -- # include_recipe "runit" runit_service "streammachine" do default_logger true options({ user: node.streammachine.user, config: "/etc/streammachine.json", }) end
require "spec_helper" describe ActiveRecord::Turntable::Migration do describe ".target_shards" do subject { migration_class.new.target_shards } context "With clusters definitions" do let(:migration_class) { Class.new(ActiveRecord::Migration[5.0]) { clusters :user_cluster } } let(:cluster_config) { ActiveRecord::Base.turntable_config[:clusters][:user_cluster] } let(:user_cluster_shards) { cluster_config[:shards].map { |s| s[:connection] } } it { is_expected.to eq(user_cluster_shards) } end context "With shards definitions" do let(:migration_class) { Class.new(ActiveRecord::Migration[5.0]) { shards :user_shard_01 } } it { is_expected.to eq([:user_shard_01]) } end end end
# frozen_string_literal: true module Bolt module Transport class Local < Sudoable OPTIONS = { "interpreters" => "A map of an extension name to the absolute path of an executable, "\ "enabling you to override the shebang defined in a task executable. The "\ "extension can optionally be specified with the `.` character (`.py` and "\ "`py` both map to a task executable `task.py`) and the extension is case "\ "sensitive. When a target's name is `localhost`, Ruby tasks run with the "\ "Bolt Ruby interpreter by default.", "run-as" => "A different user to run commands as after login.", "run-as-command" => "The command to elevate permissions. Bolt appends the user and command "\ "strings to the configured `run-as-command` before running it on the target. "\ "This command must not require an interactive password prompt, and the "\ "`sudo-password` option is ignored when `run-as-command` is specified. The "\ "`run-as-command` must be specified as an array.", "sudo-executable" => "The executable to use when escalating to the configured `run-as` user. This "\ "is useful when you want to escalate using the configured `sudo-password`, since "\ "`run-as-command` does not use `sudo-password` or support prompting. The command "\ "executed on the target is `<sudo-executable> -S -u <user> -p custom_bolt_prompt "\ "<command>`. **This option is experimental.**", "sudo-password" => "Password to use when changing users via `run-as`.", "tmpdir" => "The directory to copy and execute temporary files." }.freeze def self.options OPTIONS.keys end def provided_features ['shell'] end def self.validate(options) validate_sudo_options(options) end def with_connection(target, *_args) conn = Shell.new(target) yield conn end def connected?(_targets) true end end end end require 'bolt/transport/local/shell'
class Subway < ActiveRecord::Base has_many :restaurant_subways, dependent: :destroy has_many :restaurants, :through => :restaurant_subways end
require "test_helper" describe ArInterval do it "has a version number" do refute_nil ::ArInterval::VERSION end before do Occurence.destroy_all end it "has Occurence test model configured" do assert Occurence.count == 0 end describe "one occurence" do before do Occurence.create( start_time: DateTime.new(2021,2,12,12,02), interval: "P1DT3H18M", ) end it { _(Occurence.count) == 1 } end describe "Occurence.occuring(at)" do let(:at) { DateTime.new(2021,2,13,15,30) } subject { Occurence.occuring(at) } before do Occurence.create( start_time: DateTime.new(2021,2,12,12,02), interval: "P1DT3H18M", ) end it { _(subject.count) == 1 } describe "records" do it "all #occuring?(at)" do _(subject.all? {|occurence| occurence.occuring?(at) }).must_equal true end end end describe "#interval=" do describe "not an interval" do subject { Occurence.new(interval: "P1D3H18M") } it { _(subject).wont_be :valid? } end end end
class CvSweeper < ActionController::Caching::Sweeper observe Person, Company, Project, Responsibility, Skill, School, Task def after_create(record) expire_page root_url end def after_update(record) expire_page root_url end def after_destroy(record) expire_page root_url end end
require_relative 'db_connection' require_relative '01_mass_object' require 'active_support/inflector' require 'debugger' class MassObject def self.parse_all(results) parsed_all = [] results.each do |result| object = self.new(result) parsed_all << object end parsed_all end end class SQLObject < MassObject def self.columns @column_array ||= begin column_array = DBConnection.execute2("SELECT * FROM #{table_name}") column_array = column_array.first column_array.each do |column| define_method(column) { self.attributes[column.to_sym] } define_method("#{column}=") { |val| self.attributes["#{column}".to_sym] = val } end column_array end end def self.table_name=(table_name) @table_name = table_name end def self.table_name table_name = self.to_s.tableize @table_name ||= table_name end def self.all cats = DBConnection.execute(<<-SQL) SELECT #{table_name}.* FROM #{table_name} SQL cat_objects = [] cats.each do |cat| cat_objects << self.new(cat) end cat_objects end def self.find(id) cat = DBConnection.execute(<<-SQL) SELECT #{table_name}.* FROM #{table_name} WHERE #{table_name}.id = #{id} SQL cat = cat[0] new_object = self.new(cat) end def attributes @attributes ||= {} end def insert col_names = self.attributes.keys.join(", ") DBConnection.execute(<<-SQL) INSERT INTO #{self.class.table_name} (#{col_names}) VALUES ('#{self.attribute_values.join("', '")}') SQL self.id = DBConnection.last_insert_row_id end def initialize(options = {}) options.each do |attr_name, value| raise "unknown attribute '#{attr_name}'" unless self.class.columns.include?(attr_name.to_s) self.attributes[attr_name.to_sym] = value end end def save if id.nil? self.insert else self.update end end def update DBConnection.execute(<<-SQL) UPDATE #{self.class.table_name} SET #{self.attributes.map{|key,value| "#{key} = '#{value}'"}.join(', ')} WHERE #{self.class.table_name}.id = #{self.id} SQL end def attribute_values @attributes.values end end
require 'i18n' class EventNotificationJob < ActiveJob::Base queue_as :notifications def perform(event_id, chat_id) event = Event.find_by(id: event_id).to_s Telegram.bot.send_message(chat_id: chat_id, text: I18n.t('event_string', event: event)) end end
class New < ActiveRecord::Base validate :validation_method attr_accessible :photo, :title, :description, :show, :date, :photo_file_name, :link has_attached_file :photo, :styles => { :thumb=> "50x45#", :medium => "110x100#", :large => "550x310#{}" } def validation_method errors.add(:description, "Debes ingresar una descripcion mayor a 50 caracteres.") if description.blank? or description.size < 50 errors.add(:title, "Debes ingresar un titulo.") if title.blank? errors.add(:photo, "Si vas a mostrar esta noticia en la home, debes cargarle una foto.") if invalid_photo? end def invalid_photo? self.show == true and self.photo_file_name.nil? end end
class CreateUsers < ActiveRecord::Migration[5.0] # Set'up' def up create_table :users do |t| # Longhand t.column "name", :string # Shorthand t.boolean "anonymous", :default => false t.timestamps # 't.timestamps' auto creates both 'created_at' and 'updated_at' fields # t.datetime :created_at # t.datetime :updated_at end end # Tear'down' def down drop_table :users end end
class BirthdayDealVoucherStateTransition < ActiveRecord::Base belongs_to :birthday_deal_voucher end
require_relative 'rental' require_relative 'rental_action' class RentalModification attr_reader :id, :rental, :start_date, :end_date, :distance def initialize(args) @id = args[:id] @rental = args[:rental] @start_date = args[:start_date] @end_date = args[:end_date] @distance = args[:distance] end def modified_rental Rental.new( id: rental.id, car: rental.car, start_date: start_date || rental.start_date, end_date: end_date || rental.end_date, distance: distance || rental.distance, options: rental.options ) end def actions rental.actions.map.with_index do |rental_action, index| delta = modified_rental.actions[index].amount - rental_action.amount RentalAction.new( who: rental_action.who, type: action_type(rental_action.type, delta), amount: delta.abs ) end end def to_hash { id: id, rental_id: rental.id, actions: actions.map { |action| action.to_hash } } end private def action_type(original_type, delta) if delta < 0 return 'debit' if original_type == 'credit' return 'credit' if original_type == 'debit' else return original_type end end end
class TagsController < ApplicationController caches_page :index # GET /blogs/1/tags # GET /blogs/1/users/1/tags def index @blog = Blog.published.find(params[:blog_id]) if params[:user_id] @user = User.find(params[:user_id]) @tags = @blog.tags.by_user(@user) elsif @blog @tags = @blog.tags.find(:all, :limit => 50) end end end
require_relative '../lib/identifier_replacer' describe IdentifierReplacer do let(:code) do %q^this.is(someCode)^ end let(:words) do ['the', 'bear', 'car'] end it 'replaces the code with the words' do expect(IdentifierReplacer.replace(code, words)).to eq 'the.bear(car)' end end
class ShippingAddressesController < ApiController load_and_authorize_resource before_action :authenticate_user! before_action :set_shipping_address, only: [:update, :deactivate] # POST /shipping_addresses def create begin @shipping_address = ShippingAddress.create!(shipping_address_params) current_user.shipping_addresses << @shipping_address render json: @shipping_address rescue Exception => e @shipping_address = ShippingAddress.new @shipping_address.errors.add(:error_creating_shipping_address, e.message) render json: ErrorSerializer.serialize(@shipping_address.errors), status: 500 end end # PATCH/PUT /shipping_addresses/[id] def update if @shipping_address.update(shipping_address_params) render json: @shipping_address else render json: ErrorSerializer.serialize(@shipping_address.errors), status: 500 end end # GET /shipping_addresses/get_all_for_user def get_all_for_user begin @shipping_addresses = current_user.shipping_addresses.available render json: @shipping_addresses rescue Exception => e @shipping_address = ShippingAddress.new @shipping_address.errors.add(:error_getting_shipping_addresses, "Error obteniendo direcciones para el usuario") render json: ErrorSerializer.serialize(@shipping_address.errors), status: 500 end end def deactivate begin @shipping_address.deactivate render json: @shipping_address rescue Exception => e @shipping_address = ShippingAddress.new @shipping_address.errors.add(:error_deactivating_shipping_address, e.message) render json: ErrorSerializer.serialize(@shipping_address.errors), status: 500 end end private def set_shipping_address @shipping_address = ShippingAddress.find(params[:id]) end def shipping_address_params params.require(:shipping_address).permit(:location, :address, :state, :country, :zip, :city, :name, :phone, :reference, :between_streets) end end
class Customer < ActiveRecord::Base attr_accessible :email, :first_name, :last_name, :anonymous_donation, :billing_address_attributes, :terms, :communicate_with_site has_many :certificates has_many :newsletter_subscriptions, :dependent => :destroy has_address :billing accepts_nested_attributes_for :billing_address acts_as_buyer attr_accessor :terms, :communicate_with_site # Also validated on ActiveMerchant::Billing::CreditCard validates :first_name, :last_name, :presence => true validates :email, :presence => true validates :email, :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }, :if => Proc.new {|c| c.email.present?} validates :terms, :acceptance => true validates :anonymous_donation, :inclusion => {:in => [true, false]} after_create :create_customer_newsletter_subscriptions! def name result = [] result << first_name result << last_name result.reject(&:blank?).join(" ") end def site_newsletter_subscriptions newsletter_subscriptions.where(:merchant_id => nil, :charity_id => nil) end def communicate_with_site? !!communicate_with_site.to_s.match(/^true|1/) end private def create_customer_newsletter_subscriptions! newsletter_subscriptions.create! if communicate_with_site? end end
# FIND # Find out how to access files with and without code blocks. What is the benefit of the code block? # Using File.open # Without a block, we open a file that is always open for our use throughout the code. # It will only close if we tell it to or the program terminates # also what is returned by File.open is the File object # By using a block, the file is automatically closed after the block executes # what is returned by File.open{} is the result of the block # How would you translate a hash into array? # if we want to maintain key-value pairs, simply call `.to_a` on the hash # This will return a multidimensional array, where each "row" contains the key-value pair # if we just want the keys of the hash as an array, simply call `.keys` on the hash # if we just want the values of the hash as an array, simply call `.values` on the hash # Can to translate arrays to hashes? # Yes, but they have to be a very specific form # They have to be a multi-dimensional array as mentioned above # for example: # arr = [[:a,1],[:b,2],[:c,3]] # puts Hash[arr] # This will print {:a => 1, :b => 2, :c => 3} # Can you iterate through a hash? # Yes, we can use iterators like `each` or `map` but unlike an array # the block will have two arguments: one for the key and one for the value # example: # {a:1,b:2,c:3}.each{|k,v| puts "Key: #{k}, Value: #{v}"} # You can use Ruby arrays as stacks. What other common data structures do arrays support? # Queues - FIFO # Sets # Matrices # DO # Print the contents of an array of sixteen numbers, four numbers at a time, using just `each`. arr = (1..16).to_a.shuffle arr.each_with_index{|a,i| print "#{a}#{((i+1) % 4 == 0) ? "\n" : ","}" } # Now, do the same with `each_slice` in `Enumerable`. arr.each_slice(4){|a| puts a.join(",")} # The `Tree` class was interesting, but it did not allow you to specify # a new tree with a clean user interface. Let the initializer accept a # nested structure of hashes. You should be able to specify a tree # like this: {'grandpa' => { 'dad' => { 'child 1' => {}, 'child 2' => {}}, 'uncle' => { # 'child 3' => {}. 'child 4' => {}}}} class Tree attr_accessor :children, :node_name def self.build_from_hash(hash) node_name = hash.keys.first children = hash[node_name].map do |child, their_children| Tree.build_from_hash(child => their_children) end new(node_name, children) end def initialize(name, children=[]) @node_name = name @children = children end def visit_all(&block) visit(&block) children.each{|c| c.visit_all(&block)} end def visit(&block) block.call(self) end end tree = Tree.build_from_hash({ grandpa:{ dad:{ child_one: {}, child_two: {} }, uncle: { child_three: {}, child_four: {} } } }) puts "Visiting top of tree..." tree.visit{|n| puts n.node_name} puts "Visiting entire tree..." tree.visit_all{|n| puts n.node_name} # Write a simple `grep` that will print the lines of a file having any occurrences of a # phrase anywhere in that line. You will need to do a simple regex match and read lines # from a file. If you want, include line numbers. print "Enter phrase to search for>" phrase = gets.chomp File.open("#{__dir__}/day_2.txt").each_with_index do |line, line_number| puts "#{line_number}: #{line}" if line.include?(phrase) end
class Api::AuthorsController < ApplicationController def index @authors = Author.all render 'index.json.jbuilder' end def create @author = Author.new( first_name: params[:first_name], last_name: params[:last_name], biography: params[:biography] ) if @author.save render json: {message: "Author created successfully"}, status: :created else render json: {errors: @author.errors.full_messages}, status: :bad_request end end def show @author = Author.find(params[:id]) render 'show.json.jbuilder' end def update @author = Author.find(params[:id]) @author.first_name = params[:first_name] || @author.first_name @author.last_name = params[:last_name] || @author.last_name @author.biography = params[:biography] || @author.biography if @author.save render 'show.json.jbuilder' else render json: {errors: @author.errors.full_messages}, status: :unprocessable_entity end end def destroy author = Author.find(params[:id]) author.destroy render json: {message: "Successfully removed author."} end end
class AddTableAppointmentsServices < ActiveRecord::Migration def up create_table :appointments_services, id: false do |t| t.integer :appointment_id t.integer :service_id end end def down drop_table :appointments_services end end
module CDI module V1 module ServiceConcerns module MultimediaParams extend ActiveSupport::Concern WHITELIST_ATTRIBUTES = [ :file, :link, :name, :category_ids, :tags ] included do def multimedia_params @multimedia_params ||= filter_hash(@options[:multimedia], WHITELIST_ATTRIBUTES) # puts "@@@ #{@multimedia_params[:file]}" @multimedia_params[:multimedia_type] = multimedia_type_from_params if multimedia_type_from_params.present? @multimedia_params[:metadata] = metadata_from_params if metadata_from_params.present? @multimedia_params[:tags] = tags_from_params @multimedia_params[:status] = "social_published" if social_published? @multimedia_params[:category_ids] = categories_from_params @multimedia_params end def categories_from_params array_values_from_params(@options, :category_ids, :multimedia) end def tags_from_params array_values_from_params(@options, :tags, :multimedia) end def multimedia_type_from_params return 'link' if @multimedia_params[:link].present? if @multimedia_params[:file].present? info = @multimedia_params[:file][:type] ::Multimedia::MULTIMEDIA_TYPES.each do |key, items| items.each do |item| if info.include? item return key end end end return 'unknown' end nil end def metadata_from_params if @multimedia_params[:file] return { file_size: @multimedia_params[:file][:tempfile].size } elsif @multimedia_params[:link] return { url: @multimedia_params[:link] } end nil end def social_published? @options[:multimedia][:social] == 1 end end end end end end
require "openssl" require "webrick" require "logstash/namespace" require "logstash/inputs/base" require "thread" # Reads log events from a http endpoint. # # Configuring this plugin can be done using the following basic configuration: # # input { # http { } # } # # This will open a http server on port 8000 that accepts messages in the JSON # format. You can customize the port and bind address in the options of the # plugin. class LogStash::Inputs::Http < LogStash::Inputs::Base config_name "http" milestone 1 default :codec, "json" # The port to listen on. Default is 8000. config :port, :validate => :number, :default => 8000 # The address to bind on. Default is 0.0.0.0 config :address, :validate => :string, :default => "0.0.0.0" # The mode to run in. Use 'client' to pull requests from a specific url. # Use 'server' to enable clients to push events to this plugin. config :mode, :validate => :string, :default => 'server' # The url to fetch the log events from when running in client mode. # Currently supports only GET based requests. config :url, :validate => :string, :required => false # The interval between pull requests for new log events in milliseconds. # By default polls every second for new data. Increase or decrease as needed. config :interval, :validate => :number, :default => 1000 def register options = { :Port => @port, :BindAddress => @address } # Start a basic HTTP server to receive logging information. @http_server = WEBrick::HTTPServer.new options end def run(output_queue) if @mode == 'server' runserver output_queue else runclient output_queue end end def runclient(output_queue) while not @interrupted do begin output_queue << pull_event # Check if an interrupt came through. # When it did, stop this process. if @interrupted break end # Wait for the interval to pass, rinse and repeat the whole process. sleep @interval rescue LogStash::ShutdownSignal @interrupted = true break rescue Exception => error @logger.debug("Failed to retrieve log data from source.") end end end def pull_event() codec = @codec.clone # Download potentially new log data from the specified URL # Not using accept-type in the request, because we don't know the # content-type until we process it using the codec. response_body = HTTP.get @url # Use the codec to decode the data into something useful. codec.decode(response_body) do |event| # Decorate the event with the mandatory logstash stuff. decorate(event) return event end end def runserver(output_queue) begin @mutex = Mutex.new @wait_handle = ConditionVariable.new # Register a custom procedure with the HTTP server so that we can receive log messages # and process them using this plugin. @http_server.mount_proc '/' do |req, res| codec = @codec.clone # Decode the incoming body and store it in the event queue. codec.decode(req.body) do |event| # Add additional logging data to the event event["host"] = req.peeraddr # Decorate the event with the mandatory logstash stuff. decorate(event) # Push the event in the output queue output_queue << event end # Send a HTTP 100 continue response without content. # This acknowledges the logger that the content was received. res.status = 200 res.body = "{ \"status\": \"OK\" }" end # Start the webserver. # Start a separate thread for the http server @server_thread = Thread.new do @http_server.start end @logger.info "HTTP listener registered on #{@address}:#{@port}." # This somewhwat weird construction is required, because Logstash expects the run # method to run forever. Which is the case right here ;-) @mutex.synchronize do @wait_handle.wait(@mutex) end ensure # Close the HTTP server at the end of the run method. # This ensures that the sockets used are closed. @http_server.shutdown end end def teardown if @mode == 'server' # Interrupt the listener and stop the process. @mutex.synchronize do @wait_handle.signal end else # Interrupt the client @interrupted = true end end end
class ExperimentWatcher def self.watch_experiments Rails.logger.debug('[experiment_watcher] Watch experiments') Thread.new do while true do Rails.logger.debug("[experiment_watcher] #{Time.now} --- running") DataFarmingExperiment.get_running_experiments.each do |experiment| Rails.logger.debug("Experiment: #{experiment}") begin experiment.find_simulation_docs_by({is_done: false, to_sent: false}).each do |simulation| Rails.logger.debug("#{Time.now - simulation['sent_at']} ? #{experiment.time_constraint_in_sec * 2}") if Time.now - simulation['sent_at'] >= experiment.time_constraint_in_sec * 2 simulation['to_sent'] = true experiment.progress_bar_update(simulation['id'], 'rollback') experiment.save_simulation(simulation) end end rescue Exception => e Rails.logger.debug("Error during experiment watching #{e}") end end sleep(600) end end end end
require 'rails_helper' RSpec.describe Home, type: :model do describe "Associations" do it { should have_many(:rents) } end end
class CreateDevices < ActiveRecord::Migration[6.0] def change create_table :devices do |t| t.integer :actor_id, null: false t.string :actor_type, null: false, limit: 32 t.integer :user_id, null: false t.string :uuid, null: false, limit: 64 t.string :refresh_token, null: false, limit: 32 t.string :last_issued, null: false, limit: 32 t.datetime :last_issued_at, null: false t.integer :expires_at, null: false t.string :user_agent, null: false t.string :ip, null: false, limit: 32 t.string :client, null: false, limit: 16 t.string :client_version, null: false, limit: 32 t.timestamps t.index %i[actor_id actor_type] t.index %i[user_id] t.index %i[uuid], unique: true t.index %i[refresh_token], unique: true end end end
class CreateContracts < ActiveRecord::Migration def change create_table :contracts do |t| t.string :contract_no t.date :contract_start t.date :contract_end t.string :duty_officer t.decimal :fees, precision: 8, scale: 2 t.timestamps null: false end end end
phone_book = { "Winston Salem" => "336", "High Point" => "336", "Kernersville" => "336", "Thomasville" => "336", "Rural Hall" => "336", "Charlotte" => "704", "Imaginville" => "336", "Here" => "704", "Billyville" => "555", "Wonkaland" => "619", } def display_city(somehash) somehash.each { |k, v| puts k} end def display_area_code(somehash, key) somehash[key] end loop do puts "Do you want to look up a city name?(Y,N)?" answer = gets.chomp.capitalize if answer != "Y" break end puts "Pick a city." display_city(phone_book) puts "What is your city name?" city = gets.chomp.to_s if phone_book.key?(city) puts "The area code for #{city} is #{display_area_code(phone_book, city)}" else puts "This city is not recognized" end end
class AddColumnCities < ActiveRecord::Migration[5.2] def change add_column :cities, :map, :text add_column :cities, :facility, :text add_column :cities, :distance, :string add_column :cities, :url, :string end end
#!/usr/bin/env ruby require 'openssl' # define CA paths @katello_default_ca = '/etc/pki/katello/certs/katello-default-ca.crt' @katello_server_ca = '/etc/pki/katello/certs/katello-server-ca.crt' @puppet_ca = '/var/lib/puppet/ssl/certs/ca.pem' # set FQDN to variable fqdn = `hostname -f`.chomp # define SSL cert paths @certs = [ '/etc/pki/katello/qpid_router_client.crt', '/etc/pki/katello/qpid_router_server.crt', '/etc/pki/katello/qpid_client_striped.crt', '/etc/pki/katello/certs/java-client.crt', '/etc/pki/katello/certs/katello-apache.crt', '/etc/pki/katello/certs/pulp-client.crt', '/etc/foreman-proxy/ssl_cert.pem', "/etc/pki/katello/certs/#{fqdn}-qpid-broker.crt" ] # SSL checks def ssl_check @certs.each do |cert| puts "Checking the following cert #{cert}" sleep 1 `openssl verify -CAfile #{@katello_default_ca} #{cert}` if $?.success? puts "SSL cert looks good" sleep 1 elsif $?.success? == false `openssl verify -CAfile #{@katello_default_ca} #{cert}` puts "SSL cert looks good" sleep 1 else puts "There is an issue with the SSL certs on this satellite" sleep 1 end end end def puppet_certs_check Dir.glob('/var/lib/puppet/ssl/certs/*.pem') do |cert| puts "Checking the following cert #{cert} against #{@puppet_ca}" sleep 1 `openssl verify -CAfile #{@puppet_ca} #{cert}` if $?.success? puts "SSL cert looks good" sleep 1 else puts "There is an issue with the Puppet SSL certs on this satellite" sleep 1 end end end # check to see if custom certs are used hash1 = `md5sum /etc/pki/katello/certs/katello-default-ca.crt | awk '{ print $1 }'`.chomp hash2 = `md5sum /etc/pki/katello/certs/katello-server-ca.crt | awk '{ print $1 }'`.chomp if hash1 == hash2 puts "Using default SSL certs from the installer, proceeding with check" sleep 1 puts "\nChecking normal SSL" ssl_check puts "\nChecking Puppet SSL" puppet_certs_check else puts "Using custom SSL certs, proceeding with check" sleep 1 puts "\nChecking normal SSL" ssl_check puts "\nChecking Puppet SSL" puppet_certs_check end