text
stringlengths
10
2.61M
class Friend < ApplicationRecord enum friendship_status: { pending: 0, accepted: 1, denied: 2 } belongs_to :user belongs_to :pal, class_name: 'User' end
json.array!(@calculation_parameters) do |calculation_parameter| json.extract! calculation_parameter, :id, :stock_id, :calculation_algorithm_id, :price, :percentage, :quantity, :period json.url calculation_parameter_url(calculation_parameter, format: :json) end
class Category < ActiveRecord::Base attr_accessible :photo, :deal_site_category, :major_category, :minor_category, :description scope :preference_category, proc {|category| where("major_category like '%#{category}%'").order("photo")} scope :matching_category, proc {|minor_category, major_category| where("major_category like '%#{major_category.split(' ')[0]}%' AND minor_category like '%#{minor_category}%'")} class << self def get_business_category category = where("minor_category like 'business%'").first category.present? ? (category) : ("") end def get_lifestyle_category category = where("minor_category like 'lifestyle%'").first category.present? ? (category) : ("") end def get_sorted_minor_categories(major_category_string) minor_categories = Category.where("major_category like ?", "%#{major_category_string}%").order("description asc") duplicate_major_category = minor_categories.detect{|categ| categ.major_category.downcase == categ.minor_category.downcase } final_minor_categories = [duplicate_major_category] + (minor_categories - [duplicate_major_category]) final_minor_categories end def you_deserve_it_set(user_profile) category_1 = where("id = ?", user_profile.you_deserve_it_category).first individual_category_set(category_1) end def user_preference_categories(user_profile) category_1 = where("id = ?", user_profile.offer_category_1).first category_2 = where("id = ?", user_profile.offer_category_2).first category_3 = where("id = ?", user_profile.offer_category_3).first get_category_set(category_1, category_2, category_3) end def user_suggestion_categories(user_profile) category_1 = where("id = ?", user_profile.suggestion_category_1).first category_2 = where("id = ?", user_profile.suggestion_category_2).first category_3 = where("id = ?", user_profile.suggestion_category_3).first get_category_set(category_1, category_2, category_3) end def get_category_set(category_1, category_2, category_3) individual_category_set(category_1) + individual_category_set(category_2) + individual_category_set(category_3) end def individual_category_set(category) if category.present? if /#{category.major_category}/i.match(category.minor_category) where("major_category like ?", category.minor_category).map(&:id) else [category.id] end else [] end end end end
class Forecast module Adapters class ForecastIoAdapter include Forecast::Adapter def current(latitude, longitude) result = get_json(get_action(latitude, longitude)) get_forecast({latitude: latitude, longitude: longitude}.merge(result['currently'])) unless nil end def hourly(latitude, longitude) result = get_json(get_action(latitude, longitude)) forecasts = Forecast::Collection.new result['hourly']['data'].each do |hash| forecasts << get_forecast({latitude: latitude, longitude: longitude}.merge(hash)) end return forecasts end def daily(latitude, longitude) result = get_json(get_action(latitude, longitude)) forecasts = Forecast::Collection.new result['daily']['data'].each do |hash| forecasts << get_forecast({latitude: latitude, longitude: longitude}.merge(hash)) end return forecasts end private def get_action(latitude, longitude) api_key = options[:api_key] return "https://api.forecast.io/forecast/#{api_key}/#{latitude},#{longitude}" end def get_forecast(hash) forecast = Forecast.new(hash) forecast.latitude = hash[:latitude] forecast.longitude = hash[:longitude] forecast.time = get_time(hash['time']) forecast.condition = get_condition(hash['summary']) forecast.text = get_text(hash['summary']) forecast.temperature_min = get_temperature(hash['temperatureMin'], :fahrenheit) forecast.temperature_max = get_temperature(hash['temperatureMax'], :fahrenheit) forecast.temperature = get_temperature(hash.has_key?('temperature') ? hash['temperature'] : [hash['temperatureMin'], hash['temperatureMax']], :fahrenheit) return forecast end end end end
# frozen_string_literal: true # user_points.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that provides points for users for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "yaml" require "fileutils" require_relative "../yossarian_plugin" class UserPoints < YossarianPlugin include Cinch::Plugin use_blacklist def initialize(*args) super @points_file = File.expand_path(File.join(File.dirname(__FILE__), @bot.server_id, "user_points.yml")) if File.file?(@points_file) @points = YAML.load_file(@points_file) @points.default_proc = Proc.new { |h, k| h[k] = 0 } else FileUtils.mkdir_p File.dirname(@points_file) @points = Hash.new { |h, k| h[k] = 0 } end end def sync_points_file File.open(@points_file, "w+") do |file| file.write @points.to_yaml end end def usage "!point <command> <nick> - Give or take points away from a nickname. Commands are add, rm, and show." end def match?(cmd) cmd =~ /^(!)?point$/ end match /point add (\S+)/, method: :add_point def add_point(m, nick) nickd = nick.downcase if m.user.nick.downcase != nickd @points[nickd] += 1 m.reply "#{nick} now has #{@points[nickd]} points.", true else @points[nickd] -= 1 m.reply "Nice try. You now have #{@points[nickd]} points.", true end sync_points_file end match /point rm (\S+)/, method: :remove_point def remove_point(m, nick) nickd = nick.downcase @points[nickd] -= 1 m.reply "#{nick} now has #{@points[nickd]} points.", true sync_points_file end match /point show (\S+)/, method: :show_intro def show_intro(m, nick) m.reply "#{nick} has #{@points[nick.downcase]} points.", true end match /point leaderboard/, method: :show_leaderboard def show_leaderboard(m) top5 = @points.max_by(5) { |_, p| p } leaderboard = if top5.empty? "Empty" else top5.map { |u, p| "#{u}: #{p}" }.join ", " end m.reply "Leaderboard: #{leaderboard}.", true end end
module Vocab def self.change_avatar 'Cambia Avatar' end def self.change_title 'Cambia Titolo' end def self.gift_code 'Inserisci codice regalo' end def self.command_gift_code 'Codici regalo' end def self.messages 'Messaggi' end def self.follows 'Giocatori seguiti' end def self.followers 'I tuoi fan' end def self.command_online_dashboard 'Online' end def self.command_register 'Registrati' end def self.online_info_help "In questa schermata puoi gestire il tuo profilo online.|I progressi di gioco vengono inviati ed aggiornati quando salvi." end def self.online_notifications_help "Ci sono messaggi per te." end def self.support 'Supporto' end def self.support_help "Puoi ottenere supporto andando su %s\noppure scrivendo a %s.\nPuoi anche mandarmi un messaggio sulla pagina di Facebook!" end end module Sound def self.play_gift_code RPG::SE.new('Chime2').play end end #noinspection RubyYardReturnMatch class Scene_OnlinePlayer < Scene_MenuBase def start super get_player_data create_player_window create_help_window create_command_window create_dashboard_window create_titles_window create_gifts_windows create_avatar_window create_notifications_window create_friends_windows reset_help @dialog_window.back_opacity = 255 end # crea le finestre necessarie al sistema dei regali def create_gifts_windows create_gift_code_window create_gift_code_input_window end # crea le finestre necessarie al sistema degli amici def create_friends_windows create_follow_command_window create_follows_window create_player_search_window create_friend_player_window create_friend_command_window end # crea la finestra d'aiuto def create_help_window super @help_window.y = @player_window.bottom_corner end # scarica le informazioni sul giocatore attuale def get_player_data Online.login unless Online.logged_in? @player = Online_Player.get($game_system.player_id) end # restituisce il giocatore attuale # @return [Online_Player] def current_player @player end # crea il contenitore dei titoli sbloccati dal giocatore def create_titles_window y = Graphics.width width = Graphics.width height = Graphics.height - @help_window.bottom_corner @titles_window = Window_PlayerTitles.new(0, y, width, height) @titles_window.visible = false @titles_window.help_window = @help_window @titles_window.set_handler(:ok, method(:title_confirmation)) @titles_window.set_handler(:cancel, method(:reset_main_windows)) @titles_window.deactivate end # crea il contenitore degli avatar sbloccati dal giocatore def create_avatar_window y = Graphics.width width = Graphics.width @avatar_window = Window_AvatarList.new(0, y, width, 3) @avatar_window.visible = false @avatar_window.set_handler(:ok, method(:avatar_confirmation)) @avatar_window.set_handler(:cancel, method(:reset_main_windows)) @avatar_window.deactivate end # crea il menu principale def create_command_window @command_window = Window_PlayerCommand.new(0, @help_window.bottom_corner) @command_window.set_handler(:title, method(:command_title)) @command_window.set_handler(:avatar, method(:command_avatar)) @command_window.set_handler(:gift_code, method(:command_giftcode)) @command_window.set_handler(:cancel, method(:return_scene)) @command_window.set_handler(:messages, method(:command_messages)) @command_window.set_handler(:support, method(:command_support)) @command_window.set_handler(:follows, method(:command_follows)) @command_window.set_handler(:followers, method(:command_followers)) @command_window.activate @command_window.index = 0 end # crea la finestra del giocatore def create_player_window @player_window = Window_PlayerInfo.new(0, 0, Graphics.width) @player_window.player = @player end # crea la finestra di input del codice regalo def create_gift_code_input_window params = {:upcase => true, :permitted => Text_Inputable::ALPHA_WITH_SPACING, :max_characters => 20, :placeholder => 'XXXX-XXXX-XXXX', :title => Vocab.gift_code} @gift_input_window = Window_SingleLineInput.new(0, 0, params) @gift_input_window.center_window @gift_input_window.openness = 0 @gift_input_window.set_done_handler(method(:send_code)) @gift_input_window.set_cancel_handler(method(:cancel_code)) @gift_input_window.deactivate end # crea la finestra che mostra le ricompense del codice regalo def create_gift_code_window @gift_code_window = Window_GiftCode.new @gift_code_window.openness = 0 @gift_code_window.set_handler(:ok, method(:accept_code)) @gift_code_window.set_handler(:cancel, method(:reset_main_windows)) @gift_code_window.set_handler(:claimed, method(:rewards_claimed)) @gift_code_window.deactivate end # crea la finestra che mostra le informazioni sull'online (stato, eventi ecc...) def create_dashboard_window x = @command_window.right_corner y = @help_window.bottom_corner width = Graphics.width - x height = Graphics.height - y @dashboard_window = Window_OnlineDashboard.new(x, y, width, height) @dashboard_window.set_player @player end # crea la finestra che mostra i pulsanti da premere sulla finestra degli amici def create_follow_command_window @follows_help_window = Window_FollowHelp.new(Graphics.height) @follows_help_window.visible = false end # crea la finestra degli amici def create_follows_window y = @player_window.height height = Graphics.height - y - @follows_help_window.height @follows_window = Window_Follows.new(Graphics.width, y, Graphics.width, height) @follows_window.visible = false @follows_window.x = Graphics.width @follows_window.set_handler(:cancel, method(:reset_main_windows)) @follows_window.set_handler(:ok, method(:command_open_player)) @follows_window.info_window = @follows_help_window @follows_window.deactivate @follows_data = nil @followers_data = nil end # crea la finestra di input nome giocatore per cercarlo def create_player_search_window params = {:max_characters => Settings::MAX_NICKNAME_LEN, :title => Vocab::Add_Follow_Player} @player_search_window = Window_SingleLineInput.new(0, 0, params) @player_search_window.center_window @player_search_window.y -= 100 @player_search_window.openness = 0 @player_search_window.set_done_handler(method(:search_player)) @player_search_window.set_cancel_handler(method(:cancel_search)) @player_search_window.deactivate end # crea la finestra del giocatore (diverso da quello attuale) per mostrare il giocatore cercato o selezionato dalla lista def create_friend_player_window @friend_window = Window_PlayerInfo.new(0, @player_window.height, Graphics.width) @friend_window.openness = 0 end # crea la finestra del menu del giocatore amico def create_friend_command_window @friend_command_window = Window_FriendCommand.new(@friend_window.bottom_corner) @friend_command_window.openness = 0 @friend_command_window.deactivate @friend_command_window.set_handler(:cancel, method(:command_close_friend)) @friend_command_window.set_handler(:follow, method(:command_follow)) @friend_command_window.set_handler(:unfollow, method(:command_unfollow)) @friend_command_window.set_handler(:party, method(:command_party)) @friend_command_window.set_handler(:achievements, method(:command_achievements)) end # crea la finestra dei messaggi def create_notifications_window @notifications_downloaded = false @notifications_window = Window_NotificationMessages.new(0, Graphics.height, Graphics.width, Graphics.height - @help_window.height) @notifications_window.visible = false @notifications_window.set_handler(:cancel, method(:reset_main_windows)) @notifications_window.deactivate end def create_message_window @message_window = Window_NotificationMessage.new(Graphics.width, 0, Graphics.width, Graphics.height) @message_window.visible = false end def reset_main_windows @player_window.smooth_move(0, 0) @help_window.smooth_move(0, @player_window.height) @help_window.open @command_window.smooth_move(0, @command_window.y) @dashboard_window.smooth_move(@command_window.width, @dashboard_window.y) @avatar_window.smooth_move(@avatar_window.x, Graphics.height) @titles_window.smooth_move(@titles_window.x, Graphics.height) @notifications_window.smooth_move(0, Graphics.height) @follows_window.smooth_move(Graphics.width, @follows_window.y) @follows_help_window.smooth_move(0, Graphics.height) @follows_window.index = -1 @gift_input_window.close @gift_code_window.close @command_window.activate reset_help end def reset_help @help_window.set_text(Vocab.online_info_help) end def hide_player_window @player_window.smooth_move(0, 0 - @player_window.height) end def show_player_window @player_window.smooth_move(0, 0) end def hide_main_windows(including_player = false) hide_player_window if including_player hide_help_window stash_command_window stash_dashboard_window end def hide_help_window @help_window.close end def stash_dashboard_window @dashboard_window.smooth_move(Graphics.width, @dashboard_window.y) end def stash_command_window @command_window.smooth_move(0 - @command_window.width, @command_window.y) end def command_avatar hide_main_windows @avatar_window.y = Graphics.height unless @avatar_window.visible @avatar_window.visible = true @avatar_window.index = current_player.avatar @avatar_window.smooth_move(@avatar_window.x, @player_window.height) @avatar_window.activate end def command_title stash_dashboard_window stash_command_window @titles_window.y = Graphics.height unless @titles_window.visible @titles_window.visible = true @titles_window.smooth_move(@titles_window.x, @help_window.bottom_corner) @titles_window.activate @titles_window.set_index(current_player.title_id) end def command_support hide_main_windows #noinspection RubyResolve text = sprintf(Vocab.support_help, 'www.overdriverpg.it', CPanel::SUPPORT_MAIL) show_dialog(text, method(:reset_main_windows), :info) end # apre la finestra dei giocatori seguiti def command_follows hide_main_windows @follows_help_window.visible = true @follows_window.visible = true @follows_help_window.change_enable(0, true) @follows_window.set_handler(:shift, method(:command_search_player)) if follows_loaded? @follows_window.set_data @follows_data @follows_window.activate @follows_window.index = 0 else await_server do @follows_data = Follow_Service.get_follows($game_system.player_id) @follows_window.set_data @follows_data @follows_window.index = 0 @follows_window.activate end end @follows_window.smooth_move(0, @follows_window.y) @follows_help_window.smooth_move(0, Graphics.height - @follows_help_window.height) end # apre la finestra dei giocatori che ti seguono def command_followers hide_main_windows @follows_help_window.visible = true @follows_window.visible = true @follows_help_window.change_enable(0, false) @follows_window.delete_handler(:shift) if followers_loaded? @follows_window.set_data @followers_data, true @follows_window.activate @follows_window.index = 0 else await_server do @followers_data = Follow_Service.get_followers($game_system.player_id) @follows_window.set_data @followers_data, true @follows_window.index = 0 @follows_window.activate end end @follows_window.smooth_move(0, @follows_window.y) @follows_help_window.smooth_move(0, Graphics.height - @follows_help_window.height) end def command_follow friend_player = @friend_window.player response = Follow_Service.follow_player(friend_player.player_id) if response.success? @friend_command_window.set_follow(true) show_dialog(sprintf(Vocab::Follow_Success, friend_player.name), @friend_command_window, :success) @follows_data.push(friend_player) trigger_follow_update else Logger.error(response) show_dialog(response.failed_message, @friend_command_window, :error) end end def command_unfollow friend_player = @friend_window.player response = Follow_Service.unfollow_player(friend_player.player_id) if response.success? @friend_command_window.set_follow(false) show_dialog(sprintf(Vocab::Unfollow_Success, friend_player.name), @friend_command_window, :success) @follows_data.delete_if { |p| p.player_id == friend_player.player_id} trigger_follow_update else show_dialog(response.failed_message, @friend_command_window, :error) end end def command_party fail NotImplementedError end def command_achievements fail NotImplementedError end def command_close_friend @friend_command_window.close @friend_window.close @follows_window.open @follows_help_window.open @follows_window.activate end def cancel_search @player_search_window.close show_player_window @follows_window.open @follows_help_window.open @follows_window.activate end def command_giftcode hide_main_windows @gift_input_window.clear_text @gift_input_window.open @gift_input_window.activate end # apre un messaggio dall'elenco def command_open_message @notifications_window.smooth_move(0 - @notifications_window.width, @notifications_window.y) @help_window.smooth_move(0, 0 - @help_window.height) @message_window.set_notification(@notifications_window.item) @message_window.smooth_move(0, 0) @message_window.visible = true end # chiude il messaggio e torna all'elenco def command_close_message @notifications_window.smooth_move(0, @notifications_window.y) @help_window.smooth_move(0, 0) @message_window.smooth_move(Graphics.width, 0) @notifications_window.activate end # invia il codice regalo al server, controlla la validità e le ricompense def send_code @gift_input_window.close Online.login unless Online.logged_in? state = Gift_Code_Service.gift_code_state(@gift_input_window.text) if state == Gift_Code::AVAILABLE rewards = Gift_Code_Service.gift_code_rewards(@gift_input_window.text) @gift_code_window.set_rewards(rewards) @gift_code_window.open @gift_code_window.activate else Sound.play_buzzer show_dialog(Vocab.gift_code_error(state), method(:reset_main_windows), :warning) end end # annulla l'utilizzo del codice regalo def cancel_code @gift_input_window.close reset_main_windows end # utilizza il codice regalo def accept_code begin result = Gift_Code_Service.use_code(@gift_input_window.text) if result.success? $game_system.used_codes.push(@gift_input_window.text) Gift_Code_Service.distribute_rewards(@gift_code_window.rewards) @gift_code_window.start_claim else show_dialog(result.failed_message, method(:reset_main_windows), :error) end rescue => error Logger.error(error.message) show_dialog(Vocab.data_error, method(:reset_main_windows), :error) end end # mostra il messaggio che le ricompense sono state reclamate. def rewards_claimed @gift_code_window.close show_dialog(Vocab::Gift_Code_All_Claimed, method(:reset_main_windows)) end # apre la finestra dei messaggi ricevuti. def command_messages @help_window.smooth_move(0, 0) @help_window.set_text(Vocab.online_notifications_help) @player_window.smooth_move(0, 0 - @player_window.height) stash_command_window stash_dashboard_window @command_window.delete_read_count unless @notifications_downloaded $game_system.download_online_notifications @notifications_downloaded = true @notifications_window.set_messages($game_system.saved_notifications) $game_system.set_all_read_notifications end @notifications_window.y = Graphics.height unless @notifications_window.visible @notifications_window.visible = true @notifications_window.smooth_move(0, @help_window.height) @notifications_window.activate @notifications_window.index = 0 end # comando di selezione dell'avatar da modificare. Aggiorna l'avatar e torna al menu principale. def avatar_confirmation reset_main_windows if @avatar_window.index != current_player.avatar begin operation = Online.change_avatar(@avatar_window.index) if operation.success? current_player.avatar = @avatar_window.index $game_system.player_face = @avatar_window.index @player_window.refresh else @command_window.deactivate show_dialog(operation.failed_message, @command_window) end rescue => error Logger.error error.message @command_window.deactivate show_dialog(Vocab.data_error, @command_window) end end end # comando di selezione del titolo da modificare. Aggiorna il titolo e torna al menu principale def title_confirmation reset_main_windows if @titles_window.title != current_player.title begin title_id = @titles_window.title.nil? ? nil : @titles_window.title.id operation = Online.change_title title_id if operation.success? current_player.title_id = @titles_window.title.id @player_window.refresh else @command_window.deactivate show_dialog(operation.failed_message, @command_window) end rescue => error Logger.error error.message @command_window.deactivate show_dialog(Vocab.data_error, @command_window) end end end # comando di selezione del giocatore dall'elenco def command_open_player open_player @follows_window.item end # apre la finestra di ricerca del giocatore def command_search_player hide_player_window @follows_window.close @follows_help_window.close @player_search_window.open @player_search_window.activate end # avvia la ricerca del giocatore ed apre la finestra, se trovato def search_player player_found = Online_Player.find_by_name(@player_search_window.text) if player_found.nil? show_dialog(Vocab::Player_Not_Found, @player_search_window, :error) elsif player_found.player_id == $game_system.player_id show_dialog(Vocab::Player_Same, @player_search_window, :error) elsif @follows_data.map { |player| player.player_id }.include?(player_found.player_id) show_dialog(sprintf(Vocab::Player_Already_Followed, player_found.name), @player_search_window, :warning) else @player_search_window.close show_player_window open_player(player_found) end end # @param [Online_Player] player def open_player(player) @follows_window.close @follows_help_window.close @friend_window.player = player @friend_window.open @friend_command_window.set_follow following_player_id?(player.player_id) @friend_command_window.open @friend_command_window.activate end # determina se i giocatori seguiti sono stati scaricati dal server def follows_loaded? @follows_data != nil end # determina se l'elenco dei giocatori che ti seguono è stato caricato def followers_loaded? @followers_data != nil end # determina se stai seguendo un determinato giocatore def following_player_id?(player_id) return false unless follows_loaded? @follows_data.map { |follows| follows.player_id == player_id }.any? end def trigger_follow_update @follows_window.set_data(@follows_data) unless @follows_window.following end end class Window_PlayerCommand < Window_Command def initialize(x, y) get_unread_count super end def window_width 200 end def get_unread_count @unread = $game_system.unread_count end def make_command_list add_command(Vocab.messages, :messages, has_messages?, :message_n) add_command(Vocab.change_avatar, :avatar, can?) add_command(Vocab.change_title, :title, can?) add_command(Vocab.follows, :follows, can?) add_command(Vocab.followers, :followers, can?) add_command(Vocab.command_gift_code, :gift_code, can?) add_command(Vocab.support, :support) #add_command(Vocab.cancel, :cancel) end def can? !$game_system.user_banned? end def has_messages? $game_system.saved_notifications.size > 0 or Notification_Service.has_unread_notifications? end def draw_item(index) super rect = item_rect_for_text(index) draw_new_messages(rect) if @list[index][:ext] == :message_n end # @param [Rect] rect def draw_new_messages(rect) return if @unread == 0 change_color(crisis_color) draw_text(rect, sprintf('(%d)', @unread), 2) end def delete_read_count @unread = 0 refresh end end class Window_MenuCommand < Window_Command alias h87_online_original_cmds add_original_commands unless $@ def add_original_commands h87_online_original_cmds if Online.enabled? if $game_system.user_registered? new_messages = $game_system.unread_notifications? enabled = (Online.logged_in? or $game_system.user_banned?) add_command(Vocab.command_online_dashboard, :online, enabled, new_messages ? :new : nil) else add_command(Vocab.command_register, :register) end end end end
#!/usr/bin/env ruby # -*- mode: ruby -*- require 'muni' require 'thor' class MUNI < Thor desc "list", "Lists all routes" def list begin Muni::Route.find(:all).each do |route| say_status route.tag, route.title, :green end rescue Muni::NextBusError => e say_status "ERROR", e.message, :red end end desc "show [ROUTE_TAG] [DIRECTION]", "Shows a specifc route by name" method_option :verbose, :type => :boolean, :aliases => %w(-v --verbose) def show(tag, direction = nil) begin route = Muni::Route.find(tag) say_status route.tag, route.title, :green dirs = direction ? [route.send(direction.downcase.to_sym)] : route.directions dirs.each do |direction| say_status direction.id, direction.name, :yellow if options.verbose print_table direction.stops.collect{|stop| [stop.tag, stop.title]}, {:ident => 8} end end rescue Muni::NextBusError => e say_status "ERROR", e.message, :red end end desc "predict [ROUTE] [DIRECTION] [STOP]", "Retrieve predictions for a route at a specific stop" def predict(route, direction, *stop) # Join the remaining arguments so that predict can be called without # having to quote the stop name. stop = stop.join(' ') if stop.empty? say_status "ERROR", "A stop is required", :red exit! end # Get the bus route information # TODO Only do this if necessary bus = Muni::Route.find(route) # Look up the directon information direction = bus.direction_at(direction) # Look up the stop information stop = direction.stop_at(stop) # Retrieve the predictions begin say "Route #{bus.title} going #{direction.name} at #{stop.title}:" print_table stop.predictions.collect{|time| [time.vehicle, time.pretty_time]}, {:ident => 8} rescue Muni::NextBusError => e say_status "ERROR", e.message, :red end end end MUNI.start
class ImportTaskJob < ActiveJob::Base queue_as :import def perform(import_task_id) ProcessImportTask.new(import_task_id).process end end
class Post < ApplicationRecord belongs_to :user belongs_to :city def self.search(search) if search city = City.where(nom_reel: search).or(City.where(code_postal: search)) if city.empty? Post.limit(10) elsif city.exists? city = Post.where(city_id: city) else Post.limit(10) end else Post.limit(10) end end end
require_relative "../../aws_refresher_spec_common" require_relative "../../aws_refresher_spec_counts" describe ManageIQ::Providers::Amazon::CloudManager::Refresher do include AwsRefresherSpecCommon include AwsRefresherSpecCounts ###################################################################################################################### # Spec scenarios for making sure targeted refresh stays in it's scope ###################################################################################################################### # # We test every that every targeted refresh we do is staying in it's scope. The simplest test for this is that # after full refresh, targeted refresh should not change anything (just update existing items). So this verify the # targeted refresh is not deleting records that are out of its scope. before(:each) do @ems = FactoryBot.create(:ems_amazon_with_vcr_authentication) end it ".ems_type" do expect(described_class.ems_type).to eq(:ec2) end # Lets test only the fastest setting, since we test all settings elsewhere [ :inventory_collections => { :saver_strategy => "batch", :use_ar_object => false, }, ].each do |settings| context "with settings #{settings}" do before(:each) do stub_refresh_settings(settings) create_tag_mapping end it "will refresh an EC2 classic VM powered on and LB full targeted refresh" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager => @ems, :association => :vms, :manager_ref => {:ems_ref => "i-680071e9"}) lb_target = InventoryRefresh::Target.new(:manager => @ems, :association => :load_balancers, :manager_ref => {:ems_ref => "EmsRefreshSpec-LoadBalancer"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/ec2_classic_vm_and_lb_full_refresh") do EmsRefresh.refresh([vm_target, lb_target]) end @ems.reload assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group assert_specific_template assert_specific_load_balancer_non_vpc assert_specific_load_balancer_non_vpc_vms assert_specific_vm_powered_on end end end it "will refresh a VPC VM with floating IP and connected LBs" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-8b5739f2"}) lb_target_1 = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :load_balancers, :manager_ref => {:ems_ref => "EmSRefreshSpecVPCELB"}) lb_target_2 = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :load_balancers, :manager_ref => {:ems_ref => "EmSRefreshSpecVPCELB2"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/vpc_vm_with_floating_ip_and_lbs_full_refresh") do EmsRefresh.refresh([vm_target, lb_target_1, lb_target_2]) end @ems.reload assert_vpc assert_vpc_subnet_1 assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group_on_cloud_network assert_specific_template assert_specific_load_balancer_vpc assert_specific_load_balancer_vpc2 assert_specific_load_balancer_listeners_vpc_and_vpc_2 assert_specific_cloud_volume_vm_on_cloud_network assert_specific_vm_on_cloud_network end end end it "will refresh a VPC VM with public IP" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-c72af2f6"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/vpc_vm_with_public_ip_and_template") do EmsRefresh.refresh([vm_target]) end @ems.reload assert_vpc assert_vpc_subnet_1 assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group_on_cloud_network assert_specific_template_2 assert_specific_cloud_volume_vm_on_cloud_network_public_ip assert_specific_vm_on_cloud_network_public_ip end end end it "will refresh an orchestration stack" do assert_targeted_refresh_scope do orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stack") do EmsRefresh.refresh([orchestration_stack_target]) end @ems.reload assert_specific_orchestration_template assert_specific_orchestration_stack_data assert_specific_orchestration_stack_parameters assert_specific_orchestration_stack_resources assert_specific_orchestration_stack_outputs # orchestration stack belongs to a provider expect(@orch_stack.ext_management_system).to eq(@ems) # orchestration stack belongs to an orchestration template expect(@orch_stack.orchestration_template).to eq(@orch_template) end end end it "will refresh a nested orchestration stacks" do assert_targeted_refresh_scope do orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack/"\ "b4e06950-2fed-11e7-bd93-500c286374d1" } ) orchestration_stack_target_nested = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stacks_nested") do EmsRefresh.refresh([orchestration_stack_target, orchestration_stack_target_nested]) end @ems.reload assert_specific_orchestration_template assert_specific_parent_orchestration_stack_data assert_specific_orchestration_stack_data assert_specific_orchestration_stack_parameters assert_specific_orchestration_stack_resources assert_specific_orchestration_stack_outputs # orchestration stack belongs to a provider expect(@orch_stack.ext_management_system).to eq(@ems) # orchestration stack belongs to an orchestration template expect(@orch_stack.orchestration_template).to eq(@orch_template) # orchestration stack can be nested expect(@orch_stack.parent).to eq(@parent_stack) expect(@parent_stack.children).to match_array([@orch_stack]) end end end it "will refresh a nested orchestration stacks with Vm" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-0bca58e6e540ddc39"} ) orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack/"\ "b4e06950-2fed-11e7-bd93-500c286374d1" } ) orchestration_stack_target_nested = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stacks_nested_with_vm") do EmsRefresh.refresh([vm_target, orchestration_stack_target, orchestration_stack_target_nested]) end @ems.reload assert_specific_orchestration_template assert_specific_orchestration_stack end end end it "will refresh a volume with volume_snapshot" do assert_targeted_refresh_scope do base_volume = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volumes, :manager_ref => { :ems_ref => "vol-0e1613cacf4688009" } ) volume = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volumes, :manager_ref => { :ems_ref => "vol-0e4c86c12b28cead8" } ) snapshot = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volume_snapshots, :manager_ref => { :ems_ref => "snap-055095f47fab5e749" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/cloud_volume_with_snapshot") do EmsRefresh.refresh([base_volume, volume, snapshot]) end @ems.reload assert_specific_cloud_volume_vm_on_cloud_network assert_specific_cloud_volume_snapshot end end end end end def assert_targeted_refresh_scope stored_table_counts = make_full_refresh yield assert_all(stored_table_counts) end def make_full_refresh stored_table_counts = nil @ems.reload VCR.use_cassette(described_class.name.underscore + '_inventory_object') do EmsRefresh.refresh(@ems) EmsRefresh.refresh(@ems.network_manager) EmsRefresh.refresh(@ems.ebs_storage_manager) @ems.reload stored_table_counts = table_counts_from_api assert_counts(stored_table_counts) end assert_common assert_mapped_tags_on_template stored_table_counts end def assert_all(stored_table_counts) assert_counts(stored_table_counts) assert_common assert_mapped_tags_on_template end end
require 'rails_helper' describe 'appointments', type: :feature do before do @hawkeye = Doctor.create(name: 'Hawkeye Pierce', department: 'Surgery') @homer = Patient.create(name: 'Homer Simpson', age: 38) @appointment = Appointment.create( appointment_datetime: DateTime.new(2016, 0o3, 15, 18, 0o0, 0), patient: @homer, doctor: @hawkeye ) end it "should display an appointment's doctor" do visit appointment_path(@appointment) expect(page).to have_link('Hawkeye Pierce', href: doctor_path(@hawkeye)) end it "should display an appointment's patient" do visit appointment_path(@appointment) expect(page).to have_link('Homer Simpson', href: patient_path(@homer)) end it 'should not have an index page' do expect { visit('/appointments') }.to raise_error(ActionController::RoutingError) end end
module GroupDocs module Api module Helpers module Path # # Make helper methods accessible as class methods as well # def self.included(klass) klass.extend self end private # # Prepares path. # @param [String] path # @return [String] # @api private # def prepare_path(path) path.sub(%r(^/), '').gsub(%r(//+), '/') end end # Path end # Helpers end # Api end # GroupDocs
class ProfilesController < ApplicationController before_action :authenticate_user! def show @friend_ids = current_user.my_friends @user = User.find_by_id(params[:id]) @thoughts = @user.thoughts.order('created_at DESC') @thought = current_user.thoughts.build @pending = current_user.friendships.where('friend_id= ?', @user.id) @recieved = current_user.inverse_friendships.where('user_id= ?', @user.id) @confirmed = current_user.confirmed_profile_friendship(@user.id, current_user) end end
require 'spec_helper' describe ScannerExtensions::Extensions::XxeDetect do let(:extension) { ScannerExtensions::Extensions::XxeDetect.new } before(:all) do ScannerExtensions::Helpers::OobDnsClient.config = { 'host' => 'oob-dns', 'port' => '8080' } end it 'detects vuln by ascii' do begin port = get_open_port web_server = WebServer.new(port) web_server.server.mount_proc '/' do |req, res| addr = req.query['test'].scan(/\/\/(.*?)\//)[0][0] begin Resolv::DNS.new( nameserver_port: [['oob-dns', 5053]] ).getresources(addr, Resolv::DNS::Resource::IN::A) rescue end res.body = 'test' end web_server.start params = { 'http_params' => { host: '127.0.0.1', port: port, url: '/', param_name: 'test', request_class: Net::HTTP::Get } } object = ScannerExtensions::Wrappers::Object.new params extension.run(object, sleep: 1) expect(object.vulns.size).to eq 1 vuln = object.vulns[0] expect(vuln[:args][:exploit_example].index('oob-dns').nil?).to eq false ensure web_server.stop end end it 'detects vuln by utf-16' do begin port = get_open_port web_server = WebServer.new(port) web_server.server.mount_proc '/' do |req, res| h = { invalid: :replace, undef: :replace, replace: ' ' } data = req.query['test'].force_encoding('utf-16') .encode('ascii', h).tr("\0", ' ') addr = data.scan(/\/\/(.*?)\//)[0][0] begin Resolv::DNS.new( nameserver_port: [['oob-dns', 5053]] ).getresources(addr, Resolv::DNS::Resource::IN::A) rescue end res.body = 'test' end web_server.start params = { 'http_params' => { host: '127.0.0.1', port: port, url: '/', param_name: 'test', request_class: Net::HTTP::Get } } object = ScannerExtensions::Wrappers::Object.new params extension.run(object, sleep: 1) expect(object.vulns.size).to eq 1 ensure web_server.stop end end it 'does not detect fp' do begin port = get_open_port web_server = WebServer.new(port) web_server.server.mount_proc '/' do |_req, res| res.body = 'test' end web_server.start params = { 'http_params' => { host: '127.0.0.1', port: port, url: '/', param_name: 'test', request_class: Net::HTTP::Get } } object = ScannerExtensions::Wrappers::Object.new params extension.run(object, sleep: 1) expect(object.vulns.size).to eq 0 ensure web_server.stop end end end
require 'spec_helper' describe TwitterDirectMessage do before(:each) do FakeWeb.register_uri( :post, "http://twitter.com/direct_messages/new.json", :body => "something" ) end it { should validate_presence_of(:body) } it { should validate_presence_of(:sender) } it { should validate_presence_of(:recipient) } it { should validate_length_of(:body, :within => 1..140) } end describe TwitterDirectMessage, "save" do context "successful" do before(:each) do @sender = Factory(:user) @recipient = Factory(:user) FakeWeb.register_uri( :post, "http://twitter.com/direct_messages/new.json", :body => { :sender_id => @sender.twitter_id, :recipient_id => @recipient.twitter_id, :id => "88619848" }.to_json ) @dm = TwitterDirectMessage.new( :sender => @sender, :recipient => @recipient, :body => "Hello world" ) end it "should set it's twitter direct message id as its id" do @dm.save @dm.id.should == "88619848" end it "should not be a new record" do @dm.save @dm.should_not be_new_record end it "returns true" do @dm.save.should be_true end end end
require File.dirname(__FILE__) + '/../../test_helper' class UserCreateTest < ActionController::TestCase tests UserController def setup @request.remote_addr = '1.2.3.4' @user = users(:joe) end test 'on POST to :create with existing login' do assert_no_difference 'User.count' do post :create, :user => { :login => @user.login, :email => 'somenew@example.com' } end assert_new_form_has_errors end test 'on POST to :create with existing e-mail' do assert_no_difference 'User.count' do post :create, :user => { :login => 'bobby', :email => @user.email } end assert_new_form_has_errors end test 'on POST to :create without login and password' do assert_no_difference 'User.count' do post :create end assert_new_form_has_errors end private def assert_new_form_has_errors assert_response :success assert_template :new assert_select '.errorExplanation' end end
# TODO: Did you know that hashes can accept anything as a key and anything # as a value? Try atleast 5 different combinations of key/values # using different data types. Example: hash = {4.5 => :my_symbol} hash = { "Randy" => :name, 34 => :age, ["cheese", "sausage", "pepperoni"] => :ingredients, :state => "Texas", "Monday" => :day_of_week } p hash
#!/usr/bin/env ruby namespace "http_mongo" do task "copy_mongo_voodoo" do Dir.mkdir "/etc/http_voodoo_mongo" unless File.exists? "/etc/http_voodoo_mongo" f_in=File.open("mongo_voodoo.rb","r") f_out=File.open("/etc/http_voodoo_mongo/mongo_voodoo.rb","w") f_out.write f_in.read f_in.close f_out.close status=%x{sudo chmod +x /etc/http_voodoo_mongo/mongo_voodoo.rb}.split[-1].to_i if status==0 "Success: HTTP Voodoo MongoDB has been installed" else "Problem in installing HTTP Voodoo MongoDB" end end task "copy_mongo_voodoo_service" do f_in=File.open("mongo_voodoo","r") f_out=File.open("/etc/init.d/mongo_voodoo","w") f_out.write f_in.read f_in.close f_out.close status=%x{sudo chmod +x /etc/init.d/mongo_voodoo}.split[-1].to_i if status==0 "Success: HTTP Voodoo MongoDB System Service has been installed" else "Problem in copying HTTP Voodoo MongoDB System Service" end end desc "install http_voodoo_mongo as system service" task "install" do Rake::Task["http_mongo:copy_mongo_voodoo"].invoke Rake::Task["http_mongo:copy_mongo_voodoo_service"].invoke status=%x{sudo /etc/init.d/mongo_voodoo start; echo $?}.split[-1].to_i if status==0 "Success: HTTP Voodoo MongoDB Service has been installed & started" else "Problem in starting HTTP Voodoo MongoDB Service" end end end
require 'redmine' require_dependency 'watcher_groups/views_issues_hook' require_dependency 'watcher_groups_helper' Rails.logger.info 'Starting Watcher Groups plugin for Redmine' Rails.configuration.to_prepare do unless Issue.included_modules.include?(WatcherGroupsIssuePatch) Issue.send(:include, WatcherGroupsIssuePatch) end unless IssuesController.included_modules.include?(WatcherGroupsIssuesControllerPatch) IssuesController.send(:include, WatcherGroupsIssuesControllerPatch) end end Redmine::Plugin.register :redmine_watcher_groups do name 'Redmine Watcher Groups plugin' author 'Kamen Ferdinandov, Massimo Rossello' description 'This is a plugin for Redmine to add watcher groups functionality' version '1.0.1' url 'http://github.com/maxrossello/redmine_watcher_groups' author_url 'http://github.com/maxrossello' end
# frozen_string_literal: false require 'spec_helper' describe Lita::Interactors::ShowService do let(:interactor) { described_class.new(handler, data) } let(:handler) { double('handler') } let(:data) { ['show awesome-service', name] } let(:name) { 'awesome-service' } let(:fake_repository) { double('redis-repository') } before do allow(interactor).to receive(:repository).and_return(fake_repository) end describe '#perform' do describe 'when the service does not exist' do let(:error_message) do I18n.t('lita.handlers.service.errors.not_found', service_name: name) end before do allow(fake_repository).to receive(:exists?).with(name).and_return(false) end it 'shows an error message' do interactor.perform expect(interactor.success?).to eq false expect(interactor.error).to eq error_message end end describe 'when service exists' do let(:service) do { name: name, value: 2000, state: 'active', customers: { erlinis: { quantity: 1, value: 2000 } } } end before do allow(fake_repository).to receive(:exists?).with(name).and_return(true) allow(fake_repository).to receive(:find).with(name).and_return(service) end it 'returns the service' do interactor.perform expect(interactor.success?).to eq true expect(interactor.message).to eq service end end end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "home#show" get "/find_weather(/:city_name)" => "home#show", as: :find_weather end
class KitsController < ApplicationController def index @kits = Kit.published @programs = Program.featured.order('updated_at DESC').limit(6) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe SeatValidator do describe '.seat_is_taken?' do subject { described_class.seat_is_taken?(row, seat_number, screening) } let!(:seats_reservation) { create(:seats_reservation, reservation: reservation, cinema_hall: cinema_hall) } let(:reservation) { create(:reservation, screening: screening) } let(:screening) { create(:screening, movie: movie, cinema_hall: cinema_hall) } let(:movie) { create(:movie) } let(:cinema_hall) { create(:cinema_hall) } let(:row) { 'A' } let(:seat_number) { 6 } context 'when seat reservation does not exist for this screening' do let!(:seats_reservation) do create(:seats_reservation, reservation: reservation, cinema_hall: cinema_hall, row: row, seat_number: reservation_seat_number) end let(:reservation_seat_number) { 12 } it { is_expected.to eq(false) } end context 'when seat reservation already exists for this screening' do let!(:seats_reservation) do create(:seats_reservation, reservation: reservation, cinema_hall: cinema_hall, row: row, seat_number: seat_number) end it { is_expected.to eq(true) } end end end
class AddSendColumnToRequirement < ActiveRecord::Migration def change add_column :requirements, :sent, :datetime, default: nil end end
class CartLineItemsController < ApplicationController #before_action :set_cart, only: [:create, :destroy] def create @cart_line_item.add_product(params) @cart_line_item = CartLineItem.new(cart_line_item_params) @cart_line_item.user_id = current_user.id @cart_line_item.save_or_update # Skinny controller and Fat model redirect_to cart_line_items_path, notice: "Sucessfully added the product to the cart" end def index # CartLineItem.where('user_id = ?', current_user.id) @cart_line_items = current_user.cart_line_items # To find only the cart line items for that currently logged in user @address = Address.new end def destroy @cart_line_item = CartLineItem.find(params[:id]) @cart_line_item.destroy redirect_to cart_line_items_path,notice: "Product was sucessfully removed from cart" end def update @cart_line_item = CartLineItem.find(params[:id]) if @cart_line_item.update_attributes(params[:cart_line_item].permit(:quantity)) redirect_to cart_line_items_path, notice: "Quantity was sucessfully updated" end end private def cart_line_item_params params[:cart_line_item].permit(:quantity, :product_id) end end
# coding: utf-8 require "sinatra/base" require "sinatra/reloader" require "slim" require "sass" require "coffee-script" require "active_support/all" require "randexp" require "omniauth-twitter" require "mongoid" require "twitter" require "logger" require "yaml" Mongoid.load! "./config/mongoid.yml" class Kaeritai include Mongoid::Document include Mongoid::Timestamps::Created field :serial, type: Integer field :user_id, type: Integer field :tweet_id, type: Integer field :text, type: String scope :by_day, ->(datetime){where :created_at.gte => datetime.beginning_of_day.to_s, :created_at.lte => datetime.end_of_day.to_s} default_scope desc(:created_at) def tweet case rand(15) when 0 client.update_with_media tweet_text, Media.all.sample else client.update tweet_text end end def initialize attrs = nil super self.serial = self.class.count + 1 self.user_id = attrs[:user_id] self.text = kaeritai_text end private def client Twitter::Client.new( consumer_key: ENV["CLIENT_CONSUMER_KEY"], consumer_secret: ENV["CLIENT_CONSUMER_SECRET"], oauth_token: ENV["CLIENT_ACCESS_TOKEN"], oauth_token_secret: ENV["CLIENT_ACCESS_TOKEN_SECRET"], ) end def tweet_text "#{self.text} (#{self.serial.with_delimiter}回目)" end def kaeritai_text seeds = YAML.load_file "./config/seeds.yml" seeds.values.inject("") {|text, seed| text + generate_text(seed)} end def generate_text seed sum = seed.inject 0 do |sum, item| item[:range] = sum...(sum + item[:weight]) sum + item[:weight] end dice = rand sum seed.each do |item| next unless item[:range].include? dice if item[:pattern].empty? return "" else return Regexp.compile(item[:pattern]).generate end end end end class Media def self.glob Dir.glob "./media/*" end def self.all self.glob.map {|item| File.new item} end def self.authors self.glob.map {|item| item.match(/\.\/media\/\d+-(\w+)/)[1]}.uniq end end class Integer def with_delimiter self.to_s.reverse.gsub(/(\d{3})(?=\d)/, "\1,").reverse end end class Kaeritainess < Sinatra::Base log = Logger.new STDOUT STDOUT.sync = true configure :development do register Sinatra::Reloader end configure do enable :sessions, :logging use OmniAuth::Builder do provider :twitter, ENV["TWITTER_CONSUMER_KEY"], ENV["TWITTER_CONSUMER_SECRET"] end end helpers do def current_user_id session[:current_user_id] end def current_user_nickname session[:current_user_nickname] end def authenticated? current_user_id.present? end end error do slim :failure end get "/" do slim :index end get "/signin" do redirect to "/auth/twitter" end get "/signout" do session[:current_user_id] = session[:current_user_nickname] = nil redirect to "/" end post "/create" do redirect to "/" unless authenticated? @kaeritai = Kaeritai.new user_id: current_user_id tweet = @kaeritai.tweet if tweet @kaeritai.tweet_id = tweet.id @kaeritai.save log.info "@#{current_user_nickname} just created a kaeritai ##{@kaeritai.serial}." redirect to "/kaeritai/" + @kaeritai.serial.to_s else redirect to "/failure" end end get "/kaeritai/:serial" do @kaeritai = Kaeritai.find_by serial: params[:serial] slim :show end get "/auth/twitter/callback" do auth = env["omniauth.auth"] session[:current_user_id] = auth["uid"] session[:current_user_nickname] = auth["info"]["nickname"] redirect to "/" end end
describe HealthCheckController do include Rack::Test::Methods context "GET /health" do let(:response) { get "/health" } let(:body) { JSON.parse(response.body) } it { expect(response.status).to eq(200) } it { expect(body["result"]).to eq("ok") } end end
# require 'matrix' # No specific test for this class. It is just a helper class for # ReversePortfolioOptimization, and tested via that class. module Finance module ReturnData extend self # { # "ticker1" => [returns], # "ticker2" => [returns] # } # Order alphabetically by ticker, and convert all percentages to numerics. # All methods sorting tickers alphabetically to remain consistent. def values Rails.cache.fetch("returndata/values", expires_in: 10.minutes) do sorted_hash end end private def sorted_hash hsh = {} data.keys.sort.each do |k| hsh[k] = data[k].map(&:to_d) end return hsh end def data raise "File does not exist. You probably need to run rake google_docs." unless File.exists?(returns_file) return_data = YAML.load(File.read returns_file) security_tickers = return_data.shift returns = Matrix.rows(return_data).transpose # You have returns in vertical columns hsh = {} security_tickers.each_with_index do |ticker, index| hsh[ticker] = returns.row(index) end return hsh end def returns_file "#{Rails.root}/db/data/returns.yml" end end end
class ConvertLoopJob < ActiveJob::Base queue_as :default def perform(data) ConvertLoop.event_logs.send(data) rescue => e Rails.logger.warn "Couldn't send event log #{data[:name]} to ConvertLoop: #{e.message}" Rails.logger.error "Backtrace: \n\t#{e.backtrace.join("\n\t")}" end end
require 'rails_helper' RSpec.describe "as a user, when i visit the shelters index", type: :feature do before :each do @shelter_1 = Shelter.create( name: "Paws For You", address: "1234 W Elf Ave", city: "Denver", state: "CO", zip: "90210") end it "can update a shelters information" do visit "/shelters/#{@shelter_1.id}" expect(page).to have_link("Update Shelter") click_link "Update Shelter" expect(current_path).to eq("/shelters/#{@shelter_1.id}/edit") fill_in :name, with: "MoMo's Adoption" click_on "Update Shelter" expect(current_path).to eq("/shelters/#{@shelter_1.id}") expect(page).to have_content("MoMo's Adoption") expect(page).to have_content("1234 W Elf Ave") expect(page).to have_content("Denver") expect(page).to have_content("CO") expect(page).to have_content("90210") end it "I can click on link and return to shelters index page" do visit "/shelters/#{@shelter_1.id}/edit" click_on "Return to Shelters Index" expect(current_path).to eq("/shelters") end it "I can click on link and return to pets index page" do visit "/shelters/#{@shelter_1.id}/edit" click_on "Return to Pets Index" expect(current_path).to eq("/pets") end it "I can click on link to return to shelter page" do visit "/shelters/#{@shelter_1.id}/edit" click_on "Return to Paws For You" expect(current_path).to eq("/shelters/#{@shelter_1.id}") end end
require 'rails_helper' RSpec.describe Api::V1::SentencesController, type: :controller do describe "POST#create" do context "when given valid data" do before(:each) do Paragraphtype.create(name: "Introduction") Paragraph.create( name: "Penguin Essay Introduction", paragraphtype_id: Paragraphtype.first.id ) end it "creates a new sentence" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json expect(Sentence.all.count).to eq (0) response = post :create, body: payload expect(Sentence.all.count).to eq (1) end it "creates a new sentence with the correct content" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json response = post :create, body: payload expect(Sentence.first.content).to eq("Although penguins cannot fly, their wings are anything but useless") end it "returns a hash and not something else" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json response = post :create, body: payload returned_json = JSON.parse(response.body) expect(returned_json).to be_kind_of(Hash) expect(returned_json).to_not be_kind_of(Array) expect(returned_json).to_not be_kind_of(String) end it "returns the sentence with the correct sentence id" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json response = post :create, body: payload returned_json = JSON.parse(response.body) expect(returned_json["sentence"]["id"]).to eq(1) end it "returns the sentence with the correct paragraph id" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json response = post :create, body: payload returned_json = JSON.parse(response.body) expect(returned_json["sentence"]["paragraph"]["id"]).to eq(1) end it "returns the sentence with the correct content" do payload = { paragraph_id: Paragraph.first.id, content: "Although penguins cannot fly, their wings are anything but useless" }.to_json response = post :create, body: payload returned_json = JSON.parse(response.body) expect(returned_json["sentence"]["content"]).to eq("Although penguins cannot fly, their wings are anything but useless") end end context "when given invalid data" do before(:each) do Paragraphtype.create(name: "Introduction") Paragraph.create( name: "Penguin Essay Introduction", paragraphtype_id: Paragraphtype.first.id ) end it "does not create a new sentence" do payload = { paragraph_id: Paragraph.first.id, }.to_json expect(Sentence.all.count).to eq (0) response = post :create, body: payload expect(Sentence.all.count).to eq (0) end it "does not return a sentence object" do expect{ JSON.parse(response.body) }.to raise_error(JSON::ParserError) end it "responds with the correct text" do payload = { paragraph_id: Paragraph.first.id, }.to_json expect(Sentence.all.count).to eq (0) response = post :create, body: payload expect(response.body).to eq("Sentence was not saved") end it "responds with the correct status" do payload = { paragraph_id: Paragraph.first.id, }.to_json expect(Sentence.all.count).to eq (0) response = post :create, body: payload expect(response.status).to eq(500) end it "does not return a 200" do payload = { paragraph_id: Paragraph.first.id, }.to_json expect(Sentence.all.count).to eq (0) response = post :create, body: payload expect(response.status).to_not eq(200) end end end end
require 'spec_helper' describe DateTimeFormatValidator do let(:klass) do Class.new do include ActiveWarnings attr_accessor :string1 warnings do validates :string1, date_time_format: true end def self.name; "TestClass" end end end let(:instance) { klass.new } subject { instance.safe? } it_behaves_like "validated_types" context "proper Date" do before { instance.string1 = "2026-12-12T17:47:43.884+02:00" } it "is valid" do expect(subject).to eql true end end end
class User < ActiveRecord::Base MAX_AVATAR_SIZE_KB = 1024 acts_as_loggable # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :lockable #TODO ,:confirmable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :bike_id, :user_profiles_attributes, :username, :avatar has_many :transactions, as: :customer has_many :transaction_logs, through: :transactions, source: :logs has_many :user_profiles accepts_nested_attributes_for :user_profiles, allow_destroy: false has_many :user_role_joins, :conditions => ["ends IS NULL OR ends > ?", Time.now] has_many :roles, through: :user_role_joins belongs_to :bike has_attached_file :avatar, :styles => {:thumb => '100x100>'} default_scope order('username ASC') validates :username, :presence => true, uniqueness: true validates :first_name, :presence => true validates :last_name, :presence => true validates_attachment :avatar, :content_type => {:content_type => %w{ image/jpeg image/gif image/png }}, :file_name => {:matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]}, :size => {:in => 0..MAX_AVATAR_SIZE_KB.kilobytes} def to_s "#{first_name} #{last_name}" end def email_required? false end def full_name to_s end def role?(role) if role.kind_of?(String) or role.kind_of?(Symbol) role = Role.find_by_role(role.to_s) end roles.include?(role) end # try keeping the email field in DB clear and consistent, without empty strings (NULLs instead) def email=(other) super(other.blank? ? nil : other) end ### TODO methods below probably belong somewhere else def completed_build_bikes #default BUILDBIKE/CLASS ID is 5 purpose_id = 5 Bike.find_by_sql(" SELECT * FROM bikes INNER JOIN( SELECT * FROM transactions WHERE customer_id = #{self.id} ) AS transactions ON bikes.id = transactions.bike_id WHERE bike_purpose_id = #{purpose_id}") end def total_credits total_earned_credits - total_credits_spent end def total_credits_spent log_action_id = 1 #TIME transaction_logs. where( "log_action_id = ? AND log_action_type = ?", log_action_id, ::ActsAsLoggable::TransactionAction.to_s). sum{ |r| r.description.to_i }.round(2) end def total_earned_credits volunteer_id = 1 staff_id = 3 # Find the first credit conversion which has a created_at date before the # log's created_at date and join it to the log's row so we can calculate # the credits earned from that log entry (each log could have a different # conversion rate) # # The DISTINCT ON, and ORDER BY are important to getting the # single conversion rate that applies to the respective log. ::ActsAsLoggable::Log.find_by_sql([" SELECT DISTINCT ON (logs.created_at) start_date, end_date, conversion.conversion, conversion.created_at FROM logs INNER JOIN( SELECT conversion, created_at FROM credit_conversions ) AS conversion ON logs.created_at > conversion.created_at WHERE logs.loggable_id = :id AND logs.loggable_type = 'User' AND (log_action_id IN (:credit_actions) AND log_action_type = :log_action_type) ORDER BY logs.created_at, conversion.created_at DESC", {id: self.id, credit_actions: [volunteer_id, staff_id], log_action_type: ::ActsAsLoggable::UserAction.to_s}]). sum{ |l| ((l.end_date - l.start_date)/3600) * l.conversion.to_i}.round(2) end def total_hours log_action_id = 4 #CHECKIN logs.where("log_action_id != ? AND log_action_type = ?", log_action_id, ::ActsAsLoggable::UserAction.to_s).sum { |l| (l.end_date - l.start_date)/3600 }.round(2) end def current_month_hours log_action_id = 4 #CHECKIN #TODO need to prevent users from saving logs across months, force to create a new log if crossing month current_month_range = (Time.now.beginning_of_month..Time.now.end_of_month) logs.where("log_action_id != ? AND log_action_type = ?", log_action_id, ::ActsAsLoggable::UserAction.to_s) .where( :start_date => current_month_range) .where( :end_date => current_month_range) .sum { |l| (l.end_date - l.start_date)/3600 } .round(2) end def checked_in? #default CHECKIN log action is id, yea yea should be a constant log_action_id = 4 checked = logs.where( log_action_id: log_action_id). where("start_date >= ?", Time.zone.now.beginning_of_day). where("start_date = end_date") !checked.empty? end def checkin #default CHECKIN log action is id, yea yea should be a constant log_action_id = 4 time = Time.now logs.create( logger_id: self.id, logger_type: self.class.to_s, start_date: time, end_date: time, log_action_id: log_action_id, log_action_type: ::ActsAsLoggable::UserAction.to_s) save end def checkout #default CHECKIN log action is id, yea yea should be a constant log_action_id = 4 checked = logs.where( log_action_id: log_action_id). where("start_date >= ?", Time.zone.now.beginning_of_day). where("start_date = end_date").first checked.end_date = Time.now checked.save end end
def single_element_optimized(arr) return nil unless arr elem_hash = {} arr.each do |elem| if elem_hash.has_key? elem elem_hash.delete(elem) else elem_hash[elem] = 1 end end return elem_hash.keys.first end #Note -- we use a hash to hold elements and delete elements from hash if found this takes O(n) time and O(1) space
FactoryBot.define do factory :user_log, class: User::Log do user ip { |n| "127.0.0.#{n + 1}" } first_seen_at { Time.now.utc } last_seen_at { Time.now.utc } end end
class PostAttachment < ActiveRecord::Base belongs_to :post attr_accessible :note, :post_id ,:image_height attr_accessible :title, :content, :image , :image_content_type, :image_file_name, :image_file_size, :image_updated_at has_attached_file :image, :styles => { :small => "150x150>", :content => "800x800>", :thumb => "60x60>", :thumb_small=>"30x30>" }, :url => "/upload/post_image/:class/post/:id/:style_:basename.:extension" , :path => ":rails_root/public/upload/post_image/:class/post/:id/:style_:basename.:extension" def as_json(options={}) { id: self.id, image_url: self.image.url(:content), image_height: self.image_height } end end
class Admin::SortiesController < Admin::AdminController # GET /sorties # GET /sorties.xml def index @sorties = Sortie.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @sorties } end end # GET /sorties/1 # GET /sorties/1.xml def show @sortie = Sortie.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @sortie } end end # GET /sorties/new # GET /sorties/new.xml def new @sortie = Sortie.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @sortie } end end # GET /sorties/1/edit def edit @sortie = Sortie.find(params[:id]) end # POST /sorties # POST /sorties.xml def create @sortie = Sortie.new(params[:sortie]) respond_to do |format| if @sortie.save format.html { redirect_to(@sortie, :notice => 'Sortie was successfully created.') } format.xml { render :xml => @sortie, :status => :created, :location => @sortie } else format.html { render :action => "new" } format.xml { render :xml => @sortie.errors, :status => :unprocessable_entity } end end end # PUT /sorties/1 # PUT /sorties/1.xml def update @sortie = Sortie.find(params[:id]) respond_to do |format| if @sortie.update_attributes(params[:sortie]) format.html { redirect_to(@sortie, :notice => 'Sortie was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @sortie.errors, :status => :unprocessable_entity } end end end # DELETE /sorties/1 # DELETE /sorties/1.xml def destroy @sortie = Sortie.find(params[:id]) @sortie.destroy respond_to do |format| format.html { redirect_to(sorties_url) } format.xml { head :ok } end end end
# frozen_string_literal: true require 'test_helper' class RemindersControllerTest < ActionDispatch::IntegrationTest def setup @reminders = create_list(:reminder, 20) @resource = @reminders.first.reminderable end test 'should_get_paginated_reminders_for_a_resource' do get reminders_url, params: { resource_id: @resource.id, page: 1, per_page: 50 } assert_response :success reminders_count = Reminder.where(reminderable: @resource).count assert_equal JSON.parse(@response.body).count, reminders_count end test 'should get reminder by id' do reminder = @reminders.first get reminder_url(id: reminder.id) assert_response :success assert_equal reminder.id, JSON.parse(@response.body)['id'] end test 'should create reminder' do reminder_params = attributes_for(:reminder).merge( resource_id: @resource.id, resource_type: @resource.class.name ) post reminders_url, params: reminder_params assert_response :success end test 'should update reminder' do reminder = @reminders.first put reminder_url(id: reminder.id), params: { note: 'New Note' } assert_response :success assert_equal reminder.reload.note, 'New Note' end test 'should delete reminder' do reminder = @reminders.first delete reminder_url(id: reminder.id) assert_response :success assert_equal @reminders.count - 1, Reminder.count end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/multi_mail/version', __FILE__) Gem::Specification.new do |s| s.name = "multi_mail" s.version = MultiMail::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Open North"] s.email = ["info@opennorth.ca"] s.homepage = "http://github.com/opennorth/multi_mail" s.summary = %q{Easily switch between email APIs} s.license = 'MIT' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_runtime_dependency 'faraday', '~> 0.8.0' s.add_runtime_dependency 'mail', '~> 2.5.3' # Rails 3.2.13, less buggy than 2.4.x s.add_runtime_dependency 'rack', '~> 1.4' # For testing s.add_development_dependency 'coveralls' s.add_development_dependency 'json', '~> 1.7.7' # to silence coveralls warning s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 2.10' s.add_development_dependency 'vcr', '~> 2.4.0' # For Rake tasks s.add_development_dependency 'mandrill-api', '~> 1.0.35' s.add_development_dependency 'postmark' s.add_development_dependency 'rest-client', '~> 1.6.7' s.add_development_dependency 'sendgrid_webapi' end
require 'csv' require 'yaml' require 'themoviedb-api' module Cinema class TmdbDataGetter class << self def fetch_all(movies) return if File.exist?('data/tmdb_base.yml') configure @tmdb_base = movies.each_with_object({}) do |movie, hash| id = movie.link.match(/tt\d{5,7}/).to_s sleep(0.25) hash[id] = fetch_one(id) end self end def save(path) File.write(path,@tmdb_base.to_yaml) end private def fetch_one(imdb_id) movie = Tmdb::Find.movie(imdb_id, external_source: 'imdb_id', language: 'ru').first poster_path = @config.images.base_url + @config.images.poster_sizes[1] + movie.poster_path [movie.original_title, movie.title, poster_path] end def configure Tmdb::Api.key(File.open('config/key.yml', &:readline)) @config = Tmdb::Configuration.get end end end end
class GamesController < ApplicationController before_action :authenticate_user, only: [:new, :create, :index] def create @game = Game.new(game_params) @game.user = current_user if @game.save flash[:success] = "Game created successfully." redirect_to game_path(@game) else flash.now[:alert] = "Error! Please check your input and retry." render :new end end def index @games = Game.all.select { |g| g.user == current_user } end def new @game = Game.new end def player_characters @game = Game.find(params[:game_id]) @characters = @game.characters.order(:name) end def show @game = Game.find(params[:id]) @game_traits = @game.game_traits.order(:name) end def update @game = Game.find(params[:id]) if @game.update(desc_params) flash[:success] = "Game description updated successfully." redirect_to game_path(@game) else flash.now[:alert] = "Error! Unable to update game description." render 'show' end end protected def desc_params params.require(:game).permit(:description) end def game_params params.require(:game).permit(:name, :starting_points) end end
require 'spec_helper' describe "'Attach file' form", :js => true do let(:current_user) { FactoryGirl.create(:user) } let(:position) { FactoryGirl.create(:position, :user => current_user) } let(:request) {FactoryGirl.create(:position_request,:position => position, :status => PositionRequest::STATUS_ACCEPTED)} before {login_as(current_user, :scope => :user)} context "upload is available request is in process with one comment at least" do before {request.process!} before {FactoryGirl.create(:comment, :commentable => request, :comment => "Owner comment")} before {stub_request(:put, "https://applicant-dev.s3-eu-west-1.amazonaws.com/attachments/Zu0_llVmh6Cyu8gUQr1Uug/1/sample.doc"). with(:body => "This is sample attachment", :headers => {'Authorization'=>'AWS AKIAJUR4JH57JHN5WPVA:r0WY67wNJmzbl8UFtWGeZO3Dfj0=', 'Cache-Control'=>'max-age=315576000', 'Content-Length'=>'25', 'Content-Type'=>'application/msword', 'Date'=>'Tue, 27 May 2014 09:05:48 +0000', 'Host'=>'applicant-dev.s3-eu-west-1.amazonaws.com:443', 'User-Agent'=>'fog/1.22.0', 'X-Amz-Acl'=>'public-read'}). to_return(:status => 200, :body => "", :headers => {}) } context "the form that attaching file of unsupported type" do before(:each) do visit position_request_path(request.token) pending "Modal dialog present for unsupported format" #attach_file 'file', File.join(Rails.root, '/spec/fixtures/data_files/sample.jgv') end it 'attach the file to related document' do page.should_not have_content 'sample.jgv' current_path.should == position_request_path(request.token) end end context "the form that attaching file to the related request", :js => true do before(:each) do visit position_request_path(request.token) find("#image").click #attach_file 'image', File.join(Rails.root, '/spec/fixtures/data_files/sample.doc') hidden_field = find('#file_upload', :visible => false) hidden_field.set File.join(Rails.root, '/spec/fixtures/data_files/sample.doc') end it 'attach the file to related document' do page.should have_content 'sample.doc' current_path.should == position_request_path(request.token) #request.attachments.count.should == 1 #.last.should exist(file: 'sample.doc') end # context "after uploading" do # before(:each) do # expect(page).to have_content 'sample.txt' # Wait while file will be loaded # end # it "shows 'Related to' on the show file page", js: true do # data_file = Attachment.last(conditions: { file: 'sample.txt' }) # ensure_on data_file_path(data_file) # file_related_to.should have_content(related_document.name) # end # end end end end
require 'rubygems' require 'sinatra/base' require 'sinatra/namespace' # require 'coffee-script' require 'haml' require 'sass' require 'models' class HackNite < Sinatra::Base register Sinatra::Namespace configure do set :root, File.expand_path('../', __FILE__) end get "/" do haml :index#, :layout => false end # Handle that SASS (as SCSS)! http://sass-lang.com/docs/yardoc/file.SCSS_FOR_SASS_USERS.html get /\/(.*)\.css/ do |stylesheet| headers 'Content-Type' => 'text/css; charset=utf-8' scss :"scss/#{stylesheet}" end # CoffeeScript handler get /\/(.*)\.js/ do |javascript| headers 'Content-Type' => 'application/x-javascript' coffee :"coffee/#{javascript}" end # HAML handler for templates get %r{/(.*)\.html} do |template| haml_target = "#{template}.haml" haml_engine = Haml::Engine.new(File.read(haml_target)) haml_engine.render end get "/env" do <<-EOS <pre> DATABASE_URL: #{ENV['DATABASE_URL']} SHARED_DATABASE_URL: #{ENV['SHARED_DATABASE_URL']} -- #{ENV.map { |k,v| "#{k} => #{v}" }.join("\n")} </pre> EOS end namespace "/window" do get '/current' do if window = Window.current window.to_json end end post do unless window = Window.current window = Window.create end window.to_json end post "/reply" do # Create or update reply for current window end end end
class Admin::ArticlesController < Admin::RootController # GET /admin_articles # GET /admin_articles.xml def index @articles = ::Article.paginate :page=>params[:page], :per_page=>20 respond_to do |format| format.html # index.html.erb format.xml { render :xml => @admin_articles } end end # GET /admin_articles/1 # GET /admin_articles/1.xml def show @article = ::Article.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @article } end end # GET /admin_articles/new # GET /admin_articles/new.xml def new @article = ::Article.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @article } end end # GET /admin_articles/1/edit def edit @article = ::Article.find(params[:id]) @article_content = @article.article_content end # POST /admin_articles # POST /admin_articles.xml def create @article = ::Article.new(params[:article]) @article_content = ArticleContent.new(params[:article_content]) @article_content.article = @article @article.save @article_content.save respond_to do |format| if @article.save format.html { redirect_to(admin_articles_path, :notice => '::Article was successfully created.') } else format.html { render :action => "new" } end end end # PUT /admin_articles/1 # PUT /admin_articles/1.xml def update @article = ::Article.find(params[:id]) @article_content = @article.article_content respond_to do |format| if @article_content.update_attributes(params[:article_content]) and @article.update_attributes(params[:article]) format.html { redirect_to(admin_articles_path, :notice => '::Article was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } end end end # DELETE /admin_articles/1 # DELETE /admin_articles/1.xml def destroy @article = ::Article.find(params[:id]) @article.destroy respond_to do |format| format.html { redirect_to(admin_articles_url) } format.xml { head :ok } end end end
require 'spec_helper' RSpec.describe ActionController do class TestController < ActionController::Base before_action :callback, only: [:show] after_action :callback_after, only: [:show] def index response << "index" end def show response << "show" end def redirect redirect_to "/" end private def callback response << "callback" end def callback_after response << "callback_after" end end it 'can get a response when calling index' do thing = TestController.new thing.response = [] thing.process :index expect(thing.response).to eq ["index"] end it 'returns the callback when calling show' do subject = TestController.new subject.response = [] subject.process :show expect(subject.response).to eq ["callback", "show", "callback_after"] end class Request def params { 'id' => 1 } end end it 'works on a real controller' do controller = PostsController.new controller.request = Request.new controller.process :show expect(controller.instance_variable_get(:@post)).to eq "something" end class Response attr_accessor :status, :location, :body end xit 'can redirect to a specific page' do controller = TestController.new controller.response = Response.new controller.process :redirect expect(controller.response.status).to eq 302 expect(controller.response.location).to eq "/" expect(controller.response.body).to eq ["You are being redirected"] end end
require 'rails_helper' feature 'Project management' do let!(:project) { create(:project) } before do sign_in(create(:user)) end it 'User can view all projects and project details' do visit root_path expect(page).to have_content 'Projects' click_link project.name expect(page.find('.project-heading')).to have_content project.name end it 'User can edit a project' do visit project_path(project) click_link "edit-project-#{project.id}" fill_in 'Name', with: 'New Project Name!' click_button 'Save' expect(page.find('.project-heading')).to have_content 'New Project Name!' end it 'User can add a new Project' do visit root_path click_link 'New Project' fill_in('Name', with: 'NEW PROJECT') fill_in('Description', with: 'NEW PROJECT DESCRIPTION') click_button('Save') expect(page).to have_text('NEW PROJECT') end end
class AddPhoto4ToCreations < ActiveRecord::Migration[5.2] def change add_column :creations, :photo4, :string end end
class UserProduct < ActiveRecord::Base belongs_to :user belongs_to :product before_save :update_user_tags private def update_user_tags if self.tags_change previous = self.tags_change.first || [] current = self.tags_change.last || [] added = current - previous removed = previous - current user.update_tags(added, removed) user.save end end end
class User < ActiveRecord::Base EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i has_many :history def display_name "#{first_name} #{last_name}" end validates :first_name, :presence => { :message => "is Required"}, :length => { :maximum => 25, :message => "First Name is too long"} validates :last_name, :presence => { :message => "is Required"}, :length => { :maximum => 25, :message => "Last Name is too long"} validates :email, :presence => { :message => "is Required"}, :length => { :maximum => 25, :message => "Email is too long"}, :format => { :with => EMAIL_REGEX, :message => "is Invalid"}, :uniqueness => { :message => "Email already registered"} validates :password, :presence => { :message => "is Required"}, :length => { :maximum => 15, :message => "Password is too long"} validates :gender, :presence => { :message => "is Required"} end
require 'spec_helper' describe ChequesController do let(:cheque) { FactoryGirl.create :cheque } describe "#show" do let(:user) { cheque.cheque_run.owner } before do basic_auth_login sign_in user end it "renders a pdf binary" do @prawn_document = double(:prawn_document) cheque.stub!(:to_prawn).and_return(@prawn_document) Cheque.stub!(:find).and_return(cheque) @prawn_document.should_receive(:render) get :show, id: cheque.to_param, format: 'pdf' response.headers['Content-Type'].should == 'application/pdf' end it "forbids access if user organization does not own cheque" do rival_run = FactoryGirl.create :cheque_run, owner: FactoryGirl.create(:rival) rival_cheque = FactoryGirl.create :cheque, cheque_run: rival_run get :show, :id => rival_cheque.to_param, format: 'pdf' response.status.should == 403 end end end
# encoding: utf-8 module SetSeoHash module SeoShops private def return_seo_hash(title, description, keywords, h1, options = {}) seo_hash = {} seo_hash[:title] = title seo_hash[:description] = description seo_hash[:keywords] = keywords seo_hash[:h1] = h1 if options[:link].present? seo_hash[:link] = {} seo_hash[:link][:start] = options[:link][:start] seo_hash[:link][:prev] = options[:link][:prev] seo_hash[:link][:next] = options[:link][:next] end seo_hash end def seo_shops_show(options) shop_name = options[:shop].try(:name) title = "#{shop_name} 店舗詳細 [Sweeta]" description = "#{shop_name}の店舗詳細ページです" keywords = "#{shop_name}、お菓子,スイーツ,お土産,プレゼント" h1 = "#{shop_name} 店舗詳細" return_seo_hash(title, description, keywords, h1) end end end
#!/usr/bin/env ruby # example: flash.rb -l 3 -t 5 -c red -n 3 require 'ostruct' require 'optparse' require_relative '../lib/philips_hue' # set default values here options = OpenStruct.new options.light_id = 2 options.delay = 1 options.repeat = 3 options.crazy = false options.color = PhilipsHue::Helpers::RED # get everything ready... hue = PhilipsHue::Bridge.new(PhilipsHue::Config::API_URL,PhilipsHue::Config::APP_NAME) light = hue.light(options.light_id) # ...make magic happen light.clear options.repeat.times do |n| puts "flashing light ##{options.light_id}" light.flash(options.color, options.delay, options.crazy) sleep options.delay unless options.repeat == n+1 end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) password = "asdfasdf" user1 = User.create(username: Faker::Name.name, password: password) user2 = User.create(username: Faker::Name.name, password: password) user3 = User.create(username: Faker::Name.name, password: password) #user1 created all the subs sub1 = Sub.create(name: Faker::Name.title, user_id: user1.id) sub2 = Sub.create(name: Faker::Name.title, user_id: user1.id) sub3 = Sub.create(name: Faker::Name.title, user_id: user2.id) #post to many subs #User1 has 0 posts, but 3 subs #User2 has 2 posts, and 1 sub #user3 has 2 posts and 0 subs post1 = Post.new( title: Faker::Lorem.sentence, body: Faker::Lorem.sentence(40), user_id: user2.id ) post1.sub_ids = [1, 2] post1.save post2 = Post.new( title: Faker::Lorem.sentence, body: Faker::Lorem.sentence(40), user_id: user2.id ) post2.sub_ids = [1, 2] post2.save post3 = Post.new( title: Faker::Lorem.sentence, body: Faker::Lorem.sentence(40), user_id: user3.id ) post3.sub_ids = [1] post3.save post4 = Post.new( title: Faker::Lorem.sentence, body: Faker::Lorem.sentence(40), user_id: user3.id ) post4.sub_ids = [3] post4.save post5 = Post.new( title: Faker::Lorem.sentence, body: Faker::Lorem.sentence(40), user_id: user2.id, parent_comment_id: post3.id ) post4.sub_ids = [3] post4.save
module JWK class Key class << self def from_pem(pem) key = OpenSSL::PKey.read(pem) if defined?(OpenSSL::PKey::EC) && key.is_a?(OpenSSL::PKey::EC) $stderr.puts('WARNING: EC Keys have bugs on jRuby') if defined?(JRUBY_VERSION) end from_openssl(key) end def from_openssl(key) if key.is_a?(OpenSSL::PKey::RSA) RSAKey.from_openssl(key) elsif key.is_a?(OpenSSL::PKey::EC) || key.is_a?(OpenSSL::PKey::EC::Point) ECKey.from_openssl(key) end end def from_json(json) key = JSON.parse(json) validate_kty!(key['kty']) case key['kty'] when 'EC' ECKey.new(key) when 'RSA' RSAKey.new(key) when 'oct' OctKey.new(key) end end def validate_kty!(kty) unless %w[EC RSA oct].include?(kty) raise JWK::InvalidKey, "The provided JWK has an unknown \"kty\" value: #{kty}." end end end def to_json @key.to_json end %w[kty use key_ops alg kid x5u x5c x5t].each do |part| define_method(part) do @key[part] end end def x5t_s256 @key['x5t#S256'] end protected def pem_base64(content) Base64.strict_encode64(content).scan(/.{1,64}/).join("\n") end def generate_pem(header, asn) "-----BEGIN #{header} KEY-----\n" + pem_base64(asn) + "\n-----END #{header} KEY-----\n" end end end
#!/usr/bin/env ruby #-- # Copyright 2010 Red Hat, 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. #++ require 'rubygems' require 'parseconfig' require 'getoptlong' def usage puts <<USAGE == Synopsis ss-setup-broker: Script to setup the broker and required services on this machine. This command must be run as root. == Usage -i|--static-ip <IP> Sets up the vm to use a static IP and not regenrate the forwarders file using dhcp hooks -n|--static-dns <IP>[,<IP>] Comma seperated list of IP addresses to use for DNS forwarding -d|--eth-device Ethernet device to use for broker setup. Defaults to eth0 -h|--help Print this message USAGE end opts = GetoptLong.new( ["--static-ip", "-i", GetoptLong::OPTIONAL_ARGUMENT], ["--static-dns", "-n", GetoptLong::OPTIONAL_ARGUMENT], ["--eth-device", "-d", GetoptLong::OPTIONAL_ARGUMENT], ["--help", "-?", GetoptLong::NO_ARGUMENT]) args = {} begin opts.each{ |k,v| args[k]=v } rescue GetoptLong::Error => e usage exit -100 end eth_device = args["--eth-device"] || "eth0" use_dhcp = args["--static-ip"].nil? dns = args["--static-dns"] dns_address = dns.split(/,/) unless dns.nil? if use_dhcp ip_address = `ip addr show dev #{eth_device} | awk '/inet / { split($2,a, "/") ; print a[1];}'` else ip_address = args["--static-ip"] end if dns_address.nil? if use_dhcp dns_address = `cat /var/lib/dhclient/dhclient-*#{eth_device}.lease* | grep domain-name-servers | awk '{print $3}' | sort -u`.split(";\n").map{ |ips| ips.split(",") }.flatten dns_address.delete '127.0.0.1' else dns_address = ["8.8.8.8", "8.8.4.4"] end end if dns_address.nil? || dns_address.length == 0 print "Error: Unable to determine DNS servers.\n\n" usage exit -1 end if ip_address.nil? || ip_address.empty? print "Error: Unable to determine IP address of server.\n\n" usage exit -1 end if args["--help"] usage exit -1 end if use_dhcp File.open("/etc/sysconfig/network-scripts/ifcfg-#{eth_device}","w") do |f| f.write "DEVICE=#{eth_device}\n" f.write "BOOTPROTO=dhcp\n" f.write "ONBOOT=yes\n" f.write "NM_MANAGED=no\n" end end unless File.exist?('/etc/rndc.key') print "Unable to find rnds.key .. generating\n" system "rndc-confgen -a" system "/sbin/restorecon /etc/rndc.* /etc/named.*" system "chown root:named /etc/rndc.key" system "chmod 0640 /etc/rndc.key" end if system("chkcinfig --list NetworkManager") system "chkconfig NetworkManager off" system "service NetworkManager stop" end system "chkconfig network on" system "service network restart" #pickup new IP incase it changed if use_dhcp ip_address = `ip addr show dev #{eth_device} | awk '/inet / { split($2,a, "/") ; print a[1];}'` end print "Opening required ports\n" system "lokkit --service=ssh" system "lokkit --service=http" system "lokkit --service=https" system "lokkit --service=dns" system "lokkit -p 5672:tcp" #qpid print "Starting mongodb\n" system("chkconfig mongod on") system("service mongod start") print "Initializing mongodb database..." #..wait for mongo to initialize while not system('/bin/fgrep "[initandlisten] waiting for connections" /var/log/mongodb/mongodb.log') do print "." sleep 5 end print "Setup mongo db user\n" print `/usr/bin/mongo localhost/stickshift_broker_dev --eval 'db.addUser("stickshift", "mooo")'` print "Configure and start local named\n" File.open("/var/named/forwarders.conf", "w") do |f| f.write("forwarders { #{dns_address.join(" ; ")} ; } ;") end system "/sbin/restorecon -v /var/named/forwarders.conf" system "chkconfig named on" system "service named restart" system "/usr/bin/ss-register-dns -h broker -n #{ip_address}" print "Update resolve.conf with dns servers\n" File.open("/etc/resolv.conf", "w") do |f| f.write("nameserver 127.0.0.1\n") dns_address.each { |ns| f.write("nameserver #{ns}\n") } end print "Register admin user\n" `mongo stickshift_broker_dev --eval 'db.auth_user.update({"_id":"admin"}, {"_id":"admin","user":"admin","password":"2a8462d93a13e51387a5e607cbd1139f"}, true)'` ["httpd","sshd","qpidd","mcollective","stickshift-broker","stickshift-proxy"].each do |service| system "chkconfig #{service} on" system "service #{service} restart" end print "Connect node services to local broker\n" system "/usr/bin/ss-setup-node --with-node-hostname broker --with-broker-ip #{ip_address}"
require 'rails_helper' RSpec.feature 'Expiring price in admin area', settings: false do given!(:price) { create(:effective_price) } background do sign_in_to_admin_area end scenario 'expires price' do visit admin_prices_path open_edit_form expire expect(page).to have_text(t('admin.billing.prices.expire.expired')) end def open_edit_form find('.edit-price-btn').click end def expire click_link_or_button t('admin.billing.prices.edit.expire_btn') end end
class WordsApiController < ApplicationController def show_by_id @word = Word.find_by_id(params[:id]) if !@word.nil? if stale?(last_modified: @word.updated_at) render json: @word end else render json: {} end end def show @words = Word.all render json: @words end end
#!/bin/env ruby # encoding: utf-8 class Admin::PaintingsController < Admin::BaseController before_filter only: [:destroy] {|controller| controller.modify_right(Painting)} before_filter :find_gallery def new @painting = Painting.new end def create @painting = @gallery.paintings.new(params[:painting]) if @painting.save else render 'new' end end def destroy @painting = Painting.find(params[:id]) FileUtils.rm_rf("public/uploads/painting/image/#{@gallery.id}/#{@painting.id}") @painting.destroy flash[:success] = "Photo supprimée" redirect_to edit_admin_gallery_path(@gallery.id) end private def find_gallery @gallery = Gallery.find(params[:gallery_id]) end end
class UsersController < ApplicationController before_action :set_user, only: [:edit, :update, :destroy] # GET /users # GET /users.json before_filter :authorize, only: [:edit, :update, :index] def index @users = User.all respond_to do |format| format.html # index.html.erb format.json { render json: @users } end end # GET /users/1 # GET /users/1.json def show @user = User.find(current_user.id) @registrations = Registration.where(:user_id => @user.id) @travels = @user.travels.all @meals = @user.meals.all @children = Child.where(:user_id => @user.id) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end # GET /users/new # GET /users/new.json def new reset_session @user = User.new @meal_dates = ["2014-07-22","2014-07-23","2014-07-24","2014-07-25","2014-07-26","2014-07-27"] @child = @user.children.build @meals = @user.meals.build @travels = @user.travels.build @registration = @user.registrations.build @programs = Program.all respond_to do |format| format.html # new.html.erb format.json { render json: @user } end end # GET /users/1/edit def edit @meal_dates = ["2014-07-22","2014-07-23","2014-07-24","2014-07-25","2014-07-26","2014-07-27"] @user.meals @user.programs @user.travels @programs = Program.all end # POST /users # POST /users.json def create @user = User.new(user_params) @meal_dates = ["2014-07-22","2014-07-23","2014-07-24","2014-07-25","2014-07-26","2014-07-27"] @programs = Program.all start = DateTime.new(2014,7,22,0,0,0) finish = DateTime.new(2014,7,27,0,0,0) @range = start..finish respond_to do |format| if @user.save session[:user_id] = @user.id UserMailer.confirmation_email(@user).deliver format.html { redirect_to @user, notice: t('user_created') } format.json { render json: @user, status: :created, location: @user } else format.html { render action: "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PUT /users/1 # PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @User, notice: 'User was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @User.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to Users_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:email_address, :password, :password_confirmation, :first_name, :home_country, :payment, :phone_number, :price_category, :price_method, :reference_number, :second_name, meals_attributes: [:fifth_day, :fifth_day_meal_type, :first_day, :first_day_meal_type, :food_type, :fourth_day, :fourth_day_meal_type, :second_day, :second_day_meal_type, :sixth_day, :sixth_day_meal_type, :third_day, :third_day_meal_type], registrations_attributes: [:user_id, :program_id, :participate], children_attributes: [:age, :child_care, :language, :name, :user_id], travels_attributes: [:arrival, :arrival_seats, :bus_trip, :departure, :departure_seats, :flight_date, :flight_number, :user_id] ) end end
require_relative 'maze' RSpec.describe 'maze' do describe '#shortest_path' do subject { maze = Maze.new(grids) maze.shortest_path } context '4 x 5' do let(:grids) { [ %w(0 s 0 1), %w(0 0 1 0), %w(0 1 1 0), %w(0 0 1 g), %w(0 0 0 0), ] } it { is_expected.to eq 9 } end context '4 x 4, unsolvable' do let(:grids) { [ %w(0 s 0 1), %w(1 0 0 0), %w(0 1 1 1), %w(0 0 0 g), ] } it { is_expected.to eq 'Fail' } end context '6 x 7' do let(:grids) { [ %w(0 s 0 1 0 0), %w(0 1 0 0 0 0), %w(0 0 1 1 1 0), %w(0 0 1 g 0 1), %w(0 0 0 1 0 0), %w(0 0 0 1 1 0), %w(0 0 0 0 0 0), ] } it { is_expected.to eq 17 } end context 'easiest' do let(:grids) { [ %w(s), %w(g), ] } it { is_expected.to eq 1 } end end end
resource_name :deploy_key property :key_name, kind_of: String, name_property: true property :key_location, kind_of: String property :key_content, kind_of: String property :user, kind_of: String action :create do Chef::Log.info "Creating directory on #{key_location}" directory key_location do path key_location owner new_resource.user group new_resource.user mode '0700' recursive true action :create end Chef::Log.info "Creating key #{key_name}" file "#{key_location}" + "/#{key_name}" do owner new_resource.user group new_resource.user mode '0600' content key_content sensitive true action :create end end action :delete do Chef::Log.info "Deleting key #{key_name}" file "#{key_location}" + "/#{key_name}" do sensitive true action :delete end end
require 'rails_helper' RSpec.describe User, type: :model do it 'validates acceptance of :tos on create' do user = User.new(name: 'Fred') expect(user.valid?).to be false end end
require 'pry' class PhoneNumber class << self def clean(number) cleaned = remove_country_code(number.gsub(/\D/,'')) if valid_length?(cleaned) && valid_area_and_exchange?(cleaned) cleaned else nil end end private def remove_country_code(number) valid_country_code?(number) ? number.slice(1, 10) : number end def valid_area_and_exchange?(number) range = (2..9) range.include?(number[0].to_i) && range.include?(number[3].to_i) end def valid_length?(number) number.length == 10 end def valid_country_code?(number) number.length == 11 && number.start_with?("1") end end end class BookKeeping VERSION = 2 end
FactoryBot.define do factory :store do sequence(:store_name) { |n| "Store-#{n}" } sequence(:store_phonenumber) { |n| "0120-000-00#{n}" } after(:build) do |store| store.store_manager = create(:store_manager) end end end
# frozen_string_literal: true module Api module V1 class PhotopostsController < ApiController before_action :api_user, only: %i[create destroy] def index photoposts = Photopost.custom_order(params[:order_by], params[:order_type]) render json: photoposts, current_user: api_user.id, status: :ok end def create validate Photoposts::Create.run(content: params[:photopost][:content], picture: params[:photopost][:picture], user: @api_user) end def destroy photopost = Photopost.find(params[:id]) photopost.delete render json: { message: 'Deleted successfully' }, status: :ok end def show photopost = Photopost.find(params[:id]) if photopost.moderating? raise ActiveRecord::RecordNotFound unless photopost.user == api_user render json: { message: "Post with id #{params[:id]} on moderation" } else render json: photopost, status: :ok, current_user: api_user.id end rescue ActiveRecord::RecordNotFound render json: { message: "Post with id #{params[:id]} is not found" }, status: :not_found end def search if params[:search].nil? render json: { message: 'No posts were found', photoposts: Photopost.custom_order(params[:order_by], params[:order_type]) }, status: :bad_request else render json: { photoposts: send("#{params[:search][:model]}_search") }, current_user: api_user.id end end private def user_search Photopost.user_search(params[:search][:search_by], params[:search][:value]) end def post_search Photopost.post_search(params[:search][:search_by], params[:search][:value]) end end end end
class AddTrendingIdToArticle < ActiveRecord::Migration def change add_column :articles, :trending_id, :integer end end
class Admin::DashboardController < Admin::BaseController before_action :authenticate_user! after_action :verify_authorized, only: :dashboard def dashboard authorize :dashboard, :show? end end
name "chef-php-extra" maintainer "Alistair Stead" maintainer_email "alistair.stead@inviqa.com" license "Apache 2.0" description "Installs/Configures additional PHP modules, PEAR and PECL packages" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.4.2" depends "git", ">= 1.0.0" depends "yum", ">= 0.8.0" depends "apt", ">= 1.8.4" depends "php", "= 1.1.8" %w{ ubuntu debian centos redhat fedora }.each do |os| supports os end recipe "chef-php-extra", "No default install" recipe "chef-php-extra::development", "Install development tools" recipe "chef-php-extra::module_dev", "Install additional module" recipe "chef-php-extra::module_gd", "Install additional module" recipe "chef-php-extra::module_imagick", "Install additional module" recipe "chef-php-extra::module_mcrypt", "Install additional module" recipe "chef-php-extra::module_soap", "Install additional module soap" recipe "chef-php-extra::module_xml", "Install additional module xml" recipe "chef-php-extra::pear", "Updates pear using pear" recipe "chef-php-extra::PHP_CodeSniffer", "Install PHP_CodeSniffer" recipe "chef-php-extra::PHP_Depend", "Install PHP_Depend" recipe "chef-php-extra::PHP_PMD", "Install PHP_PMD" recipe "chef-php-extra::PhpDocumentor", "Install PhpDocumentor" recipe "chef-php-extra::vfsStream", "Install vfsStream with PEAR" recipe "chef-php-extra::xdebug", "Install xdebug"
# frozen_string_literal: true RSpec.describe EsaArchiver do it 'has a version number' do expect(EsaArchiver::VERSION).not_to be nil end end
class Book < ApplicationRecord validates :title,presence:true validates :body,presence:true,length: {maximum:200} belongs_to :user end
class AddNotificationIdToReceipts < ActiveRecord::Migration def change add_column :receipts, :notification_id, :integer end end
# encoding: utf-8 require 'packetfu' require 'sippy_cup/media/rtp_header' module SippyCup class Media class RTPPayload attr_reader :header def initialize(payload_id = 0) @header = RTPHeader.new payload_id: payload_id end def to_bytes @header.to_s + media end def method_missing(method, *args) if method.to_s =~ /^rtp_/ method = method.to_s.sub(/^rtp_/, '').to_sym @header.send method, *args else super end end end end end
module Gpdb class ConnectionChecker def self.check!(gpdb_instance, account) validate_model!(gpdb_instance) validate_model!(account) ConnectionBuilder.connect!(gpdb_instance, account) true rescue ActiveRecord::JDBCError => e raise ApiValidationError.new(:connection, :generic, {:message => e.message}) end def self.validate_model!(model) model.valid? || raise(ActiveRecord::RecordInvalid.new(model)) end end end
# encoding: UTF-8 class News < ActiveRecord::Base has_and_belongs_to_many :groups # Validations validates :title, :presence => true validates :content, :presence => true validates :date, :presence => true validates :groups, :presence => true def attributes if active ret = { 'id' => id, 'title' => title, 'content' => content, 'date' => date, 'updated_at' => updated_at, 'active' => active } else ret = { 'id' => id, 'active' => active, 'updated_at' => updated_at } end return ret end rails_admin do navigation_label 'Für alle Gruppen' list do field :id field :title field :active field :date field :groups end edit do field :title field :active field :content, :ck_editor field :date field :groups do inline_add false end end end # Class methods def self.all_public since, groups if since.nil? includes(:groups).where(:groups => {id: groups}).order("news.date desc") else since = (since.to_i + 1).to_s includes(:groups).where(:groups => {id: groups}).where('news.updated_at > ?', DateTime.strptime(since, '%s')).order("news.date desc") end end end
module Lacquer::ResourceControllerExtension def self.included(clazz) clazz.class_eval do require 'lacquer' def clear_model_cache_with_lacquer if model_name == 'Page' if model.published_at != nil && model.published? purge_page_and_ancestors(model) end else purge_all_pages end clear_model_cache_without_lacquer end alias_method_chain :clear_model_cache, :lacquer def purge_page_and_ancestors(page) if page.path == '/' Lacquer::Varnish.new.purge("^/$") # Instead of "/", which does a global purge else Lacquer::Varnish.new.purge(page.path) end purge_page_and_ancestors(page.parent) if page.parent end def purge_all_pages Lacquer::Varnish.new.purge('.*') end end end end
module Rack module WebSocket module Extensions module Thin autoload :Connection, "#{::File.dirname(__FILE__)}/thin/connection" def self.included(thin) thin_connection = thin.const_get(:Connection) thin_connection.send(:include, Thin.const_get(:Connection)) end end end end end
require "rails_helper" RSpec.feature "User can edit a page" do context "When a page exists" do scenario "The page's title can be changed" do test_page = Page.create(title: "test_title", content: "test_content", slug: "test_slug") visit page_path(test_page.id) expect(page).to have_content(test_page.title) click_link "Edit" fill_in "Title", with: "Edited Page Title" click_button "Update Page" expect(page).to have_content("Edited Page Title") end scenario "The page's content can be changed" do test_page = Page.create(title: "test_title", content: "test_content", slug: "test_slug") visit page_path(test_page.id) expect(page).to have_content(test_page.content) click_link "Edit" fill_in "Content", with: "Edited Page Content" click_button "Update Page" expect(page).to have_content("Edited Page Content") end end end
require 'rails_helper' RSpec.describe RatesController, type: :controller do let(:room) {FactoryBot.create :room} let(:user) {FactoryBot.create :user} let(:rate) {FactoryBot.attributes_for :rate} let(:rate2) {FactoryBot.create :rate} let(:rate1) {FactoryBot.attributes_for :rate, score: nil} before {log_in user} describe "POST #create" do context "when valid params" do before {post :create, params: {rate: rate,room_id: room.id, score: 4},format: :js} it "should render show template" do expect(response).to render_template :create end end context "when invalid params" do before {post :create, params: {rate: rate1,room_id: room.id}} it "should update and redirect to root_path" do expect(response).to redirect_to root_path end end end describe "PATCH #update" do context "when valid params" do before {patch :update, params: {id: rate2.id, room_id: room.id,score: 5}, format: :js} it "should correct name" do expect(assigns(:rate).score).to eq 5 end it "should render show template" do expect(response).to render_template :update end end context "when invalid params" do before {patch :update, params: {id: rate2.id, room_id: room.id, score: nil }} it "should a invalid type" do expect(assigns(:rate).invalid?).to eq true end it "should update and redirect to root_path" do expect(response).to redirect_to root_path end end end end
require 'vimrunner' require 'tempfile' require 'letters' def specs_run parsed_quickfix_list.last['text'] =~ /(\d+) example/ $1.to_i end def parsed_quickfix_list eval(@vim.command("echo getqflist()").gsub(/:/, "=>")) end describe "spec runner plugin" do let (:path_to_plugin) { File.expand_path(File.join(File.dirname(__FILE__), '..')) } let (:path_to_formatter) { File.expand_path(File.join(path_to_plugin, 'plugin', 'formatter', 'vim_quickfix_formatter.rb')) } let (:path_to_sample_spec) { File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'spec_sample.rb')) } let (:spec_file) { f = Tempfile.new("vim-rspec-runner") f.write(IO.read(path_to_sample_spec)) f.close f } let (:formatter_class) { "RSpec::Core::Formatters::VimQuickfixFormatter" } before(:all) do p = IO.popen(["gvim", "--version"]) i = p.readlines File.open('/tmp/rory.out', 'w') { |f| f.write(i) } p.close @vim = Vimrunner.start @vim.add_plugin(path_to_plugin, 'plugin/rspec-runner.vim') end after(:all) do @vim.kill spec_file.unlink end it "returns the path to the file containing the custom formatter for the relevant version of Rspec" do @vim.command('echo rspecrunner#PathToFormatter("2.x")').should eq path_to_formatter path_to_rspec_1_formatter = File.expand_path(File.join(path_to_plugin, 'plugin', 'formatter', 'vim_quickfix_formatter_rspec1.rb')) @vim.command('echo rspecrunner#PathToFormatter("1.x")').should eq path_to_rspec_1_formatter end it "returns the namespaced class of the selected formatter for the relevant version of Rspec" do @vim.command(%Q{echo rspecrunner#FormatterClass("2.x")}).should eq "RSpec::Core::Formatters::VimQuickfixFormatter" end it "returns the current version of Rspec" do # TODO: before you're done figure out if you want this to be more granular - e.g. rspec 1 checks @vim.command("echo rspecrunner#RspecVersion()").should eq "2.x" end it "returns the name of the spec file to be run" do @vim.edit(spec_file.path) @vim.command("echo rspecrunner#SpecFilePath()").should eq spec_file.path end it "returns the command to be run to execute all specs in a file" do rspec_command = "bundle exec rspec -r #{path_to_formatter} -f #{formatter_class} -o ~/.last-rspec -f p #{spec_file.path}" @vim.edit(spec_file.path) @vim.command('echo rspecrunner#RspecCommand("file")').should eq rspec_command end it "runs all the specs in the file in a quickfix list" do @vim.edit(spec_file.path) @vim.command("call rspecrunner#RunSpecsFile()") specs_run.should eq 2 end it "returns the line number of the current example" do @vim.edit(spec_file.path) @vim.normal("/fail!!<CR>") @vim.command("echo rspecrunner#ExampleLineNumber()").should eq "2" end it "returns the command to be run to execute only the spec under cursor" do rspec_command = "bundle exec rspec -r #{path_to_formatter} -f #{formatter_class} -o ~/.last-rspec -f p #{spec_file.path}:2" @vim.edit(spec_file.path) @vim.normal("/fail!!<CR>") @vim.command('echo rspecrunner#RspecCommand("example")').should eq rspec_command end it "runs the spec at the specified file number" do @vim.edit(spec_file.path) @vim.normal("/fail!!<CR>") @vim.command("call rspecrunner#RunSpecsExample()") specs_run.should eq 1 end end
class MP3Importer #let(:file_name) {'Michael Jackson - Black or White - pop.mp3'} attr_accessor :path, :files def initialize(file_path) @path = file_path @files = [] end def files Dir.entries(path).select {|file| file.include?(".mp3")} end def import files.collect do |file| artist_song = file.split(" - ") artist = Artist.find_or_create_by_name(artist_song[0]) song = artist.add_song_by_name(artist_song[1]) # song.artist = artist # artist.songs << song end end end
class PeerAlly < ActiveRecord::Base attr_accessible :name, :grade, :bio, :avatar, :display, :ups_id, :email, :last_name, :first_name, :member_of, :administrator #ups data fields attr_protected :uid, :provider #for omniauth authentication validates :name, :ups_id, :presence => true, :uniqueness => true #must have name to display an ally and ups_id for login verification has_attached_file :avatar, :styles => {:thumb => "100x100>" }, :default_url => "/images/:style/missing.png" #directory of default image validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/ #avatar photos for each ally must by an image before_save :downcase_fields #make sure ups_id is lowercase for login validation def downcase_fields self.ups_id.downcase end # is a faculty member? def faculty? member_of.downcase.include? "faculty" end # is a student? def student? member_of.downcase.include? "student" end #Changes routing so the name of the ally is included when on their profile page def to_param "#{id}-#{name}" end # creates a new user from the given omniauth authorization # def self.create_with_omniauth(auth) # user = PeerAlly.new( # :ups_id => auth["info"]["name"], # :email => auth["info"]["email"], # :last_name => auth["info"]["last_name"], # :first_name => auth["info"]["first_name"], # :member_of => auth["info"]["memberOf"] # ) # user.provider = auth["provider"] # user.uid = auth["uid"] # user.save! # return user # end end
class ProjectsController < ApplicationController before_action :check_current_user before_action :find_project, only: [:show, :edit, :update, :destroy] before_action :check_member, only: [:show, :edit, :update, :destroy] before_action :find_member, only: [:edit, :update, :destroy] def index @projects = Project.all if current_user.tracker_token.present? tracker_api = TrackerAPI.new @tracker_projects = tracker_api.projects(current_user.tracker_token) end end def new @project = Project.new end def create @project = Project.new(projects_params) if @project.save @project.memberships.create(user_id: current_user.id, role: "Owner") redirect_to project_tasks_path(@project), notice: "Project was created successfully" else render :new end end def show end def edit end def update if @project.update(projects_params) redirect_to project_path(@project), notice: "Project was updated successfully" else render :edit end end def destroy if @project.destroy redirect_to projects_path, notice: "Project was deleted successfully" end end private def projects_params params.require(:project).permit(:name) end def find_project @project = Project.find(params[:id]) end def check_current_user if current_user @user = current_user else session[:redirect_to] = request.fullpath redirect_to sign_in_path, alert: "You must sign in" end end def check_member @current_membership = current_user.memberships.find_by(project_id: @project.id) if !(current_user.memberships.find_by(project_id: @project.id) == nil) || current_user.admin else flash[:alert] = 'You do not have access to that project' redirect_to projects_path end end def find_member if !(current_user.admin) @current_membership = current_user.memberships.find_by(project_id: @project.id) if @current_membership.role == "Owner" else flash[:alert] = 'You do not have access' render :show end end end end
# merge method =begin merge - returns a new hash; non-destructive merge! - overwrites the existing hash; destructive - entries with duplicate keys will use the value from the "other" hash unless otherwise specified in a block { | key, oldval, newval | block } =end h1 = { a: 100, b: 200, c: 300} h2 = { b: 164, c: 238, d: 400} p h1 p h2 p h1.merge(h2) # duplicate values overwritten by h2 p h1.merge(h2) { |k,v1,v2| v1 } # duplicate values preserved from h1 p h1.merge(h2) { |k,v1,v2| v2 } # duplicate values overwritten by h2 (default behavior) #merge! works the same way but overwrites the existing hash
RSpec.feature "Users can create a third-party project" do context "when the user does NOT belong to BEIS" do let(:user) { create(:partner_organisation_user) } before { authenticate!(user: user) } after { logout } context "when viewing a project" do scenario "a new third party project cannot be added to the programme when a report does not exist" do programme = create(:programme_activity, :gcrf_funded, extending_organisation: user.organisation) project = create(:project_activity, :gcrf_funded, organisation: user.organisation, parent: programme) visit activities_path click_on project.title click_on t("tabs.activity.children") expect(page).to_not have_button(t("action.activity.add_child")) end scenario "a new third party project can be added to the project" do programme = create(:programme_activity, :gcrf_funded, extending_organisation: user.organisation) project = create(:project_activity, :gcrf_funded, organisation: user.organisation, extending_organisation: user.organisation, parent: programme) _report = create(:report, :active, organisation: user.organisation, fund: project.associated_fund) activity = build(:third_party_project_activity, :gcrf_funded, :with_commitment, country_partner_organisations: ["National Council for the State Funding Agencies (CONFAP)"], benefitting_countries: ["AG", "HT"], sdgs_apply: true, sdg_1: 5) visit activities_path click_on(project.title) click_on t("tabs.activity.children") click_on(t("action.activity.add_child")) form = ActivityForm.new(activity: activity, level: "project", fund: "gcrf") form.complete! expect(page).to have_content t("action.third_party_project.create.success") expect(project.child_activities.count).to eq 1 created_activity = form.created_activity expect(created_activity).to eq(project.child_activities.last) expect(created_activity.organisation).to eq user.organisation expect(created_activity.title).to eq(activity.title) expect(created_activity.description).to eq(activity.description) expect(created_activity.objectives).to eq(activity.objectives) expect(created_activity.sector_category).to eq(activity.sector_category) expect(created_activity.sector).to eq(activity.sector) expect(created_activity.programme_status).to eq(activity.programme_status) expect(created_activity.planned_start_date).to eq(activity.planned_start_date) expect(created_activity.planned_end_date).to eq(activity.planned_end_date) expect(created_activity.actual_start_date).to eq(activity.actual_start_date) expect(created_activity.actual_end_date).to eq(activity.actual_end_date) expect(created_activity.benefitting_countries).to match_array(activity.benefitting_countries) expect(created_activity.gdi).to eq(activity.gdi) expect(created_activity.aid_type).to eq(activity.aid_type) expect(created_activity.collaboration_type).to eq(activity.collaboration_type) expect(created_activity.sdgs_apply).to eq(activity.sdgs_apply) expect(created_activity.sdg_1).to eq(activity.sdg_1) expect(created_activity.policy_marker_gender).to eq(activity.policy_marker_gender) expect(created_activity.policy_marker_climate_change_adaptation).to eq(activity.policy_marker_climate_change_adaptation) expect(created_activity.policy_marker_climate_change_mitigation).to eq(activity.policy_marker_climate_change_mitigation) expect(created_activity.policy_marker_biodiversity).to eq(activity.policy_marker_biodiversity) expect(created_activity.policy_marker_desertification).to eq(activity.policy_marker_desertification) expect(created_activity.policy_marker_disability).to eq(activity.policy_marker_disability) expect(created_activity.policy_marker_disaster_risk_reduction).to eq(activity.policy_marker_disaster_risk_reduction) expect(created_activity.policy_marker_nutrition).to eq(activity.policy_marker_nutrition) expect(created_activity.channel_of_delivery_code).to eq(activity.channel_of_delivery_code) expect(created_activity.gcrf_challenge_area).to eq(activity.gcrf_challenge_area) expect(created_activity.gcrf_strategic_area).to eq(activity.gcrf_strategic_area) expect(created_activity.covid19_related).to eq(activity.covid19_related) expect(created_activity.oda_eligibility).to eq(activity.oda_eligibility) expect(created_activity.oda_eligibility_lead).to eq(activity.oda_eligibility_lead) expect(created_activity.uk_po_named_contact).to eq(activity.uk_po_named_contact) expect(created_activity.commitment.value).to eq(activity.commitment.value) expect(created_activity.publish_to_iati).to be(true) end scenario "a new third party project can be added to an ISPF ODA project" do programme = create(:programme_activity, :ispf_funded, extending_organisation: user.organisation) project = create(:project_activity, :ispf_funded, organisation: user.organisation, extending_organisation: user.organisation, parent: programme, is_oda: true) _report = create(:report, :active, organisation: user.organisation, fund: project.associated_fund) implementing_organisation = create(:implementing_organisation) activity = build(:third_party_project_activity, :with_commitment, parent: project, is_oda: true, ispf_oda_partner_countries: ["IN"], ispf_non_oda_partner_countries: ["CA"], benefitting_countries: ["AG", "HT"], sdgs_apply: true, sdg_1: 5, ispf_themes: [1], implementing_organisations: [implementing_organisation], tags: [1]) visit activities_path click_on(project.title) click_on t("tabs.activity.children") click_on(t("action.activity.add_child")) form = ActivityForm.new(activity: activity, level: "project", fund: "ispf") form.complete! expect(page).to have_content t("action.third_party_project.create.success") expect(project.child_activities.count).to eq 1 created_activity = form.created_activity expect(created_activity).to eq(project.child_activities.last) expect(created_activity.organisation).to eq(user.organisation) expect(created_activity.is_oda).to eq(activity.is_oda) expect(created_activity.title).to eq(activity.title) expect(created_activity.description).to eq(activity.description) expect(created_activity.objectives).to eq(activity.objectives) expect(created_activity.sector_category).to eq(activity.sector_category) expect(created_activity.sector).to eq(activity.sector) expect(created_activity.programme_status).to eq(activity.programme_status) expect(created_activity.planned_start_date).to eq(activity.planned_start_date) expect(created_activity.planned_end_date).to eq(activity.planned_end_date) expect(created_activity.actual_start_date).to eq(activity.actual_start_date) expect(created_activity.actual_end_date).to eq(activity.actual_end_date) expect(created_activity.ispf_oda_partner_countries).to match_array(activity.ispf_oda_partner_countries) expect(created_activity.ispf_non_oda_partner_countries).to match_array(activity.ispf_non_oda_partner_countries) expect(created_activity.benefitting_countries).to match_array(activity.benefitting_countries) expect(created_activity.gdi).to eq(activity.gdi) expect(created_activity.aid_type).to eq(activity.aid_type) expect(created_activity.collaboration_type).to eq(activity.collaboration_type) expect(created_activity.sdgs_apply).to eq(activity.sdgs_apply) expect(created_activity.sdg_1).to eq(activity.sdg_1) expect(created_activity.ispf_themes).to eq(activity.ispf_themes) expect(created_activity.policy_marker_gender).to eq(activity.policy_marker_gender) expect(created_activity.policy_marker_climate_change_adaptation).to eq(activity.policy_marker_climate_change_adaptation) expect(created_activity.policy_marker_climate_change_mitigation).to eq(activity.policy_marker_climate_change_mitigation) expect(created_activity.policy_marker_biodiversity).to eq(activity.policy_marker_biodiversity) expect(created_activity.policy_marker_desertification).to eq(activity.policy_marker_desertification) expect(created_activity.policy_marker_disability).to eq(activity.policy_marker_disability) expect(created_activity.policy_marker_disaster_risk_reduction).to eq(activity.policy_marker_disaster_risk_reduction) expect(created_activity.policy_marker_nutrition).to eq(activity.policy_marker_nutrition) expect(created_activity.covid19_related).to eq(activity.covid19_related) expect(created_activity.channel_of_delivery_code).to eq(activity.channel_of_delivery_code) expect(created_activity.oda_eligibility).to eq(activity.oda_eligibility) expect(created_activity.oda_eligibility_lead).to eq(activity.oda_eligibility_lead) expect(created_activity.uk_po_named_contact).to eq(activity.uk_po_named_contact) expect(created_activity.implementing_organisations).to eq(activity.implementing_organisations) expect(created_activity.tags).to eq(activity.tags) expect(created_activity.commitment.value).to eq(activity.commitment.value) expect(created_activity.publish_to_iati).to be(true) end scenario "a new third party project can be added to an ISPF non-ODA project" do programme = create(:programme_activity, :ispf_funded, extending_organisation: user.organisation, is_oda: false) project = create(:project_activity, :ispf_funded, organisation: user.organisation, extending_organisation: user.organisation, parent: programme, is_oda: false) _report = create(:report, :active, organisation: user.organisation, fund: project.associated_fund) implementing_organisation = create(:implementing_organisation) activity = build(:third_party_project_activity, :with_commitment, parent: project, is_oda: false, ispf_non_oda_partner_countries: ["IN"], benefitting_countries: ["AG", "HT"], sdgs_apply: true, sdg_1: 5, ispf_themes: [1], implementing_organisations: [implementing_organisation], tags: [4]) visit activities_path click_on(project.title) click_on t("tabs.activity.children") click_on(t("action.activity.add_child")) form = ActivityForm.new(activity: activity, level: "project", fund: "ispf") form.complete! expect(page).to have_content t("action.third_party_project.create.success") expect(project.child_activities.count).to eq 1 created_activity = form.created_activity expect(created_activity).to eq(project.child_activities.last) expect(created_activity.organisation).to eq(user.organisation) expect(created_activity.is_oda).to eq(activity.is_oda) expect(created_activity.title).to eq(activity.title) expect(created_activity.description).to eq(activity.description) expect(created_activity.sector_category).to eq(activity.sector_category) expect(created_activity.sector).to eq(activity.sector) expect(created_activity.programme_status).to eq(activity.programme_status) expect(created_activity.planned_start_date).to eq(activity.planned_start_date) expect(created_activity.planned_end_date).to eq(activity.planned_end_date) expect(created_activity.actual_start_date).to eq(activity.actual_start_date) expect(created_activity.actual_end_date).to eq(activity.actual_end_date) expect(created_activity.ispf_non_oda_partner_countries).to match_array(activity.ispf_non_oda_partner_countries) expect(created_activity.ispf_themes).to eq(activity.ispf_themes) expect(created_activity.uk_po_named_contact).to eq(activity.uk_po_named_contact) expect(created_activity.implementing_organisations).to eq(activity.implementing_organisations) expect(created_activity.tags).to eq(activity.tags) expect(created_activity.finance).to be_nil expect(created_activity.tied_status).to be_nil expect(created_activity.flow).to be_nil expect(created_activity.transparency_identifier).to be_nil expect(created_activity.oda_eligibility).to be_nil expect(created_activity.fstc_applies).to be_nil expect(created_activity.covid19_related).to be_nil expect(created_activity.policy_marker_gender).to be_nil expect(created_activity.policy_marker_climate_change_adaptation).to be_nil expect(created_activity.policy_marker_climate_change_mitigation).to be_nil expect(created_activity.policy_marker_biodiversity).to be_nil expect(created_activity.policy_marker_desertification).to be_nil expect(created_activity.policy_marker_disability).to be_nil expect(created_activity.policy_marker_disaster_risk_reduction).to be_nil expect(created_activity.policy_marker_nutrition).to be_nil expect(created_activity.commitment.value).to eq(activity.commitment.value) expect(created_activity.publish_to_iati).to be(false) end context "when the `activity_linking` feature flag is enabled" do before do allow(ROLLOUT).to receive(:active?).and_call_original allow(ROLLOUT).to receive(:active?).with(:activity_linking).and_return(true) end scenario "an ODA third-party project can be linked to an existing non-ODA third-party project" do implementing_organisation = create(:implementing_organisation) non_oda_programme = create(:programme_activity, :ispf_funded, is_oda: false, extending_organisation: user.organisation) _report = create(:report, :active, organisation: user.organisation, fund: non_oda_programme.associated_fund) non_oda_project = create(:project_activity, :ispf_funded, is_oda: false, parent: non_oda_programme, organisation: user.organisation, extending_organisation: user.organisation, ispf_themes: [1]) non_oda_3rdp_project = create(:third_party_project_activity, :ispf_funded, is_oda: false, extending_organisation: user.organisation, parent: non_oda_project) oda_programme = create(:programme_activity, :ispf_funded, is_oda: true, linked_activity: non_oda_programme, extending_organisation: user.organisation) oda_project = create(:project_activity, :ispf_funded, is_oda: true, parent: oda_programme, organisation: user.organisation, extending_organisation: user.organisation, linked_activity: non_oda_project, ispf_themes: [1]) oda_3rdp_project = build(:third_party_project_activity, :with_commitment, parent: oda_project, is_oda: true, linked_activity_id: non_oda_3rdp_project.id, benefitting_countries: ["AG", "HT"], sdgs_apply: true, sdg_1: 5, ispf_themes: [1], implementing_organisations: [implementing_organisation], extending_organisation: user.organisation) visit activities_path click_on(oda_project.title) click_on t("tabs.activity.children") click_on(t("action.activity.add_child")) form = ActivityForm.new(activity: oda_3rdp_project, level: "project", fund: "ispf") form.complete! expect(page).to have_content t("action.third_party_project.create.success") created_activity = form.created_activity expect(created_activity.title).to eq(oda_3rdp_project.title) expect(created_activity.is_oda).to eq(oda_3rdp_project.is_oda) expect(created_activity.linked_activity).to eq(non_oda_3rdp_project) end context "without an editable report" do scenario "a new third party project cannot be added" do programme = create(:programme_activity, :gcrf_funded, extending_organisation: user.organisation) project = create(:project_activity, :gcrf_funded, organisation: user.organisation, extending_organisation: user.organisation, parent: programme) visit activities_path click_on(project.title) click_on t("tabs.activity.children") expect(page).to have_no_button t("action.activity.add_child") end end end end end end
GhFeedReader::Application.routes.draw do get "activities/show" resources :rsses get 'activities/:uid' => 'activities#show', as: :activity namespace :authors do get ':uid/activities' => 'activities#show', as: :activity end root 'welcome#index' end
require "set" module BlameAnalyzer class Author attr_accessor :name, :abbreviation, :solitary_loc, :paired_loc, :owned_loc, :created_commits, :participated_commits def initialize(name: nil, email: nil, abbreviation: nil) @name = name @email = email @abbreviation = abbreviation @solitary_loc = 0 @paired_loc = 0 @owned_loc = 0 @created_commits = Set.new @participated_commits = Set.new end def loc @solitary_loc + @paired_loc end def name @name || "Unknown name" end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require "faker" Invitation.destroy_all Course.destroy_all User.destroy_all Video.destroy_all publishers = [] 3.times do publisher = User.new( first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, #role: User.role, email: Faker::Internet.email, password: "12345a1!" ) publisher.role = User.role.publisher publisher.save! publishers << publisher end students = [] 3.times do student = User.create( first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, #role: "student", email: Faker::Internet.email, password: "12345a1!" ) students << student end courses = [] 3.times do course = Course.new( name: Faker::Educator.course, description: Faker::Lorem.sentence(3) ) course.user = publishers.sample course.save! courses << course end videos = [] courses.each do |course| 3.times do video = Video.new( name: Faker::Lorem.sentence(3), url: Faker::Internet.url ) video.course = course video.save! videos << video end end invitations = [] 3.times do invitation = Invitation.new( message: Faker::Lorem.sentence(3), status: ["pending", "accepted"].sample ) invitation.course = courses.sample invitation.user = students.sample invitation.save! invitations << invitation end
require 'spec_helper' describe MonthlycostsController do render_views describe "GET 'index'" do it "should be successful" do get 'index' response.should be_success end end describe "GET 'show'" do before(:each) do @monthlycost = Factory(:monthlycost) end it "should be successful" do get :show, :id => @monthlycost response.should be_success end end describe "GET 'new'" do it "should be successful" do get :new response.should be_success end end describe "POST 'create'" do describe "failure" do before(:each) do @attr = { :clock_no => "", :name => "", :role => "", :contract => "", :hours => "", :amount => "" } end it "should not create a monthlycost" do lambda do post :create, :monthlycost => @attr end.should_not change(Monthlycost, :count) end it "should render the 'new' page" do post :create, :monthlycost => @attr response.should render_template('new') end end describe "success" do before(:each) do @attr = { :clock_no => "M0001", :name => "F Bloggs", :role => "QS", :contract => "3423", :hours => 20, :amount => 2000, :period => "01", :year => 2012 } end it "should create a monthlycost" do lambda do post :create, :monthlycost => @attr end.should change(Monthlycost, :count).by(1) end it "should redirect to the 'show' page" do post :create, :monthlycost => @attr response.should redirect_to(monthlycost_path(assigns(:monthlycost))) end end end describe "GET 'edit'" do before(:each) do @monthlycost = Factory(:monthlycost) end it "should be successful" do get :edit, :id => @monthlycost response.should be_success end end describe "POST 'update'" do before(:each) do @monthlycost = Factory(:monthlycost) end describe "failure" do before(:each) do @attr = { :clock_no => "", :name => "", :role => "", :contract => "", :hours => "", :amount => "" } end it "should render the 'edit' page" do put :update, :id => @monthlycost, :monthlycost => @attr response.should render_template('edit') end end describe "success" do before(:each) do @attr = { :clock_no => "M9999", :name => "New Name", :role => "IT", :contract => "3666", :hours => 25, :amount => 3500, :period => "02", :year => 2012 } end it "should change the record's attributes" do put :update, :id => @monthlycost, :monthlycost => @attr @monthlycost.reload @monthlycost.name.should == @attr[:name] @monthlycost.hours.should == @attr[:hours] @monthlycost.period.should == @attr[:period] end it "should redirect to the 'show' page" do put :update, :id => @monthlycost, :monthlycost => @attr response.should redirect_to(monthlycost_path(@monthlycost)) end it "should have a flash message" do put :update, :id => @monthlycost, :monthlycost => @attr flash[:success].should =~ /updated/ end end end describe "DELETE 'destroy'" do before(:each) do @monthlycost = Factory(:monthlycost) end it "should destroy the monthlycost" do lambda do delete :destroy, :id => @monthlycost end.should change(Monthlycost, :count).by(-1) end it "should redirect to the 'list' page" do delete :destroy, :id => @monthlycost response.should redirect_to(monthlycosts_path) end end end
class CreateMonsters < ActiveRecord::Migration[5.2] def change create_table :monsters do |t| t.string :name t.integer :hp t.integer :att t.string :img t.integer :loot, :default => 5 t.timestamps end end end
require 'spec_helper' describe Rack::APICoder::RequestValidator, type: :request do include Rack::Test::Methods before do load File.expand_path '../../../fixtures/user.conf', __FILE__ end let(:app) do Rack::Builder.new do use Rack::APICoder::RequestValidator run ->(_env) { [200, {}, ['Internal Server Error']] } end end describe '#call' do subject { app } let(:parsed_body) { JSON.parse(last_response.body).symbolize_keys } context 'when not found route given(GET)' do it 'should return status 404' do get '/not_found' expect(last_response.status).to eq 404 expect(parsed_body).to match( id: 'not_found', message: be_a(String) ) end end context 'when found route given(GET)' do it 'should return status 200' do get '/users' expect(last_response.status).to eq 200 end end context 'when found route and content_type is not application/jsoon given(POST)' do let(:params) do { id: 1, name: 'name', created_at: '20160101', updated_at: '20160102' }.to_json end it 'should return status 400' do post '/users', params, 'CONTENT_TYPE' => 'application/x-www-form-urlencoded' expect(last_response.status).to eq 400 expect(parsed_body).to match( id: 'invalid_content_type', message: be_a(String) ) end end context 'when valid route, header, not valid parameter given' do let(:params) do { name: 1, password: 'password' }.to_json end it 'should return status 400' do post '/users', params, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 400 expect(parsed_body).to match( id: 'invalid_parameter', message: be_a(String) ) end end context 'when valid route, header, parameter given' do let(:params) do { name: 'name', password: 'password' }.to_json end it 'should return status 200' do post '/users', params, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 200 end end end end
class AddRequestMaterialLineIdToWarehouseTransactionLines < ActiveRecord::Migration[5.0] def change add_column :warehouse_transaction_lines, :request_material_line_id, :integer, index: true end end
require 'bcrypt' class User < ApplicationRecord before_save :encrypt_password after_save :clear_password attr_accessor :password #EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i validates :email, :presence => true, :uniqueness => true validates :password, :confirmation => true #password_confirmation attr validates_length_of :password, :in => 6..20, :on => :create def encrypt_password if password.present? self.salt = BCrypt::Engine.generate_salt self.encrypted_password= BCrypt::Engine.hash_secret(password, salt) end end def clear_password self.password = nil end end
require 'spec_helper' describe StripDownConverter do subject { described_class } describe '#call' do it 'returns an empty string for nil' do expect(subject.call(nil)).to be == "" end it 'removes markdown formatting' do expect(subject.call("# Header\n")).to be == "Header\n" end end end
class TestSheetsController < ApplicationController add_breadcrumb I18n.t('breadcrumbs.home'), :root_path, :only => [:index, :new, :edit, :show] add_breadcrumb I18n.t('breadcrumbs.form_test'), :test_sheets_path, :only => [:index, :new, :edit, :show] respond_to :html, :json def new @sheet = TestSheet.new(:public => true) @topics = [] add_breadcrumb I18n.t('breadcrumbs.new_test'), new_test_sheet_path end def create #@sheet = TestSheet.new(params[:test_sheet]) @sheet = current_user.test_sheets.build(params[:test_sheet]) if @sheet.save flash[:success] = "Test create successful!" redirect_to @sheet else render 'new' end end def index #@test_sheets = TestSheet.paginate(page: params[:page]) if current_user.super_user? @test_sheets = TestSheet.paginate(per_page: 10, page: params[:page]) else @test_sheets = TestSheet.where('user_id = ? OR public = ?', current_user.id, true).paginate(per_page: 10, page: params[:page]) end end def show @sheet = TestSheet.find(params[:id]) #@items = Item.all if current_user.super_user? @items = Item.paginate(page: params[:page], per_page: 10).order('updated_at DESC') else @items = Item.where('user_id = ? OR public = ? AND approved = ?', current_user.id, true, true) .paginate(page: params[:page], per_page: 10).order('updated_at DESC') end if params[:tag] @items = @items.tagged_with(params[:tag]) end @tags = current_user.owned_tags add_breadcrumb @sheet.title, @sheet end def edit @sheet = TestSheet.find(params[:id]) @topics = Subject.find(@sheet.subject_id).topics add_breadcrumb @sheet.title, @sheet add_breadcrumb I18n.t('breadcrumbs.edit_test'), edit_test_sheet_path end def update @sheet = TestSheet.find(params[:id]) if @sheet.update_attributes(params[:test_sheet]) flash[:success] = "Test sheet update successful!" redirect_to @sheet else @topics = Subject.find(@sheet.subject_id).topics render 'edit' end end def destroy TestSheet.find(params[:id]).destroy flash[:success] = "Test destroyed." redirect_to test_sheets_path end def preview @sheet = TestSheet.find(params[:id]) @page = params.has_key?(:page) ? params[:page].to_i : 1 @items = @sheet.items @item = @items[@page - 1] @sub_items = @item.sub_items @time = 0 end end
# frozen_string_literal: true class User < ActiveRecord::Base include Hydra::User include CurationConcerns::User include Sufia::User include Sufia::UserUsageStats if Blacklight::Utils.needs_attr_accessible? attr_accessible :email, :password, :password_confirmation end Devise.add_module(:saml_authenticatable, strategy: true, controller: :sessions, model: 'devise/models/saml_authenticatable') devise :saml_authenticatable # TODO: Add additional attributes from Shibboleth properties def populate_attributes self end # Method added by Blacklight; Blacklight uses #to_s on your # user class to get a user-displayable login/identifier for # the account. def to_s email end def admin? groups.include?('admin') end def groups groups = super groups << department groups end class << self def find_by_email(query) User.where(email: query).first end def batchuser User.find_by_user_key(batchuser_key) || User.create!(email: batchuser_key) end def batchuser_key 'batchuser' end def audituser User.find_by_user_key(audituser_key) || User.create!(email: audituser_key) end def audituser_key 'audituser' end end end
class HotelsController < InheritedResources::Base before_filter :authenticate_user!, :except => [:index,:show,:update] before_filter :authenticate_admin!, :only => [:update] def show show!{ @users=User.all @hotel.average_rating } end def index if admin_signed_in? hotel_for_index(status) else hotel_for_index("approved") end end def create @hotel = current_user.hotels.new(hotel_params) if @hotel.save flash[:success] = "Hotel created!" redirect_to hotels_path else flash[:error] = "Failed to create hotel!" render 'new' end end def update @hotel = Hotel.find_by_id(params[:id]) respond_to do |format| if (@hotel.may_reject? || @hotel.may_approve?) if params[:hotel][:status] == "approved" @hotel.approve! else if params[:hotel][:status] == "rejected" @hotel.reject! end end UserMailer.change_status(User.find(@hotel.user_id),@hotel.status).deliver format.html { redirect_to hotels_path, :notice => 'Hotel was successfully updated.' } else format.html { redirect_to hotels_path, :notice => 'Hotel was not successfully updated.' } end end end def destroy if Hotel.find_by_id(params[:id]).user_id == current_user.id Hotel.find_by_id(params[:id]).destroy else end redirect_to hotels_path end private def hotel_params params.require(:hotel).permit(:title,:rating,:breakfast,:price_for_room,:country,:state,:city,:street, :room_description, :name_of_photo) end def correct_user @hotel = current_user.hotels.find_by(id: params[:id]) redirect_to root_path if @hotel.nil? end def status %w[pending approved rejected].include?(params[:status]) ? params[:status] : "pending" end def hotel_for_index(status) @hotels=Hotel.status(status) if !@hotels.nil? if !@hotels.empty? @hotels.each {|hotel| hotel.average_rating} @hotels = Hotel.status(status).paginate(:per_page => 5, :page => params[:page]) end end end end
require_relative 'colors.rb' # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity class Table attr_reader :table def initialize @table = { "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9 } end def modify_table(move = nil, sign = nil) @table[:"#{move}"] = case sign when 'x' sign.pink when 'o' sign.yellow else sign end end def valid_move(move) check = @table[:"#{move}"] check == 'o'.yellow || check == 'x'.pink || move > 9 || move < 1 ? true : false end def check_win if @table[:"1"] == @table[:"2"] && @table[:"3"] == @table[:"1"] 1 elsif @table[:"4"] == @table[:"5"] && @table[:"4"] == @table[:"6"] 1 elsif @table[:"7"] == @table[:"8"] && @table[:"7"] == @table[:"9"] 1 elsif @table[:"7"] == @table[:"4"] && @table[:"7"] == @table[:"1"] 2 elsif @table[:"8"] == @table[:"5"] && @table[:"8"] == @table[:"2"] 2 elsif @table[:"9"] == @table[:"6"] && @table[:"9"] == @table[:"3"] 2 elsif @table[:"7"] == @table[:"5"] && @table[:"5"] == @table[:"3"] 3 elsif @table[:"1"] == @table[:"5"] && @table[:"5"] == @table[:"9"] 3 end end end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
class ScoreUpdater module Week TWO = Date.parse("30/12/2013") #week 2 ends Dec 30 THREE = Date.parse("31/12/2013") #week 3 starts on Dec 31, 2013 end def self.run(period = nil) #returns array of xml_tags containing info for each bowl game games_xml_array = get_score_data(period) #turn each into hash then use data to find/update scores update_count = 0 games_xml_array.each do |game_xml| game_hash = Hash.from_xml(game_xml)['ticker_entry'] #don't need to update if the game hasn't been played yet next if game_not_started?(game_hash) #don't update if game already has winner next if game_has_winner?(game_hash) #if the game has finished, don't need to udpate if game_finished?(game_hash) finished_game_update(game_hash) update_count += 1 else regular_update(game_hash) update_count += 1 end end Rails.logger.info("Finished updating #{update_count} records.") end def self.get_score_data(period) period ||= Date.today >= Week::THREE ? "19" : "18" Rails.logger.info "Updating scores using period: #{period} ..." body = Net::HTTP.get_response(URI("http://scores.nbcsports.com/ticker/data/gamesMSNBC.js.asp?sport=CFB&period=#{period}")).body JSON.parse(body)['games'] end def self.game_not_started?(game_hash) if game_hash['gamestate']['status'] == 'Pre-Game' Rails.logger.info("Game not started. Skipping update...") true else false end end def self.game_finished?(game_hash) #to make sure we don't miss data, we will only say a game is finished if it was finished the day before game_hash['gamestate']['status'] == 'Final' end def self.game_has_winner?(game_hash) p game_hash bowl = Bowl.includes(:teams).where("teams.nbc_id = ?", game_hash['visiting_team']['id']).references(:teams).first #if winner is already assigned, do nothing if bowl.has_winner? Rails.logger.info "#{bowl.name} has winner. Skipping update..." true else false end end def self.finished_game_update(game_hash) bowl = Bowl.includes(:teams).where("teams.nbc_id = ?", game_hash['visiting_team']['id']).references(:teams).first #update scores regular_update(game_hash) #assign winner bowl.set_winner end def self.regular_update(game_hash) #find visitng team and update its score visiting_team_raw_data = game_hash['visiting_team'] visitng_team = Team.find_by_nbc_id(visiting_team_raw_data['id']) #score is an array of score_info. first value is total score visitng_team.game_result.update_attributes(score: visiting_team_raw_data['score'].first) #find home team and update its score home_team_raw_data = game_hash['home_team'] home_team = Team.find_by_nbc_id(home_team_raw_data['id']) #score is an array of score_info. first value is total score home_team.game_result.update_attributes(score: home_team_raw_data['score'].first) end end
Sequel.migration do change do create_table :transactions do primary_key :id foreign_key :invoice_id Integer :credit_card_number DateTime :credit_card_expiration_date #we never really use this stuff. needed? String :result DateTime :created_at DateTime :updated_at end end end
module Commuting class StopEventCluster < ActiveRecord::Base self.table_name = 'commuting_stop_event_clusters' def self.query selects = <<-SQL row_number() over () AS id, 2 as total_wait_time, AVG(cse.duration) as average_stop_duration, ST_NumGeometries(sc.cluster) AS cluster_count, sc.cluster AS geom_collection, ST_Centroid(sc.cluster) AS centroid, ST_MinimumBoundingCircle(sc.cluster) AS circle, sqrt(ST_Area(ST_MinimumBoundingCircle(sc.cluster)) / pi()) AS radius SQL nested_clusters = <<-SQL (SELECT unnest(ST_ClusterWithin( c.lonlat::geometry, -- 63m ST_Distance( ST_GeomFromText('POINT(34.0151661 -118.49075029)', 4326), ST_GeomFromText('POINT(34.0153382 -118.4901983)', 4326) ) )) AS cluster FROM commuting_stop_events c) AS sc, commuting_stop_events cse SQL where_sql = "ST_Contains(ST_CollectionExtract(sc.cluster, 1), cse.lonlat::geometry)" group_sql = 'sc.cluster' select(selects) .from(nested_clusters) .where(where_sql) .group(group_sql) end def as_json(attrs={}) c = RGeo::GeoJSON.encode(centroid) cir = RGeo::GeoJSON.encode(circle) cluster = RGeo::GeoJSON.encode(geom_collection) { id: id, centroid: c, circle: cir, radius: radius, geom_collection: cluster } end end end