text
stringlengths
10
2.61M
#!/opt/ruby/bin/ruby require '/applis/cmd/cmd_line.rb' require 'savon' require 'pp' require 'mixlib/shellout' require 'oci8' require 'html/table' include HTML require 'mail' require 'fileutils' class Histo attr_accessor :cmd, :env, :app, :options, :env_name def initialize(cmd) @cmd = cmd @options = cmd.options @app = cmd.app_conf set_env end def set_env @env = app[options[:env]] raise "[initialize] Could not Find env='#{options[:env]}'" if env.nil? end def launch_action return 1 end end def prm_watcher_main cmd cmd.get_opts raise '[histo_main] Could not Parse Arguments' unless cmd.check_args prm_watcher = PrmWatcher.new cmd return prm_watcher.launch_action end cmd = CmdLine.new __FILE__ begin exit_code = prm_watch_main cmd rescue Exception => e cmd.err_stack e, "[main] Unexpected Error" exit_code = 5 end exit exit_code
class DropTempletIdFromPages < ActiveRecord::Migration def change remove_column :pages, :templet_id end end
module ActionComponent module ActionControllerRendering private def render_component(component_class, opts = {}) @_component_class = component_class @_component_options = opts render_opts = { inline: "<% render_component(@_component_class, @_component_options) %>", layout: true } [:content_type, :layout, :location, :status, :formats].each do |option| render_opts[option] = opts[option] if opts.member?(option) end render render_opts end end end
class V1::Apps::ItemsController < V1::AppsController before_filter :set_resources, :set_amount def add item = @inventory.add_item(@app_item, @amount) render status: :ok, json: item end def take item = @inventory.subtract_item(@app_item, @amount) if item render status: :ok, json: item else render status: 428, json: {errors: ["Not enough '#{@app_item.key}' on Inventory #{@inventory.id}"]} end end private def set_resources @app_item = App.find_by(package_name: params[:app_id]).app_items.find_by(key: params[:id]) @inventory = Inventory.find_by(user_id: params[:user_id], app_id: @app_item.app_id) end def set_amount @amount = params[:amount] head :bad_request if @amount.blank? end end
require 'yt/models/base' module Yt module Models # Provides methods to interact with YouTube ContentID claims. # @see https://developers.google.com/youtube/partner/docs/v1/claims class Claim < Base attr_reader :auth, :data def initialize(options = {}) @data = options[:data] @id = options[:id] @auth = options[:auth] @asset = options[:asset] if options[:asset] end # @!attribute [r] claim_history # @return [Yt::Collections::ClaimHistories] the claim's history. has_one :claim_history # Soft-deletes the claim. # @note YouTube API does not provide a +delete+ method for the Asset # resource, but only an +update+ method. Updating the +status+ of a # Asset to "inactive" can be considered a soft-deletion. # @return [Boolean] whether the claim is inactive. def delete body = {status: :inactive} do_patch(body: body) {|data| @data = data} inactive? end # @return [String] the ID that YouTube assigns and uses to uniquely # identify the claim. has_attribute :id # @return [String] the unique YouTube asset ID that identifies the asset # associated with the claim. has_attribute :asset_id # @return [String] the unique YouTube video ID that identifies the video # associated with the claim. has_attribute :video_id # Status # Returns the claim’s status. # @return [String] the claim’s status. Possible values are: +'active'+, # +'appealed'+, +'disputed'+, +'inactive'+, +'pending'+, +'potential'+, # +'takedown'+, +'unknown'+. # @note When updating a claim, you can update its status from active to # inactive to effectively release the claim, but the API does not # support other updates to a claim’s status. has_attribute :status # @return [Boolean] whether the claim is active. def active? status == 'active' end # @return [Boolean] whether the claim is appealed. def appealed? status == 'appealed' end # @return [Boolean] whether the claim is disputed. def disputed? status == 'disputed' end # @return [Boolean] whether the claim is inactive. def inactive? status == 'inactive' end # @return [Boolean] whether the claim is pending. def pending? status == 'pending' end # @return [Boolean] whether the claim is potential. def potential? status == 'potential' end # @return [Boolean] whether the claim is takedown. def takedown? status == 'takedown' end # @return [Boolean] whether the claim status is unknown. def has_unknown_status? status == 'unknown' end # Content Type # Returns the audiovisual portion of the claimed content. # @return [String] the audiovisual portion of the claimed content. # Possible values are: +'audio'+, +'audiovisual'+, +'video'+. has_attribute :content_type # @return [Boolean] whether the claim covers only the audio. def audio? content_type == 'audio' end # @return [Boolean] whether the claim covers only the video. def video? content_type == 'video' end # @return [Boolean] whether the claim covers both audio and video. def audiovisual? content_type == 'audiovisual' end # @return [String] the source of the claim def source @data.fetch('origin', {})['source'] end # @return [Yt::Models::Asset] the asset of the claim def asset @asset end # @return [Time] the date and time that the claim was created. has_attribute :created_at, type: Time, from: :time_created # @return [Boolean] whether a third party created the claim. has_attribute :third_party?, from: :third_party_claim do |value| value == true end # Return whether the video should be blocked where not explicitly owned. # @return [Boolean] whether the claimed video should be blocked anywhere # it is not explicitly owned. For example, if you upload a video for an # asset that you own in the United States and Canada, and you claim the # video with a usage policy to monetize the video everywhere. Since the # policy is only applied in countries where you own the asset, YouTube # will actually monetize the video in the United States and Canada. # By default, the video will still be viewable in other countries even # though it will not be monetized in those countries. However, if you # set this property to true, then the video will be monetized in the # United States and Canada and blocked in all other countries. has_attribute :block_outside_ownership?, from: :block_outside_ownership # @return [String] The unique ID that YouTube uses to identify the # reference that generated the match. has_attribute :match_reference_id, from: :match_info do |match_info| (match_info || {})['referenceId'] end private # @see https://developers.google.com/youtube/partner/docs/v1/claims/update def patch_params super.tap do |params| params[:expected_response] = Net::HTTPOK params[:path] = "/youtube/partner/v1/claims/#{id}" params[:params] = {on_behalf_of_content_owner: @auth.owner_name} end end end end end
class Rental < ApplicationRecord belongs_to :customer belongs_to :movie validates :customer_id, presence: true validates :movie_id, presence: true def rent_movie(customer, movie) checked_out = customer.movies_checked_out_count customer.update(movies_checked_out_count: checked_out +1) inventory = movie.available_inventory movie.update(available_inventory: inventory - 1) end def return_movie(customer, movie) checked_out = customer.movies_checked_out_count customer.update(movies_checked_out_count: checked_out -1) inventory = movie.available_inventory movie.update(available_inventory: inventory +1) end end
class Api::V1::TopicsController < ApplicationController def index respond_to do |wants| begin owner # Load. wants.json { render :json => topics_hash } rescue ActiveRecord::RecordNotFound => e wants.json { render :json => e.message, :status => :not_found } end end end private def topics_hash @topics_hash ||= Api::V1::Helpers.topics_hash(owner) end def owner @owner ||= if params[:category_id] load_category elsif params[:product_id] load_product end end def load_category partner_category = PartnerCategory.find_by_source_id_and_partner_key( source.id, params[:category_id]) or raise(ActiveRecord::RecordNotFound, "Couldn't find PartnerCategory with partner_key=#{params[:category_id]}") partner_category.category rescue ActiveRecord::RecordNotFound # If partner_key logic fails, fall back. Category.find params[:category_id] end def load_product partner_product = PartnerProduct.find_by_source_id_and_partner_key( source.id, params[:product_id]) or raise(ActiveRecord::RecordNotFound, "Couldn't find PartnerProduct with partner_key=#{params[:product_id]}") partner_product.product rescue ActiveRecord::RecordNotFound # If partner_key logic fails, fall back. Product.find params[:product_id] end def source @source ||= case @cobrand.short_name when "mysears" then Source["sears"] when "mykmart" then Source["kmart"] end end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/fingerprintless/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Joost Diepenmaat"] gem.email = ["joost@moneybird.com"] gem.description = "Use the rails image_tag without fingerprinting." gem.summary = "Don't want to use fingerprinted filenames when you use <%= image_tag => on your rails website in production mode? Use fingerprintless." gem.homepage = "https://github.com/moneybird/fingerprintless" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "fingerprintless" gem.require_paths = ["lib"] gem.version = Fingerprintless::VERSION end
class CreateFormNumbers < ActiveRecord::Migration def change create_table :form_numbers do |t| t.string :trsType, limit: 2 t.string :yymm, limit: 6 t.integer :seq t.timestamps null: false end end end
require 'rails_helper' feature 'User can see a list of 5 of their Github repositories' do scenario 'with the name of each Repo linking to the repo on Github' do VCR.use_cassette('GitHub Feature User Sees Their Repos') do user = create(:user) GhUser.create(token: ENV['USER_GITHUB_TOKEN_1'], user_id: user.id) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit '/dashboard' expect(current_path).to eq('/dashboard') expect(page).to have_content('Github') expect(page).to have_content('Repositories') expect(page).to have_css('.repo', count: 5) within(first('.repo')) do expect(page).to have_css('.name') expect(page).to have_link('trelora_consult_app') end end end end feature 'A different user can see a list of 5 of their Github repositories' do scenario 'with the name of each Repo linking to the repo on Github' do VCR.use_cassette('GitHub Feature A Different User Sees Their Repos') do user = create(:user) GhUser.create(token: ENV['USER_GITHUB_TOKEN_2'], user_id: user.id) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit '/dashboard' expect(current_path).to eq('/dashboard') expect(page).to have_content('Github') expect(page).to have_content('Repositories') expect(page).to have_css('.repo', count: 5) within(first('.repo')) do expect(page).to have_css('.name') expect(page).to have_link('night_writer') end end end end feature 'User can not see a Github section' do scenario "if they have not connected to Github" do user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit '/dashboard' expect(current_path).to eq('/dashboard') expect(page).to have_button('Connect to Github') expect(page).to_not have_content('Repositories') end end
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Note::Base < ApplicationRecord self.table_name = 'notes' class_attribute :rdf_namespace, :rdf_predicate self.rdf_namespace = nil self.rdf_predicate = nil # ********** Validations # FIXME: throws validation errors # validates :position, uniqueness: { scope: [:owner_id, :owner_type] } validates :position, numericality: { greater_than: 0 } # FIXME: None?? What about language and value? # ********** Associations belongs_to :owner, polymorphic: true belongs_to :concept, class_name: Iqvoc::Concept.base_class_name, foreign_key: 'owner_id', optional: true belongs_to :collection, class_name: Iqvoc::Collection.base_class_name, foreign_key: 'owner_id', optional: true has_many :annotations, class_name: 'Note::Annotated::Base', foreign_key: :note_id, dependent: :destroy, inverse_of: :note accepts_nested_attributes_for :annotations # ********** Scopes default_scope { order(position: :asc) } before_validation(on: :create) do if position.blank? self.position = (self&.owner&.send(Iqvoc.change_note_class_name.to_relation_name)&.maximum(:position) || 0).succ end end def self.by_language(lang_code) lang_code = Array.wrap(lang_code).flatten.compact if lang_code.none? || lang_code.include?(nil) where(arel_table[:language].eq(nil).or(arel_table[:language].in(lang_code))) else where(language: lang_code) end end def self.by_query_value(query) where(["#{table_name}.value ILIKE ?", query.mb_chars.downcase.to_s]) end def self.by_owner_type(klass) where(owner_type: klass.is_a?(ActiveRecord::Base) ? klass.name : klass) end def self.for_concepts where(owner_type: 'Concept::Base') end def self.for_labels where(owner_type: 'Label::Base') end def self.by_owner(owner) if owner.is_a?(Label::Base) for_labels.where(owner_id: owner.id) elsif owner.is_a?(Concept::Base) for_concepts.where(owner_id: owner.id) else raise "Note::Base.by_owner: Unknown owner (#{owner.inspect})" end end # ********** Methods def <=>(other) self.to_s.downcase <=> other.to_s.downcase end # TODO: This should move to umt because the "list" is more or less proprietary def from_annotation_list!(str) str.gsub(/\[|\]/, '').split('; ').map { |a| a.split(' ') }.each do |annotation| namespace, predicate = annotation.first.split(':', 2) annotations << Note::Annotated::Base.new(value: annotation.second, namespace: namespace, predicate: predicate) end self end def to_s "#{self.value}" end def self.view_section(obj) 'notes' end def self.view_section_sort_key(obj) 100 end def self.partial_name(obj) 'partials/note/base' end def self.edit_partial_name(obj) 'partials/note/edit_base' end def self.single_query(params = {}) query_str = build_query_string(params) scope = by_query_value(query_str). by_language(params[:languages].to_a) case params[:for] when 'concept' scope = scope.where('concepts.type' => Iqvoc::Concept.base_class_name) .includes(:concept) .references(:concepts) owner = :concept when 'collection' scope = scope.where('concepts.type' => Iqvoc::Collection.base_class_name) .includes(:concept) .references(:concepts) owner = :collection else # no additional conditions scope end if params[:collection_origin].present? collection = Collection::Base.where(origin: params[:collection_origin]).last if collection if owner scope = scope.includes(owner => :collection_members) else scope = scope.includes(:concept => :collection_members) .includes(:collection => :collection_members) end scope = scope.where("#{Collection::Member::Base.table_name}.collection_id" => collection.id) scope = scope.references(:collection_members) else raise "Collection with Origin #{params[:collection_origin]} not found!" end end scope = yield(scope) if block_given? scope.map { |result| SearchResult.new(result) } end def self.search_result_partial_name 'partials/note/search_result' end def build_search_result_rdf(document, result) result.Sdc::link(IqRdf.build_uri(owner.origin)) build_rdf(document, result) end end
require "open-uri" require "net/https" require "yaml" require "cgi" module Oauth HMAC_SHA1 = "HMAC-SHA1" PLAINTEXT = "PLAINTEXT" @debug_flg = true class Token def initialize(token) @http = token["http"] @method = token["method"] @host = token["host"] @path = token["path"] end def get_http @http end def get_method @method end def get_host @host end def get_path @path end end class Authorization def initialize params if params[:file]!=nil load_file params[:file] end end def load_file(filename) json = YAML.load_file filename @consumer_key = json["consumer_key"] @consumer_secret = json["consumer_secret"] @method = json["method"] @req_token = Token.new(json["request_token"]) @auth_token = Token.new(json["authorize"]) @access_token= Token.new(json["access_token"]) return self end def create_params { :oauth_consumer_key => @consumer_key, :oauth_timestamp => Time.now.to_i.to_s, :oauth_nonce => nonce, :oauth_signature_method => @method, :oauth_version => "1" } end def get_params get_body @params end def authorize begin rq = @req_token ua = @auth_token at = @access_token params = create_params params = request_token rq.get_host,rq.get_path,params params = user_authorization ua.get_host,ua.get_path,params params = access_token at.get_host,at.get_path,params @params = params rescue => ext puts ext puts ext.backtrace end end def request_token(host , path , params) #step 1 raise "req token's params are not enough" unless check_request_token params params.store :oauth_signature , signature(params) resp , data = post(host , path , get_body(params)) data.split("&").each do |ele| e = ele.split("=") case e[0] when "oauth_token" params.store :oauth_token, e[1] when "oauth_token_secret" @oauth_token_secret = e[1] end end return params end def user_authorization(host,path,params) #step 2 puts params.collect{|k,v| puts "%s=%s,"%[k,v]} # params.store "GET","" # params.store "https://%s%s"%[host,path],"" system("open 'https://%s%s?%s'"%[host , path, get_body(params)]) sleep 10 return params end def access_token(host,path,params) #step 3 return unless check_access_token params resp, data = post(host , path , get_body(params)) data.split("&").each do |ele| e = ele.split("=") case e[0] when "oauth_token" params.store :oauth_token, e[1] when "oauth_token_secret" @oauth_token_secret = e[1] end end return params end def get_body params singarr = [] pairarr = [] params.collect do |k,v| if v.to_s.empty? singarr << k else pairarr << "%s=%s"%[k,v] end end singarr.concat(pairarr) body = singarr.join("&") puts "" params.delete :oauth_signature unless params[:oauth_signature] ==nil body = "%s&oauth_signature=%s"%[body,signature(params)] return body end def signature(params) return if params[:oauth_signature_method]==nil case params[:oauth_signature_method] when HMAC_SHA1 return Hmac_sha1.new(@consumer_secret,@oauth_token_secret,params).get_signature when PLAINTEXT return CGI.escape("%s&%s"%[@consumer_secret,@oauth_token_secret]) else return end end def post(host,path,body) raise "host is nil" if host==nil raise "path is nil" if path==nil raise "body is nil" if body==nil http = Net::HTTP.new(host,443) http.use_ssl = true http.set_debug_output $stderr if @debug_flg return http.post(path, body) end def check_tokens(params) raise "oauth_consumer_key is nil" if params[:oauth_consumer_key] == nil raise "oauth_signature_method is nil" if params[:oauth_signature_method] == nil raise "oauth_timestamp is nil" if params[:oauth_timestamp] == nil raise "oauth_nonce is nil" if params[:oauth_nonce] == nil raise "oauth_version is nil" if params[:oauth_version] == nil return true end def nonce return @nonce unless @nonce == nil @nonce = rand(100000000).to_s+Time.now.to_i.to_s end def check_request_token(params) return check_tokens params end def check_access_token(params) return check_tokens params end end class Hmac_sha1 def initialize(consumer_secret,oauth_token_secret,params) @consumer_secret = consumer_secret @oauth_token_secret = oauth_token_secret @params = params end def get_signature body = @params.collect{|k,v| "%s=%s"%[k,v]}.sort.join("&") digest = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA1.new,"%s&%s"%[@consumer_secret,@oauth_token_secret]) end end end
require "sinatra" require "rack" require "rack/contrib" require "ruby-bandwidth" require "yaml" Call = Bandwidth::Call Bridge = Bandwidth::Bridge client = nil options = YAML.load(File.read("./options.yml")) use Rack::PostBodyContentTypeParser get "/" do if !options["api_token"] || !options["api_secret"] || !options["caller"] || !options["bridge_callee"] || !options["domain"] "Please fill options.yml with right values" else "This app is ready to use" end end post "/start/demo" do halt 400, "number is required" unless params["to"] callback_url = "http://#{options["domain"]}/events/demo"; Call.create(client, { :from => options["caller"], :to => params["to"], :callback_url => callback_url, :recording_enabled => false }) end post "/events/demo" do call = Call.new({:id => params["callId"]}, client) case(params["eventType"]) when "answer" sleep 3 call.speak_sentence("hello flipper", "hello-state") when "speak" return "" unless params["status"] == "done" case(params["tag"]) when "gather_complete" Call.create(client, { :from => options["caller"], :to => options["bridge_callee"], :callback_url => "http://#{options["domain"]}/events/bridged", :tag => "other-leg:#{call.id}" }) when "terminating" call.hangup() when "hello-state" call.play_audio({ :file_url => "http://#{options["domain"]}/dolphin.mp3", :tag => "dolphin-state" }) end when "dtmf" if params["dtmfDigit"][0] == "1" call.speak_sentence("Please stay on the line. Your call is being connected.", "gather_complete") else call.speak_sentence("This call will be terminated", "terminating") end when "playback" return "" unless params["status"] == "done" if params["tag"] == "dolphin-state" call.create_gather({ :max_digits => 2, :terminating_digits => "*", :inter_digit_timeout => "3", :prompt => { :sentence => "Press 1 to speak with the dolphin, press 2 to let it go", :loop_enabled => false, :voice => "Kate" }, :tag => "gather_started" }) end else puts "Unhandled event type #{params["eventType"]} for #{request.url}" end end post "/events/bridged" do call = Call.new({:id => params["callId"]}, client) values = (params["tag"] || "").split(":") other_call_id = values[1] case (params["eventType"]) when "answer" sleep 3 call.speak_sentence("You have a dolphin on line 1. Watch out, he's hungry!", "warning:#{other_call_id}") when "speak" return "" unless params["status"] == "done" if values[0] == "warning" Bridge.create(client, { :callIds => [other_call_id] }) end when "hangup" call.id = other_call_id if params["cause"] == "CALL_REJECTED" call.speak_sentence("We are sorry, the user rejected your call", "terminating") else call.hangup() end else puts "Unhandled event type #{params["eventType"]} for #{request.url}" end end opts = {} options.each do |k,v| opts[k.to_sym] = v end client = Bandwidth::Client.new(opts) set :bind, "0.0.0.0" set :port, (ENV["PORT"] || "3000").to_i set :public_folder, "public"
require 'rails_helper' describe Assignment do it { should validate_presence_of :course } end
feature 'PremierRequests' do let!(:premier) { create(:premier) } let!(:first_request) { create(:request, user: premier) } let!(:second_request) { create(:request, user: premier) } let!(:third_request) { create(:request) } describe 'Pending requests ' do it 'should transition correctly through request states' do expect(Request.by_premier(premier).length).to be 2 expect(Request.pending.by_premier(premier).length).to be 2 first_request.accept! expect(Request.pending.by_premier(premier).length).to be 1 expect(Request.accepted.by_premier(premier).length).to be 1 second_request.reject! expect(Request.pending.by_premier(premier).length).to be 0 expect(Request.rejected.by_premier(premier).length).to be 1 end end end
# This class store infomation for person class Person # Init object person with name def initialize(name) # Create an exception throw error when attribute name empty raise ArgumentError, 'No name present' if name.empty? end end # This class BaddataException inherit standard RuntimeError class BadDataException < RuntimeError; end class Person def initialize(name) raise BadDataException, 'No name present' if name.empty? end end fred = Person.new('') begin puts 10 / 0 rescue => exception puts exception.class puts 'You caused an error!' end # catch and throw catch(:finish) do 10.times do x = rand(10) puts x throw :finish if x == 3 end puts 'Generated 1000 random number without generating 3!' end
#require_relative "../lib/models/countryholiday.rb" #require_relative "../Seeding_Stuff/populateCountryHoliday.rb" # use .inspect on a file? # PASTE IN ALL DATA !!! (@ top of this file) # move files to Seeding Stuff def find_country_holiday_pairs(data) all_array = [] data.each do |country, server_replies| #CountryHoliday.create(country_id: , holiday_id: ) server_replies.each do |server_reply, server_datas| #server_datas = holidays if server_reply == "response" server_datas.each do |holiday_key, holiday_values | holiday_values.each do |holiday_array_element| holiday_array_element.each do |holiday_hash, holiday_datas| if holiday_hash == "name" all_array << country all_array << holiday_datas end end end end end end end return all_array end # seed_array = find_country_holiday_pairs(holidays_of_the_world) # holidays_of_the_world = US only to test def populate_db_holidays_countries(array) country_id_for_db = nil holiday_id_for_db = nil array.each_with_index do |element, elements_index| if elements_index % 2 == 0 country_id_for_db = Country.where(:country_code => "#{element}")[0].id else if element != holiday_id_for_db holiday_id_for_db = Holiday.where(:name => "#{element}")[0].id if CountryHoliday.where(country_id: country_id_for_db, holiday_id: holiday_id_for_db) == [] CountryHoliday.create(country_id: country_id_for_db, holiday_id: holiday_id_for_db ) end end end end end
# frozen_string_literal: true feature 'delete listing' do scenario 'If a user owns a listing they can choose to delete it' do visit '/' click_on 'Sign in' fill_in('username', with: 'poshhouseperson') fill_in('password', with: 'password1') click_button 'Submit' click_on 'poshhouse' click_button 'Delete listing' expect(page).to have_button('Add listing') end end
class ChangeDefaultValue < ActiveRecord::Migration[5.2] def change change_column_default :bids, :status, from: "true", to: "pending" end end
module SessionsHelper def signed_in? !current_user.nil? end def current_user=(user) @current_user = user end def current_user remember_token = cookies[:remember_token] if remember_token.nil? @current_user = nil else session = Session.include(:user).find_by remember_token: Session.encrypt(remember_token) @current_user ||= session.user end @current_user end def current_user?(user) signed_in? && !user.nil? && user.id == current_user.id end #def current_user_by_id?(user_id) # !current_user.nil? && !user_id.nil? && user_id == current_user.id.to_s #end def signed_in_user unless signed_in? redirect_to signin_url, notice: "Please sign in." end end def unsigned_in_user unless !signed_in? redirect_to signin_url, notice: "Please sign in." end end #def redirect_back_or(default) # #redirect_to(session[:return_to] || default) # session.delete(:return_to) #end #def store_location # session[:return_to] = request.get? ? request.url : nil #if request.get? #end end
#!/usr/bin/env ruby # # profile-grep will take a stdin list of collapsed graphs (see note-collapse) # read through the posts, and then take the arguments from the command line # and print out the posts which have the percentage of likes and reblogs # matching the pattern # # By using stdin, this allows one to read over multiple blogs. # require 'rubygems' require 'bundler' Bundler.require $start = Time.new count = 0 qstr = ARGV[0] puts "Searching for #{qstr}" resultsMap = {} $stdin.each_line { | file | file.strip! count += 1 if count % 200 == 0 $stderr.putc "." end File.open(file, 'r') { | content | keyout = file.gsub('graphs', 'post').gsub('.json','').gsub('/raid/tumblr','http:/') resultsMap[keyout] = 0 json = JSON.parse(content.read) map = {} json.each { | entry | if entry.is_a?(String) who = entry else who, source, post = entry who = source end unless map.key? who map[who] = true unless (who =~ /#{qstr}/).nil? resultsMap[keyout] += 1.0 end end } resultsMap[keyout] /= [json.length, 70].max.to_f } } resultsMap.sort_by{|k, v| v }.each { | name, count | printf "%5.3f %-25s\n", count * 100, name unless count == 0 }
# -*- coding: utf-8 -*- # # = bitstring.rb - Bounded and unbounded bit strings # # Author:: Ken Coar # Copyright:: Copyright © 2010 Ken Coar # License:: Apache Licence 2.0 # # == Synopsis # # require 'rubygems' # require 'bitstring' # bString = BitString.new([initial-value], [bitcount]) # bString = BitString.new(bitcount) { |index| block } # # Bug/feature trackers, code, and mailing lists are available at # http://rubyforge.org/projects/bitstring. # # Class and method documentation is online at # http://bitstring.rubyforge.org/rdoc/ # # == Description # # The <i>BitString</i> package provides a class for handling a series # of bits as an array-like structure. Bits are addressable individually # or as subranges. # # BitString objects can be either bounded or unbounded. Bounded bitstrings # have a specific number of bits, and operations that would affect bits # outside those limits will raise exceptions. Unbounded bitstrings can # grow to arbitrary lengths, but some operations (like rotation) cannot # be performed on them. #-- # Copyright © 2010 Ken Coar # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You may # obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. #++ require 'rubygems' require 'versionomy' require 'bitstring/operators' # # It's sort of like a fake a subclass of Integer solely to # differentiate bitstrings. # class BitString # # Versionomy object for the class, recording the current version. # Version = Versionomy.parse('1.0.0') # # Version number as a simple readable string. # VERSION = Version.to_s # # Other constants: # # # Identifer specifying the least significant (low) end of the bitstring # (used by <i>grow</i>, <i>shrink</i>, and <i>mask</i>). # LOW_END = :low # # Identifer specifying the most significant (high) end of the bitstring # (used by <i>grow</i>, <i>shrink</i>, and <i>mask</i>). # HIGH_END = :high # :stopdoc: # # These classes are part of our internal error condition handling # mechanism, and aren't intended to be used externally. # class InternalError < Exception # # Used internally only -- except for internal consistency errors. # end # class InternalError class BadDigit < InternalError # # Turned into an ArgumentError. # end # class BadDigit class BitsRInts < InternalError # # Turned into an ArgumentError. # end # class BitsRInts class BogoIndex < InternalError # # Turned into an IndexError. # end # class BogoIndex class NeedGPS < InternalError # # Turned into an ArgumentError. # end # class NeedGPS class NoDeficitBits < InternalError # # Turned into an IndexError. # end # class NoDeficitBits class OuttasightIndex < InternalError # # Turned into an IndexError. # end # class OuttasightIndex class UnboundedNonsense < InternalError # # Turned into a RuntimeError. # end # class UnboundedNonsense class UnInterable < InternalError # # Turned into a RuntimeError. # end # class UnInterable class WrongNargs < InternalError # # Turned into an ArgumentError. # end # class WrongNargs # :startdoc: # # We want a bunch of Enumerable's methods.. # include Enumerable # # ..but not all of them. Some just don't make sense for bitstrings. # (.zip makes sense, but I'm going to defer it until I have a test for it.) # undef :grep, :sort, :sort_by, :zip # # <i>Boolean</i>. Whether or not the bitstring is bounded and limited # to a specific length. Read-only; set at object creation. # attr_reader :bounded # # <i>Integer</i>. Length of the bitstring. Only meaningful for bounded # strings. Read-only; set at object creation. # #attr_reader :length # # === Description # # Create a new <i>BitString</i> object. By default, it will be unbounded and # all bits clear. # # :call-seq: # new<i>([val], [bitcount])</i> => <i>BitString</i> # new<i>(length) {|index| block }</i> => <i>BitString</i> # # === Arguments # [<i>val</i>] <i>Array</i>, <i>Integer</i>, <i>String</i>, or <i>BitString</i>. Initial value for the bitstring. If a <i>String</i>, the value must contain only '0' and '1' characters; if an <i>Array</i>, all elements must be 0 or 1. Default 0. # [<i>bitcount</i>] <i>Integer</i>. Optional length (number of bits) for a bounded bitstring. # # === Examples # bs = BitString.new(4095) # bs.to_s # => "111111111111" # bs.bounded? # => false # # bs = BitString.new('110000010111', 12) # bs.bounded? # => true # bs.to_i # => 3095 # # bs = BitString.new(12) { |pos| pos % 2 } # bs.to_s # => "101010101010" # # === Exceptions # [<tt>RangeError</tt>] <i>val</i> is a string, but contains non-binary digits. # def initialize(*args_p, &block) # # Two constructor scenarios: # # 1. With a block and an optional length (defaults to 1) # 2. No block, and with value and length both optional. # # We don't do any type-checking on the arguments until later. # unless (block.nil?) # # We got a block; set up the constraints. Bitstrings constructed # this way are bounded. # unless (args_p.length < 2) raise ArgumentError.new('only bitstring length ' + 'may be specified with a block') end @bounded = true @length = args_p.length > 0 ? args_p[0] : 1 else # # Get value and possibly length from the argument list. # unless (args_p.length < 3) raise ArgumentError.new('wrong number of arguments ' + '(must be 2 or fewer)') end val = args_p[0] || 0 @length = args_p[1] if (@bounded = ! args_p[1].nil?) end # # Now do some validation on the arguments. # if (@bounded) unless ((@length = @length.to_i) > 0) raise ArgumentError.new('bitstring length must be greater than 0') end end if (block.nil?) # # We weren't passed a block, so get the info directly from the argument # list. # @value = _arg2int(val) else # # We were passed a block, so invoke it for each bit position to # determine that bit's value from the LSB of the result. # @value = 0 @length.times { |i| self[i] = block.call(i).to_i & 1 } end end # def initialize # # === Description # # Convert a value from some representation into an integer. Possibly # acceptable inputs are: # # o An <i>Array</i> containing only 0 and 1 values. # o An existing <i>BitString</i> object # o An <i>Integer</i> or descendent binary value # o A <i>String</i> containing only '0' and '1' characters # # Any other inputs will raise an exception. # # :call-seq: # _arg2int<i>(value)</i> => <i>Integer</i> # # === Arguments # [<i>value</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, <i>String</i>. The value to be converted to an integer. # [<i>msg</i>] <i>String</i>. Message to use if we don't have a canned one. # # === Examples # _arg2int(23) # => 23 # _arg2int('110000010111') # => 3095 # _arg2int([1,1,0,0,0,0,0,1,0,1,1,1]) # => 3095 # _arg2int('alpha') # => exception: "ArgumentError: value ('alpha':String) contains invalid digits" # # === Exceptions # [<tt>ArgumentError</tt>] Can't reduce the argument to a binary integer. # def _arg2int(val_p) # :nodoc: if (val_p.class.eql?(BitString)) # # If we were passed a bitstring, convert it. # val = val_p.to_i elsif (val_p.class.eql?(String)) # # If we were given a String for the value, it must consist of valid # binary digits. # _raise(BadDigit, nil, val_p) unless (val_p.gsub(/[01]/, '').empty?) val = val_p.to_i(2) elsif (val_p.class.eql?(Array)) # # If we were given an array, make sure that all the values are # integers and either 1 or 0. # _raise(BadDigit, nil, val_p) unless ((val_p - [0, 1]).empty?) val = val_p.collect { |bit| bit.to_s(2) }.join('').to_i(2) elsif (val_p.kind_of?(Integer)) val = val_p else # # Let's try to convert it to an integer from whatever class we # were passed. # unless (val_p.respond_to?(:to_i)) raise ArgumentError.new('unable to determine bitstring value from ' + "\"#{val_p.to_s}\":#{val_p.class.name}") end end val end # def _arg2int # # === Description # # Raise a standard exception. # # :call-seq: # _raise<i>(exc, [msg])</i> => Exception raised # # === Arguments # [<i>exc</i>] <i>Exception</i>. One of our 'known' repeated exceptions. # [<i>msg</i>] <i>String</i>. Message to use if we don't have a canned one. # # === Examples # _raise(BadDigit, nil, bogusvalue) # _raise(OuttasightIndex, 'you are kidding, right?') # # === Exceptions # [<tt>InternalError</tt>] Called with something other than an exception. # [<i>other</I>] As indicated. # def _raise(*args) # :nodoc: exc = args.shift unless (exc.ancestors.include?(Exception)) raise InternalError.new('asked to raise non-exception') end begin raise InternalError rescue InternalError => e if (args[0].kind_of?(String) && args[0].match(/%/)) msg = sprintf(*args) args = [] elsif (args[0].kind_of?(String)) msg = args.shift else msg = nil end mName = e.backtrace[1].match(/in \`(\S*)'/).captures[0] case exc.name.sub(/^.*::/, '') when 'BadDigit' if (msg.nil?) val = args[1].respond_to?(:to_s) ? args[1].to_s : args[1].inspect msg = "value ('#{val}':#{args[1].class.name}) contains invalid digits" end raise ArgumentError.new(msg) when 'BitsRInts' raise ArgumentError.new(msg || 'bitcount must be an integer') when 'BogoIndex' if (msg.nil?) val = args[0] msg = "illegal index value #{val.inspect}" end raise IndexError.new(msg) when 'NeedGPS' raise ArgumentError.new(msg || 'invalid direction for operation') when 'NoDeficitBits' raise IndexError.new(msg || 'bitcount must be positive') when 'NotImplementedError' raise NotImplementedError.new(msg || "method '#{mName}' not yet implemented") when 'OuttasightIndex' if (msg.kind_of?(Integer)) msg = "index out of range: '#{msg.to_s}'" end raise IndexError.new(msg || 'index out of range') when 'UnboundedNonsense' raise RuntimeError.new(msg || 'operation only meaningful for ' + 'bounded bitstrings') when 'UnInterable' if (msg.nil?) val = args[0].respond_to?(to_s) ? args[0].to_s : args[0].inspect msg = "unable to reduce '#{val}':#{args[0].class.name} " + "to a binary value" end raise ArgumentError.new(msg) when 'WrongNargs' if (msg.nil?) val = args[0].respond_to?(:to_i) ? args[0].to_i : args[0].inspect req = args[1].respond_to?(:to_i) ? args[1].to_i : args[1].inspect msg = "wrong number of arguments (#{val} for #{req})" end raise ArgumentError.new(msg) else raise exc.new(msg) end end end # def _raise # # === Description # # Return a binary string representation of the value, zero filled # or left-truncated to the specified length. # # :call-seq: # _zfill<i>(value, length)</i> => <i>String</i> # # === Arguments # [<i>val</i>] <i>Integer</i> or <i>String</i>. Value to be represented as a string of binary digits. # [<i>length</i>] <i>Integer</i>. Length of output string to return. # # === Examples # _zfill(0, 12) # => "000000000000" # # _zfill(3095, 4) # => "0111" # # _zfill(3095, 15) # => "000110000010111" # # === Exceptions # <i>None</i>. # def _zfill(val_p, length_p) # :nodoc: sVal = val_p.kind_of?(String) ? val_p : val_p.to_s(2) return sVal if (length_p.to_i <= 0) if (length_p > sVal.length) ('0' * (length_p - sVal.length)) + sVal elsif (length_p < sVal.length) sVal[-length_p, length_p] else sVal end end # def _zfill # # === Description # # Return a Boolean indicating whether the bitstring has a fixed length # (is bounded) or not. # # :call-seq: # bitstring.bounded?() # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new(3095) # bs.bounded? # => false # # bs = BitString.new(3095, 12) # bs.bounded? # => true # # === Exceptions # <i>None</i>. # def bounded?() @bounded end # def bounded?() # # === Description # # Return a duplicate of the current bitstring -- with all bits cleared. # # :call-seq: # bitstring.clear<i>()</i> => <i>BitString</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new(3095) # nbs = bs.clear # bs.to_s # => "110000010111" # nbs.to_s # => "0" # # === Exceptions # <i>None</i>. # def clear() bs = dup bs.from_i(0) bs end # def clear() # # === Description # # Clear all the bits in the bitstring. # # :call-seq: # bitstring.clear!<i>()</i> => <i>BitString</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new(3095, 12) # bs.to_s # => "110000010111" # bs.clear! # bs.to_s # => "000000000000" # # === Exceptions # <i>None</i>. # def clear!() @value = 0 self end # def clear!() # # === Description # # Execute a block for each bit in the bitstring. # # :call-seq: # bitstring.<i>each</i> { |<i>bitval</i>| <i>block</i> } => <i>BitString</i> # # === Arguments # [<i>block</i>] <i>Proc</i>. Block to be called for each bit in the string. The block is passed the bit value. # # === Examples # bs = BitString.new('100101') # bs.each { |bitval| puts bitval } # 1 # 0 # 1 # 0 # 0 # 1 # # === Exceptions # <i>None</i>. # def each(&block) self.length.times { |bit| block.call(self[bit]) } self end # def each # # === Description # # Return true if there are no bits set in the bitstring. # # :call-seq: # bitstring.<i>empty?</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('100101') # bs.empty? # => false # # bs = BitString.new('000000') # bs.empty? # => true # # === Exceptions # <i>None</i>. # def empty?() @value.to_i.zero? end # def empty? # # === Description # # Treat the bitstring as an Integer and store its entire value at # once. # # :call-seq: # bitstring.from_i<i>(newval)</i> => <i>BitString</i> # # === Arguments # [<i>newval</i>] <i>Integer</i>. Value from which bits will be copied to the bitstring. # # === Examples # bs = BitString.new(0, 12) # bs.to_s # => "000000000000" # bs.from_i(3095) # bs.to_s # => "110000010111" # # === Exceptions # <i>None</i>. # def from_i(newval) unless (newval.respond_to?(:to_i)) what = newval.respond_to?(:to_s) ? newval.to_s : newval.inspect _raise(UnInterable, newval) end newval = newval.to_i newval &= 2**@length - 1 if (bounded?) @value = newval self end # def from_i() # # === Description # # Return a new bitstring based on the current one, grown (made longer) # in one direction (toward the least significant bits) or the other. # Growing an unbounded string toward the high end is a no-op. # # Bits added are set to <i>defval</i> (default 0). # # :call-seq: # bitstring.grow<i>(bits, [defval], [direction])</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] <i>Integer</i>. Number of bits to add. # [<i>defval</i>] <i>Integer</i>. Value to which added bits should be set. # [<i>direction</i>] <i>Constant</i>. Either <tt>BitString::HIGH_END</tt> (the default) or <tt>BitString::LOW_END</t>. Indicates whether bits are added at the least or most significant end. Growing with <tt>BitString::LOW_END</tt> results in the bitstring being shifted left. # # === Examples # bs = BitString(5, 3) # bs.to_s # => "101" # nbs = bs.grow(3) # nbs.to_s # => "000101" # nbs = bs.grow(3, 1) # nbs.to_s # => "111101" # nbs = bs.grow(3, 0, BitString::LOW_END) # nbs.to_s # => "101000" # # === Exceptions # [<tt>ArgumentError</tt>] <i>bits</i> isn't an integer, <i>defval</i> can't be reduced to a binary value, or <i>direction</i> isn't one of the defined values. # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # [<tt>RuntimeError</tt>] Can't grow an unbounded string at the high end. # def grow(bits=1, defval=0, direction=HIGH_END) unless (bits.kind_of?(Integer)) _raise(BitsRInts) end unless (defval.respond_to?(:to_i)) what = defval.respond_to?(:to_s) ? defval.to_s : defval.inspect _raise(UnInterable, defval) end unless ([HIGH_END, LOW_END].include?(direction)) _raise(NeedGPS) end unless (bits >= 0) _raise(NoDeficitBits) end unless ((direction == LOW_END) || bounded?) _raise(UnboundedNonsense) end return dup if (bits == 0) value = @value vMask = 2**bits - 1 if (direction == HIGH_END) vMask *= 2**@length if (bounded?) elsif (direction == LOW_END) value *= (2**bits) end value |= vMask if (defval == 1) bounded? ? self.class.new(value, @length + bits) : self.class.new(value) end # def grow # # === Description # # As #grow, except that the current bitstring is changed rather # than a new one returned. # # Bits added are set to <i>defval</i> (default 0). # # :call-seq: # bitstring.grow!<i>(bits, [defval], [direction])</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] <i>Integer</i> Number of bits to add. # [<i>defval</i>] <i>Integer</i> Value to which added bits should be set. # [<i>direction</i>] <i>Constant</i>. Either <tt>BitString::HIGH_END</tt> (the default) or <tt>BitString::LOW_END</tt>. Indicates whether bits are added at the least or most significant end. Growing with <tt>BitString::LOW_END</tt> results in the bitstring being shifted left. # # === Examples # bs = BitString.new(5, 3) # bs.to_s # => "101" # bs.grow!(3) # bs.to_s # => "000101" # bs.grow!(3, 1, BitString::LOW_END) # bs.to_s # => "000101111" # # === Exceptions # [<tt>ArgumentError</tt>] <i>bits</i> isn't an integer, <i>defval</i> can't be reduced to a binary value, or <i>direction</i> isn't one of the defined values. # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # [<tt>RuntimeError</tt>] Can't grow an unbounded string at the high end. # def grow!(bits=1, defval=0, direction=HIGH_END) bs = grow(bits, defval, direction) @length = bs.length if (bs.bounded?) @value = bs.to_i self end # def grow! # # === Description # # Return the length of the bitstring. If it's bounded, the fixed size # is returned, otherwise the number of significant binary digits. # # :call-seq: # bitstring.length() # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('101', 3) # bs.length # => 3 # # bs = BitString.new('00101', 5) # bs.length # => 5 # # bs = BitString.new('00101') # bs.length # => 3 # # === Exceptions # <i>None</i>. # def length() bounded? ? @length : @value.to_s(2).length end # def length() # # === Description # # Return the value of the least significant (low) bit. # # :call-seq: # bitstring.lsb() # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('101') # bs.lsb # => 1 # # bs = BitString.new('010') # bs.lsb # => 0 # # === Exceptions # <i>None</i>. # def lsb() self[0] end # def lsb() # # === Description # # Return an integer with bits set to mask the specified portion of the # bitstring. # # If you want to create a mask wider than the bitstring, use the class # method <i>BitString.mask()</i> instead. # # :call-seq: # bitstring.mask<i>([bitcount], [direction])</i> => <i>Integer</i> # # === Arguments # [<i>bitcount</i>] <i>Integer</i>. Number of bits to set in the mask. # [<i>direction</i>] <i>Constant</i>. <tt>BitString::HIGH_END</tt> (the default) or <tt>BitString::LOW_END</tt>. Specifies the end of the bitstring from which the mask starts. # # === Examples # bs = BitString.new(0, 12) # bs.mask.to_s(2) # => "111111111111" # bs.mask(5).to_s(2) # => "111110000000" # bs.mask(5, BitString::LOW_END).to_s(2) # => "11111" # BitString.new(bs.mask(5, BitString::LOW_END), 12).to_s # => "000000011111" # # === Exceptions # [<tt>IndexError</tt>] Raised if <i>bitcount</i> is negative or grater than the bitstring length. # def mask(bits=self.length, direction=HIGH_END) _raise(OuttasightIndex, bits) if (bits > self.length) _raise(NoDeficitBits) if (bits < 0) vMask = 2**bits - 1 vMask *= 2**(self.length - bits) if (direction == HIGH_END) vMask end # def mask() # # === Description # # Class method to return an integer value with the specified number # of bits (starting at position 0) all set to 1. # # :call-seq: # BitString.mask<i>(bitcount)</i> => <i>Integer</i> # # === Arguments # [<i>bitcount</i>] <i>Integer</i>. Number of bits to set in the mask. # # === Examples # BitString.mask(5).to_s(2) # => "11111" # # === Exceptions # <i>None</i>. # def self.mask(bits=1) new._raise(NoDeficitBits) if (bits < 0) vMask = 2**bits - 1 end # def self.mask # # === Description # # Return the value of the most significant (high) bit. # Only meaningful for bounded bitstrings. # # :call-seq: # bitstring.msb() # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('0101') # bs.msb # => 1 # Leading zeroes stripped in unbouded bitstrings # # bs = BitString.new('0101', 4) # bs.msb # => 0 # # === Exceptions # [<tt>RuntimeError</tt>] There is no 'MSB' for an unbounded bitstring. # def msb() unless (bounded?) _raise(UnboundedNonsense, 'most significant bit only applies to bounded bitstrings') end self[@length - 1] end # def msb() # # === Description # # Return the number of bits in the bitstring that are either set (1) # or clear (0). Leading zeroes on unbounded bitstrings are ignored. # # :call-seq: # bitstring.population<i>(testval)</i> => <i>Integer</i> # # === Arguments # [<i>testval</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, or <i>String</i> whose low bit is used for the test. # # === Examples # bs = BitString.new('0001111001010') # bs.population(0) # => 4 # bs.population(1) # => 6 # # bs = BitString.new('0001111001010', 13) # bs.population(0) # => 7 # bs.population(1) # => 6 # # === Exceptions # [<tt>ArgumentError</tt>] The argument cannot be reduced to a binary digit. # def population(val) val = _arg2int(val) & 1 self.select { |bval| bval == val }.length end # def population # # === Description # # Return a copy of the bitstring resized to the specified number of bits, # resulting in truncation or growth. Bits are added to, or removed from, # the high (more significant) end. Resizing an unbounded bitstring # makes it bounded. # # :call-seq: # bitstring.resize<i>(bits)</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] Width of the resulting bitstring. # # === Examples # bs = BitString.new('101') # bs.bounded? # => false # nbs = bs.resize(5) # nbs.bounded? # => true # nbs.length # => 5 # nbs.to_s # => "00101" # nbs = bs.resize(7) # nbs.to_s # => "0000101" # # === Exceptions # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # def resize(bits) unless (bits.kind_of?(Integer)) _raise(BitsRInts) end unless (bits > 0) _raise(NoDeficitBits) end value = @value length = self.length bs = self.class.new(value, length) diffbits = bits - length diffbits < 0 ? bs.shrink!(-diffbits) : bs.grow!(diffbits) end # def resize # # === Description # # As #resize except it's the current bitstring that gets resized. # # :call-seq: # bitstring.resize!<i>(bits)</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] Width of the resulting bitstring. # # === Examples # bs = BitString.new('101') # bs.bounded? # => false # bs.resize!(5) # bs.bounded? # => true # bs.length # => 5 # bs.to_s # => "00101" # bs.resize!(7) # bs.to_s # => "0000101" # # === Exceptions # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # def resize!(bits) bs = resize(bits) @bounded = true @length = bs.length @value = bs.to_i self end # def resize! # # === Description # # Rotate the bitstring, taking bits from one end and shifting them # in at the other. Only makes sense with bounded strings. # # A negative value rotates left; a positive one rotates to the right. # # :call-seq: # bistring.rotate<i>(bits)</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] <i>Integer</i>. Number of positions to rotate left (negative) or right (positive). Bits rotated off one end are rotated in on the other. # # === Examples # bs = BitString.new('000000011111', 12) # bs.rotate(3).to_s # => "000011111000" # bs.rotate(-4).to_s # => "100000001111" # # === Exceptions # [<tt>RuntimeError</tt>] Can't rotate an unbounded bitstring. # def rotate(bits_p) unless (bounded?) _raise(UnboundedNonsense, 'rotation only applies to bounded bitstrings') end value = @value length = @length bits = bits_p.to_i.abs % length vMask = (mult = 2**bits) - 1 ldiff = length - bits if (bits_p > 0) # # Rotate right (toward the LSB) # residue = value & vMask value /= mult value |= residue * 2**ldiff elsif (bits_p < 0) # # Rotate left (toward the MSB) # vMask *= 2**ldiff residue = value & vMask value = ((value & ~vMask) * mult) | (residue / 2**ldiff) end self.class.new(value, @length) end # def rotate # # === Description # # Same as #rotate except that the result is stored back into the # current object. # # :call-seq: # bitstring.rotate!<i>(bits)</i> => <i>BitString</i> # # === Arguments # [<i>bits</i>] <i>Integer</i>. Number of positions to rotate left (negative) or right (positive). Bits rotated off one end are rotated in on the other. # # === Examples # bs = BitString.new('000000011111', 12) # bs.rotate!(3) # bs.to_s # => "000011111000" # bs.rotate!(-4) # bs.to_s # => "100000001111" # # === Exceptions # <i>None</i>. # def rotate!(bits_p) @value = rotate(bits_p).to_i self end # def rotate! # # === Description # # Iterate through all the bits, invoking the specified block with the # value of each in turn. If the block returns a true value, the # bit value is added to the result array. # # :call-seq: # bitstring.select { <i>|bit| block</i> } => <i>Array</i> # # === Arguments # [<i>bit</i>] <i>Integer</i>. The value (0 or 1) of the current bit. # [<i>block</i>] <i>Proc</i>. The block of code to execute. # # === Examples # bs = BitString.new('11001110001') # bs.select { |bit| bit == 1} # => [1, 1, 1, 1, 1, 1] # # bs = BitString.new('0011001110001') # bs.select { |bit| bit == 0} # => [0, 0, 0, 0, 0] # because unbounded leadings zeroes are dropped # # bs = BitString.new('0011001110001', 13) # bs.select { |bit| bit == 0} # => [0, 0, 0, 0, 0, 0, 0] # # === Exceptions # <i>None</i>. # def select(&block) result = [] self.each do |val| result.push(val) if (block.call(val)) end result end # def select # # === Description # # Shrink the bitstring (make it shorter) by truncating bits from # one end or the other. Shrinking to fewer than 1 bits raises # an exception. # # :call-seq: # bitstring.shrink<i>(bits, [direction])</i> # # === Arguments # [<i>bits</i>] <i>Integer</i>. Number of bits to truncate. # [<i>direction</i>] <i>Constant</i>. Either <tt>BitString::HIGH_END</tt> (the default) or <tt>BitString::LOW_END</tt>. # # === Examples # bs = BitString.new(3095) # 110000010111 # nbs = bs.shrink(5) # nbs.to_s # => "10111" # Unbounded leading zeroes aren't significant # nbs = nbs.shrink(2, BitString::LOW_END) # nbs.to_s # => "101" # # bs = BitString.new(3095, 12) # 110000010111 # nbs = bs.shrink(5) # nbs.to_s # => "0010111" # # === Exceptions # [<tt>ArgumentError</tt>] <i>bitcount</i> isn't an integer or <i>direction</i> isn't one of the defined values. # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # def shrink(bits=1, direction=HIGH_END) unless (bits.kind_of?(Integer)) _raise(BitsRInts) end unless (bits >= 0) _raise(NoDeficitBits) end unless ([HIGH_END, LOW_END].include?(direction)) _raise(NeedGPS) end return dup if (bits == 0) if (bounded? && (bits >= @length)) _raise(RuntimeError, 'shrink count greater than bitstring size') end value = @value length = bounded? ? @length - bits : nil if (direction == LOW_END) value /= 2**bits else _raise(UnboundedNonsense) unless (bounded?) value &= 2**length - 1 end bounded? ? self.class.new(value, length) : self.class.new(value) end # def shrink # # === Description # # As #shrink except that the current bitstring is modified rather than # a copy being made and altered. # # :call-seq: # bitstring.shrink!<i>(bits, [direction])</i> # # === Arguments # [<i>bits</i>] <i>Integer</i>. Number of bits to truncate. # [<i>direction</i>] <i>Constant</i>. <tt>BitString::HIGH_END</tt> (the default) or <tt>BitString::LOW_END</tt>. # # === Examples # bs = BitString.new(3095) # 110000010111 # bs.shrink!(5) # bs.to_s # => "10111" # Unbounded leading zeroes aren't significant # bs.shrink!(2, BitString::LOW_END) # bs.to_s # => "101" # # bs = BitString.new(3095, 12) # 110000010111 # bs.shrink!(5) # bs.to_s # => "0010111" # # === Exceptions # [<tt>ArgumentError</tt>] <i>bitcount</i> isn't an integer or <i>direction</i> isn't one of the defined values. # [<tt>IndexError</tt>] <i>bits</i> is negative or meaningless. # def shrink!(bits=1, direction=HIGH_END) bs = shrink(bits, direction) @length = bs.length if (bs.bounded?) @value = bs.to_i self end # def shrink! # # === Description # # Extract a subset from the bitstring. See the description of # the <tt>[]</tt> method. # # :call-seq: # bitstring.slice<i>(index)</i> => <i>Integer</i> # bitstring.slice<i>(start, length)</i> => <i>BitString</i> # bitstring.slice<i>(range)</i> => <i>BitString</i> # # === Arguments # [<i>index</i>] <i>Integer</i>. Single bit position. # [<i>start</i>] <i>Integer</i>. Start position of subset. # [<i>length</i>] <i>Integer</i>. Length of subset. # [<i>range</i>] <i>Range</i>. Subset specified as a range. # # === Exceptions # [<tt>ArgumentError</tt>] If length specified with a range. # [<tt>IndexError</tt>] If bounded bitstring and substring is illegal. # def slice(*args) self[*args] end # def slice # # === Description # # Select the specified bits from the bitstring, and remake it using # only those bits. If bounded, the size will be adjusted to match # the number of bits selected. This is an alternative way to change # the size and value of an existing bitstring (see the grow!(), shrink!(), # and resize!() methods.) # # :call-seq: # bitstring.slice!<i>(index)</i> => <i>Integer</i> # bitstring.slice!<i>(start, length)</i> => <i>BitString</i> # bitstring.slice!<i>(range)</i> => <i>BitString</i> # # === Arguments # [<i>index</i>] <i>Integer</i>. Single bit position. # [<i>start</i>] <i>Integer</i>. Start position of subset. # [<i>length</i>] <i>Integer</i>. Length of subset. # [<i>range</i>] <i>Range</i>. Subset specified as a range. # # === Examples # bs = BitString.new(3095, 12) # bs.to_s # => "110000010111" # bs.slice!(4..10) # bs.to_s # => "1000001" # # === Exceptions # [<tt>ArgumentError</tt>] If length specified with a range. # [<tt>IndexError</tt>] If bounded bitstring and substring is illegal. # def slice!(*args) bs = self[*args] @value = bs.to_i @bounded = bs.bounded? @length = bs.length if (bs.bounded?) self end # def slice! # # === Description # # Return the full value of the bitstring represented as an integer. # # :call-seq: # bitstring.to_i<i>()</i> => <i>Integer</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('110000010111') # bs.to_i # => 3095 # # === Exceptions # <i>None</i>. # def to_i() @value.to_i end # def to_i() # # === Description # # Return the bitlist as a <i>String</i> object consisting of '0' and '1' # characters. If the bitstring is bounded, the <i>String</i> will # be zero-filled on the left (high end). # # :call-seq: # bitstring.to_s<i>()</i> => <i>String</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new(3095) # bs.to_s # => "110000010111" # # bs = BitString.new(3095, 14) # bs.to_s # => "00110000010111" # # === Exceptions # <i>None</i>. # def to_s() _zfill(@value, @length) end # def to_s() # # List visibility alterations here, since the directive effects persist # past the next definition. # protected(:_arg2int, :_raise, :_zfill) end # class BitString
class Comment < ActiveRecord::Base attr_accessible :comment, :name, :site_id belongs_to :site validates :name, :presence => true validates :comment, :presence => true end
#!/usr/bin/env ruby # Write a method to determine if two strings are anagrams of each other. # e.g. isAnagram(“secure”, “rescue”) → false # e.g. isAnagram(“conifers”, “fir cones”) → true # e.g. isAnagram(“google”, “facebook”) → false class String def anagram?(s) s1 = self.split("").sort.join.strip s2 = s.split("").sort.join.strip s1 == s2 end end tests = [["secure", "rescue"],["conifers","fir cones"],["google","facebook"]] tests.each do |test| s1,s2 = test puts "\"#{s1}\" <=> \"#{s2}\" are anagrams? #{s1.anagram?(s2)}" end
require 'codily/elements/service_belongging_base' module Codily module Elements class Dictionary < ServiceBelonggingBase def_attr *%i( ) def fastly_class Fastly::Dictionary end end end end
require 'roda' require 'json' require 'lib/action_handler' module ImageGetter # Start the action handler and its worker $action = ActionHandler.new(items: Page.inprogress) $action.worker.start class App < Roda plugin :slash_path_empty plugin :halt plugin :json plugin :error_handler def request_data request.body.rewind JSON.parse(request.body.read,symbolize_names: true) end route do |r| r.root do "This isn't the page you're looking for ;)" end r.on 'jobs' do r.is do # List all Jobs r.get do Job.all.map(&:to_hash) end # Create a Job r.post do job = $action.create_job(request_data[:urls]) response.status = 202 {id: job.id} end end r.on ':id' do |id| begin @job = Job.with_pk! id rescue r.halt 404 end # Get specific job status r.get('status'){ @job.status_hash } # Get specific job results r.get('results'){ @job.results_hash } end end end error do |e| if e.is_a?(ValidationError) response.status = 400 end e.message end end end
class InvoicesController < ApplicationController def index gon.invoices = Invoice.all end def create cart = build_cart @invoice = cart.checkout! @invoice.items << cart.items if @invoice.save session[:cart] = [] session[:coupons] = [] redirect_to invoice_path(@invoice), notice: "Successfully checked out" else redirect_to cart_path, alert: "Unable to check out" end end def show @invoice = current_user.invoices.find params[:id] gon.invoiceId = @invoice.id gon.invoiceAmount = @invoice.amount gon.invoicePaid = @invoice.paid gon.invoiceItems = @invoice.items end def close @invoice = current_user.invoices.find params[:id] begin CardProcessor.new(@invoice, params[:stripeToken]).process flash[:success] = "Your purchase went through" rescue Stripe::CardError => e flash[:error] = "Couldn't process card" end redirect_to invoice_path(@invoice) end end
require 'httparty' require 'json' def convert_geoip_boolean(value) value == 'yes' ? true : false end def lambda_handler(event:, context:) sourceIp = event['requestContext']['identity']['sourceIp'] certPath = './cosmos/cert.pem' options = { pem: File.read(certPath), verify: false } begin response = HTTParty.head("https://geoip.test.tools.bbc.co.uk/#{sourceIp}", options) uk_combined = convert_geoip_boolean(response.headers['x-ip_is_uk_combined']); advertise_combined = convert_geoip_boolean(response.headers['x-ip_is_advertise_combined']); country_code = response.headers['x-country']; rescue HTTParty::Error => error puts error.inspect raise error end return { :statusCode => response.code, :body => { :geoip => { uk_combined: uk_combined, advertise_combined: advertise_combined, country_code: country_code } }.to_json } end
class Api::V3::AppointmentTransformer class << self def creation_facility_id(payload) payload[:creation_facility_id].blank? ? payload[:facility_id] : payload[:creation_facility_id] end def to_response(appointment) Api::V3::Transformer.to_response(appointment).except("user_id") end def from_request(appointment_payload) Api::V3::Transformer.from_request(appointment_payload .merge(creation_facility_id: creation_facility_id(appointment_payload))) end end end
class Staffs::StaffsController < Staffs::BaseController before_action :authenticate_staff! def index @staffs = Staff.all.order(:id) end def create @staff = Staff.create(staff_params) @staff.update(password: PasswordService.default, reset_password: true) end def update @staff = Staff.where(id: params[:id]).first @staff.update(staff_params) end def destroy Staff.delete(params[:id]) end def current @staff = current_staff end private def staff_params params.permit(:name, :phone, :email, :reset_password) end end
require 'test_helper' class CustomFieldsControllerTest < ActionDispatch::IntegrationTest setup do @custom_field = custom_fields(:one) end test "should get index" do get custom_fields_url assert_response :success end test "should get new" do get new_custom_field_url assert_response :success end test "should create custom_field" do assert_difference('CustomField.count') do post custom_fields_url, params: { custom_field: { label: @custom_field.label, option_id: @custom_field.option_id, type_id: @custom_field.type_id } } end assert_redirected_to custom_field_url(CustomField.last) end test "should get edit" do get edit_custom_field_url(@custom_field) assert_response :success end test "should update custom_field" do patch custom_field_url(@custom_field), params: { custom_field: { label: @custom_field.label, option_id: @custom_field.option_id, type_id: @custom_field.type_id } } assert_redirected_to custom_field_url(@custom_field) end test "should destroy custom_field" do assert_difference('CustomField.count', -1) do delete custom_field_url(@custom_field) end assert_redirected_to custom_fields_url end end
class RecipeIngredient < ApplicationRecord belongs_to :recipe_ingredient_group belongs_to :ingredient validates :quantity, presence: true # validates :unit, presence: true validates :ingredient_id, presence: true before_save do self.unit = unit.singularize end after_create_commit { broadcast_prepend_to "recipe_ingredients" } after_update_commit { broadcast_replace_to "recipe_ingredients" } after_destroy_commit { broadcast_remove_to "recipe_ingredients" } end
#!/usr/bin/env rake require "bundler/gem_tasks" require "rake/testtask" require "yard" desc "generate documentation" YARD::Rake::YardocTask.new do |task| task.files << 'lib/**/*.rb' end desc "run the minitest specs" Rake::TestTask.new(:spec) do |task| task.libs << "spec" task.test_files = FileList["spec/**/*_spec.rb"] end task :default => [:spec, :build, :yard]
module Motion; module Project class Config alias :original_spec_files :spec_files def spec_files red_green_style_config_file = File.expand_path(redgreen_style_config) return original_spec_files if original_spec_files.include? red_green_style_config_file index = original_spec_files.find_index do |file| file.include? "/lib/motion/spec.rb" end original_spec_files.insert(index + 1, *[ red_green_style_config_file, File.expand_path(File.dirname(__FILE__) + '/spec_setup.rb') ]) end attr_accessor :redgreen_style def redgreen_style_config config_file = File.join(build_dir, 'redgreen_style_config.rb') @redgreen_style ||= :focused f = open(config_file, 'wb') f.write("$RedGreenStyleFormat = :#{@redgreen_style}\n") f.close config_file end end end ; end
class QuoteItem < ApplicationRecord belongs_to :quotation_request belongs_to :order_item validates :quantity, presence: true validates :quote_price, presence: true validates :price, presence: true def item_details_hash { price: self.price, quote_price: self.quote_price, quantity: self.quantity, title: self.order_item.title, order_item_id: self.order_item.id, owner_id: self.order_item.catalog.store_owner_id } end end
class Importsession < ApplicationRecord has_many :imports end
module NumberFinder class << self def find_n_numbers(n, num = 1, found =[], &predicate) if found.size == n found elsif predicate.call(num) find_n_numbers(n, num + 1, found + [num], &predicate) else find_n_numbers(n, num + 1, found, &predicate) end end def find_numbers(range, &predicate) range.select { |num| predicate.call(num) } end def find_factors(num) (1..num).select do |divisor| num % divisor == 0 && num != divisor end end def is_perfect?(num) num == find_factors(num).reduce(&:+) end end end puts "Finding the first four perfect numbers:" puts NumberFinder.find_n_numbers(4) { |num| NumberFinder.is_perfect? num } puts "\n" puts "Finding all numbers between 1 and 1000 with exactly 3 factors:" puts NumberFinder.find_numbers((1..1000)) { |num| NumberFinder.find_factors(num).size == 3 }
module Domgen class << self def template_sets template_set_map.values end def template_set(name, options = {}, &block) if name.is_a?(Hash) && name.size == 1 req = name.values[0] options = options.dup options[:required_template_sets] = req.is_a?(Array) ? req : [req] name = name.keys[0] end template_set = Domgen::Generator::TemplateSet.new(name, options, &block) template_set_map[name.to_s] = template_set template_set end def template_set_by_name(name) template_set = template_set_map[name.to_s] error("Unable to locate template_set #{name}") unless template_set template_set end private def template_set_map @template_sets ||= Domgen::OrderedHash.new end end module Generator class TemplateSet < BaseElement attr_reader :name attr_accessor :required_template_sets def initialize(name, options = {}, &block) @name = name @required_template_sets = [] super(options, &block) end def templates template_map.values end def template(facets, scope, template_filename, output_filename_pattern, helpers = [], guard = nil) template = Template.new(facets, scope, template_filename, output_filename_pattern, helpers, guard) template_map[template.name] = template end def xml_template(facets, scope, template_filename, output_filename_pattern, helpers = [], guard = nil) template = XmlTemplate.new(facets, scope, template_filename, output_filename_pattern, helpers, guard) template_map[template.name] = template end def template_by_name(name) template = template_map[name.to_s] error("Unable to locate template #{name}") unless template template end private def template_map @templates ||= Domgen::OrderedHash.new end end class Template < BaseElement attr_reader :template_filename attr_reader :output_filename_pattern attr_reader :guard attr_reader :helpers attr_reader :scope attr_reader :facets def initialize(facets, scope, template_filename, output_filename_pattern, helpers, guard) Domgen.error("Unexpected facets") unless facets.is_a?(Array) && facets.all? {|a| a.is_a?(Symbol)} Domgen.error("Unknown scope for template #{scope}") unless valid_scopes.include?(scope) @facets = facets @scope = scope @template_filename = template_filename @output_filename_pattern = output_filename_pattern @helpers = helpers @guard = guard end def to_s name end def applicable?(faceted_object) self.facets.all? {|facet_key| faceted_object.facet_enabled?(facet_key) } end def render_to_string(context_binding) erb_instance.result(context_binding) end def name @name ||= "#{facets.inspect}:#{File.basename(template_filename, '.erb')}" end protected def valid_scopes [:enumeration, :message, :exception, :method, :service, :struct, :entity, :data_module, :repository] end def erb_instance unless @template @template = ERB.new(IO.read(template_filename), nil, '-') @template.filename = template_filename end @template end end class XmlTemplate < Template def initialize(facets, scope, render_class, output_filename_pattern, helpers, guard) super(facets, scope, render_class.name, output_filename_pattern, helpers + [render_class], guard) end def render_to_string(context_binding) context_binding.eval('generate') end end end end
require 'net/scp' require 'net/ssh' require 'archive/tar/minitar' require 'zlib' class LinuxServer < Server def initialize(parent_dir, conf) @conf = conf @logs_dir = server_dir_in File.join(parent_dir, "logs") @report_dir = File.expand_path(File.join(parent_dir, "report")) @ssh_opts = {} @ssh_opts[:password] = @conf[:password] if @conf[:password] @ssh_opts[:keys] = [ @conf[:private_key] ] if @conf[:private_key] end def start puts '-' * 80 log 'deploying scripts' deploy_scripts() log 'starting log collection' remote_run("perf_logs/start.sh") log 'done' end def stop puts '-' * 80 log 'stopping log collection' remote_run("perf_logs/stop.sh") log 'downloading logs' download_tarred_logs() log 'extracting logs' untar_logs() log 'done' end def report puts '-' * 80 plot('cpu.plt', '_cpu.png') plot('runqueue.plt', '_runqueue.png') plot('memory.plt', '_memory.png') plot_context_switches() plot_iostats() end def log(message) puts "[#{@conf[:alias]}] #{message}" end def server_dir_in(dir) subdir = File.join(dir, @conf[:alias]) Dir.mkdir(subdir) if not Dir.exists? subdir File.expand_path(subdir) end def deploy_scripts scripts_dir = File.join(File.dirname(__FILE__), '..', '..', 'resources', 'linux', 'perf_logs') Net::SCP.start(@conf[:host], @conf[:user], @ssh_opts) do |scp| scp.upload!(scripts_dir, '.', :recursive => true) end end def remote_run(command) Net::SSH.start(@conf[:host], @conf[:user], @ssh_opts) do |ssh| output = ssh.exec!(command) puts output end end def download_tarred_logs Net::SCP.start(@conf[:host], @conf[:user], @ssh_opts) do |scp| scp.download!('perf_logs/logs.tgz', @logs_dir) end end def untar_logs tar_path = File.join(@logs_dir, 'logs.tgz') reader = Zlib::GzipReader.new(File.open(tar_path, 'rb')) Archive::Tar::Minitar.unpack(reader, @logs_dir) end def plot(gnuplot_script, output_file_suffix, env = {}) gnuplot_dir = File.join(File.dirname(__FILE__), '..', '..', 'resources', 'linux', 'gnuplot') Dir.chdir(@logs_dir) do Process.spawn(env, 'gnuplot', :in => File.join(gnuplot_dir, gnuplot_script), :out => File.join(@report_dir, "#{@conf[:alias]}#{output_file_suffix}")) end end def plot_context_switches pidstats = Pidstats.new(@logs_dir) pidstats.aggregate_switch_stats_to('switches_total.log') limit = pidstats.compute_voluntary_switch_limit() plot('vcs.plt', '_vcs.png', 'LIMIT' => limit.to_s) end def plot_iostats() iostats = Iostats.new(@logs_dir) iostats.split() Dir.chdir(@logs_dir) do Dir['iostat_*.log'].each do |file| device = file.scan(/iostat_(.*).log/)[0][0] plot('iostat.plt', "_iostat_#{device}.png", 'DEVICE' => device) end end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module ActionView #:nodoc: class PathSet < Array #:nodoc: def self.type_cast(obj) if obj.is_a?(String) if Base.cache_template_loading? Template::EagerPath.new(obj.to_s) else ReloadableTemplate::ReloadablePath.new(obj.to_s) end else obj end end def initialize(*args) super(*args).map! { |obj| self.class.type_cast(obj) } end def <<(obj) super(self.class.type_cast(obj)) end def concat(array) super(array.map! { |obj| self.class.type_cast(obj) }) end def insert(index, obj) super(index, self.class.type_cast(obj)) end def push(*objs) super(*objs.map { |obj| self.class.type_cast(obj) }) end def unshift(*objs) super(*objs.map { |obj| self.class.type_cast(obj) }) end def load! each(&:load!) end def find_template(original_template_path, format = nil, html_fallback = true) return original_template_path if original_template_path.respond_to?(:render) template_path = original_template_path.sub(/^\//, '') each do |load_path| if format && (template = load_path["#{template_path}.#{I18n.locale}.#{format}"]) return template elsif format && (template = load_path["#{template_path}.#{format}"]) return template elsif template = load_path["#{template_path}.#{I18n.locale}"] return template elsif template = load_path[template_path] return template # Try to find html version if the format is javascript elsif format == :js && html_fallback && template = load_path["#{template_path}.#{I18n.locale}.html"] return template elsif format == :js && html_fallback && template = load_path["#{template_path}.html"] return template end end return Template.new(original_template_path) if File.file?(original_template_path) raise MissingTemplate.new(self, original_template_path, format) end end end
require_relative 'master_method_tests' include MasterMethodTests #Given(/^I am on Hayneedles website$/) do #goto_hayneedle_site #close_popup #end When(/^I click on the Account drop down and click Sign In$/) do @browser.div(:id, 'HN_Accounts_Btn').click @browser.div(:id, 'HN_Accounts_DD').a(:href, '/templates/hn_modals.cfm?mode=sign_in').click end And(/^when the sign in modal pops up, I enter "(.*?)" and "(.*?)" for the username and password before clicking the sign in button$/) do |username, password| sign_in(username, password) end And(/^now hayneedle should be welcoming "(.*?)"$/) do |name| @browser.img(:src, /Hayneedle_Logo.gif/).wait_until_present @browser.text.should include name end And(/^when I click the welcoming text, I will click to manage my profile$/) do @browser.div(:id, 'HN_Accounts_Btn').click @browser.div(:id, 'HN_Accounts_DD').a(:text, 'Manage Profile').click end And(/^I click Manage Your Address Book to see my saved address$/) do @browser.a(:title, 'Manage Your Address Book').click end Then(/^I should see "(.*?)" with my saved addresses$/) do |expected| @browser.text.should include expected end
class Item < ActiveRecord::Base belongs_to :list validates :name, presence: true validates :name, length: { minimum: 1, message: "you must enter a list name with at least 1 character"} end
class PollChoicesController < ApplicationController before_action :get_poll before_action :get_poll_choice, except: [:index, :new, :create] def index @poll_choices = @poll.poll_choices end def new @poll_choice = @poll.poll_choices.new end def create @poll_choice = @poll.poll_choices.new(poll_choice_params) @poll_choice.save! redirect_to @poll end def edit end def update @poll_choice.update(poll_choice_params) @poll_choice.save redirect_to @poll end def destroy @poll_choice.destroy redirect_to @poll end private def poll_choice_params params.require(:poll_choice).permit(:name, :description) end def get_poll_choice @poll_choice = @poll.poll_choices.find(params[:id]) end def get_poll @poll = Poll.find(params[:poll_id]) end end
class Calculator attr_accessor :name, :num_calculations def initialize(name="no name") @name = name @num_calculations = 0 end def add(a, b) @num_calculations += 1 a + b end def sum(ary) @num_calculations += 1 sum = ary.inject do |tot, elem| tot + elem end if sum.nil? sum = 0 end sum end def product(ary) @num_calculations += 1 product = ary.inject(1) do |prd, elem| prd * elem end product end def exp(a, b) product = 1 b.times do product *= a end product end def factorial(a) if a == 0 return 1 end a * factorial(a - 1) end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :logged_in_user, only: [:create, :new] skip_before_action :admin_user, only: [:create,:show, :new, :destroy, :edit, :update] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show if !logged_in? || (!admin? && !(current_user == @user)) naughty_user end @activity = Hash.new cd = DateTime.now.to_date pd = 1.year.ago(cd) pd.upto(cd) { |date| no = Booking.where(created_at: date.midnight..date.end_of_day).where(user_id: @user.id).count @activity[date] = no } end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users # POST /users.json def create @user = User.new(user_params) if verify_recaptcha(model: @user) && @user.save @user.send_activation_email flash[:info] = "Please check your email to activate your account." redirect_to root_url else render 'new' end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update if !logged_in? || (!admin? && !(current_user == @user)) naughty_user else if verify_recaptcha(model: @user) problem = false update_params.each do |param| if !@user.update_attribute(param[0], param[1]) problem = true end end respond_to do |format| if !problem format.html { redirect_to @user flash[:info] = 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end else flash[:info] = 'ReCAPTCHA not validated' render 'edit' end end end # DELETE /users/1 # DELETE /users/1.json def destroy if !logged_in? || (!admin? && !(current_user == @user)) naughty_user else @user.destroy respond_to do |format| if admin? format.html { redirect_to users_url flash[:info] = 'User was successfully destroyed.' } else format.html { redirect_to root_url flash[:info] = 'User was successfully destroyed.' } end format.json { head :no_content } end end end def allowed_params params.require(:user).permit(:email, :password, :password_confirmation) end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end def update_params params.require(:user).permit(:Fname, :Lname, :Email, :Address, :Postcode, :City, :Country, :Phone, :Privilege) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:Fname, :Lname, :Email, :Address, :Postcode, :City, :Country, :Phone, :Privilege, :CardRegistered, :password, :password_confirmation) end end
require 'test_helper' class AgentMailerTest < ActionMailer::TestCase test 'welcome' do email = AgentMailer.welcome(agents(:archer)).deliver assert_equal [agents(:archer).email], email.to assert_equal ['handlers@secretagentplan.shhh'], email.from assert_equal "Welcome to Secret Agent Plan", email.subject assert_match agents(:archer).name, email.body.to_s assert ActionMailer::Base.deliveries.any?, 'expected welcome email to be delivered' end end
require 'rails_helper' RSpec.describe Team do context 'is a model and has attributes' do it "exists" do expect(Team.new).to be_a(Team) end it 'has a name attribute' do expect(Team.new).to respond_to(:team_name) end it 'has a info attribute' do expect(Team.new).to respond_to(:info) end it 'has an admin id' do expect(Team.new).to respond_to(:admin_id) end end context 'has correct validations and associations' do it { should validate_presence_of(:team_name) } it { should validate_presence_of(:admin_id) } it { should belong_to(:admin) } it { should have_many(:media) } it { should have_many(:players) } it { should have_many(:sports) } end end
# frozen_string_literal: true require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest def setup @users = create_list(:user, 20) end test 'should get paginated users' do get users_url, params: { page: 1, per_page: 50 } assert_response :success assert_equal @users.first.name, JSON.parse(@response.body).first['name'] end test 'should get user by id' do user = @users.first get user_url(id: user.id) assert_response :success assert_equal user.id, JSON.parse(@response.body)['id'] end test 'should create user' do user_params = attributes_for(:user) post users_url, params: user_params assert_response :success end test 'should update user' do user = @users.first put user_url(id: user.id), params: { name: 'New name' } assert_response :success assert_equal user.reload.name, 'New name' end test 'should delete user' do delete user_url(id: @users.first.id) assert_response :success assert_equal @users.count - 1, User.count end end
module ReportsKit module Reports module Data class FormatTwoDimensions attr_accessor :series, :dimension, :second_dimension, :dimension_keys_values, :order, :limit def initialize(series, dimension_keys_values, order:, limit:) self.series = series self.dimension = series.dimensions[0] self.second_dimension = series.dimensions[1] self.dimension_keys_values = dimension_keys_values self.order = order self.limit = limit end def perform { entities: entities, datasets: datasets } end private def entities sorted_primary_keys.map do |primary_key| Utils.dimension_key_to_entity(primary_key, dimension, dimension_ids_dimension_instances) end end def datasets secondary_keys_values = sorted_secondary_keys.map do |secondary_key| raw_values = sorted_primary_keys.map do |primary_key| primary_keys_secondary_keys_values[primary_key][secondary_key] end values = raw_values.map do |raw_value| Utils.raw_value_to_value(raw_value, series.value_format_method) end [secondary_key, values] end secondary_keys_values.map do |secondary_key, values| next if secondary_key.blank? { entity: Utils.dimension_key_to_entity(secondary_key, second_dimension, second_dimension_ids_dimension_instances), values: values } end.compact end def sorted_primary_keys_secondary_keys_values @sorted_primary_keys_secondary_keys_values ||= begin if order.relation == 'dimension1' && order.field == 'label' primary_keys_secondary_keys_values sorted_primary_keys_secondary_keys_values = primary_keys_secondary_keys_values.sort_by do |primary_key, _| primary_dimension_keys_sorted_by_label.index(primary_key) end elsif order.relation == 'dimension1' && order.field.nil? sorted_primary_keys_secondary_keys_values = primary_keys_secondary_keys_values.sort_by do |primary_key, _| primary_key end elsif order.relation == 'count' primary_keys_sums = Hash.new(0) primary_keys_secondary_keys_values.each do |primary_key, secondary_keys_values| primary_keys_sums[primary_key] += secondary_keys_values.values.sum end sorted_primary_keys = primary_keys_sums.sort_by(&:last).map(&:first) sorted_primary_keys_secondary_keys_values = primary_keys_secondary_keys_values.sort_by do |primary_key, _| sorted_primary_keys.index(primary_key) end else dimension_keys_values end sorted_primary_keys_secondary_keys_values = sorted_primary_keys_secondary_keys_values.reverse if order.direction == 'desc' Hash[sorted_primary_keys_secondary_keys_values] end end def primary_keys_secondary_keys_values @primary_keys_secondary_keys_values ||= begin primary_keys_secondary_keys_values = {} dimension_keys_values.each do |(primary_key, secondary_key), value| primary_key = primary_key.to_date if primary_key.is_a?(Time) secondary_key = secondary_key.to_date if secondary_key.is_a?(Time) primary_keys_secondary_keys_values[primary_key] ||= {} primary_keys_secondary_keys_values[primary_key][secondary_key] = value end primary_keys_secondary_keys_values end end def dimension_ids_dimension_instances @dimension_ids_dimension_instances ||= begin Utils.dimension_to_dimension_ids_dimension_instances(dimension, primary_keys) end end def second_dimension_ids_dimension_instances @second_dimension_ids_dimension_instances ||= begin Utils.dimension_to_dimension_ids_dimension_instances(second_dimension, secondary_keys) end end def sorted_primary_keys @sorted_primary_keys ||= begin keys = sorted_primary_keys_secondary_keys_values.keys limit = dimension.dimension_instances_limit keys = keys.first(limit) if limit keys end end def sorted_secondary_keys @sorted_secondary_keys ||= begin keys = sorted_primary_keys_secondary_keys_values.values.first.keys limit = second_dimension.dimension_instances_limit keys = keys.first(limit) if limit keys end end def primary_summaries primary_keys.map do |key| label = Utils.dimension_key_to_label(key, dimension, dimension_ids_dimension_instances) next if label.blank? [key, label] end.compact end def primary_dimension_keys_sorted_by_label @primary_dimension_keys_sorted_by_label ||= primary_summaries.sort_by { |key, label| label.is_a?(String) ? label.downcase : label }.map(&:first) end def primary_keys @primary_keys ||= dimension_keys_values.keys.map(&:first).uniq end def secondary_keys @secondary_keys ||= dimension_keys_values.keys.map(&:last).uniq end end end end end
# Write two methods that each take a time of day in 24 hour format, and return # the number of minutes before and after midnight, respectively. Both methods # should return a value in the range 0..1439. # You may not use ruby's Date and Time methods. # split the strink into 2 numbers, use split with : # multiply hours by 60 and add it to the minutes def after_midnight(time) time = time.split(':').map(&:to_i) time = 0 if time[0] == 24 && time[1].zero? (time[0] * 60) + time[1] end def before_midnight(time) time = time.split(':').map(&:to_i) if time[0] == 24 && time[1].zero? time = 0 elsif time[0] > 0 || time[1] > 0 1440 - ((time[0] * 60) + time[1]) else (time[0] * 60) + time[1] end end p after_midnight('00:00') == 0 p before_midnight('00:00') == 0 p after_midnight('12:34') == 754 p before_midnight('12:34') == 686 p after_midnight('24:00') == 0 p before_midnight('24:00') == 0
require 'spec_helper' describe MSFLVisitors::Nodes::Iterator do describe ".new" do subject { described_class.new arg } context "when the argument is not a MSFLVisitors::Nodes::Set instance" do let(:arg) { double('Not a Set node') } it "raises an ArgumentError" do expect { subject }.to raise_error ArgumentError end end end describe "#==" do let(:one) { MSFLVisitors::Nodes::Number.new(1) } let(:two) { MSFLVisitors::Nodes::Number.new(2) } let(:left) { MSFLVisitors::Nodes::Iterator.new left_set } let(:left_set) { MSFLVisitors::Nodes::Set.new [one, two] } let(:right) { MSFLVisitors::Nodes::Iterator.new right_set } let(:right_set) { MSFLVisitors::Nodes::Set.new [one, two] } subject { left == right } context "when lhs and rhs are the same class" do context "when lhs#items is equal to rhs#items" do it { is_expected.to be true } end context "when lhs#items is not equal to rhs#items" do let(:right_set) { MSFLVisitors::Nodes::Set.new [one] } it { is_expected.to be false } end end context "when lhs is a different class than rhs" do let(:right) { Object.new } it { is_expected.to be false } end end end
Factory.sequence :company_unique_identifier do |n| "unique_identifier#{n}" end # Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :company do name "MyString" brief_description "MyText" city { |c| c.association(:city) } unique_identifier { Factory.next(:company_unique_identifier) } company_type 'companytype' maintainer { |c| c.association(:user) } account { Account.first } end end
module Moped module Logging def logger return @logger if defined?(@logger) @logger = rails_logger || default_logger end def rails_logger defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger end def default_logger Logger.new(STDOUT).tap do |logger| logger.level = Logger::INFO end end def logger=(logger) @logger = logger end end extend Logging end
require 'rails_helper' RSpec.describe 'admin price expire', settings: false do before :example do sign_in_to_admin_area end it 'expires price' do price = create(:effective_price) expect { patch expire_admin_price_path(price); price.reload } .to change { price.expired? }.from(false).to(true) end it 'redirects to :index' do price = create(:effective_price) patch expire_admin_price_path(price) expect(response).to redirect_to admin_prices_url end end
require 'FFMPEG.rb' require 'thread' # VideoConverter enables converting of videos. It is based on FFMPEG. class VideoConverter # VideoConverter constructor. # +video+:: identifier for the to be converted video file def initialize(video) if not File.exist?(video) raise "File #{video} does not exist." end @video = video @converter = FFMPEG.new @progress = 0 @mutex = Mutex.new @done = false end def done res = false @mutex.synchronize do res = @done end res end # Returns duration of the video file in seconds. def get_duration res = 0 @mutex.synchronize do @duration = @converter.get_duration(@video) res = @duration end res end # Returns the progress in seconds of the conversion process. def get_progress res = 0 if not done() @mutex.synchronize do res = @progress end else res = 100 end res end # Converts the video. The target codec is deduced from the +ouput_file+'s file extension. # This method is non-blocking, you can check if the job is done with the +done()+ method. # +output_file+:: name of the output video file def convert_to(output_file) if File.exist?(output_file) raise "Output file already exists: #{output_file}" end @out_video = output_file Thread.new do @converter.convert(@video, @out_video, Proc.new do |progress| @mutex.synchronize do if @progress < @duration @progress = (0.5 + ((100 * progress).to_f / get_duration().to_f)).to_i else @progress = 100 end end end) @mutex.synchronize do @done = true end end end end
module PageHelper include Rails.application.routes.url_helpers def default_url_options {} end def goto_url @session.visit @url end def notice @session.find("#messages .notice").text end end
json.array!(@game_details) do |game_detail| json.extract! game_detail, :id, :game_id, :question_id, :status_id json.url game_detail_url(game_detail, format: :json) end
movies = {'A Man for All Seasons' => 10} print 'What operation: ' choice = gets.chomp until choice == 'end' do case choice when 'add' print 'Movie title: ' title = gets.chomp.to_sym print "\nRating: " rating = gets.chomp.to_i if movies.has_key? title puts 'Movie has already been added' else movies[title] = rating puts "#{title} => #{movies[title]} was added" end when 'update' print 'Movie title: ' title = gets.chomp.to_sym if movies.has_key? title print "\nRating: " rating = gets.chomp.to_i movies[title] = rating puts "#{title} => #{movies[title]} was updated" else puts "No such movie has been added" end when 'display' movies.each{|x, y| puts "#{x} #{y}" } when 'delete' print 'Movie title: ' title = gets.chomp.to_sym if movies.has_key? title movies.delete(title) puts "#{title} was deleted" movies.each{|x, y| puts "#{x} #{y}" } else puts "No such movie exists" end else puts 'Error' end print 'What operation: ' choice = gets.chomp end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # before_action :set_breadcrumb # def set_breadcrumb # @breadcrumbs ||= session[:breadcrumbs] # @breadcrumbs.push(request.url) # end # this lets the view access the helper method helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def current_admin? current_user && current_user.admin? end end
def capfile(config) if config.installed? done "Cap files '#{config.files}' exists, not running `cap install`" else sys_exec! 'cap install' end ruby = :ruby create_initial_file( source: config.source_dir_for.dest_files_that_exist.join( ruby.to_s, config.capfile ), dest: config.capfile, comment: :ruby, key_string: config.key_string ) end
class BottleDepot attr_accessor :total_bottles, :bottle_caps, :investment, :caps, :empties def initialize (investment) @investment = investment @total_bottles = 0 @caps = 0 @empties = 0 end BOTTLE_PRICE = 2 TRADE_CAPS_IN = 4 TRADE_BOTTLES_IN = 2 def trading_in? @caps < TRADE_CAPS_IN && @empties < TRADE_BOTTLES_IN end def buy_pop @total_bottles = @investment / BOTTLE_PRICE @empties = @total_bottles @caps = @total_bottles end def trade trade_in_bottles trade_in_caps trading_in? end def trade_in_bottles new_bottles = @empties / TRADE_BOTTLES_IN @total_bottles += new_bottles @caps += new_bottles @empties = (@empties % TRADE_BOTTLES_IN) + new_bottles end def trade_in_caps new_bottles = @caps / TRADE_CAPS_IN @total_bottles += new_bottles @empties += new_bottles @caps = (@caps % TRADE_CAPS_IN) + new_bottles end def final_report puts "You have returned a total of #{@total_bottles}" end end
class AddPhotoToMeetingRoom < ActiveRecord::Migration[5.0] def change add_column :meeting_rooms, :photo, :string end end
module Lita module Handlers class Heartbeat < Handler # insert handler code here http.get "/heartbeat", :heartbeat def heartbeat(request, response) response.body << "I'm alive!" end Lita.register_handler(self) end end end
Rails.application.routes.draw do devise_for :users root to: "categories#index" resources :categories, only: [:show] do resources :tips, only: [:index] end resources :users, only: [:show, :edit, :update] resources :party_challenges, only: [:update] resources :challenges, only: [:index, :show, :new, :create, :update] do resources :party_challenges, only: [:create] end resources :tips, only: [:show, :new, :create, :destroy] do resources :votes, only: [:create] end resources :quizzes, only: [:index, :show] # Creation de la partie Quiz a partir du quiz resources :quizzes, only: [] do resources :party_quizzes, only: [:new] end # Réalisation de la partie à partir du party_quiz resources :party_quizzes, only: [] do # Boucles du Quiz resources :answers, only: [:new, :create] end resources :places, only: [:index] get "*unmatched_route", to: "errors#not_found" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require_relative "lib/sentry/resque/version" Gem::Specification.new do |spec| spec.name = "sentry-resque" spec.version = Sentry::Resque::VERSION spec.authors = ["Sentry Team"] spec.description = spec.summary = "A gem that provides Resque integration for the Sentry error logger" spec.email = "accounts@sentry.io" spec.license = 'MIT' spec.homepage = "https://github.com/getsentry/sentry-ruby" spec.platform = Gem::Platform::RUBY spec.required_ruby_version = '>= 2.4' spec.extra_rdoc_files = ["README.md", "LICENSE.txt"] spec.files = `git ls-files | grep -Ev '^(spec|benchmarks|examples)'`.split("\n") spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/master/CHANGELOG.md" spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "sentry-ruby", "~> 5.10.0" spec.add_dependency "resque", ">= 1.24" end
$:.unshift(File.expand_path('../lib', __FILE__)) require 'active_support/all' require 'sinatra' require 'sinatra/base' require 'sinatra/reloader' require 'sinatra/config_file' require 'tile_service' require 'badge_service' require 'dot_service' require 'iodine' set :public_folder, File.dirname(__FILE__) + '/public' set :root, File.dirname(__FILE__) configure :production do set :logging, Logger::ERROR end configure :development do set :logging, Logger::DEBUG end if (defined?(Iodine)) Iodine.threads = ENV.fetch("RAILS_MAX_THREADS", 5).to_i if Iodine.threads.zero? Iodine.workers = ENV.fetch("WEB_CONCURRENCY", 2).to_i if Iodine.workers.zero? Iodine::DEFAULT_SETTINGS[:port] = ENV.fetch("PORT", 3000).to_i end DEFAULT_COLOR = 'DDDCBF' DEFAULT_SIZE = 200 DEFAULT_BADGE_SIZE = 100 MAX_AGE = 60 * 60 use Rack::Cache before do content_type :svg end def color(color = nil) color = DEFAULT_COLOR if color.nil? || color.size == 0 "##{color}" end def generate_dots(params) enemies,team,faction,friends = params[:count].split('_') DotService.instance.create(enemies.to_i, size: (params[:s] || DEFAULT_SIZE).to_i, team: team.to_i, faction: faction.to_i, friends: friends.to_i) end def generate_tile(params) if params[:r] if params[:r].match(/\d+/) r = params[:r].to_i if r < 6 case r when 1..3 params[:r] = r * 90 when 4 params[:r] = 0 params[:flip] = true when 5 params[:r] = 0 params[:flop] = true end else params[:r] = ((r / 22.5).round * 22.5).round end else case params[:r] when 'flip' params[:flip] = true when 'flop' params[:flop] = true end params[:r] = 0 end end TileService.instance.create(params[:base], color(params[:c]), size: (params[:s] || DEFAULT_SIZE).to_i, rotation: params[:r] || 0, hflip: params[:flip], vflip: params[:flop], owner_percent: params[:p], owner_color: params[:o], highlight: params[:h] ) end def generate_badge(params) BadgeService.instance.create(params[:base], size: (params[:s] || DEFAULT_BADGE_SIZE).to_i, friend: params[:f], tile: params[:t], badge_size: params[:bs]) end #### # FAVICON # get '/favicon.ico' do content_type 'image/svg+xml' BadgeService.instance.create('traitor',size: 64,friend: true).to_s end get '/favicon.svg' do content_type 'image/svg+xml' BadgeService.instance.create('traitor',size: 64,friend: true).to_s end #### # TILES # get '/t/:base.svg' do generate_tile(params).to_s end get '/t/c/:base.svg' do cache_control :public, max_age: MAX_AGE tile = generate_tile(params).to_s etag Digest::MD5.hexdigest(tile) tile end #### # DOTS # get '/d/:count.svg' do generate_dots(params).to_s end get '/d/c/:count.svg' do cache_control :public, max_age: MAX_AGE tile = generate_dots(params).to_s etag Digest::MD5.hexdigest(tile) tile end #### # BADGES # get '/b/:base.svg' do generate_badge(params).to_s end get '/b/c/:base.svg' do cache_control :public, max_age: MAX_AGE tile = generate_badge(params).to_s etag Digest::MD5.hexdigest(tile) tile end #### # ROOT # get '/' do content_type :text 'TileServer 0.2' end #### # HONEYPOT # get '/phpmyadmin' do sleep(60) end post '/login.action' do sleep(60) end
class CreateEmailHistories < ActiveRecord::Migration def self.up create_table :email_histories do |t| t.integer :to_email_id t.integer :from_email_id t.string :message_id t.string :unique t.string :subject t.datetime :open_at t.datetime :visit_at t.datetime :bounce_at t.string :bounce_reason t.timestamps end add_index :email_histories, :to_email_id add_index :email_histories, :from_email_id add_index :email_histories, :message_id end def self.down drop_table :email_histories end end
require 'spec_helper' require 'rack/test' describe IndexController do def app() ApiController end context 'Api' do it 'should allow accessing the home page' do get '/all', {}, { 'rack.session' => { user: 'foo' } } expect(last_response.body).to include('Some new task') end it 'should add a task' do get '/add', params = {name: 'foo', detail: 'bar'} task_id = last_response.body.gsub('"','') task_file = ENV['TEST_BOARD_LOCATION'] + '/Standard/Backlog/' + task_id + '.yml' expect(File.exist?(task_file)) File.delete(task_file) end it 'should add a task and then move it' do get '/add', params = {name: 'foo', detail: 'bar'} task_id = last_response.body.gsub('"','') task_file = ENV['TEST_BOARD_LOCATION'] + '/Standard/Backlog/' + task_id + '.yml' expect(File.exist?(task_file)) get '/move', params = {id: task_id, to_row: 'Expedite', to_column: 'Deployed'} move_result = last_response.body.gsub('"','') expect(move_result).to eq 'true' task_file = ENV['TEST_BOARD_LOCATION'] + '/Expedite/Deployed/' + task_id + '.yml' expect(File.exist?(task_file)) File.delete(task_file) end end end
# encoding: utf-8 class TweetsController < ApplicationController # GET /tweets # GET /tweets.xml require 'RMagick' include ApplicationHelper caches_action :index, :expires_in => 30.minutes, :if => proc { (params.keys - ['format', 'action', 'controller']).empty? } caches_action :thumbnail before_filter :enable_filter_form def index @filter_action = "/" if params.has_key?(:see) && params[:see] == :all @tweets = Tweet.in_order else @tweets = DeletedTweet.in_order end @tweets = @tweets.where(:politician_id => @politicians) tweet_count = 0 #@tweets.count if params.has_key?(:q) and params[:q].present? # Rails prevents injection attacks by escaping things passed in with ? @query = params[:q] query = "%#{@query}%" @search_pols = Politician.where("MATCH(user_name, first_name, middle_name, last_name) AGAINST (?)", query) @tweets = @tweets.where("content like ? or deleted_tweets.user_name like ? or politician_id in (?)", query, query, @search_pols) end # only approved tweets @tweets = @tweets.where(:approved => true) @per_page_options = [20, 50] @per_page = closest_value((params.fetch :per_page, 0).to_i, @per_page_options) @page = [params[:page].to_i, 1].max @tweets = @tweets.includes(:tweet_images, :politician => [:party]).paginate(:page => params[:page], :per_page => @per_page) respond_to do |format| format.html # index.html.erb format.rss do response.headers["Content-Type"] = "application/rss+xml; charset=utf-8" render end format.json { render :json => {:meta => {:count => tweet_count}, :tweets => @tweets.map{|tweet| tweet.format } } } end end # GET /tweets/1 # GET /tweets/1.xml def show @tweet = DeletedTweet.includes(:politician).find(params[:id]) if (@tweet.politician.status != 1 and @tweet.politician.status != 4) or not @tweet.approved not_found end respond_to do |format| format.html # show.html.erb format.xml { render :xml => @tweet } format.json { render :json => @tweet.format } end end def thumbnail tweet = Tweet.find(params[:tweet_id]) if not tweet not_found end images = tweet.tweet_images.all if not images not_found end filename = "#{params[:basename]}.#{params[:format]}" image = images.select do |img| img.filename == filename end .first if not image not_found end resp = HTTParty.get(image.url) img = Magick::Image.from_blob(resp.body) layer0 = img[0] aspect_ratio = layer0.columns.to_f / layer0.rows.to_f if aspect_ratio > 1.0 new_width = 150 new_height = layer0.rows.to_f / aspect_ratio else new_width = layer0.columns.to_f / aspect_ratio new_height = 150 end thumb = layer0.resize_to_fit(new_width, new_height) send_data(thumb.to_blob, :disposition => 'inline', :type => resp.headers.fetch('content-type', 'application/octet-stream'), :filename => filename) end end
require 'open-uri' require 'pry' class Scraper def self.scrape_index_page(index_url) html=open(index_url) doc=Nokogiri::HTML(html) students_array=[] doc.css(".student-card").each do |student| hash={} hash[:name]= student.css("h4.student-name").text hash[:location]=student.css("p.student-location").text hash[:profile_url]=student.children[1].values.first students_array << hash end students_array end def self.scrape_profile_page(profile_url) html = open(profile_url) profile_page = Nokogiri::HTML(html) hash = {} profile_page.css('.social-icon-container a').each do |icon| student_name = profile_page.css('.profile-name').text student_fname, student_lname = student_name.split(" ") hash[:twitter] = icon["href"] unless !hash[:twitter].nil? if icon["href"].include?("twitter") hash[:linkedin] = icon["href"] unless !hash[:linkedin].nil? if icon["href"].include?("linkedin") hash[:github] = icon["href"] unless !hash[:github].nil? if icon["href"].include?("github") hash[:blog] = icon["href"] unless !hash[:blog].nil? if icon["href"].include?(student_fname.downcase) && !icon["href"].include?("linkedin") && !icon["href"].include?("twitter") && !icon["href"].include?("github") end hash[:profile_quote] = profile_page.css('div.profile-quote').text hash[:bio] = profile_page.css('.bio-content .description-holder').text.strip hash end end
json.array!(@needs) do |need| json.extract! need, :title, :description json.url need_url(need, format: :json) end
class Ride < ApplicationRecord belongs_to :route has_many :ride_attendances has_many :users, through: :ride_attendances end
class Post < ApplicationRecord has_one_attached :image belongs_to :user has_many :comments, dependent: :destroy acts_as_votable has_many :post_hash_tags has_many :hash_tags, through: :post_hash_tags def thumbnail return self.image.variant(resize: '500x500!').processed end def profile_thumbnail return self.image.variant(resize: '350x350!').processed end after_commit :create_hash_tags, on: :create def create_hash_tags extract_name_hash_tags.each do |name| hash_tags.create(name: name) end end def extract_name_hash_tags caption.to_s.scan(/#\w+/).map{|name| name.gsub("#", "")} end end
# Lists things = ['a', 'b', 'c', 'd'] puts things[1] things[1] = 'z' puts things[1] # Dictionaries or hashmaps or hashes stuff = {'name' => 'Zed', 'age' => 39, 'height' => 6 * 12 + 2} # print puts stuff['name'] puts stuff['height'] # add stuff['city'] = "San Francisco" puts stuff['city'] # Adding non string keys stuff[1] = "Wow" stuff[2] = "Neato" puts stuff[1] puts stuff[2] puts stuff # Using the delete function to remove keys/values stuff.delete('city') stuff.delete(1) stuff.delete(2) puts stuff # Important to learn # Create mapping of state to abbreviation states = { 'Oregon' => 'OR', 'Florida' => 'FL', 'California' => 'CA', 'New York' => 'NY', 'Michigan' => 'MI' } # Create basic set of states with cities cities = { 'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville' } # Add more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # puts out some cities puts '-' * 30 puts "NY state has: #{cities['NY']}" puts "OR state has: #{cities['OR']}" # puts using state then cities dict puts '-' * 30 puts "Michigan's abbreviation is #{states['Michigan']}" puts "Florida's abbreviation is #{states['Florida']}" # puts every state abbreviation puts '-' * 30 states.each do |state, abbrev| puts "#{state}'s abbreviation is #{abbrev}" end # puts every city in state puts '-' * 30 cities.each do |abbrev, city| puts "#{abbrev} has the city #{city}" end # now both state and city at the same time puts '-' * 30 states.each do |state, abbrev| city = cities[abbrev] puts "#{state} is abbreviated #{abbrev} and has city #{city}" end # By default, ruby says "nil" when something isn't in there puts '-' * 30 state = states['Texas'] if !state # False since it doesn't exist puts "Sorry, no Texas." end # Default values using ||= with the nil result puts '-' * 30 city = cities['TX'] city ||= 'Does not exist' # This is the same as city = city || 'Does not exist' # Since city is returned false, it will set it to 'Does not exist' since # strings are True puts "The city for the state 'TX' is: #{city}"
class CreateAttributeItems < ActiveRecord::Migration def change create_table :attribute_items do |t| t.string :target_type, null: false t.integer :target_id, null: false t.string :title, null: false t.text :body t.integer :position, null: false t.timestamps null: false end add_index :attribute_items, [:target_type, :target_id] add_index :attribute_items, :position end end
require './canhelplib' module CanhelpPlugin include Canhelp def grade_submission(token, canvas_url, course_id, assignment_id, user_id, grade) canvas_put("#{canvas_url}/api/v1/courses/#{course_id}/assignments/#{assignment_id}/submissions/#{user_id}", token, { submission: { posted_grade: grade } }) end def self.grade_all_old( canvas_url = prompt(:canvas_url), course_id = prompt(:course_id), assignment_id = prompt(:assignment_id) ) token = get_token users = get_json_paginated(token, "#{canvas_url}/api/v1/courses/#{course_id}/users") puts "#{users.count} users found" user_ids = users.map do |user| user['id'] end if assignment_id.empty? assignments = get_json_paginated(token, "#{canvas_url}/api/v1/courses/#{course_id}/assignments") assignments.each do |assignment| assignment_id = assignment['id'] user_ids.each do |user_id| score = rand(10) + 1 result = grade_submission(token, canvas_url, course_id, assignment_id, user_id, score) puts "User #{user_id} grade for Assignment #{assignment_id}: #{score}" end end else user_ids.each do |user_id| score = rand(10) + 1 result = grade_submission(token, canvas_url, course_id, assignment_id, user_id, score) puts "User #{user_id} Grade for Assignment #{assignment_id}: #{score}" end end end end
class CreateContacts < ActiveRecord::Migration def change create_table :contacts do |t| t.string :name t.integer :business_phone t.integer :home_phone t.integer :extension t.integer :department_id t.string :em_contact_name t.integer :em_contact_num t.timestamps null: false end end end
require 'test_helper' class NoteTest < ActiveSupport::TestCase def setup @note = notes(:one) end test "project, title and text should be present" do assert @note.valid? @note.title = "" @note.text = "" @note.project = nil assert_not @note.valid? end end
require 'spec_fast_helper' require 'hydramata/works/attachment_presenter' require 'hydramata/works/work' require 'hydramata/works/predicate' module Hydramata module Works describe AttachmentPresenter do let(:work) { 'a work type' } let(:predicate) { 'a predicate' } let(:value) { double('Value', to_s: 'HELLO WORLD', raw_object: raw_object) } let(:raw_object) { double('Raw Object', file_uid: 'my_file_uid') } let(:renderer) { double('Renderer', call: true) } let(:template) { double('Template') } let(:remote_url_builder) { double('Remote URL Builder', call: true) } subject { described_class.new(value: value, work: work, predicate: predicate, renderer: renderer, remote_url_builder: remote_url_builder) } it 'has a url' do expect(remote_url_builder).to receive(:call).with(raw_object.file_uid).and_return("THE URL") expect(subject.url).to eq("THE URL") end it 'renders via the template' do expect(renderer).to receive(:call).with(template, kind_of(Hash)).and_return('YES') expect(subject.render(template)).to eq('YES') end it 'renders the value as a string' do expect(renderer).to receive(:call).with(template, kind_of(Hash)).and_yield expect(subject.render(template)).to eq(value.to_s) end it 'has a default partial prefixes' do expect(subject.partial_prefixes).to eq([['a_work_type','a_predicate'], ['a_predicate']]) end it 'has a label that delegates to the underlying object' do expect(subject.label).to eq(value.to_s) end end end end
# STEAL SCRIPT # Questo script permette alle abilità di rubare. module StealSettings # icona che compare nel popup quando nulla viene rubato NO_STEAL_ICON = 0 # icona che compare quando si ruba del denaro ROBBERY_ICON = 0 # moltiplicatore probabilità di furto se il nemico è # addormentato SLEEP_MULTIPLIER = 3 # se true, tutti i nemici su cui non metti il tag # di furto denaro, verrà applicato un calcolo # automatico. Altrimenti, se false, il nemico # non avrà oro da farsi rubare AUTO_ROBBERY_CALC = false # calcola l'ammontare di denaro da rubare dal nemico # per l'abilità di furto, nel caso non sia stato # specificato (se AUTO_ROBBERY_CALC è true) ROBBERY_DEFAULT_CALC = '@gold * 2' # la probabilità predefinita di rubare soldi (può essere # ampliata dagli oggetti e status) DEFAULT_ROBBERY_PROBABILITY = 30#% end module Vocab NOTHING_TO_STEAL_ENEMY = '%s non ha niente da rubare!' NOTHING_TO_STEAL_PARTY = 'Non hai nulla di buono!' FAILED_STEAL = '%s non riesce a rubare!' STEAL_SUCCESS_ACTOR = '%s ha rubato %s!' STEAL_SUCCESS_ENEMY = '%s ti ha rubato %s!' ROBBERY_NOTHING = '%s non ha soldi!' end module StealBonus def init_steal_data return if @steal_data_init @steal_data_init = true @steal_bonus = 0 self.note.split(/[\n\r]+/).each do |line| case line when /<steal bonus:[ ]*([+\-]\d+)%>/i @steal_bonus = $1.to_f / 100 else # type code here end end end def steal_bonus @steal_bonus end end class RPG::State include StealBonus end class RPG::Weapon include StealBonus # determina se l'oggetto può essere rubato dai # nemici def stealable? false end end class RPG::Armor include StealBonus # determina se l'oggetto può essere rubato dai # nemici def stealable? false end end class RPG::Item # determina se l'oggetto può essere rubato dai # nemici def stealable? return false if self.price <= 0 return false if key_item? true end end class RPG::Enemy # @return [Array<RPG::Enemy::StealItem] attr_reader :steals attr_reader :steal_bonus def init_steal_data return if @steal_data_init @steal_data_init = true @steals = [] @gold_steal = nil @steal_bonus = 0 self.note.split(/[\n\r]+/).each do |line| # noinspection RegExpSingleCharAlternation case line when /<steal (item|armor|weapon) (\d+):[ ]*(\d+)%>/i @steals.push(StealItem.new($1.downcase.to_sym, $2.to_i, $3.to_i)) when /<steal (i|a|w):(\d+) (\d+)%>/i # legacy type = {:i => :item, :w => :weapon, :a => :armor}[$1.downcase.to_sym] @steals.push(StealItem.new(type, $2.to_i, $3.to_i)) when /<steal gold: [ ]*(\d+)>/i @gold_steal = $1.to_i else # type code here end end end # restituisce l'ammontare dell'oro che può essere # rubato def robbery_amount return @gold_steal if @gold_steal return 0 unless StealSettings::AUTO_ROBBERY_CALC eval(StealSettings::ROBBERY_DEFAULT_CALC) end class StealItem attr_reader :kind attr_reader :data_id attr_reader :probability def initialize(kind, data_id, probability) if kind.is_a?(Symbol) kind = {:item => 1, :weapon => 2, :armor => 3}[kind] end @probability = probability @data_id = data_id @kind = kind end # restituisce l'istanza dell'oggetto rubabile # @return [RPG::BaseItem] def item case @kind when 1; $data_items[@data_id] when 2; $data_weapons[@data_id] when 3; $data_armors[@data_id] else; nil end end end end class RPG::UsableItem # inizializza i dati del furto def init_steal_data return if @steal_data_init @steal_data_init = true @steal_skill = false @robbery_skill = false self.note.split(/[\n\r]+/).each do |line| case line when /<steal skill>/i @steal_skill = true when /<robbery skill>/i @robbery_skill = true else # type code here end end end # determina se è una skill in grado di rubare oggetti def steal? @steal_skill end # determina se è una skill in grado di rubare oro def robbery? @robbery_skill end end module DataManager class << self alias steal_normal_database load_normal_database alias steal_bt_database load_battle_test_database end def self.load_normal_database steal_normal_database $data_enemies.each { |enemy| enemy.init_steal_data if enemy } $data_armors.each { |armor| armor.init_steal_data if armor } $data_weapons.each { |weapon| weapon.init_steal_data if weapon } $data_skills.each { |skill| skill.init_steal_data if skill } $data_states.each { |state| state.init_steal_data if state } end end class Game_Battler alias :damage_action_before_steal :execute_damage unless $@ # processo di esecuzione del danno # @param [Game_Battler] user def execute_damage(user) #noinspection RubyArgCount damage_action_before_steal(user) obj = @no_action_dmg ? nil : user.action.action_object if obj != nil steal_action(user) if obj.steal? robbery_action(user) if obj.robbery? end end # non implementato. Va nelle sottoclassi # @param [Game_Battler] target def steal_action(target) fail NotImplementedError end # non implementato. Va nelle sottoclassi # @param [Game_Battler] user def robbery_action(user) fail NotImplementedError end # probabilità di rubare (o farsi derubare, se è un nemico) # @return [Float] def steal_rate 1.0 + features_sum(:steal_bonus) end end class Game_Actor < Game_Battler # azione per essere derubato dal nemico # @param [Game_Enemy] user def steal_action(user) stolen_item = try_steal(user) if stolen_item add_drop stolen_item message = sprintf(Vocab::STEAL_SUCCESS_ENEMY, user.name, stolen_item.name) $scene.push_popup(message, stolen_item.icon_index) end end # @param [Game_Enemy] user # @return [RPG::BaseItem] # noinspection RubyUnusedLocalVariable def try_steal(user) items = $game_party.items.compact.select {|item| item.stealable?} return nil if items.empty? stolen_item = items.sample $game_party.lose_item(stolen_item, 1) stolen_item end end class Game_Enemy < Game_Battler alias h87_steal_setup initialize # inizializzazione def initialize(index, enemy_id) h87_steal_setup(index, enemy_id) @steal_items = enemy.steals.clone @robbery_done = enemy.robbery_amount == 0 end # restituisce la lista degli oggetti ancora rubabili # @return [Array<RPG::Enemy::StealItem>] def steal_items @steal_items end # determina se il nemico non ha oggetti da rubare def no_steals? @steal_items.empty? end # azione di essere rubato dall'eroe # @param [Game_Actor] user def steal_action(user) if no_steals? message = sprintf(Vocab::NOTHING_TO_STEAL_ENEMY, self.name) $scene.push_popup(message, StealSettings::NO_STEAL_ICON) else item = try_steal(user) if item #noinspection RubyYardParamTypeMatch $game_party.gain_item(item, 1) message = sprintf(Vocab::STEAL_SUCCESS_ACTOR, user.name, item.name) $scene.push_popup(message, item.icon_index) else message = sprintf(Vocab::FAILED_STEAL, user.name) $scene.push_popup(message, StealSettings::NO_STEAL_ICON) end end end # prova ad essere rubato e restituisce # l'oggetto se ci riesce, altrimenti nil # @param [Game_Actor] user # @return [RPG::BaseItem] def try_steal(user) @steal_items.shuffle.each do |steal_item| probability = steal_item.probability * calculate_steal_prob(user) if probability > rand(100) @steal_items.delete steal_item return steal_item.item end end nil end # azione che fa subire il furto # @param [Game_Actor] user def robbery_action(user) if @robbery_done message = sprintf(Vocab::ROBBERY_NOTHING, self.name) $scene.push_popup(message, StealSettings::NO_STEAL_ICON) return end result = try_robbery(user) if result message = sprintf(Vocab::STEAL_SUCCESS_ACTOR, result) $scene.push_popup(message, StealSettings::ROBBERY_ICON) @robbery_done = true $game_party.gain_gold(result) else message = sprintf(Vocab::FAILED_STEAL, user.name) $scene.push_popup(message, StealSettings::NO_STEAL_ICON) end end # prova a rubare soldi e restituisce il valore o nil se fallisce # @param [Game_Actor] user def try_robbery(user) probability = StealSettings::DEFAULT_ROBBERY_PROBABILITY * calculate_steal_prob(user) if probability > rand(100) @robbery_done = true enemy.robbery_amount else nil end end # calcola le probabilità di default per rubare gli oggetti # aumenta se il bersaglio è incapacitato # @param [Game_Actor] user def calculate_steal_prob(user) # parriable? definito in RGSS2 come può schivare # noinspection RubyResolve sleep_mul = parriable? ? 1 : StealSettings::SLEEP_MULTIPLIER user.steal_rate * steal_rate * sleep_mul end end
class AddSearchActivatedToSwitchboard < ActiveRecord::Migration def change add_column :switchboards, :search_activated, :boolean end end
require "rails_helper" feature "As visitor I can't" do let(:article) { create :article } let(:panel_content) { "You should sign in for have ability to add comments" } scenario "create comment" do visit article_path(article) expect(page).not_to have_button "Create Comment" expect(page).to have_content(panel_content) end end
class XSD::ElementsList < Array def self.create(list_node, schema) case list_node.name when 'choice' XSD::Choice.new(list_node, schema) when 'sequence' XSD::Sequence.new(list_node, schema) when 'all' XSD::All.new(list_node, schema) else raise("not supported node on create_list:\n#{list_node.name}") end end attr_reader :min, :max, :schema def initialize(list_node, schema) @min, @max = list_node['minOccurs'], list_node['maxOccurs'] @min = @min.to_i if @min @max = @max.to_i if @max list = list_node.elements.map do |node| case node.name when 'element' XSD::Element.new(node, schema) when 'choice', 'sequence', 'all' schema.create_list(node) else raise("not supported node on create_list:\n#{node.name}: #{node.inspect}") end end self.concat list.compact end def inspect_name_type "#{self.class.name.demodulize}[#{map(&:inspect_name_type).join(', ')}]" end def instance(parent=nil, &block) map { |e| e.instance(parent, &block) }.join end end class XSD::Choice < XSD::ElementsList def inspect "Choice:#{super}" end def instance(parent=nil, &block) "<!-- Choice start -->#{super}<!-- Choice end -->" end end class XSD::Sequence < XSD::ElementsList def inspect "Sequence:#{super}" end end class XSD::All < XSD::ElementsList def inspect "All:#{super}" end end
require 'rails_helper' RSpec.describe Gif, type: :model do context "relationships" do it "belongs to category" do gif = Gif.new(image_url: "http://giphy.com/embed/11sBLVxNs7v6WA", category_id: 1 ) expect(gif).to respond_to(:category) end it "has many users" do gif = Gif.new(image_url: "http://giphy.com/embed/11sBLVxNs7v6WA", category_id: 1 ) expect(gif).to respond_to(:users) end end end
class MicroposiesController < ApplicationController # GET /microposies # GET /microposies.json def index @microposies = Microposy.all respond_to do |format| format.html # index.html.erb format.json { render json: @microposies } end end # GET /microposies/1 # GET /microposies/1.json def show @microposy = Microposy.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @microposy } end end # GET /microposies/new # GET /microposies/new.json def new @microposy = Microposy.new respond_to do |format| format.html # new.html.erb format.json { render json: @microposy } end end # GET /microposies/1/edit def edit @microposy = Microposy.find(params[:id]) end # POST /microposies # POST /microposies.json def create @microposy = Microposy.new(params[:microposy]) respond_to do |format| if @microposy.save format.html { redirect_to @microposy, notice: 'Microposy was successfully created.' } format.json { render json: @microposy, status: :created, location: @microposy } else format.html { render action: "new" } format.json { render json: @microposy.errors, status: :unprocessable_entity } end end end # PUT /microposies/1 # PUT /microposies/1.json def update @microposy = Microposy.find(params[:id]) respond_to do |format| if @microposy.update_attributes(params[:microposy]) format.html { redirect_to @microposy, notice: 'Microposy was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @microposy.errors, status: :unprocessable_entity } end end end # DELETE /microposies/1 # DELETE /microposies/1.json def destroy @microposy = Microposy.find(params[:id]) @microposy.destroy respond_to do |format| format.html { redirect_to microposies_url } format.json { head :no_content } end end end
require File.expand_path('../spec_helper', __FILE__) describe "WLang's version of BasicObject" do class A # Methods that we keep KEPT_METHODS = ["__send__", "__id__", "instance_eval", "initialize", "object_id", "nil?", "singleton_method_added", "__clean_scope__", "singleton_method_undefined"] def self.__clean_scope__ # Removes all methods that are not needed to the class (instance_methods + private_instance_methods).each do |m| undef_method(m.to_s.to_sym) unless KEPT_METHODS.include?(m.to_s) end end __clean_scope__ end it "should not have kernel methods except certain" do [:puts, :to_s, :hash].each do |sym| begin A.new.instance_eval{ __send__(sym, []) } "Not pass here".should == "" rescue NoMethodError true.should == true end end end it "should not gain methods when requiring gems" do Kernel.load(File.join(File.dirname(__FILE__),"global_extensions.rb")) begin A.new.__clean_scope__.instance_eval{ hello_world } "Not pass here".should == "" rescue NoMethodError true.should == true end end end
require 'rails_helper' RSpec.describe FeedController, type: :controller do describe '#index' do let(:time) { Time.utc(2019, 1, 20, 20, 3, 15) } let!(:article) do Timecop.freeze(time) do FactoryBot.create(:article) end end it 'returns a successful response' do get :index expect(response.code).to eq('200') end describe 'entry' do it 'includes the article uid' do get :index expect(response.body).to include("<id>#{article.uid}</id>") end it 'includes the article url' do get :index expect(response.body) .to include("<link href=\"#{article_url(article.uid)}\"/>") end it 'includes the article description' do get :index text = "<summary>&lt;p&gt;#{article.description}&lt;/p&gt;\n</summary>" expect(response.body).to include(text) end it 'includes the article title' do get :index expect(response.body) .to include("<title>#{article.title}</title>") end it 'includes the article created_at' do get :index expect(response.body) .to include('<updated>2019-01-20T20:03:15Z</updated>') end end end end
module BancSabadell class Product < Base attr_accessor :owner, :description, :user, :iban, :balance, :product, :product_number, :product_id, :currency, :has_more_pages def self.generate_url_keyword(_ = nil) 'productos' end def self.attribute_translations { propietario: :owner, descripcion: :description, usuario: :user, iban: :iban, balance: :balance, producto: :product, numeroProducto: :product_number, numeroProductoCodificado: :product_id, currency: :currency } end def account_transactions(opts = {}) AccountTransaction.query(opts.merge(product_data: { product_number: product_number, product_type: self.class.generate_url_keyword }, more_pages_container: self)) end end end
Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) namespace :api, format: 'json' do resources :books, only: %i[index show], param: :title get :search, to: 'books#search' get :ranking, to: 'books#ranking' resources :authors, only: %i[index show], param: :name end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'set' require 'fileutils' require 'dataMetaDom/help' require 'dataMetaDom/field' require 'dataMetaDom/util' require 'erb' require 'ostruct' module DataMetaDom =begin rdoc Definition for generating Plain Old Java Objects (POJOs) and everything related that depends on JDK only witout any other dependencies. TODO this isn't a bad way, but beter use templating next time such as {ERB}[http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html]. For command line details either check the new method's source or the README.rdoc file, the usage section. =end module PojoLexer include DataMetaDom =begin rdoc Maps DataMeta DOM datatypes to the matching Java classes, for those that need to be imported. The Java source generator will import these if they are used in the class. =end JAVA_IMPORTS = { DATETIME => 'java.time.ZonedDateTime', NUMERIC => 'java.math.BigDecimal' } =begin rdoc DataMeta DOM aggregated field type spec mapped to matching Java class: =end AGGR_CLASSES = { Field::SET => 'java.util.Set', Field::LIST => 'java.util.List', Field::DEQUE => 'java.util.LinkedList', } # Augment the class with Java specifics class JavaRegExRoster < RegExRoster # converts the registry to the java declarations for the class def to_patterns i_to_r.keys.map { |ix| r = i_to_r[ix] rx = r.r.to_s %<#{INDENT}private static final java.util.regex.Pattern #{RegExRoster.ixToVarName(ix)} = // #{r.vars.to_a.sort.join(', ')} #{INDENT*2}java.util.regex.Pattern.compile(#{rx.inspect});> }.join("\n\n") end # converts the registry to the verification code for the verify() method def to_verifications result = (canned.keys.map { |r| r = canned[r] vs = r.vars.to_a.sort vs.map { |v| rx = r.r.to_s %<#{INDENT*2}if(#{r.req? ? '' : "#{v} != null && "}!getCannedRegEx(#{rx.inspect}).matcher(#{v}).matches()) #{INDENT*3}throw new VerificationException("Variable \\"#{v}\\" == {{" + #{v} + "}} didn't match canned expression \\"#{rx}\\"" );> } }).flatten (result << i_to_r.keys.map { |ix| r = i_to_r[ix] vs = r.vars.to_a.sort rv = RegExRoster.ixToVarName(ix) vs.map { |v| %<#{INDENT*2}if(#{r.req? ? '' : "#{v} != null && "}!#{rv}.matcher(#{v}).matches()) #{INDENT*3}throw new VerificationException("Variable \\"#{v}\\" == {{" + #{v} + "}} didn't match custom expression {{" + #{rv} + "}}");> } }).flatten result.join("\n") end end =begin rdoc Special import for special case -- the map =end MAP_IMPORT = 'java.util.Map' # URL data type projection into Java URL_CLASS = 'java.net.URL' =begin rdoc Field types for which Java primitivs can be used along with == equality. Note that CHAR is not primitivable, we do not expect any single character fields in our metadata that should be treated differently than multichar fields. Deprecated. With the advent of the Verifiable interface, we must have all objects, no primitives. =end PRIMITIVABLE_TYPES = Set.new # [DataMetaDom::INT, BOOL, FLOAT] =begin Primitives that need to be converted to wrappers for aggregate types. =end PRIMS_TO_WRAP = { :int => 'Integer', :long => 'Long', :boolean => 'Boolean', :float => 'Float', :double => 'Double', } # Methods to fetch primitives values: def primValMethod(dt) case dt.type when INT dt.length < 5 ? 'intValue' : 'longValue' when FLOAT dt.length < 5 ? 'floatValue' : 'doubleValue' else raise ArgumentError, %<Can't determine primitive value method for the data type: #{dt}> end end =begin rdoc Wraps type into <tt>com.google.common.base.Optional<></tt> if it is required <tt> def wrapOpt(isReq, t); isReq ? t : "Optional<#{t}>" end </tt> After a bit of thinking, decided not to employ the Optional idiom by Guava then of the JDK 8 for the following reasons: * the pros don't look a clear winner vs the cons * if an optional field is made non-optional, lots of refactoring would be needed that is hard to automate * Java developers are used to deal with nulls, not so with Optionals * it requires dragging another dependency - Guava with all the generated files. * wrapping objects into Optional would create a lot of extra objects in the heap potentially with long lifespan =end def wrapOpt(isReq, t); t end # - left the work done just in case =begin rdoc Renderer for the String type. =end TEXTUAL_TYPER = lambda{|t| 'String'} =begin rdoc A map from DataMeta DOM standard types to the lambdas that render correspondent Java types per Java syntax. We used to render the primitives for the required types but the Verifiable interface made it impractical. =end JAVA_TYPES = { DataMetaDom::INT => lambda{ |t| len = t.length case when len <= 4; 'Integer' #req ? 'int' : 'Integer' when len <=8; 'Long' # req ? 'long' : 'Long' else; raise "Invalid integer length #{len}" end }, STRING => TEXTUAL_TYPER, DATETIME => lambda{|t| 'ZonedDateTime'}, BOOL => lambda{|t| 'Boolean'}, # req ? 'boolean' : 'Boolean'}, CHAR => TEXTUAL_TYPER, FLOAT => lambda{|t| len = t.length case when len <= 4; 'Float' # req ? 'float' : 'Float' when len <=8; 'Double' #req ? 'double' : 'Double' else; raise "Invalid float length #{len}" end }, RAW => lambda{|t| 'byte[]'}, URL => lambda{|t| URL_CLASS}, NUMERIC => lambda{|t| 'BigDecimal'} } =begin rdoc A hash from a character sequences to their Java escapes. Used by escapeJava method which is deprecated, see the docs, there are better ways to escape Java string in Ruby. =end JAVA_ESCAPE_HASH = { '\\'.to_sym => '\\\\', "\n".to_sym => '\\n', '"'.to_sym => '\\"', "\t".to_sym => '\\t', } =begin rdoc Maximum size of a Mapping (Map), rather aribtrary choice, not backed by any big idea. =end MAX_MAPPING_SIZE = 10000 class << self =begin rdoc Figures out type adjusted for aggregates and maps. =end def aggrType(aggr, trg, rawType, javaPackage) if aggr k = rawType.to_sym subType = PRIMS_TO_WRAP.has_key?(k) ? PRIMS_TO_WRAP[k] : rawType "#{aggr}<#{subType}>" elsif trg k = rawType.to_sym srcType = PRIMS_TO_WRAP.has_key?(k) ? PRIMS_TO_WRAP[k] : rawType typeRenderer = JAVA_TYPES[trg.type] rawTrg = typeRenderer ? typeRenderer.call(trg) : DataMetaDom.condenseType(trg.type, javaPackage) k = rawTrg.to_sym trgType = PRIMS_TO_WRAP.has_key?(k) ? PRIMS_TO_WRAP[k] : rawTrg "Map<#{srcType}, #{trgType}>" else rawType end end end =begin rdoc Given the property +docs+ of Documentable, return the JAVA_DOC_TARGET if it is present, PLAIN_DOC_TARGET otherwise. Returns empty string if the argument is nil. =end def javaDocs(docs) return '' unless docs case when docs[JAVA_DOC_TARGET] docs[JAVA_DOC_TARGET].text when docs[PLAIN_DOC_TARGET] docs[PLAIN_DOC_TARGET].text else '' end end =begin rdoc Java Class JavaDoc text with the Wiki reference. =end def classJavaDoc(docs) return <<CLASS_JAVADOC /** #{PojoLexer.javaDocs(docs)} * This class is generated by * #{WIKI_REF_HTML}. */ CLASS_JAVADOC end =begin rdoc Java Enum class-level JavaDoc text with the Wiki reference. =end def enumJavaDoc(docs) return <<ENUM_JAVADOC /** #{PojoLexer.javaDocs(docs)} * This enum is generated by * #{WIKI_REF_HTML}. */ ENUM_JAVADOC end =begin rdoc For the given DataMeta DOM data type and the isRequired flag, builds and returns the matching Java data type declaration. For standard types, uses the JAVA_TYPES map =end def getJavaType(dmDomType) typeRenderer = JAVA_TYPES[dmDomType.type] typeRenderer ? typeRenderer.call(dmDomType) : dmDomType.type end =begin rdoc Renders the value for the given DataType according to Java syntax, for all standard data types. See STANDARD_TYPES. =end def getJavaVal(dataType, val) case when dataType.type == DATETIME %Q< java.time.ZonedDateTime.from(java.time.format.DateTimeFormatter.ISO_DATE_TIME.parse("#{val.to_s}")) > when dataType.type == NUMERIC %Q< new BigDecimal(#{val.inspect}) > when val.kind_of?(Symbol) val.to_s.inspect when dataType.type == FLOAT && dataType.length <= 4 "#{val.inspect}F" when dataType.type == INT && dataType.length > 4 "#{val.inspect}L" when dataType.type == URL %Q< new java.net.URL(#{val.inspect}) > else val.inspect end end =begin rdoc Used to escape the given string according to the Java syntax, now *deprecated*, use Ruby Object.inspect or the getJavaVal method. =end def escapeJava(what) result = '' what.each_char { |c| replacement = JAVA_ESCAPE_HASH[c.to_sym] result << ( replacement ? replacement : c ) } result end =begin rdoc Builds Java imports for the given fields if any, per JAVA_IMPORTS. Returns the text of imports to insert straight into the Java source file =end def javaImports(fields) imports = Set.new fields.each { |f| importable = JAVA_IMPORTS[f.dataType.type] imports << importable.to_sym if importable if f.aggr? imports << AGGR_CLASSES[f.aggr].to_sym elsif f.map? imports << MAP_IMPORT.to_sym srcImport = JAVA_IMPORTS[f.trgType.type] imports << srcImport.to_sym if srcImport end } imports # remnant of the Optional effort for non-required fields #hasOpt = fields.values.map{|f| !f.isRequired }.reduce(:|) # true if there is at least one optional field #imports << 'com.google.common.base.Optional' << 'static com.google.common.base.Optional.fromNullable' if hasOpt end # Converts an import set to the matching Java source snippet. def importSetToSrc(importSet) importSet.to_a.map{|k| "import #{k};"}.sort.join("\n") + "\n" end =begin rdoc Generates Java source code, the Java class for a DataMeta DOM Record Parameters: * +model+ - the source model to export from * +out+ - open output file to write the result to. * +record+ - instance of DataMetaDom::Record to export * +javaPackage+ - Java package to export to * +baseName+ - the name of the class to generate. =end def genEntity(model, out, record, javaPackage, baseName) fields = record.fields # scan for imports needed out.puts <<ENTITY_CLASS_HEADER package #{javaPackage}; #{importSetToSrc(javaImports fields.values)} import org.ebay.datameta.dom.Verifiable; import java.util.Objects; import java.util.StringJoiner; import org.ebay.datameta.dom.VerificationException; import org.ebay.datameta.util.jdk.SemanticVersion; import static org.ebay.datameta.dom.CannedRegexUtil.getCannedRegEx; #{PojoLexer.classJavaDoc(record.docs)}public class #{baseName} implements Verifiable { ENTITY_CLASS_HEADER if record.ver out.puts %Q<#{INDENT}public static final SemanticVersion VERSION = SemanticVersion.parse("#{record.ver.full}"); > end fieldDeclarations = '' gettersSetters = '' eqHashFields = record.identity ? record.identity.args : fields.keys.sort reqFields = fields.values.select{|f| f.isRequired }.map{|f| f.name} rxRoster = JavaRegExRoster.new fieldVerifications = '' fields.each_key { |k| f = fields[k] dt = f.dataType rxRoster.register(f) if f.regex typeDef = aggrJavaType(f, javaPackage) if f.trgType # Maps: if either the key or the value is verifiable, do it mainVf = model.records[dt.type] # main data type is verifiable trgVf = model.records[f.trgType.type] # target type is verifiable if mainVf || trgVf fieldVerifications << "#{INDENT*2}#{!f.isRequired ? "if(#{f.name} != null) " : '' }#{f.name}.forEach((k,v) -> {#{mainVf ? 'k.verify();' : ''} #{trgVf ? 'v.verify();' : ''}});\n" end end if model.records[dt.type] && !f.trgType # maps handled separately fieldVerifications << "#{INDENT*2}#{!f.isRequired ? "if(#{f.name} != null) " : '' }#{f.name}#{f.aggr ? '.forEach(Verifiable::verify)' : '.verify()'};\n" # the Verifiable::verify method reference works just fine, tested it: Java correctly calls the method on the object end fieldDeclarations << "\n#{INDENT}private #{wrapOpt(f.isRequired, typeDef)} #{f.name};" if f.isRequired gettersSetters << <<CHECKING_SETTER #{INDENT}public void #{DataMetaDom.setterName(f)}(final #{typeDef} newValue) { #{INDENT*2}if(newValue == null) throw new IllegalArgumentException( #{INDENT*4}"NULL passed to the setter of the required field '#{f.name}' on the class #{record.name}."); #{INDENT*2}this.#{f.name} = newValue; #{INDENT}} CHECKING_SETTER else # not required, can not be primitive - wrap into Optional<> gettersSetters << "\n#{INDENT}public void #{DataMetaDom.setterName(f)}(final #{wrapOpt(f.isRequired, typeDef)} newValue) {this.#{f.name} = newValue; }\n" end if f.docs.empty? gettersSetters << "\n" else gettersSetters << <<FIELD_JAVADOC #{INDENT}/** #{PojoLexer.javaDocs f.docs}#{INDENT} */ FIELD_JAVADOC end gettersSetters << "#{INDENT}public #{wrapOpt(f.isRequired, typeDef)} #{DataMetaDom.getterName(f)}() {return this.#{f.name}; }\n" } out.puts(rxRoster.to_patterns) out.puts fieldDeclarations out.puts out.puts gettersSetters out.puts %| #{INDENT}/** #{INDENT}* If there is class type mismatch, somehow we are comparing apples to oranges, this is an error, not #{INDENT}* a not-equal condition. #{INDENT}*/ #{INDENT}@SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object other) { #{INDENT * 2}return Objects.deepEquals(new Object[]{#{eqHashFields.map{|q| "this.#{q}"}.join(', ')}}, #{INDENT * 2} new Object[]{#{eqHashFields.map{|q| "((#{baseName}) other).#{q}"}.join(', ')}}); #{INDENT}} | out.puts %| #{INDENT}@Override public int hashCode() {// null - safe: result = 31 * result + (element == null ? 0 : element.hashCode()); #{INDENT * 2}return Objects.hash(#{eqHashFields.map{|q| "this.#{q}"}.join(', ')}); #{INDENT}} | verCalls = reqFields.map{|r| %<if(#{r} == null) missingFields.add("#{r}");>}.join("\n#{INDENT * 2}") out.puts %| #{INDENT}public void verify() { | unless verCalls.empty? out.puts %| #{INDENT * 2}StringJoiner missingFields = new StringJoiner(", "); #{INDENT * 2}#{verCalls} #{INDENT * 2}if(missingFields.length() != 0) throw new VerificationException(getClass().getSimpleName() + ": required fields not set: " + missingFields); | end out.puts %| #{rxRoster.to_verifications} #{fieldVerifications} #{INDENT}} | out.puts %< #{INDENT}public final SemanticVersion getVersion() { return VERSION; } }> end # Unaggregated Java type def unaggrJavaType(dt, javaPackage) typeRenderer = JAVA_TYPES[dt.type] typeRenderer ? typeRenderer.call(dt) : DataMetaDom.condenseType(dt.type, javaPackage) end # aggregated Java type def aggrJavaType(f, javaPackage) rawType = unaggrJavaType(f.dataType, javaPackage) aggr = f.aggr? ? DataMetaDom.splitNameSpace(AGGR_CLASSES[f.aggr])[1] : nil PojoLexer.aggrType(aggr, f.trgType, rawType, javaPackage) end =begin DataMetaSame condition generated for the given field. This applies only for a single instance. All aggregation specifics are hhandled elsewhere (see genDataMetaSame) =end def lsCondition(parser, f, javaPackage, suffix, imports, one, another) dt = f.dataType g = "#{DataMetaDom.getterName(f)}()" if false # Ruby prints the warning that the var is unused, unable to figure out that it is used in the ERB file # and adding insult to injury, the developers didn't think of squelching the false warnings p g end typeRec = parser.records[dt.type] enumType = parser.enums[dt.type] case when typeRec ftNs, ftClassBase = DataMetaDom.splitNameSpace(typeRec.name) # the name of the DataMetaSame implementor of the Field's type, assuming it is available during compile time ftLsClassBase = "#{ftClassBase}#{suffix}" # import the class if it belogns to a different package imports << "#{DataMetaDom.combineNsBase(ftNs, ftLsClassBase)}" unless javaPackage == ftNs %Q<#{ftLsClassBase}.I.isSame(#{one}, #{another})> when (f.isRequired && PRIMITIVABLE_TYPES.member?(dt.type)) || (enumType && enumType.kind_of?(DataMetaDom::Enum)) %Q<(#{one} == #{another})> when enumType && enumType.kind_of?(DataMetaDom::Mappings) %Q<MAP_EQ.isSame(#{one}, #{another})> else # leverage the equals method, that works for the BitMaps too %Q<EQ.isSame(#{one}, #{another})> end end =begin rdoc Generates Java source code for the DataMetaSame implementor in Java to compare by all the fields in the class for the given Record. No attempt made to pretty-format the output. Pretty-formatting makes sense only when human eyes look at the generated code in which case one keyboard shortcut gets the file pretty-formatted. Beside IDEs, there are Java pretty-formatters that can be plugged in into the build process: * {Jalopy}[http://jalopy.sourceforge.net] * {JxBeauty}[http://members.aon.at/johann.langhofer/jxb.htm] * {BeautyJ}[http://beautyj.berlios.de] To name a few. Parameters: * +parser+ - the instance of Model * +destDir+ - destination root. * +javaPackage+ - Java package to export to * +suffix+ - The suffix to append to the DataMeta DOM Class to get the DataMetaSame implementor's name. * +dmClass+ - the name of DataMeta DOM class to generate for * +record+ - the DataMeta DOM record to generate the DataMetaSame implementors for. * +fields+ - a collection of fields to compare =end def genDataMetaSame(parser, destDir, javaPackage, suffix, dmClass, record, fields) conditions = [] aggrChecks = '' imports = javaImports(fields) javaClass = "#{dmClass}#{suffix}" fields.each { |f| g = "#{DataMetaDom.getterName(f)}()" if f.aggr? if f.set? =begin # no option with the Set for full compare -- a Set is a Set, must use equals and hashCode but, if in future a need arises, could use the following pattern -- tested, the stream shortcut works fine: final Set<String> personas___1__ = one.getPersonas(); final Set<String> personas___2__ = another.getPersonas(); if(personas___1__ != personas___2__) { if(personas___1__ == null || personas___2__ == null ) return false; // one of them is null but not both -- not equal short-circuit if(personas___1__.size() != personas___2__.size()) return false; // this should run in supposedly O(N), since Set.contains(v) is supposedly O(1) final Optional<String> firstMismatch = personas___1__.stream().filter(v -> !personas___2__.contains(v)).findFirst(); if(firstMismatch.isPresent()) return false; } =end conditions << %|(one.#{g} != null && one.#{g}.equals(another.#{g}))| else a1 = "#{f.name}___1__" a2 = "#{f.name}___2__" li1 = "#{f.name}___li1__" li2 = "#{f.name}___li2__" jt = unaggrJavaType(f.dataType, javaPackage) aggrChecks << %| #{INDENT * 2}final #{aggrJavaType(f, javaPackage)} #{a1} = one.#{g}; #{INDENT * 2}final #{aggrJavaType(f, javaPackage)} #{a2} = another.#{g}; #{INDENT * 2}if(#{a1} != #{a2} ) { #{INDENT * 3}if(#{a1} == null #{'||'} #{a2} == null ) return false; // one of them is null but not both -- not equal short-circuit #{INDENT * 3}java.util.ListIterator<#{jt}> #{li1} = #{a1}.listIterator(); #{INDENT * 3}java.util.ListIterator<#{jt}> #{li2} = #{a2}.listIterator(); #{INDENT * 3}while(#{li1}.hasNext() && #{li2}.hasNext()) { #{INDENT * 4}final #{jt} o1 = #{li1}.next(), o2 = #{li2}.next(); #{INDENT * 4}if(!(o1 == null ? o2 == null : #{lsCondition(parser, f, javaPackage, suffix, imports, 'o1', 'o2')})) return false; // shortcircuit to false #{INDENT * 3}} #{INDENT * 3}if(#{li1}.hasNext() #{'||'} #{li2}.hasNext()) return false; // leftover elements in one #{INDENT * 2}} | end elsif f.map? a1 = "#{f.name}___1__" a2 = "#{f.name}___2__" aggrChecks << %| #{INDENT * 2}final java.util.Map<#{unaggrJavaType(f.dataType, javaPackage)}, #{unaggrJavaType(f.trgType, javaPackage)}> #{a1} = one.#{g}; #{INDENT * 2}final java.util.Map<#{unaggrJavaType(f.dataType, javaPackage)}, #{unaggrJavaType(f.trgType, javaPackage)}> #{a2} = another.#{g}; #{INDENT * 2}if(#{a1} != #{a2} ) { #{INDENT * 3}if(#{a1} == null #{'||'} #{a2} == null ) return false; // one of them is null but not both -- not equal short-circuit #{INDENT * 3}if(!#{a1}.equals(#{a2})) return false; // Maps are shallow-compared, otherwise logic and spread of semantics are too complex #{INDENT * 2}} | else # regular field conditions << lsCondition(parser, f, javaPackage, suffix, imports, "one.#{g}", "another.#{g}") end } out = File.open(File.join(destDir, "#{javaClass}.java"), 'wb') out.puts <<DM_SAME_CLASS package #{javaPackage}; #{importSetToSrc(imports)} import org.ebay.datameta.dom.DataMetaSame; import org.ebay.datameta.util.jdk.SemanticVersion; #{PojoLexer.classJavaDoc record.docs}public class #{javaClass} implements DataMetaSame<#{dmClass}>{ #{INDENT}/** #{INDENT}* Convenience instance. #{INDENT}*/ #{INDENT}public final static #{javaClass} I = new #{javaClass}(); #{INDENT}@Override public boolean isSame(final #{dmClass} one, final #{dmClass} another) { #{INDENT * 2}if(one == another) return true; // same object or both are null #{INDENT * 2}//noinspection SimplifiableIfStatement #{INDENT * 2}if(one == null || another == null) return false; // whichever of them is null but the other is not #{INDENT * 2}#{aggrChecks} #{INDENT * 2}return #{conditions.join(' && ')}; #{INDENT}} DM_SAME_CLASS if record.ver out.puts %Q<#{INDENT}public static final SemanticVersion VERSION = SemanticVersion.parse("#{record.ver.full}");> end out.puts '}' out.close end =begin rdoc Runs generation of Java source code for DataMetaSame implementors for the given parser into the given output path. Parameters: * +parser+ - an instance of DataMetaDom::Model * +outRoot+ - the path to output the generated Java packages into * +style+ - can pass one of the following values: * ID_ONLY_COMPARE - see the docs to it * FULL_COMPARE - see the docs to it =end def genDataMetaSames(parser, outRoot, style = FULL_COMPARE) parser.records.values.each { |record| javaPackage, base, packagePath = assertNamespace(record.name) destDir = File.join(outRoot, packagePath) FileUtils.mkdir_p destDir case style when FULL_COMPARE suffix = SAME_FULL_SFX fields = record.fields.values when ID_ONLY_COMPARE unless record.identity L.warn "#{record.name} does not have identity defined" next end suffix = SAME_ID_SFX fields = record.fields.keys.select{|k| record.identity.hasArg?(k)}.map{|k| record.fields[k]} else; raise %Q<Unsupported DataMetaSame POJO style "#{style}"> end if fields.empty? L.warn "#{record.name} does not have any fields to compare by" next end genDataMetaSame parser, destDir, javaPackage, suffix, base, record, fields } end =begin rdoc Generates Java source code for the worded enum, DataMeta DOM keyword "<tt>enum</tt>". =end def genEnumWorded(out, enum, javaPackage, baseName) values = enum.keys.map{|k| enum[k]} # sort by ordinals to preserve the order out.puts <<ENUM_CLASS_HEADER package #{javaPackage}; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import org.ebay.datameta.dom.DataMetaEntity; import org.ebay.datameta.util.jdk.SemanticVersion; import static java.util.Collections.unmodifiableMap; #{enumJavaDoc(enum.docs)}public enum #{baseName} implements DataMetaEntity { #{values.join(', ')}; /** * Staple Java lazy init idiom. * See <a href="http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom">this article</a>. */ private static class LazyInit { final static Map<String, #{baseName}> NAME_TO_ENUM; final static #{baseName}[] ORD_TO_ENUM = new #{baseName}[values().length]; static { final Map<String, #{baseName}> map = new HashMap<>(values().length * 3 / 2 + 1); for (int ix = 0; ix < values().length; ix++) { final #{baseName} val = values()[ix]; ORD_TO_ENUM[ix] = val; map.put(val.name(), val); } NAME_TO_ENUM = unmodifiableMap(map); } } /** * Retrieve a value for the given textual form. * Lenient replacement for {@link Enum#valueOf(Class, java.lang.String)} that returns null * instead of throwing an exception. */ @Nullable public static #{baseName} forName(final String textual) { return LazyInit.NAME_TO_ENUM.get(textual); } /** * Fast instance retrieval for the given ordinal, works super fast because it uses an array * indexing, not a map. */ @Nullable public static #{baseName} forOrd(final int ordinal) { return LazyInit.ORD_TO_ENUM[ordinal]; } public static interface Visitor<IN, OUT> { ENUM_CLASS_HEADER values.each { |v| out.puts " OUT visit#{v}(IN input);" } out.puts <<VISITOR_SWITCH_HEAD } /** Use this switch with your {@link Visitor} implementation, * There should be no other switches of this kind in your program. * If the enum changes, all implementations will break and will need to be fixed. * This will ensure that no unhandled cases will be left in the program. */ public static <IN, OUT> OUT visit(final #{baseName} value, final Visitor<IN, OUT> visitor, final IN input) { switch(value) { VISITOR_SWITCH_HEAD values.each { |v| out.puts " case #{v}:\n return visitor.visit#{v}(input);" } out.puts <<VISITOR_SWITCH_TAIL default: throw new IllegalArgumentException("Unsupported enum value: " + value); } } VISITOR_SWITCH_TAIL if enum.ver out.puts %Q< public static final SemanticVersion VERSION = SemanticVersion.parse("#{enum.ver.full}");> end out.puts %< #{INDENT}public final SemanticVersion getVersion() { return VERSION; } }> end =begin rdoc Generates Java source code for the DataMeta DOM Mapping, DataMeta DOM keyword "<tt>mapping</tt>". =end def genMapping(out, mapping, javaPackage, baseName) keys = mapping.keys raise "Mapping too big, size = #{keys.length}, max size #{MAX_MAPPING_SIZE}" if keys.length > MAX_MAPPING_SIZE fromType = getJavaType(mapping.fromT) toType = getJavaType(mapping.toT) imports = {} importable = JAVA_IMPORTS[mapping.fromT.type]; imports[importable.to_sym] = 1 if importable importable = JAVA_IMPORTS[mapping.toT.type]; imports[importable.to_sym] = 1 if importable importText = imports.keys.to_a.map{|i| "import #{i};"}.join("\n") mapGeneric = "#{fromType}, #{toType}" out.puts <<MAPPING_CLASS_HEADER package #{javaPackage}; import org.ebay.datameta.dom.Mapping; #{importText} import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.ebay.datameta.util.jdk.SemanticVersion; #{PojoLexer.classJavaDoc mapping.docs}public final class #{baseName} implements Mapping<#{mapGeneric}>{ private final static Map<#{mapGeneric}> mapping; protected final static int count = #{keys.length}; static { final Map<#{mapGeneric}> m = new HashMap<#{mapGeneric}>(count * 3 / 2 + 1); MAPPING_CLASS_HEADER keys.sort.each { |k| out.puts %Q<#{INDENT*2}m.put(#{getJavaVal(mapping.fromT, k)}, #{getJavaVal(mapping.toT, mapping[k])});> } out.puts <<MAPPING_CLASS_FOOTER mapping = Collections.unmodifiableMap(m); } public static int size() { return mapping.size(); } public static boolean containsKey(#{fromType} key) { return mapping.containsKey(key); } public static #{toType} get(#{fromType} key) { return mapping.get(key); } public static Set<#{fromType}> keySet() { return mapping.keySet(); } public static Collection<#{toType}> values() { return mapping.values(); } private static void assertKey(#{fromType} key) { if(!mapping.containsKey(key)) throw new IllegalArgumentException("The key " + key + " does not belong to this mapping"); } private #{fromType} key; public #{baseName}(){} public #{baseName}(#{fromType} key){ assertKey(key); this.key = key;} public void setKey(#{fromType} key) {assertKey(key); this.key = key; } public #{fromType} getKey() { return key; } public #{toType} getValue() { return mapping.get(key); } @Override public String toString() { return getClass().getSimpleName() + '{' + key + "=>" + mapping.get(key) + '}'; } MAPPING_CLASS_FOOTER if mapping.ver out.puts %Q< public static final SemanticVersion VERSION = SemanticVersion.parse("#{mapping.ver.full}");> end out.puts %< #{INDENT}public final SemanticVersion getVersion() { return VERSION; } }> end =begin rdoc Generates Java source code for the DataMeta DOM BitSet, DataMeta DOM keyword "<tt>bitset</tt>". =end def genBitSet(out, bitSet, javaPackage, baseName) keys = bitSet.keys toType = getJavaType(bitSet.toT) importable = JAVA_IMPORTS[bitSet.toT.type] importTxt = importable ? "import #{importable};" : '' maxBit = bitSet.keys.max raise "Mapping too big, size = #{maxBit}, max size #{MAX_MAPPING_SIZE}" if maxBit > MAX_MAPPING_SIZE out.puts <<BIT_SET_HEADER package #{javaPackage}; import org.ebay.datameta.dom.BitSetImpl; import org.ebay.datameta.util.jdk.SemanticVersion; #{importTxt} #{PojoLexer.classJavaDoc bitSet.docs}public final class #{baseName} extends BitSetImpl<#{toType}>{ public static final int MAX_BIT = #{maxBit}; public static final int COUNT = MAX_BIT + 1; // we do not expect huge arrays here, the sizes should be very limited and likely continuous. private static final #{toType}[] mapping = new #{toType}[COUNT]; static { BIT_SET_HEADER keys.sort.each { |k| out.puts %Q<#{INDENT*2}mapping[#{k}] = #{getJavaVal(bitSet.toT, bitSet[k])};> } out.puts <<BIT_SET_FOOTER } public #{baseName}() { } public #{baseName}(long[] image) { super(image); } public final int getCount() { return COUNT; } public final #{toType}[] getMap() { return mapping;} BIT_SET_FOOTER if bitSet.ver out.puts %Q< public static final SemanticVersion VERSION = SemanticVersion.parse("#{bitSet.ver.full}");> end out.puts %< #{INDENT}public final SemanticVersion getVersion() { return VERSION; } }> end =begin rdoc Extracts 3 pieces of information from the given full name: * The namespace if any, i.e. Java package, empty string if none * The base name for the type, without the namespace * Java package's relative path, the dots replaced by the file separator. Returns an array of these pieces of info in this exact order as described here. =end def assertNamespace(name) ns, base = DataMetaDom.splitNameSpace(name) javaPackage = DataMetaDom.validNs?(ns, base) ? ns : '' packagePath = javaPackage.empty? ? '' : javaPackage.gsub('.', File::SEPARATOR) [javaPackage, base, packagePath] end =begin rdoc Generates java sources for the model, the POJOs. * Parameters * +parser+ - instance of Model * +outRoot+ - output directory =end def genPojos(model, outRoot) (model.enums.values + model.records.values).each { |e| javaPackage, base, packagePath = assertNamespace(e.name) destDir = File.join(outRoot, packagePath) FileUtils.mkdir_p destDir out = File.open(File.join(destDir, "#{base}.java"), 'wb') begin case when e.kind_of?(DataMetaDom::Record) genEntity model, out, e, javaPackage, base when e.kind_of?(DataMetaDom::Mappings) genMapping out, e, javaPackage, base when e.kind_of?(DataMetaDom::Enum) genEnumWorded out, e, javaPackage, base when e.kind_of?(DataMetaDom::BitSet) genBitSet out, e, javaPackage, base else raise "Unsupported Entity: #{e.inspect}" end ensure out.close end } end =begin Generates migration guides from the given model to the given model =end def genMigrations(mo1, mo2, outRoot) v1 = mo1.records.values.first.ver.full v2 = mo2.records.values.first.ver.full destDir = outRoot javaPackage = '' # set the scope for the var vars = OpenStruct.new # for template's local variables. ERB does not make them visible to the binding if false # Ruby prints the warning that the var is unused, unable to figure out that it is used in the ERB file # and adding insult to injury, the developers didn't think of squelching the false warnings p vars # it's interesting that there is no warning about the unused destDir and javaPackage. Duh! end # sort the models by versions out, 2nd to be the latest: raise ArgumentError, "Versions on the model are the same: #{v1}, nothing to migrate" if v1 == v2 if v1 > v2 model2 = mo1 model1 = mo2 ver1 = v2 ver2 = v1 else model2 = mo2 model1 = mo1 ver1 = v1 ver2 = v2 end puts "Migrating from ver #{ver1} to #{ver2}" ctxs = [] droppedRecs = [] addedRecs = [] (model1.enums.values + model1.records.values).each { |srcE| trgRecName = flipVer(srcE.name, ver1.toVarName, ver2.toVarName) trgE = model2.records[trgRecName] || model2.enums[trgRecName] droppedRecs << srcE.name unless trgE } (model2.enums.values + model2.records.values).each { |trgE| srcRecName = flipVer(trgE.name, ver2.toVarName, ver1.toVarName) srcE = model1.records[srcRecName] || model1.enums[srcRecName] unless srcE addedRecs << trgE.name next end javaPackage, baseName, packagePath = assertNamespace(trgE.name) javaClassName = migrClass(baseName, ver1, ver2) destDir = File.join(outRoot, packagePath) migrCtx = MigrCtx.new trgE.name ctxs << migrCtx FileUtils.mkdir_p destDir javaDestFile = File.join(destDir, "#{javaClassName}.java") case when trgE.kind_of?(DataMetaDom::Record) if File.file?(javaDestFile) migrCtx.isSkipped = true $stderr.puts %<Migration target "#{javaDestFile} present, therefore skipped"> else IO::write(javaDestFile, ERB.new(IO.read(File.join(File.dirname(__FILE__), '../../tmpl/java/migrationEntityEnums.erb')), $SAFE, '%<>').result(binding), mode: 'wb') end when trgE.kind_of?(DataMetaDom::Mappings) $stderr.puts "WARN: Migration guides for the mapping #{trgE.name} are not generated; migration is not implemented for mappings" when trgE.kind_of?(DataMetaDom::Enum) # handled by the POJO migrator above, i.e. the case when trgE.kind_of?(DataMetaDom::Record) when trgE.kind_of?(DataMetaDom::BitSet) $stderr.puts "WARN: Migration guides for the bitset #{trgE.name} are not generated; migration is not implemented for bitsets" else raise "Unsupported Entity: #{trgE.inspect}" end } noAutos = ctxs.reject{|c| c.canAuto} skipped = ctxs.select{|c| c.isSkipped} $stderr.puts %<Migration targets skipped: #{skipped.size}> unless skipped.empty? unless noAutos.empty? $stderr.puts %<#{noAutos.size} class#{noAutos.size > 1 ? 'es' : ''} out of #{ctxs.size} can not be migrated automatically: #{noAutos.map{|c| c.rec}.sort.join("\n")} Please edit the Migrate_ code for #{noAutos.size > 1 ? 'these' : 'this one'} manually. > end unless droppedRecs.empty? $stderr.puts %<#{droppedRecs.size} class#{droppedRecs.size > 1 ? 'es were' : ' was'} dropped from your model: #{droppedRecs.sort.join("\n")} -- you may want to review if #{droppedRecs.size > 1 ? 'these were' : 'this one was'} properly handled. > end unless addedRecs.empty? $stderr.puts %<#{addedRecs.size} class#{addedRecs.size > 1 ? 'es were' : ' was'} added to your model: #{addedRecs.sort.join("\n")} -- no migration guides were generated for #{addedRecs.size > 1 ? 'these' : 'this one'}. > end end =begin rdoc Runs DataMetaSame generator for the given style. Parameters: * +style+ - FULL_COMPARE or ID_ONLY_COMPARE * +runnable+ - the name of the executable script that called this method, used for help =end def dataMetaSameRun(style, runnable, source, target, options={autoVerNs: true}) @source, @target = source, target helpDataMetaSame runnable, style unless @source && @target helpDataMetaSame(runnable, style, "DataMeta DOM source #{@source} is not a file") unless File.file?(@source) helpDataMetaSame(runnable, style, "DataMetaSame destination directory #{@target} is not a dir") unless File.directory?(@target) @parser = Model.new begin @parser.parse(@source, options) genDataMetaSames(@parser, @target, style) rescue Exception => e puts "ERROR #{e.message}; #{@parser.diagn}" puts e.backtrace.inspect end end # Shortcut to help for the Full Compare DataMetaSame generator. def helpDataMetaSame(file, style, errorText=nil) styleWording = case style when FULL_COMPARE; "Full" when ID_ONLY_COMPARE; "Identity Only" else raise %Q<Unsupported identity style "#{style}"> end help(file, "#{styleWording} Compare DataMetaSame generator", '<DataMeta DOM source> <target directory>', errorText) end # Switches Namespace version part on a versioned DataMeta DOM entity. def flipVer(fullName, from, to) fullName.to_s.gsub(".v#{from}.", ".v#{to}.").to_sym end # The field must be an aggregate. The method puts together an argument for the proper collection setter def setAggrPrims(trgFld) #new LinkedList<>(src.getInts().stream().map(Integer::longValue).collect(Collectors.toList())) case trgFld.aggr when Field::SET %|src.#{DataMetaDom.getterName(trgFld)}().stream().map(e -> e.#{primValMethod(trgFld.dataType)}()).collect(toSet())| when Field::LIST %|new ArrayList<>(src.#{DataMetaDom.getterName(trgFld)}().stream().map(e -> e.#{primValMethod(trgFld.dataType)}()).collect(toList()))| when Field::DEQUE %|new LinkedList<>(src.#{DataMetaDom.getterName(trgFld)}().stream().map(e -> e.#{primValMethod(trgFld.dataType)}()).collect(toList()))| else raise ArgumentError, %<Unsupported aggregation type on the field: #{trgFld}> end end module_function :getJavaType, :getJavaVal, :wrapOpt, :classJavaDoc, :assertNamespace, :dataMetaSameRun, :genDataMetaSames, :genDataMetaSame, :helpDataMetaSame, :javaImports, :javaDocs, :genPojos, :genEntity, :flipVer, :primValMethod, :importSetToSrc, :aggrJavaType, :unaggrJavaType, :lsCondition end end
class StudentsController < ApplicationController def index if params[:cohort_id] @cohort = Cohort.find(params[:cohort_id]) @students = @cohort.students else @students = Student.all end end def new @cohorts = Cohort.all @cohort = Cohort.find_by(id: params[:cohort_id]) @student = Student.new @student.textbooks.build([{}, {}]) end def create @student = Student.new(student_params) if @student.save redirect_to students_url else @errors = @student.errors.full_messages @cohorts = Cohort.all render :new end end private def student_params params.require(:student).permit(:name, :cohort_id, textbooks_attributes: [:vandalized, :title]) end end
class Note < ApplicationRecord belongs_to :user validates_presence_of :name, presence: true validates_presence_of :body, presence: true end
class WebHookParser attr_reader :params def initialize(params) @params = params end def parse link end def self.parse(params) new(params).parse end private def link @link ||= @params[:text].scan(/https:\/\/hooks.slack.com\/services\/\S+/).first end end
module Fog module Compute class ProfitBricks class Real # Update a group. # Normally a PUT request would require that you pass all the attributes and values. # In this implementation, you must supply the name, even if it isn't being changed. # As a convenience, the other four attributes will default to false. # You should explicitly set them to true if you want to have them enabled. # # ==== Parameters # * group_id<~String> - Required, The ID of the specific group to update. # * resource_id<~String> - Required, The ID of the specific resource to update. # * properties<~Hash>: - A collection of properties. # * editPrivilege<~Boolean> - The group has permission to edit privileges on this resource. # * sharePrivilege<~Boolean> - The group has permission to share this resource. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~String> - Id of the requested resource # * type<~String> - type of the requested resource # * href<~String> - url to the requested resource # * items<~Array> # * id<~String> - The resource's unique identifier # * type<~String> - The type of the requested resource # * href<~String> - URL to the object’s representation (absolute path) # * properties<~Hash> - Hash containing the share properties. # * editPrivilege<~Boolean> - The group has permission to edit privileges on this resource. # * sharePrivilege<~Boolean> - The group has permission to share this resource. # # {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v4/#update-a-share] def update_share(group_id, resource_id, options = {}) share = { :properties => options } request( :expects => [202], :method => 'PUT', :path => "/um/groups/#{group_id}/shares/#{resource_id}", :body => Fog::JSON.encode(share) ) end end class Mock def update_share(group_id, resource_id, options = {}) if share = data[:shares]['items'].find do |shr| shr["id"] == resource_id end share['editPrivilege'] = options[:edit_privilege] if options[:edit_privilege] share['sharePrivilege'] = options[:share_privilege] if options[:share_privilege] else raise Excon::Error::HTTPStatus, 'The requested resource could not be found' end response = Excon::Response.new response.status = 202 response.body = share response end end end end end
# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. class OngoingMatchChannel < ApplicationCable::Channel def subscribed stream_from "ongoing_match_#{params[:table_id]}" end def unsubscribed # Any cleanup needed when channel is unsubscribed end class << self def broadcast_update(table: Table.default) return unless table json = payload_json(table.ongoing_match) ActionCable.server.broadcast "ongoing_match_#{table.id}", json end private def payload_json(match) if match options = { serializer: OngoingMatchSerializer, include: [ :home_player, :away_player, :next_matchup, :betting_info ] } ActiveModelSerializers::SerializableResource.new(match, options).to_json else nil.to_json end end end end
# If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. # # {20,48,52}, {24,45,51}, {30,40,50} # # For which value of p <= 1000, is the number of solutions maximised? # beginning_time = Time.now class Integer def num_solutions solutions = [] a,b,c = 1,1,0 while a < self while b < self c = self-a-b if a**2 + b**2 == c**2 solutions << [a,b,c] end b+=1 end b=1 a+=1 end return solutions.map { |x| x.sort}.uniq.length end end solutions = 0 maxP = 0 maxSolutions = 0 1.upto(1000) do |p| if p%1 == 0 solutions = p.num_solutions if solutions > maxSolutions maxSolutions = solutions maxP = p puts maxP.to_s + " " + maxSolutions.to_s end end end p maxP end_time = Time.now puts puts "Time elapsed #{(end_time - beginning_time)} seconds"
require 'rails_helper' describe Users::CreditcardsController do describe "#index" do context 'not login' do before do @request.env["devise.mapping"] = Devise.mappings[:user] session[:received_form] = { user: { nickname: Faker::Name.last_name, email: Faker::Internet.free_email, password: "password", password_confirmation: "password", last_name: Gimei.last.kanji, first_name: Gimei.first.hiragana, last_name_kana: Gimei.last.katakana, first_name_kana: Gimei.first.katakana, birth_day: "20190415" } } get :index end it 'assigns @user' do expect(assigns(:user)).to be_a_new(User) end it 'renders the :index template' do expect(response).to render_template :index end end end end
class RemoveRepeatFromOccurrences < ActiveRecord::Migration def self.up remove_column :occurrences, :repeat end def self.down add_column :occurrences, :repeat, :boolean end end
$LOAD_PATH.unshift File.join(__dir__, "..", "lib", "bogus_twitter_pictures_ingestor") $LOAD_PATH.unshift File.join(__dir__, "helpers") require "minitest/autorun" require "data_export_task" require "fake_data_exporter" # Test DataExportTask class TestDataExportTask < Minitest::Test def create_fake_data_exporter FakeDataExporter.new end def test_data_export_task texts = [".@a It's fake"] username_text_pairs = [["a", ".@a It's fake"]] usernames = ["a"] fake_data_exporter = create_fake_data_exporter data_export_task = DataExportTask.new(texts, username_text_pairs, usernames, fake_data_exporter) data_export_task.run end end
class UsersController < ApiController helper ApplicationHelper def create @user = User.create_with(user_params).find_or_create_by(email: user_params[:email]) render json: @user.to_json(root:true, methods: [:gravatar_url]) end def interaction from_user = User.find_by_email(params[:from_email_id]) to_user = User.find_by_email(params[:to_email_id]) @user_interaction = UserInteraction.create(from_user: from_user, to_user: to_user, interaction_type: params[:interaction_type]) if @user_interaction render json: @user_interaction, status: :created end end def leaderboard month = params[:month] if month.blank? render json: {error: "Month parameter should be sent"}, status: :unprocessable_entity else start_of_month = Time.parse(month).beginning_of_month end_of_month = Time.parse(month).end_of_month @user = User.find_by_email(params[:email]) @entries = Entry.where('date >= ? AND date <= ?', start_of_month, end_of_month) .select("sum(duration) as total_duration, sum(amount_contributed) as total_amount_contributed, count(*) as total_days, users.id as user_id") .joins(:user).group("users.id").order("SUM(amount_contributed) desc") user_ids_with_entries = @entries.map {|entry| entry.user.id} @users_without_entries = User.from_multunus.where("id NOT in (?)", user_ids_with_entries) end end def monthly_summary month = params[:month] @user = User.find_by email: params[:email] if @user if month.blank? @entries = @user.entries.current_month else @entries = @user.entries.during_month(month) end else render json: { error: "User not found" }, status: :not_found end end def timeline_feed @user = User.find_by email: params[:email] if @user @timeline_activities = Activity.by_workout_type.for_user(@user).limit(100) else render json: { error: "User not found" }, status: :not_found end end private def user_params params.require(:user).permit(:name,:email) end end