text
stringlengths
10
2.61M
class AddDownPaymentToTrips < ActiveRecord::Migration def change add_column :trips, :down_payment , :decimal add_column :trips, :down_payment_currency, :string add_column :trips, :booking_fee, :decimal add_column :trips, :booking_fee_currency, :string end end
# frozen_string_literal: true module CMS class SemanticFormBuilder < ::ThreeScale::SemanticFormBuilder def input(method, options = {}) if options.delete(:autofocus) super( method, :input_html => { :autofocus => 'autofocus' }) else super( method, options) end end def section_input(method, options = {}) sections = template.current_account.sections options.reverse_merge! :collection => template.cms_section_select(sections.root), :include_blank => false select_input(method, options).tap do |html| if options[:paths] paths = Hash[sections.partial_paths] html << template.javascript_tag("$.partial_paths(#{paths.to_json});") end end end def handler_input(method, options = {}) handlers = CMS::Handler.available.map { |h| [h.to_s.humanize, h] } options.reverse_merge! :collection => handlers, :include_blank => true select_input(method, options) end def select_input(method, options = {}) if @object.send(method).nil? && @object.new_record? options[:selected] ||= options.delete(:default)&.id end super end def codemirror_input(method, options = {}) html_options = options.delete(:input_html) || {} if value = options.delete(:value) html_options[:value] = value end html_options[:class] = 'mousetrap' codemirror_options = options.delete(:options) || {} label(method, options_for_label(options)) << text_area(method, html_options) << template.render('/provider/admin/cms/codemirror', :html_id => "cms_template_#{method}", :options => codemirror_options, :content_type => object.content_type, :liquid_enabled => object.liquid_enabled) end def delete_button(*args) icon = template.content_tag(:i, '', :class => 'fa fa-trash') button = template.link_to(icon << ' Delete', template.url_for(:action => :destroy), :'data-method' => :delete, :class => 'delete dangerous-button', :title => "Delete this #{@object.class.model_name.human.downcase}", :'data-confirm' => "Do you really want to delete this #{@object.class.model_name.human.downcase}?") template.content_tag(:li, button, :id => 'cms-template-delete-button') end def disabled_delete_button(*args) icon = template.content_tag(:i, '', :class => 'fa fa-trash') button = template.link_to(icon << ' Delete', '', :class => 'delete less-important-button disabled-button', :title => "You can not delete this #{@object.class.model_name.human.downcase} because it's being used") template.content_tag(:li, button, :id => 'cms-template-delete-button') end def commit_button(*args) options = args.extract_options! button_html = options[:button_html] ||= {} unless @object.new_record? button_html.reverse_merge! :title => 'Save the draft' options[:label] ||= "Save" end button_html[:class] ||= 'important-button' args << options # ruby 1.8 super(*args) end def publish_button(*args) options = args.extract_options! button_html = options.delete(:button_html) || {} button_html.reverse_merge! :title => 'Save and publish the current draft.', :type => :submit, :name => :publish, :value => true, :class => 'less-important-button' template.content_tag(:button, 'Publish', button_html) end def hide_button(*args) options = args.extract_options! button_html = options.delete(:button_html) || {} button_html.reverse_merge! :class => 'hide', :title => 'Unpublishes the page. User would receive a 404 when trying to access its path. ', :type => :submit, :name => :hide, :value => true template.content_tag(:button, 'Hide', button_html) end def save_as_version_button(*args) options = args.extract_options! # TODO: Save Page as version text = options.delete(:label) || args.shift || "Save as Version" button_html = options.delete(:button_html) || {} button_html.merge! :class => 'save_as_version', :title => 'Saves current draft in a version history without publishing it.', :type => :submit, :name => :version, :value => true button = template.content_tag(:button, text, button_html) template.content_tag(:li, button, :class => :save_as_version) end end end
# == Schema Information # # Table name: events # # id :integer not null, primary key # title :string # description :text # starts_at :datetime # ends_at :datetime # venue_name :string # venue_address :string # venue_url :string # sponsor_name :string # sponsor_url :string # contact_name :string # contact_email :string # tickets_price :string # tickets_details :string # tickets_url :string # created_at :datetime not null # updated_at :datetime not null # deleted :boolean # recurring :boolean # recurring_duration :string # recurring_source_id :integer # facebook_url :string # class Event < ApplicationRecord scope :for_date, ->(date){ where("starts_at BETWEEN ? AND ?", date.beginning_of_day, date.end_of_day)} scope :for_week, ->(date){ where("starts_at BETWEEN ? AND ?", date.beginning_of_week, date.end_of_week)} scope :starts_after, ->(datetime){ where("starts_at >= ?", datetime) } scope :not_deleted, ->{ where("deleted IS NULL OR deleted = ?", false)} validates :title, presence: true validates :title, length: { maximum: 150 } validates :description, length: { maximum: 750 } validates :starts_at, presence: true validate :ends_after_start_time after_create :create_future_recurring_events!, if: :recurring? has_many :event_recursions, class_name: "Event", foreign_key: "recurring_source_id" def self.event_dates pluck(:starts_at).map(&:to_date).uniq end private def create_future_recurring_events! (1..20).each do |index| if recurring_duration == "week" new_start_time = starts_at + index.weeks new_end_time = ends_at + index.weeks elsif recurring_duration == "month" new_start_time = starts_at + index.months new_end_time = ends_at + index.months end break if new_start_time.beginning_of_month >= Time.now.beginning_of_month + 3.months attrs = attributes.except("recurring", "recurring_duration", "starts_at", "ends_at", "id") attrs.merge!(starts_at: new_start_time, ends_at: new_end_time, recurring_source_id: id) Event.create(attrs) end end def ends_after_start_time return if ends_at.nil? || ends_at >= starts_at raise "ends_at time must be after starts_at time" end end
require 'rails_helper' describe "Admin view of user list" do before { login_as user1 } let(:user1) { create :user, admin: true} let!(:user2) { create :user } it "shows all user names on index" do visit admin_users_path expect(page).to have_text(user1.full_name) expect(page).to have_text(user2.full_name) end end
#copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email class AuthenticationTokenStrategy < ::Warden::Strategies::Base def valid? user_email_from_headers.present? && auth_token_from_headers.present? end def authenticate! failure_message = "Authentication failed for user/token" user = User.find_by(email: user_email_from_headers) return fail!(failure_message) unless user token = TokenIssuer.build.find_token(user, auth_token_from_headers) if token touch_token(token) return success!(user) end fail!(failure_message) end def store? false end private def user_email_from_headers env["HTTP_X_USER_EMAIL"] end def auth_token_from_headers env["HTTP_X_AUTH_TOKEN"] end def touch_token(token) token.update_attribute(:last_used_at, DateTime.current) if token.last_used_at < 1.hour.ago end end
module UploadImageRetainLowQuality class Console # Class Methods class << self def gets_from_stdin(message = nil) print "#{message}: " unless message.nil? str = STDIN.gets.chomp end def get_y_or_n_from_stdin(message) bol = "" while !%w(Y N).include?(bol.upcase) bol = gets_from_stdin("#{message}(y/n)") end bol.upcase == "Y" end def show_item_with_pointer(iterator, console_print = true) rtn_hash = {} iterator.each_with_index do |value, idx| rtn_hash[idx.to_s] = value if console_print if value.is_a?(AWS::S3::Bucket) p "[" + (idx).to_s + "] " + value.name.to_s else p "[" + (idx).to_s + "] " + value end end end rtn_hash end def progress_bar(i, max = 100) i = i.to_f max = max.to_f i = max if i > max percent = i / max * 100.0 rest_size = 1 + 5 + 1 # space + progress_num + % bar_size = 79 - rest_size # (width - 1) - rest_size bar_str = '%-*s' % [bar_size, ('#' * (percent * bar_size / 100).to_i)] progress_num = '%3.1f' % percent print "\r#{bar_str} #{'%5s' % progress_num}%" end def print_green(str) puts "\e[32m#{str}\e[0m" end def print_red(str) puts "\e[31m#{str}\e[0m" end end # Class Methods End end end
class NewsHeadlines::Api # Does it make more sense to make this a module instead since there no instances of this class being created (i.e. no attributes, just behavior)? def self.get_sources doc = RestClient.get('https://newsapi.org/v1/sources?language=en') sources = JSON.parse(doc) sources["sources"] end def self.make_news_sources self.get_sources.each do |news_source| NewsHeadlines::Source.new_from_json(news_source) end end def self.make_articles(news_source) doc = RestClient.get("https://newsapi.org/v1/articles?source=#{news_source.id}&apiKey=#{NewsHeadlines::API_KEY}") articles = JSON.parse(doc) articles["articles"].each do |article_hash| if !NewsHeadlines::Article.find_article(article_hash["title"]) article = NewsHeadlines::Article.new_from_json(article_hash) article.add_news_source(news_source) news_source.add_article(article) end end end end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) end def set_current_client @current_client = Client.find_by(user_id: current_user.id) end def set_current_contractor @current_contractor = Contractor.find_by(user_id: current_user.id) end end
class IdentificationsController < ApplicationController before_action :authenticate_user!, only: [:index, :create, :update] before_action :address_existence, only: [:index, :update] def index if @address.present? @path = identification_path(@address) else @address = Address.new @path = identifications_path end end def create @address = Address.new(address_params) if @address.save redirect_to identifications_path, notice: '本人情報を登録しました' else @path = identifications_path(@address) render 'identifications/index' end end def update if @address.update(address_params) redirect_to identifications_path, notice: '本人情報を更新しました' else @path = identification_path(@address) render 'identifications/index' end end private def address_existence @address = current_user.address end def address_params params.require(:address).permit(:user_id, :postal_code, :prefecture, :city, :street, :building_name, :phone) end end
# coding: utf-8 lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "fastlane/plugin/localize/version" Gem::Specification.new do |spec| spec.name = "fastlane-plugin-localize" spec.version = Fastlane::Localize::VERSION spec.author = "Wolfgang Lutz" spec.email = "wlut@num42.de" spec.summary = "Searches the code for extractable strings and allows interactive extraction to .strings file." spec.homepage = "https://github.com/num42/fastlane-plugin-localize" spec.license = "MIT" spec.files = Dir["lib/**/*"] + %w(README.md LICENSE) spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.5" spec.add_development_dependency("bundler") spec.add_development_dependency("fastlane", ">= 2.204.3") spec.add_development_dependency("pry") spec.add_development_dependency("rake") spec.add_development_dependency("rspec") spec.add_development_dependency("rspec_junit_formatter") spec.add_development_dependency("rubocop", "1.12.1") spec.add_development_dependency("rubocop-performance") spec.add_development_dependency("rubocop-require_tools") spec.add_development_dependency("simplecov") end
module Bijou class Response attr_reader :reply def initialize(body, status, headers = {}) @reply = Rack::Response.new body, status, headers end end end
# encoding: utf-8 describe Faceter::Nodes::AddPrefix do it_behaves_like :creating_immutable_node do let(:attributes) { { prefix: "foo" } } end it_behaves_like :mapping_immutable_input do let(:attributes) { { prefix: "foo" } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { foo_bar: "BAR", "foo_baz" => { qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:attributes) { { prefix: "foo", separator: "." } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { :"foo.bar" => "BAR", "foo.baz" => { qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:selector) { Selector.new(only: /bar/) } let(:attributes) { { prefix: "foo", selector: selector } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { foo_bar: "BAR", "baz" => { qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:selector) { Selector.new(except: "baz") } let(:attributes) { { prefix: "foo", selector: selector } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { foo_bar: "BAR", "baz" => { qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:attributes) { { prefix: "foo", nested: true } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { foo_bar: "BAR", "foo_baz" => { foo_qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:selector) { Selector.new(except: /b/) } let(:attributes) { { prefix: "foo", nested: true, selector: selector } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { bar: "BAR", "baz" => { foo_qux: :QUX } } } end it_behaves_like :mapping_immutable_input do let(:selector) { Selector.new(only: /q/) } let(:attributes) { { prefix: "foo", nested: true, selector: selector } } let(:input) { { bar: "BAR", "baz" => { qux: :QUX } } } let(:output) { { bar: "BAR", "baz" => { foo_qux: :QUX } } } end end # describe Faceter::Nodes::AddPrefix
#Common deploy Options for all apps set :scm, :git # set :log_level, :debug # set :pty, true #Directories to be created in shared path shared_dirs = %w{config log runtime assets disputes vendor uploads uploads/images} # set :default_env, { path: "/opt/ruby/bin:$PATH" } namespace :onrun do desc "Show some internal Cap-Fu: What's mah NAYM?!?" task :setvars do set :task_name, task_call_frames.first.task.fully_qualified_name puts "Running #{task_name} task" end end namespace :deploy do task :finalize_update do # do nothing end # Setups dirs needed for running application' after "deploy:setup" do shared_dirs.each do |dir| run "mkdir -p #{shared_path}/#{dir}" run "chmod -R o+rwX #{shared_path}/#{dir}" end end desc 'Restart application' task :restart do # Your restart mechanism here, for example: # execute :touch, release_path.join('tmp/restart.txt') end after :restart do # Here we can do anything such as: # within release_path do # execute :rake, 'cache:clear' # end end desc "Will send a notification with details on the release" task :notify, :roles => :app do onrun.setvars Notifier.notification_email(self).deliver end after :deploy, 'deploy:notify' end
require('rspec') require('Triangle') describe('Triangle') do describe('#equilateral?') do it("will determine whether the triangle is equilateral") do test_triangle = Triangle.new(3,3,3) expect(test_triangle.equilateral?()).to(eq(true)) end end describe('#isosceles?') do it("will determine whether the triangle is isosceles") do test_triangle = Triangle.new(3,2,2) expect(test_triangle.isosceles?()).to(eq(true)) end end describe('#scalene?') do it("will determine whether the triangle is scalene") do test_triangle = Triangle.new(3,2,4) expect(test_triangle.scalene?()).to(eq(true)) end end describe('#triangle?') do it("will determine whether the sides do not make a triangle") do test_triangle = Triangle.new(3,2,2) expect(test_triangle.triangle?()).to(eq(true)) end end end
# EASY # Define a method that, given a sentence, returns a hash of each of the words as # keys with their lengths as values. Assume the argument lacks punctuation. def word_lengths(str) hsh = {} str.split.each { |word| hsh[word] = word.downcase.count('a-z') } hsh end # Define a method that, given a hash with integers as values, returns the key # with the largest value. def greatest_key_by_val(hash) hash.max_by { |_key, value| value }.first end # Define a method that accepts two hashes as arguments: an older inventory and a # newer one. The method should update keys in the older inventory with values # from the newer one as well as add new key-value pairs to the older inventory. # The method should return the older inventory as a result. march = {rubies: 10, # emeralds: 14, diamonds: 2} april = {emeralds: 27, moonstones: 5} # update_inventory(march, april) => {rubies: 10, emeralds: 27, diamonds: 2, # moonstones: 5} def update_inventory(older, newer) older.update(newer) end # Define a method that, given a word, returns a hash with the letters in the # word as keys and the frequencies of the letters as values. def letter_counts(word) hsh = Hash.new(0) word.chars.each { |ch| hsh[ch] += 1 } hsh end # MEDIUM # Define a method that, given an array, returns that array without duplicates. # Use a hash! Don't use the uniq method. def my_uniq(arr) hsh = Hash.new(0) arr.each { |element| hsh[element] += 1 } hsh.keys end # Define a method that, given an array of numbers, returns a hash with "even" # and "odd" as keys and the frequency of each parity as values. def evens_and_odds(numbers) hsh = Hash.new(0) numbers.each { |num| num.even? ? hsh[:even] += 1 : hsh[:odd] += 1 } hsh end # Define a method that, given a string, returns the most common vowel. If # there's a tie, return the vowel that occurs earlier in the alphabet. Assume # all letters are lower case. def most_common_vowel(string) hsh = Hash.new(0) string.chars.each { |ch| hsh[ch] += 1 if 'aeiou'.include?(ch.downcase) } hsh.sort_by { |_k, v| v }[-1][0] end # HARD # Define a method that, given a hash with keys as student names and values as # their birthday months (numerically, e.g., 1 corresponds to January), returns # every combination of students whose birthdays fall in the second half of the # year (months 7-12). students_with_birthdays = { "Asher" => 6, "Bertie" => 11, # "Dottie" => 8, "Warren" => 9 } # fall_and_winter_birthdays(students_with_birthdays) => [ ["Bertie", "Dottie"], # ["Bertie", "Warren"], ["Dottie", "Warren"] ] def fall_and_winter_birthdays(students) students.select { |_name, month| month >= 7 }.keys.combination(2).to_a end # Define a method that, given an array of specimens, returns the biodiversity # index as defined by the following formula: number_of_species**2 * # smallest_population_size / largest_population_size biodiversity_index(["cat", # "cat", "cat"]) => 1 biodiversity_index(["cat", "leopard-spotted ferret", # "dog"]) => 9 def biodiversity_index(specimens) specimens.uniq.count**2 end # Define a method that, given the string of a respectable business sign, returns # a boolean indicating whether pranksters can make a given vandalized string # using the available letters. Ignore capitalization and punctuation. # can_tweak_sign("We're having a yellow ferret sale for a good cause over at the # pet shop!", "Leopard ferrets forever yo") => true def can_tweak_sign?(normal_sign, vandalized_sign) nsign = character_count(normal_sign) vsign = character_count(vandalized_sign) nsign.each do |key, value| vsign.delete_if do |k, v| k == key && value >= v end end vsign.empty? end def character_count(str) hsh = Hash.new(0) punctuation = "!/\'?*" str.delete(punctuation) str.chars.each { |ch| hsh[ch.downcase] += 1 } hsh end
require 'test_helper' class ErrorDrop < Liquid::Drop def standard_error raise Liquid::StandardError, 'standard error' end def argument_error raise Liquid::ArgumentError, 'argument error' end def syntax_error raise Liquid::SyntaxError, 'syntax error' end def exception raise Exception, 'exception' end end class ErrorHandlingTest < Minitest::Test include Liquid def test_templates_parsed_with_line_numbers_renders_them_in_errors template = <<-LIQUID Hello, {{ errors.standard_error }} will raise a standard error. Bla bla test. {{ errors.syntax_error }} will raise a syntax error. This is an argument error: {{ errors.argument_error }} Bla. LIQUID expected = <<-TEXT Hello, Liquid error (line 3): standard error will raise a standard error. Bla bla test. Liquid syntax error (line 7): syntax error will raise a syntax error. This is an argument error: Liquid error (line 9): argument error Bla. TEXT output = Liquid::Template.parse(template, line_numbers: true).render('errors' => ErrorDrop.new) assert_equal expected, output end def test_standard_error template = Liquid::Template.parse( ' {{ errors.standard_error }} ' ) assert_equal ' Liquid error: standard error ', template.render('errors' => ErrorDrop.new) assert_equal 1, template.errors.size assert_equal StandardError, template.errors.first.class end def test_syntax template = Liquid::Template.parse( ' {{ errors.syntax_error }} ' ) assert_equal ' Liquid syntax error: syntax error ', template.render('errors' => ErrorDrop.new) assert_equal 1, template.errors.size assert_equal SyntaxError, template.errors.first.class end def test_argument template = Liquid::Template.parse( ' {{ errors.argument_error }} ' ) assert_equal ' Liquid error: argument error ', template.render('errors' => ErrorDrop.new) assert_equal 1, template.errors.size assert_equal ArgumentError, template.errors.first.class end def test_missing_endtag_parse_time_error assert_raises(Liquid::SyntaxError) do Liquid::Template.parse(' {% for a in b %} ... ') end end def test_unrecognized_operator with_error_mode(:strict) do assert_raises(SyntaxError) do Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ') end end end def test_lax_unrecognized_operator template = Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', :error_mode => :lax) assert_equal ' Liquid error: Unknown operator =! ', template.render assert_equal 1, template.errors.size assert_equal Liquid::ArgumentError, template.errors.first.class end def test_with_line_numbers_adds_numbers_to_parser_errors err = assert_raises(SyntaxError) do template = Liquid::Template.parse(%q{ foobar {% "cat" | foobar %} bla }, :line_numbers => true ) end assert_match /Liquid syntax error \(line 4\)/, err.message end def test_parsing_warn_with_line_numbers_adds_numbers_to_lexer_errors template = Liquid::Template.parse(%q{ foobar {% if 1 =! 2 %}ok{% endif %} bla }, :error_mode => :warn, :line_numbers => true ) assert_equal ['Liquid syntax error (line 4): Unexpected character = in "1 =! 2"'], template.warnings.map(&:message) end def test_parsing_strict_with_line_numbers_adds_numbers_to_lexer_errors err = assert_raises(SyntaxError) do Liquid::Template.parse(%q{ foobar {% if 1 =! 2 %}ok{% endif %} bla }, :error_mode => :strict, :line_numbers => true ) end assert_equal 'Liquid syntax error (line 4): Unexpected character = in "1 =! 2"', err.message end def test_syntax_errors_in_nested_blocks_have_correct_line_number err = assert_raises(SyntaxError) do Liquid::Template.parse(%q{ foobar {% if 1 != 2 %} {% foo %} {% endif %} bla }, :line_numbers => true ) end assert_equal "Liquid syntax error (line 5): Unknown tag 'foo'", err.message end def test_strict_error_messages err = assert_raises(SyntaxError) do Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', :error_mode => :strict) end assert_equal 'Liquid syntax error: Unexpected character = in "1 =! 2"', err.message err = assert_raises(SyntaxError) do Liquid::Template.parse('{{%%%}}', :error_mode => :strict) end assert_equal 'Liquid syntax error: Unexpected character % in "{{%%%}}"', err.message end def test_warnings template = Liquid::Template.parse('{% if ~~~ %}{{%%%}}{% else %}{{ hello. }}{% endif %}', :error_mode => :warn) assert_equal 3, template.warnings.size assert_equal 'Unexpected character ~ in "~~~"', template.warnings[0].to_s(false) assert_equal 'Unexpected character % in "{{%%%}}"', template.warnings[1].to_s(false) assert_equal 'Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].to_s(false) assert_equal '', template.render end def test_warning_line_numbers template = Liquid::Template.parse("{% if ~~~ %}\n{{%%%}}{% else %}\n{{ hello. }}{% endif %}", :error_mode => :warn, :line_numbers => true) assert_equal 'Liquid syntax error (line 1): Unexpected character ~ in "~~~"', template.warnings[0].message assert_equal 'Liquid syntax error (line 2): Unexpected character % in "{{%%%}}"', template.warnings[1].message assert_equal 'Liquid syntax error (line 3): Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].message assert_equal 3, template.warnings.size assert_equal [1,2,3], template.warnings.map(&:line_number) end # Liquid should not catch Exceptions that are not subclasses of StandardError, like Interrupt and NoMemoryError def test_exceptions_propagate assert_raises Exception do template = Liquid::Template.parse('{{ errors.exception }}') template.render('errors' => ErrorDrop.new) end end end
class Event < ActiveRecord::Base attr_accessible :date, :events_type_id, :image_id, :info, :lieu, :remarque, :theme belongs_to :image belongs_to :events_type validates :date, presence: true validates :events_type_id, presence: true validates :theme, presence: true, length: { maximum: 55 } validates :lieu, presence: true, length: { maximum: 55 } validates :info, presence: true end
class NearbyPlaces GOOGLE_SRID = 4326 DEFAULTS = { record_name: :pub, distance: 5, lat: 0, lng: 0 } include ActiveModel::Model attr_accessor :record_name, :distance, :lat, :lng def initialize *attrs super DEFAULTS.each do |k,v| self.send("#{k}=", v) if self.send(k).blank? end end def find_places where_clause = <<-SQL ST_DISTANCE( ST_TRANSFORM(geom, #{GOOGLE_SRID}), ST_GeomFromText('POINT(#{lng} #{lat})', #{GOOGLE_SRID}), true ) <= #{distance_metres} SQL record_model.select("*, ST_TRANSFORM(geom, #{GOOGLE_SRID}) AS ggeom").where(where_clause).collect do |r| Record.new(id: r.id, title: r.name, geom: r.ggeom) end end def distance_metres distance.to_d * 1000 end def record_model @model ||= case record_name.to_sym when :hospital then BCHospital when :pub then BCPub else raise AgumentError, "model_name" end end class Record attr_accessor :id, :title, :geom include ActiveModel::Model def point { lat: geom.y, lng: geom.x } end def to_hash { id: id, title: title, point: point } end end end
require_relative '../../lib/model/lib/model' class Person extend Triply::BaseModel persistable property :first_name property :last_name property :email, required: true, format: /\A\S+@\S+\.\S+\z/ property :mobile_phone, format: /\A[0-9\- ]+\z/ property :phone, format: /\A[0-9\- ]+\z/ property :role property :belongs_to, type: Reference end
require 'concurrent' module SemanticLogger # Logger stores the class name to be used for all log messages so that every # log message written by this instance will include the class name class Logger < Base include SemanticLogger::Concerns::Compatibility # Returns a Logger instance # # Return the logger for a specific class, supports class specific log levels # logger = SemanticLogger::Logger.new(self) # OR # logger = SemanticLogger::Logger.new('MyClass') # # Parameters: # application # A class, module or a string with the application/class name # to be used in the logger # # level # The initial log level to start with for this logger instance # Default: SemanticLogger.default_level # # filter [Regexp|Proc] # RegExp: Only include log messages where the class name matches the supplied # regular expression. All other messages will be ignored # Proc: Only include log messages where the supplied Proc returns true # The Proc must return true or false def initialize(klass, level=nil, filter=nil) super end # Returns [Integer] the number of log entries that have not been written # to the appenders # # When this number grows it is because the logging appender thread is not # able to write to the appenders fast enough. Either reduce the amount of # logging, increase the log level, reduce the number of appenders, or # look into speeding up the appenders themselves def self.queue_size Processor.queue_size end # Flush all queued log entries disk, database, etc. # All queued log messages are written and then each appender is flushed in turn def self.flush Processor.submit_request(:flush) end # Close all appenders and flush any outstanding messages def self.close Processor.submit_request(:close) end # Allow the internal logger to be overridden from its default of STDERR # Can be replaced with another Ruby logger or Rails logger, but never to # SemanticLogger::Logger itself since it is for reporting problems # while trying to log to the various appenders def self.logger=(logger) Processor.logger = logger end # Place log request on the queue for the Appender thread to write to each # appender in the order that they were registered def log(log, message = nil, progname = nil, &block) # Compatibility with ::Logger return add(log, message, progname, &block) unless log.is_a?(SemanticLogger::Log) Processor << log end end end
class Student < ApplicationRecord belongs_to :lop validates_presence_of :hoten, :ngaysinh, :gioitinh, :choohientai, :hokhauthuongtru, :noisinh, :quequan, :tencha, :nghenghiepcha, :dienthoaibo, :tenme, :nghenghiepme, :dienthoaime end
class Image < ActiveRecord::Base mount_uploader :url, ImageUploader has_many :tags has_many :comments, :dependent => :destroy belongs_to :user public def search(query, user_id) Image.where("name LIKE ? and user_id = ?", "%#{query}%", "#{user_id}") end end
# frozen_string_literal: true # TODO rename dir to resources due to service being domain model require 'csv' class CompanyCsvImport EXPECTED_COMPANY_NAMES = %w(Google Apple IBM) attr_reader :valid_rows, :bad_rows def initialize(file, row_parser: Row) @file = file @bad_rows = [] @row_parser = row_parser end def perform! @valid_rows = rows.uniq.map do |row| @bad_rows << row && next if bad_row? row company = Company.find_or_create_by! name: row.company region = Region.find_or_create_by! name: row.region branch = company.branches.where(region: region).find_or_create_by! \ name: row.branch branch.services.find_or_create_by! \ name: row.service, price_cents: row.price_cents, duration_minutes: row.duration_minutes, disabled: row.disabled end end private def rows @rows ||= raw_rows.map &@row_parser.method(:new) end def raw_rows csv = CSV.parse @file, headers: false csv.tap &:shift end def bad_row?(row) EXPECTED_COMPANY_NAMES.exclude? row.company end end
# AnnouncementController: functions for announcemnt manuipulation # referenced https://www.codecademy.com/courses/learn-rails/lessons/one-model/exercises/one-model-view?action=lesson_resume # referenced https://www.twilio.com/blog/2012/02/adding-twilio-sms-messaging-to-your-rails-app.html class AnnouncementController < ApplicationController include AnnouncementHelper before_action :coach?, except: %i[index show] def index @announcements = Announcement.scoped(current_user) @announcement = Announcement.new if current_user.has_role? :coach render 'admin_index' else render end end def new @announcement = Announcement.new end def create @announcement = Announcement.new(announcement_params) if @announcement.sms && @announcement.save send_text_message(@announcement.title, @announcement.content) announcement_success elsif @announcement.save announcement_success else redirect_to '/announcement' flash[:alert] = 'Please select a send type before submitting announcement' end end def destroy begin Announcement.find(params[:id]).destroy flash[:success] = 'Announcement deleted' rescue ActiveRecord::RecordNotFound flash[:alert] = 'Could not find this announcement' end redirect_to action: 'index' end def show @announcement = Announcement.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = 'Could not find this announcement' render 'index' end private def announcement_params params.require(:announcement).permit(:email, :sms, :title, :content) end def announcement_success @announcement.sender = [current_user.first_name, current_user.last_name].join(' ') @announcement.save @announcement.scopify(params[:roles]) redirect_to '/announcement' flash[:success] = 'Announcement sent' end def send_text_message(subject, words) number_to_send_to = '2066180749' # "params[:number_to_send_to]" twilio_sid = 'ACc17e1968205992bb82bdb0ba8de37732' # this is public twilio_token = ENV['TWILIO_TOKEN'] # private, environment variable twilio_phone_number = '2062078212' @twilio_client = Twilio::REST::Client.new(twilio_sid, twilio_token) @twilio_client.messages.create( from: "+1#{twilio_phone_number}", to: number_to_send_to, body: subject + ' - ' + words ) end end
FactoryGirl.define do factory :cardset do topic "Topic" description "Description" author_id 1 end end
class AddCommentsToDatasets < ActiveRecord::Migration def change add_column :datasets, :comments, :text end end
class UserNotifierMailer < ApplicationMailer default :from => 'any_from_address@example.com' # send a signup email to the user, pass in the user object that contains the user's email address def send_signup_email(user) @user = user mail( :to => @user.email, :subject => 'Thanks for signing up to EY Time' ) end # recreate one for each email, then create content in corresponding .html.erb file # run mailcatcher to test # Check: how to call mailers? request.user? def send_changed_password_email(user) @user = user mail( :to => @user.email, :subject => 'Your password has been changed' ) end def leave_denied_email(user) @user = user mail( :to => @request.user.email, :subject => 'Your leave request has been denied' ) end def leave_approved_email(user) @user = user mail( :to => @request.user.email, :subject => 'Your leave request has been approved' ) end def leave_revoked_email(user) @user = user mail( :to => @request.user.email, :subject => 'You have successfully revoked your leave request' ) end # inform counsellor of leave revoked def leave_revoked_email_4cm(request, user, counsellor) @user = user mail( :to => @request.user.counsellor.email, :subject => 'User has revoked leave request' ) end # inform manager of leave revoked def leave_revoked_email_4cm(request, user, manager) @user = user mail( :to => @request.user.manager.email, :subject => 'User has revoked leave request' ) end # THIS ONE NEEDS TO GO TO A USER"S COUNCELLOR def leave_request_cm_email(user, counsellor) @user = user mail( :to => @request.user.counsellor.email, :subject => 'New leave request(s)' ) end # THIS ONE NEEDS TO GO TO A USER"S COUNCELLOR def leave_request_cm_email(user, manager) @user = user mail( :to => @request.user.manager.email, :subject => 'New leave request(s)' ) end end
# # A wrapper around redis that namespaces keys with the current site id # class KanmenrenRedis def self.raw_connection(config = nil) config ||= self.config redis_opts = {host: config['host'], port: config['port'], db: config['db']} redis_opts[:password] = config['password'] if config['password'] Redis.new(redis_opts) end def self.config @config ||= YAML.load(ERB.new(File.new("#{Rails.root}/config/redis.yml").read).result)[Rails.env] end def self.url(config=nil) config ||= self.config "redis://#{(':' + config['password'] + '@') if config['password']}#{config['host']}:#{config['port']}/#{config['db']}" end def initialize @config = KanmenrenRedis.config @redis = KanmenrenRedis.raw_connection(@config) end def url self.class.url(@config) end # prefix the key with the namespace def method_missing(meth, *args, &block) if @redis.respond_to?(meth) @redis.send(meth, *args, &block) else super end end # Proxy key methods through, but prefix the keys with the namespace [:append, :blpop, :brpop, :brpoplpush, :decr, :decrby, :del, :exists, :expire, :expireat, :get, :getbit, :getrange, :getset, :hdel, :hexists, :hget, :hgetall, :hincrby, :hincrbyfloat, :hkeys, :hlen, :hmget, :hmset, :hset, :hsetnx, :hvals, :incr, :incrby, :incrbyfloat, :lindex, :linsert, :llen, :lpop, :lpush, :lpushx, :lrange, :lrem, :lset, :ltrim, :mget, :move, :mset, :msetnx, :persist, :pexpire, :pexpireat, :psetex, :pttl, :rename, :renamenx, :rpop, :rpoplpush, :rpush, :rpushx, :sadd, :scard, :sdiff, :set, :setbit, :setex, :setnx, :setrange, :sinter, :sismember, :smembers, :sort, :spop, :srandmember, :srem, :strlen, :sunion, :ttl, :type, :watch, :zadd, :zcard, :zcount, :zincrby, :zrange, :zrangebyscore, :zrank, :zrem, :zremrangebyrank, :zremrangebyscore, :zrevrange, :zrevrangebyscore, :zrevrank, :zrangebyscore].each do |m| define_method m do |*args| args[0] = "#{KanmenrenRedis.namespace}:#{args[0]}" @redis.send(m, *args) end end def self.namespace 'kanmenren' end def self.new_redis_store redis_config = YAML.load(ERB.new(File.new("#{Rails.root}/config/redis.yml").read).result)[Rails.env] unless redis_config puts '', "Redis config for environment '#{Rails.env}' was not found in #{Rails.root}/config/redis.yml." puts "Did you forget to do RAILS_ENV=production?" puts "Check your redis.yml and make sure it has configuration for the environment you're trying to use.", '' raise 'Redis config not found' end redis_store = ActiveSupport::Cache::RedisStore.new "redis://#{(':' + redis_config['password'] + '@') if redis_config['password']}#{redis_config['host']}:#{redis_config['port']}/#{redis_config['cache_db']}" redis_store.options[:namespace] = -> { KanmenrenRedis.namespace } redis_store end end
require "rails_helper" require "notify/otp_message" def log_in_via_form(user, remember_me: false) click_on t("header.link.sign_in") # type in username and password fill_in "Email", with: user.email fill_in "Password", with: user.password check "Remember me" if remember_me click_on "Log in" end RSpec.feature "Users can sign in" do after { logout } context "user does not have 2FA enabled" do scenario "successful sign in via header link" do # Given a user exists user = create(:administrator) # When I log in with that user's credentials visit root_path expect(page).to have_content(t("start_page.title")) expect(page).to have_content(t("header.link.sign_in")) log_in_via_form(user) # Then I should be logged in. expect(page).to have_link(t("header.link.sign_out")) expect(page).to have_content("Signed in successfully.") # And at the home page expect(page).to have_content("You can search by RODA, Partner Organisation, BEIS, or IATI identifier, or by the activity's title") end end context "user has MFA enabled" do let(:notify_client) { spy("Notifications::Client") } before do allow_any_instance_of(Notify::OTPMessage).to receive(:client).and_return(notify_client) end context "user has a confirmed mobile number" do scenario "successful sign in via header link" do # Given a user with 2FA enabled and a confirmed mobile number exists user = create(:administrator, :mfa_enabled, mobile_number_confirmed_at: DateTime.current) # When I log in with that user's email and password visit root_path log_in_via_form(user) # Then there should be no link to check my mobile number expect(page).not_to have_link "Check your mobile number is correct" otp_at_time_of_login = user.current_otp # And I should receive an OTP to my mobile number expect(notify_client).to have_received(:send_sms).with({ phone_number: user.mobile_number, template_id: ENV["NOTIFY_OTP_VERIFICATION_TEMPLATE"], personalisation: {otp: otp_at_time_of_login} }) # When I enter the one-time password before it expires travel 3.minutes do fill_in "Please enter your six-digit verification code", with: otp_at_time_of_login click_on "Continue" end # Then I should be logged in expect(page).to have_link(t("header.link.sign_out")) expect(page).to have_content("Signed in successfully.") # And I should be at the home page expect(page).to have_content("You can search by RODA, Partner Organisation, BEIS, or IATI identifier, or by the activity's title") end scenario "unsuccessful OTP attempt" do # Given a user with 2FA enabled and a confirmed mobile number exists user = create(:administrator, :mfa_enabled, mobile_number_confirmed_at: DateTime.current) # When I log in with that user's email and password visit root_path log_in_via_form(user) # And I enter an incorrect OTP fill_in "Please enter your six-digit verification code", with: "000000" click_on "Continue" # Then I should not be logged in expect(page).to have_content("Invalid two-factor verification code") expect(page).not_to have_link(t("header.link.sign_out")) visit root_path expect(page).to have_content("Sign in") end scenario "logins can be remembered for 30 days" do # Given a user with 2FA enabled and a confirmed mobile number exists user = create(:administrator, :mfa_enabled, mobile_number_confirmed_at: DateTime.current) # When I log in with MFA and choose Remember me visit root_path log_in_via_form(user, remember_me: true) fill_in "Please enter your six-digit verification code", with: user.current_otp click_on "Continue" # Then I should be logged in expect(page).to have_link(t("header.link.sign_out")) expect(page).to have_content("Signed in successfully.") # And I should be at the home page expect(page).to have_content("You can search by RODA, Partner Organisation, BEIS, or IATI identifier, or by the activity's title") # When I visit the site 29 days later travel 29.days do visit reports_path # Then I should still be logged in expect(page).to have_content("Create a new report") end # When I visit the site 31 days later travel 31.days do visit reports_path # Then I should be logged out expect(page).to have_content("Sign in") end end end context "user initially entered an incorrect mobile number" do scenario "the email/password are correct but the user still needs confirm their mobile number" do incorrect_number = "123456wrong" # Given a user with 2FA enabled exists user = create(:administrator, :mfa_enabled, mobile_number_confirmed_at: nil, mobile_number: incorrect_number) # When I log in with that user's email and password visit root_path log_in_via_form(user) # But I do not receive a message despite it having been sent expect(notify_client).to have_received(:send_sms).once.with({ phone_number: incorrect_number, template_id: ENV["NOTIFY_OTP_VERIFICATION_TEMPLATE"], personalisation: {otp: user.current_otp} }) # When I follow the link to check my mobile number click_link "Check your mobile number is correct" # Then I should see the incorrect number expect(page).to have_field("Enter your mobile number", with: incorrect_number) # When I update my number correct_number = "07799000000" fill_in "Enter your mobile number", with: correct_number click_on "Continue" # Then I should receive an OTP to my mobile number expect(notify_client).to have_received(:send_sms).once.with({ phone_number: correct_number, template_id: ENV["NOTIFY_OTP_VERIFICATION_TEMPLATE"], personalisation: {otp: user.current_otp} }) # When I enter the one-time password before it expires fill_in "Please enter your six-digit verification code", with: user.current_otp expect(user.mobile_number_confirmed_at).to be_nil click_on "Continue" # Then my mobile number should be confirmed expect(user.reload.mobile_number_confirmed_at).to be_a(ActiveSupport::TimeWithZone) # And I should be logged in at the home page expect(page).to have_link(t("header.link.sign_out")) expect(page).to have_content("Signed in successfully.") expect(page).to have_content("You can search by RODA, Partner Organisation, BEIS, or IATI identifier, or by the activity's title") end end context "User has no mobile number provisioned" do scenario "successful mobile confirmation" do # Given that I am a RODA user user = create(:partner_organisation_user, :mfa_enabled, :no_mobile_number) # When I log in for the first time, visit root_path log_in_via_form(user, remember_me: true) # Then I am prompted for my mobile number expect(page).to have_content("Enter your mobile number") # And I enter my mobile number fill_in "Enter your mobile number", with: "07700900000" click_on "Continue" user = user.reload # Mobile number has changed # Then I should receive an automated text message, expect(notify_client).to have_received(:send_sms).with({ phone_number: user.mobile_number, template_id: ENV["NOTIFY_OTP_VERIFICATION_TEMPLATE"], personalisation: {otp: user.current_otp} }) # When I enter the code fill_in "Please enter your six-digit verification code", with: user.current_otp click_on "Continue" # Then I am successfully logged in. expect(page).to have_link(t("header.link.sign_out")) expect(page).to have_content("Signed in successfully.") # When I visit the site 29 days later travel 29.days do visit reports_path # Then I should still be logged in expect(page).to have_link(t("header.link.sign_out")) end end context "user enters an invalid mobile number" do let(:govuk_response) { double("Response", code: 400, body: "ValidationError: phone_number Not enough digits") } scenario "the email/password are correct but the mobile number is invalid" do # Given a user with 2FA enabled exists user = create(:administrator, :mfa_enabled, :no_mobile_number) # When I log in for the first time visit root_path log_in_via_form(user) # Then I am prompted for my mobile number expect(page).to have_content("Enter your mobile number") # And I enter an invalid mobile number invalid_number = "123456" fill_in "Enter your mobile number", with: invalid_number # And the notify service raises an error allow(notify_client).to receive(:send_sms).once.with({ phone_number: invalid_number, template_id: ENV["NOTIFY_OTP_VERIFICATION_TEMPLATE"], personalisation: {otp: user.current_otp} }).and_raise(Notifications::Client::BadRequestError.new(govuk_response)) click_on "Continue" # Then I should see an informative message expect(page).to have_content("There is a problem") expect(page).to have_content("Not enough digits") # And I should be able to edit my mobile number expect(page).to have_field("Enter your mobile number") end end end scenario "they can sign in using a different capitalisation of their email address" do # Given a user exists user = create(:administrator, :mfa_enabled, email: "forename.lastname@somesite.org") # When I go to log in visit root_path click_on t("header.link.sign_in") # And I use a different capitalisation of the email than that in the database fill_in "Email", with: "Forename.Lastname@SOMEsite.org" fill_in "Password", with: user.password click_on "Log in" # Then I should be prompted for the OTP expect(page).to have_field("Please enter your six-digit verification code") end end scenario "a user is redirected to a link they originally requested" do user = create(:administrator) visit reports_path log_in_via_form(user) expect(current_path).to eq(reports_path) end scenario "a BEIS user lands on their home page" do user = create(:beis_user) visit root_path expect(page).to have_content(t("start_page.title")) log_in_via_form(user) expect(page.current_path).to eql home_path end scenario "a partner organisation user lands on their home page" do user = create(:partner_organisation_user) visit root_path expect(page).to have_content(t("start_page.title")) log_in_via_form(user) expect(page.current_path).to eql home_path end scenario "protected pages cannot be visited unless signed in" do visit root_path expect(page).to have_content(t("start_page.title")) end context "incorrect credentials are supplied" do it "displays the error message so they can try to correct the problem themselves" do user = double("User", email: "dont@exist.com", password: "anything") visit root_path log_in_via_form(user) expect(page).to have_content("Invalid Email or password") end end context "when the user has been deactivated" do scenario "the user cannot log in and sees an informative message" do user = create(:partner_organisation_user, active: false) visit root_path log_in_via_form(user) expect(page).to have_content("Your account is not active. If you believe this to be in error, please contact the person who invited you to the service.") end scenario "a user who is logged in and then deactivated sees an error message" do user = create(:partner_organisation_user) visit root_path log_in_via_form(user) expect(page.current_path).to eql home_path user.active = false user.save visit home_path expect(page).to have_content("Your account is not active. If you believe this to be in error, please contact the person who invited you to the service.") end end end
module Recommendations module Model class Preferences include Enumerable def initialize @by_user={} @by_item={} @by_user_item={} @preferences = [] end def <<(preference) (@by_user[preference.user] ||= []) << preference (@by_item[preference.item] ||= []) << preference (@by_user_item[preference.user] ||= {})[preference.item] = preference @preferences << preference self end def for_user(user) prefs = Preferences.new @by_user[user].each do|preference| prefs << preference end prefs end def for_item(item) prefs = Preferences.new @by_item[item].each do |preference| prefs << preference end prefs end def for_user_item(user,item) @by_user_item[user][item] end def each @preferences.each do|preference| yield preference end end def size @preferences.size end def empty? @preferences.empty? end def [](index) @preferences[index] end end end end
#!/usr/bin/env ruby require 'pry' class String def isnum? /\A[-+]?\d+\z/ === self end def ishex? self.gsub(/0x/, "")[/\H/] end end class Parser def self.parse(file) file.readlines.each do |line| line.strip! if line.size == 0 || line[0] == '#' then puts "skip" # skip empty lines next end parsed_instr = parseline(line) if parsed_instr.nil? then next end parsed_instr[:line] = line #binding.pry if $instr_nr > 584 if parsed_instr[:command] == ".code" then if $instr_nr != 0 then Error.mexit("ERROR: .code needs to be the first declaration (is: #{$instr_nr})") end if parsed_instr[:no_args] then next end # we need to relocate code and add a little trampoline to it at the start # load addr, branch to it # trampoline = parseld16({:args => ["r1", parsed_instr[:args][0]], :line => line}) # trampoline << {:command => "br", :args => [parsed_instr[:args][0]]} # #binding.pry # noreloc = 0 # trampoline.each do |tr| # tr[:no_reloc] = noreloc # noreloc +=2 # end # appendinstr(trampoline) $code_ptr = parsed_instr[:args][0] next end if parsed_instr[:command] == ".data" then if $data_ptr != 0 then binding.pry Error.mexit("ERROR: .data can only be declared once") end if parsed_instr[:no_args] then next end $data_ptr = parsed_instr[:args][0] puts "data pointer #{$data_ptr}\n" next end if parsed_instr[:command] == "ld16" then instructions = parseld16(parsed_instr) elsif parsed_instr[:command] == "la16" then # this will often be a symbol which we haven't resolved at this point # we take a conservative approach and insert 2 instructions to be adjusted after symbols # have been resolved instr_lo = {:command => "lda", :args => [parsed_instr[:args][0], parsed_instr[:args][1]], :adjust => true, :line => line} instr_hi = {:command => "addhi", :args => [parsed_instr[:args][0], parsed_instr[:args][1]], :adjust => true} instructions = [instr_lo, instr_hi] #binding.pry elsif parsed_instr[:command] == "defstr" then # expand the string into individual chars and add NULL instructions = [] for i in 0..(parsed_instr[:string].length) instr ={} instr[:command] = "defb" instr[:mem] = true instr[:byte_enable] = true if i == parsed_instr[:string].length instr[:args] = [0] # null terminator else instr[:args] = [parsed_instr[:string][i].ord] end if i == 0 || i == 1 then instr[:line] = line end #binding.pry instructions << instr end #binding.pry elsif parsed_instr[:command] == "defs" then instructions = [] for i in 1..(parsed_instr[:bss] / 2) instr ={} instr[:command] = "defw" instr[:mem] = true instr[:bss] = true instr[:args] = [0] if i == 1 then instr[:line] = line end instructions << instr end else # if its a stw/b s7(bp), r0 instr if parsed_instr[:command] == "stw" && parsed_instr[:args][0].is_a?(Integer) && parsed_instr[:args][2] == "r0" then parsed_instr[:command] = "stw0" end if parsed_instr[:command] == "stb" && parsed_instr[:args][0].is_a?(Integer) && parsed_instr[:args][2] == "r0" then parsed_instr[:command] = "stb0" end instructions = [parsed_instr] end appendinstr(instructions) end end def self.appendinstr(instructions) instructions.each do |instr| valid_instr?(instr) puts "adding: #{instr} - #{$instr_nr} (#{$double_label_guard})\n" if instr[:mem] then instr[:instr_nr] = $instr_nr $instr_nr += 1 $mem_instructions << instr $double_label_guard = 0 next end if instr[:label] then if $double_label_guard > 0 then if $double_label_guard > 1 then binding.pry Error.mexit("Encountered more than two sequential labels") end prev_label = find_label($instr_nr - 1) prev_label[:ptr] += 1 end instr[:ptr] = $instr_nr + 1 instr[:instr_nr] = $instr_nr $instr_nr += 1 $labels << instr $double_label_guard += 1 next end instr[:addr] = $instr_addr instr[:instr_nr] = $instr_nr $instr_nr += 1 $instructions << instr $double_label_guard = 0 end end def self.valid_instr?(instr) if instr[:label] then return end if ISA::OPCODES[instr[:command]].nil? Error.mexit("Unknown command: #{instr[:command]}\n") end unless instr[:no_args] nr_of_args = ISA::ARGS[instr[:command]].values.select {|a| a != :x}.length if nr_of_args != instr[:args].length then binding.pry Error.mexit("Argument error: #{instr[:command]}, #{ISA::ARGS[instr[:command]].length} got #{instr[:args].length}") end end return end def self.find_label(nr) $labels.each do |label| if label[:instr_nr] == nr then return label end end end def self.parseline(line) puts "Parsing: #{line}" instr = {} commands, comment = line.split(";") #binding.pry if commands.nil? then return end if commands.length == 0 then return end if commands[0] == '.' && commands[0..4] != '.code' && commands[0..4] != '.' then return end command, argstr = commands.split(" ", 2) # is it a label? if command.include?(":") then # it is a label puts "Found label: #{commands.strip.chop}\n" instr[:label] = true; instr[:name] = commands.chop.strip return instr end instr[:command] = command.strip if ISA::MEMINSTR.include?(instr[:command]) puts "Found mem instr: #{command}\n" instr[:mem] = true if instr[:command] == 'defb' || instr[:command] == 'defw' then args = argstr.split("'") if args.length == 1 then arg = number(args[0].strip) else arg = args[1].ord end instr[:args]=[arg] end if instr[:command] == 'defb' then instr[:byte_enable] = true end if instr[:command] == 'defstr' then if argstr.scan(/["]/).empty? Error.mexit("ERROR: defs expects a quoted string or # of bytes. (#{argstr})") end instr[:string] = argstr[1..-2] #binding.pry end if instr[:command] == 'defs' then instr[:bss] = argstr.to_i end return instr end if instr[:command].length > 4 && instr[:command][0..3] == "skip" then # split condition from command and add it to the argstr skip, cond = instr[:command].split(".") instr[:command] = skip argstr += "," + cond #binding.pry end if argstr.nil? || argstr == "" then # instr without args instr[:no_args] = true return instr end args = argstr.split(",") i = 0; args_array = [] args[0..(args.length)].each do |arg| a = arg.strip.tr(",", "") if a.include?("(") then offset, base = a.split("(") base.chop! args_array << number(offset) args_array << number(base) else args_array << number(a) end i += 1 end instr[:args] = parseargs(args_array) puts instr return instr end def self.parseargs(args) #binding.pry # check if we are loading a char if args[1].is_a? String then if args[1][0..3] == "char" then if args[1].include?("@") then # extra signal char for use with m4 macros x, char = args[1].split("@") else x, char = args[1].split("'") end #binding.pry args[1] = char.ord end end #binding.pry return args end def self.number(nr) #binding.pry if nr.to_s[0..1] == "0x" then return nr.to_i(16) #hex elsif nr.isnum? then return nr.to_i(10) #dec else return nr #label or variable end end def self.parseld16(instr) # ld16 allows the compiler to load an arbitrary length (up to 16b) imm in a reg # here we check its length and see if we need 1 or 2 instructions if instr[:args][1] <= 511 then # imm is small enough to load with ldi return [{:command => "ldi", :args => instr[:args], :line => instr[:line]}] else # imm requires two instructions to load: ldi followed by addhi lo = instr[:args][1] & 0x1ff hi = (instr[:args][1] & 0xfe00) >> 9 instr_lo = {:command => "ldi", :args => [instr[:args][0], lo], :line => instr[:line] } instr_hi = {:command => "addhi", :args => [instr[:args][0], hi] } return [instr_lo, instr_hi] end end end class SymbolTable # only label symbols for now def self.idsymbols() puts "ID SYM\n" $labels.each do |label| SymbolTable.push(label[:ptr], label[:name], :label) end $instructions.each do |instr| # is it a symbol if instr[:no_args] then next end new_args = [] idx = 0 instr[:args].each do |arg| # id calculations if arg.is_a?(String) && ( arg.include?("+") || arg.include?("-")) then if !(["lda", "addhi"].include?(instr[:command])) then Error.mexit("Encountered arithmetic expression outside LA16 instruction.\n") end arg_array = arg.split(/(?=[+|-])\s*/) arg = arg_array[0] new_args << arg puts "<<calc #{arg_array[0]}" calc_string = "" for i in 1..(arg_array.size-1) do calc_string += arg_array[i] end instr[:calc] = calc_string instr[:calc_argnr] = idx #binding.pry else new_args << arg end if SymbolTable.issym?(arg) then SymbolTable.push(999, arg, :var) next end idx += 1 end instr[:args] = new_args #binding.pry if instr[:instr_nr] == 1003 end end def self.issym?(token) if token.is_a? Integer then return false end if ISA::REGS.include?(token) then return false end if ISA::COND.include?(token) then return false end if token == 'NO ARG TEMPLATE' then return false end return true end def self.placeinstr() $last_addr = $code_ptr $instructions.each do |instr| # if instr[:mem] then # next # end if instr[:no_reloc] then instr[:addr] = instr[:no_reloc] else if instr[:byte2] then instr[:addr] = $last_addr - 1 else instr[:addr] = $last_addr $last_addr += 2 end end end #binding.pry end def self.placemem() if $data_ptr != 0 then if $last_addr > $data_ptr then Error.mexit("ERROR: .code and .data sections overlap") end ptr = $data_ptr lock_loc = 1; else ptr = $last_addr end i = 0 init_mem = [] bss_mem = [] #binding.pry while(i <= $mem_instructions.length - 1) do if $mem_instructions[i][:bss] then bss_mem << $mem_instructions[i] else init_mem << $mem_instructions[i] end i +=1 end $mem_instructions = init_mem + bss_mem i = 0 while(i <= $mem_instructions.length - 1) do instr = $mem_instructions[i] # for byte loads: check if next is also a byte then merge and skip one; other wise proceed as normal # we cannot fully skip the 2nd byte since we need to leave a breadcrumb to resolve the address if instr[:byte_enable] && $mem_instructions[i+1] && $mem_instructions[i+1][:byte_enable] then # byte_1 #binding.pry instr[:args][0] = instr[:args][0] << 8 | $mem_instructions[i+1][:args][0] instr[:addr] = ptr $instructions << instr # byte_2 $mem_instructions[i+1][:byte2] = true $mem_instructions[i+1][:addr] = ptr + 1 $instructions << $mem_instructions[i+1] ptr += 2 i += 2 # skip the 2nd byte since we already added it else instr[:addr] = ptr $instructions << instr ptr += 2 i += 1 end if lock_loc == 1 then instr[:no_reloc] = instr[:addr] end end #binding.pry end def self.resolveptrs() $symbols.each do |nr, sym| #binding.pry if sym[:ptr] then sym[:addr] = find_instr_nr(sym[:ptr]) #puts "resolve: ptr(#{sym[:ptr]} => #{$instructions[sym[:ptr]][:addr]})\n" end end dump() end def self.adjustla16(resolve) to_delete = [] $instructions.each_with_index do |instr, idx| if instr[:no_reloc] then next end if ["lda", "addhi"].include?(instr[:command]) && instr[:adjust] then arg = instr[:args][1] if SymbolTable.issym?(arg) then argr = arg arg = SymbolTable.resolvesym(arg) puts "Resolved: #{argr} into #{SymbolTable.resolvesym(argr)} (#{instr[:instr_nr]})\n" end # evaluate calculation if resolve && instr[:calc] then argstr = arg.to_s+instr[:calc] arg = eval(argstr) #binding.pry end #binding.pry if instr[:instr_nr] == 2427 adjarg = parsela16(instr[:command], arg) if adjarg == :nop then $instructions.delete_at(idx) end if resolve then instr[:args][1] = adjarg #binding.pry end end end end def self.parsela16(cmd, addr) # la16 allows the compiler to load an arbitrary length (up to 16b) address in a reg # here we check its length and see if we need 1 or 2 instructions puts "parsela16: #{addr}\n" if addr <= 511 then if cmd == "lda" then # addr is small enough to load with lda return addr else # commmand == addhi which is not needed return :nop end else # addr requires two instructions to load if cmd == "lda" then #binding.pry return (addr & 0x1ff) else return (addr & 0xfe00) >> 9 end end end def self.find_instr_nr(nr) # for performance we could build a seperate ordered hash of linenr => addr # lets deal with that later #binding.pry $instructions.each do |instr| #binding.pry return instr[:addr] if instr[:instr_nr] == nr #puts "found: #{instr[:addr]}\n" end SymbolTable.dump() puts "Error: cannot resolve ptr: #{nr}\n" exit end def self.resolvesym(name) $symbols.each do |nr, symbol| #binding.pry return symbol[:addr] if symbol[:name] == name end return false end def self.push(ptr, name, type) #binding.pry s = { name: name, type: type} #does the symbol already exist? #if name == "r1" then binding.pry end if SymbolTable.find(name) then if s[:type] == :label then puts "triggered!" existing_key = SymbolTable.findindex(s) $symbols.delete(existing_key) s[:ptr] = ptr $symbols[existing_key] = s return else puts " - exists" return end end #is it a label? if s[:type] == :label then s[:ptr] = ptr end #add the symbol to the table $symbols[$symnr] = s $symnr +=1 end def self.find(name) $symbols.each do |nr, symbol| return symbol if symbol[:name] == name end return false end def self.findaddr(addr) $symbols.each do |nr, symbol| return symbol if symbol[:addr] == addr end return false end def self.findindex(symbol) # clients.select{|key, hash| hash["client_id"] == "2180" } matches = $symbols.find{ |index, s| s[:name] == symbol[:name] } puts "matches: #{matches[0]}" return matches[0] end def self.dump() puts "- SYMBOL TABLE ----- (#{$symbols.length})" $symbols.each do |nr, symbol| if symbol[:addr].nil? then #binding.pry Error.mexit("Encountered undefined symbol: '#{symbol[:name]}'") end puts "#{nr} => #{symbol} (#{(symbol[:addr]).to_s(16)})\n" end end end class Coder def self.build() # $instructions.each do |instr| #binding.pry if instr[:label] || instr[:byte2] then next end code = encode(instr) if code.length != 16 then binding.pry puts "Coder::build: code malformed (#{code.length} instead of 16b)\n" exit end instr[:code] = code end end def self.encode(instr) code = "" puts "Encoding: #{instr}\n" #binding.pry instr[:opcode] = ISA::OPCODES[instr[:command]] if instr[:opcode].nil? then puts "Unknown instruction: #{instr[:command]}\n" exit end # some code to allow me to use ldw, ldb, stw and stb for 2 opcodes if [4,5,6,7].include?(instr[:opcode]) then # command is ldw, ldb, stw, stb # find out if its idx/base or imm/bp if instr[:command][0] == 'l' then unless instr[:args][1].is_a?(Integer) && instr[:args][2] == 'bp' then instr[:opcode] += 20 instr[:command] = ISA::OPCODES.key(instr[:opcode]) end else unless instr[:args][0].is_a?(Integer) && instr[:args][1] == 'bp' then instr[:opcode] += 20 instr[:command] = ISA::OPCODES.key(instr[:opcode]) end end end if instr[:opcode] == :mem then code = "" elsif instr[:opcode] <= 3 then code += "0" code += "%02b" % instr[:opcode] else code += "1" code += "%06b" % instr[:opcode] end if instr[:no_args] then code += "000000000" return code end #i = 0 #binding.pry ISA::ARGS[instr[:command]].each do |template, argnr| # get the right arg from argtemplate #binding.pry #template = argtemplate.keys[i] arg = instr[:args][argnr] unless argnr == :x #i += 1 #binding.pry if SymbolTable.issym?(arg) then argr = arg arg = SymbolTable.resolvesym(arg) puts "Resolved: #{argr} into #{SymbolTable.resolvesym(argr)}\n" #binding.pry #if instr[:instr_nr] == 1827 end case template when :imm16 code += bitsfromint(arg, 16, false) when :imm10 code += bitsfromint(arg, 10, true) when :imm13br # we need to calculate the relative offset # instructions are +2 # and we need to account for the extra increment the CPU does #binding.pry if arg > instr[:addr] then loc = arg - (instr[:addr] + 2) else loc = arg - (instr[:addr] + 2) end if loc > 4095 || loc < -4095 then Error.mexit("BR: br max offset is 4095. Instruction at #{instr[:addr]} is trying to br #{loc}") end #binding.pry puts "BR: calculated offset #{loc}\n" code += bitsfromint(loc, 13, true) when :imm7 code += bitsfromint(arg, 7, true) when :imm4 if arg == 0 then Error.mexit("shift amount cannot equal zero") end code += bitsfromint(arg, 4, false) when :imm7u code += bitsfromint(arg, 7, false) when :immir if ISA::IRIMM[arg.to_i].nil? then puts "Encode: no encoding available for immidiate: #{arg}\n" exit end code += "%03b" % ISA::IRIMM[arg.to_i] when :reg, :reg1, :reg2 #binding.pry if instr[:instr_nr] == 131 code += "%03b" % ISA::REGS[arg] when :tgt2 #binding.pry if ISA::REGS2[arg].nil? then Error.mexit("Encode: instruction can only target R1-R4") end code += "%02b" % ISA::REGS2[arg] when :xr0 code += "000" when :BPreg if arg.upcase != "BP" then puts "Encode: base must be bp/r5" exit(1) end when :R0reg if arg.upcase != "R0" then puts "Encode: error on stw0/stb0; not R0!" exit(1) end code += "00" when :pad3 code += "000" when :pad6 code += "000000" when :pad9 code += "000000000" when :cond code += "%03b" % ISA::COND[arg] else #binding.pry puts "Encode: cannot resolve argument: #{arg}(:#{template})\n" exit end end puts code return code end def self.bitsfromint(int, bitnr, sext) #binding.pry #if int == false if sext then # MSB reserved for sign # 13bits -> 12 bits signed -> max 0xfff # 10bits -> 9 bits signed -> max 0x1FF # 7 bits -> 6 bits signed -> max 0x3f if int.abs > ((2**(bitnr-1))-1) then Error.mexit("Bitsfromint: signed int #{int} cannot fit in #{bitnr} bits!") end if int < 0 then bin = (int & 0xffff).to_s(2) # bin will always be 16b long offset = 15 - bitnr bin.slice!(0..offset) return bin else return "%0#{bitnr}b" % int end else # we can use all the bits if int < 0 then puts "Bitsfromint: unsigned number cannot be negative! (#{int})\n" exit end if int > ((2**bitnr)-1) then Error.mexit("Bitsfromint: unsigned int #{int} cannot fit in #{bitnr} bits!") end return "%0#{bitnr}b" % int end end end class Writer def self.addhex() $instructions.each do |instr| next if instr[:byte2] code = instr[:code] b0 = code[0..7] b1 = code[8..15] h0 = b0.to_i(2) h1 = b1.to_i(2) hex = (h0.to_i == 0) ? "00" : "%02x" % h0 hex += (h1.to_i == 0) ? "00" : "%02x" % h1 instr[:hex] = hex instr[:h0] = h0 instr[:h1] = h1 end end def self.write(file, target) # FIXME: this loop is called n times, could just store result in instr_hash if target == :bin && $header then Writer.writeheader(file) end $instructions.each do |instr| next if instr[:byte2] case target when :hex Writer.hex(file, instr[:hex]) when :simple_hex if $code_ptr > 0 && instr[:addr] < 10 then next end Writer.simplehex(file, instr[:hex]) when :ram Writer.mif(file, (instr[:addr]/2), instr[:code], target) when :sim Writer.mif(file, instr[:addr], instr[:code], target) when :bin Writer.bin(file, instr[:h0], instr[:h1]) when :list Writer.list(file, instr[:addr], instr[:hex], instr[:line]) end end end def self.writeheader(output) header = [] header << 0xbabe header << $last_addr header << 0 # entry point assumed to be 0, would need special identifier output.write(header.pack("nnn")) end def self.bin(output, h0, h1) h = [(h0<<8)|h1] output.write(h.pack("n")) end def self.list(output, addr, hex, line) # FIXME: this is a very expensive way to add labels to the listing(but safe) if s=SymbolTable.findaddr(addr) then output.write(" : | #{s[:name]}:\n") end output.write("%04x" % addr) output.write(" : #{hex} | #{line}\n") end def self.simplehex(output, hex) # iverilog cannot load to address # so we need to output two files: 1. code and 2. data # since data is loaded not immediately after... output.write(hex) output.write("\n") end def self.hex(output, hex) if ($hex_addr % 16) > 0 then output.write("#{hex} ") else output.write("\n") output.write("%04x: " % $hex_addr) output.write("#{hex} ") end $hex_addr += 2 end def self.mifinit(output) $mif_addr = 0 output.write("DEPTH = 8192;\n") output.write("WIDTH = 16;\n") output.write("ADDRESS_RADIX = HEX;\n") output.write("DATA_RADIX = BIN;\n") output.write("CONTENT\n") output.write("BEGIN\n") output.write("\n") end def self.mif(output, addr, code, target) #output.write("%04x" % addr) output.write("%04x" % $mif_addr) output.write(" : ") output.write(code) output.write(";\n") if target == :ram then $mif_addr +=1 else $mif_addr +=2 end end def self.mifclose(output) output.write("\n") output.write("END;") end end class ISA OPCODES= { "ldi" => 0, "lda" => 0, "br" => 1, "ldw" => 4, "ldb" => 5, "stw" => 6, "stb" => 7, "stw0" => 8, "stb0" => 9, "add" => 10, "mov" => 10, "sub" => 11, "and" => 12, "or" => 13, "skip" => 14, "addskp.z" => 15, "addskp.nz" => 16, "addi" => 17, "subi" => 18, "andi" => 19, "ori" => 20, "addskpi.z" => 22, "addskpi.nz" => 23, "ldw.b" => 24, "ldb.b" => 25, "stw.b" => 26, "stb.b" => 27, "sext" => 28, "addhi" => 30, "push" => 31, "pop" => 32, "br.r" => 33, "syscall" => 34, "reti" => 35, "push.u" => 36, "brk" => 37, "lcr" => 38, "wcr" => 39, "wpte" => 40, "lpte" => 41, "wptb" => 42, "lptb" => 43, "wivec" => 44, "shl" => 45, "shr" => 46, "shl.r" => 47, "shr.r" => 48, "pop.u" => 49, "lcr.u" => 50, "wcr.u" => 51, "defw" => :mem, "defb" => :mem, "hlt" => 63, "nop" => 200 }.freeze # these templates reflect the order in which args should end up in the encoding # template => arg number from parse (e.g. order in isa) ARGS= { "ldi" => {:imm10 => 1, :reg => 0}, "lda" => {:imm10 => 1, :reg => 0}, "br" => {:imm13br => 0}, "ldw" => {:imm7 => 1, :BPreg => 2, :tgt2 => 0}, "ldb" => {:imm7 => 1, :BPreg => 2, :tgt2 => 0}, "stw" => {:imm7 => 0, :BPreg => 1, :tgt2 => 2}, "stb" => {:imm7 => 0, :BPreg => 1, :tgt2 => 2}, "stw0" => {:imm7 => 0, :BPreg => 1, :R0reg => 2}, "stb0" => {:imm7 => 0, :BPreg => 1, :R0reg => 2}, "add" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "mov" => {:reg => 1, :xr0 => :x, :reg1 => 0}, "sub" => {:reg =>1, :reg1 => 2, :reg2 => 0}, "and" => {:reg =>1, :reg1 => 2, :reg2 => 0}, "or" => {:reg =>1, :reg1 => 2, :reg2 => 0}, "skip" => {:reg => 0, :reg1 => 1, :cond => 2}, "addskp.z" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "addskp.nz" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "addi" => {:immir => 2, :reg =>1, :reg2 => 0}, "andi" => {:immir => 2, :reg =>1, :reg2 => 0}, "subi" => {:immir => 2, :reg =>1, :reg2 => 0}, "ori" => {:immir => 2, :reg =>1, :reg2 => 0}, "addskpi.z" => {:immir => 2, :reg => 1, :reg1 => 0}, "addskpi.nz" => {:immir => 2, :reg => 1, :reg1 => 0}, "ldw.b" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "ldb.b" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "stw.b" => {:reg => 0, :reg1 => 1, :reg2 => 2}, "stb.b" => {:reg => 0, :reg1 => 1, :reg2 => 2}, "sext" => {:reg => 0, :pad3 => :x, :reg1 => 1}, "addhi" => {:imm7u => 1, :tgt2 => 0}, "push" => {:pad6 => :x, :reg => 0}, "pop" => {:pad6 => :x, :reg => 0}, "br.r" => {:pad6 => :x, :reg => 0}, "syscall" =>{:pad9 => :x}, "reti" =>{:pad9 => :x}, "push.u" => {:pad6 => :x, :reg => 0}, "brk" =>{:pad9 => :x}, "lcr" => {:pad6 => :x, :reg => 0}, "wcr" => {:reg => 0, :pad6 => :x}, "wpte" => {:reg => 0, :reg1 => 1, :pad3 => :x}, "lpte" => {:reg => 1, :pad3 => :x, :reg1 => 0}, "wptb" => {:reg => 0, :pad6 => :x}, "lptb" => {:pad6 => :x, :reg => 0}, "wivec" => {:pad6 => :x, :reg => 0}, "shl" => {:imm4 => 2, :reg => 1, :tgt2 => 0}, "shr" => {:imm4 => 2, :reg => 1, :tgt2 => 0}, "shl.r" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "shr.r" => {:reg => 1, :reg1 => 2, :reg2 => 0}, "pop.u" => {:pad6 => :x, :reg => 0}, "lcr.u" => {:pad6 => :x, :reg => 0}, "wcr.u" => {:reg => 0, :pad6 => :x}, "defw" => {:imm16 => 0}, "defb" => {:imm16 => 0} }.freeze REGS= { "r0" => 0, 0 => 0, "r1" => 1, "r2" => 2, "r3" => 3, "r4" => 4, "r5" => 5, "bp" => 5, "sp" => 6, "r6" => 6, "pc" => 7 }.freeze REGS2= { "r1" => 0, "r2" => 1, "r3" => 2, "r4" => 3 }.freeze IRIMM= { #{ 1,2,4,8,-8,-4,-2,-1 } 1 => 0, 2 => 1, 4 => 2, 8 => 3, -8 => 4, -4 => 5, -2 => 6, -1 => 7 }.freeze MEMINSTR= { "defw" => 1, # define word "defb" => 2, # define byte "defstr" => 3, # define string "defs" => 4 # reserve n bytes }.freeze COND= { "eq" => 0, "ne" => 1, "lt" => 2, "lte" => 3, "gt" => 4, "gte" => 5, "ult" => 6, "ulte" => 7 } end class Error def self.mexit(msg) puts "\n#{msg}\n\n" exit(1) end end # main args = Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?:=(\S+))?/) ] file_name = args["f"] if args["h"] then $header = true end if file_name.nil? then Error.mexit("ERROR: no filename given\n") end input = File.open(file_name, "r") #out_hex = File.open("A.hex", "w+") out_bin = File.open("A.bin", "w+") sim_mif = File.open("A_sim.mif", "w+") ram_mif = File.open("A_ram.mif", "w+") simple_hex = File.open("A_simple.hex", "w+") listing = File.open("A_old.list", "w+") $instructions = [] $list = [] $mem_instructions =[] $labels = [] $symbols = {} $instr_nr = 0 $symnr = 0 $code_ptr = 0 $data_ptr = 0 $last_addr = 0 $hex_addr = 0 $double_label_guard = 0 # problem is i have 1 uncertain instruction: addhi which might not be needed: # we do this: # 1. resolve symbols -> first addresses # 2. process la16s and identify unneeded addhi's - we could stop at like 2x 0x3ff probably # 3. update addresses and resolve symbols again # ALSO: if we load .data above 0x3ff (1023) all constant loads need two instructions # this is only ~1000 instructions so it is safe to assume that all global loads will be 2 instructions # but branching will also be below, we could optimise this later #SymbolTable.loadpredefined() Parser.parse(input) SymbolTable.idsymbols() SymbolTable.placeinstr() SymbolTable.placemem() SymbolTable.resolveptrs() SymbolTable.adjustla16(false) SymbolTable.placeinstr() SymbolTable.resolveptrs() SymbolTable.adjustla16(true) Coder.build() Writer.addhex() Writer.write(out_bin, :bin) Writer.mifinit(ram_mif) Writer.write(ram_mif, :ram) Writer.mifinit(sim_mif) Writer.write(sim_mif, :sim) Writer.write(simple_hex, :simple_hex) Writer.write(listing, :list) Writer.mifclose(ram_mif) Writer.mifclose(sim_mif) SymbolTable.dump() #puts "\n------ Instruction tokens -----------\n" #$instructions.each do |instr| # puts "0x#{(instr[:addr]).to_s(16)} => #{instr}\n" #end
LITTLE_WORDS = %w( and as but for if nor or so yet a an the at by in of off on per to up via over ) def echo(what) what end def shout(what) what.upcase end def repeat (what, count=2) ((what + " " ) * (count - 1)) + what end def start_of_word (what, count) what[0, count] end def first_word (what) what.partition(" ").first end def titleize (text) words = text.split capitalized_words = words.map do |w| next w if LITTLE_WORDS.include?(w) w.capitalize end capitalized_words[0] = capitalized_words[0].capitalize capitalized_words.join(' ') end
require File.join(File.dirname(__FILE__), "bitfield") class BloomFilter attr_accessor :bitfield def initialize(bitfield_size) @bitfield = BitField.new(bitfield_size) end def hashes(item) [item.hash, item.crypt("42").hash, item.sum] end def add(item) field_size = @bitfield.length hashes(item.to_s).each do |item_hash| @bitfield[item_hash % field_size] = 1 end end def includes?(item) field_size = @bitfield.length hashes(item).each do |item_hash| return false unless @bitfield[item_hash % field_size] == 1 end true end def saturation @bitfield.saturation.to_f / @bitfield.length.to_f end def to_s @bitfield.to_s end end
class CouponsController < ApplicationController before_filter :must_be_signed_in before_filter :must_be_admin_user, :except => [:index, :show] # show the page for creating a coupon def new @title = "Create a new coupon" @coupon = Coupon.new end # used when we need to change a coupon that's already in the system def edit @title = "Edit coupon" @coupon = Coupon.find_by_id(params[:id]) end # use this to create a new coupon def create @coupon = Coupon.new(params[:coupon]) if @coupon.save flash[:success] = "Coupon saved to database" redirect_to coupons_path else @title = "Create a new coupon" render 'new' end end # we want to show the selected coupon def show @coupon = Coupon.find_by_id(params[:id]) if current_user.days_until_available(@coupon) > 0 @coupon = nil else current_user.use_coupon!(@coupon) end end # the action of editing a coupon, ie pushing a change to the database def update @coupon = Coupon.find_by_id(params[:id]) if @coupon.update_attributes(params[:coupon]) flash[:success] = "Coupon updated." redirect_to coupons_path else @title = "Edit coupon" render 'edit' end end # we can use index to show all coupons def index @title = "All coupons" @coupons = Array.new Coupon.find(:all, :order => "created_at").each do |item| @coupons << item end #@coupons = Coupon.all.sort! { :created_at } #@coupons_pag = Coupon.paginate( :page => params[:page]) end # to delete a coupon def destroy Coupon.find(params[:id]).destroy flash[:success] = "Coupon destroyed." redirect_to coupons_path end private end
class PurchaseAddress include ActiveModel::Model attr_accessor :user_id, :item_id, :post_code,:prefecture_id, :city, :address, :building_name, :phone_number, :purchase_id, :token with_options presence:true do validates :post_code,format: {with: /\A[0-9]{3}-[0-9]{4}\z/} validates :city validates :address validates :phone_number,format: {with: /\A[0-9]{10,11}\z/ } validates :prefecture_id, numericality:{other_than: 1} validates :token validates :user_id validates :item_id end def save purchase = Purchase.create(user_id:user_id,item_id:item_id) Address.create(post_code:post_code,prefecture_id:prefecture_id, city:city, address:address, building_name:building_name, phone_number:phone_number,purchase_id:purchase.id) end end
require "roo" class Facility < ApplicationRecord include Mergeable include QuarterHelper include PgSearch::Model include LiberalEnum extend FriendlyId extend RegionSource attribute :import, :boolean, default: false attribute :organization_name, :string attribute :facility_group_name, :string belongs_to :facility_group, optional: true has_many :phone_number_authentications, foreign_key: "registration_facility_id" has_many :users, through: :phone_number_authentications has_and_belongs_to_many :teleconsultation_medical_officers, -> { distinct }, class_name: "User", association_foreign_key: :user_id, join_table: "facilities_teleconsultation_medical_officers" has_many :encounters has_many :blood_pressures, through: :encounters, source: :blood_pressures has_many :blood_sugars, through: :encounters, source: :blood_sugars has_many :patients, -> { distinct }, through: :encounters has_many :prescription_drugs has_many :appointments has_many :teleconsultations has_many :registered_patients, class_name: "Patient", foreign_key: "registration_facility_id" has_many :registered_diabetes_patients, -> { with_diabetes }, class_name: "Patient", foreign_key: "registration_facility_id" has_many :registered_hypertension_patients, -> { with_hypertension }, class_name: "Patient", foreign_key: "registration_facility_id" has_many :assigned_patients, class_name: "Patient", foreign_key: "assigned_facility_id" has_many :assigned_hypertension_patients, -> { with_hypertension }, class_name: "Patient", foreign_key: "assigned_facility_id" pg_search_scope :search_by_name, against: {name: "A", slug: "B"}, using: {tsearch: {prefix: true, any_word: true}} enum facility_size: { community: "community", small: "small", medium: "medium", large: "large" } liberal_enum :facility_size auto_strip_attributes :name, squish: true, upcase_first: true auto_strip_attributes :district, squish: true, upcase_first: true auto_strip_attributes :zone, squish: true, upcase_first: true with_options if: :import do |facility| facility.validates :organization_name, presence: true facility.validates :facility_group_name, presence: true facility.validate :facility_name_presence facility.validate :organization_exists facility.validate :facility_group_exists facility.validate :facility_is_unique end with_options unless: :import do |facility| facility.validates :name, presence: true end alias_attribute :block, :zone validates :district, presence: true validates :state, presence: true validates :country, presence: true validates :zone, presence: true, on: :create validates :pin, numericality: true, allow_blank: true validates :facility_size, inclusion: {in: facility_sizes.values, message: "not in #{facility_sizes.values.join(", ")}", allow_blank: true} validates :enable_teleconsultation, inclusion: {in: [true, false]} validates :teleconsultation_medical_officers, presence: { if: :enable_teleconsultation, message: "must be added to enable teleconsultation" } validates :enable_diabetes_management, inclusion: {in: [true, false]} delegate :protocol, to: :facility_group, allow_nil: true delegate :organization, :organization_id, to: :facility_group, allow_nil: true delegate :follow_ups_by_period, to: :patients, prefix: :patient def hypertension_follow_ups_by_period(*args) patients .hypertension_follow_ups_by_period(*args) .where(blood_pressures: {facility: self}) end def diabetes_follow_ups_by_period(*args) patients .diabetes_follow_ups_by_period(*args) .where(blood_sugars: {facility: self}) end friendly_id :name, use: :slugged # For compatibility w/ parent FacilityGroups def facilities [self] end def recent_blood_pressures blood_pressures.includes(:patient, :user).order(Arel.sql("DATE(recorded_at) DESC, recorded_at ASC")) end def cohort_analytics(period:, prev_periods:) query = CohortAnalyticsQuery.new(self, period: period, prev_periods: prev_periods) query.call end def dashboard_analytics(period: :month, prev_periods: 3, include_current_period: false) query = FacilityAnalyticsQuery.new(self, period, prev_periods, include_current_period: include_current_period) query.call end CSV_IMPORT_COLUMNS = { organization_name: "organization", facility_group_name: "facility_group", name: "facility_name", facility_type: "facility_type", street_address: "street_address (optional)", village_or_colony: "village_or_colony (optional)", zone: "zone_or_block", district: "district", state: "state", country: "country", pin: "pin (optional)", latitude: "latitude (optional)", longitude: "longitude (optional)", facility_size: "size (optional)", enable_diabetes_management: "enable_diabetes_management (true/false)" } def self.parse_facilities(file_contents) facilities = [] CSV.parse(file_contents, headers: true, converters: :strip_whitespace) do |row| facility = CSV_IMPORT_COLUMNS.map { |attribute, column_name| [attribute, row[column_name]] }.to_h next if facility.values.all?(&:blank?) facilities << facility.merge(enable_diabetes_management: facility[:enable_diabetes_management] || false, enable_teleconsultation: facility[:enable_teleconsultation] || false, import: true) end facilities end def organization_exists organization = Organization.find_by(name: organization_name) errors.add(:organization, "doesn't exist") if organization_name.present? && organization.blank? end def facility_group_exists organization = Organization.find_by(name: organization_name) if organization.present? facility_group = FacilityGroup.find_by(name: facility_group_name, organization_id: organization.id) end if organization.present? && facility_group_name.present? && facility_group.blank? errors.add(:facility_group, "doesn't exist for the organization") end end def facility_is_unique organization = Organization.find_by(name: organization_name) if organization.present? facility_group = FacilityGroup.find_by(name: facility_group_name, organization_id: organization.id) end facility = Facility.find_by(name: name, facility_group: facility_group.id) if facility_group.present? errors.add(:facility, "already exists") if organization.present? && facility_group.present? && facility.present? end def facility_name_presence if name.blank? errors.add(:facility_name, "can't be blank") end end def diabetes_enabled? enable_diabetes_management.present? end def opd_load_estimated? monthly_estimated_opd_load.present? end def opd_load monthly_estimated_opd_load || opd_load_for_facility_size end def opd_load_for_facility_size case facility_size when "community" then 450 when "small" then 1800 when "medium" then 3000 when "large" then 7500 else 450 end end def teleconsultation_enabled? enable_teleconsultation.present? end def teleconsultation_phone_number_with_isd teleconsultation_phone_numbers_with_isd.first end def teleconsultation_phone_numbers_with_isd teleconsultation_medical_officers.map(&:full_teleconsultation_phone_number) end CSV::Converters[:strip_whitespace] = ->(value) { begin value.strip rescue value end } def discardable? registered_patients.none? && blood_pressures.none? && blood_sugars.none? && appointments.none? end end
class User < ApplicationRecord has_many :usertest has_many :tests, through: :usertests end
class AddGoodsMaterials < ActiveRecord::Migration def change create_table :goods_materials do |t| t.belongs_to :good t.belongs_to :material end end end
class CreateTokenIndexOnAccessTokens < ActiveRecord::Migration def up # Since we are using rails generate for the token, # we are actually guaranteed uniqueness, which is # neat. add_index(:access_tokens, :token, { name: "access_tokens_token_index", uniq: true, length: 16 }) end def down remove_index(:access_tokens, name: "access_tokens_token_index") end end
require "pry" class User attr_accessor :username, :age @@all = [] def initialize(username, age) @username = username @age = age @@all << self end def self.all @@all end end
class Location < ActiveRecord::Base # @param [float] total_distance # @return [Location] def self.current_location(total_distance) Location.where('total_distance <= ?', total_distance).order('number desc').first end def self.reverse_current_location(total_distance) Location.where("#{Location.max_total_distance} - total_distance <= ?", total_distance).order('number').first end def self.max_total_distance Location.select('max(total_distance) as total_distance').first.total_distance end end
def hopper programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } return programmer_hash[:grace_hopper]; end def alan_kay_is_known_for # What combination of keys would you use to return the value of the :known_for key of :alan_kay? programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } return programmer_hash[:alan_kay][:known_for]; end def dennis_ritchies_language programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } return programmer_hash[:dennis_ritchie][:languages][0]; end def adding_matz # add the following information to the top level of programmer_hash # :yukihiro_matsumoto => { # :known_for => "Ruby", # :languages => ["LISP", "C"] # } programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } programmer_hash[:yukihiro_matsumoto] = {:known_for => "Ruby", :languages => ["LISP", "C"]}; return programmer_hash; end def changing_alan programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } #change what Alan Kay is :known_for to the value of the alans_new_info variable. alans_new_info = "GUI" # did statement was already here in this lab, I did not input this. programmer_hash[:alan_kay][:known_for] = alans_new_info; return programmer_hash; end def adding_to_dennis programmer_hash = { :grace_hopper => { :known_for => "COBOL", :languages => ["COBOL", "FORTRAN"] }, :alan_kay => { :known_for => "Object Orientation", :languages => ["Smalltalk", "LISP"] }, :dennis_ritchie => { :known_for => "Unix", :languages => ["C"] } } # programmer_hash[:dennis_ritchie][:languages].push "Assembly"; programmer_hash[:dennis_ritchie][:languages] << "Assembly"; return programmer_hash; end puts hopper(); # {:known_for=>"COBOL", :languages=>["COBOL", "FORTRAN"]} puts alan_kay_is_known_for # Object Orientation puts dennis_ritchies_language # C puts adding_matz # {:grace_hopper=>{:known_for=>"COBOL", :languages=>["COBOL", "FORTRAN"]}, :alan_kay=>{:known_for=>"Object Orientation", :languages=>["Smalltalk", "LISP"]}, :dennis_ritchie=>{:known_for=>"Unix", :languages=>["C"]}, :yukihiro_matsumoto=>{:known_for=>"Ruby", :languages=>["LISP", "C"]}} puts changing_alan # {:grace_hopper=>{:known_for=>"COBOL", :languages=>["COBOL", "FORTRAN"]}, :alan_kay=>{:known_for=>"GUI", :languages=>["Smalltalk", "LISP"]}, :dennis_ritchie=>{:known_for=>"Unix", :languages=>["C"]}} puts adding_to_dennis # {:grace_hopper=>{:known_for=>"COBOL", :languages=>["COBOL", "FORTRAN"]}, :alan_kay=>{:known_for=>"Object Orientation", :languages=>["Smalltalk", "LISP"]}, :dennis_ritchie=>{:known_for=>"Unix", :languages=>["C", "Assembly"]}}
#!/usr/bin/env ruby require_relative "../lib/api_communicator.rb" require_relative "../lib/command_line_interface.rb" def welcome puts "Welcome, User" end def get_character_from_user puts "Please enter character name:" gets.chomp end welcome character = get_character_from_user show_character_movies(character)
# # Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # In XML requests, the quota is embedded as a node in the container object, # because more than one root nodes are not allowed. # # In other types of requests, the quota param is in the "root" and the # controllers are written to expect that. # # For XML requests we need to move the quota params back to the "root". module QuotaAware def set_quota_param(node_where_quota_is_embedded) if !params.has_key? :quota and !params[node_where_quota_is_embedded][:quota].nil? params[:quota] = params[node_where_quota_is_embedded][:quota] params[node_where_quota_is_embedded].delete(:quota) end end def set_quota(quota_aware_model) limit = if params.has_key? :quota and not params[:unlimited_quota] params[:quota][:maximum_running_instances] else nil end quota_aware_model.quota.set_maximum_running_instances(limit) end end
initializer("active_record.rb") do <<-CODE # encoding: utf-8 class ActiveRecord::Base def self.random random = rand(count) uncached do find(:first, :offset => random) end end def self.per_page(num=nil) @per_page = num if num @per_page || 10 end def self.t(name) human_attribute_name(name.to_s) end # mostly for tests def save_and_reload save reload end end CODE end git :add => "." git :commit => "-m 'added active_record.rb initializer'" initializer("module.rb") do <<-CODE # encoding: utf-8 class Module # A version of Rails' delegate method which enables the prefix and allow_nil def soft_delegate(*attrs) options = attrs.extract_options! options[:prefix] = true unless options.has_key?(:prefix) options[:allow_nil] = true unless options.has_key?(:allow_nil) attrs.push(options) delegate *attrs end end CODE end git :add => "." git :commit => "-m 'added module.rb initializer'" initializer("inaccessible_attributes.rb") do <<-CODE # encoding: utf-8 ActiveRecord::Base.send(:attr_accessible, nil) if Rails.env.test? or Rails.env.development? module ActiveRecord class MassAssignmentError < StandardError; end end ActiveRecord::Base.class_eval do def log_protected_attribute_removal(*attributes) raise ActiveRecord::MassAssignmentError, "Can't mass-assign these protected attributes: \#{attributes.join(', ')}" end end end CODE end git :add => "." git :commit => "-m 'added inaccessible_attributes.rb initializer'" # option with a list of fields to sanitize: plugin 'xss_terminate', :git => 'git://github.com/look/xss_terminate.git' inside('vendor/plugins/xss_terminate/test') do run("rm xss_terminate_test.rb") run("rm setup_test.rb") end git :add => "." git :commit => "-m 'added xss_terminate'" plugin 'demeters_revenge', :git => 'git://github.com/caius/demeters_revenge.git' git :add => "." git :commit => "-m 'added demeters_revenge'" #I18n run "curl -s -L http://github.com/unders/rails-i18n/raw/master/rails/locale/sv.yml > config/locales/sv.yml" run "curl -s -L http://github.com/unders/rails-i18n/raw/master/rails/locale/en.yml > config/locales/en.yml" # in environments/test.rb # config.i18n.default_locale = :en #in routes.rb #map.filter 'locale' # in application_controller.rb # before_filter :set_locale # # private # # def set_locale # parsed_locale = params[:locale] # if parsed_locale.present? and I18n.backend.available_locales.include?(parsed_locale.to_sym) # I18n.locale = parsed_locale # else # I18n.locale = I18n.default_locale # end # end # routing filter plugin git :add => "." git :commit => "-m 'added en.yml and sv.yml localization file'" gem 'formtastic', :lib => 'formtastic', :version => '>=0.9.7' rake "gems:install" generate "formtastic" git :add => "." git :commit => "-m 'added formtastic'" # validation_reflection plugin file 'lib/tasks/ci.rake' do <<-CODE namespace :ci do task :copy_yml do %x{cp \#{Rails.root}/config/database.yml.ci \#{Rails.root}/config/database.yml} end task :build => ['ci:copy_yml', 'db:migrate', 'spec', 'features'] do end end CODE end git :add => "." git :commit => "-m 'added lib/tasks/ci.rake'" file 'lib/tasks/super.rake' do <<-CODE task :supermigrate => ['environment', 'db:migrate', 'db:test:prepare'] do %x(cd \#{RAILS_ROOT} && annotate) end task :superspec => ['spec', 'cucumber'] do end CODE end git :add => "." git :commit => "-m 'added lib/tasks/super.rake'" file 'lib/tasks/capybara.rake' do <<-CODE namespace :capybara do desc "Deletes all capybara-*.html files in root directory" task :delete_files => :environment do %x(cd \#{Rails.root} && rm capybara-*.html) end end CODE end git :add => "." git :commit => "-m 'added lib/tasks/super.rake'" run "touch public/stylesheets/master.css" file 'app/views/layouts/application.html.erb' do <<-CODE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="shortcut icon" href="/favicon.ico" /> <%= stylesheet_link_tag 'master.css' %> </head> <body> <div id="flash-msg"> <%- flash.each do |name, msg| -%> <%= content_tag :div, msg, :class => "flash \#{name}" %> <%- end -%> </div> <%= yield %> <%= javascript_include_tag 'jquery.js', 'application.js' %> </body> </html> CODE end git :add => "." git :commit => "-m 'added layout file: app/views/layouts/application.html.erb'"
require 'cocoapods' RSpec.describe Podspec::Editor do it 'has a version number' do expect(Podspec::Editor::VERSION).not_to be nil end def origin_json_content File.read(File.expand_path('fixtures/A.podspec.json', __dir__)) end def generate_normal_editor PodspecEditor::Editor.new( json_path: File.expand_path('fixtures/A.podspec.json', __dir__) ) end describe PodspecEditor::Editor do describe 'initialize' do it 'initialize wrong file will raise error' do expect { PodspecEditor::Editor.new(json_path: 'Dangerfile') }.to raise_error(ArgumentError) end it 'initialize with a json path will not raise error' do editor = generate_normal_editor expect(editor.origin_json_content).to eq(origin_json_content) end it 'initialize with a spec path will not raise error' do editor = PodspecEditor::Editor.new( spec_path: File.expand_path('fixtures/A.podspec', __dir__) ) expect(editor.origin_json_content).to eq(origin_json_content) end end it 'generate default template for pod' do content = PodspecEditor::Editor.default_json_spec_content('RxSwift') expect(content) == "{\n \"name\": \"RxSwift\",\n \"version\": \"1.0.0\",\n \"summary\": \"TestPod summary\",\n \"lic...\n \"homepage\": \"https://www.example.com\",\n \"platforms\": {\n \"ios\": \"9.0\"\n },\n}\n" end it 'get value from spec' do editor = generate_normal_editor kvs = [ editor.spec.name => 'TestPod', editor.spec.version => '1.0.0', editor.spec.license => 'MIT', editor.spec.requires_arc => true, editor.spec.key_not_exist => nil, editor.spec.authors => OpenStruct.new('test' => 'test@test.com'), editor.spec.subspecs[0].name => 'SubSpecA', editor.spec.subspecs[0].dependencies => OpenStruct.new('Masonry': [], 'ReactiveObjC': [], 'SDWebImage': []) ] kvs.each do |kv| kv.each do |k, v| expect(k).to eq(v) end end end describe 'delete value from spec' do before :context do @editor = generate_normal_editor end it 'delete normal key' do @editor.spec.name = nil expect(@editor.spec.name).to eq(nil) @editor.spec.authors = nil expect(@editor.spec.authors).to eq(nil) end it 'delete non-exist key' do @editor.spec.key_not_exist = nil expect(@editor.spec.key_not_exist).to eq(nil) end it 'delete nested key' do @editor.spec.subspecs[0].source_files = nil expect(@editor.spec.subspecs[0].source_files).to eq(nil) end end describe 'update value from spec' do before :context do @editor = generate_normal_editor end it 'update first level key' do expect(@editor.spec.name).to eq('TestPod') new_name = 'NewTestPod' @editor.spec.name = new_name expect(@editor.spec.name).to eq(new_name) end it 'update nested key' do expect(@editor.spec.subspecs[0].name).to eq('SubSpecA') new_name = 'newNameA' @editor.spec.subspecs[0].name = new_name expect(@editor.spec.subspecs[0].name).to eq(new_name) new_source_files = ['A.h'] @editor.spec.subspecs[0].source_files = new_source_files expect(@editor.spec.subspecs[0].source_files).to eq(new_source_files) end it 'update invalid key will add new key to spec' do expect(@editor.spec.invlid_key).to eq(nil) new_value = 'value' @editor.spec.invlid_key = new_value expect(@editor.spec.invlid_key).to eq(new_value) end end describe 'generate json content' do before :context do @editor = generate_normal_editor end it 'current json content' do expect(@editor.current_json_content).to eq(origin_json_content) end it 'update value then generate json' do @editor.spec.name = 'NewTestPod' new_dependencies = OpenStruct.new('Masonry' => []) @editor.spec.subspecs[0].dependencies = new_dependencies expect(@editor.spec.subspecs[0].dependencies).to eq(new_dependencies) new_json_content = File.read(File.expand_path('fixtures/A_t.podspec.json', __dir__)).chomp expect(@editor.current_json_content).to eq(new_json_content) end end end end
def multiply_all_pairs(array_1, array_2) new_array = [] array_1.each do |first| array_2.each do |second| new_array << first * second end end new_array.sort end p multiply_all_pairs([2, 4], [4, 3, 1, 2]) == [2, 4, 4, 6, 8, 8, 12, 16] def multiply_all_pairs2(array_1, array_2) array_1.product(array_2).map {|num1, num2| num1 * num2}.sort end p multiply_all_pairs2([2, 4], [4, 3, 1, 2]) == [2, 4, 4, 6, 8, 8, 12, 16]
require 'rails_helper' require 'database_cleaner' describe "Transactions API" do describe "GET /transactions" do it "returns a list of all transactions" do i1 = Invoice.create i2 = Invoice.create t1 = Transaction.create(invoice_id: i1.id, credit_card_number: 4654405418249632, result: "good") t2 = Transaction.create(invoice_id: i2.id, credit_card_number: 4580251236515201, result: "bad") get "/api/v1/transactions" body = JSON.parse(response.body) transaction_credit_card_numbers = body.map {|m| m["credit_card_number"]} transaction_credit_card_expiration_dates = body.map {|m| m["credit_card_expiration_date"]} transaction_ids = body.map {|m| m["id"]} invoice_ids = body.map {|m| m["invoice_id"]} expect(response.status).to eq 200 expect(invoice_ids).to match_array([i1.id, i2.id]) expect(transaction_ids).to match_array([t1.id, t2.id]) expect(transaction_credit_card_numbers).to match_array(["4580251236515201", "4654405418249632"]) end end describe "GET /transactions/:id" do it "returns a specific transaction" do i1 = Invoice.create t1 = Transaction.create(invoice_id: i1.id, credit_card_number: 4654405418249632, result: "good") get "/api/v1/transactions/#{t1.id}" body = JSON.parse(response.body) transaction_credit_card_number = body["credit_card_number"] transaction_credit_card_expiration_date = body["credit_card_expiration_date"] transaction_id = body["id"] invoice_id = body["invoice_id"] expect(response.status).to eq 200 expect(invoice_id).to eq(i1.id) expect(transaction_id).to eq(t1.id) expect(transaction_credit_card_number).to eq("4654405418249632") end end end
require 'redis_bid' require 'fakeredis' require 'pry' describe RedisBid do before { RedisBid.redis.flushdb } let(:bid_id) { "BID_ID" } let(:user_id) { "USER_ID" } let(:second_user_id) { "SECOND_USER_ID" } describe "#register_bid_item" do context "when min_bid_score option is given and less than DEFAULT_MIN_BID_SCORE" do it { RedisBid.register_bid_item(bid_id, min_bid_score: RedisBid::DEFAULT_MIN_BID_SCORE - 1).should == false } after { RedisBid.is_registered?(bid_id).should be_false } end it "should add bid_id to redis set" do RedisBid.register_bid_item(bid_id) RedisBid.redis.sismember(RedisBid::BID_ITEMS_KEY_PREFIX, bid_id).should be_true RedisBid.is_registered?(bid_id).should be_true RedisBid.get_min_bid(bid_id).should == RedisBid::DEFAULT_MIN_BID_SCORE end it "min bid should be set to min bid score" do RedisBid.register_bid_item(bid_id, min_bid_score: 100) RedisBid.get_min_bid(bid_id).should == 100 end end describe "#set_min_bid" do context "when given bid_id is not registered" do it { expect { RedisBid.set_min_bid(bid_id, 100) }.to raise_error(RedisBid::ItemNotRegisteredError) } end context "for registered bid item" do before { RedisBid.register_bid_item(bid_id) } context "for score < DEFAULT_MIN_BID_SCORE" do it { expect { RedisBid.set_min_bid(bid_id, RedisBid::DEFAULT_MIN_BID_SCORE - 1) }.to raise_error(RedisBid::InvalidBidScoreError) } end it "should set minimum bid for a bid item" do RedisBid.get_min_bid(bid_id).should == RedisBid::DEFAULT_MIN_BID_SCORE RedisBid.set_min_bid(bid_id, 100) RedisBid.get_min_bid(bid_id).should == 100 end end end describe "#add_user_bid" do context "when bid_id is not registered yet" do it { expect {RedisBid.add_user_bid(user_id, bid_id, 100) }.to raise_error(RedisBid::ItemNotRegisteredError) } end context "when bid_id is registered" do before { RedisBid.register_bid_item(bid_id) } it { RedisBid.add_user_bid(user_id, bid_id, RedisBid.get_min_bid(bid_id) + 1).should == true } context "when score < min bid" do it { expect { RedisBid.add_user_bid(user_id, bid_id, RedisBid.get_min_bid(bid_id) - 1) }.to raise_error(RedisBid::InvalidBidScoreError) } end end end describe "#bid_items" do before { RedisBid.register_bid_item(bid_id) } it { RedisBid.bid_items.include?(bid_id).should be_true } end describe "#list_user_bids" do before { RedisBid.register_bid_item(bid_id) } before { RedisBid.add_user_bid(user_id, bid_id, 999) } it { RedisBid.list_user_bids(bid_id).include?(user_id).should be_true } it { RedisBid.list_user_bids(bid_id, with_scores: true).include?([user_id, 999]).should be_true } context "after adding another user bid" do before { RedisBid.add_user_bid(second_user_id, bid_id, 1000) } it { RedisBid.list_user_bids(bid_id).first.should == second_user_id } it { RedisBid.list_user_bids(bid_id, with_scores: true).first.should == [second_user_id, 1000] } it { RedisBid.list_user_bids(bid_id, order: "asc").first.should == user_id } it { RedisBid.list_user_bids(bid_id, with_scores: true, order: "asc").first.should == [user_id, 999] } end end describe "#num_user_bids" do before { RedisBid.register_bid_item(bid_id) } before { RedisBid.add_user_bid(user_id, bid_id, 999) } it { RedisBid.num_user_bids(bid_id).should == 1 } end describe "#remove_user_bid" do before { RedisBid.register_bid_item(bid_id) } it { RedisBid.remove_user_bid(user_id, bid_id).should == false } context "when user bid exists" do before { RedisBid.add_user_bid(user_id, bid_id, 999) } it { RedisBid.remove_user_bid(user_id, bid_id).should == true } end end describe "#unregister_bid_item" do context "when item is not registered" do it { expect { RedisBid.unregister_bid_item(bid_id) }.to raise_error(RedisBid::ItemNotRegisteredError) } end context "when item is registered" do before { RedisBid.register_bid_item(bid_id) } it { RedisBid.unregister_bid_item(bid_id).should == true } after { RedisBid.redis.hexists("min_bid", bid_id).should == false } end end after { RedisBid.redis.flushdb } end
class Dj include Mongoid::Document include Mongoid::Timestamps::Short field :name_first, type: String field :name_last, type: String field :email, type: String field :timezone, type: String field :requested_slot, type: String field :live, type: Mongoid::Boolean field :genres, type: String field :frequency, type: String field :broadcast_license, type: Mongoid::Boolean # Required Fields validates :name_first, :name_last, presence: true, length: { minimum: 2 } validates :email, :frequency, :requested_slot, presence: true validates :timezone, presence: true # Validation of select field values validates :requested_slot, inclusion: { in: %w(mor after even late onight), message: "%{value} is not a valid timeslot"} validates :genres, inclusion: { in: %w(talk avantgarde latin comedy country easylistening electronic folk hiphop jazz pop rnb blues rock ska other), message: "%{value} is not a valid genre"} # Additional validation validates :name_first, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } validates :name_last, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } validates :email, uniqueness: true validates :email, email: true validates :broadcast_license, :acceptance => {:accept => true} end
require 'spec_helper' describe PantographCore::UI do it "uses a PantographCore::Shell by default" do expect(PantographCore::UI.ui_object).to be_kind_of(PantographCore::Shell) end it "redirects all method calls to the current UI object" do expect(PantographCore::UI.ui_object).to receive(:error).with("yolo") PantographCore::UI.error("yolo") end it "allows overwriting of the ui_object for pantograph.ci" do third_party_output = "third_party_output" PantographCore::UI.ui_object = third_party_output expect(third_party_output).to receive(:error).with("yolo") PantographCore::UI.error("yolo") PantographCore::UI.ui_object = nil end end
# Extendable Grid column object. # Used to define a column in the grid registration DSL class RailsPowergrid::Column @default_options = {} @hash_making_callbacks = [] class << self attr_reader :default_options attr_reader :hash_making_callbacks # Set the default value for an option def default_for name, value @default_options[name] = value end # Add some fields to the output hash def add_to_hash &block @hash_making_callbacks << block end # Example: # # x = _call_of(:test) # x.call(a,b,c) => x.send(:test, a, b, c) # def _call_of(method) proc{ |*args| send(method, *args) } end end attr_reader :name attr_reader :opts # # Just an `instance_exec` wrapper, where the block is before # the arguments # def _exec block, *args instance_exec(*args, &block) end add_to_hash{{ field: name }} def initialize grid, name, opts={}, &block @name = name @opts = self.class.default_options.merge(opts) opts.each do |o, v| send("#{o.to_s.gsub(/\?$/, "")}=", v) end @grid = grid if block_given? DSL.new(self, &block) end end def model @grid.model end # Generate the hash defining the column client side # for ReactJS component. def to_hash out = {} self.class.hash_making_callbacks.each do |cb| out.merge!(instance_eval(&cb)) end out end end # I don't use module and include because I use some # class level functions, and I don't want to make concerns # in this case (theses should concern only the column, that's not reusable code) RailsPowergrid::_require "column/dsl" RailsPowergrid::_require "column/editor" RailsPowergrid::_require "column/filtering" RailsPowergrid::_require "column/form" RailsPowergrid::_require "column/getset" RailsPowergrid::_require "column/html" RailsPowergrid::_require "column/renderer" RailsPowergrid::_require "column/select" RailsPowergrid::_require "column/sorting" RailsPowergrid::_require "column/typing" RailsPowergrid::_require "column/visibility"
module Gitlab module Metrics module Subscribers # Class for tracking the total time spent in Rails cache calls class RailsCache < ActiveSupport::Subscriber attach_to :active_support def cache_read(event) increment(:cache_read_duration, event.duration) end def cache_write(event) increment(:cache_write_duration, event.duration) end def cache_delete(event) increment(:cache_delete_duration, event.duration) end def cache_exist?(event) increment(:cache_exists_duration, event.duration) end def increment(key, duration) return unless current_transaction current_transaction.increment(:cache_duration, duration) current_transaction.increment(key, duration) end private def current_transaction Transaction.current end end end end end
class UsersController < ApplicationController include AdminHelper layout "admin" before_filter :validate_admin before_filter :set_tab_index before_filter :prepare_config def set_tab_index @tab = 3 end def index @keyword = params[:keyword] if @keyword criteria = User.general_search @keyword else criteria = User.all end @users = criteria.page(params[:page]).per(10) @title = I18n.t "admin.user_list" render "admin/user/index" end end
# frozen_string_literals: true require 'rbconfig' require 'time' require 'thread' require 'securerandom' require 'logger' module Lumberjack LINE_SEPARATOR = (RbConfig::CONFIG['host_os'].match(/mswin/i) ? "\r\n" : "\n") require_relative "lumberjack/severity.rb" require_relative "lumberjack/formatter.rb" require_relative "lumberjack/context.rb" require_relative "lumberjack/log_entry.rb" require_relative "lumberjack/device.rb" require_relative "lumberjack/logger.rb" require_relative "lumberjack/tags.rb" require_relative "lumberjack/tag_formatter.rb" require_relative "lumberjack/tagged_logger_support.rb" require_relative "lumberjack/tagged_logging.rb" require_relative "lumberjack/template.rb" require_relative "lumberjack/rack.rb" class << self # Define a unit of work within a block. Within the block supplied to this # method, calling +unit_of_work_id+ will return the same value that can # This can then be used for tying together log entries. # # You can specify the id for the unit of work if desired. If you don't supply # it, a 12 digit hexidecimal number will be automatically generated for you. # # For the common use case of treating a single web request as a unit of work, see the # Lumberjack::Rack::UnitOfWork class. def unit_of_work(id = nil) id ||= SecureRandom.hex(6) context do context[:unit_of_work_id] = id yield end end # Get the UniqueIdentifier for the current unit of work. def unit_of_work_id context[:unit_of_work_id] end # Contexts can be used to store tags that will be attached to all log entries in the block. # # If this method is called with a block, it will set a logging context for the scope of a block. # If there is already a context in scope, a new one will be created that inherits # all the tags of the parent context. # # Otherwise, it will return the current context. If one doesn't exist, it will return a new one # but that context will not be in any scope. def context current_context = Thread.current[:lumberjack_context] if block_given? Thread.current[:lumberjack_context] = Context.new(current_context) begin yield ensure Thread.current[:lumberjack_context] = current_context end else current_context || Context.new end end # Return true if inside a context block. def context? !!Thread.current[:lumberjack_context] end # Return the tags from the current context or nil if there are no tags. def context_tags context = Thread.current[:lumberjack_context] context.tags if context end # Set tags on the current context def tag(tags) context = Thread.current[:lumberjack_context] context.tag(tags) if context end end end
require_relative 'db_connection' require 'active_support/inflector' require 'byebug' # NB: the attr_accessor we wrote in phase 0 is NOT used in the rest # of this project. It was only a warm up. class SQLObject def self.columns return @columns if @columns @columns = DBConnection.execute2(<<-SQL) SELECT * FROM #{table_name} SQL .first.map(&:to_sym) @columns end def self.finalize! # debugger # Now we can finally write ::finalize!. It should iterate through # all the ::columns, using define_method (twice) to create a getter # and setter method for each column, just like my_attr_accessor. # But this time, instead of dynamically creating an instance # variable, store everything in the #attributes hash. # # NB: it's important that the user of SQLObject call finalize! # at the end of their subclass definition, otherwise the # getter/setter methods don't get defined. That's hacky, but it will # have to do. :- # Make sure the ::columns and setter/getter specs now pass. self.columns.each do |col| define_method(col) do self.attributes[col] end define_method("#{col}=") do |set_to| self.attributes[col] = set_to end end end def self.table_name=(table_name) @table_name = table_name end def self.table_name self_string = "#{self}" self_string = self_string[0].downcase + self_string[1..-1] @table_name ||= "#{self_string}s" end def self.all results = DBConnection.execute(<<-SQL) SELECT * FROM #{self.table_name} SQL self.parse_all(results) end def self.parse_all(results) all = [] results.each do |hash| all << self.new(hash) end all end def self.find(id) row = DBConnection.execute(<<-SQL, id) SELECT * FROM #{self.table_name} WHERE id = ? SQL return nil if row.empty? self.new(row.first) end def initialize(params = {}) #unknown attribute 'favorite_band' params.each do |attr_name, value| raise "unknown attribute '#{attr_name}'" unless self.class.columns.include?(attr_name.to_sym) self.send("#{attr_name}=", value) end end def attributes @attributes ||= {} # columns.each do |column| # result[column] = instance_variable_get("@#{column}") # end # @attributes = result end def attribute_values self.class.columns.map do |column| self.send(column) end end def insert columns = self.class.columns.drop(1) col_names = columns.map(&:to_s).join(", ") question_marks = [] columns.size.times { question_marks << "?"} question_marks = question_marks.join(", ") att_vals = self.attribute_values puts columns p att_vals puts question_marks DBConnection.execute(<<-SQL, *att_vals.drop(1)) INSERT INTO #{self.class.table_name} (#{col_names}) VALUES (#{question_marks}) SQL self.id = DBConnection.last_insert_row_id end def update att_vals = self.attribute_values att_vals = att_vals[1..-1] + [att_vals[0]] set_line = self.class.columns.drop(1).map { |attr_name| "#{attr_name} = ?"}.join(", ") DBConnection.execute(<<-SQL, *att_vals) UPDATE #{self.class.table_name} SET #{set_line} WHERE id = ? SQL end def save if self.id update else insert end end end
require 'pry' module SeasonMethods def group_games_by_season(id) hash = Hash.new {|h,k| h[k] = [] } @games.each do |game| if game.season == id hash[game.season] << game end end hash end def find_games_in_gt(id) arr = [] group_games_by_season(id).values.flatten.each do |game| arr << game.game_id end arr_2 = [] @game_teams.each do |gt| if arr.include?(gt.game_id) arr_2 << gt end end arr_2 end def wins_per_coach_per_season(id) hash = Hash.new(0) find_games_in_gt(id).each do |gt| if gt.won == true hash[gt.head_coach] += 1 end end hash end def games_per_coach_per_season(id) hash = Hash.new(0) find_games_in_gt(id).each do |gt| hash[gt.head_coach] += 1 end hash end def win_perc_per_coach(id) wins_per_coach_per_season(id) .merge!(games_per_coach_per_season(id)) {|k, v1, v2| (v1.to_f / v2) * 100} end def winningest_coach(id) win_perc_per_coach(id).max_by do |k, v| v end[0] end def worst_coach(id) win_perc_per_coach(id).min_by do |k, v| v end[0] end def wins_per_team_per_season(id) hash = Hash.new(0) group_games_by_season(id).each do |k, v| v.each do |game| if game.outcome.include?("home") hash[game.home_team_id] += 1 elsif game.outcome.include?("away") hash[game.away_team_id] += 1 end end end hash end def most_accurate_team(id) hash_shots = Hash.new(0) find_games_in_gt(id).each do |gt| hash_shots[gt.team_id] += gt.shots end hash_goals = Hash.new(0) find_games_in_gt(id).each do |gt| hash_goals[gt.team_id] += gt.goals end mos_acc = hash_shots.merge!(hash_goals) {|k, v1, v2| v1.to_f / v2} a = mos_acc.min_by do |k, v| v end team_id_to_name(a[0]) end def least_accurate_team(id) hash_shots = Hash.new(0) find_games_in_gt(id).each do |gt| hash_shots[gt.team_id] += gt.shots end hash_goals = Hash.new(0) find_games_in_gt(id).each do |gt| hash_goals[gt.team_id] += gt.goals end mos_acc = hash_shots.merge!(hash_goals) {|k, v1, v2| v1.to_f / v2} a = mos_acc.max_by do |k, v| v end team_id_to_name(a[0]) end def power_play_goal_percentage(id) hash = {:goals => 0, :ppgoals => 0} find_games_in_gt(id).each do |gt| hash[:goals] += gt.goals hash[:ppgoals] += gt.powerplaygoals end (hash[:ppgoals].to_f / hash[:goals]).round(2) end def reg_season_games_per_team_per_season(id) hash = Hash.new(0) group_games_by_season(id).each do |k, v| v.each do |game| if game.type == "R" hash[game.away_team_id] += 1 hash[game.home_team_id] += 1 end end end hash end def post_season_games_per_team_per_season(id) hash = Hash.new(0) group_games_by_season(id).each do |k, v| v.each do |game| if game.type == "P" hash[game.away_team_id] += 1 hash[game.home_team_id] += 1 end end end hash end def wins_per_team_by_reg_season(id) hash_r = Hash.new(0) reg_season_games_per_team_per_season(id).each do |k, v| hash_r[k] = (v - v) end group_games_by_season(id).each do |k, v| v.each do |game| if game.type == "R" if game.outcome.include?("home") hash_r[game.home_team_id] += 1 elsif game.outcome.include?("away") hash_r[game.away_team_id] += 1 end end end end hash_r end def wins_per_team_by_post_season(id) hash_p = Hash.new(0) post_season_games_per_team_per_season(id).each do |k, v| hash_p[k] = (v - v) end group_games_by_season(id).each do |k, v| v.each do |game| if game.type == "P" if game.outcome.include?("home") hash_p[game.home_team_id] += 1 elsif game.outcome.include?("away") hash_p[game.away_team_id] += 1 end end end end hash_p end def team_and_games_in_post_season(id) hash = Hash.new(0) post_season_games_per_team_per_season(id).each do |k1, v1| reg_season_games_per_team_per_season(id).each do |k2, v2| if k1 == k2 hash[k1] = v1 end end end hash end def reg_seas_win_perc_season(id) wins_per_team_by_reg_season(id) .merge!(reg_season_games_per_team_per_season(id)) do |k, v1, v2| (v1.to_f/v2)*100 end end def post_seas_win_perc_season(id) wins_per_team_by_post_season(id) .merge!(post_season_games_per_team_per_season(id)) do |k, v1, v2| (v1.to_f/v2).round(2)*100 end end def only_teams_in_p_and_r(id) reg = reg_seas_win_perc_season(id) post = post_seas_win_perc_season(id) reg.map do |k, v| reg.delete(k) if !post.keys.include?(k) end reg end def biggest_bust(id) hash = post_seas_win_perc_season(id) .merge!(only_teams_in_p_and_r(id)) {|k, v1, v2| v2 - v1} hash_1 = hash.max_by do |k, v| v end team_id_to_name(hash_1[0]) end def biggest_surprise(id) hash = post_seas_win_perc_season(id) .merge!(only_teams_in_p_and_r(id)) {|k, v1, v2| v1 - v2} hash_1 = hash.max_by do |k, v| v end team_id_to_name(hash_1[0]) end def number_hits(season_id) games_per_season =[] team_hits = Hash.new(0) @games.each do |game| if game.season.include?(season_id) games_per_season << game.game_id end end @game_teams.each do |game_team| games_per_season.each do |game| if game_team.game_id == game team_hits[game_team.team_id] += game_team.hits end end end team_hits end def most_hits(season_id) a = number_hits(season_id).max_by do |k, v| v end team_id_to_name(a[0]) end def fewest_hits(season_id) a = number_hits(season_id).min_by do |k, v| v end team_id_to_name(a[0]) end end
# encoding: UTF-8 require 'base64' require 'yaml' require 'fileutils' class AppConfig attr_accessor :config_name, :config_path, #app/script configuration. :tweet_template, #Template for conversion process. :inbox, :outbox, :save_json, :processed_box, :compress_csv, :arrays_to_collapse, :header_overrides, :header_mappings def initialize #Defaults. @tweet_template = './templates/original_select.json' @config_path = './config/' #Default to app config directory. @config_name = 'config.yaml' @inbox = './input' @outbox = './output' @save_json = true @processed_box = './input/processed' @retain_compression = true #TODO: gz in, gz out if true #These need to be unique, thus 'urls' require their parent object name. @arrays_to_collapse = 'hashtags,user_mentions,entities.urls,urls,matching_rules,topics' @header_overrides = 'user.location.objectType,user.location.displayName' @header_mappings = generate_special_header_mappings end #entities.hashtags.0.text --> hashtags #entities.urls.0.url --> twitter_urls #entities.urls.0.expanded_url --> twitter_expanded_urls #entities.urls.0.display_url --> twitter_display_urls #entities.user_mentions.0.screen_name --> user_mention_screen_names #entities.user_mentions.0.name --> user_mention_names #entities.user_mentions.0.id --> user_mention_ids #matching_rules.0.value --> rule_values #matching_rules.0.tag --> tag_values def generate_special_header_mappings mappings = Hash.new mappings['entities.hashtags.0.text'] = 'hashtags' mappings['entities.urls.0.url'] = 'twitter_urls' mappings['entities.urls.0.expanded_url'] = 'twitter_expanded_urls' mappings['entities.urls.0.display_url'] = 'twitter_display_urls' mappings['entities.user_mentions.0.screen_name'] = 'user_mention_screen_names' mappings['entities.user_mentions.0.name'] = 'user_mention_names' mappings['entities.user_mentions.0.id'] = 'user_mention_ids' mappings['matching_rules.0.value'] = 'rule_values' mappings['matching_rules.0.tag'] = 'rule_tags' mappings['language.value'] = 'gnip_lang' #Geographical metadata labels. mappings['location.geo.coordinates.0.0.0'] = 'box_sw_long' mappings['location.geo.coordinates.0.0.1'] = 'box_sw_lat' mappings['location.geo.coordinates.0.1.0'] = 'box_nw_long' mappings['location.geo.coordinates.0.1.1'] = 'box_nw_lat' mappings['location.geo.coordinates.0.2.0'] = 'box_ne_long' mappings['location.geo.coordinates.0.2.1'] = 'box_ne_lat' mappings['location.geo.coordinates.0.3.0'] = 'box_se_long' mappings['location.geo.coordinates.0.3.1'] = 'box_se_lat' mappings['geo.coordinates.0'] = 'point_long' mappings['geo.coordinates.1'] = 'point_lat' #These Klout topics need some help. #mappings['gnip.klout_profile.topics.0.klout_topic_id'] = 'klout_topic_id' #mappings['gnip.klout_profile.topics.0.display_name'] = 'klout_topic_name' #mappings['gnip.klout_profile.topics.0.link'] = 'klout_topic_link' mappings end #Confirm a directory exists, creating it if necessary. def check_directory(directory) #Make sure directory exists, making it if needed. if not File.directory?(directory) then FileUtils.mkpath(directory) #logging and user notification. end directory end def config_file return @config_path + @config_name end def save_config_yaml #Write current config settings as YAML. #TODO: used? needed? settings = {} #Downloading, compression. settings['tweet_template'] = @tweet_template settings['dir_input'] = @inbox settings['dir_output'] = @outbox settings['save_json'] = @save_json settings['dir_processed'] = @processed_box settings['compress_csv'] = @compress_csv settings['arrays_to_collapse'] = @arrays_to_collapse settings['header_overrides'] = @header_overrides header_mappings = {} config = {} config['settings'] = settings config['header_mappings'] = header_mappings File.open(config_file, 'w') do |f| f.write config.to_yaml end end #Open YAML file and load settings into config object. def get_config_yaml begin config = YAML::load_file(config_file) rescue save_config_yaml config = YAML::load_file(config_file) end @tweet_template = config['json2csv']['tweet_template'] @inbox = check_directory(config['json2csv']['inbox']) @outbox = check_directory(config['json2csv']['outbox']) @save_json = config['json2csv']['save_json'] @processed_box = check_directory(config['json2csv']['processed_box']) @compress_csv = config['json2csv']['compress_csv'] temp = config['json2csv']['arrays_to_collapse'] if !temp.nil? then @arrays_to_collapse = temp end temp = config['json2csv']['header_overrides'] if !temp.nil? then @header_overrides = temp end #Header mappings temp = config['header_mappings'] if temp.length > 0 then @header_mappings = temp end end end #-------------------------------------------------------------------------- if __FILE__ == $0 #This script code is executed when running this file. oConfig = AppConfig.new end
# frozen_string_literal: true module AFK # stores task information class Task attr_reader :children, :title def initialize(title) @title = title @children = AFK::NodeCollection.new end def add_child_task(title) @children.add_task(title) end def signifier AFK.configuration.task_signifier end def inspect "<Task> #{title.inspect}" end end end
module Fog module Compute class Google class Mock def invalidate_url_map_cache(_url_map_name, _path, _host = nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def invalidate_url_map_cache(url_map_name, path, host = nil) @compute.invalidate_url_map_cache( @project, url_map_name, ::Google::Apis::ComputeV1::CacheInvalidationRule.new( path: path, host: host ) ) end end end end end
require "sshkit" module Airbrussh # This class quacks like an SSHKit::Formatter, but when any formatting # methods are called, it simply forwards them to one more more concrete # formatters. This allows us to split out the responsibilities of # ConsoleFormatter and LogFileFormatter into two separate classes, with # DelegatingFormatter forwarding the logging messages to both at once. # class DelegatingFormatter FORWARD_METHODS = %w[ fatal error warn info debug log log_command_start log_command_data log_command_exit ].freeze DUP_AND_FORWARD_METHODS = %w[<< write].freeze attr_reader :formatters def initialize(formatters) @formatters = formatters end FORWARD_METHODS.each do |method| define_method(method) do |*args| formatters.map { |f| f.public_send(method, *args) }.last end end # For versions of SSHKit up to and including 1.7.1, the LogfileFormatter # and ConsoleFormatter (and all of SSHKit's built in formatters) clear # the stdout and stderr data in the command obj. Therefore, ensure only # one of the formatters (the last one) gets the original command. This is # also the formatter whose return value is passed to the caller. # DUP_AND_FORWARD_METHODS.each do |method| define_method(method) do |command_or_log_message| formatters[0...-1].each do |f| f.public_send(method, command_or_log_message.dup) end formatters.last.public_send(method, command_or_log_message) end end end end
class EventAttendee < ApplicationRecord belongs_to :event, class_name: 'Event', optional: true belongs_to :attendee, class_name: 'User', optional: true end
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe Vault::Accounts::RegistrationController do ActionController::Integration::Session fixtures :subscriptions, :subscription_plans, :countries before(:each) do @request.env['HTTPS'] = 'on' end describe "on new" do it "should load default instances" do get :new assigns[:account].should be_a Account assigns[:user].should be_a User assigns[:terms_of_service].should be_true session[:account_id].should be_nil session[:invitation_token].should be_nil end end describe "on create" do # TODO: USE FORMTASTIC HELPER TO GENERATE PARAMS def required_params {:account => {:company_name => Faker::Company.name, :phone_number => Faker::PhoneNumber.phone_number, :users_attributes => {'0' => {:email => Faker::Internet.email, :password => @pwd = Faker::Lorem.words(3).join(''), :password_confirmation => @pwd, :full_name => Faker::Name.name, :terms_of_service => '1'}}} } end def post_info(opts=required_params) post :create, @params.merge!(opts) end describe "without required parameters" do before(:each) do @params = {:plan => 'Free'} controller.stubs(:verify_recaptcha).returns(true) end it "should display the signup form with errors unless all required parameters are entered" do post :create, {} response.should render_template(:new) assigns[:user].errors.should_not be_empty params = @params.merge(required_params) params[:account][:phone_number] = nil post :create, @params response.should render_template(:new) assigns[:account].errors.should_not be_empty end end describe "with required parameters" do describe "with terms of service not accepted" do before(:each) do @params = {:plan => 'Free'} end # Weird that this should fail..oh well. it "should not create an account even when required params filled" do req = required_params req[:account][:users_attributes]['0'][:terms_of_service] = '0' post_info req response.should render_template(:new) end end describe "with terms of service accepted" do before(:each) do @params = {:plan => 'Free'} end it "should create an account" do lambda { post_info }.should change(Account, :count).by(1) end it "should save form values to account records" do params = required_params post_info params assigns[:account].name.should == params[:account][:users_attributes]['0'][:full_name] assigns[:account].user.login.should == params[:account][:users_attributes]['0'][:email] assigns[:account].user.email.should == params[:account][:users_attributes]['0'][:email] assigns[:account].company_name.should == params[:account][:company_name] assigns[:account].phone_number.should == params[:account][:phone_number] end it "should redirect to the plans page" do post_info response.should redirect_to(plans_account_registration_url) end it "should assign member role to the user" do post_info assigns[:user].should be_member end end end end describe "on subscription plans" do it "should redirect to the login url if no account id in the session" do get :plans # subdomain_fu prevents using routes - it prefixes 'www' to domain response.should redirect_to('https://test.host:80/vlogin') end it "should load an account from the session" do @account = create_account session[:account_id] = @account.id get :plans response.should render_template(:plans) end it "should load the plans into an instance array" do @account = create_account session[:account_id] = @account.id get :plans assigns[:plans].first.should be_a SubscriptionPlan end end describe "choosing plan" do before(:each) do @account = create_account session[:account_id] = @account.id end describe "with no payment required" do it "should redirect to account setup" do post :choose_plan # subdomain_fu prevents using routes - it prefixes 'www' to domain response.should redirect_to('https://test.host:80/account_setup') end end describe "with payment required" do it "should render the billing view" do post :choose_plan, :plan => 'Advanced' response.should render_template("billing") end it "should save the account id in the session" do post :choose_plan, :plan => 'Advanced' session[:account_id].should == @account.id end it "should save the new plan if different than the default" do post :choose_plan, :plan => 'Advanced' assigns[:subscription].subscription_plan.name.should == 'Advanced' @account.reload.subscription.should == assigns[:subscription] end it "should load the chosen plan for display in the billing template" do post :choose_plan, :plan => 'Advanced' assigns[:plan].name.should == 'Advanced' end end end describe "saving billing information" do before(:each) do @account = create_account session[:account_id] = @account.id post :choose_plan, :plan => 'Advanced' end it "should should not do anything unless request is put or post" do get :billing response.should render_template(:billing) end it "should initialize activemerchant billing objects" do get :billing assigns[:creditcard].should_not be_nil assigns[:subscription_address].should_not be_nil end it "should display errors without required fields" do post :billing assigns[:creditcard].should_not be_valid assigns[:subscription_address].should_not be_valid end describe "on success" do before(:each) do ActiveMerchant::Billing::CreditCard.stubs(:new).returns(@cc = mock('ActiveMerchant::Billing::CreditCard')) SubscriptionAddress.stubs(:new).returns(@addr = mock('SubscriptionAddress')) @cc.stubs(:valid? => true, :first_name => 'dr', :last_name => 'no') @addr.stubs(:valid? => true, :country => stub("Country", :id => 1, :name => "US"), :to_activemerchant => "") @addr.expects(:first_name=).with('dr') @addr.expects(:last_name=).with('no') Subscription.any_instance.stubs(:store_card).returns(true) end it "should render thanks template" do post :billing response.should render_template(:thanks) end it "should send an activation email" do controller.expects(:send_activation_mail) post :billing end it "should log the user in" do UserSession.expects(:create).with(@account.admin, true) post :billing end end end end
require_relative 'mediagem/version' require_relative 'config/locale' module Mediagem # Your code goes here... class Gif def self.name return I18n.t('hello') end end end
require_relative 'cartodb-utils/metrics.rb' require_relative 'cartodb-utils/mail.rb' require 'json/ext' require 'openssl' require 'json' require 'typhoeus' require 'date' OpenSSL::SSL.send :remove_const, :VERIFY_PEER OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE module CartoDBUtils MAX_REQUEST_RETRY = 3 def self.http_request(url, request_retry = 1, extra_options = {}) http_method = extra_options[:http_method] || :get if http_method == :post body = extra_options[:body] || nil end params = extra_options[:params] || nil headers = extra_options[:headers] || nil expected_responses = extra_options[:expected_responses] || [200] request = Typhoeus::Request.new( url, method: http_method.to_sym, body: body, params: params, headers: headers ) response = request.run if expected_responses.include?(response.code) return response.code, response.body else if request_retry < MAX_REQUEST_RETRY sleep request_retry return http_request(url, request_retry + 1, extra_options) else raise(response.body) end end end # interval must be in hours # end_time must be a datetime def self.format_period(interval, end_time = nil) if end_time.nil? end_time = DateTime.now end from = DateTime.parse((end_time - interval.to_f/24.0).strftime("%Y-%m-%d %H:00:00")) to = DateTime.parse(end_time.strftime("%Y-%m-%d %H:00:00")) return [from, to] end end
# encoding: utf-8 require File.expand_path(File.join(File.dirname(__FILE__), *%w(.. test_helper))) require 'active_support/test_case' class ModelValidationsTest < ::ActiveSupport::TestCase include ActionView::Helpers::FormHelper context "validation options" do test ":client_side - enabling_disabling client-side validations" do ::ValidatiousOnRails.client_side_validations_by_default = false validators = ::ValidatiousOnRails::ModelValidations.from_active_record(:bogus_item, :field_with_defaults) assert_validator_class '', validators # FIXME: Fails for some obscure reason. If switching place with the one above, that one fails instead. =S ::ValidatiousOnRails.client_side_validations_by_default = true validators = ::ValidatiousOnRails::ModelValidations.from_active_record(:bogus_item, :field_with_defaults) #assert_not_validator_class '', validators validators = ::ValidatiousOnRails::ModelValidations.from_active_record(:bogus_item, :field_with_client_side_validations) assert_not_validator_class '', validators validators = ::ValidatiousOnRails::ModelValidations.from_active_record(:bogus_item, :field_without_client_side_validations) assert_validator_class '', validators end end context "from_active_record" do test "non concrete models" do assert_nothing_raised(NameError) do ::ValidatiousOnRails::ModelValidations.from_active_record(:thing, :field_with_defaults) end assert_equal [], ::ValidatiousOnRails::ModelValidations.from_active_record(:thing, :field_with_defaults) end end context "acceptance_of" do test "with defaults" do validators = ::ValidatiousOnRails::ModelValidations.acceptance_of( validation(:validates_acceptance_of) ) assert_validator_class 'acceptance-accept_1_false', validators end test "with :accept" do validators = ::ValidatiousOnRails::ModelValidations.acceptance_of( validation(:validates_acceptance_of, :accept => true) ) assert_validator_class 'acceptance-accept_true_false', validators end end test "associated" do # TODO: not implemented end test "confirmation_of" do validators = ::ValidatiousOnRails::ModelValidations.confirmation_of( validation(:validates_confirmation_of) ) assert_validator_class 'confirmation-of_name', validators end test "exclusion_of" do values = (6..10).to_a validators = ::ValidatiousOnRails::ModelValidations.exclusion_of( validation(:validates_exclusion_of, :in => values) ) assert_validator_class /^exclusion-in_(\d+)/, validators assert_match /#{values.to_json}/, validators.first.fn end test "format_of" do pattern = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i validators = ::ValidatiousOnRails::ModelValidations.format_of( validation(:validates_format_of, :with => pattern) ) assert_validator_class /^format-with_(\d+)_false_false/, validators assert_match /#{pattern.inspect[1,-1]}/, validators.first.fn end test "inclusion_of" do values = (1..5).to_a validators = ::ValidatiousOnRails::ModelValidations.inclusion_of( validation(:validates_inclusion_of, :in => values) ) assert_validator_class /^inclusion-in_(\d+)_false_false/, validators assert_match /#{values.to_json}/, validators.first.fn end context "length_of" do test "with :is" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :is => 2) ) assert_validator_class 'length-is_2_false_false', validators end test "with :in" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :in => 2..10) ) assert_validator_class 'length-minimum_2_false_false length-maximum_10_false_false', validators end test "with :within" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :within => 2..10) ) assert_validator_class 'length-minimum_2_false_false length-maximum_10_false_false', validators end test "with :minimum" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :minimum => 2) ) assert_validator_class 'length-minimum_2_false_false', validators end test "with :maximum" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :maximum => 10) ) assert_validator_class 'length-maximum_10_false_false', validators end test "with :minimum + :maximum" do validators = ::ValidatiousOnRails::ModelValidations.length_of( validation(:validates_length_of, :minimum => 2, :maximum => 10) ) assert_validator_class 'length-minimum_2_false_false length-maximum_10_false_false', validators end end context "numericality_of" do context ":odd/:even" do test "with :odd only" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :even => false, :odd => true) ) assert_validator_class 'numericality-odd_false', validators end test "with :even only" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :even => true, :odd => false) ) assert_validator_class 'numericality-even_false', validators end test "with :odd and :even" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :even => true, :odd => true) ) assert_validator_class '', validators end test "with neither :odd or :even" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of) ) assert_validator_class '', validators end end test "with :only_integer" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :only_integer => true) ) # Alt. more generic idea: assert_equal 'numericality-precision_0', validator.to_class assert_validator_class 'numericality-only-integer_false', validators end test "with :greater_than" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :greater_than => 2) ) assert_validator_class 'numericality-greater-than_2_false', validators end test "with :greater_than_or_equal_to" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :greater_than_or_equal_to => 2) ) assert_validator_class 'numericality-greater-than-or-equal-to_2_false', validators end test "with :equal_to" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :equal_to => 2) ) assert_validator_class 'numericality-equal-to_2_false', validators end test "with :less_than" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :less_than => 10) ) assert_validator_class 'numericality-less-than_10_false', validators end test "with :less_than_or_equal_to" do validators = ::ValidatiousOnRails::ModelValidations.numericality_of( validation(:validates_numericality_of, :less_than_or_equal_to => 10) ) assert_validator_class 'numericality-less-than-or-equal-to_10_false', validators end end test "presence_of" do validators = ::ValidatiousOnRails::ModelValidations.presence_of(validation(:validates_presence_of)) assert_validator_class 'presence', validators end test "uniqueness_of" do validators = ::ValidatiousOnRails::ModelValidations.uniqueness_of(validation(:validates_uniqueness_of)) assert_validator_class 'uniqueness_false_false', validators # Ignore duplicates (Note: defined two times in TestHelper). assert_equal 1, [*validators].collect { |v| v.to_class.split(' ') }.flatten.select { |c| c == 'uniqueness_false_false'}.size end private # Simulate a validation # def validation(macro, options = {}) ::ActiveRecord::Reflection::MacroReflection.new(macro, :name, options, BogusItem.new) end def assert_validator_class(expected, actual) if expected.is_a?(::Regexp) assert_match expected, [*actual].collect { |v| v.to_class }.join(' ') else assert_equal expected, [*actual].collect { |v| v.to_class }.join(' ') end end def assert_not_validator_class(expected, actual) if expected.is_a?(::Regexp) assert_no_match expected, [*actual].collect { |v| v.to_class }.join(' ') else assert_not_equal expected, [*actual].collect { |v| v.to_class }.join(' ') end end end
# describe "CartesianProduct" do # it "should exist" do # lambda { CartesianProduct.new() }.should_not raise_error(::NoMethodError) # end # end class CartesianProduct include Enumerable # your code here def initialize(a, b) # YOUR CODE HERE @a = a @b = b end def each @a.each do |i| @b.each do |j| yield [i,j] end end end end c = CartesianProduct.new([:a,:b], [4,5]) c.each { |elt| puts elt.inspect } # [:a, 4] # [:a, 5] # [:b, 4] # [:b, 5] c = CartesianProduct.new([:a,:b], []) c.each { |elt| puts elt.inspect } # (nothing printed since Cartesian product # of anything with an empty collection is empty)
require_dependency 'user_query' class UsersController < ApplicationController before_filter :hide_cover_image def index if params[:followed_by] or params[:followers_of] if params[:followed_by] users = User.find(params[:followed_by]).following elsif params[:followers_of] users = User.find(params[:followers_of]).followers end users = users.page(params[:page]).per(20) UserQuery.load_is_followed(users, current_user) render json: users, meta: {cursor: 1 + (params[:page] || 1).to_i} elsif params[:to_follow] render json: User.where(to_follow: true), each_serializer: UserSerializer else ### OLD CODE PATH BELOW. Used only by the recommendations page. authenticate_user! @status = { recommendations_up_to_date: current_user.recommendations_up_to_date } respond_to do |format| format.html { flash.keep redirect_to '/' } format.json { render :json => @status } end end end def show @user = User.find(params[:id]) # Redirect to canonical URL if this isn't it. if request.path != user_path(@user) return redirect_to user_path(@user), status: :moved_permanently end if user_signed_in? and current_user == @user # Clear notifications if the current user is viewing his/her feed. # TODO This needs to be moved elsewhere. Notification.where(user: @user, notification_type: "profile_comment", seen: false).update_all seen: true end respond_to do |format| format.html do preload_to_ember! @user render_ember end format.json { render json: @user } end end def followers user = User.find(params[:user_id]) preload_to_ember! user render_ember end def following user = User.find(params[:user_id]) preload_to_ember! user render_ember end def favorite_anime @active_tab = :favorite_anime @user = User.find(params[:user_id]) @favorite_anime = @user.favorites.where(item_type: "Anime").includes(:item).order('favorites.fav_rank, favorites.id').page(params[:page]).per(50) render "favorite_anime", layout: "layouts/profile" end def library @user = User.find(params[:user_id]) # Redirect to canonical URL if this isn't it. if request.path != user_library_path(@user) return redirect_to user_library_path(@user), status: :moved_permanently end preload_to_ember! @user render_ember end def groups user = User.find(params[:user_id]) preload_to_ember! user render_ember end def manga_library @user = User.find(params[:user_id]) preload_to_ember! @user render_ember end def follow authenticate_user! @user = User.find(params[:user_id]) if @user != current_user if @user.followers.include? current_user @user.followers.destroy current_user action_type = "unfollowed" else if current_user.following_count < 10000 @user.followers.push current_user action_type = "followed" else flash[:message] = "Wow! You're following 10,000 people?! You should unfollow a few people that no longer interest you before following any others." action_type = nil end end if action_type Substory.from_action({ user_id: current_user.id, action_type: action_type, followed_id: @user.id }) end end respond_to do |format| format.html { redirect_to :back } format.json { render json: true } end end def reviews user = User.find(params[:user_id]) preload_to_ember! user render_ember end def update_cover_image @user = User.find(params[:user_id]) authorize! :update, @user if params[:user][:cover_image] @user.cover_image = params[:user][:cover_image] flash[:success] = "Cover image updated successfully." if @user.save end redirect_to :back end def update_avatar authenticate_user! user = User.find(params[:user_id]) if user == current_user user.avatar = params[:avatar] || params[:user][:avatar] user.save! respond_to do |format| format.html { redirect_to :back } format.json { render json: user, serializer: CurrentUserSerializer } end else error! 403 end end def disconnect_facebook authenticate_user! current_user.update_attributes(facebook_id: nil) redirect_to :back end def redirect_short_url @user = User.find_by_name params[:username] raise ActionController::RoutingError.new('Not Found') if @user.nil? redirect_to @user end def comment authenticate_user! # Create the story. @user = User.find(params[:user_id]) story = Action.broadcast( action_type: "created_profile_comment", user: @user, poster: current_user, comment: params[:comment] ) respond_to do |format| format.html { redirect_to :back } format.json { render :json => true } end end def update_setting authenticate_user! if params[:rating_system] if params[:rating_system] == "simple" current_user.star_rating = false elsif params[:rating_system] == "advanced" current_user.star_rating = true end end if current_user.save render :json => true else render :json => false end end def cover_image user = User.find_by_name(params[:user_id]) || not_found! redirect_to user.cover_image.url(:thumb) end def update authenticate_user! user = User.find(params[:id]) changes = params[:current_user] || params[:user] if current_user == user user.about = changes[:about] || "" user.location = changes[:location] user.waifu = changes[:waifu] user.website = changes[:website] user.waifu_or_husbando = changes[:waifu_or_husbando] user.bio = changes[:bio] || "" user.waifu_char_id = changes[:waifu_char_id] if Rails.env.production? and changes[:cover_image_url] =~ /^data:image/ user.cover_image = changes[:cover_image_url] end # Settings page stuff if params[:current_user] user.email = changes[:email] user.password = changes[:new_password] unless changes[:new_password].blank? user.name = changes[:new_username] unless changes[:new_username].blank? user.star_rating = (changes[:rating_type] == 'advanced') user.sfw_filter = changes[:sfw_filter] user.title_language_preference = changes[:title_language_preference] end end if user.save render json: user else return error!(user.errors.full_messages * ', ', 500) end end def to_follow fixedUserList = [ 'Gigguk', 'Holden', 'JeanP', 'Arkada', 'HappiLeeErin', 'DoctorDazza', 'Yokurama', 'dexbonus', 'DEMOLITION_D' ] @users = User.where(:name => fixedUserList) render json: @users, each_serializer: UserSerializer end end
Rails.application.routes.draw do root 'states#index' devise_for :users resources :users, only: [:show] namespace :admin do resources :petitions, only: [:index, :destroy] resources :users, only: [:edit, :update, :destroy] end resources :states, only: [:show] do resources :petitions end resources :petitions, only: [:show, :index] do resources :memberships, only: [:create, :destroy] end end
require "json" require "active_support/all" def handler(event:, context:) puts "EVENT #{event.to_json}" response = {time: Time.now.utc - 1.day} puts "RESPONSE #{response.to_json}" end
Gem::Specification.new do |s| s.name = 'jcouchbase' s.version = '0.1.3' s.date = '2012-08-28' s.platform = Gem::Platform::RUBY s.authors = ["Jeremy J Brenner"] s.email = ["jeremyjbrenner@gmail.com"] s.summary = "Thin ruby wrapper around Couchbase Java Driver; for JRuby only" s.description = %q{Thin jruby wrapper around Couchbase Java Driver} s.homepage = 'http://github.com/jeremy-brenner/jcouchbase' # = MANIFEST = s.files = %w[ Gemfile README.md Rakefile jcouchbase.gemspec lib/jcouchbase.rb lib/jcouchbase/jars/commons-codec-1.5.jar lib/jcouchbase/jars/commons-codec-1.6.jar lib/jcouchbase/jars/commons-logging-1.1.1.jar lib/jcouchbase/jars/couchbase-client-1.1-dp2-javadocs.jar lib/jcouchbase/jars/couchbase-client-1.1-dp2.jar lib/jcouchbase/jars/fluent-hc-4.2.1.jar lib/jcouchbase/jars/httpclient-4.2.1.jar lib/jcouchbase/jars/httpclient-cache-4.2.1.jar lib/jcouchbase/jars/httpcore-4.1.1.jar lib/jcouchbase/jars/httpcore-4.2.1.jar lib/jcouchbase/jars/httpcore-ab-4.2.1.jar lib/jcouchbase/jars/httpcore-nio-4.1.1.jar lib/jcouchbase/jars/httpcore-nio-4.2.1.jar lib/jcouchbase/jars/httpmime-4.2.1.jar lib/jcouchbase/jars/jettison-1.1.jar lib/jcouchbase/jars/netty-3.2.0.Final.jar lib/jcouchbase/jars/spymemcached-2.8.4-javadocs.jar lib/jcouchbase/jars/spymemcached-2.8.4.jar lib/jcouchbase/jcouchbase.rb lib/jcouchbase/version.rb ] # = MANIFEST = s.add_dependency 'require_all', '~> 1.2' end
# frozen-string_literal: true module Decidim module Participations class ParticipationCreatedEventModerator < Decidim::Events::BaseEvent include Decidim::Events::EmailEvent include Decidim::Events::NotificationEvent # Notification def notification_title I18n.t( "decidim.events.participation_created.moderator.notification_title", processus_participatif_title: extra[:participatory_process_title], processus_participatif_url: action_url ).html_safe end # Moderation email settings def email_subject I18n.t( "decidim.events.participation_created.moderator.email_subject", processus_participatif_title: extra[:participatory_process_title] ).html_safe end def email_intro I18n.t( "decidim.events.participation_created.moderator.email_intro", processus_participatif_title: extra[:participatory_process_title], author_name: participation.author.name ).html_safe end def action_url_name I18n.t( "decidim.events.participation_created.moderator.action_url_name" ).html_safe end def action_url admin_router_proxy.send("edit_participation_url", {id:resource.id}) end private def participation @participation ||= Decidim::Participations::Participation.find(resource.id) end def admin_router_proxy admin_router_arg = resource.respond_to?(:feature) ? resource.feature : resource @admin_router_proxy ||= EngineRouter.admin_proxy(admin_router_arg) end end end end
require "rails_helper" RSpec.describe Experimentation::CurrentPatientExperiment do describe "#eligible_patients" do it "calls super to get default eligible patients" do create(:experiment, experiment_type: "current_patients") filters = {"states" => {"exclude" => ["Non Existent State"]}} expect(Experimentation::NotificationsExperiment).to receive(:eligible_patients).with(filters).and_call_original described_class.first.eligible_patients(Date.today, filters) end it "includes patients who have an appointment on the date the first reminder is to be sent" do patient = create(:patient, age: 18) scheduled_appointment_date = 2.days.from_now create(:appointment, scheduled_date: scheduled_appointment_date, status: :scheduled, patient: patient) experiment = create(:experiment, experiment_type: "current_patients") group = create(:treatment_group, experiment: experiment) earliest_reminder = create(:reminder_template, message: "1", treatment_group: group, remind_on_in_days: -1) create(:reminder_template, message: "2", treatment_group: group, remind_on_in_days: 0) expect(described_class.first.eligible_patients(scheduled_appointment_date - 3.days)).not_to include(patient) expect(described_class.first.eligible_patients(scheduled_appointment_date - 2.days)).not_to include(patient) expect(described_class.first.eligible_patients(scheduled_appointment_date + earliest_reminder.remind_on_in_days.days)).to include(patient) expect(described_class.first.eligible_patients(scheduled_appointment_date)).not_to include(patient) expect(described_class.first.eligible_patients(scheduled_appointment_date + 1.days)).not_to include(patient) end end describe "#memberships_to_notify" do it "returns memberships to be notified for the day with expected_return_date set to any time of day" do experiment = create(:experiment, experiment_type: "current_patients") treatment_group = create(:treatment_group, experiment: experiment) create(:reminder_template, treatment_group: treatment_group, remind_on_in_days: 0) patient_1 = create(:patient) patient_2 = create(:patient) patient_3 = create(:patient) date = Date.today treatment_group.enroll(patient_1, expected_return_date: date.beginning_of_day) treatment_group.enroll(patient_2, expected_return_date: date.middle_of_day) treatment_group.enroll(patient_3, expected_return_date: (date + 1.day).end_of_day) membership_1 = experiment.treatment_group_memberships.find_by(patient_id: patient_1.id) membership_2 = experiment.treatment_group_memberships.find_by(patient_id: patient_2.id) membership_3 = experiment.treatment_group_memberships.find_by(patient_id: patient_3.id) expect(described_class.first.memberships_to_notify(date)).to contain_exactly(membership_1, membership_2) expect(described_class.first.memberships_to_notify(date + 1.day)).to contain_exactly(membership_3) end it "returns treatment_group_memberships whose expected visit is in the future and need to be reminded `remind_on_in_days` before" do experiment = create(:experiment, experiment_type: "current_patients") treatment_group = create(:treatment_group, experiment: experiment) patient_1 = create(:patient) patient_2 = create(:patient) membership_1 = treatment_group.enroll(patient_1, expected_return_date: 2.days.from_now.to_date) membership_2 = treatment_group.enroll(patient_2, expected_return_date: 3.days.from_now.to_date) create(:reminder_template, message: "1", treatment_group: treatment_group, remind_on_in_days: -2) create(:reminder_template, message: "2", treatment_group: treatment_group, remind_on_in_days: -3) create(:reminder_template, message: "3", treatment_group: treatment_group, remind_on_in_days: 0) expect(described_class.first.memberships_to_notify(Date.today)).to contain_exactly(membership_1, membership_2) expect(described_class.first.memberships_to_notify(Date.today).select(:message).pluck(:message)).to contain_exactly("1", "2") end it "returns treatment_group_memberships whose expected visit is today and need to be reminded `remind_on_in_days` today" do experiment = create(:experiment, experiment_type: "current_patients") treatment_group = create(:treatment_group, experiment: experiment) patient = create(:patient) membership = treatment_group.enroll(patient, expected_return_date: Date.today) create(:reminder_template, treatment_group: treatment_group, remind_on_in_days: 0) expect(described_class.first.memberships_to_notify(Date.today)).to contain_exactly(membership) end it "returns treatment_group_memberships whose expected visit date has passed by `remind_on_in_days` days away" do experiment = create(:experiment, experiment_type: "current_patients") treatment_group = create(:treatment_group, experiment: experiment) patient_1 = create(:patient) patient_2 = create(:patient) membership_1 = treatment_group.enroll(patient_1, expected_return_date: 1.days.from_now.to_date) membership_2 = treatment_group.enroll(patient_2, expected_return_date: 10.days.from_now.to_date) create(:reminder_template, message: "1", treatment_group: treatment_group, remind_on_in_days: -1) create(:reminder_template, message: "2", treatment_group: treatment_group, remind_on_in_days: -10) create(:reminder_template, message: "3", treatment_group: treatment_group, remind_on_in_days: 1) expect(described_class.first.memberships_to_notify(Date.today)).to contain_exactly(membership_1, membership_2) expect(described_class.first.memberships_to_notify(Date.today).select(:message).pluck(:message)).to contain_exactly("1", "2") end it "only picks patients who are still enrolled in the experiment" do experiment = create(:experiment, experiment_type: "current_patients") treatment_group = create(:treatment_group, experiment: experiment) patient_1 = create(:patient) patient_2 = create(:patient) membership_1 = treatment_group.enroll(patient_1, expected_return_date: Date.today, status: :enrolled) _membership_2 = treatment_group.enroll(patient_2, expected_return_date: Date.today, status: :evicted) create(:reminder_template, treatment_group: treatment_group, remind_on_in_days: 0) expect(described_class.first.memberships_to_notify(Date.today)).to contain_exactly(membership_1) end end end
module Yaks class Mapper class Form class Field include Attribs.new( :name, label: nil, options: [].freeze, if: nil ).add(HTML5Forms::FIELD_OPTIONS) Builder = Yaks::Builder.new(self) do def_set :name, :label def_add :option, create: Option, append_to: :options def condition(blk1 = nil, &blk2) @config = @config.with(if: blk1 || blk2) end HTML5Forms::FIELD_OPTIONS.each do |option, _| def_set option end end def self.create(*args) attrs = args.last.instance_of?(Hash) ? args.pop : {} if name = args.shift attrs = attrs.merge(name: name) end new(attrs) end # Convert to a Resource::Form::Field, expanding any dynamic # values def to_resource_fields(mapper) return [] unless self.if.nil? || mapper.expand_value(self.if) [ Resource::Form::Field.new( resource_attributes.each_with_object({}) do |attr, attrs| attrs[attr] = mapper.expand_value(public_send(attr)) end.merge(options: resource_options(mapper))) ] end def resource_options(mapper) # make sure all empty options arrays are the same instance, # makes for prettier #pp if options.empty? options else options.map {|opt| opt.to_resource_field_option(mapper) }.compact end end # All attributes that can be converted 1-to-1 to # Resource::Form::Field def resource_attributes self.class.attributes.names - [:options, :if] end end # Field end # Form end # Mapper end # Yaks
module Imagery module Missing # Allows you to set the current filename of your photo. # Much of Imagery::Missing is hinged on this. # # @example # # Photo = Class.new(Struct.new(:id)) # i = Imagery::Model.new(Photo.new(1001)) # i.extend Imagery::Missing # i.url == "/photo/1001/original.png" # # => true # # i.existing = "Filename" # i.url == "/missing/photo/original.png" # # => true # # @see Imagery::Missing#url # attr_accessor :existing def url(size = self.default_size) if existing.to_s.empty? return ['', 'missing', namespace, filename(size)].join('/') else super end end end end
if defined?(ActionMailer) class WeddingMailer < Devise::Mailer include Devise::Controllers::UrlHelpers include Devise::Mailers::Helpers def wedding_sweepstakes(event_params, user) if Rails.env.development? || Rails.env.test? recipients = [ { type: 'to', name: "Al's @ V+V", email: 'ross@verbalplusvisual.com' } ] else recipients = [ format_receipient_from_form(event_params, user) ] end message = { headers: { "Reply-to": "notify@alsformalwear.com" }, to: recipients } MANDRILL.messages.send_template 'wedding-sweepstakes', [], message end def wedding_sweepstakes_submission(event_params) location = Location.find event_params[:location_id] if Rails.env.development? || Rails.env.test? recipients = [ { type: 'to', name: "Al's @ V+V", email: 'ross@verbalplusvisual.com' } ] else recipients = [ { type: 'to', name: 'Marketing', email: 'marketing@alsformalwear.com' } ] end message = { headers: { "Reply-to": "notify@alsformalwear.com" }, to: recipients, global_merge_vars:[ {name: "WEDDING_DATE", content: event_params[:date] }, {name: "DATE_SUBMITTED", content: Time.now.strftime("%D") }, {name: "ROLE", content: event_params[:role] }, {name: "FIRST_NAME", content: event_params[:first_name] }, {name: "LAST_NAME", content: event_params[:last_name] }, {name: "ADDRESS", content: event_params[:street_address] }, {name: "CITY", content: event_params[:city] }, {name: "STATE", content: event_params[:state] }, {name: "ZIP", content: event_params[:zip_code] }, {name: "PHONE", content: event_params[:contact_phone] }, {name: "PREF_ALS_LOCATION_NAME", content: location.store_name }, {name: "PREF_ALS_LOCATION_ADDRESS", content: location.street_address }, {name: "BRIDE_FNAME", content: event_params[:bride_first_name] || "Not provided" }, {name: "BRIDE_LNAME", content: event_params[:bride_last_name] || "Not provided" }, {name: "BRIDE_EMAIL", content: event_params[:bride_email] || "Not provided" }, {name: "GROOM_FNAME", content: event_params[:groom_first_name] || "Not provided"}, {name: "GROOM_LNAME", content: event_params[:groom_last_name] || "Not provided"}, {name: "GROOM_EMAIL", content: event_params[:groom_email] || "Not provided"} ] } MANDRILL.messages.send_template 'wedding-sweepstakes-submission', [], message end private def format_receipient_user user { type: 'to', name: "#{user.first_name} #{user.last_name}".strip, email: user.email } end def format_receipient_from_form(params, user) { type: 'to', name: "#{params[:first_name]} #{params[:first_name]}".strip, email: user.email } end end end
require "spec_helper" RSpec.describe EventHub::Message do before(:each) do @m = EventHub::Message.new end context "general" do it "should have n required header keys" do expect(EventHub::Message::REQUIRED_HEADERS.size).to eq(12) end it "shoudld have a default output" do expect(@m.to_s).to \ match(/Msg: process \[undefined, 0, [0-9a-f-]+\], status \[0,,0\]/) end end context "initialization" do it "should have a valid header (structure and data)" do expect(@m.valid?).to eq(true) end it "should be invalid if one or more values are nil" do EventHub::Message::REQUIRED_HEADERS.each do |key| m = @m.dup m.header.set(key, nil, true) expect(m.valid?).to eq(false) end end it "should initialize from a json string" do # construct a json string header = {} body = {"data" => "1"} EventHub::Message::REQUIRED_HEADERS.each do |key| header.set(key, "1") end json = {"header" => header, "body" => body}.to_json # build message from string m = EventHub::Message.from_json(json) expect(m.valid?).to eq(true) EventHub::Message::REQUIRED_HEADERS.each do |key| expect(header.get(key)).to eq("1") end end it "should initialize to INVALID from an invalid json string" do invalid_json_string = "{klasjdkjaskdf" m = EventHub::Message.from_json(invalid_json_string) expect(m.valid?).to eq(true) expect(m.status_code).to eq(EventHub::STATUS_INVALID) expect(m.status_message).to match(/^JSON parse error/) expect(m.raw).to eq(invalid_json_string) end it "should have a clear state" do expect(@m.initial?).to eq(true) expect(@m.success?).to eq(false) expect(@m.invalid?).to eq(false) expect(@m.retry_pending?).to eq(false) end end context "copy" do it "should copy the message with status success" do copied_message = @m.copy expect(copied_message.valid?).to eq(true) expect(copied_message.message_id).not_to eq(@m.message_id) expect(copied_message.created_at).not_to eq(@m.created_at) expect(copied_message.status_code).to eq(EventHub::STATUS_SUCCESS) EventHub::Message::REQUIRED_HEADERS.each do |key| next if /message_id|created_at|status.code/i.match?(key) expect(copied_message.header.get(key)).to eq(@m.header.get(key)) end end it "should copy the message with status invalid" do copied_message = @m.copy(EventHub::STATUS_INVALID) expect(copied_message.valid?).to eq(true) expect(copied_message.message_id).not_to eq(@m.message_id) expect(copied_message.created_at).not_to eq(@m.created_at) expect(copied_message.status_code).to eq(EventHub::STATUS_INVALID) EventHub::Message::REQUIRED_HEADERS.each do |key| next if /message_id|created_at|status.code/i.match?(key) expect(copied_message.header.get(key)).to eq(@m.header.get(key)) end end end context "translate status code" do it "should translate status code to meaningful string" do expect(EventHub::Message.translate_status_code(EventHub::STATUS_INITIAL)).to eq("STATUS_INITIAL") expect(EventHub::Message.translate_status_code(EventHub::STATUS_SUCCESS)).to eq("STATUS_SUCCESS") expect(EventHub::Message.translate_status_code(EventHub::STATUS_RETRY)).to eq("STATUS_RETRY") expect(EventHub::Message.translate_status_code(EventHub::STATUS_RETRY_PENDING)).to eq("STATUS_RETRY_PENDING") expect(EventHub::Message.translate_status_code(EventHub::STATUS_INVALID)).to eq("STATUS_INVALID") expect(EventHub::Message.translate_status_code(EventHub::STATUS_DEADLETTER)).to eq("STATUS_DEADLETTER") expect(EventHub::Message.translate_status_code(EventHub::STATUS_SCHEDULE)).to eq("STATUS_SCHEDULE") expect(EventHub::Message.translate_status_code(EventHub::STATUS_SCHEDULE_RETRY)).to eq("STATUS_SCHEDULE_RETRY") expect(EventHub::Message.translate_status_code(EventHub::STATUS_SCHEDULE_PENDING)).to eq("STATUS_SCHEDULE_PENDING") end end context "execution history" do it "should have a execution history entry" do allow_any_instance_of(EventHub::Message).to receive(:now_stamp).and_return("a.stamp") # no history initially expect(@m.header["execution_history"]).to eq(nil) # add an entry @m.append_to_execution_history("processor_name") execution_history = @m.header.get("execution_history") expect(execution_history).not_to eq(nil) expect(execution_history.size).to eq(1) expect(execution_history[0]).to eq("processor" => "processor_name", "timestamp" => "a.stamp") # add 2nd entry allow_any_instance_of(EventHub::Message).to receive(:now_stamp).and_return("b.stamp") @m.append_to_execution_history("processor_name2") execution_history = @m.header.get("execution_history") expect(execution_history.size).to eq(2) expect(execution_history[1]).to eq("processor" => "processor_name2", "timestamp" => "b.stamp") end end context "retry" do it "should response to retry?" do @m.status_code = EventHub::STATUS_RETRY expect(@m.retry?).to eq(true) @m.status_code = EventHub::STATUS_SUCCESS expect(@m.retry?).to eq(false) @m.status_code = "STATUS_RETRY" expect(@m.retry?).to eq(false) @m.status_code = "UNKNOWN_CODE" expect(@m.retry?).to eq(false) @m.status_code = 90000 expect(@m.retry?).to eq(false) end end context "schedule" do it "should response to schedule?" do expect(@m.schedule?).to eq(false) @m.status_code = EventHub::STATUS_SCHEDULE expect(@m.schedule?).to eq(true) end it "should response to schedule_retry?" do expect(@m.schedule_retry?).to eq(false) @m.status_code = EventHub::STATUS_SCHEDULE_RETRY expect(@m.schedule_retry?).to eq(true) end it "should response to schedule_pending?" do expect(@m.schedule_pending?).to eq(false) @m.status_code = EventHub::STATUS_SCHEDULE_PENDING expect(@m.schedule_pending?).to eq(true) end end end
require_relative 'propertiesmanager.rb' require 'roo' require 'faraday' require "nokogiri" require 'nokogiri-pretty' require 'colorize' require 'gmail' class BatchUpdater def initialize() @IRIS_NS = 'http://iris-database.org/iris' @RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' @REL_INT_NS = 'http://dlib.york.ac.uk/rel-int#' @FEDORA_MODEL_NS = 'info:fedora/fedora-system:def/model#' @REL_NS = 'info:fedora/fedora-system:def/relations-external#' @props = PropertiesManager.new("system.yaml").getPropertiesHash() @logfile = @props['logfile'] @LOG = Logger.new(@logfile, 'monthly') @LOG.debug('loading system properties ... ') @protocol = @props['protocol'] @host = @props['host'] @irishost = @props['irishost'] @admin = @props['admin'] @password = @props['password'] @path = @props['path'] @processed_path = @props['path_processed'] @dd_commons_file = @props['dd_commons'] @dd_authors_file = @props['dd_authors'] @dd_languages_file = @props['dd_languages'] @gmail_user = @props['gmail_user'] @gmail_pass = @props['gmail_pass'] @gmail_to = @props['gmail_to'] @gmail_default_subject = @props['gmail_default_subject'] @xslt = @props['iris_to_dc_xslt'] @iris_parent_collection = @props['iris_collection'] @object_label = @props['object_label'] @object_ownerid = @props['object_ownerid'] @object_namespace = @props['object_namespace'] @default_iris_url = @props['iris.instruments.url'] @thumbnail_ds_id = @props['iris.ds.thumbnail.id'] @thumbnail_ds_label = @props['iris.ds.thumbnail.label'] @sound_thumbnail = @props['iris.ds.thumbnail.sound'] @video_thumbnail = @props['iris.ds.thumbnail.video'] @text_thumbnail = @props['iris.ds.thumbnail.text'] @image_thumbnail = @props['iris.ds.thumbnail.stillimage'] @software_thumbnail = @props['iris.ds.thumbnail.software'] @multi_thumbnail = @props['iris.ds.thumbnail.multi'] @props2 = PropertiesManager.new("excel_settings.yaml").getPropertiesHash() @sheetname= @props2['sheetname'] @column_author1 = @props2['column_author1'].to_i @column_author2 = @props2['column_author2'].to_i @column_author3 = @props2['column_author3'].to_i @column_author4 = @props2['column_author4'].to_i @column_author5 = @props2['column_author5'].to_i @column_author6 = @props2['column_author6'].to_i @column_instrumenttype1 = @props2['column_instrumenttype1'].to_i @column_instrumenttype2 = @props2['column_instrumenttype2'].to_i @column_reseracharea1 = @props2['column_reseracharea1'].to_i @column_reseracharea2 = @props2['column_reseracharea2'].to_i @column_reseracharea3 = @props2['column_reseracharea3'].to_i @column_typeoffile1 = @props2['column_typeoffile1'].to_i @column_typeoffile2 = @props2['column_typeoffile2'].to_i @column_software = @props2['column_software'].to_i @column_other_software_url = @props2['column_other_software_url'].to_i @column_instrumenttitle = @props2['column_instrumenttitle'].to_i @column_notes = @props2['column_notes'].to_i @column_participanttype1 = @props2['column_participanttype1'].to_i @column_participanttype2 = @props2['column_participanttype2'].to_i @column_language1 = @props2['column_language1'].to_i @column_language1_2 = @props2['column_language1_2'].to_i @column_language1_3 = @props2['column_language1_3'].to_i @column_language2 = @props2['column_language2'].to_i @column_language2_2 = @props2['column_language2_2'].to_i @column_language2_3 = @props2['column_language2_3'].to_i @column_publication1_type = @props2['column_publication1_type'].to_i @column_publication1_author1 = @props2['column_publication1_author1'].to_i @column_publication1_author2 = @props2['column_publication1_author2'].to_i @column_publication1_author3 = @props2['column_publication1_author3'].to_i @column_publication1_author4 = @props2['column_publication1_author4'].to_i @column_publication1_author5 = @props2['column_publication1_author5'].to_i @column_publication1_author6 = @props2['column_publication1_author6'].to_i @column_publication1_title = @props2['column_publication1_title'].to_i @column_publication1_journal = @props2['column_publication1_journal'].to_i @column_publication1_date = @props2['column_publication1_date'].to_i @column_publication1_volume = @props2['column_publication1_volume'].to_i @column_publication1_issue_no = @props2['column_publication1_issue_no'].to_i @column_publication1_page_number_from = @props2['column_publication1_page_number_from'].to_i @column_publication1_page_number_to = @props2['column_publication1_page_number_to'].to_i @column_publication1_doi = @props2['column_publication1_doi'].to_i @column_email = @props2['column_email'].to_i @LOG.debug('loading data dictionaries ... ') @dd_commons_doc = Nokogiri::XML(File.open(@dd_commons_file)) @dd_authors_doc = Nokogiri::XML(File.open(@dd_authors_file)) @dd_languages_doc = Nokogiri::XML(File.open(@dd_languages_file)) end def is_author_in_dd(author) a = @dd_authors_doc.at_xpath("/authors/author[.='"+author+"']") !a.nil? end def dd_value_from_xpath(xpath) v = @dd_commons_doc.at_xpath(xpath) end def update() conn = Faraday.new(:url => @protocol + '://' + @host) do |c| c.use Faraday::Request::UrlEncoded #c.use Faraday::Response::Logger c.use Faraday::Adapter::NetHttp end conn.basic_auth(@admin, @password) if Dir[@path+'*'].empty? @LOG.debug('Folder ' + @path + ' is EMPTY!') else Dir.foreach(@path) do |filename| next if filename == '.' or filename == '..' if !filename.end_with?('xls') and !filename.end_with?('xlsm') @LOG.debug('Ignore file: ' + filename) next end @LOG.debug('Analyzing ' + filename + ' ... ') iris_metadata = excel_to_iris_xmls(@path + filename) iris_metadata.each do |iris| begin ingest(conn, iris) rescue Exception => e @LOG.error(e.message) @LOG.error(iris) end end @LOG.debug('Moving file ' + filename + ' to ' + @processed_path) today = Time.now.strftime("%Y%m%d") FileUtils.mv(@path + filename, @processed_path + today + '_' + filename) end end end def excel_to_iris_xmls(excel_file_name) iris_metadata = Set.new xsl = Roo::Spreadsheet.open(excel_file_name) sheet = xsl.sheet(@sheetname) if !sheet.nil? last_row = sheet.last_row last_column = sheet.last_column if !last_row.nil? and !last_column.nil? for row in 2..last_row author1 = sheet.cell(row, @column_author1) if author1.nil? or author1.strip=='' next end author2 = sheet.cell(row, @column_author2) author3 = sheet.cell(row, @column_author3) author4 = sheet.cell(row, @column_author4) author5 = sheet.cell(row, @column_author5) author6 = sheet.cell(row, @column_author6) instrumenttype1 = sheet.cell(row, @column_instrumenttype1) instrumenttype2 = sheet.cell(row, @column_instrumenttype2) reseracharea1 = sheet.cell(row, @column_reseracharea1) reseracharea2 = sheet.cell(row, @column_reseracharea2) reseracharea3 = sheet.cell(row, @column_reseracharea3) typeoffile1 = sheet.cell(row, @column_typeoffile1) typeoffile2 = sheet.cell(row, @column_typeoffile2) software = sheet.cell(row, @column_software) other_software_url = sheet.cell(row, @column_other_software_url) instrumenttitle = sheet.cell(row, @column_instrumenttitle) notes = sheet.cell(row, @column_notes) participanttype1 = sheet.cell(row, @column_participanttype1) participanttype2 = sheet.cell(row, @column_participanttype2) language1 = sheet.cell(row, @column_language1) language1_2 = sheet.cell(row, @column_language1_2) language1_3 = sheet.cell(row, @column_language1_3) language2 = sheet.cell(row, @column_language2) language2_2 = sheet.cell(row, @column_language2_2) language2_3 = sheet.cell(row, @column_language2_3) publication1_type = sheet.cell(row, @column_publication1_type) publication1_author1 = sheet.cell(row, @column_publication1_author1) publication1_author2 = sheet.cell(row, @column_publication1_author2) publication1_author3 = sheet.cell(row, @column_publication1_author3) publication1_author4 = sheet.cell(row, @column_publication1_author4) publication1_author5 = sheet.cell(row, @column_publication1_author5) publication1_author6 = sheet.cell(row, @column_publication1_author6) publication1_title = sheet.cell(row, @column_publication1_title) publication1_journal = sheet.cell(row, @column_publication1_journal) publication1_date = sheet.cell(row, @column_publication1_date) publication1_volume = sheet.cell(row, @column_publication1_volume) publication1_issue_no = sheet.cell(row, @column_publication1_issue_no) publication1_page_number_from = sheet.cell(row, @column_publication1_page_number_from) publication1_page_number_to = sheet.cell(row, @column_publication1_page_number_to) publication1_doi = sheet.cell(row, @column_publication1_doi) email = sheet.cell(row, @column_email) builder = Nokogiri::XML::Builder.new do |xml| xml['iris'].iris('xmlns:iris' => @IRIS_NS) { ########################################################################### # instrument xml['iris'].instrument() { # processing authors type = 'new' if is_author_in_dd(author1.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author1.strip xml['iris'].firstName author1.split(',')[1].strip xml['iris'].lastName author1.split(',')[0].strip } if !author2.nil? and author2!='' type = 'new' if is_author_in_dd(author2.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author2.strip xml['iris'].firstName author2.split(',')[1].strip xml['iris'].lastName author2.split(',')[0].strip } end if !author3.nil? and author3!='' type = 'new' if is_author_in_dd(author3.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author3.strip xml['iris'].firstName author3.split(',')[1].strip xml['iris'].lastName author3.split(',')[0].strip } end if !author4.nil? and author4!='' type = 'new' if is_author_in_dd(author4.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author4.strip xml['iris'].firstName author4.split(',')[1].strip xml['iris'].lastName author4.split(',')[0].strip } end if !author5.nil? and author5!='' type = 'new' if is_author_in_dd(author5.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author5.strip xml['iris'].firstName author5.split(',')[1].strip xml['iris'].lastName author5.split(',')[0].strip } end if !author6.nil? and author6!='' type = 'new' if is_author_in_dd(author6.strip) type = 'auto' end xml['iris'].creator(:type => type) { xml['iris'].fullName author6.strip xml['iris'].firstName author6.split(',')[1].strip xml['iris'].lastName author6.split(',')[0].strip } end # processing instrument types if !instrumenttype1.nil? xpath = "/IRIS_Data_Dict/instrument/typeOfInstruments//type[@label='"+instrumenttype1.strip+"']/@value" v = dd_value_from_xpath(xpath) newValue = nil if v.nil? v = '999' newValue = instrumenttype1.strip end primary = v # assuming first ins type is the primary type if !instrumenttype2.nil? xpath = "/IRIS_Data_Dict/instrument/typeOfInstruments//type[@label='"+instrumenttype2.strip+"']/@value" v2 = dd_value_from_xpath(xpath) if !v2.nil? v = v.to_s + ' ' + v2.to_s end end if newValue.nil? xml['iris'].instrumentType(:primary=>primary) { xml.text(v) } else xml['iris'].instrumentType(:primary=>primary, :newValue=>newValue) { xml.text(v) } end end # processing research areas if !reseracharea1.nil? xpath = "/IRIS_Data_Dict/instrument/researchAreas//researchArea[@label='"+reseracharea1.strip+"']/@value" v = dd_value_from_xpath(xpath) newValue = nil if v.nil? v = '999' newValue = reseracharea1.strip end if !reseracharea2.nil? xpath = "/IRIS_Data_Dict/instrument/researchAreas//researchArea[@label='"+reseracharea2.strip+"']/@value" v2 = dd_value_from_xpath(xpath) if !v2.nil? v = v.to_s + ' ' + v2.to_s end end if !reseracharea3.nil? xpath = "/IRIS_Data_Dict/instrument/researchAreas//researchArea[@label='"+reseracharea3.strip+"']/@value" v3 = dd_value_from_xpath(xpath) if !v3.nil? v = v.to_s + ' ' + v3.to_s end end if newValue.nil? xml['iris'].researchArea() { xml.text(v) } else xml['iris'].researchArea(:newValue=>newValue) { xml.text(v) } end end # Processing type of file # processing research areas if !typeoffile1.nil? xpath = "/IRIS_Data_Dict/instrument/types/type[@value='"+typeoffile1.strip+"']/@value" v = dd_value_from_xpath(xpath) typeoffile = typeoffile1.strip if !typeoffile2.nil? xpath = "/IRIS_Data_Dict/instrument/types/type[@value='"+typeoffile2.strip+"']/@value" v2 = dd_value_from_xpath(xpath) v = v.to_s + ' ' + v2.to_s.strip end xml['iris'].type() { xml.text(v) } # Add software details if 'Software' is ticked if v.include? 'Software' and !software.nil? xpath = "/IRIS_Data_Dict/instrument/required_software/software[@label='"+software.strip+"']/@value" v = dd_value_from_xpath(xpath) newValue = nil href = nil if v.nil? v = '999' newValue = software.strip href = other_software_url end if !newValue.nil? xml['iris'].requires() { xml['iris'].software() { xml.text(v) } } else xml['iris'].requires() { xml['iris'].software(:href=>href, :newValue=>newValue) { xml.text(v) } } end end end # processing instrumenttitle if !instrumenttitle.nil? xml['iris'].title() { xml.text(instrumenttitle.strip) } end # processing notes if !notes.nil? xml['iris'].notes() { xml.text(notes.strip) } end } ########################################################################### # participants xml['iris'].participants() { # processing participant types if !participanttype1.nil? xpath = "/IRIS_Data_Dict/participants/participantTypes//type[@label='"+participanttype1.strip+"']/@value" v = dd_value_from_xpath(xpath) newValue = nil if v.nil? v = '999' newValue = participanttype1.strip end if !participanttype2.nil? xpath = "/IRIS_Data_Dict/participants/participantTypes//type[@label='"+participanttype2.strip+"']/@value" v2 = dd_value_from_xpath(xpath) if !v2.nil? v = v.to_s + ' ' + v2.to_s end end if newValue.nil? xml['iris'].participantType() { xml.text(v) } else xml['iris'].participantType(:newValue=>newValue) { xml.text(v) } end end # processing l1 if !language1.nil? and language1.strip!='' xml['iris'].firstLanguage() { xml.text(language1.strip) } end if !language1_2.nil? and language1_2.strip!='' xml['iris'].firstLanguage() { xml.text(language1_2.strip) } end if !language1_3.nil? and language1_3.strip!='' xml['iris'].firstLanguage() { xml.text(language1_3.strip) } end # processing l2 if !language2.nil? and language2.strip!='' xml['iris'].targetLanguage() { xml.text(language2.strip) } end if !language2_2.nil? and language2_2.strip!='' xml['iris'].targetLanguage() { xml.text(language2_2.strip) } end if !language2_3.nil? and language2_3.strip!='' xml['iris'].targetLanguage() { xml.text(language2_3.strip) } end } ########################################################################### # relatedItems xml['iris'].relatedItems() { xml['iris'].relatedItem(:type=>'publication') { # processing publication type if !publication1_type.nil? xpath = "/IRIS_Data_Dict/relatedItems/publicationTypes/type[@label='"+publication1_type.strip+"']/@value" v = dd_value_from_xpath(xpath) xml['iris'].publicationType() { xml.text(v) } end # processing authors type = 'new' if is_author_in_dd(publication1_author1.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author1.strip xml['iris'].firstName publication1_author1.split(',')[1].strip xml['iris'].lastName publication1_author1.split(',')[0].strip } if !publication1_author2.nil? and publication1_author2.to_s.strip!='' and publication1_author2.to_s.strip!='0' type = 'new' if is_author_in_dd(publication1_author2.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author2.strip xml['iris'].firstName publication1_author2.split(',')[1].strip xml['iris'].lastName publication1_author2.split(',')[0].strip } end if !publication1_author3.nil? and publication1_author3.to_s.strip!='' and publication1_author3.to_s.strip!='0' type = 'new' if is_author_in_dd(publication1_author3.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author3.strip xml['iris'].firstName publication1_author3.split(',')[1].strip xml['iris'].lastName publication1_author3.split(',')[0].strip } end if !publication1_author4.nil? and publication1_author4.to_s.strip!='' and publication1_author4.to_s.strip!='0' type = 'new' if is_author_in_dd(publication1_author4.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author4.strip xml['iris'].firstName publication1_author4.split(',')[1].strip xml['iris'].lastName publication1_author4.split(',')[0].strip } end if !publication1_author5.nil? and publication1_author5.to_s.strip!='' and publication1_author5.to_s.strip!='0' type = 'new' if is_author_in_dd(publication1_author5.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author5.strip xml['iris'].firstName publication1_author5.split(',')[1].strip xml['iris'].lastName publication1_author5.split(',')[0].strip } end if !publication1_author6.nil? and publication1_author6.to_s.strip!='' and publication1_author6.to_s.strip!='0' type = 'new' if is_author_in_dd(publication1_author6.strip) type = 'auto' end xml['iris'].author(:type => type) { xml['iris'].fullName publication1_author6.strip xml['iris'].firstName publication1_author6.split(',')[1].strip xml['iris'].lastName publication1_author6.split(',')[0].strip } end # processing title if !publication1_title.nil? xml['iris'].itemTitle(:type => '') { xml.text publication1_title.strip } end # processing journal if !publication1_journal.nil? xpath = "/IRIS_Data_Dict/relatedItems/journals/journal[@label='"+publication1_journal.strip+"']/@value" v = dd_value_from_xpath(xpath) newValue = nil if v.nil? v = '999' newValue =publication1_journal.strip end if newValue.nil? xml['iris'].journal() { xml.text(v) } else xml['iris'].journal(:newValue=>newValue) { xml.text(v) } end end # processing date if !publication1_date.nil? xml['iris'].yearOfPublication() { xml.text(publication1_date) } end # processing volume if !publication1_volume.nil? xml['iris'].volume() { xml.text(publication1_volume) } end # processing issue no if !publication1_issue_no.nil? xml['iris'].issue() { xml.text(publication1_issue_no) } end # processing page no from if !publication1_page_number_from.nil? xml['iris'].pageFrom(:notknown=>"false") { xml.text(publication1_page_number_from) } else xml['iris'].pageFrom(:notknown=>"true") { xml.text("") } end # processing page no to if !publication1_page_number_to.nil? xml['iris'].pageTo() { xml.text(publication1_page_number_to) } end # processing doi if !publication1_doi.nil? xml['iris'].identifier() { xml.text(publication1_doi) } end } } ########################################################################### # settings xml['iris'].settings() { xml['iris'].feedback() { xml.text('1') } xml['iris'].notifyDownloads() { xml.text('true') } # processing email if !email.nil? xml['iris'].email() { xml.text(email) } end xml['iris'].comments() { } xml['iris'].licenceagreement() { xml.text('true') } } } end iris_metadata << builder.to_xml end else @LOG.warn('Seems no data in ' + sheet_name) end end iris_metadata end # convert IRIS to DC def iris_to_dc(iris) xsl = Nokogiri::XSLT(File.read(@xslt)) xml = Nokogiri::XML(iris) xsl.apply_to(xml).to_s end def rels_int(pid) builder = Nokogiri::XML::Builder.new do |xml| xml['rdf'].RDF('xmlns:rdf' => @RDF_NS, 'xmlns:rel-int' => @REL_INT_NS) { xml['rdf'].Description(:'rdf:about' => 'info:fedora/'+pid+'/THUMBNAIL_IMAGE') { xml['rel-int'].hasDatastreamLabel() { xml.text('Thumbnail') } } } end builder.to_xml end def rels_ext(pid) builder = Nokogiri::XML::Builder.new do |xml| xml['rdf'].RDF('xmlns:rdf' => @RDF_NS, 'xmlns:fedora-model' => @FEDORA_MODEL_NS, 'xmlns:rel' => @REL_NS) { xml['rdf'].Description(:'rdf:about' => 'info:fedora/'+pid) { xml['rel'].isMemberOf(:'rdf:resource'=>'info:fedora/'+@iris_parent_collection) xml['fedora-model'].hasModel(:'rdf:resource'=>'info:fedora/york:CModel-Iris') } } end builder.to_xml end def ingest(conn, iris) @LOG.debug('Transferring data to IRIS object ... ') # Create empty object @LOG.debug(' Creating empty object ... ') resp = conn.post '/fedora/objects/new?label='+@object_label+'&namespace='+@object_namespace+'&ownerId=' + @object_ownerid do |req| req.headers['Content-Type'] = '' # the default Content Type set by Faraday is NOT accepted by Fedora server, so reset it to blank req.headers['charset'] = 'utf-8' end pid = resp.body.to_s @LOG.debug(' Created: ' + pid) # ingest IRIS datastream @LOG.debug(' Adding IRIS datastream ... ') resp = conn.post '/fedora/objects/'+pid+'/datastreams/IRIS?format=xml&dsLabel=IRIS&mimeType=text/xml&controlGroup=X', iris do |req| req.headers['Content-Type'] = '' # the default Content Type set by Faraday is NOT accepted by Fedora server, so reset it to blank req.headers['charset'] = 'utf-8' end # update DC @LOG.debug(' Updating DC datastream ... ') dc = iris_to_dc(iris) resp = conn.put '/fedora/objects/'+pid+'/datastreams/DC?format=xml&dsLabel=Dublin%20Core%20Metadata%20(DC)&mimeType=text/xml&controlGroup=X', dc do |req| req.headers['Content-Type'] = '' req.headers['charset'] = 'utf-8' end # ingest RELS_INT @LOG.debug(' Adding RELS-INT datastream ... ') relsint = rels_int(pid) resp = conn.post '/fedora/objects/'+pid+'/datastreams/RELS-INT?format=xml&dsLabel=Relationship%20Assertion%20Metadata%20(RELS-INT)&mimeType=text/xml&controlGroup=X', relsint do |req| req.headers['Content-Type'] = '' req.headers['charset'] = 'utf-8' end # ingest RELS_EXT @LOG.debug(' Adding RELS-EXT datastream ... ') relsext = rels_ext(pid) resp = conn.post '/fedora/objects/'+pid+'/datastreams/RELS-EXT?format=xml&dsLabel=Fedora%20Object-to-Object%20Relationship%20Metadata%20(RELS-EXT)&mimeType=text/xml&controlGroup=X', relsext do |req| req.headers['Content-Type'] = '' req.headers['charset'] = 'utf-8' end @LOG.debug(' Adding thumbnails ... ') irisdoc = Nokogiri::XML(iris) filetype = irisdoc.at_xpath('/iris:iris/iris:instrument/iris:type').text thumbnail = thumbnail_url(filetype.strip) resp = conn.post '/fedora/objects/'+pid+'/datastreams/'+@thumbnail_ds_id+'?dsLabel='+@thumbnail_ds_label+'&mimeType=image/png&controlGroup=E&dsLocation='+thumbnail do |req| req.headers['Content-Type'] = '' req.headers['charset'] = 'utf-8' end @LOG.debug(' Sending notification email ... ') # send_via_gmail(@gmail_user,@gmail_pass,@gmail_to,'Your instrument has been created from Excel spreadsheet',"http://"+@irishost+'/iris/app/home/detail?id='+pid,nil) end def thumbnail_url(filetype) url = '' @default_iris_url = @props['iris.instruments.url'] if filetype=='Sound' url = @default_iris_url + @sound_thumbnail elsif filetype=='Video' url = @default_iris_url + @video_thumbnail elsif filetype=='Text' url = @default_iris_url + @text_thumbnail elsif filetype=='StillImage' url = @default_iris_url + @image_thumbnail elsif filetype=='Software' url = @default_iris_url + @software_thumbnail else url = @default_iris_url + @multi_thumbnail end url end # def send_via_gmail(user,pass,_to,_subject,_body,attach_file_name) # gmail = Gmail.connect(user, pass) # email = gmail.compose do # to _to # subject _subject # body _body # if !attach_file_name.nil? # add_file attach_file_name # end # end # email.deliver! # end end bu = BatchUpdater.new() bu.update()
class Comment < ActiveRecord::Base attr_accessible :post_id, :user_id, :content validates :content, presence: true validates :user_id, presence: true belongs_to :user end
require "spec_helper" module LabelGen describe "confirming numbers" do context "after they have been rendered to a page" do let(:fname){'confirm_render_spec_0.pdf'} let(:fpath){File.join(SPEC_TMP_PATH, fname)} let(:doc){Page.new(:title => fname)} let(:n_vals){5} let(:vals){NumberGenerator.new(n_vals)} before :all do DataMapper.auto_migrate! doc.fill_labels(vals) NumberRecord.confirm_used(vals.number) end it "records the last number from the generator as the max used" do expect(NumberRecord.max_number_confirmed).to eq vals.number end context "more numbers are rendered" do let(:n_vals_more){7} let(:vals_more){NumberGenerator.new(n_vals_more)} before :all do doc.fill_labels(vals_more) end it "generates a higher number than the previous generator" do expect(vals_more.number).to be_> vals.number end it "records the last number in the generator as used" do expect(NumberRecord.max_number_used).to eq vals_more.number end describe "confirming the additional numbers" do before :all do NumberRecord.confirm_used(vals_more.number) end it "records the last number from the generator as the max used" do expect(NumberRecord.max_number_confirmed).to eq vals_more.number end end # describe "confirming the additional numbers" end # context "more nebers are rendered" end # context "after they have been rendered to a page" end # describe "confirming numbers" do end
#Simple math game to practice addition, subtraction and multiplication with negative numbers # This particular challenge will address the teaching standards module MathGame class << self def play print("\nChoose your challenge! \n1 = Addition\n2 = Subtraction\n3 = Multiplication\n4 = Random\n") choice = gets.to_i #gets returns a String. Ruby never autoconverts to Integer, so to_i does that. firstchoice = choice #necessary to have the random choice carried out properly rounds = 1 #gets returns a String. Ruby never autoconverts to Integer, so to_i does that. #Defining the values to be factored into the questions addminusmax = (-10..10) #The max number of add and minus calcs factormax = 12 #The max number of factor try = nil while rounds > 0 # Defining & resetting variables if firstchoice == 4 #if the choice is 4, from now on, keep looping the random numbers for each round choice = 1 + rand(3) #the 1 + thing makes it a random draw from 1 to 3 instead of 0 to 3 end ctries = 0 #default try count aaddminus = rand(addminusmax) baddminus = rand(addminusmax) cfactormax = 1 + rand(factormax) dfactormax = 1 + rand(factormax) # Asking the questions if choice == 1 result = aaddminus + baddminus puts "What is the result of #{aaddminus} + #{baddminus}?" elsif choice == 2 result = aaddminus - baddminus puts "What is the result of #{aaddminus} - #{baddminus}?" elsif choice == 3 result = cfactormax * dfactormax puts "What is the result of #{cfactormax} * #{dfactormax}?" end # Check the answers rounds = 0 while try != result and rounds < 2 rounds += 1 try = gets.to_i #gets returns a String. Ruby never autoconverts to Integer, so to_i does that. ## this needs ot change to only allow for 2 tries by the user. Once the second user is done then it continues to the death class. if (try < result) puts "Incorrect. Try again! Hint: it's bigger..." # INCORRECT IS INFINITE elsif (try > result) puts "Incorrect. Try again! Hint: it's smaller..." ## perhaps this solution should also include remember your number line! end if try == result #if answer is correct print " #{result} is correct! \n\n" ## output extra information story wise end end end end end end ###after two incorrect answers pull from deathclass. ## after correct answer pull from next quest class
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) (2...13)each do |i| [ :spade, :heart, :club, :diamond ].each do |suit| Card.create(card: i, suit: suit) end end
module Authenticate module Testing # Helpers for view tests/specs. # # Use login_as to log in a user for your test case, which allows # `current_user`, `logged_in?` and `logged_out?` to work properly in your test. module ViewHelpers # Set the current_user on the view being tested. def login_as(user) view.current_user = user end module CurrentUser attr_accessor :current_user def logged_in? current_user.present? end def logged_out? !logged_in? end end end end end
class UpdatePhotos < ActiveRecord::Migration def up remove_column :photos, :event_id create_table :events_photos, :id => false do |t| t.integer "event_id", :null => false t.integer "photo_id", :null => false end execute <<-SQL ALTER TABLE events_photos ADD CONSTRAINT fk_event_photos FOREIGN KEY (event_id) REFERENCES events(id) SQL add_index :events_photos, ["event_id","photo_id"], :unique => true end def down execute <<-SQL ALTER TABLE events_photos DROP CONSTRAINT fk_event_photos SQL drop_table :events_photos add_column :photos, :event_id,:integer end end
require 'rbconfig' require 'fileutils' require 'pathname' require 'presser/version' module Presser autoload :Dsl, 'presser/dsl' autoload :UI, 'presser/ui' class PresserError < StandardError def self.status_code(code) define_method(:status_code) { code } end end class PressfileNotFound < PresserError; status_code(10) ; end class PluginNotFound < PresserError; status_code(7) ; end class PressfileError < PresserError; status_code(4) ; end class InstallError < PresserError; status_code(5) ; end class InstallHookError < PresserError; status_code(6) ; end class PathError < PresserError; status_code(13) ; end class GitError < PresserError; status_code(11) ; end class DeprecatedError < PresserError; status_code(12) ; end class PluginspecError < PresserError; status_code(14) ; end class DslError < PresserError; status_code(15) ; end class ProductionError < PresserError; status_code(16) ; end class InvalidOption < DslError ; end class HTTPError < PresserError; status_code(17) ; end class RubyVersionMismatch < PresserError; status_code(18) ; end WINDOWS = RbConfig::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw)! FREEBSD = RbConfig::CONFIG["host_os"] =~ /bsd/ NULL = WINDOWS ? "NUL" : "/dev/null" # Internal errors, should be rescued class VersionConflict < PresserError attr_reader :conflicts def initialize(conflicts, msg = nil) super(msg) @conflicts = conflicts end status_code(6) end class InvalidSpecSet < StandardError; end class << self attr_writer :ui, :press_path def ui @ui ||= UI.new end end end
Rails.application.routes.draw do root 'home#index', as: 'home' post 'shorten-url', to: 'url#shortenUrl' get '/:url', to: 'url#getOriginalUrl' end
require "minitest/autorun" require "minitest/pride" require_relative './gilded_rose' class GildedRoseTest < MiniTest::Unit::TestCase def update_quality_for_item_with(sell_in, quality, name = 'normal item', sell_in_decrease = 1) item = GildedRose.new(name, sell_in, quality) item.update assert_equal item.days_remaining, sell_in - sell_in_decrease item end def test_normal_item_before_sell_date item = update_quality_for_item_with(5, 10, 'normal') assert_equal 9, item.quality end def test_normal_item_on_sell_date item = update_quality_for_item_with(0, 10, 'normal') assert_equal 8, item.quality end def test_normal_item_after_sell_date item = update_quality_for_item_with(-10, 10, 'normal') assert_equal 8, item.quality end def test_normal_item_of_zero_quality item = update_quality_for_item_with(5, 0, 'normal') assert_equal 0, item.quality end def test_brie_before_sell_date item = update_quality_for_item_with(5, 10, 'Aged Brie') assert_equal 11, item.quality end def test_brie_before_sell_date_with_max_quality item = update_quality_for_item_with(5, 50, 'Aged Brie') assert_equal 50, item.quality end def test_brie_on_sell_date item = update_quality_for_item_with(0, 10, 'Aged Brie') assert_equal 12, item.quality end def test_brie_on_sell_date_near_max_quality item = update_quality_for_item_with(5, 49, 'Aged Brie') assert_equal 50, item.quality end def test_brie_on_sell_date_with_max_quality item = update_quality_for_item_with(5, 50, 'Aged Brie') assert_equal 50, item.quality end def test_brie_after_sell_date item = update_quality_for_item_with(-10, 10, 'Aged Brie') assert_equal 12, item.quality end def test_brie_after_sell_date_with_max_quality item = update_quality_for_item_with(-10, 50, 'Aged Brie') assert_equal 50, item.quality end def test_sulfuras_before_sell_date item = update_quality_for_item_with(5, 80, 'Sulfuras, Hand of Ragnaros', 0) assert_equal 80, item.quality end def test_sulfuras_on_sell_date item = update_quality_for_item_with(0, 80, 'Sulfuras, Hand of Ragnaros', 0) assert_equal 80, item.quality end def test_sulfuras_after_sell_date item = update_quality_for_item_with(-10, 80, 'Sulfuras, Hand of Ragnaros', 0) assert_equal 80, item.quality end def test_backstage_pass_long_before_sell_date item = update_quality_for_item_with(11, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 11, item.quality end def test_backstage_pass_medium_close_to_sell_date_upper_bound item = update_quality_for_item_with(10, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 12, item.quality end def test_backstage_pass_medium_close_to_sell_date_upper_bound_at_max_quality item = update_quality_for_item_with(10, 50, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 50, item.quality end def test_backstage_pass_medium_close_to_sell_date_lower_bound item = update_quality_for_item_with(6, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 12, item.quality end def test_backstage_pass_medium_close_to_sell_date_lower_bound_at_max_quality item = update_quality_for_item_with(6, 50, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 50, item.quality end def test_backstage_pass_very_close_to_sell_date_upper_bound item = update_quality_for_item_with(5, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 13, item.quality end def test_backstage_pass_very_close_to_sell_date_upper_bound_at_max_quality item = update_quality_for_item_with(5, 50, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 50, item.quality end def test_backstage_pass_very_close_to_sell_date_lower_bound item = update_quality_for_item_with(1, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 13, item.quality end def test_backstage_pass_very_close_to_sell_date_lower_bound_at_max_quality item = update_quality_for_item_with(1, 50, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 50, item.quality end def test_backstage_pass_on_sell_date item = update_quality_for_item_with(0, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 0, item.quality end def test_backstage_pass_after_sell_date item = update_quality_for_item_with(-10, 10, 'Backstage passes to a TAFKAL80ETC concert') assert_equal 0, item.quality end def test_conjured_item_before_sell_date skip item = update_quality_for_item_with(5, 10, 'Conjured Mana Cake') assert_equal 8, item.quality end def test_conjured_item_at_zero_quality skip item = update_quality_for_item_with(5, 0, 'Conjured Mana Cake') assert_equal 0, item.quality end def test_conjured_item_on_sell_date skip item = update_quality_for_item_with(0, 10, 'Conjured Mana Cake') assert_equal 6, item.quality end def test_conjured_item_on_sell_date_at_zero_quality skip item = update_quality_for_item_with(0, 0, 'Conjured Mana Cake') assert_equal 0, item.quality end def test_conjured_item_after_sell_date skip item = update_quality_for_item_with(-10, 10, 'Conjured Mana Cake') assert_equal 6, item.quality end def test_conjured_item_after_sell_date_at_zero_quality skip item = update_quality_for_item_with(-10, 0, 'Conjured Mana Cake') assert_equal 0, item.quality end end
class CreateFriendShips < ActiveRecord::Migration def up create_table :friendships do |t| t.integer :friendable_id t.integer :friend_id t.string :token t.integer :pending t.integer :location_id t.integer :point t.timestamps end end def down drop_table :friendships end end
module RSpec module Matchers module Sequel class HavePrimaryKey def matches?(subject) @table = subject get_keys includes_all? end def description %(have #{wording(@names)}) end def failure_message %(expected #{@table} to #{description} but #{@table} have #{wording(@keys)}) end def failure_message_when_negated %(did not expect #{@table} to #{description}) end private def initialize(*names) @names = names @keys = [] end def get_keys @keys = DB.schema(@table).reject { |tuple| !tuple.last[:primary_key] }.map(&:first) end def includes_all? @names.reject { |k| @keys.include?(k) }.empty? end def wording(arr) case arr.length when 0 %(no primary keys) when 1 %(primary key "#{arr.first}") else %(primary keys #{arr.inspect}) end end end def have_primary_key(*names) HavePrimaryKey.new(*names) end alias :have_primary_keys :have_primary_key end end end
require_relative("../db/sql_runner") require_relative("film.rb") class Customer attr_reader :id attr_accessor :name, :funds def initialize(options) @id = options['id'].to_i @name = options['name'] @funds = options['funds'] end def save() sql = "INSERT INTO customers(name, funds) VALUES($1, $2) RETURNING id" values = [@name, @funds] customer = SqlRunner.run(sql, values).first @id = customer['id'].to_i end def self.all() sql = "SELECT * FROM customers" values = [] customers = SqlRunner.run(sql, values) results = customers.map {|customer| Customer.new(customer)} return results end def self.delete_all() sql = "DELETE FROM customers" values = [] SqlRunner.run(sql, values) end end
class Card attr_accessor :suit, :rank, :nominal SUITS = ["✣", "❤", "♦", "♠"] RANKS = { "2" => 2,"3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10, "V" => 10, "D" => 10, "K" => 10, "T" => 11 } def initialize(suit, rank, nominal) @suit = suit @rank = rank @nominal = nominal end end
require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) class JSLineTerminatorTest < Test::Unit::TestCase include TestHelper def setup @parser = JSLineTerminatorParser.new end def test_LineTerminator assert_parsed "\n" assert_parsed <<-EOF EOF end end
class Entry < ApplicationRecord belongs_to :user belongs_to :category scope :income, -> {where(type: 'income')} scope :expense, -> {where(type: 'expense')} def self.to_csv(options = {}) CSV.generate(options) do |csv| csv << column_names all.each do |entry| csv << entry.attributes.values_at(*column_names) end end end end
class CreateCidades < ActiveRecord::Migration def change create_table :cidades do |t| t.string :nome, :limit => 50, :null => false t.date :data_fundacao, :null => true t.float :area, :null => true t.integer :populacao, :null => true t.float :altitude, :null => true t.float :longitude, :null => true t.float :latitude, :null => true t.references :Pais t.references :Foto_Cidade t.timestamps end add_index :cidades, :foto_cidade_id, :unique =>true add_index :cidades, :pais_id, :unique => true end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'omniauth-redis-store/version' Gem::Specification.new do |spec| spec.add_development_dependency 'bundler', '~> 1.0' spec.authors = ['Paul Scarrone'] spec.description = %Q(An adapter for using Redis like a session keystore during requests compatible with #{OmniAuthRedisStore::OMNIAUTH_COMPAT}) spec.email = ['paul.scarrone@gmail.com'] spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.homepage = 'http://github.com/ninjapanzer/omniauth-redis-store' spec.licenses = %w(MIT) spec.name = 'omniauth-redis-store' spec.require_paths = %w(lib) spec.required_rubygems_version = '>= 1.3.5' spec.summary = spec.description spec.version = OmniAuthRedisStore::VERSION end
class MealsController < ApplicationController before_action :set_meal, only: [:show, :edit, :update, :destroy] # GET /meals # GET /meals.json def index @meals = Meal.all respond_to do |format| format.html # index.html.erb format.json { render json: @meals } end end # GET /meals/1 # GET /meals/1.json def show respond_to do |format| format.html # show.html.erb format.json { render json: @meal } end end # GET /meals/new # GET /meals/new.json def new @meal = Meal.new respond_to do |format| format.html # new.html.erb format.json { render json: @meal } end end # GET /meals/1/edit def edit end # POST /meals # POST /meals.json def create @meal = Meal.new(meal_params) respond_to do |format| if @meal.save format.html { redirect_to @meal, notice: 'Meal was successfully created.' } format.json { render json: @meal, status: :created, location: @meal } else format.html { render action: "new" } format.json { render json: @meal.errors, status: :unprocessable_entity } end end end # PUT /meals/1 # PUT /meals/1.json def update respond_to do |format| if @meal.update(meal_params) format.html { redirect_to @meal, notice: 'Meal was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @meal.errors, status: :unprocessable_entity } end end end # DELETE /meals/1 # DELETE /meals/1.json def destroy @meal.destroy respond_to do |format| format.html { redirect_to meals_url } format.json { head :no_content } end end def report @meals = Meal.all @breakfast = [] @lunch = [] @dinner = [] @meals.each do |meal| case meal.first_day_meal_type when 1 @lunch[0] += 1 when 3 @breakfast[0] += 1 @lunch[0] += 1 @dinner[0] += 1 end case meal.second_day_meal_type when 1 @lunch[1] += 1 when 3 @breakfast[1] += 1 @lunch[1] += 1 @dinner[1] += 1 end case meal.third_day_meal_type when 1 @lunch[2] += 1 when 3 @breakfast[2] += 1 @lunch[2] += 1 @dinner[2] += 1 end case meal.fourth_day_meal_type when 1 @lunch[3] += 1 when 3 @breakfast[3] += 1 @lunch[3] += 1 @dinner[3] += 1 end case meal.fifth_day_meal_type when 1 @lunch[4] += 1 when 3 @breakfast[4] += 1 @lunch[4] += 1 @dinner[4] += 1 end case meal.sixth_day_meal_type when 1 @lunch[5] += 1 when 3 @breakfast[5] += 1 @lunch[5] += 1 @dinner[5] += 1 end end end private # Use callbacks to share common setup or constraints between actions. def set_meal @meal = Meal.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def meal_params params.require(:meal).permit(:fifth_day, :fifth_day_meal_type, :first_day, :first_day_meal_type, :food_type, :fourth_day, :fourth_day_meal_type, :second_day, :second_day_meal_type, :sixth_day, :sixth_day_meal_type, :third_day, :third_day_meal_type) end end
class ProcessPool def initialize debug_options = {} @debug_options = debug_options @pool = [] end def dispatch node, &block if @debug_options[ :dry_run ] block.call node return end pid = Kernel.fork do block.call node end @pool << [ pid, node ] end def shutdown return if @debug_options[ :dry_run ] @pool.each do | pid, node | begin hoge, status = Process.waitpid2( pid ) if status.exitstatus != 0 raise "Node #{ node.name } failed" end rescue Errno::ECHILD # do nothing nil end end end def killall @pool.each do | pid, node | Process.kill "TERM", pid end end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
# # Cookbook Name: monit-ng # Attributes: rsyslog # default['monit']['checks'].tap do |check| check['rsyslog_init'] = '/etc/init.d/rsyslog' check['rsyslog_pid'] = value_for_platform_family( 'rhel' => '/var/run/syslogd.pid', 'debian' => '/var/run/rsyslogd.pid', 'default' => '/var/run/rsyslogd.pid', ) end
class RoomDate < ApplicationRecord belongs_to :room has_many :reservations_room_dates has_many :reservations, through: :reservations_room_dates end
panel t("reports.name.#{params[:action]}", :name => params[:action], :time_group => time_group_t, :time_period => time_period_t), :class => :table do block do if @report.empty? h3 t('reports.no_visits_recorded') else total_page_views = @report.map{|v| v.page_views.to_i }.sum store @report.to_table(:percent_of_page_views => total_page_views) end end end