text
stringlengths
10
2.61M
class ImageCropper def self.enabled? Danbooru.config.aws_sqs_cropper_url.present? end def self.notify(post) if post.is_image? sqs = SqsService.new(Danbooru.config.aws_sqs_cropper_url) sqs.send_message("#{post.id},https://#{Danbooru.config.hostname}/data/#{post.md5}.#{post.file_ext}") end end end
module ApplicationHelper # Возвращает полный заголовок зависящий от страницы # Документирующий комментарий def full_title(page_title) # Определение метода base_title = "Галант | Установка винеонаблюдения и видеодомофонов" # Назначение переменной if page_title.empty? # Булевый тест base_title # Явное возвращение else "#{page_title} | #{base_title}" # Интерполяция строки end end def hidden_div_if(condition, attributes = {}, &block) attributes["class"] = "list-group-item" if condition attributes["style"] = "display: none" end content_tag("div", attributes, &block) end def form_user_text(str) sanitize(str.gsub("\r\n", "<br>"), tags: %w(br)) end def index_info_list Info.order(:created_at) end end
class RecordpnyttsController < ApplicationController before_action :set_recordpnytt, only: [:show, :edit, :update, :destroy] # GET /recordpnytts # GET /recordpnytts.json def index @recordpnytts = Recordpnytt.all end # GET /recordpnytts/1 # GET /recordpnytts/1.json def show end # GET /recordpnytts/new def new @recordpnytt = Recordpnytt.new end # GET /recordpnytts/1/edit def edit end # POST /recordpnytts # POST /recordpnytts.json def create @recordpnytt = Recordpnytt.new(recordpnytt_params) respond_to do |format| if @recordpnytt.save format.html { redirect_to @recordpnytt, notice: 'Recordpnytt was successfully created.' } format.json { render :show, status: :created, location: @recordpnytt } else format.html { render :new } format.json { render json: @recordpnytt.errors, status: :unprocessable_entity } end end end # PATCH/PUT /recordpnytts/1 # PATCH/PUT /recordpnytts/1.json def update respond_to do |format| if @recordpnytt.update(recordpnytt_params) format.html { redirect_to @recordpnytt, notice: 'Recordpnytt was successfully updated.' } format.json { render :show, status: :ok, location: @recordpnytt } else format.html { render :edit } format.json { render json: @recordpnytt.errors, status: :unprocessable_entity } end end end # DELETE /recordpnytts/1 # DELETE /recordpnytts/1.json def destroy @recordpnytt.destroy respond_to do |format| format.html { redirect_to recordpnytts_url, notice: 'Recordpnytt was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_recordpnytt @recordpnytt = Recordpnytt.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def recordpnytt_params params.require(:recordpnytt).permit(:ticket_id, :n1, :n2, :siglas, :monto) end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module FilesystemTargetTree class File < ::TreeItem def initialize(file, snapshot, log) @file, @snapshot, @log = file, snapshot, log super(@file.id.to_s, :name => @file.filename, :partial_name => 'browse_file', :expanded => false) end def set_snapshot(snapshot) @snapshot = snapshot @log = @file.log_for_snapshot(@snapshot) end def file_type @log.file_type end def size @log.remote_size end def mtime @log.mtime end def btime @log.btime end def error @log.error end end end
require('rspec') require('contacts') require('email') describe('Email') do describe('#address') do it("returns the email address of the contact") do test_email = Email.new("johnsmith@123.com", "work") expect(test_email.address()).to(eq("johnsmith@123.com")) end end describe('#type') do it("returns the type of email address of the contact") do test_email = Email.new("johnsmith@123.com", "work") expect(test_email.type()).to(eq("work")) end end describe('.all') do it("is empty at first") do expect(Email.all()).to(eq([])) end end describe('#save') do it("adds an email to the array of saved emails") do test_email = Email.new("johnsmith@123.com", "work") test_email.save() expect(Email.all()).to(eq([test_email])) end end describe('.clear') do it("empties all of the saved emails") do Email.new("johnsmith@123.com", "work").save() Email.clear() expect(Email.all()).to(eq([])) end end end
Given(/^I login with single account and select specified transaction "([^"]*)" and dispute using i do not recognize a charge reason$/) do |txn_to_select| visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:dispute_single_disputable_ods) #dispute_single_DNR_charge username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end @authenticated = on(DisputesPage).is_summary_shown? if @authenticated[0] == false fail("#{@authenticated[1]}" "--" "#{@authenticated[2]}") end visit(TransactionsDetailsPage) on(DisputesPage) do |page| page.search_for_valid_disputable_txn_iteratively @matching_transaction_id, @txn_details = page.selected_txn_index_value(txn_to_select) page.click_on_file_a_dispute_link(@matching_transaction_id) page.wait_for_disputes_page end #on(DisputesPage).reason_option_selection = 'I am still being charged for something I cancelled' end When(/^the surcharge and disputed amount fields are selected$/) do # on(DisputesPage).disputed_amount = @txn_details['transaction_amount'].delete('$').to_f on(DisputesPage).disputed_amount = '0.01' puts on(DisputesPage).disputed_amount on(DisputesPage).surcharge_radio_yes_option_selected?.should be false # on(DisputesPage).select_surcharge_radio_yes_option on(DisputesPage).surcharge_radio_no_option_selected?.should be false on(DisputesPage).select_surcharge_radio_no_option on(DisputesPage).surcharge_radio_no_option_selected?.should be true end And(/^"([^"]*)" dispute reason is selected$/) do |arg| puts "time before the reason selection #{Time.now}" on(DisputesPage).disable_menu_option puts "time after menu disabled#{Time.now}" on(DisputesPage).reason_option_selection = arg puts "time after reason selected#{Time.now}" end Then(/^the page will display the 'Do you have more than one transaction you do not recognize\?' question$/) do puts on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.text on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.text.should == "Do you have more than one transaction you do not recognize?" on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_yes_selected?.should be false on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_no_selected?.should be false end And(/^the Submit button is not displayed$/) do puts on(DisputesPage).text.should_not include "Submit" #.should be false #on(DisputesPage).submit_button end And(/^select the "([^"]*)" option$/) do |arg| if arg == 'No' on(DisputesPage).select_do_you_have_more_than_one_transaction_you_do_not_recognize_response_no on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_no_selected?.should be true elsif arg == 'Yes' on(DisputesPage).select_do_you_have_more_than_one_transaction_you_do_not_recognize_response_yes on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_yes_selected?.should be true end end Then(/^the "([^"]*)" text area is displayed with a (\d+) characters remaining counter$/) do |arg1, arg2| puts on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_question_element.text on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_question_element.text.should == arg1 puts on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_characters_remaining puts arg2 end And(/^the submit button is displayed$/) do on(DisputesPage).submit_button_element.visible?.should be true end And(/^text is entered into the "([^"]*)" text area$/) do |arg| on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_question_response = arg sleep(4) end And(/^the Submit button is clicked$/) do on(DisputesPage).submit_button_element.visible?.should be true on(DisputesPage).submit_button end Then(/^the Confirmation page is displayed$/) do on(DisputesConfirmationPage).wait_for_disputes_confirmation_page # puts on(DisputesConfirmationPage).page_title on(DisputesConfirmationPage).disputes_confirmation_title.should == data_for(:disputes_confirmation_page)['confirmation_page_title'] on(DisputesConfirmationPage).thank_you_text.should == data_for(:disputes_confirmation_page)['success_confirmation_text'] on(DisputesConfirmationPage).what_happens_next.should == data_for(:disputes_confirmation_page)['confirmation_whats_next'] on(DisputesConfirmationPage).confirmation_text_additional_text_element.text.gsub!(/\s+/, ' ').should == data_for(:disputes_confirmation_page)['whats_next_additional_text'] on(DisputesConfirmationPage).thanks.should == data_for(:disputes_confirmation_page)['thanks_for_the_business'] on(DisputesConfirmationPage).return_to_transactions_element.text.should == data_for(:disputes_confirmation_page)['retrun_to_transactions_button_text'] end And(/^the error text will no longer display$/) do pending end Then(/^the page will display an error stating "([^"]*)"Please describe your attempt to resolve this dispute with the merchant"([^"]*)"$/) do |arg1, arg2| pending end Then(/^the page will display the Call Us text$/) do on(DisputesPage).call_us_text.gsub!(/\s+/, ' ').should include data_for(:call_us_text)['call_us_text_message'] puts on(DisputesPage).call_us_text on(DisputesPage).billing_rights_summary_link on(BillingRightsSummaryPage).wait_until_billingrightssummarypage on(BillingRightsSummaryPage) do |page| page.attach_to_current_window(on(DisputesPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_title'].gsub!(/\s+/, ' ')) page.title.should include on(DisputesPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_title'].gsub!(/\s+/, ' ') end #puts on(BillingRightsSummaryPage).billing_rights_summary_page_heading.gsub!(/\s+/, ' ') #puts on(BillingRightsSummaryPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_heading'].gsub!(/\s+/, ' ') on(BillingRightsSummaryPage).billing_rights_summary_page_heading.gsub!(/\s+/, ' ').should eq on(BillingRightsSummaryPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_heading'].gsub!(/\s+/, ' ') end Then(/^the Call Us text will be displayed with the potential fraud message for the first paragraph$/) do on(DisputesPage).call_us_text_DNR.gsub!(/\s+/, ' ').should include data_for(:call_us_text_DNR)['call_us_text_message_DNR_potentialfraud'] puts on(DisputesPage).call_us_text_DNR end And(/^the Submit button will no longer be displayed$/) do puts on(DisputesPage).text.include?("Cancel") end Then(/^the page will display the 'Do you have more than one transaction you do not recognize\?' radio selection with 'Yes' and 'No' options$/) do puts on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.text on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.text.should == "Do you have more than one transaction you do not recognize?" on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_yes_selected?.should be false on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_no_selected?.should be false end Then(/^tab through the 'Yes' and 'No' options without making a selection$/) do # on(DisputesPage).reason_option_selection # # on(DisputesPage).find_element(:id, "not_recognized_radio_more_yes").send_keys :tab # sleep(4) # on(DisputesPage).find_element(:id, "not_recognized_radio_more_no").send_keys :tab # sleep(4) on(DisputesPage).select_do_you_have_more_than_one_transaction_you_do_not_recognize_response_yes # # sleep(4) # on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_response_no send_keys :tab # sleep(4) end Then(/^the page will display an error stating on top of the field label$/) do puts on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_error puts on(DisputesPage).please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_error.should == data_for(:i_do_not_recognize_this_charge_error_text)['please_describe_your_attempt_to_resolve_this_dispute_with_the_merchant_did_not_recognize_charge_error_text'] end And(/^click the submit button without filling in the 'Please describe your attempt to resolve this dispute with the merchant' text area$/) do on(DisputesPage).submit_button_element.visible?.should be true on(DisputesPage).submit_button end And(/^Click on Billing rights summary link takes the user to www page$/) do on(DisputesPage).billing_rights_summary_link on(BillingRightsSummaryPage) do |page| page.attach_to_current_window(on(DisputesPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_title'].gsub!(/\s+/, ' ')) page.title.should include on(DisputesPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_title'].gsub!(/\s+/, ' ') end on(BillingRightsSummaryPage).billing_rights_summary_page_heading.gsub!(/\s+/, ' ').should eq on(BillingRightsSummaryPage).data_for(:billing_rights_summary_page_details)['billing_rights_summary_heading'].gsub!(/\s+/, ' ') end And(/^I fill in the data for 'I do not recognize this charge' option$/) do on(DisputesPage).dispute_reason_questions_date('i_do_not_recognize_this_charge_default_data_response', ) end And(/^I fill in all the fields, except "([^"]*)" for dispute reason 'I do not recognize this charge' dispute reason$/) do |exclude_this_field_data| DataMagic.load 'disputes.yml' p @questions, @field_type, @response_ids, @error_ids, @id_values= on(DisputesPage).i_do_not_recognize_this_charge(exclude_this_field_data) on(DisputesPage).dispute_reason_questions_date('i_do_not_recognize_this_charge_default_data_response', @response_ids) end Then(/^I should fill in the data for the missing field\(s\) "([^"]*)" for dispute reason 'I do not recognize this charge' dispute reason$/) do |fill_in_data_for_the_following_fields| DataMagic.load 'disputes.yml' default_data = data_for(:default_data_based_on_field_type_on_disputes_page) @questions_to_fill, @field_type_to_fill, @response_ids_to_fill, @error_ids_to_not_shown, @id_values_to_not_shown = on(DisputesPage).i_do_not_recognize_this_charge(fill_in_data_for_the_following_fields) if @questions_to_fill.nil? puts "There are no questions to fill" else number_of_questions_to_fill = @questions_to_fill.size (0..number_of_questions_to_fill).each do |question_index| field_type = @field_type_to_fill[question_index] @page_element, @type = on(DisputesPage).fill_in_fields_based_on_field_type(field_type, question_index, @response_ids_to_fill,@error_ids_to_not_shown ) case @type when @type = 'numeric' on(DisputesPage).send("#{@page_element}"+"=",default_data['numeric']) when @type = 'radio' on(DisputesPage).send("select_#{@page_element}") when @type = 'text' on(DisputesPage).send("#{@page_element}"+"=",default_data['text']) when @type = 'date' on(DisputesPage).send("#{@page_element}"+"=",default_data['date_us']) when @type = 'checkbox' on(DisputesPage).send("check_#{@page_element}") end end end end And(/^I should not see the error message for the fields we filled in$/) do number_of_questions_to_fill = @questions_to_fill.size (0..number_of_questions_to_fill).each do |question_index| field_type = @field_type_to_fill[question_index] @error_text_to_exclude, @error_ids_to_exclude, @id_values_to_exclude = on(DisputesPage).error_message_string_should_not_be_displayed_for_these_fields(field_type, question_index, @questions_to_fill,@error_ids_to_not_shown,@id_values_to_not_shown ) error_string = @error_ids_to_exclude.to_s id_values_for_errors = @id_values_to_exclude.to_s on(DisputesPage).check_for_id_on_disputes_page(id_values_for_errors) end sleep(10) end Then(/^I should see the error message for the left over fields after populating some of the missing field\(s\) "([^"]*)" for 'I do not recognize this charge' reason$/) do |left_over_fields_that_are_not_populated| DataMagic.load 'disputes.yml' default_data = data_for(:default_data_based_on_field_type_on_disputes_page) @questions_not_populated, @field_type_not_populated, @response_ids_not_populated, @error_ids_not_populated, @id_values_not_populated = on(DisputesPage).i_do_not_recognize_this_charge(left_over_fields_that_are_not_populated) p number_of_questions_not_populated = @questions_not_populated.size.to_i iterate_through_missing_questions = number_of_questions_not_populated -1 (0..iterate_through_missing_questions).each do |question_index| p question_index field_type = @field_type_not_populated[question_index] @error_text_to_exclude, @error_ids_to_exclude, @id_values_to_exclude = on(DisputesPage).error_message_string_should_not_be_displayed_for_these_fields(field_type, question_index, @questions_not_populated,@error_ids_not_populated,@id_values_not_populated ) puts error_string = @error_ids_to_exclude.to_s puts id_values_for_errors = @id_values_to_exclude.to_s p on(DisputesPage).error_message_string_for_missing_data(field_type, question_index, @questions_not_populated,@error_ids_not_populated ).should == on(DisputesPage).check_for_id_on_disputes_page(id_values_for_errors) end end
class CreateEntryActions < ActiveRecord::Migration def self.up create_table :entry_actions do |t| t.references :entry, :null => false t.references :by, :null => false t.string :action, :null => false t.timestamps end end def self.down drop_table :entry_actions end end
#!/usr/bin/env ruby # http://adventofcode.com/2017/day/1 # # The captcha requires you to review a sequence of digits (your puzzle # input) and find the sum of all digits that match the next digit in # the list. The list is circular, so the digit after the last digit is # the first digit in the list. # # For example: # # 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches # the second digit and the third digit (2) matches the fourth digit. # # 1111 produces 4 because each digit (all 1) matches the next. # # 1234 produces 0 because no digit matches the next. # # 91212129 produces 9 because the only digit that matches the next one # is the last digit, 9. require 'pry' def sum_seq(input_str, answer) data = input_str.split('') total = 0 i = 0 data.each do |cur_ch| if cur_ch == data[i+1] #puts "Cur #{cur_ch} idx #{i}" total += cur_ch.to_i end i += 1 end if data[0] == data[-1] total += data[0].to_i end puts "Total #{total} Answer #{answer} input #{input_str[0..40]}" end def sum_seq2(input_str, answer) look_ahead = input_str.length/2 data = input_str.split('') total = 0 i = 0 data.each do |cur_ch| if cur_ch == data[i+look_ahead] #puts "Cur #{cur_ch} idx #{i}" total += cur_ch.to_i*2 end i += 1 # binding.pry break if i > input_str.length/2 end # if data[0] == data[-1] # total += data[0].to_i # end puts "Total #{total} Answer #{answer} input #{input_str[0..40]}" end def read_input(file_name, method) file = File.open(file_name) input_data = file.read input_data.each_line do |line| next if line.start_with?('#') next if line.chomp.empty? (input, answer) = line.chomp.split('=') raise if input.nil? input.strip! if answer.nil? answer = '?' else answer.strip! end if method.nil? puts "No method. Answer #{answer} input #{input[0..40]}" else send(method, input, answer) end end end file_name = 'aoc_1_2017_data1.txt' read_input(file_name, :sum_seq) file_name = 'aoc_1_2017_data2.txt' read_input(file_name, :sum_seq2)
Write a method that takes a String as an argument, and returns a new String that contains the original value using a staggered capitalization scheme in which every other character is capitalized, and the remaining characters are lowercase. Characters that are not letters should not be changed, but count as characters when switching between upper and lowercase. Example: staggered_case('I Love Launch School!') == 'I LoVe lAuNcH ScHoOl!' staggered_case('ALL_CAPS') == 'AlL_CaPs' staggered_case('ignore 77 the 444 numbers') == 'IgNoRe 77 ThE 444 NuMbErS' Question: Write a method that takes a string and returns a new string that contains the original value using a staggered capitalization scheme where every other character is capitalized and remaining characters are lowercase. Clarification: 1) spaces count as characters in the staggering scheme Input vs Output: Input: string Output: new string Explicit vs Implicit Rules: Explicit: 1) letters should be uppercase / lowercase (alternates) 2) Spaces and non characters count as upper case and lower case counter Implicit: N/A Algorithm: staggered_case method 1) initialize variable 'result' with empty array 2) invoke chars method on string input, which would create an array of characters and non-characters 3) in the same line of code, invoke each_with_index 4) if index.even? or index % 2 == 0 a. result << char.upcase else b. result << char.downcase 5) result.join('') def staggered_case(string) result = [] string.chars.each_with_index do |letter, idx| if idx % 2 == 0 result << letter.upcase else result << letter.downcase end end result.join('') end p staggered_case('I Love Launch School!') == 'I LoVe lAuNcH ScHoOl!' p staggered_case('ALL_CAPS') == 'AlL_CaPs' p staggered_case('ignore 77 the 444 numbers') == 'IgNoRe 77 ThE 444 NuMbErS'
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) user = User.create!( email: 'admin@example.com', first_name: 'admin', last_name: 'system', password: 'supersecret', password_confirmation: 'supersecret', two_factor_secret: 'v6nasf4kfe45qxbq' ) puts 'Created `admin` user:' puts "Email: #{user.email}" puts "Password: #{user.password}" puts puts "Google Authenticator time based two_factor_secret (spaces optional): #{user.two_factor_secret.scan(/.{4}/).join(' ')}" puts
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'pages#home' get 'about', to: 'pages#home' get 'app/tasks', to: 'pages#app' get 'app/tasks/tags/:tagId', to: 'pages#app' resources :tasks, except: [:new, :edit, :show] resources :categories, except: [:new, :edit, :show] end
class RenamePriorityTicket < ActiveRecord::Migration def change rename_column :tickets, :priority, :ticket_priority_id end end
# Ruby notes: # Ruby is an Object Oriented Programming lanaguage. Code is organized in classes and objects which allow applications to access methods and variables across the application in an organized and intuitive way. (think russian doll) # The word 'object is an abstraction of thought - # In code, an object is defined in a partcular way but is not prescripting. Its made up of methods and values. # For example an object Pipe could contain values for length, diameter, material, manufacturer, etc, and also methods that are performed on that data. # "An object in code is a thing with all the data and all the logic required to complete a task" # Ruby comes with Integer, String, Array, Hash which are all types of Objects. We can create our own unique Objects with the class keyword def greet name, name2 puts "Hello, #{name} and #{name2} how are you all doing today?" end greet 'Lydia', 'Meredith' class DogClass end # on the dog class we call the .new method that will instantiate a new dog fido = DogClass.new
json.array!(@sales) do |sale| json.(sale, :id, :created_at, :value) json.entries do json.array!(sale.sale_entries) do |sale_entry| json.(sale_entry, :id, :price_at_date, :quantity) json.product do json.extract! sale_entry.product, :id, :name end end end end
feature "Installation page" do background do visit "/" end scenario "shows preconditions" do expect(page).to have_content("Files can be written and deleted on your server") expect(page).to have_content("GD PHP extension is installed and supports the required filetypes") expect(page).to have_content("DBA PHP extension is installed and supports an acceptable handler") end scenario "takes initial configuration" do fill_in "admin_password", with: "admin" # Only filling-in fields that need # to be changed for tests click_button "Install" expect(page).to have_current_path("/index.php") expect(page).to_not have_content("installation") end end
# -*- encoding: utf-8 -*- require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "IO#readline" do it "returns the next line on the stream" do testfile = File.dirname(__FILE__) + '/fixtures/gets.txt' f = File.open(testfile, 'r') do |f| f.readline.should == "Voici la ligne une.\n" f.readline.should == "Qui è la linea due.\n" end end it "goes back to first position after a rewind" do testfile = File.dirname(__FILE__) + '/fixtures/gets.txt' f = File.open(testfile, 'r') do |f| f.readline.should == "Voici la ligne une.\n" f.rewind f.readline.should == "Voici la ligne une.\n" end end it "is modified by the cursor position" do testfile = File.dirname(__FILE__) + '/fixtures/gets.txt' f = File.open(testfile, 'r') do |f| f.seek(1) f.readline.should == "oici la ligne une.\n" end end it "raises EOFError on end of stream" do testfile = File.dirname(__FILE__) + '/fixtures/gets.txt' File.open(testfile, 'r') do |f| lambda { while true; f.readline; end }.should raise_error(EOFError) end end it "raises IOError on closed stream" do lambda { IOSpecs.closed_file.readline }.should raise_error(IOError) end it "assigns the returned line to $_" do File.open(IOSpecs.gets_fixtures, 'r') do |f| IOSpecs.lines.each do |line| f.readline $_.should == line end end end it "accepts a separator" do path = tmp("readline_specs") begin File.open(path, "w") do |f| f.print("A1\nA2\n\nB\nC;D\n") end File.open(path, "r") do |f| f.readline("\n\n").should == "A1\nA2\n\n" f.readline.should == "B\n" f.readline(";").should == "C;" f.readline.should == "D\n" lambda { f.readline }.should raise_error(EOFError) end ensure File.unlink(path) end end end
# frozen_string_literal: true require 'spec_helper' require 'param/secure_auth_header' module Uploadcare RSpec.describe Param::SecureAuthHeader do subject { Param::SecureAuthHeader } describe 'signature' do before(:each) do allow(Time).to receive(:now).and_return(Time.parse('2017.02.02 12:58:50 +0000')) Uploadcare.config.public_key = 'pub' Uploadcare.config.secret_key = 'priv' end it 'returns correct headers for complex authentication' do headers = subject.call(method: 'POST', uri: '/path', content_type: 'application/x-www-form-urlencoded') expected = '47af79c7f800de03b9e0f2dbb1e589cba7b210c2' expect(headers[:Authorization]).to eq "Uploadcare pub:#{expected}" end end end end
class CustomerCard < ActiveRecord::Base has_secure_password has_many :pendings has_many :claimed_rewards end
module WaterBan::Addresses class AddressesController < WaterBan::Addresses::ApplicationController def index view ::Address::Cell::Index, addresses end private def address @address ||= WaterBan::Addresses::Address.find(params[:id]) end def addresses @addresses ||= WaterBan::Addresses::Address.last(5) end def address_params params.require(:address).permit(:name) end end end
class TareasController < ApplicationController before_action :set_tarea, except: [:index,:new,:create] before_action :authenticate_usuario!, except: [:index,:show] #get tareas/ def index @tareas= Tarea.all #select * from tareas #llamar vista views/tareas/index.html.erb end #get tareas/:id def show @comentario= Comentario.new #select * from tareas where id= :id #llamar vista views/tareas/show.html.erb end #get tareas/new def new @tarea = Tarea.new #llamar vista views/tareas/new.html.erb end #post tareas/ def create @tarea = current_usuario.tareas.new(tarea_params) #@tarea = Tarea.new(tarea_params) #@tarea.usuario_id= current_usuario.id if @tarea.save TareasMailer.notify(@tarea,current_usuario).deliver_now #TareasMailer.notify(@tarea,current_usuario).deliver_later # rake jobs:workoff #insert into tareas(titulo,descripcion,usuario_id) values(:titulo,:descripcion, current_usuario.id) redirect_to @tarea #redirigiendo a show usando como parametro el id que se acabo #de crear else render :new #renderiza nuevamente la vista new(formulario) end end #delete tareas/:id def destroy @tarea.destroy #delete from tareas where id= :id redirect_to tareas_path end #get tareas/:id/edit def edit end #patch tareas/:id def update if @tarea.update(tarea_params) #update tareas set titulo= :titulo, descripcion= :descripcion where id= :id redirect_to @tarea else render :edit end end private def tarea_params params.require(:tarea).permit(:titulo,:descripcion) end def set_tarea @tarea = Tarea.find(params[:id]) end end
class CustomerName < ActiveRecord::Base include Lookup DOS = { code: 'DOS', label: 'US Department of State' } USDT = { code: 'USDT', label: 'US Department of Treasury' } DOD = { code: 'DOD', label: 'US Department of Defense' } DOJ = { code: 'DOJ', label: 'US Department of Justice' } DOI = { code: 'DOI', label: 'US Department of Interior' } DOA = { code: 'DOA', label: 'US Department of Agriculture' } DOC = { code: 'DOC', label: 'US Department of Commerce' } DOL = { code: 'DOL', label: 'US Department of Labor' } DHHS = { code: 'DHHS', label: 'US Department of Health and Human Services' } HUD = { code: 'HUD', label: 'US Department of Housing and Urban Development' } DOT = { code: 'DOT', label: 'US Department of Transportation' } DOE = { code: 'DOE', label: 'US Department of Energy' } DOED = { code: 'DOED', label: 'US Department of Education' } DVA = { code: 'DVA', label: 'US Department of Veteran Affairs' } DHS = { code: 'DHS', label: 'US Department of Homeland Security' } INTEL = { code: 'INTEL', label: 'US Intelligence Community' } OMB = { code: 'OMB', label: 'Office of Management and Budget' } EPA = { code: 'EPA', label: 'Environmental Protection Agency' } SBA = { code: 'SBA', label: 'Small Business Administration' } JCOS = { code: 'JCOS', label: 'Joint Chiefs of Staff' } ARMY = { code: 'ARMY', label: 'United States Army' } NAVY = { code: 'NAVY', label: 'United States Navy' } AIRFORCE = { code: 'AIRFORCE', label: 'United States Air Force' } MARINE = { code: 'MC', label: 'United States Marine Corps' } NORTHCOM = { code: 'NORTHCOM', label: 'US Northern Command' } SOUTHCOM = { code: 'SOUTHCOM', label: 'US Southern Command' } CENTCOM = { code: 'CENTCOM', label: 'US Central Command' } EUCOM = { code: 'EUCOM', label: 'US European Command' } PACOM = { code: 'PACOM', label: 'US Pacific Command' } AFRICOM = { code: 'AFRICOM', label: 'US Africa Command' } STRATCOM = { code: 'STRATCOM', label: 'US Strategic Command' } SOCOM = { code: 'SOCOM', label: 'US Special Operations Command' } TRANSCOM = { code: 'TRANSCOM', label: 'US Transportation Command' } COAST = { code: 'COAST', label: 'US Coast Guard' } ODNI = { code: 'ODNI', label: 'Office of the Director of National Intelligence' } CIA = { code: 'CIA', label: 'Central Intelligence Agency' } CGI = { code: 'CGI', label: 'Coast Guard Intelligence' } HSI = { code: 'HSI', label: 'Homeland Security Investigations' } INR = { code: 'INR', label: 'Bureau of Intelligence and Research' } TFI = { code: 'TFI', label: 'Office of Terrorism and Financial Intelligence' } DIA = { code: 'DIA', label: 'Defense Intelligence Agency' } NSA = { code: 'NSA', label: 'National Security Agency' } NGA = { code: 'NGA', label: 'National Geospatial-Intelligence Agency' } NRO = { code: 'NRO', label: 'National Reconnaissance Office' } CYBERCOM = { code: 'CYBERCOM', label: 'US Cyber Command' } AFISRA = { code: 'AFISRA', label: 'Air Force Intelligence, Surveillance and Reconnaissance Agency' } NASIC = { code: 'NASIC', label: 'National Air and Space Intelligence Center' } INSCOM = { code: 'INSCOM', label: 'United States Army Intelligence and Security Command' } NGIC = { code: 'NGIC', label: 'National Ground Intelligence Center' } MCIA = { code: 'MCIA', label: 'Marine Corpse Intelligence Activity' } ONI = { code: 'ONI', label: 'Office of Naval Intelligence' } FBI = { code: 'FBI', label: 'Federal Bureau of Investigation, National Security Branch' } DEA = { code: 'DEA', label: 'Drug Enforcement Administration, Office of National Security Intelligence' } FDIC = { code: 'FDIC', label: 'Federal Deposit Insurance Corporation' } CUSTOMER_NAME_TYPES = [DOS, USDT, DOD, DOJ, DOI, DOA, DOC, DOL, DHHS, HUD, DOT, DOE, DOED, DVA, DHS, INTEL, OMB, EPA, SBA, JCOS, ARMY, NAVY, AIRFORCE, MARINE, NORTHCOM, SOUTHCOM, CENTCOM, EUCOM, PACOM, AFRICOM, STRATCOM, SOCOM, TRANSCOM, COAST, ODNI, CIA, CGI, HSI, INR, TFI, DIA, NSA, NGA, NRO, CYBERCOM, AFISRA, NASIC, INSCOM, NGIC, MCIA, ONI, FBI, DEA, FDIC].freeze end
class AddNotNullToMachineDeploymentsLogField < ActiveRecord::Migration[5.0] def change change_column_null :machine_deployments, :log, false, '' end end
require 'pp' require 'yajl/json_gem' require 'stringio' require 'cgi' module GitHub module Resources module Helpers STATUSES = { 200 => '200 OK', 201 => '201 Created', 202 => '202 Accepted', 204 => '204 No Content', 301 => '301 Moved Permanently', 304 => '304 Not Modified', 401 => '401 Unauthorized', 403 => '403 Forbidden', 404 => '404 Not Found', 409 => '409 Conflict', 422 => '422 Unprocessable Entity', 500 => '500 Server Error' } AUTHORS = { :technoweenie => '821395fe70906c8290df7f18ac4ac6cf' } DefaultTimeFormat = "%B %-d, %Y".freeze def post_date(item) strftime item[:created_at] end def strftime(time, format = DefaultTimeFormat) attribute_to_time(time).strftime(format) end def gravatar_for(login) %(<img height="16" width="16" src="%s" />) % gravatar_url_for(login) end def gravatar_url_for(login) md5 = AUTHORS[login.to_sym] default = "https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" "https://secure.gravatar.com/avatar/%s?s=20&d=%s" % [md5, default] end def headers(status, head = {}) css_class = (status == 204 || status == 404) ? 'headers no-response' : 'headers' lines = ["Status: #{STATUSES[status]}"] head.each do |key, value| case key when :pagination lines << 'Link: <https://api.github.com/resource?page=2>; rel="next",' lines << ' <https://api.github.com/resource?page=5>; rel="last"' else lines << "#{key}: #{value}" end end %(<pre class="#{css_class}"><code>#{lines * "\n"}</code></pre>\n) end def json(key) hash = case key when Hash h = {} key.each { |k, v| h[k.to_s] = v } h when Array key else Resources.const_get(key.to_s.upcase) end hash = yield hash if block_given? %(<pre class="highlight"><code class="language-javascript">) + JSON.pretty_generate(hash) + "</code></pre>" end def text_html(response, status, head = {}) hs = headers(status, head.merge('Content-Type' => 'text/html')) res = CGI.escapeHTML(response) hs + %(<pre class="highlight"><code>) + res + "</code></pre>" end end USER = { "id" => 1, "username" => "someguy7", "email" => "someguy7@example.com", "photo_url" => "http://says.com/photo/someguy7.jpg", "wallet" => "SGD 50", "country" => "sg", "notify_new_specials" => true, "notify_cashout_completed" => true, "invite_url" => "http://says.com/someguy7/invite", "invite_reward" => "SGD1", "minimum_required_referree_earning" => "SGD5", "created_at" => "2012-05-29T10:46:36+08:00", "updated_at" => "2012-05-29T10:46:36+08:00" } SPECIAL = { "id" => 123, "title" => "A really cool specials", "description" => "This is a specials description", "photo_url" => "http://says.com/campaigns/2291/photos/profile/gatsby.jpg", "client_url" => "http://cocacola.com", "total_available_reward" => "SGD1.00", "per_uv_reward" => "SGD0.20", "created_at" => "2012-05-29T10:46:36+08:00", "updated_at" => "2012-05-29T10:46:36+08:00" } SHARE = { "id" => 1234, "unique_visits" => 10, "total_earnings" => "SGD1.20", "url" => "http://sy.my/abc123", "special" => SPECIAL } end end include GitHub::Resources::Helpers
class Sale < ApplicationRecord belongs_to :bill validates :bill_id, presence: true, numericality: {only_integer: true}, on: :create end
class ProposedBooksController < ApplicationController before_action :set_proposed_book, only: [:show, :edit, :destroy, :update] before_action :authenticate_user!, only: [:index, :new, :edit] # GET /proposed_books # GET /proposed_books.json def index @proposed_books = current_user.ProposedBook end def search @ricerca = params['ricerca'] @value = params[:search_book] ascdesc = ' ASC' ord = 'nome' if params['Ordina'] != nil ord = params['Ordina'] if params['AscDesc'] == 'decrescente' ascdesc = ' DESC' end end puts ord + ascdesc @proposed_books = ProposedBook.where([@ricerca + " LIKE ?","%#{@value}%"]).order(ord + ascdesc) end # GET /proposed_books/1 # GET /proposed_books/1.json def show if user_signed_in? @user_books = current_user.ProposedBook.all end end # GET /proposed_books/new def new authorize! :show, ProposedBook @proposed_book = ProposedBook.new end # GET /proposed_books/1/edit def edit authorize! :edit, @proposed_book end # POST /proposed_books # POST /proposed_books.json def create if params[:commit] == 'Salva' @proposed_book = ProposedBook.new(proposed_book_params) respond_to do |format| if @proposed_book.save format.html { redirect_to @proposed_book, notice: 'Proposed book was successfully created.' } format.json { render :show, status: :created, location: @proposed_book } else format.html { render :new } format.json { render json: @proposed_book.errors, status: :unprocessable_entity } end end else require 'open-uri' @data = JSON.parse(URI.parse('https://www.googleapis.com/books/v1/volumes?q=isbn:' + proposed_book_params[:ISBN]).read) if @data['totalItems'] > 0 @b = @data['items'][0]['volumeInfo'] @g = '' if @b.key?('categories') @g = @b['categories'][0] else @g = proposed_book_params[:genere] end p = { 'nome' => @b['title'], 'autore' => @b['authors'][0], 'genere' => @g, 'anno' => @b['publishedDate'], 'stato' => proposed_book_params[:stato], 'ISBN' => proposed_book_params[:ISBN], 'user_id' => proposed_book_params[:user_id]} @proposed_book = ProposedBook.new(p) respond_to do |format| if @proposed_book.save format.html { redirect_to @proposed_book, notice: 'Proposed book was successfully created.' } format.json { render :show, status: :created, location: @proposed_book } else format.html { render :new } format.json { render json: @proposed_book.errors, status: :unprocessable_entity } end end else redirect_to root_path end end end # PATCH/PUT /proposed_books/1 # PATCH/PUT /proposed_books/1.json def update respond_to do |format| authorize! :edit, @proposed_book if @proposed_book.update(proposed_book_update_params) format.html { redirect_to @proposed_book, notice: 'Proposed book was successfully updated.' } format.json { render :show, status: :ok, location: @proposed_book } else format.html { render :edit } format.json { render json: @proposed_book.errors, status: :unprocessable_entity } end end end # DELETE /proposed_books/1 # DELETE /proposed_books/1.json def destroy @proposed_book.destroy respond_to do |format| format.html { redirect_to proposed_books_url, notice: 'Proposed book was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_proposed_book @proposed_book = ProposedBook.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def proposed_book_params params.require(:proposed_book).permit(:nome, :autore, :genere, :stato, :anno, :ISBN, :user_id) end def proposed_book_update_params params.require(:proposed_book).permit(:nome, :autore, :genere, :stato, :anno, :ISBN) end end
class PinType < ActiveRecord::Base attr_accessible :pin_id, :type_id belongs_to :pin belongs_to :type end
require_relative '../test_helper' require 'yaml' def vulnerability_data @vulnerability_data ||= File.read('./test/fixtures/wheezy_vulnerability_data.txt') end def vulnerabilities_fixtures @vulnerabilities_fixures ||= YAML.load_file('./test/fixtures/wheezy_vulnerabilities.yml') end def cve_list_fixtures @cve_list_fixtures ||= YAML.load_file('./test/fixtures/wheezy_cve_list.yml') end describe Bisu::VulnerabilityParser::Debian do describe '#source' do it 'returns the URL ending with the platform name if a platform is specified' do assert Bisu::VulnerabilityParser::Debian.new(platform: Bisu::Platform.new(name: 'foobar')).source =~ /foobar$/ end it 'returns the URL ending with GENERIC if no platform is specified' do assert Bisu::VulnerabilityParser::Debian.new.source =~ /GENERIC$/ end end describe '#parse_vulnerabilities' do it 'returns correctly built objects' do parser = Bisu::VulnerabilityParser::Debian.new(platform: 'wheezy') parser.stub(:vulnerability_data, vulnerability_data) do assert parser.parse_vulnerabilities == vulnerabilities_fixtures end end end describe '#cve_list' do it 'returns a correctly built hash' do parser = Bisu::VulnerabilityParser::Debian.new(platform: 'wheezy') parser.stub(:vulnerability_data, vulnerability_data) do assert parser.send(:cve_list) == cve_list_fixtures end end end end
class CompaniesController < ApplicationController include CompanySupport before_filter :must_view, :only => [:show] before_filter :must_edit, :only => [:update] def show @drinks = @company.drinks @break_room = params.include? "breakroom" end def update if can_edit? and @company.update_attribute(:name, params[:name]) render :inline => @company.name else render :nothing => true, :status => :bad_request end end private end
class Job include ActiveModel::Model attr_accessor :queue, :latency, :strategy def initialize(*attributes) # Default values @queue = "default" @latency = "1000" @strategy = Pause::SLEEP super end def save! LoadedJob.set(queue: queue).perform_later latency: latency, strategy: strategy end end
require 'rails_helper' require 'capybara/rails' require 'capybara/rspec' describe 'Unauthenticated visitor happy path', type: :feature do around(:each) do |example| DatabaseCleaner.start example.run DatabaseCleaner.clean end let(:torta_shop) { FactoryGirl.build(:torta_shop) } let(:lechuga) { FactoryGirl.build(:lechuga) } let(:nba_cares) { FactoryGirl.build(:nba_cares) } let(:hoop) { FactoryGirl.build(:hoop) } before do lechuga.categories << FactoryGirl.build(:category) hoop.categories << FactoryGirl.build(:category) lechuga.save!(validate: false) hoop.save!(validate: false) torta_shop.save!(validate: false) torta_shop.items << lechuga nba_cares.save!(validate: false) nba_cares.items << hoop end context "when visitor visits a business" do it "has list of all suppliers" do visit suppliers_path expect(page).to have_content("Torta's Supplies") end end end
Capistrano::Configuration.instance.load do namespace :deploy do namespace :release do desc "Creatse a REVISION file for the current git hash for use as a 'release version' in the app." task :mark, roles: :app, except: { no_release: true } do run "cd #{current_path} && git rev-parse --short HEAD > REVISION" end after "deploy:finalize_update", "deploy:release:mark" end end end
require 'spec_helper' require 'set' describe Immutable::SortedSet do let(:set) { SS[*values] } let(:comparison) { SS[*comparison_values] } describe '#eql?' do let(:eql?) { set.eql?(comparison) } shared_examples 'comparing something which is not a sorted set' do let(:values) { %w[A B C] } it 'returns false' do expect(eql?).to eq(false) end end context 'when comparing to a standard set' do let(:comparison) { ::Set.new(%w[A B C]) } include_examples 'comparing something which is not a sorted set' end context 'when comparing to a arbitrary object' do let(:comparison) { Object.new } include_examples 'comparing something which is not a sorted set' end context 'when comparing to an Immutable::Set' do let(:comparison) { Immutable::Set.new(%w[A B C]) } include_examples 'comparing something which is not a sorted set' end context 'when comparing with a subclass of Immutable::SortedSet' do let(:comparison) { Class.new(Immutable::SortedSet).new(%w[A B C]) } include_examples 'comparing something which is not a sorted set' end context 'with an empty set for each comparison' do let(:values) { [] } let(:comparison_values) { [] } it 'returns true' do expect(eql?).to eq(true) end end context 'with an empty set and a set with nil' do let(:values) { [] } let(:comparison_values) { [nil] } it 'returns false' do expect(eql?).to eq(false) end end context 'with a single item array and empty array' do let(:values) { ['A'] } let(:comparison_values) { [] } it 'returns false' do expect(eql?).to eq(false) end end context 'with matching single item array' do let(:values) { ['A'] } let(:comparison_values) { ['A'] } it 'returns true' do expect(eql?).to eq(true) end end context 'with mismatching single item array' do let(:values) { ['A'] } let(:comparison_values) { ['B'] } it 'returns false' do expect(eql?).to eq(false) end end context 'with a multi-item array and single item array' do let(:values) { %w[A B] } let(:comparison_values) { ['A'] } it 'returns false' do expect(eql?).to eq(false) end end context 'with matching multi-item array' do let(:values) { %w[A B] } let(:comparison_values) { %w[A B] } it 'returns true' do expect(eql?).to eq(true) end end context 'with a mismatching multi-item array' do let(:values) { %w[A B] } let(:comparison_values) { %w[B A] } it 'returns true' do expect(eql?).to eq(true) end end context 'with the same values, but a different sort order' do let(:set) { SS[1, 2, 3] } let(:comparison) { SS.new([1, 2, 3], &:-@)} it 'returns false' do expect(eql?).to eq(false) end end end end
require 'spec_helper' describe "job_experiences/index" do before(:each) do assign(:job_experiences, [ stub_model(JobExperience, :org_name => "Org Name", :post => "Post", :salary => "9.99", :leave_due_to_work => "MyText", :teacher_id => 1 ), stub_model(JobExperience, :org_name => "Org Name", :post => "Post", :salary => "9.99", :leave_due_to_work => "MyText", :teacher_id => 1 ) ]) end it "renders a list of job_experiences" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Org Name".to_s, :count => 2 assert_select "tr>td", :text => "Post".to_s, :count => 2 assert_select "tr>td", :text => "9.99".to_s, :count => 2 assert_select "tr>td", :text => "MyText".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 end end
# encoding: utf-8 class An < ActiveRecord::Base has_paper_trail :only => [:content], :on=> [:update], :meta => { :user_id => Proc.new { |m| m.updated_by.id }, :summary => Proc.new { |m| m.vsummary if m.changed? && !m.vsummary.blank? } } include Extender::Voteable before_create { self.activity_at = Time.now } STATUS_INACTIVE = 0 STATUS_ACTIVE = 1 STATUS_HIDDEN = 8 STATUS_DELETED = 9 UNRESOLVED = 0 RESOLVED = 1 has_many :comments, :as => :commentable ,:dependent => :destroy has_many :activities,:as => :activityable # never destroy user activities accepts_nested_attributes_for :activities belongs_to :thr belongs_to :user apply_simple_captcha attr_accessor :vsummary, :updated_by attr_accessible :content validates :content, :length => {:within => 20..3000}, :presence => true after_save :set_version_summary after_create :set_subscription scope :active, where(:status => STATUS_ACTIVE) scope :hidden_or_deleted, where(:status => [STATUS_HIDDEN,STATUS_DELETED]) scope :sortable, lambda { |sort=nil| case sort when "oldest" then order("created_at ASC") when "votes" then order("(vote_up + vote_down) DESC") else order("activity_at DESC") end } def resolve if self.thr.resolved? errors.add(:base,:resolved) return false end self.resolved = RESOLVED saved = self.save thr.reload return saved end def unresolve unless self.can_unresolve? errors.add(:base,:unresolved) return false end self.resolved = UNRESOLVED saved = self.save thr.reload return saved end def can_unresolve? self.resolved == RESOLVED && thr.resolved? end def resolved? self.resolved == RESOLVED end def stitle status_string + content end def status_string case self[:status] # when STATUS_ACTIVE then '[active] ' when STATUS_HIDDEN then '[hidden] ' when STATUS_DELETED then '[deleted] ' else '' end end def mark_as_destroy self.status = STATUS_DELETED self.save(:validate => false) end def mark_as_hidden_if_needed if self.activities.flagged.count >= APP_VOTING_CONFIG['flags_to_hide_post'] self.status = STATUS_HIDDEN self.save else self.save end end protected private def set_subscription self.thr.subscriptions.find_or_create_by_user_id(user_id) end def set_version_summary versions.last.update_attributes(:summary => vsummary) if self.changed? && !vsummary.blank? end end
class AddApprovedToUser < ActiveRecord::Migration def change add_column :users, :approved, :boolean, :default => false, :null => false add_index :users, :approved end def self.down delete_column :users, :approved delete_index :users, :approved end end
class AddAppointmentservicesToPractiInfo < ActiveRecord::Migration def change add_column :practi_infos , :appointment_services , :text end end
require 'spec_helper' describe ReviewsController do describe "POST create" do context "with authenticated users" do context "with valid inputs" do it "redirects to the video show page" do video = Fabricate(:video) post :create, review: Fabricate.attributes_for(:review), video_id: video.id expect(response).to redirect_to video end it "creates a review" do video = Fabricate(:video) post :create, review: Fabricate.attributes_for(:review), video_id: video_id expect(Review.count).to eq(1) end it "creates a review associated with the video" it "creates a review associated with the signed in user" end context "with invalid inputs" do end end context "with unauthenticated users" do end end end
require 'webmachine' require 'reel' require 'json' class LiveResource < Webmachine::Resource def initialize set_headers end def set_headers response.headers['Connection'] ||= 'keep-alive' response.headers['Cache-Control'] ||= 'no-cache' end def allowed_methods %W[GET] end def content_types_provided [['text/event-stream', :render_event]] end def render_event Fiber.new do data = JSON.generate(hello: 'world') 10.times do |id| Fiber.yield "id: #{id}\nevent: hello\ndata: #{data}\n\n" sleep 2 end end end end app = Webmachine::Application.new app.routes do add ['live'], LiveResource end app.configure do |config| config.adapter = :Reel end app.run
# frozen_string_literal: true require 'drb/drb' class Client DRb.start_service def self.server DRbObject.new_with_uri(Server::URI) end def self.load_data(filename, data) server.load_data(filename, data) end def self.search(filename, field, target) server.search(filename, field, target) rescue DRb::DRbConnError nil end end
class Book attr_accessor :title def title words_to_ignore = ["and", "the", "in", "of", "a", "an"] input = @title.split(" ") input[0].capitalize! input[1..input.length-1].each{|x| x.capitalize! unless words_to_ignore.include? x} return input.join(" ") end end
#!/usr/bin/env ruby # Convert environment variables into json format output dumped to the console. Its up to the caller # to sort the output appropriately and then use that as input to build-jar.rb # include the "lib" directory File.expand_path(File.join(__dir__, "lib")).tap {|pwd| $LOAD_PATH.unshift(pwd) unless $LOAD_PATH.include?(pwd) } require 'json' require 'optparse' require 'ostruct' @options = OpenStruct.new(all: false) OptionParser.new do |opts| opts.banner = "Usage: setup-env.rb [options]" opts.separator "Setup the input file from environment variables for deploying jars" opts.separator " Options:" opts.on("--deploy-all", "Ignore environment variables and just deploy all the jars. Should be used for == TESTING ==") do |t| @options.all = true end end.parse!(ARGV) require 'environment_settings' include EnvironmentSettings params = [] # Ingest ingest = [] append(ingest,'Ingest_External', "ingest") append(ingest,'Ingest_Raw', "raw") append(ingest,'Ingest_Write', "storage") append(ingest,'Ingest_CleanDynamo', "clean") input = as_input(ingest, "stream", 'Ingest_Source_Dir') params << input unless input.nil? # Schema schema = [] append(schema, 'Schema_Org_Update', "org") append(schema, 'Schema_Metrics_Read', "metrics") metric = [] # this creates a 'name key' of the form "metric-create" append(metric, 'Schema_Metric_Create', "create") append(metric, 'Schema_Metric_Read', "read") append(metric, 'Schema_Metric_Update', "update") append(metric, 'Schema_Metric_Delete', "delete") schema << {"metric" => metric} unless metric.empty? field = [] append(field, 'Schema_Field_Create', "create") append(field, 'Schema_Field_Read', "read") append(field, 'Schema_Field_Update', "update") schema << {"field" => field} unless field.empty? input = as_input(schema, "schema", 'Schema_Source_Dir') params << input unless input.nil? # Schema Internal schema_internal = [] append(schema_internal, 'Internal_Schema_Org_Create', "org") input = as_input(schema_internal, "schema-internal", 'Schema_Source_Dir') params << input unless input.nil? # Batch batch = [] sns = [] append(sns,'Batch_Sns_S3_Local', "local") append(sns,'Batch_Sns_S3_Remote', "remote") batch << {"sns" => sns} unless sns.empty? append(batch,'Batch_Spark_Processor', "processor") append(batch,'Batch_Launch_EMR_Cluster', "launchemr") input = as_input(batch, "batch", 'Batch_Processing_Parent_Dir') params << input unless input.nil? # Meta meta = [] user = [] append(user,'User_Info', "user") meta << {"meta" => user} unless user.empty? tenant = [] append(tenant,'Tenant_Info', "info") append(tenant,'Tenant_Create', "create") meta << {"tenant" => tenant} unless tenant.empty? device = [] append(device,'Device_Mgmt', "devices") append(device,'Device_Key_Mgmt', "keys") meta << {"device" => device} unless device.empty? input = as_input(meta, "meta", 'Meta_Dir') params << input unless input.nil? ## Done! puts "#{JSON.pretty_generate(params)}"
# FamilyMember encapsulates the attributes and behaviors of a Family member. class FamilyMember # can do attr_read and write attr_accessor :name, :sex, :status, :age, :children, :species # like default constructor in java def initialize(name:, sex:, status:, age:, children:, species:) @name = name @sex = sex @status = status @age = age @children = children @species = species || "human" end #methods to check def parent? if @children.empty? == false # return false return true end @species.to_s == 'human' end def child? # @children.empty? # @species.to_s == 'child' @age < 39 end def dad? # parent && male @age.to_i == 40 end # functions as accessor def mom? @children != "SAM" if my_string.to_s.empty? # It's nil or empty end end def son? end def daughter? end def dog? end def human? end end # # notes # # Initializing # arthur = FamilyMember.new(name: 'arthur', sex: 'male', status: 'male', age: 27, children: [], species: 'human') # puts arthur.inspect # pp arthur # puts arthur.age # 27 # ## Since Ruby is not statically typed in the future you'll want to test your # ## classes, making sure to test methods and attribtues # # expect(arthur.age).to eq 27 # # expect(arthur.human?).to eq true # # Inheritance # class Parent < FamilyMember # attr_accessor :children # end # class Mother < Parent # end # class Father < Parent # end # mom = Mother.new # mom.dog? # mom.human?
# params for visits_controller nested attributes module NestedParams attr_reader :diagnoses_attributes, :dissections_attributes, :family_members_attributes, :genetic_tests_attributes, :heart_measurements_attributes, :hospitalizations_attributes, :medications_attributes, :patient_attributes, :procedures_attributes, :tests_attributes, :vitals_attributes def nested_params def diagnoses_attributes Diagnosis.attributes end def dissections_attributes Dissection.attributes end def family_members_attributes FamilyMember.attributes end def genetic_tests_attributes GeneticTest.attributes end def heart_measurements_attributes HeartMeasurement.attributes end def hospitalizations_attributes Hospitalization.attributes end def medications_attributes Medication.attributes end def patient_attributes %i[id primary_diagnosis] end def procedures_attributes Procedure.attributes end def tests_attributes Test.attributes end def vitals_attributes Vital.attributes end end end
require 'helpers/interface' module SortingStrategy extend Interface method :order def initialize container, desc=false unless container.is_a? Enumerable raise "Please provide an array or other Enumerable" end unless (container.all? {|item| item.is_a? Comparable}) raise "All objects must implement Comparable" end end def swap array, i, j array[i], array[j] = array[j], array[i] end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) types = ["hotel", "hostel", "resort", "sleeping bag"] Hotel.destroy_all for i in (1..20) Hotel.create( name: Faker::Company.name, address: Faker::Address.street_address, star_rating: rand(1..5), accomodation_type: types.sample ) end
#!/usr/bin/env ruby # # Read bib file and check the difference for merge # $:.unshift(File.dirname(__FILE__)) require 'bib_library.rb' require 'papers_library.rb' require 'getoptlong' require 'kconv' require 'date' require 'ap' $stdout.set_encoding("EUC-JP", "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.on("--utf-8", "-u", "Set both i/o encoding to UTF-8") {|x| opts[:encoding] = "UTF-8" ; opts[:output_encoding] = opts[:encoding] } o.on("--euc-jp", "-e", "Set both i/o encoding to EUC-JP") {|x| opts[:encoding] = "EUC-JP" ; opts[:output_encoding] = opts[:encoding] } o.on("--sjis", "-s", "Set both i/o encoding to Shift_JIS") {|x| opts[:encoding] = "Shift_JIS" ; opts[:output_encoding] = opts[:encoding] } o.on("--output-utf-8", "Set output encoding to UTF-8") {|x| opts[:output_encoding] = "UTF-8" } o.on("--output-euc-jp", "Set output encoding to EUC-JP") {|x| opts[:output_encoding] = "EUC-JP" } o.on("--output-sjis", "Set output encoding to Shift_JIS") {|x| opts[:output_encoding] = "Shift_JIS" } o.on("--bib-dir", "-B DIR", "Set bib dir (currently ./bib)") {|x| opts[:bib_dir] = x } o.on("--force", "-f", "Force to overwrite files") {|x| opts[:force] = true } o.on("--no-time-stamp", "-t", "don't add bibdump date") {|x| opts[:timestamp] = false } o.on("--write", "-w", "Write out each entries in each file in the output-dir") {|x| opts[:write] = true } o.on("--list", "-l", "List bib cite keys") {|x| opts[:list] = true } 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 # List cite keys. If parameters are given, only list that key if exists if opts[:list] cite_keys.each do |k| puts k if blib.has_key?(k) end # Write out each entries in the dir, elsif opts[:write] marker_lines = [] if opts[:timestamp] marker_lines = [ ", date-written-via-bibdump = {#{DateTime.now.to_s}}" ] end unless File.directory?(opts[:bib_dir]) puts "Directory #{opts[:bib_dir]} does not exists" else cite_keys.each do |c| unless blib.has_key?(c) puts "cite key <#{c}> does not exist" else e = blib[c] file = blib.mkbibpath(c, true) if File.file?(file) and opts[:force] == false puts "File #{file} alrady exists -- don't overwrite" else e.write_to_file(file, opts, marker_lines) end end end end end end end
require 'digest' require 'fileutils' ## # The Buster class provides cache-busting functionality. class Buster attr_reader :files, :map ## # Instantiates a buster, taking an array of +files+ on which to operate on. # Params: # +files+:: an array of files def initialize(files=[]) raise Exception.new("Expect an array, not #{ files } for Buster.new!") if (not files.is_a? Array) @files = files @map = {} end def self.[](directory=".") if (not directory.is_a? Array) && File.directory?(directory_or_files) Buster.new(Dir[File.join(directory_or_files, "**/*.*")]) else raise Exception.new("Expected a directory, not #{ directory } for Buster[]!") end end ## # Create cache-busted versions of the files in the instance. Internally uses an # MD5 digest to create six values which get prepended to a file. As well, # the instance provides a +@map+ attribute, mapping the original filename to the # new busted name. # # +bust+ will delete all previous busted files in the destination before # adding fresh busted files. Optionally, you can provide a +out+ destination where # files will be output, as well as a +preserve_tree+ option which will preserve # copy the origin file into the destination along with its parent folders. # Params: # +out+:: An optional destination for the newly busted files (ALL OTHER BUSTED FILES ARE REMOVED). # +preserve_tree+:: When copying to destination, preserve nested folders. Doesn't do anything if no +out+ is set. # +preserve_original+:: Whether or not to delete the original, non-hashed input files. # TODO: not all busted files should be deleted, only the ones belonging to this instance. def bust(out: nil, preserve_tree: false, preserve_original: true) FileUtils.mkdir_p(out) if out @map = @files.each_with_object({}) do |f, result| hash = Digest::MD5.hexdigest File.read f basename = File.basename f dirname = File.dirname f new_name = hash[0...6] + "_" + basename destination = out ? out : dirname if preserve_tree && destination dirname = out ? path_diff(dirname, out) : dirname destination = File.join(out, dirname) FileUtils.mkdir_p(destination) end # TODO: This will remove a hashed file if it follows the format of # 6letters_anything.css rm_busted(destination) FileUtils.cp f, File.join(destination, new_name) result[basename] = new_name result end FileUtils.rm(@files) if (not preserve_original) return self end ## # Will replace references to the original files in the instance with references # to the busted files the instance has created. This is a fairly slow operation # as it is implemented naively. # Params: # +files+:: An array of files in which to replace references. def replace_in(files=[]) files.each do |f| content = File.read f @map.each do |original, busted| content = content.gsub(/#{ original }/, busted) end File.write f, content end end ## # Checks to see whether a file adheres to our busted file naming rules. These # are defined as 6 lower-case alphanumeric values followed by an underscore. # Params: # +filename+:: filename to check def busted?(filename) f = File.basename(filename) /\A(.*\/)?[a-z0-9]{6}_[a-zA-Z0-9\-_]+\.[a-zA-Z0-9]+\z/.match?(f) end ## # Removes all busted files in a given directory. # Params: # +directory+:: directory to operate on def rm_busted(directory) FileUtils.rm Dir[directory + "/*.*"].select { |f| busted? f } end ## # Utility for ensuring that nested paths, if copied, do not repeat # already-present parent dirs. # Params: # +path1+:: path to make unique # +path2+:: path to subtract def path_diff(path1, path2) File.join(path1.split("/") - path2.split("/")) end end
# frozen_string_literal: true require 'parseline' module Brcobranca module Retorno # Formato de Retorno CNAB 643 class RetornoCbr643 < Base extend ParseLine::FixedWidth # Extendendo parseline fixed_width_layout do |parse| parse.field :agencia_com_dv, 17..21 parse.field :cedente_com_dv, 22..30 parse.field :convenio, 31..37 parse.field :nosso_numero, 63..79 parse.field :tipo_cobranca, 80..80 parse.field :tipo_cobranca_anterior, 81..81 parse.field :natureza_recebimento, 86..87 parse.field :carteira_variacao, 91..93 parse.field :desconto, 95..99 parse.field :iof, 100..104 parse.field :carteira, 106..107 parse.field :comando, 108..109 parse.field :data_liquidacao, 110..115 parse.field :data_vencimento, 146..151 parse.field :valor_titulo, 152..164 parse.field :banco_recebedor, 165..167 parse.field :agencia_recebedora_com_dv, 168..172 parse.field :especie_documento, 173..174 parse.field :data_credito, 175..180 parse.field :valor_tarifa, 181..187 parse.field :outras_despesas, 188..200 parse.field :juros_desconto, 201..213 parse.field :iof_desconto, 214..226 parse.field :valor_abatimento, 227..239 parse.field :desconto_concedito, 240..252 parse.field :valor_recebido, 253..265 parse.field :juros_mora, 266..278 parse.field :outros_recebimento, 279..291 parse.field :abatimento_nao_aproveitado, 292..304 parse.field :valor_lancamento, 305..317 parse.field :indicativo_lancamento, 318..318 parse.field :indicador_valor, 319..319 parse.field :valor_ajuste, 320..331 parse.field :sequencial, 394..399 end end end end
class Office < ActiveRecord::Base has_many :employees default_scope lambda { if $default_office_scope where $default_office_scope end } scope :usa, -> { where(:country => "USA") } end
require "spec_helper" describe AccountsController do describe "routing" do it "routes to #edit" do get("/account").should route_to("accounts#edit") end it "routes PUTs to #update" do put("/account").should route_to("accounts#update") end it "routes PATCHs to #update" do patch("/account").should route_to("accounts#update") end end end
class AddStacheUrlToStaches < ActiveRecord::Migration def change add_column :staches, :stache_url, :string end end
module Enum_status extend ActiveSupport::Concern included do enum status: { run: 0, done: 1, expired: 2 } end end
class AddArticleToGoods < ActiveRecord::Migration def change change_table :goods do |t| t.string :article, null: false, default: '' end end end
class Task attr_reader :title def initialize(title) @title = title # string @done = false # boolean end def mark_as_done! @done = true end def done? @done end end
require 'db/MiqBdb/MiqBdb' require "#{__dir__}/test_files" describe MiqBerkeleyDB::MiqBdb do it "#new" do expect { described_class.new(MiqBdb::TestFiles::RPM_PROVIDE_VERSION).close }.not_to raise_error end it "#pages" do bdb = described_class.new(MiqBdb::TestFiles::RPM_PROVIDE_VERSION) nkeys = 0 bdb.pages do |page| page.keys do |_key| nkeys += 1 end end expect(nkeys).to eq(657) bdb.close end context "Hash Database" do it "validates" do bdb = described_class.new(MiqBdb::TestFiles::RPM_PACKAGES) expect(bdb.db).to be_kind_of(MiqBerkeleyDB::MiqBdbHashDatabase) # Assert that the number of keys in header is what was extracted expect(bdb.db.nkeys).to eq(bdb.size) bdb.close end end end
require 'test_helper' class CreateArticleTest < ActionDispatch::IntegrationTest def setup @password = 'password' @user = User.create( username: 'adam', email: 'adam@gmail.com', password: @password, admin: true ) end test 'unauthenticated users cannot create articles' do get new_article_path assert_redirected_to root_path end test 'invalid article title results in failure' do sign_in_as(@user, @password) assert_no_difference 'Article.count' do post articles_path, article: { title: '' * 100, description: 'gjgadjshagjdafgsjhfdjhsafhjgjhf' } post articles_path, article: { title: 'g', description: 'hghjfhjafdjhfadhjgafahjdfghjafd' } post articles_path, article: { title: 'g' * 100, description: 'gjgadjshagjdafgsjhfdjhsafhjgjhf' } end end test 'invalid article description results in failure' do sign_in_as(@user, @password) assert_no_difference 'Article.count' do post articles_path, article: { title: 'gggg', description: 'h' * 4 } post articles_path, article: { title: 'ggggg', description: 'h' * 301 } post articles_path, article: { title: 'ggggg', description: '' } end end test 'article is created' do sign_in_as(@user, @password) assert_difference 'Article.count', 2 do post articles_path, article: { title: 'gggg', description: 'h' * 12 } post articles_path, article: { title: 'ggggg', description: 'h' * 250 } end end end
require 'spec_helper' describe RedirectorController do context "GET" do it 'follows redirects' do category_mappings = redirector_read_csv("spec/fixtures/categories.csv") CategoryService.stub(:category_mappings).and_return(category_mappings) [ [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-dresses", "http://www.example.com/products?category=womens-dresses"], [ "/au/shopping/womens-fashion-accessories/womens-maternity/w-dresses-maternity", "http://www.example.com/products"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-dresses?retailer=forcast", "http://www.example.com/products?category=womens-dresses&retailer=forcast"], [ "/au/shopping/womens-fashion-accessories/womens-clothing", "http://www.example.com/products"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-swimwear?type=w-swim-bikini", "http://www.example.com/products?sub_category=w-swim-bikini"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-swimwear", "http://www.example.com/products?category=womens-swimwear"], [ "/au/shopping/womens-fashion-accessories/bl-handbags", "http://www.example.com/products?category=bl-handbags"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-jeans?type=w-jeans-skinny", "http://www.example.com/products?category=womens-pants"], [ "/au/shopping/mens-fashion-accessories/mens-watches", "http://www.example.com/products"], [ "/au/shopping/shoes-footwear", "http://www.example.com/products?super_cat=shoes-footwear"], [ "/au/shopping/shoes-footwear/womens-shoes-footwear", "http://www.example.com/products?category=womens-shoes-footwear"], [ "/au/shopping/shoes-footwear/womens-plus-swimwear?retailer=oroton", "http://www.example.com/products?category=womens-plus-size&retailer=oroton"], [ "/au/shopping/shoes-footwear/mens-shoes-footwear", "http://www.example.com/products?category=mens-shoes-footwear"], [ "/au/shopping/mens-fashion-accessories/mens-clothing/mens-shirts", "http://www.example.com/products?category=mens-shirts"], [ "/au/shopping/mens-fashion-accessories/mens-clothing/mens-shirts?retailer=lowes", "http://www.example.com/products?category=mens-shirts&retailer=lowes"], [ "/au/shopping/mens-fashion-accessories/mens-clothing/mens-underwear-socks", "http://www.example.com/products?category=mens-underwear-socks"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-skirts", "http://www.example.com/products?category=womens-skirts"], [ "/au/shopping/womens-fashion-accessories", "http://www.example.com/products?super_cat=womens-fashion-accessories"], [ "/au/shopping/mens-fashion-accessories/mens-accessories/mens-ties", "http://www.example.com/products?sub_category=mens-ties"], [ "/au/shopping/mens-fashion-accessories/mens-accessories/mens-ties?type=m-ties-bowties", "http://www.example.com/products?category=mens-accessories"], [ "au/shopping/mens-fashion-accessories/mens-accessories/mens-ties?type=m-ties-business-ties", "http://www.example.com/products?category=mens-accessories"], [ "/au/shopping/womens-fashion-accessories/womens-accessories", "http://www.example.com/products?category=womens-accessories"], [ "/au/shopping/womens-fashion-accessories/womens-accessories/womens-belts", "http://www.example.com/products?sub_category=womens-belts"], [ "/au/shopping/mens-fashion-accessories/mens-clothing/mens-coats-jackets", "http://www.example.com/products?category=mens-coats-jackets"], [ "/au/shopping/mens-fashion-accessories/mens-clothing/mens-coats-jackets?type=m-coats-leather", "http://www.example.com/products?sub_category=m-coats-leather"], [ "/au/shopping/womens-fashion-accessories/womens-clothing/womens-coats-jackets", "http://www.example.com/products?category=womens-coats-jackets"], [ "/au/shopping/womens-fashion-accessories/bl-handbags/bl-handbags-clutch", "http://www.example.com/products?sub_category=bl-handbags-clutch"], ].each do |source_url,redirected_to| get source_url response.should redirect_to(redirected_to) response.code.to_i.should == 301 end end end end
require 'pry' class CashRegister attr_accessor :total, :discount, :new_item, :items, :last_transaction def initialize(discount = nil) @total = 0 @discount = discount @items = [] end def add_item(title, price, quantity = 1) self.total += (price * quantity) quantity.times do items << title end self.last_transaction = price * quantity end def apply_discount if discount != nil # binding.pry disc1 = 100.0 - discount percent = disc1/100.0 self.total = self.total * percent.to_f # binding.pry "After the discount, the total comes to $#{self.total.to_i}." else "There is no discount to apply." end end def void_last_transaction @total = @total - @last_transaction @total end end
# frozen_string_literal: true require 'spec_helper' require 'date' require 'xero_exporter/export' describe XeroExporter::Export do subject(:export) { described_class.new } context '#reference' do it 'contains the currency' do export.date = Date.new(2020, 3, 12) export.currency = 'gbp' expect(export.reference).to eq '20200312-GBP-' end it 'contains the ID' do export.date = Date.new(2020, 3, 12) export.currency = 'gbp' export.id = 'someid' expect(export.reference).to eq '20200312-GBP-someid' end end context '#invoices' do it 'is an array of invoices' do expect(export.invoices).to be_a Array end end context '#add_invoice' do it 'adds a new invoice' do invoice = export.add_invoice do |i| i.id = 'example' end expect(invoice.id).to eq 'example' expect(export.invoices).to eq [invoice] end end context '#add_payment' do it 'adds a new payment' do payment = export.add_payment do |p| p.id = 'example' end expect(payment.id).to eq 'example' expect(export.payments).to eq [payment] end end context '#add_refund' do it 'adds a new refund' do refund = export.add_refund do |r| r.id = 'example' end expect(refund.id).to eq 'example' expect(export.refunds).to eq [refund] end end end
# Set a fact to return the version of slapd that is installed # Facter.add("slapd_version") do slapd_bin = Facter::Core::Execution.which('slapd') setcode do if slapd_bin out = Facter::Core::Execution.execute("#{slapd_bin} -VV 2>&1") version = out.match(/slapd (\d+\.\d+\.\d+)/) $1 end end end
class Gtk2Mp3 def Gtk2Mp3.system_mpd # check if mpd is already running unless system 'ps -C mpd' unless system 'mpd' $stderr.puts 'Could not start the mpd daemon.' exit 69 # EX_UNAVAILABLE end end end def Gtk2Mp3.system_mpc # initialize playlist unless system 'mpc --wait update' and system 'mpc clear' and system 'mpc ls | mpc add' and system 'mpc consume off' and system 'mpc repeat off' and system 'mpc random on' and system 'mpc single off' $stderr.puts %q(Could not initialize mpd's playlist) exit 76 # EX_PROTOCOL end end def Gtk2Mp3.mpc_command(command) case command when :next_button! if system 'mpc pause-if-playing' sleep 0.25 system 'mpc next' else system 'mpc play' end when :stop_button! system 'mpc stop' else Gtk2Mp3.hook(command) end end def Gtk2Mp3.hook(command) # You can monkey-patch this function end def Gtk2Mp3.mpc_idleloop(gui) Thread.new do IO.popen('mpc idleloop player', 'r') do |pipe| while line = pipe.gets gui.set_label File.basename(`mpc current`.strip, '.*') end end end end end
require 'spec_helper.rb' describe IapReceiptVerification do subject { FactoryGirl.build :iap_receipt_verification, :successful } it('has a valid factory') { expect(FactoryGirl.build(:iap_receipt_verification)).to be_valid } it('has a valid unsuccessful factory') { expect(FactoryGirl.build :iap_receipt_verification, :unsuccessful).to be_valid } it { should validate_presence_of :user } it { should validate_presence_of :service } it { should validate_inclusion_of(:service).in_array Purchase::SERVICES } context 'when successful' do it { validate_presence_of :receipt_data } end context 'when unsuccessful' do subject { FactoryGirl.build :iap_receipt_verification, :unsuccessful } it { validate_presence_of :result } it { validate_presence_of :result_message } end end
module PlayerStatistics class MapsPlayedStatistic < PlayerStatistic def compute q = MatchScore .joins(:match) .where(player: @player) apply_filter(q).count(:all) end end end
module GapIntelligence class Promotion < Record attribute :start_date, class: Date attribute :end_date, class: Date attribute :promotion_type attribute :value attribute :bundle_type attribute :merchant_sku attribute :notes attribute :category_name attribute :brand attribute :part_number attribute :product_name attribute :merchant attribute :deleted end end
module Ign class Game attr_accessor :noko def initialize(noko) self.noko = noko end def rating @rating ||= lambda do begin rating = noko.css(".ratingBox").first.content.to_f rescue nil if rating == 0 href = noko.css(".game-title a").first.attributes["href"].value game_page = Nokogiri::HTML(Net::HTTP.get_response(URI.parse(href)).body) rating = game_page.css(".score-item-number").first.content.to_f rating = nil if rating == 0 end rating rescue nil end end.call end def name noko.css(".game-title a").first.content.strip rescue nil end def platform noko.css(".game-title span").first.content.strip rescue nil end end end
require 'rubygems' require 'json' require './Node.rb' # Used to decode the path from the goal node to the first def decode_path(goal_node) path = [] until goal_node.nil? path.unshift goal_node goal_node = goal_node.previous end return path end def bfs(start_id, goal_id, nodes) start_node = nodes[start_id] nodelist = [start_node] until nodelist.empty? current = nodelist.shift current.neighbours.each do |node| if node.id == goal_id node.previous = current puts "Goal found" return decode_path(node) end if node.colour == :white node.previous = current node.colour = :gray nodelist.push node end end current.colour = :black end raise "No route found" end filename = "verkko.json" lines = IO.readlines(filename) # Read file is used to generate hashes from json hashes = JSON.parse(lines[0]) nodes = {} # Nodes are initialized from hashes generated from json # Previous attribute also added for path decoding # Colour attribute added for searching, initialized to :white hashes.each do |hash| node = Node.new.hash_initialize(hash) nodes[node.id] = node class << node attr_accessor :previous, :colour end node.colour = :white end # This block of code fills neighbours for ids nodes.each do |key,node| neighbour_ids = node.neighbours.keys node.neighbours = [] neighbour_ids.map { |id| node.neighbours << nodes[id] } end puts "Nodes: #{nodes.size}" puts "Starts: " start = readline.strip puts start.class puts "Ends: " goal = readline.strip path = bfs(start, goal, nodes) # Printing names of stops from path (to_s) path.each { |node| puts node }
# encoding: utf-8 # copyright: 2016, you # license: All rights reserved # date: 2016-09-16 # description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil # impacts title 'V-46619 - Internet Explorer must be configured to use machine settings.' control 'V-46619' do impact 0.5 title 'Internet Explorer must be configured to use machine settings.' desc 'Users who change their Internet Explorer security settings could enable the execution of dangerous types of code from the Internet and websites listed in the Restricted Sites zone in the browser. This setting enforces consistent security zone settings to all users of the computer. Security zones control browser behavior at various websites and it is desirable to maintain a consistent policy for all users of a machine. This policy setting affects how security zone changes apply to different users. If you enable this policy setting, changes that one user makes to a security zone will apply to all users of that computer. If this policy setting is disabled or not configured, users of the same computer are allowed to establish their own security zone settings.' tag 'stig', 'V-46619' tag severity: 'medium' tag checkid: 'C-49785r2_chk' tag fixid: 'F-50389r1_fix' tag version: 'DTBI320-IE11' tag ruleid: 'SV-59483r1_rule' tag fixtext: 'Set the policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer Security Zones: Use only machine settings to Enabled. ' tag checktext: 'The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer Security Zones: Use only machine settings must be Enabled. Procedure: Use the Windows Registry Editor to navigate to the following key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings Criteria: If the value "Security_HKLM_only" is REG_DWORD = 1, this is not a finding.' # START_DESCRIBE V-46619 describe registry_key({ hive: 'HKLM', key: 'Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings', }) do its('Security_HKLM_only') { should eq 1 } end # STOP_DESCRIBE V-46619 end
require 'spec_helper' describe Enumerable do class TestEnumerable include Enumerable def initialize(*values) @values = values end def each(&block) @values.each(&block) end end let(:enumerable) { TestEnumerable.new('A', 'B', 'C') } describe '#to_list' do let(:to_list) { enumerable.to_list } it 'returns an equivalent list' do expect(to_list).to eq(L['A', 'B', 'C']) end it 'works on Ranges' do expect((1..3).to_list).to eq(L[1, 2, 3]) end end end
class JointVenturesController < ApplicationController before_action :get_joint_venture, except: [:index, :new, :create] breadcrumb "Joint Ventures", :joint_ventures_path, match: :exact def index @joint_ventures = JointVenture.paginate(page: params[:page], per_page: 8) end def show breadcrumb @joint_venture.headline, joint_venture_path(@joint_venture) end def new head(404) and return unless can?(current_user, :create) breadcrumb "New Joint Venture", new_joint_venture_path @joint_venture = JointVenture.new end def edit head(404) and return unless can?(current_user, :edit) breadcrumb @joint_venture.headline, joint_venture_path(@joint_venture), match: :exact breadcrumb 'Edit', edit_joint_venture_path(@joint_venture) end def create head(404) and return unless can?(current_user, :create) @joint_venture = JointVenture.new(joint_venture_params) respond_to do |format| if @joint_venture.save format.html {redirect_to @joint_venture, flash: {success: 'Pattern Created Successfully'}} else format.json {render json: @joint_venture.errors, status: :unprocessable_entity} end end end def update head(404) and return unless can?(current_user, :edit) respond_to do |format| if @joint_venture.update(joint_venture_params) format.json {redirect_to @joint_venture, flash: {success: 'Company Created Successfully'}} else format.json {render json: @joint_venture.errors, status: :unprocessable_entity} end end end def destroy head(404) and return unless can?(current_user, :destroy) @joint_venture.destroy respond_to do |format| format.html {redirect_to joint_ventures_url, notice: 'Joint Venture was successfully destroyed.'} format.json {head :ok} end end private def joint_venture_params params.require(:joint_venture).permit(:headline, :date, :link, :status, :party_1_company, :party_2_company, :party_3_company, :transaction_type, :jv_description, :details) end def get_joint_venture @joint_venture = JointVenture.find(params[:id]) end end
# coding: UTF-8 require 'test_helper' class StripDownRender < Redcarpet::TestCase def setup @parser = Redcarpet::Markdown.new(Redcarpet::Render::StripDown) end def test_titles markdown = "# Foo bar" output = @parser.render(markdown) assert_equal "Foo bar\n", output end def test_code_blocks markdown = "\tclass Foo\n\tend" output = @parser.render(markdown) assert_equal "class Foo\nend\n", output end def test_images markdown = "Look at this ![picture](http://example.org/picture.png)\n" \ "And this: ![](http://example.org/image.jpg)" expected = "Look at this picture http://example.org/picture.png\n" \ "And this: http://example.org/image.jpg\n" output = @parser.render(markdown) assert_equal expected, output end def test_links markdown = "Here's an [example](https://github.com)" expected = "Here's an example (https://github.com)\n" output = @parser.render(markdown) assert_equal expected, output end end
class User # < ActiveRecord::Base include Mongoid::Document field :username field :password field :color has_many :blogs, dependent: :destroy # embeds_many :blogs validates :username, presence: true, uniqueness: true validates :password, presence: true, length: { minimum: 8 } end
class VoucherPresenter # # Presentation logic to show ValidVouchers in customer view. # Vouchers of same type and reserved for same showdate are grouped together. # For groups of vouchers that are unreserved, we display a dropdown menu so customer can select # how many of that voucher to confirm a reservation for. # For groups of vouchers that are reserved, we show the date and, if it's a self-cancelable-by-customer # voucher, a Cancel button. # # The presentation logic takes a whole batch of vouchers and returns an ordered list of # VoucherPresenter objects. # require 'set' attr_reader :vouchers, :reserved, :group_id, :size, :vouchertype, :name, :showdate, :voucherlist, :redeemable_showdates # Constructor takes a set of vouchers that should be part of a group, and constructs the # presentation logic for them. It's an error for the provided vouchers not to "belong together" # (must all have same showdate and vouchertype, OR must all be unreserved and same vouchertype) class InvalidGroupError < StandardError ; end def initialize(vouchers,ignore_cutoff=false) @vouchers = vouchers raise InvalidGroupError.new("Vouchers don't belong together") unless vouchers_belong_together first = @vouchers[0] @reserved = first.reserved? @group_id = first.id @size = @vouchers.length @vouchertype = first.vouchertype @name = @vouchertype.name @showdate = first.showdate @voucherlist = @vouchers.map { |v| v.id }.join(',') @redeemable_showdates = if first.reservable? then first.redeemable_showdates(ignore_cutoff) else [] end end def cancelable_by(user) user.is_boxoffice || vouchers.all?(&:can_be_changed?) end # Within a show category, OPEN VOUCHERS are listed last, others are shown by order of showdate # vouchers for DIFFERENT SHOWS are ordered by opening date of the show # vouchers NOT VALID FOR any show are ordered by their vouchertype's display_order def <=>(other) sd1,vt1 = self.showdate, self.vouchertype sd2,vt2 = other.showdate, other.vouchertype if vt1 == vt2 # same vouchertype: order by OPENING DATE of the show for which reserved, or display order # if not reserved return (if sd1 then (sd1 <=> sd2) else (vt1.display_order <=> vt2.display_order) end) end # else different vouchertypes, so the rules are: # vouchertypes WITH assigned showdates always go first shows1,shows2 = vt1.showdates, vt2.showdates # which showdates is vouchertype valid for? if ! shows1.empty? && ! shows2.empty? then (shows1.min <=> shows2.min) elsif shows1.empty? && shows2.empty? then (vt1.display_order <=> vt2.display_order) # voucher having show validity goes first elsif shows1.empty? && ! shows2.empty? then 1 # voucher having show validity goes first else # !shows1.empty? && shows2.empty? -1 end end def self.groups_from_vouchers(vouchers,ignore_cutoff=false) # Group the vouchers so that a set of vouchers sharing same vouchertype and showdate stay together groups = Set.new(vouchers).classify { |v| [v.showdate, v.vouchertype] } # Create a presenter object for each group formatted_groups = groups.keys.map { |k| VoucherPresenter.new(groups[k].to_a, ignore_cutoff) } # # Ordering rules: # Subscriber vouchers all reserved for SAME SHOW (ie, same subscriber vouchertype) are grouped. # formatted_groups.sort end private def vouchers_belong_together first = @vouchers.first if @vouchers.any?(&:reserved?) @vouchers.all? { |v| v.showdate == first.showdate && v.vouchertype == first.vouchertype } else @vouchers.all? { |v| v.vouchertype == first.vouchertype } end end end
require 'bundler/setup' require 'nokogiri' require 'open-uri' require 'csv' def setup_doc(url) charset = 'utf-8' html = URI.parse(url).open.read doc = Nokogiri::HTML.parse(html, nil, charset) doc.search('br').each { |n| n.replace("\n") } doc end def scrape(url) doc = setup_doc(url) title = doc.title result1 = doc.css('h2').first.content [url, title, result1] end if __FILE__ == $PROGRAM_NAME urls = [ 'https://bokihajimeru.com/' ] csv_header = %W[URL \u30DA\u30FC\u30B8\u30BF\u30A4\u30C8\u30EB \u7D50\u679C1] CSV.open('result.csv', 'w') do |csv| csv << csv_header urls.each do |url| csv << scrape(url) rescue StandardError # エラー処理 csv << ['err', 'err', url] end end end
class User attr_accessor :name, :age def initialize(**params) @name = params[:name] @age = params[:age] end #Userクラスから生成されてインスタンスの情報を出力するメソッド(インスタンスメソッド) def info "名前:#{@name}:#{@age}歳" end #user_dataを引数で受け取り、そこからUserクラスのインスタンスを生成するメソッド(クラスメソッド) def self.create_users(user_data) user_data.map{|params| User.new(params)} end end user_data = [{name: "神里", age: 32},{name: "ふっしー", age: 34},{name: "あじー", age: 32}] users = User.create_users(user_data) users.each{|user| puts user.info}
class CreateGrounds < ActiveRecord::Migration def change create_table :grounds do |t| t.string :name t.integer :sport t.integer :access t.text :description t.string :address t.string :city t.string :state t.string :zip_code t.timestamps end end end
class Api::V1::PostsController < Api::V1::BaseController before_action :authenticate_user! def index posts = Post.page(params[:page]).per(params[:per_page]) response.headers['X-Total-Count'] = posts.total_count.to_s response.headers["X-Pages-Count"] = posts.total_pages.to_s render json: posts end def show post = Post.find(params[:id]) render json: post end def create post = @current_user.posts.new(post_params) if post.save render json: post else render json: { errors: post.errors.full_messages } end end private def post_params params.require(:post).permit(:title, :body, :published_at) end end
# RubIRCd - An IRC server written in Ruby # Copyright (C) 2013 Lloyd Dilley (see authors.txt for details) # http://www.rubircd.rocks/ # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. require 'logger' require_relative 'log' require_relative 'network' require_relative 'options' require_relative 'server' # Check if Celluloid is available begin gem 'celluloid-io', '>=0.16.0' require 'celluloid/io' require 'celluloid/autostart' rescue Gem::LoadError puts 'Celluloid-IO gem not found!' Log.write(4, 'Celluloid-IO gem not found!') exit! end # Handles event-driven I/O for network communication # using Celluloid # This class should offer better performance than # native select() since it provides access to libev # implementations of epoll and kqueue where available class Cell include Celluloid::IO finalizer :shutdown Celluloid.logger = ::Logger.new('logs/celluloid.log') def initialize(host, plain_port, ssl_port) # Since Celluloid::IO is included, this is a Celluloid::IO::TCPServer if Options.enable_starttls.to_s == 'false' @plain_server = TCPServer.new(host, plain_port) else tls_context = OpenSSL::SSL::SSLContext.new tls_context.cert = OpenSSL::X509::Certificate.new(File.read('cfg/cert.pem')) tls_context.key = OpenSSL::PKey::RSA.new(File.read('cfg/key.pem')) tls_server = SSLServer.new(TCPServer.new(host, plain_port), tls_context) tls_server.start_immediately = false # don't start SSL handshake until client issues "STARTTLS" @plain_server = tls_server # plain_server is now an SSLServer end async.plain_acceptor return if Options.ssl_port.nil? ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.cert = OpenSSL::X509::Certificate.new(File.read('cfg/cert.pem')) ssl_context.key = OpenSSL::PKey::RSA.new(File.read('cfg/key.pem')) @ssl_server = SSLServer.new(TCPServer.new(host, ssl_port), ssl_context) async.ssl_acceptor @connection_check_thread = Thread.new { Network.connection_checker } end def shutdown @plain_server.close if @plain_server @ssl_server.close if @ssl_server end def plain_acceptor loop { async.handle_plain_connections(@plain_server.accept) } end def ssl_acceptor loop { async.handle_ssl_connections(@ssl_server.accept) } end def handle_plain_connections(plain_client) Server.increment_clients user = Network.register_connection(plain_client, nil) Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) Network.main_loop(user) end def handle_ssl_connections(ssl_client) Server.increment_clients user = Network.register_connection(ssl_client, nil) Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) Network.main_loop(user) end def self.start if Options.listen_host.nil? listen_host = '0.0.0.0' else listen_host = Options.listen_host end supervisor = supervise(listen_host, Options.listen_port, Options.ssl_port) trap('INT') do supervisor.terminate exit end sleep end end
require "test/unit" require 'rugged' require 'tmpdir' require 'json' class ExperimentTestCase < Test::Unit::TestCase def initialize(test_method_name) super(test_method_name) @c = <<eos #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char** argv) { usleep(atoi(argv[1])*1000); printf(\"slept %dms\\n\", atoi(argv[1])); } eos @modc = @c @e = { "experiment" => "Run tests", "checkout" => "master", "iterations" => 1, "repository" => "..", "parallelism" => 1, "keep-stdout" => true, "build" => "clang -o test test.c", "arguments" => [ "$SRC/test", "10" ], "versions" => { "a" => { }, } } end def build(dir) dir = File.absolute_path dir repo = Rugged::Repository.init_at(dir) oid = repo.write @c, :blob index = repo.index index.add(:path => "test.c", :oid => oid, :mode => 0100644) File.open File.join(dir, "test.c"), "w" do |f| f.write(@c) end options = {} options[:tree] = index.write_tree(repo) options[:author] = { :email => "test@example.com", :name => 'Test Author', :time => Time.now } options[:committer] = { :email => "test@example.com", :name => 'Test Author', :time => Time.now } options[:message] ||= "Add test.c" options[:parents] = [] options[:update_ref] = 'HEAD' Rugged::Commit.create(repo, options) return repo end def experiment_out(dir, showerr, *args) dir = File.absolute_path dir File.open File.join(dir, "experiment.json"), "w" do |f| f.write(JSON.generate(@e)) end exp = File.absolute_path File.join(File.dirname(__FILE__), "../bin/experiment") here = Dir.pwd Dir.chdir dir r = Kernel.system(exp, "--trace", "--output", File.join(dir, "out"), *args, :out=>File.join(dir, "stdout.log"), :err=>File.join(dir, "stderr.log")) Dir.chdir here if !r and showerr File.open File.join(dir, "stderr.log"), "r" do |f| f.each_line do |line| puts line end end puts $? end return r end def experiment(dir, *args) return experiment_out(dir, true, *args) end def mkcommit(repo) oid = repo.write @modc, :blob index = repo.index index.read_tree(repo.head.target.tree) index.add(:path => "test.c", :oid => oid, :mode => 0100644) File.open File.join(repo.workdir, "test.c"), "w" do |f| f.write(@modc) end options = {} options[:tree] = index.write_tree(repo) options[:author] = { :email => "test@example.com", :name => 'Test Author', :time => Time.now } options[:committer] = { :email => "test@example.com", :name => 'Test Author', :time => Time.now } options[:message] ||= "Add test.c" options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact options[:update_ref] = 'HEAD' return Rugged::Commit.create(repo, options) end def test_build Dir.mktmpdir("test_", ".") {|d| build d assert_true(File.exist? File.join(d, ".git")) assert_true(File.exist? File.join(d, "test.c")) assert_true(File.directory? File.join(d, ".git")) ls = [] File.open File.join(d, "test.c"), "r" do |f| f.each_line do |line| ls.push line end end assert_equal(@c, ls.join) } end def validate_run_dir(d, ms=10) assert_true(File.directory? d) assert_true(File.exist? File.join(d, "experiment.log")) assert_true(File.exist? File.join(d, "stdout.log")) assert_true(File.exist? File.join(d, "stderr.log")) ls = [] File.open File.join(d, "stdout.log"), "r" do |f| f.each_line do |line| ls.push line end end assert_equal("slept " + ms.to_s + "ms\n", ls.join) end def test_run Dir.mktmpdir("test_", ".") {|d| build d assert_true(experiment d) assert_true(File.exist? File.join(d, "experiment.json")) assert_true(File.directory? File.join(d, "out", "a")) assert_true(File.exist? File.join(d, "out", "a", "build.log")) assert_true(File.directory? File.join(d, "out", "a", "source")) assert_true(File.exist? File.join(d, "out", "a", "source", "test.c")) validate_run_dir(File.join(d, "out", "a", "run-1")) } end end
require 'minitest/autorun' require_relative '../../lib/mastermind/code.rb' class TestCode < Minitest::Test def setup @code = Code.new([0, 1, 2, 2]) end TEST_DATA = { cd: [[3, 3, 4, 5], [3, 3, 4, 2], [3, 3, 4, 0], [3, 2, 4, 2], [0, 1, 2, 2]].map! { |code| Code.new(code) }, cattle: [[0, 0], [1, 0], [0, 1], [1, 1], [4, 0]], words: %w[to_none bulls cows bulls_and_cows identical] }.freeze (0..4).to_a.each do |i| define_method("test_counts_#{TEST_DATA[:words][i]}".to_sym) do assert_equal(TEST_DATA[:cattle][i], @code.count_cattle(TEST_DATA[:cd][i])) end define_method("test_counts_#{TEST_DATA[:words][i]}".to_sym) do assert(@code.compare_cattle(TEST_DATA[:cd][i], TEST_DATA[:cattle][i])) end ((0..4).to_a - [i]).each do |j| define_method("test_cattle_comparison_#{i}_#{j}".to_sym) do refute(@code.compare_cattle(TEST_DATA[:cd][i], TEST_DATA[:cattle][j])) end end end end class Array def to_code map! { |code| Code.new(code) } end end class CodeData < Minitest::Test CODES = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]].to_code.freeze GROUPS = [[3], [3], [2], [2], [2, 2], [3], [2], [2, 2], [4]].map! do |arr| (5 - arr.sum).times { arr << 1 } arr end.freeze end class TestCodeHerding < CodeData [0, 1, 2].repeated_permutation(2).with_index do |code, i| define_method("test_herds_#{code.join('_')}".to_sym) do assert_equal(GROUPS[i], Code.new(code).herd_cattle(CODES).sort!.reverse!) end end end class TestCodes < CodeData require_relative '../../lib/mastermind/codes.rb' def setup @poss_codes = Codes.new CODES @all_codes = Codes.new([0, 1, 2].repeated_permutation(2).to_a.to_code) end def test_picks_most_instructive_from_subset assert_includes([[0, 2], [1, 0], [2, 0]], @all_codes.most_instructive(@poss_codes)) end def test_picks_most_instructive_from_superset assert_equal([0, 1], @poss_codes[0..1].most_instructive(@all_codes)) end def test_gives_prescedence_to_possible_codes @all_codes[0..4] = @all_codes[0..4].each do |code| code.instance_variable_set(:@possible, true) end assert_includes([[0, 2], [1, 0]], @all_codes.most_instructive(@poss_codes)) end def first_pass @all_codes.full.sort_by_cattle!(Code.new([1, 2]), [1, 0]) end def test_sorts_virgin_codes_by_cattle first_pass assert_empty([[0, 2], [1, 0], [1, 1], [2, 2]] - @all_codes[0..3]) end def test_sort_sets_possibles_in_virgin_codes first_pass assert(@all_codes[0..3].all?(&:possible?)) end def test_sort_sets_impossibles_in_virgin_codes first_pass refute(@all_codes[4..-1].any?(&:possible?)) end def test_sort_resets_first_imposs_in_virgin_codes first_pass assert_equal(4, @all_codes.first_imposs) end def second_pass @all_codes.sort_by_cattle!(Code.new([2, 1]), [1, 0]) end def test_sorts_used_codes_by_cattle first_pass second_pass assert_empty([[1, 1], [2, 2]] - @all_codes[0..1]) end def test_sort_sets_possibles_in_used_codes first_pass second_pass assert(@all_codes[0..1].all?(&:possible?)) end def test_sort_sets_impossibles_in_used_codes first_pass second_pass refute(@all_codes[2..-1].any?(&:possible?)) end def test_sort_resets_first_imposs_in_used_codes first_pass second_pass assert_equal(2, @all_codes.first_imposs) end end
require 'test_helper' class ExamPointsControllerTest < ActionController::TestCase setup do sign_in teachers(:one) @exam_point = exam_points(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:exam_points) end test "should get new" do get :new assert_response :success end test "should create exam_point" do assert_difference('ExamPoint.count') do post :create, exam_point: { point: @exam_point.point, school_exam_id: @exam_point.school_exam_id, subject: @exam_point.subject } end assert_redirected_to exam_point_path(assigns(:exam_point)) end test "should show exam_point" do get :show, id: @exam_point assert_response :success end test "should get edit" do get :edit, id: @exam_point assert_response :success end test "should update exam_point" do patch :update, id: @exam_point, exam_point: { point: @exam_point.point, school_exam_id: @exam_point.school_exam_id, subject: @exam_point.subject } assert_redirected_to exam_point_path(assigns(:exam_point)) end test "should destroy exam_point" do assert_difference('ExamPoint.count', -1) do delete :destroy, id: @exam_point end assert_redirected_to exam_points_path end end
require 'github/client' class Actor < ActiveRecord::Base has_many :events def self.import name, klass = ::Github::Client records = klass.fetch name actor = Actor.find_or_create_by(name: name) records.each do |record| begin Event.create_from_record actor, record rescue next end end actor end def score events.map(&:score).reduce(:+) end end
class Credential < ApplicationRecord belongs_to :user def name "#{self.title} #{self.first_name} #{self.last_name}" end end
class SpecialistDecorator < Draper::Decorator delegate_all decorates_association :user def positive_feedback source.positive_feedback end def negative_feedback "-#{source.negative_feedback}" end def link_to_profile_admin h.link_to user.to_s, h.admin_user_path(user) end def orders_info h.link_to 'Назначенные заказы', h.admin_orders_path(executor: source.id) end def to_s "#{specialization} #{source.to_s}" end # 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 # source.created_at.strftime("%a %m/%d/%y") # end # end def avatar user.decorate.avatar end end
require 'spec_helper' describe ApplicationController do context 'filters' do it { expect(subject).to use_before_filter :authenticate_user! } it { expect(subject).to use_before_filter :configure_permitted_parameters } it { expect(subject).to use_before_filter :set_user_uid } end describe '#set_user_uid' do let(:user) { double :current_user, uid: 'qwe' } it 'should set current user uid as prefix to resources' do allow(subject).to receive(:current_user).and_return user expect(BaseResource).to receive(:user_uid=).with 'qwe' subject.send :set_user_uid end end end
require 'pry' require 'anagram.rb' anagram = Anagram.new('', '') # anagram.word1 = 'listen' # anagram.word2 = 'silent' describe('anagram') do it('check if two words are anagrams') do anagram.word1 = 'nomar' anagram.word2 = 'ramon' expect(anagram.anagram_check).to(eq('These words are anagrams')) end it('standardize casing for words entered') do anagram.word1 = 'ElBoW' anagram.word2 = "below" expect(anagram.anagram_check).to(eq('These words are anagrams')) end it('check if inputted string is actually words') do anagram.word1 = 'qzxws' anagram.word2 = 'plmnjh' expect(anagram.anagram_check).to(eq('You need to input real words')) end it('check if two words are antigrams') do anagram.word1 = 'mad' anagram.word2 = 'true' expect(anagram.anagram_check).to(eq('These words are antigrams')) end it('check if multiple words entered are anagrams') do anagram.word1 = 'go hang a salami' anagram.word2 = 'im a lasanga hog' expect(anagram.anagram_check).to(eq('These words are anagrams')) end it('remove any punctuation or spacing and still check for anagrams') do anagram.word1 = '@FUN$eral!' anagram.word2 = 'real fun' expect(anagram.anagram_check).to(eq('These words are anagrams')) end end
class CoursesController < ApplicationController def create @student=Student.find(current_student.id) if @student.courses.create(course_params) redirect_to(:controller => "welcomes", :action => "profile") end end private def course_params params.permit(:course_name, :course_code, :associated_with) end end
require "spec_helper" RSpec.describe Rails::Sources::VERSION do it "is a string" do expect(Rails::Sources::VERSION).to be_kind_of(String) end end
class Post < ActiveRecord::Base has_and_belongs_to_many :tags belongs_to :category end
class Teacher < ApplicationRecord has_many :students has_many :lessons has_many :cards, through: :lessons end
WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def play(board) until over?(board) turn(board) end if won?(board) winner = winner(board) puts "Congratulations #{winner}!" elsif draw?(board) puts "Cats Game!" end end def won?(board) WIN_COMBINATIONS.each do |combo| if board[combo[0]] == "X" && board[combo[1]] == "X" && board[combo[2]] == "X" return combo end end WIN_COMBINATIONS.each do |combo| if board[combo[0]] == "O" && board[combo[1]] == "O" && board[combo[2]] == "O" return combo end end return false end def full?(board) board.all? do |spot| spot.include?("X") == true || spot.include?("O") == true end end def draw?(board) if won?(board) return false end if full?(board) return true end end def over?(board) if draw?(board) return true end if won?(board) return true end return false end def winner(board) if over?(board) == false return nil end WIN_COMBINATIONS.each do |combo| if board[combo[0]] == "X" && board[combo[1]] == "X" && board[combo[2]] == "X" return "X" end end WIN_COMBINATIONS.each do |combo| if board[combo[0]] == "O" && board[combo[1]] == "O" && board[combo[2]] == "O" return "O" end end end def turn_count(board) counter = 0 board.each do |spot| if spot == "X" counter += 1 elsif spot == "O" counter += 1 end end return counter end def current_player(board) turns = turn_count(board) if turns.even? return "X" end return "O" end def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end def input_to_index(str) int = str.to_i if int == 0 return -1 end return int - 1 end def move(board, position, current_player) board[position] = current_player return board end def valid_move?(board, input) index = input if index > 8 || index < 0 return false end position_taken?(board, index) == false end def position_taken?(board, index) if board[index] == " " return false elsif board[index] == "" return false elsif board[index] == nil return false else return true end end def turn(board) current_player = current_player(board) puts " #{current_player}, Please enter 1-9:" input = gets.strip index = input_to_index(input) if valid_move?(board, index) == false puts "invalid" turn(board) end move(board, index, current_player) display_board(board) end
require 'spec_helper' describe Bitcourier::Protocol::Message::PeerInfo do before do @peer_info = Bitcourier::Protocol::Message::PeerInfo.new @peer_info_bytes = "\x01\x02\x03\x04\xFF\xFF\xAF5\xA24".force_encoding(Encoding::BINARY) end describe '#payload' do it 'returns payload bytes' do @peer_info.ip = '1.2.3.4' @peer_info.port = 65535 @peer_info.last_seen_at = Time.utc(1997, 12, 25, 10, 30, 7) @peer_info.payload.must_equal @peer_info_bytes end end describe '#extract' do it 'extracts payload bytes to object values' do @peer_info.extract @peer_info_bytes @peer_info.ip.must_equal '1.2.3.4' @peer_info.port.must_equal 65535 @peer_info.last_seen_at.must_equal Time.utc(1997, 12, 25, 10, 30, 7) end end end
require 'rails_helper' RSpec.describe "Repositories", type: :request do describe "GET /repositories" do subject { get '/repositories' } it_behaves_like 'HTTP 200 OK' end describe 'GET /repositories/:name' do context 'when repository exists' do subject { get "/users/#{user.login}/repositories/#{repo.name}" } let(:repo) { create(:repository, user: user) } let(:user) { create(:user) } it_behaves_like 'HTTP 200 OK' end xcontext 'when user does not exist' do subject { get "/users/not-found/repositories/#{repo.name}" } let(:repo) { create(:repository) } it_behaves_like 'HTTP 404 Not Found' end xcontext 'when repository does not exist' do subject { get "/users/#{user.login}/repositories/unknown-name" } let(:user) { create(:user) } it_behaves_like 'HTTP 404 Not Found' end end end
class Message include Mongoid::Document field :send_id, type: Integer field :send_user_name, type: String field :send_status, type: Integer field :receive_id, type: Integer field :receive_user_name, type: String field :receive_status, type: Integer field :content, type: String field :created_at, type: DateTime field :user_ids, type: Array def to_hash {:send_id => self.send_id, :send_user_name => self.send_user_name, :send_status => self.send_status, :receive_id => self.receive_id, :receive_user_name => self.receive_user_name, :receive_status => self.receive_status, :content => self.content, :created_at => self.created_at} end end
class IntellijIdeaCommunity < Cask url 'http://download.jetbrains.com/idea/ideaIC-12.1.6.dmg' homepage 'https://www.jetbrains.com/idea/index.html' version '12.1.6' sha1 '276301bd01fffdc3e6ddd0c4e2acccfb49b82b54' link 'IntelliJ IDEA 12 CE.app' end
#!/usr/bin/env ruby require 'etc' require 'yaml' require 'optparse' require 'socket' require 'pp' require_relative 'functions' unless Etc.getpwuid(Process.euid).name == "root" then STDERR.puts "Must run as root.\n" abort end options = {} OptionParser.new do |opts| opts.banner = "Usage: connect.rb [options]" opts.on('-c', '--config FILE', 'Config file') { |v| options[:config_file] = v } end.parse! unless options[:config_file] && File.exists?(options[:config_file]) then STDERR.puts "Missing config file\n" abort end config = YAML.load_file(options[:config_file]) #pp config unless config['interface'] then STDERR.puts "Interface not configured\n" abort end # find interface address based on configuration iface = Socket.getifaddrs.select { |ifaddr| ifaddr.name == config['interface'] && ifaddr.addr.ipv4? }.map { |ifaddr| { :name => ifaddr.name, :addr => ifaddr.addr.ip_address } }.first # verify that pf.conf has relayd anchor if File.readlines('/etc/pf.conf').grep(/anchor \"relayd\/\*\"/).empty? then puts "Adding relayd anchor to pf.conf, do you wish to proceed" if get_user_confirmation then open('/etc/pf.conf', 'a') do |f| f << "anchor \"relayd/*\"\n" end %x( pfctl -d ) %x( pfctl -e -f /etc/pf.conf ) else STDERR.puts "VPN Proxy will not work until you set relayd anchor to pf.conf.\nSee 'man 8 relayd' for more information" end end # verify system configuration if %x( sysctl net.inet.esp.enable ) != '0' then %x( sysctl net.inet.esp.enable=0 ) end if %x( sysctl net.inet.esp.udpencap ) != '0' then %x( sysctl net.inet.esp.udpencap=0 ) end if !config['ipsec']['gateway'] || !config['ipsec']['group'] || !config['ipsec']['user'] || !config['ipsec']['group_pw'] then STDERR.puts "One of mandatory VPNC configuration properties [ gateway | group | user | group_pw ] is missing\n" abort end open('/etc/vpnc/vpnhack.conf', 'w') do |vpnhack| vpnhack << "IPSec gateway #{config['ipsec']['gateway']}\n" vpnhack << "IPSec ID #{config['ipsec']['group']}\n" vpnhack << "IPSec secret #{config['ipsec']['group_pw']}\n" vpnhack << "Xauth username #{config['ipsec']['user']}\n" end pp "Starting VPNC" system 'vpnc vpnhack.conf' if $? != 0 then STDERR.puts "Failed to connect" abort end pp "Started VPNC" open('/etc/relayd.conf', 'w') do |relaydconf| relaydconf << "interval 5\n\n" config['relayd'].each do |relay| if !relay['name'] || !relay['src_port'] || !relay['dst_port'] || !relay['dst_host'] then STDERR.puts "Ignoring #{relay}" next end relaydconf << "relay \"#{relay['name']}\" {\n" relaydconf << " listen on #{iface[:addr]} port #{relay['src_port']}\n" relaydconf << " forward to #{relay['dst_host']} port #{relay['dst_port']}\n" relaydconf << "}\n\n" end end pp "Starting relayd" system 'relayd -v -f /etc/relayd.conf' if $? != 0 then STDERR.puts "Failed to start relayd" abort end pp "Started relayd"
ActiveAdmin.register PointOfInterest do index do column :id column :title column :footnote column :description column :imageURL column :lat column :lon column :anchor column :facebook_id default_actions end filter :id filter :title filter :lat filter :lon form do |f| f.inputs "Point of Interest Details" do f.input :title f.input :footnote f.input :description f.input :imageURL f.input :lat f.input :lon f.input :anchor f.input :facebook_id, :as => :select, :collection => User.all end f.buttons end show do attributes_table do row :title row :title row :footnote row :description row :imageURL row :lat row :lon row :anchor row :facebook_id end active_admin_comments end end
class Changeusers < ActiveRecord::Migration def up add_index :users, :perishable_token add_index :users, :email remove_column :users, :avatar_file_name end def down end end
class Weather def initialize(lat_long) @latitude = lat_long[:lat] @longitude = lat_long[:lng] end def current_weather DarkSkyService.new.get_weather(@latitude, @longitude) end end
class TryThemsController < ApplicationController before_action :set_try_them, only: [:show, :edit, :update, :destroy] # GET /try_thems # GET /try_thems.json def index @try_thems = TryThem.all end # GET /try_thems/1 # GET /try_thems/1.json def show end # GET /try_thems/new def new @try_them = TryThem.new end # GET /try_thems/1/edit def edit end # POST /try_thems # POST /try_thems.json def create @try_them = TryThem.new(try_them_params) respond_to do |format| if @try_them.save format.html { redirect_to @try_them, notice: 'Try them was successfully created.' } format.json { render :show, status: :created, location: @try_them } else format.html { render :new } format.json { render json: @try_them.errors, status: :unprocessable_entity } end end end # PATCH/PUT /try_thems/1 # PATCH/PUT /try_thems/1.json def update respond_to do |format| if @try_them.update(try_them_params) format.html { redirect_to @try_them, notice: 'Try them was successfully updated.' } format.json { render :show, status: :ok, location: @try_them } else format.html { render :edit } format.json { render json: @try_them.errors, status: :unprocessable_entity } end end end # DELETE /try_thems/1 # DELETE /try_thems/1.json def destroy @try_them.destroy respond_to do |format| format.html { redirect_to try_thems_url, notice: 'Try them was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_try_them @try_them = TryThem.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def try_them_params params.require(:try_them).permit(:title, :description) end end
class CreatePlayers < ActiveRecord::Migration def change create_table :players do |t| t.integer :playerId t.string :position t.string :display_name t.string :fname t.string :lname t.string :team t.integer :byeweek t.float :stn_dev t.float :nerd_rank t.float :position_rank t.float :overall_rank t.boolean :drafted, default: false t.string :fantasy_team t.timestamps null: false end end end