text
stringlengths
10
2.61M
namespace :data do desc "import data from old ABJ database to Ruby database" task :import_prodlines => :environment do file = File.open("./lib/tasks/data/prodlines.csv") file.each_with_index do |line, i| next if i == 0 attrs = [] attrs_outer = line.split("|") attrs_outer.each do |val| newval = /\"(.+)\"/.match(val) if newval && newval.length > 1 attrs << newval[1] else attrs << "" end end p = ProductLine.new(:old_id => attrs[0], :description => attrs[1], :notes => attrs[2], :prefix => attrs[3]) p.save! end end task :import_customers => :environment do require 'csv' CSV.foreach('./lib/tasks/data/customers.csv', :headers => true) do |row| cust = Customer.new(:old_id => row[0], :name => row[1], :address => row[2]) city_state_zip = /(.+)[,]*\s+(\w+)[,]*\s+(\d*[-\d+]*)/.match(row[3]) if city_state_zip.nil? cust.city = row[3] else cust.city = city_state_zip[1] unless city_state_zip[1].nil? cust.state = city_state_zip[2] unless city_state_zip[2].nil? cust.zip = city_state_zip[3] unless city_state_zip[3].nil? end cust.fax = row[4] unless row[4].nil? cust.phone = row[5] unless row[5].nil? cust.save! end end task :import_customer_prodlines => :environment do require 'csv' CSV.foreach('./lib/tasks/data/vendor_matrix.csv', :headers => true) do |row| cust = Customer.find_by_old_id(row[0]) unless row[0].nil? cpl = CustomerProductLine.new(:name => row[1]) unless row[1].nil? pl = ProductLine.find_by_old_id(row[2]) unless row[2].nil? unless pl.nil? || cust.nil? cpl.customer = cust cpl.product_line = pl cpl.save! end end end task :import_parts_from_sales => :environment do require 'csv' connection = ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :database => "abj_ruby_development", :username => "abj_ruby", :password => "AbjIsGr8") prod_lines = connection.connection.execute("SELECT old_id, id FROM product_lines").to_a pl_ids = Hash.new prod_lines.each do |pl| pl_ids[pl[0]] = pl[1] end cnt = 0 sql_start = "INSERT INTO parts_from_sales (product_line_id, part_num, description, created_at, updated_at) VALUES " sql = sql_start CSV.foreach('./lib/tasks/data/sales_history.csv', :headers => true) do |row| unless row["part_num"].nil? values = Array.new values << pl_ids[row["prod_line"].to_i].to_s values += row.to_a.map{|keyval| keyval[1] }.slice(2..3) # puts "values: " + values.to_s sql += ", " if cnt > 0 sql += " (" + values.map{|v| v.nil? ? "NULL" : ("'" + v + "'") }.join(", ") + ", NOW(), NOW())" cnt += 1 # break if cnt > 20 if cnt > 500 connection.connection.execute(sql) sql = sql_start cnt = 0 end end end # puts sql if cnt > 0 connection.connection.execute(sql) end end task :import_parts_from_prices => :environment do require 'csv' connection = ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :database => "abj_ruby_development", :username => "abj_ruby", :password => "AbjIsGr8") prod_lines = connection.connection.execute("SELECT old_id, id FROM product_lines").to_a pl_ids = Hash.new prod_lines.each do |pl| pl_ids[pl[0]] = pl[1] end cnt = 0 sql_start = "INSERT INTO parts_from_prices(part_num, product_line_id, price0, price1, price2, price3, price4, price5) VALUES " sql = sql_start CSV.foreach('./lib/tasks/data/prices.csv', :headers => true) do |row| unless row["part_num"].nil? values = Array.new values << row["part_num"] values << pl_ids[row["prod_line"].to_i].to_s values += row.to_a.map{|keyval| keyval[1] }.slice(2..7) sql += "," if cnt > 0 sql += " (" + values.map{|v| v.nil? ? "NULL" : ("'" + v + "'") }.join(", ") + ")" cnt += 1 if cnt > 500 connection.connection.execute(sql) sql = sql_start cnt = 0 end end end if cnt > 0 connection.connection.execute(sql) end end task :merge_parts => :environment do require 'csv' connection = ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :database => "abj_ruby_development", :username => "abj_ruby", :password => "AbjIsGr8") sql = "DELETE FROM parts" connection.connection.execute(sql) sql = "ALTER TABLE parts AUTO_INCREMENT = 1" connection.connection.execute(sql) sql = "INSERT INTO parts(product_line_id, part_num, description, " + "price0, price1, price2, price3, price4, price5, created_at, updated_at)" + "SELECT ps.product_line_id, ps.part_num, ps.description, pp.price0, pp.price1, pp.price2, " + "pp.price3, pp.price4, pp.price5, ps.created_at, ps.updated_at " + "FROM parts_from_sales AS ps LEFT JOIN " + "parts_from_prices AS pp ON pp.part_num = ps.part_num" connection.connection.execute(sql) end end
class TalenttoolsApi::Participant include Her::Model collection_path "/api/v1/projects" parse_root_in_json :participant include_root_in_json true use_api TalenttoolsApi.api custom_get :get_assessment_link, :get_assessment_status, :get_report_link class << self def create(project_id, params = {}) post "/api/v1/projects/#{project_id}/participants", params end def update(project_id, participant_id, params = {}) patch "/api/v1/projects/#{project_id}/participants/#{participant_id}", params end def get_assessment_link(project_id, participant_id) get "/api/v1/projects/#{project_id}/participants/#{participant_id}/get_assessment_link" end def get_assessment_status(project_id, participant_id) get "/api/v1/projects/#{project_id}/participants/#{participant_id}/get_assessment_status" end def get_report_link(project_id, participant_id, params={}) get "/api/v1/projects/#{project_id}/participants/#{participant_id}/get_report_link", params end end end
require "include" require "runit/cui/testrunner" # tests the customization of Log4r levels class TestCustom < TestCase def test_validation assert_exception(TypeError) { Configurator.custom_levels "lowercase" } assert_exception(TypeError) { Configurator.custom_levels "With space" } end def test_create assert_no_exception { Configurator.custom_levels "Foo", "Bar", "Baz" } assert_no_exception { Configurator.custom_levels } assert_no_exception { Configurator.custom_levels "Bogus", "Levels" } end def test_methods l = Logger.new 'custom1' assert_respond_to(:foo, l) assert_respond_to(:foo?, l) assert_respond_to(:bar, l) assert_respond_to(:bar?, l) assert_respond_to(:baz, l) assert_respond_to(:baz?, l) assert_no_exception(NameError) { Bar } assert_no_exception(NameError) { Baz } assert_no_exception(NameError) { Foo } end end CUI::TestRunner.run(TestCustom.new("test_validation")) CUI::TestRunner.run(TestCustom.new("test_create")) CUI::TestRunner.run(TestCustom.new("test_methods"))
class CreateReads < ActiveRecord::Migration[6.0] def change create_table :reads do |t| t.date :data_leitura t.integer :qtd_lido t.timestamps end end end
class OrderItemsController < ApplicationController before_action :set_order_item, only: [:destroy, :increase_quantity, :decrease_quantity] before_action :authenticate_user! def create order_item = current_order.order_items.find_by(product_id: params[:product_id]) if order_item.present? order_item.update(quantity: order_item.quantity + 1) redirect_to order_path(current_order) else current_order.order_items.create(product_id: params[:product_id]) redirect_to order_path(current_order) end end def increase_quantity if @order_item.update(quantity: @order_item.quantity + 1) render "order_items/increase_quantity" else redirect_to order_path(current_order) end end def decrease_quantity if @order_item.quantity > 0 if @order_item.update(quantity: @order_item.quantity - 1) render "order_items/increase_quantity" else redirect_to order_path(current_order) end else @order_item.quantity = 0 end end def destroy if @order_item.destroy render "destroy" else redirect_to order_path(current_order) end end private def set_order_item @order_item = OrderItem.find(params[:id]) end end
require 'endpointer/errors/cached_item_not_found_error' require 'endpointer/errors/invalid_cache_dir_error' require 'endpointer/cache_container' require 'endpointer/cache_key_resolver' require 'endpointer/response_presenter' require 'yaml' module Endpointer class Cacher def initialize(path) initialize_path(path) end def get(resource, request_body) cache_key = get_cache_key(resource, request_body) cache_container = retrieve_cache_container(cache_key) raise Endpointer::Errors::CachedItemNotFoundError unless cache_container.resource == resource present_response(resource, request_body, cache_container) end def set(resource, request_body, response) cache_container = create_cache_container(resource, response) File.write(File.join(@path, get_cache_key(resource, request_body)), YAML.dump(cache_container)) end def invalidate FileUtils.remove_entry(@path) initialize_path(@path) end private def create_cache_container(resource, response) Endpointer::CacheContainer.new(resource, response, Time.now.utc) end def retrieve_cache_container(cache_key) begin YAML.load(File.read(File.join(@path, cache_key))) rescue Errno::ENOENT => e raise Endpointer::Errors::CachedItemNotFoundError, e.message end end def get_cache_key(resource, request_body) Endpointer::CacheKeyResolver.new.get_key(resource, request_body) end def initialize_path(path) begin @path = path Dir.mkdir(@path) unless File.exist?(@path) rescue Errno::ENOENT => e raise Endpointer::Errors::InvalidCacheDirError, e.message end end def present_response(resource, request_body, cache_container) Endpointer::ResponsePresenter.new.present( status: cache_container.response.code, body: cache_container.response.body, headers: cache_container.response.headers, request_body: request_body, resource: resource ) end end end
require 'rails_helper' RSpec.describe 'the competition index page' do # User Story 1 - Competition Index # As a user # When I visit the competion index # Then I see the names of all competitions # Each competition name links to its show page it 'shows the name of all the competitions' do comp1 = Competition.create!(name: 'Chuck Stuff', location: 'Denver', sport: 'Axe Throwing') comp2 = Competition.create!(name: 'Rowin for Freedom', location: 'Fort Collins', sport: 'Rowing') comp3 = Competition.create!(name: 'Baseball Stuff', location: 'Thornton', sport: 'Baseball') visit '/competitions' expect(page).to have_content(comp1.name) expect(page).to have_content(comp2.name) expect(page).to have_content(comp3.name) end it 'has a link to each competitions show page' do comp1 = Competition.create!(name: 'Chuck Stuff', location: 'Denver', sport: 'Axe Throwing') comp2 = Competition.create!(name: 'Rowin for Freedom', location: 'Fort Collins', sport: 'Rowing') comp3 = Competition.create!(name: 'Baseball Stuff', location: 'Thornton', sport: 'Baseball') visit '/competitions' expect(page).to have_link(comp1.name) expect(page).to have_link(comp2.name) expect(page).to have_link(comp3.name) end end
require 'app/models/brewery' require 'app/presenters/paginated_presenter' require 'app/presenters/location_presenter' require 'app/presenters/social_media_account_presenter' class BreweryPresenter < Jsonite properties :name, :alternate_names, :description, :website, :organic, :established property(:beers) { beers_count } property(:events) { events_count } property(:guilds) { guilds_count } embed :locations, with: LocationPresenter embed :social_media_accounts, with: SocialMediaAccountPresenter link { "/breweries/#{self.to_param}" } link(:beers) { "/breweries/#{self.to_param}/beers" } link(:events) { "/breweries/#{self.to_param}/events" } link(:guilds) { "/breweries/#{self.to_param}/guilds" } link :image, templated: true, size: %w[icon medium large] do |context| throw :ignore unless image_id.present? "https://s3.amazonaws.com/brewerydbapi/brewery/#{brewerydb_id}/upload_#{image_id}-{size}.png" end end class BreweriesPresenter < PaginatedPresenter property(:breweries, with: BreweryPresenter) { to_a } end
class Player attr_accessor :nom, :valeur def initialize(nom= nil, valeur= nil) #S'il n'y a pas de nom de base, on demande au joueur de rentrer un nom if nom == nil puts "Quel est votre nom de guerre ?" nom = gets.chomp end @nom = nom #S'il n'y a pas de valeur de base, on demande au joueur de choisir entre la valeur X ou la valeur O if valeur == nil puts "Choisissez entre X ou O, avec quoi préfèrez-vous jouer ?" prise = gets.chomp while prise != "X" && prise != "O" #Si l'utilisateur choisi une autre valeur que X et O, on lui retourne un message d'erreur puts "Non non non ! Tu dois choisir entre X ou O" prise = gets.chomp end valeur = prise end @valeur = valeur end end
json.array!(@money_checks) do |money_check| json.extract! money_check, :id json.url money_check_url(money_check, format: :json) end
class AwardQuery def self.all relation.order(:title) end def self.find(id) relation.friendly.find(id) end def self.relation Award.all end end
class Review < ActiveRecord::Base validates :rental, :review, :review_text, presence: true belongs_to :rental has_one :listing, through: :rental has_one :reviewer, through: :rental, source: :lessee end
class ChatMailer < ApplicationMailer default from: "mogushare.net@gmail.com" def send_mail_about_new_chat(user, group, current_user) @user = user @current_user = current_user @group = group mail( subject: "【もぐシェア】メッセージが届きました", to: @user.email ) end end
# encoding: UTF-8 class Collecte # = main = # # Méthode principale pour procéder au parsing du dossier de # collecte. # # NOTES # * En fin de parsing, on sauve toutes les données # dans le fichier data/film.msh qui contient tout. # # +options+ # :debug Si true, on ouvre le fichier journal # à la fin du parsing. # Noter qu'il sera de toutes façon toujours # ouvert lorsqu'une erreur survient. def parse options = nil options ||= Hash.new Collecte.load_module 'parsing' parse_all # On sauve tout film.save # Si le fichier de données (marshal ou pstore) n'a pas été # produit, il faut signaler une erreur check_fichier_data_film rescue Exception => e log 'à la fin de Collecte#parse', fatal_error: e ensure if (errors != nil && errors.count > 0) || options[:debug] Log.build_and_open_html_file end end # En fin de parsing, on vérifie que le fichier data a # bien été produit. On raise dans le cas contraire def check_fichier_data_film fichier_final = Film::MODE_DATA_SAVE == :pstore ? film.pstore_file : film.marshal_file File.exist?(fichier_final) || raise("Le fichier data `#{fichier_final}` n’a pas été produit. La collecte n’a pas abouti.") end end
class User < ApplicationRecord has_many :posts has_many :images, through: :posts has_many :likes has_many :liked_images, through: :likes, source: :images has_many :comments def images_and_comments liked_images.includes(:comments) end end
module SnakeCase module Bruteforce module_function def path_count(m, n) (0..(2**(m+n))).count { |x| x.to_s(2).chars.count("1") == n } end end module Factorial module_function def path_count(m, n) (m+n).downto(m+1).reduce(:*) / n.downto(1).reduce(:*) end end module Recursive module_function def path_count(m, n) return 1 if m == 0 || n == 0 path_count(m-1, n) + path_count(m, n-1) end end module Iterative module_function def path_count(h, w) row = [1] * (w+1) h.times do row = row.reduce([]) { |acc, p| acc << (p + acc.last.to_i) } end row.last end end module Enumerative module_function def path_count(m, n) grid(m, n).drop(m-1).last.last end def grid(h, w) return to_enum(:grid, h, w) unless block_given? row = [1] * (w+1) yield row h.times do row = row.reduce([]) { |acc, p| acc << (p + acc.last.to_i) } yield row end end end end if __FILE__ == $0 require "benchmark/ips" Benchmark.ips do |x| x.report("snake case factorial") do SnakeCase::Factorial.path_count(10, 10) end x.report("snake case brute force") do SnakeCase::Bruteforce.path_count(10, 10) end x.report("snake case recursive") do SnakeCase::Recursive.path_count(10, 10) end x.report("snake case iterative") do SnakeCase::Iterative.path_count(10, 10) end x.report("snake case enumerative") do SnakeCase::Enumerative.path_count(10, 10) end x.compare! end # $ ruby code/snake_case.rb # Calculating ------------------------------------- # snake case factorial 34.658k i/100ms # snake case brute force # 1.000 i/100ms # snake case recursive 5.000 i/100ms # snake case iterative 4.920k i/100ms # snake case enumerative # 4.109k i/100ms # ------------------------------------------------- # snake case factorial 456.100k (± 7.8%) i/s - 2.287M # snake case brute force # 0.325 (± 0.0%) i/s - 2.000 in 6.161730s # snake case recursive 50.084 (±10.0%) i/s - 250.000 # snake case iterative 52.616k (± 5.3%) i/s - 265.680k # snake case enumerative # 42.875k (± 7.1%) i/s - 213.668k # # Comparison: # snake case factorial: 456100.0 i/s # snake case iterative: 52615.9 i/s - 8.67x slower # snake case enumerative: 42874.6 i/s - 10.64x slower # snake case recursive: 50.1 i/s - 9106.72x slower # snake case brute force: 0.3 i/s - 1405090.92x slower end
class MasterMindGame attr_accessor :colors_to_guess, :user_guesses, :total_colors, :total_positions, :start_time, :end_time def initialize(colors_to_guess=secret_colors_generator) @colors_to_guess = colors_to_guess @total_colors = total_colors @total_positions = total_positions @user_guesses = 0 @start_time = Time.now @end_time = Time.now end def secret_colors_generator ("rybg" * 4).chars.shuffle.take(4).join("") end def cheat puts @colors_to_guess.upcase end def elapsed_time (@end_time - @start_time) end end
#!/bin/env ruby # encoding: utf-8 module Admin::RightsHelper # called by controllers on CRUD actions. Perform a redirect_to if unnecessary right # on index actions def index_right(element) if @ownerships_all.any? @elements = element.page(params[:page]).per_page(10) else if @ownerships_on_ownership.any? @elements = element.where('user_id = ?', current_user.id).page(params[:page]).per_page(10) end if @ownerships_on_entry.any? if @elements.nil? @elements = element.where(id: @ownerships_on_entry).page(params[:page]).per_page(10) else @elements = (@elements + element.where(id: @ownerships_on_entry)).paginate(per_page: 10) end end end redirect_to(root_path, notice: "Vous n'avez pas les droits nécessaires pour éditer l'élément.") if @elements.nil? end # on update, edit and delete actions def modify_right(element) if @ownerships_all.any? @element = true elsif @ownerships_on_ownership.any? @element = (element.where('user_id = ? AND id = ?', current_user.id, params[:id]).first.nil?) ? false : true elsif @ownerships_on_entry.any? @ownerships_on_entry.each do |entry| if entry.id == params[:id] @element = true end end end redirect_to(root_path, notice: "Vous n'avez pas les droits nécessaires pour modifier l'élément.") unless @element end # buttons in the view def create? if signed_in? @ownerships ||= Ownership.where('user_id = ? AND element_id = ? AND right_create = ?', current_user.id, Element.find_by_name('admin/' + params[:controller]).id, true ) @ownerships.any? end end def edit?(element) if signed_in? @element_id ||= Element.find_by_name('admin/' + params[:controller]).id @ownerships_all ||= Ownership.where('user_id = ? AND element_id = ? AND ownership_type_id = ? AND right_update = ?', current_user.id, @element_id, OwnershipType.find_by_name('all_entries').id, true ) @ownerships_on_entry ||= Ownership.where('user_id = ? AND element_id = ? AND ownership_type_id = ? AND right_update = ? AND id_element = ?', current_user.id, @element_id, OwnershipType.find_by_name('on_entry').id, true, element.id) @ownerships_on_ownership = Ownership.where('user_id = ? AND element_id = ? AND ownership_type_id = ? AND right_update = ?', current_user.id, @element_id, OwnershipType.find_by_name('on_ownership').id, true ) @ownerships_all.any? || @ownerships_on_entry.any? || (element.user_id == current_user.id if @ownerships_on_ownership.any? ) end end end
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: 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. # # This example creates an HTML5 display creative. # # Requires an HTML5 asset, backup image asset, and an advertiser ID as input. # To get an advertiser ID, run get_advertisers.rb. require_relative '../creative_asset_utils' require_relative '../dfareporting_utils' def create_html5_banner_creative(profile_id, advertiser_id, size_id, path_to_html5_asset_file, path_to_backup_image_file) # Authenticate and initialize API service. service = DfareportingUtils.initialize_service util = CreativeAssetUtils.new(service, profile_id) # Locate an advertiser landing page to use as a default. default_landing_page = get_advertiser_landing_page(service, profile_id, advertiser_id) # Upload the HTML5 asset. html5_asset_id = util.upload_asset(advertiser_id, path_to_html5_asset_file, 'HTML').asset_identifier # Upload the backup image asset. backup_image_asset_id = util.upload_asset(advertiser_id, path_to_backup_image_file, 'HTML_IMAGE').asset_identifier # Construct the creative structure. creative = DfareportingUtils::API_NAMESPACE::Creative.new( advertiser_id: advertiser_id, backup_image_click_through_url: DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( landing_page_id: default_landing_page.id ), backup_image_reporting_label: 'backup', backup_image_target_window: DfareportingUtils::API_NAMESPACE::TargetWindow.new( target_window_option: 'NEW_WINDOW' ), click_tags: [ DfareportingUtils::API_NAMESPACE::ClickTag.new( event_name: 'exit', name: 'click_tag', click_through_url: DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new( landing_page_id: default_landing_page.id ) ) ], creative_assets: [ DfareportingUtils::API_NAMESPACE::CreativeAsset.new( asset_identifier: html5_asset_id, role: 'PRIMARY' ), DfareportingUtils::API_NAMESPACE::CreativeAsset.new( asset_identifier: backup_image_asset_id, role: 'BACKUP_IMAGE' ) ], name: 'Example HTML5 display creative', size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id), type: 'DISPLAY' ) # Insert the creative. result = service.insert_creative(profile_id, creative) puts format('Created HTML5 display creative with ID %d and name "%s".', result.id, result.name) end def get_advertiser_landing_page(service, profile_id, advertiser_id) # Retrieve a sigle landing page from the specified advertiser. result = service.list_advertiser_landing_pages(profile_id, advertiser_ids: [advertiser_id], max_results: 1) if result.landing_pages.none? abort format('No landing pages for for advertiser with ID %d', advertiser_id) end result.landing_pages[0] end if $PROGRAM_NAME == __FILE__ # Retrieve command line arguments. args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :advertiser_id, :size_id, :path_to_html5_asset_file, :path_to_backup_image_file) create_html5_banner_creative(args[:profile_id], args[:advertiser_id], args[:size_id], args[:path_to_html5_asset_file], args[:path_to_backup_image_file]) end
#puppet-gcloudsdk/spec/acceptance/standard_spec.rb require 'spec_helper_acceptance' describe 'gclogging class' do context 'default parameters' do # Using puppet_apply as a helper it 'should work with no errors based on the example' do pp = <<-EOS class { 'gclogging':} EOS # Run it twice and test for idempotency expect(apply_manifest(pp).exit_code).to_not eq(1) expect(apply_manifest(pp).exit_code).to eq(0) end it 'should place the file /tmp/install_logging.sh' do # Check whether the file exists File.exist?('~/tmp/install_logging.sh') end describe file('/tmp/install_logging.sh') do its(:content) { should match /fluentd_log/ } end describe command('logger --version /') do its(:stdout) { should contain /util-linux/ } end end end
# -*- mode: ruby -*- # vi: set ft=ruby : require 'getoptlong' VAGRANTFILE_API_VERSION = "2" MANAGERS = 1 workers = <%= workers %> opts = GetoptLong.new( # Native Vagrant options [ '--force', '-f', GetoptLong::NO_ARGUMENT ], [ '--provision', '-p', GetoptLong::NO_ARGUMENT ], [ '--provision-with', GetoptLong::NO_ARGUMENT ], [ '--provider', GetoptLong::OPTIONAL_ARGUMENT ], [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--check', GetoptLong::NO_ARGUMENT ], [ '--logout', GetoptLong::NO_ARGUMENT ], [ '--token', GetoptLong::NO_ARGUMENT ], [ '--disable-http', GetoptLong::NO_ARGUMENT ], [ '--http', GetoptLong::NO_ARGUMENT ], [ '--https', GetoptLong::NO_ARGUMENT ], [ '--ssh-no-password', GetoptLong::NO_ARGUMENT ], [ '--ssh', GetoptLong::NO_ARGUMENT ], [ '--ssh-port', GetoptLong::NO_ARGUMENT ], [ '--ssh-once', GetoptLong::NO_ARGUMENT ], [ '--host', GetoptLong::NO_ARGUMENT ], [ '--entry-point', GetoptLong::NO_ARGUMENT ], [ '--plugin-source', GetoptLong::NO_ARGUMENT ], [ '--plugin-version', GetoptLong::NO_ARGUMENT ], [ '--debug', GetoptLong::NO_ARGUMENT ], # custom options ['--caas-mode', GetoptLong::OPTIONAL_ARGUMENT], ['--workers', GetoptLong::OPTIONAL_ARGUMENT] ) caasModeParameter='<%= caasMode %>' opts.each do |opt, arg| case opt when '--caas-mode' caasModeParameter=arg when '--workers' workers=Integer(arg) end end Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "<% if (os === "ubuntu") { %>bento/ubuntu-16.04<% } %><% if (os === "centos") { %>tsihosting/centos7<% } %>" # config.vm.network :forwarded_port, host: 8082, guest: 8082 # config.vm.network :forwarded_port, host: 9000, guest: 9000 # config.vm.network :forwarded_port, host: 9999, guest: 9999 config.vm.synced_folder '.', '/vagrant', disabled: true config.vm.provider 'virtualbox' do |v| v.linked_clone = true if Vagrant::VERSION =~ /^1.8/ end config.ssh.insert_key = false (1..MANAGERS).each do |manager_id| config.vm.define "<%= appName %>-manager#{manager_id}" do |manager| manager.vm.hostname = "<%= appName %>-manager#{manager_id}" manager.ssh.forward_agent = true manager.ssh.insert_key = true manager.vm.provision :shell, :path => "scripts/setup_ubuntu.sh" manager.vm.network "private_network", ip: "<%= defaultIp %>.#{20+manager_id}" manager.vm.network :forwarded_port, guest: 22, host: "122#{20+manager_id}", id: 'ssh' manager.vm.network :forwarded_port, host: 8082, guest: 8082 manager.vm.network :forwarded_port, host: 9000, guest: 9000 manager.vm.network :forwarded_port, host: 9999, guest: 9999 manager.vm.synced_folder '.', '/vagrant', disabled: true manager.vm.provider "virtualbox" do |v| v.memory = <%= memoryManager %> v.cpus = 2 v.name = "<%= appName %>-manager#{manager_id}" end end end (1..workers).each do |worker_id| config.vm.define "<%= appName %>-worker#{worker_id}" do |worker| worker.vm.hostname = "<%= appName %>-worker#{worker_id}" worker.ssh.forward_agent = true worker.ssh.insert_key = true worker.vm.provision :shell, :path => "scripts/setup_ubuntu.sh" worker.vm.network "private_network", ip: "<%= defaultIp %>.#{30+worker_id}" worker.vm.network :forwarded_port, guest: 22, host: "122#{30+worker_id}", id: 'ssh' worker.vm.synced_folder '.', '/vagrant', disabled: true worker.vm.provider "virtualbox" do |v| v.memory = <%= memoryWorkers %> v.name = "<%= appName %>-worker#{worker_id}" end # Only execute once the Ansible provisioner, # when all the workers are up and ready. if worker_id == workers if caasModeParameter == "swarm" worker.vm.provision "base", type: "ansible" do |ansible| ansible.playbook = "ansible/swarm/<%= appName %>-base-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "images", type: "ansible" do |ansible| ansible.playbook = "ansible/images/<%= appName %>-images-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "swarm", type: "ansible" do |ansible| ansible.playbook = "ansible/swarm/<%= appName %>-swarm-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "services", type: "ansible" do |ansible| ansible.playbook = "ansible/swarm/<%= appName %>-services-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "registry", type: "ansible" do |ansible| ansible.playbook = "ansible/images/<%= appName %>-registry-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end end if caasModeParameter == "k8s" worker.vm.provision "base", type: "ansible" do |ansible| ansible.playbook = "ansible/k8s/<%= appName %>-base-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "images", type: "ansible" do |ansible| ansible.playbook = "ansible/images/<%= appName %>-images-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "k8s", type: "ansible" do |ansible| ansible.playbook = "ansible/k8s/<%= appName %>-k8s-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end worker.vm.provision "registry", type: "ansible" do |ansible| ansible.playbook = "ansible/images/<%= appName %>-registry-playbook.yml" ansible.raw_arguments = ["--inventory=ansible/<%= appName %>-hosts"] ansible.verbose = "vv" ansible.limit = "all" end end end end end end
class ListSerializer < BaseSerializer attributes :name, :permissions has_many :items end
module Mastermind class Resource module Server class EC2 < Resource provider Mastermind::Provider::Server::EC2 actions :create, :destroy, :stop, :start, :restart, :reboot attribute :image_id, :type => String attribute :key_name, :type => String attribute :ami_launch_index, :type => Integer attribute :availability_zone, :type => String #, :default => 'us-east-1a' attribute :block_device_mapping, :type => Object, :default => [] attribute :client_token, :type => String attribute :dns_name, :type => String attribute :groups, :type => Object, :default => [ 'default' ] attribute :flavor_id, :type => String attribute :iam_instance_profile, :type => Object, :default => {} attribute :instance_id, :type => String attribute :kernel_id, :type => String attribute :created_at, :type => DateTime attribute :monitoring, :type => Boolean, :default => false attribute :network_interface, :type => Object, :default => [] attribute :placement_group, :type => String attribute :platform, :type => String attribute :product_codes, :type => Object, :default => [] attribute :private_dns_name, :type => String attribute :private_ip_address, :type => String attribute :public_ip_address, :type => String attribute :ramdisk_id, :type => String attribute :reason, :type => String attribute :region, :type => String #, :default => 'us-east-1' attribute :root_device_name, :type => String attribute :root_device_type, :type => String attribute :security_group_ids, :type => Object, :default => [] attribute :state, :type => String attribute :state_reason, :type => Object attribute :subnet_id, :type => String attribute :tenancy, :type => String attribute :tags, :type => Object attribute :user_data, :type => String attribute :vpc_id, :type => String alias_method :id, :instance_id alias_method :id=, :instance_id= validates! :image_id, :flavor_id, :availability_zone, :region, :key_name, :presence => true, :on => :create [ :destroy, :stop, :start, :restart, :reboot ].each do |act| validates! :instance_id, :region, :presence => true, :on => act end validates! :image_id, :format => { with: /^ami-[a-f0-9]{8}$/ }, :allow_blank => true validates! :flavor_id, inclusion: { in: Mastermind::Mixins::AWS::FLAVORS }, :allow_blank => true validates! :availability_zone, :if => lambda { |s| s.region? && Mastermind::Mixins::AWS::ZONES[s.region] }, :inclusion => { in: lambda { |s| Mastermind::Mixins::AWS::ZONES[s.region] } }, :allow_blank => true validates! :region, :inclusion => { in: Mastermind::Mixins::AWS::ZONES.keys }, :allow_blank => true validates! :id, :instance_id, :format => { with: /^i-[a-f0-9]{8}$/ }, :allow_blank => true end end end end
class MerchantsController < ApplicationController before_action :require_login, except: [:login] def login auth_hash = request.env["omniauth.auth"] @merchant = Merchant.find_by(uid: auth_hash[:uid], provider: "github") if @merchant # merchant was found in the database flash[:success] = "Logged in as returning merchant #{@merchant.name}" else # merchant doesn't match anything in the DB # Attempt to create a new merchant merchant = Merchant.build_from_github(auth_hash) if merchant.save flash[:success] = "Logged in as new merchant #{merchant.name}" @merchant = Merchant.last else flash[:error] = "Could not create new merchant account!" flash[:error_msgs] = merchant.errors.full_messages return redirect_to root_path end end # If we get here, we have a valid merchant instance session[:merchant_id] = @merchant.id session[:merchant_name] = @merchant.name return redirect_to root_path end def update if @merchant.update(merchant_params) flash[:success] = "Information was updated" if @merchant.name != session[:merchant_name] # I want the nav buttons to reflect the new name session[:merchant_name] = @merchant.name end redirect_to merchant_path(@merchant.id) return else flash.now[:error] = "Unable to update" flash.now[:error_msgs] = @merchant.errors.full_messages render action: "edit" return end end def show end def logout session[:merchant_id] = nil session[:merchant_name] = nil flash[:success] = "Successfully logged out!" return redirect_to root_path end private def current_merchant @merchant ||= Merchant.find(session[:merchant_id]) if session[:merchant_id] end def merchant_params return params.require(:merchant).permit(:name, :email) end def require_login if current_merchant.nil? flash[:error] = "You must be logged in to view this section" return redirect_to root_path end end end
class UnitsController < ApplicationController before_action :get_unit, only: [:update, :edit, :show, :destroy] before_action :get_race def index @units = @races.units end def new @unit = @race.units.new render "form" end def create @unit = @race.units.new(unit_params) if @unit.save redirect_to race_units_path(@race) else render "form" end end def edit render "form" end def update if @unit.update(unit_params) redirect_to race_units_path else render "form" end end def show end def destroy @unit.destroy redirect_to race_units_path end private def unit_params params.require(:unit).permit(:name, :speed, :melee, :range, :defense, :attack, :nerve, :point, :race_id) end def get_unit @unit = Unit.find(params[:id]) end def get_race @race = Race.find(params[:race_id]) end end t.string "name" t.string "type" t.string "speed" t.string "melee" t.string "range" t.string "defense" t.string "attack" t.string "nerve" t.string "point" t.bigint "race_id"
require "spec_helper" describe LaunchersController do describe "routing" do it "routes to #index" do get("/launchers").should route_to("launchers#index") end it "routes to #new" do get("/launchers/new").should route_to("launchers#new") end it "routes to #show" do get("/launchers/1").should route_to("launchers#show", :id => "1") end it "routes to #edit" do get("/launchers/1/edit").should route_to("launchers#edit", :id => "1") end it "routes to #create" do post("/launchers").should route_to("launchers#create") end it "routes to #update" do put("/launchers/1").should route_to("launchers#update", :id => "1") end it "routes to #destroy" do delete("/launchers/1").should route_to("launchers#destroy", :id => "1") end end end
require 'delegate' module HamlUserTags module Helpers # Same as Haml::Buffer.attributes, but returns the hash instead of writing # the attributes to the buffer. def self.attributes_hash(class_id, obj_ref, *attributes_hashes) attributes = class_id attributes_hashes.each do |old| Haml::Buffer.merge_attrs(attributes, Hash[old.map {|k, v| [k.to_s, v]}]) end Haml::Buffer.merge_attrs(attributes, Haml::Buffer.new.parse_object_ref(obj_ref)) if obj_ref attributes end def define_tag name, &tag unless name =~ HamlUserTags::TAG_NAME_REGEX raise "define_tag: #{name.inspect} is not a valid user tag name. It must match #{HamlUserTags::TAG_NAME_REGEX}" end func = proc do |attributes = {}, &contents| @haml_buffer ||= Haml::Buffer.new(nil, Haml::Options.defaults) tag.binding.eval("proc { |v| _hamlout = v }").call @haml_buffer # Use a proxy String class that will only evaluate its contents once # it is referenced. This make the behavior similar to how "yield" # would be in a ruby helper. content_getter = LazyContents.new { capture_haml(&contents) || "" } if contents capture_haml { instance_exec attributes, content_getter, &tag } end define_singleton_method name, &func if self.is_a?(Module) define_method name, &func end end def include_tags path source = File.read path HamlUserTags::Engine.new(source, :filename => path).extend_object self nil end end class LazyContents < DelegateClass(String) def initialize(&generator) @generator = generator end def __getobj__ unless @results @results, @generator = @generator.call, nil end @results end end end module Haml module Helpers include HamlUserTags::Helpers end end
describe DatabaseConnection do describe '.setup' do it 'establishes a connection to the database using PG' do expect(PG).to receive(:connect).with(dbname: 'bookmarks_manager_test') DatabaseConnection.setup('bookmarks_manager_test') end end describe '.query' do it "executes the query passed in using PG's exec method" do connection = DatabaseConnection.setup('bookmarks_manager_test') expect(connection).to receive(:exec).with("SELECT * FROM bookmarks;") DatabaseConnection.query("SELECT * FROM bookmarks;") end end end
class CreateVacations < ActiveRecord::Migration[6.1] def change create_table :vacations do |t| t.integer :traveler_id t.integer :country_id t.boolean :favorite t.timestamps 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' require 'csv' require 'activerecord-import/base' require 'activerecord-import/active_record/adapters/postgresql_adapter' Faker::Config.locale = 'fr' User.destroy_all City.destroy_all Gossip.destroy_all Tag.destroy_all PrivateMessage.destroy_all JoinTableMessageRecipient.destroy_all Comment.destroy_all Like.destroy_all def pick_quote quote_reservoir = [ Faker::TvShows::AquaTeenHungerForce, Faker::TvShows::BigBangTheory, Faker::TvShows::BojackHorseman, Faker::TvShows::Buffy, Faker::TvShows::DrWho, Faker::TvShows::DumbAndDumber, Faker::TvShows::FamilyGuy, Faker::TvShows::FinalSpace, Faker::TvShows::Friends, Faker::TvShows::GameOfThrones, Faker::TvShows::HeyArnold, Faker::TvShows::HowIMetYourMother, Faker::TvShows::MichaelScott, Faker::TvShows::NewGirl, Faker::TvShows::RickAndMorty, Faker::TvShows::RuPaul, Faker::TvShows::Seinfeld, Faker::TvShows::SiliconValley, Faker::TvShows::Simpsons, Faker::TvShows::SouthPark, Faker::TvShows::Stargate, Faker::TvShows::StrangerThings, Faker::TvShows::Suits, Faker::TvShows::TheExpanse, Faker::TvShows::TheFreshPrinceOfBelAir, Faker::TvShows::TheITCrowd, Faker::TvShows::TwinPeaks, Faker::TvShows::VentureBros, Faker::Movie, Faker::Movies::BackToTheFuture, Faker::Movies::Departed, Faker::Movies::Ghostbusters, Faker::Movies::HarryPotter, Faker::Movies::HitchhikersGuideToTheGalaxy, Faker::Movies::Hobbit, Faker::Movies::Lebowski, Faker::Movies::PrincessBride, Faker::Movies::StarWars, Faker::Movies::VForVendetta ] quote_reservoir.sample.quote end def pick_recipient (private_message) user = User.all.sample user == private_message.sender ? pick_recipient(private_message) : user end cities = [] CSV.foreach('./db/insee.csv', headers: true) do |row| city = row.to_h cities << City.new( name: city['Commune'].split.map { |w| w.capitalize }.join(' '), zip_code: city['Codepos'] ) end City.import cities, recursive: true 20.times do User.create( first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, description: pick_quote, email: Faker::Internet.email, age: rand(18..80), city: City.all.sample, password: Faker::Internet.password ) end 10.times do Tag.create( title: Faker::Space.star ) end 50.times do gossip = Gossip.create( title: Faker::BossaNova.song, content: pick_quote, user: User.all.sample ) JoinTableGossipTag.create( gossip: gossip, tag: Tag.all.sample ) end 20.times do JoinTableGossipTag.create( gossip: Gossip.all.sample, tag: Tag.all.sample ) end 50.times do pm = PrivateMessage.create( content: pick_quote, sender: User.all.sample ) JoinTableMessageRecipient.create( private_message: pm, recipient: pick_recipient(pm) ) end 20.times do private_message = PrivateMessage.all[rand(0..49)] recipient = pick_recipient(private_message) while private_message.recipients.include?(recipient) recipient = pick_recipient(private_message) end JoinTableMessageRecipient.create( private_message: private_message, recipient: recipient ) end 40.times do Comment.create( commentable: Gossip.all.sample, user: User.all.sample, content: pick_quote ) end 60.times do if rand(0..1) == 0 likeable = Comment.all.sample else likeable = Gossip.all.sample end Like.create( user: User.all.sample, likeable: likeable ) end 40.times do if rand(0..1) == 0 commentable = Comment.all.sample else commentable = Gossip.all.sample end Comment.create( commentable: commentable, user: User.all.sample, content: pick_quote ) end
module PathHelper { root: '/', adverts: '/adverts', packages: '/packages', publishers: '/publishers', influencers: '/influencers', messages: '/messages', requests: '/requests' }.each do |name, path| define_method("#{name}_path") do |searches = nil| searches = CGI.unescape(searches.to_query) if searches result_path = ['/app', path] result_path << ['?', searches] if searches result_path.join end end def login_path '/login' end end
class State < ActiveRecord::Base belongs_to :country has_many :cities validates :name, :presence=>true end
class BuildHistory < ActiveRecord::Base belongs_to :scenario include Steppable after_create :start_test enum result: { pending: 0, passed: 1, failed: 2, error: 3 } def started_at_string return nil unless self.started_at self.started_at.to_s(:datetime) end def finished_at_string return nil unless self.finished_at self.finished_at.to_s(:datetime) end def build_path Pathname(STORE_BASE_DIR) / "build_histories/#{id}" end def screenshot_path build_path / 'screenshots' end def screenshot_path_for(step_no) screenshot_path / "img_#{step_no}.png" end def feature_path build_path / "features/scenario.feature" end def started? started_at.present? end def finished? finished_at.present? end def result_string I18n.t("text.build_history.results.#{result}") end def populate_steps! scenario.steps.each do |s| steps.build(s.attributes.slice('step_no', 'command', 'target', 'value', 'encrypted_value', 'targets', 'raw_targets', 'comment')) end save! end def command cmd = %w(bundle exec cucumber) env = %W( SCREENSHOT_DIR=#{screenshot_path} APP_HOST=#{scenario.app_host} APP_PORT=#{scenario.app_port} ) if SystemSetting.first && SystemSetting.first.selenium_host.present? env += %W( DEVICE=#{self.device} REMOTE=#{SystemSetting.first.selenium_host} ) else env += %w( DEVICE=headless_chrome ) end args = %W( --format json --out #{build_result_path} --guess --no-multiline --no-snippets --quiet ) cmd + env + args + [feature_path.to_s] end def step_status(step_no) step_result(step_no).dig('status') end def step_failed?(step_no) step_status(step_no) == 'failed' end def step_skipped?(step_no) step_status(step_no) == 'skipped' end def error_messages @error_messages ||= begin build_result&.dig(0, 'elements', 0, 'before').to_a.map do |hash| hash['result']['error_message'] end.compact end end def step_message(step_no) case step_status(step_no) when 'failed' step_result(step_no)['error_message'] end end class << self def build_sequence_code(branches) branches.first.build_sequence_code end def started_at_string(branches) return nil if branches.map(&:started_at_string).include?(nil) branches.map(&:started_at_string).min end def finished_at_string(branches) return nil if branches.map(&:finished_at_string).include?(nil) branches.map(&:finished_at_string).max end def all_finished?(branches) return false if branches.map(&:finished?).include?(false) true end def result_string(branches) results = branches.map(&:result) if results.include?('error') return I18n.t("text.build_history.results.error") end if results.include?('failed') return I18n.t("text.build_history.results.failed") end if results.include?('pending') return I18n.t("text.build_history.results.pending") end I18n.t("text.build_history.results.passed") end def processing_time(branches) branches.map(&:finished_at).max - branches.map(&:started_at).min end end def update_step_processing_time steps.each do |step| duration = step_result(step.step_no)['duration'] || 0 processing_time = (duration / 1_000_000_000.0).round(2) step.update(processing_time: processing_time) end end private def build_result_path build_path / 'result.json' end def build_result @build_result ||= begin if build_result_path.exist? data = build_result_path.read data.blank? ? nil : ActiveSupport::JSON.decode(data) end end end def step_result(step_no) build_result&.dig(0, 'elements', 0, 'steps', step_no.to_i - 1, 'result') || {} end def start_test JobUtils.add_job(RunScenarioJob, :project_id => scenario.project_id, :scenario_id => scenario.id, :build_history_id => id) end end
# frozen_string_literal: true module Dmarcurator VERSION = "0.1.1" end
Given /^I've started to create a work "([^"]*)"$/ do |arg1| $title = arg1 $content = "This is my draft." @site.create_draft_flow(:rating => "General Audiences",:fandom => "Supernatural RPF",:title => $title,:content => $content) end Then /^I should be taken to the "([^"]*)" page$/ do |arg1| @site.header.header.text.include?(arg1) end Then /^the option "([^"]*)"$/ do |arg1| $arg1 = arg1 @site.header.link.should be_visible end Then /^I should see my draft with a Title of "([^"]*)"$/ do |arg1| @site.header.works_blurb.text.should include(arg1) end Then /^I should be taken to the new works form$/ do @site.works_new_page.new_form.should exist end Then /^I should not see my draft with a Title of "([^"]*)"$/ do |arg1| @site.header.works_blurb.text.should_not include(arg1) end
# This is a service object that will create a new game class CreateGameService class << self def create_game(game_room_slug) @gr = GameRoom.find_by_url_slug(game_room_slug) destroy_previous_game new_game = create_new_game_object @gr.touch { success: true, id: new_game.id } end private def destroy_previous_game @gr.game.destroy unless @gr.game.nil? end def create_new_game_object g = Game.new(spy_player_id: random_player_id, first_player_id: random_player_id) g.game_room = @gr g.location = random_location g.save g end def random_location Location.order('RANDOM()').first end def random_player_id @gr.players.order('RANDOM()').first.id end end end
class ApplicationController < Sinatra::Base disable :show_exceptions error Bunny::TCPConnectionFailedForAllHosts, Redis::CannotConnectError do render_error end set :raise_errors, true set :dump_errors, false set :show_exceptions, false attr_reader :body_params before do request.body.rewind request_body = request.body.read @body_params = if !request_body.empty? JSON.parse request_body else {} end end protected def auth_header_token env['HTTP_AUTHORIZATION'] end def render_error e = env['sinatra.error'] MyLogger.error e.message render_response(ResponsesDto.server_unavailable(e)) end def render_unprocessable_entity(params) status 415 json({ data: params }) end def render_unauthorized status 401 json({ data: 'unauthorized :(' }) end def render_server_unavailable(message = 'service unavailabe :(') status 503 json({ data: message }) end def render_response(response_dto) status response_dto.status_code json response_dto.data end end
class CreateReviewOfRooms < ActiveRecord::Migration def change create_table :review_of_rooms do |t| t.integer :accuracy t.integer :communication t.integer :cleanliness t.integer :location t.integer :check_in t.integer :value t.text :content t.integer :guests_id t.timestamps end end end
require 'test_helper' class CurrencyTest < ActiveSupport::TestCase def setup @c = Currency.new( symbol: "BTC" ) end test "it creates a Currency on Currency.new" do assert_instance_of Currency, @c, "Object not an instance of Currency" end test "Currency has a .cur_name method" do assert_respond_to @c, :cur_name, "Currency does not have a .cur_name method" end test "Currency has a .symbol method" do assert_respond_to @c, :symbol, "Currency does not have a .symbol method" end test "Currency validates symbol as existing currency" do @c.symbol = '123' refute @c.save, "symbol is not a valid currency" end test "Currency validates symbol length" do @c.symbol = 'invalid' refute @c.save, "symbol is not a valid length" end end
require 'rails_helper' RSpec.describe "Articles", type: :routing do before(:each) do user = User.create({ name: "Nombre1", email: "nombre@nombre.com", password: "12345678", password_confirmation: "12345678" }) @article = Article.create({ title: 'Title', lead: 'Lead', body: 'Body' }) @user = User.last end it 'routes /articles to the articles controller' do expect(get(articles_path)).to route_to(:controller => 'articles', :action => 'index') end it 'routes /articles/new to the articles controller' do expect(get(new_user_article_path(@user.id))).to route_to(:controller => 'articles', :action => 'new', :user_id => @user.id.to_s) end it 'routes /articles to the articles controller' do expect(post(articles_path)).to route_to(:controller => 'articles', :action => 'create') end it 'routes /articles/:id/edit to the articles controller' do expect(get(edit_article_path(@article))).to route_to(:controller => 'articles', :action => 'edit', :id => "#{@article.id}") end it 'routes /articles/:id to the articles controller' do expect(patch(article_path(@article))).to route_to(:controller => 'articles', :action => 'update', :id => "#{@article.id}") end it 'routes /articles/:id to the articles controller' do expect(put(article_path(@article))).to route_to(:controller => 'articles', :action => 'update', :id => "#{@article.id}") end it 'routes /articles/:id to the articles controller' do expect(delete(article_path(@article))).to route_to(:controller => 'articles', :action => 'destroy', :id => "#{@article.id}") end end
class CreateTracks < ActiveRecord::Migration def self.up create_table :tracks do |t| t.string :persistent_id t.string :name t.string :artist t.string :album t.float :duration t.integer :rating t.boolean :enabled, :default => true t.timestamps end end def self.down drop_table :tracks end end
class ArtsType < ActiveRecord::Base has_and_belongs_to_many :media_items validates_presence_of :name validates_uniqueness_of :name end
# FakeFS::SpecHelpers provides a simple macro for RSpec example groups to turn FakeFS on and off. # To use it simply require 'fakefs/spec_helpers', then include FakeFS::SpecHelpers into any # example groups that you wish to use FakeFS in. For example: # # require 'fakefs/spec_helpers' # # describe "Some specs that deal with files" do # include FakeFS::SpecHelpers # ... # end # # Alternatively, you can include FakeFS::SpecHelpers in all your example groups using RSpec's # configuration block in your spec helper: # # require 'fakefs/spec_helpers' # # Spec::Runner.configure do |config| # config.include FakeFS::SpecHelpers # end # # If you do the above then use_fakefs will be available in all of your example groups. # require 'fakefs/safe' module FakeFS module SpecHelpers def self.extended(example_group) example_group.use_fakefs(example_group) end def self.included(example_group) example_group.extend self end def use_fakefs(describe_block) describe_block.before :each do FakeFS.activate! end describe_block.after :each do FakeFS.deactivate! FakeFS::FileSystem.clear end end end end
class DeliveryEntrySerializer def initialize(object) @entry = object end def to_serialized_json options = { include: { user: { only: [:username] }, methods: [:created], except: [:updated_at, :created_at] } } @entry.to_json(options) end end
require 'rails_helper' describe ActiveAdmin::Views::SidebarSection do let(:options) { {} } let(:section) do ActiveAdmin::SidebarSection.new("Help Section", options) do span "Help Me" end end let(:html) do result = render_arbre_component section: section do sidebar_section(assigns[:section]) end Capybara.string(result.to_s) end it "should have a title h3" do expect(html).to have_css '.panel-title', text: 'Help Section' end it "should have the class of 'sidebar_section'" do expect(html).to have_css ".sidebar_section" end it "should have an id based on the title" do expect(html).to have_css "#help-section_sidebar_section" end it "should have a panel body" do expect(html).to have_css '.panel-body' end it "should add children to the panel body" do expect(html).to have_css '.panel-body > span' end context 'with a custom class attribute' do let(:options) { { class: 'custom_class' } } it "should have 'custom_class' class" do expect(html).to have_css ".custom_class" end end end
require_relative 'test_helper' require_relative '../lib/invoice_item' class InvoiceItemTest < Minitest::Test attr_reader :ii def setup @ii = InvoiceItem.new({ id: 999999, item_id: 111111, invoice_id: 234234, quantity: 34, unit_price: 500, created_at: Time.now, updated_at: Time.now, }, "self") end def test_invoice_item_class_exists assert_instance_of InvoiceItem, ii end def test_it_returns_id result = ii.id assert_equal 999999, result end def test_it_returns_item_id result = ii.item_id assert_equal 111111, result end def test_it_returns_invoice_id result = ii.invoice_id assert_equal 234234, result end def test_it_returns_quantity result = ii.quantity assert_equal 34, result end def test_it_returns_unit_price result = ii.unit_price assert_equal 0.5E1, result end def test_it_can_return_created_at_value time = Time.now result = ii.created_at refute_equal result, time end def test_it_can_return_updated_at_value time = Time.now result = ii.updated_at refute_equal result, time end def test_it_converts_unit_price_to_float result = ii.unit_price_to_dollars assert_equal 5, result end end
require 'faraday' require 'faraday_middleware' require 'faraday/panoptes' require "panoptes/client/version" require "panoptes/client/me" require "panoptes/client/projects" require "panoptes/client/subjects" require "panoptes/client/subject_sets" require "panoptes/client/user_groups" require "panoptes/client/workflows" module Panoptes class Client class GenericError < StandardError; end class ConnectionFailed < GenericError; end class ResourceNotFound < GenericError; end class ServerError < GenericError; end include Panoptes::Client::Me include Panoptes::Client::Projects include Panoptes::Client::Subjects include Panoptes::Client::SubjectSets include Panoptes::Client::UserGroups include Panoptes::Client::Workflows # A client is the main interface to the API. # # @param auth [Hash] Authentication details # * either nothing, # * a hash with +:token+ (an existing OAuth user token), # * or a hash with +:client_id+ and +:client_secret+ (a keypair for an OAuth Application). # @param url [String] Optional override for the API location to use. Defaults to the official production environment. def initialize(auth: {}, url: "https://panoptes.zooniverse.org") @conn = Faraday.new(url: url) do |faraday| case when auth[:token] faraday.request :panoptes_access_token, url: url, access_token: auth[:token] when auth[:client_id] && auth[:client_secret] faraday.request :panoptes_client_credentials, url: url, client_id: auth[:client_id], client_secret: auth[:client_secret] end faraday.request :panoptes_api_v1 faraday.request :json faraday.response :json faraday.adapter Faraday.default_adapter end end def get(path, query = {}) response = conn.get("/api" + path, query) handle_response(response) end def post(path, body = {}) response = conn.post("/api" + path, body) handle_response(response) end def put(path, body = {}, etag: nil) headers = {} headers["If-Match"] = etag if etag response = conn.put("/api" + path, body, headers) handle_response(response) end def patch(path, body = {}, etag: nil) headers = {} headers["If-Match"] = etag if etag response = conn.patch("/api" + path, body, headers) handle_response(response) end def delete(path, query = {}, etag: nil) headers = {} headers["If-Match"] = etag if etag response = conn.delete("/api" + path, query, headers) handle_response(response) end # Get a path and perform automatic depagination def paginate(path, query, resource: nil) resource = path.split("/").last if resource.nil? data = last_response = get(path, query) while next_path = last_response["meta"][resource]["next_href"] last_response = get(next_path, query) if block_given? yield data, last_response else data[resource].concat(last_response[resource]) if data[resource].is_a?(Array) data["meta"][resource].merge!(last_response["meta"][resource]) data["links"].merge!(last_response["links"]) end end data end private def conn @conn end def handle_response(response) case response.status when 404 raise ResourceNotFound, status: response.status, body: response.body when 400..600 raise ServerError.new(response.body) else response.body end end end end
# frozen_string_literal: true # borzoi.rb # Author: William Woodruff # ----------------------- # Fetches a random picture of a Borzoi from the Dog CEO API. # ----------------------- # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "open-uri" require "json" require_relative "yossarian_plugin" class Borzoi < YossarianPlugin include Cinch::Plugin use_blacklist URL = "https://dog.ceo/api/breed/borzoi/images/random" def usage "!borzoi - Get a random Borzoi picture." end def match?(cmd) cmd =~ /^(!)?borzoi$/ end match /borzoi$/, method: :borzoi def borzoi(m) hsh = JSON.parse(URI.open(URL).read) m.reply hsh["message"], true rescue Exception => e m.reply e.to_s, true end end
def fill_out_location # Hard-code values and should use parameterization select('Business', from: 'Address_Type_Select') fill_in('Street', with: '7950 Jones Branch Dr') fill_in('City', with: 'McLean') select('VA', from: 'Region') fill_in('Postal_Code', :with => '22102') end def continue_button find_button('Continue').click end # Page Object - Readable Link def click_mystore_change find(:css, '.qa-Mys_Change').click end # Navigation Steps When(/^I click the Order Online tab$/) do click_link('Order Online') require "debug" expect(page).to have_css('.Delivery') expect(page).to have_css('.Carryout') expect(page).to have_css('.Locations') find('.Delivery').click end When(/^I click the Continue button$/) do continue_button end When(/^I click Future Carryout Order button$/) do pending # express the regexp above with the code you wish you had end # Change MY LOCATION and MY STORE Steps When(/^I click Change My Location link$/) do pending # express the regexp above with the code you wish you had end When(/^I click the Change My Store link$/) do click_mystore_change within ("[data-storeid='4348']") do find("[data-type='Carryout']").click end end # Validate Then(/^I should see the Dominos Location Search page$/) do expect(page).to have_selector(:id, 'locationsSearchPage') end Then(/^I should see "(.*?)" selected in the order settings$/) do |my_location| page.has_content?(my_location) end # Location Form When(/^I select "([^"]*)" from address type drop\-down$/) do |address_type| select(address_type, from: 'Address_Type_Select') end When(/^I enter "(.*?)" in the street address input field$/) do |street_address| fill_in('Street', with: street_address) end When(/^I enter "(.*?)" in the city input field$/) do |city| fill_in('City', with: city) end When(/^I select "(.*?)" from state drop\-down$/) do |state| select(state, from: 'Region') end When(/^I enter "(.*?)" in the zip code input field$/) do |zip| fill_in('Postal_Code', with: zip) end # Example of Page Object for Location Form When(/^I fill out location search$/) do fill_out_location end
class Presentation < ActiveRecord::Base belongs_to :room belongs_to :time_slot end
require 'net/http' require "rexml/document" class Reading < ActiveRecord::Base belongs_to :device has_one :stop_event belongs_to :geofence include ApplicationHelper acts_as_mappable :lat_column_name => :latitude,:lng_column_name => :longitude def self.per_page 25 end def speed read_attribute(:speed).round if read_attribute(:speed) end def get_fence_name return nil if self.geofence_id.blank? || self.geofence_id.zero? @fence_name ||= self.geofence.nil? ? nil : self.geofence.name end def fence_description return '' if self.geofence_id.blank? || self.geofence_id.zero? @fence_description ||= self.geofence_event_type + 'ing ' + (get_fence_name() || 'geofence') end def short_address if(admin_name1.nil?) latitude.to_s + ", " + longitude.to_s else begin addressParts = Array.new if(!street.nil?) if(!street_number.nil?) streetAddress = [street_number, street] streetAddress.delete("") addressParts << streetAddress.join(' ') else addressParts << street end end addressParts << place_name addressParts << admin_name1 addressString = addressParts.join(', ') addressString.empty? ? latitude.to_s + ", " + longitude.to_s : addressString rescue latitude.to_s + ", " + longitude.to_s end end end def short_address_with_rg if(self.geocoded) short_address else ReverseGeocoder.find_reading_address(self) update_attributes({:geocoded => true}) short_address end end def self.clear_rgs Reading.update_all({:geocoded => false, :street_number => nil, :street => nil, :place_name => nil, :admin_name1 => nil}) end end
require "minitest/autorun" require "minitest/pride" require './lib/card' require './lib/deck' require "./lib/player" require "./lib/turn" class TurnTest < Minitest::Test def test_it_exists card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_instance_of Turn, turn end def test_player_can_have_a_turn card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_equal player1, turn.player1 assert_equal player2, turn.player2 end def test_there_are_no_spoils_at_first card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_equal [], turn.spoils_of_war end def test_for_basic_turn_type card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_equal :basic, turn.type end def test_a_winner_is_declared card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert player1, turn.winner end def test_after_pile_cards_the_spoils_appear card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) turn.pile_cards assert_includes(turn.spoils_of_war, card1) assert_includes(turn.spoils_of_war, card3) end def test_spoils_awarded_to_winner_in_basic card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card3, card4, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) winner = turn.winner turn.pile_cards turn.award_spoils(winner) assert_includes(player1.deck.cards, card1) assert_includes(player1.deck.cards, card3) refute_includes(player2.deck.cards, card1) refute_includes(player2.deck.cards, card3) end def test_spoils_awarded_in_war card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "Queen", 12) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card4, card3, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_equal :war, turn.type winner = turn.winner turn.pile_cards assert_includes(turn.spoils_of_war, card1, card2) assert_includes(turn.spoils_of_war, card5, card4) assert_includes(turn.spoils_of_war, card3, card6) turn.award_spoils(winner) assert_equal [card8], player1.deck.cards assert_includes(player2.deck.cards, card7, card1) assert_includes(player2.deck.cards, card2, card5) assert_includes(player2.deck.cards, card4, card3) assert_includes(player2.deck.cards, card6) end def test_for_mutually_assured_destruction card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 = Card.new(:diamond, "Jack", 11) card5 = Card.new(:heart, "8", 8) card6 = Card.new(:diamond, "8", 8) card7 = Card.new(:heart, "3", 3) card8 = Card.new(:diamond, "2", 2) deck1 = Deck.new([card1, card2, card5, card8]) deck2 = Deck.new([card4, card3, card6, card7]) player1 = Player.new("Megan", deck1) player2 = Player.new("Aurora", deck2) turn = Turn.new(player1, player2) assert_equal :mutually_assured_destruction, turn.type assert_equal "No Winner", winner = turn.winner turn.pile_cards assert_equal [], turn.spoils_of_war assert_equal [card8], player1.deck.cards assert_equal [card7], player2.deck.cards end end
class AddPriorityToContacts < ActiveRecord::Migration[5.0] def change add_column :contacts, :rush_priority, :integer add_column :contacts, :is_brother, :boolean, default: false end end
require 'spec_helper' module Alf describe AttrList do describe "coerce" do subject{ AttrList.coerce(arg) } describe "when passed a AttrList" do let(:arg){ [:a, :b] } it{ should eq(AttrList.new(arg)) } end describe "when passed an array" do let(:arg){ [:a, :b] } specify{ subject.attributes.should eq([:a, :b]) } end describe "when passed an Ordering" do let(:arg){ Ordering.new [[:a, :asc], [:b, :asc]] } it{ should eq(AttrList.new([:a, :b])) } end end describe "from_argv" do subject{ AttrList.from_argv(argv) } describe "on an empty array" do let(:argv){ [] } it{ should eq(AttrList.new([])) } end describe "on a singleton" do let(:argv){ ["hello"] } it{ should eq(AttrList.new([:hello])) } end describe "on multiple strings" do let(:argv){ ["hello", "world"] } it{ should eq(AttrList.new([:hello, :world])) } end end describe "to_ordering" do specify "when passed an array" do key = AttrList.coerce [:a, :b] okey = key.to_ordering okey.attributes.should == [:a, :b] okey.order_of(:a).should == :asc okey.order_of(:b).should == :asc end end describe "split" do subject{ key.split(tuple, allbut) } describe "when used without allbut" do let(:key){ AttrList.new [:a, :b] } let(:allbut){ false } let(:tuple){ {:a => 1, :b => 2, :c => 3} } let(:expected){ [{:a => 1, :b => 2}, {:c => 3}] } it{ should == expected } end describe "when used with allbut" do let(:key){ AttrList.new [:a, :b] } let(:allbut){ true } let(:tuple){ {:a => 1, :b => 2, :c => 3} } let(:expected){ [{:c => 3}, {:a => 1, :b => 2}] } it{ should == expected } end end describe "project" do subject{ key.project(tuple, allbut) } describe "when used without allbut" do let(:key){ AttrList.new [:a, :b] } let(:allbut){ false } let(:tuple){ {:a => 1, :b => 2, :c => 3} } let(:expected){ {:a => 1, :b => 2} } it{ should == expected } end describe "when used with allbut" do let(:key){ AttrList.new [:a, :b] } let(:allbut){ true } let(:tuple){ {:a => 1, :b => 2, :c => 3} } let(:expected){ {:c => 3} } it{ should == expected } end end end end
require 'albacore' require 'nokogiri' $connection_string = ENV['CONNECTION_STRING'] $aws_access_key = ENV['AWS_ACCESS_KEY'] $aws_secret_key = ENV['AWS_SECRET_KEY'] task :default => [:restore, :compile_this, :transform_config, :deploy] #https://github.com/Albacore/albacore/wiki/nugets_restore nugets_restore :restore do |p| p.out = 'packages' p.nuget_gem_exe end #https://github.com/Albacore/albacore/wiki/build build :compile_this do |b| b.file = Paths.join 'StockSharer.Web', 'StockSharer.Web.csproj' b.target = ['Clean', 'Rebuild'] b.prop 'Configuration', 'Release' b.nologo b.be_quiet b.prop 'UseWPP_CopyWebApplication', 'true' b.prop 'PipelineDependsOnBuild', 'false' b.prop 'webprojectoutputdir', '../deploy/' b.prop 'outdir', 'bin/' end #http://www.nokogiri.org/tutorials/modifying_an_html_xml_document.html task :transform_config do filename = "deploy/Web.config" doc = File.open(filename) { |f| Nokogiri::XML(f) } connectionStringNode = doc.xpath("//connectionStrings/add[@name='StockSharerDatabase']")[0] connectionStringNode['connectionString'] = $connection_string awsAccessKeyNode = doc.xpath("//appSettings/add[@key='AWSAccessKey']")[0] awsAccessKeyNode['value'] = $aws_access_key awsSecretKeyNode = doc.xpath("//appSettings/add[@key='AWSSecretKey']")[0] awsSecretKeyNode['value'] = $aws_secret_key File.write(filename, doc.to_xml) end task :deploy do FileUtils.cp_r 'deploy/.', 'C:/inetpub/wwwroot' end
class OrderItem < ActiveRecord::Base belongs_to :order belongs_to :product def price product.price * quantity end end
class Goal < ActiveRecord::Base include TokenFinder validates_presence_of :title belongs_to :user has_many :memberships has_many :members, :source => :user, :through => :memberships, :conditions => "status = 'approved'" has_many :posts belongs_to :city before_save :parse_date before_save :set_city_id after_create :set_token scope :recent, order("created_at DESC") scope :current, where(["date >= ?", Time.now]) scope :valid, where("user_id IS NOT NULL") def distance(city_name) to_city = City.find_by_name(city_name) return 9999999 if to_city.nil? Geocoder::Calculations.distance_between([city.latitude.to_f, city.longitude.to_f], [to_city.latitude.to_f, to_city.longitude.to_f], :units => :km) end protected def set_token self.token = Token.get_token(self.id) self.save end def set_city_id city = City.find_by_name(self.location) self.city_id = city.id if city end def parse_date str = self.title.dup str.slice!(" at ") str.slice!(" on ") str.slice!(" in ") self.date = Chronic.parse(str) self.date = Time.now.to_date if self.date.nil? end end
=begin 1 ---------------------------- Print 1-255 Write a program that would print all the numbers from 1 to 255. =end # Code 1 --------------- (1..255).each{|i| puts i} for i in 1..255 puts "#{i}" end =begin 2 ---------------------------- Print odd numbers between 1-255 Write a program that would print all the odd numbers from 1 to 255. =end # Code 2 --------------- (1..255).each{|i| puts i if i.odd?} puts "for" for i in 1..255 puts i if i.odd? end =begin 3 ---------------------------- Print Sum Write a program that would print the numbers from 0 to 255 but this time, it would also print the sum of the numbers that have been printed so far. For example, your output should be something like this: New number: 0 Sum: 0 New number: 1 Sum: 1 New number: 2 Sum: 3 New number: 3 Sum: 6 ... New number: 255 Sum: __ Do NOT use an array to do this exercise. =end # Code 3 --------------- sum = 0 (0..255).each {|i| puts "New number: #{i} Sum: #{sum += i}"} =begin 4 ---------------------------- Iterating through an array Given an array X, say [1,3,5,7,9,13], write a program that would iterate through each member of the array and print each value on the screen. Being able to loop through each member of the array is extremely important. =end # Code 4 --------------- x = [1,3,5,7,9,13] x.each {|i| puts i} =begin 5 ---------------------------- Find Max Write a program (sets of instructions) that takes any array and prints the maximum value in the array. Your program should also work with a given array that has all negative numbers (e.g. [-3, -5, -7]), or even a mix of positive numbers, negative numbers and zero. =end # Code 5 --------------- x = [-3, -5, -7] puts x.max y = [5, -9, 8] puts y.max z = [9, 0, -4] puts z.max =begin 6 ---------------------------- Get Average Write a program that takes an array, and prints the AVERAGE of the values in the array. For example for an array [2, 10, 3], your program should print an average of 5. Again, make sure you come up with a simple base case and write instructions to solve that base case first, then test your instructions for other complicated cases. You can use a length function with this assignment. =end # Code 6 --------------- array1 = [2, 10, 3] puts array1.reduce(:+) / array1.length.to_f =begin 7 ---------------------------- Array with Odd Numbers Write a program that creates an array 'y' that contains all the odd numbers between 1 to 255. When the program is done, 'y' should have the value of [1, 3, 5, 7, ... 255]. =end # Code 7 --------------- y = [] (1..255).each {|i| y << i if i.odd?} puts y =begin 8 ---------------------------- Greater Than Y Write a program that takes an array and returns the number of values in that array whose value is greater than a given value y. For example, if array = [1, 3, 5, 7] and y = 3, after your program is run it will print 2 (since there are two values in the array that are greater than 3). =end # Code 8 --------------- array1 = [1, 3, 5, 7] y = 3 puts array1.count {|i| i > y} =begin 9 ---------------------------- Square the values Given any array x, say [1, 5, 10, -2], create an algorithm (sets of instructions) that multiplies each value in the array by itself. When the program is done, the array x should have values that have been squared, say [1, 25, 100, 4]. =end # Code 9 --------------- x = [1, 5, 10, -2] puts x.map! {|i| i * i} =begin 10 ---------------------------- Eliminate Negative Numbers Given any array x, say [1, 5, 10, -2], create an algorithm that replaces any negative number with the value of 0. When the program is done, x should have no negative values, say [1, 5, 10, 0]. =end # Code 10 --------------- x = [1, 5, 10, -2] puts x.each_index {|i| x[i] = 0 if x[i] < 0} =begin 11 ---------------------------- Max, Min, and Average Given any array x, say [1, 5, 10, -2], create an algorithm that returns a hash with the maximum number in the array, the minimum value in the array, and the average of the values in the array. =end # Code 11 --------------- x = [1, 5, 10, -2] { max: x.max, min: x.min, average: x.reduce(:+) / x.length.to_f } puts x.max, x.min, x.reduce(:+) / x.length.to_f =begin 12 ---------------------------- Shifting the Values in the Array Given any array x, say [1, 5, 10, 7, -2], create an algorithm that shifts each number by one to the front. For example, when the program is done, an x of [1, 5, 10, 7, -2] should become [5, 10, 7, -2, 0]. =end # Code 12 --------------- x = [1, 5, 10, 7, -2] x.rotate!(1)[x.length-1] = 0 puts x =begin 13 ---------------------------- Number to String Write a program that takes an array of numbers and replaces any negative number with the string 'Dojo'. For example, if array x is initially [-1, -3, 2] after your program is done that array should be ['Dojo', 'Dojo', 2]. =end # Code 13 --------------- x = [-1, -3, 2] puts x.each_index {|i| x[i] = "Dojo" if x[i] < 0}
require "spec_helper" describe Balanced::Account do use_vcr_cassette before do api_key = Balanced::ApiKey.new.save Balanced.configure api_key.secret @marketplace = Balanced::Marketplace.new.save end describe "merchant" do use_vcr_cassette before do @merchant_attributes = { :type => "person", :name => "Billy Jones", :street_address => "801 High St.", :postal_code => "94301", :country => "USA", :dob => "1842-01", :phone_number => "+16505551234", } end describe "new" do use_vcr_cassette before do @bank_account = Balanced::BankAccount.new( :account_number => "1234567890", :bank_code => "321174851", :name => "Jack Q Merchant" ).save end it do -> do @merchant = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "merchant@example.org", :merchant => @merchant_attributes, :bank_account_uri => @bank_account.uri, :name => "Jack Q Merchant" ) end.should_not raise_error end end describe "#save" do describe "when creating" do use_vcr_cassette before do bank_account = Balanced::BankAccount.new( :account_number => "1234567890", :bank_code => "321174851", :name => "Jack Q Merchant" ).save @merchant = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "merchant@example.org", :merchant => @merchant_attributes, :bank_account_uri => bank_account.uri, :name => "Jack Q Merchant" ) end it { -> { @merchant.save }.should_not raise_error } end describe "after #save" do describe "attributes" do use_vcr_cassette before do bank_account = Balanced::BankAccount.new( :account_number => "1234567890", :bank_code => "321174851", :name => "Jack Q Merchant" ).save @merchant = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "merchant2@example.org", :merchant => @merchant_attributes, :bank_account_uri => bank_account.uri, :name => "Jack Q Merchant" ).save end describe "#id" do subject { @merchant.id } it { should_not be_nil } it { should_not be_empty } end describe "#roles" do subject { @merchant.roles } it { should include("merchant") } end describe "#email_address" do subject { @merchant.email_address } it { should eql "merchant2@example.org" } end describe "#name" do subject { @merchant.name } it { should eql "Jack Q Merchant" } end describe "#created_at" do subject { @merchant.created_at } it { should_not be_nil } it { should_not be_empty } end describe "#uri" do subject { @merchant.uri } it { should match MERCHANT_URI_REGEX } end describe "#holds_uri" do subject { @merchant.holds_uri } it { should match HOLDS_URI_REGEX } end describe "#bank_accounts_uri" do subject { @merchant.bank_accounts_uri } it { should match BANK_ACCOUNTS_URI_REGEX } end describe "#refunds_uri" do subject { @merchant.refunds_uri } it { should match REFUNDS_URI_REGEX } end describe "#debits_uri" do subject { @merchant.debits_uri } it { should match DEBITS_URI_REGEX } end describe "#transactions_uri" do subject { @merchant.transactions_uri } it { should match TRANSACTIONS_URI_REGEX } end describe "#credits_uri" do subject { @merchant.credits_uri } it { should match CREDITS_URI_REGEX } end describe "#cards_uri" do subject { @merchant.cards_uri } it { should match CARDS_URI_REGEX } end end end end describe "#add_bank_account" do describe "when executing" do use_vcr_cassette before do @bank_account = Balanced::BankAccount.new( :account_number => "1234567890", :bank_code => "321174851", :name => "Jack Q Merchant" ).save @merchant = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "merchant1@example.org", :merchant => @merchant_attributes, :bank_account_uri => @bank_account.uri, :name => "Jack Q Merchant" ).save @new_bank_account = Balanced::BankAccount.new( :account_number => "53434533", :bank_code => "12345678", :name => "Jack Q Merchant" ).save end it { -> { @merchant.add_bank_account(@new_bank_account.uri) }.should_not raise_error } end describe "after executing" do use_vcr_cassette before do @bank_account = Balanced::BankAccount.new( :account_number => "12345678901", :bank_code => "321174851", :name => "Jack Q Merchant" ).save @merchant = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "merchant4@example.org", :merchant => @merchant_attributes, :bank_account_uri => @bank_account.uri, :name => "Jack Q Merchant" ).save @new_bank_account = Balanced::BankAccount.new( :account_number => "53434533", :bank_code => "12345678", :name => "Jack Q Merchant" ).save @merchant.add_bank_account(@new_bank_account.uri) @bank_accounts = Balanced::BankAccount.find(@merchant.bank_accounts_uri).items end subject { @bank_accounts.size } it { should eql 2 } end end end describe "buyer" do describe "#save" do describe "when creating" do use_vcr_cassette before do card = Balanced::Card.new( :card_number => "5105105105105100", :expiration_month => "12", :expiration_year => "2015", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ) end it { -> { @buyer.save }.should_not raise_error } end describe "after #save" do describe "attributes" do use_vcr_cassette before do card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "12", :expiration_year => "2015", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer2@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ).save end describe "#id" do subject { @buyer.id } it { should_not be_nil } it { should_not be_empty } end describe "#roles" do subject { @buyer.roles } it { should include("buyer") } it { should_not include("merchant") } end describe "#email_address" do subject { @buyer.email_address } it { should eql "buyer2@example.org" } end describe "#name" do subject { @buyer.name } it { should eql "Jack Q Buyer" } end describe "#created_at" do subject { @buyer.created_at } it { should_not be_nil } it { should_not be_empty } end describe "#uri" do subject { @buyer.uri } it { should match MERCHANT_URI_REGEX } end describe "#holds_uri" do subject { @buyer.holds_uri } it { should match HOLDS_URI_REGEX } end describe "#bank_accounts_uri" do subject { @buyer.bank_accounts_uri } it { should match BANK_ACCOUNTS_URI_REGEX } end describe "#refunds_uri" do subject { @buyer.refunds_uri } it { should match REFUNDS_URI_REGEX } end describe "#debits_uri" do subject { @buyer.debits_uri } it { should match DEBITS_URI_REGEX } end describe "#transactions_uri" do subject { @buyer.transactions_uri } it { should match TRANSACTIONS_URI_REGEX } end describe "#credits_uri" do subject { @buyer.credits_uri } it { should match CREDITS_URI_REGEX } end describe "#cards_uri" do subject { @buyer.cards_uri } it { should match CARDS_URI_REGEX } end end end end describe "#add_card" do describe "when executing" do use_vcr_cassette before do card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "12", :expiration_year => "2015", ).save @new_card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "1", :expiration_year => "2015", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer3@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ).save end it do -> { @buyer.add_card(@new_card.uri) }.should_not raise_error end end describe "after executing" do use_vcr_cassette before do card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "12", :expiration_year => "2015", ).save @new_card = Balanced::Card.new( :card_number => "5105105105105100", :expiration_month => "1", :expiration_year => "2017", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer4@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ).save @buyer.add_card(@new_card.uri) @cards = Balanced::Card.find @buyer.cards_uri end subject { @cards.items.size } it { should eql 2 } end end describe "#promote_to_merchant" do describe "when executing" do use_vcr_cassette before do @merchant_attributes = { :type => "person", :name => "Billy Jones", :street_address => "801 High St.", :postal_code => "94301", :country => "USA", :dob => "1842-01", :phone_number => "+16505551234", } card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "12", :expiration_year => "2015", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer5@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ).save end it do -> { @buyer.promote_to_merchant @merchant_attributes}.should_not raise_error end end describe "after executing" do use_vcr_cassette before do @merchant_attributes = { :type => "person", :name => "Billy Jones", :street_address => "801 High St.", :postal_code => "94301", :country => "USA", :dob => "1842-01", :phone_number => "+16505551234", } card = Balanced::Card.new( :card_number => "4111111111111111", :expiration_month => "12", :expiration_year => "2015", ).save @buyer = Balanced::Account.new( :uri => @marketplace.accounts_uri, :email_address => "buyer6@example.org", :card_uri => card.uri, :name => "Jack Q Buyer" ).save @buyer.promote_to_merchant @merchant_attributes end subject { @buyer.roles } it { should include("merchant") } end end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. before_filter :configure_permitted_parameters, if: :devise_controller? protected include PublicActivity::StoreController # ... hide_action :current_user #@activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.followers, owner_type: "User") def configure_permitted_parameters ## Permit the custom fields below which you would like to update, I have shown a few examples devise_parameter_sanitizer.for(:account_update) << :LastName << :firstName<< :avatar devise_parameter_sanitizer.for(:sign_up) << :LastName << :firstName << :avatar end def after_sign_in_path_for(resource) if current_user.admin rails_admin.dashboard_path else root_path end #request.env['omniauth.origin'] || stored_location_for(resource) || root_path end protect_from_forgery with: :exception def avatar_url(user) if user.avatar_url.present? user.avatar_url else default_url = "#{root_url}images/guest.png" gravatar_id = Digest::MD5.hexdigest(user.email.downcase) "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}" end end end
class AddPageDecriptionToPage < ActiveRecord::Migration def self.up add_column :pages, :page_description, :text end def self.down remove_column :pages, :page_description end end
class Store attr_reader :longname, :city, :distance, :phone, :type def initialize(attrs = {}) @longname = attrs["longName"] @city = attrs["city"] @distance = attrs["distance"] @phone = attrs["phone"] @type = attrs["storeType"] end def self.fetch_by_zip(zip) stores = BestbuyService.fetch_by_zip(zip) stores.map do |store| Store.new(store) end end end
class Member < ApplicationRecord searchkick has_many :matches has_many :matched_members, through: :matches, dependent: :destroy has_many :headers before_save :set_short_url, if: :original_url_changed? after_create :scrape_headings validates :name, :original_url, presence: true validates :original_url, url: true def search_data { name: name } end def set_short_url self.short_url = Bitly.client.shorten(original_url).short_url end def scrape_headings HeadingScraper.new.scrape(id, original_url) end end
class MovieTitle STRINGS_TO_REMOVE = YAML.load(File.read("./configuration.yml"))["strings_to_remove"] attr_accessor :text def initialize(text:) @text = text end def format remove_periods() put_screen_resolution_in_brackets() remove_disallowed_strings() put_years_in_parens() remove_trailing_characters() clean_braces_and_parens() remove_extra_spaces() return self end private def remove_periods self.text = text.split('.').join(' ') end def put_screen_resolution_in_brackets # add brackets around 2160p, 1080p, and 720p, fix `p]p` created by accident self.text = text.gsub("2160", "[2160p]") .gsub("1080", "[1080p]") .gsub("720", "[720p]") .gsub("p]p", "p]") end def remove_disallowed_strings STRINGS_TO_REMOVE.each do |string_to_remove| self.text = text.gsub(string_to_remove, "") end end def put_years_in_parens # find four digit numbers starting with 1 or 2 years = text.scan(/[1-2]\d{3}/); if years.length > 0 years.each do |year| unless ["1080", "2160"].include?(year) # if the number is not 2160 or 1080, add `()` around it # because its probably an actual year self.text = text.gsub(year, "(#{year})") end end end end def remove_trailing_characters if text.rindex("]") # remove everything after last `]` if there is one self.text = text[0, text.rindex("]") + 1] elsif text.rindex(")") # remove everything after last `)` if there is one self.text = text[0, text.rindex(")") + 1] end end def clean_braces_and_parens # 1. clean up double braces and parens # 2. clean up empty braces and parens self.text = text.gsub("[[", "[") .gsub("]]", "]") .gsub("((", "(") .gsub("))", ")") .gsub("[]", "") .gsub("()", "") end def remove_extra_spaces self.text = text.split().join(" ") end end
Gem::Specification.new do |spec| spec.name = 'google_directions' spec.version = '0.2.0' spec.files = Dir['lib/**/*', 'test/**/*', 'README.textile', 'Gemfile', 'init.rb', 'Manifest', 'Rakefile'] spec.summary = 'Class for retrieving directions from the Google Directions API service' spec.description = "Easily retrieve turn-by-turn directions, polylines, and distances from Google using just addresses. Also supports waypoints." spec.authors = 'Josh Crews, Danny Summerlin' spec.email = 'hello@craftedbycreo.com' spec.homepage = 'http://www.craftedbycreo.com/' spec.add_runtime_dependency 'nokogiri', '~>1.6.0' end
class CreateCategoryz3Categories < ActiveRecord::Migration def change create_table :categoryz3_categories do |t| t.string :name t.references :parent t.integer :items_count , default: 0 t.integer :child_items_count , default: 0 t.integer :childrens_count , default: 0 t.timestamps end add_index :categoryz3_categories, :parent_id add_index :categoryz3_categories, :name end end
# In this exercise, you will be creating two classes AND the driver code to test them. # You will create a Tv class and a Remote class. # The Tv class will have the attributes: power, volume, and channel. class Television attr_accessor :power, :volume, :channel def initialize @power = false @volume = 0 @channel = 2 end end # The Remote class will have just one attribute: tv. This will represent which tv it # actually controls. class Remote attr_reader :tv def initialize(tv) @tv = tv end def toggle_power tv.power = (tv.power == false) ? true : false end def increment_volume tv.volume += 1 end def decrement_volume tv.volume -= 1 end def set_channel(channel) tv.channel = channel end end # TEST DRIVERS tv = Television.new remote = Remote.new(tv) # The Remote will have the following instance methods: # toggle_power (this will turn off the tv if it's on, or turn it on if it's off) puts 'Test Remote\'s Power Toggle' puts '-'*60 # Test Methods orig_pwr_status = tv.power remote.toggle_power # Assertion puts ( tv.power != orig_pwr_status) ? "Pass\n\n" : "F\n\n" # increment_volume (this will increase the tv's volume by 1) puts 'Test Remote\'s Volume Up Toggle' puts '-'*60 # Test Methods orig_vol = tv.volume remote.increment_volume # Assertion puts ( tv.volume == (orig_vol+1)) ? "Pass\n\n" : "F\n\n" # decrement_volume (this will decrease the tv's volume by 1) puts 'Test Remote\'s Volume Down Toggle' puts '-'*60 # Test Methods orig_vol = tv.volume remote.decrement_volume # Assertion puts ( tv.volume == (orig_vol-1)) ? "Pass\n\n" : "F\n\n" # set_channel (this will change the tv's channel to whatever integer is passed to this method) puts 'Test Remote\'s Channel Set Method' puts '-'*60 # Test Methods intended_channel = 20 remote.set_channel(intended_channel) # Assertion puts ( tv.channel == intended_channel) ? "Pass\n\n" : "F\n\n"
require 'find' require 'fileutils' require 'yaml' require 'ostruct' require 'zlib' class MiqFsUtil attr_accessor :verbose, :fromFs, :toFs def initialize(fromFs, toFs, us = nil) setUpdateSpec(us) @fromFs = fromFs @toFs = toFs @verbose = false end def updateSpec=(us) setUpdateSpec(us) end def setUpdateSpec(us) if us @csa = us @csa = YAML.load_file(us) if @csa.kind_of? String @csa = [@csa] if @csa.kind_of? Hash raise "Invalid collection spec" unless @csa.kind_of? Array else @csa = nil end end # # Load the update spec from a file in the fromFs. # def loadUpdateSpec(path) @fromFs.fileOpen(path) { |fo| @csa = YAML.load(fo.read) } end def update raise "MiqFsUpdate.update: no current update spec" unless @csa @csa.each { |cs| doUpdate(OpenStruct.new(cs)) } end def dumpSpec(specFile) raise "MiqFsUpdate.dumpSpec: no current update spec" unless @csa YAML.dump(@csa, File.open(specFile, "w")) end # # Copy files and directories from fromFs to the toFs. # # FILE -> FILE # FILE -> DIR # DIR -> DIR (recursive = true) # def copy(from, to, recursive = false) allTargets = [] from = [from] unless from.kind_of?(Array) from.each { |t| allTargets.concat(dirGlob(t)) } raise "copy: no source files matched" if allTargets.length == 0 if allTargets.length > 1 || recursive raise "copy: destination directory does not exist" unless @toFs.fileExists?(to) raise "copy: destination must be a directory for multi-file copy" unless @toFs.fileDirectory?(to) end allTargets.each do |f| owd = @fromFs.pwd @fromFs.chdir(File.dirname(f)) f = File.basename(f) # # Copy plain files. # if @fromFs.fileFile?(f) if @toFs.fileDirectory?(to) tf = File.join(to, File.basename(f)) else tf = to end copySingle(f, tf) next end # # If the recursive flag is not set, skip directories. # next unless recursive # # Recursively copy directory sub-tree. # @fromFs.chdir(f) td = File.join(to, f) @toFs.dirMkdir(td) unless @toFs.fileExists?(td) @fromFs.findEach('.') do |ff| tf = File.join(td, ff) if @fromFs.fileDirectory?(ff) @toFs.dirMkdir(tf) elsif @fromFs.fileFile?(ff) copySingle(ff, tf) end end # findEach @fromFs.chdir(owd) end # allTargets.each end private def log_puts(str = "") if $log $log.info str else puts str end end GLOB_CHARS = '*?[{' def isGlob?(str) str.count(GLOB_CHARS) != 0 end def dirGlob(glb, *flags, &block) return([glb]) unless isGlob?(glb) if glb[0, 1] == '/' dir = '/' glb = glb[1..-1] else dir = @fromFs.pwd end matches = doGlob(glb.split('/'), dir, flags) return(matches) unless block_given? matches.each do |e| block.call(e) end (false) end def doGlob(glbArr, dir, flags) return [] if !glbArr || glbArr.length == 0 retArr = [] glb = glbArr[0] dirForeach(dir) do |e| if flags.length == 0 match = File.fnmatch(glb, e) else match = File.fnmatch(glb, e, flags) end if match if glbArr.length == 1 retArr << File.join(dir, e) else next unless @fromFs.fileDirectory?(nf = File.join(dir, e)) retArr.concat(doGlob(glbArr[1..-1], nf, flags)) end end end (retArr) end def copySingle(ff, tf) if @verbose log_puts "Copying: #{ff}" log_puts " to: #{tf}" end @fromFs.fileOpen(ff) do |ffo| tfo = @toFs.fileOpen(tf, "wb") while (buf = ffo.read(1024)) tfo.write(buf) end tfo.close end end def doUpdate(cs) # # The directory where the collection will be created. # destDir = cs.todir # # Save the current directory. # fowd = @fromFs.pwd towd = @toFs.pwd begin # # The directory relative to which the files will be collected. # @fromFs.chdir(cs.basedir) # # Loop through the files and directories that are to be included in the collection. # cs.include.each do |i| raise "File: #{i} does not exist" unless @fromFs.fileExists? i # # If this is a plain file, then include it in the collection. # unless @fromFs.fileDirectory? i toFile = File.join(destDir, i) makePath(File.dirname(toFile)) # # If the file path matches an encrypt RE and doesn't # match a noencrypt RE, then encrypt the contents of # the file before copying it to the collection. # if cs.encrypt && cs.encrypt.detect { |e| i =~ e } if !cs.noencrypt || !cs.noencrypt.detect { |ne| i =~ ne } compressFile(i, toFile) next end end # # If the file path matches an compress RE and doesn't # match a nocompress RE, then compress the contents of # the file before copying it to the collection. # if cs.compress && cs.compress.detect { |e| i =~ e } if !cs.nocompress || !cs.nocompress.detect { |ne| i =~ ne } compressFile(i, toFile) next end end copyFile(i, toFile) next end # # If this is a directory, then recursively copy its contents # to the collection directory. # @fromFs.findEach(i) do |path| # # Prune directories that match an exclude RE. # if @fromFs.fileDirectory? path @fromFs.findEachPrune if cs.exclude && cs.exclude.detect { |e| path =~ e } next end # # Skip files that match an exclude RE. # next if cs.exclude && cs.exclude.detect { |e| path =~ e } toFile = File.join(destDir, path) makePath(File.dirname(toFile)) # # If the file path matches an encrypt RE and doesn't # match a noencrypt RE, then encrypt the contents of # the file before copying it to the collection. # if cs.encrypt && cs.encrypt.detect { |e| path =~ e } if !cs.noencrypt || !cs.noencrypt.detect { |ne| path =~ ne } compressFile(path, toFile) next end end # # If the file path matches an compress RE and doesn't # match a nocompress RE, then compress the contents of # the file before copying it to the collection. # if cs.compress && cs.compress.detect { |e| path =~ e } if !cs.nocompress || !cs.nocompress.detect { |ne| path =~ ne } compressFile(path, toFile) next end end copyFile(path, toFile) end end if cs.include # # Remove files from the destination fs. # @toFs.chdir(destDir) cs.remove.each do |r| if r.kind_of? Regexp # # If the entry is a RE, then remove all files and directories in # the destination directory that match the RE> # @toFs.findEach(".") do |p| next unless r.match(p) log_puts "\tRemoving: #{p}" if @verbose if !@toFs.fileDirectory? p @toFs.fileDelete(p) else @toFs.rmBranch(p) @toFs.findEachPrune end end else # # If the entry is a string, then it should be the path to the file # or directory to be removed. # unless @toFs.exists? r log_puts "Remove file: #{i} does not exist" if @verbose next end log_puts "\tRemoving: #{r}" if @verbose if !@toFs.fileDirectory? r @toFs.fileDelete(r) else @toFs.rmBranch(r) end end end if cs.remove ensure @fromFs.chdir(fowd) @toFs.chdir(towd) end end def makePath(path) return if @toFs.fileExists? path parentDir = @toFs.fileDirname(path) makePath(parentDir) unless @toFs.fileExists? parentDir @toFs.dirMkdir(path) end def copyFile(src, dest) if @fromFs.respond_to?(:hasTag?) && @fromFs.hasTag?(src, "compressed") decompressFile(src, dest) return end if @verbose log_puts "\t COPY: #{src}" log_puts "\t TO: #{dest}" end @fromFs.fileOpen(src) do |ffo| tfo = @toFs.fileOpen(dest, "wb") while (buf = ffo.read(4096)) tfo.write(buf, buf.length) end tfo.close end end def compressFile(src, dest) if @verbose log_puts "\tCOMPRESS: #{src}" log_puts "\t TO: #{dest}" end @fromFs.fileOpen(src) do |ffo| tfo = @toFs.fileOpen(dest, "wb") zipper = Zlib::Deflate.new while (buf = ffo.read(4096)) zipper << buf end tfo.write(zipper.deflate(nil, Zlib::FINISH)) tfo.addTag("compressed") if tfo.respond_to?(:addTag) tfo.close end end def decompressFile(src, dest) if @verbose log_puts "\tDECOMPRESS: #{src}" log_puts "\t TO: #{dest}" end @fromFs.fileOpen(src) do |ffo| tfo = @toFs.fileOpen(dest, "wb") unzipper = Zlib::Inflate.new while (buf = ffo.read(4096)) unzipper << buf end tfo.write(unzipper.inflate(nil)) tfo.close end end end # class MiqFsUpdate
class CoursesController < ApplicationController def new @area = load_area_from_url @course = Course.new end def create @area = load_area_from_url @course = @area.courses.new(course_params) if @course.save course_entry = NewCourseEntry.create(course_id: @course.id) current_user.feed_updates.create( entry: course_entry, poster_id: current_user.id ) redirect_to area_courses_path(@area) else redirect_to root_path end end def index @area = load_area_from_url @paginated_courses = @area.courses.page(params[:page]).per(10) end def show @area = load_area_from_url @course = load_course_from_url @course_time = @course.course_times.new respond_to do |format| format.html { render :show } format.json do render json: { start_point: @course.start_point, end_point: @course.end_point, mid_points: @course.mid_points } end end end private def course_params params. require(:course). permit( :name, :distance, :description, waypoints_attributes: [:lat, :lng, :order] ). merge(user_id: current_user.id) end def load_area_from_url Area.find(params[:area_id]) end def load_course_from_url Course.find(params[:id]) end end
require 'assessment' class CorrectionOfQuarterly < Assessment def title "Correction of Quarterly" end def fields super + %w( A2200 A2300 B0100 B0200 B0300 B1000 B0600 B0700 B0800 B1200 C0100 C0200 C0300a C0300b C0300c C0400a C0400b C0400c C0500 C0700 C0800 C0900a C0900b C0900c C0900d C1000 C1310a C1310b C1310c C1310d D0200a1 D0200a2 D0200b1 D0200b2 D0200c1 D0200c2 D0200d1 D0200d2 D0200i1 D0300 D0500a1 D0500a2 D0500b1 D0500b2 D0500c1 D0500c2 D0500d1 D0500d2 D0500i1 D0600 E0100a E0100b E0200a E0200b E0200c E0800 E0900 E1000a G0110a1 G0110a2 G0110b1 G0110b2 G0110c1 G0110c2 G0110d1 G0110d2 G0110e1 G0110f1 G0110g1 G0110g2 G0110h1 G0110h2 G0110i1 G0110i2 G0110j1 G0110j2 G0120a G0120b G0300a G0300e G0400a G0400b G0600a G0600b G0600c GG0100a GG0100b GG0100c GG0100d GG0110a GG0110b GG0110c GG0110d GG0110e GG0130a1 GG0130a2 GG0130a3 GG0130b1 GG0130b2 GG0130b3 GG0130c1 GG0130c2 GG0130c3 GG0130e1 GG0130e2 GG0130e3 GG0130f1 GG0130f2 GG0130f3 GG0130g1 GG0130g2 GG0130g3 GG0130h1 GG0130h2 GG0130h3 GG0170a1 GG0170a2 GG0170a3 GG0170b1 GG0170b2 GG0170b3 GG0170c1 GG0170c2 GG0170c3 GG0170d1 GG0170d2 GG0170d3 GG0170e1 GG0170e2 GG0170e3 GG0170f1 GG0170f2 GG0170f3 GG0170g1 GG0170g2 GG0170g3 GG0170i1 GG0170i2 GG0170i3 GG0170j1 GG0170j2 GG0170j3 GG0170k1 GG0170k2 GG0170k3 GG0170l1 GG0170l2 GG0170l3 GG0170m1 GG0170m2 GG0170m3 GG0170n1 GG0170n2 GG0170n3 GG0170o1 GG0170o2 GG0170o3 GG0170p1 GG0170p2 GG0170p3 GG0170q1 GG0170q3 GG0170r1 GG0170r2 GG0170r3 GG0170rr1 GG0170rr3 GG0170s1 GG0170s2 GG0170s3 GG0170ss1 GG0170ss3 H0100a H0100b H0100c H0100d H0200a H0200b H0200c H0300 H0400 H0500 I0020 I0020a I0200 I0600 I0700 I0800 I0900 I1500 I1550 I1650 I1700 I2000 I2100 I2200 I2300 I2400 I2500 I2900 I3100 I3200 I3300 I3900 I4000 I4200 I4300 I4400 I4500 I4800 I4900 I5000 I5100 I5200 I5250 I5300 I5350 I5400 I5500 I5600 I5700 I5800 I5900 I5950 I6000 I6100 I6200 I6300 J0400 J0500a J0500b J1100b J1400 J1550a J1550b J1550c J1550d J1800 J1900b J1900c J2000 K0100a K0100b K0100c K0100d K0200a K0200b K0300 K0310 K0510a2 K0510b2 K0510c2 L0200a L0200b L0200c L0200d L0200e L0200f L0200g M0100a M0100b M0100c M0150 M0210 M0300a1 M0300b1 M0300b2 M0300c1 M0300c2 M0300d1 M0300d2 M0300e1 M0300e2 M0300f1 M0300f2 M0300g1 M0300g2 M1030 M1040a M1040b M1040c M1040d M1040e M1040f M1040g M1040h M1200a M1200b M1200c M1200d M1200e M1200f M1200g M1200h M1200i N0300 N0350a N0410a N0410b N0410c N0410d N0410e N0410f N0410g N0410h N0450a N0450b N0450c N0450d N0450e N2001 N2003 N2005 O0100a1 O0100a2 O0100b1 O0100b2 O0100c2 O0100d2 O0100e2 O0100f2 O0100h2 O0100i2 O0100j1 O0100j2 O0100k2 O0100m2 O0250a O0300a O0400a4 O0400b4 O0400c4 O0400d2 O0400e2 O0500a O0500b O0500c O0500d O0500e O0500f O0500g O0500h O0500i O0500j P0100a P0100b P0100c P0100d P0100e P0100f P0100g P0100h P0200a P0200b P0200c P0200d P0200e P0200f X0150 X0200a X0200c X0300 X0400 X0500 X0600a X0600b X0600f X0600h X0700a X0700c ) end end
class Comment < ActiveRecord::Base belongs_to :user belongs_to :articles end
class Node attr_accessor :val, :next def initialize(value,next_node = nil) @val = value @next = next_node end end
module LazySerializable extend ActiveSupport::Concern def serialize_lazy(annotations: false, facets: true, public: false) params = { params: { facet_items: facets, navigation_items: facets, public: public } } hash = lazy_serializer.new(self, params).serializable_hash[:data] if annotations annotations = AnnotationSerializer.new(self.annotations).serializable_hash[:data] hash[:relationships][:annotations] = annotations end hash end def lazy_serializer raise NotImplementedError, "please implement the serializer factor for #{self}" end end
class Repo < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :tools has_many :completions end
class Tag include Mongoid::Document include Mongoid::Timestamps::Short field :name, type: String validates :name, presence: true validates :name, uniqueness: { case_sensitive: false } end
class ChangeColumnToCollege < ActiveRecord::Migration[5.1] def change rename_column :colleges, :image_co, :image end end
# # The MIT License (MIT) # # Copyright (c) 2014 Wynand Pieterse # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Version 0.1.0 # require $setUpSerialLogging require $setUpProvisionLogging # Defines our control VM, the primary VM for all tasks. def defineControlVM(control, vmName) control.vm.hostname = vmName control.vm.box = "https://cloud-images.ubuntu.com/vagrant/utopic/%s/utopic-server-cloudimg-amd64-vagrant-disk1.box" % $controlRequestImagePath control.vm.network :private_network, ip: "10.10.10.10" # Forward our Docker registry port to the outside world. control.vm.network "forwarded_port", guest: 5000, host: $controlDockerRegistryPort, auto_correct: true # Enabled serial logging if the user asked for it. setUpSerialLogging vmName # Build the log directory where all internal control machines logs will go to. logFile = setUpProvisionLogging vmName # Provision the machines. control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlBase.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlFiles.sh", :privileged => false, :args => "%s %s" % [logFile, $coreInstances] control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlAnsible.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlDocker.sh", :privileged => false, :args => "%s" % logFile control.vm.provision :shell, :path => "automation/vagrant/tasks/ProvisionControlRegistry.sh", :privileged => false, :args => "%s" % logFile end
module Returning module ActiveRecord module Adapter def to_sql(arel) if arel.respond_to?(:ast) visitor.accept(arel.ast) else arel end end def returning? !!@_returning end def exec_with_returning(sql, binds) records = @_returning[1].find_by_sql("#{to_sql(sql)} RETURNING #{@_returning[0]}", binds) records.each { |r| r.readonly! } records end [:update, :delete].each do |method| if ::ActiveRecord::VERSION::STRING =~ /^3\.0/ class_eval <<-RUBY, __FILE__, __LINE__+1 def #{method}(sql, name = nil) if @_returning exec_with_returning(sql, []) else super end end RUBY else class_eval <<-RUBY, __FILE__, __LINE__+1 def #{method}(sql, name = nil, binds = []) if @_returning exec_with_returning(sql, binds) else super end end RUBY end end def returning(columns, klass) old_returning, @_returning = @_returning, [columns, klass] yield ensure @_returning = old_returning end end end end
module DiscourseSimpleCalendar class EventValidator def initialize(post) @post = post end def validate_event return false if @post.is_first_post? calendar_custom_field = @post.topic.first_post.custom_fields[DiscourseSimpleCalendar::CALENDAR_CUSTOM_FIELD] return false unless calendar_custom_field return false if calendar_custom_field == "static" true end end end
class Api::BaseController < ApplicationController rescue_from StandardError, with: :respond_with_error def respond_with_error(exe) logger.error(exe) render json: { message: exe.message, backtrace: exe.backtrace[0..5] }, status: :internal_server_error end def respond_with_success(res) render json: res, status: :ok end end
class CreateUfafees < ActiveRecord::Migration def change create_table :ufafees do |t| t.timestamp :created_on t.timestamp :updated_on t.string :number t.decimal :amount, precision: 10, scale: 2 t.integer :project_id t.integer :period_id t.decimal :service_UFA, precision: 10, scale: 2 t.decimal :expense_UFA, precision: 10, scale: 2 end end end
class SysActionOnTable < ActiveRecord::Base attr_accessible :action, :table_name, :as => :role_new_update has_many :sys_user_groups, :through => :sys_user_rights validates_presence_of :action validates_presence_of :table_name validates :action, :uniqueness => {:scope => :table_name, :case_sensitive => false, :message => "NO duplicate action and table_name pair" } validates :table_name, :uniqueness => { :scope => :action, :case_sensitive => false } end
require 'sidekiq/testing' require 'rails_helper' RSpec.describe SyncHistoryOrderJob do let!(:user) { User.create!( email: 'foo@bar.com', password: 'abcdabcd', bitget_access_key: 'oo', bitget_secret_key: 'ooo', bitget_pass_phrase: '111' ) } it 'works' do Sidekiq::Testing.inline! Setting.support_currencies = %w[BTC] stub_bitget_history_first_100 stub_bitget_history_second_100 SyncHistoryOrderJob.perform_async expect(HistoryOrder.count).to eq(2) first_order = HistoryOrder.first puts first_order.inspect expect(first_order.profit).to eq('3.593'.to_d) expect(first_order.exchange).to eq('bitget') expect(first_order.currency).to eq('BTC') expect(first_order.volume).to eq(1) expect(first_order.fees).to eq('-0.1692798'.to_d) expect(first_order.remote_order_id).to eq('784226200150081515') expect(first_order.trade_avg_price).to eq('2821.33'.to_d) expect(first_order.user_id).to eq(1) end end
class Post < ApplicationRecord before_create :generate_permalink after_create :generate_reference, :assign_tags, :assign_promotion_updated_at has_many_attached :images has_many :markers, dependent: :destroy has_one :meta_datum belongs_to :user, :counter_cache => true validates :permalink, :uniqueness => true searchkick WATERMARK_PATH = Rails.root.join('lib', 'assets', 'images', '2dots-watermark.png') scope :scorable, -> { where("score > ?", 0).where.not(unpublish: true) } scope :without_meta, -> { where.not(id: MetaDatum.select(:post_id)) } def self.thumbnail_options { resize: "300x300^", gravity: 'center', extent: '300x300', strip: true, 'sampling-factor': '4:2:0', quality: '85', interlace: 'JPEG', colorspace: 'sRGB' } end def self.large_options { resize: "850x500^", gravity: 'center', draw: 'image SrcOver 0,0 0.5,0.5 "' + Post::WATERMARK_PATH.to_s + '"', strip: true, 'sampling-factor': '4:2:0', quality: '85', interlace: 'JPEG', colorspace: 'sRGB' } end def self.medium_options { resize: "320x240^", gravity: 'center', strip: true, 'sampling-factor': '4:2:0', quality: '35', interlace: 'JPEG', colorspace: 'sRGB' } end def card_image i return self.images[i].variant(combine_options: Post.medium_options).processed end def to_param permalink end # NOTE: Need further research on this approach. In case, we don't need other fields for elasticsearch - this may decrease the indexes size # def search_data # attributes.filter { |k, v| ['title', 'street', 'lga', 'state', 'area', 'tags', 'reference_id', 'type_of_property', 'state'].include?(k) } # end private def generate_permalink pattern=self.title.parameterize+"-in-#{self.lga.parameterize}-#{self.state.parameterize}" duplicates = Post.where('permalink like ?', "%#{pattern}%") if duplicates.present? self.permalink = "#{pattern}-#{duplicates.count+1}" else self.permalink = pattern end end def generate_reference self.update_attributes(reference_id: "#{rand(5**12).to_s(28).upcase}") end def assign_tags self.update_attributes(tags: "#{self.state}, #{self.lga}, #{self.area}") end def assign_promotion_updated_at self.update_attributes(promotion_updated_at: Time.now.beginning_of_year) end end
require 'spec_helper' describe Collins::SimpleCallback do def get_cb *args has_block = !args.find_index{|a| a.is_a?(Proc)}.nil? if not has_block then args.unshift(Proc.new{}) end Collins::SimpleCallback.new(*args) end it "#name" do get_cb(:fizz).name.should == :fizz end it "#options" do get_cb(:fizz, :opt1 => "val", :block => Proc.new{}).options.should == {:opt1 => "val"} end it "#empty" do Collins::SimpleCallback.empty.empty?.should be_true Collins::SimpleCallback.empty.defined?.should be_false end it "#defined?" do get_cb(:foo).defined?.should be_true end context "#arity" do it "0" do get_cb(:fizz, Proc.new{}).arity.should == 0 end it "1" do get_cb(:fizz, Proc.new{|a| puts(a)}).arity.should == 1 end it "2" do get_cb(:fizz, Proc.new{|a,b| puts(a,b)}).arity.should == 2 end end context "#parameters" do it "abba, zabba" do params = get_cb(:fizz, Proc.new{|abba,zabba| puts(abba)}).parameters params.map{|p| p[1]}.should == [:abba, :zabba] end it "none" do get_cb(:fizz).parameters.should == [] end end end
module Azendoo class Subject < AzResource has_many :tasks, class_name: 'Azendoo::Task' has_many :conversations, class_name: 'Azendoo::Conversation' def add_member(user) self.post(:add_member, user_id: user.id) end def remove_member(user) self.post(:remove_member, user_id: user.id) end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # This configuration requires Vagrant 1.5 or newer and two plugins: # # vagrant plugin install vagrant-hosts ~> 2.1.4 # vagrant plugin install vagrant-hostmanager # vagrant plugin install vagrant-auto_network ~> 1.0.0 # Vagrant.require_version ">= 1.7.2" require 'vagrant-hosts' require 'vagrant-hostmanager' require 'vagrant-auto_network' ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox' # these are the internal IPs, alternate IPs are auto-assigned using vagrant-auto_network puppetmaster_nodes = { 'puppetmaster' => { :ip => '192.168.50.9', :hostname => 'puppetmaster', :domain => 'scaleio.local', :memory => 512, :cpus => 1 } } # these are the internal IPs, alternate IPs are auto-assigned using vagrant-auto_network scaleio_nodes = { 'mdm1' => { :ip => '192.168.50.12', :hostname => 'mdm1', :domain => 'scaleio.local', :memory => 2048, :cpus => 2 }, 'tb' => { :ip => '192.168.50.11', :hostname => 'tb', :domain => 'scaleio.local', :memory => 2048, :cpus => 2 }, 'mdm2' => { :ip => '192.168.50.13', :hostname => 'mdm2', :domain => 'scaleio.local', :memory => 2048, :cpus => 2 }, } Vagrant.configure('2') do |config| config.ssh.insert_key = false config.hostmanager.enabled=true config.hostmanager.include_offline = true config.vm.define puppetmaster_nodes['puppetmaster'][:hostname] do |node| node_hash = puppetmaster_nodes['puppetmaster'] node.vm.box = 'relativkreativ/centos-7-minimal' node.vm.hostname = "#{node_hash[:hostname]}.#{node_hash[:domain]}" node.vm.provider "virtualbox" do |vb| vb.memory = node_hash[:memory] || 1024 vb.cpus = node_hash[:cpus] || 1 end node.vm.network :private_network, :ip => node_hash[:ip] node.vm.network :private_network, :auto_network => true bootstrap_script = <<-EOF if which puppet > /dev/null 2>&1; then echo 'Puppet Installed.' else yum remove -y firewalld && yum install -y iptables-services && iptables --flush echo 'Installing Puppet Master.' rpm -ivh http://yum.puppetlabs.com/el/7/products/x86_64/puppetlabs-release-7-10.noarch.rpm yum --nogpgcheck -y install puppet-server echo '*.#{node_hash[:domain]}' > /etc/puppet/autosign.conf puppet module install puppetlabs-stdlib puppet module install puppetlabs-firewall puppet module install puppetlabs-java puppet module install emccode-scaleio cp -Rf /opt/puppet/* /etc/puppet/. puppet config set --section main parser future puppet config set --section master certname puppetmaster.#{node_hash[:domain]} /usr/bin/puppet resource service iptables ensure=stopped enable=false /usr/bin/puppet resource service puppetmaster ensure=running enable=true fi EOF node.vm.provision :shell, :inline => bootstrap_script node.vm.synced_folder "puppet", "/opt/puppet" end scaleio_nodes.each do |node_name,value| config.vm.provision :hosts do |provisioner| provisioner.add_host puppetmaster_nodes['puppetmaster'][:ip], ["#{puppetmaster_nodes['puppetmaster'][:hostname]}.#{puppetmaster_nodes['puppetmaster'][:domain]}","#{puppetmaster_nodes['puppetmaster'][:hostname]}"] end # config.vm.provider "virtualbox" do |v| # v.customize ["setextradata", :id, "VBoxInternal/Devices/piix3ide/0/LUN0/Config/FlushInterval", "1"] # end config.vm.define node_name do |node| node_hash = scaleio_nodes[node_name] node.vm.box = 'relativkreativ/centos-7-minimal' node.vm.hostname = "#{node_hash[:hostname]}.#{node_hash[:domain]}" node.vm.provider "virtualbox" do |vb| vb.memory = node_hash[:memory] || 1024 vb.cpus = node_hash[:cpus] || 1 end node.vm.network :private_network, :ip => node_hash[:ip] node.vm.network :private_network, :auto_network => true bootstrap_script = <<-EOF if which puppet > /dev/null 2>&1; then echo 'Puppet Installed.' else yum remove -y firewalld && yum install -y iptables-services && iptables --flush echo 'Installing Puppet Agent.' rpm -ivh http://yum.puppetlabs.com/el/7/products/x86_64/puppetlabs-release-7-10.noarch.rpm yum --nogpgcheck -y install puppet puppet config set --section main server #{puppetmaster_nodes['puppetmaster'][:hostname]}.#{puppetmaster_nodes['puppetmaster'][:domain]} puppet agent -t --detailed-exitcodes || [ $? -eq 2 ] fi if which docker > /dev/null 2>&1; then echo 'Docker Installed.' systemctl stop docker else yum install -y docker fi rm -Rf /var/lib/docker if which screen > /dev/null 2>&1; then echo 'Screen installed.' else yum install -y screen fi chmod +x /opt/schelper/schelper.sh /usr/bin/screen -m -d bash -c "/opt/schelper/schelper.sh" EOF node.vm.provision :shell, :inline => bootstrap_script node.vm.synced_folder "schelper", "/opt/schelper" end end end
class ReportsController < ApplicationController before_filter :authenticate_user! def call_traffic_data_range authorize :report, :call_traffic_data_range? calls = Call.data_for_report(params[:date_range]) formatted_report = Call.prepare_data_for_date_range(calls) render json: formatted_report, status: 200 end def export_calls_traffic authorize :report, :export_calls_traffic? file_path = Call.export_calls_traffic(params[:export]) send_file file_path, type: "application/xlsx" end end
class AddWhyUseToUsers < ActiveRecord::Migration def change add_column :users, :whyUse, :string end end
class EventPerformersSplitService def initialize(event_performer_param,event_id) @event_id = event_id @event_performer_param = event_performer_param @event_performer = @event_performer_param.to_h['0']["performer"] end def execute # 改行コードで分割して、改行分レコードを作成する @event_performer_list = @event_performer.split("\r\n") # 1回消して、もう1回登録する EventPerformer.where(event_id: @event_id).delete_all @event_performer_list.each do |performer| # 登録する EventPerformer.create(event_id: @event_id, performer: performer) end end end
#!/usr/bin/env ruby # encoding: utf-8 require "open-uri" require "optparse" require_relative 'iconfinder_api' options = {} path = 'img' optparse = OptionParser.new do |opts| opts.banner = "Command-line tool for downloading icons from https://www.iconfinder.com\n" opts.banner += "Copyright (c) 2014 Zhussupov Zhassulan zhzhussupovkz@gmail.com\n" opts.banner += "While using this program, get API key from https://www.iconfinder.com.\nUsage: dl.rb [options]" opts.on('-h', '--help', "help page") do puts opts exit end opts.on('-q', '--query QUERY', "search for icons by search term") do |q| options[:q] = q end opts.on('-d', '--directory DIRECTORY', "folder, which will be uploaded icons") do |dir| path = dir end opts.on('-p', '--page PAGE', "specify result page(index). starts from 0") do |page| options[:p] = page end opts.on('-c', '--count COUNT', "number of icons per page") do |c| options[:c] = c end opts.on('-i', '--min MIN', "specify minimum size of icons") do |min| options[:min] = min end opts.on('-a', '--max MAX', "specify maximum size of icons") do |max| options[:max] = max end end optparse.parse! if options.empty? p optparse exit end if not path or path == false path = 'img' end query = options[:q] path = File.dirname(__FILE__) + '/' + path.to_s Dir.mkdir(path) unless File.exists?(path) ic = IconfinderApi.new 'your api key' threads = [] t1 = Time.now result = ic.search options puts "Found " + result.length.to_s + " icons for search query: #{query}." puts "Downloading icons to " + path.to_s + " directory." result.each do |e| threads << Thread.new do filename = File.basename e['image'] begin open(e['image'], 'rb') do |img| File.new("#{path}/#{filename}", 'wb').write(img.read) puts "Icon '" + filename + "': OK" end rescue Exception => e next end end end threads.each do |th| th.join end t2 = Time.now msecs = ((t2-t1).round(2)).to_s puts "Successfully downloaded " + result.length.to_s + " icons at #{msecs} sec."
FactoryGirl.define do factory :bike_brand do brand {Faker::Commerce.product_name} end end
require "redis" require "json" # Note: By linking containers using the name redis, we get the following ENV: # # REDIS_NAME=/sleepy_galileo/redis # REDIS_PORT_6379_TCP_ADDR=172.17.0.14 # REDIS_PORT_6379_TCP_PORT=6379 # REDIS_PORT_6379_TCP=tcp://172.17.0.14:6379 # REDIS_PORT=tcp://172.17.0.14:6379 url = ENV['REDIS_PORT'] if url url = url.gsub('tcp', 'redis') puts "Using Redis on url: #{url}" redis_sub = Redis.new(:url=>url) redis = Redis.new(:url=>url) else puts "Using Redis on localhost" redis_sub = Redis.new(:host => "127.0.0.1", :port => 6379) redis = Redis.new(:host => "127.0.0.1", :port => 6379) end trap(:INT) { puts "Exiting..."; exit } begin redis_sub.subscribe(:solar_events) do |on| on.subscribe do |channel, subscriptions| puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)" end on.message do |channel, message| # puts "##{channel}: #{message}" redis_sub.unsubscribe if message == "stop" data = redis.zrevrange('solar_service', 0, 99) puts "Found #{data.length} records for aggregation" # calc the average total charge for the last sample set total_charge_values = data.collect { |record| JSON.parse(record)['total_charge'] } average_total_charge = total_charge_values.inject(0.0) { |sum, el| sum + el } / total_charge_values.size # calc the average watts total_watts_values = data.collect { |record| JSON.parse(record)['total_watts'] } average_total_watts = total_watts_values.inject(0.0) { |sum, el| sum + el } / total_watts_values.size now = Time.now parsed = JSON.parse(data[0]) hostname = parsed['hostname'] json = { :hostname=>hostname, :timestamp=>now.to_i, :average_total_charge=>average_total_charge, :average_total_watts=>average_total_watts}.to_json redis.zadd('solar_service_aggregated', now.to_i, json) end on.unsubscribe do |channel, subscriptions| puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)" end end rescue Redis::BaseConnectionError => error puts "#{error}, retrying in 1s" sleep 1 retry end
class AddStatusToEnquiries < ActiveRecord::Migration def change add_column :enquiries, :status, :string, limit: 32, default: 'pending' end end
class AddPortAndPostgresPasswordToProjects < ActiveRecord::Migration[5.0] def change add_column :projects, :port, :integer, default: 80 add_column :projects, :db_admin_password, :string, default: '' end end
require 'spec_helper' describe 'POST recommendations/follow' do let!(:user) { stub_authentication } let!(:place) { create :place } let(:params) do { target_type: :place, target_id: place.id, emails: ['foo@bar.com'] } end subject { post recommendation_url, params; json } it { subject; expect(response.status).to eq 201 } it { expect(subject).to be_a_kind_of Array } it 'renders one array item per email address' do params[:emails] << 'herp@derp.com' expect(subject.length).to eq 2 end # todo SCHEMAS # it { expect(subject).to match_json_schema :recommendation } end
def da_boas_vindas puts "Bem vindo ao jogo da forca" puts "Qual é o seu nome?" nome = gets.strip puts "\n\n\n\n\n" puts "Começaremos o jogo para você, #{nome}" nome end def avisa_escolhendo_palavra_secreta puts "Escolhendo uma palavra secreta..." end def avisa_palavra_escolhida(palavra_secreta) puts "Palavra secreta com #{palavra_secreta.size} letras... boa sorte!" return palavra_secreta end def nao_quer_jogar puts "Deseja novamente? S/N" quero_jogar = gets.strip nao_quero_jogar = quero_jogar.upcase == "N" end def cabecalho_de_tentativa(chutes, erros, mascara) puts "\n\n\n\n\n" puts "Palabra secreta: #{mascara}" puts "Erros até agora: #{erros}" puts "Chutes até agora: #{chutes}" end def pede_um_chute puts "Entre com uma letra ou uma palavra" chute = gets.strip.downcase puts "Será que acertou ? Você chutou #{chute}" chute end def avisa_chute_efetuado(chute) puts "Você ja chutou esse #{chute}" end def avisa_letra_nao_encontrada puts "Letra não encontrada." end def avisa_letra_encontrada(total_encontrado) puts "Letra encontrada #{total_encontrado} vezes" end def avisa_acertou puts "Parabéns! Acertou" end def avisa_errou puts "Que pena... errou" end def avisa_pontos(pontos_ate_agora) puts "Você ganhou #{pontos_ate_agora} pontos." end def avisa_pontos_totais(pontos_totais) puts "Você possui pontos totais: #{pontos_totais}" end def avisa_campeao_atual(dados) puts "Nosso campeão atual é #{dados[0]} com #{dados[1]} pontos." end
class CreateCyClickerSettings < ActiveRecord::Migration def change create_table :cy_clicker_settings do |t| t.boolean :studentsBlocked t.timestamps end end end
#!/usr/bin/env ruby $is_Jekyll = false begin require "jekyll" puts "testing cases using jekyll" $is_Jekyll = true rescue LoadError require "liquid" puts "testing cases using liquid" end def isJekyll $is_Jekyll end def assertEqual(expected, real) if expected != real raise "#{real} is not #{expected}" end end Liquid::Template.error_mode = :strict def render(data = {}, source) Liquid::Template.parse(source, {:strict_variables => true}).render!(data); end # assertEqual("-1-2-2", render({}, "{% decrement var %}{% decrement var %}{{ var }}")) assertEqual("06", render({}, "{% increment var %}{% assign a = var | plus: 5 %}{{ a }}")) # assertEqual("0152", render({}, "{% increment var %}{% assign var=5 %}{% increment var %}{{ var }}{% increment var %}"))
module OHOLFamilyTrees class CombinedLogfile def initialize(logfiles) @logfiles = logfiles end attr_reader :logfiles def path logfiles.last.path end def cache logfiles.last.cache end def file_path logfiles.last.file_path end def date logfiles.last.date end def server logfiles.last.server end def cache_valid_at?(at_time) logfiles.each do |logfile| return false unless logfile.cache_valid_at?(at_time) end return true end def placements? logsfiles.last.placements? end def seed_only? logsfiles.last.placements? end def seed logfiles.last.seed end def open CombinedFile.new(logfiles) end end class CombinedFile def initialize(logfiles) @queue = logfiles.dup @current = queue.shift.open end attr_reader :queue attr_reader :current def gets value = current.gets if current.eof? && queue.any? @current.close @current = queue.shift.open end value end def eof? current.eof? end def close current && current.close end end end