text
stringlengths
10
2.61M
class TeacherController < ApplicationController rescue_from CanCan::AccessDenied do |exception| flash[:error] = exception.message redirect_to home_path end before_filter :authenticate_user! before_filter :authenticate_teacher def index end def practicas @practicas = current_user.practicas render 'practicas/index' end def courses @courses = current_user.courses render 'courses/index' end def students @students = current_user.students render 'students/index' end private def authenticate_teacher authorize! :do_teacher_stuff, :stuff end end
class ActionStepsController < ApplicationController include Authenticatable before_action :lookup_all, only: [:index] before_action :lookup_one_action, only: [:edit, :update, :complete, :uncomplete] # GET /action_steps # GET /action_steps.json def index @action_step = ActionStep.new respond_to do |format| format.html { render :index } format.json { render json: ActionStep.export(@in_progress), status: :unprocessable_entity } end end # GET /action_steps/new def new @action_step = ActionStep.new end # GET /action_steps/1/edit def edit end # POST /action_steps # POST /action_steps.json def create @action_step = current_user.action_steps.new(action_step_params) @action_step.state_for(params[:commit]); @action_step.touch respond_to do |format| if @action_step.save format.html { redirect_to action_steps_path, notice: "ADDED #{@action_step.description}" } format.json { render :show, status: :created, location: @action_step } else format.html { render :new } format.json { render json: @action_step.errors, status: :unprocessable_entity } end end end # PATCH/PUT /action_steps/1 # PATCH/PUT /action_steps/1.json def update @action_step.state_for(params[:commit]); @action_step.touch respond_to do |format| if @action_step.update(action_step_params) format.html { redirect_to action_steps_path, notice: "UPDATED #{@action_step.description}" } format.json { render :show, status: :ok, location: @action_step } else format.html { render :edit } format.json { render json: @action_step.errors, status: :unprocessable_entity } end end end # GET /action_steps/1/complete def complete respond_to do |format| if @action_step.complete format.html { redirect_to action_steps_path, notice: "COMPLETED #{@action_step.description}" } format.json { render :show, status: :ok, location: @action_step } else format.html { render :edit } format.json { render json: @action_step.errors, status: :unprocessable_entity } end end end # GET /action_steps/1/uncomplete def uncomplete respond_to do |format| if @action_step.uncomplete format.html { redirect_to action_steps_path, notice: "UNCOMPLETED '#{@action_step.description}'" } format.json { render :show, status: :ok, location: @action_step } else format.html { render :edit } format.json { render json: @action_step.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_action_step @action_step = ActionStep.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def action_step_params params.require(:action_step).permit(:description, :state, :due, :start, :frequency) end def lookup_all @in_progress = current_user.action_steps.incomplete @cards = DeckOfCards.new @cards.deal(@in_progress, :statefull) @journals = current_user.journals.recent.by_created end def lookup_one_action @action_step = current_user.action_steps.find_by(id: params[:id]) redirect_to :action => :index if @action_step.nil? end end
require 'setback/util' require 'redis' require 'redis-namespace' require 'uri' require 'yaml' module Psych class SyntaxError end end module Setback class RedisProvider class << self attr_writer :redis_url, :namespace_prefix def redis_url @redis_url ||= 'redis://localhost:6379' end def namespace_prefix @namespace_prefix ||= 'purgatory:' end end def initialize(options = {}) @redis_url = options[:redis_url] || Setback::RedisProvider.redis_url @parent = options.fetch(:parent_class) end def namespace @namespace ||= "#{Setback::RedisProvider.namespace_prefix}" << Setback::Util.underscore(@parent.name).gsub(/\//, ':') end def get(key) value = redis.get(key.to_s) return YAML.load(value) if value nil rescue Psych::SyntaxError, StandardError => e STDERR.puts "Corrupted YAML in #{key.to_s.inspect} -> #{e.class.name} #{e.message}" nil end def set(key, value) redis.set(key, YAML.dump(value)) value end def keys(filter_internal = true) redis.keys.reject do |k| k =~ /^__/ && filter_internal end.map(&:to_sym) end def all(filter_internal = true) {}.tap do |ret| keys(filter_internal).each do |k| ret[k.to_sym] = self.get(k) end end end private def redis @redis ||= Redis::Namespace.new(namespace, :redis => Redis.new(:url => @redis_url) ) end end end
class Contact < ActiveRecord::Base attr_accessible :email, :name validates :email, :presence => true validates :name, :format => { :with => /^[a-zA-z ]*$/} # Alpha, Nil and Spaces has_many :send_lists_contacts, :dependent => :destroy has_many :send_lists, :through => :send_lists_contacts def send_format name ? '<' + name + '>' + email : email end end
class TasksController < ApplicationController before_action :set_list , only: [:new, :create, :show, :edit, :update,:destroy] before_action :set_task, only: [ :show, :edit, :update,:destroy] before_action :check_admin , only: [:new, :destroy] before_action :downcase_strip_title, only: [:create] def index @tasks = Task.all end def userindex @tasks = current_user.tasks respond_to do |format| format.html { render :userindex } format.json {render json: @tasks} end end def new @task = @list.tasks.build end def create @task = @list.tasks.build(admin_task_params) if @task.save flash[:success] = "Task created" render json: @task, status: 201 end end def show respond_to do |format| format.html { render :show } format.json {render json: @task} end end def completed @tasks = current_user.completed_tasks render :index, :locals => {:my_string=>"My Completed"} end def overdue @tasks = current_user.overdue_tasks render :index,:locals => {:my_string=>"My Overdue"} end def edit end def update if current_user.admin? @task.update(admin_task_params) redirect_to @list else verify_valid_fields end end def destroy @task = @list.tasks.find(params[:id]) @task.destroy flash[:success] = "Task deleted" redirect_to list_path (@list) end private def admin_task_params params.require(:task).permit(:title, :description, :status, :due_date, :user_id) end def user_task_params params.require(:task).permit(:status, :user_id) end def set_list @list = List.find(params[:list_id]) end def set_task @task = @list.tasks.find(params[:id]) end def downcase_strip_title params[:task][:title] = params[:task][:title].strip.downcase end def verify_valid_fields if !@task.user.nil? && @task.user != current_user flash[:danger] = "You can only edit tasks assigned to you" redirect_to edit_list_task_path(@list,@task) and return elsif params[:task][:user_id].to_i != current_user.id flash[:danger] = "You can only assign tasks to yourself" redirect_to edit_list_task_path(@list,@task) and return else @task.update(user_task_params) redirect_to @list end end def check_admin if !current_user.admin? flash[:danger] = "Only Admins can add/delete Tasks" redirect_to @list end end end
class RenameEvaluationColumnToStoreComments < ActiveRecord::Migration[5.2] def change rename_column :store_comments, :evaluation, :rate end end
class AddLastPublicStoryFieldsToUsers < ActiveRecord::Migration def change add_column :users, :last_public_story_id, 'CHAR(10)' add_column :users, :last_public_story_created_at, :datetime add_index :users, :last_public_story_created_at end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Applicants name link', type: :feature do before(:each) do @application1 = Application.create( name: 'Test App Name', address: 'Test App Address', city: 'Test App City', state: 'Test App State', zip: 'Test App Zip', phone_number: 'Test App Number', description: 'Test App Description!' ) @application1.pets << [@pet1] end it 'pet show page after approval it is a link to their application show page' do visit "/applications/#{@application1.id}" click_on "Approve Application For: #{@pet1.name}" visit "/pets/#{@pet1.id}" expect(page).to have_link(@application1.name.to_s, href: "/applications/#{@application1.id}") end end
# -*- coding: utf-8 -*- require 'gtk2' require 'lib/diva_hacks' module Pango ESCAPE_RULE = {'&': '&amp;'.freeze ,'>': '&gt;'.freeze, '<': '&lt;'.freeze}.freeze class << self # テキストをPango.parse_markupで安全にパースできるようにエスケープする。 def escape(text) text.gsub(/[<>&]/){|m| ESCAPE_RULE[m] } end alias old_parse_markup parse_markup # パースエラーが発生した場合、その文字列をerrorで印字する。 def parse_markup(str) old_parse_markup(str) rescue GLib::Error => e error str raise e end end end =begin rdoc 本文の、描画するためのテキストを生成するモジュール。 =end module Gdk::MarkupGenerator # 表示する際に本文に適用すべき装飾オブジェクトを作成する # ==== Return # Pango::AttrList 本文に適用する装飾 def description_attr_list(attr_list=Pango::AttrList.new, emoji_height: 24) score.inject(0){|start_index, note| end_index = start_index + note.description.bytesize if UserConfig[:miraclepainter_expand_custom_emoji] && note.respond_to?(:inline_photo) end_index += -note.description.bytesize + 1 rect = Pango::Rectangle.new(0, 0, emoji_height * Pango::SCALE, emoji_height * Pango::SCALE) shape = Pango::AttrShape.new(rect, rect, note.inline_photo) shape.start_index = start_index shape.end_index = end_index attr_list.insert(shape) elsif clickable?(note) underline = Pango::AttrUnderline.new(Pango::Underline::SINGLE) underline.start_index = start_index underline.end_index = end_index attr_list.insert(underline) end end_index } attr_list end def clickable?(model) has_model_intent = Plugin.collect(:intent_select_by_model_slug, model.class.slug, Pluggaloid::COLLECT).first return true if has_model_intent Plugin.collect(:model_of_uri, model.uri).any? do |model_slug| Plugin.collect(:intent_select_by_model_slug, model_slug, Pluggaloid::COLLECT).first end end # Entityを適用したあとのプレーンテキストを返す。 # Pangoの都合上、絵文字は1文字で表現する def plain_description _plain_description[UserConfig[:miraclepainter_expand_custom_emoji]] end private def _plain_description @_plain_description ||= Hash.new do |h, expand_emoji| h[expand_emoji] = score.map{|note| if expand_emoji && note.respond_to?(:inline_photo) '.' else note.description end }.to_a.join end end end
class Participant < ActiveRecord::Base belongs_to :role belongs_to :event has_many :participant_days has_many :days, through: :participant_days has_many :participant_services has_many :services, through: :participant_services enum gender: %i(man woman) enum status: %w(created pending delayed paid arrived deleted) validates_presence_of :first_name, :last_name, :role, :event validates :days, length: { minimum: 1 } validates :email, presence: true, uniqueness: { scope: [:first_name, :last_name, :status] } validates :gender, inclusion: { in: genders.keys } validates :status, inclusion: { in: statuses.keys } validates :age, numericality: { only_integer: true, greater_than: 1, less_than: 130 } validate :paid_equals_cost before_create :calculate_cost before_create :calculate_deadline scope :active, -> { where.not(status: statuses[:deleted]) } scope :created, -> { where(status: statuses[:created]) } scope :unpaid, -> { where(status: statuses[:delayed]) } scope :women, -> { where(gender: genders[:woman]) } scope :men, -> { where(gender: genders[:man]) } def full_name [last_name, first_name].compact.join(' ') end def payment_deadline_at_string payment_deadline.strftime('%d-%m-%Y').to_s if payment_deadline.present? end def payment_deadline_at_string=(payment_deadline_at_str) self.payment_deadline = DateTime.strptime(payment_deadline_at_str, '%d-%m-%Y') if payment_deadline.present? end def self.gender_attributes_for_select genders.keys.to_a.map { |g| [I18n.t("participant_gender.#{g}"), g] } end def self.status_attributes_for_select statuses.keys.to_a.map { |s| [I18n.t("participant_status.#{s}"), s] } end def status_i18n I18n.t("participant_status.#{status}") end def gender_i18n I18n.t("participant_gender.#{gender}") end def send_confirmation @mandrill = MandrillMailer.new @mandrill.prepare_confirmation_message(self, Day.all) @mandrill.send_message('Confirmation_new') end def send_delete_info @mandrill = MandrillMailer.new @mandrill.prepare_delete_info_message(self) @mandrill.send_message('delete_participant') end def send_confirm_payment @mandrill = MandrillMailer.new @mandrill.prepare_confirm_payment_message(self, Day.all) @mandrill.send_message('confirm_payment') end attr_accessor :mandrill # private def paid_equals_cost return unless arrived? && paid < cost errors.add(:paid, 'does not equal cost') end def days_must_be_in_proper_groups day1 = Day.find_by_number(1) day2 = Day.find_by_number(2) day3 = Day.find_by_number(3) if days.length == 1 && !days.include?(day3) errors.add(:days, 'only third day can be chosen single') elsif days.length == 2 && (!days.include?(day1) || !days.include?(day2)) errors.add(:days, 'only first and second day can be chosen in pair') elsif days.length > Day.all.length errors.add(:days, 'too many days') end end def calculate_deadline current_period = PricingPeriod.current_period payment_time = 7 payment_deadline = Time.now.to_date + payment_time.days self.payment_deadline = payment_deadline logger.debug "Finished deadline calculation. Deadline: #{payment_deadline}" end def calculate_cost self.created_at ||= Time.now.getlocal('+01:00') current_period = PricingPeriod.corresponding_period(self.created_at.to_date) cost = 0 services.each do |service| service_price = service.service_prices.select { |sp| sp.role_id == role_id } cost += service_price[0].price end event = Event.find(event_id) if days.length == event.days.length event_price = event.event_prices.select { |event_price| event_price.role_id == role_id && event_price.pricing_period_id == current_period.id } cost += event_price[0].price else days.each do |day| day_price = day.day_prices.select { |dp| dp.role_id == role_id && dp.pricing_period_id == current_period.id } cost += day_price[0].price end end self.cost = cost end def days_include?(day_id) days.include?(Day.find_by_number(day_id)) end end
Rails.application.routes.draw do # get 'sessions/new' # get 'sessions/create' # get 'sessions/destroy' # get 'users/new' # get 'users/create' # get 'users/show' #user signup routes get "/signup", to: "users#new" get"/profile", to: "users#show" resources :users, only: [:create] #sessions routes get "/login", to: "sessions#new" get "/logout", to: "sessions#destroy" post "", to: "sessions#create" resources :sessions, only: [:create] #posts resources :posts, except: [:index] root "posts#index" end
class EditItem < HyperComponent param :todo triggers :saved triggers :cancel others :etc after_mount { DOM[dom_node].focus } render do INPUT(@Etc, defaultValue: @Todo.title, placeholder: 'What is left to do today?', key: @Todo) .on(:enter) do |evt| @Todo.update(title: evt.target.value) saved! end .on(:blur) do |evt| cancel! end end end
require './morse.rb' class Game ALPHABET = ("a".."z").to_a + [" "] MAX_LETTERS_IN_ANSWER = 100 def initialize(answer=nil) @answer = answer @answer ||= (rand(MAX_LETTERS_IN_ANSWER)+1).times.map{ ALPHABET[rand(26)] }.join @question = Morse.tap_out(@answer) end def question @question end def answer @answer end def guess(g) score = 0 @question.split("").each_with_index do |letter, i| score += 1 if @answer[i] == g[i % g.size] end score.to_f / @answer.size end end
#!/usr/bin/env ruby require 'TestSetup' require 'test/unit' #require 'rubygems' require 'ibruby' include IBRuby class SQLTypeTest < Test::Unit::TestCase CURDIR = "#{Dir.getwd}" DB_FILE = "#{CURDIR}#{File::SEPARATOR}sql_type_test.ib" def setup puts "#{self.class.name} started." if TEST_LOGGING if File::exist?(DB_FILE) Database.new(DB_FILE).drop(DB_USER_NAME, DB_PASSWORD) end @database = Database.create(DB_FILE, DB_USER_NAME, DB_PASSWORD) @connection = @database.connect(DB_USER_NAME, DB_PASSWORD) @connection.start_transaction do |tx| tx.execute("create table all_types (col01 boolean, col02 blob, "\ "col03 char(100), col04 date, col05 decimal(5,2), "\ "col06 double precision, col07 float, col08 integer, "\ "col09 numeric(10,3), col10 smallint, col11 time, "\ "col12 timestamp, col13 varchar(23))") end end def teardown @connection.close if @connection != nil && @connection.open? if File::exist?(DB_FILE) Database.new(DB_FILE).drop(DB_USER_NAME, DB_PASSWORD) end puts "#{self.class.name} finished." if TEST_LOGGING end def test01 types = [] types.push(SQLType.new(SQLType::BOOLEAN)) types.push(SQLType.new(SQLType::VARCHAR, 1000)) types.push(SQLType.new(SQLType::DECIMAL, nil, 10)) types.push(SQLType.new(SQLType::NUMERIC, nil, 5, 3)) types.push(SQLType.new(SQLType::BLOB, nil, nil, nil, 1)) assert(types[0] == types[0]) assert(!(types[0] == types[1])) assert(types[1] == SQLType.new(SQLType::VARCHAR, 1000)) assert(types[0].type == SQLType::BOOLEAN) assert(types[0].length == nil) assert(types[0].precision == nil) assert(types[0].scale == nil) assert(types[0].subtype == nil) assert(types[1].type == SQLType::VARCHAR) assert(types[1].length == 1000) assert(types[1].precision == nil) assert(types[1].scale == nil) assert(types[1].subtype == nil) assert(types[2].type == SQLType::DECIMAL) assert(types[2].length == nil) assert(types[2].precision == 10) assert(types[2].scale == nil) assert(types[2].subtype == nil) assert(types[3].type == SQLType::NUMERIC) assert(types[3].length == nil) assert(types[3].precision == 5) assert(types[3].scale == 3) assert(types[3].subtype == nil) assert(types[4].type == SQLType::BLOB) assert(types[4].length == nil) assert(types[4].precision == nil) assert(types[4].scale == nil) assert(types[4].subtype == 1) end def test02 types = SQLType.for_table("all_types", @connection) assert(types['COL01'] == SQLType.new(SQLType::BOOLEAN)) assert(types['COL02'] == SQLType.new(SQLType::BLOB, nil, nil, nil, 0)) assert(types['COL03'] == SQLType.new(SQLType::CHAR, 100)) assert(types['COL04'] == SQLType.new(SQLType::DATE)) assert(types['COL05'] == SQLType.new(SQLType::DECIMAL, nil, 5, 2)) assert(types['COL06'] == SQLType.new(SQLType::DOUBLE)) assert(types['COL07'] == SQLType.new(SQLType::FLOAT)) assert(types['COL08'] == SQLType.new(SQLType::INTEGER)) assert(types['COL09'] == SQLType.new(SQLType::NUMERIC, nil, 10, 3)) assert(types['COL10'] == SQLType.new(SQLType::SMALLINT)) assert(types['COL11'] == SQLType.new(SQLType::TIME)) assert(types['COL12'] == SQLType.new(SQLType::TIMESTAMP)) assert(types['COL13'] == SQLType.new(SQLType::VARCHAR, 23)) end end
=begin This file is part of the Arachni::Reactor project and may be subject to redistribution and commercial restrictions. Please see the Arachni::Reactor web site for more information on licensing and terms of use. =end module Arachni class Reactor class Connection # @author Tasos "Zapotek" Laskos <tasos.laskos@gmail.com> module TLS # Converts the {#socket} to an SSL one. # # @param [Hash] options # @option [String] :certificate # Path to a PEM certificate. # @option [String] :private_key # Path to a PEM private key. # @option [String] :ca # Path to a PEM CA. def start_tls( options = {} ) if @socket.is_a? OpenSSL::SSL::SSLSocket @ssl_context = @socket.context return end @ssl_context = OpenSSL::SSL::SSLContext.new @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:certificate] && options[:private_key] @ssl_context.cert = OpenSSL::X509::Certificate.new( File.open( options[:certificate] ) ) @ssl_context.key = OpenSSL::PKey::RSA.new( File.open( options[:private_key] ) ) @ssl_context.ca_file = options[:ca] @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT elsif @role == :server @ssl_context.key = OpenSSL::PKey::RSA.new( 2048 ) @ssl_context.cert = OpenSSL::X509::Certificate.new @ssl_context.cert.subject = OpenSSL::X509::Name.new( [['CN', 'localhost']] ) @ssl_context.cert.issuer = @ssl_context.cert.subject @ssl_context.cert.public_key = @ssl_context.key @ssl_context.cert.not_before = Time.now @ssl_context.cert.not_after = Time.now + 60 * 60 * 24 @ssl_context.cert.version = 2 @ssl_context.cert.serial = 1 @ssl_context.cert.sign( @ssl_context.key, OpenSSL::Digest::SHA1.new ) end if @role == :server @socket = OpenSSL::SSL::SSLServer.new( @socket, @ssl_context ) else @socket = OpenSSL::SSL::SSLSocket.new( @socket, @ssl_context ) @socket.sync_close = true # We've switched to SSL, a connection needs to be re-established # via the SSL handshake. @connected = false _connect if unix? end @socket end # Performs an SSL handshake in addition to a plaintext connect operation. # # @private def _connect return if @ssl_connected Error.translate do @plaintext_connected ||= super return if !@plaintext_connected # Mark the connection as not connected due to the pending SSL handshake. @connected = false @socket.connect_nonblock @ssl_connected = @connected = true end rescue IO::WaitReadable, IO::WaitWritable, Errno::EINPROGRESS rescue Error => e close e end # First checks if there's a pending SSL #accept operation when this # connection is a server handler which has been passed an accepted # plaintext connection. # # @private def _write( *args ) return ssl_accept if accept? super( *args ) end # First checks if there's a pending SSL #accept operation when this # connection is a server handler which has been passed an accepted # plaintext connection. # # @private def _read return ssl_accept if accept? super rescue OpenSSL::SSL::SSLErrorWaitReadable end private def ssl_accept Error.translate do @accepted = !!@socket.accept_nonblock end rescue IO::WaitReadable, IO::WaitWritable rescue Error => e close e false end def accept? return false if @accepted return false if role != :server || !@socket.is_a?( OpenSSL::SSL::SSLSocket ) true end # Accepts a new SSL client connection. # # @return [OpenSSL::SSL::SSLSocket, nil] # New connection or `nil` if the socket isn't ready to accept new # connections yet. # # @private def socket_accept Error.translate do socket = to_io.accept_nonblock ssl_socket = OpenSSL::SSL::SSLSocket.new( socket, @ssl_context ) ssl_socket.sync_close = true ssl.accept if @start_immediately ssl_socket end rescue IO::WaitReadable, IO::WaitWritable rescue Error => e close e end end end end end
require 'graphql' module Types ManagedSubscriptionType = GraphQL::ObjectType.define do name 'ManagedSubscription' description 'Resembles a ManagedSubscription Object Type' field :id, !types.ID field :tenant_id, types.String field :subscription_id, types.String field :subscription_source, types.String end end
# frozen_string_literal: true # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :order do date Time.zone.today from { Faker::Company.name } user company trait :with_ordered_status do status :ordered end factory :past_order do sequence :date do |n| Time.zone.today - 2 * n.days end end end end
require 'test_helper' class FlannelTest < Test::Unit::TestCase should "wrap functionality up in a neat package" do markup = ":header_two foo: Foo\n\n:list list: Bar" assert_equal "<h2 id='foo'>Foo</h2>\n\n<ul id='list'><li>Bar</li></ul>", Flannel.quilt(markup) end should "return nil if text is nil" do assert_nil Flannel.quilt(nil) end should "parse paragraphs correctly" do input = ":paragraph p_one:\nThis is paragraph one.\n\n:paragraph p_two:\nThis is paragraph two.\n\n:paragraph p_three:\nThis is paragraph three. Watchout for the end of file.\n" output = "<p id='p_one'>This is paragraph one.</p>\n\n<p id='p_two'>This is paragraph two.</p>\n\n<p id='p_three'>This is paragraph three. Watchout for the end of file.</p>" assert_equal output, Flannel.quilt(input) end context "basic behavior" do should "parse a block without an id" do markup = ":paragraph:\n this is my paragraph" assert_equal "<p>this is my paragraph</p>", Flannel.quilt(markup) end should "strip and convert underscores to pre tags" do markup = ":preformatted foo:\nfoo\n\n bar\n" assert_equal "<pre id='foo'>foo\n\n bar\n</pre>", Flannel.quilt(markup) end should "escape preformatted text" do markup = ":preformatted math:\n4 - 2 > 2 - 2\n" assert_equal "<pre id='math'>4 - 2 &gt; 2 - 2\n</pre>", Flannel.quilt(markup) end end context "When block starts with header, it" do should "convert one to a header one" do markup = ":header_one h:\n Some header" result = "<h1 id='h'>Some header</h1>" assert_equal result, Flannel.quilt(markup) end should "convert two equals to a header two" do markup = ":header_two h:\n Some header" result = "<h2 id='h'>Some header</h2>" assert_equal result, Flannel.quilt(markup) end end context "When block is a list, it" do should "be wrapped in ul tags" do markup = ":list list:\n Yadda\nYadda\nYadda" result = "<ul id='list'><li>Yadda</li>\n<li>Yadda</li>\n<li>Yadda</li></ul>" assert_equal result, Flannel.quilt(markup) end end context "bug fixes" do should "parse a simple paragraph" do markup = ":paragraph:\nbar bar\n" result = "<p>bar bar</p>" assert_equal result, Flannel.quilt(markup) end end end
class QuoteItemsController < ApplicationController before_filter :authenticate def new end def create @quote = Quote.find(params[:quote_id]) @quote_item = @quote.quote_items.build(params[:quote_item]) if @quote_item.save @quote_items = @quote.quote_items.paginate(:page => params[:page], :per_page => 10) flash[:success] = "#{@quote_item.item_num} successfully added." redirect_to edit_quote_path(@quote.id) else flash[:error] = "Unable to add #{@quote_item.item_num}." redirect_to edit_quote_path(@quote.id) end end def show end def edit end def destroy end def update @quote_item = QuoteItem.find(params[:id]) @quote = @quote_item.quote @quote_item.destroy render edit_quote_path(@quote.id) end def itemtotal(qty, price) number_to_currency(qty*price) end end
# Advance Conditionals with Methods in Ruby part 3 # Check if this object is responsive to the method next num = 1000 p num.respond_to?("next") puts # check if this object is responsive to .length method p num.respond_to?("length") puts # Making a condition to run a method if num.respond_to?("next") p num.next end if num.respond_to?("length") p num.length end puts # Using the symbol syntax as an argument to .respond puts "hello".respond_to?("length") puts "hello".respond_to?(:length) puts 1.respond_to?("next") puts 1.respond_to?(:next) puts # Ternary operator puts 1 < 2 ? "yes, it is" : "No, it is not" puts # Ternary operator inside a method def even_or_odd(number) number.even? ? "Number is even." : "Number is odd." end puts even_or_odd(6) puts # One more <3 pokemon = "Pickachu" puts pokemon == "Charizard" ? "Fireball" : "That is cute a #{pokemon} pokemon" puts # Default parameter in a method def make_phone_call(number, international_code =966, area_code = 555) puts "Calling #{international_code}-#{area_code}-#{number}" end puts make_phone_call(1234567) puts make_phone_call(1234567, 4) puts make_phone_call(1234567, 4, 999) puts # Calling a method from another method def add(a, b) a + b end def subtract (a, b) a - b end def multiply(a, b) a * b end def calculate(a, b, operation = "add") if operation == "add" add(a, b) elsif operation == "subtract" subtract(a, b) elsif operation == "multiply" multiply(a, b) else "There was a problem" end end p calculate(25, 10, "subtract")
require 'rails_helper' RSpec.describe "Microposts", type: :request do before(:each) do user = create(:user) visit signin_path fill_in "session_email", :with => user.email fill_in "session_password", :with => user.password click_button "Sign in" end describe "creation" do describe "failure" do it "should not make a new micropost" do expect { visit root_path fill_in 'micropost_content', :with => "" click_button "Submit" expect(page).to have_http_status(200) expect(current_path).to eq microposts_path expect(page).to have_css('div','#error_explanation') }.to_not change(Micropost, :count) end end describe "success" do it "should create a new micropost" do content = "lalala" expect { visit root_path fill_in 'micropost_content', :with => content click_button "Submit" expect(page).to have_http_status(200) expect(current_path).to eq root_path expect(page).to have_selector('span.content', :text => content) }.to change(Micropost, :count).by(1) end end end end
# coding: utf-8 module HupoWidget class Engine < Rails::Engine initializer 'hupo_widget.add_widget_paths' do |app| app.config.paths.add 'app/widgets', glob: '**/*.rb' app.config.eager_load_paths += app.config.paths['app/widgets'] app.config.paths.add 'config/widgets', glob: '**/*.yml' end end end
require 'rails_helper' RSpec.describe UsersExpense, type: :model do it { expect(subject).to belong_to(:user) } it { expect(subject).to belong_to(:expense) } end
class Lichsu < ActiveRecord::Base belongs_to :cauhoi belongs_to :nguoichoi end
namespace :unit do desc "Builds the unit tests for COMPONENT on the MinGW platform" task :'mingw' do include UnitTestOperations component=Gaudi::Component.new($configuration.component,$configuration,'mingw') ut=unit_test_task(component,$configuration) Rake::Task[ut].invoke sh(ut.name) end end namespace :clean do task :all => :test_runners task :test_runners do |t| rm_rf(FileList[*$configuration.sources.pathmap("%p/**/*Runner.c")],:verbose=>false) puts "#{t.name} done!" end end
$: << File.join( File.dirname( __FILE__ ), '../lib' ) require 'rubygems' require 'rspec' require 'data_table/validators' describe Validators do before :each do class MyTest include Validators end end context "DataTable" do it 'raise an exception when not a DataTable' do t = MyTest.new lambda { t.validate_data_table( [] ) }.should raise_exception( Validators::Exceptions::UndefinedDataTable ) end it 'be valid when receiving a DataTable' do t = MyTest.new dt = DataTable.new lambda { t.validate_data_table( dt ) }.should_not raise_exception end end context "pointers" do it 'raise an exception when not a digit' do t = MyTest.new lambda { t.validate_pointer( 'asdf' ) }.should raise_exception( Validators::Exceptions::UndefinedPointer ) end it 'valid when digit(s)' do end end end
begin require 'robots' rescue LoadError end module Spider class Agent def initialize_robots unless Object.const_defined?(:Robots) raise(ArgumentError,":robots option given but unable to require 'robots' gem") end @robots = Robots.new(@user_agent) end def robot_allowed?(url) if @robots @robots.allowed?(url) else true end end end end
if(ARGV.empty?) puts "empty argument" exit end domain = ARGV.first dns_raw = File.readlines("zone.txt") $typeA = {} $typeC = {} def parse_dns(dns_raw) dns_raw.each do |raw_record| record = raw_record.split(",") if record[0] == "A" $typeA[record[1].strip.to_sym] = record[2].strip elsif record[0] == "CNAME" $typeC[record[1].strip.to_sym] = record[2].strip else puts "Wrong record type" end end dns_record = {} dns_record[:typeA] = $typeA dns_record[:typeC] = $typeC return dns_record end def resolve(dns_records, output, new_domain) if dns_records[:typeA][new_domain.to_sym] output.append(dns_records[:typeA][new_domain.to_sym]) return output elsif dns_records[:typeC][new_domain.to_sym] output.append(dns_records[:typeC][new_domain.to_sym]) resolve(dns_records, output, dns_records[:typeC][new_domain.to_sym]) else puts "#{new_domain} has no IPv4 address in the zone file" output.append("End") return output end end dns_records = parse_dns(dns_raw) puts $typeA puts $typeC output = [domain] output = resolve(dns_records, output, domain) puts output.join(" => ")
class Fine < ActiveRecord::Base belongs_to :infraction belongs_to :law end
class AddUserIdToOgre < ActiveRecord::Migration[5.2] def change add_column :ogres, :user_id, :string end end
class Hazy < Formula desc "Command line interface (CLI) to the Hazy web service." homepage "https://github.com/hazy/toolbelt" url "https://github.com/hazy/toolbelt/releases/download/v0.0.3-alpha/hazy.tar.gz" sha256 "a88cd10f9f57fe15798d8dac581b744b0aa1d9bd575df91cb47ff6835ef925e1" version "0.0.3" bottle :unneeded def install bin.install "hazy" end end
# @param {Integer[]} nums # @return {Integer} def array_pair_sum(nums) nums.sort! res = 0 nums.each_with_index do |n, index| if index % 2 == 0 res += n end end return res end p array_pair_sum([1,1])
require 'rails_helper' RSpec.describe "admin/mona_articles/index", type: :view do before(:each) do assign(:mona_articles, [ MonaArticle.create!(), MonaArticle.create!() ]) end it "renders a list of admin/mona_articles" do render end end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # # **************************************************************************** require 'System.Management.Automation' include System::Management::Automation runspace = RunspaceInvoke.new game_name = "Age of Empires III Trial" min_clock = 1400 min_ram = 64000000 game_proc_name = "age3" puts "This program will determine if your PC meets some of the minimum system requirements to play the game, #{game_name}" results = runspace.Invoke("Get-process -Name #{game_proc_name}") unless results.empty? proc_info = results.first mem_usage = proc_info.members["WS"].value/1045576 proc_id = proc_info.members["ID"].value puts "It appears as if you are currently running #{game_name}!" puts "The gmae is using #{mem_usage} megs of RAM and has a process ID of #{proc_id}" puts end video_results = runspace.Invoke("Get-WmiObject Win32_VideoController | Select-Object -First 1 | %{$_.AdapterRam}") video_ram = unless video_results.first puts "Cannot determine the amount of RAM on your video card. We'll assume there is enough.'" min_ram + 1 else video_results.first.to_s.to_i end max_clock_speed = runspace.Invoke("Get-WmiObject Win32_Processor | Select-Object -First 1 | %{$_.MaxClockSpeed}").first.to_s.to_i has_sound = false begin sound_results = runspace.Invoke("Get-WmiObject Win32_SoundDevice | Select-Object -First 1 | %{$_.Status}") has_sound = true if sound_results.first.to_s.upcase == "OK" rescue Exception has_sound = false end if min_clock > max_clock_speed puts "Your system is too slow to play '#{game_name}.'" puts "You need a CPU that operates at '#{min_clock/1000}Ghz' or higher" puts "Sorry!" exit else puts "Your CPU is fast enough(#{max_clock_speed/1000.0}Ghz)!" puts end if min_ram > video_ram puts "Your video card doesn't have enough memory to play '#{gameName}'." puts "You need a video card with at least '#{minVideoRam/1045576}MB'." exit else puts "#{video_ram/1045576}MB is enough video memory!" puts end unless has_sound puts "Unfortunately it appears as if you have no sound card." puts "Playing #{game_name} would be a much better experience with sound!" end puts "Have a nice day!"
Types::ConversationType = GraphQL::ObjectType.define do name 'Conversation' field :author do type Types::UserType resolve ->(obj, args, ctx) { obj.author } end field :receiver do type Types::UserType resolve ->(obj, args, ctx) { obj.receiver } end end
class InviteRequestPolicy < ApplicationPolicy def new? true end def create? true end def created? true end def approve? user.admin? end def save_approve? user.admin? end def decline? user.admin? end end
require "digest" module Digest class Perfect class << self def hexdigest(string_to_hash) bytes = byte_array(string_to_hash) length = bytes.length a = b = 0x9E3779B9 c = 0xE6359A60 k, len = 0, length while(len >= 12) a = m(a + bytes[k + 0] + (bytes[k + 1] << 8) + (bytes[k + 2] << 16) + (bytes[k + 3] << 24)) b = m(b + bytes[k + 4] + (bytes[k + 5] << 8) + (bytes[k + 6] << 16) + (bytes[k + 7] << 24)) c = m(c + bytes[k + 8] + (bytes[k + 9] << 8) + (bytes[k + 10] << 16) + (bytes[k + 11] << 24)) a, b, c = mix(a, b, c) k += 12 len -= 12 end c = c + length c = mix(*toss(a, b, c, bytes, len, k))[2] "6" + c.to_s end private def byte_array(string_to_hash) bytes = [] string_to_hash.each_byte {|b| bytes << b} bytes end # Need to keep numbers in the unsigned int 32 range def m(v) v % 0x100000000 end def mix(a, b, c) a, b, c = m(a), m(b), m(c) a = m(a-b-c) ^ m(c >> 13) b = m(b-c-a) ^ m(a << 8) c = m(c-a-b) ^ m(b >> 13) a = m(a-b-c) ^ m(c >> 12) b = m(b-c-a) ^ m(a << 16) c = m(c-a-b) ^ m(b >> 5) a = m(a-b-c) ^ m(c >> 3) b = m(b-c-a) ^ m(a << 10) c = m(c-a-b) ^ m(b >> 15) [a, b, c] end def toss(a, b, c, bytes, len, k) case len when 9..11 c = c + (bytes[k+len-1] << ((len % 8) * 8)) when 5..8 b = b + (bytes[k+len-1] << ((len % 5) * 8)) when 1..4 a = a + (bytes[k+len-1] << ((len - 1) * 8)) else return [a, b, c] end toss(a, b, c, bytes, len-1, k) end end end end
require 'spec_helper' describe 'CapsuleCD::Ruby::RubyEngine', :ruby do describe '#build_step' do describe 'when building an empty package' do let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, package_type: :ruby) end it 'should raise an error' do engine.instance_variable_set(:@source_git_local_path, test_directory ) expect { engine.build_step }.to raise_error(CapsuleCD::Error::BuildPackageInvalid) end end describe 'when building a simple package ' do let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, package_type: :ruby) end it 'should create a Gemfile, Rakefile, .gitignore file and spec folder' do FileUtils.copy_entry('spec/fixtures/ruby/gem_analogj_test', test_directory) FileUtils.rm(test_directory + '/Gemfile') FileUtils.rm(test_directory + '/Rakefile') engine.instance_variable_set(:@source_git_local_path, test_directory) VCR.use_cassette('gem_build_step',:tag => :ruby) do engine.build_step end expect(File.exist?(test_directory+'/.gitignore')).to eql(true) expect(File.exist?(test_directory+'/Gemfile')).to eql(true) expect(File.exist?(test_directory+'/Rakefile')).to eql(true) end it 'should raise an error if version.rb is missing' do FileUtils.copy_entry('spec/fixtures/ruby/gem_analogj_test', test_directory) FileUtils.rm(test_directory + '/lib/gem_analogj_test/version.rb') engine.instance_variable_set(:@source_git_local_path, test_directory) VCR.use_cassette('gem_build_step_without_version.rb',:tag => :ruby) do expect{engine.build_step}.to raise_error(CapsuleCD::Error::BuildPackageInvalid) end end end describe 'when building and dogfooding capsulecd package ' do let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, package_type: :ruby) end it 'should create a Gemfile, Rakefile, .gitignore file and spec folder' do FileUtils.copy_entry('spec/fixtures/ruby/capsulecd', test_directory) FileUtils.rm(test_directory + '/Gemfile') FileUtils.rm(test_directory + '/Rakefile') engine.instance_variable_set(:@source_git_local_path, test_directory) VCR.use_cassette('gem_build_step',:tag => :ruby) do engine.build_step end expect(File.exist?(test_directory+'/.gitignore')).to eql(true) expect(File.exist?(test_directory+'/Gemfile')).to eql(true) expect(File.exist?(test_directory+'/Rakefile')).to eql(true) expect(File.exist?(test_directory+'/capsulecd-1.0.2.gem')).to eql(true) end it 'should raise an error if version.rb is missing' do FileUtils.copy_entry('spec/fixtures/ruby/gem_analogj_test', test_directory) FileUtils.rm(test_directory + '/lib/gem_analogj_test/version.rb') engine.instance_variable_set(:@source_git_local_path, test_directory) VCR.use_cassette('gem_build_step_without_version.rb',:tag => :ruby) do expect{engine.build_step}.to raise_error(CapsuleCD::Error::BuildPackageInvalid) end end end end describe '#test_step' do before(:each) do FileUtils.copy_entry('spec/fixtures/ruby/gem_analogj_test', test_directory) FileUtils.cp('spec/fixtures/ruby/gem_analogj_test-0.1.4.gem', test_directory) end let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, package_type: :ruby) end let(:config_double) { CapsuleCD::Configuration.new } describe 'when testing ruby package' do it 'should run install dependencies' do allow(Open3).to receive(:popen3).and_return(false) allow(config_double).to receive(:engine_cmd_test).and_call_original allow(config_double).to receive(:engine_disable_test).and_call_original engine.instance_variable_set(:@source_git_local_path, test_directory) engine.instance_variable_set(:@config, config_double) engine.test_step end end end describe '#release_step' do let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, package_type: :ruby) end let(:config_double) { CapsuleCD::Configuration.new } describe 'when no rubygems_api_key provided' do it 'should raise an error' do engine.instance_variable_set(:@config, config_double) expect{engine.release_step}.to raise_error(CapsuleCD::Error::ReleaseCredentialsMissing) end end end describe 'integration tests' do let(:engine) do require 'capsulecd/ruby/ruby_engine' CapsuleCD::Ruby::RubyEngine.new(source: :github, runner: :default, package_type: :ruby, config_file: 'spec/fixtures/sample_ruby_configuration.yml' # config_file: 'spec/fixtures/live_ruby_configuration.yml' ) end let(:git_commit_double) { instance_double(Git::Object::Commit) } describe 'when testing ruby package' do it 'should complete successfully' do FileUtils.copy_entry('spec/fixtures/ruby/gem_analogj_test', test_directory) VCR.use_cassette('integration_ruby',:tag => :ruby) do #set defaults for stubbed classes source_git_local_path = test_directory allow(File).to receive(:exist?).and_call_original allow(File).to receive(:open).and_call_original allow(Open3).to receive(:popen3).and_call_original #stub methods in source_process_pull_request_payload allow(CapsuleCD::GitUtils).to receive(:clone).and_return(source_git_local_path) allow(CapsuleCD::GitUtils).to receive(:fetch).and_return(true) allow(CapsuleCD::GitUtils).to receive(:checkout).and_return(true) #stub methods in build_step allow(CapsuleCD::GitUtils).to receive(:create_gitignore).with(source_git_local_path, ['Ruby']).and_return(true) #stub methods in package_step allow(CapsuleCD::GitUtils).to receive(:commit).and_return(true) allow(CapsuleCD::GitUtils).to receive(:tag).with(source_git_local_path,'v0.1.4').and_return(git_commit_double) allow(git_commit_double).to receive(:sha).and_return('7d10007c0e1c6262d5a93cc2d3225c1c651fa13a') allow(git_commit_double).to receive(:name).and_return('v0.1.4') #stub methods in release_step allow(Open3).to receive(:popen3).with('gem push gem_analogj_test-0.1.4.gem',{:chdir=>source_git_local_path}).and_return(true) allow(FileUtils).to receive(:mkdir_p).with(File.expand_path('~/.gem')).and_return(true) allow(File).to receive(:open).with(File.expand_path('~/.gem/credentials'), 'w+').and_return(true) #stub methods in source_release allow(CapsuleCD::GitUtils).to receive(:push).and_return(true) allow(CapsuleCD::GitUtils).to receive(:generate_changelog).and_return('') engine.start end end end end end
class User < ActiveRecord::Base searchkick callbacks: :async enum role: [:guest, :user, :manager, :administrator] after_initialize :set_default_role, :if => :new_record? has_many :news has_many :knowledge has_many :overtime has_many :logbook has_many :holidays has_many :event has_many :post devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "64x64#" }, :default_url => "/images/:style/missing.png" validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/ def set_default_role self.role ||= :guest end def as_json(options = {}) json = {:nickname => nickname, :id => id} super.tap { |hash| hash["name"] = hash.delete "nickname" } end end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # # **************************************************************************** require '../../util/assert.rb' # "require" load any given file only once $global_var = 88 assert_true { require "module_with_global.rb" } assert_equal($global_var, 90) assert_false { require "module_with_global" } assert_equal($global_var, 90) assert_true { require "module_with_Global" } # cap "G" assert_equal($global_var, 92) assert_true { require "./module_with_global" } # ?? assert_equal($global_var, 94) # page: 124 # accept relative and absolute paths; if given a relative path (or just a plain name), # they will search every directory in the current load path ($:) for the file # todo
# frozen_string_literal: true module Sentry # TransactionEvent represents events that carry transaction data (type: "transaction"). class TransactionEvent < Event TYPE = "transaction" # @return [<Array[Span]>] attr_accessor :spans # @return [Hash] attr_accessor :measurements # @return [Float, nil] attr_reader :start_timestamp # @return [Hash, nil] attr_accessor :profile def initialize(transaction:, **options) super(**options) self.transaction = transaction.name self.transaction_info = { source: transaction.source } self.contexts.merge!(transaction.contexts) self.contexts.merge!(trace: transaction.get_trace_context) self.timestamp = transaction.timestamp self.start_timestamp = transaction.start_timestamp self.tags = transaction.tags self.dynamic_sampling_context = transaction.get_baggage.dynamic_sampling_context self.measurements = transaction.measurements finished_spans = transaction.span_recorder.spans.select { |span| span.timestamp && span != transaction } self.spans = finished_spans.map(&:to_hash) populate_profile(transaction) end # Sets the event's start_timestamp. # @param time [Time, Float] # @return [void] def start_timestamp=(time) @start_timestamp = time.is_a?(Time) ? time.to_f : time end # @return [Hash] def to_hash data = super data[:spans] = @spans.map(&:to_hash) if @spans data[:start_timestamp] = @start_timestamp data[:measurements] = @measurements data end private def populate_profile(transaction) profile_hash = transaction.profiler.to_hash return if profile_hash.empty? profile_hash.merge!( environment: environment, release: release, timestamp: Time.at(start_timestamp).iso8601, device: { architecture: Scope.os_context[:machine] }, os: { name: Scope.os_context[:name], version: Scope.os_context[:version] }, runtime: Scope.runtime_context, transaction: { id: event_id, name: transaction.name, trace_id: transaction.trace_id, # TODO-neel-profiler stubbed for now, see thread_id note in profiler.rb active_thead_id: '0' } ) self.profile = profile_hash end end end
#!/usr/bin/env ruby $LOAD_PATH << File.expand_path("../../lib", __dir__) require 'async/reactor' require 'async/io/stream' require 'async/io/host_endpoint' require 'async/io/protocol/line' class User < Async::IO::Protocol::Line end endpoint = Async::IO::Endpoint.parse(ARGV.pop || "tcp://localhost:7138") input = Async::IO::Protocol::Line.new( Async::IO::Stream.new( Async::IO::Generic.new($stdin) ) ) Async::Reactor.run do |task| socket = endpoint.connect stream = Async::IO::Stream.new(socket) user = User.new(stream) connection = task.async do while line = user.read_line puts line end end while line = input.read_line user.write_lines line end rescue EOFError # It's okay, we are disconnecting, because stdin has closed. ensure connection.stop user.close end
# source: https://fire.ca.gov/incidents/2019/ # pulled from https://fire.ca.gov/umbraco/Api/IncidentApi/GetIncidents?year=2019 require "json" require "hashie" require "active_support/all" class Fire < Hashie::Mash def initialize(hash) super( hash.dup.transform_keys { |k| k.underscore } ) end end class County attr_accessor :fires, :name def initialize(name) @name = name @fires = [] end def add_fire(fire) @fires << fire if fire.present? end def total_acres_burned fires.map { |fire| fire.acres_burned || 0 }.reduce(&:+) end end file_data = File.read("./ca-fire-data-11-4-2019.json") fire_table = JSON.parse(file_data)["Incidents"].map { |fire| Fire.new(fire) } all_counties_table = {} fire_table.each do |fire| next unless fire.counties.present? fire.counties.each do |county_name| all_counties_table[county_name] ||= County.new(county_name) all_counties_table[county_name].add_fire(fire) end end all_counties_table = all_counties_table.sort_by { |k, v| -v.total_acres_burned }.to_h core_counties_list = [ "San Bernardino", "Riverside", "Los Angeles", "San Joaquin", "San Diego", "Fresno" ] core_counties_table = all_counties_table.select { |k, v| k.in?(core_counties_list) } puts "\n\nCore County Totals:".upcase index = 1 core_counties_table.each do |_, county| puts "#{index}. #{county.name}: #{county.total_acres_burned}" index += 1 end grand_total = core_counties_table.map { |_, county| county.total_acres_burned }.reduce(&:+) puts "TOTAL ACRES BURNED: #{grand_total}" puts "\n\nAll County Totals:".upcase index = 1 all_counties_table.each do |_, county| puts "#{index}. #{county.name}: #{county.total_acres_burned}" index += 1 end grand_total = all_counties_table.map { |_, county| county.total_acres_burned }.reduce(&:+) puts "TOTAL ACRES BURNED: #{grand_total}" puts "All county list in HTML" puts "<ol>" all_counties_table.each do |_, county| puts "<li>#{county.name}: #{county.total_acres_burned}</li> " end puts "</ol>"
module PluckMap module HashPresenter def to_h(query) define_to_h! to_h(query) end private def define_to_h! ruby = <<-RUBY def to_h(query) pluck(query) do |results| results.map { |values| values = Array(values); { #{attributes.map { |attribute| "#{attribute.name.inspect} => #{attribute.to_ruby}" }.join(", ")} } } end end RUBY # puts "\e[34m#{ruby}\e[0m" # <-- helps debugging PluckMapPresenter class_eval ruby, __FILE__, __LINE__ - 7 end end end
module LittleMapper module Mappers module AR class OneToOne < Mappers::Base attr_accessor :mapper, :field, :persistent_klass, :persistent_field, :entity_setter, :persistent_entity_setter def initialize(mapper, field, opts = {}) @mapper = mapper @field = field @persistent_klass = opts[:as] @persistent_field = opts[:to] || field @entity_setter = opts[:entity_setter] || "#{field}=".to_sym @persistent_entity_setter = opts[:persistent_entity_setter] || "#{persistent_field}=".to_sym end def to_persistent(target) if persistent_klass val = source.__send__(field) if val target.__send__(persistent_entity_setter, LittleMapper[persistent_klass].to_persistent(val)) end else target.__send__(persistent_entity_setter, source.__send__(field)) end end def to_entity(target) if persistent_klass val = source.__send__(persistent_field) if val target.__send__(entity_setter, LittleMapper[persistent_klass].to_entity(val)) end else target.__send__(entity_setter, source.__send__(persistent_field)) end end end end end end
class ItemPolicy < ApplicationPolicy attr_reader :user, :item def initialize(user, item) @user = user @item = item end def update? user.admin? end def destroy? user.admin? end end
module SchemaToScaffold class Schema attr_reader :data, :tables def initialize(data) @data, @tables = data, Schema.parse(data) end def table_names tables.map(&:name) end def print_table_names table_names.each_with_index { |name, i| puts "#{i}. #{name}" } end def select_tables(input) case input when "*" table_range.to_a when /^\d/ table_range.include?(input.to_i) ? [input.to_i] : [] end end def table(id) case id when Symbol then table(id.to_s) when String then tables[table_names.index(id)] when Integer then tables[id] else nil end end def to_script tables.map(&:to_script) end def self.parse(data) data.split(/^\s*create_/)[1..-1].map {|table_data| Table.parse(table_data) }.reject{ |e| e.nil? } end private def table_range 0...table_names.count end end end
class Try def inspect "Trying to inspect me, eh!?" end def to_s "See? 'to_s' is called." end end man = Try.new # method 'p' calls instance method internally on the object passed to it. p man # 'puts' calls 'to_s' method internally. puts man
class CreateWebPlans < ActiveRecord::Migration def change create_table :web_plans do |t| t.references :project, index: true, foreign_key: true t.string :moodboard t.text :themes t.string :chosen_theme t.text :desc t.string :inspiration_links t.timestamps null: false end end end
class CreateCourses < ActiveRecord::Migration[6.0] def change create_table :courses do |t| t.string :title, null: false t.string :term, null: false t.string :units t.string :campus t.string :subject, default: 'CSE' t.string :catalog_number, null: false t.timestamps end end end
require 'pp' class TileBag def initialize(options) fill_bag(options.fetch(:tiles, [])) end def count(tile) @counts[tile] end def points(tile) @points[tile] end def can_form?(word) letters = {} word.each_char do |letter| letters[letter] = letters.fetch(letter, 0) + 1 end result = true letters.each do |key, count| result = result && @counts[key.to_sym] && @counts[key.to_sym] >= count end result end def words_available_in(dictionary) dictionary.select {|word| can_form?(word)} end private def fill_bag(tiles) @counts, @points = {}, {} tiles.each do |tile| letter, points = tile[0...1].to_sym, tile[1..-1].to_i @counts[letter] = @counts.fetch(letter, 0) + 1 @points[letter] = points end end end
require 'spec_helper' describe StylistAdmin::Assigns::BedroomsController do # fixtures :all render_views before(:all) do create_product_type_structure end before(:each) do activate_authlogic @user = Factory(:stylist_user) login_as(@user) @customer = Factory(:user) @product = Factory(:product, :product_type_id => ProductType.find_by_name('Dressers').id) end it "index action should render index template" do get :index, :user_id => @customer.id response.should render_template(:index) end it "show action should render show template" do product = Factory(:product) get :show, :id => product.id, :user_id => @customer.id response.should render_template(:show) end it "update action should render edit template when model is invalid" do product = Factory(:product) Product.any_instance.stubs(:valid?).returns(false) put :update, :id => bedroom.id, :bedroom => bedroom.attributes, :user_id => @customer.id, :bedroom_ids => [] response.should render_template(:edit) end it "update action should redirect when model is valid" do bedroom = Factory(:bedroom) Bedroom.any_instance.stubs(:valid?).returns(true) put :update, :id => bedroom.id, :bedroom => bedroom.attributes, :user_id => @customer.id, :bedroom_ids => [] response.should redirect_to(stylist_admin_assigns_user_bedroom_url(@customer, assigns[:bedroom])) end it "destroy action should destroy model and redirect to index action" do @product = Factory(:product) @bed_room.add_bedrooms([@product.id]) delete :destroy, :id => @product.id response.should redirect_to(stylist_admin_assigns_user_bedrooms_url(@customer)) @bed_room.reload @bed_room.showroom_product_ids.include?(@product.id).should be_false end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :visit do visit_nr 1 visit_date 2.years.ago league "The Championship" home_club "Charlton Athletic" away_club "Millwall" ground "The Valley" street "Floyd Road" city "London" country "United Kingdom" longitude 1.5 latitude 1.5 result "1-1" season "2012-2013" kickoff "15:00" gate 12345 association :user end end
# frozen_string_literal: true module Dry module Types # Sum type # # @api public class Sum include Composition def self.operator :| end # @return [Boolean] # # @api public def optional? primitive?(nil) end # @param [Object] input # # @return [Object] # # @api private def call_unsafe(input) left.call_safe(input) { right.call_unsafe(input) } end # @param [Object] input # # @return [Object] # # @api private def call_safe(input, &block) left.call_safe(input) { right.call_safe(input, &block) } end # @param [Object] input # # @api public def try(input) left.try(input) do right.try(input) do |failure| if block_given? yield(failure) else failure end end end end # @param [Object] value # # @return [Boolean] # # @api private def primitive?(value) left.primitive?(value) || right.primitive?(value) end # Manage metadata to the type. If the type is an optional, #meta delegates # to the right branch # # @see [Meta#meta] # # @api public def meta(data = Undefined) if Undefined.equal?(data) optional? ? right.meta : super elsif optional? self.class.new(left, right.meta(data), **options) else super end end # @param [Hash] options # # @return [Constrained,Sum] # # @see Builder#constrained # # @api public def constrained(options) if optional? right.constrained(options).optional else super end end end end end
require "rails_helper" RSpec.describe InvestigationinjurylocationsController, type: :routing do describe "routing" do it "routes to #index" do expect(get: "/investigationinjurylocations").to route_to("investigationinjurylocations#index") end it "routes to #new" do expect(get: "/investigationinjurylocations/new").to route_to("investigationinjurylocations#new") end it "routes to #show" do expect(get: "/investigationinjurylocations/1").to route_to("investigationinjurylocations#show", id: "1") end it "routes to #edit" do expect(get: "/investigationinjurylocations/1/edit").to route_to("investigationinjurylocations#edit", id: "1") end it "routes to #create" do expect(post: "/investigationinjurylocations").to route_to("investigationinjurylocations#create") end it "routes to #update via PUT" do expect(put: "/investigationinjurylocations/1").to route_to("investigationinjurylocations#update", id: "1") end it "routes to #update via PATCH" do expect(patch: "/investigationinjurylocations/1").to route_to("investigationinjurylocations#update", id: "1") end it "routes to #destroy" do expect(delete: "/investigationinjurylocations/1").to route_to("investigationinjurylocations#destroy", id: "1") end end end
require 'em-synchrony' require 'em-synchrony/mysql2' require 'em-synchrony/fiber_iterator' require 'amqp' require 'fiber' require 'yaml' require 'logging' require 'digest' require_relative 'SearchWorker' require_relative File.expand_path(File.join(File.dirname(__FILE__), '../app/models/Product')) require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/async/NonBlockingDB')) require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/async/StorageItem')) require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/async/StoragePrice')) require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/async/StorageComparison')) require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/async/ShopItem')) require_relative 'Webserver' module Mapper class Base attr_reader :search_worker, :config def initialize raise StandardError, "Mapper env is not defined!" if ENV['MAPPER_ENV'].nil? @options = {:env => ENV['MAPPER_ENV']} @working_dir = File.dirname(__FILE__) p "working dir #{@working_dir}" config_dir = File.expand_path(File.join(File.dirname(__FILE__), '../config')) config, dictionary = "#{config_dir}/config.yaml", "#{config_dir}/dictionary.yaml" begin @config = YAML.load_file(config)[@options[:env]] @dictionary = YAML.load_file(dictionary) rescue Errno::ENOENT => e p e.message end Thread.abort_on_exception=true @output ||= STDOUT set_logger define_workers end public #runs reactor and starts amqp broker for receveing messages def run @output.print "Run, Forest, run!" EM.synchrony do print "Mapper has been started #{Time.now}" AMQP.start do |connection| print "AMQP started #{Time.now}" channel = AMQP::Channel.new connection queue = channel.queue(@config["broker"]["queue-name"], :auto_delete => true) queue.subscribe do |payload| print "Received message #{payload}" connection.close {EM.stop} if payload == "stop" Fiber.new{start}.resume if payload == "start" Fiber.new {match}.resume if payload == 'match' EM.defer {start_webserver} if payload == 'start_webserver' EM.defer {start_search_server} if payload == 'start_solr' EM.defer {stop_search_server} if payload == 'stop_solr' EM.defer {add_db_to_search_index} if payload == 'index' EM.defer {setup_storage} if payload == 'setup_storage' end end end end # parse price-lists def start Fiber.new{PriceManager.new.load_prices}.resume end # web-interface for price managment on localhost:4567 def start_webserver stop_webserver Webserver.run! end def stop_webserver system "fuser -k 4567/tcp" end def setup_storage StorageBase.setup end def add_db_to_search_index @search_worker.index end def stop_search_server system "fuser -k 8983/tcp" end def start_search_server begin return false if @search_worker.server_running? stop_search_server FileUtils.cd '../solr/' do command = ["java"] command << "-jar" command << "start.jar" pid = spawn(*command,:in=>'/dev/null',:err => :out) p "Solr is running on #{pid}" return true end rescue => e p e end end # match products from parsed price-lists and products from online shop def match EM::Synchrony::FiberIterator.new(@storage_item.all, @config["concurrency"]["iterator-size"].to_i).each do |product, iter| link(product) end end def print message @logger.debug message @output.print message end def set_logger logger = Logging.logger[self.class.name] filename = File.expand_path(File.join(File.dirname(__FILE__),"../log/#{@options[:env]}.log")) logger.add_appenders( Logging.appenders.stdout, Logging.appenders.file(filename) ) logger.level = :debug @logger = logger end def set_output output; @output = output; end private def define_workers @price = StoragePrice.new "storage" @shop_item = ShopItem.new "shop" @storage_item = StorageItem.new "storage" @storage_comparison = StorageComparison.new "storage" @search_worker = SearchWorker.new @config["search"], @dictionary["search"] # <= пошук end def link(product) begin (product["code"].empty?) ? storage_item_model = product["article"] : storage_item_model = product["code"] response = @search_worker.find({:title => product["title"],:model => storage_item_model}) if response[:count] > 0 shop_item = response.docs[0] # <= беремо тільки перший знайдений товар shop_product_id = shop_item["id"].to_i price_product_id = product["id"] p shop_item linked = check_models(shop_item["model"][0], storage_item_model) || check_titles(shop_item["title"][0], product["title"]) p "Linked: #{linked}" @storage_comparison.link(price_product_id, shop_product_id, linked).errback {|error|p error} else p "Product: #{product["title"]} has no results :((" end rescue => e p e end end #TODO: добавити порівняння Назва товару арт. [артикул] з моделлю def check_titles(shop_item_title, storage_item_title) shop_item_title.downcase! storage_item_title.downcase! if (shop_item_title.size == storage_item_title.size) shop_item_title == storage_item_title elsif shop_item_title.size > storage_item_title.size shop_item_title.include? storage_item_title else storage_item_title.include? shop_item_title end end # compare two models from storage and shop databases def check_models(shop_item_model, storage_item_model) return false if (shop_item_model.nil? || shop_item_model.empty? || shop_item_model == "NULL") || (storage_item_model.empty? || storage_item_model.nil? || storage_item_model == "NULL") p "#{shop_item_model} - #{storage_item_model}" begin shop_item_model["-"] = "" if shop_item_model.index "-" storage_item_model["-"] = "" if storage_item_model.index "-" rescue => e p e end shop_item_model.downcase == storage_item_model.downcase end def update_settings(new_data, config) raise ArgumentError, "new_data must be a hash!" unless new_data.kind_of? Hash raise StandardError, "Yaml file with settings is not defined!" unless config.is_a? String begin settings = YAML.load_file(config) File.open(config, "w"){|f|f.write settings.merge(new_data).to_yaml} rescue => e p e end end end end require_relative 'PriceManager' require_relative 'PriceReader'
module Mutations class Parse < Mutations::BaseMutation argument :cdl, String, required: true field :response, GraphQL::Types::JSON, null: true def resolve(cdl:) { response: (ParserEval.run!(cdl, :Ns) rescue nil) } end end end
class CreateTables < ActiveRecord::Migration def change create_table :tables do |t| t.string :position t.string :team t.string :played t.string :won t.string :drawn t.string :lost t.string :goalfor t.string :goalagainst t.string :goaldifference t.string :points t.timestamps end end end
# == Schema Information # # Table name: profiles # # id :bigint not null, primary key # role :string # profile_type :string # first_name :string # last_name :string # civility :string # address :string # phone :string # country_id :bigint # locality_id :bigint # description :text # speciality :string # views :bigint default(0) # status :string # user_id :bigint # created_at :datetime not null # updated_at :datetime not null # class ProfileSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :id, :profile_type, :first_name, :last_name, :civility, :address, :phone, :country_id , :locality_id, :description, :speciality, :views, :status, :user_id#, :avatar_url belongs_to :user belongs_to :country belongs_to :locality def avatar_url rails_blob_url(object.avatar) if object.avatar.attachment end end
module SyntheticHelper include CradleModule def show_internal_structure(option) option[:section_indexes] = "" if option[:section_indexes].blank? html_string = "" option[:structure].each_with_index{|section,index| next if index == 0 if is_string(section) == true if section =~ /^\d+$/ and (verify_domain(option[:info][:domain])['Synthetic'].constantize.exists?(:sth_ref_id=>section.to_i) or verify_domain(option[:info][:domain])['Lexeme'].constantize.find(section.to_i).tagging_state_item.tree_string == 'DUMMY') html_string << "<td style='background:#F0F8FF;padding:5px 10px 5px 10px;color:#047;font-weight:bold;text-align:center;font-size:120%;'>\n" html_string << verify_domain(option[:info][:domain])['Lexeme'].constantize.find(section).surface+"\n" html_string << "</td>\n" elsif section =~ /^dummy_(.*)$/ html_string << "<td style='background:#F0F8FF;padding:5px 10px 5px 10px;color:#047;font-weight:bold;text-align:center;font-size:120%;'>\n" html_string << $1+"\n" html_string << "</td>\n" else if (section =~ /^meta_(.*)$/) or (section =~ /^initial_(.*)$/) temp = $1.scan(/./) elsif section =~ /^update_(.*)$/ temp = verify_domain(option[:info][:domain])['Lexeme'].constantize.find($1.to_i).surface.scan(/./) else temp = verify_domain(option[:info][:domain])['Lexeme'].constantize.find(section.to_i).surface.scan(/./) end split_action = {:type=>"new", :point=>option[:section_indexes]+'['+index.to_s+']'} for inner_index in 0..temp.size-1 html_string << "<td style='background:#F0F8FF;padding:5px 10px 5px 10px;color:#047;font-weight:bold;text-align:center;font-size:120%;'>\n" html_string << temp[inner_index]+"\n" html_string << "</td>\n" unless inner_index == temp.size-1 html_string << "<td style='text-align:center;'>\n" left = temp[0..inner_index].join('') right = temp[inner_index+1..-1].join('') if option[:first_time]==true html_string << link_to_remote(image_tag("internal.jpg", :border=>0), :url=>{:action=>"split_word", :left=>left, :right=>right, :split_action=>split_action.update(:divide_type=>"horizontal"), :info=>option[:info], :structure=>option[:original_struct]}) elsif option[:first_time]==false html_string << link_to_remote(image_tag("internal-horizontal.jpg", :border=>0), :url=>{:action=>"split_word", :left=>left, :right=>right, :split_action=>split_action.update(:divide_type=>"horizontal"), :info=>option[:info], :structure=>option[:original_struct]}) html_string << '<br/>' html_string << link_to_remote(image_tag("internal-vertical.jpg", :border=>0), :url=>{:action=>"split_word", :left=>left, :right=>right, :split_action=>split_action.update(:divide_type=>"vertical"), :info=>option[:info], :structure=>option[:original_struct]}) end html_string << "</td>\n" end end end else html_string << show_internal_structure(:structure=>section, :first_time=>false, :info=>option[:info], :original_struct=>option[:original_struct], :section_indexes=>option[:section_indexes]+'['+index.to_s+']') end unless index == option[:structure].size-1 html_string << "<td style='text-align:center;vertical-align: middle;'>\n" left = get_chars_from_structure(section, option[:info][:domain]) right = get_chars_from_structure(option[:structure][index+1], option[:info][:domain]) option[:structure].size > 3 ? divide_type = "horizontal" : divide_type = "vertical" html_string << link_to_remote(image_tag("internal-plus.jpg", :border=>0, :style=>"vertical-align: middle;"), :url=>{:action=>"split_word", :structure=>option[:original_struct], :left=>left, :right=>right, :info=>option[:info], :split_action=>{:type=>"modify", :divide_type=>divide_type, :left_hand_index=>(option[:section_indexes]+'['+index.to_s+']'), :right_hand_index=>(option[:section_indexes]+'['+(index+1).to_s+']')}}) html_string << struct_level[option[:section_indexes].blank? ? 1 : option[:section_indexes].count('[')+1]+"\n" if divide_type == "horizontal" if index == option[:structure].size-2 right = left+right left = get_chars_from_structure(option[:structure][index-1], option[:info][:domain]) left_hand_index = option[:section_indexes]+'['+(index-1).to_s+']' right_hand_index = option[:section_indexes]+'['+index.to_s+'..-1]' else left = left+right right = get_chars_from_structure(option[:structure][index+2], option[:info][:domain]) left_hand_index = option[:section_indexes]+'['+index.to_s+'..'+(index+1).to_s+']' right_hand_index = option[:section_indexes]+'['+(index+2).to_s+']' end split_action = {:type=>"delete", :divide_type=>divide_type, :left_hand_index=>left_hand_index, :right_hand_index=>right_hand_index} html_string << link_to_remote(image_tag("internal-minus.jpg", :border=>0, :style=>"vertical-align: middle;"), :url=>{:action=>"split_word", :structure=>option[:original_struct], :info=>option[:info], :split_action=>split_action, :left=>left, :right=>right}) elsif divide_type == "vertical" html_string << link_to_remote(image_tag("internal-minus.jpg", :border=>0, :style=>"vertical-align: middle;"), :url=>{:action=>"define_internal_structure", :structure=>option[:original_struct], :info=>option[:info], :split_action=>{:type=>"delete", :divide_type=>divide_type, :point=>option[:section_indexes]}}) end html_string << "</td>\n" end } return html_string end private def get_chars_from_structure(section, domain) char_string = "" if is_string(section) == true if section =~ /^\d+$/ char_string << verify_domain(domain)['Lexeme'].constantize.find(section.to_i).surface elsif (section =~ /^dummy_(.*)$/) or (section =~ /^meta_(.*)$/) char_string << $1 elsif section =~ /^update_(.*)$/ char_string << verify_domain(domain)['Lexeme'].constantize.find($1.to_i).surface end else section[1..-1].each{|item| char_string << get_chars_from_structure(item, domain)} end return char_string end end
module Effects class External < Effect class ExternalEffectFailed < StandardError; end class InvalidConfiguration < StandardError; end def perform(workflow_id, subject_id) raise InvalidConfiguration unless valid? reductions = SubjectReduction.where( workflow_id: workflow_id, subject_id: subject_id, reducer_key: reducer_key ) if reductions.length != 1 raise ExternalEffectFailed, "Incorrect number of reductions found" end begin response = RestClient.post(url, reductions.first.prepare.to_json, {content_type: :json, accept: :json}) rescue RestClient::InternalServerError raise ExternalEffectFailed end end def valid? reducer_key.present? && url.present? && valid_url? end def self.config_fields [:url, :reducer_key].freeze end def url config[:url] end def reducer_key config[:reducer_key] end def valid_url? if url.present? begin uri = URI.parse(url) uri && uri.host && uri.kind_of?(URI::HTTPS) rescue URI::InvalidURIError false end else false end end end end
require 'spec_helper' describe MarkdownMediaSplitter do subject { described_class } it "splits the content on the split tag " do ms = subject.new(one_media_tag) expect(ms.top_text).to eq(split_top_text) expect(ms.bottom_text).to eq(split_bottom_text) end it "puts all the content in the bottom if the split tag is not found" do ms = subject.new(no_media_tag) expect(ms.top_text).to eq("") expect(ms.bottom_text).to eq(no_media_tag) end it "splits on the first split tag" do ms = subject.new(multiple_media_tags) expect(ms.top_text).to eq(split_top_text) expect(ms.bottom_text).to eq(split_bottom_text) end it "removes any additional split tags from the bottom" do ms = subject.new(multiple_media_tags) expect(ms.bottom_text[subject::SPLIT_TAG]).to be_nil end let(:one_media_tag) { " An h1 header ============ Paragraphs are separated by a blank line. 2nd paragraph. *Italic*, **bold**, `monospace`. Itemized lists look like: * this one * that one * the other one <!!media-bar!!> Note that --- not considering the asterisk --- the actual text content starts at 4-columns in. > Block quotes are > written like so. > > They can span multiple paragraphs, > if you like. Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex. \"it's all in chapters 12--14\"). Three dots ... will be converted to an ellipsis. " } let(:no_media_tag) { " An h1 header ============ Paragraphs are separated by a blank line. 2nd paragraph. *Italic*, **bold**, `monospace`. Itemized lists look like: * this one * that one * the other one Note that --- not considering the asterisk --- the actual text content starts at 4-columns in. > Block quotes are > written like so. > > They can span multiple paragraphs, > if you like. Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex. \"it's all in chapters 12--14\"). Three dots ... will be converted to an ellipsis. " } let(:multiple_media_tags) { " An h1 header ============ Paragraphs are separated by a blank line. 2nd paragraph. *Italic*, **bold**, `monospace`. Itemized lists look like: * this one * that one * the other one <!!media-bar!!> Note that --- not considering the asterisk --- the actual text content starts at 4-columns in. > Block quotes are > written like so. > > They can span multiple paragraphs, > if you like.<!!media-bar!!> Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex. \"it's all in chapters 12--14\"). Three dots ... will be converted to an ellipsis. " } let(:split_top_text) { " An h1 header ============ Paragraphs are separated by a blank line. 2nd paragraph. *Italic*, **bold**, `monospace`. Itemized lists look like: * this one * that one * the other one " } let(:split_bottom_text) { " Note that --- not considering the asterisk --- the actual text content starts at 4-columns in. > Block quotes are > written like so. > > They can span multiple paragraphs, > if you like. Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex. \"it's all in chapters 12--14\"). Three dots ... will be converted to an ellipsis. " } end
class AddScaleToPress < ActiveRecord::Migration def self.up add_column :press, :scale, :string end def self.down remove_column :press, :scale end end
require "spec_helper" describe "/api/v1/features", :type => :api do let(:market) { Factory(:market, :name => "Atlanta") } before do @user = create_user! @user.update_attribute(:admin, true) @user.permissions.create!(:action => "view", :thing => market) @feature = Factory(:feature) end let(:token) { @user.authentication_token } context "index" do before do 5.times do Factory(:feature, :market => market, :user => @user) end end let(:url) { "/api/v1/markets/#{market.id}/features" } it "XML" do get "#{url}.xml", :token => token last_response.body.should eql(market.features.to_xml) end it "JSON" do get "#{url}.json", :token => token last_response.body.should eql(market.features.to_json) end end context "create" do let(:url) { "/api/v1/markets/#{market.id}/features" } #curl -v -H "Content-Type: application/xml; charset=utf-8" --data-ascii @new.xml http://localhost:3000/api/v1/markets/9/features?token=qqMJpyFbnqXVyPRLCwrv it "successful JSON" do post "#{url}.json", :token => token, :feature => { :title => "New Feature Article", :content => "This is the article" } feature = Feature.find_by_title("New Feature Article") route = "/api/v1/markets/#{feature.id}" last_response.status.should eql(201) last_response.headers["Location"].should eql(route) last_response.body.should eql(feature.to_json) post "#{url}.json", :token => token, :feature => { :title => "Boston", :content => "This is the article" } feature = Feature.find_by_title("Boston") puts last_response.headers["Location"] #route = "/api/v1/markets/#{feature.id}" #puts last_response.headers["Location"] #last_response.status.should eql(201) #last_response.headers["Location"].should eql(route) #last_response.body.should eql(feature.to_json) end end context "update" do let(:url) { "/api/v1/markets/#{market.id}/features/#{@feature.id}" } it "successful JSON via api" do @feature.title.should eql("A feature") put "#{url}.json", :token => token, :feature => { :title => "New Feature Article", :content => "This is the article" } puts last_response.status last_response.status.should eql(200) @feature.reload # @feature.title.should eql("New Feature Article") last_response.body.should eql("{}") end end end
Rails.application.routes.draw do root to: 'users#welcome' devise_for :users get '/proposals', to: "proposals#index", as: "after_sign_out_path_for" get '/users/proposals', to: "users#proposals", as: "users_proposals" get '/proposals/:proposal_id/amendments/:id/accept', to: "amendments#accept", as: "accept_amendment" resources :proposals do resources :comments, only: [:new, :create, :destroy] resources :amendments do resources :comments, only: [:new, :create, :destroy] end end end
class ApplicationController < ActionController::Base protect_from_forgery def current_user if session[:user_id] # ||= assigns only if not already assigned (only calling db if necessary) @current_user ||= User.find(session[:user_id]) end @current_user end def logged_in? # !! Ruby trick - double-negate current_user existence and return the boolean !!current_user end def require_user redirect_to root_path unless logged_in? end def require_no_user #allows for pages to be viewed without logging in end def email_or_username?(content) # The first element in the array is the username, the 2nd element is the title of the link # All other elements will be ignored. if content =~ /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]+\z/i return "email" else return "username" end end def does_username_exist?(username) @user = User.find_by_username(username) if @user return true else return false end end def does_email_exist?(email) logger.info(email) @user = User.find_by_email(email) if @user return true else return false end end helper_method :current_user, :logged_in?, :require_user, :does_email_exist?, :does_username_exist? end
class Hangman attr_accessor :name,:guessed,:correct_blank,:counter def initialize(password_name) @name = password_name.upcase @guessed = [] @counter = 7 @correct_blank = blank end def make_move(letter) if correct_letter?(letter) correct_index(letter) else @counter -=1 end end def charcount name.length end def blank Array.new(charcount,"_") end def correct_letter?(letter) name.include?(letter) end def update_guessed(letter) guessed.push(letter) end def verify_guessed(letter) guessed.include?(letter) end def correct_index(guessedletter) password=name.split("") password.each_with_index do |letter,index_position| if letter == guessedletter correct_blank[index_position] = guessedletter end end end def available_guess(choice) if guessed.count(choice) == 0 true else false end end def loser counter == 0 end def winner if correct_blank.include?("_") false else true end end end
require 'singleton' class Question include Singleton include Enumerable attr_accessor :answer, :question def initialize @statement = [ { q: [ '3 5 R', '790319030', '091076399', '143245946', '590051196', '398226115', '442567154', '112705290', '716433235', '221041645', ], a: '8226', }, { q: [ '5 7 D', '271573743', '915078603', '102553534', '996473623', '595593497', '573572507', '340348994', '253066837', '643845096', ], a: '4646', }, { q: [ '2 2 LU', '729142134', '509607882', '640003027', '215270061', '214055727', '745319402', '777708131', '018697986', '277156993', ], a: '0700' }, { q: [ '8 9 LU', '206932999', '471100777', '973172688', '108989704', '246954192', '399039569', '944715218', '003664867', '219006823', ], a: '2853', }, { q: [ '8 7 RD', '985877833', '469488482', '218647263', '856777094', '012249580', '845463670', '919136580', '011130808', '874387671', ], a: '8878', }, { q: [ '1 1 R', '729142134', '509607882', '640003027', '215270061', '214055727', '745319402', '777708131', '018697986', '277156993', ], a: '7291' }, ] end def each(&block) until @statement.empty? build_question self.instance_exec(@answer, &block) end end def gets build_question unless @question && @answer @question.shift end def build_question @question, @answer = @statement.shift.values_at(:q, :a) answer end module STDIN def self.gets Question.instance.gets end end $stdin = STDIN end class Solver # R: [row, col], GAID = { R: [0, 1], L: [0, -1], U: [-1, 0], D: [1, 0], RU: [-1, 1], RD: [1, 1], LU: [-1, -1], LD: [1, -1], }.freeze def initialize col, row, @w = gets.chomp.split(' ') @course = GAID[@w.to_sym].dup @current_index = [row.to_i - 1, col.to_i - 1] @map = 9.times.map { gets.chomp.split('').map(&:to_i) } end def solve indexes = [@current_index] indexes += 3.times.map { ahead } indexes.map { |v| @map[v[0]][v[1]] }.join end private def ahead # i == 0 #=> row # i == 1 #=> col @current_index = @course.dup.map.with_index do |v, i| next_index = v + @current_index[i] if next_index < 0 next_index += 2 @course[i] *= -1 elsif next_index > 8 next_index -= 2 @course[i] *= -1 end next_index end @current_index end end if Object.const_defined?(:Question) Question.instance.each do |expected| res = Solver.new.solve puts "#{res}:#{expected}" puts res == expected end else puts Solver.new.solve end
require 'net/http' namespace :crawler do desc "Do all currently opened tasks from crawlers" task :crawl => :environment do # while CrawlerLog.count(:conditions => ['status = ? or status = ?', :pull, :push]) > 0 Crawler.pull :sleep => 10, :limit => 5 Crawler.push :sleep => 10, :limit => 5 # end end desc "Loads default configs from config/crawlers/*.yml to database" task :load_config => :environment do Dir.glob("#{Rails.root}/config/crawlers/*.yml").each do |file| config = YAML.load(File.open(file)) crawler = Crawler.find_by_name(config['name'].strip) || Crawler.new(config) crawler.attributes = config unless crawler.new_record? crawler.save end end # /static/archivos/14557 | #| /static/archivos/14264 desc "Loads images to local store" task :fetch_images => :environment do while !(events = Event.find(:all, :conditions => ["image_url not like ?", "/th%"], :limit => 10)).blank? events.each do |event| uri = URI.parse(event.image_url) Net::HTTP.start(uri.host) do |http| resp = http.get(uri.path) content_type = resp['content-type'] image_type = content_type.split('/')[1] unless content_type.blank? puts image_type new_url = "/thumbnails/event_#{event.id}.#{image_type || 'jpeg'}" open("#{Rails.root}/public#{new_url}", 'wb' ) do |file| file.write(resp.body) end event.update_attribute('image_url', new_url) end sleep(10) end end end end
module Yaks class Format # Hypertext Application Language (http://stateless.co/hal_specification.html) # # A lightweight JSON Hypermedia message format. # # Options: +:plural_links+ In HAL, a single rel can correspond to # a single link, or to a list of links. Which rels are singular # and which are plural is application-dependant. Yaks assumes all # links are singular. If your resource might contain multiple # links for the same rel, then configure that rel to be plural. In # that case it will always be rendered as a collection, even when # the resource only contains a single link. # # @example # # yaks = Yaks.new do # format_options :hal, {plural_links: [:related_content]} # end # class Hal < self register :hal, :json, 'application/hal+json' def transitive? true end def inverse Yaks::Reader::Hal.new end protected # @param [Yaks::Resource] resource # @return [Hash] def serialize_resource(resource) # The HAL spec doesn't say explicitly how to deal missing values, # looking at client behavior (Hyperagent) it seems safer to return an empty # resource. # result = resource.attributes if resource.links.any? result = result.merge(_links: serialize_links(resource.links)) end if resource.collection? result = result.merge(_embedded: serialize_embedded([resource])) elsif resource.subresources.any? result = result.merge(_embedded: serialize_embedded(resource.subresources)) end result end # @param [Array] links # @return [Hash] def serialize_links(links) links.reduce({}, &method(:serialize_link)) end # @param [Hash] memo # @param [Yaks::Resource::Link] # @return [Hash] def serialize_link(memo, link) hal_link = {href: link.uri} hal_link.merge!(link.options) memo[link.rel] = if singular?(link.rel) hal_link else (memo[link.rel] || []) + [hal_link] end memo end # @param [String] rel # @return [Boolean] def singular?(rel) !options.fetch(:plural_links) { [] }.include?(rel) end # @param [Array] subresources # @return [Hash] def serialize_embedded(subresources) subresources.each_with_object({}) do |sub, memo| memo[sub.rels.first] = if sub.collection? sub.map(&method(:serialize_resource)) elsif sub.null_resource? nil else serialize_resource(sub) end end end end end end
require 'rubygems' require 'ngrams' class PasswordGenerator def initialize(file = Ngram::Dictionary::DEFAULT_STORE) @dictionary = Ngram::Dictionary.load(file) end def generate_password(length) @dictionary.word(length) end end
class Group < ActiveRecord::Base has_many :matches has_many :teams belongs_to :competition end
require File.dirname(__FILE__) + '/spec_helper' describe "pattern_match" do def o(&block) Class.new(&block).new end def not_pattern_match raise_error(/No pattern matching/) end it "should call the method when pattern is matched" do o { pattern_match(:foo, Integer) { :integer } }. foo(123).should == :integer end it "should raise an error when the pattern doesn't match" do lambda { o { pattern_match(:foo, Integer) { :integer } }. foo("uh", "oh") }. should raise_error(/No pattern matching "uh", "oh"/) end it "should handle multiple patterns" do o { pattern_match(:foo, Numeric, /asdf/) { :matched } }. foo(123, "FOOasdfBAR").should == :matched end it "should raise a nice error when not matched & no args given" do lambda { o { pattern_match(:foo, Integer) { :integer } }. foo }. should not_pattern_match end it "should match no args" do object = o { pattern_match(:foo) { :matched } } object.foo.should == :matched lambda { object.foo(123) }.should not_pattern_match end it "should match literals" do o { pattern_match(:foo, "asdf") { :matched } }. foo("asdf").should == :matched lambda { o { pattern_match(:foo, "asdf") { :matched } }.foo }. should not_pattern_match end it "should match superclasses" do o { pattern_match(:foo, Numeric) { :matched} }. foo(123.45).should == :matched end it "should handle blocks" do o { pattern_match(:foo, Integer) { block.call } }. foo(123) { :hello! }.should == :hello! end it "should know about block_given?" do o { pattern_match(:foo, Integer) { block_given? } }. foo(123).should be_false o { pattern_match(:foo, Integer) { block_given? } }. foo(123) { :hello }.should be_true end end
module Kindergarten # A very easy governess, lets everything happen unguarded. Perhaps not such # a good idea to be using this... # class EasyGoverness < HeadGoverness def initialize(child) super @unguarded = true end end end
def multiplication_table (number, heading = false, decorate = false) column_width(number) heading(heading) decorate(decorate) table(number) decorate(decorate) end private def column_width(number) @col_width = (number * number).to_s.length if number == 0 || number == 1 @decoration_width = 3 else @decoration_width = number.to_s.length + ((number - 1) * @col_width) + number + 1 end end def decorate(boolean) @table << '=' * @decoration_width + "\n" if boolean end def table(num) if num == 0 || num == 1 @table << " #{num} \n" else for i in 1..num @table << " %#{num.to_s.length}d " %i (i+i).step(i * num, i) { |i| @table << "%#{@col_width}d " %i } @table << "\n" end end end def heading(heading) @table = '' if heading @table << ' ' * ((@decoration_width / 2) - heading.length / 2) if @decoration_width > heading.length @table << heading + "\n" end end if __FILE__ == $PROGRAM_NAME [ [5, 'abc', true], [10, 'Multiplication tables upto 10', true], [1, 'one', true], [0, 'zero', true] ].each do |parameters| puts multiplication_table(*parameters) end end
require 'active_record' require 'active_support/concern' module ActsAsSuggestable extend ActiveSupport::Concern included do extend ClassMethods end module ClassMethods def is_suggestee send :include, SuggesteeMethods end def is_suggestor send :include, SuggestorMethods end def is_suggestable send :include, SuggestedMethods end end module SuggestorMethods def can_suggest? true end def suggest(suggestable, user) msg = <<-EOS That model is not suggestable, please include ActsAsSuggestable and call is_suggestable in the model EOS raise Exception.new(msg) unless suggestable.respond_to?(:is_suggestable?) Suggestable.create( :suggested_by => self, :suggestion => suggestable, :user => user ) end end module SuggesteeMethods def can_be_suggested_to? true end def has_suggestion?(model) Suggestable.by_user_id(self.id).by_type(model).any? end end module SuggestedMethods def is_suggestable? true end end end ActiveRecord::Base.send :include, ActsAsSuggestable
class InstantBookingProfilesController < ApplicationController layout 'application-admin' before_filter :profile_owner, :only => [:edit, :update] def edit @instant_booking_profile = InstantBookingProfile.find_by_id(params[:id]) render 'edit' end def update @instant_booking_profile = InstantBookingProfile.find(params[:id]) respond_to do |format| if @instant_booking_profile.update_attributes(params[:instant_booking_profile]) format.html { redirect_to edit_instant_booking_profile_path(@instant_booking_profile), notice: 'Your profile was successfully updated!' } format.json { head :no_content } else flash.now[:error] = "Please review the errors below" format.html { render action: "edit" } format.json { render json: @instant_booking_profile.errors, status: :unprocessable_entity } end end end def embedded_assets @instant_booking_profile = InstantBookingProfile.find_by_id(params[:id]) respond_to do |format| format.css { render 'embedded_assets' } end end protected def profile_owner if current_user.blank? || current_user != InstantBookingProfile.find_by_id(params[:id]).user redirect_to user_root_path, notice: "Please sign in" end end end
class User < ApplicationRecord devise :invitable, :database_authenticatable, :lockable, :recoverable, :rememberable, :trackable, :secure_validatable, :password_expirable, :password_archivable, :invite_for => 1.week attr_reader :raw_invitation_token enum role: [:volunteer, :accompaniment_leader, :admin] enum volunteer_type: [:english_speaking, :spanish_interpreter, :lawyer] validates :first_name, :last_name, :email, :phone, :volunteer_type, :presence => true validates :email, uniqueness: true validates_inclusion_of :pledge_signed, :in => [true] has_many :user_friend_associations, dependent: :destroy has_many :friends, through: :user_friend_associations has_many :user_application_draft_associations, dependent: :destroy has_many :application_drafts, through: :user_application_draft_associations has_many :accompaniments, dependent: :destroy has_many :user_event_attendances, dependent: :destroy has_many :accompaniment_reports, dependent: :destroy def confirmed? self.invitation_accepted_at.present? end def name "#{first_name} #{last_name}" end def attending?(activity) activity.users.include?(self) end def accompaniment_report_for(activity) self.accompaniment_reports.where(activity_id: activity.id).first end def generate_new_invitation User.invite!(email: self.email, skip_invitation: true) token = self.raw_invitation_token domain = ENV['MAILER_DOMAIN'] "http://#{domain}/users/invitation/accept?invitation_token=#{token}" end end
require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "pokename" gem.summary = "Choose a random Pokémon name to name your project" gem.description = "This gem choose one from the 151 Pokémons names (Yeah, just the first generation) to be used in your projects." gem.email = "lucascrsaldanha@gmail" gem.homepage = "https://github.com/lucassaldanha/pokename" gem.authors = ["Lucas Saldanha"] gem.executables = ["pokename"] gem.license = "MIT" gem.add_dependency 'slop', '4.2.0' end Jeweler::GemcutterTasks.new rescue LoadError puts "pokename is not available. Install it with: gem install pokename" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end begin require 'rcov/rcovtask' Rcov::RcovTask.new do |test| test.libs << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end rescue LoadError task :rcov do abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" end end task :test => :check_dependencies task :default => :test require 'rdoc/task' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "pokename #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
class OrderItem < ApplicationRecord belongs_to :dish belongs_to :order belongs_to :user belongs_to :day before_save :set_total def total if persisted? self[:total] else dish.price end end private def set_total self[:total] = total end end
module BEL module Format Format = BEL::Extension::Format FormatError = BEL::Extension::Format::FormatError def self.evidence(input, input_format) prepared_input = process_input(input) in_formatter = BEL::Extension::Format.formatters(input_format) or raise FormatError.new(input_format) EvidenceIterable.new(prepared_input, in_formatter) end def self.translate(input, input_format, output_format, writer = nil) prepared_input = process_input(input) in_formatter = BEL::Extension::Format.formatters(input_format) or raise FormatError.new(input_format) out_formatter = BEL::Extension::Format.formatters(output_format) or raise FormatError.new(output_format) objects = in_formatter.deserialize(prepared_input) output = out_formatter.serialize(objects, writer) end def self.process_input(input) if input.respond_to? :read input elsif File.exist?(input) File.open(input, :ext_enc => Encoding::UTF_8) elsif input.respond_to? :to_s input.to_s end end private_class_method :process_input class EvidenceIterable include Enumerable def initialize(input, format) @input = input @format = format end def each if block_given? @format.deserialize(@input).each do |evidence| yield evidence end else to_enum(:each) end end end end end
require 'bcrypt' class User attr_reader :password attr_accessor :password_confirmation include DataMapper::Resource # when we 'include' and call DataMapper as a class, # Resource is the module in that class # include takes all the methods in the Resource module # and makes them class methods inside the User class property :id, Serial property :email, String, :unique => true#, :message => "This email is already registered" # error msg commented out as rack-flash has built in msg for email duplication, (it seems!!??) # this stores both p/w and Salt, its Text as String only # holds 50 chars which is not only for Hash and Salt property :password_digest, Text property :password_token, String property :password_token_timestamp, Text # this is DMs method of validating the model which # won't be saved unless both p/w and p/w conf match validates_confirmation_of :password, :message => "Sorry, your passwords don't match" validates_uniqueness_of :email # when assigned the p/D we don't store it directly # instead, we generate a password digest, that looks like this: # "$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa" # and save to the db. The digest, provided by bcrypt, # has both the p/d Hash and the Salt. We save it to the # db instead of the plain p/d for security reasons. def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end def self.authenticate(email, password) # the user who's trying to sign in user = first(:email => email) # if this user exists and the p/d matches # (the one we have password_digest for) everything's fine # The Password.new returns an object that overrides the == method. # Instead of comparing two passwords directly # (which is impossible because we only have a one-way hash) # the == method calculates the candidate password_digest from # the password given and compares it to the password_digest # it was initialised with. # So, to recap: THIS IS NOT A STRING COMPARISON!!! if user && BCrypt::Password.new(user.password_digest) == password # return this user user else nil end end end
# Encoding: UTF-8 require 'spec_helper' require 'openssl' describe WikipediaWrapper, :type => :model do describe ".search" do ww = WikipediaWrapper.new("svend foyn") before { @result = ww.search() } subject { @result } it "should return array" do expect(@result).to be_an_instance_of(Array) end it "should return array of References" do @result.each do |r| expect(r).to be_an_instance_of(Reference) end end end describe ".new_reference_from" do before { @ref = WikipediaWrapper::new_reference_from("http://no.wikipedia.org/wiki/Svend_Foyn") } subject { @ref } it "should be a reference" do expect(@ref).to be_an_instance_of(Reference) end it "should have correct info" do expect(@ref.title).to eq("Svend Foyn") expect(@ref.creator).to eq("Wikipedia") expect(@ref.lang).to eq("no") expect(@ref.year).to eq(nil) end end end
class OrderItemsController < ApplicationController before_action :authenticate_user!, only: [:create] layout 'header' def show render 'carts/show' end def create if user_signed_in? @order = current_order @order_item = @order.order_items.new(order_item_params) @order_item.save! @order.progress! @order.save session[:order_id] = @order.id else redirect_to new_user_session_path end end def update @order = current_order @order_items = @order.order_items @order_item = @order.order_items.find(params[:id]) @order_item.update_attributes(order_item_params) end def destroy @order = current_order @order_item = @order.order_items.find(params[:id]) @order_item.destroy @order_items = @order.order_items end private def order_item_params params.require(:order_item).permit(:quantity, :product_id) end end
class ChangeDates < ActiveRecord::Migration def change change_column :cat_rental_requests, :start_date, :datetime change_column :cat_rental_requests, :end_date, :datetime end end
class Warden::SessionSerializer def serialize(record) [record.class, record.id] end def deserialize(keys) klass, id = keys klass.first(:conditions => { :id => id }) end end
# Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz” oneToHundred = 1..100 oneToHundred.each {|i| if i%3==0 && i%5==0 puts "FizzBuzz" elsif i%5==0 puts "Buzz" elsif i%3==0 puts "Fizz" else puts i end }
class PrivateController < ApplicationController before_action :before_action after_action :after_action private def before_action redirect_to root_path if !user_signed_in? @user = current_user end private def after_action end end
require 'i18n' module Rack module DevMark module I18nHelper def self.included(base) class << base def env_with_i18n s = env_without_i18n ::I18n.translate(s, scope: 'rack_dev_mark', default: s) end alias_method :env_without_i18n, :env alias_method :env, :env_with_i18n end end end end end
require 'rails_helper' RSpec.describe "guns/edit", type: :view do before(:each) do @gun = assign(:gun, Gun.create!( :name => "MyString", :description => "MyText", :size => 1, :damage => 1.5, :fire_rate => 1.5, :clip_size => 1, :reload_time => 1.5, :proj_size => 1.5, :proj_speed => 1.5, :proj_distance => 1, :proj_number => 1, :proj_spread => 1, :functions => "MyText", :sprite => "MyText", :sprite_firing => "MyText", :sprite_reload => "MyText" )) end it "renders the edit gun form" do render assert_select "form[action=?][method=?]", gun_path(@gun), "post" do assert_select "input#gun_name[name=?]", "gun[name]" assert_select "textarea#gun_description[name=?]", "gun[description]" assert_select "input#gun_size[name=?]", "gun[size]" assert_select "input#gun_damage[name=?]", "gun[damage]" assert_select "input#gun_fire_rate[name=?]", "gun[fire_rate]" assert_select "input#gun_clip_size[name=?]", "gun[clip_size]" assert_select "input#gun_reload_time[name=?]", "gun[reload_time]" assert_select "input#gun_proj_size[name=?]", "gun[proj_size]" assert_select "input#gun_proj_speed[name=?]", "gun[proj_speed]" assert_select "input#gun_proj_distance[name=?]", "gun[proj_distance]" assert_select "input#gun_proj_number[name=?]", "gun[proj_number]" assert_select "input#gun_proj_spread[name=?]", "gun[proj_spread]" assert_select "textarea#gun_functions[name=?]", "gun[functions]" assert_select "textarea#gun_sprite[name=?]", "gun[sprite]" assert_select "textarea#gun_sprite_firing[name=?]", "gun[sprite_firing]" assert_select "textarea#gun_sprite_reload[name=?]", "gun[sprite_reload]" end end end
task :test do original_words = File.readlines 'words.txt' unique_words = original_words.uniq if original_words.size != unique_words.size raise "Duplicate words detected" end puts "No duplicate words" sorted_words = original_words.sort original_words.each.with_index do |w1,i| w2 = sorted_words[i] if w1 != w2 raise "Please keep words.txt in alphabetical order" end end puts "Words sorted alphabetically" puts "Everything good" end task default: :test
#!/usr/bin/env ruby class Hangman def initialize(guessing_player, checking_player) @guessing_player, @checking_player = guessing_player, checking_player @board = [] guessing_player.board = @board end def play puts 'Thank-you for playing HangmanTM, Enterprise Edition!' secret_word_pick until solved? display guessing_turn end winning_message end def secret_word_pick @checking_player.pick_secret_word @guessing_player.secret_word_length = @checking_player.secret_word_length @checking_player.secret_word_length.times { @board << '_' } end def guessing_turn guess = @guessing_player.guess correct_index_array = @checking_player.check_guess(guess) board_update(correct_index_array, guess) end private def board_update(correct_index_array, guess) if correct_index_array correct_index_array.each do |index| @board[index] = guess end end end def solved? !@board.include?('_') end def display puts @board.join('') end def winning_message puts display puts 'The guesser has correctly chosen the word!' end end class Player attr_accessor :secret_word, :secret_word_length def check_guess(guess_char) if @secret_word.include?(guess_char) result = [] @secret_word.split('').each_with_index do |char, i| result << i if char == guess_char end else false end result end end class HumanPlayer < Player def pick_secret_word puts 'Please choose a secret word:' @secret_word = gets.chomp @secret_word_length = @secret_word.length end def guess puts 'Please choose a letter to be checked:' gets.chomp end end class ComputerPlayer < Player attr_accessor :character_map, :board def initialize(dictionary) @dictionary = File.readlines(dictionary).map(&:chomp) @guessed_letters = [] end def secret_word_length=(secret_word_length) @secret_word_length = secret_word_length setup_dictionary end def setup_dictionary @dictionary.select! { |word| word.length == @secret_word_length } character_map_setup end def pick_secret_word @secret_word = @dictionary.sample @secret_word_length = @secret_word.length end def guess character_map_setup character_map.each do |char, freq| unless @guessed_letters.include?(char) @guessed_letters << char return char end end end private def character_map_setup current_state = @board.join('').gsub('_', '.') regex = Regexp.new(current_state) character_map = Hash.new { |h, k| h[k] = 0 } @dictionary.each do |word| next unless regex.match(word) word.each_char do |char| character_map[char] += 1 end end self.character_map = character_map.sort_by { |char, freq| -1 * freq } end end if $PROGRAM_NAME == __FILE__ puts 'Input \'hp\' for human, \'cp\' for comupter' puts 'Guessing Player:' guesser = gets.chomp puts 'Checking Player:' checker = gets.chomp player_map = { 'cp' => ComputerPlayer.new('dictionary.txt'), 'hp' => HumanPlayer.new } Hangman.new(player_map[guesser], player_map[checker]).play end
module Api class BooksController < ApplicationController before_action :authenticate_user!, except: [:index, :show] before_action :set_book, only: [:show, :update] skip_before_action :check_user_confirmation_status, only: [:index, :show] def index @books = Book.nearby(set_coordinates, current_user.try(:id)) if @books.empty? @books = Book.mocks @distance = rand(100) @nearby_users = nil end @pagy, @books = pagy(@books, items: params[:per_page]) end def show if @book.is_mock? @distance = rand(100) else @distance = @book.owner.distance_to(set_coordinates, :km) end end def create @book = @current_user.books.new(book_params) if @book.save render 'show' else @error_message = @book.errors render 'shared/errors', status: :unprocessable_entity end end def update if @book.update(book_params) render 'show' else @error_message = @book.errors render 'shared/errors', status: :unprocessable_entity end end private def book_params params.permit(:title, :author, :description, :page_count, :language, :image, :published_at, :genre_id, :status) end def set_book if params[:id].present? @book = Book.find(params[:id]) elsif params[:friendly_id].present? @book = Book.friendly.find(params[:friendly_id]) end end def set_coordinates user_signed_in? ? [current_user.latitude, current_user.longitude] : [params[:latitude], params[:longitude]] end end end
class Ogre attr_accessor :name, :home, :encounter_counter, :swings def initialize(name, home = "Swamp") @name = name @home = home @encounter_counter = 0 @swings = 0 end def encounter(human) human.encounter_counter += 1 if human.encounter_counter < 3 human.ogre_aware = false else human.ogre_aware = true self.swing_at(human) if self.swings >= 2 human.conscious = false end human.encounter_counter = 0 end self.encounter_counter += 1 end def swing_at(human) @swings += 1 end def apologize(human) human.conscious = true end end class Human attr_accessor :name, :encounter_counter, :ogre_aware, :conscious def initialize(name = "Jane") @name = name @encounter_counter = 0 @ogre_aware = false @conscious = true end def notices_ogre? @ogre_aware end def knocked_out? @conscious == false end end
# frozen_string_literal: true module Assembler class Parser AInstruction = Struct.new(:value) do def accept(visitor) visitor.visit_a_instruction(self) end end CInstruction = Struct.new(:destination, :computation, :jump) do def accept(visitor) visitor.visit_c_instruction(self) end end Destination = Struct.new(:register) do def accept(visitor) visitor.visit_destination(self) end end LiteralExpression = Struct.new(:value) do def accept(visitor) visitor.visit_literal_expression(self) end end UnaryExpression = Struct.new(:operator, :operand) do def accept(visitor) visitor.visit_unary_expression(self) end end BinaryExpression = Struct.new(:left_operand, :operator, :right_operand) do def accept(visitor) visitor.visit_binary_expression(self) end end Jump = Struct.new(:condition) do def accept(visitor) visitor.visit_jump(self) end end SymbolDeclaration = Struct.new(:symbol) do def accept(visitor) visitor.visit_symbol_definition(self) end end def initialize(tokens) @tokens = tokens end def parse @tokens.map do |line| case line in [[:"@", _], [:number | :identifier | :pointer, value]] AInstruction.new(value) in [[:"(", _], [:identifier, symbol], [:")", _]] SymbolDeclaration.new(symbol) else destination, maybe_computation_and_jump = case line in [[:register, destination_register], [:"=", _], *maybe_computation_and_jump] [Destination.new(destination_register), maybe_computation_and_jump] else [Destination.new(nil), line] end computation, maybe_jump = case maybe_computation_and_jump in [[:! | :-, operator], [:register | :number, operand], *maybe_jump] [UnaryExpression.new(operator, operand), maybe_jump] in [ [:register | :number, left_operand], [:+ | :- | :| | :&, operator], [:register | :number, right_operand], *maybe_jump ] [BinaryExpression.new(left_operand, operator, right_operand), maybe_jump] in [[:register | :number, literal], *maybe_jump] [LiteralExpression.new(literal), maybe_jump] end jump = case maybe_jump in [[:";", _], [:jump, jump_value]] Jump.new(jump_value) in [] Jump.new(nil) end CInstruction.new(destination, computation, jump) end end end end end
require 'test/unit' # require "global/jwOneTag" # require "global/jwSingle" require '../../lib/global/jwOneTag' require '../../lib/global/jwSingle' module Jabverwock using StringExtension class DoctypeTest < Test::Unit::TestCase class << self # テスト群の実行前に呼ばれる.変な初期化トリックがいらなくなる def startup p :_startup end # テスト群の実行後に呼ばれる def shutdown p :_shutdown end end # 毎回テスト実行前に呼ばれる def setup p :setup @meta = META.new end # テストがpassedになっている場合に,テスト実行後に呼ばれる.テスト後の状態確認とかに使える def cleanup p :cleanup end # 毎回テスト実行後に呼ばれる def teardown p :treadown end ############## test ############### test "confirm name" do assert_equal(@meta.name , "meta") end test "press" do assert_equal(@meta.pressDefault, "<meta>") end test "add charset" do @meta.attr(:charset, "en") assert_equal(@meta.pressDefault, "<meta charset=\"en\">") end end end
# Copyright 2011-2015, The Trustees of Indiana University and Northwestern # University. Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # --- END LICENSE_HEADER BLOCK --- require 'spec_helper' describe 'collection management' do before :all do @collection = Collection.new Collection.destroy_all end it 'determines of Switchyard previously created the collection' do test_collection = { name: Time.now.utc.iso8601.to_s, url: "https://bar#{@url}.edu", pid: 'foo', fullname: 'A human readable unit name'} expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:exists]).to be_falsey sleep(1) end it 'creates a collection and determines it exists' do test_collection = { name: Time.now.utc.iso8601.to_s, url: "https://bar#{@url}.edu", pid: 'foo', fullname: 'A human readable unit name'} stub_request(:get, "https://bar.edu/admin/collections/foo.json").to_return(status: 200, body: "{\"id\":\"foo\"}") expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:exists]).to be_falsey @collection.save_collection_in_database(test_collection[:name], test_collection[:pid], test_collection[:url], test_collection[:fullname]) expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:exists]).to be_truthy sleep(1) end it 'can retrieve the pid of a created collection' do collection_name = Time.now.utc.to_s pid = Time.now.utc.to_s test_collection = { name: collection_name, url: "https://bar#{@url}.edu", pid: pid, fullname: 'A human readable unit name'} stub_request(:get, "https://bar.edu/admin/collections/#{collection_name}.json").to_return(status: 200, body: "{\"id\":\"#{pid}\"}") expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:exists]).to be_falsey @collection.save_collection_in_database(test_collection[:name], test_collection[:pid], test_collection[:url], test_collection[:fullname]) expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:pid]).to eq(test_collection[:pid]) sleep(1) end it 'retrieves the new pid of a migrated collection and updates the collection in the database' do collection_name = Time.now.utc.to_s pid = Time.now.utc.to_s new_pid = 'newpid' test_collection = { name: collection_name, url: "https://bar#{@url}.edu", pid: pid, fullname: 'A human readable unit name'} stub_request(:get, "https://bar.edu/admin/collections/#{collection_name}.json").to_return(status: 200, body: "{\"id\":\"#{new_pid}\"}") expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:exists]).to be_falsey @collection.save_collection_in_database(test_collection[:name], test_collection[:pid], test_collection[:url], test_collection[:fullname]) expect(@collection.collection_information(test_collection[:name], test_collection[:url])[:pid]).to eq(new_pid) expect(Collection.find_by(name: collection_name).pid).to eq(new_pid) sleep(1) end it 'requires both name and url to match' do stub_request(:get, "http://vader/admin/collections/sith.json").to_return(status: 200, body: "{\"id\":\"sith\"}") expect(@collection.collection_information('darth', 'vader')[:exists]).to be_falsey @collection.save_collection_in_database('darth', 'sith', 'vader', 'Anakin Skywalker') expect(@collection.collection_information('darth', 'maul')[:exists]).to be_falsey expect(@collection.collection_information('Noooooo', 'vader')[:exists]).to be_falsey expect(@collection.collection_information('darth', 'vader')[:exists]).to be_truthy end describe 'creating a collection via POST to Avalon' do before :all do @data= {name: 'test', unit: 'test', managers: ['test1@example.edu', 'test2@example.edu'], fullname: 'A human readable unit name'} end it 'attempts to create the collection via post' do stub_request(:post, "https://test.edu/admin/collections"). with(:body => {"admin_collection"=>{"name"=>"A human readable unit name", "description"=>"Avalon Switchyard Created Collection for test", "unit"=>"A human readable unit name", "managers"=>["test1@example.edu", "test2@example.edu"] , "default_read_groups"=>["BL-LDLP-MDPI-MANAGERS-test"]}}, :headers => {'Avalon-Api-Key'=>'foo'}).to_return(:status => 200, :body => "#{{id: 'pid'}.to_json}", :headers => {}) @collection.post_new_collection(@data[:name], @data[:unit], @data[:managers], {url: 'https://test.edu', api_token: 'foo'}) end it 'forms a post request properly' do stub_request(:post, "https://test.edu/admin/collections"). with(:body => {"admin_collection"=>{"name"=>"A human readable unit name", "description"=>"Avalon Switchyard Created Collection for test", "unit"=>"A human readable unit name", "managers"=>["test1@example.edu", "test2@example.edu"], "default_read_groups"=>["BL-LDLP-MDPI-MANAGERS-test"]}}, :headers => {'Avalon-Api-Key'=>'foo'}).to_return(:status => 200, :body => "#{{id: 'pid'}.to_json}", :headers => {}) expect(@collection.post_new_collection(@data[:name], @data[:unit], @data[:managers], {url: 'https://test.edu', api_token: 'foo'})).to eq('pid') end it 'calls post collection if a collection does not exist' do allow(@collection).to receive(:collection_information).and_return({exists: false}, {exists: true, pid: 'foo'}) expect(@collection).to receive(:post_new_collection).at_least(:once).and_return('foo') expect(@collection.get_or_create_collection_pid({stub: 'object', json: { metadata: {'unit'=>'foo'}}}, url: 'http://somewhere.edu')).to eq('foo') end end describe '#lookup_fullname' do it 'should lookup a full name' do expect(Collection.lookup_fullname('test')).to eq 'A human readable unit name' end it 'should default to the passed name if no long form is found' do expect(Collection.lookup_fullname('none')).to eq 'none' end end describe 'collection creation errors' do before :all do @data= {name: 'test', unit: 'test', managers: ['test1@example.edu', 'test2@example.edu'], fullname: 'A human readable unit name'} end it 'captures a 422 error and logs it' do stub_request(:post, "https://test.edu/admin/collections").to_return(:status => 422) expect(Sinatra::Application.settings.switchyard_log).to receive(:error).at_least(:once) expect{ @collection.post_new_collection(@data[:name], @data[:unit], @data[:managers], url: 'https://test.edu') }.to raise_error(RuntimeError) end it 'sets the object to an error state when it cannot create the collection' do allow(@collection).to receive(:post_new_collection).and_raise(RuntimeError) allow(@collection).to receive(:collection_information).and_return({}) obj = Objects.new allow(Objects).to receive(:new).and_return(obj) expect(obj).to receive(:object_error_and_exit).at_least(:once).and_raise(RuntimeError) expect{@collection.get_or_create_collection_pid({json: {metadata: {'unit'=>'test'}}}, {})}.to raise_error(RuntimeError) end end describe 'default read groups' do it 'adds the prefix to the group name' do name = 'B-FOO' expected_result = ['BL-LDLP-MDPI-MANAGERS-B-FOO'] expect(@collection.populate_read_group(name)).to eq(expected_result) end end end
class BeerClub < ActiveRecord::Base has_many :memberships, dependent: :destroy has_many :members, through: :memberships, source: :user def to_s "#{name}, anno #{founded} #{city}" end end
class MatchesController < ApplicationController before_action :set_match, only: [:show, :edit, :update, :destroy] before_action :require_login def require_login if not user_signed_in? || admin_signed_in? flash[:error] = "Você precisa estar logado para acessar esta seção." redirect_to new_user_session_path # halts request cycle end end def index @matches = Match.all.paginate(:page => params[:page], :per_page => 30).order('created_at DESC') end def new @match = Match.new if not Championship.find_by_id(params[:championship_id]).blank? $championship = Championship.find_by_id(params[:championship_id]) end end def create @match = Match.new(match_params) if $championship.nil? @match.friendly = true respond_to do |format| if @match.save friendly() format.html { redirect_to matches_path notice: 'Partida criada com sucesso.' } format.json { render :show, status: :created, location: @match } else format.html { render :new } format.json { render json: @match.errors, status: :unprocessable_entity } end end else unless $championship.matches.include? @match $championship.matches << @match end @champ = $championship $championship = nil respond_to do |format| format.html { redirect_to @champ } format.xml { head :ok } end end end def destroy delete_match = @match @match.destroy destroy_friendly(delete_match) end $friendly_array = Array.new def friendly @matches = Match.all.paginate(:page => params[:page], :per_page => 30).order('created_at DESC') @matches.each do |match| if match.friendly == true if not $friendly_array.include? match $friendly_array << match $friendly_array.sort!{|a,b| b.id <=> a.id } end end end end def destroy_friendly(match) $friendly_array.each do |friendly| if friendly.id == match.id $friendly_array.delete(match) end end respond_to do |format| format.html { redirect_to matches_url,notice: 'Partida excluida com sucesso.'} format.xml { head :ok } end end private def set_match @match = Match.find(params[:id]) end def match_params params.require(:match).permit(:team1_id, :team2_id, :date_match, :link) end end
require File.dirname(__FILE__) + '/../spec_helper' describe PostsController do include SpecControllerHelper include FactoryScenario before :each do Site.delete_all factory_scenario :forum_with_topics @post = Factory(:post, :author => @user, :commentable => @topic) @topic.reload; @forum.reload # wtf ! TODO there is something wrong with setup Site.stub!(:find_by_host).and_return @site @site.sections.stub!(:find).and_return @forum controller.stub!(:current_user).and_return @user @controller.stub!(:has_permission?).and_return true end it "should be a BaseController" do controller.should be_kind_of(BaseController) end describe "GET to new" do before :each do Post.stub!(:new).and_return @post end act! { request_to :get, "/forums/#{@forum.id}/topics/#{@topic.id}/posts/new" } it_assigns :post it_guards_permissions :create, :post end describe "GET to edit" do before :each do @topic.comments.stub!(:find).and_return @post end act! { request_to :get, "/forums/#{@forum.id}/topics/#{@topic.id}/posts/#{@post.id}/edit" } it_assigns @post it_guards_permissions :update, :post end describe "POST to create" do before :each do @forum.topics.stub!(:find).and_return @topic @topic.stub!(:reply).and_return @post end act! { request_to :post, "/forums/#{@forum.id}/topics/#{@topic.id}/posts", {} } it_guards_permissions :create, :post it "instantiates a new post through topic.reply" do @topic.should_receive(:reply).with(@user, nil).and_return(@post) act! end describe "with valid parameters" do it_redirects_to { "http://test.host/forums/#{@forum.id}/topics/#{@topic.permalink}#post_#{@post.id}" } it_assigns_flash_cookie :notice => :not_nil it "saves the post" do @post.should_receive(:save).and_return true act! end end describe "with invalid parameters" do before :each do @post.stub!(:save).and_return false end it_renders_template :new it_assigns_flash_cookie :error => :not_nil end end describe "PUT to update" do before :each do @forum.topics.stub!(:find).and_return @topic @topic.comments.stub!(:find).and_return @post end act! { request_to :put, "/forums/#{@forum.id}/topics/#{@topic.id}/posts/#{@post.id}", {} } it_guards_permissions :update, :post describe "with valid parameters" do it_redirects_to { "http://test.host/forums/#{@forum.id}/topics/#{@topic.permalink}#post_#{@post.id}" } it_assigns_flash_cookie :notice => :not_nil it "updates the post" do @post.should_receive(:update_attributes).and_return true act! end end describe "with invalid parameters" do before :each do @post.stub!(:update_attributes).and_return false end it_renders_template :edit it_assigns_flash_cookie :error => :not_nil end end describe "DELETE to destroy" do describe "with normal posts" do before :each do @topic.comments.stub!(:find).and_return @post @topic.stub!(:initial_post).and_return Comment.new end act! { request_to :delete, "/forums/#{@forum.id}/topics/#{@topic.id}/posts/#{@post.id}" } it_assigns @post it_assigns_flash_cookie :notice => :not_nil it_redirects_to { "http://test.host/forums/#{@forum.id}/topics/#{@topic.id}" } it_guards_permissions :destroy, :post it "destroys the post" do @post.should_receive(:destroy) act! end end describe "with initial post" do before :each do @post = @topic.comments.first @topic.comments.stub!(:find).and_return @post end act! { request_to :delete, "/forums/#{@forum.id}/topics/#{@topic.id}/posts/#{@post.id}" } it_assigns_flash_cookie :error => :not_nil it_redirects_to { "http://test.host/forums/#{@forum.id}/topics/#{@topic.id}" } end end end describe "PostsSweeper" do include SpecControllerHelper include FactoryScenario controller_name 'posts' before :each do Site.delete_all factory_scenario :forum_with_topics @sweeper = CommentSweeper.instance end it "observes Section, Board, Topic" do ActiveRecord::Base.observers.should include(:comment_sweeper) end it "should expire pages that reference a post, post.topic comments_counter and post.topics owners comments_counter" do @sweeper.should_receive(:expire_cached_pages_by_reference).with(@topic.initial_post.commentable) @sweeper.should_receive(:expire_cached_pages_by_reference).with(@topic.comments_counter) @sweeper.should_receive(:expire_cached_pages_by_reference).with(@topic.owner.comments_counter) @sweeper.after_save(@topic.initial_post) end end