text
stringlengths
10
2.61M
require "hemp/extensions/object" require "hemp/extensions/hash" require "hemp/routing/base" require "hemp/request_processor" require "rack" module Hemp class Application attr_reader :route_pot, :request, :params def initialize @route_pot = Hemp::Routing::Base.new end def call(env) @request = Rack::Request.new(env) route = find_route(request) unless env.empty? processor = RequestProcessor.new(request, route) processor.rack_response end def find_route(request) verb = request.request_method.downcase.to_sym route = @route_pot.routes[verb].detect do|route_val| route_val == request.path_info end route end end end
require("./block.rb") class BlockChain attr_accessor :blocks def initialize(array) self.blocks = [] previous_hash = "" array.each_with_index do |content, i| if i === 0 # genesis block block = Block.new(content, nil) previous_hash = block.do_work else block = Block.new(content, previous_hash) previous_hash = block.do_work end self.blocks.push(block) end end end
class CardTemplateItem < ActiveRecord::Base belongs_to :card_apply_template belongs_to :item validates :card_apply_template, presence: true validates :item, presence: true, uniqueness: { scope: :card_apply_template_id } end
class Rating < ActiveRecord::Base belongs_to :rating_definition serialize :value def self.set!(rundef, item_id, value) if item_id.nil? r = Rating.find(:first, :conditions => ['rating_definition_id = ? AND item_id IS NULL', rundef.id]) else r = Rating.find(:first, :conditions => ['rating_definition_id = ? AND item_id = ?', rundef.id, item_id]) end r = Rating.new(:rating_definition_id => rundef.id, :item_id => item_id) if r.nil? r.value = value r.save! end def inner_rating_definitions RatingDefinition.find(:all, :conditions => ["scope_type = ? AND parent_scope_id = ?", rating_definition.inner_scope_type, self.item_id]) end def teams unpack! if @results.nil? unpack_teams! if @teams.nil? @teams end def team_ids unpack! if @team_ids.nil? @team_ids end def result(team_id) unpack! if @results.nil? @results[team_id] end def fast_result(team_id) unpack_fast! if @fast_results.nil? @fast_results[team_id] end def trash! @results = nil @teams = nil @team_ids = nil end private def unpack! @team_ids = [] @results = {} self.value.each do |info| @team_ids << info[:team_id] @results[info[:team_id]] = OpenStruct.new(info) end end def unpack_fast! @team_ids = [] @fast_results = {} self.value.each do |info| @team_ids << info[:team_id] @fast_results[info[:team_id]] = info end end def unpack_teams! @teams = Team.find(@team_ids) th = {} @teams.each { |t| th[t.id] = t } @teams = @team_ids.collect { |id| th[id] } end end
module Nsn class TScore SIZE = 100 def initialize @data = data end def call result = nil @result = result || Result.latest t_score end def data Result.night.where(is_sunny: true).limit(SIZE).map {|v| v.darkness } .compact end def max data.max end def average @data.sum.to_f / @data.size end def variance @data.reduce(0) { |memo, v| memo + (v - average) ** 2 } / SIZE end def standard_deviation Math.sqrt variance end def target @result.darkness end def t_score t = target ((t - average) / standard_deviation + 50).to_i end end end
class CreateThemes < ActiveRecord::Migration def change create_table :themes do |t| t.string :name t.text :about t.datetime :created_at t.timestamps end create_table :items_themes, id: false do |t| t.belongs_to :item t.belongs_to :theme end end end
class CreateActivities < ActiveRecord::Migration def change create_table :activities do |t| t.string :description t.boolean :active , null: false, default: true t.timestamps end add_index :activities, :description, :unique => true end end
class ShameInit < ActiveRecord::Migration def change create_table "case_signs", force: true do |t| t.integer "case_id" t.integer "sign_id" end create_table "cases", force: true do |t| t.string "title" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "contributions", force: true do |t| t.integer "user_id" t.integer "contribute_id" t.string "contribute_type" end create_table "options", force: true do |t| t.string "content" t.string "description" t.datetime "created_at" t.datetime "updated_at" t.integer "question_id" end create_table "part_solos", force: true do |t| t.integer "part_id" t.integer "solo_id" end create_table "questions", force: true do |t| t.string "title" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", force: true do |t| t.string "name", null: false t.string "title", null: false t.text "description", null: false t.text "the_role", null: false end create_table "sections", force: true do |t| t.string "name" t.integer "sort_id" t.integer "position", default: 0 t.integer "add_sort_id" end create_table "sign_items", force: true do |t| t.integer "sign_id" t.integer "item_id" end create_table "sign_options", force: true do |t| t.integer "option_id" t.integer "sign_id" t.integer "user_id" t.string "reason" end create_table "signs", force: true do |t| t.string "name" t.text "content" t.integer "wiki_id" end create_table "solo_parts", force: true do |t| t.integer "solo_id" t.integer "part_id" t.integer "position", default: 0 end create_table "solo_taxons", force: true do |t| t.integer "child_id" t.integer "parent_id" t.integer "position", default: 0 end create_table "sorts", force: true do |t| t.string "name", default: "" t.integer "tags_count", default: 0 t.integer "position", default: 0 t.string "type" t.integer "status", default: 0 end create_table "sources", force: true do |t| t.integer "mum" t.string "headline" t.string "url" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "stars", force: true do |t| t.integer "user_id" t.integer "lovable_id" t.string "lovable_type" t.datetime "created_at" t.datetime "updated_at" end create_table "tags", force: true do |t| t.string "name" t.string "picture" t.integer "praise", default: 0 t.datetime "updated_at" t.integer "sort_id" t.text "content" t.string "sort_name" t.string "type" t.integer "parent_id" t.integer "lft" t.integer "rgt" t.integer "children_count", default: 0 t.integer "depth", default: 0 end create_table "user_cases", force: true do |t| t.integer "user_id" t.integer "case_id" t.datetime "created_at" t.datetime "updated_at" end create_table "user_options", force: true do |t| t.integer "user_id" t.integer "option_id" end create_table "users", force: true do |t| t.string "email", default: "", null: false t.string "password_digest", default: "", null: false t.string "confirm_token" t.datetime "confirm_sent_at" t.integer "logins_count", default: 0 t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "avatar" t.string "name", default: "" t.integer "role_id" end add_index "users", ["confirm_token"], name: "index_users_on_confirm_token", unique: true add_index "users", ["email"], name: "index_users_on_email", unique: true create_table "wiki_histories", force: true do |t| t.text "content" t.string "reason" t.integer "wiki_id" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "wikis", force: true do |t| t.text "content" t.string "reason" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "picture" t.string "name", default: "" t.string "subname", default: "" t.integer "sections_count", default: 0 t.string "type" t.integer "wiki_histories_count", default: 0 end add_index "wikis", ["user_id"], name: "index_wikis_on_user_id" end end
class InvoicesController < ApplicationController def index invoices = Invoice.all.order(created_at: :desc) render json: invoices end def create invoice = Invoice.create!(invoice_params) if invoice render json: invoice else render json: invoice.errors.full_messages end @full_paid = Invoice.fully_paid? end def show invoice = Invoice.find(params[:id]) end private def invoice_params params.require(invoice).permit(:invoice_total) end end
class AddConfirmStateToLadyDoctors < ActiveRecord::Migration def change add_column :lady_doctors, :confirm_state, :boolean, default: false, null: false end end
class CapturedImagesController < ApplicationController def destroy captured_images_sub = CapturedImage.find_by(id: params[:id], user_id: params[:user_id]) if captured_images_sub.destroy redirect_to "/users/#{params[:user_id]}/edit" else redirect_to "/users/#{params[:user_id]}/edit", alert: "FAILED TO DELETE IMAGE." end end end
module Admin class CommitteesController < BaseController load_and_authorize_resource def index @committees = Committee.all @committee = Committee.new end def show @congressman = Congressman.new end def create if @committee.save redirect_to [:admin, @committee] else errors_to_flash(@committee) redirect_to admin_committees_url end end def update if @committee.update(committee_params) redirect_to [:admin, @committee] else errors_to_flash(@committee) render 'edit' end end def destroy if @committee.congressmen.present? flash[:notice] = t('messages.has_congressman') redirect_to admin_committees_url else errors_to_flash(@committee) unless @committee.destroy redirect_to admin_committees_url end end private def committee_params params.require(:committee).permit(:name, :description) end end end
class RemoveTagListFromProducts < ActiveRecord::Migration def change remove_column :products, :tag_list, :text end end
# frozen_string_literal: true module RollbarApi class Resource attr_reader :response_json def initialize(response) response = response.body if response.is_a?(Faraday::Response) @response_json = if response.is_a?(String) JSON.parse(response) else response end @struct = ResourceStruct.new(@response_json, { recurse_over_arrays: true }) end delegate :inspect, to: :@struct def as_json(_options = {}) @response_json end def method_missing(name, *args) @struct.send(name, *args) end def respond_to_missing?(method_name, _include_private = false) @struct.respond_to?(method_name) end end class ResourceStruct < RecursiveOpenStruct def inspect %(#<RollbarApi::Resource: #{JSON.pretty_generate(@table)}>) end end end
module Boxes class Box < Apotomo::Widget helper Boxes::ViewHelpers attr_accessor :meta, :widget def initialize(controller, name) super(controller, name, :display) # prevent propagation of some event on :configure do |event| event.stop!; end on :save do |event| event.stop!; end on :display do |event| event.stop!; end on :update_configure do |event| event.stop!; end end responds_to_event :display, :with => :reload def reload replace :state => :display end def display render end responds_to_event :configure, :with => :configure def configure c = meta.configure_widget(parent_controller) if not c.nil? @configurable = true reset_widget(c) end replace end responds_to_event :update_configure, :with => :update_configure def update_configure meta.wclass = param(:wclass) if param(:wclass) render :state => :configure end responds_to_event :save, :with => :save def save configurable = meta.configurable? # save the configurable state meta = Boxes.meta_model.find(param(:meta_id)) ::Rails.logger.debug "MetaBox: #{meta}" unless meta.blank? published = meta.published? if meta.update_attributes(param(:meta)) self.meta = meta self.meta.configurable = configurable # The widget tree is already built so ... if not self.meta.published? # remove children self.children.reject{|w|w == @widget}.each{|w|w.removeFromParent!} @widget.removeFromParent! if not @widget.blank? else # we should add the children by hand Boxes::Core.build_boxes_tree(self, parent_controller, Boxes.meta_model.at_address(session[:boxes_address]), self) if not published end end reset_widget(meta.published? ? meta.widget(parent_controller) : nil) end replace :state => :display end private def reset_widget(widget) @widget.removeFromParent! if not @widget.blank? @widget = widget self << @widget if not @widget.blank? end end end
FactoryBot.define do factory :loan do value { Faker::Number.decimal(l_digits: 2) } rate { Faker::Number.between(from: 0.1, to: 1.0) } pmt { Faker::Number.decimal(l_digits: 2) } months { Faker::Number.decimal(l_digits: 2) } end end
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe "/admin/tags/index" do include Admin::TagsHelper before(:each) do blog = mock_model(Blog, :title => 'Blog Title') tag_98 = mock_model(Tag) tag_99 = mock_model(Tag) tag_98.should_receive(:name).and_return("MyString") tag_99.should_receive(:name).and_return("MyString2") tag_98.should_receive(:blog_taggings_count).with(blog).and_return(1) tag_99.should_receive(:blog_taggings_count).with(blog).and_return(2) assigns[:blog] = blog assigns[:tags] = [tag_98, tag_99] assigns[:tags].stub!(:total_pages).and_return(0) end it "should render list of tags" do render "/admin/tags/index.html.erb" response.should have_tag("h1", :text => "Blog Title tags") response.should have_tag("tr>td", "MyString (1 times)") response.should have_tag("tr>td", "MyString2 (2 times)") end end
def merge_sort(array, sorted_left, sorted_right) array_size = array.length left_size = sorted_left.length right_size = sorted_right.length array_pointer = 0 left_pointer = 0 right_pointer = 0 while left_pointer < left_size && right_pointer < right_size if sorted_left[left_pointer] < sorted_right[right_pointer] array[array_pointer] = sorted_left[left_pointer] left_pointer+=1 else array[array_pointer] = sorted_right[right_pointer] right_pointer+=1 end array_pointer+=1 end while left_pointer < left_size array[array_pointer] = sorted_left[left_pointer] left_pointer+=1 array_pointer+=1 end while right_pointer < right_size array[array_pointer] = sorted_right[right_pointer] right_pointer+=1 array_pointer+=1 end return array end def breakdown(array) if array.length <= 1 return array end array_size = array.length middle = (array.length / 2).round left_side = array[0...middle] right_side = array[middle...array_size] sorted_left = breakdown(left_side) sorted_right = breakdown(right_side) merge_sort(array, sorted_left, sorted_right) puts array return array end try = [2, 35] breakdown(try) # def merged_sorted_arrays(arr1, arr2) # merged_array = [] # merged_array_size = arr1.length + arr2.length # arr1_count = 0 # arr2_count = 0 # merged_array_count = 0 # while merged_array_count < merged_array_size # if arr1_count >= arr1.length || arr1[arr1_count] > arr2[arr2_count] # merged_array[merged_array_count] = arr2[arr2_count] # arr2_count += 1 # elsif # arr2_count >= arr2.length || merged_array[merged_array_count] = arr1[arr1_count] # arr1_count +=1 # end # merged_array_count += 1 # end # return merged_array # end # first = [3, 4, 6, 10, 11, 15] # arr1 # second = [5, 8, 12, 14, 19] # arr2 # merged_sorted_arrays(first, second) # # [3, 4, 5, 6, 8, 10, 11, 12, 14, 15 ] #merged_array
class ReviewsController < ApplicationController def new end def create @review = Review.new(review_params) @idea = Idea.find params[:idea_id] @review.idea = @idea @review.user = current_user if cannot? :create, @review flash[:alert] = "cannot create a review." redirect_to @idea elsif @review.save flash[:notice] = "Review Created" redirect_to idea_path(@idea) else flash[:alert] = "Problem creating review" render 'ideas/show' end end def update @review = Review.find params[:id] @review.update(flagged: !@review.flagged) @idea = @review.idea redirect_to idea_path(@idea, anchor: "#{@review.id}") # redirect_to idea_path(@idea) end def destroy @review = Review.find params[:id] @idea = Idea.find params[:idea_id] if can? :destroy, @review @review.destroy flash[:notice] = "Review successfully deleted" redirect_to idea_path(@idea) else flash[:alert] = "NO!" redirect_to @review.idea end # render json: params end private def review_params params.require(:review).permit(:body) end end
class FontTrebuchetMs < Formula head "https://downloads.sourceforge.net/corefonts/trebuc32.exe" desc "Trebuchet MS" homepage "https://sourceforge.net/projects/corefonts/files/the%20fonts/final/" def install (share/"fonts").install "trebuc.ttf" (share/"fonts").install "Trebucbd.ttf" (share/"fonts").install "trebucbi.ttf" (share/"fonts").install "trebucit.ttf" end test do end end
class AddFieldsToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :name, :string add_column :users, :birthdate, :datetime add_column :users, :about, :text add_column :users, :twitter_url, :string add_column :users, :facebook_url, :string add_column :users, :youtube_url, :string add_column :users, :location, :string add_column :users, :creator, :boolean add_column :users, :billing_street_address_1, :string add_column :users, :billing_street_address_2, :string add_column :users, :billing_city, :string add_column :users, :billing_state, :string add_column :users, :billing_postal_code, :string add_column :users, :billing_country, :string add_column :users, :mailing_street_address_1, :string add_column :users, :mailing_street_address_2, :string add_column :users, :mailing_city, :string add_column :users, :mailing_state, :string add_column :users, :mailing_postal_code, :string add_column :users, :mailing_country, :string end end
class RemindsController < ApplicationController def index @reminds = Remind.all.page(params[:page]) end def new @remind = Remind.new end def show @remind = Remind.find(params[:id]) respond_to do |format| format.html format.json { render :json => { id: @remind.id, alarm: @remind.alarm, address: @remind.address, content: @remind.content }.to_json } end end def create @remind = Remind.new(remind_params) respond_to do |format| format.html { if @remind.save redirect_to reminds_path else render 'new' end } format.json { if @remind.save render json: @remind, status: :created else render json: @remind.errors, status: :unprocessable_entity end } end end def destroy end private def remind_params params.require(:remind).permit(:alarm, :content) end end
require_relative '../views/orders_view' class OrdersController def initialize(orders_repository) @orders_repository = orders_repository @meals_repository = orders_repository.meals_repository @customers_repository = orders_repository.customers_repository @employees_repository = orders_repository.employees_repository @view = OrdersView.new end def create @view.list_items(@meals_repository.meals) meal_id = @view.ask_for("Meal number") @view.list_items(@customers_repository.customers) customer_id = @view.ask_for("Customer number") @view.list_items(@employees_repository.delivery_guys) employee_id = @view.ask_for("Employee number") meal = @meals_repository.find(meal_id) customer = @customers_repository.find(customer_id) employee = @employees_repository.find(employee_id) order = Order.new(meal: meal, customer: customer, employee: employee) @orders_repository.add(order) end def list_undelivered @view.list_orders(@orders_repository.undelivered_orders) end def list_undelivered_delivery_guy(employee) @view.list_orders(@orders_repository.undelivered_orders.select { |order| order.employee == employee }) end def mark_as_delivered(employee) list_undelivered_delivery_guy(employee) order_id = @view.ask_for("Order delivered") @orders_repository.update(order_id) end end
module Strategies class Log def initialize path @path = path @file = File.open path, "w" end def call msg ts = msg.timestamp.strftime '%Y/%m/%d %H:%M:%S' @file.puts "[#{ts}] #{msg.user} - #{msg.text}" @file.flush end def history File.read(@path).split("\n") end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'graphql/query_resolver/version' Gem::Specification.new do |spec| spec.name = "graphql-query-resolver" spec.version = GraphQL::QueryResolver::VERSION spec.authors = ["nettofarah"] spec.email = ["nettofarah@gmail.com"] spec.summary = %q{Minimize N+1 queries generated by GraphQL} spec.description = %q{GraphQL::QueryResolver is an add-on to graphql-ruby that allows your field resolvers to minimize N+1 SELECTS issued by ActiveRecord. } spec.homepage = "https://github.com/nettofarah" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "graphql", '~> 1.0', '>= 1.0.0' spec.add_development_dependency "bundler", "~> 1.11" spec.add_development_dependency "sqlite3", "~> 1.3", ">= 1.3.12" spec.add_development_dependency "appraisal", "~> 2.1.0", ">= 2.1.0" spec.add_development_dependency "byebug", "~> 9.0.6", ">= 9.0.6" spec.add_development_dependency "activerecord", "~> 5.0" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" end
RSpec.shared_context "dummy provider" do before(:each) do if defined? ::DiscourseChat::Provider::DummyProvider ::DiscourseChat::Provider.send(:remove_const, :DummyProvider) end module ::DiscourseChat::Provider::DummyProvider PROVIDER_NAME = "dummy".freeze PROVIDER_ENABLED_SETTING = :chat_integration_enabled # Tie to main plugin enabled setting @@sent_messages = [] @@raise_exception = nil def self.trigger_notification(post, channel) if @@raise_exception raise @@raise_exception end @@sent_messages.push(post: post.id, channel: channel) end def self.sent_messages @@sent_messages end def self.set_raise_exception(bool) @@raise_exception = bool end end end let(:provider){::DiscourseChat::Provider::DummyProvider} end RSpec.configure do |rspec| rspec.include_context "dummy provider" end
class CommentsController < ApplicationController before_action :set_pattern def index @comments = @pattern.comments respond_to do |format| format.html format.json {render json: @comments} end end def create @comment = @pattern.comments.build(comments_params) if @comment.save render json: @comment else render "patterns/show" end end #def next # @next_comment = @comment.next # render json: @next_comment #end def show @comment = Comment.find(params[:id]) respond_to do |format| format.html format.json {render json: @comment} end end private def comments_params params.require(:comment).permit(:content) end def set_pattern @pattern = Pattern.find(params[:pattern_id]) end end
require 'rails_helper' RSpec.describe User, type: :model do describe '正常系の機能' do context 'ユーザー登録する' do it '正しく登録できること 名前:田中太郎、ユーザーネーム:たなたろ、 email: taro.tanaka@example.com' do user = FactoryBot.build(:user_tanaka) expect(user).to be_valid user.save registared_user = User.last; expect(registared_user.name).to eq('田中 太郎') expect(registared_user.email).to eq('taro.tanaka@example.com') expect(registared_user.username).to eq('たなたろ') end end context 'ユーザーをフォローする' do it '正しくフォローできること' do user1 = FactoryBot.build(:user_tanaka) user2 = FactoryBot.build(:user_suzuki) user3 = FactoryBot.build(:user_satou) user1.save user2.save user3.save user1.follow(user2) user1.follow(user3) user1.unfollow(user3) user2.follow(user1) expect(user1.following?(user2)).to be_truthy expect(user2.following?(user1)).to be_truthy expect(user1.following?(user3)).to be_falsy end end end describe '異常系の機能' do context 'ユーザー登録に失敗' do it '名前がnilのときに登録できないこと' do user = User.new(name: "", username: "たなたろ", email: "tanaka@test.co.jp") expect(user).not_to be_valid end it 'ユーザーネームがnilのときに登録できないこと' do user = User.new(name: "田中", username: "", email: "tanaka@test.co.jp") expect(user).not_to be_valid end it 'メールアドレスがnilのときに登録できないこと' do user = User.new(name: "田中", username: "たなたろ", email: "") expect(user).not_to be_valid end end end end
class CreateUnusedRestaurants < ActiveRecord::Migration def change create_table :unused_restaurants do |t| t.string :name t.string :address1 t.string :address2 t.string :town t.string :towns t.string :postcode t.string :norm_postcode t.string :phone t.string :cuisine t.string :email t.string :website t.string :image t.integer :hygiene_rating t.date :hygiene_rating_date t.decimal :longitude t.decimal :latitude t.timestamps end end end
class Admin::BaseController < ApplicationController before_filter :authenticate_user! before_filter :admin_required! def admin_required! if current_user.admin? true else render :file => "#{Rails.root}/public/401.html" end end end
# frozen_string_literal: true class OutputService class << self include InitialData def fine_print(results) prepare_results(results).each do |k, v| total_length = v.first[:from].to_s.length + ' to '.length + v.first[:from].to_s.length puts '=' * total_length puts k puts '*' * total_length v.each { |kk, _vv| puts "#{kk[:from]} to #{kk[:to]}" } puts '*' * total_length end end def prepare_results(results) results_modified = prepare_values(results) results_modified.transform_keys { |k| k.to_date.to_s } end def prepare_values(results) results.transform_values do |a| a.map do |val| next_val = (val + DateTimeService.time_fraction(INTERVAL, MIN_IN_DAY)) { from: val.strftime("%H:%M"), to: next_val.strftime("%H:%M") } end end end end end
class AddSchoolIdToUser < ActiveRecord::Migration def change add_column :users, :school_id, :integer add_column :classrooms, :school_id, :integer add_column :classrooms, :teacher_id, :integer end end
json.array!(@profiles) do |profile| json.extract! profile, :id, :client_id, :staff_id, :name, :dob, :contact_no, :work_no json.url profile_url(profile, format: :json) end
require Core::ROOT + "utils/TechniqueUsine.rb" # => Author:: Valentin, DanAurea # => Version:: 0.1 # => Copyright:: © 2016 # => License:: Distributes under the same terms as Ruby # ## ## Classe permettant de créer un contrôleur pour la vue FenetreJeuLibre ## class JeuLibreControleur < Controller ## ## Initialize ## def initialize() #charge le modèle grille loadModel("Configuration") loadModel("Grille") loadModel("Score") loadModel("Jeu") loadModel("Utilisateur") #paramètres fenêtre @title = "Sudoku - Jeu Libre" @content = {"grille" => nil} @height = 720 end ## Met à jour la grille de données ## ## @param x Position x de la case ## @param y Position y de la case ## @param value La valeur ## ## @return self ## def updateGrille(x, y, value) ## Met à jour le compteur if(@content["grille"][x][y]["value"] == nil && value != nil) @Grille.nbVides -= 1 elsif(@content["grille"][x][y]["value"] != nil && value == nil) @Grille.nbVides += 1 end @content["grille"][x][y]["value"] = value return self end ## ## Vérifie que la grille est correcte ## ## @return True si correcte sinon false ## def grilleCorrecte() @content["grille"].each_with_index do | ligne, ligneIndex | ligne.each_with_index do | colonne, colonneIndex | if(!@Grille.valeurUnique(colonne["value"], ligneIndex, colonneIndex)) return false end end end return true end ## ## Vérifie si la partie est terminée c'est à dire ## grille complète et correcte. ## ## @return ## def finPartie?() return self.getNbVides == 0 && self.grilleCorrecte() end ## ## Récupère le nombre de cases encore vides ## ## @return Nombre de cases vides ## def getNbVides() return @Grille.nbVides end ## ## Récupère seulement les valeurs de la grille ## ## @return La grille que sous forme de valeur ## def valeursGrille() grille = Array.new() @content["grille"].each_with_index do |ligne, index| grille << Array.new() ligne.each do |c| grille[index] << c["value"] end end end ## ## Action lorsque la partie est terminée, ## sauvegarde du score de l'utilisateur. ## ## @return self ## def partieTerminee() Header.pause = true @Score.creer(@content["pseudo"], @Score.difficulte, Header.score) if(@Utilisateur.partieUtilisateur?(@content["pseudo"])) @Jeu.supprimerPartie(@content["pseudo"]) end end ## ## Sauvegarde la partie dans un fichier yaml ## ## @return self ## def sauvegarder() @Jeu.chrono = Header.temps @Jeu.score = Header.score @Jeu.grille = @content["grille"] @Jeu.niveau = @Score.difficulte ## Sauvegarde la partie dans un fichier yaml au nom de l'utilisateur @Jeu.creerPartie (@content["pseudo"]) return self end ## ## Calcule les endroits possible pour une valeur ## ## @param valeur La valeur ## ## @return self ## def possibilites(valeur) possibilites = Array.new() ## Calcule les coordonnées des cases qui permettent l'unicité sur la valeur ## passée en paramètre for i in 0..8 for j in 0..8 if (@content["grille"][i][j]["editable"] && @Grille.valeurUnique(valeur, i, j) ) possibilites << [i, j] end end end return possibilites end ## ## Réinitialise la grille ## ## @return self ## def reinitialiser() grille = @content["grille"] for i in 0..8 for j in 0..8 if(grille[i][j]["editable"]) grille[i][j]["value"] = nil end end end @content["grille"] = grille return self end ## ## Calcule les candidats possibles pour chaque case ## ## @return Hash de tableau avec coordonnées des possibilités ## pour chaque chiffre ## def getCandidats candidats = Hash.new() for i in 1..9 candidats[i.to_s] = self.possibilites(i) end return candidats end ## ## Méthode à définir dans tous les cas ! ## ## @return self ## def run() ## Reprends la grille dans son état (singleton pattern) si on viens ## d'une fenêtre par le biais d'un bouton retour if(@Grille.grille != nil && !@content.has_key?("charger")) @content["grille"] = @Grille.grille ## Reprends les configurations d'un fichier elsif(@content.has_key?("charger")) donnees = @Jeu.chargerPartie(@content["pseudo"]) @content["difficulte"] = donnees["niveau"] Header.score = donnees["score"] Header.temps = donnees["chrono"] @content["grille"] = donnees["grille"] @Grille.grille = donnees["grille"] ## Reggénère une grille else @content["grille"] = @Grille.generer(@content["difficulte"]) end @content["config"] = @Configuration.getConfiguration(@content["pseudo"]) if(@Score.difficulte == nil) @Score.difficulte = @content["difficulte"] end @Grille.countNbVides @content["Techniques"] = TechniqueUsine.new() return self end end
require 'spec_helper' describe StudentGrades::Student do subject(:student) { StudentGrades::Student.new } describe '#add' do it 'adds a grade to a student' do student.add '85' student.add '76' expect(student.grades).to eq([85,76]) end end describe '#grade_average' do it 'averages the students grades' do student.grades = [88,92,65,99] expect(student.grade_average).to eq(86) end end end
class ApplicationController < ActionController::Base # :nodoc: protect_from_forgery with: :exception layout 'application' #before_action :authorize_user! helper_method :logger!, :current_user private def logger!(*args) @log = ActiveCodhab::LoggerService.new(args[:target_model], args[:user_id], args[:user_type], target_ip) @log.log!(args[:message], args[:target_id], args[:target_object], args[:critical]) end # => Metodos para gestao do :current_user def current_user_ip request.remote_ip end def authorize_user! redirect_to main_app.new_session_path unless user_authorized? end def current_user ActiveCodhab::Person::Staff.find(session[:user_id]) rescue StandardError nil end def user_authorized? !current_user.nil? || user_session_expires_at > Time.now end def user_session_expires_at Date.parse(session[:user_session_expires_at]) rescue StandardError Time.now end end
module Protip module Resource # Mixin for a resource that has an active `:destroy` action. Should be treated as private, # and will be included automatically when appropriate. module Destroyable def destroy raise RuntimeError.new("Can't destroy a non-persisted object") if !persisted? self.message = self.class.client.request path: "#{self.class.base_path}/#{id}", method: Net::HTTP::Delete, message: nil, response_type: self.class.message end end end end
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # 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. actions :create, :delete, :modify, :restore_online, :restore_offline default_action :create property :storage_system, kind_of: Hash, required: true property :snapshot_name, kind_of: String, required: true, name_property: true, callbacks: { 'Name of the snapshot should not exceed 31 characters' => lambda { |name| name.length > 0 && name.length < 32 } } property :base_volume_name, kind_of: String property :read_only, kind_of: [TrueClass, FalseClass] property :expiration_time, kind_of: Integer property :retention_time, kind_of: Integer property :expiration_unit, kind_of: String, default: 'Hours', equal_to: %w[Hours Days] property :retention_unit, kind_of: String, default: 'Hours', equal_to: %w[Hours Days] property :expiration_hours, kind_of: Integer, default: 0 property :retention_hours, kind_of: Integer, default: 0 property :online, kind_of: [TrueClass, FalseClass] property :priority, kind_of: String, default: 'MEDIUM', equal_to: %w[HIGH MEDIUM LOW] property :allow_remote_copy_parent, kind_of: [TrueClass, FalseClass] property :new_name, kind_of: String property :snap_cpg, kind_of: String property :rm_exp_time, kind_of: [TrueClass, FalseClass] property :debug, kind_of: [TrueClass, FalseClass], default: false
# Create a person class with at least 2 attributes and 2 behaviors. # Call all person methods below the class and print results # to the terminal that show the methods in action. # YOUR CODE HERE class Person attr_accessor :name, :age, :hometown def initialize(name, age, hometown) @name = name @age = age @hometown = hometown end def weekday puts "It's a weekday, #{name}. Better to get to work." end def weekend puts "It's the freakin weekend, I'm about to have me some fun!" end def rkelly if weekend puts "It's probably not cool to use this quote anymore...." end end end jacob = Person.new("Jacob", 33, "Tulsa,OK") puts "#{jacob.name} from #{jacob.hometown} is #{jacob.age} years old.\n\n" puts jacob.weekday puts jacob.weekend
class User < ActiveRecord::Base before_save { self.email = email.downcase } validates :username, presence: true, length: {minimum:3 , maximum:25}, uniqueness: {case_sensitive: false } VALID_EMAIL_REGEX= /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true,length: {maximum:105}, uniqueness: {case_sensitive: false }, format: { with: VALID_EMAIL_REGEX} has_secure_password; end
require_relative "../question" describe Question do describe "#rating_question?" do context "type is ratingquestion" do before do @question = Question.new("ratingquestion") @question.text="What is your favorite number?" end it { expect(@question.rating_question?).to be true } end context "type is not ratingquestion" do before do @question = Question.new("select") @question.text="What is your favorite number?" end it { expect(@question.rating_question?).to be false } end end end
class Admin::GuitarAttachmentsController < ApplicationController before_action :set_guitar_attachment def create @guitar_attachment = GuitarAttachment.new(guitar_attachment_params) respond_to do |format| if @guitar_attachment.save format.html { redirect_to @guitar_attachment, notice: 'Guitar attachment was successfully created.' } format.json { render :show, status: :created, location: @guitar_attachment } else format.html { render :new } format.json { render json: @guitar_attachment.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_guitar_attachment @guitar_attachment = GuitarAttachment.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def guitar_attachment_params params.require(:guitar_attachment).permit(:guitar_id, :image) end end
class CreateFormularios < ActiveRecord::Migration def self.up create_table :formularios do |t| t.string :nm_titulo t.string :nm_subtitulo t.string :desc_msg_sucesso t.integer :usuario_id t.boolean :varias_respostas, :default => true t.timestamps end end def self.down drop_table :formularios end end
module Noodle module Factories class Node def self.create(service_name, node_class_name, properties) node_class = Noodle::NodeClass.where(["service = ? and name = ?", service_name, node_class_name]).first node = Noodle::Node.new(node_class: node_class) node.from_json(properties) end end end end
class SessionsController < ApplicationController skip_before_filter :require_login def create session[:github_user_id] = env['omniauth.auth'].extra.raw_info.id session[:github_login] = env['omniauth.auth'].extra.raw_info.login session[:github_token] = env['omniauth.auth'].credentials.token if session[:next_url].nil? || session[:next_url] == '/' # redirect_to "/~#{session[:github_login]}" redirect_to '/' else redirect_to session[:next_url] end end def logout [:github_user_id, :github_login, :github_token].each { |k| session[k] = nil } redirect_to "https://github.com/logout" end end
class AddVideoHtmlToUpdate < ActiveRecord::Migration def change add_column :updates, :video_html, :string end end
class AddPetType < ActiveRecord::Migration def up add_column :pets, :pet_type, :string end end
module SheepWall class Display def initialize @history = [] @timestamps = [] end def show entity return if @history.include? entity if ENV["DEBUG"] print "[debug] Accepted: " p entity end @history << entity @timestamps << [ entity, Time.now ] case entity when Hash puts "%s %s %s %s" % [ entity[:type], entity[:client], entity[:host], entity[:cred] ] else puts entity end end end end
class CreateLinksTable < ActiveRecord::Migration[5.0] def change create_table :links do |t| t.string :url t.integer :trend_id t.timestamps(null:false) end end end
class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.string :department t.string :email t.string :name t.string :subject t.text :body t.boolean :read, default: false t.timestamps end add_index :messages, :email add_index :messages, :name add_index :messages, [:email, :name] end end
require 'rails_helper' RSpec.describe "entries/edit", :type => :request do it "show form to edit an entry with values (body and title)" do entry = Entry.create(title: "First entry", body: "Bla bla bla", author: "me XD") get edit_entry_path(entry) assert_select "form" do assert_select "input" do assert_select "[name=?]", "entry[title]" assert_select "[value=?]", entry.title end assert_select "textarea" do assert_select "[name=?]", "entry[body]" end end assert_select "a[href=?]", root_path end end
class AddRatingToTrails < ActiveRecord::Migration[5.0] def change add_column :trails, :rating, :integer end end
require_relative '../phase2/controller_base' require 'active_support/core_ext' require 'erb' require 'active_support/inflector' module Phase3 class ControllerBase < Phase2::ControllerBase # use ERB and binding to evaluate templates # pass the rendered html to render_content def render(template_name) template = File.read("views/#{self.class.name.underscore}/#{template_name}.html.erb") erb_template = ERB.new(template) html_template = erb_template.result(binding) render_content(html_template, "text/html") end end end
require 'spec_helper' describe Api::V2::CountsController do before(:each) do post api_sessions_path, {:user => {:email => 'gxbsst@gmail.com', :password => 'wxh51448888'}}, {'Accept' => 'application/vnd.iwine.com; version=2'} @user = User.find_by_email('gxbsst@gmail.com') @response = response @parsed_body = JSON.parse(@response.body) @token = @parsed_body["user"]['auth_token'] end describe "#index" do before(:each) do get api_counts_path, {:countable_type => 'Note', :countable_id => 1}, {'Accept' => 'application/vnd.iwine.com; version=2'} @response = response @parsed_body = JSON.parse(@response.body) end it { @parsed_body["success"].should == 1} it { @parsed_body["resultCode"].should == 200} it { @parsed_body['data'].should include("likes_count") } it { @parsed_body['data'].should include("comments_count") } end describe "#notes" do before(:each) do post api_comments_path, {:notes_comment => {:commentable_id => 10, :commentable_type => 'Note', :body => "here is comment body"}, :auth_token => @token}, {'Accept' => 'application/vnd.iwine.com; version=2'} post api_votes_path, {:id => 1, :votable_type => 'Note', :auth_token => @token}, {'Accept' => 'application/vnd.iwine.com; version=2'} get notes_api_counts_path, {:ids => '1,2,10', :user_id => 2}, {'Accept' => 'application/vnd.iwine.com; version=2'} @response = response @parsed_body = JSON.parse(@response.body) end it { @parsed_body["success"].should == 1} it { @parsed_body["resultCode"].should == 200} it { @parsed_body['data'].should include("likes_count") } it { @parsed_body['data'].should include("comments_count") } end end
json.array!(@empregadors) do |empregador| json.extract! empregador, :id, :nome, :endereco, :numero json.url empregador_url(empregador, format: :json) end
class User < ActiveRecord::Base has_many :reservations has_many :listings include Clearance::User end
# The Luhn formula is a simple checksum formula used to validate a variety of identification numbers, such as credit card # numbers and Canadian Social Insurance Numbers. # # The formula verifies a number against its included check digit, which is usually appended to a partial number to generate # the full number. This number must pass the following test: # # - Counting from rightmost digit (which is the check digit) and moving left, double the value of every second digit. # - For any digits that thus become 10 or more, subtract 9 from the result. # • 1111 becomes 2121. # • 8763 becomes 7733 (from 2×6=12 → 12-9=3 and 2×8=16 → 16-9=7). # # - Add all these digits together. # • 1111 becomes 2121 sums as 2+1+2+1 to give a check digit of 6. # • 8763 becomes 7733, and 7+7+3+3 is 20. # # If the total ends in 0 (put another way, if the total modulus 10 is congruent to 0), then the number is valid according to # the Luhn formula; else it is not valid. So, 1111 is not valid (as shown above, it comes out to 6), while 8763 is valid # (as shown above, it comes out to 20). # # Write a program that, given a number # - Can check if it is valid per the Luhn formula. This should treat, for example, "2323 2005 7766 3554" as valid. # - Can return the checksum, or the remainder from using the Luhn method. # - Can add a check digit to make the number valid per the Luhn formula and return the original number plus that digit. This # should give "2323 2005 7766 3554" in response to "2323 2005 7766 355". # # About Checksums: # # A checksum has to do with error-detection. There are a number of different ways in which a checksum could be calculated. # # When transmitting data, you might also send along a checksum that says how many bytes of data are being sent. That means # that when the data arrives on the other side, you can count the bytes and compare it to the checksum. If these are different, # then the data has been garbled in transmission. # # In the Luhn problem the final digit acts as a sanity check for all the prior digits. Running those prior digits through a # particular algorithm should give you that final digit. # # It doesn't actually tell you if it's a real credit card number, only that it's a plausible one. It's the same thing with the # bytes that get transmitted -- you could have the right number of bytes and still have a garbled message. So checksums are a # simple sanity-check, not a real in-depth verification of the authenticity of some data. It's often a cheap first pass, and # can be used to quickly discard obviously invalid things.
# This is a test file used for the test driven development process. Each test ensures the URL of each page can be accessed, # and the title of each page is correct. require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title1 = "CS2012 Assignment 2: Earthquake Data App" end test "should get home" do get root_path assert_response :success assert_select "title", "#{@base_title1}" end test "should get donate" do get donate_path assert_response :success assert_select "title", "Donate | #{@base_title1}" end test "should get about" do get about_path assert_response :success assert_select "title", "About | #{@base_title1}" end test "should get contact" do get contact_path assert_response :success assert_select "title", "Contact | #{@base_title1}" end end
control "M-1.2" do title "Ensure the container host has been Hardened (Not Scored)" desc " Description: Containers run on a Linux host. A container host can run one or more containers. It is of utmost importance to harden the host to mitigate host security misconfiguration. Rationale: You should follow infrastructure security best practices and harden your host OS. Keeping the host system hardened would ensure that the host vulnerabilities are mitigated. Not hardening the host system could lead to security exposures and breaches. " impact 1 tag "ref": ["1. https://docs.docker.com/engine/security/security/", "2. https://learn.cisecurity.org/benchmarks", "3. https://docs.docker.com/engine/security/security/#other-kernel-security-features", "4. https://grsecurity.net/", "5. https://en.wikibooks.org/wiki/Grsecurity", "6. https://pax.grsecurity.net/", "7. http://en.wikipedia.org/wiki/PaX"] tag "applicability": "Linux Host OS" tag "cis_id": "1.2" tag "cis_control": ["3"] tag "cis_level": 1 tag "check": "Audit:\nEnsure that the host specific security guidelines are followed. Ask the system administrators which security benchmark does current host system comply with. Ensure that the host systems actually comply with that host specific security benchmark." tag "fix": "Remediation:\nYou may consider various CIS Security Benchmarks for your container host. If you have other security guidelines or regulatory requirements to adhere to, please follow them as suitable in your environment.\nAdditionally, you can run a kernel with grsecurity and PaX. This would add many safety checks, both at compile-time and run-time. It is also designed to defeat many exploits and has powerful security features. These features do not require Docker-specific configuration, since those security features apply system-wide, independent of containers.\nImpact:\nNone.\nDefault Value:\nBy default, host has factory settings. It is not hardened." end
class ProductArtist < ApplicationRecord belongs_to :product belongs_to :artist end
# This class is a rails controller for calendar objects # Author:: Mark Grebe # Copyright:: Copyright (c) 2013 Mark Grebe # License:: Distributes under the same terms as Ruby # Developed for Master of Engineering Project # University of Colorado - Boulder - Spring 2013 class CalendarsController < ApplicationController before_filter :signed_in_user before_filter :correct_user, only: [:edit, :show, :update] # Start creating a new calendar def new @calendar = Calendar.new @calendar.title = "" end # Save a new calendar def create @calendar = Calendar.new(params[:calendar]) @calendar.user_id = current_user.id @calendar.default = false if @calendar.save redirect_to request.referer else flash[:error] = "Duplicate Calendar Title Not Allowed!" redirect_to request.referer end end # Setup to edit a calendar def edit @calendar = Calendar.find_by_id(params[:id]) respond_to do |format| format.html format.js end end # Handle user clicking to show or not show a calendar def show @calendar = Calendar.find_by_id(params[:id]) @calendar.displayed = params[:displayed] if @calendar.save redirect_to request.referer else flash[:error] = "Error showing/hiding calendar!" redirect_to request.referer end end # Update an edited calendar def update @calendar = Calendar.find_by_id(params[:id]) if @calendar.update_attributes(params[:calendar]) redirect_to request.referer else flash[:error] = "Calendar update failed!" redirect_to request.referer end end # Delete a calendar def destroy @calendar = Calendar.find_by_id(params[:id]) @calendar.destroy redirect_to request.referer end # Utility AJAX method used to determine if calendar title is unique def check id = params[:calcheck].split('/').last.to_i cal = Calendar.where(id: id) # For invalid calendars or unchanged titles, just return valid if cal.size != 0 and cal[0].title == params[:calendar][:title] response = true else # Check both local and shared calendar names cals = Calendar.where(user_id: current_user.id, title: params[:calendar][:title]) subs = Subscription.where(user_id: current_user.id, title: params[:calendar][:title]) response = (cals.size == 0 and subs.size == 0) end respond_to do |format| format.json { render :json => response } end end private # Valaidte the user, making sure they own the calendar being accessed def correct_user @calendar = current_user.calendars.find_by_id(params[:id]) redirect_to root_url if @calendar.nil? end end
#!/usr/bin/env ruby # https://en.wikipedia.org/wiki/Monty_Hall_problem class MontyHallSimulator attr_reader :switcher_total_wins attr_reader :stayer_total_wins attr_reader :chaosmonkey_total_wins attr_reader :random def initialize(num_games) @num_games = num_games.to_i put_greeting @printer = ProgressBarPrinter.new(1000) @random = Random.new end def put_greeting puts "Suppose you're on a game show, and you're given the choice of three doors: " puts "Behind one door is a car; behind the others, goats. [Assume: you want the car]" puts "- You pick a door, say No. 1" puts "- Then the host, who knows what's behind the doors, opens another door, " puts " which has a goat.\n\n" puts "He then says to you, \"Do you want to pick your door or the other?\"\n\n" puts "Q: Is it to your advantage to switch your choice?\n\n" @switcher_total_wins = 0 puts '- Switcher always switches' @stayer_total_wins = 0 puts '- Stayer never switches' @chaosmonkey_total_wins = 0 puts '- Chaosmonkey chooses at random between switching or not' puts "\nI'll run the simulation #{@num_games} times:\n\n" end # The players always initially choose Door 1 def run_one_game # the car is actually in any of three doors: car_location = random.rand(1..3) revealed_goat_door = host_opens_door(car_location) other_choice = remaining_closed_door(revealed_goat_door) if (car_location == other_choice) @switcher_total_wins += 1 end # Stayer will stay (Door 1) if (car_location == 1) @stayer_total_wins += 1 end # Chaosmonkey will either stay (Door 1) or switch chaosmonkey_choice = (random.rand(0..1) == 0) ? other_choice : 1 if (car_location == chaosmonkey_choice) @chaosmonkey_total_wins += 1 end end # The host opens a door, either Door 2 or Door 3 # @param [Integer] car_location which is 1, 2, or 3 # @return [Integer] goat_door revealed by the host, which will be 2 or 3 def host_opens_door(car_location) case car_location when 2 3 # the only unpicked door with a goat when 3 2 # the only unpicked door with a goat else random.rand(2..3) end end # @param [Integer] opened_door which is 2 or 3 # @return [Integer] non_opened_door which is 3 or 2, respectively def remaining_closed_door(opened_door) return opened_door == 2 ? 3 : 2 end # printer utility to print the percent of the wins to 4 decimal places # @param [Integer] wins out of @num_games # @return [Float] percentage of games won def percent_wins(wins) ((wins.to_f / @num_games.to_f) * 100).round(4) end def print_totals @num_games.times do run_one_game @printer.print_progress_bar end puts "\n\n" puts "The Switcher won the car #{percent_wins(switcher_total_wins)}% of the time" puts "The Stayer won the car #{percent_wins(stayer_total_wins)}% of the time" puts "The ChaosMonkey won the car #{percent_wins(chaosmonkey_total_wins)}% of the time" puts "\n\n" end class ProgressBarPrinter def initialize(how_often) @sample_period = how_often puts "I'll print a dot every #{how_often} tests:\n\n" @current_count = 0 end # print the progress bar every @sample_period times def print_progress_bar if @current_count % @sample_period == 0 print '.' $stdout.flush end @current_count += 1 end end end MontyHallSimulator.new(ARGV[0]).print_totals
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :tenant do title "MyString" firstname "MyString" surname "MyString" dateofbirth "2013-07-13" telno 1 contact_type "MyString" email "MyString" end end
class AddSpotsToPictures < ActiveRecord::Migration def change add_column :pictures, :spot_id, :integer, index: true end end
require "rails_helper" RSpec.describe "Order", type: :system, js:true do let!(:product) { create(:product) } before do visit "/" click_button "Add to Cart" within("#aside-cart") do expect(page).to have_content product.title expect(page).to have_content "1 times;" end end context "現金の場合" do example "注文できること" do click_button "Checkout" fill_in "Name", with: "name" fill_in "Address", with: "address" fill_in "Email", with: "mail@example.com" select "Cash", from: "order_pay_type" click_button "Place Order" expect(page).to have_content /thank you/i end end context "注文書の場合" do example "注文できること" do click_button "Checkout" fill_in "Name", with: "name" fill_in "Address", with: "address" fill_in "Email", with: "mail@example.com" select "Purchase order", from: "order_pay_type" click_button "Place Order" expect(page).to have_content /thank you/i end end context "クレジットカードの場合", vcr: true do example "注文できること" do click_button "Checkout" fill_in "Name", with: "name" fill_in "Address", with: "address" fill_in "Email", with: "mail@example.com" select "Credit card", from: "order_pay_type" click_button "Place Order" fill_in "number", with: "4242424242424242" fill_in "cvc", with: "123" fill_in "exp_month", with: "03" fill_in "exp_year", with: "2099" click_button "Pay" expect(page).to have_content /thank you/i end end end
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '新規商品出品' do context '新規出品できるとき' do it '全項目存在すれば出品できる' do expect(@item).to be_valid end it 'priceが300以上9999999以下であれば出品できる' do @item.price = 300 expect(@item).to be_valid @item.price = 9_999_999 expect(@item).to be_valid end end context '商品出品できないとき' do it 'nameが空では出品できない' do @item.name = '' @item.valid? expect(@item.errors.full_messages).to include("Name can't be blank") end it 'descriptionが空では出品できない' do @item.description = '' @item.valid? expect(@item.errors.full_messages).to include("Description can't be blank") end it 'category_idが0では出品できない' do @item.category_id = 0 @item.valid? expect(@item.errors.full_messages).to include('Category must be other than 0') end it 'status_idが0では出品できない' do @item.status_id = 0 @item.valid? expect(@item.errors.full_messages).to include('Status must be other than 0') end it 'shipping_charges_idが0では出品できない' do @item.shipping_charges_id = 0 @item.valid? expect(@item.errors.full_messages).to include('Shipping charges must be other than 0') end it 'shipping_area_idが0では出品できない' do @item.shipping_area_id = 0 @item.valid? expect(@item.errors.full_messages).to include('Shipping area must be other than 0') end it 'shipping_days_idが0では出品できない' do @item.shipping_days_id = 0 @item.valid? expect(@item.errors.full_messages).to include('Shipping days must be other than 0') end it 'priceが空では出品できない' do @item.price = '' @item.valid? expect(@item.errors.full_messages).to include("Price can't be blank") end it 'priceが300未満では出品できない' do @item.price = 299 @item.valid? expect(@item.errors.full_messages).to include('Price must be greater than or equal to 300') end it 'priceが10000000以上では出品できない' do @item.price = 10_000_000 @item.valid? expect(@item.errors.full_messages).to include('Price must be less than or equal to 9999999') end it 'priceが全角では出品できない' do @item.price = '1000' @item.valid? expect(@item.errors.full_messages).to include('Price is not a number') end it 'priceが半角英数字混合では出品できない' do @item.price = '1000a' @item.valid? expect(@item.errors.full_messages).to include('Price is not a number') end it 'priceが半角英語だけでは出品できない' do @item.price = 'abcd' @item.valid? expect(@item.errors.full_messages).to include('Price is not a number') end it 'ユーザーが紐付いていなければ出品できない' do @item.user = nil @item.valid? expect(@item.errors.full_messages).to include('User must exist') end end end end
class TeamRandomizer attr_reader :error_message attr_reader :teams def initialize @heads = [] @teams = [] @head_count = 0 @team_count = 0 @loose_head_count = 0 @team_head_count = 0 @error_message = '' @testnames = "Alfa,Bravo,Coca,Delta,Echo,Foxtrot,Golf,Hotel,India,Juliett,Kilo,Lima,Metro,Nectar,Oscar,Papa,Quebec,Romeo,Sierra,Tango,Union,Victor,Whisky,Extra,Yankee,Zulu" end def generate(names, team_count, loose_at_random = 1) # Uncomment line below to use dummy data. # names = @testnames # -------------------------------------- @team_count = team_count.to_i # return unless prep_names_array?(names) unless prep_names_array?(names) @error_message = gen_err_msg return end prep_teams_array(@team_count) get_team_head_count get_loose_head_count make_teams assign_loose_heads_in_team(loose_at_random) puts "Team created success!" @teams.count.times { |num| print @teams[num],"\n" } end private def prep_names_array?(names) @heads.clear unless @heads.nil? @heads = names.split(',') @heads.map! { |name| name.strip } @heads.delete('') @head_count = @heads.count @team_count > @head_count || @team_count < 1 ? false : true end def gen_err_msg return 'Too many teams or no names entered.' if @team_count > @head_count return 'Invalid team number.' if @team_count < 1 return 'No names entered.' if @heads == '' end def prep_teams_array(team_count) @teams.clear unless @teams.nil? team_count.times {|team_num| @teams[team_num] = []} end def make_teams @teams.count.times {|team_num| @team_head_count.times {|head_num| @teams[team_num] << shift_random_name } } end def get_team_head_count @team_head_count = @head_count / @team_count end def get_loose_head_count @loose_head_count = @team_count % @head_count end def assign_loose_heads_in_team(at_random) @heads.count.times {|head_num| @teams[at_random == 1 ? rand(0...@team_count) : head_num] << shift_random_name } end def shift_random_name @heads.delete(@heads.sample) unless @heads.sample.nil? end end
# frozen_string_literal: true RSpec.describe 'Reset password' do resource 'Reset password request' do route '/api/v1/reset_password', 'Reset password' do post 'Reset password' do with_options scope: %i[data attributes] do parameter :email, required: true end let(:email) { FFaker::Internet.email } context 'when emails exists' do before do create(:user, email: email) end example 'Responds with 202' do do_request expect(status).to eq(202) end end context 'when email does not exist' do example 'Responds with 202', document: false do do_request expect(status).to eq(202) end end end end end end
require 'spec_helper' describe Issue do before :each do @project = Factory(:project) @attr = { :title => "Major Bug", :content => "Something important doesn't seem to work", :status => "new", :priority => 1 } end it "should create a new instance given valid attributes" do @project.issues.create! @attr end describe "project associations" do before :each do @issues = @project.issues.create @attr end it "should have a project attribute" do @issues.should respond_to(:project) end it "should have the righ associated project" do @issues.project_id.should == @project.id @issues.project.should == @project end end end
class Ositem < ApplicationRecord has_many :dataositems has_many :t3ds, through: :dataositems end
puts "\n Newline (0x0a) \r Carriage return (0x0d) \f Formfeed (0x0c) \b Backspace (0x08) \a Bell (0x07) \e Escape (0x1b) \s Space (0x20) \nnn Octal notation (n being 0-7) \xnn Hexadecimal notation (n being 0-9, a-f, or A-F) \cx, \C-x Control-x \M-x Meta-x (c | 0x80) \M-\C-x Meta-Control-x \x Character x "
require_relative "../Modules" require_relative "../Piece" class Queen < Piece attr_reader :symbol, :color include Slidable def initialize(name, start_pos, color, board) super(name, start_pos, color, board) @symbol = :Q @color = color end def move_dirs return [[-1,0], [0,1], [1,0], [0,-1], [1, 1], [-1, -1], [-1, 1], [1, -1]] end def to_s "Q" end end
module V1::ImgurApiWrapperHelper def handleRequest(response, errorMsg) if(response.status == 200) render :json => response.body else puts response render json: { :error => errorMsg }.to_json, :status => response.status end rescue JSON::ParserError render json: { #todo figure out if this is a good way to return errors :error => 'Response was not valid json' }.to_json, :status => 500 end end
class StaticPagesController < ApplicationController before_action :logged_in_user, except: [:signup] def home @photos = Photo.all.reverse end def help end def about end def tutorial render "static_pages/tutorial_page_#{params[:id]}", layout: "home_layout" end def signup render layout: 'home_layout' end end
describe Exporter::FieldContactNames do include_context "exporter" describe "minimal field_contact_name" do let!(:field_contact_name) { create(:field_contact_name) } it "exports" do export expect(record["fc_num"]).to eql("FC123") expect(record["field_contact_fc_num"]).to eql("FC123") end end describe "maximal field_contact_name" do let!(:field_contact_name_kirk) { create(:field_contact_name_kirk) } it "exports" do export expect(record["fc_num"]).to eql("FC234") expect(record["race"]).to eql("black") expect(record["age"]).to eql("25") expect(record["build"]).to eql("heavy") expect(record["hair_style"]).to eql("afro") expect(record["skin_tone"]).to eql("brown") expect(record["ethnicity"]).to eql("not of hispanic origin") expect(record["other_clothing"]).to eql("blue hoodie/ jeans") expect(record["license_state"]).to eql("ma") expect(record["license_type"]).to eql("id only") expect(record["frisked_searched"]).to eql("true") expect(record["gender"]).to eql("man") expect(record["field_contact_fc_num"]).to eql("FC234") end end end
module AresClient # model pro praci se zakladnim vypisem ARES class Records attr_accessor :ic, :basic_output, :response, :http_response include HTTParty base_uri 'http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi' def initialize(ic=nil) @ic = ic if ic end def fetch self.http_response = self.class.get("?ico=#{ic}&jazyk=cz&aktivni=false&ver=1.0.2") self.response = http_response.parsed_response end def basic_output response['Ares_odpovedi']['Odpoved']['Vypis_basic'] end def name basic_output['Obchodni_firma']['__content__'] end def dic basic_output['DIC']['__content__'] if basic_output['DIC'] end def address_code basic_output['Adresa_ARES']['Adresa_UIR']['Kod_adresy'] if basic_output['Adresa_ARES']['Adresa_UIR'] end def building_code basic_output['Adresa_ARES']['Adresa_UIR']['Kod_objektu'] if basic_output['Adresa_ARES']['Adresa_UIR'] end def established_on basic_output['Datum_vzniku'] end def self.find_by_ic(ic) record = self.new(ic) record.fetch record end def self.from_xml(xml) request = new request.response = MultiXml.parse(xml) request.ic = request.basic_output['ICO']['__content__'] request end end end
require 'rails_helper' describe CurrentCharacter do describe "#id" do it "returns the id of the character" do character = Character.create current_character = CurrentCharacter.new(character) expect(current_character.id).to eq character.id end end describe "#player_name" do it "returns the name of the character's player" do player = Player.create name: "Player One" character = Character.create player: player current_character = CurrentCharacter.new(character) expect(current_character.player_name).to eq "Player One" end end describe "#current_picks" do it "returns the current picks for the character" do character = Character.create week = Week.create number: 1 team = Team.create character.picks.create week: week, team: team current_character = CurrentCharacter.new(character) expect(current_character.current_picks.count).to eq 1 current_pick = current_character.current_picks.first expect(current_pick.week_number).to eq week.number expect(current_pick.team_id).to eq team.id end end end
require "spec_helper" describe Item do describe "Item.rate(item_id, incoming_rating)" do it "changes an items rating" do item = Item.new item.times_rated = 0 item.save! Item.rate(item.id, 5) item = Item.find(item.id) expect(item.times_rated).to eq 1 expect(item.rating).to eq 5 end it "increments an items rating" do item = Item.new item.times_rated = 1 item.rating = 3 item.save! Item.rate(item.id, "5") item = Item.find(item.id) expect(item.times_rated).to eq 2 expect(item.rating).to eq 4 end it "changes items that already have multiple ratings" do item = Item.new item.times_rated = 49 item.rating = 4 item.save! Item.rate(item.id, 1) item = Item.find(item.id) expect(item.times_rated).to eq 50 expect(item.rating).to eq 3.94 end it "ignores improper ratings" do item = Item.new item.times_rated = 1 item.rating = 3 item.save! Item.rate(item.id, "45") item = Item.find(item.id) expect(item.times_rated).to eq 1 expect(item.rating).to eq 3 end end end
# encoding: UTF-8 module API module V1 module Games class RelatedItems < API::V1::Base helpers API::Helpers::V1::GamesHelpers before do authenticate_user end namespace :games do namespace :related_items do desc "Create a new game GameRelatedItem for user" params do requires :game, type: Hash do requires :columns, type: Array end end post do service = execute_service('GameRelatedItems::CreateService', current_user, params) response_for_create_service(service, :game_related_item) end route_param :id do desc "Updates owned game GameRelatedItem" put do game = find_game(current_user, params[:id], :related_item) service = execute_service('GameRelatedItems::UpdateService', game, current_user, params) response_for_update_service(service, :game_related_item) end desc "Delete owned user game GameRelatedItem" delete do game = find_game(current_user, params[:id], :related_item) service = execute_service('GameRelatedItems::DeleteService', game, current_user, params) response_for_delete_service(service, :game_related_item) end end end end end end end end
class AddRestaurantIDtoDeals < ActiveRecord::Migration def change add_column :deals, :restaurant_id, :integer end end
# frozen_string_literal: true class Rubocop < Aid::Script def self.description 'Runs rubocop against the codebase' end def self.help <<~HELP Usage: #{colorize(:green, '$ aid rubocop')} - runs all the cops #{colorize(:green, '$ aid rubocop fix')} - auto-fixes any issues HELP end def run step 'Running Rubocop' do cmd = 'bundle exec rubocop' cmd << ' -a' if auto_fix? system! cmd end end private def auto_fix? argv.first == 'fix' end end
class Message < ApplicationRecord include Rails.application.routes.url_helpers belongs_to :reporting_relationship, class_name: 'ReportingRelationship', foreign_key: 'reporting_relationship_id' belongs_to :original_reporting_relationship, class_name: 'ReportingRelationship', foreign_key: 'original_reporting_relationship_id' belongs_to :like_message, class_name: 'Message', foreign_key: 'like_message_id' has_one :client, through: :reporting_relationship has_one :user, through: :reporting_relationship has_many :attachments, dependent: :nullify before_validation :set_original_reporting_relationship, on: :create validates :send_at, presence: { message: "That date didn't look right." } validates :body, presence: { unless: ->(message) { message.attachments.present? || message.inbound } } validates :reporting_relationship, presence: true validates :original_reporting_relationship, presence: true validates_datetime :send_at, before: :max_future_date validates :type, exclusion: { in: %w[Message] } validates :body, length: { maximum: 1600 } validate :same_reporting_relationship_as_like_message scope :inbound, -> { where(inbound: true) } scope :outbound, -> { where(inbound: false) } scope :unread, -> { where(read: false) } scope :scheduled, -> { where('send_at >= ?', Time.zone.now).order('send_at ASC') } scope :messages, -> { where(type: [TextMessage.to_s, CourtReminder.to_s]) } class TransferClientMismatch < StandardError; end INBOUND = 'inbound'.freeze OUTBOUND = 'outbound'.freeze READ = 'read'.freeze UNREAD = 'unread'.freeze ERROR = 'error'.freeze def self.create_client_edit_markers(user:, phone_number:, reporting_relationships:, as_admin:) if as_admin && user.admin user_full_name = I18n.t('messages.admin_user_description') user_id = nil else user_full_name = user.full_name user_id = user.id end display_phone_number = PhoneNumberParser.format_for_display(phone_number) reporting_relationships.each do |rr| message_body = if rr.user_id == user_id I18n.t( 'messages.phone_number_edited_by_you', new_phone_number: display_phone_number ) else I18n.t( 'messages.phone_number_edited', user_full_name: user_full_name, new_phone_number: display_phone_number ) end ClientEditMarker.create!( reporting_relationship: rr, body: message_body ) end end def self.create_transfer_markers(sending_rr:, receiving_rr:) raise TransferClientMismatch unless sending_rr.client == receiving_rr.client TransferMarker.create!( reporting_relationship: sending_rr, body: I18n.t( 'messages.transferred_to', user_full_name: receiving_rr.user.full_name ) ) TransferMarker.create!( reporting_relationship: receiving_rr, body: I18n.t( 'messages.transferred_from', user_full_name: sending_rr.user.full_name, client_full_name: sending_rr.client.full_name ) ) true end def self.create_conversation_ends_marker(reporting_relationship:, full_name:, phone_number:) last_message_send_at = reporting_relationship.messages.messages.order(send_at: :desc).first&.send_at return false if last_message_send_at.nil? ConversationEndsMarker.create!( reporting_relationship: reporting_relationship, body: I18n.t( 'messages.conversation_ends', full_name: full_name, phone_number: phone_number ), send_at: last_message_send_at + 1.second ) true end def self.create_merged_with_marker(reporting_relationship:, from_full_name:, to_full_name:, from_phone_number:, to_phone_number:) MergedWithMarker.create!( reporting_relationship: reporting_relationship, body: I18n.t( 'messages.merged_with', from_full_name: from_full_name, from_phone_number: from_phone_number, to_full_name: to_full_name, to_phone_number: to_phone_number ) ) true end def self.create_from_twilio!(twilio_params) from_phone_number = twilio_params[:From] to_phone_number = twilio_params[:To] department = Department.find_by(phone_number: to_phone_number) begin client = Client.create!( phone_number: from_phone_number, last_name: from_phone_number, users: [department.unclaimed_user] ) rescue ActiveRecord::RecordInvalid client = Client.find_by(phone_number: from_phone_number) user = department.users .active .joins(:reporting_relationships) .order('reporting_relationships.active DESC') .order('reporting_relationships.updated_at DESC') .find_by(reporting_relationships: { client: client }) user ||= department.unclaimed_user else user = department.unclaimed_user end rr = ReportingRelationship.find_or_create_by(user: user, client: client) new_message = TextMessage.new( reporting_relationship: rr, inbound: true, twilio_sid: twilio_params[:SmsSid], twilio_status: twilio_params[:SmsStatus], body: twilio_params[:Body], send_at: Time.current ) twilio_params[:NumMedia].to_i.times.each do |i| attachment = Attachment.new attachment.update_media(url: twilio_params["MediaUrl#{i}"]) new_message.attachments << attachment end new_message.save! dept_rrs = ReportingRelationship.where(client: client, user: department.users) if user == department.unclaimed_user && Message.where(reporting_relationship: dept_rrs).count <= 1 send_unclaimed_autoreply(rr: rr) end new_message end def analytics_tracker_data { client_id: client.id, message_id: id, message_length: body.length, current_user_id: user.id, attachments_count: attachments.count, message_date_scheduled: send_at, message_date_created: created_at, client_active: client.active(user: user), first_message: first?, created_by: created_by_type } end def marker? [CourtReminder.to_s, TextMessage.to_s].exclude? type end def transfer_marker? type == TransferMarker.to_s end def client_edit_marker? type == ClientEditMarker.to_s end def conversation_ends_marker? type == ConversationEndsMarker.to_s end def merged_with_marker? type == MergedWithMarker.to_s end def past_message? return false if send_at.nil? if send_at < time_buffer errors.add(:send_at, I18n.t('activerecord.errors.models.message.attributes.send_at.on_or_after')) true else false end end def first? reporting_relationship.messages.order(send_at: :asc).first == self end def any_image_attachments? attachments.map(&:image?).reduce(:|) end def self.send_unclaimed_autoreply(rr:) now = Time.zone.now unclaimed_response = rr.department.unclaimed_response unclaimed_response = I18n.t('message.unclaimed_response') if unclaimed_response.blank? message = TextMessage.create!( body: unclaimed_response, inbound: false, read: true, reporting_relationship: rr, send_at: now ) message.send_message end def send_message return if sent || send_at > (Time.zone.now + APP_CONFIG['scheduled_message_rate'].minutes) MessageBroadcastJob.perform_now(message: self) ScheduledMessageJob.set(wait_until: send_at).perform_later(message: self) end private def same_reporting_relationship_as_like_message return unless like_message errors.add(:like_message, :different_reporting_relationship) if like_message.reporting_relationship != reporting_relationship end def positive_template_type body if like_message.present? end def set_original_reporting_relationship self.original_reporting_relationship = reporting_relationship end def time_buffer Time.current - 5.minutes end def max_future_date Time.current + 1.year end def created_by_type if type == CourtReminder.to_s 'auto-uploader' elsif type == TextMessage.to_s if inbound 'client' else 'user' end end end end
MagickTitle::Options.class_eval do # Alias the defaults for use later alias :standard_defaults :defaults # Overwrite defaults to include the attribute option def defaults standard_defaults.merge(:attribute => :title) end end
Pod::Spec.new do |s| s.name = 'PhilipsHueiOS' s.version = '1.1.3' s.license = 'Copyright (c) 2012- 2013, Philips Electronics N.V. All rights reserved.' s.summary = 'The Software Development Kit for Philips Hue on iOS' s.homepage = 'https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX' s.requires_arc = true s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.8' # We can use the official PhilipsHue SDK once we confirm everything is working with the podfile and then do a pull request. s.source = { :git => 'git@github.com:objectiveSee/PhilipsHueSDK-iOS-OSX.git', :tag => 'v1.1.3beta' } s.dependency 'CocoaLumberjack', '~> 1.8' s.vendored_frameworks = "HueSDK_iOS.framework" s.xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => "'${PODS_ROOT}/PhilipsHueiOS/Frameworks/HueSDK_iOS.framework'" } s.compiler_flags = '-ObjC' end
class Candidate < ApplicationRecord belongs_to :job belongs_to :user, -> { where.not role: 'company_admin' } end
class SessionsController < ApplicationController layout "login" def new # render the login form end def create @user = User.find_by("LOWER(email) = ?", user_params[:email].downcase) if @user.present? && @user.authenticate(user_params[:password]) cookies.permanent.signed[:user_id] = @user.id flash[:success] = "You've been successfully logged in" redirect_to dashboard_path else flash[:error] = "Incorrect email/password" redirect_to login_path end end def destroy cookies.delete(:user_id) flash[:success] = "You've been successfully logged out" redirect_to login_path end private def user_params params.require(:user).permit(:email, :password) end end
require 'flip_the_switch/generator/base' require 'plist' module FlipTheSwitch module Generator class Plist < Base def generate ::Plist::Emit.save_plist(feature_states, output_file) end private def output_file File.join(output, 'Features.plist') end end end end
# encoding: utf-8 class Zone attr_accessor :objects def initialize(&block) @objects = Array.new instance_eval(&block) end def objects(&block) if block_given? instance_eval(&block) else @objects end end def add(object) @objects << object end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Milestoner::Errors::Base do subject(:error) { described_class.new } describe "#message" do it "answers default message" do expect(error.message).to eq("Invalid Milestoner action.") end end end
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # 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. module HP module Cloud class CLI < Thor map 'containers:set' => 'metadata:set' desc "metadata:set <name> <attribute> <value>", "Set attributes on a object." long_desc <<-DESC Set metadata values for containers and objects. Container metadata keys generally begin with 'X-Container-Meta-' and some other special metadata values you can set for containers include: #{RemoteResource.VALID_CONTAINER_META} Object metadata keys generally begin with 'X-Object-Meta-' and some other special metadata values you can set for objects include: #{RemoteResource.VALID_OBJECT_META} Check http://docs.hpcloud.com/api/object-storage/ for up to date changes on the valid keys and values. Unfortunately, the server may positively acknowledge the setting of invalid keys. It may be best to query for the value after setting it to verify the set worked. Examples: hpcloud metadata :my_container "X-Container-Meta-Web-Index" index.htm # Set the attribute 'X-Container-Meta-Web-Index' to index.htm hpcloud metadata:set :my_container/objay.txt X-Object-Meta-Key metavalue # Set the attribute 'X-Object-Meta-Key' to metavalue hpcloud metadata:set :my_container/objay.txt Content-Type text/plain # Set the attribute 'Content-Type' to text/plain DESC CLI.add_common_options define_method "metadata:set" do |name, attribute, value| cli_command(options) { resource = ResourceFactory.create(Connection.instance.storage, name) unless resource.head @log.fatal resource.cstatus end unless resource.valid_metadata_key?(attribute) @log.warn "Metadata key appears to be invalid and your request may be ignored" end resource.set_metadata(attribute, value) @log.display "The attribute '#{attribute}' with value '#{value}' was set on object '#{name}'." } end end end end
class ChangeFiguresCorrectTableName < ActiveRecord::Migration[5.1] def change rename_table :name, :figures end end
class Rating < ApplicationRecord validates :value, :inclusion => 1..5 belongs_to :user belongs_to :post end
module TicTacToeGame class Play def initialize(board) @board = board end def possible_moves @board.map.with_index { |piece, idx| piece == "-" ? idx : nil }.compact end end end
require './board' class KnownBoard < Board UNKNOWN = -3 FLAGGED = -2 EXPLODED = -1 def initialize(width, height) super(width, height, UNKNOWN) end def known?(x, y) get(x, y) != UNKNOWN end def unknown?(x, y) get(x, y) == UNKNOWN end def flag!(x, y) set(x, y, FLAGGED) end def flagged?(x, y) get(x, y) == FLAGGED end def to_s(x, y) c = get(x, y) case c when UNKNOWN then '_' when FLAGGED then 'F' when EXPLODED then 'X' when 0 then '.' else c.to_s end end end
unit_tests do test "can try pr merge" do default_vcr_state do status = PRW.try_merge assert status.key?(:result) assert status.key?(:message) assert_equal :ok, status[:result] assert_equal status, PRW.build_status[:main][:steps][:merge] end end test "can try run build step" do default_vcr_state do status = PRW.try_merge status = PRW.try_run_build_step("uptime", "uptime") assert status.key?(:result) assert status.key?(:message) assert_equal :ok, status[:result] assert status.key?(:exit_code) assert status.key?(:result) assert status.key?(:message) assert status.key?(:command) build_dir_path="/tmp/thumbs/#{PRW.build_guid}" assert_equal "cd #{build_dir_path}; uptime", status[:command] assert status.key?(:output) assert status.key?(:exit_code) assert status[:exit_code]==0 assert status.key?(:result) assert status[:result]==:ok end end test "can try run build step with error" do default_vcr_state do status = PRW.try_merge status = PRW.try_run_build_step("uptime", "uptime -ewkjfdew") assert status.key?(:exit_code) assert status.key?(:result) assert status.key?(:message) assert status.key?(:command) assert status.key?(:output) assert status.key?(:exit_code) assert status[:exit_code] != 0, status[:exit_code].inspect assert status.key?(:result) assert status[:result]==:error end end test "can try run build step and verify build dir" do default_vcr_state do status = PRW.try_merge status = PRW.try_run_build_step("build", "make build") assert status.key?(:exit_code) assert status.key?(:result) assert status.key?(:message) assert status.key?(:command) assert status.key?(:output) assert status.key?(:exit_code) assert status[:exit_code]==0 assert status.key?(:result) assert status[:result]==:ok build_dir_path="/tmp/thumbs/#{PRW.build_guid}" assert_equal "cd #{build_dir_path}; make build", status[:command] assert_equal "BUILD OK\n", status[:output] end end test "can try run build step make test" do default_vcr_state do status = PRW.try_merge status = PRW.try_run_build_step("make_test", "make test") assert status.key?(:exit_code) assert status.key?(:result) assert status.key?(:message) assert status.key?(:command) assert status.key?(:output) assert_equal "TEST OK\n", status[:output] assert status.key?(:exit_code) assert status[:exit_code]==0 assert status.key?(:result) assert status[:result]==:ok end end test "pr should not be merged" do default_vcr_state do assert PRW.minimum_reviewers==2 assert PRW.respond_to?(:reviews) cassette(:comments) do assert PRW.respond_to?(:valid_for_merge?) cassette(:get_state) do cassette(:get_commits) do assert_equal false, PRW.valid_for_merge? end end end end end test "can verify valid for merge" do default_vcr_state do PRW.build_steps=["make test"] PRW.try_merge PRW.run_build_steps cassette(:get_state) do cassette(:get_commits) do cassette(:get_more_commits) do assert_equal false, PRW.valid_for_merge? end end end end end test "unmergable with failing build steps" do default_vcr_state do cassette(:get_events_unmergable) do UNMERGABLEPRW.build_steps = ["make", "make test", "make UNKNOWN_OPTION"] cassette(:get_state, :record => :new_episodes) do cassette(:get_open) do assert_equal true, UNMERGABLEPRW.open? UNMERGABLEPRW.reset_build_status UNMERGABLEPRW.unpersist_build_status UNMERGABLEPRW.try_merge cassette(:commits, :record => :new_episodes) do cassette(:commits_update, :record => :new_episodes) do UNMERGABLEPRW.run_build_steps assert_equal :error, UNMERGABLEPRW.aggregate_build_status_result, UNMERGABLEPRW.build_status step, status = UNMERGABLEPRW.build_status[:main][:steps].collect { |step_name, status| [step_name, status] if status[:result] != :ok }.compact.shift assert_equal :merge, step assert status[:result]==:error assert status[:exit_code]!=0 cassette(:get_new_comments, :record => :new_episodes) do assert_equal false, UNMERGABLEPRW.valid_for_merge? end end end end end end end end test "can get aggregate build status" do default_vcr_state do PRW.unpersist_build_status PRW.reset_build_status PRW.build_steps=["make", "make test"] PRW.run_build_steps assert_equal :ok, PRW.aggregate_build_status_result PRW.unpersist_build_status PRW.reset_build_status PRW.clear_build_progress_comment PRW.build_steps=["make", "make error"] PRW.run_build_steps cassette(:new_agg_result, :record => :new_episodes) do assert_equal :error, PRW.aggregate_build_status_result, PRW.build_status.inspect end end end test "add comment" do default_vcr_state do comment_length = PRW.comments.length cassette(:add_comment_test) do assert PRW.respond_to?(:add_comment) comment = PRW.add_comment("test") assert comment.to_h.key?(:created_at), comment.to_h.to_yaml assert comment.to_h.key?(:id), comment.to_h.to_yaml end end end test "uses custom build steps" do default_vcr_state do PRW.respond_to?(:build_steps) PRW.reset_build_status PRW.unpersist_build_status assert PRW.build_status[:main][:steps] == {}, PRW.build_status[:main][:steps].inspect PRW.build_steps = ["make", "make test"] PRW.run_build_steps assert PRW.build_steps.sort == ["make", "make test"].sort, PRW.build_steps.inspect assert PRW.build_status[:main][:steps].keys.sort == [:make, :make_test].sort, PRW.build_status[:main][:steps].inspect PRW.reset_build_status PRW.unpersist_build_status PRW.build_steps = ["make build", "make custom"] assert PRW.build_steps.include?("make build") PRW.run_build_steps assert PRW.build_status[:main][:steps].keys.include?(:make_build), PRW.build_status[:main][:steps].keys.inspect PRW.reset_build_status PRW.build_steps = ["make -j2 -p -H all", "make custom"] PRW.run_build_steps assert PRW.build_status[:main][:steps].keys.sort == [:make_custom, :make_j2_p_H_all].sort, PRW.build_status[:main][:steps].keys.sort.inspect end end test "code reviews from random users are not counted" do default_vcr_state do cassette(:load_comments_update, :record => :all) do cassette(:get_state, :record => :new_episodes) do assert_equal false, ORGPRW.valid_for_merge? cassette(:update_reviews, :record => :all) do assert ORGPRW.review_count => 2 ORGPRW.run_build_steps assert_equal false, ORGPRW.valid_for_merge?, ORGPRW.build_status end end end end end test "should not merge if merge false in thumbs." do default_vcr_state do PRW.reset_build_status PRW.unpersist_build_status PRW.try_merge assert PRW.thumb_config.key?('merge') assert PRW.thumb_config['merge'] == false cassette(:get_state, :record => :all) do assert_equal false, PRW.valid_for_merge? cassette(:create_code_reviews, :record => :all) do create_test_code_reviews(TESTREPO, TESTPR) assert PRW.review_count >= 1, PRW.review_count.to_s cassette(:get_post_code_review_count, :record => :all) do assert PRW.aggregate_build_status_result == :ok cassette(:get_updated_state, :record => :all) do assert_equal false, PRW.valid_for_merge? cassette(:get_valid_for_merge, :record => :all) do PRW.validate PRW.thumb_config['merge'] = true PRW.thumb_config['minimum_reviewers'] = 0 assert_equal true, PRW.valid_for_merge? end end end end end end end test "should not merge if wait_lock?" do cassette(:get_wait_lock_pr, :record => :new_episodes) do prw = Thumbs::PullRequestWorker.new(repo: 'davidx/prtester', pr: 323) prw.validate prw.thumb_config['merge'] = true prw.thumb_config['minimum_reviewers'] = 0 client2 = Octokit::Client.new(:netrc => true, :netrc_file => ".netrc.davidpuddy1") cassette(:get_updated_comments, :record => :new_episodes) do cassette(:get_valid_for_merge_update, :record => :all) do cassette(:get_valid_for_merge_update_refresh, :record => :all) do assert_equal true, prw.wait_lock? assert_equal false, prw.valid_for_merge? end end end end end test "should identify org comments" do default_vcr_state do assert ORGPRW.respond_to?(:org_member_comments) org=ORGPRW.repo.split(/\//).shift org_member_comments = ORGPRW.non_author_comments.collect { |comment| comment if ORGPRW.client.organization_member?(org, comment[:user][:login]) }.compact assert_equal ORGPRW.org_member_comments, org_member_comments end end test "should identify org code reviews" do default_vcr_state do assert ORGPRW.respond_to?(:org_member_code_reviews) org=ORGPRW.repo.split(/\//).shift org_member_comments = ORGPRW.non_author_comments.collect { |comment| comment if ORGPRW.client.organization_member?(org, comment[:user][:login]) }.compact org_member_code_reviews=org_member_comments.collect { |comment| comment if ORGPRW.contains_plus_one?(comment[:body]) }.compact assert_equal ORGPRW.org_member_code_reviews, org_member_code_reviews end end test "can get events for pr" do default_vcr_state do assert PRW.respond_to?(:events) events = PRW.events assert events.kind_of?(Array) assert events.first.kind_of?(Hash) assert events.first.key?(:created_at) end end test "can get comments after sha" do default_vcr_state do comments = PRW.comments sha_time_stamp=PRW.push_time_stamp(PRW.pr.head.sha) comments_after_sha=PRW.client.issue_comments(PRW.repo, PRW.pr.number, per_page: 100).collect { |c| c.to_h if c[:created_at] > sha_time_stamp }.compact assert_equal comments_after_sha, comments end end end
class User < ActiveRecord::Base has_many :scores belongs_to :user_type def new_token s = SecureRandom.base64(24) s[0, if s.size > 32 then 32 else s.size end] self.token = s end end
class AppDelegate attr_accessor :should_kill_workers, :window def application(application, didFinishLaunchingWithOptions:launchOptions) application.setStatusBarHidden(true, withAnimation:UIStatusBarAnimationFade) @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) @window.rootViewController = MainController.alloc.initWithNibName(nil, bundle: nil) # this must be after setting rootViewController, otherwise CRASH @window.makeKeyAndVisible UIApplication.sharedApplication.setIdleTimerDisabled true @should_kill_workers = true true end def applicationDidBecomeActive application route = Route.find('me') if route @window.rootViewController.username_text_field.text = route.username @window.rootViewController.password_text_field.text = route.password end if @should_kill_workers @window.rootViewController.power_switch_pressed end end def applicationWillResignActive application end def applicationDidEnterBackground application @bgTask = application.beginBackgroundTaskWithExpirationHandler(lambda do application.endBackgroundTask @bgTask @bgTask = UIBackgroundTaskInvalid end) end def dispatch_workers username, password @current_service = get_service username, password queue = Dispatch::Queue.concurrent(priority=:default) WORKERS.times do |i| queue.async{ dispatch_majordomo_worker @current_service } end if @current_service && @current_service != WRONG_USERNAME_OR_PASSWORD @current_service end def get_service username, password host = "iphone.nandalu.idv.tw" #host = "localhost:9292" #host = "geneva3.godfat.org:12352" theRequest = NSURLRequest.requestWithURL NSURL.URLWithString( "http://#{host}/route_login?username=#{username}&password=#{password}") requestError = Pointer.new(:object); urlResponse = Pointer.new(:object) data = (NSURLConnection.sendSynchronousRequest(theRequest, returningResponse:urlResponse, error:requestError) || "").to_str puts "route_login data = #{data} #{Time.now}" return unless urlResponse[0].statusCode == 200 return unless /^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ =~ data or WRONG_USERNAME_OR_PASSWORD == data data end def dispatch_majordomo_worker service worker = Majordomo::Worker.new "tcp://geneva3.godfat.org:5555", service reply = nil loop do request = worker.streamed_recv reply if @should_kill_workers puts "!!! WORKER DYING..." Dispatch::Queue.main.async do main_controller.msg_area.text = "" UIView.animateWithDuration(1, animations:lambda{main_controller.power_switch.alpha = 1}) main_controller.power_switch_go end return end code, headers, body = Cnatra.new.handle_request(request) reply = [[code].concat(headers)].concat( BinData.chunk(body, 200 * 1000) ) # split into chunks of 200kb puts "[DEBUG] in loop: reply.size = #{reply.size}" end end def main_controller @window.rootViewController end WORKERS = 2 WRONG_USERNAME_OR_PASSWORD = "wrong username or password" end
# frozen_string_literal: true module WasteExemptionsShared class SummaryData include WasteExemptionsShared::PrepareDataForReview end class EnrollmentMailer < WasteExemptionsShared::ApplicationMailer # Note that because we were getting issues connecting to PG from here, possible because # we were running out of pooled connections, we now pass an enrollment_id and scope all # database activity with #with_connection to prevent leaking connections. def confirmation(enrollment_id:, recipient_address:) ActiveRecord::Base.connection_pool.with_connection do enrollment = Enrollment.find(enrollment_id) @review_data_sections = EnrollmentReview .new(enrollment, ".confirmation_email") .prepare_review_data_list mail to: recipient_address, from: no_reply_email_address, subject: subject(__method__) end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # ARRAY APP VM vmsrvs=[ { :hostname => "dbapp", :ip => "192.168.1.16", :cpu => "2", :ram => 1024, :file => "" }, { :hostname => "webapp", :ip => "192.168.1.15", :cpu => "2", :ram => 1024, :file => "cfg_files.tgz" } ] # MAIN CONFIG Vagrant.configure(2) do |config| # DISABLE DEFAULT SHARE FOLDER config.vm.synced_folder ".", "/vagrant", disabled: true # CONFIGURE EACH VM IN ARRAY vmsrvs.each do |machine| config.vm.define machine[:hostname] do |node| # CREATE VM FROM IMAGE BOX node.vm.box = "centos/8" # PORTS RANGE FOR VM BY 127.0.0.1 node.vm.usable_port_range = (2200..2250) # SET HOSTNAME OS VM node.vm.hostname = machine[:hostname] # VM LAN CONFIGURE node.vm.network "public_network", ip: machine[:ip] # DETAILS SETTINGS VM node.vm.provider "virtualbox" do |vb| # NAME vb.name = machine[:hostname] # RAM vb.memory = machine[:ram] #CPU vb.cpus = machine[:cpu] end node.vm.provision "file", source: "./webapp_settings.conf", destination: "/tmp/webapp_settings.conf" node.vm.provision "file", source: machine[:file], destination: "/tmp/"+machine[:file] node.vm.provision "shell", path: "init_"+machine[:hostname]+"_service.sh" end end end
class IctVpnsController < ApplicationController before_filter :authenticate_user! def index if current_user && current_user.is_super_admin? @ict_vpn = IctVpn.page(params[:page]).per(2) elsif current_user && current_user.is_department_admin? @ict_vpn = IctVpn.page(params[:page]).per(2) else @ict_vpn = IctVpn.where("user_id = ? or forward_to = ?", current_user.id, current_user.id).order.page(params[:page]).per(2) end end def new @ict_vpn=IctVpn.new end def create @ict_vpn = IctVpn.create(params[:ict_vpn]) @ict_vpn.requisition_type_id = params[:requisition_type_id] @ict_vpn.user_id = current_user.id @ict_vpn.department_id = current_user.departments if @ict_vpn.valid? @ict_vpn.save @approve = Approver.active.find_all_by_department_id(current_user.departments).first dept = Department.find_by_id(current_user.departments) @requisition_ict_vpn=RequisitionType.find(@ict_vpn.requisition_type_id) @system_access_ict_vpn=SystemAccess.find(@ict_vpn.system_access_id) if !@approve.present? ict_email = dept.users.where("role_id = 2").first UserMailer.send_mail_to_ict_vpn(ict_email, @ict_vpn, @requisition_ict_vpn, @system_access_ict_vpn, current_user).deliver else ict_email = User.find_by_id(@approve.user_id) UserMailer.send_mail_to_ict_vpn(ict_email, @ict_vpn, @requisition_ict_vpn, @system_access_ict_vpn, current_user).deliver end redirect_to(ict_vpns_path, :notice => "Resource Requisition ICT VPN has been created successfully.") else render :action=>'new' end end def update @ict_vpn=IctVpn.find_by_id(params[:id]) @requisition_ict_vpn=RequisitionType.find(@ict_vpn.requisition_type_id) @system_access_ict_vpn=SystemAccess.find(@ict_vpn.system_access_id) @ict_vpn.update_attributes(params[:ict_vpn]) if @ict_vpn.update_attributes(params[:ict_vpn]) ict_email = User.find_by_id(@ict_vpn.forward_to) UserMailer.send_mail_to_ict_vpn(ict_email, @ict_vpn, @requisition_ict_vpn, @system_access_ict_vpn, current_user).deliver redirect_to(ict_vpns_path, :notice => 'Booked Requisition ICT VPN has been updated and Mail has been sent successfully') else render :action=>'new' end end def approval @ict_vpn=IctVpn.find_by_id(params[:id]) @requisition_ict_vpn=RequisitionType.find(@ict_vpn.requisition_type_id) end def show if !params[:id].nil? @ict_vpn=IctVpn.find(params[:id]) @ict_vpns = IctVpn.find_by_forward_to(params[:forward_to]) end end def download_attachments @ict_vpn = IctVpn.find(params[:id]) send_file @ict_vpn.vpn_attachment.path end end