text
stringlengths
10
2.61M
class User < ApplicationRecord has_many :lessons_for_teacher,class_name:"Lesson",foreign_key:"user_id" has_many :questions has_many :registrations has_many :courses, through: :registrations has_many :metoos has_many :agoods has_many :cgoods has_many :lessons, through: :registrations, through: :courses #user.lessonsを使用すると,warningが出ますが無視していただいて大丈夫です. #Lessonにもuser_idが存在するのですが,これは教師のidを示しています. #ここで取ってくるのは生徒のuser_idに対応したLessonになります. has_secure_password enum usertag:{ teacher: 0, #先生 ta: 1, #TA student: 2, #生徒 admin: 3 #開発・保守専用 } end
class Recipe < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :user belongs_to :category belongs_to :time_required has_many_attached :images validates :title, presence: true validates :text, presence: true validates :category_id, numericality: { other_than: 0 } validates :time_required_id, numericality: { other_than: 0 } validate :image_length private def image_length if images.length >= 4 errors.add(:images, "は3枚以内にしてください") end end end
class HomeController < ApplicationController def welcome @recipe = Recipe.order("RAND()").first end end
# -*- encoding : utf-8 -*- require 'spec_helper' describe Banner do let(:block) { FactoryGirl.create(:block) } let(:banner) { FactoryGirl.create(:banner) } let(:banner_with_url) { FactoryGirl.create(:banner, :with_url, block: block) } let(:block_banners) { FactoryGirl.create_list(:banner, 3, block: block) } let(:sorted_block_banners) { block_banners.sort { |a,b| a.position <=> b.position } } subject { FactoryGirl.build(:banner) } it { should belong_to(:block).touch(true) } it { should validate_presence_of(:block_id) } it { should validate_attachment_presence(:photo) } it { should validate_attachment_content_type(:photo). allowing('image/jpeg','image/png', 'image/gif') } describe "save" do it "touches block" do subject.block.should_receive(:touch) subject.save end end describe ".get_banner" do it "fetches all banners sorted for a block" do Banner.get_banner(block.id).should == sorted_block_banners end it "should not have banner from other block" do Banner.get_banner(block.id).should_not include(banner) end end describe "#path" do it "returns photo url" do banner.path.should == banner.photo.url end it "returns the url of the url field" do banner_with_url.path.should == banner_with_url.url end end end
class ChangeColumnAuthorizedToStatusInFriendship < ActiveRecord::Migration def self.up add_column :friendships, :status, :string, :default => "pending" remove_column :friendships, :authorized end def self.down add_column :friendships, :authorized, :boolean, :default => false remove_column :friendships, :status end end
require 'xmlrpc/client' module RestoreAgent::XMLRPC class Client < ::XMLRPC::Client def do_rpc(request, async=false) header = { "User-Agent" => USER_AGENT, "Content-Type" => "text/xml; charset=utf-8", "Content-Length" => request.size.to_s, "Connection" => (async ? "close" : "keep-alive") } header["Cookie"] = @cookie if @cookie header.update(@http_header_extra) if @http_header_extra if @auth != nil # add authorization header header["Authorization"] = @auth end resp = nil @http_last_response = nil if async # use a new HTTP object for each call Net::HTTP.version_1_2 http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) http.use_ssl = @use_ssl if @use_ssl http.read_timeout = @timeout http.open_timeout = @timeout # post request http.start { resp = http.post2(@path, request, header) } @http_last_response = resp process_headers(resp) return resp.body else # reuse the HTTP object for each call => connection alive is possible # post request data = ''#resp.body @http.post2(@path, request, header) do |resp| @http_last_response = resp process_headers(resp) resp.read_body do |segment| data += segment #puts segment end end return data end end def process_headers(resp) if resp.code == "401" # Authorization Required raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" elsif resp.code[0,1] != "2" raise "HTTP-Error: #{resp.code} #{resp.message}" end ct = parse_content_type(resp["Content-Type"]).first if ct != "text/xml" if ct == "text/html" raise "Wrong content-type: \n#{data}" else raise "Wrong content-type" end end expected = resp["Content-Length"] || "<unknown>" # if data.nil? or data.size == 0 # raise "Wrong size. Was #{data.size}, should be #{expected}" # elsif expected != "<unknown>" and expected.to_i != data.size and resp["Transfer-Encoding"].nil? # raise "Wrong size. Was #{data.size}, should be #{expected}" # end c = resp["Set-Cookie"] @cookie = c if c end end end
# @param {Integer[]} nums # @return {Integer} def maximum_gap(nums) if nums.length < 2 0 else a = nums.sort max_diff = (a[0] - a[1]).abs (1..(a.length - 1)).each do |i| d = (a[i] - a[i-1]).abs max_diff = d > max_diff ? d : max_diff end max_diff end end
require 'optparse' module RemoteProc class CLI def self.parse_options(argv=ARGV) opts = {} @parser = OptionParser.new do |o| o.on '-c', '--concurrency CONCURRENCY', 'processor threads to use' do |arg| opts[:concurrency] = Integer(arg) end o.on '-t', '--timeout TIMEOUT', 'Shutdown timeout' do |arg| opts[:timeout] = Integer(arg) end o.on '-p', '--port PORT', 'Port RPC server listen to' do |arg| opts[:port] = Integer(arg) end o.on '-b', '--bind BIND', 'bind on host' do |arg| opts[:host] = arg end o.on '', '--commands-dir FOLDER', 'directory where commands file are stored' do |arg| opts[:commands_dir] = arg end end @parser.banner = 'remote_proc [options]' @parser.on_tail '-h', '--help', 'Show help' do puts @parser exit 1 end @parser.parse!(argv) opts end end end
class DockerMachine < FPM::Cookery::Recipe description 'Machine management for a container-centric world' homepage 'https://docs.docker.com/machine/' name 'docker-machine' version '0.16.2' revision '1' source "https://github.com/docker/machine/releases/download/v#{version}/docker-machine-Linux-x86_64" sha256 'a7f7cbb842752b12123c5a5447d8039bf8dccf62ec2328853583e68eb4ffb097' def build end def install chmod 0555, 'docker-machine-Linux-x86_64' bin.install 'docker-machine-Linux-x86_64', 'docker-machine' end end
# -*- coding: utf-8 -*- FactoryBot.define do factory :project do sequence(:project_name) { |n| "pn#{n}_#{Time.now.to_i}" } # project_name Faker::TwinPeaks.unique.location project_title 'MyStringAloneIsNotLongEnough' project_description 'MyString' rfa_url 'http://www.northwestern.edu' association :program, factory: :program project_url = Faker::Internet.url initiation_date Date.today submission_open_date Date.today submission_close_date Date.today review_start_date Date.today review_end_date Date.today project_period_start_date Date.today project_period_end_date Date.today status 'MyString' min_budget_request 5000 max_budget_request 100000 max_assigned_reviewers_per_proposal 2 max_assigned_proposals_per_reviewer 2 applicant_wording 'Principal Investigator' association :creator, factory: :user created_ip '127.0.0.1' created_at Time.now visible true factory :pre_initiated_project do project_title 'Pre-Initiated Project' initiation_date 1.week.from_now submission_open_date 2.week.from_now submission_close_date 3.week.from_now review_start_date 3.week.from_now review_end_date 4.week.from_now project_period_start_date 4.week.from_now project_period_end_date 5.week.from_now end factory :initiated_project do project_title 'Initiated Project' initiation_date 1.day.ago submission_open_date 1.week.from_now submission_close_date 2.week.from_now review_start_date 2.week.from_now review_end_date 3.week.from_now project_period_start_date 3.week.from_now project_period_end_date 4.week.from_now end factory :open_project do project_title 'Open Project' initiation_date 1.day.ago submission_open_date 1.day.ago submission_close_date 1.week.from_now review_start_date 1.week.from_now review_end_date 2.week.from_now project_period_start_date 2.week.from_now project_period_end_date 3.week.from_now end factory :closed_project do project_title 'Closed Project' initiation_date 3.week.ago submission_open_date 2.week.ago submission_close_date 1.day.ago review_start_date 1.day.ago review_end_date 1.week.from_now project_period_start_date 1.week.from_now project_period_end_date 2.week.from_now end end end
Pod::Spec.new do |s| s.name = 'CiteprocRsKit' s.version = '0.0.1' s.summary = 'citeproc-rs bindings for Swift' s.description = <<-DESC citeproc-rs bindings for Swift DESC s.homepage = 'https://github.com/zotero/citeproc-rs' # s.license = { :type => '', :file => 'LICENSE' } s.author = { 'Cormac Relf' => 'cormac@cormacrelf.net', } s.source = { :git => 'https://github.com/zotero/citeproc-rs', :tag => s.version.to_s } s.source_files = 'bindings/swift/CiteprocRsKit/**/*.{swift,h,a}' s.swift_version = '5.1' s.ios.deployment_target = '12.0' s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } # s.dependency 'dependency-name', '= 0.0.0' s.ios.vendored_libraries = 'lib/libciteproc_rs.a' s.preserve_paths = ['Scripts', 'rust','docs','Cargo.*','CiteprocRsKit/Stencil'] # s.prepare_command = <<-CMD # CMD s.script_phase = { :name => 'Build libciteproc_rs', :script => 'sh ${PODS_TARGET_SRCROOT}/Scripts/build_libciteproc_rs.sh', :execution_position => :before_compile } s.test_spec 'Tests' do | test_spec | test_spec.source_files = 'CiteprocRsKitTests/**/*.{swift}' test_spec.ios.resources = 'CiteprocRsKitTests/**/*.{db,params}' test_spec.script_phase = { :name => 'Build libciteproc_rs', :script => '${PODS_TARGET_SRCROOT}/Scripts/build_libciteproc_rs_xcode.sh --testing', :execution_position => :before_compile } # test_spec.dependency 'dependency-name', '= version' end end
require 'listen' require 'rspec_runner/configuration' module RspecRunner class Watcher class << self def start(&block) if @thread then raise RuntimeError, "already started" end @thread = Thread.new do config = RspecRunner.configuration @listener = Listen.to(*config.listen_directories, config.listen_options) do |modified, added, removed| if((modified.size + added.size + removed.size) > 0) block.call(modified: modified, added: added, removed: removed) end end @listener.start puts 'Watcher started!' end sleep(0.1) until @listener at_exit { stop } @thread end private def stop @thread.wakeup rescue ThreadError begin @listener.stop rescue => e puts "#{e.class}: #{e.message} stopping listener" end @thread.kill rescue ThreadError end end end end
require "sartre/version" module Sartre protected def existential?(name) name =~ /\?\Z/ end def try?(name) !!send(name) end end class Object include Sartre def method_missing name, *arguments super unless existential? name method = name[0..-2] return false unless respond_to? method try? method end end
module PivotalToPdf module Formatters class Base attr_reader :stories private :stories def initialize(stories) @stories = stories p stories.size end end end end
# frozen_string_literal: true require 'sinatra/base' # http://www.omdbapi.com class FakeOMDB < Sinatra::Base get '/' do json_response 200, 'movie.json' end private def json_response(response_code, file_name) content_type :json status response_code File.open("#{File.dirname(__FILE__)}/api/omdb/#{file_name}", 'rb').read end end
class Block < ActiveRecord::Base attr_accessible :blocked_id, :blocker_id belongs_to :blocker, class_name: "User" belongs_to :blocked, class_name: "User" end
class TestScore < ActiveRecord::Base belongs_to :test belongs_to :user belongs_to :contact def self.grade_test user_id, test, answers, contact_id = nil if answers.uniq.count == test.questions.count and validate_answers(answers, test) if user_id user = User.find(user_id) if test.test_type == "percentage" return grade_percentage_test answers, user, test elsif test.test_type == "correct_incorrect" return grade_correct_incorrect_test answers, user, test elsif test.test_type == "multiple" if not contact_id raise "Falta contact_id para este tipo de test" end contact = Contact.find(contact_id) return grade_multiple_test answers, user, test, contact end else if test.test_type == "percentage" return grade_percentage_test answers, nil, test else raise "Test que no es de porcentaje sin usuario para evaluar" end end else raise "El número de respuestas únicas no corresponde al número de las preguntas" end end private def self.grade_multiple_test answers, user, test, contact ts = nil answers.each do |answer| answer = Answer.find(answer["id"]) ts = TestScore.find_or_initialize_by(user_id: user.id, test_id: test.id, contact_id: contact.id) if answer.text.to_i != 0 ts.score = answer.text else ts.description = answer.text end ts.save! end #Enviar Correo con respuestas IuvareMailer.send_answers(user, ts).deliver_now return [ts] end def self.grade_percentage_test answers, user, test percentage_types_with_count = {} Test::PERCENTAGE_ANSWER_TYPES_BY_CODE[test.code].each do |answer_type| percentage_types_with_count[answer_type] = 0.0 end total = answers.count answers.each do |answer| answer = Answer.find(answer["id"]) percentage_types_with_count[answer.answer_type] += 1 end test_scores = [] percentage_types_with_count.each do |key, value| if user ts = TestScore.find_or_initialize_by(user_id: user.id, test_id: test.id, description: key) ts.score = (value/total*100).round(2) ts.save! else ts = TestScore.new(test_id: test.id, description: key, score: (value/total*100).round(2)) end test_scores << ts end return test_scores end def self.grade_correct_incorrect_test answers, user, test correct = 0.0 total = answers.count answers.each do |answer| answer = Answer.find(answer["id"]) correct += 1.0 if answer.answer_type == "correct" end ts = TestScore.find_or_initialize_by(user_id: user.id, test_id: test.id) ts.score = (correct/total*100).round(2) ts.save! return [ts] end def self.validate_answers answers, test questions_array = [] answers.each do |aa| questions_array << Answer.find(aa["id"]).question_id end test.questions.each do |question| if not questions_array.index(question.id) raise "Una pregunta del test no cuenta con su respuesta" end end return true end end
# @author Marek Czuma <marek.czuma@gmail.com> class Statistics # SKILL # Give hash {Day: hour} for specific skill by rate # @param skill_id [Integer] # @param from [Date] # @param to [Date] # @return hash {Day: hour} def self.skill_single_hours (user, skill_id, from, to) skill = user.skills.find(skill_id) prefabs = skill.prefabs log_times = [] days = {} prefabs.each do |prefab| prefab_log_times = Statistics.log_times_of_prefab(prefab.id, from, to) log_times.push(prefab_log_times) end log_times.each do |log_time| log_time.each do |single_log_time| current_day = single_log_time.date_start.to_date if days[current_day].nil? days[current_day] = single_log_time.time else days[current_day] += single_log_time.time end end end return days, skill end # Give number of hours to mastery # @param skill_id [Integer] # @return Integer def self.skill_mastery (skill_id) minutes = Statistics.time_of_skill(skill_id) mastery = 600000 # 10 000 hours * 60 minutes mastery -= minutes mastery = (mastery.to_f / 60).round return mastery.to_i end # Give number of hours # @param skill_id [Integer] # @return Hash {Skill: Hours} def self.skill_greatest (user) skills = user.skills hours = {} time = 0 current_skill = nil skills.each do |skill| hours[skill.name] = Statistics.time_of_skill_wo(skill.id) end skills.each do |skill| if hours[skill.name] > time time = hours[skill.name] current_skill = skill end end skill = {} skill[current_skill] = time return skill end # PREFABS # Give hash {Day: hour} by rate for some specific prefab # @param user [User] # @param prefab_id [Integer] # @param from [Date] # @param to [Date] # @return hash {Day: hour} def self.prefab_single_hours (user, prefab_id, from, to) prefab = user.prefabs.find(prefab_id) days = {} prefab_log_times = prefab.log_times.where('date_start >? AND date_end <?', from, to) prefab_log_times.each do |log_time| current_day = log_time.date_start.to_date if days[current_day].nil? days[current_day] = log_time.time else days[current_day] += log_time.time end end return days, prefab end # It gives prefab with the gratest amount of hours # by rate and time of that # @param user [User] # @param from [Date] # @param to [Date] # @return hash {Prefab: Hours} def self.prefab_greatest(user, from, to) prefabs = user.prefabs #.where('date_start >? AND date_end <?', from, to) prefabs_time = {} greatest_time = 0 greatest_prefab = nil final_prefab = {} prefabs.each do |prefab| prefabs_time[prefab] = 0 prefab_log_times = prefab.log_times.where('date_start >? AND date_end <?', from, to) prefab_log_times.each do |log_time| prefabs_time[prefab] += log_time.time puts prefab.name + ' ' + log_time.time.to_s puts 'total: ' + prefabs_time[prefab].to_s end end prefabs.each do |prefab| if prefabs_time[prefab] > greatest_time greatest_time = prefabs_time[prefab] greatest_prefab = prefab end end puts 'prefab: ' + greatest_prefab.name final_prefab[greatest_prefab.name] = greatest_time return final_prefab end # TODO def self.log_times_of_prefab(prefab_id, from, to) prefab = Prefab.find(prefab_id) time = 0 log_times = prefab.log_times.where('date_start >? AND date_end <?', from, to) return log_times end def self.time_of_prefab(prefab_id, from, to) prefab = Prefab.find(prefab_id) time = 0 log_times = prefab.log_times.where('date_start >? AND date_end <?', from, to) log_times.each do |log_time| time += log_time.time end return time end def self.time_of_prefab_general(prefab_id) prefab = Prefab.find(prefab_id) log_times = prefab.log_times return log_times end def self.time_of_skill(skill_id) skill = Skill.find(skill_id) prefabs = skill.prefabs log_times = [] minutes = 0 prefabs.each do |prefab| prefab_log_times = Statistics.time_of_prefab_general(prefab.id) log_times.push(prefab_log_times) end log_times.each do |log_time| log_time.each do |single_log_time| minutes += single_log_time.time end end return minutes end # GENERAL # Method give us hash with all hours in specific range of time # @param user [User] # @param from [Date] # @param to [Date] # return hash {Day: Hours} def self.general_hours(user, from, to) days = {} user_log_times = user.log_times.where('date_start >? AND date_end <?', from, to) user_log_times.each do |log_time| current_day = log_time.date_start.to_date if days[current_day].nil? days[current_day] = log_time.time else days[current_day] += log_time.time end end return days end def self.time_of_skill_wo(skill_id) skill = Skill.find(skill_id) prefabs = skill.prefabs log_times = [] hours = 0 prefabs.each do |prefab| prefab_log_times = prefab.log_times log_times.push(prefab_log_times) end log_times.each do |log_time| log_time.each do |single_log_time| hours += single_log_time.time end end return hours end end
class Api::V1::PartsController < ApplicationController before_action :find_part, only: [:update] before_action :authorized, only: [:create, :update] def index @parts = Part.all render json: @parts end def create @part = Part.create(part_params) render json: @part, status: :accepted end def update @part.update(part_params) if @part.save render json: @part, status: :accepted else render json: { errors: @part.errors.full_messages }, status: :unprocessible_entity end end private def part_params params.permit(:post_id, :product_id) end def find_part @part = Part.find(params[:id]) end end
step "I go to the next page" do page.find('.pagination li.next a').click end
# == Schema Information # # Table name: frames # # id :integer not null, primary key # game_id :integer # score :integer default(0) # ball_position :integer default(1), not null # special_score :integer default("regular"), not null # created_at :datetime not null # updated_at :datetime not null # frame_number :integer # class Frame < ApplicationRecord belongs_to :game enum special_score: [:regular,:spare,:strike] enum ball_position: [:finished, :first_shot, :second_shot] def valid_pins?(number_of_pins) number_of_pins >= 0 && number_of_pins <= 10 && number_of_pins.kind_of?(Integer) ? not_more_than_ten(number_of_pins) : false end # MAIN ENTRY POINT def update_frame(number) total_score = self.second_shot? ? self.score + number : number update(score: total_score) set_special_score if is_special_score?(total_score) update_previous_special_score(number) update_ball end private def update_ball new_position = (self.read_attribute_before_type_cast(:ball_position) + 1) %3 self.update(ball_position: new_position) update_total_score if time_to_update_total_score? check_change_frame(new_position) end def check_change_frame(position) change_frame if position === 0 end def change_frame self.game.add_frame end def not_more_than_ten(number_of_pins) return true if self.first_shot? return true if (10 - self.score) >= number_of_pins return true if self.frame_number >= 10 && 10 - number_of_pins return false end def time_to_update_total_score? self.regular? end def update_total_score self.game.update_score end def is_special_score?(total_score) return false if self.frame_number >= 10 return true if total_score === 10 end def set_special_score if self.first_shot? self.strike! self.finished! change_frame else self.spare! end end def update_previous_special_score(number) previous_frames = query_previous_frames if previous_frames.exists? update_previous_spares(previous_frames,number) update_previous_strikes(previous_frames,number) end end def query_previous_frames self.game.frames.where(special_score: ["spare","strike"], frame_number: [self.frame_number - 1,self.frame_number - 2]) end def update_previous_spares(frames,number) spare_frame = frames.find{|frame| frame.spare?} return unless spare_frame update_action(spare_frame,number){ |object| object.regular! } change_frame if self.frame_number >= 10 end def update_previous_strikes(frames,number) one_previous_frame = find_previous_strike_frames(frames,1) two_previous_frames = find_previous_strike_frames(frames,2) callback = ->(object) {object.regular!} if one_previous_frame if self.strike? update_action(one_previous_frame,number) else update_action(one_previous_frame,number,& -> (object) { object.regular! if self.second_shot? } ) end end if two_previous_frames update_action(two_previous_frames,number,&callback) end end def find_previous_strike_frames(frames, previous_number) frames.find{|frame| frame.strike? && frame.frame_number === (self.frame_number - previous_number)} end def update_action(object,number,&block) object.update(score: object.score + number) block.call(object) if block_given? time_to_update_total_score? end end
require 'rails_helper' feature 'Edit blog post', vcr: true, js: true, record: :new_episodes do let!(:post) { create(:post) } before do login_admin visit edit_post_path(post) end context '(when attributes are invalid)' do scenario 're-renders the edit post form' do fill_in 'post[title]', with: '' fill_in 'post[excerpt]', with: 'stuff' fill_in 'post[body]', with: 'more stuff' click_button 'Post This Bitch!' expect(page).to have_content 'Notify related users' end end scenario 'allows me to delete assets' do asset = post.assets.first within "#asset_#{asset.id}" do find('.asset-delete').click end page.driver.browser.switch_to.alert.accept click_button 'Post This Bitch!' expect(post.reload.assets.count).to eq(0) end end
# -*- encoding : utf-8 -*- class CreateGroups < ActiveRecord::Migration def change create_table :groups do |t| t.string :uuid, limit: 36, null: false t.references :course, null: false t.string :name, limit: 191 t.integer :holes_count, default: 0, null: false t.timestamps null: false end end end
class RelationshipsController < ApplicationController include ActionController::Live def create @user = User.find(params[:relationship][:followed_id]) current_user.follow!(@user) redirect_to @user end def destroy @user = Relationship.find(params[:id]).followed current_user.unfollow!(@user) redirect_to @user end end private def relationship_params params.require(:relationship).permit(:followed_id, :follower_id) end
require 'spec_helper' describe PaypalDetail do it "has a valid factory" do @user = FactoryGirl.create(:user) FactoryGirl.create(:paypal_detail, user_id: @user.id).should be_valid end it "is invalid without a email" do FactoryGirl.build(:paypal_detail, email: nil).should_not be_valid end it "is invalid without a first_name" do FactoryGirl.build(:paypal_detail, first_name: nil).should_not be_valid end it "is invalid without a last_name" do FactoryGirl.build(:paypal_detail, last_name: nil).should_not be_valid end it "belongs to the user" do expect { FactoryGirl.create(:paypal_detail).user }.to_not raise_error end #====================fail case ========================================== it "has a valid factory" do @user = FactoryGirl.create(:user) FactoryGirl.create(:paypal_detail, user_id: @user.id).should_not be_valid end it "is invalid without a email" do FactoryGirl.build(:paypal_detail, email: nil).should be_valid end it "is invalid without a first_name" do FactoryGirl.build(:paypal_detail, first_name: nil).should be_valid end it "is invalid without a last_name" do FactoryGirl.build(:paypal_detail, last_name: nil).should be_valid end it "belongs to the user" do expect { FactoryGirl.create(:paypal_detail).user }.to raise_error end end
module Api module V1 class BaseApiController < ApplicationController before_filter :parse_request, :authenticate_user_from_token! rescue_from ActiveRecord::RecordNotFound, with: :record_not_found private def record_not_found format_json_output(nil, status: 'exception', message: 'Record not found') end def authenticate_user_from_token! #if !@json['api_token'] # render nothing: true, status: :unauthorized #else # @user = nil # User.find_each do |u| # if Devise.secure_compare(u.api_token, @json['api_token']) # @user = u # end # end #end end def parse_request @json = JSON.parse(request.body.read) unless request.body.present? @json ||= {} end def format_json_output(data, options = {}) options = options.reverse_merge({ status: 'success', message: nil }) options[:data] = data options.to_json end end end end
# Copyright (C) 2011 Marco Mornati (<ilmorna@gmail.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require 'curb' require 'inifile' require 'socket' require 'json' require 'base64' module MCollective module Agent class Postgresql<RPC::Agent action "execute_sql" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing execute_sql Action" conffile = '/etc/kermit/kermit.cfg' section = 'postgresql' baseurl = getkey(conffile, section, 'sqlrepo') logmsg = "Contacting repository using URL #{baseurl}" logmsg << " to request #{request[:sqlfile]}" Log.debug logmsg fileout = download(baseurl, request[:sqlfile], '/tmp') unless File.exists?(fileout) reply['status'] = "Error - Unable to get #{request[:sqlfile]}" reply.fail! "Error - Unable to get #{request[:sqlfile]} " end db_user = Base64.decode64(getkey(conffile, section, 'dbuser')) db_password = Base64.decode64(getkey(conffile, section, 'dbpassword')) cmd = "su - postgres -c '" if db_password cmd << "export PGPASSWORD=\"#{db_password}\";" end if request[:dbname].nil? Log.debug "Executing SQL script without DBName specfied. Need to be present in SQL file" cmd << "psql -U #{db_user} < #{fileout}" else db_name = request[:dbname] Log.debug "Executing SQL script with provided DBName: #{db_name}" cmd << "psql -U #{db_user} #{db_name} < #{fileout}" end cmd << "'" Log.debug "Executing command #{cmd}" result = %x[#{cmd}] shorthostname=`hostname -s`.chomp file_name = "sql.log.#{shorthostname}.#{Time.now.to_i}" Log.debug "Creating log file #{file_name}" File.open("/tmp/#{file_name}", 'w') {|f| f.write(result) } send_log("/tmp/#{file_name}") reply['logfile'] = file_name end action "inventory" do reply.fail! "Error - No pgsql server found or started" unless check_pg reply[:result] = inventory end action "get_databases" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing get_databases Action" databaselist = get_databases reply['databases'] = databaselist end action "get_database_size" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing get_databases Action" db_name = request[:dbname] result = get_database_size(db_name) reply['size'] = result end action "get_tables" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing get_tables Action" db_name = request[:dbname] tables = get_tables(db_name) reply['tables'] = tables end action "get_data_dir" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing get_data_dir Action" data_dir = get_data_dir reply['data_dir'] = data_dir end action "get_version" do reply.fail! "Error - No pgsql server found or started" unless check_pg Log.debug "Executing get_version Action" version = get_version reply['version'] = version end action "sql_list" do filetype = 'sql' result = { :sqllist => [] } SECTION = 'postgresql' MAINCONF = '/etc/kermit/kermit.cfg' ini=IniFile.load(MAINCONF, :comment => '#') params = ini[SECTION] repourl = params['sqlrepo'] c = Curl::Easy.perform(repourl) pattern = /<a.*?href="(.*#{filetype}?)"/ m=c.body_str.scan(pattern) result[:sqllist] = m.map{ |item| item.first } reply.data = result end private def get_tables(database) query = "SELECT table_name FROM information_schema.tables" query << " WHERE table_type = 'BASE TABLE'" query << " and table_schema != 'pg_catalog'" query << " and table_schema != 'information_schema';" result = execute_query(query, database) tablelist = Array.new return tablelist unless result result.each_line do |row| row.strip! tablelist << row unless row.empty? end tablelist end def get_database_size(db_name) query = "SELECT pg_size_pretty(pg_database_size('#{db_name}'))" query << " as database_size" result = execute_query(query) if not result.nil? result = result.strip result = result.gsub('\n', '') end result end def get_databases query = 'SELECT pg_database.datname as \"Database\",pg_user.usename' query << ' as \"Owner\" FROM pg_database, pg_user' query << ' WHERE pg_database.datdba = pg_user.usesysid' query << ' UNION' query << ' SELECT pg_database.datname as \"Database\", NULL as "Owner"' query << ' FROM pg_database WHERE pg_database.datdba' query << ' NOT IN (SELECT usesysid FROM pg_user) ORDER BY \"Database\"' result = execute_query(query) databaselist = Array.new return databaselist unless result result.each_line do |row| content = row.split('|') if content.length == 2 dbname = content[0].strip owner = content[1].strip data = { "name" => dbname, "owner" => owner } databaselist << data end end databaselist end def get_data_dir query = 'SHOW data_directory;' result = execute_query(query) if not result.nil? result = result.strip result = result.gsub('\n', '') end result end def check_pg conffile = '/etc/kermit/kermit.cfg' section = 'postgresql' db_user = Base64.decode64(getkey(conffile, section, 'dbuser')) db_password = Base64.decode64(getkey(conffile, section, 'dbpassword')) query = 'select version();' cmd = "su - postgres -c '" if db_password cmd << "export PGPASSWORD=\"#{db_password}\";" end cmd << "psql -U #{db_user} -d postgres -tc \"#{query}\"" cmd << "'" Log.debug "Check Postgres Command: #{cmd}" %x[#{cmd}] return $? == 0 end def get_version query = 'select version();' result = execute_query(query) if not result.nil? result = result.strip result = result.gsub('\n', '') end result end def get_users query = 'SELECT u.usename AS \"User name\", u.usesysid AS \"User ID\", ' query << 'CASE WHEN u.usesuper AND u.usecreatedb THEN CAST(\'superuser, create database\' AS pg_catalog.text)' query << ' WHEN u.usesuper THEN CAST(\'superuser\' AS pg_catalog.text) WHEN u.usecreatedb ' query << 'THEN CAST(\'create database\' AS pg_catalog.text) ELSE CAST(\'\' AS pg_catalog.text) ' query << 'END AS \"Attributes\" FROM pg_catalog.pg_user u ORDER BY 1; ' result = execute_query(query) userlist = Array.new return userlist unless result result.each_line do |row| content = row.split('|') if content.length == 3 uname = content[0].strip uid = content[1].strip attributes = content[2].strip data = { "username" => uname, "uid" => uid, "attributes" => attributes } userlist << data end end userlist end def inventory inventory = Hash.new inventory[:databases] = [] inventory[:version] = get_version inventory[:data_dir] = get_data_dir inventory[:users] = get_users databases = get_databases databases.each do |db| tables = get_tables(db['name']) db_size = get_database_size(db['name']) database = {"name" => db['name'], "size" => db_size, "tables" => tables} inventory[:databases] << database end jsonfilename = send_inventory(dump_inventory('postgresql', inventory)) jsonfilename end def dump_inventory(dump_name, inventory) hostname = Socket.gethostname jsoncompactfname="/tmp/#{dump_name}inventory-#{hostname}-compact.json" jsoncompactout = File.open(jsoncompactfname,'w') jsoncompactout.write(JSON.generate(inventory)) jsoncompactout.close jsonprettyfname="/tmp/#{dump_name}inventory-#{hostname}-pretty.json" jsonprettyout = File.open(jsonprettyfname,'w') jsonprettyout.write(JSON.pretty_generate(inventory)) jsonprettyout.close jsoncompactfname end def send_log(logfile) cmd = "ruby /usr/local/bin/kermit/queue/sendlog.rb #{logfile}" %x[#{cmd}] logfile end def send_inventory(jsoncompactfname) cmd = "ruby /usr/local/bin/kermit/queue/send.rb #{jsoncompactfname}" %x[#{cmd}] jsoncompactfname end def execute_query(query, database='postgres') conffile = '/etc/kermit/kermit.cfg' section = 'postgresql' db_user = Base64.decode64(getkey(conffile, section, 'dbuser')) db_password = Base64.decode64(getkey(conffile, section, 'dbpassword')) cmd = "echo \"#{query}\"" cmd << " | su - postgres -c '" if db_password cmd << "export PGPASSWORD=\"#{db_password}\";" end cmd << "psql -U #{db_user} #{database} -t" cmd << "'" Log.debug "Command RUN: #{cmd}" result = %x[#{cmd}] result end def getkey(conffile, section, key) ini=IniFile.load(conffile, :comment => '#') params = ini[section] params[key] end # Download a file with Curl def download(repourl, file, targetfolder) url="#{repourl}/#{file}".gsub(/([^:])\/\//, '\1/') fileout = "#{targetfolder}/#{file}".gsub(/([^:])\/\//, '\1/') Curl::Easy.download(url,filename=fileout) fileout end end end end
class ChangeNewMembersSignOnsToNewMobilizerSignOns < ActiveRecord::Migration[6.0] def change rename_column :growth_activities, :new_members_sign_ons, :new_mobilizer_sign_ons end end
module Platforms module Yammer module Api # Open Graph Objects in Yammer # # This is read-only through the API. # # @author Benjamin Elias # @since 0.1.0 class OpenGraphObjects < Base # Get open graph obects # URL is actually a required parameter so require that when # calling this function. # @param url [#to_s] URL of the OG item to get # @param options [Hash] Options for the request # @param headers [Hash] Additional headers to send with the request # @return [Faraday::Response] the API response # @see https://developer.yammer.com/docs/open_graph_objects def get url, options={}, headers={} params = options.merge({url: url}) @connection.get 'open_graph_objects.json', params, headers end end end end end
#!/usr/bin/env ruby require 'webrick' require 'open3' $AUTH_TOKEN = ENV["NCLIP_AUTH_TOKEN"] || "my-token" $PORT = 2547 puts "NCLIP server starting at http://127.0.0.1:#{$PORT}" puts puts "Using '#{$AUTH_TOKEN}' as the authorization token." puts class OSXClipboard def self.paste() `pbpaste` end def self.copy(text) stdin, stdout, stderr = Open3.popen3('pbcopy') stdin.write(text) stdin.close end end server = WEBrick::HTTPServer.new :BindAddress => "127.0.0.1", :Port => $PORT server.mount_proc '/' do |req, res| raise WEBrick::HTTPStatus::Forbidden, "Invalid token." if req.query_string != $AUTH_TOKEN if req.request_method == 'GET' res.body = OSXClipboard.paste else OSXClipboard.copy(req.body) res.body = "OK" end end trap 'INT' do server.shutdown end server.start
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_locale def after_sign_in_path_for(resource) sign_in_url = new_user_session_url if request.referer == sign_in_url && resource.admin? admin_welcome_path else stored_location_for(resource) || root_path end end def set_locale if cookies[:trains_locale] && I18n.available_locales.include?(cookies[:trains_locale].to_sym) l = cookies[:trains_locale].to_sym else l = I18n.default_locale cookies.permanent[:trains_locale] = l end I18n.locale = l end end
module Sentry module Rails module Tracing class AbstractSubscriber class << self def subscribe! raise NotImplementedError end def unsubscribe! self::EVENT_NAMES.each do |name| ActiveSupport::Notifications.unsubscribe(name) end end if ::Rails.version.to_i == 5 def subscribe_to_event(event_names) event_names.each do |event_name| ActiveSupport::Notifications.subscribe(event_name) do |*args| next unless Tracing.get_current_transaction event = ActiveSupport::Notifications::Event.new(*args) yield(event_name, event.duration, event.payload) end end end else def subscribe_to_event(event_names) event_names.each do |event_name| ActiveSupport::Notifications.subscribe(event_name) do |event| next unless Tracing.get_current_transaction yield(event_name, event.duration, event.payload) end end end end def record_on_current_span(duration:, **options) return unless options[:start_timestamp] Sentry.with_child_span(**options) do |child_span| # duration in ActiveSupport is computed in millisecond # so we need to covert it as second before calculating the timestamp child_span.set_timestamp(child_span.start_timestamp + duration / 1000) yield(child_span) if block_given? end end end end end end end
class AddPasswordDigestToUsers < ActiveRecord::Migration def up remove_column "users", "password" add_column "users", "password_digest", :string end def down add_column "users", "password" remove_column "users", "password_digest" end end
require 'rails_helper' RSpec.describe 'AdminSessionsController', type: :request do before do Admin.create(email: 'a@email.com', password: '1234567', password_confirmation: '1234567') end describe 'GET /admin_sessions' do it 'sign in admin' do get admins_sign_in_path expect(response).to have_http_status(:ok) end end describe 'POST /admin_sessions' do it 'sign in admin' do post admins_sign_in_path, params: { email: 'a@email.com', password: '1234567' } expect(response).to redirect_to(admins_path) end end describe 'DELETE /admin_sessions' do it 'sign out admin' do delete logout_path expect(response).to redirect_to(admins_sign_in_path) end end end
require "rails_helper" RSpec.describe UpdateContact do describe "#call" do it "updates a contact if the number is not provided" do contact = create(:contact) params = { first_name: "John", } result = described_class.new(contact: contact, params: params).call expect(result.success?).to be(true) expect(result.contact.first_name).to eq("John") end it "updates a contact if the number is valid" do contact = create(:contact) params = { phone_number: LookupResult.new(phone_number: "+18282519900"), } result = described_class.new(contact: contact, params: params).call expect(result.success?).to be(true) expect(result.contact.phone_number).to eq("+18282519900") end it "marks an unsaved contact as saved" do contact = create(:contact, :unsaved) params = { first_name: "John", } result = described_class.new(contact: contact, params: params).call expect(result.success?).to be(true) expect(result.contact.saved).to eq(true) end it "does not update a contact if the provided number is not valid" do contact = create(:contact) params = { phone_number: double(valid?: false), } result = described_class.new(contact: contact, params: params).call expect(result.success?).to be(false) expect(result.errors).not_to be_empty end end end
module AuthenticateHelper def authenticate_user email = JsonWebTokenService.decode(request.headers['HTTP_AUTH_TOKEN'])["email"] @current_user = User.find_by(email: email) render json: { error: 'Not Authorized' }, status: 401 unless @current_user end def user_sign_in? !!current_user end def current_user @current_user end end
class Admin::ReportTypesController < ApplicationController before_action :require_report_admin before_action :set_report_type, only: [:show, :edit, :update, :destroy] # GET /admin/report_types def index @report_types = ReportType.all end # GET /admin/report_types/1 def show end # GET /admin/report_types/new def new @report_type = ReportType.new end # GET /admin/report_types/1/edit def edit end # POST /admin/report_types def create @report_type = ReportType.new(report_type_params) if @report_type.save redirect_to admin_report_type_url(@report_type), notice: 'Report type was successfully created.' else render :new end end # PATCH/PUT /admin/report_types/1 def update if @report_type.update(report_type_params) redirect_to admin_report_type_url(@report_type), notice: 'Report type was successfully updated.' else render :edit end end # DELETE /admin/report_types/1 def destroy @report_type.destroy redirect_to admin_report_types_url, notice: 'Report type was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_report_type @report_type = ReportType.find(params[:id]) end # Only allow a trusted parameter "white list" through. def report_type_params params.require(:report_type).permit(:name, :description) end end
class CompetitorSetsController < ApplicationController before_filter :authorize, only: [:new, :create] before_filter :find_competitor_set, only: [:show, :edit, :update] before_filter :check_owner, only: [:edit, :update] def new @cset = current_user.competitor_sets.new end def create @cset = current_user.competitor_sets.new(params[:competitor_set]) if @cset.save redirect_to @cset, notice: "Competitor Set created!" else render "new" end end def show end def index @csets = CompetitorSet.all end def edit end def update if @cset.update_attributes(params[:competitor_set]) flash[:success] = "Competitor set updated" redirect_to @cset else render 'edit' end end private def find_competitor_set @cset = CompetitorSet.find(params[:id]) end def check_owner @cset = CompetitorSet.find(params[:id]) redirect_to root_path, alert: "You can't do that!" unless current_user?(@cset.owner) end end
require "rails_helper" RSpec.describe TokenAuthentication do it "returns the authenticated user with a valid token" do user = create(:user) token_body = token_string(user) auth = described_class.new(token_body) authenticated_user = auth.authenticate expect(authenticated_user).to eq(user) end it "sets the abilities on the returned user" do user = create(:user) token_body = token_string(user, ["manage_messaging"]) auth = described_class.new(token_body) user = auth.authenticate expect(user.abilities).to include(:manage_messaging) end it "returns a guest when provided with an invalid token" do auth = described_class.new("not-valid-token") guest_user = auth.authenticate expect(guest_user).to be_a(Guest) end def token_string(user, abilities = []) JWT.encode({email: user.email, abilities: abilities}, Token::SECRET, Token::ALGORITHM) end end
module ApplicationHelper def car_identity(request) (request.car.vin + " " + request.car.frame + " " + request.car.marka + " " + request.car.model + " " + request.car.god).strip end def days_decorator value html_escape("#{((value = value.to_i) > 0) ? value : '*'}") + "&nbsp;дн.".html_safe end def count_decorator value html_escape("#{((value = (value.to_s.gsub(/\D/, '').to_i)) > 0) ? "#{value} шт." : 'Скрыто'}") end def cost_decorator value html_escape("#{(value).round.to_s}") + "&nbsp;руб.".html_safe end def country_decorator value value.presence || "Скрыто" end def phone_decorator value value.gsub(/(\d{3})(\d{3})(\d{2})(\d{2})/, '(\1) \2-\3-\4') end def probability_decorator value value.present? ? "#{value.to_i}%" : "" end def hint_decorator value, add_class='' raw "<p><span class=\"label #{add_class}\">К сведению</span> #{value}</p>" end def brands_decorator brand, options if Brands::BRANDS[brand].key? :ref return raw Brands::BRANDS[brand][:ref].map{|ref| brands_decorator(ref, options)} end title = "" if options[:title] == true title = Brands::BRANDS[brand][:title].html_safe end link_to title, "/brands/#{Brands::BRANDS[brand][:file]}", :style => "background-image: url(#{asset_path 'brands/' + Brands::BRANDS[brand][:file]}.png)", :class => "brands-#{Brands::BRANDS[brand][:file]}" end end
# frozen_string_literal: true # creates habits records table class CreateHabitRecords < ActiveRecord::Migration[5.0] def change create_table :habit_records do |t| t.string :tz t.datetime :completed_at t.timestamps t.references :habit, index: true end end end
class AddBreadsPerWeekAndPhoneToUsers < ActiveRecord::Migration[6.0] def change add_column :users, :breads_per_week, :decimal, null: false, default: 1 add_column :users, :phone, :string end end
require 'csv2hash/version' require 'csv2hash/definition' require 'csv2hash/validator' require 'csv2hash/validator/mapping' require 'csv2hash/validator/collection' require 'csv2hash/parser' require 'csv2hash/parser/mapping' require 'csv2hash/parser/collection' require 'csv2hash/csv_array' require 'csv2hash/data_wrapper' require 'csv2hash/notifier' require 'csv2hash/extra_validator' require 'csv' class Csv2hash attr_accessor :definition, :file_path, :data, :notifier, :exception_mode, :errors, :ignore_blank_line def initialize definition, file_path, exception_mode=true, data_source=nil, ignore_blank_line=false @data_source = data_source self.definition, self.file_path = definition, file_path dynamic_lib_loading 'Parser' self.exception_mode, self.errors = exception_mode, [] dynamic_lib_loading 'Validator' self.notifier = Notifier.new self.ignore_blank_line = ignore_blank_line init_plugins end def init_plugins begin @plugins = [] ::Csv2hash::Plugins.constants.each do |name| @plugins << ::Csv2hash::Plugins.const_get(name).new(self) end rescue; end end def parse load_data_source definition.validate! definition.default! validate_data! Csv2hash::DataWrapper.new.tap do |response| if valid? fill! response.data = data[:data] else response.valid = false response.errors = csv_with_errors notifier.notify response end end end def csv_with_errors @csv_with_errors ||= begin CsvArray.new.tap do |rows| errors.each do |error| rows << error.merge({ value: (data_source[error[:y]][error[:x]] rescue nil) }) end end #.to_csv end end # protected def data_source @data_source ||= CSV.read self.file_path end alias_method :load_data_source, :data_source private def dynamic_lib_loading type case definition.type when Csv2hash::Definition::MAPPING self.extend Module.module_eval("Csv2hash::#{type}::Mapping") when Csv2hash::Definition::COLLECTION self.extend Module.module_eval("Csv2hash::#{type}::Collection") end end end
require 'rexml/document' require 'rexml/element' require 'dbi' require 'csv' require_relative 'frs_schema_utils' def makePKCol( name ) column = REXML::Element.new( "column" ) column.add_attribute( 'primaryKey', 'true' ); column.add_attribute( 'default', 0 ); column.add_attribute( 'type', "INTEGER" ); column.add_attribute( 'name', name ) return column; end def makeFKRef( target ) fk = REXML::Element.new( "reference" ) fk.add_attribute( "foreign", target ) fk.add_attribute( "local", target ); return fk end def makeFKFRS( target ) fk = REXML::Element.new( "foreign-key" ) fk.add_attribute( 'foreignTable', target ); fk << makeFKRef( "year") fk << makeFKRef( "user_id") fk << makeFKRef( "edition") fk << makeFKRef( "sernum") if( target == 'adult' or target == 'benunit' )then fk << makeFKRef( "benunit" ) end if( target == 'adult' )then fk << makeFKRef( "person" ) end return fk end def createMillTable( tableData ) tableName = tableData.tableName.downcase() tableElem = REXML::Element.new( 'table' ); tableElem.add_attribute( 'name', tableName ); tableElem.add_attribute( 'description', tableName ) tableElem << makePKCol( 'year' ) tableElem << makePKCol( 'user_id' ) tableElem << makePKCol( 'edition' ) puts "tableName #{tableName}\n" puts "needed is #{TABLES_THAT_NEED_COUNTERS.join( "|")}\n" if( TABLES_THAT_NEED_COUNTERS.include?( tableName ))then puts "needs a counter\n" tableElem << makePKCol( 'counter' ) end hasADFK = false hasBUFK = false tableData.variableNames.each{ |vname| var = tableData.variables[vname] column = REXML::Element.new( "column" ) column.add_attribute( "description", var.label ) if( var.adaType == 'Integer' ) then sqlVar = 'INTEGER' default = '0' elsif ( var.adaType == 'Real' ) then sqlVar = 'REAL' default = '0' elsif( var.adaType == 'Sernum_Value' ) then sqlVar = 'BIGINT' column.add_attribute( 'adaTypeName', 'Sernum_Value' ); default = '0' column.add_attribute( 'default', '0' ); elsif( var.adaType == 'Ada.Calendar.Time' ) then sqlVar = 'DATE' end vcu = vname.upcase() isPK = ( vcu == 'SERNUM' or vcu == 'BENUNIT' or vcu == 'PERSON' or # vcu == 'ISSUE' or vcu == 'VEHSEQ' or vcu == 'RENTSEQ' or vcu == 'PENSEQ' or vcu == 'PROVSEQ' or vcu == 'BENEFIT' or # (tableData.tableName == 'OWNER' and vcu == 'ISSUE' ) or (tableData.tableName == 'ASSETS' and vcu == 'ASSETYPE' ) or vcu == 'ODDSEQ' or vcu == 'MORTSEQ' or vcu == 'CONTSEQ' or vcu == 'MAINTSEQ' or vcu == 'JOBTYPE' or vcu == 'EXTSEQ' or vcu == 'MORTSEQ' or vcu == 'ENDOWSEQ' or vcu == 'SEQ' or vcu == 'INSSEQ' or vcu == 'ACCOUNT' or vcu == 'CHLOOK' ) if( isPK ) column.add_attribute( 'primaryKey', 'true' ); end # column.add_attribute( 'default', default ); column.add_attribute( 'type', sqlVar ); column.add_attribute( 'name', vname.downcase() ) tableElem << column if( vcu == 'BENUNIT' ) and ( tableName != 'benunit' ) and ( tableName != 'hbai' ) then hasBUFK = true end if( vcu == 'PERSON' and ( tableName != 'adult' and tableName != 'child' and tableName != 'prscrptn' and tableName != 'benefits' and tableName != 'chldcare' and tableName != 'hbai' ))then # prscrptn, chldcare and benefits since 'person' # field can point to either adult or child records so a PK isn't really possible hasADFK = true end } if( tableName != 'househol')then tableElem << makeFKFRS( 'househol' ) end if hasBUFK then tableElem << makeFKFRS( 'benunit' ) end if hasADFK then tableElem << makeFKFRS( 'adult' ) end return tableElem end loadStatementsFile = File.open( "postgres_load_statements.sql", "w") loadStatementsFile.write( "SET datestyle='MDY';\n") connection = getConnection() stmt = "select distinct year,name from tables" rs = connection.execute( stmt ) tables = Hash.new tableNames = Array.new rs.fetch_hash{ |res| year = res['year'] tableName = res['name'] recordName = recordNameFromTableName( tableName ) table = loadTable( connection, tableName, year ) tableNames << tableName puts "on table #{tableName} year #{year}" if( tables.has_key?( tableName )) then tables[ tableName ] = mergeTables( table, tables[ tableName ]) else tables[ tableName ] = table; end # readFile.write( createConvertProcedure( recordName, year, table ) ) loadStatementsFile.write( makePostgresLoadStatement("/mnt/data/frs/", recordName, table )+"\n") } millDoc = REXML::Document.new(); millDTD = REXML::DocType.new('database PUBLIC "http://virtual-worlds.biz/Mill" "http://www.virtual-worlds.biz/dtds/mill.dtd"'); millDoc << millDTD millDatabase = REXML::Element.new( 'database' ) millDatabase.add_attribute( "name", "frs" ) dpackage = REXML::Element.new( 'adaTypePackage' ) dpackage.add_attribute( "name", "Data_Constants" ) millDatabase << dpackage millDoc << millDatabase tableNames.uniq.each{ |tableName| table = tables[ tableName ] millDatabase << createMillTable( table ) } xmlFile = File.open( "schema.xml", "w") millDoc.write( xmlFile, 8 ) xmlFile.close() connection.disconnect() loadStatementsFile.close()
##################################################################### # tc_library.rb # # Test case for the Windows::Library module. ##################################################################### base = File.basename(Dir.pwd) if base == 'test' || base =~ /windows-pr/ Dir.chdir '..' if base == 'test' $LOAD_PATH.unshift Dir.pwd + '/lib' Dir.chdir 'test' rescue nil end require 'windows/library' require 'test/unit' class Foo include Windows::Library end class TC_Windows_Library < Test::Unit::TestCase def setup @foo = Foo.new end def test_numeric_constants assert_equal(0, Foo::DLL_PROCESS_DETACH) assert_equal(1, Foo::DLL_PROCESS_ATTACH) assert_equal(2, Foo::DLL_THREAD_ATTACH) assert_equal(3, Foo::DLL_THREAD_DETACH) end def test_method_constants assert_not_nil(Foo::FreeLibrary) assert_not_nil(Foo::GetModuleFileName) assert_not_nil(Foo::GetModuleHandle) assert_not_nil(Foo::LoadLibrary) assert_not_nil(Foo::LoadLibraryEx) assert_not_nil(Foo::LoadModule) end def teardown @foo = nil end end
class Move < ApplicationRecord belongs_to :game belongs_to :user validates :move, presence: true, uniqueness: { alert: "to me, it seems to be taken..." } end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :page do sequence(:slug) { |n| "page_#{n}" } template "Article" metadata_id 1 end end
require 'test_helper' class RecipesControllerTest < ActionDispatch::IntegrationTest setup do @author = Author.create(name: "someone") @r1 = Recipe.create(name: 'Lasagne Végétarienne', ingredients: 'Champignon pate', author: @author) @r2 = Recipe.create(name: 'Lasagne', ingredients: 'Champignon champignon viande', author: @author) end test "should get index and return empty recipes" do get recipes_url assert_response :success assert !response.body.include?('Végétarienne') assert !response.body.include?('viande') assert !response.body.include?('pate') assert !response.body.include?('someone') end test "should get index and return both recipes" do get recipes_url params: { search: "Lasagne"} assert_response :success assert response.body.include?('Végétarienne') assert response.body.include?('viande') assert response.body.include?('pate') assert response.body.include?('someone') end end
require 'rails_helper' RSpec.describe Rep, type: :model do # relations it { should belong_to(:exercise)} # validations it { should validate_presence_of(:dt) } it { should validate_presence_of(:qty) } it { should validate_numericality_of(:qty).is_greater_than(0) } it { should validate_numericality_of(:qty2).is_greater_than(0).allow_nil } it { should validate_numericality_of(:qty3).is_greater_than(0).allow_nil } it { should have_db_index(:deleted_at) } end
class Api::ThemesController < ApplicationController skip_before_action :verify_authenticity_token def index render( status: 200, json: {themes: Theme.all}.to_json ) end def show render( status: 200, json: {theme: Theme.find(params[:id])}.to_json ) end def create theme = Theme.new(theme_params) if theme.save render(status: 201, json: {message: "Theme created!", theme: theme}.to_json) else render(status: 422, json: {errors: theme.errors}.to_json) end end def update theme = Theme.find(params[:id]) if theme.update(theme_params) render(status: 200, json: {message: "Theme updated!"}.to_json) else render(status: 422, json: {errors: theme.errors}.to_json) end end def destroy Theme.find(params[:id]).destroy render(status: 200, json: {message: "Theme deleted!"}.to_json) end private def theme_params params.require(:theme).permit(:name) end end
require_relative 'base_email' class ResetPasswordEmail < BaseEmail subject 'Your :app_host password has been reset.' add_anchor 'Forgot your password? Oops.' add_anchor "No biggie - we're giving you a new one, so you can log in and get back to shopping." add_anchor "After all, it's not like you forgot Mother's Day." add_anchor 'Unless "mothersday" was your password - In which case, good luck with that.' add_anchor /Your password for [\w\.+-]+@[\w\.+-]+ has been reset./ add_anchor 'Now go and reset it with something memorable, following these easy steps:' add_anchor '1. Click on the link below' add_anchor '2. When the web page is displayed, enter your new password twice.' add_anchor '3. Click on the Submit button.' add_anchor 'NOTE: Password must be 6 to 15 characters, have one number, one letter, and no spaces.' add_anchor %r{https?://[^/]+/update-password/[^/">\s]+} def reset_password_link text[%r{https?://[^/]+/update-password/[^/">\s]+}] end def token reset_password_link[%r{update-password/(.+)}, 1] end def reset_password UpdatePasswordPage.open(token: token) Capybara.screenshot_and_open_image end end
# Piece is an abstruct class class Piece attr_reader :color, :board attr_accessor :pos def initialize(color, board, pos) @color, @board, @pos = color, board, pos end # def pos=(val) # board[pos] = val # end def to_s "#{symbol}" end def empty? end def valid_moves end # def symbol # symbol # end private def move_into_check?(end_pos) board.move_piece(pos, end_pos) board.in_check?(color) end end
class HomeController < ApplicationController expose(:images) { find_images } private def find_images relation = Image.includes(:gallery) if tag = params[:tag] relation.tagged_with([tag], any: true) elsif word = params[:search] relation.where('title ILIKE ?', "%#{word}%") else relation.all end end end
require 'rails_helper' describe Cardset do let(:cardset) { create(:cardset) } subject { cardset } it { should respond_to(:topic) } it { should respond_to(:description) } it { should respond_to(:author_id) } it { should respond_to(:cards) } it { should be_valid } describe "without author_id" do before { cardset.author_id = nil } it { should_not be_valid } end describe "without topic" do before { cardset.topic = nil } it { should_not be_valid } end describe ".max_order should return the last number of sort_order" do let(:card) { cardset.cards.create(question: "Question", answer: "Answer") } describe "when no level exists" do it { expect(cardset.max_order(1, card.cardset.author_id)).to eq(0) } end describe "when a level exists" do before do card.levels.create(status: 1, sort_order: 1, user_id: card.cardset.author_id) end it { expect(cardset.max_order(1, card.cardset.author_id)).to eq(1) } end end describe "destroy" do before do @cardset_2 = create(:cardset, id: 1, topic: "T1") @selection = @cardset_2.selections.create(user_id: 1, cardset_id: 1) @card = @cardset_2.cards.create(id: 1, cardset_id: 1, question: "Q1", answer: "A1") @card.levels.create(card_id: 1, user_id: 1, status: 1) @cardset_2.destroy end it "should destroy the associated selection" do expect(Selection.find_by_cardset_id(@cardset_2.id)).to be_nil end it "should destroy the cardset itself" do expect(Cardset.find_by_id(@cardset_2.id)).to be_nil end it "should destroy all associated cards, too" do expect(Card.find_by_cardset_id(@cardset_2.id)).to be_nil end it "should destroy all associated levels, too" do expect(Level.find_by_card_id(@card.id)).to be_nil end end end
class CreateGoals < ActiveRecord::Migration def change create_table :goals do |t| t.timestamp :scored_at t.references :game, index: true t.references :team, index: true t.references :position, index: true t.references :player, index: true t.timestamps end end end
class CreateCustomerCards < ActiveRecord::Migration def up create_table :customer_cards do |t| t.column :number,:string t.column :firstname,:string t.column :middlename,:string t.column :lastname,:string t.column :contact,:string t.column :email,:string t.column :birthday,:string t.column :address,:string t.column :points,:integer t.column :status,:string t.column :activator_password,:string t.column :password_digest,:string t.timestamps end end def down drop_table :customer_cards end end
class ComponentDashboard < ApplicationRecord belongs_to :dashboard belongs_to :component end
# frozen_string_literal: true namespace :load do desc "Load the moves from the IMDB top 1000 list" task imdb_top_1000: :environment do ImdbParser.load_list(url: ImdbParser::TOP_1000_LIST_URL) end end
require '/Users/sai/Documents/ada/cs_fun/stacks-queues/lib/Queue.rb' require '/Users/sai/Documents/ada/cs_fun/stacks-queues/lib/Stack.rb' class JobSimulation attr_reader :workers, :waiting, :roll def initialize jobs_available, job_seekers @waiting = Queue.new job_seekers.times do |seeker| @waiting.enqueue("Worker ##{seeker+1}") end @workers = Stack.new jobs_available.times do |worker| @workers.push(@waiting.dequeue) end end def cycle roll = rand(1..6) puts "We are moving #{roll} people" roll.times do puts "Fire: #{@workers.top}" @waiting.enqueue(@workers.pop) end roll.times do puts "Hire: #{@waiting.front}" @workers.push(@waiting.dequeue) end #take roll number of workers off the end of the stack and move them to back of waiting. #take roll number of waiting from the front of queue and move them to back of workers end end ## Allows us to run our code and see what's happening: sim = JobSimulation.new(6,10) puts "------------------------------" puts "Before the simulation starts" puts "Employed: #{sim.workers}" puts "Waitlist: #{sim.waiting}" puts "------------------------------" print "<enter to cycle>\n" count = 0 until gets.chomp != "" puts "-------Cycle #{count+=1}-------" sim.cycle puts "Employed: #{sim.workers}" puts "Waitlist: #{sim.waiting}" end # SAMPLE RUN OF CODE # # ------------------------------ # Before the simulation starts # Employed: ["Worker #1", "Worker #2", "Worker #3", "Worker #4", "Worker #5", "Worker #6"] # Waitlist: ["Worker #7", "Worker #8", "Worker #9", "Worker #10"] # ------------------------------ # <enter to cycle> # # -------Cycle 1------- # We are moving 3 people # Fire: Worker #6 # Fire: Worker #5 # Fire: Worker #4 # Hire: Worker #7 # Hire: Worker #8 # Hire: Worker #9 # Employed: ["Worker #1", "Worker #2", "Worker #3", "Worker #7", "Worker #8", "Worker #9"] # Waitlist: ["Worker #10", "Worker #6", "Worker #5", "Worker #4"] # # -------Cycle 2------- # We are moving 2 people # Fire: Worker #9 # Fire: Worker #8 # Hire: Worker #10 # Hire: Worker #6 # Employed: ["Worker #1", "Worker #2", "Worker #3", "Worker #7", "Worker #10", "Worker #6"] # Waitlist: ["Worker #5", "Worker #4", "Worker #9", "Worker #8"] # # -------Cycle 3------- # We are moving 1 people # Fire: Worker #6 # Hire: Worker #5 # Employed: ["Worker #1", "Worker #2", "Worker #3", "Worker #7", "Worker #10", "Worker #5"] # Waitlist: ["Worker #4", "Worker #9", "Worker #8", "Worker #6"] # # -------Cycle 4------- # We are moving 6 people # Fire: Worker #5 # Fire: Worker #10 # Fire: Worker #7 # Fire: Worker #3 # Fire: Worker #2 # Fire: Worker #1 # Hire: Worker #4 # Hire: Worker #9 # Hire: Worker #8 # Hire: Worker #6 # Hire: Worker #5 # Hire: Worker #10 # Employed: ["Worker #4", "Worker #9", "Worker #8", "Worker #6", "Worker #5", "Worker #10"] # Waitlist: ["Worker #7", "Worker #3", "Worker #2", "Worker #1"]
# encoding: utf-8 require 'spec_helper' describe SimpleSpreadsheet do let(:xls_file) { File.expand_path '../fixtures/file.xlsx', __FILE__ } let(:file_path) { Pathname.new xls_file } it 'allows pathnames as filename argument without raising exception' do expect { SimpleSpreadsheet::Workbook.read(file_path) }.to_not raise_error(NoMethodError) end end
class FplTeamListsController < ApplicationController before_action :authenticate_user! skip_before_action :verify_authenticity_token before_action :set_fpl_team_list, only: [:show, :update] before_action :set_fpl_team, only: [:index, :show, :update] respond_to :json # GET /fpl_teams/1/fpl_team_lists # GET /fpl_teams/1/fpl_team_lists.json def index render json: fpl_team_list_hash end # GET /fpl_team_lists/1 # GET /fpl_team_lists/1.json def show render json: fpl_team_list_hash end # PATCH/PUT /fpl_team_lists/1 # PATCH/PUT /fpl_team_lists/1.json def update player = Player.find_by(id: params[:player_id]) target = Player.find_by(id: params[:target_id]) form = ::FplTeams::ProcessSubstitutionForm.new( fpl_team_list: @fpl_team_list, player: player, target: target, current_user: current_user ) if form.save render json: fpl_team_list_hash.merge!(success: "Successfully substituted #{player.name} with #{target.name}.") else render json: fpl_team_list_hash.merge!(errors: form.errors.full_messages), status: :unprocessable_entity end end private # Use callbacks to share common setup or constraints between actions. def set_fpl_team_list @fpl_team_list = FplTeamList.find(params[:id]) end def set_fpl_team @fpl_team = FplTeam.find_by(id: params[:fpl_team_id]) end # Never trust parameters from the scary internet, only allow the white list through. def fpl_team_list_params params.fetch(:fpl_team_list, {}) end def fpl_team_list_hash return {} unless @fpl_team.active fpl_team_decorator = FplTeamDecorator.new(@fpl_team) fpl_team_list_decorator = FplTeamListDecorator.new( @fpl_team_list || fpl_team_decorator.current_fpl_team_list ) rounds_decorator = fpl_team_decorator.fpl_team_list_rounds line_up = if @fpl_team_list ListPositionsDecorator.new(@fpl_team_list.list_positions).list_position_arr else fpl_team_decorator.current_line_up end { rounds: rounds_decorator, round: fpl_team_list_decorator.round, fpl_team_lists: fpl_team_decorator.fpl_team_lists.order(:round_id), fpl_team_list: fpl_team_list_decorator, line_up: line_up, status: Round.round_status(round: fpl_team_list_decorator.round), unpicked_players: LeagueDraftPicksDecorator.new(@fpl_team.league).unpicked_players, score: fpl_team_list_decorator.score, submitted_in_trade_group_count: fpl_team_list_decorator.submitted_in_trade_group_count, approved_out_trade_group_count: fpl_team_list_decorator.approved_out_trade_group_count, declined_out_trade_group_count: fpl_team_list_decorator.declined_out_trade_group_count } end end
require_relative 'worker_thread' class Channel MAX_REQUEST = 100 attr_reader :workers def initialize(number_of_workers) @queue = Array.new(MAX_REQUEST) @head = 0 @tail = 0 @count = 0 @mutex = Thread::Mutex.new @full_cond = Thread::ConditionVariable.new @empty_cond = Thread::ConditionVariable.new @workers = number_of_workers.times.map do |i| WorkerThread.new("Worker-#{i}", self) end end def put(request) @mutex.synchronize do while @count >= @queue.size @full_cond.wait(@mutex) end @queue[@tail] = request @tail = (@tail + 1) % @queue.size @count += 1 @empty_cond.broadcast end end def take @mutex.synchronize do while @count <= 0 @empty_cond.wait(@mutex) end request = @queue[@head] @head = (@head + 1) % @queue.size @count -= 1 @full_cond.broadcast request end end end
module VraptorScaffold module Runner class Start def run(args) validate Kernel.system("ant vraptor-scanning") Kernel.system("sh $APPENGINE_SDK_HOME/bin/dev_appserver.sh #{Configuration::WEB_APP}") end private def validate unless File.exist?("src") Kernel.puts "To run vraptor start please go to the project root folder." Kernel::exit end unless Configuration.orm == "objectify" Kernel.puts "vraptor start command is available only for gae apps." Kernel::exit end unless ENV['APPENGINE_SDK_HOME'] Kernel.puts "To run vraptor start, configure environment variable APPENGINE_SDK_HOME." Kernel::exit end end end end end
class RemoveAttributefromVideo < ActiveRecord::Migration[5.1] def change remove_column :videos, :video_image add_attachment :videos, :image end end
module Api class SessionController < ApplicationApiController def create valid, obj = User.signIn session_params if valid render json: obj, status: :ok else render :json => { :mssg => 'There was an error signing in' }, status: :unprocessable_entity end end def session_params params.require(:session).permit(:email, :password) end def checkin json = {} json[:profile] = user_as_json(current_user) render json: json end end end
require 'spec_helper' describe Sprawl do it 'has a version number' do expect(Sprawl::VERSION).not_to be nil end end
require 'spec_helper' describe Subscription do before do @subscription = Factory(:subscription) end it { should belong_to(:user) } it { should belong_to(:topic) } it { should validate_presence_of(:topic_id) } it { should validate_presence_of(:user_id) } it { should validate_uniqueness_of(:topic_id).scoped_to(:user_id) } context "upon creation" do it "generates hash_key based on topic_id and user's email" do @subscription.hash_key.should_not be_nil end end end
When(/^Estar logado na aplicação e ter acesso a funcionalidade de incluir Leads$/) do visit 'https://app-staging.rdstation.com.br/login' #Informar os dados de acesso. fill_in 'user_email', with: 'marciosacco@gmail.com' fill_in 'user_password', with: 'Asdf0147*' #Clicar no botão de entrar usando o Xpath page.find(:xpath, '//*[@id="login-form"]/div[3]/div[2]/input').click #Acessar o menu Relacionar page.find(:xpath, '//*[@id="relate-menu"]/a').click #Acessar o submenu Base de leads page.find(:xpath, '//*[@id="relate-menu"]/ul/li[2]/a').click end When(/^Acessar a funcionalidade de Inserir Leads$/) do #Acessar o menu para ver as opções page.find(:xpath, '//*[@id="leads_crm"]/div[1]/div/div[2]/div/button').click #Acessar a funcionalidade de Inserir leads page.find(:xpath, '//*[@id="leads_crm"]/div[1]/div/div[2]/div/ul/li[1]/a').click end When(/^Preencher os campos da seção de Converção: <Nome do evento> Identificação: 'Nome', 'E\-mail', 'Cargo' Informações de contato: 'Telefone Fixo', 'Telefone celular', 'Twitter', 'Facebook', 'LinkedIn', 'Site\/Blog', 'Estado', 'Cidade' \tInformações da empresa: 'Nome', 'Setor', 'Tamanho \(colaboradores\)', 'Site', 'Twitter', 'Facebook', 'Telefone', 'Endereço' Informações adicionais: 'Dono do lead', 'Anotações'$/) do #Informando os dados no Lead #Conversão fill_in 'source', with: 'Primeiro Teste' #Identificação fill_in 'lead_name', with: 'Nome' fill_in 'lead_email', with: 'teste@teste.ui' fill_in 'lead_job_title', with: 'Analista de testes' #Informações de contato fill_in 'lead_lead_info_attributes_personal_phone', with: '9999966633' fill_in 'lead_lead_info_attributes_mobile_phone', with: '996655663366' fill_in 'lead_lead_info_attributes_twitter', with: 'marcioteste' fill_in 'lead_lead_info_attributes_facebook', with: 'marcioteste' fill_in 'lead_lead_info_attributes_linkedin', with: 'marcioteste' fill_in 'lead_lead_info_attributes_website', with: 'marcioteste.com.br/blog' page.select 'SC', from: 'inputUfTitle' #page.find(:id, 'select2-chosen-1').click #page.select 'Angelina', from: 'select2-chosen-1' #Informações da empresa fill_in 'lead_company_attributes_name', with: 'Empresa de Teste' page.select 'Ecommer', from:'lead_company_attributes_company_sector_id' page.select '11-25', from:'lead_company_attributes_size' fill_in 'lead_company_attributes_email', with: 'teste@teste.com.br' fill_in 'lead_company_attributes_site', with: 'empresadeteste.com.br' fill_in 'lead_company_attributes_twitter', with: 'teste' fill_in 'lead_company_attributes_facebook', with: 'teste' fill_in 'lead_company_attributes_phone', with: '99999999' fill_in 'lead_company_attributes_address', with: 'Rua dos carijos, 34, Centro, Florianópolis-sc' page.select 'marciosacco@gmail.com', from:'lead_user_id' fill_in 'lead_bio', with: 'Nada de mais para anotar.' #Salvando os dados page.find(:xpath, '//*[@id="new_lead"]/div[2]/div/input').click end #Validando e-mail When(/^Preencher os dados obregatórios, informar na seção Identificação o 'E\-mail' inválido e submeter a operação de Salvar$/)do #Conversão fill_in 'source', with: 'Teste validação email' #Identificação fill_in 'lead_name', with: 'Nome teste' fill_in 'lead_email', with: 'teste@t' page.find(:id, 'lead_job_title').click page.find(:xpath, '//*[@id="new_lead"]/div[2]/div/input').click #Caso apresente algum erro o será efetuado um print na tela como evidencia if expect(page).to have_content('Digite um endereço de e-mail válido').exception file_name = 'failed_%s.png' % rand(1000).to_s page.save_screenshot(file_name) end end #Validar campos obrigatórios When(/^Não preenhcer os campo obrigatório e submeter a operação de Salvar$/) do page.find(:xpath, '//*[@id="new_lead"]/div[2]/div/input').click #Caso apresente algum erro o será efetuado um print na tela como evidencia if expect(page).to have_content('Não foi possível criar o Lead, por favor verifique os campos').exception file_name = 'failed_%s.png' % rand(1000).to_s page.save_screenshot(file_name) end end #Excluir Lead When(/^Clicar no Lead que deseja excluir$/) do click_link 'Nome' end When(/^Expandir as opções de 'Editar' e selecionar a opção de 'Apagar lead'$/) do page.find(:xpath, '//*[@id="lead-options"]/button').click page.find(:xpath, '//*[@id="lead-options"]/ul/li[2]/a').click end
require './quicksort_op4.rb' require 'benchmark' LISTS = [ [100], (1..100_000).to_a.shuffle, (1..100_000).to_a, (1..100_000).to_a.reverse, 100_000.times.collect{rand(10)} | 100_000.times.collect{rand(1_000_000)}, (1..100_000).to_a.zip(100_001..200_000).flatten, 10000.times.collect{(0...rand(50)).map { ('a'..'z').to_a[rand(26)] }.join} ] SORTED_LISTS = LISTS.collect{|l| [l, l.sort]} def benchmark puts Benchmark.measure { 20.times do SORTED_LISTS.each do |(arg, expected)| result = sort(arg.dup) unless result == expected raise "Test failure!" end end end } end benchmark
require './base.rb' class Q6::Method < Base def self.execute puts "「y」 キーを押してスロットマシーンを回してください!" begin input_key = gets.chomp unless input_key == "y" raise end rescue puts "「y」キーを押してください" retry end numbers = [1, 3, 5, 7] number = numbers.sample number2 = numbers.sumple number3 = numbers.sample Q6::Method.check_numbers(number: number, number2: number2, number3: number3) rescue puts "エラーが発生しています。どこでエラーしているのか調査しましょう。" end private def self.check_numbers(number:, number2:, number3:) same_numbers_count = Q6::Method.count_same_numbers(number: number, number2: number2, number3: number3) puts "結果: |#{number}|#{number2}|#{number3}|" case same_numbers_count when 1 puts "残念!ハズレ!" when 2 puts "惜しい!" when 3 puts "大当たり!" end end def self.count_same_numbers(number:, number2:, number3:) same_numbers_count = if (number == number2 && number == number3) 2 elsif number == number2 || number == number3 || number2 == number3 1 else 0 end same_numbers_count end end
class CreatePushNotifications < ActiveRecord::Migration def change create_table :push_notifications do |t| t.integer :push_notifiable_id, index: true t.string :push_notifiable_type, index: true t.text :message t.timestamps end end end
# -*- coding: utf-8 -*- # Module for FileDocument models module FileDocumentsHelper def link_to_file(id = '', link_text = 'File', file_type = 'document', mouse_over = nil, is_required = false, required_path = nil, lookup_file_type = true) if id.blank? || (id.to_i < 1) if is_required.blank? || is_required == false return '' elsif required_path.blank? return image_tag('warning_16.png', width: '16px', height: '16px') else mouse_over ||= '' return link_to(link_text.html_safe, required_path, title: "Please upload #{link_text} #{mouse_over}".strip.html_safe, class: 'warning_16') end end if lookup_file_type file_name = FileDocument.find(id).file_file_name file_format = file_name.gsub(/(.*)\.([^\.+])/, '\2') file_format = 'txt' if file_format == file_name file_type = 'pdf' if file_format.to_s == 'pdf' else file_type = 'document' file_format = 'txt' end mouse_over = link_text if mouse_over.nil? mouse_over = file_name if mouse_over.blank? link_to(link_text.html_safe, file_document_path(id, format: file_format), title: "Download #{mouse_over}".html_safe, target: '_blank', class: determine_image_class(file_type)) end def determine_image_class(file_type) case file_type when :document, 'document', 'txt' 'page_white_put' when :spreadsheet, 'spreadsheet' 'page_excel' when :pdf, 'pdf' 'page_white_acrobat' else 'documenticon' end end end
# frozen_string_literal: true # game of life v 0.0001 # x - 1, y - 1 | x, y - 1 | x + 1, y - 1 # x - 1, y | x, y | x + 1, y # x - 1, y + 1 | x, y + 1 | x + 1, y + 1 # class Cell class Cell def initialize @live = [true, false].sample # [' ', '*'].sample end def alive? @live end def dead? !@live end def live! @live = true end def dead! @live = false end def show_status @live ? '*' : ' ' end end # class Universe class Universe def initialize @universe = Array.new(40) { Array.new(20) { Cell.new } } end def check(cell_x, cell_y) count = 0 cell_x = -1 if cell_x >= @universe.size - 1 cell_y = -1 if cell_y >= @universe[0].size - 1 @universe[cell_x - 1][cell_y - 1].alive? ? count += 1 : count @universe[cell_x][cell_y - 1].alive? ? count += 1 : count @universe[cell_x + 1][cell_y - 1].alive? ? count += 1 : count @universe[cell_x - 1][cell_y].alive? ? count += 1 : count @universe[cell_x + 1][cell_y].alive? ? count += 1 : count @universe[cell_x - 1][cell_y + 1].alive? ? count += 1 : count @universe[cell_x][cell_y + 1].alive? ? count += 1 : count @universe[cell_x + 1][cell_y + 1].alive? ? count += 1 : count if @universe[cell_x][cell_y].alive? if [2, 3].include?(count) @universe[cell_x][cell_y].live! elsif count < 2 || count > 3 @universe[cell_x][cell_y].dead! else puts 'Error' exit end elsif @universe[cell_x][cell_y].dead? @universe[cell_x][cell_y].live! if count == 3 else puts 'Dead End' end end def neighborhood @universe.each do |row| row.each do |col| check(@universe.index(row), row.index(col)) end end show end def show @universe.map { |row| p row.map(&:show_status) } end end u = Universe.new loop do sleep 0.45 system('clear') u.neighborhood end
class ProfileSkill < ApplicationRecord belongs_to :profile belongs_to :skill #validtaion validates_presence_of :profile, :skill, :level end
module Testy class Runnable def register(klass) @runnable_list ||= [] @runnable_list << klass end def run(reporter) @runnable_list.each { |klass| klass.run reporter } end end end
# Return Value of break # In the previous exercise, you learned that the while loop returns nil unless break is used. Locate the documentation for break, and determine what value break sets the return value to for the while loop. # The documentation does not spell out a return value for break when it is not supplied with a value. # Solution # break returns nil when no arguments are passed to break, or the value of the argument when an argument is provided. # # Discussion # Documentation for break is on the "control expressions" page. It tells you that break returns the value of the argument when given an argument. However, it doesn't explicitly say what happens when you don't. # # You have to read between the lines here; the while loop documentation says that while returns nil unless break receives a value. So, if break is not supplied a value, while still returns nil. # # Another way of figuring out that break returns nil when not given an argument comes from knowing that all statements in Ruby return a value -- usually nil unless the documentation says otherwise. Since no other return value makes sense for break, nil is the most likely value. However, this requires a bit of looking into the mind of the designer. # # You can also write and run a simple program, either in irb or as a program file, to see what the return value is: result = while true break end p result # In irb, the return value is nil.
# encoding: utf-8 # vim: ft=ruby expandtab shiftwidth=2 tabstop=2 require 'shellwords' # node.set_unless[:wpcli][:dbpassword] = secure_password execute "mysql-install-wp-privileges" do command "/usr/bin/mysql -u root -p\"#{node[:mysql][:server_root_password]}\" < #{node[:mysql][:conf_dir]}/wp-grants.sql" action :nothing end template File.join(node[:mysql][:conf_dir], '/wp-grants.sql') do source "grants.sql.erb" owner node[:wpcli][:user] group node[:wpcli][:group] mode "0600" variables( :user => node[:wpcli][:dbuser], :password => node[:wpcli][:dbpassword], :database => node[:wpcli][:dbname] ) notifies :run, "execute[mysql-install-wp-privileges]", :immediately end execute "create wordpress database" do command "/usr/bin/mysqladmin -u root -p\"#{node[:mysql][:server_root_password]}\" create #{node[:wpcli][:dbname]}" not_if do # Make sure gem is detected if it was just installed earlier in this recipe require 'rubygems' Gem.clear_paths require 'mysql' m = Mysql.new("localhost", "root", node[:mysql][:server_root_password]) m.list_dbs.include?(node[:wpcli][:dbname]) end notifies :create, "ruby_block[save node data]", :immediately unless Chef::Config[:solo] end directory File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_home]) do recursive true owner node[:wpcli][:user] group node[:wpcli][:group] end bash "wordpress-core-download" do user node[:wpcli][:user] group node[:wpcli][:group] if node[:wpcli][:wp_version] == 'latest' then code <<-EOH WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp core download \\ --path=#{File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl])} \\ --locale=#{Shellwords.shellescape(node[:wpcli][:locale])} \\ --force EOH elsif node[:wpcli][:wp_version] =~ %r{^http(s)?://.*?\.zip$} code <<-EOH cd /tmp && wget -O ./download.zip #{Shellwords.shellescape(node[:wpcli][:wp_version])} && unzip -d /var/www/ ./download.zip && rm ./download.zip EOH else code <<-EOH WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp core download \\ --path=#{File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl])} \\ --locale=#{Shellwords.shellescape(node[:wpcli][:locale])} \\ --version=#{Shellwords.shellescape(node[:wpcli][:wp_version].to_s)} \\ --force EOH end end file File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl], "wp-config.php") do action :delete backup false end bash "wordpress-core-config" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code <<-EOH WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp core config \\ --dbhost=#{Shellwords.shellescape(node[:wpcli][:dbhost])} \\ --dbname=#{Shellwords.shellescape(node[:wpcli][:dbname])} \\ --dbuser=#{Shellwords.shellescape(node[:wpcli][:dbuser])} \\ --dbpass=#{Shellwords.shellescape(node[:wpcli][:dbpassword])} \\ --dbprefix=#{Shellwords.shellescape(node[:wpcli][:dbprefix])} \\ --locale=#{Shellwords.shellescape(node[:wpcli][:locale])} \\ --extra-php <<PHP define( 'WP_HOME', 'http://#{File.join(node[:wpcli][:wp_host], node[:wpcli][:wp_home]).sub(/\/$/, '')}' ); define( 'WP_SITEURL', 'http://#{File.join(node[:wpcli][:wp_host], node[:wpcli][:wp_siteurl]).sub(/\/$/, '')}' ); define( 'JETPACK_DEV_DEBUG', #{node[:wpcli][:debug_mode]} ); define( 'WP_DEBUG', #{node[:wpcli][:debug_mode]} ); define( 'FORCE_SSL_ADMIN', #{node[:wpcli][:force_ssl_admin]} ); define( 'SAVEQUERIES', #{node[:wpcli][:savequeries]} ); #{if node[:wpcli][:is_multisite] == true then <<MULTISITE define( 'WP_ALLOW_MULTISITE', true ); MULTISITE end} PHP EOH end if node[:wpcli][:always_reset] == true then bash "wordpress-db-reset" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp db reset --yes" end end bash "wordpress-core-install" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code <<-EOH WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp core install \\ --url=http://#{File.join(node[:wpcli][:wp_host], node[:wpcli][:wp_siteurl])} \\ --title=#{Shellwords.shellescape(node[:wpcli][:title])} \\ --admin_user=#{Shellwords.shellescape(node[:wpcli][:admin_user])} \\ --admin_password=#{Shellwords.shellescape(node[:wpcli][:admin_password])} \\ --admin_email=#{Shellwords.shellescape(node[:wpcli][:admin_email])} EOH end unless node[:wpcli][:wp_home] == node[:wpcli][:wp_siteurl] unless File.exist?(File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_home], 'index.php')) template File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_home], 'index.php') do source "index.php.erb" owner node[:wpcli][:user] group node[:wpcli][:group] mode "0644" variables( :path => File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) ) end end end if node[:wpcli][:locale] == 'ja' then bash "wordpress-plugin-ja-install" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp plugin activate wp-multibyte-patch" end end node[:wpcli][:default_plugins].each do |plugin| bash "WordPress #{plugin} install" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp plugin install #{Shellwords.shellescape(plugin)} --activate" end end if node[:wpcli][:default_theme] != '' then bash "WordPress #{node[:wpcli][:default_theme]} install" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp theme install #{Shellwords.shellescape(node[:wpcli][:default_theme])}" end bash "WordPress #{node[:wpcli][:default_theme]} activate" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp theme activate #{File.basename(Shellwords.shellescape(node[:wpcli][:default_theme])).sub(/\..*$/, '')}" end end if node[:wpcli][:theme_unit_test] == true then remote_file node[:wpcli][:theme_unit_test_data] do source node[:wpcli][:theme_unit_test_data_url] mode 0644 action :create end bash "Import theme unit test data" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp plugin install wordpress-importer --activate" end bash "Import theme unit test data" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp import --authors=create #{Shellwords.shellescape(node[:wpcli][:theme_unit_test_data])}" end end node[:wpcli][:options].each do |key, value| bash "Setting up WordPress option #{key}" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp option update #{Shellwords.shellescape(key.to_s)} #{Shellwords.shellescape(value.to_s)}" end end if node[:wpcli][:rewrite_structure] then bash "Setting up rewrite rules" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp rewrite structure #{Shellwords.shellescape(node[:wpcli][:rewrite_structure])}" end bash "Flush rewrite rules" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp rewrite flush --hard" end end if node[:wpcli][:is_multisite] == true then bash "Setup multisite" do user node[:wpcli][:user] group node[:wpcli][:group] cwd File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) code "WP_CLI_CONFIG_PATH=#{Shellwords.shellescape(node[:wpcli][:config_path])} wp core multisite-convert" end template File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_home], '.htaccess') do source "multisite.htaccess.erb" owner node[:wpcli][:user] group node[:wpcli][:group] mode "0644" end end template File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_home], '.gitignore') do source "gitignore.erb" owner node[:wpcli][:user] group node[:wpcli][:group] mode "0644" action :create_if_missing variables( :siteurl => File.join(node[:wpcli][:wp_siteurl], '/'), ) end apache_site "000-default" do enable false end web_app "wordpress" do template "wordpress.conf.erb" docroot node[:wpcli][:wp_docroot] server_name node[:fqdn] end bash "create-ssl-keys" do user "root" group "root" cwd File.join(node[:apache][:dir], 'ssl') code <<-EOH openssl genrsa -out server.key 2048 openssl req -new -key server.key -subj '/C=JP/ST=Wakayama/L=Kushimoto/O=My Corporate/CN=#{node[:fqdn]}' -out server.csr openssl x509 -in server.csr -days 365 -req -signkey server.key > server.crt EOH notifies :restart, "service[apache2]" end iptables_rule "wordpress-iptables"
class Entry < ApplicationRecord belongs_to :day, optional: true attr_accessor :user scope :archived, -> { where.not(:archived_at => nil) } scope :not_archived, -> { where(:archived_at => nil) } def archive self.archived_at = DateTime.now self.save end def unarchive self.archived_at = nil self.save end before_create do self.datetime ||= DateTime.now day = Day.find_or_create(self.datetime) self.day_id = day.id end before_update do if self.datetime_changed? day = Day.find_or_create(self.datetime) self.day_id = day.id end end end
class Api::V2::NoticesController < ApplicationController before_action :set_notice, only: [:show, :edit, :update, :destroy] def allNotices @campus_id = params[:campus_id] if @campus_id == nil @notices = Notice.where("date >= ?", (Time.now - 3.day).to_i) else @notices = Notice.where("campus_id = ? and date >= ?", @campus_id , (Time.now - 3.day).to_i) end render json: @notices end def redirect @id = params[:id] @notice = Notice.find_by(:id => @id) end def webPage redirect_to 'https://db.jimu.kyutech.ac.jp/cgi-bin/cbdb/db.cgi?page=DBRecord&did=391&qid=all&vid=24&rid=50&Head=&hid=&sid=n&rev=0&ssid=3-693-26272-g181' end def notice @id = params[:id] @notice = Notice.find_by(:id => @id) render json: @notice end end
module MLP class MLP def initialize(opts) # default initial weight is random, but # if someone wants to be fancy and pass in some # parameters we will let them. opts[:initial_weight] ||= Proc.new { |a, b, c| rand } opts[:learning_rate] ||= 0.1 opts[:structure] ||= [2, 2, 2] opts[:momentum] ||= 0.0001 @structure = opts[:structure] @learning_rate = opts[:learning_rate] @threshold_function = Proc.new { |net| 1 / (1 + Math.exp(-net)) } @threshold_function_derivative = Proc.new { |out| out * (1 - out) } @initial_weight = opts[:initial_weight] @momentum = opts[:momentum] initialize_nodes initialize_weights initialize_weight_change if @momentum end def initialize_nodes @nodes = Array.new(@structure.length) do |n| Array.new(@structure[n], 1.0) end # binding.pry end #initialize weights matrix # @weights is an array of 2d weight matricies # o_1 o_2 o_3 ect # input_1 # input_2 # input_3 # ect # To get the weight from input node i to output node j of # layer l, @weights[l][i][j] def initialize_weights @weights = initialize_weight_matrix(@initial_weight) end def initialize_weight_matrix(initial_value_function) weights = Array.new(@structure.length - 1) do |i| origin_nodes = @structure[i] target_nodes = @structure[i + 1] Array.new(origin_nodes) do |j| Array.new(target_nodes) do |k| initial_value_function.call(i, j, k) end end end weights end # Initializes a structure to track last weight changes. def initialize_weight_change @previous_weight_changes = initialize_weight_matrix(Proc.new { |a,b,c| 0.0 }) end def calculate_output(input) fill_in_input_layer(input) @weights.each_index do |i| @structure[i + 1].times do |j| sum = 0.0 @nodes[i].each_index do |k| begin sum += (@nodes[i][k] * @weights[i][k][j]) rescue NoMethodError => e binding.pry end end @nodes[i+1][j] = @threshold_function.call(sum) end end @nodes.last end def fill_in_input_layer(input) # binding.pry input.each_index do |i| @nodes.first[i] = input[i] end end def backpropogate(expected_output) calculate_error_for_output(expected_output) calculate_error_for_hidden_layers end def calculate_error_for_output(expected_output) output_values = @nodes[-1] output_error = [] output_values.each_index do |index| output_error << (expected_output[index] - output_values[index]) * @threshold_function_derivative.call(output_values[index]) end @errors = [output_error] end def calculate_error_for_hidden_layers previous_error = @errors[-1] (@nodes.size - 2).downto(1) do |n| layer_error = [] @nodes[n].each_index do |i| err = 0.0 @structure[n + 1].times do |j| err += previous_error[j] * @weights[n][i][j] end layer_error[i] = (@threshold_function_derivative.call(@nodes[n][i]) * err) end previous_error = layer_error @errors.unshift(layer_error) end end def update_weights_from_error (@weights.length - 1).downto(0) do |n| @weights[n].each_index do |i| @weights[n][i].each_index do |j| delta_w = @nodes[n][i] * @errors[n][j] change = @learning_rate * delta_w if @momentum change += @momentum * @previous_weight_changes[n][i][j] @previous_weight_changes[n][i][j] = @weights[n][i][j] end @weights[n][i][j] += change end end end end # Given an input, and an array of expected # output values of the final layer, update # the weights of the neural net to fit. def train(input, expected_output) # binding.pry output = calculate_output(input) backpropogate(expected_output) update_weights_from_error calculate_error(output, expected_output) end def calculate_error(output, expected_output) error = 0.0 expected_output.each_index do |i| error += 0.5 * (output[i] - expected_output[i]) ** 2 end error end # Given a data point as an array of attribute values, # return the index of the output node with the highest activation. # This corresponds to the predicted class. def get_predicted_class(input, class_array) output = calculate_output max = output.find_index(output.max) class_array[max] end end end
class RemoveGroupColumnFromPests < ActiveRecord::Migration[5.1] def change remove_column :pests, :group, :string end end
component 'repo_definition' do |pkg, settings, platform| pkg.version '2018.3.22' if platform.is_deb? pkg.url "file://files/#{settings[:target_repo]}.list.txt" pkg.install_configfile "#{settings[:target_repo]}.list.txt", "/etc/apt/sources.list.d/#{settings[:target_repo]}.list" pkg.install do "sed -i 's|__CODENAME__|#{platform.codename}|g' /etc/apt/sources.list.d/#{settings[:target_repo]}.list" end else # Specifying the repo path as a platform config var is likely the # way to go if anything else needs to get added here: if platform.is_cisco_wrlinux? repo_path = '/etc/yum/repos.d' elsif platform.is_sles? repo_path = '/etc/zypp/repos.d' else repo_path = '/etc/yum.repos.d' end pkg.url "file://files/#{settings[:target_repo]}.repo.txt" pkg.install_configfile "#{settings[:target_repo]}.repo.txt", "#{repo_path}/#{settings[:target_repo]}.repo" install_hash = ["sed -i -e 's|__OS_NAME__|#{platform.os_name}|g' -e 's|__OS_VERSION__|#{platform.os_version}|g' #{repo_path}/#{settings[:target_repo]}.repo"] # The repo definion on sles is invalid unless each gpg key begins with a # a '='. This isn't the case for other rpm platforms, so we get to modify # the repo file after we install it on sles. if platform.is_sles? install_hash << "sed -i -e 's|file:///etc/pki/rpm-gpg/RPM-GPG-KEY-#{settings[:target_repo]}-release|=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-#{settings[:target_repo]}-release|g' #{repo_path}/#{settings[:target_repo]}.repo" end pkg.install do install_hash end end end
require 'spec_helper' describe Workfile do describe "validations" do context "file name with valid characters" do it "is valid" do workfile = Workfile.new :file_name => 'work_(-file).sql' workfile.should be_valid end end context "file name with question mark" do it "is not valid" do workfile = Workfile.new :file_name => 'workfile?.sql' workfile.should_not be_valid workfile.errors[:file_name].should_not be_empty end end context "normalize the file name" do let!(:another_workfile) { FactoryGirl.create(:workfile, :file_name => 'workfile.sql') } context "first conflict" do it "renames and turns the workfile valid" do workfile = Workfile.new(:versions_attributes => [{:contents => test_file("workfile.sql", "text/sql")}]) workfile.workspace = another_workfile.workspace workfile.owner = another_workfile.owner workfile.should be_valid workfile.file_name.should == 'workfile_1.sql' end end context "multiple conflicts" do let(:workspace) { FactoryGirl.create(:workspace) } let!(:another_workfile_1) { FactoryGirl.create(:workfile, :workspace => workspace, :file_name => 'workfile.sql') } let!(:another_workfile_2) { FactoryGirl.create(:workfile, :workspace => workspace, :file_name => 'workfile.sql') } it "increases the version number" do workfile = Workfile.new :file_name => 'workfile.sql' workfile.workspace = workspace workfile.owner = another_workfile_1.owner workfile.save workfile.should be_valid workfile.file_name.should == 'workfile_2.sql' end end end end describe ".validate_name_uniqueness" do let!(:workspace) { FactoryGirl.create(:workspace) } let!(:other_workspace) { FactoryGirl.create(:workspace) } let!(:existing_workfile) { FactoryGirl.create(:workfile, :workspace => workspace, :file_name => 'workfile.sql') } it "returns false and adds an error to the error list if name in workspace is taken" do new_workfile = Workfile.new :file_name => 'workfile.sql' new_workfile.workspace = workspace new_workfile.validate_name_uniqueness.should be_false new_workfile.errors[:file_name].should_not be_empty end it "returns true if there are no conflicts in its own workspace" do new_workfile = Workfile.new :file_name => 'workfile.sql' new_workfile.workspace = other_workspace new_workfile.validate_name_uniqueness.should be_true new_workfile.errors[:file_name].should be_empty end end describe ".create_from_file_upload" do let(:user) { users(:admin) } let(:workspace) { workspaces(:public_with_no_collaborators) } shared_examples "file upload" do it "creates a workfile in the database" do subject.should be_valid subject.should be_persisted end it "creates a workfile version in the database" do subject.versions.should have(1).version version = subject.versions.first version.should be_valid version.should be_persisted end it "sets the attributes of the workfile" do subject.owner.should == user subject.file_name.should == 'workfile.sql' subject.workspace.should == workspace end it "has a valid latest version" do subject.latest_workfile_version.should_not be_nil end it "sets the modifier of the first, recently created version" do subject.versions.first.modifier.should == user end it "sets the attributes of the workfile version" do version = subject.versions.first version.contents.should be_present version.version_num.should == 1 end it "does not set a commit message" do subject.versions.first.commit_message.should be_nil end end context "with versions" do let(:attributes) do { :description => "Nice workfile, good workfile, I've always wanted a workfile like you", :versions_attributes => [{ :contents => test_file('workfile.sql') }] } end subject { described_class.create_from_file_upload(attributes, workspace, user) } it_behaves_like "file upload" it "sets the content of the workfile" do subject.versions.first.contents.size.should > 0 end it "sets the right description on the workfile" do subject.description.should == "Nice workfile, good workfile, I've always wanted a workfile like you" end end context "without a version" do subject { described_class.create_from_file_upload({:file_name => 'workfile.sql'}, workspace, user) } it_behaves_like "file upload" it "sets the file as blank" do subject.versions.first.contents.size.should == 0 subject.versions.first.file_name.should == 'workfile.sql' end end context "with an image extension on a non-image file" do let(:attributes) do { :versions_attributes => [{ :contents => test_file('not_an_image.jpg') }] } end it "throws an exception" do expect { described_class.create_from_file_upload(attributes, workspace, user) }.to raise_error(ActiveRecord::RecordInvalid) end it "does not create a orphan workfile" do expect do begin described_class.create_from_file_upload(attributes, workspace, user) rescue Exception => e end end.to_not change(Workfile, :count) end end end describe ".create_from_svg" do let(:user) { users(:admin) } let(:workspace) { workspaces(:public_with_no_collaborators) } let(:filename) { 'svg_img.png' } subject { described_class.create_from_svg({:svg_data => '<svg xmlns="http://www.w3.org/2000/svg"></svg>', :file_name => filename}, workspace, user) } it "should make a new workfile with the initial version set to the image generated by the SVG data" do subject.versions.first.contents.size.should_not == 0 subject.versions.first.file_name.should == filename end it "creates a workfile in the database" do subject.should be_valid subject.should be_persisted end it "creates a workfile version in the database" do subject.versions.should have(1).version version = subject.versions.first version.should be_valid version.should be_persisted end it "sets the attributes of the workfile" do subject.owner.should == user subject.file_name.should == filename subject.workspace.should == workspace end it "has a valid latest version" do subject.latest_workfile_version.should_not be_nil end it "sets the modifier of the first, recently created version" do subject.versions.first.modifier.should == user end it "sets the attributes of the workfile version" do version = subject.versions.first version.contents.should be_present version.version_num.should == 1 end it "does not set a commit message" do subject.versions.first.commit_message.should be_nil end end describe "#build_new_version" do let(:user) { users(:owner) } let(:workspace) { FactoryGirl.build(:workspace, :owner => user) } let(:workfile) { FactoryGirl.build(:workfile, :workspace => workspace, :file_name => 'workfile.sql') } context "when there is a previous version" do let(:workfile_version) { FactoryGirl.build(:workfile_version, :workfile => workfile) } before do workfile_version.contents = test_file('workfile.sql') workfile_version.save end it "build a new version with version number increased by 1 " do workfile_version = workfile.build_new_version(user, test_file('workfile.sql'), "commit Message") workfile_version.version_num.should == 2 workfile_version.commit_message.should == "commit Message" workfile_version.should_not be_persisted end end context "creating the first version" do it "build a version with version number as 1" do workfile_version = workfile.build_new_version(user, test_file('workfile.sql'), "commit Message") workfile_version.version_num.should == 1 workfile_version.commit_message.should == "commit Message" workfile_version.should_not be_persisted end end end describe "#has_draft" do let(:workspace) { workspaces(:public) } let(:user) { workspace.owner } let!(:workfile1) { FactoryGirl.create(:workfile, :file_name => "some.txt", :workspace => workspace) } let!(:workfile2) { FactoryGirl.create(:workfile, :file_name => "workfile.sql", :workspace => workspace) } let!(:draft) { FactoryGirl.create(:workfile_draft, :workfile_id => workfile1.id, :owner_id => user.id) } it "has_draft return true for workfile1" do workfile1.has_draft(user).should == true end it "has_draft return false for workfile2" do workfile2.has_draft(user).should == false end end describe "associations" do it { should belong_to :owner } it { should have_many :activities } it { should have_many :events } it "belongs to an execution_schema" do workfile = workfiles(:private) workfile.execution_schema.should be_a GpdbSchema end end describe "search fields" do it "indexes text fields" do Workfile.should have_searchable_field :file_name Workfile.should have_searchable_field :description end end end
require 'spec_helper' class TestLogger def self.log(msg);"info: #{msg}";end def self.err_log(msg);"err: #{msg}";end end describe SiteMapper::Logger do before(:all) { SiteMapper::Logger.use_logger(TestLogger) } let(:logger) { SiteMapper::Logger } let(:system_logger) { SiteMapper::Logger::SystemOutLogger } let(:nil_logger) { SiteMapper::Logger::NilLogger } describe 'has NilLogger' do it 'has class' do expect { nil_logger }.not_to raise_error end it 'reponds to #log' do expect(nil_logger).to respond_to(:log) end it 'reponds to #err_log' do expect(nil_logger).to respond_to(:err_log) end end describe 'SystemOutLogger' do it 'has class' do expect { system_logger }.not_to raise_error end # Should work but doesn't.. # it '#log logs to STDOUT' do # expect { system_logger.log('log_message') }.to output('log_message').to_stdout # end # Should work but doesn't.. # it '#err_log logs to STDERR' do # expect { system_logger.err_log('log_message') }.to output('[ERROR] log_message').to_stderr # end it 'reponds to #log' do expect(system_logger).to respond_to(:log) end it 'reponds to #err_log' do expect(system_logger).to respond_to(:err_log) end end describe '#log' do it 'calls log' do expect { logger.log('asd') }.not_to raise_error end end describe '#err_log' do it 'calls err_log' do expect { logger.err_log('asd') }.not_to raise_error end end describe '#use_logger' do it 'can set custom logger' do expect(logger.log('log')).to eq 'info: log' expect(logger.err_log('log')).to eq 'err: log' end it 'raises exception if logger already has been set' do expect do logger.use_logger_type(:system) logger.use_logger(TestLogger) end.to raise_error end end end
class AddStartTimeAndDurationToContest < ActiveRecord::Migration def change add_column :contests, :start_time, :integer add_column :contests, :duration_in_minutes, :integer end end
class AddModelTypeToUserSettings < ActiveRecord::Migration def change add_column :user_settings, :model_type, :string end def down remove_column :user_settings, :model_type end end
class ImageUploader < CartoAssetsUploader include CarrierWave::RMagick # Extensions White List def extensions_white_list %w(gif jpeg jpg png) end version :full do process :store_dimensions end version :xx_large do process :crop resize_to_limit 1600, nil end version :x_large do process :crop resize_to_limit(1200, nil) end version :large do process :crop resize_to_limit(900, nil) end version :medium do process :crop resize_to_limit(600, nil) end version :small do process :crop resize_to_limit(400, nil) end version :x_small do process :crop resize_to_limit(200, nil) end version :xx_small do process :crop resize_to_limit(100, nil) end private def crop if model.crop_x.present? crop_coordinates = scaled_crop_coordinates manipulate! do |img| x = crop_coordinates[:x] y = crop_coordinates[:y] w = crop_coordinates[:w] h = crop_coordinates[:h] img.crop!(x, y, w, h) end end end def crop_coordinates @crop_coordinates ||= scaled_crop_coordinates end def raw_crop_coordinates @raw_crop_coordinates ||= { x: model.crop_x.to_i, y: model.crop_y.to_i, w: model.crop_w.to_i, h: model.crop_h.to_i } end def scaled_crop_coordinates(cropping_width=825) if model.width > cropping_width raw_crop_coordinates.inject({}) do |memo, (key, value)| memo[key] = (value * model.width.to_f / cropping_width.to_f).round memo end else raw_crop_coordinates end end def store_dimensions if @file img = ::Magick::Image::read(@file.file).first if model model.width = img.columns model.height = img.rows end end end end
def map(source_array) new_array = [] source_array.length.times do |index| new_array.push(yield(source_array[index])) #take the element at whatever index we're at and yield it to a block of code passed in when the method is called. Then we'll push that manipulated variable into our new array. end return new_array end def reduce(source_array, starting_value = nil) if starting_value i = 0 accumulator = starting_value else i = 1 #just how reduce/acc method works, don't want to add the first element twice(think of the hill). accumulator = source_array[0] #assume it's the first item in the array because no other starting value was given. end while i < source_array.length do accumulator = yield(accumulator, source_array[i]) i += 1 end return accumulator end
require "capybara" require "capybara/rspec" require "selenium-webdriver" RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups config.include Capybara::DSL #Até aqui é configuração padrão de todo projeto de automação Ruby com Capybara config.before(:example) do page.current_window.resize_to(1280, 800) #Antes de cada caso de teste ajusta a janela para 1280x800 end config.after(:example) do |e| sleep 2 #Apenas para ver o resultado da automação, esse sleep não é necessário e não altera os resultados nome = e.description.gsub(/[^A-Za-z0-9 ]/, "").tr(" ", "_") #Expressão regular para tratar o nome do caso de teste para arquivo screenshot page.save_screenshot("log/" + nome + ".png") #if e.exception #Esse if é feito para tirar print somente quando o teste falha (basta descomentar) end end Capybara.configure do |config| config.default_driver = :selenium_chrome #Navegador de teste config.default_max_wait_time = 5 #Tempo máximo de espera para um elemento HTML ser carregado. Evita sleeps \o/ config.app_host = "https://training-wheels-protocol.herokuapp.com" #Site padrão end
# -*- encoding : utf-8 -*- class BellsController < InheritedResources::Base # GET /bells # GET /bells.json #has_scope :search , :only => [:index] ,:type => :hash, :default => {:zone=>"zh"} def index @bells = Bell.search(params[:search]||{}).page(params[:page]).per(params[:per]||3) respond_to do |format| format.html # index.html.erb format.json { render json: @bells.collect{|b| tmp_arr = {} tmp_arr['tag_names']= b.tags.pluck(:title) tmp_arr['created_at'] = b.created_at.to_s tmp_arr['id']= b.id tmp_arr['name']= b.name tmp_arr['file_location']="http://115.29.151.9/"+b.file_location.to_s tmp_arr['file_size']=b.file_size tmp_arr['duration']=b.duration tmp_arr['singer']=b.singer tmp_arr } } end end # GET /bells/1 # GET /bells/1.json def show @bell = Bell.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @bell } end end # GET /bells/new # GET /bells/new.json def new @bell = Bell.new respond_to do |format| format.html # new.html.erb format.json { render json: @bell } end end # GET /bells/1/edit def edit @bell = Bell.find(params[:id]) end # POST /bells # POST /bells.json def create @bell = Bell.new(params[:bell]) respond_to do |format| if @bell.save format.html { redirect_to @bell, notice: ' 铃声创建成功.' } format.json { render json: @bell, status: :created, location: @bell } else format.html { render action: "new" } format.json { render json: @bell.errors, status: :unprocessable_entity } end end end # PUT /bells/1 # PUT /bells/1.json def update @bell = Bell.find(params[:id]) respond_to do |format| if @bell.update_attributes(params[:bell]) format.html { redirect_to @bell, notice: ' 铃声更新成功.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @bell.errors, status: :unprocessable_entity } end end end # DELETE /bells/1 # DELETE /bells/1.json def destroy @bell = Bell.find(params[:id]) @bell.destroy respond_to do |format| format.html { redirect_to bells_url } format.json { head :no_content } end end end
require File.expand_path('../helper', __FILE__) class AndPredicateTest < Test::Unit::TestCase def test_terminal? rule = AndPredicate.new assert_equal(false, rule.terminal?) end def test_match rule = AndPredicate.new('a') match = rule.match(input('b')) assert_equal(nil, match) match = rule.match(input('a')) assert(match) assert_equal('', match) assert_equal(0, match.length) end def test_to_s rule = AndPredicate.new('a') assert_equal('&"a"', rule.to_s) end end
require 'spec_helper' describe "numeric_extensions" do describe "elapsed_time" do it "should convert 0 seconds to '00:00:00'" do 0.elapsed_time_s.should == '00:00:00' end it "should convert 59 seconds to '00:00:59'" do 59.elapsed_time_s.should == '00:00:59' end it "should convert 60 seconds to '00:01:00'" do 60.elapsed_time_s.should == '00:01:00' end it "should convert 3599 seconds to '00:59:59'" do 3599.elapsed_time_s.should == '00:59:59' end it "should convert 3600 seconds to '01:00:00'" do 3600.elapsed_time_s.should == '01:00:00' end it "should convert 86399 seconds to '23:59:59'" do 86399.elapsed_time_s.should == '23:59:59' end it "should convert 86400 seconds to '24:00:00'" do 86400.elapsed_time_s.should == '24:00:00' end it "should convert 359999 seconds to '99:59:59'" do 359999.elapsed_time_s.should == '99:59:59' end it "should convert 360000 seconds to '100:00:00'" do 360000.elapsed_time_s.should == '100:00:00' end end end
class Search attr_accessor :keyword, :topic, :podcasts def initialize(keyword) @keyword = keyword end def podcasts if topic.podcasts.any? topic.podcasts else Api.new(keyword).load end end private def topic @topic = Topic.find_or_create_by(name: keyword) end end
class Notification < ActiveRecord::Base attr_accessible :user_id, :event_id, :committed belongs_to :user belongs_to :event validates_presence_of :user_id, :event_id validates_inclusion_of :committed, :in => [0, 1] validates_uniqueness_of :user_id, :scope => :event_id end
class Netmask < ActiveRecord::Base belongs_to :server validates_presence_of :netmask_ip end
FactoryGirl.define do factory :proposal do name "redesign" user_name "Joe" send_date "2014-01-01" client after(:create) do |proposal| create_list(:proposal_section, 4, proposal: proposal) end end factory :client do name "Doe" company "Apple" website "http://www.apple.com" end factory :proposal_section do sequence(:name) { |n| "Name #{n}"} sequence(:description) { |n| "Description #{n}"} end end
# The VideoFile model has a class attribute that holds a VLC::LibVLC # instance which is slow to initialize (see the vlcrb gem). Referencing # the model here forces the class to be auto-loaded up front. That way # the cost is incurred now rather than later while the app is in use. VideoFile
# encoding: utf-8 # # = Resent-From Field # # The Resent-From field inherits resent-from StructuredField and handles the Resent-From: header # field in the email. # # Sending resent_from to a mail message will instantiate a Mail::Field object that # has a ResentFromField as its field type. This includes all Mail::CommonAddress # module instance metods. # # Only one Resent-From field can appear in a header, though it can have multiple # addresses and groups of addresses. # # == Examples: # # mail = Mail.new # mail.resent_from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net' # mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net'] # mail[:resent_from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4 # mail['resent-from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4 # mail['Resent-From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4 # # mail[:resent_from].encoded #=> 'Resent-From: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n' # mail[:resent_from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net' # mail[:resent_from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net'] # mail[:resent_from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net'] # require 'mail/fields/common/common_address' module Mail class ResentFromField < StructuredField include Mail::CommonAddress FIELD_NAME = 'resent-from' CAPITALIZED_FIELD = 'Resent-From' def initialize(value = nil, charset = 'utf-8') self.charset = charset super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset) self end def encoded do_encode(CAPITALIZED_FIELD) end def decoded do_decode end end end
require 'pry' class Queens def initialize input={white: [0, 3], black: [7, 3]} raise ArgumentError.new if input[:white] == input[:black] @info = input end def to_s string = '' for y in 0..7 for x in 0..7 if @info[:white] == [y, x] string += 'W ' elsif @info[:black] == [y, x] string += 'B ' else string += 'O ' end end string.chop! string += "\n" end puts string string.chomp! end def attack? if @info[:white][0] == @info[:black][0] || @info[:white][1] == @info[:black][1] return true end x_diff = ( @info[:white][0] - @info[:black][0] ).abs y_diff = ( @info[:white][1] - @info[:black][1] ).abs if x_diff == y_diff return true end return false end def white @info[:white] end def black @info[:black] end end # binding.pry
package "redis-server" template '/etc/redis/redis.conf' do owner 'root' group 'root' mode '0644' source 'redis-conf.erb' notifies :reload, "service[redis-server]" end service "redis-server" do supports :start => true, :stop => true, :restart => true, :reload => true action [:enable, :start] end