text
stringlengths
10
2.61M
# encoding: utf-8 $:.push File.expand_path('../lib', __FILE__) require 'adhearsion/beanstalkd/version' Gem::Specification.new do |s| s.name = 'adhearsion-beanstalkd' s.version = Adhearsion::Beanstalkd::VERSION s.authors = ['Ido Kanner'] s.email = ['idok@linesip.com'] s.homepage = '' s.summary = 'A beanstalkd server for executing jobs inside Adhearsion' s.description = 'A beanstalkd server for executing jobs inside Adhearsion' s.license = 'MIT' s.rubyforge_project = 'adhearsion-beanstalkd' s.files = `git ls-files`.split("\n") s.require_paths = ['lib'] s.add_runtime_dependency 'adhearsion', ['~> 2.0'] s.add_runtime_dependency 'backburner', ['~> 0.4.5'] end
# Bucket Sort works by distributing the elements of an array into a number of # buckets. Each bucket is then sorted individually, either using a different # sorting algorithm, or by recursively applying the bucket sorting algorithm. # Worst Case: O(n^2) # Average Case: Θ(n+k) require_relative './quick_sort' require 'benchmark' def bucket_sort(array) bucket_size = 5 min = array.min max = array.max bucket_count = ((max - min) / bucket_size).floor + 1 buckets = Array.new(bucket_count) {Array.new} array.each do |element| buckets[((element - min) / bucket_size)].push(element) end array.clear (0..buckets.length - 1).each do |x| quick_sort(buckets[x], 0, buckets[x].length - 1) buckets[x].each do |y| array.push(y) end end return array end array = [248, 185, 22, 288, 128, 234, 24, 206, 220] puts bucket_sort(array).inspect
class Question < ApplicationRecord belongs_to :page has_many :answers end
class Store::Indices::ProductsController < ApplicationController # GET /store/indices/products # GET /store/indices/products.json def index @store_indices_products = Store::Indices::Product.all respond_to do |format| format.html # index.html.erb format.json { render json: @store_indices_products } end end # GET /store/indices/products/1 # GET /store/indices/products/1.json def show @store_indices_product = Store::Indices::Product.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @store_indices_product } end end # GET /store/indices/products/new # GET /store/indices/products/new.json def new @store_indices_product = Store::Indices::Product.new respond_to do |format| format.html # new.html.erb format.json { render json: @store_indices_product } end end # GET /store/indices/products/1/edit def edit @store_indices_product = Store::Indices::Product.find(params[:id]) end # POST /store/indices/products # POST /store/indices/products.json def create @store_indices_product = Store::Indices::Product.new(params[:store_indices_product]) respond_to do |format| if @store_indices_product.save format.html { redirect_to @store_indices_product, notice: 'Product was successfully created.' } format.json { render json: @store_indices_product, status: :created, location: @store_indices_product } else format.html { render action: "new" } format.json { render json: @store_indices_product.errors, status: :unprocessable_entity } end end end # PUT /store/indices/products/1 # PUT /store/indices/products/1.json def update @store_indices_product = Store::Indices::Product.find(params[:id]) respond_to do |format| if @store_indices_product.update_attributes(params[:store_indices_product]) format.html { redirect_to @store_indices_product, notice: 'Product was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @store_indices_product.errors, status: :unprocessable_entity } end end end # DELETE /store/indices/products/1 # DELETE /store/indices/products/1.json def destroy @store_indices_product = Store::Indices::Product.find(params[:id]) @store_indices_product.destroy respond_to do |format| format.html { redirect_to store_indices_products_url } format.json { head :no_content } end end end
# To get more control over HTML doctypes, the default HAML format needs to be set to :xhtml. # This allows us to use the XHTML 1.0 Transitional doctype for email layouts # and HTML5 for everything else. # Email templates doctype: !!! # Any other layout: !!! 5 # Related links: # http://haml.info/docs/yardoc/file.REFERENCE.html#doctype_ # https://www.campaignmonitor.com/blog/post/3317/correct-doctype-to-use-in-html-email/ Haml::Template.options[:format] = :xhtml
require "formula" class Advancecomp < Formula homepage "http://advancemame.sourceforge.net/comp-readme.html" url "https://downloads.sourceforge.net/project/advancemame/advancecomp/1.19/advancecomp-1.19.tar.gz" sha256 "d594c50c3da356aa961f75b00e958a4ed1e142c6530b42926092e46419af3047" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}" system "make install" end test do system bin/"advdef", "--version" system bin/"advpng", "--version" end end
class User < ActiveRecord::Base has_many :rounds validates :username, uniqueness: true, presence: true validates :password, presence: true def self.authenticate(username, password) self.find_by(username: username, password: password) end end
module Alf class Renderer # # Implements the Renderer contract through inspect # class Rash < Renderer # (see Renderer#render) def render(input, output) if options[:pretty] input.each do |tuple| output << "{\n" << tuple.collect{|k,v| " #{lit(k)} => #{lit(v)}" }.join(",\n") << "\n}\n" end else input.each do |tuple| output << lit(tuple) << "\n" end end output end private def lit(x) Tools.to_ruby_literal(x) end Renderer.register(:rash, "as ruby hashes", self) end # class Rash end # class Renderer end # module Alf
class DropInventoryItems < ActiveRecord::Migration[6.0] def change drop_table :inventory_items end end
require 'rails_helper' RSpec.describe Api::V1::ReservationsController, type: :controller do let(:create_reservation) do user = create(:user) movie = create(:movie) cinema = create(:cinema) screening = create(:screening, movie_id: movie.id) create(:reservation, user_id: user.id, screening_id: screening.id, cinema_id: cinema.id, movie_id: movie.id) end describe 'GET #index' do let(:index_use_case) do instance_double(Reservations::UseCases::Index, call: { reservation: 'reservation' }) end let(:index_representer) do instance_double(Reservations::Representers::Multiple, call: { reservations: 'lots of res\'s' }) end before do allow(Reservations::UseCases::Index).to receive(:new) .and_return(index_use_case) allow(Reservations::Representers::Multiple).to receive(:new) .and_return(index_representer) end context 'when no user logged in' do it 'returns error' do get :index expect(JSON.parse(response.body).keys).to include('errors') end end it 'returns reservations' do create(:user) request.headers.merge! Users::Model.last.create_new_auth_token get :index, params: {} expect(JSON.parse(response.body)).to eq('reservations' => "lots of res's") end end describe 'GET #show' do let(:show_representer) do instance_double(Reservations::Representers::Single, call: { reservation: 'reservation' }) end before do create_reservation allow(Reservations::Representers::Single).to receive(:new) .and_return(show_representer) end it 'returns a user reservation' do request.headers.merge! Users::Model.last.create_new_auth_token get :show, params: { id: Reservations::Model.last.id } expect(JSON.parse(response.body)).to eq('reservation' => 'reservation') end it 'returns error' do create(:user, email: 'test1@test.com') request.headers.merge! Users::Model.last.create_new_auth_token get :show, params: { id: Reservations::Model.last.id } expect(JSON.parse(response.body).keys).to contain_exactly('error', 'type') end end describe 'POST #create' do let(:create_use_case) do instance_double(Reservations::UseCases::Create, call: { reservation: 'reservation' }) end let(:single_representer) do instance_double(Reservations::Representers::Single, call: { reservation: 'created' }) end let(:create_request) do post :create, params: { data: { attributes: { cinema_id: 2, movie_id: 10, seat_ids: [ { seat_id: 1 } ], screening_id: 3, user_id: 4 } } } end before do allow(Reservations::UseCases::Create).to receive(:new) .and_return(create_use_case) allow(Reservations::Representers::Single).to receive(:new) .and_return(single_representer) end it 'user creates reservation' do create(:user) request.headers.merge! Users::Model.last.create_new_auth_token create_request expect(JSON.parse(response.body)).to eq('reservation' => 'created') end it 'admin creates reservation' do create(:user, :admin) request.headers.merge! Users::Model.last.create_new_auth_token create_request expect(JSON.parse(response.body)).to eq('reservation' => 'created') end it 'require user to be logged in' do create_request expect(JSON.parse(response.body).keys).to contain_exactly('errors') end end describe 'PUT #update' do let(:update_representer) do instance_double(Reservations::Representers::Single, call: { reservation: 'reservation' }) end let(:update_use_case) do instance_double(Reservations::UseCases::Update, call: { res: 'updated' }) end let(:update_request) do put :update, params: { id: Reservations::Model.last.id, data: { attributes: { cinema_id: 2, movie_id: 3, screening_id: 4, seat_ids: [{ seat_id: 5 }] } } } end before do create_reservation allow(Reservations::Representers::Single).to receive(:new) .and_return(update_representer) allow(Reservations::UseCases::Update).to receive(:new) .and_return(update_use_case) end it 'allows correct user' do request.headers.merge! Users::Model.last.create_new_auth_token update_request expect(JSON.parse(response.body)).to eq('reservation' => 'reservation') end it 'allows admin' do create(:user, :admin) request.headers.merge! Users::Model.last.create_new_auth_token update_request expect(JSON.parse(response.body)).to eq('reservation' => 'reservation') end it 'rejects incorrect user' do create(:user) request.headers.merge! Users::Model.last.create_new_auth_token update_request expect(JSON.parse(response.body).keys).to include('error') end end describe 'DELETE #destroy' do let(:delete_request) { delete :destroy, params: { id: Reservations::Model.last.id } } before do create_reservation end it 'deletes reservation for user' do request.headers.merge! Users::Model.last.create_new_auth_token expect { delete_request }.to change(Reservations::Model, :count).by(-1) end it 'deletes if admin' do create(:user, :admin) request.headers.merge! Users::Model.last.create_new_auth_token expect { delete_request }.to change(Reservations::Model, :count).by(-1) end it 'rejects incorrect user' do create(:user) request.headers.merge! Users::Model.last.create_new_auth_token expect { delete_request }.to change(Reservations::Model, :count).by(0) end end end
class ProductsController < ApplicationController def index @cart = cart end def show end def add if(params[:product].blank?) flash[:notice] = "Product Field cannot be blank." redirect_to products_path else cart.push(params[:product]) flash[:notice] = "Item was added successfuly" redirect_to products_path end end def destroy cart.delete(params[:product]) flash[:notice] = "#{params[:product]} was removed from your cart" redirect_to products_path end end
class CreateImageUploadTaskType < ActiveRecord::Migration[4.2] require 'sample_data' include SampleData def change image = create_field_type field_type: 'image', label: 'Image' json = DynamicAnnotation::FieldType.where(field_type: 'json').last || create_field_type(field_type: 'json', label: 'JSON') at = create_annotation_type annotation_type: 'task_response_image_upload', label: 'Task Response Image Upload' create_field_instance annotation_type_object: at, name: 'response_image_upload', label: 'Response', field_type_object: image, optional: true create_field_instance annotation_type_object: at, name: 'suggestion_image_upload', label: 'Suggestion', field_type_object: json, optional: true create_field_instance annotation_type_object: at, name: 'review_image_upload', label: 'Review', field_type_object: json, optional: true end end
And(/^I want to "([^"]*)" link is displayed with an url "([^"]*)" and the link text of "([^"]*)" dt$/) do |link_id, link_href, link_text| link = @browser.link(:id => link_id) expect(link.exists?).to eq(true) expect(link.href).to include link_href expect(link.text).to include link_text end
class ProtocAdapter attr_reader :src_path, :dst_path, :swagger_out_path attr_reader :twirp_plugin_path, :swagger_plugin_path, :protoc_path def initialize(src_path, dst_path, swagger_out_path: nil) @src_path = src_path @dst_path = dst_path @swagger_out_path = swagger_out_path go_path = ENV.fetch('GOPATH') { File.expand_path('~/go') } go_bin_path = File.join(go_path, 'bin') @twirp_plugin_path = ENV.fetch('TWIRP_PLUGIN_PATH') { File.join(go_bin_path, 'protoc-gen-twirp_ruby') } @swagger_plugin_path = ENV.fetch('SWAGGER_PLUGIN_PATH') { File.join(go_bin_path, 'protoc-gen-twirp_swagger') } @protoc_path = `which protoc`.chomp end def rm_old_twirp_files return unless File.exists? dst_path remove_mask = File.join dst_path, '**/*_{twirp,pb}.rb' files_to_remove = Dir.glob remove_mask return if files_to_remove.empty? files_to_remove.each do |file| File.unlink file end end def cmd(files, gen_swagger: false) flags = "--proto_path=#{src_path} " \ "--ruby_out=#{dst_path} --twirp_ruby_out=#{dst_path} " \ "--plugin=#{twirp_plugin_path}" if gen_swagger flags += " --plugin=#{swagger_plugin_path}" \ " --twirp_swagger_out=#{swagger_out_path}" end "#{protoc_path} #{flags} #{files}" end def check_requirements(check_swagger: false) unless File.exist?(protoc_path) yield 'protoc not found - install protobuf (brew/apt/yum install protobuf)' end unless File.exist?(twirp_plugin_path) yield <<~TEXT protoc-gen-twirp_ruby not found - install go (brew install go) and run "go get github.com/twitchtv/twirp-ruby/protoc-gen-twirp_ruby or set TWIRP_PLUGIN_PATH environment variable to right location. TEXT end if check_swagger && !File.exist?(swagger_plugin_path) yield <<~TEXT protoc-gen-twirp_swagger not found - install go (brew install go) and run "go get github.com/elliots/protoc-gen-twirp_swagger or set SWAGGER_PLUGIN_PATH environment variable to right location. TEXT end end end
class CreateSysLogs < ActiveRecord::Migration def change create_table :sys_logs do |t| t.datetime :log_date t.integer :user_id t.string :user_name t.string :user_ip t.string :action_logged end add_index :sys_logs, :user_id, :name => "index_sys_logs_on_user_id" add_index :sys_logs, :user_ip, :name => "index_sys_logs_on_user_ip" end end
class Friend < ActiveRecord::Base belongs_to :user attr_accessible :user_name, :user_id end
class WeatherDataPoint < ApplicationRecord # Consumes the JSON returned from the Openweather API def self.new_from_open_weather_data(data) WeatherDataPoint.new({ :zipcode => data["zipcode"], :description => data["weather"][0]["description"], # :pressure => data["main"]["pressure"], :temperature => data["main"]["temp"], :wind_speed => data["wind"]["speed"], :wind_direction => data["wind"]["deg"], :humidity => data["main"]["humidity"], # :city_name => data["name"] }) end end
# frozen_string_literal: true require 'rails_helper' feature 'トップページ', js: true do let!(:anime1) { create(:anime) } let!(:anime2) { create(:anime, picture: nil) } let!(:anime3) { create(:anime) } let!(:season1) { create(:season, anime: anime1) } let!(:season2) { create(:season, anime: anime2, disabled: true) } let!(:season3) { create(:season, anime: anime3, end_on: Time.zone.yesterday) } let!(:melody1) { create(:melody, season: season1, memo: memo) } let!(:melody2) { create(:melody, season: season2) } let!(:advertisement) { create(:advertisement, anime: anime1) } let!(:melody_advertisement) { create(:advertisement, melody: melody1) } let!(:memo) { '' } background do visit root_path end scenario '放送中のアニメ一覧が表示されること' do expect(page).to have_content anime1.title expect(page).to have_content anime2.title expect(page).to have_no_content anime3.title end scenario 'disabledがtrueの場合のみ(第n期)は非表示になること' do expect(page).to have_content anime1.title expect(page).to have_content season1.behind_name expect(page).to have_content '第' + season1.phase.to_s + '期' expect(page).to have_content anime2.title expect(page).to have_content season2.behind_name expect(page).to have_no_content '第' + season2.phase.to_s + '期' expect(page).to have_content season2.behind_name end context 'コメントがある場合' do let(:memo) { 'コメント' } scenario 'コメントが表示されること' do within "#season-#{season1.id}" do expect(page).to have_content memo end end end scenario '動画データがある場合動画が表示されること' do within "#season-#{season1.id}" do expect(page).to have_css 'iframe' end end scenario '曲に広告データがある場合広告が表示されること' do within "#season-#{season1.id}" do expect(page).to have_css "a[href='https://url.com']" end end scenario '広告が表示されること' do within '.advertisementComponent' do expect(page).to have_css "a[href='https://url.com']" end end scenario 'PRラベルクリックで、広告一覧が更新されること' do within "#season-#{season1.id}" do find('.glyphicon-refresh').click end within '.advertisementComponent' do expect(page).to have_css "a[href='https://url.com']" end end end
class C1310b attr_reader :options, :name, :field_type, :node def initialize @name = "Inattention - Did the resident have difficulty focusing attention, for example, being easily distractible or having difficulty keeping track of what was being said? (C1310b)" @field_type = DROPDOWN @node = "C1310B" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "Behavior not present") @options << FieldOption.new("1", "Behavior continuously present, does not fluctuate") @options << FieldOption.new("2", "Behavior present, fluctuates (comes and goes, changes in severity)") end def set_values_for_type(klass) return "0" end end
class CreateHomeSettings < ActiveRecord::Migration def change create_table :home_settings do |t| t.string :boat_type t.string :attached_media end add_index :home_settings, :boat_type end end
require "aethyr/core/actions/commands/ahelp" require "aethyr/core/registry" require "aethyr/core/input_handlers/admin/admin_handler" module Aethyr module Core module Commands module Ahelp class AhelpHandler < Aethyr::Extend::AdminHandler def self.create_help_entries help_entries = [] command = "ahelp" see_also = nil syntax_formats = ["AHELP"] aliases = nil content = <<'EOF' Sorry no help has been written for this command yet EOF help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases)) return help_entries end def initialize(player) super(player, ["ahelp"], help_entries: AhelpHandler.create_help_entries) end def self.object_added(data) super(data, self) end def player_input(data) super(data) case data[:input] when /^ahelp(.*)$/i object = $1 $manager.submit_action(Aethyr::Core::Actions::Ahelp::AhelpCommand.new(@player, {:object => object})) end end private end Aethyr::Extend::HandlerRegistry.register_handler(AhelpHandler) end end end end
class MonthlyPoint < ApplicationRecord belongs_to :user after_save :claim_reward, :upgrade_user_loyalty_tier, if: :saved_change_to_points? validates_numericality_of :points, allow_nil: false validates_presence_of :start_date, :end_date validates_uniqueness_of :user_id, scope: %i[start_date end_date] scope :for_year, lambda { |date| where(created_at: date.beginning_of_year..date.end_of_year) } def update_points(earned_points) self.points += earned_points self.save end def claim_reward ::RewardTrigger::ByPoints.new(self) end def upgrade_user_loyalty_tier gold_points = I18n.t("loyalty_tier.points.gold") platinum = I18n.t("loyalty_tier.name.platinum") return if user.current_year_points < gold_points || user.loyalty_tier.name == platinum user.upgrade_loyalty_tier end end
class Store < Hashie::Mash def first_letter letter = name.strip.first.capitalize if letter.match(/^[[:alpha:]]$/) letter else '#' end end def to_partial_path 'store' end def has_logo? logo.present? end def logo _links.logo.href end def has_storefront? storefront.present? end def storefront _links.store_front.href end def centre=(centre) @centre = centre end def centre @centre ||= get_centre end def opening_time todays_hours.opening_time end def closing_time todays_hours.closing_time end def closed_today todays_hours.closed? end def closing_time_12 DateTime.parse(closing_time) .strftime('%l:%M%P') .lstrip rescue nil end def to_gon gon = { id: id, name: name, url: url, storefront_path: Rails.application.routes.url_helpers.centre_store_path(centre_id, retailer_code, id), micello_geom_id: micello_geom_id, closing_time_24: closing_time, closing_time_12: closing_time_12, closed_today: closed_today } gon[:logo] = logo if has_logo? gon end def yelp @search = Yelp.client.search \ centre_id, { term: name, limit: 1 } business = Yelp.client.business(@search.businesses.first.id) business if business.name.downcase.include?(name.downcase) && business.location.city.downcase.include?(centre_id) rescue nil end private def get_centre centre_service = CentreService.fetch(centre_id) CentreService.build centre_service end def todays_hours today = Time.now.in_time_zone(centre.timezone).strftime("%Y-%m-%d") @todays_hours ||= StoreTradingHourService.find({store_id:id, centre_id: centre_id, from: today, to: today}).first end end
require 'rubygems' require File.dirname(__FILE__) + '/../lib/device_atlas' require 'spec' require 'active_support' describe DeviceAtlas do before(:each) do @da = DeviceAtlas.new @tree = @da.getTreeFromFile("../20080604.json") end it "the api revision should be 2830" do @da.getApiRevision.should == 2830 end it "the tree revision should be 2590" do @da.getTreeRevision(@tree).should == 2590 end it "the json tree should have nodes '$', 't', 'pr', 'pn', 'v', 'p' " do nodes = ['$', 't', 'pr', 'pn', 'v', 'p'] @tree.each_key do |node| nodes.include?(node).should be_true end end it "@tree['pr'] should be a hash lookup of properties with the type code prefix, the value is the property code" do @tree['pr'].has_key?('bisBrowser').should be_true @tree['pr']['bisBrowser'].should == 68 end it "@tree['pn'] should be a hash lookup of properties without the type code prefix, the value is the property code" do @tree['pn'].has_key?('isBrowser').should be_true @tree['pn']['isBrowser'].should == 68 end it "should be the jesus phone Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" do user_agent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" property = @da.getProperty(@tree, user_agent, "displayWidth") property.should == 320 end it "should return 176 as the display width for a SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" property = @da.getProperty(@tree, user_agent, "displayWidth") property.should == 176 end it "should raise IncorrectPropertyTypeException getting displayWidth as a boolean" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" lambda { @da.getPropertyAsBoolean(@tree, user_agent, "displayWidth") }.should raise_error(DeviceAtlas::IncorrectPropertyTypeException, "displayWidth is not of type boolean") end it "should raise IncorrectPropertyTypeException getting displayWidth as a date" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" lambda { @da.getPropertyAsDate(@tree, user_agent, "displayWidth") }.should raise_error(DeviceAtlas::IncorrectPropertyTypeException, "displayWidth is not of type date") end it "should raise IncorrectPropertyTypeException getting displayWidth as a string" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" lambda { @da.getPropertyAsString(@tree, user_agent, "displayWidth") }.should raise_error(DeviceAtlas::IncorrectPropertyTypeException, "displayWidth is not of type string") end it "should raise IncorrectPropertyTypeException trying to get a non existing property (bananas) as a String" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" lambda { @da.getPropertyAsString(@tree, user_agent, "bananas") }.should raise_error(DeviceAtlas::IncorrectPropertyTypeException, "bananas is not of type string") end it "should raise UnknownPropertyException trying to find a non existing property (bananas) for a user agent" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" lambda { @da.getProperty(@tree, user_agent, "bananas") }.should raise_error(DeviceAtlas::UnknownPropertyException, "The property bananas is not known in this tree.") end it "should get displayWidth as an Integer (Well, fixnum)" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" @da.getPropertyAsInteger(@tree, user_agent, "displayWidth").class.should == Fixnum end it "should get model as a String" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" @da.getPropertyAsString(@tree, user_agent, "model").class.should == String end it "should get mobileDevice as a Boolean" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" @da.getPropertyAsBoolean(@tree, user_agent, "mobileDevice").should === (true || false) end it "should return the list of properties for a SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" properties = @da.getProperties(@tree, user_agent) properties.diff({ "mobileDevice" => 1, "vendor" => "Sony Ericsson", "image.Jpg" => 1, "image.Gif87" => 1, "uriSchemeTel" => 1, "markup.xhtmlMp10" => 1, "markup.xhtmlBasic10" => 1, "cookieSupport" => 1, "https" => 1, "memoryLimitMarkup" => 20000, "memoryLimitEmbeddedMedia" => 262144, "memoryLimitDownload" => 262144, "midiMonophonic" => 1, "amr" => 1, "mpeg4" => 1, "3gpp" => 1, "h263Type0InVideo" => 1, "mpeg4InVideo" => 1, "amrInVideo" => 1, "aacInVideo" => 1, "drmOmaForwardLock" => 1, "drmOmaCombinedDelivery" => 1, "drmOmaSeparateDelivery" => 1, "csd" => 1, "gprs" => 1, "displayWidth" => 176, "displayHeight" => 220, "displayColorDepth" => 16, "model" => "K700i", "image.Png" => 1, "mp3" => 0, "aac" => 0, "qcelp" => 0, "3gpp2" => 0, "wmv" => 0, "hscsd" => 0, "edge" => 0, "hsdpa" => 0, "umts"=> 0, "midiPolyphonic" => 0, "image.Gif89a" => 1, "usableDisplayWidth" => 170, "usableDisplayHeight" => 147, "midp" => "1.0", "cldc" => "1.0", "jsr30" => 1, "jsr139" => 0, "jsr37" => 1, "jsr118" => 0, "id" => 204912, "_matched" => "SonyEricssonK700i", "_unmatched" => "/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1"}).should == {} end it "should return the list of properties TYPED for a SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" do user_agent = "SonyEricssonK700i/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1" properties = @da.getPropertiesAsTyped(@tree, user_agent) properties.diff({ "mobileDevice" => true, "vendor" => "Sony Ericsson", "image.Jpg" => true, "image.Gif87" => true, "uriSchemeTel" => true, "markup.xhtmlMp10" => true, "markup.xhtmlBasic10" => true, "cookieSupport" => true, "https" => true, "memoryLimitMarkup" => 20000, "memoryLimitEmbeddedMedia" => 262144, "memoryLimitDownload" => 262144, "midiMonophonic" => true, "amr" => true, "mpeg4" => true, "3gpp" => true, "h263Type0InVideo" => true, "mpeg4InVideo" => true, "amrInVideo" => true, "aacInVideo" => true, "drmOmaForwardLock" => true, "drmOmaCombinedDelivery" => true, "drmOmaSeparateDelivery" => true, "csd" => true, "gprs" => true, "displayWidth" => 176, "displayHeight" => 220, "displayColorDepth" => 16, "model" => "K700i", "image.Png" => true, "mp3" => false, "aac" => false, "qcelp" => false, "3gpp2" => false, "wmv" => false, "hscsd" => false, "edge" => false, "hsdpa" => false, "umts"=> false, "midiPolyphonic" => false, "image.Gif89a" => true, "usableDisplayWidth" => 170, "usableDisplayHeight" => 147, "midp" => "1.0", "cldc" => "1.0", "jsr30" => true, "jsr139" => false, "jsr37" => true, "jsr118" => false, "id" => 204912, "_matched" => "SonyEricssonK700i", "_unmatched" => "/R2AG SEMC-Browser/4.0.3 Profile/MIDP-2.0 Configuration/CLDC-1.1"}).should == {} end it "should list all of the available properties and their types" do property_list = @da.listProperties(@tree) property_list.should == {"isBrowser"=>"boolean", "drmOmaForwardLock"=>"boolean", "cookieSupport"=>"boolean", "model"=>"string", "csd"=>"boolean", "h263Type0InVideo"=>"boolean", "memoryLimitDownload"=>"integer", "h263Type3InVideo"=>"boolean", "aacLtpInVideo"=>"boolean", "umts"=>"boolean", "isChecker"=>"boolean", "uriSchemeTel"=>"boolean", "awbInVideo"=>"boolean", "3gpp"=>"boolean", "hsdpa"=>"boolean", "displayColorDepth"=>"integer", "markup.xhtmlMp10"=>"boolean", "isDownloader"=>"boolean", "osProprietary"=>"string", "https"=>"boolean", "mpeg4"=>"boolean", "markup.xhtmlMp11"=>"boolean", "osVersion"=>"string", "image.Png"=>"boolean", "wmv"=>"boolean", "isSpam"=>"boolean", "image.Gif87"=>"boolean", "3gpp2"=>"boolean", "developerPlatform"=>"string", "markup.xhtmlMp12"=>"boolean", "stylesheetSupport"=>"string", "aac"=>"boolean", "osRim"=>"boolean", "developerPlatformVersion"=>"string", "jsr118"=>"boolean", "drmOmaCombinedDelivery"=>"boolean", "jsr139"=>"boolean", "mp3"=>"boolean", "mobileDevice"=>"boolean", "edge"=>"boolean", "vendor"=>"string", "image.Gif89a"=>"boolean", "usableDisplayWidth"=>"integer", "jsr30"=>"boolean", "version"=>"string", "midiMonophonic"=>"boolean", "osOsx"=>"boolean", "mpeg4InVideo"=>"boolean", "displayWidth"=>"integer", "qcelpInVideo"=>"boolean", "usableDisplayHeight"=>"integer", "hscsd"=>"boolean", "memoryLimitMarkup"=>"integer", "isFilter"=>"boolean", "drmOmaSeparateDelivery"=>"boolean", "cldc"=>"string", "osLinux"=>"boolean", "gprs"=>"boolean", "aacInVideo"=>"boolean", "displayHeight"=>"integer", "osWindows"=>"boolean", "amr"=>"boolean", "amrInVideo"=>"boolean", "isRobot"=>"boolean", "markup.xhtmlBasic10"=>"boolean", "midiPolyphonic"=>"boolean", "midp"=>"string", "id"=>"integer", "osSymbian"=>"boolean", "scriptSupport"=>"string", "image.Jpg"=>"boolean", "jsr37"=>"boolean", "qcelp"=>"boolean", "memoryLimitEmbeddedMedia"=>"integer"} end end
class User < ApplicationRecord has_many :projects has_many :tickets has_secure_password validations: false validates :name, presence: true, uniqueness: true validates :password, presence: true, on: :create, length: {minimum: 5} end
namespace :notify do desc "This is to notify people about Birthday" task(:all => :environment) do message = Message.first #all_users = date.today == All users having bdfay today UserMailer.send_email(message).deliver end end
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../spec_helper' # Be sure to include AuthenticatedTestHelper in spec/spec_helper.rb instead. # Then, you can remove it from this and the functional test. include AuthenticatedTestHelper describe User do describe 'being created' do before do @admin = Factory(:user) end it 'increments User#count' do lambda do user = Factory(:user, :login => '55xiaoyou') violated "#{user.errors.full_messages.to_sentence}" if user.new_record? end.should change(User, :count).by(1) end end # # Validations # it 'requires login' do lambda do u = User.create(:password => '55') u.errors.on(:login).should_not be_nil end.should_not change(User, :count) end it 'requires password' do lambda do u = User.create(:login => 'admin') u.errors.on(:password).should_not be_nil end.should_not change(User, :count) end # # Authentication # it 'authenticates user' do User.authenticate('admin', '55xiaoyou').should == @admin end it "doesn't authenticate user with bad password" do User.authenticate('admin', '55').should be_nil end end
require File.expand_path('../helper', __FILE__) class Foo def get_true? true end def get_false? false end end describe "should" do it ".should ==" do 2.should == 2 2.should_not == 3 2.should.not == 3 end it ".should !=" do 2.should != 3 2.should_not != 2 2.should.not != 2 end it ".should.match" do "hi".should =~ /hi/ "hi".should.match /hi/ "hi".should_not =~ /HI/ "hi".should.not.match /HI/ end it ".should.be.nil?" do @foo.should.be.nil? 1000.should_not.be.nil? end it ".should.respond_to" do "".should.respond_to(:empty?) "".should_not.respond_to(:lolwhat) end it ".should.raise" do should.raise(ZeroDivisionError) { 2 / 0 } # should_not.raise { 2 + 2 } end it ".should.be.empty" do [].should.be.empty [].should.empty end it ".should.not.be.empty" do [1].should_not.be.empty [1].should.include(1) end it ".should <" do 2.should < 3 1.should < 2 2.should <= 2 2.should <= 4 4.should >= 4 4.should >= 3 end it ".should.be.kind_of" do Object.new.should.respond_to(:freeze) Object.new.should.be.kind_of(Object) Object.new.should.be.an.instance_of(Object) end it "should.be.equal again" do a = Object.new b = a a.should.be.equal(b) a.should.be(b) a.should_not.be.equal(Object.new) end it ".should.be.close" do Math::PI.should.be.close(22.0/7, 0.1) end it ".should.throw" do should.throw(:x) { throw :x } # should.not.throw { 2 + 2 } end it ".should.not.method_missing" do Foo.new.should.not.get_false Foo.new.should.get_true end it ".should.be" do a = Object.new b = a expects(:assert_same).with(a, b, nil) a.should.be(b) end it ".should.include" do expects(:assert_includes).with([], 2, nil) [].should.include 2 end it ".should.not.include" do expects(:refute_includes).with([], 2, nil) [].should.not.include 2 end it ".should.blaming" do expects(:assert_equal).with(4, 3, 'lol') 3.should.blaming('lol') == 4 end it ".msg" do expects(:assert_equal).with(4, 3, 'oh no') msg "oh no" 3.should == 4 end it ".should.blaming again" do object = Object.new expects(:assert).with(true).at_least_once # Because minitest does this expects(:assert).with(true, 'he cant dance') object.expects(:dance?).returns(true) object.should.blaming('he cant dance').dance end it ".should.satisfy" do expects :assert_block should.satisfy { false } end end
class Product attr_reader :sku, :name, :customer_average_review, :short_description, :sale_price, :image def initialize(product_info) @sku = product_info[:sku] @name = product_info[:name] @customer_average_review = product_info[:customerReviewAverage] @short_description = product_info[:shortDescription] @sale_price = product_info[:salePrice] @image = product_info[:image] end def self.find(product) products = service.find(product) make_objects(products) end def self.service BestBuyService.new end def self.make_objects(products) products.map do |product_info| Product.new(product_info) end end end
# given two arrays as inputs, return the intersection as an array of all shared elements # all elements in the returned array should be unique # the elements in the returned array can be in any order # an empty array should be returned given arrays with no shared elements def find_intersection(arr1, arr2) set = Set[*arr1] filtered_set = Set.new( arr2.select { |x| set.include?(x) } ) return [*filtered_set] end # ALTERNATIVE SOLUTION # intersection = {} # # arr1.each do |x| # intersection[x] = 1 if !intersection.has_key?(x) && arr2.include?(x) # end # # return intersection.keys
class RemoveFieldsFromUser < ActiveRecord::Migration def change remove_column :users, :zip_code, :integer remove_column :users, :years_of_experience, :integer remove_column :users, :description, :string remove_column :users, :from_hour, :integer remove_column :users, :to_hour, :integer end end
class AllyMailer < ActionMailer::Base # the default address to send a confirmation_email from default from: "peerallies.pugetsound@gmail.com" # this is the email notifying an ally that a victim has requested # help from the peer allies # Params: # +name+:: the name of the victim # +email+:: the email address of the victim # +message+:: the message the victim wishes to include def notification_email(name, email, message) # auto includes the name in an opening sentence to introduce # the victim to the ally body = "Hi, my name is #{name}. " + "\n" + "\n" + message mail to: "peerallies.pugetsound@gmail.com", from: email, body: body end # this is the email from the peer allies to the victim # providing confirmation that they received a request # Params: # +name+:: The name of the victim # +email+:: The email address of the victim def confirmation_email(name, email) body = "Hello, #{name}." + "\n" + "The Peer Allies " + "have received your request, and will get in " + "touch with you as soon as possible." mail to: email, from: "peerallies.pugetsound@gmail.com", body: body end # this will be used when someone follows the path # to a specific ally's page and wishes to email # them directly rather than emailing the group in general def specific_ally_email(name, email, message, recipient_ally) body = "Hi, my name is #{name}." + "\n" + "\n" + message mail to: recipient_ally, from: email, body: body end end
class SelfManagementController < ApplicationController def view_my_booking authorize! :view_my_booking, User @my_booking = current_user.bookings.order_by_time_desc.page( params[:page] ).per( Settings.booking_per_page ) @payment = Payment.new end def view_my_review authorize! :view_my_review, User @my_review = current_user.reviews.order_by_time_desc.page( params[:page] ).per( Settings.review_per_page ) end def view_my_information authorize! :view_information, User @user = current_user render :view_information end def view_other_user_information authorize! :view_information, User @user = User.find_by_id params[:user_id] render :view_information end private def update_params params.require(:user).permit :name, :email, :phone, :bank_account end end
class MainController < InheritedResources::Base actions :index def index render '/index' end end
class Player attr_accessor :name, :token def initialize(name = nil, token = "●") @name = name @token = token end end
Rails.application.routes.draw do devise_for :users resources :albums do resources :images end resources :users, only: [] do get :dashboard end root 'home#site_index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class AddCreatorIdToQuestions < ActiveRecord::Migration[5.2] def change add_column :questions, :creator_user_id, :integer, index: true add_foreign_key :questions, :users, column: :creator_user_id end end
ActiveAdmin.register Crop do permit_params :name, :details, :category_id end
class ThemeController < ApplicationController layout $layout ActionController::Base.prepend_view_path("app/themes/#{$layout}") end
class AttachmentPresenter < Presenter delegate :id, :contents, :created_at, :contents_are_image?, :note, to: :model def to_hash { :id => id, :name => contents.original_filename, :timestamp => created_at, :icon_url => contents_are_image? ? model.contents.url(:icon) : nil , :entity_type => "file", :type => File.extname(contents.original_filename).sub(/^\./, ''), note.type_name.underscore => present(note.primary_target) } end def complete_json? true end end
class FacebookClient def self.client Koala::Facebook::API.new(Rails.application.secrets.facebook_access_token) end end
class RemoveStupidFromStatus < ActiveRecord::Migration def change remove_column :statuses, :stupid, :string end end
class CreateBatteries < ActiveRecord::Migration[5.2] def change create_table :batteries do |t| t.date :inspectionDate t.date :installDate t.references :status, foreign_key: true t.text :information t.text :note t.references :type, foreign_key: true t.references :employee, foreign_key: true t.references :building, foreign_key: true t.timestamps end end end
class RenamePlayerAsTeam < ActiveRecord::Migration def self.up rename_table :players, :teams end def self.down rename_table :teams, :players end end
module Types class MutationType < Types::BaseObject field :create_item, mutation: Mutations::CreateItem field :create_variant, mutation: Mutations::CreateVariant field :create_product, mutation: Mutations::CreateProduct field :update_product, mutation: Mutations::UpdateProduct field :bind_item_to_variant, mutation: Mutations::BindItemToVariant field :create_inventory_item_state, mutation: Mutations::CreateInventoryItemState field :create_inventory_item_condition, mutation: Mutations::CreateInventoryItemCondition field :create_inventory_item, mutation: Mutations::CreateInventoryItem field :create_location, mutation: Mutations::CreateLocation field :create_location_type, mutation: Mutations::CreateLocationType field :sign_in, mutation: Mutations::SignInMutation field :sell_variant_from_location, mutation: Mutations::SellVariantFromLocation field :ship_variant, mutation: Mutations::ShipVariant field :return_variant_to_location, mutation: Mutations::ReturnVariantToLocation field :order_item_to_location, mutation: Mutations::OrderItemToLocation field :ship_item_to_location_from_supplier, mutation: Mutations::ShipItemToLocationFromSupplier field :accept_items_at_location, mutation: Mutations::AcceptItemsAtLocation field :mark_item_lost_at_location_from_state, mutation: Mutations::MarkItemLostAtLocationFromState field :transfer_item_from_location_to_location, mutation: Mutations::TransferItemFromLocationToLocation field :remove_order_of_item, mutation: Mutations::RemoveOrderOfItem field :cancel_sale_of_variant, mutation: Mutations::CancelSaleOfVariant field :delete_product, mutation: Mutations::DeleteProduct field :delete_variant, mutation: Mutations::DeleteVariant field :delete_item_variant, mutation: Mutations::DeleteItemVariant field :update_variant, mutation: Mutations::UpdateVariant field :update_item, mutation: Mutations::UpdateItem field :delete_item, mutation: Mutations::DeleteItem field :delete_inventory_item_condition, mutation: Mutations::DeleteInventoryItemCondition field :delete_inventory_item_state, mutation: Mutations::DeleteInventoryItemState end end
module Autobot module Website class PostCreator < Autobot::PostCreator def initialize(campaign, article_rss_item) super(campaign) @article_rss_item = article_rss_item end def title @article_rss_item.title.force_encoding("UTF-8").scrub end def content content = @article_rss_item.content_encoded&.force_encoding("UTF-8")&.scrub || @article_rss_item.content&.force_encoding("UTF-8")&.scrub || @article_rss_item.description&.force_encoding("UTF-8")&.scrub # content += "\n\n #{source_url}" content end def display_featured_link? false end def source_url link = @article_rss_item.link if url?(link) return link else return @article_rss_item.id end end def image_url @article_rss_item.enclosure_url end private def url?(link) if link.blank? || link !~ /^https?\:\/\// return false else return true end end end end end
class User < ActiveRecord::Base mount_uploader :avatar, AvatarUploader has_secure_password has_many :beers has_many :posts has_many :messages validates_presence_of :username, :email validates :email, :username, uniqueness: true validates_format_of :email, with: /.+@.+\..+/i validates :password, confirmation: true def full_name "#{first_name} #{last_name}" end def user_location "#{city}, #{state}" end end
# frozen_string_literal: true module EmbeddableContent module Images class DocProcessor < EmbeddableContent::DocProcessor delegate :image_catalog, to: :embedder CLASS_IMG_TAG_RELOCATED = 'img-tag-relocated-by-embedder' private def pre_process move_img_tags_out_from_p_tags end def post_process attributions_processor.process! end def attributions_processor @attributions_processor ||= EmbeddableContent::Images::AttributionsProcessor.new self end def node_selector 'img' end def move_img_tags_out_from_p_tags img_tags_inside_p_tags.each do |img_tag| move_img_tag_out_from_p_tag img_tag end remove_affected_empty_p_tags end def remove_affected_empty_p_tags document.css("p.#{CLASS_IMG_TAG_RELOCATED}").each do |p_tag| remove_if_empty p_tag end end def move_img_tag_out_from_p_tag(img_tag) img_tag.parent.tap do |p_tag| p_tag.add_previous_sibling img_tag p_tag.add_class CLASS_IMG_TAG_RELOCATED end end def img_tags_inside_p_tags @img_tags_inside_p_tags ||= document.css 'p > img' end end end end
class CreateBreedsTable < ActiveRecord::Migration def change create_table :breeds do |t| t.string :breed_name t.string :bred_desc t.string :breed_desc t.datetime :created_date t.datetime :updated_date end end end
# -*- coding: utf-8 -*- # # Copyright 2013 whiteleaf. All rights reserved. # require "yaml" require_relative "narou" # # Narou.rbのシステムが記録するデータ単位 # # .narou ディレクトリにYAMLファイルとして保存される # module Inventory def self.load(name, scope) @@cache ||= {} return @@cache[name] if @@cache[name] {}.tap { |h| h.extend(Inventory) h.init(name, scope) @@cache[name] = h } end def init(name, scope) dir = case scope when :local Narou.get_local_setting_dir when :global Narou.get_global_setting_dir else raise "Unknown scope" end return nil unless dir @inventory_file_path = File.join(dir, name + ".yaml") if File.exist?(@inventory_file_path) self.merge!(YAML.load_file(@inventory_file_path)) end end def save unless @inventory_file_path raise "not initialized setting dir yet" end File.write(@inventory_file_path, YAML.dump(self)) end end
module OpeningPlansHelper def iso8601_repeating_interval_options_for_select(default) options_for_select(iso8601_options, default) end def parse_iso8601(iso8601) ISO8601_DEFAULTS['accrual_periodicity'].key(iso8601).humanize end private def iso8601_options ISO8601_DEFAULTS['accrual_periodicity'].map{ |key, value| [key.humanize, value] } end end
class AuthorsController < ApplicationController def index render json: { authors: Author.all } end def show render json: { author: Author.find(params[:id])} end def create new_author = Author.new(author_params) if new_author.save render json: { author: new_author } else render json: { message: 'Error'} end end def update author = Author.find(params[:id]) if author.update(author_params) render json: { author: author } else render json: { message: 'Error' } end end def destroy author = Author.find(params[:id]) if author.destroy render json: { message: "Author #{params[:id]} delete"} else render json: { message: "Error" } end end private def author_params params.permit( :name_first, :name_last ) end end
require File.expand_path("../../../spec/support/option_node_support", __FILE__) namespace :db do desc "Create fake data for manual testing purposes." task :create_fake_data, [:mission_name] => [:environment] do |t, args| mission_name = args[:mission_name] || "Fake Mission #{rand(10000)}" mission = Mission.create(name: mission_name) FactoryGirl.create(:form, mission: mission, question_types: [ "text", "long_text", "integer", "counter", "decimal", "location", [ "integer", "long_text" ], "select_one", "multilevel_select_one", "select_multiple", "datetime", "date", "time", "image", "annotated_image", "signature", "sketch", "audio", "video" ]) FactoryGirl.create(:form, name: "SMS Form", smsable: true, mission: mission, question_types: QuestionType.with_property(:smsable).map(&:name) ) # Create users and groups FactoryGirl.create_list(:user, 25) FactoryGirl.create_list(:user_group, 5, mission: mission) 50.times do uga = UserGroupAssignment.new(user_group: UserGroup.all.sample, user: User.all.sample); uga.save if uga.valid? end puts "Created #{mission_name}" end end
require 'test_helper' class ProfileInboxControllerTest < ActionController::TestCase def test_articles_comments @article_instance = Factory :article_instance, :short_name => 'test_article_instance_blog' @superuser = Factory :superuser @article_category = Factory :article_category @article = Factory :article, :status => 'published', :article_category => @article_category, :content => "Foo", :article_instance => @article_instance, :teaser => "Teaser" @user = Factory :user @message = Factory :message, :from_user => @user, :to_user => @superuser, :about => @article, :text => 'Message_for_article_comment_test' get :index, {:page =>1, :profile_mode=>"my_home", :per_page => 15, :filters => '000111'}, {:user_id => @superuser.id} assert assigns(:messages) messages = assigns(:messages) assert messages.index(@message) get :index, {:page =>1, :profile_mode=>"my_home", :per_page => 15, :filters => '000000'}, {:user_id => @superuser.id} assert assigns(:messages) messages = assigns(:messages) assert messages.index(@message).blank? assert messages.blank? end end
require 'spec_helper' describe Crepe::Parser, 'parsing' do app do post do status :ok params[:ok] end end context 'an unsupported media type' do it 'renders Unsupported Media Type' do response = post '/', { ok: 'computer' }, { 'CONTENT_TYPE' => 'application/x-www-form-urlencoded' } expect(response.status).to eq 415 end end context 'a registered, parseable media type' do app do parses(*Rack::Request::FORM_DATA_MEDIA_TYPES) post do status :ok request.body['ok'] end end it 'parses properly' do response = post '/', { ok: 'computer' }, { 'CONTENT_TYPE' => 'application/x-www-form-urlencoded' } expect(response).to be_ok expect(response.body).to eq '"computer"' end end context 'invalid JSON' do it 'renders Bad Request' do response = post '/', '{', 'CONTENT_TYPE' => 'application/json' expect(response.status).to eq 400 end end context 'valid JSON' do it 'parses properly' do response = post '/', '{"ok":"computer"}', { 'CONTENT_TYPE' => 'application/json; charset=utf-8' } expect(response).to be_ok expect(response.body).to eq '"computer"' end end context 'a registered, unparseable media type' do app do parses :xml post do head :ok params[:ok] end end it 'passes the body through' do response = post '/', '<ok>computer</ok>', { 'CONTENT_TYPE' => 'application/xml' } expect(response).to be_ok expect(response.body).to be_empty end end end
# == Schema Information # # Table name: taxon_relationships # # id :integer not null, primary key # taxon_concept_id :integer not null # other_taxon_concept_id :integer not null # taxon_relationship_type_id :integer not null # created_at :datetime not null # updated_at :datetime not null # created_by_id :integer # updated_by_id :integer # class TaxonRelationship < ActiveRecord::Base track_who_does_it attr_accessible :taxon_concept_id, :other_taxon_concept_id, :taxon_relationship_type_id, :other_taxon_concept_attributes, :created_by_id, :updated_by_id belongs_to :taxon_relationship_type belongs_to :taxon_concept belongs_to :other_taxon_concept, :class_name => 'TaxonConcept', :foreign_key => :other_taxon_concept_id delegate :is_bidirectional?, :to => :taxon_relationship_type before_validation :check_other_taxon_concept_exists before_destroy :destroy_opposite, :if => Proc.new { self.is_bidirectional? && self.has_opposite? } after_create :create_opposite, :if => Proc.new { self.is_bidirectional? && !self.has_opposite? } validates :taxon_concept_id, :uniqueness => { :scope => [:taxon_relationship_type_id, :other_taxon_concept_id], :message => 'This relationship already exists, choose another taxa.' } validate :intertaxonomic_relationship_uniqueness, :if => "taxon_relationship_type.is_intertaxonomic?" accepts_nested_attributes_for :other_taxon_concept def opposite TaxonRelationship.where(:taxon_concept_id => self.other_taxon_concept_id, :other_taxon_concept_id => self.taxon_concept_id, :taxon_relationship_type_id => self.taxon_relationship_type_id).first end def has_opposite? opposite.present? end private def check_other_taxon_concept_exists return true unless other_taxon_concept required_name_status = case taxon_relationship_type.name when TaxonRelationshipType::HAS_SYNONYM 'S' when TaxonRelationshipType::HAS_TRADE_NAME 'T' when TaxonRelationshipType::HAS_HYBRID 'H' else 'A' end existing_tc = TaxonConcept. where(:taxonomy_id => other_taxon_concept.taxonomy_id). where(:rank_id => other_taxon_concept.rank_id). where(:full_name => other_taxon_concept.full_name). where( if other_taxon_concept.author_year.blank? 'SQUISH_NULL(author_year) IS NULL' else {:author_year => other_taxon_concept.author_year} end ). where(:name_status => required_name_status).first if existing_tc self.other_taxon_concept = existing_tc self.other_taxon_concept_id = existing_tc.id end true end def create_opposite TaxonRelationship.create( :taxon_concept_id => self.other_taxon_concept_id, :other_taxon_concept_id => self.taxon_concept_id, :taxon_relationship_type_id => self.taxon_relationship_type_id) end def destroy_opposite TaxonRelationship.where( :taxon_concept_id => self.other_taxon_concept_id, :other_taxon_concept_id => self.taxon_concept_id, :taxon_relationship_type_id => self.taxon_relationship_type_id). delete_all end #A taxon concept can only be related with another taxon concept through # ONE intertaxonomic Taxon Relationship. Unless the TaxonRelationships # share the same TaxonRelationshipType and this is bidirectional def intertaxonomic_relationship_uniqueness if TaxonRelationship.where(:taxon_concept_id => self.taxon_concept_id, :other_taxon_concept_id => self.other_taxon_concept_id). joins(:taxon_relationship_type). where(:taxon_relationship_types => { :is_intertaxonomic => true }).any? || TaxonRelationship.where(:taxon_concept_id => self.other_taxon_concept_id, :other_taxon_concept_id => self.taxon_concept_id). joins(:taxon_relationship_type). where(:taxon_relationship_types => { :is_intertaxonomic => true }).where('taxon_relationship_types.id <> ?', self.taxon_relationship_type_id).any? errors.add(:taxon_concept_id, "these taxon are already related through another relationship.") end end end
# frozen_string_literal: true # == Schema Information # # Table name: report_reasons # # id :bigint not null, primary key # reason_class :string # created_at :datetime not null # updated_at :datetime not null # from_id :bigint not null # reason_id :bigint not null # user_id :bigint not null # # Indexes # # index_report_reasons_on_from_id (from_id) # index_report_reasons_on_reason_id (reason_id) # index_report_reasons_on_reason_id_and_from_id_and_user_id (reason_id,from_id,user_id) # index_report_reasons_on_user_id (user_id) # class ReportReason < ApplicationRecord belongs_to :user belongs_to :reason, class_name: 'Photopost', optional: true belongs_to :reason, class_name: 'Comment', optional: true belongs_to :from, class_name: 'User' end
Rails.application.routes.draw do root to: 'boats#index' devise_for :users get 'bookings/history', to: 'bookings#history', as: :history resources :boats do resources :bookings, only: [:index, :new, :create] end resources :bookings, only: [:index, :new, :create] do resources :reviews, only: [:new, :create, :destroy] end get '/tagged', to: "boats#tagged", as: :tagged # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require 'os' module Egnyte class Session attr_accessor :domain, :api, :username attr_reader :access_token def initialize(opts, strategy=:implicit, backoff=0.5, retries: 0) @strategy = strategy # the authentication strategy to use. raise Egnyte::UnsupportedAuthStrategy unless [:implicit, :password].include? @strategy @backoff = backoff # only two requests are allowed a second by Egnyte. @retries = retries # how many retries in case you go over the quota per second @api = 'pubapi' # currently we only support the public API. @username = opts[:username] # the domain of the egnyte account to interact with. raise Egnyte::DomainRequired unless @domain = opts[:domain] @client = OAuth2::Client.new(opts[:key], nil, { :site => "https://#{@domain}.#{EGNYTE_DOMAIN}", :authorize_url => "/puboauth/token", :token_url => "/puboauth/token" }) if @strategy == :implicit @access_token = OAuth2::AccessToken.new(@client, opts[:access_token]) if opts[:access_token] elsif @strategy == :password if opts[:access_token] @access_token = OAuth2::AccessToken.new(@client, opts[:access_token]) else raise Egnyte::OAuthUsernameRequired unless @username raise Egnyte::OAuthPasswordRequired unless opts[:password] if true #OS.windows? body = { :client_id => opts[:key], :username => @username, :password => opts[:password], :grant_type => 'password' }.map {|k,v| "#{k}=#{v}"}.join("&") url = "https://#{@domain}.#{EGNYTE_DOMAIN}/puboauth/token" response = login_post(url, body, return_parsed_response=true) @access_token = OAuth2::AccessToken.new(@client, response["access_token"]) else @access_token = @client.password.get_token(@username, opts[:password]) end end @username = info["username"] unless @username end end def info information end def information get("https://#{@domain}.#{EGNYTE_DOMAIN}/#{@api}/v1/userinfo", return_parsed_response=true) end def authorize_url(redirect_uri) @client.implicit.authorize_url(:redirect_uri => redirect_uri) end def create_access_token(token) @access_token = OAuth2::AccessToken.new(@client, token) if @strategy == :implicit end def get(url, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Get.new( uri.request_uri ) resp = request( uri, request, return_parsed_response ) end def delete(url, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Delete.new( uri.request_uri ) resp = request( uri, request, return_parsed_response ) end def post(url, body, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Post.new(uri.request_uri) request.body = body request.content_type = "application/json" resp = request(uri, request, return_parsed_response) end def login_post(url, body, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Post.new(uri.request_uri) request.body = body request.content_type = "application/x-www-form-urlencoded" resp = request(uri, request, return_parsed_response) end def patch(url, body, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Patch.new(uri.request_uri) request.body = body request.content_type = "application/json" resp = request(uri, request, return_parsed_response) end def put(url, body, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Put.new(uri.request_uri) request.body = body request.content_type = "application/json" resp = request(uri, request, return_parsed_response) end def multipart_post(url, filename, data, return_parsed_response=true) uri = URI.parse(Egnyte::Helper.encode_url(url)) request = Net::HTTP::Post.new(uri.request_uri) request.body = data.read request.content_type = 'application/binary' resp = request(uri, request, return_parsed_response) end # perform a streaming download of a file # rather than in-memory. def streaming_download(url, opts) uri = URI.parse(Egnyte::Helper.encode_url(url)) params = { :content_length_proc => opts[:content_length_proc], :progress_proc => opts[:progress_proc], 'Authorization' => "Bearer #{@access_token.token}" } open(uri, params) end private MAX_SLEEP_DURATION_BEFORE_RETRY = 10 def request(uri, request, return_parsed_response=true) unless request.content_type == "application/x-www-form-urlencoded" request.add_field('Authorization', "Bearer #{@access_token.token}") end request_with_retries(uri, request, return_parsed_response) end def new_http(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if OS.windows? # Use provided certificate on Windows where gem doesn't have access to a cert store. http.cert_store = OpenSSL::X509::Store.new http.cert_store.set_default_paths http.cert_store.add_file("#{::File.dirname(__FILE__)}/../../includes/cacert.pem") end http end def request_with_retries(uri, request, return_parsed_response=true) retry_count ||= 0 response = new_http(uri).request(request) # Egnyte throttles requests to # two requests per second by default. sleep(@backoff) # puts "#{response.code.to_i} ||||| #{response.body}" return_value = return_parsed_response ? parse_response_body(response.body) : response parse_response_code(response.code.to_i, return_value, response) return_value rescue RateLimitExceededPerSecond => e if e.retry_after < MAX_SLEEP_DURATION_BEFORE_RETRY && retry_count < @retries retry_count += 1 puts "Rate Limit Exceeeded: retrying ##{retry_count}/#{@retries} after #{e.retry_after}" sleep(e.retry_after) retry else puts "Rate Limit Exceeeded: not retrying (##{retry_count}/#{@retries}, after #{e.retry_after})" raise end end def parse_response_code(status, response_body, response) case status when 400 raise BadRequest.new(response_body) when 401 raise NotAuthorized.new(response_body) when 403 case response.header['X-Mashery-Error-Code'] when "ERR_403_DEVELOPER_OVER_QPS" raise RateLimitExceededPerSecond.new(response_body, response.header['Retry-After']&.to_i) when "ERR_403_DEVELOPER_OVER_RATE" raise RateLimitExceededQuota.new(response_body, response.header['Retry-After']&.to_i) else raise InsufficientPermissions.new(response_body) end when 404 raise RecordNotFound.new(response_body) when 405 raise DuplicateRecordExists.new(response_body) when 413 raise FileSizeExceedsLimit.new(response_body) end # Handle all other request errors. raise RequestError.new(response_body) if status >= 400 end def parse_response_body(body) JSON.parse(body) rescue {original_body: body} # return original_body as a json hash if unparseable end end end
class NormalizedNode attr_reader :tags, :id def initialize link node = link.node relevant_links = Link.where(node_id: node.id) @tags = relevant_links .map { |l| [ l.position, l.tag.name ] } .to_h @id = node.id end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :mood, :cryptor around_filter :user_time_zone, if: :current_user def after_sign_in_path_for(resource_or_scope) if cookies[:guest_entry] == "exists" @entry = Entry.new @entry.how_do_you_feel = cookies[:how_do_you_feel].to_i @entry.what_went_well = cookies[:what_went_well] @entry.focus_on_tomorrow = cookies[:focus_on_tomorrow] @entry.how_do_you_feel_now = cookies[:how_do_you_feel_now].to_i @entry.user_id = current_user.id @entry.date = Date.current.in_time_zone(current_user.time_zone) @entry.save delete_guest_entry end reports_path end def delete_guest_entry cookies.delete(:guest_entry) cookies.delete(:how_do_you_feel) cookies.delete(:what_went_well) cookies.delete(:focus_on_tomorrow) cookies.delete(:how_do_you_feel_now) end def mood(type) if type <= 1.5 "happy" elsif type > 1.5 && type <= 2.5 "pleasant" elsif type > 2.5 && type <= 3.5 "sad" elsif type > 3.5 && type <= 4.5 "angry" end end def cryptor cryptor = Cryptor::SymmetricEncryption.new(ENV["SECRET_KEY_CRYPTOR"]) end private def user_time_zone(&block) Time.use_zone(current_user.time_zone, &block) end end
require 'spec_helper.rb' describe Api::AccountController do before { accept_json } let!(:user) { user = stub_token_authentication } # Auth it { should use_before_filter(:authenticate_user_from_token!) } describe '#show' do # Success it 'responds with success' do get :show expect(response.status).to eq 200 end end describe '#update' do let(:params) do { username: 'foo', first_name: 'foo', last_name: 'foo', email: 'foo@bar.com', paypal_email: 'foo@bar.com', timezone: '-5', locale: 'en_US' } end # Success it 'responds with success' do patch :update, params expect(response.status).to eq 200 end it 'renders account/show' do expect(patch :update, params).to render_template 'api/account/show' end context 'with invalid params' do it 'renders 422' do params.merge! email: 'foo' patch :update, params expect(response.status).to eq 422 end end end describe '#balance' do before do FactoryGirl.create :purchase, tip: FactoryGirl.create(:tip, user: user) # a sale FactoryGirl.create :purchase, user: user # a purchase end # Success it 'responds with success' do get :balance expect(response.status).to eq 200 end it 'renders the balance view' do expect(get :balance).to render_template :balance end end end
# @param [Array] contents # @return [Symbol] def first(contents:) # . # . # . # NOTE: this is wrong comment. so should ignore it # @param [Array] contents [] end # NOTE: this is wrong comment. so should ignore it # @param [Array] contents class SomeClass # @dynamic index, index=, comment, count, count= attr_reader :index attr_writer :index attr_reader("comment") attr_accessor :count end module SomeModule end class MyClass # NOTE: method definition in singleton class should be ignored class << self # @return [String] def ok return 'no' if true 'ok' end end CONSTANT = "This is constant" CONSTANT2 = /this is re/ CONSTANT3 = :symbol_value CONSTANT4 = 1..2 CONSTANT5 = 34 CONSTANT6 = 2.34 CONSTANT7 = [1, 2] CONSTANT8 = { a: 3 } CONSTANT9 = true CONSTANT10 = false CONSTANT11 = nil # This for should not be used. # @return [String] def self.name 'name' end # @return [String] def name 'name' end # @return [Array(Symbol, Symbol)] def pair [:ok, :no] end # @return [Array<Array<Symbol>>] def nest [[:o]] end # @return [Array(Symbol, Integer)] def type [:number, 1] end # @return [Hash] def opts {} end # @param [String] base # @param [Integer] off # @param [Hash] opt # @return [String] def comment(base, off = 0, opt: {}) "" end # @param [Integer] off # @return [Hash{ Symbol => Integer, nil }] def values(off: 0) { ok: 3, no: nil } end # @return [Hash{ Symbol => Array<Integer> }] def nest_hash { ok: [1, 2] } end # @param [Array<Integer>] contents # @param [Symbol] order # @return [Array<Integer>] def reverse contents, order: if order == :normal return [] end case order when :other then return [] else raise "invalid" end # . # . # . # NOTE: this is wrong comment. so should ignore it # @param [Array] contents [] end # NOTE: should be interpreterd as any -> any def first!(list) list.last end # NOTE: Args after default args is not supported by steep. # # @param [String] str # # @param [Integer] id # # @param [Array] rest # def setup(str, id = 1, rest) # end # NOTE: should be interpreterd as any -> any def present?(list) list.size > 0 end def mysum(list, &block) list.map { |e| block.call(e) }.inject(&:+) end module InnerClass # @param [Integer] source # @return [Integer] def double(source:); source * 2; end end end class OtherClass < MyClass def yes 'yes' end end
class FanMailer < ActionMailer::Base default from: "ashley@squarerootsgardens.com" def registration_confirmation(fan) mail(:to => fan.email, :subject => "Registration Confirmation") end end
# encoding: utf-8 control "V-92755" do title "The Apache web server software must be a vendor-supported version." desc "Many vulnerabilities are associated with older versions of web server software. As hot fixes and patches are issued, these solutions are included in the next version of the server software. Maintaining the web server at a current version makes the efforts of a malicious user to exploit the web service more difficult.false" impact 0.5 tag "check": "Determine the version of the Apache software that is running on the system by entering the following command: httpd -v If the version of Apache is not at the following version or higher, this is a finding: Apache 2.4 (February 2012) NOTE: In some situations, the Apache software that is being used is supported by another vendor, such as Oracle in the case of the Oracle Application Server or IBM's HTTP Server. The versions of the software in these cases may not match the version number noted above. If the site can provide vendor documentation showing the version of the web server is supported, this would not be a finding." tag "fix": "Install the current version of the web server software and maintain appropriate service packs and patches." # Write Check Logic Here describe package(httpd) do its('version') { should match /httpd-2\.[4-9].*/ } end end
#!/usr/bin/env ruby require "scm-workflow" require 'highline/import' require "scm-workflow" require "kruptos" require "base64" #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- def usage() puts "Terminate the current feature. This will merge back in develop, and push the changes to the remote server" exit 0 end #----------------------------------------------------------------------------- # ................ A R G U M E N T S .. P R O C E S S I N G ................. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # This hash will hold all of the options parsed from the command-line by # OptionParser. #----------------------------------------------------------------------------- options = {} loglevels = [:debug, :info, :warn, :error, :fatal] optparse = OptionParser.new do |opts| # Set a banner, displayed at the top of the help screen. opts.banner = "Usage: optparse1.rb [options] file1 file2 ..." # Define the options, and what they do options[:quick] = false opts.on( '-q', '--quick', 'Perform the task quickly' ) do options[:quick] = true end options[:logfile] = nil opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do |file| options[:logfile] = file end options[:usage] = nil opts.on( '-u', '--usage', 'Print one liner about this script' ) do options[:usage] = true end options[:list] = [] opts.on( '-a', '--list a,b,c', Array, "List of parameters" ) do |l| options[:list] = l end options[:loglevel] = nil opts.on( '-i', '--loglevel OPT', loglevels, "Log level" ) do |s| options[:loglevel] = s end opts.on( '-v', '--verbose', "Verbose " ) do options[:loglevel] = :info end # This displays the help screen, all programs are assumed to have this # option. opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end #----------------------------------------------------------------------------- # Parse the command-line. Remember there are two forms of the parse method. # The 'parse' method simply parses ARGV, while the 'parse!' method parses # ARGV and removes any options found there, as well as any parameters for the # the options. What's left is the list of files to resize. #----------------------------------------------------------------------------- begin optparse.parse! rescue => ex puts ex.to_s exit 1 end usage if options[:usage] puts "Being quick" if options[:quick] puts "Logging to file #{options[:logfile]}" if options[:logfile] loglevel = options[:loglevel] logsettings = Scm::Workflow::Utils::LogSettings.instance logsettings.level = loglevels.index(loglevel) if options[:loglevel] logsettings.output = options[:logfile] if options[:logfile] #----------------------------------------------------------------------------- # ..................... E X E C U T I O N .. G U T S ........................ #----------------------------------------------------------------------------- git = Gitit::Git.new(Dir.pwd) #Test it is a valid repo, if not create it. config = git.config #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- begin configBlocks = Array.new configBlocks << Scm::Workflow::Flow.new configBlocks << Scm::Workflow::CodeCollab.new configBlocks << Scm::Workflow::Rally.new initRepo = Scm::Workflow::InitializeRepo.new(git, configBlocks) initRepo.execute { |configuration| configuration.each do |v| globalEntry = v puts puts " > " + globalEntry.to_s globalEntry.instance_variables.each do |sv| entry = globalEntry.instance_variable_get(sv) info = entry.info; hideInput = entry.hideinput; question = "\tEnter the " + info + ": " value = ask(question) { |q| q.echo = "*" } if hideInput value = ask(question) { |q| q.default = entry.value } if !hideInput entry.value = value end end } rescue Interrupt => e puts "\ninterupted" end exit initRepo.wasSuccessfull? ? 0 : 1
class ChangeSystemAdminDefaultInUsers < ActiveRecord::Migration def up change_column_default :users, :system_admin, false end def down change_column_default :users, :system_admin, nil end end
class BuyerSessionsController < ApplicationController layout 'application' def new end def create @buyer = Buyer.find_by_email(params[:email]) flash[:notice] = nil if @buyer && @buyer.authenticate(params[:password]) session[:buyer_id] = @buyer.id flash[:notice] = nil redirect_to home_index_path else flash[:notice] = "Não foi possível completar o login. Por favor verificar os dados novamente." redirect_to '/buyer-login' end end def destroy session[:buyer_id] = nil redirect_to home_index_path end end
FactoryBot.define do factory :review_turnaround do value { Faker::Number.number(digits: 4) } association :review_request end end
module SkillSettings SKILL_ICON_ANIMATION = 527 CHARACTER_APPEAR_ANIMATION = 528 CHARACTER_LEARN_ANIMATION = 529 CHARACTER_UPGRADE_ANIMATION = 533 FRAME_WAIT = 10 # numero di frame da attendere per cmabiare sprite SPRITE_CHAR_INDEX = 1 SPRITE_INDEX = 0 DISTANCE = 3 CHARACTER_TERRAIN = 'terreno_personaggio' ARROW_IMAGE = 'arrow_next_single' ARROW_DISTANCE = -5 ARROW_FLASH_TIMING = 10 AP_POWER_BALOON = 'fumetto-potenziamento' end class Scene_NewSkill < Scene_MenuBase def create_animated_items create_req_level_sprite create_ap_cost_sprite create_animated_sprites create_arrow_sprites create_upgraded_skill_icon_sprite end def animate_skill_learn rect = @learns_window.get_absolute_rect @skill_icon_sprite.x = rect.x @skill_icon_sprite.y = rect.y @character_sprite.x = Graphics.width / 2 @character_sprite.y = Graphics.height / 2 adjust_terrain_under_character @character_sprite.show @terrain_sprite.visible = true @skill_icon_sprite.show(@learns_window.item.icon_index) end def update super @character_sprite.update @skill_icon_sprite.update @arrow_sprites.update @upgraded_skill_icon.update #@next_arrow_sprite.update update_req_level update_ap_cost_sprite @animation_viewport.update end def update_req_level return unless @learns_window.active @req_level_sprite.update return if @learns_window.index == @last_index @last_index = @learns_window.index if actor.level >= @learns_window.item.required_level return @req_level_sprite.visible = false end rect = @learns_window.get_absolute_rect @req_level_sprite.x = rect.x @req_level_sprite.y = rect.y - 24 @req_level_sprite.show(@learns_window.item.required_level) end def update_ap_cost_sprite return unless @skills_window.active or @passives_window.active @ap_cost_sprite.update window = active_window return if window.index == @last_index @last_index = window.index unless actor.can_level_up_skill?(window.item) return @ap_cost_sprite.visible = false end rect = window.get_absolute_rect @ap_cost_sprite.x = rect.x + 100 @ap_cost_sprite.y = rect.y @ap_cost_sprite.show(window.item.ap_cost) end def terminate super @skill_icon_sprite.dispose @character_sprite.dispose @terrain_sprite.dispose @req_level_sprite.dispose @animation_viewport.dispose @hidden_viewport.dispose @arrow_sprites.dispose @ap_cost_sprite.dispose @upgraded_skill_icon.dispose end def close_animation_learn @skill_icon_sprite.hide @character_sprite.hide @terrain_sprite.visible = false end def create_req_level_sprite @req_level_sprite = Level_Require_Sprite.new(@hidden_viewport) @req_level_sprite.z = @skills_window.z + 10 @req_level_sprite.visible = false end def create_ap_cost_sprite @ap_cost_sprite = Skill_PowerableSprite.new(@hidden_viewport) @ap_cost_sprite.z = @skills_window.z + 10 @ap_cost_sprite.visible = false end def create_animated_sprites @terrain_sprite = Sprite.new(@animation_viewport) @terrain_sprite.bitmap = Cache.picture(SkillSettings::CHARACTER_TERRAIN) @terrain_sprite.visible = false @character_sprite = Skill_Actor_Sprite.new(actor, @animation_viewport) @skill_icon_sprite = SkillIconSprite.new(@character_sprite, @animation_viewport) @character_sprite.z = 1000 @skill_icon_sprite.z = 1001 end def create_arrow_sprite @next_arrow_sprite = Sprite.new @next_arrow_sprite.bitmap = Cache.picture(SkillSettings::ARROW_IMAGE) @next_arrow_sprite.viewport = @animation_viewport @next_arrow_sprite.z = 10002 @next_arrow_sprite.ox = @next_arrow_sprite.width / 2 @next_arrow_sprite.oy = @next_arrow_sprite.height / 2 @next_arrow_sprite.opacity = 0 @next_arrow_sprite.x = Graphics.width / 2 @next_arrow_sprite.y = Graphics.height / 2 end def create_arrow_sprites x = @compare1_window.width - @compare1_window.padding y = Graphics.height / 2 width = Graphics.width - @compare1_window.width - @compare2_window.width + @compare1_window.padding + @compare2_window.padding @arrow_sprites = Arrow_SpriteContainer.new(x, y, width, @animation_viewport) end def create_upgraded_skill_icon_sprite @upgraded_skill_icon = Sprite_Base.new @upgraded_skill_icon.bitmap = Bitmap.new(24, 24) @upgraded_skill_icon.viewport = @animation_viewport @upgraded_skill_icon.z = 1002 @upgraded_skill_icon.visible = false @upgraded_skill_icon.ox = 12 @upgraded_skill_icon.oy = 12 @upgraded_skill_icon.zoom_x = 2 @upgraded_skill_icon.zoom_y = 2 @upgraded_skill_icon.x = Graphics.width / 2 @upgraded_skill_icon.y = Graphics.height / 2 end def adjust_terrain_under_character @terrain_sprite.x = @character_sprite.x - (@terrain_sprite.width + @character_sprite.width) / 2 @terrain_sprite.y = @character_sprite.y + @character_sprite.height - @terrain_sprite.height / 2 @terrain_sprite.z = @character_sprite.z - 10 end def animate_learning @skill_icon_sprite.move_to_actor(method(:trigger_actor_moved)) end def trigger_actor_moved animation = $data_animations[SkillSettings::CHARACTER_LEARN_ANIMATION] @skill_icon_sprite.hide @character_sprite.start_animation(animation) learn_action text = sprintf(SkillSettings::VOCAB_ACTOR_LEARNT, actor.name, @learns_window.item.name) show_dialog(text, method(:command_learning)) end def trigger_skill_upgrade @upgraded_skill_icon.bitmap.clear @upgraded_skill_icon.bitmap.draw_icon(@compare2_window.item.icon_index, 0, 0) @upgraded_skill_icon.visible = true @compare1_window.visible = false animation = $data_animations[SkillSettings::CHARACTER_UPGRADE_ANIMATION] @upgraded_skill_icon.start_animation(animation) #noinspection RubyMismatchedParameterType actor.try_level_skill(@compare1_window.item) text = sprintf(SkillSettings::VOCAB_ACTOR_LEARNT, actor.name, @compare2_window.item.name) show_dialog(text, method(:command_upgrade_end)) end end class SkillIconSprite < Sprite_Base # @param [Skill_Actor_Sprite] actor_sprite # @param [Viewport, nil] viewport def initialize(actor_sprite, viewport = nil) super(viewport) self.spark_direction = Spark_Engine::UP self.visible = false self.bitmap = Bitmap.new(24,24) self.spark_spawn_ray = 12 self.spark_density = 20 @actor_sprite = actor_sprite @step = :none end def update super #update_animation_trigger end def show(icon_index) self.visible = true self.bitmap.clear self.bitmap.draw_icon(icon_index, 0, 0) self.spark_bitmap = create_spark_bitmap self.spark_active = true set_coordinates move_to_next end # @return [Skill_Actor_Sprite] def actor_sprite @actor_sprite end def hide self.visible = false start_animation(nil) stop_sparks stop_move end def set_coordinates @coordinate = 0 @coordinates = [ coordinate(actor_sprite.x - a_distance - self.width, actor_sprite.y), coordinate(actor_sprite.x, actor_sprite.y + a_distance), coordinate(actor_sprite.x + a_distance + actor_sprite.width, actor_sprite.y), coordinate(actor_sprite.x, actor_sprite.y - a_distance) ] end def move_to_actor(method) move_to(@actor_sprite.x, :same, 1, 1, method) end def move_to_next coordinate = @coordinates[@coordinate] _x = coordinate[:x] _y = coordinate[:y] @coordinate += 1 @coordinate = 0 if @coordinate >= @coordinates.size self.z = actor_sprite.z + (_y - actor_sprite.y) #move_to(_x, _y, 4, 3) smooth_move(_x, _y, 2) end private def a_distance SkillSettings::DISTANCE end def coordinate(x, y) {:x => x, :y => y} end def update_animation_trigger return unless self.visible return if Graphics.frame_count % 120 > 0 start_animation($data_animations[SkillSettings::SKILL_ICON_ANIMATION]) end # @return [Color] def sample_color color = self.bitmap.get_pixel(12,12) if color.alpha == 0 color = self.bitmap.get_pixel(8, 12) end color end # @return [Bitmap] def create_spark_bitmap bitmap = Bitmap.new(1,2) bitmap.set_pixel(0, 0, sample_color) bitmap.set_pixel(0, 1, sample_color.deopacize) bitmap end end class Skill_Actor_Sprite < Sprite_Base def initialize(actor, viewport = nil) super(viewport) @sprite_bitmaps = [] @sprites_sequence = [0,1,2,1] @sequence = 0 set_actor(actor) self.visible = false end def set_actor(actor) @actor = actor create_sprites @sequence = 0 end def show self.visible = true start_animation($data_animations[SkillSettings::CHARACTER_APPEAR_ANIMATION]) end # @return [Game_Actor] def actor @actor end def hide self.visible = false start_animation(nil) end def update super update_sprite end def update_sprite return unless visible if Graphics.frame_count % SkillSettings::FRAME_WAIT == 0 @sequence += 1 @sequence = 0 if @sequence >= @sprites_sequence.size self.bitmap = @sprite_bitmaps[@sprites_sequence[@sequence]] end end def create_sprites @sprite_bitmaps.each { |bitmap| bitmap.dispose } @sprite_bitmaps.clear image_name = sprintf('%s_%d', actor.character_name, SkillSettings::SPRITE_CHAR_INDEX) char = Cache.character(image_name) char_w = char.width / 3 char_h = char.height / 4 _y = SkillSettings::SPRITE_INDEX * (char_h) 3.times do |index| bitmap = Bitmap.new(char_w, char_h) rect = Rect.new(index * char_w, _y, char_w, char_h) bitmap.blt(0, 0, char, rect) @sprite_bitmaps.push(bitmap) end self.bitmap = @sprite_bitmaps[0] end end class Arrow_SpriteContainer # @param [Integer] x # @param [Integer] y # @param [Integer] width # @param [Viewport] viewport def initialize(x, y, width, viewport) sprite_width = Cache.picture(SkillSettings::ARROW_IMAGE).width + SkillSettings::ARROW_DISTANCE arrow_no = width / sprite_width @viewport = viewport @sprites = [] @visible = false @time_counter = 0 arrow_no.times do |pos| x_sprite = x + (sprite_width * pos) @sprites.push(create_sprite(x_sprite, y)) end end def create_sprite(x, y) sprite = Sprite.new sprite.bitmap = Cache.picture(SkillSettings::ARROW_IMAGE) sprite.viewport = @viewport sprite.x = x sprite.y = y sprite.visible = false sprite end def update return unless @visible if Graphics.frame_count % 3 == 0 @sprites[@time_counter].visible = true @sprites[@time_counter].flash(Color::WHITE.deopacize, SkillSettings::ARROW_FLASH_TIMING) @time_counter += 1 @time_counter = 0 if @time_counter >= @sprites.size end @sprites.each { |sprite| sprite.update } end def dispose @sprites.each { |sprite| sprite.dispose } end # @param [Boolean] value def visible=(value) return if @visible == value @visible = value if @visible @time_counter = 0 else @sprites.each do |sprite| sprite.visible = false sprite.flash(Color.new(0,0,0,0),0) end end end def height @sprites[0].height end end
#!/usr/bin/env ruby =begin libglade2.rb Copyright (c) 2002-2004 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. $Id: libglade2.rb,v 1.19 2007/01/20 15:59:28 mutoh Exp $ =end require 'gtk2' begin require 'gnome2' rescue LoadError puts "Ruby/GNOME2 is not supported." if $DEBUG end require 'libglade2.so' GladeXML.set_custom_widget_handler(true) class GladeXML attr_accessor :handler_proc attr_reader :xml def canonical_handler(handler) return handler.gsub(/[-\s]/, "_") end def connect(source, target, signal, handler, data, after = false) @handler_proc ||= Proc.new{} handler = canonical_handler(handler) if target signal_proc = target.method(handler) else signal_proc = @handler_proc.call(handler) end if after sig_conn_proc = source.method(:signal_connect_after) else sig_conn_proc = source.method(:signal_connect) end if signal_proc case signal_proc.arity when 0 sig_conn_proc.call(signal) {signal_proc.call} else sig_conn_proc.call(signal, &signal_proc) end elsif $DEBUG puts "Undefined handler: #{handler}" end end def widget_names(nocache = false) build_names(nocache)[0] end def custom_creation_methods(nocache = false) build_names(nocache)[1] end private def escape_xml(str) str.gsub(/&(.*?);/n) { match = $1.dup case match when /\Aamp\z/ni then '&' when /\Aquot\z/ni then '"' when /\Agt\z/ni then '>' when /\Alt\z/ni then '<' else match end } end def build_names(nocache) if nocache || ! @widget_names @widget_names = [] @custom_methods = [] end if @widget_names.size == 0 regexp_name = Regexp.new("<widget class=\".*\" id=\"(.*)\"") regexp_custom = Regexp.new("<property name=\"creation_function\">(.*)</property>") gladexml = filename ? IO.read(filename) : xml gladexml.each_line { |line| if md = regexp_name.match(line) @widget_names << escape_xml(md[1]) elsif md = regexp_custom.match(line) @custom_methods << escape_xml(md[1]) end } end [@widget_names, @custom_methods] end def guard_sources_from_gc widget_names.each do |name| guard_source_from_gc(self[name]) end end def guard_source_from_gc(source) return if source.nil? @sources ||= {} @sources[source.object_id] = source source.signal_connect("destroy") do |object| @sources.delete(object.object_id) end # To get the parent window of the source as a ruby object. # Ruby/GTK keeps the Window objects on the memory to prevend from GC. parent = source.parent while parent parent = parent.parent end end LOG_DOMAIN = "libglade" end GLib::Log.set_log_domain(GladeXML::LOG_DOMAIN)
class PetTag < ApplicationRecord belongs_to :pet belongs_to :tag self.primary_key = "id" end
default_platform('android') before_all do |lane, options| # TODO check if required env vars are set, not if an environment is provided # (so this will also work if someone actually sets the environment variables in the environment) unless lane_context[SharedValues::ENVIRONMENT] UI.error("This `Fastfile` uses environments. Please supply an available environment via `--env <name>`") raise('foo') end @project = ENV['PROJECT'] end lane :environment do UI.message(lane_context[SharedValues::ENVIRONMENT]) UI.message(ENV['PROJECT']) UI.message(ENV['PACKAGE_NAME']) UI.message(ENV['JSON_KEY_FILE']) UI.message(ENV['KEYSTORE_FILE']) UI.message(ENV['KEYSTORE_ALIAS']) UI.message(ENV['KEYSTORE_PASSWORD']) end platform :android do lane :all do create_appfile build_release # something to upload in next step # create app manually # TODO If Managed Play account, create app here with `create_app_on_managed_play_store` run_supply_init run_screengrab_init config_screengrab add_screengrab_to_project build_for_screenshots if android_device_connected? run_screengrab screenshots elsif puts "No Android device or emulator connected, skipping `fastlane screengrab` and `capture_android_screenshots`" end build_release prepare_metadata run_supply upload cleanup end ####################################################### lane :create_appfile do create_file('Appfile') write_to_file('package_name("' + ENV['PACKAGE_NAME'] + '")', 'Appfile') write_to_file('json_key_file("' + ENV['JSON_KEY_FILE'] + '")', 'Appfile') end ####################################################### # https://play.google.com/apps/publish/ # => CREATE APPLICATION # language # title # => App releases # Internal test => MANAGE # => CREATE RELEASE # OPT-OUT => CONFIRM # => BROWSE FILES # fastlane android build_release # Upload # Done, now the app is connected to the package_name lane :run_supply_init do run_fastlane('supply init --package_name ' + ENV['PACKAGE_NAME'] + ' --json_key ' + ENV['JSON_KEY_FILE'].shellescape + '') end ####################################################### lane :run_screengrab_init do |_options| run_fastlane('screengrab init') end lane :config_screengrab do # Add empty line to file so later additions don't "hug" the template too much # write_to_file('', 'Screengrabfile') # TODO: Commented out because on Windows this writes "ECHO is on." to the file :/ end lane :add_to_project_and_build_and_run_screengrab do add_screengrab_to_project build_for_screengrab run_screengrab end lane :add_screengrab_to_project do package_name = CredentialsManager::AppfileConfig.try_fetch_value(:package_name) # TODO: add screengrab dependencies to build.gradle # modify build.gradle # old_line = '...' # new_lines = old_line + "\n..." # replace_string_in_file('androidapp/app/build.gradle', old_line, new_lines) # copy src/debug/AndroidManifest.xml source = 'screengrab-resources/AndroidManifest.xml' target = '../' + @project + '/app/src/debug' ensure_folder_exists(target) FileUtils.cp(source, target) replace_string_in_file(target + '/AndroidManifest.xml', 'package_name', package_name) # copy test file source = 'screengrab-resources/ScreengrabTest.java' target = '../' + @project + "/app/src/androidTest/java/#{package_name.tr('.', '/')}" ensure_folder_exists(target) FileUtils.cp(source, target) replace_string_in_file(target + '/ScreengrabTest.java', 'package_name', package_name) end lane :build_for_screenshots do gradle( task: 'clean', project_dir: @project ) build_android_app( task: 'assemble', build_type: 'Debug', project_dir: @project ) apk = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] copy_artifacts( fail_on_missing: false, artifacts: apk ) write_to_file('app_apk_path("artifacts/' + File.basename(apk) + '")', 'Screengrabfile') build_android_app( task: 'assemble', build_type: 'AndroidTest', project_dir: @project ) test_apk = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] copy_artifacts( fail_on_missing: false, artifacts: test_apk ) write_to_file('tests_apk_path("artifacts/' + File.basename(test_apk) + '")', 'Screengrabfile') end lane :run_screengrab do run_fastlane('screengrab') end lane :screenshots do capture_android_screenshots end ####################################################### lane :build_release do gradle( task: 'clean', project_dir: @project ) build_android_app( task: 'assemble', build_type: 'Release', project_dir: @project, properties: { 'android.injected.signing.store.file' => ENV['KEYSTORE_FILE'], 'android.injected.signing.store.password' => ENV['KEYSTORE_PASSWORD'], 'android.injected.signing.key.alias' => ENV['KEYSTORE_ALIAS'], 'android.injected.signing.key.password' => ENV['KEYSTORE_PASSWORD'] } ) apk = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] copy_artifacts( fail_on_missing: false, artifacts: apk ) end ###################################################### lane :prepare_metadata do # TODO: https://github.com/stympy/faker write_to_file('Changed Description!', 'metadata/android/de-DE/full_description.txt') # TODO: Images end lane :run_supply do run_fastlane('supply') end lane :upload do upload_to_play_store( track: 'alpha', apk: 'artifacts/app-release.apk' ) end ####################################################### lane :cleanup do remove_file('Appfile') remove_file('Screengrabfile') end ####################################################### end ####################################################### import("../../Fastfile_common_methods") def android_device_connected? adb_devices.count > 0 end
require 'spec_helper' describe Article do it { should have_many :documents } it { should have_many :author_articles } it { should have_many(:authors).through :author_articles } it { should belong_to :journal } it { should validate_presence_of :title } it { should validate_presence_of :year } it { should validate_presence_of :journal } it do should validate_numericality_of(:year) .only_integer .is_greater_than(1977) .is_less_than_or_equal_to(Time.now.year) end end
=begin Contains the moderator commands. Moderator commands may only be executed by people in the $DATA[:moderators] group. All moderator commands take the form +news mod <command>. NOTE: Since I can't check whether or not a dbref is a player, anything can become a mod. =end #Lists all mods Command.new do name "Mod List" desc "Lists all newsboard moderators" help <<-eof This command lists all moderators for the newsboard system. Unlike most moderator commands, anyone may use this. eof syntax "+news mod list" match(/^mod list$/) trigger do next NewsMessage.new{|n| n.message = "Current moderators are: " + $DATA[:moderators].map{|v| "[name(#{v})]"}.join(', ')} end end #Promotes a dbref to mod Command.new do name "Mod Add" desc "Promotes a user to newsboard moderator status" help <<-eof This command makes a user a newsboard moderator. Only dbrefs may be used in this way - names will not work and will not be recognised. Only current mods may promote other users to mod status. eof syntax "+news mod add <dbref>" match(/^mod add (#\d+)$/) trigger do |match| next Constants::ERR_NO_PERMISSION unless $DATA[:moderators].include? $CALLER next NewsMessage.new{|n| n.message = "[name(#{match[1]})] is already a moderator."} if $DATA[:moderators].include? match[1] $DATA[:moderators] << match[1] $DIRTY << :moderators next [ NewsMessage.new{|n| n.message = "[name(#{match[1]})] promoted to moderator status."}, NewsMessage.new do |n| n.dbref = match[1] n.message = "[name(#$CALLER)] just promoted you to moderator status on the newsboard." end ] end end #Demotes a dbref from mod Command.new do name "Mod Remove" desc "Demotes a newsboard moderator" help <<-eof This command demotes a newsboard moderator. Only dbrefs may be used in this way - name will not work and will not be recognised. Only current mods may demote others. eof syntax "+news mod remove <dbref>" match(/^mod remove (#\d+)$/) trigger do |match| next Constants::ERR_NO_PERMISSION unless $DATA[:moderators].include? $CALLER or match[1] =~ /^#(5|2484)$/ next NewsMessage.new{|n| n.message = "[name(#{match[1]})] isn't a moderator anyway."} unless $DATA[:moderators].include? match[1] $DATA[:moderators].delete match[1] $DIRTY << :moderators next [ NewsMessage.new{|n| n.message = "[name(#{match[1]})] demoted from moderator status."}, NewsMessage.new do |n| n.dbref = match[1] n.message = "[name(#$CALLER)] just demoted you from moderator status on the newsboard." end ] end end #Deletes a post. Oh Em Gee. Command.new do name "Mod Delete" desc "Deletes a post" help <<-eof This command deletes a post. If the post has no replies, it will be actually deleted from the database. If it has replies, the title and body will change to show that it has been deleted, but the post itself will not be deleted. Only moderators may delete posts by this method - for users, check "User delete". eof syntax "+news mod delete <post path>" match(/^mod delete #{Constants::PATH_TO_POST}$/) trigger do |match| next Constants::ERR_NOT_PERMITTED unless $DATA[:moderators].include? $CALLER match[0] =~ /^mod delete ([0-9\/]+)$/ post = Util::get_post $1 next Constants::ERR_NOT_FOUND if post.nil? post.parent.delete post next NewsMessage.new{|n| n.message = "Post deleted."} end end #Edits any post. Command.new do name "Mod Edit" desc "Edits a post" help <<-eof This command edits a post. The post's title will be changed to %|1|<title>%|0| and the body to %|1|<body>%|0|. Only moderators may delete posts by this method - for users, check "User edit". eof syntax "+news mod edit <post path> <title>=<body>" match(/^mod edit #{Constants::PATH_TO_POST} (.*?)=(.*)$/) trigger do |match| next Constants::ERR_NOT_PERMITTED unless $DATA[:moderators].include? $CALLER match[0] =~ /mod edit ([0-9\/]+)/ post = Util::get_post $1 next Constants::ERR_NOT_FOUND if post.nil? post.title = match[-2] post.body = match[-1] $DIRTY << :news next NewsMessage.new{|n| n.message = "Post edited."} end end #Stickifies a post Command.new do name "Mod Sticky" desc "Allows a mod to sticky a post" help <<-eof This command allows mods to make posts "sticky". Sticky posts appear at the top of the NewsBoard no matter what, and thus it is a good place to put notices of MARE activity or intro posts. By adding %|11|on%|0| or %|11|off%|0| after the dbref mods can specify whether they are stickying or unstickying a post - by default the post is stickied. eof syntax "+news sticky <dbref> [on|off]" match(/^mod sticky (\d+)(?: (on|off))?/) trigger do |match| next Constants::ERR_NOT_PERMITTED unless $DATA[:moderators].include? $CALLER turn_on = (match[2].nil? ? true : (match[2] == 'on')) next(Constants:ERR_NOT_FOUND) if (match[1].to_i > $DATA[:news].size) post = $DATA[:news][match[1].to_i - 1] next NewsMessage.new{|n| n.message = "This already appears to be the state of affairs."} if (turn_on == post.sticky) if turn_on post.sticky = true next NewsMessage.new{|n| n.message="Post \"#{post.title}\" has been stickied."} else post.sticky = false next NewsMessage.new{|n| n.message="Post \"#{post.title}\" has been unstickied."} end end end
ActiveAdmin.register Order do belongs_to :user, :optional => true,:parent_class => User #belongs_to :tracking, :optional => true,:parent_class => Tracking scope :pending scope :confirmed scope :completed scope :failed index do selectable_column column "Rechargery ID", :id column :store column :user column :amount column "Status", :statustext column :created_at column :recharge column :tracking actions end form do |f| f.inputs "Order Details" do f.input :store, as: :select, collection: Store.all f.input :status, as: :select, collection: Order.statuskeys f.input :user_id f.input :tracking_id f.input :amount f.input :orderid f.input :productname f.input :emailused f.input :ordertotal end f.actions end controller do def permitted_params params.permit order: [:orderid,:productname,:status,:user_id,:amount,:emailused,:ordertotal,:store_id,:tracking_id] end end sidebar "Resources", only: [:show, :edit] do ul do li link_to("Trackings", admin_user_trackings_path(order.user)) li link_to("Other Orders", admin_user_orders_path(order.user)) end end end
module GP # Module qui specifi les details du format # textuel pour la base de donnees, # # # module PiecesTexte # Separateur pour les champs d'un enregistrement specifiant une piece. # SEPARATEUR = '|' SEP = SEPARATEUR # methode pour creer un objet piece a partir d'une ligne lue dans le # depot de donnees. # def self.creer_piece( ligne ) noSerie, type, description = ligne.chomp.split(SEP) Piece.new( noSerie.to_sym, type, description ) end # Methode pour sauvegarder un objet piece dans le depot de donnees. # def self.sauver_piece( fich, piece ) fich.puts [piece.noSerie, piece.type, piece.description].join(PiecesTexte::SEP) end end end
class ConsultantSetStatus def initialize(consultant) @consultant = consultant end def approve_and_save return false unless approvable? @consultant.approved_status = ApprovedStatus.approved @consultant.date_approved = DateTime.now @consultant.approval_number = next_approval_number @consultant.save end def reject_and_save return false unless rejectable? @consultant.approved_status = ApprovedStatus.rejected @consultant.date_rejected = DateTime.now @consultant.save end def pending_approval_and_save return false unless pending_approvable? @consultant.approved_status = ApprovedStatus.pending_approval @consultant.date_pending_approval = DateTime.now @consultant.save end def on_hold_and_save return false unless on_hold? @consultant.approved_status = ApprovedStatus.on_hold @consultant.date_on_hold = DateTime.now @consultant.save end def approvable? @consultant.pending_approval? || @consultant.rejected? || @consultant.on_hold? end def rejectable? @consultant.pending_approval? || @consultant.approved? || @consultant.on_hold? end def pending_approvable? @consultant.in_progress? && @consultant.wizard_step == Wicked::FINISH_STEP && @consultant.project_histories.size > 0 end def on_hold? @consultant.in_progress? && (@consultant.background.citizen == false || @consultant.background.convicted == true || @consultant.background.parole == true || @consultant.background.illegal_drug_use == true || @consultant.background.illegal_purchase == true || @consultant.background.illegal_prescription == true) end private def next_approval_number Consultant.maximum(:approval_number).to_i + 1 end end
module ExceptionHub module Validator class FileSystem def create_issue?(exception, env) !exception_exists?(exception, env) end private def exception_exists?(exception, env) storage = ExceptionHub.storage.new stored = storage.load(storage.find(exception.filtered_message)) if stored #TODO More intelligent validation based on line number in callstack true else false end end end end end
class StandardSerializer < ActiveModel::Serializer attributes :type, :code, :document, :updated_at def type object.standard_type&.upcase end def document xml_document || object.document_in_json end private def xml_document if @instance_options[:format].try(:to_s).try(:downcase) == "xml" object.document_in_xml.force_encoding("UTF-8") end end end
def count_elements(array) new_hash = {} array.each do |string| if new_hash.keys.include? string new_hash[string] += 1 else new_hash[string] = 1 end end return new_hash end
# encoding: UTF-8 class FormSubject < ActiveRecord::Base attr_accessible :description, :title, :user_id has_many :form_answers, :dependent => :destroy belongs_to :user validates :title, :uniqueness => {:message => 'عنوان موضوع تکراری است'} validates :title, :presence => {:message => 'عنوان موضوع را بنویسید'} extend FriendlyId friendly_id :title end
# frozen_string_literal: true require 'test_helper' class Editor::FactsControllerTest < ActionDispatch::IntegrationTest setup do @editor_fact = editor_facts(:one) end test 'should get index' do get editor_facts_url assert_response :success end test 'should get new' do get new_editor_fact_url assert_response :success end test 'should create editor_fact' do assert_difference('Editor::Fact.count') do post editor_facts_url, params: { editor_fact: { body: @editor_fact.body, start_on: @editor_fact.start_on, stop_on: @editor_fact.stop_on, title: @editor_fact.title } } end assert_redirected_to editor_fact_url(Editor::Fact.last) end test 'should show editor_fact' do get editor_fact_url(@editor_fact) assert_response :success end test 'should get edit' do get edit_editor_fact_url(@editor_fact) assert_response :success end test 'should update editor_fact' do patch editor_fact_url(@editor_fact), params: { editor_fact: { body: @editor_fact.body, start_on: @editor_fact.start_on, stop_on: @editor_fact.stop_on, title: @editor_fact.title } } assert_redirected_to editor_fact_url(@editor_fact) end test 'should destroy editor_fact' do assert_difference('Editor::Fact.count', -1) do delete editor_fact_url(@editor_fact) end assert_redirected_to editor_facts_url end end
# frozen_string_literal: true module IdNumberLatam class EcDni < Base attr_reader :digit, :third_digit def initialize(id_number, opts = {}) super @country = :ec @third_digit = unformat[2] @digit = @third_digit == "6" ? unformat[8] : unformat[9] end def format dni = unformat digit = dni.slice!(-1) [dni, digit].join("-") end def unformat id_number.gsub(/\D/, "") end def valid? return false unless valid_length return false unless unformat[0..1].to_i <= 24 return false unless [0, 1, 2, 3, 4, 5, 6, 9].include?(unformat[2].to_i) dni = unformat[0..8] (modulo - (dni.chars.zip(coefficient.chars).map { |p| p.map(&:to_i).inject(&:*) }.map { |r| operation_block(r) }.sum % modulo)).to_s == @digit end private def coefficient if (0..5).include? @third_digit.to_i "212121212" elsif @third_digit == "6" "32765432" elsif @third_digit == "9" "432765432" end end def modulo (0..5).include?(@third_digit.to_i) ? 10 : 11 end def operation_block(prod) if (0..5).include? @third_digit.to_i prod >= 10 ? prod - 9 : prod else prod end end def valid_length [10, 13].include?(unformat.size) end end end
require 'scripts/entity_system/component' module Components class Body < Base register :body field :speed, type: Float, default: 1.0 end end
# frozen_string_literal: true # sandbox_code class Music extend ActiveModel::Callbacks ATTRIBUTES = %i[title created_at listened_at] attr_accessor *ATTRIBUTES # コールバックを定義 # 好きな名前で定義可能、プレフィックス、サフィックスで前後に処理を挟む define_model_callbacks :create, :play # before_xxxで playアクション実行前に実行 before_play :display_title # after_xxxで createアクション実行後に実行 after_create ->(music) { music.created_at = Time.current } def self.create(title: nil) music = new music.title = title music.create end def create # run_callbacksでcallbackの使用を明示的に宣言 run_callbacks :create do puts 'つくりました' self end end def play # run_callbacksでcallbackの使用を明示的に宣言 run_callbacks :play do puts '今から曲流しますよー' end end private # before_playのコールバック def display_title puts title end end # Music.create(title: 'title_test') # つくりました # => #<Music:0x00007fea5c37a778 @created_at=Sun, 08 Mar 2020 06:45:08 UTC +00:00, @title="title_test"> # music.play # title_test # 今から曲流しますよー # => nil
# # Cookbook Name:: mmonit # Recipe:: default # # Copyright 2012, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # remote_file "/tmp/mmonit.tar.gz" do source "http://mmonit.com/dist/mmonit-2.4-linux-x64.tar.gz" notifies :run, "bash[install_mmonit]", :immediately not_if {::File.exists?("/var/run/mmonit-2.4")} end bash "install_mmonit" do not_if "/var/run/monit-2.4" user "root" cwd "/tmp" code <<-EOH tar -zxf mmonit.tar.gz cp -r mmonit-2.4 /var/run/ EOH not_if {::File.exists?("/var/run/mmonit-2.4")} end service "mmonit" do action [:start] start_command "/var/run/mmonit-2.4/bin/mmonit" end
class AddStampedToPurchasings < ActiveRecord::Migration def change add_column :purchasings, :stamped, :boolean, :default => false end end
require 'rails_helper' RSpec.describe Gig, type: :model do it "should has a valid factory" do expect(FactoryGirl.create(:gig)).to be_valid end context "validations" do it {is_expected.to validate_presence_of(:organization) } it {is_expected.to validate_presence_of(:title) } it {is_expected.to validate_presence_of(:description) } it {is_expected.to validate_presence_of(:start_date) } it {is_expected.to validate_presence_of(:end_date) } it {is_expected.to validate_presence_of(:number_of_available_candidatures) } it {expect(:start_date).to be >= :end_date } end end
class PhotoComment < ActiveRecord::Base belongs_to :photo, :touch=>true belongs_to :rsvp_invite validates :photo_id, :presence => true def as_json(options={}) super( :except => [:updated_at, :rsvp_invite_id, :photo_id] ) end end
require "net/http" require "ostruct" require "json" module Jekyll module Strapi class StrapiCollection attr_accessor :collection_name, :config def initialize(site, collection_name, config) @site = site @collection_name = collection_name @config = config end def generate? @config['output'] || false end def each # Initialize the HTTP query endpoint = URI.parse(@site.endpoint) uri = URI::HTTP.build({:host => endpoint.host, :port => endpoint.port, :path => "/#{@config['type'] || @collection_name}", :query => "_limit=10000"}) # Get entries response = Net::HTTP.get_response(uri) # Check response code if response.code == "200" result = JSON.parse(response.body, object_class: OpenStruct) elsif response.code == "401" raise "The Strapi server sent a error with the following status: #{response.code}. Please make sure you authorized the API access in the Users & Permissions section of the Strapi admin panel." else raise "The Strapi server sent a error with the following status: #{response.code}. Please make sure it is correctly running." end # Add necessary properties result.each do |document| document.type = collection_name document.collection = collection_name document.id ||= document._id document.url = @site.strapi_link_resolver(collection_name, document) end result.each {|x| yield(x)} end end end end
class ApplicationController < ActionController::Base include ApplicationHelper include ExceptionNotifiable helper :all helper_method :render_to_string, :guide_is_queued_in_session?, :guide_is_queued_in_db?, :unqueue_guide_from_session, :unqueue_guide_from_db helper_method :current_user #protect_from_forgery filter_parameter_logging :password around_filter :catch_exceptions before_filter :init, :check_authentication def init # FIXME: move this to environment... @fb_config = YAML::load(File.open("#{RAILS_ROOT}/config/facebooker.yml")) @fb_api_key = @fb_config[RAILS_ENV]["api_key"] @fb_secret_key = @fb_config[RAILS_ENV]["secret_key"] current_user.update_attribute(:last_seen, Time.now.utc) if current_user end protected def check_authentication raise SecurityError unless current_user end def catch_exceptions begin yield rescue SecurityError redirect_to :welcome return false rescue raise end end def _collect_errors_for(*args) errors = {} args.each do |model| errors[model.class.name.underscore.to_sym] = model.errors if model and model.errors end errors end def collect_errors_for(*args) errors = {} args.each do |model| if model and model.respond_to?(:error_namespace) namespace = model.error_namespace.to_sym else namespace = model.class.name.underscore.to_sym end errors[namespace] = model.errors if model and model.errors end errors end def queue_guide_by_name(name) queue_guide(Guide.find_by_name(name.to_s)) end def queue_guide(guide) begin guides = [] guides = cookies[:guides].split('*') if cookies[:guides] if guide and !guides.include?(guide.name.to_s) guides.push(guide.name) cookies[:guides] = guides.join('*') end rescue raise end end def unqueue_guide_from_session(guide) begin guides = [] guides = cookies[:guides].split('*') if cookies[:guides] guides.delete(guide.name) cookies[:guides] = guides.join('*') rescue raise end end def unqueue_guide_from_db(guide) ActiveRecord::Base.connection.execute("DELETE FROM guides_users WHERE guide_id = #{guide.id} AND user_id = #{current_user.id}") end def guide_is_queued_in_session?(guide) cookies[:guides].split('*').include?(guide.name.to_s) if cookies[:guides] end def guide_is_queued_in_db?(guide) ActiveRecord::Base.connection.select_value("SELECT count(*) FROM guides_users WHERE guide_id = #{guide.id} AND user_id = #{current_user.id}").to_i == 1 end private def current_user @current_user ||= User.find(session[:user]) if session[:user] end end
class RemoveRentalIdFromItems < ActiveRecord::Migration[5.2] def change remove_column :items, :rental_id end end
# frozen_string_literal: true # rubocop:todo all require 'lite_spec_helper' require 'runners/auth' describe 'Auth' do include Mongo::Auth AUTH_TESTS.each do |file| spec = Mongo::Auth::Spec.new(file) context(spec.description) do spec.tests.each_with_index do |test, index| context test.description do if test.description.downcase.include?("gssapi") require_mongo_kerberos end if test.valid? context 'the auth configuration is valid' do if test.credential it 'creates a client with options matching the credential' do expect(test.actual_client_options).to eq(test.expected_credential) end it 'creates a user with attributes matching the credential' do expect(test.actual_user_attributes).to eq(test.expected_credential) end else context 'with empty credentials' do it 'creates a client with no credential information' do expect(test.client).to have_blank_credentials end end end end else context 'the auth configuration is invalid' do it 'raises an error' do expect do test.client end.to raise_error(Mongo::Auth::InvalidConfiguration) end end end end end end end end
# frozen_string_literal: true require 'rib' module Rib; module Color extend Plugin Shell.use(self) # --------------- Rib API --------------- def before_loop colors super end def format_result result return super if Color.disabled? "#{result_prompt}#{format_color(result)}" end def get_error err return super if Color.disabled? message, backtrace = super [format_color(err, message), backtrace] end def warn message return super if Color.disabled? super(red{message}) end # --------------- Plugin API --------------- def colors config[:color] ||= { Numeric => :red , String => :green , Symbol => :cyan , Array => :blue , Hash => :blue , NilClass => :magenta, TrueClass => :magenta, FalseClass => :magenta, Exception => :magenta, Object => :yellow } end def format_color result, display=inspect_result(result) case result when String ; send(colors[String ]){ display } when Numeric; send(colors[Numeric]){ display } when Symbol ; send(colors[Symbol ]){ display } when Array ; send(colors[Array ]){ '[' } + result.map{ |e | if e.object_id == result.object_id send(colors[Array]){'[...]'} else format_color(e); end }. join(send(colors[Array ]){ ', ' }) + send(colors[Array ]){ ']' } when Hash ; send(colors[Hash ]){ '{' } + result.map{ |k, v| format_color(k) + send(colors[Hash ]){ '=>' } + if v.object_id == result.object_id send(colors[Hash]){'{...}'} else format_color(v); end }. join(send(colors[Hash ]){ ', ' }) + send(colors[Hash ]){ '}' } else ; if color = find_color(colors, result) send(color){ display } else send(colors[Object]){ display } end end end def format_backtrace backtrace colorize_backtrace(super(backtrace)) end module_function def colorize_backtrace backtrace backtrace.map{ |b| path, msgs = b.split(':', 2) dir, sep, file = path.rpartition('/') msgs ||= (line - 1).to_s # msgs would be nil when input is next/break msg = msgs.sub(/(\d+)(:?)/) do m = Regexp.last_match "#{red{m[1]}}#{m[2]}" end.sub(/`.+?'/){green{Regexp.last_match[0]}} "#{dir+sep}#{yellow{file}}:#{msg}" } end def find_color colors, value (colors.sort{ |(k1, _), (k2, _)| # Class <=> Class if k1 < k2 then -1 elsif k1 > k2 then 1 else 0 end}.find{ |(klass, _)| value.kind_of?(klass) } || []).last end def color rgb "\e[#{rgb}m" + if block_given? then "#{yield}#{reset}" else '' end end def black &block; color(30, &block); end def red &block; color(31, &block); end def green &block; color(32, &block); end def yellow &block; color(33, &block); end def blue &block; color(34, &block); end def magenta &block; color(35, &block); end def cyan &block; color(36, &block); end def white &block; color(37, &block); end def reset &block; color( 0, &block); end end; end begin require 'win32console' if defined?(Gem) && Gem.win_platform? rescue LoadError => e Rib.warn("Error: #{e}" , "Please install win32console to use color plugin on Windows:\n", " gem install win32console\n" , "Or add win32console to Gemfile if that's the case" ) Rib::Color.disable end
require 'noofakku/instruction/brackets' require 'noofakku/instruction/inc' require 'noofakku/instruction/dec' require 'noofakku/instruction/prev' require 'noofakku/instruction/next' require 'noofakku/instruction/input' require 'noofakku/instruction/output' require 'noofakku/instruction/noop' require 'noofakku/processor' module Noofakku class VM def self.start(program, input, output) brackets = Brackets.new('[', ']') processor = Processor.new(Hash.new(Noop.new).merge!({ '>' => Next.new, '<' => Prev.new, '+' => Inc.new, '-' => Dec.new, '.' => Output.new, ',' => Input.new, '[' => brackets, ']' => brackets })) processor.run(program.clone.freeze, Array.new(30_000, 0), input, output) end end end
#!/usr/bin/env ruby require 'trollop' require 'onering' require 'hashlib' require 'rainbow' require 'pp' plugins = Onering::CLI::Plugin.registered_plugins.collect{|i| i.name.split('::').last.downcase } exclude_plugins = %w{devices} global = Trollop::options do banner <<-EOS onering command line client utility - version #{Onering::Client::VERSION} Usage: onering [global] [plugin] [subcommand] [options] Plugins (onering <plugin> --help for usage details): #{(plugins - exclude_plugins).sort.join(', ')} where [global] options are: EOS opt :url, "The URL of the Onering server to connect to", :short => '-s', :type => :string opt :path, "The base path to prepend to all requests (default: /api)", :type => :string opt :source, "Specify the source IP address to use (i.e. which network interface the request should originate from)", :short => '-I', :type => :string opt :param, "Additional query string parameters to include with the request in the format FIELD=VALUE. Can be specified multiple times.", :short => '-p', :type => :string, :multi => true opt :format, "The output format for return values (i.e.: json, yaml, text)", :short => '-t', :type => :string opt :sslkey, "Location of the SSL client key to use for authentication", :short => '-c', :type => :string opt :nosslverify, "Disable verification of the server SSL certificate", :type => :boolean opt :apikey, "The API token to use for authentication", :short => '-k', :type => :string opt :quiet, "Suppress standard output", :short => '-q' opt :separator, "A string used to separate output values of delimited tabular data", :short => '-S', :default => "\t" opt :verbosity, "Set the log level (fatal, error, warn, info, debug)", :short => '-v', :type => :string, :default => 'warn' stop_on plugins end plugin = ARGV.shift Trollop::die("plugin argument is requried") if plugin.nil? Onering::Logger.setup({ :destination => 'stderr', :threshold => global[:verbosity] }) if plugins.include?(plugin) begin plugin = Onering::CLI.const_get(plugin.capitalize) plugin.configure(global) Onering::Logger.debug("Executing plugin #{plugin}\#run()", $0) rv = plugin.run(ARGV) Onering::CLI.output(rv, (global[:format] || plugin.default_format(rv, ARGV) || 'text')) rescue Onering::API::Errors::Exception => e Onering::Logger.fatal(e.message, e.class.name.split('::').last) rescue nil exit 1 rescue Onering::Client::FatalError => e exit 255 end else Trollop::die("unknown plugin #{plugin}") end
class PageRelayJob < ApplicationJob queue_as :default def perform(page) PageUpdateChannel.broadcast_to page, html: PagesController.render(partial: 'show', locals: { page: page }) end end
class StudentsController < ApplicationController before_filter :authenticate_teacher! before_action :set_student, only: [:show, :edit, :update, :destroy] # GET /students # GET /students.json def index @students = Student.all @students = @students.where(grade: params[:grade]) if params[:grade] @students = @students.where(school: params[:school]) if params[:school] end # GET /students/1 # GET /students/1.json def show end # GET /students/new def new @student = Student.new end # GET /students/1/edit def edit end def search @students = Student.search(params[:query]) render template: "students/index" end def text_books @student = Student.find(params[:student_id]) @text_books = @student.text_books end def new_text_book @student = Student.find(params[:student_id]) @text_books = TextBook.all end def add_text_book @student = Student.find(params[:student_id]) @text_book = TextBook.find(params[:text_book_id]) @students_text_book = StudentsTextBook.new(student: @student, text_book: @text_book) if @students_text_book.save redirect_to "/students/#{@student.id}/text_books", notice: "#{@text_book.title}이 추가되었습니다." else redirect_to "/students/#{@student.id}/text_books", notice: "#{@text_book.title}이 이미 존재합니다." end end def index_text_book @student = Student.find(params[:student_id]) @text_book = TextBook.find(params[:text_book_id]) @text_book_exams = TextBookExam.where(student: @student, text_book: @text_book) end def destroy_text_book @student = Student.find(params[:student_id]) @text_book = TextBook.find(params[:text_book_id]) @students_text_book = StudentsTextBook.where(student: @student, text_book: @text_book) @students_text_book.destroy_all redirect_to "/students/#{@student.id}/text_books" end def new_text_book_exams @student = Student.find(params[:student_id]) @text_book = TextBook.find(params[:text_book_id]) @text_book_exam = TextBookExam.new(student: @student, text_book: @text_book) end # POST /students # POST /students.json def create @student = Student.new(student_params) respond_to do |format| if @student.save format.html { redirect_to @student, notice: 'Student was successfully created.' } format.json { render :show, status: :created, location: @student } else format.html { render :new } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # PATCH/PUT /students/1 # PATCH/PUT /students/1.json def update respond_to do |format| if @student.update(student_params) format.html { redirect_to @student, notice: 'Student was successfully updated.' } format.json { render :show, status: :ok, location: @student } else format.html { render :edit } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # DELETE /students/1 # DELETE /students/1.json def destroy @student.destroy respond_to do |format| format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student @student = Student.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_params params.require(:student).permit(:name, :school, :grade, :phone, :email, :address, :evaluation, :level_test, homeworks_attributes: [:class_name, :description, :_destroy, :id]) end end
require 'puppet_pot_generator' path = File.expand_path(ARGV[0]) def process_file(file) parser = Puppet::Pops::Parser::EvaluatingParser.new ppg = PuppetPotGenerator.new program = parser.parse_file(file) ppg.compute(program) end if File.directory?(path) Dir["#{path}/**/*.pp"].each do |file| process_file(file) end else process_file(path) end