text
stringlengths
10
2.61M
# encoding: utf-8 class AddIndexRecipeStepDrafts < ActiveRecord::Migration def up add_index :recipe_step_drafts, :recipe_draft_id end def down remove_index :recipe_step_drafts, :recipe_draft_id end end
module FieldCallback extend ActiveSupport::Concern included do set_callback :data_changed, :after, :data_changed_callback end def data_changed_callback; end end class TreasuryFieldsBase < Treasury::Fields::Base include FieldCallback def self.value_as_integer(params) raise_no_implemented(:integer, params) end end describe TreasuryFieldsBase do let(:field) { build_stubbed :'denormalization/field' } subject { described_class.new(field) } context '#data_changed' do let(:chaged_objects) { [1, 2, 3] } it 'run callbacks' do expect(subject).to receive(:run_callbacks).with(:data_changed) subject.send(:data_changed, chaged_objects) end it 'correctly set changed_objects' do subject.send(:data_changed, chaged_objects) expect(subject.send(:changed_objects)).to eq chaged_objects end it 'has data_changed callback' do expect(subject).to receive(:data_changed_callback) subject.send(:data_changed, chaged_objects) end end describe 'raise_no_implemented' do it do expect { described_class.value_as_integer({}) } .to raise_error(Treasury::Fields::Errors::NoAccessor) end end describe '#reset_field_value' do let(:storage) { double(id: :dummy) } before do allow(subject).to receive(:logger).and_return Rails.logger allow(subject).to receive(:storages).and_return([storage]) end it { expect(storage).to receive(:reset_data).with(nil, [:dummy_field]) } after { subject.reset_field_value(:dummy_field) } end describe '#value' do let(:silence) { false } before do described_class._instance = nil allow(field).to receive(:reload) allow(Treasury::Fields::Base).to receive(:extract_object) allow(Treasury::Fields::Base).to receive(:create_by_class).and_return(subject) allow_any_instance_of(Treasury::Fields::Base).to receive(:raw_value_from_storage).and_return(value_from_storage) described_class.init_accessor(silence: silence) end context 'when field initialized' do let(:value_from_storage) { 5 } it { expect(described_class.value).to eq 5 } end context 'when field uninitialized' do let(:field) { build_stubbed :'denormalization/field', :need_initialize } let(:value_from_storage) { nil } it { expect { described_class.value }.to raise_error Treasury::Fields::Errors::UninitializedFieldError } context 'when silence' do let(:silence) { true } it { expect(described_class.value).to eq nil } end end end end
#Given (/^I have set up the user database$/) do # User.create( # Email: "Tom@seas.upenn.edu", # Password: "12345678", # Password_confirmation: "12345678") # end # When(/^I fill the credentials and log in$/) do # fill_in 'Email', :with => "Tom@seas.upenn.edu" # fill_in 'Password', :with => "12345678" # click_button "Log in" # end # Given(/^I'm in the user launchpad$/) do # visit root_path # end # When(/^click the log out$/) do # click_link "Log out" # end # Then(/^I should be able to sign out$/) do # assert page.has_content?("Signed out successfully.") # assert page.has_no_link? "log Out" # end
class ScheduleSerializer def initialize(object) @schedule = object end def to_serialized_json options = { include: { shifts: { except: [:created_at, :updated_at] }, user: { only: [:id, :first_name, :last_name, :username] } }, except: [:created_at] } @schedule.to_json(options) end end
class SumOfMultiples def initialize(*multiples) @multiples = multiples end def to(num) (1...num).select { |n| @multiples.any? { |multiple| (n % multiple).zero? } }.reduce(0, :+) end def self.to(num) new(3,5).to(num) end end
# encoding: UTF-8 # Copyright © Emilio González Montaña # Licence: Attribution & no derivates # * Attribution to the plugin web page URL should be done if you want to use it. # https://redmine.ociotec.com/projects/advanced-roadmap # * No derivates of this plugin (or partial) are allowed. # Take a look to licence.txt file at plugin root folder for further details. require_dependency 'query' module AdvancedRoadmap module QueryPatch def self.included(base) base.class_eval do # Returns the milestones # Valid options are :conditions def milestones(options = {}) Milestone .joins(:project) .includes(:project) .where(Query.merge_conditions(project_statement, options[:conditions])) rescue ::ActiveRecord::StatementInvalid => e raise StatementInvalid.new(e.message) end # Deprecated method from Rails 2.3.X. def self.merge_conditions(*conditions) segments = [] conditions.each do |condition| unless condition.blank? sql = sanitize_sql(condition) segments << sql unless sql.blank? end end "(#{segments.join(') AND (')})" unless segments.empty? end end end end end
Rails.application.routes.draw do resources :books, only: [:show] end
require 'test_helper' class DeveloperPortal::SearchControllerTest < DeveloperPortal::ActionController::TestCase test 'index forbidden' do provider = FactoryBot.create(:provider_account) provider.settings.update_attribute(:public_search, false) request.host = provider.domain get :index, format: 'json', q: 'stuff' assert_json 'status' => 'Forbidden' end test 'index as json' do provider = FactoryBot.create(:provider_account) provider.settings.update_attribute(:public_search, true) request.host = provider.domain SearchPresenters::IndexPresenter.any_instance.stubs(search_results: [ 'stuff' ]) get :index, format: 'json', q: 'stuff' assert_json [ 'stuff' ] end end
# ..................Case Statement............ # Used in place of elsif def rate_my_food(food) case food when "Steak" "Pass the steak sauce! That's delicious!" when "Sushi" "Great choice, my favourite food" when "Tacos", "Burritos", "Quesadillas" "Yum yum! I love Mexican food" when "Tofu", "Brussel Sprouts" "Disgusting! Yuck!" else "I haven't tried that food" end end puts "What it your favourite food?" x = gets.chomp puts rate_my_food(x) # ......Grade Calculator def calculate_school_grade(grade) case grade when 100 "A*" when 90..99 "A" when 80..89 "B" when 70..79 "C" when 60..69 "D" else "F" end end def calculate_school_grade(grade) case grade when 100 then "A*" when 90..99 then "A" when 80..89 then "B" when 70..79 then "C" when 60..69 then "D" else "F" end end puts "Can I have your mark?" mark = gets.chomp.to_i if mark == 100 puts "Oh my god! I can't believe you got an #{calculate_school_grade(mark)}" elsif mark <= 59 puts "You got a #{calculate_school_grade(mark)}? Man, you're a fucking moron!" else puts "Well done, you got a #{calculate_school_grade(mark)}" end # .............. Negation with ! .............. # ! is equal to saying "this is not..." user = "free" if user != "subscriber" puts "Only subscribers here" end puts !true puts !nil puts !3 puts !!3 # ............... Unless Keyboard ........ password = "whiskers" if password != "whiskers" puts "Not allowed!" else puts "That's the right password, welcome!" end unless password == "whiskers" puts "Not allowed!" else puts "That's the right password, welcome!" end puts "Please can I have your new password?" password = "whiskers" unless password.include?("a") puts "It includes the letter a!" end # ................. While Keyword ................ i = 1 while i <= 10 puts i i += 1 end # Username and password authentication status = true while status print "Please enter username: " username = gets.chomp.downcase print "Please enter your password: " password = gets.chomp.downcase if username == "adam" && password == "udemy" puts "Entry granted. The nuclear codes are 1354" status = false elsif username == "quit" || password == "quit" puts "Goodbye! Better luck next time" status = false else puts "Incorect combination, try again or enter 'quit' to exit" end end # ................... Until keyboard ............... i = 1 until i > 9 puts i i += 1 end #...................... FizzBuzz ................... def fizzbuzz(number) i = 0 # You can use; while i <= number until i > number if (i % 3 == 0) && (i % 5 == 0) puts "FizzBuzz" elsif (i % 3 == 0) puts "Fizz" elsif (i % 5 == 0) puts "Buzz" else puts i end i += 1 end end puts "Can I have a number?" input = gets.chomp.to_i fizzbuzz(input) # ...................... Statement Modifiers / Inline modifiers .............. number = 5000 verified = true if number > 2500 && verified == true puts "Huge number!" end puts "Huge number!" if number > 2500 && verified == true # .................... Conditional Assignment ............. y = nil p y y ||= 5 p y y ||= 10 p y greeting = "Hello" extraction = 0 letter = greeting[extraction] letter ||= "Not found"
require 'net/http' require 'resolv' require 'uri' class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception # This endpoint is used for health checks. It should return a 200 OK when the app is up and ready to serve requests. def health render plain: "OK" end # Resolve the SRV records for the hostname in the URL def expand_url(url) uri = URI(url) resolver = Resolv::DNS.new() # if host is relative, append the service discovery name host = uri.host.count('.') > 0 ? uri.host : "#{uri.host}.#{ENV["_SERVICE_DISCOVERY_NAME"]}" # lookup the SRV record and use if found begin srv = resolver.getresource(host, Resolv::DNS::Resource::IN::SRV) uri.host = srv.target.to_s uri.port = srv.port.to_s logger.info "uri port is #{uri.port}" if uri.port == 0 uri.port = 80 logger.info "uri port is now #{uri.port}" end rescue => e logger.error e.message logger.error e.backtrace.join("\n") end logger.info "expanded #{url} to #{uri}" uri end before_action :discover_availability_zone before_action :code_hash def discover_availability_zone @az = ENV["AZ"] end def code_hash @code_hash = ENV["CODE_HASH"] end def custom_header response.headers['Cache-Control'] = 'max-age=86400, public' end end
require "application_system_test_case" class HealthRecordsTest < ApplicationSystemTestCase setup do @health_record = health_records(:one) end test "visiting the index" do visit health_records_url assert_selector "h1", text: "Health Records" end test "creating a Health record" do visit health_records_url click_on "New Health Record" fill_in "Birthday", with: @health_record.birthday fill_in "Diagnosis", with: @health_record.diagnosis fill_in "History", with: @health_record.history fill_in "Name", with: @health_record.name fill_in "Recorded by", with: @health_record.recorded_by click_on "Create Health record" assert_text "Health record was successfully created" click_on "Back" end test "updating a Health record" do visit health_records_url click_on "Edit", match: :first fill_in "Birthday", with: @health_record.birthday fill_in "Diagnosis", with: @health_record.diagnosis fill_in "History", with: @health_record.history fill_in "Name", with: @health_record.name fill_in "Recorded by", with: @health_record.recorded_by click_on "Update Health record" assert_text "Health record was successfully updated" click_on "Back" end test "destroying a Health record" do visit health_records_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Health record was successfully destroyed" end end
require 'test_helper' feature 'Viewing A Book Feature Test' do before do @user = FactoryGirl.create :user, password: 'password' @other_user = FactoryGirl.create :other_user, password: 'password' @shelf = FactoryGirl.create :book_shelf, user: @user @book = FactoryGirl.create :book @shelf.books << @book end scenario 'Attempting to view a book on a shelf you own' do signin @user, 'password' visit shelf_book_path(@shelf, @book) page.must_have_content @book.name page.must_have_content @book.isbn end scenario "404 when Attempting to view a book on another user's shelf" do signin @other_user, 'password' visit shelf_book_path(@shelf, @book) page.status_code.must_equal 404 page.wont_have_content @book.name page.wont_have_content @book.isbn end scenario "404 when Attempting to view a book that isn't on the shelf" do book2 = Book.create(name: 'The Joy of Cooking', isbn: '9780451195159') signin @user, 'password' visit shelf_book_path(@shelf, book2) page.status_code.must_equal 404 page.wont_have_content book2.name page.wont_have_content book2.isbn end end
require 'thread' require 'net/http' # Date : 28th July 2014 # Author : Prasad Velidi # # MultiGet provides a multi-threaded download manager. # # The threads are created dynamically as the urls are added and they will # be destroyed dynamically as soon as the download queue is exhausted. Any # newly added urls will spawn new threads and so on. # # MultiGet doesn't block the calling program when a new url is being submitted. # It returns to the caller after enrolling it as a job. However, it provides a # callback mechanism meaning which you can submit a block to the add() method # and the thread executing the job yields to the block passed with job details. # # Since the MultiGet doesn't block the calling program, the calling program # should stay alive until all the items on the queue were downloaded. This can # be done by calling the #join() method in the main thread. Since this method # tries to join all threads spawned so far, the main thread will stay alive until # all the threads are done and destroyed. class MultiGet # Initialize the MultiGet object allowing 10 threads as maximum by default. # params:: # * *maxthreads* -> limit maximum threads that can be spawned by MultiGet # returns:: nothing # # require 'multi_get' # # To make MultiGet work with 15 threads .. # downloader = MultiGet.new(15) # => ... def initialize(maxthreads = 10) # @index is an index into download @queue, accessed and maintained by threads. @index = 0 # @queue is an array of hashes with each hash representing the job information. @queue = [] # @threads is an array of thread objects already created and is used by join(). @threads = [] @semaphore = Mutex.new @maxthreads = maxthreads end # Download the url off the internet and hand over the response object to caller. # params:: # * *url* -> points to the http link that needs to be downloaded # returns:: *response* -> return response object of type Net::HTTPFound class # # => ... # # To download a url without getting the threads created .. # response = downloader.get("http://google.com/") # puts response.inspect def get(url) uri = URI(url) begin response = Net::HTTP.get_response(uri) rescue SocketError => err response = nil end case response when Net::HTTPInformation then when Net::HTTPSuccess then when Net::HTTPRedirection then while response.is_a?(Net::HTTPRedirection) && !response.is_a?(Net::HTTPSuccess) uri = URI(response['location']) response = Net::HTTP.get_response(uri) end when Net::HTTPClientError then when Net::HTTPServerError then else # HTTPUnknownResponse end response end # Submits the url as a job to the queue and registers given block as callback. # params:: # * *url* -> points to the http link that needs to be downloaded # returns:: true # # => ... # # When this job is executed by a thread, the response object is yielded back to block # downloader.add("http://google.com/") { |job| # puts job.inspect # } # => ... def add(url, &callback) # :yields: job job = Hash.new job[:id] = @queue.length job[:url] = url job[:callback] = callback job[:content] = nil job[:size] = nil job[:start_time] = nil job[:end_time] = nil job[:speed] = nil job[:code] = nil job[:message] = nil job[:response] = nil @queue.push(job) @threads.push(replicate) if @threads.length < @maxthreads true end # Returns the number of jobs pushed to download queue so far. # returns:: number of jobs currently present on download queue # # => ... # # Since queue is not exposed publicly, length helps you iterate over the queue # (0..downloader.length - 1).each { |index| # downloader[index].inspect # } def length @queue.length end # Joins all the download threads so that the calling thread waits until all # the download threads are done and destroyed # returns:: true # # => ... # (0...10).each { # downloader.add("http://google.com/") { |job| # puts job.inspect # } # } # # Since we got nothing to do, join the threads created by downloader to keep alive. # downloader.join def join @threads.each { |thread| thread.join } end # Returns the job hash at index from queue to caller. # params:: # * *index* -> index of job in the download queue # returns:: job object of type Hash # # => ... # (0..downloader.length - 1).each { |index| # # if you need to access the job data later, use overridden subscript operator []. # downloader[index].inspect # } # => ... def [](index) @queue[index] end private # Create a thread object for handling downloads and return add() i.e its caller. # returns:: thread object of type Thread # # => ... # # replicate creates a new thread and returns the thread object back to caller. # @threads.push(replicate) if @threads.length < @maxthreads # => ... def replicate Thread.new { # Each thread loops continuously to either pick up a job a) when it started fresh or # b) when its done with previous job OR to kill itself when jobs are not available while true job = nil @semaphore.synchronize { if @index < @queue.length job = @queue[@index] @index += 1 end } if job.nil? @semaphore.synchronize { 0.upto(@threads.length - 1) { |index| if Thread.current.__id__ == @threads[index].__id__ @threads.delete_at(index) end } Thread.exit } else t1 = Time.now response = get(job[:url]) t2 = Time.now unless response.nil? job[:content] = response.body job[:size] = response.body.length job[:start_time] = t1 job[:end_time] = t2 job[:speed] = response.body.length / (1024 * (t2 - t1).ceil) job[:code] = response.code job[:message] = response.message job[:response] = response unless job[:callback].nil? job[:callback].yield job STDOUT.flush end end end end } end end
require './lib/types' class InvoiceCreatedValue < Dry::Struct attribute :kind, Types::Symbol attribute :party_url, Types::String attribute :amount, Types::Float attribute :invoice_date, Types::Json::Time attribute :first_bill, Types::Bool attribute :total_kwh, Types::String end
#! /usr/bin/ruby # -*-encoding: utf-8 -*- require "rubygems" require "crack" tweet_basename = "domeniq-tweets-page-" first_page = 1 last_page = 6 total_tweet_count = 0 total_chars_in_tweets = 0 word_list = {} (first_page..last_page).each do |pg_num| tweet_filename = tweet_basename + pg_num.to_s + ".xml" tweets_file = File.open(tweet_filename) parsed_xml = Crack::XML.parse( tweets_file.read ) tweets = parsed_xml["statuses"] puts "On page: " + pg_num.to_s # A running total of tweets total_tweet_count += tweets.length tweets.each do |tweet| # The tweet text, in lowercase letters txt = tweet['text'].downcase # A running total of total tweet length in characters total_chars_in_tweets += txt.length # Regular expression to select any string of consecutive # alphabetical letters (with optional apostrophes and hypens) # that are surrounded by whitespace or end with a punctuation mark words = txt.scan(/(?:^|\s)([a-z'\-]+)(?:$|\s|[.!,?:])/).flatten.select{|w| w.length > 1} # Use of the word_list Hash to keep list of different words words.each do |word| word_list[word] ||= 0 word_list[word] += 1 end end end puts "\nTotal tweets:" puts total_tweet_count puts "\nTotal characters used:" puts total_chars_in_tweets puts "\nAverage tweet length in chars:" puts(total_chars_in_tweets/total_tweet_count) puts "\nNumber of different words:" puts word_list.length puts "\nNumber of total words used:" puts word_list.inject(0){|sum, w| sum += w[1]} # sort word_list by frequency of word, descending order word_list = word_list.sort_by{|w| w[1]}.reverse puts "\nTop 20 most frequent words" word_list[0..19].each do |w| puts "#{w[0]}:\t#{w[1]}" end puts "\nTop 20 most frequent words more than 4 characters long" word_list.select{|w| w[0].length > 4}[0..19].each do |w| puts "#{w[0]}:\t#{w[1]}" end puts "\nLongest word:" puts word_list.max_by{|w| w[0].length}[0]
class ChangeIntegerForNiveau < ActiveRecord::Migration[5.1] def change change_table :courses do |t| t.change :niveau, :string end end end
require 'colored' require_relative './methods.rb' require_relative './environment.rb' puts "" puts "Hello! Welcome to Event Finder!" def main_menu puts "" puts "What would you like to do?".bold puts "" puts "1 - See what events are happening on a certain date." puts "2 - See all upcoming small events." puts "3 - See all upcoming large events." puts "4 - See all upcoming events of tiny artists." puts "5 - See all upcoming events at a particular venue." puts "6 - Get more information about a particular venue." puts "7 - See all shows that fit your budget." puts "8 - See upcoming shows for a specific artist." puts "9 - See what events are trending." puts "10 - Exit the app." date_entered = gets.chomp case date_entered when "1" event_on_date when "2" show_small_events when "3" show_large_events when "4" show_events_tiny_artists when "5" playing_in_genre when "6" venue_details when "7" shows_under_budget when "8" shows_by_artist when "9" trending_events when "10" puts "Have a great day!" exit else puts "We're sorry, you entered an invalid input.".red main_menu end end def try_again(method_id) puts "" puts "Would you like to:" puts "1 - Try another search." puts "2 - Return to the main menu." puts "3 - Exit the app." response = gets.chomp if response == "1" case method_id when 1 event_on_date when 2 playing_in_genre when 3 venue_details when 4 shows_under_budget when 5 shows_by_artist end elsif response == "2" main_menu elsif response == "3" puts "Have a great day!" exit else puts "Invalid input" try_again(method_id) end end def event_on_date puts "What date are you interested in? (Please follow the format of 1st Jan 2019)." date = gets.chomp who_is_playing(date) try_again(1) end def show_small_events small_events puts "" puts "Returning to main menu..." puts "" main_menu end def show_large_events large_events puts "" puts "Returning to main menu..." puts "" main_menu end def show_events_tiny_artists tiny_attractions puts "" puts "Returning to main menu..." puts "" main_menu end def list_venues puts "" puts "Please select a venue from the following list:" puts "" puts "1 - Red Rocks Amphitheatre" puts "2 - Fillmore Auditorium (Denver)" puts "3 - Cervantes" puts "4 - Ogden Theatre" puts "5 - Summit" puts "6 - Marquis Theatre" puts "" end def playing_in_genre list_venues selection = gets.chomp case selection when '1' playing_near_me("Red Rocks Amphitheatre") when '2' playing_near_me("Fillmore Auditorium (Denver)") when '3' playing_near_me("Cervantes") when '4' playing_near_me("Ogden Theatre") when '5' playing_near_me("Summit") when '6' playing_near_me("Marquis Theatre") else puts "Sorry, you've made an invalid selection.".red puts "" playing_in_genre end try_again(2) end def venue_details puts "Which venue would you like to learn more about?" list_venues selection = gets.chomp case selection when '1' print_venue_details("Red Rocks Amphitheatre") when '2' print_venue_details("Fillmore Auditorium (Denver)") when '3' print_venue_details("Cervantes") when '4' print_venue_details("Ogden Theatre") when '5' print_venue_details("Summit") when '6' print_venue_details("Marquis Theatre") else puts "Sorry, you've made an invalid selection.".red puts "" venue_details end puts "" try_again(3) end def shows_under_budget puts "" puts "What is your budget?" budget = gets.chomp.to_i shows_by_budget(budget) try_again(4) end def shows_by_artist puts "" puts "Please enter the artist's name." artist_name = gets.chomp shows_by_attraction(artist_name) try_again(5) end def trending_events puts "The following three events are trending now!" trending_event main_menu end main_menu
#!/run/nodectl/nodectl script # Set memlock prlimit to unlimited require 'nodectld/standalone' include OsCtl::Lib::Utils::Log include NodeCtld::Utils::System include NodeCtld::Utils::OsCtl db = NodeCtld::Db.new db.prepared(" SELECT v.id FROM vpses v WHERE v.object_state < 2 AND v.node_id = ? ", $CFG.get(:vpsadmin, :node_id)).each do |row| puts "VPS #{row['id']}" #next begin osctl( %i(ct prlimits set), [row['id'], 'memlock', '65536', '9223372036854775807'] ) rescue OsCtl::Lib::Exceptions::SystemCommandFailed puts " -> failed, continue" end end
class CreateAssociations < ActiveRecord::Migration def change create_table :associations do |t| t.integer :from_id t.integer :to_id t.boolean :from_crow t.boolean :to_crow t.integer :from_x t.integer :from_y t.integer :from_dx t.integer :from_dy t.integer :to_x t.integer :to_y t.integer :to_dx t.integer :to_dy t.string :color t.references :database, index: true, foreign_key: true t.timestamps null: false end end end
#!/usr/bin/env ruby # # Read bib file and create link output for # <A HREF="{citeation_key}.pdf"> # $:.unshift(File.dirname(__FILE__)) require 'bib_library.rb' require 'papers_library.rb' require 'getoptlong' require 'kconv' require 'date' require 'ap' $stdout.set_encoding("UTF-8") # # main # if __FILE__ == $0 require 'optparse' opts = { # default options :mode => "plain", :draft => false, :encoding => "UTF-8", :output_encoding => "UTF-8", :key_file => "", # if it's null string, try to generate file by basename :bib_dir => "./bib", :force => false, :timestamp => true, :write => false, :list => false, :mismatch_dump => false } ARGV.options do |o| o.banner = "ruby #{$0} [options] BIB_File {cite_keys..}" o.separator "Options:" o.parse! end if ARGV.size >= 1 blib = BibLibrary.new(ARGV.shift, opts) cite_keys = blib.keys.sort if ARGV.size > 0 cite_keys = ARGV end cite_keys.each do |ck| bib = blib[ck] bib.prep au = bib.authors || [ ] f = "#{ck}.pdf" f.gsub!(/:/, '_') puts "<tr>" puts "<td><A HREF=\"#{f}\">#{ck}</td>" puts "<td>#{bib.title}</td>" puts "<td>#{au.join(', ')}</td>" puts "</tr>" end end end
require 'em-http/middleware/oauth' # An API for interfacing with XING # using event machine for async calls class XingAPI def initialize( credentials, identity, current_user=nil) @credentials = credentials @context_name = identity.context.name @current_user = current_user @token = credentials[:token] @secret = credentials[:secret] @identity = identity @total_contacts = identity.properties[:total_contacts].to_i @xing_id = identity.uid @xing_batch_size = 99 @xing_url = "https://api.xing.com/v1/" @oauth_config = { :consumer_key => Rails.configuration.api_keys['xing']['key'], :consumer_secret => Rails.configuration.api_keys['xing']['secret'], :access_token => @token, :access_token_secret => @secret } end def get_connections @connections_buffer = [] @countdown = ConnectionHandler.countdown( @total_contacts/@xing_batch_size + 1 ); EventMachine.run do (0..@total_contacts).to_a.each_slice(@xing_batch_size).each{|range| dispatch_connections(range.first) } end connection_data = {:context => ContactContext, :connections=> @connections_buffer} if (Rails.env != "production") Rails.logger.debug "DEBUG dumping json outputs to tmp/folder" File.open( "tmp/xing_contacts.json","w"){|f| f.write(connection_data.to_json) } end Rails.logger.info "INFO Writing XING Contacts" ConnectionHandler.build_user_user_connections( connection_data , @identity ) end def dispatch_connections( offset = 0 , tries = 0 ) request = EventMachine::HttpRequest.new(@xing_url+ "users/me/contacts?"+parameters(offset)) request.use EventMachine::Middleware::OAuth, @oauth_config http = request.get http.callback do if http.response_header.status != 200 and http.response_header.status != 302 Rails.logger.fatal "Xing Connection failed with Error Code #{http.response_header.status}" Rails.logger.ap http raise "Unexpected response status #{http}" end begin contacts = MultiJson.decode(http.response)["contacts"]["users"] connection_info = contacts.map{|data| data.deep_symbolize_keys }.keep_if{ |connection| connection.has_key?(:photo_urls)}.map{ |connection| { :identity => { :uid => connection[:id], :context_name => :xing, :credentials => {}, :name => connection[:display_name], :image => connection[:photo_urls][:large], :url => connection[:permalink], :properties => get_headline(connection) }, :email => connection.has_key?(:active_email)?connection[:active_email]:nil, :connection => { :from => "me", :to => "you", :properties => {} } } } @connections_buffer.concat( connection_info ) Rails.logger.info "Xing Connectino Dispatch Successful Countdown: #{@countdown.count}" rescue Exception => ex Rails.logger.fatal "FATAL : Xing Parse Error #{ex.message}" Rails.logger.fatal "FATAL : Xing Parse Error Backtrace ... " ex.backtrace[0..10].each{|trace| Rails.logger.fatal trace} Rails.logger.fatal "XING Connection Dispath Bad Responnse #{@countdawn.count}" Rails.logger.ap http.response ensure stop_if_finished end end http.errback do if tries <= 3 Rails.logger.warn "Xing Fetch Connection Request #{@countdown.count} Errored, Trying Again" dispatch_connections( offset ,tries+1) else Rails.logger.fatal "Xing Fetch Connection Request #{@countdown.count} Failed, Giving up" stop_if_finished end end end def get_headline( connection ) if connection.has_key?(:professional_experience) if connection[:professional_experience].has_key?(:primary_company) title = connection[:professional_experience][:primary_company][:title] name = connection[:professional_experience][:primary_company][:name] if title and name return {"Headline" => "#{title} at #{name}"} end end end return {} end def parameters( offset ) "offset=#{offset}&limit=#{@xing_batch_size}&user_fields=id,display_name,photo_urls.large,professional_experience.primary_company.name,professional_experience.primary_company.title,permalink,active_email" end def stop_if_finished EM.stop if @countdown.minus_one == 0 end ContactContext = { :name => 'xing-connection' } end
namespace :tenfoot do desc "Populate database with data from videos, APIs and feeds." task :populate => :environment do Media.populate YouTubeVideo.populate Tweet.populate end desc "Generate an example apache config appropriate for your settings." task :apacheconf => :environment do passenger_path = `bundle show passenger`.chomp ruby_path = `rbenv which ruby`.chomp puts <<-END.strip_heredoc Listen 8080 LoadModule passenger_module #{passenger_path}/ext/apache2/mod_passenger.so PassengerRoot #{passenger_path} PassengerRuby #{ruby_path} <VirtualHost *:8080> DocumentRoot #{Rails.public_path} ErrorLog ${APACHE_LOG_DIR}/ten-foot.error.log CustomLog ${APACHE_LOG_DIR}/ten-foot.access.log combined RailsEnv #{Rails.env} <Directory #{Rails.root}> Options -Indexes -MultiViews FollowSymlinks AllowOverride All </Directory> Alias /videos #{$settings.video_files_path} <Directory #{$settings.video_files_path}> PassengerEnabled off Options Indexes MultiViews FollowSymLinks AllowOverride None </Directory> </VirtualHost> END end end
Rails.application.routes.draw do resources :addresses get 'zipcode/:zipcode' => 'addresses#zipcode' root to: 'addresses#index' end
require 'spec_helper' describe RecordingEventsController do let(:user) { create_user } let(:valid_attributes) { { "user_id" => user.id, 'channel_id' => 2, 'start_time' => Time.now, 'end_time' => (Time.now + 1.hour), 'priority' => 2, 'recurring' => 2 } } let(:valid_session) { {} } describe "GET index" do it "assigns all recording_events as @recording_events" do recording_event = RecordingEvent.create! valid_attributes get :index, {}, valid_session assigns(:recording_events).should eq([recording_event]) end end describe "GET show" do it "assigns the requested recording_event as @recording_event" do recording_event = RecordingEvent.create! valid_attributes get :show, {:id => recording_event.to_param}, valid_session assigns(:recording_event).should eq(recording_event) end end describe "GET new" do it "assigns a new recording_event as @recording_event" do get :new, {}, valid_session assigns(:recording_event).should be_a_new(RecordingEvent) end end describe "GET edit" do it "assigns the requested recording_event as @recording_event" do recording_event = RecordingEvent.create! valid_attributes get :edit, {:id => recording_event.to_param}, valid_session assigns(:recording_event).should eq(recording_event) end end describe "POST create" do describe "with valid params" do it "creates a new RecordingEvent" do expect { post :create, {:recording_event => valid_attributes}, valid_session }.to change(RecordingEvent, :count).by(1) end it "assigns a newly created recording_event as @recording_event" do post :create, {:recording_event => valid_attributes}, valid_session assigns(:recording_event).should be_a(RecordingEvent) assigns(:recording_event).should be_persisted end it "redirects to the created recording_event" do post :create, {:recording_event => valid_attributes}, valid_session response.should redirect_to(RecordingEvent.last) end end describe "with invalid params" do it "assigns a newly created but unsaved recording_event as @recording_event" do # Trigger the behavior that occurs when invalid params are submitted RecordingEvent.any_instance.stub(:save).and_return(false) post :create, {:recording_event => { "user_id" => "invalid value" }}, valid_session assigns(:recording_event).should be_a_new(RecordingEvent) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted RecordingEvent.any_instance.stub(:save).and_return(false) post :create, {:recording_event => { "user_id" => "invalid value" }}, valid_session response.should render_template("new") end end end describe "PUT update" do describe "with valid params" do it "updates the requested recording_event" do recording_event = RecordingEvent.create! valid_attributes # Assuming there are no other recording_events in the database, this # specifies that the RecordingEvent created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. RecordingEvent.any_instance.should_receive(:update_attributes).with({ "user_id" => user.id.to_s }) put :update, {:id => recording_event.to_param, :recording_event => { "user_id" => user.id.to_s }}, valid_session end it "assigns the requested recording_event as @recording_event" do recording_event = RecordingEvent.create! valid_attributes put :update, {:id => recording_event.to_param, :recording_event => valid_attributes}, valid_session assigns(:recording_event).should eq(recording_event) end it "redirects to the recording_event" do recording_event = RecordingEvent.create! valid_attributes put :update, {:id => recording_event.to_param, :recording_event => valid_attributes}, valid_session response.should redirect_to(recording_event) end end describe "with invalid params" do it "assigns the recording_event as @recording_event" do recording_event = RecordingEvent.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted RecordingEvent.any_instance.stub(:save).and_return(false) put :update, {:id => recording_event.to_param, :recording_event => { "user_id" => "invalid value" }}, valid_session assigns(:recording_event).should eq(recording_event) end it "re-renders the 'edit' template" do recording_event = RecordingEvent.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted RecordingEvent.any_instance.stub(:save).and_return(false) put :update, {:id => recording_event.to_param, :recording_event => { "user_id" => "invalid value" }}, valid_session response.should render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested recording_event" do recording_event = RecordingEvent.create! valid_attributes expect { delete :destroy, {:id => recording_event.to_param}, valid_session }.to change(RecordingEvent, :count).by(-1) end it "redirects to the recording_events list" do recording_event = RecordingEvent.create! valid_attributes delete :destroy, {:id => recording_event.to_param}, valid_session response.should redirect_to(recording_events_url) end end end
module Api module V1 class MetricsController < ApplicationController def initialize @logs = LogService.new end def logs_per_hour context = params[:context] logs = @logs.get_by_context(context) average = logs.length / 24.0 # adequando a 1 casa decimal average = average * 10 average = average.ceil average = average / 10.0 Response.new('SUCCESS', 'Media calculada', average) render json: Response.new('SUCCESS', 'Media calculada', average), status: :ok end def hour_with_most_logs # usando um passo do count sort para calcular a frequencia porque sim context = params[:context] logs = @logs.get_by_context(context) frequency = day_frequency(logs) hour_with_most_logs = get_most_frequency(frequency) render json: Response.new('SUCCESS', 'Hora com maior numero de logs calculada', hour_with_most_logs), status: :ok end def hour_with_least_logs # mesma coisa que o outro só muda a condicao. template method? context = params[:context] logs = @logs.get_by_context(context) frequency = day_frequency(logs) hour_with_least_logs = get_least_frequency(frequency) render json: Response.new('SUCCESS', 'Hora com menor numero de logs calculada', hour_with_least_logs), status: :ok end def logs_today context = params[:context] logs = @logs.get_by_context(context) today = Time.now.strftime("%Y-%m-%d") logs_today = [] for log in logs if log.day.strftime == today logs_today.push(log) end end render json: Response.new('SUCCESS', 'Logs de hoje carregados', logs_today), status: :ok end def logs_in_hour hour = params[:hour] logs_in_hour = @logs.get_by_hour(hour) render json: Response.new('SUCCESS', 'Logs na hora ' + hour + ' carregados', logs_in_hour), status: :ok end private def day_frequency(logs) count = [0] * 24 for log in logs count[log.hour] += 1 end return count end def get_least_frequency(list) least = 0 for i in [*0..list.length-1] if list[i] < list[least] least = i end end return least end def get_most_frequency(list) most = 0 for i in [*0..list.length-1] if list[i] > list[most] most = i end end return most end end end end
module Entities class JoinFail < Grape::Entity expose :email, documentation: {type: "string", desc:"실패 이유", optional: true,is_array:true} expose :name, documentation: {type: "string", desc:"실패 이유", optional: true,is_array:true} expose :age, documentation: {type: "string", desc:"실패 이유", optional: true,is_array:true} expose :gender, documentation: {type: "string", desc:"실패 이유", optional: true,is_array:true} expose :password, documentation: {type: "string", desc:"실패 이유", optional: true,is_array:true} end end
class Collection < ApplicationRecord has_many :tasks has_many :favorites belongs_to :user end
class CreateUserConfigurations < ActiveRecord::Migration def change create_table :user_configurations do |t| t.integer :user_id t.string :booking_date_field_name, default: 'booking_date' t.string :zip_code_field_name, default: 'zip_code' t.string :city_field_name, default: 'city' t.string :state_field_name, default: 'state' t.string :charge_field_prefix, default: 'charge_' t.integer :num_charges, default: 5 t.timestamps end add_index :user_configurations, :user_id, unique: true end end
# frozen_string_literal: true # Run user's text interface require_relative 'users' require_relative 'card' require_relative 'deck' require_relative 'hand' require_relative 'game' class Interface def initialize puts 'Добро пожаловать в игру Black Jack!' @game = Game.new end def welcome print 'Введите ваше имя: ' name = gets.chomp @game.create_players(name) end def start_game @game.first_step puts "\nВам раздали карты: #{@game.user.hand.cards.map(&:face)}" puts "У вас: #{@game.user.hand.count_cards}" puts 'У дилера на руках 2 карты: [***] [***]' main_menu end def main_menu puts "\nВаш ход: 1 - Пропустить ход; 2 - Взять карту; 3 - Открыть карты;" choice = gets.chomp case choice when '1' @game.dealers_step ? stand_user : stand_dealer when '2' @game.valid_cards_user ? hit_max_cards : hit when '3' open end end def stand_user puts "\nДилер взял карту, у него 3 карты: [*] [*] [*]" open end def stand_dealer puts "\nДилер пропустил ход..." main_menu end def hit_max_cards puts "\nУ вас максимальное количество карт!" main_menu end def hit @game.one_card puts "\nВы взяли карту, у вас на руках: #{@game.user.hand.cards.map(&:face)}" puts "У вас #{@game.user.hand.count_cards} очков" @game.dealers_step ? stand_user : stand_dealer end def open @game.end_game puts "\nУ #{@game.user.name} на руках: #{@game.user.hand.cards.map(&:face)}" puts "Очков: #{@game.user.hand.score}" puts "\nУ Дилера на руках: #{@game.dealer.hand.cards.map(&:face)}" puts "Очков: #{@game.dealer.hand.score}" great_message end def great_message case @game.win when @game.dealer puts "\nПобедил Дилер, у него: #{@game.dealer.balance}$" when @game.user puts "\nВы победили, у вас: #{@game.user.balance}$" when 'draw' puts "\nНичья, все остались при своих деньгах." puts "У #{@game.user.name} - #{@game.user.balance}$" puts "У #{@game.dealer.name} - #{@game.dealer.balance}$" when 'busts' puts "\nВы оба обанкротились!!!" end again end def again @game.post_game puts "\n---------- 1: Сыграть еще раз? 2: Выйти ------------" choice = gets.chomp choice == '1' ? start_game : exit end end interface = Interface.new interface.welcome interface.start_game
require 'FileUtils' include FileUtils if ARGV.any? project_name = ARGV[0] else print "プロジェクト名を入力してください -> " project_name = gets.chomp end if Dir.exist? project_name print "フォルダが既に存在します" exit(1) else mkdir(project_name) end cd(project_name) File.write "Rakefile", <<-EOS require \"rake/clean\" PROGRAM = \"#{project_name}\" SRC = \"\#{PROGRAM}.rb\" directory BIN_DIR = \"\#{Dir.home}/bin/\" CLEAN.include(PROGRAM) task default: [\"clean\", PROGRAM] desc \"$HOME/binに追加\" task deploy: [\"clean\", PROGRAM, BIN_DIR] do |t| sh \"cp -f \#{PROGRAM} \#{BIN_DIR}\" sh \"source ~/.zshrc\" end desc \"実行ファイル生成\" file PROGRAM => [SRC] do |t| path = \"#! \#{%x{which ruby}}\" sh \"cp -f \#{t.prerequisites[0]} \#{t.name}\" open(t.name, \"r+\"){ |f| f.puts \"\#{path}\\n\#{open(t.name).read}\" } sh \"chmod 755 \#{t.name}\" end EOS File.write "readme.md", "# #{project_name}\n" File.write "#{project_name}.rb", "p 'Hello world!!'\n" File.write ".gitignore", "#{project_name}\n"
# Givens Given(/^User is on login page with account$/) do create :user visit '/users/sign_in' end Given(/^User is on login page with no account$/) do visit '/users/sign_in' end # Whens When(/^User inputs correct credentials$/) do fill_in 'user_email', with: 'freyes@enova.com' fill_in 'user_password', with: 'password' click_button 'Log in' end When(/^User inputs incorrect password$/) do fill_in 'user_email', with: 'freyes@enova.com' fill_in 'user_password', with: 'wrongpassword' click_button 'Log in' end When(/^User inputs incorrect email$/) do fill_in 'user_email', with: 'notright@enova.com' fill_in 'user_password', with: 'password' click_button 'Log in' end # Thens Then(/^User should be logged in$/) do expect(page).to have_content('Franco Reyes') end Then(/^User should be notified of invalid login$/) do expect(page).to have_content('Invalid email or password.') end Then(/^User should be notified of non-existant account$/) do expect(page).to have_content('Invalid email address or password.') end
FactoryGirl.define do sequence :name do |n| "Name-#{n}" end sequence :email do |n| "email-#{n}@email.com" end factory :artist do name similar " " photo " " user end factory :user do name email password "foobar" password_confirmation "foobar" end factory :concert do concert_date "23/08/1988.to_date" concert_time "7:00" performing_artists "Cher, Radiohead" venue "Tabernacle" website "www.lastfm.com" user end end
# -*- encoding : utf-8 -*- class CreateAdministrators < ActiveRecord::Migration def change create_table :administrators do |t| t.string :account, limit: 32, null: false t.string :hashed_password, limit: 100, null: false t.string :name, limit: 100, null: false t.boolean :available, null: false t.string :token, limit: 22, null: false t.datetime :last_signined_at, :current_signined_at t.boolean :trashed, default: false, null: false t.timestamps null: false end end end
class Message < ActiveRecord::Base attr_accessible :from, :html, :plain, :subject belongs_to :ticket validates :from, presence: true validates :subject, presence: true validates :plain, presence: true before_create :create_ticket after_create :notify_employee def to_s subject end def code ticket.code end private def create_ticket self.ticket = Ticket.create! end def notify_employee TicketMailer.notify_employee(self, User.random).deliver end end
module ApplicationHelper # convert hash to optarg tree def opt_hash(h, selected) h.collect do |k, v| if v.is_a? Hash content_tag :optgroup, :label => t(k) do opt_hash(v, selected) end else s = v == selected if selected content_tag :option, :value => v, :selected => s do t v end end end.reduce(:concat) end def hash_links_tree(h, lmargin) h.collect do |k, v| if v.is_a? Hash r = content_tag :div do t(k) end r << content_tag(:div, :style => "padding-left: #{lmargin}") do hash_links_tree v, lmargin end r else content_tag :div do link_to teas_path("tea[category]" => v) do t v end end end end.reduce(:concat) end end
require 'rails_helper' describe UsersController do include Devise::TestHelpers let(:non_admin_user) { create(:user) } let(:admin_user) { create(:admin) } let(:other_user) { create(:user) } let(:public_item) { create(:item, user: user, public: true) } let(:private_item) { create(:item, user: user, public: false) } describe 'GET show' do let(:request) { get :show, {id: user.id} } context 'while logged in' do before { @request.env["devise.mapping"] = Devise.mappings[:user] } before { sign_in(current_user) } before { request } context 'as a non-admin' do let(:current_user) { non_admin_user } context 'viewing their own profile' do let(:user) { current_user } it "assigns all the user's items to @items" do expect(assigns(:items)).to include(public_item, private_item) end end context "viewing somebody else's profile" do let(:user) { other_user } it "assigns all the user's public items ot @item" do expect(assigns(:items)).to include(public_item) end it "doesn't assign any of the user's private items" do expect(assigns(:items)).to_not include(private_item) end end end context 'as an admin' do let(:current_user) { admin_user } context "viewing somebody else's profile" do let(:user) { other_user } it "assigns all the user's items to @items" do expect(assigns(:items)).to include(public_item, private_item) end end end end end end # describe 'GET show' do # context 'as a logged in user' do # context 'viewing their own profile' do # before { sign_in(@user2) } # before { get :show, { id: @user2.id} } # it 'returns success' do # expect(response).to be_success # end # it "assigns all the user's items to @items" do # expect(assigns(:items)).to eq(@user2.items) # end # it "renders the show view" do # expect(response).to render_template(:show) # end # end # context "viewing somebody else's profile" do # before{ sign_in(@user) } # before{ get :show, { id: @user2.id} } # it 'returns success' do # expect(response).to be_success # end # it "assigns only the user's public items to @items" do # expect(assigns(:items)).to include(@user2.items.where(public: true)) # expect(assigns(:items)).to_not include(@user2.items.were(public: false)) # end # it "render the index view" do # expect(response).to render_template(:show) # end # end # context "admin viewing profile" do # before{ sign_in(@admin) } # before{ get :show, {id: @user2.id} } # it 'returns success' do # expect(response).to be_success # end # it "assigns all the user's items to @items" do # expect(assigns(:items)).to eq(@user2.items) # end # it "render the index view" do # expect(response).to render_template(:show) # end # end # end # end # end
class SubmissionComment < ActiveRecord::Base belongs_to :submission belongs_to :author, :class_name => 'User' end
# frozen_string_literal: true module LoginHelper def login_as(user) visit "/login" fill_in "メールアドレス", with: user.email fill_in "パスワード", with: user.password click_button "ログイン" end end RSpec.configure do |config| config.include LoginHelper end
class DeliveryDetail < ApplicationRecord self.abstract_class = true has_one :communication, as: :detailable def successful? raise NotImplementedError end def unsuccessful? raise NotImplementedError end def in_progress? raise NotImplementedError end # This should create the delivery detail, create an # associated communication and return the communication object. def self.create_with_communication! raise NotImplementedError end end
class AppSerializer < ActiveModel::Serializer attributes :id, :name, :package_name has_many :app_items end
class User < ActiveRecord::Base has_many :listings has_many :orders, foreign_key: "renter_id" def name "#{first_name} #{last_name}" end end
class CompaniesController < ApplicationController def index @companies = Company.all end def show @company = Company.find(params[:id]) @contacts = Contact.where(company_id: params[:id]) end def create @company = Company.new(company_params) if @company.save flash[:notice] = "Company '#{@company.name}' created Successfully" redirect_to(:controller => 'home', :action => 'index') else render('new') end end def edit @company = Company.find(params[:id]) end def new @company = Company.new end def update @company = Company.find(params[:id]) if @company.update_attributes(company_params) flash[:notice] = "Company '#{@company.name}' has been updated" redirect_to(:action => 'show', :id => @company.id) else render('edit') end end def destroy @company = Company.find(params[:id]).destroy flash[:notice] = "Company '#{@company.name}' has been deleted" redirect_to(:controller => 'home', :action => 'index') end private def company_params params.require(:company).permit(:name, :image) end end
FactoryGirl.define do factory :artist_city do artist nil city nil is_primary { Faker::Boolean.boolean } sequence(:sequence) end end
# 08.03.16, Wednesday. 11:14pm def search_array(integer_array, item) # search the array for the item. # if array includes item, return the item's index. Do not use 'index' method # .length and .each are permitted if integer_array.include?(item) == false return nil end i = -1 integer_array.each do |num| i += 1 if num == item return i end end end # Release 1, version2: fibonacci series, with recursion def fib1(number) if number < 2 puts "Please try again with a number greater than 2" else rec_fib(number, [0,1]) end end def rec_fib(number, fib_arr) until fib_arr.length == number fib_arr.push(fib_arr.last + fib_arr[fib_arr.length - 2]) rec_fib(number, fib_arr) end fib_arr end # Release 1, version1: fibonacci series def fib(number) fib_arr = [0, 1] until fib_arr.length == number if number < 2 puts "Please try again with a number greater than 2" else fib_arr.push(fib_arr.last + fib_arr[fib_arr.length - 2]) end end fib_arr end # Release 2: bubble sort method def sort(array) rec_sort(array,[]) end def rec_sort(array, sorted) if array.length <= 0 return sorted end unsorted = [] smallest = array.pop array.each do |item| if item < smallest unsorted << smallest smallest = item else unsorted << item end end sorted << smallest rec_sort(unsorted, sorted) end # returns an array of fibonacci terms # Release 0: Implement a Simple Search # Write a method that takes an array of integers and an integer to search for. T # The method should return the index of the item, or nil if the integer is not present in the array. # Don't use built-in array methods like .index. You are allowed to use .length and .each. arr = [33, 45, 3, 12] p search_array(arr, 45) p search_array(arr, 1) # Release 1:Calculate Fibonacci Numbers fib(2) fib(7) fib(10) fib(100) # Release 1.1: Calculate Fibonacci Numbers, recursively #rec_fib(100) # Release 2: Sort an Array. Create a sort method. # => Write pseudo-code for a bubble-sort (also called 'sinking-sort')method # 1. Create a function that takes two lists as parameters: the 1st list is unsorted, the 2nd list is sorted # 2. Remove a single item from the end of the unsorted list. Name this variable 'smallest'. # 3. Iterate through the list of items, comparing one item at a time to the item you just removed. # 4. If any item in the iteration is smaller than the 'smallest', # a.) Add 'smallest' to a list called unsorted # b.) update 'smallest' variable to equal the new smallest item. # 5. If any item in the iteration is larger than the 'smallest', add it to a list called 'unsorted' # 6. Once all of the items in the array are compared against the 'smallest' variable: # a.) add the updated 'smallest' variable to the 'sorted' list # 6. Now take the unsorted array and the new smallest item. Use these as parameters to repeat the code. # 7. Create wrapper code for the function just created above. Let the wrapper code take an array as a single parameter # 8. Inside this wrapper code, call the function created above. For the two parameters, list the array as the first parameter, and use # and empty array as the 2nd parameter puts(sort([2,16,4,9,1])) puts(fib1(6)) arr = [33, 45, 3, 12] p search_array(arr, 45) p search_array(arr, 1)
VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "centos/7" (1..3).each do |i| config.vm.define "docker#{i}-local" do |node| node.vm.hostname = "docker#{i}-local" node.vm.network :private_network, ip: "192.168.33.#{i+1}" node.vm.network "forwarded_port", guest: "8080", host: "808#{i}" node.vm.provider :virtualbox do |node| node.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] node.customize ["modifyvm", :id, "--memory", 512] end node.vm.provision "shell", inline: <<-SHELL sudo yum install -y yum-utils device-mapper-persistent-data lvm2 sudo yum -y install epel-release sudo yum -y install lsof sudo yum -y install net-tools.x86_64 sudo yum -y install telnet.x86_64 sudo yum -y install bind-utils sudo yum -y install nmap sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo yum -y install docker-ce python-pip sudo pip install docker sudo pip install docker-py sudo systemctl start docker sudo yum install -y vim lsof tcpdump bridge-utils wget cd /tmp && wget http://javadl.oracle.com/webapps/download/AutoDL?BundleId=225344_090f390dda5b47b9b721c7dfaa008135 && sudo rpm --force -Uvh 'AutoDL?BundleId=225344_090f390dda5b47b9b721c7dfaa008135' && echo 'export JAVA_HOME=/usr/java/latest' >> /home/vagrant/.bashrc && source /home/vagrant/.bashrc sudo pip install --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org requests urllib3 pyOpenSSL --force --upgrade SHELL end end end
class AddDepartmentRefToCohort < ActiveRecord::Migration[4.2] def change add_reference :cohorts, :department, index: true, foreign_key: true add_column :cohorts, :year, :integer remove_column :evaluation_sessions, :neterminal, :boolean remove_column :evaluation_sessions, :start_date_terminal, :date remove_column :evaluation_sessions, :end_date_terminal, :date end end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Setpassword class SetpasswordCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data room = $manager.get_object(@player.container) player = @player if event[:new_password] if event[:new_password] !~ /^\w{6,20}$/ player.output "Please only use letters and numbers. Password should be between 6 and 20 characters long." return else $manager.set_password(player, event[:new_password]) player.output "Your password has been changed." end else player.output "Please enter your current password:", true player.io.echo_off player.expect do |password| if $manager.check_password(player.name, password) player.output "Please enter your new password:", true player.io.echo_off player.expect do |password| player.io.echo_on event[:new_password] = password Settings.setpassword(event, player, room) end else player.output "Sorry, that password is invalid." player.io.echo_on end end end end end end end end end
require 'rails_helper' describe ApiNameGeneration do class ApiNameGenerationTest def self.validate(*) end include ApiNameGeneration attr_accessor :name, :api_name end let(:instance) { ApiNameGenerationTest.new } describe '#generate_api_name' do it 'underscores a name' do instance.name = 'Domestic Hot Water' instance.generate_api_name expect(instance.api_name).to eq('domestic_hot_water') end it 'strips outs non-alpha characters' do instance.name = '"I said, (parenthetically),\'...\'"' instance.generate_api_name expect(instance.api_name).to eq('i_said_parenthetically') end end end
# Copyright © Mapotempo, 2020 # # This file is part of Mapotempo. # # Mapotempo is free software. You can redistribute it and/or # modify since you respect the terms of the GNU Affero General # Public License as published by the Free Software Foundation, # either version 3 of the License, or (at your option) any later version. # # Mapotempo is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the Licenses for more details. # # You should have received a copy of the GNU Affero General Public License # along with Mapotempo. If not, see: # <http://www.gnu.org/licenses/agpl.html> # require 'active_support/concern' module OverloadableFunctions extend ActiveSupport::Concern def compatible_characteristics?(service_chars, vehicle_chars) # Compatile service and vehicle # if the vehicle cannot serve the service due to sticky_vehicle_id return false if !service_chars[:v_id].empty? && (service_chars[:v_id] & vehicle_chars[:id]).empty? # if the service needs a skill that the vehicle doesn't have return false if !(service_chars[:skills] - vehicle_chars[:skills]).empty? # if service and vehicle have no matching days return false if (service_chars[:day_skills] & vehicle_chars[:day_skills]).empty? true # if not, they are compatible end def compute_limits(cut_symbol, cut_ratio, vehicles, data_items) strict_limits = vehicles.collect{ |vehicle| s_l = { duration: vehicle[:duration] } # incase duration is not supplied inside the capacities vehicle[:capacities]&.each{ |unit, limit| s_l[unit] = limit } vehicle[:duration] = s_l[:duration] # incase duration is only supplied inside the capacities vehicle[:capacities] ||= { duration: s_l[:duration] } # incase capacities field were not suplied at all s_l } if cut_symbol total_quantity = Hash.new(0) @unit_symbols ||= nil (@unit_symbols || (cut_symbol && [cut_symbol]))&.each{ |unit| total_quantity[unit] = data_items.sum{ |item| item[3][unit].to_f } } total_capacity = vehicles.sum{ |vehicle| vehicle[:capacities][cut_symbol].to_f } metric_limits = vehicles.collect{ |vehicle| vehicle_share = total_capacity.positive? ? vehicle[:capacities][cut_symbol] / total_capacity : 1.0 / vehicles.size { limit: cut_ratio * total_quantity[cut_symbol] * vehicle_share } } end [strict_limits, metric_limits] end end
class Topic < ApplicationRecord has_many :posts validates :title, presence: true, length: { maximum: 100 } validates :default_name, presence: true, length: { maximum: 100 } validates :time_display, inclusion: { in: [true, false] } # validates :start_date, length: { maximum: 30 } # def corrupt_start_date # self.start_date = "縺ゅ>縺翫≧縺医♀" # end after_initialize :set_default_values public def set_default_values self.default_name ||= '名無しさん' # if time_display? # self.start_date ||= Time.now.strftime("%F %T") # else # self.start_date = nil # end end end
require 'spec_helper' feature 'Visitor signs up' do scenario 'with valid email and password' do sign_up_with 'First Last', 'valid@example.com', 'password' user_should_be_signed_in end scenario 'tries with invalid email' do sign_up_with '', 'invalid_email', 'password' user_should_be_signed_out end scenario 'tries with blank password' do sign_up_with '', 'valid@example.com', '' user_should_be_signed_out end scenario 'and sees a different landing page' do visit root_path page.should_not have_xpath('//textarea[@placeholder="Lesson"]') sign_up_with '', 'user@example.com', 'foobar' page.should have_xpath('//textarea[@placeholder="Lesson"]') end end
module Knowledge module DBpedia # hmm, http://www.semantic-web-journal.net/system/files/swj1141.pdf def self.is_a_person? name key = "people,#{name}" require 'dalli' dc = Dalli::Client.new('localhost:11211') res = dc.get(key) if (!res.nil?) Rails.logger.info "Using cached #{entity}" return res end res = is_a_specific_subject? 'people', name id = dc.set(key, res) Rails.logger.info "Caching #{key} as #{id}" res end def self.is_a_philosopher? name key = "philosophers,#{name}" require 'dalli' dc = Dalli::Client.new('localhost:11211') res = dc.get(key) if (!res.nil?) Rails.logger.info "Using cached #{entity}" return res end res = is_a_specific_subject? 'philosophers', name id = dc.set(key, res) Rails.logger.info "Caching #{key} as #{id}" res end def self.is_a_specific_subject? subject, name require 'sparql/client' sparql = SPARQL::Client.new("http://dbpedia.org/sparql") # SELECT DISTINCT ?resource ?cont # should use HERE DOC query = " PREFIX db-prop: <http://dbpedia.org/property/> PREFIX db-ont: <http://dbpedia.org/ontology/> PREFIX dc-term: <http://purl.org/dc/terms/> SELECT DISTINCT ?resource WHERE { ?resource dc-term:subject ?cont . ?resource <http://dbpedia.org/property/name> ?name . FILTER regex(?name, \"#{name}\", \"i\") . FILTER regex(?cont, \"#{subject}\", \"i\") . } ORDER BY ?resource " result_set = sparql.query(query) Rails.logger.info "DBpedia result #{result_set.inspect}" result_set end end # module DBpedia module Google def self.entity_search entity key = "KG,#{entity}" require 'dalli' dc = Dalli::Client.new('localhost:11211') res = dc.get(key) if (!res.nil?) Rails.logger.info "Using cached #{entity}" return res end api_key = IO.read("#{Rails.root}/.google_api_key").strip service_url = 'https://kgsearch.googleapis.com/v1/entities:search' http_params = { query: entity, limit: 1, indent: true, key: api_key, } url = service_url + '?' + http_params.to_query require 'open-uri' json_resp = open(url) if json_resp.status[0] == '200' resp = JSON.parse json_resp.read res = resp['itemListElement'][0]['result'] Rails.logger.info "KG result #{res.inspect}" id = dc.set(key, res) Rails.logger.info "Caching #{key} as #{id}" return res else raise "Google Knowledge Graph HTTP status #{json_resp.status}" end end end # module Google module LanguageLayer def self.detect phrase key = "LL,#{phrase}" require 'dalli' dc = Dalli::Client.new('localhost:11211') res = dc.get(key) if (!res.nil?) Rails.logger.info "Using cached #{entity}" return res end api_key = IO.read("#{Rails.root}/.languagelayer_api_key").strip service_url = 'http://apilayer.net/api/detect' http_params = { access_key: api_key, query: phrase, show_query: 1 } url = service_url + '?' + http_params.to_query require 'open-uri' require 'dalli' json_resp = open(url) if json_resp.status[0] == '200' resp = JSON.parse json_resp.read if resp['success'] == true res = resp['results'] Rails.logger.info "KG result #{res.inspect}" id = dc.set(key, res) Rails.logger.info "Caching #{key} as #{id}" return res else raise "Language Layer unsuccessful #{resp['error']}" end else raise "Language Layer HTTP status #{json_resp.status}" end end end # model LanguageLayer end # module Knowledge
class PostsController < ApplicationController before_action :authenticate_user! load_and_authorize_resource only: [:edit, :update, :destroy] # GET /posts # GET /posts.json def index @posts = Post.all end # GET /posts/new def new @city = City.find params[:city_id] @post = Post.new @user = current_user @post = Post.new end # create def create @city = City.find params[:city_id] @user = current_user @post = @city.posts.create(post_params) @post.user_id = current_user.id @post.save redirect_to city_path(@city) end def show @user = current_user @post = Post.find(params[:id]) end # GET /posts/1/edit def edit @city = City.find params[:city_id] @post = @city.posts.find(params[:id]) end # update def update @city = City.find params[:city_id] @post = @city.posts.find(params[:id]) @post.update(post_params) redirect_to city_post_path(@city, @post) end # destroy def destroy @city = City.find params[:city_id] @post = Post.find(params[:id]) @post.destroy redirect_to city_path(@city) end def user User.find(params[:user_id]) end private def post_params @user = current_user params.require(:post).permit(:title, :text, :user_id) end end
require 'osx/cocoa' module Installd class Notifications include OSX SYNC_DID_BEGIN = "InstalldSyncDidBegin" SYNC_DID_COMPLETE = "InstalldSyncDidComplete" CHECK_FOR_UPDATES = "InstalldCheckForUpdates" SHOW_STATUS_BAR_ITEM = "InstalldShowStatusBarItem" def initialize(bundle_identifier) @bundle_identifier = bundle_identifier @center = NSDistributedNotificationCenter.defaultCenter end def register_for_sync_did_begin(observer, selector) @center.addObserver_selector_name_object( observer, selector, SYNC_DID_BEGIN, @bundle_identifier ) end def register_for_sync_did_complete(observer, selector) @center.addObserver_selector_name_object( observer, selector, SYNC_DID_COMPLETE, @bundle_identifier ) end def register_for_check_for_updates(observer, selector) @center.addObserver_selector_name_object( observer, selector, CHECK_FOR_UPDATES, @bundle_identifier ) end def register_for_show_status_bar_item(observer, selector) @center.addObserver_selector_name_object( observer, selector, SHOW_STATUS_BAR_ITEM, @bundle_identifier ) end def sync_did_begin @center.postNotificationName_object_userInfo_deliverImmediately( SYNC_DID_BEGIN, @bundle_identifier, {}, true ) end def sync_did_complete(status) @center.postNotificationName_object_userInfo_deliverImmediately( SYNC_DID_COMPLETE, @bundle_identifier, { 'status' => status }, true ) end def check_for_updates @center.postNotificationName_object_userInfo_deliverImmediately( CHECK_FOR_UPDATES, @bundle_identifier, {}, true ) end def show_status_bar_item(state) @center.postNotificationName_object_userInfo_deliverImmediately( SHOW_STATUS_BAR_ITEM, @bundle_identifier, { 'state' => state }, true ) end end end
class String # return character array of string with indices def each_char_with_index i = 0 split(//).each do |c| yield i, c i += 1 end end end class String # get ngrams of string def ngrams(len = 1) ngrams = [] len = size if len > size (0..size - len).each do |n| ng = self[n...(n + len)] ngrams.push(ng) end ngrams end end module Renamer class Util class << self def similarity(str1, str2) dice_coefficient(str1, str2) end def basic(str1, str2) str1 = str1.dup str2 = str2.dup str1.downcase! pairs1 = (0..str1.length-2).collect do |i| str1[i,2] end.reject do |pair| pair.include? " " end str2.downcase! pairs2 = (0..str2.length-2).collect do |i| str2[i,2] end.reject do |pair| pair.include? " " end union = pairs1.size + pairs2.size intersection = 0 pairs1.each do |p1| 0.upto(pairs2.size-1) do |i| if p1 == pairs2[i] intersection += 1 pairs2.slice!(i) break end end end (2.0 * intersection) / union end def hamming_distance(str1, str2) str1.split(//).zip(str2.split(//)).inject(0) { |h, e| e[0]==e[1] ? h+0 : h+1 } end def damerau_levenshtein(str1, str2) d = Array.new(str1.size+1){Array.new(str2.size+1)} for i in (0..str1.size) d[i][0] = i end for j in (0..str2.size) d[0][j] = j end str1.each_char_with_index do |i,c1| str2.each_char_with_index do |j,c2| c = (c1 == c2 ? 0 : 1) d[i+1][j+1] = [ d[i][j+1] + 1, #deletion d[i+1][j] + 1, #insertion d[i][j] + c].min #substitution if (i>0) and (j>0) and (str1[i]==str2[j-1]) and (str1[i-1]==str2[j]) d[i+1][j+1] = [ d[i+1][j+1], d[i-1][j-1] + c].min #transposition end end end d[str1.size][str2.size] end def dice_coefficient(str1, str2) str1_2grams = str1.ngrams(2) str2_2grams = str2.ngrams(2) intersection = (str1_2grams & str2_2grams).length total = str1_2grams.length + str2_2grams.length dice = 2.0 * intersection / total end def levenshtein(str1, str2) return str1.length if 0 == str2.length return str2.length if 0 == str1.length c = Array.new c << (str1[0] == str2[0] ? 0 : 1) + (levenshtein str1[1..-1], str2[1..-1]) c << 1 + levenshtein(str1[1..-1], str2) c << 1 + levenshtein(str1, str2[1..-1]) return c.min end end end end
class OpenDayDecorator < Draper::Decorator delegate_all # Define presentation-specific methods here. Helpers are accessed through # `helpers` (aka `h`). You can override attributes, for example: # # def created_at # helpers.content_tag :span, class: 'time' do # object.created_at.strftime("%a %m/%d/%y") # end # end def date object.starts_at.to_formatted_s(:short) end def description return object.description_nl.html_safe if I18n.locale == :nl object.description_en.html_safe end def google_maps_url "https://www.google.com/maps/place/#{object.address.gsub(/ /, '+')}/@#{object.latitude},#{object.longitude}" end def google_maps_embed_url "https://www.google.com/maps/embed/v1/place?key=AIzaSyD5BFlLJ_VpC5b4JfHPy1pMHZILHGbzhSM&q=#{object.address.gsub(/ /, '+')}" end def google_maps_iframe h.content_tag :iframe, '', src: google_maps_embed_url, width: "100%", height: "450", frameborder: "0", style: "border:0", allowfullscreen: true end end
require_relative '../spec_helper' describe 'Discussion API' do before :all do @vars = {} end it 'creates a discussion' do request_data = { title: 'Test Discussion', created_by: 'test@test.com' } post '/discussion', request_data.to_json last_response.status.should == 201 @vars[:discussion] = response_data = JSON.parse last_response.body (/[\w\d]/ =~ response_data['id']).nil?.should be_false end it 'gets a discussion' do request_data = { title: 'Test Discussion', created_by: 'test@test.com' } get '/discussion/' << @vars[:discussion]['id'], request_data.to_json last_response.status.should == 200 response_data = JSON.parse last_response.body response_data['title'].should == request_data[:title] response_data['created_by'].should == request_data[:created_by] end it 'update a discussion' do request_data = { title: 'Updated Discussion', created_by: 'updated@test.com' } put '/discussion/' << @vars[:discussion]['id'], request_data.to_json last_response.status.should == 200 response_data = JSON.parse last_response.body (/[\w\d]/ =~ response_data['id']).nil?.should be_false end it 'delete a discussion' do delete '/discussion/' << @vars[:discussion]['id'] last_response.status.should == 200 end end
class Node attr_accessor :next, :data def initialize(data = nil) @next = nil @data = data end end class LinkedList include Enumerable attr_accessor :head, :tail def initialize @head = Node.new @tail = Node.new @head.next = @tail end def node_count self.count end def delete(target) false if empty? traverse = head.next until traverse == tail if traverse.data == target traverse.data = traverse.next.data traverse.next = traverse.next.next return target else traverse = traverse.next end end false end def each &block traverse = head.next until traverse == tail yield traverse if block_given? traverse = traverse.next end end def empty? head.next == tail end def insert_to_front(data) new_node = Node.new(data) new_node.next = head.next head.next = new_node end def inspect collect { |x| x.data } end end
class AddCo2EmissionsMetricTonsPerCapitaToYears < ActiveRecord::Migration def change add_column :years, :co2_emissions_metric_tons_per_capita, :decimal end end
FactoryGirl.define do factory :player do first_name "Игорь" surname "Смольников" birthday "1988-08-08" height 188 weight 90 end end
require_relative 'shape' class Square < Shape def draw puts 'Inside Square::draw() method.' end end
module RSpec module Mocks RSpec.describe "argument matchers matching" do let(:a_double) { double } after(:each, :reset => true) do reset a_double end describe "boolean" do it "accepts true as boolean" do expect(a_double).to receive(:random_call).with(boolean) a_double.random_call(true) end it "accepts false as boolean" do expect(a_double).to receive(:random_call).with(boolean) a_double.random_call(false) end it "rejects non boolean", :reset => true do expect(a_double).to receive(:random_call).with(boolean) expect { a_double.random_call("false") }.to fail_including "expected: (boolean)" end end describe "kind_of" do it "accepts fixnum as kind_of(Numeric)" do expect(a_double).to receive(:random_call).with(kind_of(Numeric)) a_double.random_call(1) end it "accepts float as kind_of(Numeric)" do expect(a_double).to receive(:random_call).with(kind_of(Numeric)) a_double.random_call(1.5) end it "handles non matching kinds nicely", :reset => true do expect(a_double).to receive(:random_call).with(kind_of(Numeric)) expect { a_double.random_call(true) }.to fail_including "expected: (kind of Numeric)" end it "matches arguments that have defined `kind_of?` to return true" do fix_num = double(:kind_of? => true) expect(a_double).to receive(:random_call).with(kind_of(Numeric)) a_double.random_call(fix_num) end it "handles a class thats overridden ===" do allow(Numeric).to receive(:===) { false } fix_num = double(:kind_of? => true) expect(a_double).to receive(:random_call).with(kind_of(Numeric)) a_double.random_call(fix_num) end end describe "instance_of" do it "accepts float as instance_of(Float)" do expect(a_double).to receive(:random_call).with(instance_of(Float)) a_double.random_call(1.1) end it "does NOT accept float as instance_of(Numeric)" do expect(a_double).not_to receive(:random_call).with(instance_of(Numeric)) a_double.random_call(1.1) end it "does NOT accept integer as instance_of(Numeric)" do expect(a_double).not_to receive(:random_call).with(instance_of(Numeric)) a_double.random_call(1) end it "rejects non numeric", :reset => true do expect(a_double).to receive(:random_call).with(an_instance_of(Numeric)) expect { a_double.random_call("1") }.to fail end it "rejects non string", :reset => true do expect(a_double).to receive(:random_call).with(an_instance_of(String)) expect { a_double.random_call(123) }.to fail end it "handles non matching instances nicely", :reset => true do expect(a_double).to receive(:random_call).with(instance_of(Numeric)) expect { a_double.random_call(1.5) }.to fail_including "expected: (an_instance_of(Numeric))" end end describe "anything" do it "accepts string as anything" do expect(a_double).to receive(:random_call).with("a", anything, "c") a_double.random_call("a", "whatever", "c") end it "doesn't accept no arguments" do expect(a_double).to_not receive(:random_call).with(anything) a_double.random_call end it "handles non matching instances nicely", :reset => true do expect(a_double).to receive(:random_call).with(anything) expect { a_double.random_call }.to fail_including "expected: (anything)" end end describe "duck_type" do it "matches duck type with one method" do expect(a_double).to receive(:random_call).with(duck_type(:length)) a_double.random_call([]) end it "matches duck type with two methods" do expect(a_double).to receive(:random_call).with(duck_type(:abs, :div)) a_double.random_call(1) end it "rejects goose when expecting a duck", :reset => true do expect(a_double).to receive(:random_call).with(duck_type(:abs, :div)) expect { a_double.random_call("I don't respond to :abs or :div") }.to fail_including "expected: (duck_type(:abs, :div))" end end describe "any_args" do context "as the only arg passed to `with`" do before { expect(a_double).to receive(:random_call).with(any_args) } it "matches no args" do a_double.random_call end it "matches one arg" do a_double.random_call("a string") end it "matches many args" do a_double.random_call("a string", :other, 3) end end context "as the last of three args" do before { expect(a_double).to receive(:random_call).with(1, /foo/, any_args) } it "matches a call of two args when it matches the first two explicit args" do a_double.random_call(1, "food") end it "matches a call of three args when it matches the first two explicit args" do a_double.random_call(1, "food", :more) end it "matches a call of four args when it matches the first two explicit args" do a_double.random_call(1, "food", :more, :args) end it "does not match a call where the first two args do not match", :reset => true do expect { a_double.random_call(1, "bar", 2, 3) }.to fail_including "expected: (1, /foo/, *(any args))" end it "does not match a call of no args", :reset => true do expect { a_double.random_call }.to fail_including "expected: (1, /foo/, *(any args))" end end context "as the first of three args" do before { expect(a_double).to receive(:random_call).with(any_args, 1, /foo/) } it "matches a call of two args when it matches the last two explicit args" do a_double.random_call(1, "food") end it "matches a call of three args when it matches the last two explicit args" do a_double.random_call(nil, 1, "food") end it "matches a call of four args when it matches the last two explicit args" do a_double.random_call(:some, :args, 1, "food") end it "does not match a call where the last two args do not match", :reset => true do expect { a_double.random_call(1, "bar", 2, 3) }.to fail_including "expected: (*(any args), 1, /foo/)" end it "does not match a call of no args", :reset => true do expect { a_double.random_call }.to fail_including "expected: (*(any args), 1, /foo/)" end end context "as the middle of three args" do before { expect(a_double).to receive(:random_call).with(1, any_args, /foo/) } it "matches a call of two args when it matches the first and last args" do a_double.random_call(1, "food") end it "matches a call of three args when it matches the first and last args" do a_double.random_call(1, nil, "food") end it "matches a call of four args when it matches the first and last args" do a_double.random_call(1, :some, :args, "food") end it "does not match a call where the first and last args do not match", :reset => true do expect { a_double.random_call(nil, "bar", 2, 3) }.to fail_including "expected: (1, *(any args), /foo/)" end it "does not match a call of no args", :reset => true do expect { a_double.random_call }.to fail_including "expected: (1, *(any args), /foo/)" end end context "when passed twice" do it 'immediately signals that this is invalid', :reset => true do expect { expect(a_double).to receive(:random_call).with(any_args, 1, any_args) }.to raise_error(ArgumentError, /any_args/) end end end describe "no_args" do it "matches no args against no_args" do expect(a_double).to receive(:random_call).with(no_args) a_double.random_call end it "fails no_args with one arg", :reset => true do expect(a_double).to receive(:msg).with(no_args) expect { a_double.msg(37) }.to fail_including "expected: (no args)" end context "when passed with other arguments" do it 'immediately signals that this is invalid', :reset => true do expect { expect(a_double).to receive(:random_call).with(no_args, 3) }.to raise_error(ArgumentError, /no_args/) end end end describe "hash_including" do it "matches hash with hash_including same hash" do expect(a_double).to receive(:random_call).with(hash_including(:a => 1)) a_double.random_call(:a => 1) end it "fails hash_including with missing key", :reset => true do expect(a_double).to receive(:random_call).with(hash_including(:a => 1)) expect { a_double.random_call(:a => 2) }.to fail_including "expected: (hash_including(:a=>1))" end end describe "hash_excluding" do it "matches hash with hash_excluding same hash" do expect(a_double).to receive(:random_call).with(hash_excluding(:a => 1)) a_double.random_call(:a => 2) end it "handles non matching instances nicely", :reset => true do expect(a_double).to receive(:random_call).with(hash_excluding(:a => 1)) expect { a_double.random_call(:a => 1) }.to fail_including "expected: (hash_not_including(:a=>1))" end end describe "array_including" do it "matches array with array_including same array" do expect(a_double).to receive(:random_call).with(array_including(1, 2)) a_double.random_call([1, 2]) end it "matches array with array_including using fuzzymatcher", :reset => true do expect(a_double).to receive(:random_call).with(array_including(a_value > 1)) a_double.random_call([1, 2]) end it "fails array_including when args aren't array", :reset => true do expect(a_double).to receive(:msg).with(array_including(1, 2, 3)) expect { a_double.msg(1, 2, 3) }.to fail_including "expected: (array_including(1, 2, 3))" end it "fails array_including when arg doesn't contain all elements", :reset => true do expect(a_double).to receive(:msg).with(array_including(1, 2, 3)) expect { a_double.msg([1, 2]) }.to fail_including "expected: (array_including(1, 2, 3))" end end describe "array_excluding" do it "matches array with array_excluding different array" do expect(a_double).to receive(:random_call).with(array_excluding(3, 4)) a_double.random_call([1, 2]) end it "fails array_excluding when is the same array", :reset => true do expect(a_double).to receive(:msg).with(array_excluding(1, 2, 3)) expect { a_double.msg(1, 2, 3) }.to fail_including "expected: (array_excluding(1, 2, 3))" end it "fails array_excluding when arg contains some elements", :reset => true do expect(a_double).to receive(:msg).with(array_excluding(2, 3)) expect { a_double.msg([1, 2]) }.to fail_including "expected: (array_excluding(2, 3))" end it "matches array_excluding when using the fuzzy matcher", :reset => true do expect(a_double).to receive(:msg).with(array_excluding(a_value > 3)) a_double.msg([1, 2]) end it "fails array_excluding when using the fuzzy matcher", :reset => true do expect(a_double).to receive(:msg).with(array_excluding(a_value > 1)) expect { a_double.msg([1, 2]) }.to fail_including "expected: (array_excluding(a value > 1))" end end context "handling arbitrary matchers" do it "matches any arbitrary object using #===" do matcher = double expect(matcher).to receive(:===).with(4).and_return(true) expect(a_double).to receive(:foo).with(matcher) a_double.foo(4) end it "matches against a Matcher", :reset => true do expect(a_double).to receive(:msg).with(equal(3)) # This spec is generating warnings on 1.8.7, not sure why so # this does with_isolated_stderr to kill them. @samphippen 3rd Jan 2013. expect { with_isolated_stderr { a_double.msg(37) } }.to fail_including "expected: (equal 3)" end it "fails when given an arbitrary object that returns false from #===", :reset => true do matcher = double expect(matcher).to receive(:===).with(4).at_least(:once).and_return(false) expect(a_double).to receive(:foo).with(matcher) expect { a_double.foo(4) }.to fail end end context "handling objects with a wrong definition of `==` that raises errors for other types" do Color = Struct.new(:r, :g, :b) do def ==(other) other.r == r && other.g == g && other.b == b end end before(:context) do expect { Color.new(0, 0, 0) == Object.new }.to raise_error(NoMethodError) end it 'matches against an equal instance of the same type' do expect(a_double).to receive(:random_call).with(Color.new(0, 0, 0)) a_double.random_call(Color.new(0, 0, 0)) end it 'fails when matched against an unequal instance of the same class', :reset do expect(a_double).to receive(:random_call).with(Color.new(0, 0, 0)) expect { a_double.random_call(Color.new(0, 1, 0)) }.to fail end it 'can match multiple instances of the type against multiple equal instances of the type' do expect(a_double).to receive(:random_call).with( Color.new(0, 0, 0), Color.new(0, 1, 0) ) a_double.random_call( Color.new(0, 0, 0), Color.new(0, 1, 0) ) end end context "handling non-matcher arguments" do it "matches string against regexp" do expect(a_double).to receive(:random_call).with(/bcd/) a_double.random_call("abcde") end it "matches regexp against regexp" do expect(a_double).to receive(:random_call).with(/bcd/) a_double.random_call(/bcd/) end it "fails if regexp does not match submitted string", :reset => true do expect(a_double).to receive(:random_call).with(/bcd/) expect { a_double.random_call("abc") }.to fail end it "fails if regexp does not match submitted regexp", :reset => true do expect(a_double).to receive(:random_call).with(/bcd/) expect { a_double.random_call(/bcde/) }.to fail end it "matches against a hash submitted and received by value" do expect(a_double).to receive(:random_call).with(:a => "a", :b => "b") a_double.random_call(:a => "a", :b => "b") end it "matches against a hash submitted as keyword arguments a and received as a positional argument (in both Ruby 2 and Ruby 3)" do opts = {:a => "a", :b => "b"} expect(a_double).to receive(:random_call).with(opts) a_double.random_call(:a => "a", :b => "b") end if RUBY_VERSION >= "3" it "fails to match against a hash submitted as a positional argument and received as keyword arguments in Ruby 3.0 or later", :reset => true do opts = {:a => "a", :b => "b"} expect(a_double).to receive(:random_call).with(:a => "a", :b => "b") expect do a_double.random_call(opts) end.to fail_with(/expected: \(\{(:a=>\"a\", :b=>\"b\"|:b=>\"b\", :a=>\"a\")\}\)/) end else it "matches against a hash submitted as a positional argument and received as keyword arguments in Ruby 2.7 or before" do opts = {:a => "a", :b => "b"} expect(a_double).to receive(:random_call).with(:a => "a", :b => "b") a_double.random_call(opts) end end it "fails for a hash w/ wrong values", :reset => true do expect(a_double).to receive(:random_call).with(:a => "b", :c => "d") expect do a_double.random_call(:a => "b", :c => "e") end.to fail_with(/expected: \(\{(:a=>\"b\", :c=>\"d\"|:c=>\"d\", :a=>\"b\")\}\)/) end it "fails for a hash w/ wrong keys", :reset => true do expect(a_double).to receive(:random_call).with(:a => "b", :c => "d") expect do a_double.random_call("a" => "b", "c" => "d") end.to fail_with(/expected: \(\{(:a=>\"b\", :c=>\"d\"|:c=>\"d\", :a=>\"b\")\}\)/) end it "matches a class against itself" do expect(a_double).to receive(:foo).with(Float) a_double.foo(Float) end it "fails a class against an unrelated class", :reset => true do expect(a_double).to receive(:foo).with(Float) expect { a_double.foo(Hash) }.to fail end it "matches a class against an instance of itself" do expect(a_double).to receive(:foo).with(Float) a_double.foo(3.3) end it "fails a class against an object of a different type", :reset => true do expect(a_double).to receive(:foo).with(Float) expect { a_double.foo(3) }.to fail end it "fails with zero arguments", :reset => true do expect do expect(a_double).to receive(:msg).with { |arg| expect(arg).to eq :received } end.to raise_error(ArgumentError, /must have at least one argument/) end it "fails with sensible message when args respond to #description", :reset => true do arg = double(:description => nil, :inspect => "my_thing") expect(a_double).to receive(:msg).with(3) expect { a_double.msg arg }.to fail_including "got: (my_thing)" end it "fails with sensible message when arg#description is nil", :reset => true do arg = double(:description => nil, :inspect => "my_thing") expect(a_double).to receive(:msg).with(arg) expect { a_double.msg 3 }.to fail_including "expected: (my_thing)" end it "fails with sensible message when arg#description is blank", :reset => true do arg = double(:description => "", :inspect => "my_thing") expect(a_double).to receive(:msg).with(arg) expect { a_double.msg 3 }.to fail_including "expected: (my_thing)" end end end end end
class Clasp < Formula desc "Answer set solver for (extended) normal logic programs" homepage "https://potassco.org/clasp/" url "https://github.com/potassco/clasp/archive/v3.3.2.tar.gz" sha256 "367f9f3f035308bd32d5177391a470d9805efc85a737c4f4d6d7b23ea241dfdf" bottle do cellar :any_skip_relocation sha256 "3669d47d74e6ec6b73c9e56278f4679305b614616a00e52784df2113a91d6b0b" => :high_sierra sha256 "02cafaad412b7b4bc1c78bbd81f153345eb1eaf22050d55c2daba069a73ffa90" => :sierra sha256 "09acf6c42509c7cc80311c181685ebb39c319a80668ab3e7a452586a72961f7b" => :el_capitan sha256 "fb6c23036a3735c43cabbe38c324cd16cf07ed4c7463396d3c559bec6c4038be" => :yosemite end depends_on "cmake" => :build def install system "cmake", ".", *std_cmake_args system "make", "install" end test do assert_match version.to_s, shell_output("#{bin}/clasp --version") end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root "static_pages#home" namespace :api, defaults: { format: :json } do namespace :v1 do namespace :student do resources :book_borrows, only: [:create, :index, :destroy] resources :books, only: [:index, :show] end namespace :librarian do resources :book_managements, only: [:create, :index, :show, :update, :destroy] end end end get "*path", :to => "static_pages#home" end
class User include Mongoid::Document include ActiveModel::SecurePassword has_secure_password field :username, type: String field :password_digest, type: String field :is_admin, type: Boolean end
module Guide::Fixtures # This file exists to help Rails autoload the fixtures directory end
module Admin class DashboardsController < ApplicationController def show @last_import = ImportLog.last @newest_trial = Trial.order(created_at: :desc).first @sites_without_coordinates = Site.without_coordinates end end end
module Antelope module DSL module Contexts # The base context, which implements some helper methods. class Base attr_reader :options def initialize(options) @options = options @contexts = Hash.new { |h, k| h[k] = k.new(@options) } end def call(&block) before_call instance_exec(self, &block) data end def context(name, &block) @contexts[name].call(&block) end def before_call; end def data; end end end end end
require('csv') require('svm') module SVM # This module is to prevent Model (which is in svm without a namespace) from # shadowing the Model which is under Classifier def self.model Model end end module Classifier class SVMachine def initialize(sample, column_names) training_categories = sample[:category].map { |val| val == "true" ? 1.0 : -1.0 } evs = {} column_names.each { |sym| evs[sym] = ExplanatoryVariable.lookup(sym) } training_data = (0...sample.size).map do |val| column_names.map do |var| if evs[var].nil? sample.hashify(sample.find_row(val))[var] #TODO refactor else evs[var].evaluate(nil, precomputed_values: sample.hashify(sample.find_row(val)), sample: sample) end end end prob = Problem.new(training_categories, training_data) param = Parameter.new(:kernel_type => LINEAR, :C => 100) @m = SVM::model.new(prob,param) end def predict(vector) @m.predict(vector) > 0 end end class Ai4r::Classifiers::EvaluationNode def rule_not_found "no rule found" end end class DecisionTreeID3 def initialize(sample, column_names) category = sample[:category] evs = {} column_names.each { |sym| evs[sym] = ExplanatoryVariable.lookup(sym) } training_data = (0...sample.size).map do |val| column_names.map do |var| if evs[var].nil? sample.hashify(sample.find_row(val))[var] #TODO refactor else evs[var].evaluate(nil, precomputed_values: sample.hashify(sample.find_row(val)), sample: sample) end end << category[val] end dataset = Ai4r::Data::DataSet.new( data_items: training_data, data_labels: column_names << :category) @m = Ai4r::Classifiers::ID3.new.build(dataset) end def predict(vector) @m.eval(vector) == "true" end end class SASDecisionTree def initialize(filename) #TODO: use the filename end def node(x,y) if !x.blank? && 1.02614315873885 <=x return 3 end if !x.blank? && x < 0.49264908877269 if !y.blank? && 0.500322369158 <= y return 7 else return 6 end else return 5 end end def predict(vector) x = vector[0] y = vector[1] if [3,6,5].include? node(x,y) return true elsif [7].include? node(x,y) return false else return nil end end end end
Rails.application.routes.draw do mount Documentation::Engine => "/docs" devise_for :admin_users, ActiveAdmin::Devise.config devise_for :users, controllers: { sessions: 'sessions' } ActiveAdmin.routes(self) root 'admin/dashboard#index' resources :users, only: [:create, :show, :update] resources :contact_emails, only: [:create] resources :restaurants, only: [:index, :show] resources :services, only: [:index, :update] resources :reservations, only: [:index,:create, :update] resources :transactions, only: [:index] get 'resend_confirmation', to: 'users#resend_confirmation', as: 'resend_confirmation' get 'confirm', to: 'users#confirm', as: 'confirm' get 'password_email', to: 'users#password_email', as: 'password_email' get 'edit_password', to: 'users#edit_password', as: 'edit_password' post 'update_password', to: 'users#update_password', as: 'update_password' get 'unsubscribe', to: 'users#unsubscribe', as: 'unsubscribe' end
class AuditReportCreator < Generic::Strict attr_accessor :data, :report_template, :user, :wegoaudit_id attr_reader :audit_report def initialize(*) super @user_org = user.organization_id self.report_template ||= Organization.find(@user_org).report_templates .first_or_create(layout: 'default', name: 'Base Template') end def create execute audit_report end def execute ActiveRecord::Base.transaction do create_audit_report end end private def create_audit_report @user = User.find_by(wegowise_id: user.wegowise_id) @audit_report = AuditReport.create!( name: data['name'], user_id: @user.id, organization_id: user.organization_id, data: data, report_template: report_template, wegoaudit_id: wegoaudit_id ) create_field_values import_wegowise_data end def create_field_values Field.where(level: 'audit_report').each do |field| options = { field_api_name: field.api_name } if field.api_name == 'audit_date' options[:value] = audit_report.audit.date elsif audit_report.audit.field_values[field.api_name] != nil options[:value] = audit_report.audit.field_values[field.api_name] end audit_report.field_values.create!(options) end end def import_wegowise_data structures = data['structures'] # wegowise_ids = WegowiseIdFinder.new(structures).find_ids # start_data_import_workers(wegowise_ids) end def start_data_import_workers(wegowise_ids) building_ids = wegowise_ids['building'][:ids] building_ids.each do |id| MonthlyDataImportWorker.perform_async( user.id, id, 'Building', audit_report.id) end apartment_ids = wegowise_ids['apartment'][:ids] apartment_ids.each do |id| MonthlyDataImportWorker.perform_async( user.id, id, 'Apartment', audit_report.id) end end end
class ShippingInfo < ApplicationRecord belongs_to :user has_many :adress_for_carts has_many :carts, through: :adress_for_carts has_many :orders end
Rails.application.routes.draw do root "welcome#index" resources :words, only: [:show, :index] resources :welcome get 'search' => 'search#index', as: :search end
require 'redis' require 'httparty' class ApiClient @redis = Redis.new API_KEY = "AIzaSyApJRMcccoLoceai4KO_L3SYdNXwybqAj8" def self.grab_data_and_save books = get_search_results('rails', 'computers', 40) update_book_ids_and_save_books(books) clear_cached_pages @redis.set "app:last_updated", Time.now end def self.get_search_results(intitle, subject, max_results) index = 0 books = [] while true results = HTTParty.get("https://www.googleapis.com/books/v1/volumes?q=intitle:#{intitle}+subject:#{subject}&startIndex=#{(index) * max_results}&maxResults=40&orderBy=relevance&key=#{API_KEY}") results['items'].each do |v| books << v end break if results['totalItems'].to_i < ((index + 1) * 40) index += 1 end books end def self.update_book_ids_and_save_books(books) books.each do |volume| key = "book:#{volume['id']}" if key_unknown?(key) @redis.lpush('book_ids', key) save_to_redis('book_ids', key, volume) elsif etag_has_changed?(key, volume['etag']) save_to_redis('book_ids', key, volume) end end end def self.key_unknown?(key) @redis.hlen(key) == 0 end def self.etag_has_changed?(key, etag) @redis.hmget(key, etag) != etag end def self.save_to_redis(list_name, key, volume) @redis.hmset(key, 'etag', volume['etag'], 'title', volume['volumeInfo']['title'], 'isbn', volume['volumeInfo']['industryIdentifiers'][0]['identifier']) # they don't always have an author nor a thumbnail volume['volumeInfo']['authors']? @redis.hmset(key, 'authors', volume['volumeInfo']['authors'].join(', ')) : @redis.hmset(key, 'authors', '-') if volume['volumeInfo']['imageLinks'] && volume['volumeInfo']['imageLinks']['smallThumbnail'] @redis.hmset(key, 'thumbnail', volume['volumeInfo']['imageLinks']['smallThumbnail']) end end def self.clear_cached_pages cached_pages = @redis.lrange "cached_page_ids", 0, -1 cached_pages.each do |page| puts "page #{page} has been cleared" @redis.del page end @redis.del "cached_page_ids" end end
module PlugemsDeploy class GemService require 'rubygems' require 'yaml' require 'rubygems/remote_installer' def initialize(sources = [ cache ]) @sources = sources @indexes = { cache => Gem.cache } end def find_gem(name, version) @sources.each do |source| specs = index(source).search(/^#{ name }$/, version) return spec_with_source(specs.last, source) unless specs.empty? end nil end private LATEST_RUBYGEMS = Gem::RubyGemsVersion.split('.').map{|v|v.to_i}.extend(Comparable) > [0,9,0] def cache 'cache' end def index(source) @indexes[source] ||= source_index(source) end def spec_with_source(spec, source) spec.class.send(:attr_accessor, :download_source) spec.download_source = source spec end def source_index(source) LATEST_RUBYGEMS ? Gem::SourceIndex.new.update(source) : Gem::RemoteSourceFetcher.new(source, nil).source_index end end end
require File.dirname(__FILE__) + '/../test_helper' require 'block_links_controller' # Re-raise errors caught by the controller. class BlockLinksController; def rescue_action(e) raise e end; end class BlockLinksControllerTest < Test::Unit::TestCase fixtures :block_links def setup @controller = BlockLinksController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_index get :index assert_response :success assert_template 'list' end def test_list get :list assert_response :success assert_template 'list' assert_not_nil assigns(:block_links) end def test_show get :show, :id => 1 assert_response :success assert_template 'show' assert_not_nil assigns(:block_link) assert assigns(:block_link).valid? end def test_new get :new assert_response :success assert_template 'new' assert_not_nil assigns(:block_link) end def test_create num_block_links = BlockLink.count post :create, :block_link => {} assert_response :redirect assert_redirected_to :action => 'list' assert_equal num_block_links + 1, BlockLink.count end def test_edit get :edit, :id => 1 assert_response :success assert_template 'edit' assert_not_nil assigns(:block_link) assert assigns(:block_link).valid? end def test_update post :update, :id => 1 assert_response :redirect assert_redirected_to :action => 'show', :id => 1 end def test_destroy assert_not_nil BlockLink.find(1) post :destroy, :id => 1 assert_response :redirect assert_redirected_to :action => 'list' assert_raise(ActiveRecord::RecordNotFound) { BlockLink.find(1) } end end
class Dig < ActiveRecord::Base belongs_to :owner, class_name: 'User' has_many :votes, as: :votable, dependent: :destroy has_many :voters, through: :votes has_many :comments, dependent: :destroy validates :title, :owner_id, presence: true def as_json(opts={}) super.merge(rating: votes.sum(:amount)) end end
ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content do panel 'Reservations' do table_for Reservation.get_unarchived.order('id DESC').each do |reservation| column(:id) do |reservation| link_to reservation.id, admin_reservation_path(reservation) end column(:status) column(:bill_amount) column(:booking_name) column(:nb_people) column(:time) column(:restaurant) do |reservation| link_to reservation.restaurant, admin_restaurant_path(reservation.restaurant.id) rescue nil end column(:user) do |reservation| link_to reservation.user, admin_user_path(reservation.user.id) rescue nil end column(:discount) do |reservation| (reservation.discount * 100).round.to_s + '%' rescue nil end column(:user_contribution) do |reservation| reservation.user_contribution.round(2).to_s + '€' rescue nil end end end end end
require 'active_support' require 'active_record' class KnownFact < ActiveRecord::Base named_scope :current, :conditions => {:is_active => 1} end class VirtualDisk attr_reader :disk_number attr_accessor :size def initialize(disk_number, size) @disk_number = disk_number @size = size end def self.all disks = [] KnownFact.current.all(:conditions => ['key like "vd%%"']).each do |f| if f.key =~ /vd(\d+)$/ disk_number = $1.to_i disks << self.find_by_disk_number(disk_number) end end disks end def self.find_by_disk_number(disk_number) fact = KnownFact.current.find_by_key('vd' + disk_number.to_s) return nil unless fact json = ActiveSupport::JSON.decode(fact.value) VirtualDisk.new(disk_number, json['size']) end def save(origin = nil, agent = nil) fact = KnownFact.current.find_by_key('vd' + @disk_number.to_s) fact = KnownFact.new(:key => 'vd' + @disk_number.to_s, :is_active => 1) unless fact fact.value = self.to_json fact.origin = origin fact.agent = agent fact.save end def delete fact = KnownFact.current.find_by_key('vd' + @disk_number.to_s) fact.update_attributes(:is_active => false) if fact end end class VirtualDiskState attr_reader :disk_number attr_accessor :is_up def initialize(disk_number, is_up) @disk_number = disk_number @is_up = is_up end def self.find_by_disk_number(disk_number) fact = KnownFact.current.find_by_key('vd' + disk_number.to_s + '-state') return nil unless fact VirtualDiskState.new(disk_number, fact.value == 'up') end def save(origin = nil, agent = nil) fact = KnownFact.current.find_by_key('vd' + @disk_number.to_s + '-state') fact = KnownFact.new(:key => 'vd' + @disk_number.to_s + '-state', :is_active => 1) unless fact fact.value = @is_up ? 'up' : 'down' fact.origin = origin fact.agent = agent fact.save end def delete fact = KnownFact.current.find_by_key('vd' + @disk_number.to_s + '-state') fact.update_attributes(:is_active => false) if fact end end ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'databases/storage.sqlite' )
require_relative "Move" require "byebug" class Board attr_reader :ply, :board_data, :white_to_move, :castling, :en_passant module ChessPieces def piece if !(self.is_a? Integer) raise ArgumentError.new "arguement must be of type Integer" elsif !((-6..-1).to_a + (0..6).to_a).include? self raise ArgumentError.new "integer #{self} is out of range" end case self.abs when 6 then "king" when 5 then "queen" when 4 then "rook" when 3 then "bishop" when 2 then "knight" when 1 then "pawn" when 0 then nil end end def color if self < 0 "black" elsif self > 0 "white" else nil end end end Fixnum.send(:include, ChessPieces) def initialize(params = {}) @ply = params[:ply] || 0 @board_data = params[:board_data] || standard_board_setup @white_to_move = params[:white_to_move].nil? ? true : params[:white_to_move] @castling = params[:castling] || { white_king: true, white_queen: true, black_king: true, black_queen: true } @en_passant = params[:en_passant] || [[0, 0], [0, 0]] end def move(move) if move.is_a? String move = Move.new([move[0].to_i, move[1].to_i], [move[2].to_i, move[3].to_i], promotion: move[4].to_i) end legal = moves.any? do |legal_move| legal_move.start_square == move.start_square && legal_move.end_square == move.end_square end if legal new_board_data = execute_move(@board_data, move) new_board = Board.new(ply: @ply + 1, board_data: new_board_data, white_to_move: !@white_to_move, castling: @castling.dup, en_passant: @en_passant.dup) new_board = castling_update(new_board, move) end return new_board end def moves output = [] each_square do |rank, file| if right_color?(rank, file) naive_moves = naive_moves(rank, file, @board_data, @castling) if !naive_moves.nil? naive_moves.each do |naive_move| if king_safe?(naive_move) output << naive_move end end end end end return output end def board_visualization @board_data.each_with_index do |row, i| row.each { |square| print square < 0 ? "#{square} " : " #{square} " } puts end end private def castling_update(board, move) castling_data = board.castling if move.start_square == [7, 4] castling_data[:white_king] = false castling_data[:white_queen] = false elsif move.start_square == [0, 4] castling_data[:black_king] = false castling_data[:black_queen] = false elsif move.start_square == [7, 7] || move.end_square == [7, 7] castling_data[:white_king] = false elsif move.start_square == [7, 0] || move.end_square == [7, 0] castling_data[:white_queen] = false elsif move.start_square == [0, 0] || move.end_square == [0, 0] castling_data[:black_queen] = false elsif move.start_square == [0, 7] || move.end_square == [0, 7] castling_data[:black_king] = false end return board end def execute_move(board, move) board_copy = board.map { |i| i.dup } if board_copy[move.start_square[0]][move.start_square[1]] == "white" promoted_piece = move.promotion else promoted_piece = move.promotion * -1 end piece_on_arrival = move.promotion.zero? ? board_copy[move.start_square[0]][move.start_square[1]] : promoted_piece board_copy[move.end_square[0]][move.end_square[1]] = piece_on_arrival board_copy[move.start_square[0]][move.start_square[1]] = 0 if move.start_square == [7, 4] && move.end_square == [7, 6] board_copy[7][7] = 0 board_copy[7][5] = 4 elsif move.start_square == [7, 4] && move.end_square == [7, 2] board_copy[7][0] = 0 board_copy[7][4] = 4 elsif move.start_square == [0, 4] && move.end_square == [0, 6] board_copy[0][7] = 0 board_copy[0][5] = -4 elsif move.start_square == [0, 4] && move.end_square == [0, 2] board_copy[0][0] = 0 board_copy[0][3] = -4 end return board_copy end def naive_moves(rank, file, board, castling) case board[rank][file].abs when 1 then naive_pawn_moves(rank, file, board) when 2 then naive_knight_moves(rank, file, board) when 3 then naive_bishop_moves(rank, file, board) when 4 then naive_rook_moves(rank, file, board) when 5 then naive_queen_moves(rank, file, board) when 6 then naive_king_moves(rank, file, board, castling) end end def find_king(board) right_color = @white_to_move ? "white" : "black" output = nil each_square do |rank, file| if !board[rank][file].zero? && board[rank][file].piece == "king" && board[rank][file].color == right_color output = [rank, file] break end end return output end def right_color?(rank, file) right_color = @white_to_move ? "white" : "black" @board_data[rank][file].color == right_color end def king_safe?(move) right_color = @white_to_move ? "black" : "white" test_board = execute_move(@board_data, move) king_location = find_king(test_board) safety = true catch :king_safety do if local_threats_to_king?(test_board, king_location[0], king_location[1]) safety = false throw :king_safety end each_square do |rank, file| if ["rook", "bishop", "queen"].include?(test_board[rank][file].piece) && test_board[rank][file].color == right_color naive_moves(rank, file, test_board, {}).each do |enemy_move| if enemy_move.end_square == king_location safety = false throw :king_safety end end end end end return safety end def local_threats_to_king?(board, rank, file) threat = false catch :king_safety do if @white_to_move king_color = "white" pawns = [[rank - 1, file - 1], [rank - 1, file + 1]] else king_color = "black" pawns = [[rank + 1, file - 1], [rank + 1, file + 1]] end pawns.each do |i| if board[i[0]] && board[i[0]][i[1]] && board[i[0]][i[1]].piece == "pawn" && board[i[0]][i[1]].color != king_color threat = true throw :king_safety end end knights = [ [rank - 2, file + 1], [rank - 1, file + 2], [rank + 1, file + 2], [rank + 2, file + 1], [rank + 2, file - 1], [rank + 1, file - 2], [rank - 1, file - 2], [rank - 2, file - 1] ] knights.each do |i| if i[0] > 0 && i[1] > 0 && board[i[0]] && board[i[0]][i[1]] && board[i[0]][i[1]].piece == "knight" && board[i[0]][i[1]].color != king_color threat = true throw :king_safety end end end return threat end def valid_pieces(pieces_array) pieces_array.length == 8 && pieces_array.all? { |i| i.length == 8 } end def valid_castling_hash(castling_hash) castling_hash.length == 4 && !!castling_hash[:white_king] == castling_hash[:white_king] && !!castling_hash[:white_queen] == castling_hash[:white_queen] && !!castling_hash[:black_king] == castling_hash[:black_king] && !!castling_hash[:black_queen] == castling_hash[:black_queen] end def valid_en_passant(en_passant_array) en_passant_array.length == 2 && en_passant_array.all? { |i| i.length == 2} # TODO: Make more robust en passant validation using game logic end def standard_board_setup [ [-4, -2, -3, -5, -6, -3, -2, -4], [-1, -1, -1, -1, -1, -1, -1, -1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1], [4, 2, 3, 5, 6, 3, 2, 4] ] end def naive_pawn_moves(rank, file, board) output = [] piece = board[rank][file] v_direction = piece > 0 ? -1 : 1 if !board[rank + 1 * v_direction].nil? && board[rank + 1 * v_direction][file].zero? && output << pawn_move_builder([rank, file], [rank + 1 * v_direction, file], piece) if !board[rank + 2 * v_direction].nil? && board[rank + 2 * v_direction][file].zero? && ((rank == 1 && piece.color == "black") || (rank == 6 && piece.color == "white")) output << pawn_move_builder([rank, file], [rank + 2 * v_direction, file], piece) end end if !board[rank + 1 * v_direction].nil? && !board[rank + 1 * v_direction][file - 1].nil? && !(board[rank + 1 * v_direction][file - 1]).zero? && piece.color != board[rank + 1 * v_direction][file - 1].color output << pawn_move_builder([rank, file], [rank + 1 * v_direction, file - 1], piece) end if !board[rank + 1 * v_direction].nil? && !board[rank + 1 * v_direction][file + 1].nil? && !(board[rank + 1 * v_direction][file + 1]).zero? && piece.color != board[rank + 1 * v_direction][file + 1].color output << pawn_move_builder([rank, file], [rank + 1 * v_direction, file + 1], piece) end remove_out_of_bounds(output.flatten) end def pawn_move_builder(start_square, end_square, piece) output = [] if piece.color == "white" && end_square[0] == 0 [2, 3, 4, 5].each { |i| output << Move.new(start_square, end_square, promotion: i) } elsif piece.color == "black" && end_square[0] == 7 [2, 3, 4, 5].each { |i| output << Move.new(start_square, end_square, promotion: i) } else output << Move.new(start_square, end_square) end return output end def naive_king_moves(rank, file, board, castling) output = [] piece = board[rank][file] [-1, 0, 1].each do |rank_inc| [-1, 0, 1].each do |file_inc| if !(rank_inc.zero? && file_inc.zero?) && !board[rank + rank_inc].nil? && !board[rank + rank_inc][file + file_inc].nil? && !(piece.color == board[rank + rank_inc][file + file_inc].color) output << Move.new([rank, file], [rank + rank_inc, file + file_inc]) end end end if piece.color == "white" if castling[:white_king] && board[7][5].zero? && board[7][6].zero? output << Move.new([rank, file], [7, 6]) end if castling[:white_queen] && board[7][3].zero? && board[7][2].zero? && board[7][1].zero? output << Move.new([rank, file], [7, 2]) end else if castling[:black_king] && board[0][5].zero? && board[0][6].zero? output << Move.new([rank, file], [0, 6]) end if castling[:black_queen] && board[0][3].zero? && board[0][2].zero? && board[0][1].zero? output << Move.new([rank, file], [0, 2]) end end remove_out_of_bounds(output) end def naive_knight_moves(rank, file, board) output = [] piece = board[rank][file] [[-2, 1], [-1, 2], [1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1]].each do |i| if !board[rank + i[0]].nil? && !board[rank + i[0]][file + i[1]].nil? && (board[rank + i[0]][file + i[1]].zero? || piece.color != board[rank + i[0]][file + i[1]].color) output << Move.new([rank, file], [rank + i[0], file + i[1]]) end end remove_out_of_bounds(output) end def naive_rook_moves(rank, file, board) output = [] variables = [[-1, 0, rank], [1, 0, 7 - rank], [0, -1, file], [0, 1, 7 - file]] variables.each { |i| move_along(i[0], i[1], i[2], rank, file, output, board) } return output end def naive_bishop_moves(rank, file, board) output = [] variables = [ [-1, 1, [rank, 7 - file].min], [-1, -1, [rank, file].min], [1, -1, [7 - rank, file].min], [1, 1, [7 - rank, 7 - file].min] ] variables.each { |i| move_along(i[0], i[1], i[2], rank, file, output, board) } return output end def naive_queen_moves(rank, file, board) output = [] output << naive_rook_moves(rank, file, board) output << naive_bishop_moves(rank, file, board) return output.flatten end def move_along (rank_mod, file_mod, sequence_builder, rank, file, output, board) piece = board[rank][file] (1..sequence_builder).each do |increment| move = Move.new([rank, file], [rank + increment * rank_mod, file + increment * file_mod]) if board[rank + increment * rank_mod][file + increment * file_mod].zero? output << move elsif board[rank + increment * rank_mod][file + increment * file_mod].color != piece.color output << move break else break end end end def each_square (0..7).each do |rank| (0..7).each do |file| yield(rank, file) end end end def remove_out_of_bounds(output) output.select { |i| i.in_bounds } end end
require 'spec_fast_helper' require 'hydramata/works/configuration_methods' module Hydramata module Works describe ConfigurationMethods do Given(:configuration) do Class.new do include ConfigurationMethods end.new end context '#work_model_name' do context 'default value' do When(:work_model_name) { configuration.work_model_name } Then { work_model_name == 'Work' } end context 'override' do Given(:work_model_name) { 'SomethingDifferent' } When { configuration.work_model_name = work_model_name } Then { configuration.work_model_name == work_model_name } end end context '#work_to_persistence_coordinator' do context 'default value' do When(:service) { configuration.work_to_persistence_coordinator } Then { service.respond_to?(:call) } end context 'override' do it 'raises an exception when the object is invalid' do expect { configuration.work_to_persistence_coordinator = :storage_service }.to raise_error(RuntimeError) end Given(:service) { double(call: true) } When { configuration.work_to_persistence_coordinator = service } Then { configuration.work_to_persistence_coordinator == service } end end context '#pid_minting_service' do context 'default' do When(:service) { configuration.pid_minting_service } Then { service.respond_to?(:call) } end context 'override #pid_minting_service' do it 'raises an exception when the object is invalid' do expect { configuration.pid_minting_service = :storage_service }.to raise_error(RuntimeError) end Given(:service) { double(call: true) } When { configuration.pid_minting_service = service } Then { configuration.pid_minting_service == service } end end context '#repository_connection' do context 'default value' do When(:repository_connection) { configuration.repository_connection } Then { repository_connection.respond_to?(:find_or_initialize) } end context 'override' do it 'raises an exception when the object is invalid' do expect { configuration.repository_connection = :repository_connection }.to raise_error(RuntimeError) end Given(:configured_repository_connection) { double(find_or_initialize: true) } When { configuration.repository_connection = configured_repository_connection } Then { configuration.repository_connection == configured_repository_connection } end end context '#work_from_persistence_coordinator' do context 'default' do When(:service) { configuration.work_from_persistence_coordinator } Then { service.respond_to?(:call) } end context 'override #work_from_persistence_coordinator' do it 'raises an exception when the object is invalid' do expect { configuration.work_from_persistence_coordinator = :storage_service }.to raise_error(RuntimeError) end Given(:service) { double(call: true) } When { configuration.work_from_persistence_coordinator = service } Then { configuration.work_from_persistence_coordinator == service } end end end end end
class CommentObserver < ActiveRecord::Observer # Send a email to admin when someone comment on site def after_create(comment) Notifier.email_comment(comment).deliver end end
class Ability include CanCan::Ability def initialize(user, namespace) case namespace when 'Manage' return unless user can :manage, :all if user.has_role? :admin else end end end
Types::MovieType = GraphQL::ObjectType.define do name "Movie" field :id, !types.ID field :title, !types.String field :description, types.String end
# give score for a word on Scrabble game class Scrabble TILES = { A: 1, N: 1, B: 3, O: 1, C: 3, P: 3, D: 2, Q: 10, E: 1, R: 1, F: 4, S: 1, G: 2, T: 1, H: 4, U: 1, I: 1, V: 4, J: 8, W: 4, K: 5, X: 8, L: 1, Y: 4, M: 3, Z: 10 } def self.score(tiles) new(tiles).score end private attr_reader :letters, :tiles def initialize(word, tiles = TILES) @letters = word.to_s.upcase.chars.map(&:to_sym) tiles.default = 0 @tiles = tiles end public def score letters.sum(&tiles) end end
class Group < ApplicationRecord has_many :people, dependent: :destroy validates :name, :street, :number, :zip, :town, :country, presence: true validates :name, uniqueness: { scope: :street, message: "Familie existiert bereits" } end
class Sale < ApplicationRecord belongs_to :client belongs_to :user has_many :item, dependent: :destroy def update_total new_total = item.map{|i| i.price}.sum update(total: new_total) end end
# -*- encoding : utf-8 -*- require 'rubygems' require 'test/unit' require 'module_say' require 'mocha' class ModuleSayTest < Test::Unit::TestCase def setup @bot = mock('bot') @m = Module_Say.new @m.init_module(@bot) end def test_does_nothing_with_empty_privmsg @m.expects(:speak).never @m.privmsg(@bot, "huamn", "#channel", "") end def test_does_nothing_with_empty_botmsg @m.expects(:speak).never @m.botmsg(@bot, "#channel", "") end def test_invokes_say_with_Kernel_system_using_Ralph_for_bot @m.expects(:system).with("say -v \"Ralph\" \"I say test\"").once @m.botmsg(@bot, "#channel", "test") end def test_invokes_say_with_Kernel_system_using_Princess_for_huamn seq = sequence('seq') @m.expects(:system).with("say -v \"Ralph\" \"huamn says\"").once @m.expects(:system).with("say -v \"Princess\" \"test\"").once @m.privmsg(@bot, "huamn", "#channel", "test") end def test_invokes_say_with_Kernel_system_using_Junior_for_Pantti seq = sequence('seq') @m.expects(:system).with("say -v \"Ralph\" \"Pantti says\"").once.in_sequence(seq) @m.expects(:system).with("say -v \"Junior\" \"test\"").once.in_sequence(seq) @m.privmsg(@bot, "Pantti", "#channel", "test") end def test_drops_unwanted_characters_from_input seq = sequence('seq') @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "cleaned, input with åäöÅÄÖ 1 2 3!").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "\"cleaned, [input]** with åäöÅÄÖ 1 2 3!\"") end def test_converts_tj seq = sequence('seq') @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "chief executive officer tjtj chief executive officer tjtj chief executive officer").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "Tj tjtj TJ tjtj tj") end def test_converts_ap seq = sequence('seq') @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "yrro mi paysa").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "ap") end def test_strips_urls_and_comments_them_separately seq = sequence('seq') @m.expects(:speak).with(nil, "huamn posts an url to boobs").once.in_sequence(seq) @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "heh smiley").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "http://www.youtube.com/watch?v=kQFKtI6gn9Y heh :)") end def test_rickrolls seq = sequence('seq') @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "I like rick").once.in_sequence(seq) @m.expects(:say).with("Cellos", "huamn I'm never gonna give you up, never gonna let you down!").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "I like rick") end def test_pig seq = sequence('seq') @m.expects(:speak).with(nil, "huamn says").once.in_sequence(seq) @m.expects(:speak).with("huamn", "pig").once.in_sequence(seq) @m.expects(:speak).with(nil, "huamn would also like to announce the following").once.in_sequence(seq) @m.expects(:speak).with("huamn", "ar ar ar niff niff niff i am a pig").once.in_sequence(seq) @m.privmsg(@bot, "huamn", "#channel", "pig") end end
class Admin::ArticlesController < AdminController def slug_settings @first_geo_slugs = FirstGeoSlug.order(:name).all @second_geo_slugs = SecondGeoSlug.order(:name).all end def new_first_geo_slug @first_geo_slug = FirstGeoSlug.new end def create_first_geo_slug @first_geo_slug = FirstGeoSlug.new(params[:first_geo_slug]) if @first_geo_slug.valid? @first_geo_slug.save redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully created!' else render :new_first_geo_slug end end def edit_first_geo_slug @first_geo_slug = FirstGeoSlug.find(params[:id]) end def update_first_geo_slug @first_geo_slug = FirstGeoSlug.find(params[:id]) if @first_geo_slug.update_attributes(params[:first_geo_slug]) redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully edited!' else render :edit_first_geo_slug end end def destroy_first_geo_slug FirstGeoSlug.destroy(params[:id]) redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully deleted!' end def new_second_geo_slug @second_geo_slug = SecondGeoSlug.new end def create_second_geo_slug @second_geo_slug = SecondGeoSlug.new(params[:second_geo_slug]) if @second_geo_slug.valid? @second_geo_slug.save redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully created!' else render :new_second_geo_slug end end def edit_second_geo_slug @second_geo_slug = SecondGeoSlug.find(params[:id]) end def update_second_geo_slug @second_geo_slug = SecondGeoSlug.find(params[:id]) if @second_geo_slug.update_attributes(params[:second_geo_slug]) redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully edited!' else render :edit_second_geo_slug end end def destroy_second_geo_slug SecondGeoSlug.destroy(params[:id]) redirect_to admin_article_slug_settings_path, :notice => 'Geo Slug succesfully deleted!' end end
class Formula attr_reader :result, :operations def initialize(operations) @operations = operations end def text @operations.map(&:text).join(" \n ") end def result @operations.last.result end def difficulty if @operations.length > 0 FormulaDifficultyCalculator.new(self).difficulty else nil end end end class Constant def initialize(value) @value = value end def value if @value.is_a?(Operation) @value.result else @value end end end class Operation attr_reader :constant1, :constant2, :operator def initialize(operator, constant1, constant2) @operator = operator @constant1 = constant1 @constant2 = constant2 end def text "#{@constant1.value} #{@operator} #{@constant2.value}" end def result @constant1.value.send(@operator, @constant2.value) end end
require 'open-uri' class SMSGateway def self.send(number, code) Resque.after_fork = Proc.new do Rails.logger.auto_flushing = true end log = Logger.new 'log/sms.log' msg = URI.encode("Hello. Your Photobook verification code is: " + code.to_s) uri = 'http://smsc.ru/sys/send.php?login=' + APP_CONFIG['smsc_login'] + '&psw=' + APP_CONFIG['smsc_pw'] + '&phones=' + number + '&mes=' + msg open(uri) log.debug("Sending sms verification code to " + number) end end
class LanguagesController < ApplicationController def index @languages = Language.all end def show @language = Language.find(params[:id]) @lessons = Lesson.where(language_id: @language.id) end end
require "spec_helper" feature "TimeEntries" do let!(:user){ FactoryGirl.create(:user) } let!(:entry){ FactoryGirl.create(:time_entry, loggable_id: user.id) } before(:each) do visit new_user_session_path fill_in "user_username", with: user.username fill_in "user_password", with: user.password click_button "Sign in" end scenario "User deletes a time entry", js: true do visit time_entries_path save_screenshot("/tmp/testingpoop.png") find('.work_entry-delete-btn').trigger('click') click_button "Delete" expect(page).to have_text("Your Timesheet") expect(TimeEntry.count).to eql 0 end end
class AddVideoUrlToRefineryNewsletterPosts < ActiveRecord::Migration def change add_column :refinery_newsletter_posts, :video_url, :integer end end
class Supplier < ApplicationRecord has_one :account, autosave: true end
class Playlist def initialize(name) @name = name @movies = [] end def add_movie(movie) @movies << movie end def roll_die rand(1..6) end def play puts "#{@name}'s PLAYLIST" @movies.each do |movie| case roll_die when 1..2 movie.thumbs_down puts "#{movie.title} wurde gedownt." when 3..4 puts "#{movie.title} wurde nix gemacht" else movie.thumbs_up puts "#{movie.title} wurde geupt." end puts movie end end def to_s @movies.size.to_s end end
class RegistersController < ApplicationController def new @user = User.find_by(id: params[:id]) @register = Register.new end def create @user = User.find_by(register_params) @register = Register.new(register_params.merge(user_id: @user.id)) @register.save end private def register_params params.require(:register).permit(:public_uid) end end
module Entities class Event < Grape::Entity expose :id expose :title expose :details expose :place expose :date expose :hour end end
UserTwoFactorAuthenticationMutation = GraphQL::Relay::Mutation.define do name 'UserTwoFactorAuthentication' input_field :id, !types.Int input_field :password, !types.String input_field :qrcode, types.String input_field :otp_required, types.Boolean return_field :success, types.Boolean return_field :user, UserType resolve -> (_root, inputs, _ctx) { user = User.where(id: inputs[:id]).last if user.nil? || User.current.id != inputs[:id] raise ActiveRecord::RecordNotFound else options = { otp_required: inputs[:otp_required], password: inputs[:password], qrcode: inputs[:qrcode]} user.two_factor=(options) { success: true , user: user.reload } end } end
require 'pp' require_relative 'RegionsParser' module Oneirros module Scrap2 class RegionsProcessor < RegionsParser def initialize(fetcher, mongo) @fetcher = fetcher @mongo = mongo super() end def run() page = @fetcher.fetch('http://rivalregions.com/info/regions') data = self.parse(page) data.each { |region| @mongo[:regions].replace_one( { 'regionid': region["regionid"] }, region, { 'upsert': true } ) unless region["regionid"].nil? @mongo[:regions].update_one( { 'regionid': region["regionid"] }, { :$currentDate => { :updated => true } } ) } end end end end