text
stringlengths
10
2.61M
require 'pry' class Translator def initialize(word_or_phrase) if word_or_phrase.split.length > 1 @phrase = word_or_phrase elsif word_or_phrase.split.length == 1 @word = word_or_phrase else raise "You must input some words to be translated." end end def words if @phrase != nil @phrase.split else @word.split end end def letters(word) word.split"" end def is_vowel?(l) if l.downcase == "a" return true elsif l.downcase == "e" return true elsif l.downcase == "i" return true elsif l.downcase == "o" return true elsif l.downcase == "u" return true end end def translate_word(word = @word) if is_vowel?(word[0]) == true word + "way" else push_to_back = [] letters(word).each do |l| break if is_vowel?(l) push_to_back << l.downcase end new_word = word[push_to_back.length,word.size-1] new_word = new_word + push_to_back.join new_word + "ay" end end def translate_phrase new_phrase = [] words.each do |word| new_phrase << translate_word(word) end new_phrase.join(" ").capitalize #break phrase into words #analyze words for vowels #if first letter is vowel, add 'way' #else 'take all letters until first vowel and put at end of word' # end end
class Show < ActiveRecord::Base belongs_to :network has_many :characters has_many :actors, through: :characters end
require 'test_helper' class ProfilesControllerTest < ActionController::TestCase test "should get show" do get :show, id: users(:moe).profile_name assert_response :success assert_template 'profiles/show' end test "should render a 404 on profile not found" do get :show, id: "doesn't exisst" assert_response "not_found" end test "that variables are assigned on successful profile viewing " do get :show, id: users(:moe).profile_name assert assigns(:user) assert_not_empty assigns(:statuses) end test " only shows the correct user's statuses" do get :show, id: users(:moe).profile_name assigns(:statuses).each do |status| assert_equal users(:moe),status.user end end end
$:.push "." require 'rt' require 'yaml' require 'stringio' module RTHelper FIXTURE_DIR=File.join(File.dirname(__FILE__),'fixtures') def fixture_path(str) File.join(FIXTURE_DIR,str) end def setup_bin_test %x{cp rt.rb #{mock_ruby_path}} %x{rm #{fixture_path('fixture.rb.bak')}} end def mock_file "mock_file.txt" end def mock_ruby_path fixture_path('fixture.rb') end def read_mock_ruby IO.read(mock_ruby_path) end def create_mock_file path = fixture_path(mock_file) f = File.open(path,File::CREAT|File::TRUNC|File::RDWR) do |f| f << %%line 1 foo\n% f << %%line 2 foplzo\n% f << %%line 3 "'foo'"^^oofoo--marm\n% end path end end RSpec.configure do |config| config.include RTHelper end
class RemoveNotNullConstraintFromReferences < ActiveRecord::Migration def up change_column :references, :title, :text, :null => true change_column :references, :citation, :text, :null => false end def down change_column :references, :title, :text, :null => false change_column :references, :citation, :text, :null => true end end
class CreateImages < ActiveRecord::Migration def up create_table :images do |t| t.references :area, :null => false t.string :name, :null => false t.string :image t.integer :image_size, :default => 0 t.string :image_content_type t.timestamps end end def down drop_table :images end end
class AddTodolistIdToListitem < ActiveRecord::Migration def change add_column :listitems, :todolist_id, :integer end end
# Fact: infiniband_hca_board_id # # Purpose: Determine the board ID of HCA # # Resolution: # Returns Hash of HCAs and their board ID. # require 'facter/util/infiniband' Facter.add(:infiniband_hca_board_id) do confine has_infiniband: true setcode do hcas = Facter.fact(:infiniband_hcas).value || [] hca_board_id = {} hcas.each do |hca| board_id = Facter::Util::Infiniband.get_hca_board_id(hca) hca_board_id[hca] = board_id end if hca_board_id.empty? nil else hca_board_id end end end
class Api::RatingsController < ApplicationController def index @ratings = Rating.order(:id) respond_to do |format| format.json { render json: @ratings.to_json, status: 200 } end end end
class AddMostRecentGdpPppToCountries < ActiveRecord::Migration def change add_column :countries, :most_recent_gdp_ppp, :integer end end
class Slide < ActiveRecord::Base include Positioned alias_attribute :parent_id, :position mount_uploader :src, SlideUploader after_destroy :clear_files private # delete attached file and its versions if present def clear_files return if src.current_path.nil? FileUtils.rm_rf(File.dirname(self.src.current_path)) end end
class FakeDuck def method_missing(m, *args) FakeDuck.new end end class UpdateTrashAndCategories < ActiveRecord::Migration[5.2] def cat(name) Category.find_by_name(name) || FakeDuck.new end def trash(name) Trash.find_by_name(name) || FakeDuck.new end def mat(name) Material.where('lower(name) like ?', "%#{name}%").first! end def up # Get rid of Foam Products category altogether along with items listed in it. cat('foam products').trashes.update_all(hidden: true) # Let's move some of the items into their proper categories: # Cigarette box -> Smoking Materials trash('cigarette box').update(category: cat('smoking materials')) # Newsprint (Adjust name to "Reading Materials") -> Other trash('pieces (newsprint, books, etc)').update( name: 'reading materials', category: cat('other') ) # Remove the rest of the items and categories (everything in Paper/Wood and Metal and the cats themselves) cat('paper/wood products').trashes.update_all(hidden: true) cat('metal products').trashes.update_all(hidden: true) # Adjust name of Miscellaneous Plastic Fragment to Miscellaneous Fragment trash('misc plastic fragment').update(name: 'miscellaneous fragment') # Sachet -> Other trash('sachet').update(category: cat('other')) # Can we add another category: Packing Materials pm = Category.create_with(order: 5).find_or_create_by!( name: 'packing materials' ) # Tape -> Packing Materials trash('tape').update(category: pm) # Add "Boxes" -> Packing Materials Trash.create_with(category: pm, material: mat('cardboard')) .find_or_create_by!(name: 'boxes') # Foam cooler -> Packing Materials trash('foam cooler').update(category: pm) # Add "Styrofoam peanuts" -> Packing Materials Trash.create_with(category: pm, material: mat('#6')).find_or_create_by!( name: 'styrofoam peanuts' ) # Film -> Packing Materials trash('misc plastic film').update(name: 'plastic film', category: pm) # Add "Bubble wrap" -> Packing Materials Trash.create_with(category: pm, material: mat('#4')).find_or_create_by!( name: 'bubble wrap' ) # Add "Delivery envelopes" -> Packing Materials Trash.create_with(category: pm, material: mat('#4')).find_or_create_by!( name: 'delivery envelopes' ) # Please delete the "Other" item in all categories as it is confusing. Do not delete the "Other" category though. :) Trash.where(name: 'other').update_all(hidden: true) end def down Category.where(name: 'packing materials').destroy_all trash('reading materials').update(name: 'pieces (newsprint, books, etc)') trash('miscellaneous fragment').update(name: 'misc plastic fragment') trash('plastic film').update(name: 'misc plastic film') end end
module Domain class Match def matches?(request) if request.subdomain.present? && request.subdomain != 'www' && request.subdomain != 'myplaces' request.path_parameters[:city_id] = request.subdomain end dom = request.host.gsub Regexp.new('^'+request.subdomain+'\.'), '' I18n.locale = LOCALE_DOMAINS.key(dom) || I18n.default_locale return true end end module Mapper def domain constraints(Domain::Match.new) { yield } end end =begin module Helper def url_for options return options if options.kind_of?(String) if options.kind_of?(Hash) options[:host] = [options.delete(:city_id), LOCALE_DOMAINS[(options.delete(:locale)||I18n.locale).to_s]].keep_if{|item|item}.join '.' end options.keys.count > 1 ? super(options) : root_url(options) end end =end end
# -*- mode: ruby -*- # vi: set ft=ruby : # For reloading the VM required_plugins = %w( vagrant-reload ) required_plugins.each do |plugin| system "vagrant plugin install vagrant-reload" unless Vagrant.has_plugin? plugin end Vagrant.configure(2) do |config| config.vm.box = "boxcutter/ubuntu1404-desktop" config.vm.provider "virtualbox" do |vb| vb.name="chowan-sagarwa6-FSE-2011-jStar-Eclipse" end config.vm.provision :shell, path: "bootstrap1.sh" config.vm.provision :reload config.vm.provision :shell, path: "bootstrap2.sh" config.vm.provision :reload config.vm.provision :shell, path: "bootstrap3.sh" config.vm.provision :reload config.vm.provision :shell, path: "bootstrap4.sh" config.vm.provision :reload end
# frozen_string_literal: true class TeacherSetSerializer < ActiveModel::Serializer cached attributes :id, :availability, :availability_string, :description, :details_url, :primary_language, :subject_key, :title, :suitabilities_string, :call_number, :physical_description, :set_type, :contents, :total_copies, :available_copies, :language has_many :teacher_set_notes has_many :books # If controller specifies :include_books=>false for perf, don't include books def include_books? @options[:include_books].nil? ? true : @options[:include_books] end def include_contents? @options[:include_contents].nil? ? true : @options[:include_contents] end # Can't just delegate cache_key to object because some serializations have books & some don't def cache_key [object, @options[:include_books], @options[:include_contents]] end end
##### Buscar cidade por id Quando('solicito o id de uma cidade para o serviço de metereologia') do @id = Servico.buscar_cidade_por_id end Então('devo obter o código de status referente ao id {string}') do |status| expect(@id.response.code).to eql status end Então('recebo uma lista com o id da cidade desejada') do expect(@id.parsed_response['name']).to eql 'Brasília' expect(@id.parsed_response['id'].to_s).to eql '3469058' end #### Buscar cidade por nome Quando('solicito o nome de uma cidade para o serviço de metereologia') do @nome = Servico.buscar_cidade_por_nome end Então('devo obter o código de status referente ao nome {string}') do |status| expect(@nome.response.code).to eql status end Então('recebo uma lista com o nome da cidade desejada') do expect(@nome.parsed_response['name']).to eql 'Brasília' expect(@nome.parsed_response['id'].to_s).to eql '3469058' end #### Buscar cidade por latitude e longitude Quando('solicito a latitude e longitude de uma cidade para o serviço de metereologia') do @lat = Servico.buscar_cidade_por_lat_long end Então('devo obter o código de status referente a sua latitude e longitude {string}') do |status| expect(@lat.response.code).to eql status end Então('recebo uma lista com a latitude e longitude da cidade desejada') do expect(@lat.parsed_response['name']).to eql 'Brasília' expect(@lat.parsed_response['id'].to_s).to eql '3469058' end #### Cidade não existe Quando('solicito uma cidade inexistente') do @city = Servico.cidade_nao_encontrada end Então('devo obter o código de status para cidade inexistente {string}') do |status| expect(@city.response.code).to eql status end Então('a mensagem de cidade inexistente {string}') do |msg_city| expect(@city.parsed_response["message"]).to eql msg_city end #### Não há geolocalização Quando('solicito uma cidade em branco') do @geo = Servico.nao_ha_geolocalizacao end Então('devo obter o código de status {string}') do |status| expect(@geo.response.code).to eql status end Então('a mensagem que não há geolocolização {string}') do |msg_geo| expect(@geo.parsed_response["message"]).to eql msg_geo end #### Não possui autorização Quando('solicito uma requisição aonde não possuo autorização') do @auth = Servico.nao_ha_autorizacao end Então('devo obter o código {string}') do |status| expect(@auth.response.code).to eql status end Então('a mensagem que não possuo autorização {string}') do |no_auth| expect(@auth.parsed_response["message"]).to eql no_auth end
class CreateProductCandidates < ActiveRecord::Migration def change create_table :product_candidates do |t| t.string :name t.integer :price t.string :source t.integer :score t.text :description t.integer :desired_object_id t.string :type t.timestamps end end end
class CommentsController < ApplicationController before_action :set_comment!, except: [:create, :new, :index] def index if params[:whiskey_id] @comments = Whiskey.find(params[:whiskey_id]).comments respond_to do |f| f.json {render json: @comments} f.html {render :index} end end end def new @comment = Comment.new end def create @comment = Comment.create(comment_params) render json: @comment, status: 201 end def show end def set_comment! @comment = Comment.find(params[:id]) end private def comment_params params.permit(:whiskey_id, :user_id, :content) end end
require 'spec_helper' describe 'Peep' do context "DataMapper Test" do it "should be created and then deleted from the database" do expect(Peep.count).to eq(0) Peep.create(:name => "Karin Nielsen", :user_handle => "@karinmnielsen", :post => "this is my first peep") expect(Peep.count).to eq(1) peep = Peep.first expect(peep.name).to eq ("Karin Nielsen") expect(peep.user_handle).to eq ("@karinmnielsen") expect(peep.post).to eq ("this is my first peep") Peep.destroy expect(Peep.count).to eq(0) end end end
class ContactSerializer < ActiveModel::Serializer attributes :id, :name, :email, :birthdate#, :author belongs_to :kind do link(:related) { contact_kind_url(object.kind.id) } end has_many :phones do link(:related) { contact_phones_url(object.kind.id) } end has_one :adddress do link(:related) { contact_adddresses_url(object.kind.id) } end #links no json HATEOAS # dessa forma ele coloca somente o endereço sem o localhost link(:self) { contact_path(object.id) } # dessa forma ele deve colocar o valor completo, porém é necessário setar no development.rb a seguinte configuração: # Rails.application.routes.default_url_options = { # host: 'localhost', # port: 3000 # } link(:kind) { kind_url(object.kind.id) } # meta para criar uma metainformação sobre o json, também chamado de informações extras meta do { author: "Antonio Carlos" } end # Atributo Virtual, podemos criar um atributo virtual na lista de atributos e depois criamos um método # com o retorno desejado por esse atributo virtual # def author # "Antonio Carlos" # end # fazendo i18n com birthdate usando active_model_serializers def attributes(*args) hsh = super(*args) # pt-BR ---> hsh[:birthdate] = (I18n.l(object.birthdate) unless object.birthdate.blank?) hsh[:birthdate] = object.birthdate.to_time.iso8601 unless object.birthdate.blank? hsh end end
class WomenApplicant < Applicant enum status: [:applied, :accepted, :enrolled, :not_enrolled, :rejected, :gave_up, :graduated] enum program: [:full, :partial] before_create :generate_uid hstore_accessor :info, uid: :string, valid_code: :boolean, accepted_terms: :boolean, birthday: :string, gender: :string, skype: :string, twitter: :string, url: :string, goal: :string, experience: :string, typical_day: :string, vision: :string, additional: :string, payment_method: :string, format: :string, stipend: :string, version: :integer, prev_salary: :integer, new_salary: :integer, company: :string, start_date: :string, contract_type: :string, socioeconomic_level: :integer, referred_by: :string, studies: :string, working: :string, aspiring_course_accepted: :boolean def self.model_name Applicant.model_name end def self.status_to_human(status) mappings = { applied: "aplicó", accepted: "aceptado", enrolled: "matriculado", not_enrolled: "no matriculado", rejected: "rechazado", gave_up: "desistió del proceso", graduated: "graduado", } mappings[status.to_sym] end def self.status_segments(status) mappings = { applied: "Filled Nesst Women Bootcamp Application", accepted: "Accepted to Nesst Women Bootcamp", enrolled: "Erolled to Nesst Women Bootcamp", not_enrolled: "Not enrolled to Nesst Women Bootcamp", rejected: "Rejected from Nesst Women Bootcamp", gave_up: "Desisted from Nesst Women Bootcamp application", graduated: "Graduated from Nesst Women Bootcamp" } mappings[status.to_sym] end protected def generate_uid begin self.uid = SecureRandom.hex(4) end while self.class.exists?(["info -> 'uid' = ?", self.uid]) end end
# frozen_string_literal: true class ChessPiece attr :position attr_reader :colour, :can_jump def initialize(position, colour) @position = position @colour = colour @unmoved = true @can_jump = false end def move(position) @position = position @unmoved = false true end def inspect @type end def to_s type = @colour == 'white' ? Rainbow(@type).ivory : Rainbow(@type).black end end class Pawn < ChessPiece def initialize(position, colour) super(position, colour) @type = " Pawn " end def can_move(start, finish) x1 = start[0] # x is column x2 = finish[0] y1 = start[1] # y is row y2 = finish[1] if @colour == "white" && (x2 == x1 - 1 || x2 == x1 - 2 && y1 == y2 && @unmoved) true elsif @colour == "black" && (x1 == x2 - 1 || x1 == x2 - 2 && y1 == y2 && @unmoved) true else puts "Pawns move forward." false end end end class Castle < ChessPiece def initialize(position, colour) super(position, colour) @type = ' Castle ' end def can_move(start, finish) x1 = start[0] x2 = finish[0] y1 = start[1] y2 = finish[1] # x or y axis only x1 == x2 || y1 == y2 ? true : false end end class Knight < ChessPiece def initialize(position, colour) super(position, colour) @type = ' knight ' @can_jump = true end def can_move(start, finish) x_diff = (start[0] - finish[0]).abs y_diff = (start[1] - finish[1]).abs x_diff + y_diff == 3 && x_diff == 1 || y_diff == 1 ? true : false end end class Bishop < ChessPiece def initialize(position, colour) super(position, colour) @type = ' Bishop ' end def can_move(start, finish) x1 = start[0] x2 = finish[0] y1 = start[1] y2 = finish[1] # diagonal only: x diff == y diff (x1 - x2).abs == (y1 - y2).abs ? true : false end end class Queen < ChessPiece def initialize(position, colour) super(position, colour) @type = ' Queen ' end def can_move(start, finish) x1 = start[0] x2 = finish[0] y1 = start[1] y2 = finish[1] # x or y axis only? OR diagonal x diff == y diff (Makes sure we're only moving in a straight line) (x1 == x2 || y1 == y2) || (x1 - x2).abs == (y1 - y2).abs ? true : false end end class King < ChessPiece def initialize(position, colour) super(position, colour) @type = ' King ' end def can_move(start, finish) x1 = start[0] x2 = finish[0] y1 = start[1] y2 = finish[1] (x1 - x2).abs <= 1 && (y1 - y2).abs <= 1 ? true : false end end
class OpinionsController < ApplicationController before_action :signed_in_user def new @opinion = Opinion.new end def create @opinion = Opinion.new(opinion_params) if @opinion.save flash[:success] = "Комментарий добавлен!" redirect_to :back else redirect_to :back end end def destroy end private def opinion_params params.require(:opinion).permit(:comment, :health, :aestetics, :technology, :user_id, :content_id) end end
=begin MEASURE default argument of 1 (because sometimes it is passed a int for repeating the block) API Time.parse is used, startTime to declare time at start of method [time - other_time → float] OR [time - numeric → time] count.times {yield} (performs block n times) =end def measure (count = 1) startTime = Time.now #Time.now returns Time obj with date such as 2002-01-01 00:00:00 -0500 count.times {yield} #Run block n times #tempTimeInt=(Time.now-startTime) #deprec- Already returns float. Ruby can do math on float - int (Time.now-startTime) / count #(Time.now-startTime) will return float end
module EmailContentsHelper def year_plain_image(year) et_image_tag YEAR_PLAIN_IMAGES[year], year, 78, 48 end def year_starred_image(year) et_image_tag YEAR_STARRED_IMAGES[year], year, 116, 65 end def year_helpful_image(year) et_image_tag YEAR_HELPFUL_IMAGES[year], year, 116, 65 end def year_friend_image(year) et_image_tag YEAR_FRIEND_IMAGES[year], year, 116, 65 end def month_header_center_image(month) et_image_tag MONTH_HEADER_CENTER_IMAGES[month], month, 78, 21 end def month_header_left_image(month) et_image_tag MONTH_HEADER_LEFT_IMAGES[month], month, 78, 21 end def date_image(date) et_image_tag DATE_IMAGES[date.to_i], date, 78, 48 end def star_image(stars) et_image_tag STAR_IMAGES[stars.to_s], pluralize(stars, 'star'), 100, 32 end def postage_stamp_image et_image_tag 'ce197709-1.gif', 'new comment', 75, 75 end def message_orange_image et_image_tag '5555c3ff-c.gif', 'comment', 32, 32 end def reply_grey_image et_image_tag '29c64b7d-4.gif', 'reply', 18, 26 end def just_posted_image et_image_tag '13e4c6da-9.gif', 'Just Posted', 75, 75 end def just_posted_compliment_image et_image_tag '1f1b86ed-6.gif', 'compliment', 74, 68 end def just_posted_comment_image et_image_tag '98861df4-f.gif', 'comment', 74, 68 end def week_green_check_image et_image_tag 'e4efdec6-a.gif', 'week', 107, 17, :vspace => 1 end def week_helpful_image et_image_tag '2a4727b2-c.gif', 'week', 107, 17, :vspace => 1 end def week_star_image et_image_tag 'c47a3fe6-f.gif', 'week', 107, 17, :vspace => 1 end def comment_icon_image et_image_tag '5d0275d9-5.gif', 'Comments', 32, 32, :hspace => 1, :align => 'absmiddle' end def compliment_icon_image et_image_tag '159a2147-7.gif', 'Compliments', 32, 32, :hspace => 1, :align => 'absmiddle' end def comment_grey_image et_image_tag '2966a580-1.gif', 'comment', 26, 25 end def compliment_grey_image et_image_tag '06f6655c-4.gif', 'compliment', 26, 25 end def just_posted_tail_image_path et_image_path '9f87eade-0.gif' end YEAR_PLAIN_IMAGES = Hash[ '2007' => '652165f5-a.gif', '2008' => 'b5314893-8.gif', '2009' => 'f2230611-2.gif', '2010' => '67ab7346-b.gif', ] YEAR_STARRED_IMAGES = Hash[ '2007' => '5cbab2b0-4.gif', '2008' => '13d84af6-4.gif', '2009' => 'c7038e79-c.gif', '2010' => '53b2f0bd-f.gif'] YEAR_HELPFUL_IMAGES = Hash[ '2007' => 'lib/fef6127573640c/i/1/372ad49b-e.gif', '2008' => 'lib/fef6127573640c/i/1/e47f6f55-a.gif', '2009' => 'lib/fef6127573640c/i/1/5088cda6-f.gif', '2010' => 'lib/fef6127573640c/i/1/4bed953d-5.gif'] YEAR_FRIEND_IMAGES = Hash[ '2007' => 'f644b519-a.gif', '2008' => '5e82a7e4-8.gif', '2009' => 'bfd579b3-4.gif', '2010' => 'a8da9d49-b.gif'] MONTH_HEADER_CENTER_IMAGES = Hash[ 'January' => '10b0cabf-3.gif', 'February' => 'e77767d0-8.gif', 'March' => 'b7cbaf5d-4.gif', 'April' => 'b98dc459-5.gif', 'May' => 'e36c1c95-4.gif', 'June' => '9ed29e05-a.gif', 'July' => 'd138318e-a.gif', 'August' => '9b15a94c-d.gif', 'September' => '90802c06-1.gif', 'October' => '7e1146c3-0.gif', 'November' => 'd370b1cf-4.gif', 'December' => '203f690a-c.gif' ] MONTH_HEADER_LEFT_IMAGES = Hash[ 'January' => '44ec548b-f.gif', 'February' => '422f1914-4.gif', 'March' => '781865c3-d.gif', 'April' => 'bda60c72-2.gif', 'May' => '58fa8664-f.gif', 'June' => 'f34170ba-9.gif', 'July' => '2922ca1b-9.gif', 'August' => '17d6be05-8.gif', 'September' => 'fc6566ca-c.gif', 'October' => '5307e537-3.gif', 'November' => 'b9c7ce33-f.gif', 'December' => 'f7134f1c-7.gif' ] DATE_IMAGES = Hash[ 1 => '7aaf2540-3.gif', 2 => '91433b64-b.gif', 3 => '7d220a2e-7.gif', 4 => '7cac8bf7-d.gif', 5 => '27bd499b-d.gif', 6 => 'e456ae23-5.gif', 7 => '2934be3c-4.gif', 8 => '81507a8b-d.gif', 9 => 'd05b1224-2.gif', 10 => '91bd696d-1.gif', 11 => 'ab50dbd9-c.gif', 12 => '2a8ab844-f.gif', 13 => '9b86572a-0.gif', 14 => '7556ec28-d.gif', 15 => '25580e38-2.gif', 16 => '710b1736-6.gif', 17 => 'c1b93eed-f.gif', 18 => '4a5dd726-8.gif', 19 => 'eabeb9e0-e.gif', 20 => '366d5e06-0.gif', 21 => '508f8e73-2.gif', 22 => '39180097-b.gif', 23 => '687f24ff-c.gif', 24 => 'f6163989-5.gif', 25 => '8f7ffb47-1.gif', 26 => '1b8c3e67-5.gif', 27 => '7a44a7f7-b.gif', 28 => '1488c469-b.gif', 29 => 'd8cbf2c9-f.gif', 30 => '121b0d9a-1.gif', 31 => '46f27e65-3.gif' ] STAR_IMAGES = Hash[ '1' => '19461824-7.gif', '1.0' => '19461824-7.gif', '1.5' => 'a5fa8062-4.gif', '2' => 'ed7ca45e-6.gif', '2.0' => 'ed7ca45e-6.gif', '2.5' => 'ec9814c8-2.gif', '3' => '168bd03f-5.gif', '3.0' => '168bd03f-5.gif', '3.5' => '60480b96-b.gif', '4' => '9fa114f5-2.gif', '4.0' => '9fa114f5-2.gif', '4.5' => '94cfabbb-f.gif', '5' => 'da0cd782-e.gif', '5.0' => 'da0cd782-e.gif' ] private def et_image_tag(image, alt, width, height, options=nil) options ||= {} options = options.merge({ :src => et_image_path(image), :alt => alt, :width => width, :height => height}) tag 'img', options end def et_image_path(image) "http://image.exct.net/" + image end COBRAND_NAMED_IMAGES = { 'viewpoints' => { :main_logo1 => 'http://image.exct.net/4d5157b0-c.gif', :main_logo2 => 'http://image.exct.net/a69e9347-6.gif', :main_logo3 => 'http://image.exct.net/e7927377-b.gif', :main_logo4 => 'http://image.exct.net/2f4ceda6-3.gif' }, 'mysears' => { :main_logo1 => 'http://image.exct.net/lib/fef6127573640c/i/1/d4822f59-f.gif', :main_logo2 => 'http://image.exct.net/lib/fef6127573640c/i/1/c60e0fea-7.gif', :main_logo3 => 'http://image.exct.net/e7927377-b.gif', :main_logo4 => 'http://image.exct.net/lib/fef6127573640c/i/1/38de361d-5.gif' }, 'startsampling' => { :main_logo1 => 'http://image.exct.net/lib/fef6127573640c/i/1/410ec8fe-7.gif', :main_logo2 => 'http://image.exct.net/a69e9347-6.gif', :main_logo3 => 'http://image.exct.net/e7927377-b.gif', :main_logo4 => 'http://image.exct.net/lib/fef6127573640c/i/1/2f0794c2-d.gif' } } def cobrand_named_image(cobrand, image_name) hash = COBRAND_NAMED_IMAGES[cobrand.short_name] hash = COBRAND_NAMED_IMAGES[cobrand.parent.short_name] if hash.blank? && cobrand.parent return hash[image_name] end def interleave_arrays(array_of_arrays, max_items=15) final = [] idx = 0 done = false while !done any_added = false array_of_arrays.each do |ary| el = ary[idx] unless el.blank? final << el any_added = true end break if final.size >= max_items end idx += 1 done = (!any_added || final.size >= max_items) end final end def get_display_activities(acts_array, max_items=12) acts_by_user = acts_array.group_by {|a| a.user} sorted_users = acts_by_user.keys.sort_by {|u| u.screen_name} a_of_a = [] sorted_users.each do |u| a_of_a << acts_by_user[u].sort_by { rand } end interleave_arrays(a_of_a, max_items) end end
require 'events/base' module Events class FileImportCreated < Base has_targets :workspace, :dataset has_activities :actor, :workspace, :dataset has_additional_data :file_name, :import_type, :destination_table end end
# frozen_string_literal: true module Users class List < Actor output :list, type: Enumerable def call self.list = User.all end end end
module IuguBase extend ActiveSupport::Concern included do attr_reader :charge end def perform if orders && charge! && success? finish_purchase else invoice.cancel end success? end def redirect_path if success? [Rails.application.routes.url_helpers.checkout_success_path(purchase.invoice_id), flash: { notice: "Compra realizada com sucesso!" }] else [Rails.application.routes.url_helpers.checkout_path, flash: { charge_messages: charge.try(:message) || 'Verifique os dados digitados' } ] end end private def items @items ||= purchase.orders.map do |order| { description: order.offer.title, quantity: order.quantity, price_cents: (order.offer_value*100).to_i } end << { description: 'Taxa da transação', quantity: 1, price_cents: (taxes*100).to_i } end def charge! @charge ||= Iugu::Charge.create(charge_param.merge({ invoice_id: invoice.id, payer: payer })) end def payer { cpf_cnpj: user.cpf.gsub(/[\.-]/, ''), name: user.name, email: user.email, phone_prefix: user.phone.first(2), phone: user.phone.last(8), } end def invoice @invoice ||= Iugu::Invoice.create(due_date.merge({ email: user.email, items: items })) end def success? charge && charge.success end def save_purchase purchase.attributes = { taxes: taxes, invoice_id: invoice.id, invoice_url: invoice.secure_url, invoice_pdf: charge.pdf } purchase.save end def send_mail PurchaseMailer.pending_payment(purchase).deliver_now end end
class RemoveViewingTimeFromShow < ActiveRecord::Migration def change remove_column :shows, :viewing_time end end
# Rakefile to build a project using HUDSON require 'rake/rdoctask' require 'rake/packagetask' require 'rake/clean' require 'find' PROJ_DOC_TITLE = "The Marionette Collective" PROJ_VERSION = "0.4.7" PROJ_RELEASE = "1" PROJ_NAME = "mcollective" PROJ_RPM_NAMES = [PROJ_NAME] PROJ_FILES = ["#{PROJ_NAME}.spec", "#{PROJ_NAME}.init", "mcollectived.rb", "COPYING", "doc"] PROJ_SUBDIRS = ["etc", "lib", "plugins", "ext"] PROJ_FILES.concat(Dir.glob("mc-*")) Find.find("etc", "lib", "plugins", "ext") do |f| if FileTest.directory?(f) and f =~ /\.svn/ Find.prune else PROJ_FILES << f end end ENV["RPM_VERSION"] ? CURRENT_VERSION = ENV["RPM_VERSION"] : CURRENT_VERSION = PROJ_VERSION ENV["BUILD_NUMBER"] ? CURRENT_RELEASE = ENV["BUILD_NUMBER"] : CURRENT_RELEASE = PROJ_RELEASE CLEAN.include("build") def announce(msg='') STDERR.puts "================" STDERR.puts msg STDERR.puts "================" end def init FileUtils.mkdir("build") unless File.exist?("build") end desc "Build documentation, tar balls and rpms" task :default => [:clean, :doc, :package, :rpm] # task for building docs rd = Rake::RDocTask.new(:doc) { |rdoc| announce "Building documentation for #{CURRENT_VERSION}" rdoc.rdoc_dir = 'doc' rdoc.template = 'html' rdoc.title = "#{PROJ_DOC_TITLE} version #{CURRENT_VERSION}" rdoc.options << '--line-numbers' << '--inline-source' << '--main' << 'MCollective' } desc "Create a tarball for this release" task :package => [:clean, :doc] do announce "Creating #{PROJ_NAME}-#{CURRENT_VERSION}.tgz" FileUtils.mkdir_p("build/#{PROJ_NAME}-#{CURRENT_VERSION}") system("cp -R #{PROJ_FILES.join(' ')} build/#{PROJ_NAME}-#{CURRENT_VERSION}") system("cd build && tar --exclude .svn -cvzf #{PROJ_NAME}-#{CURRENT_VERSION}.tgz #{PROJ_NAME}-#{CURRENT_VERSION}") end desc "Tag the release in SVN" task :tag => [:rpm] do ENV["TAGS_URL"] ? TAGS_URL = ENV["TAGS_URL"] : TAGS_URL = `/usr/bin/svn info|/bin/awk '/Repository Root/ {print $3}'`.chomp + "/tags" raise("Need to specify a SVN url for tags using the TAGS_URL environment variable") unless TAGS_URL announce "Tagging the release for version #{CURRENT_VERSION}-#{CURRENT_RELEASE}" system %{svn copy -m 'Hudson adding release tag #{CURRENT_VERSION}-#{CURRENT_RELEASE}' ../#{PROJ_NAME}/ #{TAGS_URL}/#{PROJ_NAME}-#{CURRENT_VERSION}-#{CURRENT_RELEASE}} end desc "Creates a RPM" task :rpm => [:clean, :doc, :package] do announce("Building RPM for #{PROJ_NAME}-#{CURRENT_VERSION}-#{CURRENT_RELEASE}") sourcedir = `rpm --eval '%_sourcedir'`.chomp specsdir = `rpm --eval '%_specdir'`.chomp srpmsdir = `rpm --eval '%_srcrpmdir'`.chomp rpmdir = `rpm --eval '%_rpmdir'`.chomp lsbdistrel = `lsb_release -r -s | cut -d . -f1`.chomp lsbdistro = `lsb_release -i -s`.chomp case lsbdistro when 'CentOS' rpmdist = ".el#{lsbdistrel}" else rpmdist = "" end system %{cp build/#{PROJ_NAME}-#{CURRENT_VERSION}.tgz #{sourcedir}} system %{cat #{PROJ_NAME}.spec|sed -e s/%{rpm_release}/#{CURRENT_RELEASE}/g | sed -e s/%{version}/#{CURRENT_VERSION}/g > #{specsdir}/#{PROJ_NAME}.spec} system %{cd #{specsdir} && rpmbuild -D 'version #{CURRENT_VERSION}' -D 'rpm_release #{CURRENT_RELEASE}' -D 'dist #{rpmdist}' -ba #{PROJ_NAME}.spec} system %{cp #{srpmsdir}/#{PROJ_NAME}-#{CURRENT_VERSION}-#{CURRENT_RELEASE}#{rpmdist}.src.rpm build/} system %{cp #{rpmdir}/*/#{PROJ_NAME}*-#{CURRENT_VERSION}-#{CURRENT_RELEASE}#{rpmdist}.*.rpm build/} end desc "Create the .debs" task :deb => [:clean, :doc, :package] do announce("Building debian packages") File.open("ext/debian/changelog", "w") do |f| f.puts("mcollective (#{CURRENT_VERSION}-#{CURRENT_RELEASE}) unstable; urgency=low") f.puts f.puts(" * Automated release for #{CURRENT_VERSION}-#{CURRENT_RELEASE} by rake deb") f.puts f.puts(" See http://code.google.com/p/mcollective/wiki/ReleaseNotes for full details") f.puts f.puts(" -- The Marionette Collective <mcollective-dev@googlegroups.com> #{Time.new.strftime('%a, %d %b %Y %H:%M:%S %z')}") end FileUtils.mkdir_p("build/deb") Dir.chdir("build/deb") do system %{tar -xzf ../#{PROJ_NAME}-#{CURRENT_VERSION}.tgz} system %{cp ../#{PROJ_NAME}-#{CURRENT_VERSION}.tgz #{PROJ_NAME}_#{CURRENT_VERSION}.orig.tar.gz} Dir.chdir("#{PROJ_NAME}-#{CURRENT_VERSION}") do system %{cp -R ext/debian .} system %{cp -R ext/Makefile .} system %{debuild -i -us -uc -b} end system %{cp *.deb ..} end end # vi:tabstop=4:expandtab:ai
#!/usr/bin/env ruby main_file = IO.read("main.lua") app_name = Dir.pwd[ /([^\/]+)\/?$/ ] build_dir = "build" app_dir = File.join( build_dir, "#{ app_name }Build" ) app_main_file = File.join( app_dir, "main.lua" ) already_required = [] puts "Merging files" while editing = main_file[ /require\s?"/ ] main_file.gsub!( /(require\s?"(\w+)")/ ) do filename = "#{ $2 }.lua" if File.exists?( filename ) if already_required.include?( filename ) "" else already_required << filename IO.read( filename ) end else raise "Cannot find #{ filename }" end end end unless File.exists?( build_dir ) puts "Creating build/" Dir.mkdir( build_dir ) end if File.exists?( app_dir ) puts "Old build found, cleaning up..." Dir[ File.join( app_dir, "*" ) ].each do | file | puts "* removing #{ file }" File.delete( file ) end else Dir.mkdir( app_dir ) end puts "* writing #{ app_main_file }" open( app_main_file , "w+" ) do | file | file.write( main_file ) end if File.exists?( "sounds" ) puts "* copying sounds" `cp sounds/* #{ app_dir }/` end if File.exists?( "images" ) puts "* copying images" `cp images/* #{ app_dir }/` end puts "Done"
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Expose current_user method to the views helper_method :current_user helper_method :text helper_method :logged_in? private require 'csv' def read_csv csv_data = CSV.read 'test_words.csv' csv_data.to_a.flatten end def require_no_user! # redirect_to ??? unless current_user.nil? end def current_user return nil unless session[:session_token] @current_user ||= User.find_by_session_token(session[:session_token]) end def text @text_array = read_csv() end def logged_in? !current_user.nil? end def login_user!(user) session[:session_token] = user.reset_session_token! end def logout_user! current_user.reset_session_token! session[:session_token] = nil end def require_user! redirect_to new_session_url if current_user.nil? end end
require_relative './database.rb' require 'yaml/store' require 'pry' class IdeaStore extend Database def self.all ideas = [] raw_ideas.each_with_index do |data, i| ideas << Idea.new(data.merge("id" => i)) end ideas end def self.raw_ideas database.transaction do |db| db['ideas'] || [] end end def self.create(attributes) database.transaction do database['ideas'] ||= [] # SHOULD BE ABLE TO REMOVE THIS LINE database['ideas'] << attributes end end def self.delete(position) database.transaction do database['ideas'].delete_at(position) end end def self.update(id, data) old_idea = find(id) new_idea = old_idea.to_h.merge(data) database.transaction do database['ideas'][id] = new_idea end end def self.find_all_by_user_id(user_id) all.select{|idea| idea.user_id.to_i == user_id.to_i} end def self.find_all_by_group_id(rel_group_id) all.select{|idea| idea.group_id.to_i == rel_group_id.to_i} end def self.all_tags all.flat_map(&:tags).uniq end def self.find_all_by_tag(tag_string) all.select{|idea| idea.tags.include?(tag_string)} end def self.find(id) raw_idea = find_raw_idea(id) Idea.new(raw_idea.merge("id" => id)) end def self.find_raw_idea(id) database.transaction do database['ideas'].at(id) end end def self.database Database.connect end end
# == Schema Information # # Table name: project_user_links # # id :bigint(8) not null, primary key # project_id :integer # user_id :integer # created_at :datetime not null # updated_at :datetime not null # type :string # status :string # class ProjectUserLink < ApplicationRecord before_create :set_default_status belongs_to :project belongs_to :user include Status statuses :pending def self.projects Project.where(id: pluck(:project_id)) end def self.users User.where(id: pluck(:user_id)) end private def set_default_status # set status to the first status name in the list for the STI class being created self.status = self.class.status_names.first.to_s end end
require 'rails_helper' RSpec.describe User, type: :model do it "is not valid without GitHub link if user type is coach" do user = User.new(username: "johnsmith72", first_name: "John", last_name: "Smith", user_type: "coach", email: "johnsmith@codecoach.com", location: "New York, NY", password: "password") expect(user).to_not be_valid end it "is valid without GitHub link if user type is student" do user = User.new(username: "janedoe89", first_name: "Jane", last_name: "Doe", user_type: "student", email: "janed@codecoach.com", location: "Chicago, IL", password: "password") expect(user).to be_valid end it "is not valid with invalid email" do user = User.new(username: "janedoe89", first_name: "Jane", last_name: "Doe", user_type: "student", email: "janed", location: "Chicago, IL", password: "password") expect(user).to_not be_valid end it "is not valid without user type" do user = User.new(username: "janedoe89", first_name: "Jane", last_name: "Doe", email: "janed", location: "Chicago, IL", password: "password") expect(user).to_not be_valid end it "can have a coach if user type is student" do student = User.new(username: "janedoe89", first_name: "Jane", last_name: "Doe", user_type: "student", email: "janed@codecoach.com", location: "Chicago, IL", password: "password") coach = User.new(username: "johnsmith72", first_name: "John", last_name: "Smith", user_type: "coach", email: "johnsmith@codecoach.com", github_link: "github.com/johnsmith", location: "New York, NY", password: "password") student.coach = coach coach.student = student expect(student.coach).to eq(coach) expect(coach.student).to eq(student) end it "has resources" do user = User.new(username: "johnsmith72", first_name: "John", last_name: "Smith", user_type: "coach", email: "johnsmith@codecoach.com", github_link: "github.com/johnsmith", location: "New York, NY", password: "password") lang = Language.new(name: "Ruby") first_resource = Resource.new(title: "Intro to Ruby", language: lang) second_resource = Resource.new(title: "Classes: Strings", language: lang) user.resources << first_resource user.resources << second_resource expect(user.resources).to eq([first_resource, second_resource]) end it "has many languages" do first_lang = Language.new(name: "JavaScript") second_lang = Language.new(name: "Ruby") first_user = User.new(first_name: "John", last_name: "Smith") first_user.languages << first_lang first_user.languages << second_lang expect(first_user.languages).to eq([first_lang, second_lang]) end end
class User < ApplicationRecord mount_uploader :photo, PhotoUploader devise :database_authenticatable devise :omniauthable, :omniauth_providers => [:github,:twitter] has_many :papers has_many :reviews has_many :user_activity_relationships has_many :activities, through: :user_activity_relationships has_many :comments validates_presence_of :name def self.as_yaml(options = {}) result = all.map { |item| item.as_json(options) } result = {"#{model_name.plural}" => result} if options[:include_root] result.to_yaml end def self.from_omniauth(auth) where(uid: auth.uid, provider: auth.provider).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.password = Devise.friendly_token[0,20] user.email = auth.info.email user.name = auth.info.name # assuming the user model has a name user.github_username = auth.info.nickname if user.provider == "github" # for github user.photo = auth.info.image end end def self.new_with_session(params, session) super.tap do |user| if data = session["devise.github_data"] && session["devise.github_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? elsif data = session["devise.twitter_data"] && session["devise.twitter_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? end end end def self.update_github_username User.where(provider: "github", github_username: nil).each {|user| user.update_github_username} end def update_github_username url = "https://api.github.com/user/#{self.uid}" user_data = JSON.parse(open(url).read) update(github_username: user_data["login"]) rescue logger.error "Cannot update github username for uid = #{self.id}" end def github_link_text self.github_username.nil? ? "(Not yet updated)" : self.github_username end def github_url self.github_username.present? ? "https://github.com/#{self.github_username}" : "" end def full_name if firstname.present? && lastname.present? "#{firstname} #{lastname}" else name end end def twitter_url if twitter.present? if twitter =~ /https?:\/\/twitter\.com/i twitter else "https://twitter.com/#{twitter.gsub("@","")}" end else "" end end def title_with_company @title_with_company ||= [self.title, self.company].select{|x| x.present?}.join(", ") end def as_json(options = {}) hostname = options[:hostname] result_hash = { name: full_name, avatar: full_avatar_url(hostname), title: title_with_company, urlGithub: github_url, urltwitter: twitter_url, } result_hash.stringify_keys! # remove unused while space characters result_hash.each do |key, value| result_hash[key] = value.gsub(/(\s*)\n(\s*)/,"\n") if value end end def full_avatar_url(hostname = "") if photo.present? "//#{hostname}#{photo.url}" else "//avatars.githubusercontent.com/u/#{uid}?v=3" end end end
#Copied it from http://code.google.com/p/gstreamer-java/wiki/VideoTestTutorial load '../lib/jruby_gst.rb' import javax.swing.JFrame import java.awt.BorderLayout import java.awt.Dimension class VideoTest def initialize(args = []) args = Gst.init("VideoTest", args) pipe = Gst::Pipeline.new("VideoTest") videosrc = Gst::ElementFactory.make("videotestsrc", "source") videofilter = Gst::ElementFactory.make("capsfilter", "filter") videofilter.set_caps(Gst::Caps.from_string("video/x-raw-yuv, width=720, height=576" \ + ", bpp=32, depth=32, framerate=25/1")) javax.swing.SwingUtilities.invokeLater Proc.new { videoComponent = Gst::Swing::VideoComponent.new videosink = videoComponent.get_element pipe.add(videosrc, videofilter, videosink) Gst::Element.link_many(videosrc, videofilter, videosink) #Now create a JFrame to display the video output frame = JFrame.new("Swing Video Test") frame.set_default_close_operation(JFrame::EXIT_ON_CLOSE) frame.add(videoComponent.java_videocomponent, BorderLayout::CENTER) videoComponent.java_videocomponent.set_preferred_size(Dimension.new(720, 576)) frame.pack() frame.setVisible(true) #Start the pipeline processing pipe.state = Gst::State::PLAYING } end end VideoTest.new(ARGV)
module SerializeAndSymbolize extend ActiveSupport::Concern module ClassMethods def serialize_and_symbolize(*column_names) column_names.flatten.uniq.compact.map(&:to_sym).each do |column_name| setup_name = "setup_#{column_name}".to_sym symbolize_name = "symbolize_#{column_name}".to_sym validate_name = "validate_#{column_name}".to_sym serialize column_name after_initialize setup_name before_validation symbolize_name before_save symbolize_name validate validate_name class_eval <<-RUBY def #{setup_name} self[:#{column_name}] ||= {} end def #{validate_name} # Implement me in your subclass. end def #{symbolize_name} self.#{column_name} = self[:#{column_name}] end def #{column_name}=(data) if data.is_a?(String) self[:#{column_name}] = JSON.parse(data).recursively_symbolize_keys rescue {} elsif data.is_a?(Hash) self[:#{column_name}] = data.recursively_symbolize_keys else self[:#{column_name}] = data end end RUBY end end end end
class Driver < ActiveRecord::Base belongs_to :constructor has_many :finishing_positions has_many :races, through: :finishing_positions def name "#{first_name} #{second_name}" end def increase_skill(skill_points) self.skill_factor += skill_points end def self.reset_drivers_to_teams Driver.all.each do |d| if d.id > 16 elsif d.id.even? new_id = d.id / 2 new_constructor = Constructor.find_by(id: new_id) new_constructor.drivers << d else new_id = ((d.id / 2.0).to_f + 0.5).to_i new_constructor = Constructor.find_by(id: new_id) new_constructor.drivers << d end end end end
class AddConsultantsAndProjectTypeToProjects < ActiveRecord::Migration[5.1] def change add_column :projects, :consultants, :text add_column :projects, :project_type, :text end end
class AddPublishDateToDistributions < ActiveRecord::Migration def change add_column :distributions, :publish_date, :datetime end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :payment do amount "9.99" customer nil notes "MyText" payment_method "MyString" reference "MyString" end end
class TeamMailer < ApplicationMailer def team_mail(user) mail to: user.email, subject: "あなたにチームの権限が渡されました。" end end
class BuysController < ApplicationController before_action :set_buy, only: [:index, :create] before_action :sort def index @item_buy = ItemBuy.new end def create @item_buy = ItemBuy.new(buy_params) if @item_buy.valid? pay_item @item_buy.save redirect_to items_path else render action: :index end end private def buy_params params.require(:item_buy).permit(:postal_code, :prefecture_id, :municipality, :house_number, :building_name, :phone_number).merge(user_id: current_user.id, item_id: @item.id, token: params[:token]) end def pay_item Payjp.api_key = ENV['PAYJP_SECRET_KEY'] Payjp::Charge.create( amount: @item.price, card: buy_params[:token], currency: 'jpy' ) end def set_buy @item = Item.find(params[:item_id]) end def sort @item = Item.find(params[:item_id]) unless user_signed_in? && current_user.id != @item.user_id && @item.buy == nil redirect_to items_path end end end
class GamesController < ApplicationController before_action :set_api before_action :set_game, only: [:edit, :show, :update] def index @games = @game_api.get_all_games end def new @game = {} end def show # tried to show a game that doesn't exist if @game[:error] == GameApi::ERRORS[:NOT_FOUND] redirect_to games_url, flash: {error: @game[:error]} end end def edit # tried to edit a game that doesn't exist if @game[:error] == GameApi::ERRORS[:NOT_FOUND] redirect_to games_url, flash: {error: @game[:error]} end end def create title = params[:title] new_game = @game_api.create(game_params) if new_game[:error] # Invalid Save so we send them back the 'new' page w/ error msg flash[:error] = new_game[:error] render :new else redirect_to games_url, notice: "Game: '#{title}' successfully created." end end def update title = params[:title] updated = @game_api.update(game_params) if updated[:error] # Invalid Update so we send them back the 'edit' page w/ error msg flash[:error] = updated[:error] render :edit else redirect_to games_url, notice: "Game: '#{title}' successfully updated." end end def destroy @game_api.remove(params[:id]) redirect_to games_url, notice: 'Game was successfully deleted.' end def search if params[:title].blank? redirect_to games_url else search_params = {title: params[:title], category_id: params[:category_id]} @games = @game_api.search_for(search_params) render :index end end private def set_api @game_api = GameApi.new end def set_game @game = @game_api.get_game(params[:id]) end def game_params params.permit(:id, :category_id, :title, :description, :author, :status) end end
class AddDateTimeSetToAppointments < ActiveRecord::Migration def change add_column :appointments, :proposed_date, :date add_column :appointments, :proposed_time, :time add_column :appointments, :picked, :boolean add_column :appointments, :property_id, :integer add_column :appointments, :pushed_out, :boolean end end
class Admin::UsersController < ApplicationController before_action :authenticate_user! #layout "administration" def index @users = User.all end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) # TODO rechercher les roles pour l'utilisateur # TODO les trier en roles, ownership et permissions end def update @user = User.find(params[:id]) # remove roles to an user #bad_roles = user_params[:role_ids].to_set.difference(@user.roles.to_set) # add new roles to an user new_roles = user_params[:role_ids].to_set.intersection(["guest", "generic", "user", "administrator", "webmaster"]) new_roles.each do |role| @user.add_role(role) end if @user.save redirect_to admin_users_path else render 'edit' end end def destroy @user = User.find(params[:id]) @user.destroy redirect_to admin_users_path end private def user_params params.require(:user).permit(:role_ids => []) end end
source "https://rubygems.org" # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: # # bundle exec jekyll serve # gem "github-pages", group: :jekyll_plugins gem "jekyll-include-cache" gem "jekyll-remote-theme" gem 'faraday', '0.17.3' gem "jekyll", "~> 3.8.5" # Performance-booster for watching directories on Windows gem "wdm", "~> 0.1.1", :install_if => Gem.win_platform?
class WhitelistsController < ApplicationController load_and_authorize_resource :callthrough load_and_authorize_resource :whitelist, :through => [:callthrough] before_filter :set_parent_and_path_methods before_filter :spread_breadcrumbs def index end def show end def new @whitelist.phone_numbers.build end def create @whitelist = @parent.whitelists.build(params[:whitelist]) if @whitelist.save redirect_to @show_path_method.(@parent, @whitelist), :notice => t('whitelists.controller.successfuly_created') else render :new end end def edit end def update if @whitelist.update_attributes(params[:whitelist]) redirect_to @show_path_method.(@parent, @whitelist), :notice => t('whitelists.controller.successfuly_updated') else render :edit end end def destroy @whitelist.destroy redirect_to @index_path_method.(@parent), :notice => t('whitelists.controller.successfuly_destroyed') end private def set_parent_and_path_methods @parent = @callthrough @show_path_method = method( :"#{@parent.class.name.underscore}_whitelist_path" ) @index_path_method = method( :"#{@parent.class.name.underscore}_whitelists_path" ) @new_path_method = method( :"new_#{@parent.class.name.underscore}_whitelist_path" ) @edit_path_method = method( :"edit_#{@parent.class.name.underscore}_whitelist_path" ) end def spread_breadcrumbs if @parent && @parent.class == Callthrough add_breadcrumb t("#{@parent.class.name.underscore.pluralize}.name").pluralize, tenant_callthroughs_path(@parent.tenant) add_breadcrumb @callthrough, tenant_callthrough_path(@parent.tenant, @callthrough) add_breadcrumb t("whitelists.index.page_title"), callthrough_whitelists_path(@parent) end end end
# frozen_string_literal: true require 'net/ldap' module LdapQuery # For establishing an LDAP connection (binding LDAP connection) class Connection attr_accessor :link REQUIRED_KEYS = %i[host port base auth].freeze # Used for creating the initial Ldap connection for querying with supplied parameters # # @param credentials [Hash] # @return [Interface <Net::Ldap>] def initialize(credentials, type: :basic) if type == :auth credentials = filter_auth_credentials(credentials) else valid_credentials?(credentials) end @link = bind_connection(credentials) end private # Filter out all parameter keyus/values and only keep the required auth keys # # @param credentials [Hash] # @return [Hash] def filter_auth_credentials(credentials) auth_keys = %i[host port encryption].freeze credentials.select { |key, _v| auth_keys.include?(key) }.freeze end # Validate all required keys have been included # # @param credentials [Hash] # @return [Hash] def valid_credentials?(credentials) credentials_error if !credentials.is_a?(Hash) || credentials.empty? required_credentials?(credentials) end # Validate all required auth credentials have been supplied # # @param credentials [Hash] # @return [Hash] def required_credentials?(credentials = {}) credentials_error unless REQUIRED_KEYS.all? { |k| credentials[k] } end # Raise an exception error if not all LDAP credentials have been included def credentials_error raise(CredentialsError, 'valid ldap credentials must be passed in order to establish a connection') end # Create LDAP connection string # # @params credentials [Hash] # @return [Interface <Net::Ldap>] def bind_connection(credentials) Net::LDAP.new(credentials) rescue raise(ConnectionError, 'Failure connecting to LDAP host') end end end
print "Enter Grade Point: " grade = gets.chomp.to_i result = case grade when 90..100 then "Letter Grade A" when 80...90 then "Letter Grade B" when 70...80 then "Letter Grade C" when 60...70 then "Letter Grade D" when 50...60 then "Letter Grade E" when 0...50 then "Letter Grade F" else "invalid input" end puts result
require 'minarai/actions/base' module Minarai module Actions class Rbenv < Base attribute :version, required: true, type: String attribute :global, type: [TrueClass, FalseClass], default: true def run install_specific_ruby_version unless has_specific_ruby_version? set_global_ruby_version unless set_specific_ruby_version? end private def install_specific_ruby_version run_command "rbenv install #{version}" end def complete? has_rbenv? && has_specific_ruby_version? && set_specific_ruby_version? end def has_rbenv? check_command 'which rbenv' end def has_specific_ruby_version? check_command "rbenv prefix #{version}" end def set_valid_glbal_ruby_version? global_version == version end def global_version run_command('rbenv global').stdout.rstrip end def set_specific_ruby_version? check_command "rbenv global #{version}" end def name super || "rbenv install ruby version #{version}" end end end end
class Statement4 def initialize(date) @cheryl = Cheryl.new @bernard = Person.new @date = date.is_a?(DateObject) ? date : DateObject.new(date) end def valid? not bernard.know(at_first) and bernard.know(dates_for_statement3_is_true) end private attr_reader :cheryl, :bernard, :date def at_first cheryl.tell(date.day) end def dates_for_statement3_is_true at_first.select { |date| Statement3.new(date).valid? } end end
require 'rails_helper' RSpec.describe User, type: :model do describe 'users validates' do let(:user) { create(:user) } let(:other_user) { create(:user) } let(:user_search) { User.search(other_user.name, 1) } it 'validationが全て通れば、有効' do expect(user).to be_valid end it '名前がなければ、無効' do user.name = '' expect(user).not_to be_valid end it '名前は、30文字以内でなければ無効' do user.name = 'a' * 31 expect(user).not_to be_valid end it 'メールアドレスがなければ、無効' do user.email = '' expect(user).not_to be_valid end it 'メールアドレスは、255文字以内でなければ無効' do user.email = 'a' * 256 expect(user).not_to be_valid end it 'メールアドレスは、一意でなければ無効' do other_user.email = 'n@gmail.com' other_user.save user.email = 'n@gmail.com' expect(user).not_to be_valid end it 'プロフィールは, 140文字以内でなければ無効' do user.profile = 'a' * 141 expect(user).not_to be_valid end it '他のユーザーをフォローすることができる' do user.follow(other_user) expect(user.following?(other_user)).to be_truthy end it '他のユーザーをフォロー解除することができる' do user.follow(other_user) expect(user.following.count).to eq 1 user.unfollow(other_user) expect(user.following.count).to eq 0 end it 'user検索ができる' do user_search.each do |user| expect(user.name).to eq other_user.name end end it 'guest userを取ってくる' do guest_user = create(:user, email: 'ta1.pioneer.t@gmail.com') expect(User.guest).to eq guest_user end end end
module PodStatic TARGET_SUPPORT_FILE_PATH = 'Pods/Target Support Files/' XCCONFIG_FILE_EXTENSION = 'xcconfig' LIBRARY_SEARCH_PATH_KEY = 'LIBRARY_SEARCH_PATHS' FRAMEWORK_SEARCH_PATH_KEY = 'FRAMEWORK_SEARCH_PATHS' OTHER_CFLAGS_KEY = 'OTHER_CFLAGS' STATIC_LIBRARY_DIR = 'Static' PODS_ROOT = '${PODS_ROOT}' DEFAULT_LIBRARY_DIR = '\${PODS_CONFIGURATION_BUILD_DIR}' PODS_ROOT_DIR = 'Pods' PRODUCT_TYPE_FRAMEWORK = 'com.apple.product-type.framework' VALID_ARCHS_KEY = 'VALID_ARCHS' FS = File::SEPARATOR LIB_DEBUG = "Debug" LIB_RELEASE = "Release" LIBS = [LIB_DEBUG, LIB_RELEASE] $_SKIP_LIBS = [] $_CONFIG_MAPPINGS = {} $_ENABLE_STATIC_LIB = ENV['ENABLE_STATIC_LIB'] $_FORCE_BUILD = ENV['FORCE_BUILD'] $_SIMULATOR_SUPPORT = false $_AUTO_VALID_ARCHS = false $_DEFAULT_ARCHS = "armv7 armv7s arm64 arm64e" # $_DEFAULT_SIMULATOR_ARCHS = "i386 x86_64" $_DEFAULT_SIMULATOR_ARCHS = "x86_64" $_USE_FRAMEWORKS = false def PodStatic.targetLibPath(configName) return PODS_ROOT + FS + STATIC_LIBRARY_DIR + FS + configName end def PodStatic.updateConfig(path, configName, libs) targetConfig = PodStatic.validConfigName(configName) Pod::UI.message "- PodStatic: updateConfig --->>> " + configName + "[" + targetConfig + "]" config = Xcodeproj::Config.new(path) lib_search_path = config.attributes[LIBRARY_SEARCH_PATH_KEY] libRegex = libs.join('|') new_lib_search_path = lib_search_path.gsub!(/#{DEFAULT_LIBRARY_DIR}\/(#{libRegex})/) { |str| str.gsub!(/#{DEFAULT_LIBRARY_DIR}/, PodStatic.targetLibPath(targetConfig)) } config.attributes[LIBRARY_SEARCH_PATH_KEY] = new_lib_search_path config.save_as(Pathname.new(path)) end def PodStatic.updateFrameConfig(path, configName, libs) targetConfig = PodStatic.validConfigName(configName) Pod::UI.message "- PodStatic: updateFrameConfig --->>> " + configName + "[" + targetConfig + "]" config = Xcodeproj::Config.new(path) framework_search_path = config.attributes[FRAMEWORK_SEARCH_PATH_KEY] libRegex = libs.join('|') new_framework_search_path = framework_search_path.gsub(/#{DEFAULT_LIBRARY_DIR}\/(#{libRegex})/) { |str| str.gsub(/#{DEFAULT_LIBRARY_DIR}/, PodStatic.targetLibPath(targetConfig)) } config.attributes[FRAMEWORK_SEARCH_PATH_KEY] = new_framework_search_path other_cflags = config.attributes[OTHER_CFLAGS_KEY] new_other_cflags = other_cflags.gsub(/#{DEFAULT_LIBRARY_DIR}\/(#{libRegex})/) { |str| str.gsub(/#{DEFAULT_LIBRARY_DIR}/, PodStatic.targetLibPath(targetConfig)) } config.attributes[OTHER_CFLAGS_KEY] = new_other_cflags config.save_as(Pathname.new(path)) end def PodStatic.updateEmbedFrameworkScript(path, configs, libs) embed_framework_script = "" libRegex = libs.join('|') configName = "" File.open(path, 'r').each_line do |line| configs.each do |config| line.gsub(/"\$CONFIGURATION" == "(#{config.name})"/) { configName = config.name } end embed_framework_script += line.gsub(/install_framework \"\${BUILT_PRODUCTS_DIR}\/(#{libRegex})/) { |str| str.gsub(/\${BUILT_PRODUCTS_DIR}/, PodStatic.targetLibPath(PodStatic.validConfigName(configName))) } end File.open(path, "w") { |io| io.write(embed_framework_script) } end def PodStatic.validConfigName(configName) if !(LIBS.include?(configName)) if $_CONFIG_MAPPINGS[configName] return $_CONFIG_MAPPINGS[configName] end return LIB_RELEASE end return configName end def PodStatic.updateXCConfig(target, libs) targetName = target.name Pod::UI.message "- PodStatic: Updating #{targetName} xcconfig files" configs = target.build_configurations configs.each do |config| configName = config.name configPath = TARGET_SUPPORT_FILE_PATH + targetName + FS + targetName + '.' + configName.downcase + '.' + XCCONFIG_FILE_EXTENSION if target.product_type == PRODUCT_TYPE_FRAMEWORK updateFrameConfig(configPath, configName, libs) else updateConfig(configPath, configName, libs) end end if target.product_type == PRODUCT_TYPE_FRAMEWORK embed_framework_script_path = TARGET_SUPPORT_FILE_PATH + targetName + FS + targetName + '-frameworks.sh' Pod::UI.message "- PodStatic: Updating embed framework script" updateEmbedFrameworkScript(embed_framework_script_path, configs, libs) end end def PodStatic.findProjectTarget(project, libs) podTargets = [] project.targets.each do |target| if (target.name.start_with?('Pods-')) podTargets.push(target) end end return podTargets end def PodStatic.updatePodProject(project, libs) if libs.length >0 Pod::UI.message "- PodStatic: Deleting dependencies on #{libs.join(', ')}" podTargets = PodStatic.findProjectTarget(project, libs) podTargets.each do |target| target.dependencies.delete_if { |dependency| libs.include?(dependency.name) } updateXCConfig(target, libs) end end end def PodStatic.buildLibs(installer, libs) project = installer.pods_project if libs.length > 0 Pod::HooksManager.register('cocoapods-stats', :post_install) do |context, _| startTime1 = Time.new.to_i * 1000; Dir.chdir(PODS_ROOT_DIR){ libs.each do |lib| startTime = Time.new.to_i * 1000; Pod::UI.message "- PodStatic: Building #{lib} ..." LIBS.each do |type| PodStatic.buildTypeLib(project, lib, libs, type) end endTime = Time.new.to_i * 1000 - startTime; Pod::UI.message "- PodStatic: Building #{lib} Time #{endTime}ms" end } Pod::UI.message "- PodStatic: Removing derived files" `rm -rf build` endTime1 = Time.new.to_i * 1000 - startTime1; Pod::UI.warn "- PodStatic: All time #{endTime1}ms" end end end def PodStatic.currentArchs(project, libs) return if $_AUTO_VALID_ARCHS podTargets = PodStatic.findProjectTarget(project, libs) podTargets.each do |target| targetName = target.name target.build_configurations.each do |config| configName = config.name path = TARGET_SUPPORT_FILE_PATH + targetName + FS + targetName + '.' + configName.downcase + '.' + XCCONFIG_FILE_EXTENSION puts "---->>>>>>>1 " + path # _config = Xcodeproj::Config.new(path) _validArchs = config.build_settings[VALID_ARCHS_KEY] if _validArchs $_DEFAULT_ARCHS = _validArchs puts "---->>>>>>>2 " + _validArchs else puts "---->>>>>>>3 no " end end end # puts "---->>>>>>>1 " + project.build_configuration_list.get_setting('VALID_ARCHS').to_s # targetName = podTarget.name # podTarget.build_configurations.each do |config| # configName = config.name # path = TARGET_SUPPORT_FILE_PATH + targetName + FS + targetName + '.' + configName.downcase + '.' + XCCONFIG_FILE_EXTENSION # puts "---->>>>>>>1 " + path # # _config = Xcodeproj::Config.new(path) # _validArchs = config.build_settings[VALID_ARCHS_KEY] # if _validArchs # $_DEFAULT_ARCHS = _validArchs # puts "---->>>>>>>2 " + _validArchs # else # puts "---->>>>>>>3 no " # end # end # project.targets.each do |target| # target.build_configurations.each do |config| # _validArchs = config.build_settings[VALID_ARCHS_KEY] # if _validArchs # $_DEFAULT_ARCHS = _validArchs # puts "---->>>>>>>2 " + _validArchs # else # puts "---->>>>>>>3 no " # end # end # end end end def PodStatic.staticExist(project, lib, libs, type, build_dir, isFramework) matchArch = false matchSimulatorkArch = false libPath1 = build_dir + FS + "lib" + lib + ".a" libPath2 = build_dir + FS + lib + ".framework" + FS + lib if File.exist?(libPath1) && File.exist?(libPath2) # cleaning dirt Pod::UI.message "- PodStatic: Cleaning dirt path, #{libPath1}, #{libPath2}, #{build_dir}" `rm -rf #{libPath1}` `rm -rf #{libPath2}` `rm -rf #{build_dir}` return false end libPath = isFramework ? libPath2 : libPath1 if File.exist?(libPath) archs = `lipo -info #{libPath}` archs = archs.delete!("\n").split(/: /)[2].split(/ /) archs.each do |arch| $_DEFAULT_ARCHS.split(" ").each do |ac| if arch == ac matchArch = true end end if $_SIMULATOR_SUPPORT $_DEFAULT_SIMULATOR_ARCHS.split(" ").each do |ac2| if arch == ac2 matchSimulatorkArch = true end end end end end if !$_SIMULATOR_SUPPORT return matchArch else return matchArch && matchSimulatorkArch end end def PodStatic.buildTypeLib(project, lib, libs, type) build_dir = STATIC_LIBRARY_DIR + FS + type + FS + lib # `xcodebuild clean -scheme #{lib}` # `xcodebuild -scheme #{lib} -configuration #{type} build CONFIGURATION_BUILD_DIR=#{build_dir} VALID_ARCHS="armv7 armv7s arm64" ONLY_ACTIVE_ARCH=NO` # `rm -rf #{build_dir + FS + '*.h'}` # return #xcodebuild -project ${xcode_project_path} -target ${target_name} ONLY_ACTIVE_ARCH=NO -configuration ${configuration} clean build -sdk iphoneos -arch "armv7" VALID_ARCHS="armv7 armv7s arm64" BUILD_DIR="${output_folder}/armv7" #xcodebuild -project ${xcode_project_path} -target ${target_name} ONLY_ACTIVE_ARCH=NO -configuration ${configuration} clean build -sdk iphoneos -arch "armv7s" VALID_ARCHS="armv7 armv7s arm64" BUILD_DIR="${output_folder}/armv7s" #xcodebuild -project ${xcode_project_path} -target ${target_name} ONLY_ACTIVE_ARCH=NO -configuration ${configuration} clean build -sdk iphoneos -arch "arm64" VALID_ARCHS="armv7 armv7s arm64" BUILD_DIR="${output_folder}/arm64" #xcodebuild -project ${xcode_project_path} -target ${target_name} ONLY_ACTIVE_ARCH=NO -configuration ${configuration} clean build -sdk iphonesimulator -arch "i386" VALID_ARCHS="i386 x86_64" BUILD_DIR="${output_folder}/i386" #xcodebuild -project ${xcode_project_path} -target ${target_name} ONLY_ACTIVE_ARCH=NO -configuration ${configuration} clean build -sdk iphonesimulator -arch "x86_64" VALID_ARCHS="i386 x86_64" BUILD_DIR="${output_folder}/x86_64" matchLibArch = !$_USE_FRAMEWORKS ? PodStatic.staticExist(project, lib, libs, type, build_dir, false) : false matchFrameworkArch = PodStatic.staticExist(project, lib, libs, type, build_dir, true) if !$_FORCE_BUILD if matchLibArch || matchFrameworkArch Pod::UI.message "- PodStatic: Building #{lib} [#{type}] [#{PODS_ROOT_DIR}#{FS}#{build_dir}] exist and match!" return end end validArchs = $_DEFAULT_ARCHS if !$_SIMULATOR_SUPPORT Pod::UI.message "- PodStatic: Building #{lib} [iphoneos] [#{type}] [#{PODS_ROOT_DIR}#{FS}#{build_dir}]" `xcodebuild clean -scheme #{lib}` `xcodebuild -scheme #{lib} ONLY_ACTIVE_ARCH=NO -configuration #{type} clean build -sdk iphoneos VALID_ARCHS="#{validArchs}" CONFIGURATION_BUILD_DIR=#{build_dir}` `rm -rf #{build_dir + FS + '*.h'}` return end iphoneos_dir = build_dir + FS + "iphoneos" Pod::UI.message "- PodStatic: Building #{lib} [iphoneos] [#{type}] [#{PODS_ROOT_DIR}#{FS}#{iphoneos_dir}]" `xcodebuild clean -scheme #{lib}` `xcodebuild -scheme #{lib} ONLY_ACTIVE_ARCH=NO -configuration #{type} clean build -sdk iphoneos ARCHS="#{validArchs}" VALID_ARCHS="armv7 armv7s arm64" CONFIGURATION_BUILD_DIR=#{iphoneos_dir}` # single one pack # `xcodebuild -scheme #{lib} ONLY_ACTIVE_ARCH=NO -configuration #{type} clean build -sdk iphoneos -arch "armv7s" VALID_ARCHS="armv7 armv7s arm64" CONFIGURATION_BUILD_DIR=#{iphoneos_dir}` validSimulatorArchs = $_DEFAULT_SIMULATOR_ARCHS iphonesimulator_dir = build_dir + FS + "iphonesimulator" Pod::UI.message "- PodStatic: Building #{lib} [iphonesimulator] [#{type}] [#{PODS_ROOT_DIR}#{FS}#{iphonesimulator_dir}]" `xcodebuild clean -scheme #{lib}` `xcodebuild -scheme #{lib} ONLY_ACTIVE_ARCH=NO -configuration #{type} clean build -sdk iphonesimulator VALID_ARCHS="#{validSimulatorArchs}" CONFIGURATION_BUILD_DIR=#{iphonesimulator_dir}` if File.directory? iphoneos_dir and File.directory? iphonesimulator_dir Dir.foreach(iphoneos_dir) do |file| if file !="." and file !=".." if file.end_with?('.framework') lib_name = file.gsub(/\.framework/) { |str| str.gsub!(/\.framework/, "") } targe_lib = iphoneos_dir + FS + file iphoneos_lib = iphoneos_dir + FS + file + FS + lib_name iphonesimulator_lib = iphonesimulator_dir + FS + file + FS + lib_name `lipo -create -output #{iphoneos_lib} #{iphoneos_lib} #{iphonesimulator_lib}` `cp -R #{targe_lib} #{build_dir}` elsif file.end_with?('.a') targe_lib = build_dir + FS + file iphoneos_lib = iphoneos_dir + FS + file iphonesimulator_lib = iphonesimulator_dir + FS + file `lipo -create -output #{targe_lib} #{iphoneos_lib} #{iphonesimulator_lib}` end end end else STDERR.puts "[!] iphoneos_dir[#{PODS_ROOT_DIR}#{FS}#{iphoneos_dir}] or iphonesimulator_dir[#{PODS_ROOT_DIR}#{FS}#{iphonesimulator_dir}] or is not exist.".red end `rm -rf #{iphoneos_dir}` `rm -rf #{iphonesimulator_dir}` `rm -rf #{build_dir + FS + '*.h'}` end def PodStatic.libsNeedBuild(installer, libs) changedLibs = libs sandbox_state = installer.analysis_result.sandbox_state deletedList = sandbox_state.deleted if deletedList.size > 0 deletedList.each do |lib| if deletedList.include?(lib) PodStatic.deleteLibFile(installer, lib) changedLibs.delete(lib) end end end changedList = sandbox_state.changed if changedList.size > 0 changedList.each do |lib| if changedList.include?(lib) PodStatic.deleteLibFile(installer, lib) end end end if !$_FORCE_BUILD targetMap = Hash.new installer.pods_project.targets.each do |target| targetMap[target.name] = target end unchangedLibs = sandbox_state.unchanged if unchangedLibs.size > 0 changedLibs = changedLibs.select { |lib| target = targetMap[lib] if target libName = target.product_type == PRODUCT_TYPE_FRAMEWORK ? lib + '.framework' : 'lib' + lib + '.a' !unchangedLibs.include?(lib) || !File.exist?(PODS_ROOT_DIR + FS + STATIC_LIBRARY_DIR + FS + lib + FS + libName) else Pod::UI.message "- PodStatic: Skip #{lib}" $_SKIP_LIBS.push(lib) end } end end cleanLibs = changedLibs cleanLibs.each do |lib| $_SKIP_LIBS.each do |lib1| if lib == lib1 changedLibs.delete(lib) end end end changedLibs end def PodStatic.deleteLibFile(installer, lib) #version = PodStatic.libVersion(installer, lib) # version changed, clear cache ... LIBS.each do |type| build_dir = PODS_ROOT_DIR + FS+ STATIC_LIBRARY_DIR + FS + type + FS + lib Pod::UI.message "- PodStatic: Cleaning dirt path, #{lib} [#{build_dir}]" `rm -rf #{build_dir}` end end def PodStatic.deleteLibs(installer) toDeleted = installer.analysis_result.podfile_state.deleted if toDeleted.size > 0 Dir.chdir(PODS_ROOT_DIR){ toDeleted.each do |lib| Pod::UI.message "- PodStatic: Deleting #{lib}" `rm -rf #{STATIC_LIBRARY_DIR + FS + lib}` end } end end def PodStatic.libVersion(installer, lib) version = "" root_specs = installer.analysis_result.specifications.map(&:root).uniq root_specs.sort_by(&:name).each do |spec| #Pod::UI.message "- PodStatic:libVersion #{spec.name} #{spec.version} " if spec.name == lib version = spec.version end end version end def PodStatic.configMapping(mappings) $_CONFIG_MAPPINGS = mappings end def PodStatic.forceBuild(t) $_FORCE_BUILD = t end def PodStatic.enableStaticLib(t) $_ENABLE_STATIC_LIB = t end def PodStatic.simulatorSupport(t) $_SIMULATOR_SUPPORT = t end def PodStatic.autoValidArchs(t) $_AUTO_VALID_ARCHS = t end def PodStatic.userArchs(s) if s $_DEFAULT_ARCHS = s end end def PodStatic.useFrameworks(t) $_USE_FRAMEWORKS = t end def PodStatic.run(installer, libs) if $_ENABLE_STATIC_LIB deleteLibs(installer) project = installer.pods_project libs = libsNeedBuild(installer, libs) currentArchs(project, libs) buildLibs(installer, libs) updatePodProject(project, libs) end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # Default User Details user_types = [ {name: 'admin'}, {name: 'agent'}, {name: 'customer'} ] user_types.each do |user_type| UserType.where(user_type).first_or_create end unless Rails.env.test? admin = UserType.find_by(name: 'admin') agent = UserType.find_by(name: 'agent') customer = UserType.find_by(name: 'customer') users = [ {email: 'admin@gmail.com', name: 'Admin', password: 'admin@123456', password_confirmation: 'admin@123456', user_type_id: admin.id}, {email: 'agent@gmail.com', name: 'Agent', password: 'agent@123456', password_confirmation: 'agent@123456', user_type_id: agent.id}, {email: 'customer@gmail.com', name: 'Customer', password: 'customer@123456', password_confirmation: 'customer@123456', user_type_id: customer.id} ] users.each do |user| User.where(email: user[:email]).first_or_create.update(user) end end # Default Ticket Details all_states = ['new', 'inprogress', 'close', 'delete'] all_states.each do |state| State.where(name: state).first_or_create end unless Rails.env.test? customer = Customer.first State.all.each do |state| state_id = state.id tickets = { customer_id: customer.id, name: "Test Ticket #{state_id}", description: "Test Ticket #{state_id} Description", state_id: state_id } Ticket.where(tickets).first_or_create end end
module FigRake class Command attr_accessor :container_name, :rake_args, :command def initialize(command, container_name, rake_args) @command, @container_name, @rake_args = command, container_name, rake_args end def exec p "fig run --rm --entrypoint=#{command} #{container_name} #{rake_args.join(' ')}" exit system("fig run --rm --entrypoint=#{command} #{container_name} #{rake_args.join(' ')}") end end end
class Technique < ActiveRecord::Base validates_presence_of :name has_many :qualifications has_many :users, :through => :qualifications # Class methods class << self def dropdown [['All', 'all'] ] + all.map { |u| [u.name, u.id] } end end end
#!/usr/bin/env ruby Dir[File.join('lib', '**', '*.rb')].each do |file| require_relative file end def play_new blackjack = Game.new blackjack.begin_blackjack! blackjack.display_player_hand blackjack.prompt_hit_or_stand blackjack.compare_scores play_again? end def play_again? print "Play again? (Y/N): " answer = gets.chomp.downcase if answer == "y" play_new elsif answer == "n" puts "Ok, goodbye!" else puts "Invalid input. \n" play_again? end end play_new
module GoogleSpreadsheets class Worksheet < Base class Format < GDataFormat def encode(hash, options = {}) super({'title'=>hash['title'],'gs:rowCount'=>hash['rowCount'],'gs:colCount'=>hash['colCount']}, { :namespaces => { 'gs' => 'http://schemas.google.com/spreadsheets/2006' } }) end private def format_entry(e) e = super e['rowCount'] = e['rowCount'].to_i if e.has_key?('rowCount') e['colCount'] = e['colCount'].to_i if e.has_key?('colCount') end end self._connection = nil # avoid using base class's connection. self.prefix = '/:document_id/:visibility/:projection/' self.format = Format.new def self.collection_name; 'worksheets' end end end
json.array!(@attended_events) do |attended_event| json.extract! attended_event, :id, :user_id, :event_id json.url attended_event_url(attended_event, format: :json) end
class Api::V1::PlacesController < Api::V1::BaseController before_action :set_place, only: [:show] respond_to :json def index @places = Place.includes(:place_types_places).includes(:place_type).order('places.name') @cache_id = places_cache_id end def show @cache_id = place_cache_id end private def set_place @place = Place.find_by(url_name: params[:id]) end def places_cache_id count = Place.count last_updated = Place.maximum :updated_at "api-v1-places-#{count}-#{last_updated}.json" end def place_cache_id "api-v1-place#{@place.id}-#{@place.updated_at}.json" end end
require 'rake' require 'rake/file_utils_ext' class SnapDeploy::Provider::Update < Clamp::Command SnapDeploy::CLI.subcommand 'update', 'Update snap deploy', self include SnapDeploy::CLI::DefaultOptions include SnapDeploy::Helpers include Rake::FileUtilsExt option '--revision', 'REVISION', "Update to specified revision", :default => 'release' def execute cd(File.dirname(__FILE__), :verbose => !!verbose?) do $stderr.puts "DEPRECATION WARNING: snap-deploy update will be deprecated soon" sh("sudo $(which git) fetch --all", :verbose => !!verbose?) sh("sudo $(which git) merge --ff-only origin/#{revision}", :verbose => !!verbose?) sh("cd \"$(git rev-parse --show-toplevel)\" && sudo ./install.sh") end end end
class TweetsController < ApplicationController # solo si usuario está logeado puede acceder before_action :authenticate_user!, only: [ :retweets, :show ] def index if params[:q] # búsqueda parcial por el content del tweet @tweets = Tweet.where('content LIKE ?', "%#{params[:q]}%").order(created_at: :desc).page params[:page] elsif user_signed_in? @tweets = Tweet.tweets_for_me(current_user).or(current_user.tweets).order(created_at: :desc).page params[:page] else @tweets = Tweet.all.order(created_at: :desc).page params[:page] # @tweets = Tweet.eager_load(:user, :likes).order(created_at: :desc).page params[:page] end @tweet = Tweet.new @likes = Like.where(user: current_user).pluck(:tweet_id) # @users = User.where('id IS NOT ?', current_user.id).last(5) if user_signed_in? # Error en Heroku @users = User.where.not(id: current_user.id).last(5) if user_signed_in? end def create @users = User.all @tweets = Tweet.all.order(created_at: :desc).page params[:page] @likes = Like.where(user: current_user).pluck(:tweet_id) @tweet = Tweet.new(content: params[:tweet][:content]) @tweet.user = current_user respond_to do |format| if @tweet.save format.html { redirect_to root_path, notice: "¡Tweet creado con éxito!" } else format.html { render :index } end end end def retweets @tweet = Tweet.find(params[:id]) @retweet = Tweet.new @retweet.content = @tweet.content @retweet.user_id = current_user.id @retweet.tweet_id = @tweet.id @retweet.created_at = DateTime.now @retweet.updated_at = DateTime.now respond_to do |format| if @retweet.save format.html { redirect_to root_path, notice: "¡Haz hecho un RT éxito!" } else format.html { render :index } end end end def show @tweet = Tweet.find(params[:id]) @tweet_likes = @tweet.likes end end
require 'formula' class Corkscrew < Formula homepage 'http://www.agroman.net/corkscrew/' url 'http://www.agroman.net/corkscrew/corkscrew-2.0.tar.gz' sha1 '8bdb4c0dc71048136c721c33229b9bf795230b32' depends_on "libtool" => :build def install cp Dir["#{Formula["libtool"].opt_share}/libtool/*/config.{guess,sub}"], buildpath system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end
FactoryGirl.define do factory :notification do title "test" description "test description" entry_message "test entry message" exit_message "test exit message" association :beacon end end
class ToolPhoto < ApplicationRecord belongs_to :tool validates :url, presence: true validates :tool_id, presence: true end
require 'nokogiri' require 'yaml' require 'fileutils' require 'digest/md5' $: << File.dirname(__FILE__) + '/lib' require 'util' begin $config = YAML::load_file('/etc/aggregator-singpolyma/config.yml') rescue Errno::ENOENT $config = YAML::load_file(File.dirname(__FILE__) + '/config.yml') end entries = Hash.new {|h, k| h[k] = {}} # Go through all the tmp files, read out the entries, and delete the files Dir::glob(File.join($config['data_dir'], 'tmp', '*')).each do |file| Nokogiri::parse("<html>#{open(file).read.force_encoding('utf-8')}</html>").search('.hentry').each do |entry| published = hentry_published(entry) source = entry.at('*[rel~=source][href]').attributes['href'].to_s entries[source][published.strftime('%Y-%j')] ||= [] entries[source][published.strftime('%Y-%j')] << {:entry => entry, :published => published} end FileUtils.rm(file) end entries.each do |source, entries| users = (open(File.join($config['data_dir'], u(source))).read rescue '').split(/\s+/) next unless users.length > 0 entries.each do |date, entries| users.each do |user| published = entries.first[:published] # Granularity down to day path = File.join(File.dirname(__FILE__), 'feeds', user, published.strftime('%Y')) FileUtils.mkdir_p(path) # Make sure the directory exists # Add entries already from that day doc = Nokogiri::parse((open(File.join(path, "#{published.strftime('%j')}.xhtml")).read rescue '')) doc.search('.hentry').each do |entry| entries << {:entry => entry, :published => hentry_published(entry)} end # Sort entries by pubdate within day entries.sort! {|a,b| b[:published] <=> a[:published]} # Dedup items seen = [] entries.reject! {|entry| id = (entry[:entry].attributes['id'] || Digest::MD5.hexdigest(entry[:entry].to_xhtml)).to_s next true if seen.include?(id) seen << id false } open(File.join(path, "#{published.strftime('%j')}.xhtml"), 'w') { |fh| fh.puts '<!DOCTYPE html>' fh.puts '<html xmlns="http://www.w3.org/1999/xhtml">' fh.puts "<head><title>#{user}</title></head>" fh.puts '<body>' entries.each do |entry| fh.puts entry[:entry].to_xhtml end fh.puts "<a rel=\"prev\" href=\"/feeds/#{user}/#{published.strftime('%Y')}/#{published.strftime('%j').to_i-1}.xhtml\">Previous day</a>" fh.puts "<a rel=\"next\" href=\"/feeds/#{user}/#{published.strftime('%Y')}/#{published.strftime('%j').to_i+1}.xhtml\">Next day</a>" fh.puts '</body>' fh.puts '</html>' } end end end
class CreateAvgratings < ActiveRecord::Migration def change create_table :avgratings do |t| t.integer :ratingsum t.integer :rateduser t.references :gallary, index: true, foreign_key: true t.timestamps null: false end end end
module Plasma module Interpreter module PlasmaGrammar include Treetop::Runtime def root @root || :template end module Template0 def macro elements[0] end def tail elements[1] end end module Template1 def head elements[0] end def body elements[1] end end def _nt_template start_index = index if node_cache[:template].has_key?(index) cached = node_cache[:template][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] s1, i1 = [], index loop do r2 = _nt_plain if r2 s1 << r2 else break end end r1 = SyntaxNode.new(input, i1...index, s1) s0 << r1 if r1 s3, i3 = [], index loop do i4, s4 = index, [] r5 = _nt_macro s4 << r5 if r5 s6, i6 = [], index loop do r7 = _nt_plain if r7 s6 << r7 else break end end r6 = SyntaxNode.new(input, i6...index, s6) s4 << r6 end if s4.last r4 = (SyntaxNode).new(input, i4...index, s4) r4.extend(Template0) else self.index = i4 r4 = nil end if r4 s3 << r4 else break end end r3 = SyntaxNode.new(input, i3...index, s3) s0 << r3 end if s0.last r0 = (TemplateNode).new(input, i0...index, s0) r0.extend(Template1) else self.index = i0 r0 = nil end node_cache[:template][start_index] = r0 return r0 end def _nt_plain start_index = index if node_cache[:plain].has_key?(index) cached = node_cache[:plain][index] @index = cached.interval.end if cached return cached end if input.index(Regexp.new('[^\\[\\]`\']'), index) == index r0 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r0 = nil end node_cache[:plain][start_index] = r0 return r0 end def _nt_macro start_index = index if node_cache[:macro].has_key?(index) cached = node_cache[:macro][index] @index = cached.interval.end if cached return cached end i0 = index r1 = _nt_quote if r1 r0 = r1 else r2 = _nt_expansion if r2 r0 = r2 else self.index = i0 r0 = nil end end node_cache[:macro][start_index] = r0 return r0 end module Quote0 def template elements[1] end end def _nt_quote start_index = index if node_cache[:quote].has_key?(index) cached = node_cache[:quote][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('`', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('`') r1 = nil end s0 << r1 if r1 r2 = _nt_template s0 << r2 if r2 if input.index('\'', index) == index r3 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('\'') r3 = nil end s0 << r3 end end if s0.last r0 = (QuoteNode).new(input, i0...index, s0) r0.extend(Quote0) else self.index = i0 r0 = nil end node_cache[:quote][start_index] = r0 return r0 end module Expansion0 def x elements[1] end def plasma elements[2] end def x elements[3] end end def _nt_expansion start_index = index if node_cache[:expansion].has_key?(index) cached = node_cache[:expansion][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('[', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('[') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r3 = _nt_plasma s0 << r3 if r3 r4 = _nt_x s0 << r4 if r4 if input.index(']', index) == index r5 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(']') r5 = nil end s0 << r5 end end end end if s0.last r0 = (ExpansionNode).new(input, i0...index, s0) r0.extend(Expansion0) else self.index = i0 r0 = nil end node_cache[:expansion][start_index] = r0 return r0 end def _nt_plasma start_index = index if node_cache[:plasma].has_key?(index) cached = node_cache[:plasma][index] @index = cached.interval.end if cached return cached end i0 = index r1 = _nt_decl if r1 r0 = r1 else r2 = _nt_seq if r2 r0 = r2 else r3 = _nt_quote if r3 r0 = r3 else r4 = _nt_defun if r4 r0 = r4 else r5 = _nt_def if r5 r0 = r5 else r6 = _nt_fun if r6 r0 = r6 else r7 = _nt_if if r7 r0 = r7 else r8 = _nt_apply if r8 r0 = r8 else r9 = _nt_bool if r9 r0 = r9 else r10 = _nt_sym if r10 r0 = r10 else r11 = _nt_hash if r11 r0 = r11 else r12 = _nt_list if r12 r0 = r12 else r13 = _nt_regex if r13 r0 = r13 else r14 = _nt_date if r14 r0 = r14 else r15 = _nt_time if r15 r0 = r15 else r16 = _nt_str if r16 r0 = r16 else r17 = _nt_num if r17 r0 = r17 else self.index = i0 r0 = nil end end end end end end end end end end end end end end end end end node_cache[:plasma][start_index] = r0 return r0 end module Decl0 def s elements[0] end def s elements[2] end def plasma elements[3] end end module Decl1 def x elements[1] end def first elements[2] end def rest elements[3] end def x elements[4] end end def _nt_decl start_index = index if node_cache[:decl].has_key?(index) cached = node_cache[:decl][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('|', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('|') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r4 = _nt_plasma if r4 r3 = r4 else r3 = SyntaxNode.new(input, index...index) end s0 << r3 if r3 s5, i5 = [], index loop do i6, s6 = index, [] r7 = _nt_s s6 << r7 if r7 if input.index('|', index) == index r8 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('|') r8 = nil end s6 << r8 if r8 r9 = _nt_s s6 << r9 if r9 r10 = _nt_plasma s6 << r10 end end end if s6.last r6 = (SyntaxNode).new(input, i6...index, s6) r6.extend(Decl0) else self.index = i6 r6 = nil end if r6 s5 << r6 else break end end r5 = SyntaxNode.new(input, i5...index, s5) s0 << r5 if r5 r11 = _nt_x s0 << r11 if r11 if input.index('|', index) == index r12 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('|') r12 = nil end s0 << r12 end end end end end if s0.last r0 = (DeclNode).new(input, i0...index, s0) r0.extend(Decl1) else self.index = i0 r0 = nil end node_cache[:decl][start_index] = r0 return r0 end module Seq0 def s elements[0] end def s elements[2] end def plasma elements[3] end end module Seq1 def x elements[1] end def first elements[2] end def rest elements[3] end def x elements[4] end end def _nt_seq start_index = index if node_cache[:seq].has_key?(index) cached = node_cache[:seq][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r4 = _nt_plasma if r4 r3 = r4 else r3 = SyntaxNode.new(input, index...index) end s0 << r3 if r3 s5, i5 = [], index loop do i6, s6 = index, [] r7 = _nt_s s6 << r7 if r7 if input.index('|', index) == index r8 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('|') r8 = nil end s6 << r8 if r8 r9 = _nt_s s6 << r9 if r9 r10 = _nt_plasma s6 << r10 end end end if s6.last r6 = (SyntaxNode).new(input, i6...index, s6) r6.extend(Seq0) else self.index = i6 r6 = nil end if r6 s5 << r6 else break end end r5 = SyntaxNode.new(input, i5...index, s5) s0 << r5 if r5 r11 = _nt_x s0 << r11 if r11 if input.index(')', index) == index r12 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r12 = nil end s0 << r12 end end end end end if s0.last r0 = (SeqNode).new(input, i0...index, s0) r0.extend(Seq1) else self.index = i0 r0 = nil end node_cache[:seq][start_index] = r0 return r0 end module Defun0 def x elements[1] end def s elements[3] end def params elements[4] end def s elements[5] end def plasma elements[6] end def x elements[7] end end def _nt_defun start_index = index if node_cache[:defun].has_key?(index) cached = node_cache[:defun][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 if input.index('defun', index) == index r3 = (SyntaxNode).new(input, index...(index + 5)) @index += 5 else terminal_parse_failure('defun') r3 = nil end s0 << r3 if r3 r4 = _nt_s s0 << r4 if r4 r5 = _nt_params s0 << r5 if r5 r6 = _nt_s s0 << r6 if r6 r7 = _nt_plasma s0 << r7 if r7 r8 = _nt_x s0 << r8 if r8 if input.index(')', index) == index r9 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r9 = nil end s0 << r9 end end end end end end end end if s0.last r0 = (DefunNode).new(input, i0...index, s0) r0.extend(Defun0) else self.index = i0 r0 = nil end node_cache[:defun][start_index] = r0 return r0 end module Def0 def x elements[1] end def s elements[3] end def sym elements[4] end def s elements[5] end def plasma elements[6] end def x elements[7] end end def _nt_def start_index = index if node_cache[:def].has_key?(index) cached = node_cache[:def][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 if input.index('def', index) == index r3 = (SyntaxNode).new(input, index...(index + 3)) @index += 3 else terminal_parse_failure('def') r3 = nil end s0 << r3 if r3 r4 = _nt_s s0 << r4 if r4 r5 = _nt_sym s0 << r5 if r5 r6 = _nt_s s0 << r6 if r6 r7 = _nt_plasma s0 << r7 if r7 r8 = _nt_x s0 << r8 if r8 if input.index(')', index) == index r9 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r9 = nil end s0 << r9 end end end end end end end end if s0.last r0 = (DefNode).new(input, i0...index, s0) r0.extend(Def0) else self.index = i0 r0 = nil end node_cache[:def][start_index] = r0 return r0 end module Fun0 def x elements[1] end def s elements[3] end def params elements[4] end def s elements[5] end def plasma elements[6] end def x elements[7] end end def _nt_fun start_index = index if node_cache[:fun].has_key?(index) cached = node_cache[:fun][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 if input.index('fun', index) == index r3 = (SyntaxNode).new(input, index...(index + 3)) @index += 3 else terminal_parse_failure('fun') r3 = nil end s0 << r3 if r3 r4 = _nt_s s0 << r4 if r4 r5 = _nt_params s0 << r5 if r5 r6 = _nt_s s0 << r6 if r6 r7 = _nt_plasma s0 << r7 if r7 r8 = _nt_x s0 << r8 if r8 if input.index(')', index) == index r9 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r9 = nil end s0 << r9 end end end end end end end end if s0.last r0 = (FunNode).new(input, i0...index, s0) r0.extend(Fun0) else self.index = i0 r0 = nil end node_cache[:fun][start_index] = r0 return r0 end module Params0 def s elements[0] end def sym elements[1] end end module Params1 def x elements[1] end def first elements[2] end def rest elements[3] end def x elements[4] end end def _nt_params start_index = index if node_cache[:params].has_key?(index) cached = node_cache[:params][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r3 = _nt_sym s0 << r3 if r3 s4, i4 = [], index loop do i5, s5 = index, [] r6 = _nt_s s5 << r6 if r6 r7 = _nt_sym s5 << r7 end if s5.last r5 = (SyntaxNode).new(input, i5...index, s5) r5.extend(Params0) else self.index = i5 r5 = nil end if r5 s4 << r5 else break end end r4 = SyntaxNode.new(input, i4...index, s4) s0 << r4 if r4 r8 = _nt_x s0 << r8 if r8 if input.index(')', index) == index r9 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r9 = nil end s0 << r9 end end end end end if s0.last r0 = (ParamsNode).new(input, i0...index, s0) r0.extend(Params1) else self.index = i0 r0 = nil end node_cache[:params][start_index] = r0 return r0 end module If0 def s elements[0] end def s elements[2] end def other elements[3] end end module If1 def x elements[1] end def s elements[3] end def pred elements[4] end def s elements[5] end def s elements[7] end def body elements[8] end def maybe elements[9] end def x elements[10] end end def _nt_if start_index = index if node_cache[:if].has_key?(index) cached = node_cache[:if][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 if input.index('if', index) == index r3 = (SyntaxNode).new(input, index...(index + 2)) @index += 2 else terminal_parse_failure('if') r3 = nil end s0 << r3 if r3 r4 = _nt_s s0 << r4 if r4 r5 = _nt_plasma s0 << r5 if r5 r6 = _nt_s s0 << r6 if r6 if input.index('then', index) == index r7 = (SyntaxNode).new(input, index...(index + 4)) @index += 4 else terminal_parse_failure('then') r7 = nil end s0 << r7 if r7 r8 = _nt_s s0 << r8 if r8 r9 = _nt_plasma s0 << r9 if r9 i11, s11 = index, [] r12 = _nt_s s11 << r12 if r12 if input.index('else', index) == index r13 = (SyntaxNode).new(input, index...(index + 4)) @index += 4 else terminal_parse_failure('else') r13 = nil end s11 << r13 if r13 r14 = _nt_s s11 << r14 if r14 r15 = _nt_plasma s11 << r15 end end end if s11.last r11 = (SyntaxNode).new(input, i11...index, s11) r11.extend(If0) else self.index = i11 r11 = nil end if r11 r10 = r11 else r10 = SyntaxNode.new(input, index...index) end s0 << r10 if r10 r16 = _nt_x s0 << r16 if r16 if input.index(')', index) == index r17 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r17 = nil end s0 << r17 end end end end end end end end end end end if s0.last r0 = (IfNode).new(input, i0...index, s0) r0.extend(If1) else self.index = i0 r0 = nil end node_cache[:if][start_index] = r0 return r0 end module Apply0 def s elements[0] end def plasma elements[1] end end module Apply1 def x elements[1] end def applied elements[2] end def s elements[3] end def first elements[4] end def rest elements[5] end def x elements[6] end end def _nt_apply start_index = index if node_cache[:apply].has_key?(index) cached = node_cache[:apply][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('(', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('(') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 i3 = index r4 = _nt_fun if r4 r3 = r4 else r5 = _nt_sym if r5 r3 = r5 else self.index = i3 r3 = nil end end s0 << r3 if r3 r6 = _nt_s s0 << r6 if r6 r7 = _nt_plasma s0 << r7 if r7 s8, i8 = [], index loop do i9, s9 = index, [] r10 = _nt_s s9 << r10 if r10 r11 = _nt_plasma s9 << r11 end if s9.last r9 = (SyntaxNode).new(input, i9...index, s9) r9.extend(Apply0) else self.index = i9 r9 = nil end if r9 s8 << r9 else break end end r8 = SyntaxNode.new(input, i8...index, s8) s0 << r8 if r8 r12 = _nt_x s0 << r12 if r12 if input.index(')', index) == index r13 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(')') r13 = nil end s0 << r13 end end end end end end end if s0.last r0 = (ApplyNode).new(input, i0...index, s0) r0.extend(Apply1) else self.index = i0 r0 = nil end node_cache[:apply][start_index] = r0 return r0 end def _nt_bool start_index = index if node_cache[:bool].has_key?(index) cached = node_cache[:bool][index] @index = cached.interval.end if cached return cached end i0 = index if input.index('true', index) == index r1 = (TrueNode).new(input, index...(index + 4)) @index += 4 else terminal_parse_failure('true') r1 = nil end if r1 r0 = r1 else if input.index('false', index) == index r2 = (FalseNode).new(input, index...(index + 5)) @index += 5 else terminal_parse_failure('false') r2 = nil end if r2 r0 = r2 else self.index = i0 r0 = nil end end node_cache[:bool][start_index] = r0 return r0 end def _nt_sym start_index = index if node_cache[:sym].has_key?(index) cached = node_cache[:sym][index] @index = cached.interval.end if cached return cached end s0, i0 = [], index loop do if input.index(Regexp.new('[a-z+!\\^&@?*%<>=_-]'), index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r1 = nil end if r1 s0 << r1 else break end end if s0.empty? self.index = i0 r0 = nil else r0 = SymNode.new(input, i0...index, s0) end node_cache[:sym][start_index] = r0 return r0 end module Hash0 def s elements[0] end def relation elements[1] end end module Hash1 def x elements[1] end def first elements[2] end def rest elements[3] end def x elements[4] end end def _nt_hash start_index = index if node_cache[:hash].has_key?(index) cached = node_cache[:hash][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('{', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('{') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r4 = _nt_relation if r4 r3 = r4 else r3 = SyntaxNode.new(input, index...index) end s0 << r3 if r3 s5, i5 = [], index loop do i6, s6 = index, [] r7 = _nt_s s6 << r7 if r7 r8 = _nt_relation s6 << r8 end if s6.last r6 = (SyntaxNode).new(input, i6...index, s6) r6.extend(Hash0) else self.index = i6 r6 = nil end if r6 s5 << r6 else break end end r5 = SyntaxNode.new(input, i5...index, s5) s0 << r5 if r5 r9 = _nt_x s0 << r9 if r9 if input.index('}', index) == index r10 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('}') r10 = nil end s0 << r10 end end end end end if s0.last r0 = (HashNode).new(input, i0...index, s0) r0.extend(Hash1) else self.index = i0 r0 = nil end node_cache[:hash][start_index] = r0 return r0 end module Relation0 def sym elements[0] end def x elements[1] end def x elements[3] end def plasma elements[4] end end def _nt_relation start_index = index if node_cache[:relation].has_key?(index) cached = node_cache[:relation][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] r1 = _nt_sym s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 if input.index(':', index) == index r3 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(':') r3 = nil end s0 << r3 if r3 r4 = _nt_x s0 << r4 if r4 r5 = _nt_plasma s0 << r5 end end end end if s0.last r0 = (RelationNode).new(input, i0...index, s0) r0.extend(Relation0) else self.index = i0 r0 = nil end node_cache[:relation][start_index] = r0 return r0 end module List0 def s elements[0] end def plasma elements[1] end end module List1 def x elements[1] end def first elements[2] end def rest elements[3] end def x elements[4] end end def _nt_list start_index = index if node_cache[:list].has_key?(index) cached = node_cache[:list][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('[', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('[') r1 = nil end s0 << r1 if r1 r2 = _nt_x s0 << r2 if r2 r4 = _nt_plasma if r4 r3 = r4 else r3 = SyntaxNode.new(input, index...index) end s0 << r3 if r3 s5, i5 = [], index loop do i6, s6 = index, [] r7 = _nt_s s6 << r7 if r7 r8 = _nt_plasma s6 << r8 end if s6.last r6 = (SyntaxNode).new(input, i6...index, s6) r6.extend(List0) else self.index = i6 r6 = nil end if r6 s5 << r6 else break end end r5 = SyntaxNode.new(input, i5...index, s5) s0 << r5 if r5 r9 = _nt_x s0 << r9 if r9 if input.index(']', index) == index r10 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(']') r10 = nil end s0 << r10 end end end end end if s0.last r0 = (ListNode).new(input, i0...index, s0) r0.extend(List1) else self.index = i0 r0 = nil end node_cache[:list][start_index] = r0 return r0 end module Regex0 def body elements[1] end end def _nt_regex start_index = index if node_cache[:regex].has_key?(index) cached = node_cache[:regex][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('/', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('/') r1 = nil end s0 << r1 if r1 s2, i2 = [], index loop do r3 = _nt_regex_char if r3 s2 << r3 else break end end r2 = SyntaxNode.new(input, i2...index, s2) s0 << r2 if r2 if input.index('/', index) == index r4 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('/') r4 = nil end s0 << r4 end end if s0.last r0 = (RegexNode).new(input, i0...index, s0) r0.extend(Regex0) else self.index = i0 r0 = nil end node_cache[:regex][start_index] = r0 return r0 end def _nt_regex_char start_index = index if node_cache[:regex_char].has_key?(index) cached = node_cache[:regex_char][index] @index = cached.interval.end if cached return cached end i0 = index if input.index('\\/', index) == index r1 = (SyntaxNode).new(input, index...(index + 2)) @index += 2 else terminal_parse_failure('\\/') r1 = nil end if r1 r0 = r1 else if input.index(Regexp.new('[^/]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end if r2 r0 = r2 else self.index = i0 r0 = nil end end node_cache[:regex_char][start_index] = r0 return r0 end module Date0 def s elements[0] end def time elements[1] end end module Date1 def year elements[0] end def month elements[2] end def day elements[4] end end def _nt_date start_index = index if node_cache[:date].has_key?(index) cached = node_cache[:date][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] r1 = _nt_year s0 << r1 if r1 if input.index(Regexp.new('[-]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end s0 << r2 if r2 r3 = _nt_dual s0 << r3 if r3 if input.index(Regexp.new('[-]'), index) == index r4 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r4 = nil end s0 << r4 if r4 r5 = _nt_dual s0 << r5 if r5 i7, s7 = index, [] r8 = _nt_s s7 << r8 if r8 r9 = _nt_time s7 << r9 end if s7.last r7 = (SyntaxNode).new(input, i7...index, s7) r7.extend(Date0) else self.index = i7 r7 = nil end if r7 r6 = r7 else r6 = SyntaxNode.new(input, index...index) end s0 << r6 end end end end end if s0.last r0 = (DateNode).new(input, i0...index, s0) r0.extend(Date1) else self.index = i0 r0 = nil end node_cache[:date][start_index] = r0 return r0 end module Year0 end def _nt_year start_index = index if node_cache[:year].has_key?(index) cached = node_cache[:year][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index(Regexp.new('[0-9]'), index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r1 = nil end s0 << r1 if r1 if input.index(Regexp.new('[0-9]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end s0 << r2 if r2 if input.index(Regexp.new('[0-9]'), index) == index r3 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r3 = nil end s0 << r3 if r3 if input.index(Regexp.new('[0-9]'), index) == index r4 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r4 = nil end s0 << r4 end end end if s0.last r0 = (SyntaxNode).new(input, i0...index, s0) r0.extend(Year0) else self.index = i0 r0 = nil end node_cache[:year][start_index] = r0 return r0 end module Dual0 end def _nt_dual start_index = index if node_cache[:dual].has_key?(index) cached = node_cache[:dual][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index(Regexp.new('[0-9]'), index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r1 = nil end s0 << r1 if r1 if input.index(Regexp.new('[0-9]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end s0 << r2 end if s0.last r0 = (SyntaxNode).new(input, i0...index, s0) r0.extend(Dual0) else self.index = i0 r0 = nil end node_cache[:dual][start_index] = r0 return r0 end module Time0 def hours elements[0] end def minutes elements[2] end def seconds elements[4] end end def _nt_time start_index = index if node_cache[:time].has_key?(index) cached = node_cache[:time][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] r1 = _nt_dual s0 << r1 if r1 if input.index(':', index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(':') r2 = nil end s0 << r2 if r2 r3 = _nt_dual s0 << r3 if r3 if input.index(':', index) == index r4 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure(':') r4 = nil end s0 << r4 if r4 r5 = _nt_dual s0 << r5 end end end end if s0.last r0 = (TimeNode).new(input, i0...index, s0) r0.extend(Time0) else self.index = i0 r0 = nil end node_cache[:time][start_index] = r0 return r0 end module Str0 def body elements[1] end end def _nt_str start_index = index if node_cache[:str].has_key?(index) cached = node_cache[:str][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] if input.index('"', index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('"') r1 = nil end s0 << r1 if r1 s2, i2 = [], index loop do r3 = _nt_str_char if r3 s2 << r3 else break end end r2 = SyntaxNode.new(input, i2...index, s2) s0 << r2 if r2 if input.index('"', index) == index r4 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('"') r4 = nil end s0 << r4 end end if s0.last r0 = (StrNode).new(input, i0...index, s0) r0.extend(Str0) else self.index = i0 r0 = nil end node_cache[:str][start_index] = r0 return r0 end def _nt_str_char start_index = index if node_cache[:str_char].has_key?(index) cached = node_cache[:str_char][index] @index = cached.interval.end if cached return cached end i0 = index if input.index('\\"', index) == index r1 = (SyntaxNode).new(input, index...(index + 2)) @index += 2 else terminal_parse_failure('\\"') r1 = nil end if r1 r0 = r1 else if input.index(Regexp.new('[^"]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end if r2 r0 = r2 else self.index = i0 r0 = nil end end node_cache[:str_char][start_index] = r0 return r0 end module Num0 end module Num1 def whole elements[0] end def decimal elements[1] end end def _nt_num start_index = index if node_cache[:num].has_key?(index) cached = node_cache[:num][index] @index = cached.interval.end if cached return cached end i0, s0 = index, [] s1, i1 = [], index loop do if input.index(Regexp.new('[0-9]'), index) == index r2 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r2 = nil end if r2 s1 << r2 else break end end if s1.empty? self.index = i1 r1 = nil else r1 = SyntaxNode.new(input, i1...index, s1) end s0 << r1 if r1 i4, s4 = index, [] if input.index('.', index) == index r5 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else terminal_parse_failure('.') r5 = nil end s4 << r5 if r5 s6, i6 = [], index loop do if input.index(Regexp.new('[0-9]'), index) == index r7 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r7 = nil end if r7 s6 << r7 else break end end if s6.empty? self.index = i6 r6 = nil else r6 = SyntaxNode.new(input, i6...index, s6) end s4 << r6 end if s4.last r4 = (SyntaxNode).new(input, i4...index, s4) r4.extend(Num0) else self.index = i4 r4 = nil end if r4 r3 = r4 else r3 = SyntaxNode.new(input, index...index) end s0 << r3 end if s0.last r0 = (NumNode).new(input, i0...index, s0) r0.extend(Num1) else self.index = i0 r0 = nil end node_cache[:num][start_index] = r0 return r0 end def _nt_x start_index = index if node_cache[:x].has_key?(index) cached = node_cache[:x][index] @index = cached.interval.end if cached return cached end r1 = _nt_s if r1 r0 = r1 else r0 = SyntaxNode.new(input, index...index) end node_cache[:x][start_index] = r0 return r0 end def _nt_s start_index = index if node_cache[:s].has_key?(index) cached = node_cache[:s][index] @index = cached.interval.end if cached return cached end s0, i0 = [], index loop do if input.index(Regexp.new('[ \\n]'), index) == index r1 = (SyntaxNode).new(input, index...(index + 1)) @index += 1 else r1 = nil end if r1 s0 << r1 else break end end if s0.empty? self.index = i0 r0 = nil else r0 = SyntaxNode.new(input, i0...index, s0) end node_cache[:s][start_index] = r0 return r0 end end class PlasmaGrammarParser < Treetop::Runtime::CompiledParser include PlasmaGrammar end end end
# frozen_string_literal: true module RubyPushNotifications module FCM # Encapsulates a FCM Notification. # By default only Required fields are set. # (https://developer.android.com/google/fcm/server-ref.html#send-downstream) # # @author Carlos Alonso class FCMNotification attr_reader :registration_ids, :data include RubyPushNotifications::NotificationResultsManager # Initializes the notification # # @param [Array]. Array with the receiver's FCM registration ids. # @param [Hash]. Payload to send. def initialize(registration_ids, data) @registration_ids = registration_ids @data = data end def make_payload { registration_ids: @registration_ids }.merge(@data) end # @return [String]. The FCM's JSON format for the payload to send. # (https://developer.android.com/google/fcm/server-ref.html#send-downstream) # Credits: https://github.com/calos0921 - for this url change to FCM std def as_fcm_json JSON.dump(make_payload) end end end end
class Game attr_accessor :board, :player_1, :player_2 WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2] ] def initialize(player_1 = Players::Human.new("X"), player_2 = Players::Human.new("O"), board = Board.new) @board = board @player_1 = player_1 @player_2 = player_2 end def current_player self.board.turn_count.even? ? player_1 : player_2 end def over? self.won? || self.draw? || self.board.full? end def won? WIN_COMBINATIONS.any? do |combination| return combination if (self.board.taken?(combination[0] + 1)) && (self.board.position(combination[0] + 1) == self.board.position(combination[1] + 1)) && (self.board.position(combination[1] + 1) == self.board.position(combination[2] + 1)) end end def draw? !self.won? && self.board.full? end def winner win_combination = self.won? if win_combination return self.board.position(win_combination[0]+1) else return nil end end def turn move = self.current_player.move(self.board) if self.board.valid_move?(move) self.board.update(move, self.current_player) self.board.display else self.turn end end def play while !self.over? puts "Please enter a number 1-9:" self.turn end if self.won? puts "Congratulations #{self.winner}!" elsif self.draw? puts "Cat's Game!" end end end
# Virus Predictor # I worked on this challenge [by myself, with: ]. # We spent [#] hours on this challenge. # EXPLANATION OF require_relative # # require_relative 'state_data' class VirusPredictor # method initializes a class instance setting it with state, pop density , population def initialize(state_of_origin, population_density, population) @state = state_of_origin @population = population @population_density = population_density end # method calling predicted deaths method and speed_of_spread metod def virus_effects predicted_deaths speed_of_spread end private # method takes 3 parameters and is private def predicted_deaths # predicted deaths is solely based on population density # the if else seems to say the larger the density the higher the deaths and rounding down death_percentage = 0 #getting the death_percentage rate for the density if @population_density >= 200 death_percentage = 0.4 elsif @population_density >= 150 death_percentage = 0.3 elsif @population_density >= 100 death_percentage = 0.2 elsif @population_density >= 50 death_percentage = 0.1 else death_percentage = 0.05 end number_of_deaths = (@population * death_percentage).floor print "#{@state} will lose #{number_of_deaths} people in this outbreak" end # speed is setting the number of months as the speed at 0 # why is the speed slower when the population density is higher?? # change it to months def speed_of_spread #in months #doesn't need arguments # We are still perfecting our formula here. The speed is also affected # by additional factors we haven't added into this functionality. months = 0.0 if @population_density >= 200 months = 0.5 elsif @population_density >= 150 months = 1 elsif @population_density >= 100 months = 1.5 elsif @population_density >= 50 months = 2 else months = 2.5 end puts " and will spread across the state in #{months} months.\n\n" end end #======================================================================= # DRIVER CODE # initialize VirusPredictor for each state alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population]) alabama.virus_effects p '-----------------' jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population]) jersey.virus_effects california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population]) california.virus_effects alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population]) alaska.virus_effects # creating a report for each state , and then finding it's virus effects. STATE_DATA.each do |state, state_info| report = VirusPredictor.new(state, state_info[:population_density], state_info[:population] ) report.virus_effects end #======================================================================= # Reflection Section
require './lib/enrollment.rb' require './lib/district_repository' require './lib/district' require './lib/custom_errors' include Errors class EnrollmentTest < Minitest::Test def data_dir File.expand_path '../data', __dir__ end def test_it_can_find_participation_by_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 2752, district.enrollment.participation_in_year(2010) end def test_it_knows_the_known_races dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal [:white, :asian, :black, :hispanic, :two_or_more, :pacific_islander, :native_american, :all_students, :female_students, :male_students], district.enrollment.known_races end def test_it_can_find_graduation_rate_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 0.814, district.enrollment.graduation_rate_in_year(2010) end def test_it_can_find_dropout_rate_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 0.013, district.enrollment.dropout_rate_in_year(2011) end def test_it_can_find_dropout_rate_by_gender_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal '', district.enrollment.dropout_rate_by_gender_in_year(2011) end def test_it_can_find_online_participation_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 77, district.enrollment.online_participation_in_year(2011) end def test_it_can_find_hash_of_online_particiaption dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {2011=>77, 2012=>42, 2013=>37} assert_equal expected, district.enrollment.online_participation_by_year end def test_it_can_return_races_with_rates dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {:native_american=>0.01, :asian=>0.01, :black=>0.01, :hispanic=>0.08, :pacific_islander=>0, :two_or_more=>0.04, :white=>0.86} assert_equal expected, district.enrollment.participation_by_race_or_ethnicity_in_year(2010) end def test_it_can_find_races_and_dropout_rates dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {:native_american=>0.01, :asian=>0.01, :black=>0.01, :hispanic=>0.08, :pacific_islander=>0, :two_or_more=>0.04, :white=>0.86} assert_equal expected, district.enrollment.participation_by_race_or_ethnicity_in_year(2010) end def test_it_can_find_special_education_by_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {2009=>0.094, 2011=>0.077, 2012=>0.08, 2013=>0.081, 2010=>0.082, 2014=>0.085} assert_equal expected, district.enrollment.special_education_by_year end def test_it_can_find_special_education_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 0.094, district.enrollment.special_education_in_year(2009) end def test_it_can_find_remediation_by_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {2011=>0.348, 2010=>0.415, 2009=>0.357} assert_equal expected, district.enrollment.remediation_by_year end def test_it_can_find_remediation_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 0.348, district.enrollment.remediation_in_year(2011) end def test_it_can_find_kindergarten_participation_by_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {2007 => 0, 2006 => 0, 2005 => 0.005, 2004 => 0, 2008 => 0, 2009 => 1, 2010 => 1, 2011 => 1, 2012 => 1, 2013 => 1, 2014 => 1} assert_equal expected, district.enrollment.kindergarten_participation_by_year end def test_it_can_find_kindergarten_participation_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 1, district.enrollment.kindergarten_participation_in_year(2011) end def test_it_can_find_dropout_rate_by_gender_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {:female=>0.016, :male=>0.011} assert_equal expected, district.enrollment.dropout_rate_by_gender_in_year(2011) end def test_it_can_find_dropout_rate_for_race_in_year dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') assert_equal 0, district.enrollment.dropout_rate_for_race_or_ethnicity_in_year(:asian, 2011) end def test_it_can_find_races_and_dropout_rates_and_return_hash dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {:asian=>0, :black=>0, :pacific_islander=>0, :hispanic=>0.008, :native_american=>0, :two_or_more=>0.03, :white=>0.013} assert_equal expected, district.enrollment.dropout_rate_by_race_in_year(2011) end def test_it_can_return_years_associated_with_race dr = DistrictRepository.from_json(data_dir) district = dr.find_by_name('WOODLAND PARK RE-2') expected = {2011=>0.013, 2012=>0.007} assert_equal expected, district.enrollment.dropout_rate_for_race_or_ethnicity(:white) end end
class User < ActiveRecord::Base has_many :rounds validates :email, uniqueness: true, :presence => true validates :password, uniqueness: true, :presence => true def self.authenticate(email, password) if User.exists?(email: email, password: password) User.where(email: email, password: password) else nil end end end
class Organization < ActiveRecord::Base MEMBER = 'member' ADMIN = 'admin' OWNER = 'owner' ROLES = [MEMBER, ADMIN, OWNER] has_many :organization_buildings has_many :buildings, through: :organization_buildings has_many :audit_reports has_many :report_templates has_many :users validates :owner, presence: true validates :name, presence: true def default_report_template report_templates.first end end
require 'rails_helper' RSpec.describe "Comments", type: :request do describe "GET /movies/:id", :vcr do let!(:comment) { create(:comment) } it "displays comments on movie page" do visit movie_path(comment.movie) expect(page).to have_selector(".panel-body", text: comment.content) expect(page).to have_selector(".commented_user", text: comment.user.email) end end describe "display top 10 commenters" do before do create_list :user, 5 create_list :movie, 5 User.limit(3).pluck(:id).each do |user_id| create :comment, movie: Movie.first, user_id: user_id end Movie.offset(1).limit(3).pluck(:id).each do |movie_id| create :comment, movie_id: movie_id, user: User.second end create :comment, movie: Movie.last, user: User.third end it "displays top 10 commenters" do visit "/top_10_commenters" expect(page.body.gsub(/<\/?[^>]+>/, '')).to include("1.\n#{User.second.email}\n4") expect(page.body.gsub(/<\/?[^>]+>/, '')).to include("2.\n#{User.third.email}\n2") expect(page.body.gsub(/<\/?[^>]+>/, '')).to include("3.\n#{User.first.email}\n1") end end end
# input: array of integers # output: sum of sums of each leading subsequence (integer) # sequence of sums starts with sum of first integer(which is just integer) then sum of first integer and second integer, and then sum of first three integers, then sum of first four integers etc # index goes up by one and then you work out the sum of the integer at the index and all the other integers at the previous indexes # data structure: array # algo: # set new variable as an empty array # set new variable as 0 for the sum # iterate through input array and push each element into the empty array # sum the other integer array for each iteration and increment sum variable in each iteration def sum_of_sums(array) sum_array = [] sum = 0 array.each do |integer| sum_array << integer sum += sum_array.sum end sum end # or def sum_of_sums(numbers) sum_total = 0 1.upto(numbers.size) do |count| sum_total += numbers.slice(0, count).reduce(:+) end sum_total end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "centos/6" config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.network "forwarded_port", guest: 443, host: 8443 config.vm.network "private_network", ip: "192.168.33.11" config.vm.hostname = "vagrant" config.vm.define "vagrant" config.vm.provision "ansible" do |ansible| ansible.compatibility_mode = "2.0" ansible.playbook = "provisioning/playbook.yml" ansible.groups = { "local" => ["vagrant"] } ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end end
require_dependency "administration/application_controller" module Administration class MembersController < ApplicationController def index @members = Member::User.all.order("created_at DESC").page(params[:page]).per(10) end def show @member = Member::User.find(params[:id]) @publications = Article::Publication.where(author: params[:id]).order("created_at DESC").page(params[:page]).per(10) end def new @user = Member::User.new variables_for_new end def create @user = Member::User.new(user_params) if @user.save redirect_to administration.members_path, :notice => "A new type was created!" else variables_for_new render action: :new, :notice => "An error occured, the type was not saved" end end def edit @user = Member::User.find(params[:id]) variables_for_edit end def update @user = Member::User.find(params[:id]) if @user.update_attributes(user_params) redirect_to administration.members_path, notice: 'Member was successfully updated.' else variables_for_edit render action: :edit, notice: "Update failed, please try again" end end def destroy @member = Member::User.find(params[:id]) unless @member.destroy redirect_to(administration.members_path, notice: "An error occured, the deletion was not successful") else redirect_to(administration.members_path, notice: "A member's account was deleted") end end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :email, :role) end # these variables are required whenever the new view is rendered def variables_for_new @path = administration.members_path @method = :post end # these variables are required whenever the edit view is rendered def variables_for_edit @path = administration.member_path @method = :patch end end end
class CreateReviews < ActiveRecord::Migration def change create_table :reviews do |t| t.string :url t.decimal :rating, :precision => 4, :scale => 2 t.integer :bnm t.integer :year t.string :author t.text :body t.integer :album_id end end end
Integer.class_eval do def is_prime? return false if self < 2 (2..Math.sqrt(self).to_i).none?{ |i| self % i == 0 } end end
require_relative 'swagger_definition.rb' # The Swagger1DefinitionExtractor class is responsible for # extracting information out of Swagger 1.x documents. class Swagger1DefinitionExtractor def extract(json) operations = available_operations(json) models = available_models(json) SwaggerDefinition.new(operations, models) end private def available_operations(json) return {} unless json.key?('apis') operations = {} json['apis'].map do |api| api['operations'].map do |operation| operation['path'] = api['path'] operations[operation['nickname']] = operation end end.flatten operations end def available_models(json) return {} unless json.key?('models') json['models'] end end
=begin Gives "boardable" pieces the basics for being placed and moving. =end module Game module Thud module Piece attr_reader :x, :y, :board # has a board and coordinates # board:: Board instance, required # x, y:: coordinates, only if the piece is not out def initialize board, x = nil, y = nil @board = board self.put x, y end # put the piece from wherever to a free position on the board # x, y:: new position def put x, y unless @board.free? x, y raise ArgumentError.new("Cell #{x}, #{y} occupied.") end fromx, fromy = [@x, @y] @x, @y = [x, y] @board.piece_event self, fromx, fromy self end # takes the piece out of the board as a prisonner def kill fromx, fromy = [@x, @y] @x = @y = nil @board.piece_event self, fromx, fromy self end # is the piece out of the board ? def dead? @x.nil? end end end end
class Event < ApplicationRecord before_save :system_name_trim, :update_purge_date, :update_url, :update_purge_status validates :event_system_name, :uniqueness => {:scope => [:company_id,:event_type_id]} validates :event_name, :event_system_name, :start_date, :end_date, :card_no, :company_id, :event_type_id, presence: true scope :passive, -> (date_search) {where("purge_date < ?", "%#{date_search}%")} scope :cluster_events, -> (cluster_id) { where(company: Company.cluster(cluster_id))} belongs_to :company belongs_to :event_type has_many :plugins, as: :entity def plugin_names self.plugins.pluck(:name).uniq end def self.search(search) self.where("event_system_name ILIKE ?", "%#{search}%") end def cluster company.cluster end def purge self.purge_status = true self.save end def unpurge self.purge_status = false self.save end def self.purge_passive date self.passive(date).update_all(purge_status: true) end def self.to_csv(events,options = {}) desired_columns = [ "company_name","company_system_name","name", "system_name","cluster","event_type","start_date","end_date","plugin"] CSV.generate(options) do |csv| csv << column_names events.each do |event| csv << product.attributes.values_at(*desired_columns) end end end private def system_name_trim self.event_system_name = self.event_system_name.strip self.event_system_name = self.event_system_name.downcase end def update_purge_date self.purge_date = self.end_date + 14.days end def update_purge_status self.purge_status = false if self.purge_status == nil end def update_url if self.company.cluster.name == "staging" self.link = "https://#{self.company.system_name}-staging.jifflenow.com/#{self.event_system_name}" elsif self.company.cluster.name == "demo" self.link = "https://#{self.company.system_name}-staging.jifflenow.com/#{self.event_system_name}" else self.link = "https://#{self.company.system_name}.jifflenow.com/#{self.event_system_name}" end end end
# @author Carlos Arvelo Garcia (alu0100943849) require 'nutrientes/version' require 'Antropometrico' #Clase Individuo almacena los datos de un individuo class Individuo attr_reader :nombre def initialize(nombre) @nombre = nombre @datos = nil end # Comprueba si el Tipo de un objeto es de tipo Individuo # # == Parameters: # Recibe un objeto # # == Returns: # Retorna true o false def es (other) if other.is_a? Individuo @nombre == other.nombre elsif false end end # Define el metodo para imprimir por pantalla # # == Parameters: # No recibe ninguno # # == Returns: # Un string con el contenido de las variables def to_s puts "#{nombre}" end end class Pacientes < Individuo attr_reader :datos def initialize(nombre,datos) super(nombre) @datos = datos end def == (other) if other.is_a? Individuo nombre == other.nombre elsif false end end # Comprueba entre que valores esta el icm de un pacuente y determina su estado corporal # # == Parameters: # No recibe ninguno # # == Returns: # Un string con el peso del paciente def indice_corporal if @datos.indice_masa_corporal <= 18.5 "Bajo peso" elsif @datos.indice_masa_corporal > 18.5 and @datos.indice_masa_corporal <= 24.9 "Peso adecuado" elsif @datos.indice_masa_corporal > 25.0 and @datos.indice_masa_corporal <= 29.9 "Sobrepeso" elsif @datos.indice_masa_corporal > 30.0 and @datos.indice_masa_corporal <= 34.9 "Obesidad grado 1" elsif @datos.indice_masa_corporal > 35.0 and @datos.indice_masa_corporal <= 39.9 "Obesidad grado 2" elsif @datos.indice_masa_corporal > 40 "Obesidad grado 3" end end # Define el metodo para imprimir por pantalla # # == Parameters: # No recibe ninguno # # == Returns: # Un string con el contenido de las variables def to_s "#{@datos.indice_masa_corporal}" end end
class CreateCheckOutEarlyViews < ActiveRecord::Migration def change create_view :check_out_early_views, materialized: true end end
class PurchaseMailer < ApplicationMailer def mail_purchase_notification(customer_email, message) @customer_email = customer_email @message = message shop_email = 'filip.maslovaric@gmail.com' mail(to: shop_email, subject: "Customer @ #{@customer_email} just made a purchase!") end def mail_purchase_confirmation(customer_email, message) @customer_email = customer_email @message = message mail(to: @customer_email, subject: "Your order was successful!") end end
class CustomersController < ApplicationController def index customers = Customer.all render json: customers.as_json(except: [:created_at, :updated_at]), status: :ok end end
require "redis" require "sinatra" require "uri" class App < Sinatra::Base configure do set :redis, Redis.new(:url => ENV["REDIS_URI"]) end get "/" do <<-HTML <html> <p>Hello, Redis!</p> <form method="post" action="/set"> Set <input name="key" placeholder="key" required> = <input name="value" placeholder="value" required> <input type="submit" value="Set"> </form> </html> HTML end get "/get/:key" do |key| puts "Retrieving value for #{key}" settings.redis.get(key) # result goes to user end post "/set/:key/:value" do |key, value| puts "Setting value #{key} = #{value}" settings.redis.set(key, value) # result goes to user end post "/set" do key = request["key"] value = request["value"] puts "Setting value #{key} = #{value}" settings.redis.set(key, value) # result goes to user end error do err = env['sinatra.error'] if err "Encountered an error: #{err.class.name}" # goes to user end end end
# you can write to stdout for debugging purposes, e.g. # puts "this is a debug message" def solution(a) # write your code in Ruby 2.2 a.sort! #use two pointers and do slidding window technique pointer_a = 0 pointer_b = 1 while(pointer_b < a.size) if a[pointer_a] == a[pointer_b] a.delete(a[pointer_a]) else pointer_a += 1 pointer_b += 1 end end return a[0] end
module Api::V1 class OnlyCardMemberSerializer < ActiveModel::Serializer attributes :id, :individuals_point end end
FactoryGirl.define do factory :studio_brand_studio do association :studio_brand association :studio end end
# frozen_string_literal: true module Dynflow module Debug module Telemetry module Persistence methods = [ :load_action, :load_actions, :load_action_for_presentation, :load_action, :load_actions, :load_action_for_presentation, :load_actions_attributes, :save_action, :find_execution_plans, :find_execution_plan_counts, :delete_execution_plans, :load_execution_plan, :save_execution_plan, :find_old_execution_plans, :find_past_delayed_plans, :delete_delayed_plans, :save_delayed_plan, :set_delayed_plan_frozen, :load_delayed_plan, :load_step, :load_steps, :save_step, :push_envelope, :pull_envelopes ] methods.each do |name| define_method(name) do |*args| Dynflow::Telemetry.measure(:dynflow_persistence, :method => name, :world => @world.id) { super *args } end end end end end end ::Dynflow::Persistence.send(:prepend, ::Dynflow::Debug::Persistence)
require 'spec_helper' describe Comment do describe "valid comment" do subject { create(:comment) } it "is valid with a link and a comment and a username" do should be_valid end end describe "invalid comment" do it "is invalid without a link" do expect(build(:comment, link: nil)).to have(1).errors_on(:link) end it "is invalid without a comment" do expect(build(:comment, comment: nil)).to have(1).errors_on(:comment) end it "is invalid without a username" do expect(build(:comment, username: nil)).to have(1).errors_on(:username) end end end
load 'Modelo/Conectividad.rb' load 'Modelo/Disco.rb' load 'Modelo/Grafica.rb' load 'Modelo/Procesador.rb' load 'Modelo/Puertos.rb' load 'Modelo/Ram.rb' load 'Modelo/Componente.rb' class ModeloPC::Ordenador def initialize disco, procesador, puertos, ram, conectividad, grafica @disco=disco @procesador=procesador @puertos=puertos @ram=ram @conectividad=conectividad @grafica=grafica end def precio_total @total= @disco.precio.to_i+@procesador.precio.to_i+@puertos.precio.to_i+@ram.precio.to_i+@conectividad.precio.to_i+@grafica.precio.to_i end def to_s "Descripción de componentes:\n#{@disco}#{@procesador}#{@puertos}#{@ram}#{@conectividad}#{@grafica}El precio total: #{precio_total} €" end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| # Use a preconfigured Vagrant box config.vm.box = "charlesportwoodii/php7_xenial64" config.vm.box_check_update = true # Mount the directory with sufficient privileges config.vm.synced_folder ".", "/var/www", id: "vagrant-root", owner: "vagrant", group: "www-data", mount_options: ["dmode=775,fmode=775"] # Provisioning config.vm.provision "shell", inline: <<-SHELL, privileged: false # Upgrade PHP & Nginx echo "Upgrading web server packages" sudo apt-get update sudo apt-get install -y php7.0-fpm nginx-mainline sudo ldconfig # Update the user's path for the ~/.bin directory export BINDIR="$HOME/.bin" if [[ ! -d "${BINDIR}" ]] then # Add ~/.bin to PATH and create the ~/.bin directory echo "export PATH=\"\$PATH:\$HOME/.bin\"" >> /home/vagrant/.bashrc mkdir -p /home/vagrant/.bin chown -R vagrant:vagrant /home/vagrant/.bin # Install Composer php -r "readfile('https://getcomposer.org/installer');" > composer-setup.php php -r "if (hash('SHA384', file_get_contents('composer-setup.php')) === '7228c001f88bee97506740ef0888240bd8a760b046ee16db8f4095c0d8d525f2367663f22a46b48d072c816e7fe19959') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php --install-dir=/home/vagrant/.bin --filename=composer php -r "unlink('composer-setup.php');" # Make sure the composer file has the right permissions on it chmod a+x /home/vagrant/.bin/composer chown -R vagrant:vagrant /home/vagrant/.bin/composer fi # Make composer do Parallel Downloading /home/vagrant/.bin/composer global require hirak/prestissimo # Copy the Nginx configuration and restart the web server echo "Copying Nginx configuration" sudo service nginx stop sudo killall nginx # Copy the new configuration files in sudo cp /var/www/config/.vagrant/http.conf /etc/nginx/conf/conf.d/http.conf sudo service nginx start # Create the database echo "Creating MySQL database if it is not present" mysql -u root -proot -e "CREATE DATABASE IF NOT EXISTS root;" # Update composer /home/vagrant/.bin/composer self-update # Install the website cd /var/www rm -rf /var/www/vendor /home/vagrant/.bin/composer install -ovn # Run the migration chmod a+x /var/www/yii ./yii migrate/up --interactive=0 SHELL end
describe "DELETE /spot/:id" do before(:all) do result = SpotApi.new.session({ email: "delete@gmail.com" }) @user_id = result.parsed_response["_id"] end describe "when delete unique spot" do before(:all) do spot = ({ thumbnail: "delete.jpg", company: "Deletão", techs: ["java", "react"], price: 120, user: @user_id.to_mongo_id }) @spot_id = MongoDb.new.save_spot(spot) @result = SpotApi.new.remove_spot(@user_id, @spot_id) end it "should return 204" do expect(@result.response.code).to eql "204" end # it "should return empty body" do # expect(@result.parsed_response).to be_empty # end after(:all) do result = SpotApi.new.find_spot(@user_id, @spot_id) expect(result.response.code).to eql "404" end end describe "when spot does not exists" do before(:all) do @spot_id = MongoDb.new.mongo_id @result = SpotApi.new.remove_spot(@user_id, @spot_id) end it "should return 204" do expect(@result.response.code).to eql "204" end # it "should return empty body" do # expect(@result.response.code).to be_empty # end end end
module SessionsHelper def current_user @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id] end def admin? logged_in? && session[:user_id] == current_user.id && current_user.admin end def logged_in? !current_user.nil? end end
module Rednode class Process < EventEmitter include Constants include Namespace attr_reader :global, :env, :scheduler def initialize(node) @node = node @engine = node.engine @global = @engine.scope @bindings = {} @env = Env.new @scheduler = Rednode::Scheduler.new end def binding(id) if @bindings[id] @bindings[id] elsif Rednode::Bindings::const_defined?(pascalize(id)) @bindings[id] = Rednode::Bindings::const_get(pascalize(id)).new elsif id == "natives" exports = @engine['Object'].new for native in Dir["#{NODE_HOME}/lib/*.js"] File.basename(native) =~ /^(.*)\.js$/ exports[$1] = File.read(native) end @bindings[id] = exports else raise "no such module: #{id}" end end def compile(source, filename) @engine.eval(source, filename) end def argv ['rednode', @node.main] end def cwd(*args) Dir.pwd end def chdir(dirname) Dir.chdir(dirname) end def _byteLength(str, encoding = 'utf8') chars = encoding == 'utf8' ? str.unpack('C*') : str.unpack('U*') chars.length end #TODO: find a good place to read this. def version "0.2.0" end def loop(*args) @scheduler.start_loop end def dlopen(filename, exports) raise "Rednode currently can't read native (.node) modules. Failed to load: #{filename}" end def umask(mask = nil) mask ? File.umask(mask) : File.umask end def _needTickCallback(*args) @scheduler.next_tick do @node.engine.eval("process._tickCallback()") end end class Env def [](property) ENV.has_key?(property) ? ENV[property] : yield end end class Timer attr_accessor :callback def initialize(process) @process = process @timer = nil end def start(start, interval) if interval == 0 @timer = @process.scheduler.add_timer(start) { callback.call } else @timer = @process.scheduler.add_periodic_timer(start) { callback.call } end end def cancel @process.scheduler.cancel_timer(@timer) end end def Timer @timer ||= lambda { Process::Timer.new(self) } end EventEmitter = self.superclass private def pascalize(str) str.gsub(/(_|^)(\w)/) {$2.upcase} end end end