text
stringlengths
10
2.61M
module Chronic class Arrow BASE_UNITS = [ :years, :months, :days, :hours, :minutes, :seconds ] UNITS = BASE_UNITS + [ :miliseconds, :mornings, :noons, :afternoons, :evenings, :nights, :midnights, :weeks, :weekdays, :wdays, :weekends, :fortnights, :quarters, :seasons ] PRECISION = [ :miliseconds, :seconds, :minutes, :noons, :midnights, :hours, :mornings, :afternoons, :evenings, :nights, :days, :weekdays, :weekends, :wdays, :weeks, :fortnights, :months, :quarters, :seasons, :years ] attr_reader :begin attr_reader :end UNITS.each { |u| attr_reader u } attr_reader :pointer attr_reader :order def initialize(arrows, options) @options = options @ordered = [] build(arrows) end def range @begin..@end end def width @end - @begin end def overlap?(r2) r1 = range (r1.begin <= r2.end) and (r2.begin <= r1.end) end def translate_unit(unit) unit.to_s + 's' end def to_span(span, timezone = nil) precision = PRECISION.length - 1 ds = Date::split(span.begin) ds += Time::split(span.begin) case span.precision when :year precision = PRECISION.index(:years) ds[3] = ds[4] = ds[5] = 0 when :month precision = PRECISION.index(:months) ds[3] = ds[4] = ds[5] = 0 when :day, :day_special precision = PRECISION.index(:days) ds[3] = ds[4] = ds[5] = 0 when :hour precision = PRECISION.index(:hours) when :minute precision = PRECISION.index(:minutes) when :second precision = PRECISION.index(:seconds) when :time_special precision = 0 end sign = (@pointer == :past) ? -1 : 1 @ordered.each do |data| unit = data.first count = data[1] special = data.last case unit when *BASE_UNITS ds[BASE_UNITS.index(unit)] += sign * count ds[2], ds[3], ds[4], ds[5] = Time::normalize(ds[2], ds[3], ds[4], ds[5]) ds[0], ds[1], ds[2] = Date::normalize(ds[0], ds[1], ds[2]) precision = update_precision(precision, unit) when :seasons # TODO raise "Not Implemented Arrow #{unit}" when :quarters ds[0], quarter = Date::add_quarter(ds[0], Date::get_quarter_index(ds[1]), sign * count) ds[1] = Date::QUARTERS[quarter] ds[2] = 1 ds[3], ds[4], ds[5] = 0, 0, 0 precision = PRECISION.index(unit) when :fortnights ds[0], ds[1], ds[2] = Date::add_day(ds[0], ds[1], ds[2], sign * count * Date::FORTNIGHT_DAYS) precision = update_precision(precision, unit) when :weeks ds[0], ds[1], ds[2] = Date::add_day(ds[0], ds[1], ds[2], sign * count * Date::WEEK_DAYS) precision = update_precision(precision, unit) when :wdays date = Chronic.time_class.new(ds[0], ds[1], ds[2]) diff = Date::wday_diff(date, special, sign) ds[0], ds[1], ds[2] = Date::add_day(ds[0], ds[1], ds[2], diff + sign * (count - 1) * Date::WEEK_DAYS) precision = update_precision(precision, unit) when :weekends date = Chronic.time_class.new(ds[0], ds[1], ds[2]) diff = Date::wday_diff(date, Date::DAYS[:saturday], sign) ds[0], ds[1], ds[2] = Date::add_day(ds[0], ds[1], ds[2], diff + sign * (count - 1) * Date::WEEK_DAYS) ds[3], ds[4], ds[5] = 0, 0, 0 precision = update_precision(precision, unit) when :weekdays # TODO raise "Not Implemented Arrow #{unit}" when :days # TODO raise "Not Implemented Arrow #{unit}" when :mornings, :noons, :afternoons, :evenings, :nights, :midnights name = n(unit) count -= 1 if @pointer == :past and ds[3] > Time::SPECIAL[name].end count += 1 if @pointer == :future and ds[3] < Time::SPECIAL[name].begin ds[0], ds[1], ds[2] = Date::add_day(ds[0], ds[1], ds[2], sign * count) ds[3], ds[4], ds[5] = Time::SPECIAL[name].begin, 0, 0 precision = PRECISION.index(unit) when :miliseconds # TODO raise "Not Implemented Arrow #{unit}" end end de = ds.dup case PRECISION[precision] when :miliseconds de[4], de[5] = Time::add_second(ds[4], ds[5], 0.001) when :seconds de[4], de[5] = Time::add_second(ds[4], ds[5]) when :minutes de[3], de[4] = Time::add_minute(ds[3], ds[4]) de[5] = 0 when :mornings, :noons, :afternoons, :evenings, :nights, :midnights name = n(PRECISION[precision]) de[3], de[4], de[5] = Time::SPECIAL[name].end, 0, 0 when :hours de[2], de[3] = Time::add_hour(ds[2], ds[3]) de[4] = de[5] = 0 when :days, :weekdays, :wdays de[0], de[1], de[2] = Date::add_day(ds[0], ds[1], ds[2]) de[3] = de[4] = de[5] = 0 when :weekends end_date = Chronic.time_class.new(ds[0], ds[1], ds[2]) diff = Date::wday_diff(end_date, Date::DAYS[:monday]) de[0], de[1], de[2] = Date::add_day(ds[0], ds[1], ds[2], diff) de[3] = de[4] = de[5] = 0 when :weeks end_date = Chronic.time_class.new(ds[0], ds[1], ds[2]) diff = Date::wday_diff(end_date, Date::DAYS[@options[:week_start]]) de[0], de[1], de[2] = Date::add_day(ds[0], ds[1], ds[2], diff) de[3] = de[4] = de[5] = 0 when :fortnights end_date = Chronic.time_class.new(ds[0], ds[1], ds[2]) diff = Date::wday_diff(end_date, Date::DAYS[@options[:week_start]]) de[0], de[1], de[2] = Date::add_day(ds[0], ds[1], ds[2], diff + Date::WEEK_DAYS) de[3] = de[4] = de[5] = 0 when :months de[0], de[1] = Date::add_month(ds[0], ds[1]) de[2] = 1 de[3] = de[4] = de[5] = 0 when :quarters de[0], quarter = Date::add_quarter(ds[0], Date::get_quarter_index(ds[1])) de[1] = Date::QUARTERS[quarter] de[2] = 1 de[3] = de[4] = de[5] = 0 when :seasons # TODO raise "Not Implemented Arrow #{PRECISION[precision]}" when :years de[0] += 1 de[1] = de[2] = 1 de[3] = de[4] = de[5] = 0 end utc_offset = nil end_utc_offset = nil if timezone utc_offset = timezone.to_offset(ds[0], ds[1], ds[2], ds[3], ds[4], ds[5]) end_utc_offset = timezone.to_offset(de[0], de[1], de[2], de[3], de[4], de[5]) end span_start = Chronic.construct(ds[0], ds[1], ds[2], ds[3], ds[4], ds[5], utc_offset) span_end = Chronic.construct(de[0], de[1], de[2], de[3], de[4], de[5], utc_offset) Span.new(span_start, span_end) end def to_s full = [] UNITS.each do |unit| count = instance_variable_get('@'+unit.to_s) full << [unit, count].join(' ') unless count.nil? end unless full.empty? 'Arrow => ' + @pointer.inspect + ' ' + full.join(', ') else 'Arrow => empty' end end protected def n(unit) s = unit.to_s s.to_s[0, s.length - 1].to_sym end def v(v) '@'+v.to_s end def update_precision(precision, unit) new_precision = PRECISION.index(unit) precision = new_precision if new_precision < precision precision end def build(arrows) arrows.each do |arrow| @begin = arrow.begin if @begin.nil? or @begin > arrow.begin @end = arrow.end if @end.nil? or @end < arrow.end @pointer = arrow.pointer if @pointer.nil? and not arrow.pointer.nil? next if arrow.unit.nil? unit = translate_unit(arrow.unit) raise "Uknown unit #{unit.to_sym.inspect}" unless UNITS.include?(unit.to_sym) count = instance_variable_get(v(unit)) count ||= 0 @ordered << [unit.to_sym, arrow.count, arrow.special] instance_variable_set(v(unit), count+arrow.count) end end end end
class AlterBikeWheelToId < ActiveRecord::Migration def up add_column :bikes, :bike_wheel_size_id, :integer undetermined_id = BikeWheelSize.find_by_rdin("0") Bike.find_each do |bike| wheel_size = BikeWheelSize.find_by_rdin(bike['wheel_size'].to_s) if wheel_size.nil? wheel_size_id = undetermined_id else wheel_size_id = wheel_size.id end bike.update_attribute(:bike_wheel_size_id, wheel_size_id) end remove_column :bikes, :wheel_size end def down add_column :bikes, :wheel_size, :integer Bike.find_each do |bike| wheel_size = BikeWheelSize.find_by_id(bike['bike_wheel_size_id']) bike.update_attribute(:wheel_size, wheel_size["rdin"].to_i) end remove_column :bikes, :bike_wheel_size_id end end
RSpec.shared_examples "failed authentication" do it "redirects to /users/sign_in" do subject expect(response).to redirect_to("/users/sign_in") end end RSpec.shared_examples "failed routing" do it "raises a routing error" do expect { subject }.to raise_error(ActionController::RoutingError) end end
require 'test_helper' class Liquid::Drops::ApplicationPlanDropTest < ActiveSupport::TestCase context 'ApplicationPlanDrop' do setup do @plan = FactoryBot.create(:application_plan) 2.times { |u| FactoryBot.create(:usage_limit, :plan => @plan) } @drop = Liquid::Drops::ApplicationPlan.new(@plan) end should 'return id' do assert_equal @drop.id, @plan.id end should 'wrap usage_limits' do assert_equal 2, @drop.usage_limits.size assert @drop.usage_limits.all? { |d| d.class == Liquid::Drops::UsageLimit } end should 'wrap metrics' do assert_equal 1, @drop.metrics.size assert @drop.metrics.all? { |d| d.class == Liquid::Drops::Metric } end end end
class State < ActiveRecord::Base has_many :institutions belongs_to :region validates :name, :abbreviation, presence: true end
require "banxico/sie/version" require "banxico/sie/connection" require "banxico/sie/client" require "banxico/sie/endpoints" require "banxico/sie/usd_exchange_rate" require "banxico/sie/errors/base_error" require "banxico/sie/errors/network_error" module Banxico module SIE def self.config yield self end def self.version @version end def self.base_uri @base_uri end def self.base_uri=(base_uri) @base_uri = base_uri end def self.key @key end def self.key=(key) @key = key end end end
class RenameMcoIdOnMcos < ActiveRecord::Migration def change rename_column :mcos, :mco_id, :bwc_mco_id end end
module API module V1 class Properties < Grape::API include API::V1::Defaults helpers PropertyHelpers resource :properties, desc: 'Properties Endpoint' do desc 'Return the most Viewed Properties.' get '/most-viewed' do present Property.most_viewed, with: API::V1::Entities::Property end desc 'Return all Properties.' get '/' do present Property.all, with: API::V1::Entities::Property end desc 'Return the specified property if exists.' get ':id' do property = Property.find(params[:id]) property.visits.create!({visit_time: Time.current}) present property, with: API::V1::Entities::Property end desc 'Create Property.' do detail 'Create a new Property in the system. Note that your role must be broker or admin' end params do requires :name, type: String, allow_blank: false, desc: 'The name of the property' requires :property_type, type: Symbol, allow_blank: false, values: [:farm, :home, :apartment, :land, :studio], desc: 'The type of the property' requires :goal, type: Symbol, allow_blank: false, values: [:buy, :rent], desc: 'The goal of the property' requires :price, type: Float, allow_blank: false, desc: 'The price of the property' optional :description, type: String, desc: 'Description of the Property' use :property_info end post '/' do authorize Property, :create? current_user.properties.create!(filtered_params(params)) body {} end desc 'Update Property.' do detail 'Update an existing Property in the system. Note that your role must be an admin.' + 'If you are a broker, you can only edit your own inserted Properties' end params do optional :name, type: String, allow_blank: false, desc: 'The name of the property' optional :property_type, type: Symbol, allow_blank: false, values: [:farm, :home, :apartment, :land, :studio], desc: 'The type of the property' optional :goal, type: Symbol, allow_blank: false, values: [:buy, :rent], desc: 'The goal of the property' optional :price, type: Float, allow_blank: false, desc: 'The price of the property' optional :description, type: String, allow_blank: false, desc: 'Description of the Property' use :property_info at_least_one_of :name, :property_type, :goal, :price, :property_info_attributes, :description end put ':id' do property = Property.find(params[:id]) authorize property, :update? property.update!(filtered_params(params)) body false end desc 'Delete Property.' do detail 'Exclude an existing Property from the system. Note that your role must be Admin.' + 'If you are a Broker, you can only delete your own inserted Properties' end delete ':id' do property = Property.find(params[:id]) authorize property, :destroy? property.destroy! end end end end end
FactoryGirl.define do factory :problem do text { Faker::StarWars.quote } setup { Faker::StarWars.quote } function_name { Faker::Space.agency_abv } association :user, factory: :user association :language, factory: :language end end
class AddProcessedAtToPerson < ActiveRecord::Migration def change add_column :people, :processed_at, :datetime add_index :people, :processed_at end end
class Attachment < ActiveRecord::Base mount_uploader :file, FileUploader before_create do self.original_file = self.file.original_file end end
RSpec.describe Hcheck::Checks::Postgresql do include Hcheck::Checks::Postgresql describe '#status' do let(:test_config) do { host: 'PG_DB_HOST', dbname: 'PG_DBNAME', user: 'PG_DB_USER', password: 'PG_DB_PASSWORD' } end let(:pg_connection) { double('PG::Connection', close: true) } before do allow(PG::Connection).to receive(:new) { pg_connection } end subject { status(test_config) } it 'tries to make pg connection with supplied config' do expect(PG::Connection).to receive(:new).with(test_config) subject end context 'when hcheck is able to connect to postgres with supplied config' do it 'returns ok' do expect(subject).to eql 'ok' end end context 'when hcheck is not able to connect to postgres with supplied config' do before do allow(PG::Connection).to receive(:new).and_raise(PG::ConnectionBad) end it 'returns bad' do expect(subject).to eql 'bad' end end end end
class ClientsController < ApplicationController def new @client = Client.new end def create @client = Client.new(client_params) if verify_recaptcha(model: @client) && @client.valid? ClientMailer.new_client(@client).deliver unless client_params[:honey].present? redirect_to thank_you_path, notice: "Your message has been sent." else flash[:alert] = "An error occurred while delivering this message. All fields are required." render :new end end private def client_params params.require(:client).permit(:first_name, :last_name, :phone, :address, :email, :case_type, :content, :honey) end end
###################################################################### # Copyright (c) 2008-2014, Alliance for Sustainable Energy. # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ###################################################################### module BCL class ComponentMethods attr_accessor :config attr_accessor :parsed_measures_path attr_reader :session attr_reader :http attr_reader :logged_in def initialize @parsed_measures_path = './measures/parsed' @config = nil @session = nil @access_token = nil @http = nil @api_version = 2.0 @group_id = nil @logged_in = false load_config end def login(username = nil, secret = nil, url = nil, group_id = nil) # figure out what url to use if url.nil? url = @config[:server][:url] end # look for http vs. https if url.include? 'https' port = 443 else port = 80 end # strip out http(s) url = url.gsub('http://', '') url = url.gsub('https://', '') if username.nil? || secret.nil? # log in via cached credentials username = @config[:server][:user][:username] secret = @config[:server][:user][:secret] @group_id = group_id || @config[:server][:user][:group] puts "logging in using credentials in .bcl/config.yml: Connecting to #{url} on port #{port} as #{username} with group #{@group_id}" else @group_id = group_id || @config[:server][:user][:group] puts "logging in using credentials in function arguments: Connecting to #{url} on port #{port} as #{username} with group #{@group_id}" end if @group_id.nil? puts '[WARNING] You did not set a group ID in your config.yml file or pass in a group ID. You can retrieve your group ID from the node number of your group page (e.g., https://bcl.nrel.gov/node/32). Will continue, but you will not be able to upload content.' end @http = Net::HTTP.new(url, port) @http.verify_mode = OpenSSL::SSL::VERIFY_NONE if port == 443 @http.use_ssl = true end data = %({"username":"#{username}","secret":"#{secret}"}) login_path = '/api/user/loginsso.json' headers = { 'Content-Type' => 'application/json' } res = @http.post(login_path, data, headers) # for debugging: # res.each do |key, value| # puts "#{key}: #{value}" # end if res.code == '200' puts 'Login Successful' bnes = '' bni = '' junkout = res['set-cookie'].split(';') junkout.each do |line| if line =~ /BNES_SESS/ bnes = line.match(/(BNES_SESS.*)/)[0] end end junkout.each do |line| if line =~ /BNI/ bni = line.match(/(BNI.*)/)[0] end end # puts "DATA: #{data}" session_name = '' sessid = '' json = MultiJson.load(res.body) json.each do |key, val| if key == 'session_name' session_name = val elsif key == 'sessid' sessid = val end end @session = session_name + '=' + sessid + ';' + bni + ';' + bnes # get access token token_path = '/services/session/token' token_headers = { 'Content-Type' => 'application/json', 'Cookie' => @session } # puts "token_headers = #{token_headers.inspect}" access_token = @http.post(token_path, '', token_headers) if access_token.code == '200' @access_token = access_token.body else puts 'Unable to get access token; uploads will not work' puts "error code: #{access_token.code}" puts "error info: #{access_token.body}" end # puts "access_token = *#{@access_token}*" # puts "cookie = #{@session}" res else puts "error code: #{res.code}" puts "error info: #{res.body}" puts 'continuing as unauthenticated sessions (you can still search and download)' res end end # retrieve, parse, and save metadata for BCL measures def measure_metadata(search_term = nil, filter_term = nil, return_all_pages = false) # setup results directory unless File.exist?(@parsed_measures_path) FileUtils.mkdir_p(@parsed_measures_path) end puts "...storing parsed metadata in #{@parsed_measures_path}" # retrieve measures puts "retrieving measures that match search_term: #{search_term.nil? ? 'nil' : search_term} and filters: #{filter_term.nil? ? 'nil' : filter_term}" measures = [] retrieve_measures(search_term, filter_term, return_all_pages) do |m| begin r = parse_measure_metadata(m) measures << r if r rescue => e puts "[ERROR] Parsing measure #{e.message}:#{e.backtrace.join("\n")}" end end measures end # Read in an existing measure.rb file and extract the arguments. # TODO: deprecate the _measure_name. This is used in the openstudio analysis gem, so it has to be carefully removed or renamed def parse_measure_file(_measure_name, measure_filename) measure_hash = {} if File.exist? measure_filename # read in the measure file and extract some information measure_string = File.read(measure_filename) measure_hash[:classname] = measure_string.match(/class (.*) </)[1] measure_hash[:name] = measure_hash[:classname].to_underscore measure_hash[:display_name] = nil measure_hash[:display_name_titleized] = measure_hash[:name].titleize measure_hash[:display_name_from_measure] = nil if measure_string =~ /OpenStudio::Ruleset::WorkspaceUserScript/ measure_hash[:measure_type] = 'EnergyPlusMeasure' elsif measure_string =~ /OpenStudio::Ruleset::ModelUserScript/ measure_hash[:measure_type] = 'RubyMeasure' elsif measure_string =~ /OpenStudio::Ruleset::ReportingUserScript/ measure_hash[:measure_type] = 'ReportingMeasure' elsif measure_string =~ /OpenStudio::Ruleset::UtilityUserScript/ measure_hash[:measure_type] = 'UtilityUserScript' else fail "measure type is unknown with an inherited class in #{measure_filename}: #{measure_hash.inspect}" end # New versions of measures have name, description, and modeler description methods n = measure_string.scan(/def name(.*?)end/m).first if n n = n.first.strip n.gsub!('return', '') n.gsub!(/"|'/, '') n.strip! measure_hash[:display_name_from_measure] = n end # New versions of measures have name, description, and modeler description methods n = measure_string.scan(/def description(.*?)end/m).first if n n = n.first.strip n.gsub!('return', '') n.gsub!(/"|'/, '') n.strip! measure_hash[:description] = n end # New versions of measures have name, description, and modeler description methods n = measure_string.scan(/def modeler_description(.*?)end/m).first if n n = n.first.strip n.gsub!('return', '') n.gsub!(/"|'/, '') n.strip! measure_hash[:modeler_description] = n end measure_hash[:arguments] = [] args = measure_string.scan(/(.*).*=.*OpenStudio::Ruleset::OSArgument.*make(.*)Argument\((.*).*\)/) args.each do |arg| new_arg = {} new_arg[:name] = nil new_arg[:display_name] = nil new_arg[:variable_type] = nil new_arg[:local_variable] = nil new_arg[:units] = nil new_arg[:units_in_name] = nil new_arg[:local_variable] = arg[0].strip new_arg[:variable_type] = arg[1] arg_params = arg[2].split(',') new_arg[:name] = arg_params[0].gsub(/"|'/, '') next if new_arg[:name] == 'info_widget' choice_vector = arg_params[1] ? arg_params[1].strip : nil # try find the display name of the argument reg = /#{new_arg[:local_variable]}.setDisplayName\((.*)\)/ if measure_string =~ reg new_arg[:display_name] = measure_string.match(reg)[1] new_arg[:display_name].gsub!(/"|'/, '') if new_arg[:display_name] else new_arg[:display_name] = new_arg[:name] end p = parse_measure_name(new_arg[:display_name]) new_arg[:display_name] = p[0] new_arg[:units_in_name] = p[1] # try to get the units reg = /#{new_arg[:local_variable]}.setUnits\((.*)\)/ if measure_string =~ reg new_arg[:units] = measure_string.match(reg)[1] new_arg[:units].gsub!(/"|'/, '') if new_arg[:units] end if measure_string =~ /#{new_arg[:local_variable]}.setDefaultValue/ new_arg[:default_value] = measure_string.match(/#{new_arg[:local_variable]}.setDefaultValue\((.*)\)/)[1] else puts "[WARNING] #{measure_hash[:name]}:#{new_arg[:name]} has no default value... will continue" end case new_arg[:variable_type] when 'Choice' # Choices to appear to only be strings? # puts "Choice vector appears to be #{choice_vector}" new_arg[:default_value].gsub!(/"|'/, '') if new_arg[:default_value] # parse the choices from the measure # scan from where the "instance has been created to the measure" possible_choices = nil possible_choice_block = measure_string # .scan(/#{choice_vector}.*=(.*)#{new_arg[:local_variable]}.*=/mi) if possible_choice_block # puts "possible_choice_block is #{possible_choice_block}" possible_choices = possible_choice_block.scan(/#{choice_vector}.*<<.*(')(.*)(')/) possible_choices += possible_choice_block.scan(/#{choice_vector}.*<<.*(")(.*)(")/) end # puts "Possible choices are #{possible_choices}" if possible_choices.nil? || possible_choices.empty? new_arg[:choices] = [] else new_arg[:choices] = possible_choices.map { |c| c[1] } end # if the choices are inherited from the model, then need to just display the default value which # somehow magically works because that is the display name if new_arg[:default_value] new_arg[:choices] << new_arg[:default_value] unless new_arg[:choices].include?(new_arg[:default_value]) end when 'String', 'Path' new_arg[:default_value].gsub!(/"|'/, '') if new_arg[:default_value] when 'Bool' if new_arg[:default_value] new_arg[:default_value] = new_arg[:default_value].downcase == 'true' ? true : false end when 'Integer' new_arg[:default_value] = new_arg[:default_value].to_i if new_arg[:default_value] when 'Double' new_arg[:default_value] = new_arg[:default_value].to_f if new_arg[:default_value] else fail "unknown variable type of #{new_arg[:variable_type]}" end measure_hash[:arguments] << new_arg end end # check if there is a measure.xml file? measure_xml_filename = "#{File.join(File.dirname(measure_filename), File.basename(measure_filename, '.*'))}.xml" if File.exist? measure_xml_filename f = File.open measure_xml_filename doc = Nokogiri::XML(f) # pull out some information measure_hash[:name_xml] = doc.xpath('/measure/name').first.content measure_hash[:uid] = doc.xpath('/measure/uid').first.content measure_hash[:version_id] = doc.xpath('/measure/version_id').first.content measure_hash[:tags] = doc.xpath('/measure/tags/tag').map(&:content) measure_hash[:modeler_description_xml] = doc.xpath('/measure/modeler_description').first.content measure_hash[:description_xml] = doc.xpath('/measure/description').first.content f.close end # validate the measure information validate_measure_hash(measure_hash) measure_hash end # Validate the measure hash to make sure that it is meets the style guide. This will also perform the selection # of which data to use for the "actual metadata" # # @param h [Hash] Measure hash def validate_measure_hash(h) if h.key? :name_xml if h[:name_xml] != h[:name] puts "[ERROR] {Validation}. Snake-cased name and the name in the XML do not match. Will default to automatic snake-cased measure name. #{h[:name_xml]} <> #{h[:name]}" end end puts '[WARNING] {Validation} Could not find measure description in measure.' unless h[:description] puts '[WARNING] {Validation} Could not find modeler description in measure.' unless h[:modeler_description] puts '[WARNING] {Validation} Could not find measure name method in measure.' unless h[:name_from_measure] # check the naming conventions if h[:display_name_from_measure] if h[:display_name_from_measure] != h[:display_name_titleized] puts '[WARNING] {Validation} Display name from measure and automated naming do not match. Will default to the automated name until all measures use the name method because of potential conflicts due to bad copy/pasting.' end h[:display_name] = h.delete :display_name_titleized else h[:display_name] = h.delete :display_name_titleized end h.delete :display_name_from_measure if h.key?(:description) && h.key?(:description_xml) if h[:description] != h[:description_xml] puts '[ERROR] {Validation} Measure description and XML description differ. Will default to description in measure' end h.delete(:description_xml) end if h.key?(:modeler_description) && h.key?(:modeler_description_xml) if h[:modeler_description] != h[:modeler_description_xml] puts '[ERROR] {Validation} Measure modeler description and XML modeler description differ. Will default to modeler description in measure' end h.delete(:modeler_description_xml) end h[:arguments].each do |arg| if arg[:units_in_name] puts "[ERROR] {Validation} It appears that units are embedded in the argument name for #{arg[:name]}." if arg[:units] if arg[:units] != arg[:units_in_name] puts '[ERROR] {Validation} Units in argument name do not match units in setUnits method. Using setUnits.' arg.delete :units_in_name end else puts '[ERROR] {Validation} Units appear to be in measure name. Please use setUnits.' arg[:units] = arg.delete :units_in_name end else # make sure to delete if null arg.delete :units_in_name end end end def translate_measure_hash_to_csv(measure_hash) csv = [] csv << [false, measure_hash[:display_name], measure_hash[:classname], measure_hash[:classname], measure_hash[:measure_type]] measure_hash[:arguments].each do |argument| values = [] values << '' values << 'argument' values << '' values << argument[:display_name] values << argument[:name] values << argument[:display_name] # this is the default short display name values << argument[:variable_type] values << argument[:units] # watch out because :default_value can be a boolean argument[:default_value].nil? ? values << '' : values << argument[:default_value] choices = '' if argument[:choices] choices << "|#{argument[:choices].join(',')}|" unless argument[:choices].empty? end values << choices csv << values end csv end # Read the measure's information to pull out the metadata and to move into a more friendly directory name. # argument of measure is a hash def parse_measure_metadata(measure) m_result = nil # check for valid measure if measure[:measure][:name] && measure[:measure][:uuid] file_data = download_component(measure[:measure][:uuid]) if file_data save_file = File.expand_path("#{@parsed_measures_path}/#{measure[:measure][:name].downcase.gsub(' ', '_')}.zip") File.open(save_file, 'wb') { |f| f << file_data } # unzip file and delete zip. # TODO: check that something was downloaded here before extracting zip if File.exist? save_file BCL.extract_zip(save_file, @parsed_measures_path, true) # catch a weird case where there is an extra space in an unzip file structure but not in the measure.name if measure[:measure][:name] == 'Add Daylight Sensor at Center of Spaces with a Specified Space Type Assigned' unless File.exist? "#{@parsed_measures_path}/#{measure[:measure][:name]}" temp_dir_name = "#{@parsed_measures_path}/Add Daylight Sensor at Center of Spaces with a Specified Space Type Assigned" FileUtils.move(temp_dir_name, "#{@parsed_measures_path}/#{measure[:measure][:name]}") end end temp_dir_name = File.join(@parsed_measures_path, measure[:measure][:name]) # Read the measure.rb file # puts "save dir name #{temp_dir_name}" measure_filename = "#{temp_dir_name}/measure.rb" measure_hash = parse_measure_file(nil, measure_filename) if measure_hash.empty? puts 'Measure Hash was empty... moving on' else # puts measure_hash.inspect m_result = measure_hash # move the directory to the class name new_dir_name = File.join(@parsed_measures_path, measure_hash[:classname]) # puts "Moving #{temp_dir_name} to #{new_dir_name}" if temp_dir_name == new_dir_name puts 'Destination directory is the same as the processed directory' else FileUtils.rm_rf(new_dir_name) if File.exist?(new_dir_name) && temp_dir_name != measure_hash[:classname] FileUtils.move(temp_dir_name, new_dir_name) unless temp_dir_name == measure_hash[:classname] end # create a new measure.json file for parsing later if need be File.open(File.join(new_dir_name, 'measure.json'), 'w') { |f| f << MultiJson.dump(measure_hash, pretty: true) } end else puts "Problems downloading #{measure[:measure][:name]}... moving on" end end end m_result end # parse measure name def parse_measure_name(name) # TODO: save/display errors errors = '' m = nil clean_name = name units = nil # remove everything btw parentheses m = clean_name.match(/\((.+?)\)/) unless m.nil? errors += ' removing parentheses,' units = m[1] clean_name = clean_name.gsub(/\((.+?)\)/, '') end # remove everything btw brackets m = nil m = clean_name.match(/\[(.+?)\]/) unless m.nil? errors += ' removing brackets,' clean_name = clean_name.gsub(/\[(.+?)\]/, '') end # remove characters m = nil m = clean_name.match(/(\?|\.|\#).+?/) unless m.nil? errors += ' removing any of following: ?.#' clean_name = clean_name.gsub(/(\?|\.|\#).+?/, '') end clean_name = clean_name.gsub('.', '') clean_name = clean_name.gsub('?', '') [clean_name.strip, units] end # retrieve measures for parsing metadata. # specify a search term to narrow down search or leave nil to retrieve all # set all_pages to true to iterate over all pages of results # can't specify filters other than the hard-coded bundle and show_rows def retrieve_measures(search_term = nil, filter_term = nil, return_all_pages = false, &_block) # raise "Please login before performing this action" if @session.nil? # make sure filter_term includes bundle if filter_term.nil? filter_term = 'fq[]=bundle%3Anrel_measure' elsif !filter_term.include? 'bundle' filter_term += '&fq[]=bundle%3Anrel_measure' end # use provided search term or nil. # if return_all_pages is true, iterate over pages of API results. Otherwise only return first 100 results = search(search_term, filter_term, return_all_pages) puts "#{results[:result].count} results returned" results[:result].each do |result| puts "retrieving measure: #{result[:measure][:name]}" yield result end end # evaluate the response from the API in a consistent manner def evaluate_api_response(api_response) valid = false result = { error: 'could not get json from http post response' } case api_response.code when '200' puts " Response Code: #{api_response.code} - #{api_response.body}" if api_response.body.empty? puts ' 200 BUT ERROR: Returned body was empty. Possible causes:' puts ' - BSD tar on Mac OSX vs gnutar' result = { error: 'returned 200, but returned body was empty' } valid = false else puts ' 200 - Successful Upload' result = MultiJson.load api_response.body valid = true end when '404' puts " Response: #{api_response.code} - #{api_response.body}" puts ' 404 - check these common causes first:' puts ' - the filename contains periods (other than the ones before the file extension)' puts " - you are not an 'administrator member' of the group you're trying to upload to" result = MultiJson.load api_response.body valid = false when '406' puts " Response: #{api_response.code} - #{api_response.body}" puts ' 406 - check these common causes first:' puts ' - the UUID of the item that you are uploading is already on the BCL' puts ' - the group_id is not correct in the config.yml (go to group on site, and copy the number at the end of the URL)' puts " - you are not an 'administrator member' of the group you're trying to upload to" result = MultiJson.load api_response.body valid = false when '500' puts " Response: #{api_response.code} - #{api_response.body}" fail 'server exception' valid = false else puts " Response: #{api_response.code} - #{api_response.body}" valid = false end [valid, result] end # Construct the post parameter for the API content.json end point. # param(@update) is a boolean that triggers whether to use content_type or uuid def construct_post_data(filepath, update, content_type_or_uuid) # TODO: remove special characters in the filename; they create firewall errors # filename = filename.gsub(/\W/,'_').gsub(/___/,'_').gsub(/__/,'_').chomp('_').strip file_b64 = Base64.encode64(File.binread(filepath)) data = {} data['file'] = { 'file' => file_b64, 'filesize' => File.size(filepath).to_s, 'filename' => File.basename(filepath) } data['node'] = {} # Only include the content type if this is an update if update data['node']['uuid'] = content_type_or_uuid else data['node']['type'] = content_type_or_uuid end # TODO: remove this field_component_tags once BCL is fixed data['node']['field_component_tags'] = { 'und' => '1289' } data['node']['og_group_ref'] = { 'und' => ['target_id' => @group_id] } # NOTE THIS ONLY WORKS IF YOU ARE A BCL SITE ADMIN data['node']['publish'] = '1' data end # pushes component to the bcl and publishes them (if logged-in as BCL Website Admin user). # username, secret, and group_id are set in the ~/.bcl/config.yml file def push_content(filename_and_path, write_receipt_file, content_type) fail 'Please login before pushing components' if @session.nil? fail 'Do not have a valid access token; try again' if @access_token.nil? data = construct_post_data(filename_and_path, false, content_type) path = '/api/content.json' headers = { 'Content-Type' => 'application/json', 'X-CSRF-Token' => @access_token, 'Cookie' => @session } res = @http.post(path, MultiJson.dump(data), headers) valid, json = evaluate_api_response(res) if valid # write out a receipt file into the same directory of the component with the same file name as # the component if write_receipt_file File.open("#{File.dirname(filename_and_path)}/#{File.basename(filename_and_path, '.tar.gz')}.receipt", 'w') do |file| file << Time.now.to_s end end end [valid, json] end # pushes updated content to the bcl and publishes it (if logged-in as BCL Website Admin user). # username and secret set in ~/.bcl/config.yml file def update_content(filename_and_path, write_receipt_file, uuid = nil) fail 'Please login before pushing components' unless @session # get the UUID if zip or xml file version_id = nil if uuid.nil? puts File.extname(filename_and_path).downcase if filename_and_path =~ /^.*.tar.gz$/i uuid, version_id = uuid_vid_from_tarball(filename_and_path) puts "Parsed uuid out of tar.gz file with value #{uuid}" end else # verify the uuid via regex unless uuid =~ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ fail "uuid of #{uuid} is invalid" end end fail 'Please pass in a tar.gz file or pass in the uuid' unless uuid data = construct_post_data(filename_and_path, true, uuid) path = '/api/content.json' headers = { 'Content-Type' => 'application/json', 'X-CSRF-Token' => @access_token, 'Cookie' => @session } res = @http.post(path, MultiJson.dump(data), headers) valid, json = evaluate_api_response(res) if valid # write out a receipt file into the same directory of the component with the same file name as # the component if write_receipt_file File.open("#{File.dirname(filename_and_path)}/#{File.basename(filename_and_path, '.tar.gz')}.receipt", 'w') do |file| file << Time.now.to_s end end end [valid, json] end def push_contents(array_of_components, skip_files_with_receipts, content_type) logs = [] array_of_components.each do |comp| receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt' log_message = '' if skip_files_with_receipts && File.exist?(receipt_file) log_message = "skipping because found receipt #{comp}" puts log_message else log_message = "pushing content #{File.basename(comp, '.tar.gz')}" puts log_message valid, res = push_content(comp, true, content_type) log_message += " #{valid} #{res.inspect.chomp}" end logs << log_message end logs end # Unpack the tarball in memory and extract the XML file to read the UUID and Version ID def uuid_vid_from_tarball(path_to_tarball) uuid = nil vid = nil fail "File does not exist #{path_to_tarball}" unless File.exist? path_to_tarball tgz = Zlib::GzipReader.open(path_to_tarball) Archive::Tar::Minitar::Reader.open(tgz).each do |entry| # If taring with tar zcf ameasure.tar.gz -C measure_dir . if entry.name =~ /^.{0,2}component.xml$/ || entry.name =~ /^.{0,2}measure.xml$/ xml_file = Nokogiri::XML(entry.read) # pull out some information if entry.name =~ /component/ u = xml_file.xpath('/component/uid').first v = xml_file.xpath('/component/version_id').first else u = xml_file.xpath('/measure/uid').first v = xml_file.xpath('/measure/version_id').first end fail "Could not find UUID in XML file #{path_to_tarball}" unless u # Don't error on version not existing. uuid = u.content vid = v ? v.content : nil # puts "uuid = #{uuid}; vid = #{vid}" end end [uuid, vid] end def update_contents(array_of_tarball_components, skip_files_with_receipts) logs = [] array_of_tarball_components.each do |comp| receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt' log_message = '' if skip_files_with_receipts && File.exist?(receipt_file) log_message = "skipping update because found receipt #{File.basename(comp)}" puts log_message else uuid, vid = uuid_vid_from_tarball(comp) if uuid.nil? log_message = "ERROR: uuid not found for #{File.basename(comp)}" puts log_message else log_message = "pushing updated content #{File.basename(comp)}" puts log_message valid, res = update_content(comp, true, uuid) log_message += " #{valid} #{res.inspect.chomp}" end end logs << log_message end logs end # Simple method to search bcl and return the result as hash with symbols # If all = true, iterate over pages of results and return all # JSON ONLY def search(search_str = nil, filter_str = nil, all = false) full_url = '/api/search/' # add search term if !search_str.nil? && search_str != '' full_url += search_str # strip out xml in case it's included. make sure .json is included full_url = full_url.gsub('.xml', '') unless search_str.include? '.json' full_url += '.json' end else full_url += '*.json' end # add api_version if @api_version < 2.0 puts "WARNING: attempting to use search with api_version #{@api_version}. Use API v2.0 for this functionality." end full_url += "?api_version=#{@api_version}" # add filters unless filter_str.nil? # strip out api_version from filters, if included if filter_str.include? 'api_version=' filter_str = filter_str.gsub(/api_version=\d{1,}/, '') filter_str = filter_str.gsub(/&api_version=\d{1,}/, '') end full_url = full_url + '&' + filter_str end # simple search vs. all results if !all puts "search url: #{full_url}" res = @http.get(full_url) # return unparsed MultiJson.load(res.body, symbolize_keys: true) else # iterate over result pages # modify filter_str for show_rows=200 for maximum returns if filter_str.include? 'show_rows=' full_url = full_url.gsub(/show_rows=\d{1,}/, 'show_rows=200') else full_url += '&show_rows=200' end # make sure filter_str doesn't already have a page=x full_url.gsub(/page=\d{1,}/, '') pagecnt = 0 continue = 1 results = [] while continue == 1 # retrieve current page full_url_all = full_url + "&page=#{pagecnt}" puts "search url: #{full_url_all}" response = @http.get(full_url_all) # parse here so you can build results array res = MultiJson.load(response.body) if res['result'].count > 0 pagecnt += 1 res['result'].each do |r| results << r end else continue = 0 end end # return unparsed b/c that is what is expected formatted_results = { 'result' => results } results_to_return = MultiJson.load(MultiJson.dump(formatted_results), symbolize_keys: true) end end # Delete receipt files def delete_receipts(array_of_components) array_of_components.each do |comp| receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt' if File.exist?(receipt_file) FileUtils.remove_file(receipt_file) end end end def list_all_measures json = search(nil, 'fq[]=bundle%3Anrel_measure&show_rows=100') json end def download_component(uid) result = @http.get("/api/component/download?uids=#{uid}") puts "Downloading: http://#{@http.address}/api/component/download?uids=#{uid}" # puts "RESULTS: #{result.inspect}" # puts "RESULTS BODY: #{result.body}" # look at response code if result.code == '200' # puts 'Download Successful' result.body ? result.body : nil else puts "Download fail. Error code #{result.code}" nil end rescue puts "Couldn't download uid(s): #{uid}...skipping" nil end private def load_config config_filename = File.expand_path('~/.bcl/config.yml') if File.exist?(config_filename) puts "loading config settings from #{config_filename}" @config = YAML.load_file(config_filename) else # location of template file FileUtils.mkdir_p(File.dirname(config_filename)) File.open(config_filename, 'w') { |f| f << default_yaml.to_yaml } File.chmod(0600, config_filename) puts "******** Please fill in user credentials in #{config_filename} file if you need to upload data **********" end end def default_yaml settings = { server: { url: 'https://bcl.nrel.gov', user: { username: 'ENTER_BCL_USERNAME', secret: 'ENTER_BCL_SECRET', group: 'ENTER_GROUP_ID' } } } settings end end # class ComponentMethods # TODO: make this extend the component_xml class (or create a super class around components) def self.gather_components(component_dir, chunk_size = 0, delete_previousgather = false, destination = nil) if destination.nil? @dest_filename = 'components' else @dest_filename = destination end @dest_file_ext = 'tar.gz' # store the starting directory current_dir = Dir.pwd # an array to hold reporting info about the batches gather_components_report = [] # go to the directory containing the components Dir.chdir(component_dir) # delete any old versions of the component chunks FileUtils.rm_rf('./gather') if delete_previousgather # gather all the components into array targzs = Pathname.glob('./**/*.tar.gz') tar_cnt = 0 chunk_cnt = 0 targzs.each do |targz| if chunk_size != 0 && (tar_cnt % chunk_size) == 0 chunk_cnt += 1 end tar_cnt += 1 destination_path = "./gather/#{chunk_cnt}" FileUtils.mkdir_p(destination_path) destination_file = "#{destination_path}/#{File.basename(targz.to_s)}" # puts "copying #{targz.to_s} to #{destination_file}" FileUtils.cp(targz.to_s, destination_file) end # gather all the .tar.gz files into a single tar.gz (1..chunk_cnt).each do |cnt| currentdir = Dir.pwd paths = [] Pathname.glob("./gather/#{cnt}/*.tar.gz").each do |pt| paths << File.basename(pt.to_s) end Dir.chdir("./gather/#{cnt}") destination = "#{@dest_filename}_#{cnt}.#{@dest_file_ext}" puts "tarring batch #{cnt} of #{chunk_cnt} to #{@dest_filename}_#{cnt}.#{@dest_file_ext}" BCL.tarball(destination, paths) Dir.chdir(currentdir) # move the tarball back a directory FileUtils.move("./gather/#{cnt}/#{destination}", "./gather/#{destination}") end Dir.chdir(current_dir) end end # module BCL
class Brand < ActiveRecord::Base has_many :models def device_count models.collect{ |m| m.device_count }.sum end end
=begin Write a method that can rotate the last n digits of a number. For example: =end def rotate_array(ary) new_ary = ary.dup first_item = new_ary.shift new_ary.push(first_item) new_ary end # Option A: def rotate_rightmost_digits(num, n_last_digits) return num if n_last_digits <= 1 ary_of_digits = num.digits.reverse sub_ary_for_rotation = ary_of_digits.slice!(-n_last_digits..-1) result = ary_of_digits << rotate_array(sub_ary_for_rotation) result.flatten.join.to_i end # Option B: def rotate_rightmost_digits(number, n) all_digits = number.to_s.chars all_digits[-n..-1] = rotate_array(all_digits[-n..-1]) all_digits.join.to_i end puts rotate_rightmost_digits(735291, 1) == 735291 puts rotate_rightmost_digits(735291, 2) == 735219 puts rotate_rightmost_digits(735291, 3) == 735912 puts rotate_rightmost_digits(735291, 4) == 732915 puts rotate_rightmost_digits(735291, 5) == 752913 puts rotate_rightmost_digits(735291, 6) == 352917
class Evil::Client::Middleware class MergeSecurity < Base private def build(env) env.dup.tap do |hash| security = hash.delete(:security).to_h %i(headers body query).each do |key| next unless security[key] hash[key] ||= {} hash[key].update security[key] end end end end end
module DateOutput module ViewHelpers def full_date_with_time(date,options={}) DateOutput.full_date_with_time(date,options) end def short_date_with_time(date,options={}) DateOutput.short_date_with_time(date,options) end def numbered_date_with_time(date,options={}) DateOutput.numbered_date_with_time(date,options) end def numbered_date(date,options={}) DateOutput.numbered_date(date,options) end def full_date(date,options={}) DateOutput.full_date(date,options) end def short_date(date,options={}) DateOutput.short_date(date,options) end def long_date_no_day(date, options={}) DateOutput.long_date_no_day(date, options) end def short_date_no_day(date, options={}) DateOutput.short_date_no_day(date, options) end def long_date_no_day_with_time(date, options={}) DateOutput.long_date_no_day_with_time(date, options) end def short_date_no_day_with_time(date, options={}) DateOutput.short_date_no_day_with_time(date, options) end end end
require 'nokogiri' require 'open-uri' class GetSnapcodeImageFromExternalApi FetchingFailed = Class.new(StandardError) def call(snapchat_username) image = Nokogiri::XML(open(api_url_for_image(snapchat_username))) image.to_html rescue OpenURI::HTTPError raise FetchingFailed end private def api_url_for_image(username) "https://feelinsonice-hrd.appspot.com/web/deeplink/snapcode?username=#{username}&type=SVG" end end
#encoding: utf-8 module UsersHelper def change_account_display_or_not code = <<-ACCOUNTFIELD $(function(){ $('#isappuser').click(function() { if($('#isappuser').is(":checked")) { $('#account_field').attr("class", "control-group"); } else { $('#account_field').attr("class", "control-group hidden"); } }); }); ACCOUNTFIELD javascript_tag code end def user_dynatree(args) code = <<-DHTMLXTREE var tree = new dhtmlXTreeObject("#{args[:tree_id]}", "100%", "100%", 0); tree.setImagePath("/assets/dhtmlxtree/imgs/csh_dhx_skyblue/"); var jsonObject = #{Department.to_dhtmlxtree_node.to_json} tree.loadJSONObject(jsonObject); tree.attachEvent("onClick", function(itemId) { $('#_iframe').attr("src", "/departments/"+itemId+"/users"); return true; }); DHTMLXTREE javascript_tag(code) end def contactway(user) if user.mobile.empty? user.officephone else user.mobile end end def human_sex(user) if user.sex == 1 '男' else '女' end end def is_appuser(user) if user.isappuser? "是" else "否" end end end
class RecreateInventories < ActiveRecord::Migration def change create_table :inventories do |t| t.integer :order_line_id t.timestamps end end end
class ProductsController < ApplicationController def who_bought @product = Product.find(params[:id]) respond_to do |format| format.atom end end def index @products = Product.all end def new @product = Product.new end def create @product = Product.new(product_params) if @product.save flash[:success] = 'Продукт создан' redirect_to @product else render 'new' end end def show @product = Product.find(params[:id]) end def edit @product = Product.find(params[:id]) end def update @product = Product.find(params[:id]) if @product.update_attributes(product_params) flash[:success] = 'Изменения сохранены' redirect_to root_path else render 'edit' end end def destroy Product.find(params[:id]).destroy flash[:success] = 'Продукт удален' redirect_to root_path end private def product_params params.require(:product).permit(:name, :description, :image_url, :price) end end
class CreateOrganizationProfileViews < ActiveRecord::Migration def self.up create_table :organization_profile_views, :id => false do |t| t.integer :viewer_id t.integer :organization_id t.datetime :created_at end end def self.down drop_table :organization_profile_views end end
require 'rails_helper' RSpec.describe Path do subject { described_class.new } it { is_expected.to have_many(:users) } it { is_expected.to have_many(:path_courses).order(:position) } it { is_expected.to have_many(:courses).through(:path_courses) } it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_presence_of(:description) } it { is_expected.to validate_presence_of(:position) } end
class ArtistTagsController < ApplicationController before_action :set_artist def new @artist_tag = ArtistTag.new end def create names = params[:artist_tag][:tag].reject(&:empty?).map(&:downcase) names.each do |name| tag = Tag.find_or_create_by(name: name) ArtistTag.create(artist: @artist, tag: tag) end redirect_to @artist end private def set_artist @artist = Artist.find(params[:artist_id]) end end
class NotAffectingInvestment NOT_AFFECTING_INVESTMENT = { 'f[]' => 'issue.cf_20', 'op[issue.cf_20]' => '!', 'v[issue.cf_20][]' => 0 }.freeze def array_queries NOT_AFFECTING_INVESTMENT.map { |key, value| [key, value] } end def hash_queries NOT_AFFECTING_INVESTMENT end end
#!/usr/bin/env ruby require "rubygems" require 'sdl' require_relative 'board.rb' class Principal def initialize SDL.init SDL::INIT_VIDEO @screen = SDL.set_video_mode 806, 604, 0, 0 @tabuleiro = SDL::Surface.load "Tabuleiro.png" @peca = SDL::Surface.load "Bloco.png" @peca2 = SDL::Surface.load "Bloco2.png" #Coloca o desenho do tabuleiro na tela: SDL.blit_surface @tabuleiro, 0, 0, 0, 0, @screen, 0, 0 #Cria um tabuleiro: @board = Board.new done = false while not done ticks = SDL.get_ticks while event = SDL::Event2.poll case event when SDL::Event2::Quit done = true when SDL::Event2::KeyDown case event.sym when SDL::Key::LEFT @board.esquerda when SDL::Key::RIGHT @board.direita when SDL::Key::DOWN @board.mais_rapido true when SDL::Key::UP @board.rotacionar when SDL::Key::Q done = true end when SDL::Event2::KeyUp @board.mais_rapido(false) if event.sym == SDL::Key::DOWN end end desenha tempo = SDL.get_ticks - ticks SDL.delay 60 - tempo if tempo < 60 end SDL.quit end def desenha SDL.blit_surface @tabuleiro, 258, 0, 299, 604, @screen, 258, 0 SDL.blit_surface @tabuleiro, 605, 86, 120, 120, @screen, 605,85 #Desenha o tabuleiro 10.times do |x| 20.times do |y| SDL.blit_surface @peca2, 0,0,0,0, @screen, x*30+258,y*30+3 if @board.tabuleiro[y][x] == 1 end end #Desenha peça caindo pecay = @board.peca.y.to_i @board.peca.matriz.length.times do |y| @board.peca.matriz[0].length.times do |x| if @board.peca.matriz[y][x] == 1 SDL.blit_surface @peca, 0,0,0,0, @screen, (x+@board.peca.x)*30+258,(y+pecay)*30+3 end end end #Desenha a próxima peça @board.next.matriz.length.times do |y| @board.next.matriz[0].length.times do |x| if @board.next.matriz[y][x] == 1 SDL.blit_surface @peca, 0,0,0,0, @screen, (x+2-@board.next.matriz[0].length / 2)*30+605, y*30+85 end end end @board.baixo @screen.flip end end Principal.new if $0 == __FILE__
class Recipe < ActiveRecord::Base has_many :recipe_ingredients has_many :ingredients, through: :recipe_ingredients validates_presence_of :name accepts_nested_attributes_for :ingredients, reject_if: lambda {|attributes| attributes['name'].blank?} def ingredients_attributes=(ingredients_attributes) ingredients_attributes.each do |i, ingredient_attributes| self.ingredients.build(ingredient_attributes) if ingredient_attributes.present? && ingredient_attributes[:name].present? end end end
def T_WHITESPACES(value) { type: 'T_WHITESPACES', value: value } end T_COMMA = { type: 'T_COMMA', value: ',' } T_COLON = { type: 'T_COLON', value: ':' } T_SEMICOLON = { type: 'T_SEMICOLON', value: ';' } T_OPEN_ROUND_BRACKET = { type: 'T_OPEN_ROUND_BRACKET', value: '(' } T_CLOSE_ROUND_BRACKET = { type: 'T_CLOSE_ROUND_BRACKET', value: ')' } T_OPEN_SQUARE_BRACKET = { type: 'T_OPEN_SQUARE_BRACKET', value: '[' } T_CLOSE_SQUARE_BRACKET = { type: 'T_CLOSE_SQUARE_BRACKET', value: ']' } T_OPEN_CURLY_BRACKET = { type: 'T_OPEN_CURLY_BRACKET', value: '{' } T_CLOSE_CURLY_BRACKET = { type: 'T_CLOSE_CURLY_BRACKET', value: '}' } T_OPEN_ANGLE_BRACKET = { type: 'T_OPEN_ANGLE_BRACKET', value: '<' } T_CLOSE_ANGLE_BRACKET = { type: 'T_CLOSE_ANGLE_BRACKET', value: '>' } T_QUOTED_EXPRESSION_OPEN = { type: 'T_QUOTED_EXPRESSION_OPEN', value: '\(' } T_QUOTED_EXPRESSION_CLOSE = { type: 'T_QUOTED_EXPRESSION_CLOSE', value: ')' } def T_UNICODE_CHAR(value) { type: 'T_UNICODE_CHAR', value: value } end T_QUOTED_UNICODE_CHAR_OPEN = { type: 'T_QUOTED_UNICODE_CHAR_OPEN', value: '\\u' + 123.chr } T_QUOTED_UNICODE_CHAR_CLOSE = { type: 'T_QUOTED_UNICODE_CHAR_CLOSE', value: 125.chr } T_FALSE = { type: 'T_FALSE', value: 'false' } T_TRUE = { type: 'T_TRUE', value: 'true' } T_WILDCARD = { type: 'T_WILDCARD', value: '_' } def T_LITERAL_INTEGER_DECIMAL(value) { type: 'T_LITERAL_INTEGER_DECIMAL', value: value } end def T_LITERAL_FLOATING_POINT_DECIMAL(value) { type: 'T_LITERAL_FLOATING_POINT_DECIMAL', value: value } end def T_LITERAL_FLOATING_POINT_HEXADECIMAL(value) { type: 'T_LITERAL_FLOATING_POINT_HEXADECIMAL', value: value } end def T_LITERAL_INTEGER_BINARY(value) { type: 'T_LITERAL_INTEGER_BINARY', value: value } end def T_LITERAL_INTEGER_HEXADECIMAL(value) { type: 'T_LITERAL_INTEGER_HEXADECIMAL', value: value } end def T_LITERAL_INTEGER_OCTAL(value) { type: 'T_LITERAL_INTEGER_OCTAL', value: value } end def T_LITERAL_STRING(value) { type: 'T_LITERAL_STRING', value: value } end def T_IDENTIFIER(value) { type: 'T_IDENTIFIER', value: value } end def T_OPERATOR(value) { type: 'T_OPERATOR', value: value } end T_VAR = { type: 'T_VAR', value: 'var' } T_LET = { type: 'T_LET', value: 'let' } T_FOR = { type: 'T_FOR', value: 'for' } T_IN = { type: 'T_IN', value: 'in' } T_DO = { type: 'T_DO', value: 'do' } T_WHILE = { type: 'T_WHILE', value: 'while' } T_IF = { type: 'T_IF', value: 'if' } T_ELSE = { type: 'T_ELSE', value: 'else' } T_STRUCT = { type: 'T_STRUCT', value: 'struct' } T_NIL = { type: 'T_NIL', value: 'nil' } T_SELF = { type: 'T_SELF', value: 'self' } T_SUPER = { type: 'T_SUPER', value: 'super' } T_DOUBLE_QUOTE = { type: 'T_DOUBLE_QUOTE', value: '"' } T_FUNCTION = { type: 'T_FUNCTION', value: 'func' } T_RETURN_TYPE_ARROW = { type: 'T_RETURN_TYPE_ARROW', value: '->' } T_PROTOCOL = { type: 'T_PROTOCOL', value: 'protocol' } T_GET = { type: 'T_GET', value: 'get' } T_SET = { type: 'T_SET', value: 'set' } T_INIT = { type: 'T_INIT', value: 'init' } T_TYPEALIAS = { type: 'T_TYPEALIAS', value: 'typealias' } T_UNOWNED = { type: 'T_UNOWNED', value: 'unowned' }
# # 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/>. # class TopoisController < ApplicationController before_filter :editor_required, :except => [:index, :show] before_filter :find_topos, :except => [:index, :new, :create] def create @topoi = Topoi.new(params[:topoi]) if params[:backtowork]=='topos' if @topoi.save log_change('create', 1, @topoi) flash[:notice] = 'Topos successfully created.' redirect_to :controller => 'works', :action => "edit", :id => params[:work_id] else render :action => "new" end else if @topoi.save log_change('create', 1, @topoi) flash[:notice]= 'Topos successfully created.' redirect_to :action => "index" else render :action => "new" end end end def destroy @topoi.destroy log_change('delete', 1, @topoi) redirect_to :action => "index" end def edit end def index if params[:page].to_i<1 then params[:page]=1 end if params[:per_page].to_i<1 then params[:per_page]=20 end if !params[:search_name] .nil? then searched_name = '%'+params[:search_name]+'%' else searched_name='%' end if params[:sort] .nil? then params[:sort]="upper(topois.topos)" end @pagin = Topoi.find(:all, :conditions => ["topois.topos iLIKE ?", searched_name,]) @help_paginate = @pagin.length if @help_paginate.to_i <= (params[:per_page].to_i * (params[:page].to_i - 1)) then params[:page] = 1 end @topois = Topoi.paginate :per_page => params[:per_page], :order => params[:sort], :page => params[:page], :conditions => ["topois.topos iLIKE ?", searched_name] @count=@topois.total_entries if request.xml_http_request? render :partial => "topoilist" end end def new @topoi = Topoi.new end def show end def update if @topoi.update_attributes(params[:topoi]) log_change('update', 1, @topoi) flash[:notice] = 'Topos successfully updated.' redirect_to :action => "show", :id => params[:id] else render :action => "edit" end end private def find_topos @topoi = Topoi.find(params[:id]) end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Operation::Indexes do require_no_required_api_version let(:context) { Mongo::Operation::Context.new } describe '#execute' do let(:index_spec) do { name: 1 } end before do authorized_collection.drop authorized_collection.insert_one(test: 1) authorized_collection.indexes.create_one(index_spec, unique: true) end after do authorized_collection.indexes.drop_one('name_1') end let(:operation) do described_class.new({ selector: { listIndexes: TEST_COLL }, coll_name: TEST_COLL, db_name: SpecConfig.instance.test_db }) end let(:indexes) do operation.execute(authorized_primary, context: context) end it 'returns the indexes for the collection' do expect(indexes.documents.size).to eq(2) end end end
class CreateDiscipleEquipments < ActiveRecord::Migration def change create_table :disciple_equipments, options: 'ENGINE=INNODB, CHARSET=UTF8' do |t| t.integer :disciple_id, default: -1 t.integer :equipment_id, default: -1 t.timestamps end end end
class User < ActiveRecord::Base validates :name, presence: true, length: { in: 1..10 }, uniqueness: true validates :password, presence: true, length: {minimum: 1, maximum: 6 } def self.login(name, password) find_by(name: name, password: password) end def try_login find_user = User.login(self.name, self.password) if find_user.nil? errors.add(:base,'invalid password or username') return false else self.id = find_user.id return true end end end
require 'aws/templates/utils' module Aws module Templates module Help module Rdoc module Parametrized module Constraints ## # Case-like constraint documentation provider # # Prints all handled value and respective constraints. class DependsOnValue < Parametrized::Constraint for_entity Templates::Utils::Parametrized::Constraint::DependsOnValue protected def add_description(item) item << text('depends on value:') item << _members end private def _members context.selector .lazy .map { |value, constraint| _constraint_variant_for(value, constraint) } .each_with_object(list) { |part, l| l << part } end def _constraint_variant_for(value, constraint) sub(text("when _#{value}_ :"), processed_for(constraint)) end end end end end end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :token_authenticatable, :invitable, :omniauthable, omniauth_providers: [:weibo, :qq_connect] # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :uid, :provider,:name,:admin,:avatar,:sign # attr_accessible :title, :body validates :email, uniqueness: true, presence: true, format: { with: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i } validates :name, uniqueness: true, presence: true,:length => { :maximum => 30 } end
# https://github.com/stormasm/sds-warden/blob/rediswarden/doc/redisapi.md # Tokens map to account and project # Accounts map to Dbs # You can have multiple projects in a DB, but not multiple accounts require 'json' require 'redis' require_relative './redisoptions' class RedisData def initialize @redisc ||= Redis.new :host => REDIS_OPTIONS['host'] end def build_hash_key(project,dimension,key,calculation,interval) "hash:" + project + ":" + dimension + ":" + key + ':' + calculation + ":" + interval end def get_data(db_number,project,dimension,key,calculation,interval) @redisc.select db_number hashkey = build_hash_key(project,dimension,key,calculation,interval) hmap = @redisc.hgetall(hashkey) end def get_json(db_number,project,dimension,key,calculation,interval) data = get_data(db_number,project,dimension,key,calculation,interval) json = JSON::generate(data) end end =begin rd = RedisData.new json = rd.get_json('100','2','job-skills','python','count','months') print json; puts =end
class Client < ApplicationRecord validates :name, :num_dogs, :dogs, presence: true has_many :bookings end
module CoinsExtensions refine Array do def can_return_coin?(change) raise 'change < 0' if change < 0 tmp = self.dup return {change_coins:[], rest_coins:tmp} if 0 == change if tmp.include? change tmp.delete_at(tmp.index(change)) return {change_coins:[change], rest_coins:tmp} end # おつりの金額を構成できるかをチェックする tmp.sort!.reverse! change_coins = [] cur_price = change loop do tgt_price = tmp.find{|c| c <= cur_price } return nil unless tgt_price cur_price -= tgt_price return nil if cur_price < 0 change_coins << tgt_price tmp.delete_at(tmp.index(tgt_price)) return {change_coins:change_coins, rest_coins:tmp} if 0 == cur_price end raise 'failure to get change' end end end class Drink attr_reader :name def initialize(name) raise 'not supported drink' unless VendingMachine::PRICE_LIST[name] @name = name end def price VendingMachine::PRICE_LIST[@name] end def to_s "<Drink: name=#{@name.to_s}, price=#{self.price}>" end def *(count) ret = [] count.times do ret << self.dup end ret end def self.method_missing(name) Drink.new(name) end end class VendingMachine require 'yaml' PRICE_LIST ||= YAML.load_file(File.expand_path('../price_list.yaml', __FILE__)) def initialize(active_proc = nil) require 'thread' @lock = Mutex::new @lock.synchronize do @active = nil @active_proc = active_proc @stocks = (Drink.cola * 5) @cur_coins = [] @sold_coins = [] end end def stock_info grouped = @stocks.group_by {|drink| drink.name} summeried = grouped.map do |name, drinks| prices = drinks.map{|d| d.price}.uniq raise 'multiple PRICE_LIST exist in #{d.to_s}' unless 1 == prices.count [name, {price: prices.first, stock: drinks.count}] end Hash[summeried] end def store drink return unless drink.is_a? Drink @lock.synchronize do @stocks << drink end end OK_COINS = [10, 50, 100] def insert coin return coin unless OK_COINS.include?(coin) @lock.synchronize do if @active_proc @active ||= @active_proc.call raise 'not active!' if @active_proc.call != @active end @cur_coins << coin return nil end end def total @cur_coins.inject(:+).to_i end def refund @lock.synchronize do return 0 if @cur_coins.empty? raise 'not active!' if (@active_proc && @active_proc.call != @active) tot = total @cur_coins.clear @active = nil return tot end end def purchasable_drink_names names = @stocks.map {|drink| drink.name}.uniq names.select{|name| purchasable?(name)} end using CoinsExtensions def purchasable?(name) tgt = @stocks.find{|drink| drink.name == name} return false unless tgt return false if total < tgt.price # 全金額からおつりが返せるかどうか? all_coins = (@sold_coins + @cur_coins) return true if all_coins.can_return_coin?(total - tgt.price) false end def purchase(name) @lock.synchronize do raise 'not active!' if (@active_proc && @active_proc.call != @active) return nil unless purchasable?(name) tgt = @stocks.find{|drink| drink.name == name} change = total - tgt.price #おつり all_coins = (@sold_coins + @cur_coins) ret = all_coins.can_return_coin?(change) raise 'no purchasable!' unless ret # 全金額からおつりをひいた分を、sold_coins(売上)として再登録 @sold_coins.clear @sold_coins << ret[:rest_coins] @sold_coins.flatten! @cur_coins.clear @stocks.delete(tgt) @active = nil return [tgt, change] end end def sale_amount @sold_coins.inject(:+).to_i end end
class UsersController < ApplicationController before_action :redirect_if_logged_out skip_before_action :redirect_if_logged_out, only: [:new, :create, :index] before_action :disable_forum_style, except: [:index] def new redirect_if_logged_in @user = User.new end def create redirect_if_logged_in @user = User.new(user_params) if @user.save session[:user_id] = @user.id flash.notice = "Signup successful!" redirect_to root_path else render 'new' end end def show @user = User.find_by(username: deslugger(params[:slug])) end def edit @user = User.find_by(username: deslugger(params[:slug])) match_user_or_admin(@user) session[:slug] = @user.slug end def update @user = User.find_by(username: deslugger(session[:slug])) session.delete(:slug) match_user_or_admin(@user) check_password_update default_avatar_if_necessary if @user.update(user_params) flash.notice = "Profile successfully updated!" redirect_to user_path(@user.slug) else render 'edit' end end def index @admins = User.admin @users = User.regular_user.where(banned: false) @banned_users = User.where(banned: true) end def destroy @user = User.find_by(username: params[:slug]) if @user == primary_admin redirect_to user_path(@user.username) and return else if @user == current_user @user.posts.delete @user.delete flash.notice = "User deleted!" redirect_to logout_path and return else @user.posts.delete @user.delete flash.notice = "User deleted!" redirect_to root_path and return end end end def karma @user = User.find_by(username: deslugger(params[:user][:slug])) increase_karma(@user) @user.update(user_params) redirect_to user_path(@user.slug) end def banned @user = User.find_by(username: deslugger(params[:user][:slug])) swap_ban(@user) end private def user_params params.require(:user).permit(:username, :password, :password_confirmation, :karma, :avatar_url) end def primary_admin User.find_by(id: 1) end def increase_karma(user) user.karma += 1 end def check_password_update if params[:user][:password].blank? && params[:user][:password_confirmation].blank? params[:user].delete(:password) params[:user].delete(:password_confirmation) end end def default_avatar_if_necessary params[:user][:avatar_url] = "https://eitrawmaterials.eu/wp-content/uploads/2016/09/empty-avatar.jpg" if params[:user][:avatar_url].blank? end def swap_ban(user) if admin? && user != current_user user.banned = !user.banned user.save end redirect_to user_path(user.slug) end end
class CreateEvaluations < ActiveRecord::Migration[5.2] def change create_table :evaluations do |t| t.string :evaluation_name t.integer :evaluation_numeric_number t.datetime :deleted_at t.timestamps end end end
class LogEntry < ActiveRecord::Base belongs_to :loggable, :polymorphic => true belongs_to :company belongs_to :user belongs_to :customer, :class_name => 'User' # LogEntries must be associated with a company. We usually capture the user who created the event, but not necessarily. validates_presence_of :etype, :company_id # LogEntry types URGENT = 1 # urgent messages APPROVAL = 2 # messages indicating that approval is required INFORMATIONAL = 3 # informational messages named_scope :urgent, :conditions => {:etype => URGENT} named_scope :approval, :conditions => {:etype => APPROVAL} named_scope :informational, :conditions => {:etype => INFORMATIONAL} named_scope :seen, :conditions => {:state => "seen"} named_scope :unseen, :conditions => {:state => "unseen"} # order by start_at, most recent first named_scope :order_recent, {:order => 'updated_at DESC'} # Will paginate paging info def self.per_page 10 end # BEGIN acts_as_state_machine include AASM aasm_column :state aasm_initial_state :unseen aasm_state :unseen aasm_state :seen aasm_event :mark_as_seen do transitions :to => :seen, :from => [:unseen, :seen] end aasm_event :mark_as_unseen do transitions :to => :unseen, :from => [:unseen, :seen] end # END acts_as_state_machine def seen? self.state == "seen" end def make_event() end def etype_to_s case self.etype when URGENT "urgent" when APPROVAL "approval" when INFORMATIONAL "informational" else "" end end end
class BidIsHighEnoughValidator < ActiveModel::Validator def validate(bid) unless bid.round.has_no_bids_yet? || higher_than_current_highest_bid?( bid.suit, bid.number_of_tricks, bid.round.highest_bid ) bid.errors.add(:base, "your bid isn't high enough") end end private def higher_than_current_highest_bid?(suit, number_of_tricks, highest_bid) highest_bid.nil? || number_of_tricks > highest_bid.number_of_tricks || number_of_tricks == highest_bid.number_of_tricks && Bid.suits[suit] > Bid.suits[highest_bid.suit] end end
require 'rspec' describe 'No Subscription' do it 'price should be zero' do subscription = NoSubscription expect(subscription.price).to eq 0 end it 'does not have mentoring' do subscription = NoSubscription.new expect(subscription.has_mentoring?).to be_false end it 'does not charge the credit card' do subscription = NoSubscription.new credit_card = double('credit_card') credit_card.stub('charge') subscription.charge(credit_card) expect(credit_card).not_to have_received(:charge) end end
class GraphqlCrudOperations def self.type_mapping proc do |_classname| { 'str' => types.String, '!str' => !types.String, 'int' => types.Int, '!int' => !types.Int, 'id' => types.ID, '!id' => !types.ID, 'bool' => types.Boolean, 'json' => JsonStringType }.freeze end end def self.safe_save(obj, attrs, parents = [], inputs = {}) attrs.each do |key, value| method = key == 'clientMutationId' ? 'client_mutation_id=' : "#{key}=" obj.send(method, value) if obj.respond_to?(method) end obj.disable_es_callbacks = Rails.env.to_s == 'test' obj.save_with_version! name = obj.class_name.underscore { name.to_sym => obj }.merge(GraphqlCrudOperations.define_returns(obj, inputs, parents)) end def self.define_returns(obj, _inputs, parents) ret = {} name = obj.class_name.underscore parents.each do |parent_name| child, parent = obj, obj.send(parent_name) parent = obj.version_object if parent_name == 'version' unless parent.nil? parent.no_cache = true if parent.respond_to?(:no_cache) ret["#{name}Edge".to_sym] = GraphQL::Relay::Edge.between(child, parent) if !['related_to', 'public_team', 'version', 'source_project_media', 'target_project_media', 'current_project_media'].include?(parent_name) && !child.is_a?(ProjectMediaProject) ret[parent_name.to_sym] = parent end end ret.merge(GraphqlCrudOperations.define_conditional_returns(obj)) end def self.define_conditional_returns(obj) ret = {} if obj.is_a?(Team) && User.current.present? team_user = obj.reload.team_user ret["team_userEdge".to_sym] = GraphQL::Relay::Edge.between(team_user, User.current.reload) unless team_user.nil? ret[:user] = User.current end if [Comment, Task, Dynamic].include?(obj.class) version = obj.version_object ret["versionEdge".to_sym] = GraphQL::Relay::Edge.between(version, obj.annotated) unless version.nil? end ret[:affectedId] = obj.graphql_id if obj.is_a?(ProjectMedia) ret end def self.create(type, inputs, ctx, parents = []) klass = type.camelize obj = klass.constantize.new obj.is_being_created = true if obj.respond_to?(:is_being_created) obj.file = ctx[:file] if !ctx[:file].blank? attrs = inputs.keys.inject({}) do |memo, key| memo[key] = inputs[key] memo end attrs['annotation_type'] = type.gsub(/^dynamic_annotation_/, '') if type =~ /^dynamic_annotation_/ self.safe_save(obj, attrs, parents) end def self.crud_operation(operation, obj, inputs, ctx, parents, _returns = {}) self.send("#{operation}_from_single_id", inputs[:id] || obj.graphql_id, inputs, ctx, parents) if inputs[:id] || obj end def self.object_from_id_and_context(id, ctx) obj = CheckGraphql.object_from_id(id, ctx) obj = obj.load if obj.is_a?(Annotation) obj end def self.update_from_single_id(id, inputs, ctx, parents) obj = self.object_from_id_and_context(id, ctx) obj.file = ctx[:file] if !ctx[:file].blank? attrs = inputs.keys.inject({}) do |memo, key| memo[key] = inputs[key] unless key == 'id' memo end self.safe_save(obj, attrs, parents, inputs) end def self.update(type, inputs, ctx, parents = []) obj = inputs[:id] ? self.object_from_id_and_context(inputs[:id], ctx) : self.load_project_media_project_without_id(type, inputs) returns = obj.nil? ? {} : GraphqlCrudOperations.define_returns(obj, inputs, parents) self.crud_operation('update', obj, inputs, ctx, parents, returns) end def self.destroy_from_single_id(graphql_id, inputs, ctx, parents) obj = self.object_from_id(graphql_id) obj.current_id = inputs[:current_id] if obj.is_a?(Relationship) obj.keep_completed_tasks = inputs[:keep_completed_tasks] if obj.is_a?(TeamTask) obj.disable_es_callbacks = (Rails.env.to_s == 'test') if obj.respond_to?(:disable_es_callbacks) obj.respond_to?(:destroy_later) ? obj.destroy_later(ctx[:ability]) : ActiveRecord::Base.connection_pool.with_connection { obj.destroy } deleted_id = obj.respond_to?(:graphql_deleted_id) ? obj.graphql_deleted_id : graphql_id ret = { deletedId: deleted_id } parents.each { |parent| ret[parent.to_sym] = obj.send(parent) } ret end def self.object_from_id(graphql_id) type, id = CheckGraphql.decode_id(graphql_id) obj = type.constantize.where(id: id).last obj = obj.load if obj.respond_to?(:load) obj end def self.object_from_id_if_can(graphql_id, ability) type, id = CheckGraphql.decode_id(graphql_id) obj = type.constantize.find_if_can(id, ability) obj = obj.load if obj.respond_to?(:load) obj end def self.load_project_media_project_without_id(type, inputs) ProjectMediaProject.where(project_id: inputs[:previous_project_id] || inputs[:project_id], project_media_id: inputs[:project_media_id]).last if type.to_s == 'project_media_project' end def self.destroy(type, inputs, ctx, parents = []) returns = {} obj = nil obj = self.object_from_id(inputs[:id]) if inputs[:id] obj = self.load_project_media_project_without_id(type, inputs) if obj.nil? unless obj.nil? parents.each do |parent| parent_obj = obj.send(parent) returns[parent.to_sym] = parent_obj end end self.crud_operation('destroy', obj, inputs, ctx, parents, returns) end def self.define_create(type, create_fields, parents = []) self.define_create_or_update('create', type, create_fields, parents) end def self.define_update(type, update_fields, parents = []) self.define_create_or_update('update', type, update_fields, parents) end def self.define_create_or_update(action, type, fields, parents = []) GraphQL::Relay::Mutation.define do mapping = instance_exec(&GraphqlCrudOperations.type_mapping) name "#{action.camelize}#{type.camelize}" if action == 'update' input_field :id, types.ID end fields.each { |field_name, field_type| input_field field_name, mapping[field_type] } klass = "#{type.camelize}Type".constantize return_field type.to_sym, klass return_field(:affectedId, types.ID) if type.to_s == 'project_media' if type.to_s == 'team' return_field(:team_userEdge, TeamUserType.edge_type) return_field(:user, UserType) end if type =~ /^dynamic_annotation_/ return_field :dynamic, DynamicType return_field :dynamicEdge, DynamicType.edge_type end return_field("versionEdge".to_sym, VersionType.edge_type) if ['task', 'comment'].include?(type.to_s) || type =~ /dynamic/ return_field type.to_sym, klass return_field "#{type}Edge".to_sym, klass.edge_type GraphqlCrudOperations.define_parent_returns(parents).each{ |field_name, field_class| return_field(field_name, field_class) } resolve -> (_root, inputs, ctx) { GraphqlCrudOperations.send(action, type, inputs, ctx, parents) } end end def self.define_bulk_update_or_destroy(update_or_destroy, klass, fields, parents) GraphQL::Relay::Mutation.define do mapping = instance_exec(&GraphqlCrudOperations.type_mapping) name "#{update_or_destroy.to_s.capitalize}#{klass.name.pluralize}" input_field :ids, !types[types.ID] fields.each { |field_name, field_type| input_field field_name, mapping[field_type] } return_field :ids, types[types.ID] GraphqlCrudOperations.define_parent_returns(parents).each{ |field_name, field_class| return_field(field_name, field_class) } resolve -> (_root, inputs, ctx) { if inputs[:ids].size > 10000 raise I18n.t(:bulk_operation_limit_error, limit: 10000) end sql_ids = [] processed_ids = [] inputs[:ids].to_a.each do |graphql_id| type, id = CheckGraphql.decode_id(graphql_id) if type == klass.name sql_ids << id processed_ids << graphql_id end end ability = ctx[:ability] || Ability.new if ability.can?("bulk_#{update_or_destroy}".to_sym, klass.new(team: Team.current)) filtered_inputs = inputs.to_h.reject{ |k, _v| ['ids', 'clientMutationId'].include?(k.to_s) }.with_indifferent_access method_mapping = { update: :bulk_update, destroy: :bulk_destroy } method = method_mapping[update_or_destroy.to_sym] result = klass.send(method, sql_ids, filtered_inputs, Team.current) { ids: processed_ids }.merge(result) else raise CheckPermissions::AccessDenied, I18n.t(:permission_error) end } end end def self.define_bulk_update(klass, fields, parents) self.define_bulk_update_or_destroy(:update, klass, fields, parents) end def self.define_bulk_destroy(klass, fields, parents) self.define_bulk_update_or_destroy(:destroy, klass, fields, parents) end def self.define_bulk_create(klass, fields, parents) input_type = "Create#{klass.name.pluralize}BulkInput" definition = GraphQL::InputObjectType.define do mapping = instance_exec(&GraphqlCrudOperations.type_mapping) name(input_type) fields.each { |field_name, field_type| argument field_name, mapping[field_type] } end Object.const_set input_type, definition GraphQL::Relay::Mutation.define do name "Create#{klass.name.pluralize}" input_field :inputs, types[input_type.constantize] GraphqlCrudOperations.define_parent_returns(parents).each{ |field_name, field_class| return_field(field_name, field_class) } resolve -> (_root, input, ctx) { if input[:inputs].size > 10000 raise I18n.t(:bulk_operation_limit_error, limit: 10000) end ability = ctx[:ability] || Ability.new if ability.can?(:bulk_create, klass.new(team: Team.current)) klass.bulk_create(input['inputs'], Team.current) else raise CheckPermissions::AccessDenied, I18n.t(:permission_error) end } end end def self.define_destroy(type, parents = []) GraphQL::Relay::Mutation.define do name "Destroy#{type.camelize}" input_field :id, types.ID if type == 'project_media_project' input_field :project_id, types.Int input_field :project_media_id, types.Int end input_field(:current_id, types.Int) if type == 'relationship' input_field(:keep_completed_tasks, types.Boolean) if type == 'team_task' return_field :deletedId, types.ID GraphqlCrudOperations.define_parent_returns(parents).each{ |field_name, field_class| return_field(field_name, field_class) } resolve -> (_root, inputs, ctx) { GraphqlCrudOperations.destroy(type, inputs, ctx, parents) } end end def self.define_parent_returns(parents = []) fields = {} parents.each do |parent| parentclass = parent =~ /^check_search_/ ? 'CheckSearch' : parent.gsub(/_was$/, '').camelize parentclass = 'ProjectMedia' if ['related_to', 'source_project_media', 'target_project_media', 'current_project_media'].include?(parent) parentclass = 'TagText' if parent == 'tag_text_object' fields[parent.to_sym] = "#{parentclass}Type".constantize end fields end def self.define_crud_operations(type, create_fields, update_fields = {}, parents = []) update_fields = create_fields if update_fields.empty? [GraphqlCrudOperations.define_create(type, create_fields, parents), GraphqlCrudOperations.define_update(type, update_fields, parents), GraphqlCrudOperations.define_destroy(type, parents)] end def self.define_default_type(&block) GraphQL::ObjectType.define do global_id_field :id field :permissions, types.String do resolve -> (obj, _args, ctx) { obj.permissions(ctx[:ability]) } end field :created_at, types.String do resolve -> (obj, _args, _ctx) { obj.created_at.to_i.to_s if obj.respond_to?(:created_at) } end field :updated_at, types.String do resolve -> (obj, _args, _ctx) { obj.updated_at.to_i.to_s if obj.respond_to?(:updated_at) } end instance_eval(&block) end end def self.field_published proc do |_classname| field :published do type types.String resolve ->(obj, _args, _ctx) { obj.created_at.to_i.to_s } end end end def self.field_annotations proc do |_classname| connection :annotations, -> { AnnotationUnion.connection_type } do argument :annotation_type, !types.String resolve ->(obj, args, _ctx) { obj.get_annotations(args['annotation_type'].split(',').map(&:strip)) } end end end def self.field_annotations_count proc do |_classname| field :annotations_count do type types.Int argument :annotation_type, !types.String resolve ->(obj, args, _ctx) { obj.get_annotations(args['annotation_type'].split(',').map(&:strip)).count } end end end def self.field_log proc do |_classname| connection :log, -> { VersionType.connection_type } do argument :event_types, types[types.String] argument :field_names, types[types.String] argument :annotation_types, types[types.String] argument :who_dunnit, types[types.String] argument :include_related, types.Boolean resolve ->(obj, args, _ctx) { obj.get_versions_log(args['event_types'], args['field_names'], args['annotation_types'], args['who_dunnit'], args['include_related']) } end end end def self.field_log_count proc do |_classname| field :log_count do type types.Int resolve ->(obj, _args, _ctx) { obj.get_versions_log_count } end end end def self.define_annotation_fields [:annotation_type, :annotated_id, :annotated_type, :content, :dbid] end def self.define_annotation_mutation_fields { fragment: 'str', annotated_id: 'str', annotated_type: 'str' } end def self.define_annotation_type(type, fields = {}, &block) GraphQL::ObjectType.define do name type.capitalize interfaces [NodeIdentification.interface] field :id, !types.ID do resolve -> (annotation, _args, _ctx) { annotation.relay_id(type) } end GraphqlCrudOperations.define_annotation_fields.each { |name| field name, types.String } field :permissions, types.String do resolve -> (annotation, _args, ctx) { annotation.permissions(ctx[:ability], annotation.annotation_type_class) } end field :created_at, types.String do resolve -> (annotation, _args, _ctx) { annotation.created_at.to_i.to_s } end field :updated_at, types.String do resolve -> (annotation, _args, _ctx) { annotation.updated_at.to_i.to_s } end fields.each { |name, _field_type| field name, types.String } connection :medias, -> { ProjectMediaType.connection_type } do resolve ->(annotation, _args, _ctx) { annotation.entity_objects } end instance_exec :annotator, AnnotatorType, &GraphqlCrudOperations.annotation_fields instance_exec :version, VersionType, &GraphqlCrudOperations.annotation_fields connection :assignments, -> { UserType.connection_type } do resolve ->(annotation, _args, _ctx) { annotation.assigned_users } end connection :annotations, -> { AnnotationUnion.connection_type } do argument :annotation_type, !types.String resolve ->(annotation, args, _ctx) { Annotation.where(annotation_type: args['annotation_type'], annotated_type: ['Annotation', annotation.annotation_type.camelize], annotated_id: annotation.id) } end field :locked, types.Boolean field :project, ProjectType field :image_data, JsonStringType field :data, JsonStringType field :parsed_fragment, JsonStringType instance_eval(&block) if block_given? end end def self.annotation_fields proc do |name, field_type = types.String, method = nil| field name do type field_type resolve -> (annotation, _args, _ctx) { annotation.send(method.blank? ? name : method) } end end end def self.load_if_can(klass, id, ctx) klass.find_if_can(id, ctx[:ability]) end end JsonStringType = GraphQL::ScalarType.define do name "JsonStringType" coerce_input -> (val, _ctx) { JSON.parse(val) } coerce_result -> (val, _ctx) { val.as_json } end
class Need < ApplicationRecord attribute :is_taken, :boolean, default: false attribute :datetime_range_start, :datetime, default: DateTime.now attribute :datetime_range_end, :datetime, default: DateTime.now.end_of_day end
class Material::File < ActiveRecord::Base attr_accessible :file, :material, :material_id belongs_to :material mount_uploader :file, MaterialFileUploader def name @name ||= File.basename file.url end end
require 'rails_helper' RSpec.describe 'Services', type: :request do before(:all) do Jurisdiction.all.map(&:destroy) Service.all.map(&:destroy) @good_service = Fabricate(:service) end describe 'GET /services' do it 'returns a collection' do get services_path expect(response).to have_http_status(200) expect(response).to render_template(:index) end end describe 'GET /services/:id' do it 'returns a valid instance' do get service_path(@good_service) expect(response).to have_http_status(200) expect(response).to render_template(:show) end it 'returns 404 for an invalid jurisdiction id' do @bad_service = Fabricate(:service) @bad_service.update_attributes(jurisdiction_id: 10000000) # @bad_service.jurisdiction_id = nil # puts "\n----\n#{@bad_service.inspect}" get service_path(@bad_service) expect(response).to have_http_status(404) end end end
require_relative '../lib/parser_log.rb' describe ParserLog do let(:expected_output) { File.open(File.dirname(__FILE__) + '/support/results.txt').read } let(:parser_log) { ParserLog.new(File.dirname(__FILE__) + '/support/webserver.log') } it "initialize parser with file" do expect(parser_log).to_not be nil end it "should create an array the webpages" do expect(parser_log.webpages).to_not be_empty expect(parser_log.webpages.count).to eq(30) expect(parser_log.webpages[0]).to eq('/home') expect(parser_log.webpages[1]).to eq('/contact/') end it "should create an array the ip addresses" do expect(parser_log.webpages_addresses).to_not be_empty expect(parser_log.webpages_addresses.count).to eq(30) expect(parser_log.webpages_addresses[0]).to eq({"/home"=>"225.183.113.22"}) expect(parser_log.webpages_addresses[1]).to eq({"/contact/"=>"245.141.61.189"}) end it "should print the output correctly" do parser_log.calculate expect { parser_log.print_results }.to output(expected_output).to_stdout end end
FactoryGirl.define do factory :asset_type do |at| at.name 'Laptop' end factory :asset do |a| a.asset_id 'asset id' a.purchase_date Time.now a.serial_number '1234' a.make_year Time.now a.description 'This is description' a.display_size 15 a.manufacturer 'HP' a.model 'TEST-123' a.operating_system 'Windows' a.asset_bounded 't' association :asset_type, factory: :asset_type end end
class Authentication::LocalsController < ApplicationController before_action :set_authentication_local, only: [:show, :edit, :update, :destroy] before_action :logged_in_user, only: [:index, :show, :edit, :update, :destroy] def index @authentication_locals = Authentication::Local.all end def show end def new @authentication_local = Authentication::Local.new end def edit end def create @user = User.where(:email => params[:email])[0] if !@user @user = User.create(:email => authentication_local_params[:email]) end @authentication_local_params = {:email => authentication_local_params[:email], :password_digest => User.hash_password(authentication_local_params[:password_digest])} @authentication_local_params[:user_id] = @user.id @authentication_local = Authentication::Local.new(@authentication_local_params) if @authentication_local.save redirect_to @authentication_local, notice: 'Local was successfully created.' else render :new end end def update @authentication_local_params = {:email => authentication_local_params[:email], :password_digest => User.hash_password(authentication_local_params[:password_digest])} if @authentication_local.update(@authentication_local_params) redirect_to @authentication_local, notice: 'Local was successfully updated.' else render :edit end end def destroy @authentication_local.destroy redirect_to authentication_locals_url, notice: 'Local was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_authentication_local @authentication_local = Authentication::Local.find(params[:id]) end # Only allow a list of trusted parameters through. def authentication_local_params params.require(:authentication_local).permit(:email, :password_digest, :password_confirmation, :user_id) end end
class Expense < ActiveRecord::Base belongs_to :category has_and_belongs_to_many :tags validates :price, numericality: true, presence: true validates :name, presence: true end
require "formula" class Ruby19Dependency < Requirement fatal true default_formula "ruby" satisfy do `ruby --version` =~ /ruby (\d\.\d).\d/ $1.to_f >= 1.9 end def message "Betty requires Ruby 1.9 or better." end end class Betty < Formula homepage "https://github.com/pickhardt/betty" url "https://github.com/pickhardt/betty/archive/v0.1.7.tar.gz" sha1 "ec21ec5541289a9902874c7897f8d521044daf27" depends_on Ruby19Dependency def install libexec.install "lib", "main.rb" => "betty" bin.write_exec_script libexec/"betty" end test do system bin/"betty", "speech on" system bin/"betty", "what is your name" system bin/"betty", "version" system bin/"betty", "speech off" end end
FactoryGirl.define do sequence :metasploit_model_architecture_abbreviation, Metasploit::Model::Architecture::ABBREVIATIONS.cycle sequence :metasploit_model_architecture_bits, Metasploit::Model::Architecture::BITS.cycle sequence :metasploit_model_architecture_endianness, Metasploit::Model::Architecture::ENDIANNESSES.cycle sequence :metasploit_model_architecture_family, Metasploit::Model::Architecture::FAMILIES.cycle end
class CreateEditionsWorks < ActiveRecord::Migration def change create_table :editions_works, :id => false do |t| t.integer :edition_id t.integer :work_id end end end
Pod::Spec.new do |s| s.name = "ObjectiveCOAuth1Consumer" s.version = "0.0.1" s.summary = "OAuth1.0a Framework for Dealing with the Yelp API's Quirky '2-Legged' OAuth Variant" s.description = "Yelp requires a weird variant of 2-legged OAuth from a client trying to access it's API. The API has no user-centric entities and hence no need for 3-legged OAuth (to obtain a user's access token). However, the API still needs all requests to be signed with the CLIENT's consumer key, consumer secret, token and token secret. This framework is flexible enough to accomodate this behavior." s.homepage = "https://github.com/tracktorbeam/ObjectiveCOAuth1Consumer" s.license = 'MIT' s.author = { "Arpan Ghosh" => "arpan@tracktorbeam.com" } s.platform = :ios s.source = { :git => "https://github.com/tracktorbeam/ObjectiveCOAuth1Consumer.git", :tag => "0.0.1" } s.source_files = 'ObjectiveCOAuth1Consumer', 'ObjectiveCOAuth1Consumer/Crypto' s.public_header_files = 'ObjectiveCOAuth1Consumer/*.h' 'ObjectiveCOAuth1Consumer/Crypto/*.h' s.framework = 'Foundation' s.requires_arc = false end
module RbacCore::Concerns module OptionsModel module Serialization extend ActiveSupport::Concern def to_h hash = {} self.class.attribute_names.each do |attribute_name| attribute = public_send(attribute_name) if attribute.is_a?(self.class) hash[attribute_name] = attribute.to_h else hash[attribute_name] = attribute end end hash end def to_h_with_unused to_h.merge unused_attributes end module ClassMethods def dump(obj) return YAML.dump({}) unless obj unless obj.is_a? self raise ArgumentError, "can't dump: was supposed to be a #{self}, but was a #{obj.class}. -- #{obj.inspect}" end YAML.dump obj.to_h end def load(yaml) return new unless yaml return new unless yaml.is_a?(String) && /^---/.match?(yaml) hash = YAML.load(yaml) || Hash.new unless hash.is_a? Hash raise ArgumentError, "can't load: was supposed to be a #{Hash}, but was a #{hash.class}. -- #{hash.inspect}" end new hash end end end end end
class AddColumnsToBanks < ActiveRecord::Migration def change add_column :banks, :money_id, :integer add_column :banks, :account_type, :string add_column :banks, :account_number, :string add_column :banks, :account_detraction, :string add_column :banks, :cci, :string end end
class DogsController < ApplicationController before_action :set_dog, only: [:show, :edit, :update, :destroy] # Runs set_dog before only the show, edit, and update methods def index @dogs = Dog.all end def new @dog = Dog.new end def create @dog = Dog.new(dog_params) # if saves, go to index w/ notification if @dog.save redirect_to dogs_url, notice: "Successfully created #{@dog.name}." else # if doesn't save, re-render the new dog form flash.now[:notice] = "Something went wrong. We couldn't save #{@dog.name}..." render :new end end def show # set_dog end def edit # set_dog end def update # set_dog if @dog.update(dog_params) redirect_to dog_url(@dog), notice: "Successfully updated #{@dog.name}." else flash.now[:notice] = "Something went wrong. We couldn't update #{@dog.name}..." render :edit end end def destroy if @dog.destroy redirect_to dogs_url, notice: "Successfully deleted #{@dog.name}." else redirect_to dog_url, notice: "Couldn't delete #{@dog.name}." end end private def dog_params params.require(:dog).permit(:name, :age, :breed_id, :owner_id) end def set_dog @dog = Dog.find(params[:id]) end end
require 'linkedlist/version' require 'date' module Ref # Clase Referencia class Referencia include Comparable # Se tiene acceso de lectura y escritura a todos los atributos attr_accessor :titulo, :autores, :fec, :pa, :an, :edit, :edic, :vol def initialize(titulo, &block) # Comprobamos tipo fail ArgumentError, 'El titulo no es un string' unless titulo.is_a?(String) # #Evaluamos el bloque instance_eval &block # #Creamos variables con los valores que recibimos del bloque # @titulo = @tit autores = [] autores.push(@aut) @pa = @pais @an = @anio # # Comprobamos tipo fail ArgumentError, 'Autores debe ser un array' unless autores.is_a?(Array) # cadena = '' autores.each do |au| fail ArgumentError, 'Uno de los autores no es un string' unless au.is_a?(String) fail ArgumentError, 'Se especifica unicamente el nombre o el apellido' unless au.split(/\W+/).length > 1 aux = au.split(/\W+/) cadena += aux[1] cadena += ', ' unless aux[2].nil? cadena += aux[2][0] cadena += '. ' end cadena += aux[0][0] cadena += '.' cadena += ' & ' unless au == autores.last end @autores = cadena # Comprobamos tipos fail ArgumentError, 'El titulo no es un string' unless titulo.is_a?(String) fail ArgumentError, 'El pais no es string o nulo' unless pa.nil? || pa.is_a?(String) # aux2 = @titulo.split(/\W+/) aux2.each do |aux3| if aux3.length > 3 aux3.capitalize! else aux3.downcase! end end # Asignamos el titulo formateado @titulo = aux2.join(' ') # # Asignamos pais @pa = @pais # # Compruebo tipo fail ArgumentError, 'Anio debe ser un entero' unless an.is_a?(Integer) @fec = Date.new(@an, 1, 1) # # Asignamos los valores @edit = @editorial @edic = @edicion @vol = @volumen # # Compruebo tipo fail ArgumentError, 'La editorial no es una cadena de caracteres' unless edit.is_a?(String) fail ArgumentError, 'La edicion no es un entero' unless edic.is_a?(Integer) fail ArgumentError, 'El volumen no es un entero' unless vol.is_a?(Integer) # #Pruebas de creación - Debug #puts(@titulo) #puts(@autores) #puts(@fec) #puts(@pa) #puts(@an) #puts(@edit) #puts(@edic) #puts(@vol) # end # Fin constructor #Accesores def author(entrada) @aut = entrada end def title(entrada) @tit = entrada end def pais(entrada) @pais = entrada end def anio(entrada) @anio = entrada end def editorial(entrada) @editorial = entrada end def edicion(entrada) @edicion = entrada end def volumen(entrada) @volumen = entrada end # def <=>(other) if @autores == other.autores if @fec == other.fec if @titulo == other.titulo # Iguales return 0 else aux = [@titulo, other.titulo] aux.sort_by!(&:downcase) return -1 if aux.first == @titulo return 1 end elsif fec > other.fec return 1 else return -1 end else aux = [@autores, other.autores] aux.sort_by!(&:downcase) return 1 if aux.first == @autores return -1 end end end ## end
ActiveAdmin.register Category do menu :parent => "Admin resource", label: 'Courses Categories' index do column :id column :name, :sortable => :name do |c| link_to c.name, admin_category_path(c) end column :parent do |c| link_to c.parent.name, admin_category_path(c) if c.parent.present? end column :priority column :keyword column :has_advanced_courses actions end # filter :email member_action :add_child_category, :method => :get do end show do |category| attributes_table do table_for category do column 'Parent category' do |category| category.parent.present? ? category.parent.name : 'Root' end column 'name' end end panel "Actions" do table_for category do column do |category| link_to 'Add child category', add_child_category_admin_category_path(category) end end end panel "Root categories" do table_for category.root do column do |category| link_to category.name, admin_category_path(category) end end end panel "Child categories" do table_for category.children do column do |category| link_to category.name, admin_category_path(category) end end end end form do |f| cat = Category.find(params[:id]) if params[:id].present? categories = params[:id].present? ? Category.where(cat.parent_id).first.self_and_siblings : Category.roots f.inputs "Category" do f.input :parent_id, as: :select, :collection => categories.map{|c| [c.name, c.id]} f.input :name f.input :priority f.input :has_advanced_courses f.input :hidden end f.actions end controller do def permitted_params params.permit category: [:name, :parent_id, :priority, :has_advanced_courses, :hidden] end end end
require 'spec_helper' describe SubscriptionsController do describe "GET 'unsubscribe'" do def do_request(params = {}) get :unsubscribe, params end it "finds subscription with given token" do Subscription.should_receive(:find_by_hash_key).with('foo') do_request :id => 'foo' end context "with valid token" do before do @subscription = Factory(:subscription) Subscription.stub!(:find_by_hash_key).and_return(@subscription) end it "removes subscription for user on the topic" do @subscription.should_receive(:destroy) do_request :id => 'foo' end it "redirects to topic path" do do_request :id => 'foo' response.should redirect_to(@subscription.topic) end end context "with invalid token" do before do @subscription = Factory(:subscription) Subscription.stub!(:find_by_hash_key).and_return(nil) end it "redirects to root path" do do_request :id => 'foo' response.should redirect_to(root_path) end end end end
class Response < ActiveRecord::Base belongs_to :user belongs_to :respondable, :polymorphic=>true has_many :votes, :as => :votable validates :body, :respondable_id, :respondable_type, :presence=>true validates :respondable_type, :inclusion => { :in => %w(Question Answer), :message => "%{value} is not a valid type" } attr_accessible :body, :respondable, :respondable_id, :respondable_type end
require './contact_menu' require './modify_menu' require './contact.rb' class MainMenu #attr_accessor :contact def initialize @done = false @menu = [ "\e[H\e[2J", "---- Main Menu ----".center(25), "1. Add New Contact", "2. Display Contacts", "3. Modify A Contact", "0. QUIT", ] end def run while !@done display_menu get_request perform_request end end def display_menu puts @menu end def get_request @usr_request = gets.chomp.to_i end def perform_request case @usr_request when 1 then add_contact when 2 then display_contact when 3 then modify_contact when 0 then @done = true end end def add_contact @contact_menu = ContactMenu.new contact = Contact.new @contact_menu.run(contact) end def display_contact puts "\e[H\e[2J" # Clears terminal window $database.display puts "\nReturn to main menu? (Enter)" gets.chomp end def modify_contact @modify_menu = ModifyMenu.new @modify_menu.run end end
module CarrierWave class SanitizedFile # FIXME (Did) CarrierWave speaks mime type now def content_type_with_file_mime_type mt = content_type_without_file_mime_type mt.blank? || mt == 'text/plain' ? File.mime_type?(original_filename) : mt end alias_method_chain :content_type, :file_mime_type end module Uploader module Store # unfortunately carrierwave does not support an easy way of changing # version file extensions def store_path(for_file=filename) File.join([store_dir, full_filename(for_file)].compact).gsub(/(compiled_[^\.]+\.)(scss|coffee)$/) do "#{$1}#{$2=='scss'? 'css':'js'}" end end end class Base def build_store_dir(*args) default_dir = self.class.store_dir if default_dir.blank? || default_dir == 'uploads' File.join(args.map(&:to_s)) else File.join([default_dir] + args.map(&:to_s)) end end end end end
require 'mysql2' class Server def initialize(mysql_config) @mysql_config = mysql_config end def with_connection yield(mysql_client) mysql_client.close end private def mysql_client @mysql_client ||= Mysql2::Client.new(@mysql_config) end end config = { username: "root", password: "", host: "mysql-schema-compare.railgun", reconnect: true } server = Server.new(config) server.with_connection do |client| client.query("SHOW DATABASES") end server.with_connection do |client| client.query("SHOW DATABASES") end
# frozen_string_literal: true require_relative 'lib/riteway/version' Gem::Specification.new do |spec| spec.name = 'riteway' spec.version = Riteway::VERSION spec.authors = ['Mikey Hargiss'] spec.summary = 'Simple, readable, helpful unit tests in Ruby' spec.license = 'MIT' spec.required_ruby_version = Gem::Requirement.new('>= 2.4.0') spec.metadata = { 'allowed_push_host' => 'https://rubygems.org', 'source_code_uri' => 'https://github.com/mycargus/riteway-ruby', 'changelog_uri' => 'https://github.com/mycargus/riteway-ruby/blob/master/CHANGELOG.md' } # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test)/}) } end spec.require_paths = ['lib'] spec.add_development_dependency 'minitest', '~> 5.0' spec.add_development_dependency 'pry', '~> 0.13' spec.add_development_dependency 'pry-byebug', '~> 3.9' spec.add_development_dependency 'pry-doc', '~> 1.1' spec.add_development_dependency 'rake', '~> 12.0' spec.add_development_dependency 'rubocop', '~> 0.89.1' spec.add_development_dependency 'rubocop-minitest', '~> 0.10' end
module Assistant class SharesController < InheritedResources::Base InheritedResources.flash_keys = [ :success, :failure ] before_filter :authenticate_user! actions :all, :only => [:new, :create] respond_to :html defaults :route_prefix => 'assistant' def new @share = current_user.shares.build @goal = current_user.goals.find(params[:goal_id]) @friends = Tracker.non_shared_friends(@goal, current_user) end def create create! do |success, failure | success.html {redirect_to assistant_goals_path} failure.js {} failure.html do @friends = Tracker.non_shared_friends(@goal, current_user) render 'new' end end end private def begin_of_association_chain @goal = current_user.goals.find(params[:goal_id]) end end end
share_examples_for 'It can transfer a Resource from another association' do before :all do @no_join = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter) || defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapters::YamlAdapter) @one_to_many = @articles.kind_of?(DataMapper::Associations::OneToMany::Collection) @many_to_many = @articles.kind_of?(DataMapper::Associations::ManyToMany::Collection) @skip = @no_join && @many_to_many end before :all do unless @skip %w[ @resource @original ].each do |ivar| raise "+#{ivar}+ should be defined in before block" unless instance_variable_defined?(ivar) raise "+#{ivar}+ should not be nil in before block" unless instance_variable_get(ivar) end end end before do pending if @skip end it 'should relate the Resource to the Collection' do @resource.collection.should equal(@articles) end it 'should remove the Resource from the original Collection' do pending do @original.should_not be_include(@resource) end end end share_examples_for 'A public Association Collection' do before :all do @no_join = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter) || defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapters::YamlAdapter) @one_to_many = @articles.kind_of?(DataMapper::Associations::OneToMany::Collection) @many_to_many = @articles.kind_of?(DataMapper::Associations::ManyToMany::Collection) @skip = @no_join && @many_to_many end before :all do unless @skip %w[ @articles @other_articles ].each do |ivar| raise "+#{ivar}+ should be defined in before block" unless instance_variable_get(ivar) end end @articles.loaded?.should == loaded end before do pending if @skip end describe '#<<' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles << @resource end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#collect!' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first @return = @articles.collect! { |resource| @resource } end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#concat' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles.concat([ @resource ]) end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#create' do describe 'when the parent is not saved' do it 'should raise an exception' do author = @author_model.new(:name => 'Dan Kubb') lambda { author.articles.create }.should raise_error(DataMapper::UnsavedParentError) end end end describe '#destroy' do describe 'when the parent is not saved' do it 'should raise an exception' do author = @author_model.new(:name => 'Dan Kubb') lambda { author.articles.destroy }.should raise_error(DataMapper::UnsavedParentError, 'The source must be saved before mass-deleting the collection') end end end describe '#destroy!' do describe 'when the parent is not saved' do it 'should raise an exception' do author = @author_model.new(:name => 'Dan Kubb') lambda { author.articles.destroy! }.should raise_error(DataMapper::UnsavedParentError, 'The source must be saved before mass-deleting the collection') end end end describe '#insert' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles.insert(0, @resource) end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end it 'should respond to a public collection method with #method_missing' do @articles.respond_to?(:to_a) end describe '#method_missing' do describe 'with a public collection method' do before :all do @return = @articles.to_a end it 'should return expected object' do @return.should == @articles end end describe 'with unknown method' do it 'should raise an exception' do lambda { @articles.unknown }.should raise_error(NoMethodError) end end end describe '#new' do before :all do @resource = @author.articles.new end it 'should associate the Resource to the Collection' do if @resource.respond_to?(:authors) pending 'TODO: make sure the association is bidirectional' do @resource.authors.should == [ @author ] end else @resource.author.should == @author end end end describe '#push' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles.push(@resource) end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#replace' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles.replace([ @resource ]) end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it 'should relate the Resource to the Collection' do @resource.collection.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#unshift' do describe 'when provided a Resource belonging to another association' do before :all do @original = @other_articles @resource = @original.first rescue_if 'TODO', @skip do @return = @articles.unshift(@resource) end end it 'should return a Collection' do @return.should be_kind_of(DataMapper::Collection) end it 'should return self' do @return.should equal(@articles) end it_should_behave_like 'It can transfer a Resource from another association' end end describe '#update' do describe 'when the parent is not saved' do it 'should raise an exception' do author = @author_model.new(:name => 'Dan Kubb') lambda { author.articles.update(:title => 'New Title') }.should raise_error(DataMapper::UnsavedParentError, 'The source must be saved before mass-updating the collection') end end end describe '#update!' do describe 'when the parent is not saved' do it 'should raise an exception' do author = @author_model.new(:name => 'Dan Kubb') lambda { author.articles.update!(:title => 'New Title') }.should raise_error(DataMapper::UnsavedParentError, 'The source must be saved before mass-updating the collection') end end end end
FactoryBot.define do factory :notification_preference do notification_type { NotificationPreference::SIGNUP } notification_frequency { NotificationPreference::IMMEDIATELY } association :user, factory: :user factory :organization_notification_preference do association :settable, factory: :organization end factory :event_notification_preference do association :settable, factory: :event end end end
# == Schema Information # # Table name: questions # # id :integer not null, primary key # survey_id :integer # label :string(255) # position :integer # created_at :datetime not null # updated_at :datetime not null # class Question < ActiveRecord::Base attr_accessible :label, :position, :survey_id default_scope order("position") belongs_to :survey has_many :user_responses, :class_name => "QuestionResponse", :foreign_key => :question_id has_many :users_responded, :through => :user_responses, :source => :user end
##### # @author Mars ##### require 'test_helper' class ImageTest < ActiveSupport::TestCase test "should not save image without an image url" do image = Image.new assert_not image.save, "Saved image without url" end end
module LoggingExtensions # Create our default log formatter so that we can use it everywhere, and keep formats consistent. def self.default_log_formatter @default_log_formatter = if Rails.env.development? || Rails.env.profiling? || Rails.env.test? Ougai::Formatters::Readable.new else Ougai::Formatters::Bunyan.new end end end # Ensure Tagged Logging formatter plays nicely with Ougai. # See also https://github.com/tilfin/ougai/wiki/Use-as-Rails-logger module ActiveSupport::TaggedLogging::Formatter def call(severity, time, progname, data) data = {msg: data.to_s} unless data.is_a?(Hash) tags = current_tags data[:tags] = tags if tags.present? _call(severity, time, progname, data) end end
module Entities class New < Grape::Entity expose :title expose :details expose :img_dir expose :img_num expose :date expose :important end end
FactoryGirl.define do factory :user do first_name "John" last_name "Smith" sequence(:email) { |n| "#{first_name}.#{last_name}.#{n}@example.com".downcase } password "secret" password_confirmation { password } password_recovery_token "secret_token" password_recovery_sent_at Time.zone.now end end
class AddForfeitAllMatchesWhenRosterDisbandsOptionToLeagues < ActiveRecord::Migration[5.0] def change add_column :leagues, :forfeit_all_matches_when_roster_disbands, :boolean, null: false, default: true end end
#!/usr/bin/env ruby # # Node visualiser for IF engine. # # Grapher requires svg2png installed on OSX # brew install svg2png if you have homebrew installed require 'graph' class Node < OpenStruct def graph(gr=Graph.new) gr.edge tag.to_s, parent.tag.to_s unless parent.nil? gr.node_attribs << gr.filled if tag == :player || tag == :root gr.tomato << gr.node(tag.to_s) elsif parent && parent.tag == :root gr.mediumspringgreen << gr.node(tag.to_s) end children.each{|c| c.graph(gr) } return gr end def save_graph graph.save 'graph', 'svg' `svg2png graph.svg graph.png` `open graph.png` end def map(gr=Graph.new) if parent && parent.tag == :root methods.grep(/^exit_[a-z]+(?!=)$/) do|e| dir = e.to_s.split(/_/).last.split(//).first gr.edge(tag.to_s, send(e).to_s).label(dir) end end children.each{|c| c.map(gr) } return gr end def save_map map.save 'map', 'svg' `svg2png map.svg map.png` `open map.png` end end
require 'rails_helper' RSpec.describe ReferralCode, type: :model do context 'when being created' do it 'generates three profiles' do ref_code = FactoryBot.create(:referral_code) expect(ref_code.code).to match(/^[a-z]{8}$/) end end end
# Things to Test ----- # Ensure that create_map returns a generated map with all the expected attributes. # Ensure that create_map returns a map with a level that it's given. # Ensure create_map returns a map at level 1 without a level given. # Ensure that create_map returns a map with the number of rooms sent in. require_relative './spec_helper.rb' require_relative '../lib/dungeon/map/map_factory.rb' describe MapFactory do context 'When create_map is called' do num_rooms = 2 level = 1 it 'should return a map with all expected attributes' do map = MapFactory.create_map(num_rooms, level) expect(map[:level]).to be(1) expect(map[:tiles]).to be_a(Hash) expect(map[:stairs_up]).to be_a(Array) expect(map[:stairs_down]).to be_a(Array) expect(map[:x_low_bound]).to be_a(Integer) expect(map[:x_up_bound]).to be_a(Integer) expect(map[:y_low_bound]).to be_a(Integer) expect(map[:y_up_bound]).to be_a(Integer) end it 'should return a map of the level provided' do level = 3 map = MapFactory.create_map(num_rooms, level) expect(map[:level]).to be(3) end it 'should return a map of level 1 when no level is provided' do map = MapFactory.create_map(num_rooms) expect(map[:level]).to be(1) end it 'should return a map with the number of rooms sent in' do map = MapFactory.create_map(num_rooms, level) counted_rooms = count_rooms(map[:tiles]) expect(counted_rooms).to be(num_rooms) end end end def count_rooms(tiles) tiles.values.count { |tile| tile.type == 'room' } - 1 end
module WSDL module Reader class PortTypes < Hash def lookup_operation_message(type, operation, messages) # TODO: lookup_message_by_operation each do |_, port_type| message = port_type.lookup_operation_message type, operation, messages return message if message end end def lookup_operations_by_message(type, message) inject([]) do |array, (_, port_type)| array + port_type.lookup_operations_by_message(type, message) end end end class PortType attr_reader :operations attr_reader :name def initialize(element) @operations = Hash.new @name = element.attributes['name'] process_all_operations(element) end def lookup_operation_message(type, operation, messages) operation_name = operation.is_a?(Operation) ? operation.name : operation.to_s messages[@operations[operation_name][type][:message].split(':').last] end def lookup_operations_by_message(type, message) ops = @operations.values.select do |operation| operation_message? type, operation, message end ops.map do |operation_hash| operation_hash[:name] end end def operation_message?(type, operation, message) message_name = message.is_a?(Message) ? message.name : message.to_s operation[type][:message] == message_name || operation[type][:message].split(':').last == message_name end protected def store_attributes(element, operation) operation.attributes.each { |name, value| case name when 'name' @operations[operation.attributes['name']][:name] = value else warn "Ignoring attribut '#{name}' in operation '#{operation.attributes['name']}' for portType '#{element.attributes['name']}'" end } end def store_input(action, element, operation) @operations[operation.attributes['name']][:input] = Hash.new action.attributes.each do |name, value| case name when 'name' @operations[operation.attributes['name']][:input][:name] = value when 'message' @operations[operation.attributes['name']][:input][:message] = value else warn_ignoring(action, element, name, operation) end end end def store_output(action, element, operation) @operations[operation.attributes['name']][:output] = Hash.new action.attributes.each { |name, value| case name when 'name' @operations[operation.attributes['name']][:output][:name] = value when 'message' @operations[operation.attributes['name']][:output][:message] = value else warn_ignoring(action, element, name, operation) end } end def store_fault(action, element, operation) @operations[operation.attributes['name']][:fault] = Hash.new action.attributes.each { |name, value| case name when 'name' @operations[operation.attributes['name']][:fault][:name] = value when 'message' @operations[operation.attributes['name']][:fault][:message] = value else warn_ignoring(action, element, name, operation) end } end def process_all_operations(element) element.find_all { |e| e.class == REXML::Element }.each do |operation| case operation.name when "operation" @operations[operation.attributes['name']] = Hash.new store_attributes(element, operation) operation.find_all { |e| e.class == REXML::Element }.each do |action| case action.name when "input" store_input(action, element, operation) when "output" store_output(action, element, operation) when "fault" store_fault(action, element, operation) else warn "Ignoring element '#{action.name}' in operation '#{operation.attributes['name']}' for portType '#{element.attributes['name']}'" end end else warn "Ignoring element '#{operation.name}' in portType '#{element.attributes['name']}'" end end end def warn_ignoring(action, element, name, operation) warn "Ignoring attribute '#{name}' in #{action.name} '#{action.attributes['name']}' in operation '#{operation.attributes['name']}' for portType '#{element.attributes['name']}'" end end end end
require 'test_helper' class PetsControllerTest < ActionDispatch::IntegrationTest setup do @pet = pets(:one) end test "should get index" do get pets_url, as: :json assert_response :success end test "should create pet" do assert_difference('Pet.count') do post pets_url, params: { pet: { attention: @pet.attention, hunger: @pet.hunger, hygiene: @pet.hygiene, name: @pet.name, user_id: @pet.user_id } }, as: :json end assert_response 201 end test "should show pet" do get pet_url(@pet), as: :json assert_response :success end test "should update pet" do patch pet_url(@pet), params: { pet: { attention: @pet.attention, hunger: @pet.hunger, hygiene: @pet.hygiene, name: @pet.name, user_id: @pet.user_id } }, as: :json assert_response 200 end test "should destroy pet" do assert_difference('Pet.count', -1) do delete pet_url(@pet), as: :json end assert_response 204 end end
class BatchDefinitions::LaunchEmrCluster < BatchDefinition def initialize() super("launchemr", "BatchLaunchEMRCluster", [Properties::Dynamo.new().withCreateBatchManifestTable(), Properties::LaunchEmr], ["lambda-emr-launch"]) end end
class AddFlagFct280ToMpoints < ActiveRecord::Migration[5.0] def change add_column :mvalues, :fct280, :boolean end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe SentenceHelper, type: :helper do context ".smart_sentence" do let(:wrapper) { ->(k) { k } } let(:options) { {} } let(:sentence) { [] } subject { helper.smart_sentence(sentence, options, wrapper) } it { is_expected.to eq "" } context do let(:sentence) { [1, 2, 3] } it { is_expected.to eq "1, 2, and 3" } end context do let(:sentence) { [1, 2, 3, 4, 5, 6, 7, 8] } it { is_expected.to eq "1, 2, 3, 4, and other" } end context do let(:sentence) { [1, 2, 3, 4, 5, 6, 7, 8] } let(:options) { { count: 2, two_words_connector: ' with ' } } it { is_expected.to eq "1 with other" } end context do let(:sentence) { [1, 2, 3, 4, 5, 6, 7, 8] } let(:options) { { count: 3, other: 'more', words_connector: '; ', last_word_connector: ' ... ' } } it { is_expected.to eq "1; 2 ... more" } end context("", skip: 'uniq should be before counting') do let(:sentence) { [1, 1, 2, 2, 3, 3, 4, 4] } let(:options) { { count: 3, uniq: true } } it { is_expected.to eq "1, 2, and other" } end context do before do without_partial_double_verification do allow(helper).to receive(:display_name).and_return(1, 2, 3, 4, 5, 6, 7) end end let(:wrapper) { nil } let(:sentence) { %w[a b c d e f g] } it { is_expected.to eq "1, 2, 3, 4, and other" } end context do before do without_partial_double_verification do allow(helper).to receive(:display_link_to).and_return(1, 2, 3, 4, 5, 6, 7) end end let(:wrapper) { nil } let(:options) { { links: true } } let(:sentence) { %w[a b c d e f g] } it { is_expected.to eq "1, 2, 3, 4, and other" } end end context ".smart_sanitize" do it { expect(helper.smart_sanitize("1234567890123456789012345678901234567890123456789012345678901234567890")).to eq("123456789012345678901234567890123456...678901234567890") } it { expect(helper.smart_sanitize("123456789012345678", 10)).to eq("12345678...678") } it { expect(helper.smart_sanitize("https://example.com")).to eq("example.com") } it { expect(helper.smart_sanitize("http://example.com:80")).to eq("example.com") } it { expect(helper.smart_sanitize("123456789012345678")).to eq("123456789012345678") } it { expect(helper.smart_sanitize("123456789012345678", 1)).to eq("1...8") } it { expect(helper.smart_sanitize("123456789012345678", 0)).to eq("123456789012345678") } end end
#This file provides the basic environment for cucumber steps to work with. #Permits use of the project's libraries in step definitions. $LOAD_PATH << File.expand_path('../../lib', __FILE__)
class CloudspaceChat::HandleMessages < ApplicationController # connect a user and give them permission to post def connect @current_room_user = CloudspaceChat::CurrentRoomUser.find_by_user_id_and_room_id(current_user.id, params[:room_id]) if @current_room_user.nil? @current_room_user = CloudspaceChat::CurrentRoomUser.create( :room_id => params[:room_id], :user_id => current_user.id, :connected => false, :allowed => true, :banned => false) end current_room_user_hash = @current_room_user.connect_and_generate_hash respond_to do |format| if current_room_user_hash format.json { render :json => { :user_hash => current_room_user_hash } } else format.json { render :json => { :error => "A user hash could not be created" } } end end end def disconnect @current_room_user = CloudspaceChat::CurrentRoomUser.find_by_user_hash(params[:user_hash]) @current_room_user.disconnect_user_and_remove_hash end # the user validation check on the hash should probably be done in a before filter def send_message @current_room_user = CloudspaceChat::CurrentRoomUser.find_by_user_hash(params[:user_hash]) respond_to do |format| if @current_room_user.user_id == current_user.id @message = CloudspaceChat::Message.new(:current_room_user_id => @current_room_user.id, :input_text => params[:message]) if(@message.save) format.json { render :json => { :message_id => @message.id, :message_text => @message.output_text } } else format.json { render :json => { :error => "The message could not be saved." } } end else format.json { render :json => { :error => "The user could not be found." } } end end end # the user validation check on the hash should probably be done in a before filter def get_messages_since_timestamp(timestamp) @current_room_user = CloudspaceChat::CurrentRoomUser.find_by_user_hash(params[:user_hash]) respond_to do |format| if @current_room_user.user_id == current_user.id if params[:timestamp] == "undefined" created_at = 1.year.ago else created_at = Time.at(params[:timestamp].to_i/1000).localtime end # this could be written much better @messages = CloudspaceChat::Message.created_after(created_at) @output_messages = {} @messages.each do |message| # id is listed twice here becuase I am not sure which one will be more useful @output_messages[message.id] = { :id => message.id, :text => message.output_text, :user_name => message.current_room_user.user.name } end format.json { render :json => @output_messages } else format.json { render :json => { :error => "The user could not be found." } } end end end end
require("minitest/autorun") require("minitest/rg") require_relative("../bank_account.rb") class TestBankAccount < MiniTest::Test def setup() @account = BankAccount.new("Ally", 500, "Business") end def test_account_name() assert_equal("Ally", @account.holder_name()) end def test_account_balance() assert_equal(500, @account.balance()) end def test_account_type() assert_equal("Business", @account.type()) end def test_change_account_name() @account.set_holder_name("Upul") assert_equal("Upul", @account.holder_name()) end def test_change_balance() @account.set_balance(600) assert_equal(600, @account.balance()) end def test_change_account_type() @account.set_type("Personal") assert_equal("Personal", @account.type()) end def test_pay_into_account() @account.pay_in(1000) assert_equal(1500, @account.balance()) end def test_monthly_fee_business() @account.pay_monthly_fee() assert_equal(450, @account.balance()) end def test_monthly_fee_personal() personal_account = BankAccount.new("Alan", 20, "Personal") #only using personal_account in one test so don't need @ personal_account.pay_monthly_fee() assert_equal(20, personal_account.balance()) end end
class LatestBloodPressuresPerPatientPerQuarter < ApplicationRecord include BloodPressureable scope :with_hypertension, -> { where("medical_history_hypertension = ?", "yes") } def self.refresh Scenic.database.refresh_materialized_view(table_name, concurrently: true, cascade: false) end belongs_to :patient end
class AppointmentsController < ApplicationController def show @appointment = Appointment.find(params[:id]) end def new @appointment = Appointment.new @appointment.doctor.build @appointment.patient.build end def create appointment = Appointment.create(appointment_params) redirect_to appointment end private def appointment_params params.require(:appointment).permit(:appointment_datetime, doctor_attributes: [:name, :department], patient_attributes: [:name, :age]) end end
class AddBannedToIdentities < ActiveRecord::Migration[6.0] def up add_column :identities, :banned, :boolean, :null => false, :default => :false end def down remove_column :identities, :banned end end
class PostsController < ApplicationController before_action :set_user before_action :set_event def index json_response(Post.all) end def create @event.posts.create!(user_id: @user.id, content: params[:content], image_url: params[:image_url]) json_response(@event, :created) end def destroy post = Post.find(params[:id]) post.destroy head :no_content end def get_all_by_user res = Post.where(user_id: params[:user_id]) json_response(res) end def get_all_by_event res = Post.where(event_id: params[:event_id]) json_response(res) end private def set_user @user = User.find_by(id: params[:user_id]) end def set_event @event = Event.find_by(id: params[:event_id]) end end
class GeneralExpenses::LoansController < ApplicationController before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ] protect_from_forgery with: :null_session, :only => [:destroy, :delete] def new @costcenters = CostCenter.where('id not in ('+ params[:cc_id]+')') @cc = CostCenter.find(params[:cc_id]) rescue nil @loan = Loan.new render layout: false end def create render json: {:cc_id=>loan.cost_center_lender_id.to_s} end def create_loan flash[:error] = nil loan = Loan.new(loan_params) if loan.save loan.errors.messages.each do |attribute, error| flash[:error] = flash[:error].to_s + error.to_s + " " end end render json: {:cc_id=>loan.cost_center_lender_id.to_s} end def update loan = Loan.find(params[:id]) if loan.update_attributes(loan_params) flash[:notice] = "Se ha actualizado correctamente los datos." redirect_to :action => :index, :controller => "loans" else con.errors.messages.each do |attribute, error| flash[:error] = attribute " " + flash[:error].to_s + error.to_s + " " end # Load new() @loan = loan render :edit, layout: false end end def display_workers if params[:element].nil? word = params[:q] else word = params[:element] end workers_hash = Array.new if params[:element].nil? workers = ActiveRecord::Base.connection.execute(" SELECT w.id, e.name, e.paternal_surname, e.maternal_surname, e.dni FROM workers w, entities e WHERE ( e.name LIKE '%#{word}%' || e.paternal_surname LIKE '%#{word}%' || e.maternal_surname LIKE '%#{word}%' || e.dni LIKE '%#{word}%') AND w.entity_id = e.id GROUP BY e.id" ) else workers = ActiveRecord::Base.connection.execute(" SELECT w.id, e.name, e.paternal_surname, e.maternal_surname, e.dni FROM workers w, entities e WHERE w.entity_id = e.id AND w.id = #{word} GROUP BY e.id" ) end workers.each do |art| workers_hash << {'name' => art[1],"paternal_surname"=> art[2],"maternal_surname"=> art[3],"id"=> art[0],"dni"=> art[4]} end render json: {:workers => workers_hash} end def edit @cc1 = params[:cc1] @cc2 = params[:cc2] @cc3 = params[:cc3] @costcenters = CostCenter.all @loan = Loan.find(params[:id]) @action = 'edit' render layout: false end def destroy loan = Loan.destroy(params[:id]) flash[:notice] = "Se ha eliminado correctamente el pedido seleccionado." render :json => loan end def index @cc = CostCenter.find(params[:cc_id]) @presto = Loan.where('cost_center_lender_id=?', @cc.id) @prestaron = Loan.where('cost_center_beneficiary_id=?', @cc.id) @ledeben = Array.new @debe = Array.new ledeben = ActiveRecord::Base.connection.execute(" SELECT cost_center_beneficiary_id FROM loans WHERE cost_center_lender_id ="+@cc.id.to_s+" GROUP BY cost_center_beneficiary_id ") ledeben.each do |ld| aldp=0 aldd=0 ldp = ActiveRecord::Base.connection.execute(" SELECT Sum(amount) FROM loans WHERE cost_center_lender_id ="+@cc.id.to_s+" AND cost_center_beneficiary_id = "+ld[0].to_s+" AND state = 1 ") ldp.each do |ldp| aldp=ldp[0] end ldd = ActiveRecord::Base.connection.execute(" SELECT Sum(amount) FROM loans WHERE cost_center_lender_id ="+@cc.id.to_s+" AND cost_center_beneficiary_id = "+ld[0].to_s+" AND state = 2 ") ldd.each do |ldp| aldd=ldp[0] end @ledeben << [ld[0].to_s,aldp,aldd] end debe = ActiveRecord::Base.connection.execute(" SELECT cost_center_lender_id FROM loans WHERE cost_center_beneficiary_id ="+@cc.id.to_s+" GROUP BY cost_center_lender_id ") debe.each do |ld| aldp=0 aldd=0 ldp = ActiveRecord::Base.connection.execute(" SELECT Sum(amount) FROM loans WHERE cost_center_beneficiary_id ="+@cc.id.to_s+" AND cost_center_lender_id = "+ld[0].to_s+" AND state = 1 ") ldp.each do |ldp| aldp=ldp[0] end ldd = ActiveRecord::Base.connection.execute(" SELECT Sum(amount) FROM loans WHERE cost_center_beneficiary_id ="+@cc.id.to_s+" AND cost_center_lender_id = "+ld[0].to_s+" AND state = 2 ") ldd.each do |ldp| aldd=ldp[0] end @debe << [ld[0].to_s,aldp,aldd] end render layout: false end def show @type = params[:type] @cost_center1 = CostCenter.find(params[:cc1]) @cost_center2 = CostCenter.find(params[:cc2]) @cc = params[:cc3] @loan = Loan.where("cost_center_lender_id = ? AND cost_center_beneficiary_id = ?",@cost_center1.id, @cost_center2.id) @total = 0 @devuelto = 0 @loan.each do |loan| @total+= loan.amount if loan.state == "2" @devuelto += loan.amount end end render layout: false end def show_details @loan= Loan.find(params[:id]) @num = params[:num] render(partial: 'show_detail', :layout => false) end def report_pdf respond_to do |format| format.html format.pdf do @todo = Array.new cc_lender_in_loan = ActiveRecord::Base.connection.execute("SELECT DISTINCT cost_center_lender_id FROM loans").to_a cc_beneficiary_in_loan = ActiveRecord::Base.connection.execute("SELECT DISTINCT cost_center_beneficiary_id FROM loans").to_a total_cc = cc_lender_in_loan + cc_beneficiary_in_loan total_cc = total_cc.uniq.join(',') @ccs = CostCenter.where("id IN (" + total_cc.to_s+")").order(:code) @ccs.each do |cc| flag1 =true flag2 =true @array_le_deben = Array.new @array_debe = Array.new suma_total = 0 suma_total_le_deben = 0 suma_total_debe = 0 lender = ActiveRecord::Base.connection.execute(" SELECT cc.id, CONCAT(cc.code, ' - ', cc.name), SUM(l.amount) FROM loans l, cost_centers cc WHERE cost_center_lender_id ="+cc.id.to_s+" AND cost_center_beneficiary_id = cc.id GROUP BY cost_center_beneficiary_id ") lender.each do |l| suma_devuelto = 0 suma_pendiente = 0 suma_total += l[2].to_f montos = ActiveRecord::Base.connection.execute(" SELECT SUM(l.amount), l.state FROM loans l WHERE cost_center_lender_id = "+cc.id.to_s+" AND cost_center_beneficiary_id = "+l[0].to_s+" GROUP BY l.state ") montos.each do |m| if m[1].to_i == 2 suma_devuelto+=m[0].to_f elsif m[1].to_i == 1 suma_total_le_deben += m[0].to_f suma_pendiente += m[0].to_f end end @array_le_deben << [l[1].to_s, l[2].to_f, suma_devuelto.to_f, suma_pendiente.to_f, "lender_detail"] end beneficiary = ActiveRecord::Base.connection.execute(" SELECT cc.id, CONCAT(cc.code, ' - ', cc.name), SUM(l.amount) FROM loans l, cost_centers cc WHERE cost_center_lender_id = cc.id AND cost_center_beneficiary_id = "+cc.id.to_s+" GROUP BY cost_center_lender_id ") beneficiary.each do |b| suma_devuelto = 0 suma_pendiente = 0 suma_total -= b[2].to_f montos = ActiveRecord::Base.connection.execute(" SELECT SUM(l.amount), l.state FROM loans l WHERE cost_center_lender_id = "+b[0].to_s+" AND cost_center_beneficiary_id = "+cc.id.to_s+" GROUP BY l.state ") montos.each do |m| if m[1].to_i == 2 suma_devuelto+=m[0].to_f elsif m[1].to_i == 1 suma_total_debe += m[0].to_f suma_pendiente += m[0].to_f end end @array_debe << [b[1].to_s, b[2].to_f, suma_devuelto.to_f, suma_pendiente.to_f, "beneficiary_detail"] end @todo << [cc.code+" - "+cc.name, suma_total, suma_total_le_deben, suma_total_debe, "main"] if lender.count != 0 @todo << ["Centro de Costo Beneficiaro", "Total", "Devuelto", "Pendiente","lender_detail_header"] @todo += @array_le_deben flag1 = false end if beneficiary.count != 0 @todo << ["Centro de Costo al que se debe", "Total", "Devuelto", "Pendiente","beneficiary_detail_header"] @todo += @array_debe flag2 = false end if flag1 && flag2 @todo << ["NO SE REGISTRARON MOVIMIENTOS DE ESTE CENTRO DE COSTO "," "," "," ","blank2"] end @todo << [" "," "," "," ","blank"] end @todo.delete_at(@todo.length-1) render :pdf => "reporte_movimientos-#{Time.now.strftime('%d-%m-%Y')}", :template => 'general_expenses/loans/report_pdf.pdf.haml', :orientation => 'Landscape', :page_size => 'A4' end end end def bidimensional_report_pdf respond_to do |format| format.html format.pdf do @todo = Array.new @ccs = CostCenter.all.order(:id) @todo << ["CUADRO COMPARATIVO"] i = 1 @ccs.each do |ccr| @todo << [ccr.name] @ccs.each do |ccc| if ccr.id == ccc.id @todo[i] << "es el mismo" if !@todo[0].include?(ccc.name) @todo[0] << ccc.name.to_s end else lender_am = 0 bene_am = 0 if !@todo[0].include?(ccc.name) @todo[0] << ccc.name.to_s end lender = ActiveRecord::Base.connection.execute(" SELECT SUM(l.amount) FROM loans l WHERE cost_center_lender_id ="+ccr.id.to_s+" AND cost_center_beneficiary_id = "+ccc.id.to_s+" AND state = 1 GROUP BY cost_center_beneficiary_id ") if lender.count == 0 lender_am = 0 else lender_am = lender.first[0].to_f end beneficiary = ActiveRecord::Base.connection.execute(" SELECT SUM(l.amount) FROM loans l WHERE cost_center_lender_id = "+ccc.id.to_s+" AND cost_center_beneficiary_id = "+ccr.id.to_s+" AND state = 1 GROUP BY cost_center_beneficiary_id ") if beneficiary.count == 0 bene_am = 0 else bene_am = beneficiary.first[0] end diferencia = lender_am - bene_am @todo[i] << [lender_am.to_s , bene_am.to_s, diferencia.to_s] end end i+=1 end render :pdf => "reporte_movimientos-#{Time.now.strftime('%d-%m-%Y')}", :template => 'general_expenses/loans/bidimensional_report_pdf.pdf.haml', :orientation => 'Landscape', :page_size => 'A4' end end end private def loan_params params.require(:loan).permit(:person,:loan_date,:loan_type, :loan_doc, :refund_doc, :amount,:description,:refund_type,:check_number,:check_date,:state,:refund_date,:cost_center_beneficiary_id,:cost_center_lender_id) end end
# encoding: US-ASCII require 'fs/ext4/group_descriptor_table' require 'fs/ext4/inode' require 'binary_struct' require 'uuidtools' require 'stringio' require 'memory_buffer' require 'rufus/lru' module Ext4 # //////////////////////////////////////////////////////////////////////////// # // Data definitions. Linux 2.6.2 from Fedora Core 6. SUPERBLOCK = BinaryStruct.new([ 'L', 'num_inodes', # Number of inodes in file system. 'L', 'num_blocks', # Number of blocks in file system. 'L', 'reserved_blocks', # Number of reserved blocks to prevent file system from filling up. 'L', 'unallocated_blocks', # Number of unallocated blocks. 'L', 'unallocated_inodes', # Number of unallocated inodes. 'L', 'block_group_zero', # Block where block group 0 starts. 'L', 'block_size', # Block size (saved as num bits to shift 1024 left). 'L', 'fragment_size', # Fragment size (saved as num bits to shift 1024 left). 'L', 'blocks_in_group', # Number of blocks in each block group. 'L', 'fragments_in_group', # Number of fragments in each block group. 'L', 'inodes_in_group', # Number of inodes in each block group. 'L', 'last_mount_time', # Time FS was last mounted. 'L', 'last_write_time', # Time FS was last written to. 'S', 'mount_count', # Current mount count. 'S', 'max_mount_count', # Maximum mount count. 'S', 'signature', # Always 0xef53 'S', 'fs_state', # File System State: see FSS_ below. 'S', 'err_method', # Error Handling Method: see EHM_ below. 'S', 'ver_minor', # Minor version number. 'L', 'last_check_time', # Last consistency check time. 'L', 'forced_check_int', # Forced check interval. 'L', 'creator_os', # Creator OS: see CO_ below. 'L', 'ver_major', # Major version: see MV_ below. 'S', 'uid_res_blocks', # UID that can use reserved blocks. 'S', 'gid_res_blocks', # GID that can uss reserved blocks. # Begin dynamic version fields 'L', 'first_inode', # First non-reserved inode in file system. 'S', 'inode_size', # Size of each inode. 'S', 'block_group', # Block group that this superblock is part of (if backup copy). 'L', 'compat_flags', # Compatible feature flags (see CFF_ below). 'L', 'incompat_flags', # Incompatible feature flags (see ICF_ below). 'L', 'ro_flags', # Read Only feature flags (see ROF_ below). 'a16', 'fs_id', # File system ID (UUID or GUID). 'a16', 'vol_name', # Volume name. 'a64', 'last_mnt_path', # Path where last mounted. 'L', 'algo_use_bmp', # Algorithm usage bitmap. # Performance hints 'C', 'file_prealloc_blks', # Blocks to preallocate for files. 'C', 'dir_prealloc_blks', # Blocks to preallocate for directories. 'S', 'unused1', # Unused. # Journal support 'a16', 'jrnl_id', # Joural ID (UUID or GUID). 'L', 'jrnl_inode', # Journal inode. 'L', 'jrnl_device', # Journal device. 'L', 'orphan_head', # Head of orphan inode list. 'a16', 'hash_seed', # HTREE hash seed. This is actually L4 (__u32 s_hash_seed[4]) 'C', 'hash_ver', # Default hash version. 'C', 'unused2', 'S', 'group_desc_size', # Group descriptor size. 'L', 'mount_opts', # Default mount options. 'L', 'first_meta_blk_grp', # First metablock block group. 'a360', 'reserved' # Unused. ]) SUPERBLOCK_SIG = 0xef53 SUPERBLOCK_OFFSET = 1024 SUPERBLOCK_SIZE = 1024 GDE_SIZE = 32 # default group descriptor size. INODE_SIZE = 128 # Default inode size. # //////////////////////////////////////////////////////////////////////////// # // Class. class Superblock # Default cache sizes. DEF_BLOCK_CACHE_SIZE = 50 DEF_INODE_CACHE_SIZE = 50 # File System State. FSS_CLEAN = 0x0001 # File system is clean. FSS_ERR = 0x0002 # File system has errors. FSS_ORPHAN_REC = 0x0004 # Orphan inodes are being recovered. # NOTE: Recovered NOT by this software but by the 'NIX kernel. # IOW start the VM to repair it. FSS_END = FSS_CLEAN | FSS_ERR | FSS_ORPHAN_REC # Error Handling Method. EHM_CONTINUE = 1 # No action. EHM_RO_REMOUNT = 2 # Remount file system as read only. EHM_PANIC = 3 # Don't mount? halt? - don't know what this means. # Creator OS. CO_LINUX = 0 # NOTE: FS creation tools allow setting this value. CO_GNU_HURD = 1 # These values are supposedly defined. CO_MASIX = 2 CO_FREE_BSD = 3 CO_LITES = 4 # Major Version. MV_ORIGINAL = 0 # NOTE: If version is not dynamic, then values from MV_DYNAMIC = 1 # first_inode on may not be accurate. # Compatible Feature Flags. CFF_PREALLOC_DIR_BLKS = 0x0001 # Preallocate directory blocks to reduce fragmentation. CFF_AFS_SERVER_INODES = 0x0002 # AFS server inodes exist in system. CFF_JOURNAL = 0x0004 # File system has journal (Ext3). CFF_EXTENDED_ATTRIBS = 0x0008 # Inodes have extended attributes. CFF_BIG_PART = 0x0010 # File system can resize itself for larger partitions. CFF_HASH_INDEX = 0x0020 # Directories use hash index (another modified b-tree). CFF_FLAGS = (CFF_PREALLOC_DIR_BLKS | CFF_AFS_SERVER_INODES | CFF_JOURNAL | CFF_EXTENDED_ATTRIBS | CFF_BIG_PART | CFF_HASH_INDEX) # Incompatible Feature flags. ICF_COMPRESSION = 0x0001 # Not supported on Linux? ICF_FILE_TYPE = 0x0002 # Directory entries contain file type field. ICF_RECOVER_FS = 0x0004 # File system needs recovery. ICF_JOURNAL = 0x0008 # File system uses journal device. ICF_META_BG = 0x0010 # ICF_EXTENTS = 0x0040 # File system uses extents (ext4) ICF_64BIT = 0x0080 # File system uses 64-bit ICF_MMP = 0x0100 # ICF_FLEX_BG = 0x0200 # ICF_EA_INODE = 0x0400 # EA in inode ICF_DIRDATA = 0x1000 # data in dirent ICF_FLAGS = (ICF_COMPRESSION | ICF_FILE_TYPE | ICF_RECOVER_FS | ICF_JOURNAL | ICF_META_BG | ICF_EXTENTS | ICF_64BIT | ICF_MMP | ICF_FLEX_BG | ICF_EA_INODE | ICF_DIRDATA) # ReadOnly Feature flags. ROF_SPARSE = 0x0001 # Sparse superblocks & group descriptor tables. ROF_LARGE_FILES = 0x0002 # File system contains large files (over 4G). ROF_BTREES = 0x0004 # Directories use B-Trees (not implemented?). ROF_HUGE_FILE = 0x0008 # ROF_GDT_CSUM = 0x0010 # ROF_DIR_NLINK = 0x0020 # ROF_EXTRA_ISIZE = 0x0040 # ROF_FLAGS = (ROF_SPARSE | ROF_LARGE_FILES | ROF_BTREES | ROF_HUGE_FILE | ROF_GDT_CSUM | ROF_DIR_NLINK | ROF_EXTRA_ISIZE) # ///////////////////////////////////////////////////////////////////////// # // initialize attr_reader :numGroups, :fsId, :stream, :numBlocks, :numInodes, :volName attr_reader :sectorSize, :blockSize @@track_inodes = false def initialize(stream) raise "Ext4::Superblock.initialize: Nil stream" if (@stream = stream).nil? # Seek, read & decode the superblock structure @stream.seek(SUPERBLOCK_OFFSET) @sb = SUPERBLOCK.decode(@stream.read(SUPERBLOCK_SIZE)) # Grab some quick facts & make sure there's nothing wrong. Tight qualification. raise "Ext4::Superblock.initialize: Invalid signature=[#{@sb['signature']}]" if @sb['signature'] != SUPERBLOCK_SIG raise "Ext4::Superblock.initialize: Invalid file system state" if @sb['fs_state'] > FSS_END if (state = @sb['fs_state']) != FSS_CLEAN $log.warn("Ext4 file system has errors") if $log && gotBit?(state, FSS_ERR) $log.warn("Ext4 orphan inodes being recovered") if $log && gotBit?(state, FSS_ORPHAN_REC) end raise "Ext4::Superblock.initialize: Invalid error handling method=[#{@sb['err_method']}]" if @sb['err_method'] > EHM_PANIC @blockSize = 1024 << @sb['block_size'] @block_cache = LruHash.new(DEF_BLOCK_CACHE_SIZE) @inode_cache = LruHash.new(DEF_INODE_CACHE_SIZE) # expose for testing. @numBlocks = @sb['num_blocks'] @numInodes = @sb['num_inodes'] # Inode file size members can't be trusted, so use sector count instead. # MiqDisk exposes blockSize, which for our purposes is sectorSize. @sectorSize = @stream.blockSize # Preprocess some members. @sb['vol_name'].delete!("\000") @sb['last_mnt_path'].delete!("\000") @numGroups, @lastGroupBlocks = @sb['num_blocks'].divmod(@sb['blocks_in_group']) @numGroups += 1 if @lastGroupBlocks > 0 @fsId = UUIDTools::UUID.parse_raw(@sb['fs_id']) @volName = @sb['vol_name'] end # //////////////////////////////////////////////////////////////////////////// # // Class helpers & accessors. def gdt @gdt ||= GroupDescriptorTable.new(self) end def isDynamic? @sb['ver_major'] == MV_DYNAMIC end def isNewDirEnt? gotBit?(@sb['incompat_flags'], ICF_FILE_TYPE) end def fragmentSize 1024 << @sb['fragment_size'] end def blocksPerGroup @sb['blocks_in_group'] end def fragmentsPerGroup @sb['fragments_in_group'] end def inodesPerGroup @sb['inodes_in_group'] end def inodeSize isDynamic? ? @sb['inode_size'] : INODE_SIZE end def is_enabled_64_bit? @is_enabled_64_bit ||= gotBit?(@sb['incompat_flags'], ICF_64BIT) end def groupDescriptorSize @groupDescriptorSize ||= is_enabled_64_bit? ? @sb['group_desc_size'] : GDE_SIZE end def freeBytes @sb['unallocated_blocks'] * @blockSize end def blockNumToGroupNum(block) unless block.kind_of?(Numeric) $log.error("Ext4::Superblock.blockNumToGroupNum called from: #{caller.join('\n')}") raise "Ext4::Superblock.blockNumToGroupNum: block is expected to be numeric, but is <#{block.class.name}>" end group = (block - @sb['block_group_zero']) / @sb['blocks_in_group'] offset = block.modulo(@sb['blocks_in_group']) return group, offset end def firstGroupBlockNum(group) group * @sb['blocks_in_group'] + @sb['block_group_zero'] end def inodeNumToGroupNum(inode) (inode - 1).divmod(inodesPerGroup) end def blockToAddress(block) address = block * @blockSize address += (SUPERBLOCK_SIZE + groupDescriptorSize * @numGroups) if address == SUPERBLOCK_OFFSET address end def isValidInode?(inode) group, offset = inodeNumToGroupNum(inode) gde = gdt[group] gde.inodeAllocBmp[offset] end def isValidBlock?(block) group, offset = blockNumToGroupNum(block) gde = gdt[group] gde.blockAllocBmp[offset] end # Ignore allocation is for testing only. def getInode(inode, _ignore_alloc = false) unless @inode_cache.key?(inode) group, offset = inodeNumToGroupNum(inode) gde = gdt[group] # raise "Inode #{inode} is not allocated" if (not gde.inodeAllocBmp[offset] and not ignore_alloc) @stream.seek(blockToAddress(gde.inodeTable) + offset * inodeSize) @inode_cache[inode] = Inode.new(@stream.read(inodeSize), self, inode) $log.info "Inode num: #{inode}\n#{@inode_cache[inode].dump}\n\n" if $log && @@track_inodes end @inode_cache[inode] end # Ignore allocation is for testing only. def getBlock(block, _ignore_alloc = false) raise "Ext4::Superblock.getBlock: block is nil" if block.nil? unless @block_cache.key?(block) if block == 0 @block_cache[block] = MemoryBuffer.create(@blockSize) else # raise "Block #{block} is not allocated" if (not gde.blockAllocBmp[offset] and not ignore_alloc) address = blockToAddress(block) # This function will read the block into our cache @stream.seek(address) @block_cache[block] = @stream.read(@blockSize) end end @block_cache[block] end # //////////////////////////////////////////////////////////////////////////// # // Utility functions. def gotBit?(field, bit) field & bit == bit end # Dump object. end end # moule Ext4
module SQLHelpers # # This is useful for breaking up the recording time in various time-periods in SQL. # It takes the recorded_at (timestamp without timezone) and truncates it to the beginning of the month. # # Following is the series of transformations it applies to truncate it in right timezone: # # * Interpret the "timestamp without timezone" in the DB timezone (UTC). # * Converts it to a "timestamp with timezone" the country timezone. # * Truncates it to a month (this returns a "timestamp without timezone") # * Converts it back to a "timestamp with timezone" in the country timezone # # FAQ: # # Q. Why should we cast the truncate into a timestamp with timezone at all? Don't we just end up with day/month? # # A. DATE_TRUNC returns a "timestamp without timezone" not a month/day/quarter. If it's used in a "where" # clause for comparison, the timezone will come into effect and is valuable to be kept correct so as to not run into # time-period-boundary issues. # # Usage: # BloodPressure.date_to_period_sql('blood_pressures.recorded_at', :month) # def date_to_period_sql(time_col_with_model_name, period) tz = Time.zone.name "(DATE_TRUNC('#{period}', (#{time_col_with_model_name}::timestamptz) AT TIME ZONE '#{tz}')) AT TIME ZONE '#{tz}'" end end
module Finance module PortfolioStatisticsGenerator extend self def statistics_for_allocation(allocation, return_source=:implied_return) securities_hash = summarize_security_data_for(allocation, return_source) expected_return = calculate_expected_return_for(securities_hash) expected_std_dev = calculate_expected_std_dev_for(securities_hash) return { expected_return: expected_return, expected_std_dev: expected_std_dev, annual_nominal_return: ( (1 + expected_return) ** 52 - 1 ) + 0.02, annual_std_dev: expected_std_dev * Math.sqrt(52) } end private def summarize_security_data_for(allocation, return_source) tickers = allocation.keys.sort securities_hash = Security.statistics_for(tickers, return_source).inject({}) do |h, security| h[security[:ticker]] = { weight: allocation[security[:ticker]], mean_return: security[:mean_return], std_dev: security[:std_dev], returns: security[:returns] } h end end def calculate_expected_return_for(securities_hash) securities_hash.reduce(0.0) do |sum, (ticker, data)| sum += data[:weight].to_f * data[:mean_return].to_f end end def calculate_expected_std_dev_for(securities_hash) # Don't need the weights / implied returns etc. for the correlation method. # Pluck out the returns: returns_hash = securities_hash.inject({}) { |h, (k,v)| h[k] = v[:returns]; h} correlation_matrix = Finance::MatrixMethods.correlation(returns_hash) variance = 0.0 securities_hash.each_with_index do |(ticker1, data1), i| securities_hash.each_with_index do |(ticker2, data2), j| variance += data1[:weight].to_f * data2[:weight].to_f * data1[:std_dev].to_f * data2[:std_dev].to_f * correlation_matrix[i,j] end end Math.sqrt(variance) end end end
require "cc/engine/analyzers/command_line_runner" require "timeout" require "json" module CC module Engine module Analyzers module Python class Parser < ParserBase attr_reader :code, :filename, :syntax_tree def initialize(code, filename) @code = code @filename = filename end def parse runner = CommandLineRunner.new(python_command) runner.run(code) do |ast| @syntax_tree = parse_json(ast) end self end def python_command file = File.expand_path(File.dirname(__FILE__)) + '/parser.py' "python #{file}" end end end end end end
class Executive < Employee attr_accessor :percentage DEFAULT_PERCENTAGE = 0.10 def initialize(name, percentage = DEFAULT_PERCENTAGE) @percentage = percentage super name end def pay(profits) total_pay = profits * @percentage end end
require 'spec_helper' require "rails_helper" describe ReviewsController, :type => :controller do context "change_approve_reply" do before do @user1 = create(:user, {email: "dieuit07@gmail.com"}) user2 = create(:user) @admin = create(:user, {admin_role: true}) @restaurant = create(:restaurant, {user_id: @user1.id}) @review1 = create(:review, {user_reply: @user1.id, user_id: user2.id, restaurant_id: @restaurant.id, reply_content: "reply review1"}) end it "case 1: not login, call action, return error" do xhr :post, "change_approve_reply", format: "js", id: @review1.id, approve_reply: 1 response.should redirect_to(new_user_session_path) end it "case 2: login user, call action, redirect to home page" do sign_in @user1 xhr :post, "change_approve_reply", format: "js", id: @review1.id, approve_reply: 1 response.should redirect_to("/") end it "case 3: login admin, call action success" do sign_in @admin xhr :post, "change_approve_reply", format: "js", id: @review1.id, approve_reply: 1 expect(assigns[:review].approve_reply).to eq true xhr :post, "change_approve_reply", format: "js", id: @review1.id, approve_reply: 0 expect(assigns[:review].approve_reply).to eq false assigns[:email].should deliver_to(@user1.email) xhr :post, "change_approve_reply", format: "js", id: @review1.id, approve_reply: 1 expect(assigns[:review].approve_reply).to eq true end end end
#Inspired by Kirupa's Flash Snow flakes (still looking for license) include System::Windows::Shapes include System::Windows::Controls include System::Windows::Media class SnowMaker def initialize(container, maker_options={}) @options = {:total_flakes=>40, :width=>800, :height=>600}.merge!(maker_options) 1.upto(@options[:total_flakes].to_i) do |index| circle = Ellipse.new(@options.merge!(:index=>index)) circle.Fill = SolidColorBrush.new(Colors.White) circle.Stroke = SolidColorBrush.new(Colors.White) container.children.add(circle) yield(circle) if block_given? end end end #monkeypatch Ellipse into a SnowFlake. BECAUSE WE CAN!!!! :) class System::Windows::Shapes::Ellipse def initialize(boundaries={}) @options = {:height=>800, :width=>600}.merge!(boundaries) @@random ||= System::Random.new() @canvas_width = @options[:width].to_i @canvas_height = @options[:height].to_i @x = 1 create() end def create @x_speed = (@@random.next_double/20.0) @y_speed = (0.01 + @@random.next_double * 2.0) @radius = @@random.next_double @scale = (0.01 + @@random.next_double * 2.0) Canvas.set_top(self, @@random.next(@canvas_height)) Canvas.set_left(self, @@random.next(@canvas_width)) @y = Canvas.get_top(self) self.width = (5 * @scale) self.height = (5 * @scale) self.opacity = 0.1 + @@random.next_double CompositionTarget.Rendering{|s, e| move(s, e) } end def move(sender, eventargs) @x += @x_speed @y += @y_speed Canvas.set_top(self, @y) Canvas.set_left(self, (Canvas.get_left(self) + @radius*Math.cos(@x)).to_f) if (Canvas.get_top(self) > @canvas_height): Canvas.set_top(self, 0) @y = Canvas.get_top(self) end end end SnowMaker.new(me.find_name('backyard'))
class Route < ActiveRecord::Base has_many :participants has_many :users, :through => :participants, :source => :user validates :name, :presence => true, :uniqueness => true,:length => {:minimum => 5, :maximum => 70} validates :description, :presence => true, :length => {:minimum => 5, :maximum => 200} validates :country, :presence => true,:length => {:minimum => 3, :maximum => 30} validates :date, :presence => true validates :province, :presence => true validates :city, :presence => true end
class User < ApplicationRecord before_save {email.downcase!} # 省略してかけるが,まだわかりにくいので()つきで書く # validates :name, presence: true validates(:name, presence: true, length: { maximum: 50 } ) VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates(:email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false} ) has_secure_password # セキュアにハッシュ化したパスワードを、データベース内のpassword_digestという属性に保存できるようになる。 # 2つのペアの仮想的な属性 (passwordとpassword_confirmation) が使えるようになる。また、存在性と値が一致するかどうかのバリデーションも追加される。 # authenticateメソッドが使えるようになる (引数の文字列がパスワードと一致するとUserオブジェクトを、間違っているとfalseを返すメソッド) 。 validates(:password, presence: true, length: {minimum: 6} ) end