text
stringlengths
10
2.61M
require 'sinatra' require 'google/cloud/storage' require 'digest' require 'logger' require 'json' storage = Google::Cloud::Storage.new(project_id: 'cs291-f19') bucket = storage.bucket 'cs291_project2', skip_lookup: true logger = Logger.new $stdout logger.level = Logger::INFO Google::Apis.logger = logger get '/' do logger.info "URL Matched /" redirect "/files/" end def is_valid_sha256_hexdigest(string) if string and string.length == 64 and !string[/\H/] puts "valid sha256_digest" return true end puts "invalid sha256_digest" return false end def is_valid_filename(name) begin if name[2] == '/' and name[5] == '/' puts "Slashes exist" name[2] = "" name[4] = "" puts "New file name is: " print(name) else puts "invalid path in name" return "" end rescue puts "an error occurred" return "" end if is_valid_sha256_hexdigest(name) return name end puts "not a valid sha 256 hex digest" return "" end get '/files/:digest' do puts "URL Matched /files/:digest" digest = params['digest'].downcase puts "Digest: " puts digest if not is_valid_sha256_hexdigest(digest) puts "Filename is not a valid hexdigest" status 422 return end digest = add_slashes(digest) file = bucket.file digest if file puts "file in bucket: " print(file) downloaded_file = file.download downloaded_file.rewind content_type file.content_type status 200 body downloaded_file.read return else status 404 body "File not found" return end end def add_slashes(string) modified_string = string modified_string = modified_string.insert(2, '/') modified_string = modified_string.insert(5, '/') return modified_string end get '/files/' do puts "URL Matched /files/" puts "Get files in the bucket\n" files_in_bucket = bucket.files files = [] files_in_bucket.each do |file| print(file.name) parsed_file = is_valid_filename(file.name) print "parsed name: " print(parsed_file) if parsed_file != "" files.push parsed_file end end files = files.sort files = files.to_json print(files) status 200 body files return end post '/files/' do begin if params.key?('file') file = params['file'] puts "File: " puts file if file == "" puts "File is empty" status 422 return end else status 422 return end puts "Getting file size: " if file.key?('tempfile') tempfile = file['tempfile'] file_size = tempfile.size puts file_size if not tempfile or not file["filename"] or file_size > 1048576 puts "File not provided or file too large" status 422 return end else puts "No tempfile key found" status 422 return end rescue puts "Caught exception" status 422 return end downloaded_file = tempfile.read puts "downloaded_file: " puts downloaded_file digested_file = Digest::SHA256.hexdigest(downloaded_file) puts "digested_file: " puts digested_file file_name = add_slashes(digested_file) if bucket.file file_name puts "File with same name already exists" status 409 return else puts "file head" puts file["head"] puts "tempfile path" puts tempfile.path head = file['head'] arr = head.split("\r\n") content_type_str = arr[1].delete(' ') type = (content_type_str.split(":"))[1] print("type: " + type) file = bucket.create_file tempfile.path, file_name, content_type: type digested_file[2] = "" digested_file[4] = "" return_body = "{\"uploaded\": \"#{digested_file}\"}" puts "return_body: " puts return_body status 201 body return_body return end end delete '/files/:digest' do file_name = params['digest'].downcase if not is_valid_sha256_hexdigest(file_name) puts "Filename is not a valid hexdigest" status 422 return end file_name = add_slashes(file_name) file = bucket.file file_name if file file.delete puts "File deleted" end status 200 return end
module ConditionsHelper def format_temperature_for(condition) '%.1f' % condition.temperature end def google_maps_javascript_include_tag javascript_include_tag google_maps_source end def google_maps_source 'https://maps.googleapis.com/maps/api/js?key=%s&sensor=true' % google_maps_api_key end def google_maps_api_key ENV['GOOGLE_MAPS_API_KEY'] end def map_tag_for(condition) content_tag :div, '', id: 'map-canvas', data: data_for(condition) end def data_for(condition) { latitude: condition.latitude, longitude: condition.longitude } end end
# frozen_string_literal: true require 'spec_helper' require 'facter/util/globus' describe 'globus_info Fact' do before :each do Facter.clear allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') end it 'returns Globus info' do allow(Facter::Util::Globus).to receive(:read_info).and_return(JSON.parse(my_fixture_read('info.json'))) value = Facter.fact(:globus_info).value expect(value).not_to be_nil expect(value['domain_name']).to eq('example0001.data.globus.org') expect(value['endpoint_id']).to eq('1c6b6e6a-3791-4213-b3e6-00001') end it 'returns nil if info.json does not exist' do allow(Facter::Util::Globus).to receive(:read_info).and_return(nil) expect(Facter.fact(:globus_info).value).to be_nil end end
class Question attr_reader(:correct_answer) # new question is generated for each turn # by picking two numbers between 1 and 20 def initialize @first_number = rand(1..20) @second_number = rand(1..20) # simple math addition problems @correct_answer = @first_number + @second_number end def question_display "What does #{@first_number} plus #{@second_number} equal?" end # must answer correctly or lose a life. def answer_correct?(player_answer) if player_answer == @correct_answer true else false end end end
module GreenByPhone class Gateway API_URL = 'https://www.greenbyphone.com/eCheck.asmx' def initialize(options = {}) @login = options[:login] @password = options[:password] end def one_time_draft(options = {}) post = {} add_customer(post, options) add_check(post, options) commit(options[:real_time] ? 'OneTimeDraftRTV' : 'OneTimeDraftBV', post) end def recurring_draft(options = {}) post = {} add_customer(post, options) add_check(post, options) add_recurring(post, options) commit(options[:real_time] ? 'RecurringDraftRTV' : 'RecurringDraftBV', post) end def verification_result(options = {}) post = { 'Check_ID' => options[:check_id] } commit('VerificationResult', post) end private def add_customer(post, options) post['Name'] = options[:name] post['EmailAddress'] = options[:email_address] post['Phone'] = options[:phone] post['PhoneExtension'] = options[:phone_extension] post['address1'] = options[:address1] post['address2'] = options[:address2] post['city'] = options[:city] post['state'] = options[:state] post['Zip'] = options[:zip] end def add_check(post, options) post['RoutingNumber'] = options[:routing_number] post['AccountNumber'] = options[:account_number] post['BankName'] = options[:bank_name] post['CheckAmount'] = options[:check_amount] post['CheckDate'] = options[:check_date] post['CheckMemo'] = options[:check_memo] end def add_recurring(post, options) post['RecurringType'] = options[:recurring_type] post['RecurringOffset'] = options[:recurring_offset] post['RecurringPayments'] = options[:recurring_payments] end def parse(response) Crack::XML.parse(response) end def commit(action, post) post['Client_ID'] = @login post['ApiPassword'] = @password uri = URI.parse(API_URL + "/#{action}") request = Net::HTTP.new(uri.host, 443) request.use_ssl = true data = parse(request.post(uri.path, post.collect { |k,v| "#{k}=#{v}" }.join('&')).body) Response.new_from_request(data['DraftResult']) end end end
# frozen_string_literal: true require 'spec_helper' describe 'influxdb', type: :class do on_supported_os.each do |os, facts| context "on #{os} " do let :facts do facts end it do is_expected.to compile.with_all_deps is_expected.to contain_class('influxdb') is_expected.to contain_class('influxdb::repo').that_comes_before('Class[influxdb::install]') is_expected.to contain_class('influxdb::install').that_comes_before(['Class[influxdb::config]', 'Class[influxdb::service]']) is_expected.to contain_exec('is_influx_already_listening') case facts[:os]['name'] when 'Debian', 'Ubuntu' is_expected.to have_class_count(10) is_expected.to have_resource_count(26) when 'CentOS' is_expected.to have_class_count(7) is_expected.to have_resource_count(12) end end end end end
# $Id$ module TabsHelper # For tabs with contents already rendered in main page def link_to_tab(name) link_to_function(name.humanize.capitalize, "tabselect($('#{name}_tab')); paneselect($('#{name}_pane'))") end # For tabs that dynamically load contents def link_to_ajax_tab(name, ajax_url) link_to_function(name.humanize.capitalize, "loadPane($('#{name}_pane'), '#{ajax_url}'), tabselect($('#{name}_tab')); paneselect($('#{name}_pane'))") end end
Then /^data should be loaded into the development database$/ do # end Then /^the "(.*?)" database should include a friend named "(.*?)"$/ do |env, name| names = `RAILS_ENV=#{env} bundle exec rails runner 'puts Friend.all.map(&:name)'` names.should include name end
class Project < ApplicationRecord has_many :groups, dependent: :destroy has_many :tasks, :through => :groups has_many :memberships, dependent: :destroy has_many :users, :through => :memberships end
# frozen_string_literal: true require 'rails_helper' RSpec.describe PressuresController, type: :controller do before do @user = FactoryBot.create :user, email: 'joao@example.org' sign_in @user @existing_profile = FactoryBot.create :profile, email: 'joao@example.org', user: @user end after do sign_out @user end describe 'GET #index' do it 'returns a success response' do get :index, params: { profile_email: @existing_profile.email } expect(response).to be_successful end it 'returns a page with all pressures registered from an user' do get :index, params: { profile_email: @existing_profile.email } expect(assigns(:pressures)).to eq(@existing_profile.pressures) end it 'render a index page' do get :index, params: { profile_email: @existing_profile.email } expect(response).to render_template(:index) end end describe 'GET #new' do it 'returns a success response' do get :new, params: { profile_email: @existing_profile.email } expect(response).to be_successful end it 'render a new pressure page' do get :new, params: { profile_email: @existing_profile.email } expect(response).to render_template(:new) end end describe 'GET #edit' do before do @existing_pressure = FactoryBot.create :pressure, profile: @existing_profile end it 'returns a success response' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_pressure.id } expect(response).to be_successful end it 'returns an existing pressure' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_pressure.id } expect(assigns(:pressure)).to eq(@existing_pressure) end it 'returns an edit view' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_pressure.id } expect(response).to render_template(:edit) end end describe 'POST #create' do context 'with valid params' do let(:valid_attributes) do { diastolic: '10', systolic: '80', date: 1.day.ago } end it 'creates a new Pressure' do expect do post :create, params: { profile_email: @existing_profile.email, pressure: valid_attributes } end.to change(@existing_profile.pressures, :count).by(1) end it 'redirects to the Pressure page' do post :create, params: { profile_email: @existing_profile.email, pressure: valid_attributes } expect(response).to redirect_to( profile_pressures_path(profile_email: @existing_profile.email) ) end end end context 'with invalid params' do let(:invalid_attributes) do { diastolic: '', systolic: '80', date: 1.day.ago } end it "doesn't creates a new pressure" do expect do post :create, params: { profile_email: @existing_profile.email, pressure: invalid_attributes } end.to_not change(@existing_profile.pressures, :count) end it 'stay in the new pressure' do post :create, params: { profile_email: @existing_profile.email, pressure: invalid_attributes } expect(response).to render_template(:new) end end describe 'DELETE #destroy' do before do @existing_pressure = FactoryBot.create :pressure, profile: @existing_profile end it 'destroys the requested pressure' do expect do delete :destroy, params: { profile_email: @existing_profile.email, id: @existing_pressure.to_param } end.to change(Pressure, :count).by(-1) end it 'redirects to the pressures list' do delete :destroy, params: { profile_email: @existing_profile.email, id: @existing_pressure.to_param } expect(response).to redirect_to( profile_pressures_path(profile_email: @existing_profile.email) ) end end describe 'PUT #update' do before do @existing_pressure = FactoryBot.create :pressure, profile: @existing_profile @original_pressure_systolic = @existing_pressure.systolic @original_pressure_diastolic = @existing_pressure.diastolic @original_pressure_date = @existing_pressure.date end context 'with valid params' do let(:new_attributes) do { diastolic: '11', systolic: '22', date: '2018-10-18 11:58:22' } end it 'updates the requested profile' do put :update, params: { profile_email: @existing_profile.email, id: @existing_pressure.id, pressure: new_attributes } @existing_pressure.reload expect(@existing_pressure.systolic).to eq(new_attributes[:systolic].to_i) expect(@existing_pressure.diastolic).to eq(new_attributes[:diastolic].to_i) expect(@existing_pressure.date).to eq(new_attributes[:date].to_datetime) expect(@existing_pressure.profile).to eq(@existing_profile) end it 'redirects to the pressure page' do put :update, params: { profile_email: @existing_profile.email, id: @existing_pressure.id, pressure: new_attributes } expect(response).to redirect_to( profile_pressures_path(profile_email: @existing_profile.email) ) end end context 'with invalid params' do let(:invalid_attributes) do { diastolic: '-2', systolic: '-1', date: '2018-10-18 11:58:22' } end it "doesn't change the Pressure" do put :update, params: { profile_email: @existing_profile.email, id: @existing_pressure.id, pressure: invalid_attributes } @existing_pressure.reload expect(@existing_pressure.systolic).to eq(@original_pressure_systolic) expect(@existing_pressure.diastolic).to eq(@original_pressure_diastolic) expect(@existing_pressure.date).to eq(@original_pressure_date) expect(@existing_pressure.profile).to eq(@existing_profile) end it 'stay in the edit pressure' do put :update, params: { profile_email: @existing_profile.email, id: @existing_pressure.id, pressure: invalid_attributes } expect(response).to render_template(:edit) end end end end
require 'rails_helper' describe 'navigate' do let(:lecturer) { FactoryBot.create(:lecturer) } let(:user) { FactoryBot.create(:user) } let(:userpost) { FactoryBot.create(:user_post, user_id: user.id)} before do login_as(lecturer, :scope => :user) end describe 'index' do before do FactoryBot.create(:lecture_post, user_id: lecturer.id) visit activity_posts_path end it 'has a list of activity posts' do expect(page).to have_content(/LecturePost/) end end describe 'creation' do before do visit new_activity_post_path end it 'can be created successfully' do fill_in 'Title', with: 'Title' fill_in 'Description', with: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' fill_in 'activity_post[start_date]', with: Date.today fill_in 'activity_post[end_date]', with: Date.today + 3.days fill_in 'Venue', with: "Venue" click_on "Save" expect(page).to have_content(/Lorem ipsum/) end end describe 'edit' do it 'can be edited by lecturer' do lecture_post = FactoryBot.create(:lecture_post, user_id: lecturer.id) visit activity_posts_path click_link("edit_#{lecture_post.id}") fill_in 'Title', with: 'Edited Lecture Post from clicking link' click_on "Save" expect(page).to have_content(/Edited Lecture Post from clicking link/) end it 'can not edit other posts' do visit edit_activity_post_path(userpost) expect(current_path).to eq(root_path) end end end
# frozen_string_literal: true #= Controller for course functionality class ExploreController < ApplicationController respond_to :html def index # 'cohort' is the old name for campaign. We accept 'cohort' as an alternative # parameter to keep old incoming links from breaking. campaign = params[:campaign] || params[:cohort] || ENV['default_campaign'] @presenter = CoursesPresenter.new(current_user, campaign) return unless @presenter.campaign.nil? raise ActionController::RoutingError.new('Not Found'), 'Campaign does not exist' end end
class ItemDetail < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :condition belongs_to_active_hash :size belongs_to :item with_options presence: true do validates :condition # ToDo brand,sizeは実装したらバリデーションを加える # validates :size # validates :brand end end
# frozen_string_literal: true require 'test_helper' class OrderItemTest < ActiveSupport::TestCase test 'order item is valid' do order_item = OrderItem.new( order: orders(:car), price: MIN_PRICE, count: 10_000, product_item: product_items(:black_car) ) assert order_item.valid? end test 'price is validated' do order_item = OrderItem.new assert_not order_item.valid? order_item.price = MIN_PRICE - 1 assert_not order_item.valid? assert_not_empty order_item.errors[:price] order_item.price = -MIN_PRICE assert_not order_item.valid? assert_not_empty order_item.errors[:price] order_item.price = MIN_PRICE + 1 order_item.valid? assert_empty order_item.errors[:price] end test 'count is validated' do order_item = OrderItem.new assert_not order_item.valid? order_item.count = 0 assert_not order_item.valid? assert_not_empty order_item.errors[:count] order_item.count = -1 assert_not order_item.valid? assert_not_empty order_item.errors[:count] order_item.count = 1 order_item.valid? assert_empty order_item.errors[:count] order_item.count = 12 order_item.valid? assert_empty order_item.errors[:count] end test 'order item is invalid' do order_item = OrderItem.new assert_not order_item.valid? assert_not_empty order_item.errors[:order] assert_not_empty order_item.errors[:price] assert_not_empty order_item.errors[:count] assert_not_empty order_item.errors[:product_item] end end
module Kaigara class Package # # The base project files and directories # METADATA_FILE_NAME = 'metadata.rb' VAGRANT_FILE_NAME = 'Vagrantfile' OPERATIONS_DIR_NAME = 'operations' RESOURCES_DIR_NAME = 'resources' # Project directory attr_accessor :work_dir # metadata.rb path attr_accessor :script_path attr_accessor :operations_dir attr_accessor :dependencies attr_accessor :version attr_accessor :name class MetadataNotFound < RuntimeError; end def initialize(path = '.') @options = {} @work_dir = path ? File.expand_path(path) : '.' @operations_dir = File.join(@work_dir, OPERATIONS_DIR_NAME) @script_path = File.expand_path(File.join(@work_dir, METADATA_FILE_NAME)) @spec = Spec.new(self) end def full_name @full_name ||= [name, version].compact.join("/") end # Read and execute metadata.rb def load! raise MetadataNotFound.new unless File.exist?(@script_path) script = File.read(@script_path) @spec.instance_eval(script) end # Create an empty operation in ./operations def operation_name(name) ts = DateTime.now.strftime('%Y%m%d%H%M%S') return "%s_%s.rb" % [ts, name] end # Execute operations in the operations directory one by one def run!(operations) Dir[File.join(@operations_dir, '*.rb')].sort.each do |x| if operations.empty? or operations.find { |op| x.include?(op) } execute_operation!(x) end end end def execute_operation!(path) context = Operation.new path context.work_dir = @work_dir context.environment = @spec.environment context.apply! end end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu14" config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-web-cloudimg-amd64-vagrant-disk1.box" config.ssh.forward_agent = true config.vm.provider "virtualbox" do |vb| vb.customize ["modifyvm", :id, "--memory", "4096", "--cpus", "2", "--ioapic", "on"] end config.vm.define :web, primary: true do |web| web.vm.hostname = "web" web.vm.network :forwarded_port, guest: 22, host: 2000, id: "ssh" web.vm.network :forwarded_port, guest: 80, host: 8000, id: "http" web.vm.network :private_network, ip: "192.168.33.12", virtualbox__intnet: "network" web.vm.synced_folder "./web", "/var/www/html", :nfs => true, mount_options: ['dmode=777','fmode=666'] end config.vm.define :ansible, autostart: false do |ansible| ansible.vm.hostname = "ansible" ansible.vm.network :forwarded_port, guest: 22, host: 2001, id: "ssh" ansible.vm.network :private_network, ip: "192.168.33.11", virtualbox__intnet: "network" ansible.vm.synced_folder "./ansible", "/home/vagrant/ansible", mount_options: ['dmode=777','fmode=666'] ansible.vm.provision "shell", path: "ansible.sh" end end
class CreateReservas < ActiveRecord::Migration def change create_table :reservas do |t| t.integer :cliente_id t.integer :local_id t.date :fecha_emision t.time :hora_inicio t.time :hora_final t.boolean :estado t.integer :validez_pre_reserva t.integer :total t.timestamps end end end
class AddDefaultColumnsToEasyQuerySettings < ActiveRecord::Migration def self.up EasySetting.create(:name => 'easy_budget_sheet_query_list_default_columns', :value => ['spent_on', 'user', 'activity', 'issue', 'hours']) EasySetting.create(:name => 'easy_budget_sheet_query_grouped_by', :value => 'project') end def self.down end end
module Helpers def self.get_env(key) #Automatically try to be case insensitive return ENV[key] || ENV[key.downcase] || ENV[key.upcase] end end
module Kilomeasure class InputsFormatter < ObjectBase fattrs :inputs, :measure boolean_attr_accessor :strict boolean_attr_accessor :add_defaults def initialize(*) super raise ArgumentError, :inputs unless inputs raise ArgumentError, :measure unless measure @inputs = @inputs.clone @inputs.symbolize_keys! self.add_defaults = true if @add_defaults.nil? self.strict = false if @strict.nil? clean_inputs modify_inputs end private def add_constant_inputs inputs.merge!(CALCULATION_CONSTANTS) end def add_default_inputs measure.defaults.each do |key, value| if value.is_a?(Hash) default = inputs[:proposed] ? value[:proposed] : value[:existing] inputs[key] ||= default else inputs[key] ||= value end end end def clean_inputs inputs.delete_if { |_, v| [nil, ''].include?(v) } end def modify_inputs add_default_inputs if add_defaults? add_constant_inputs end end end
class MakeHistoricalEventPolymorphic < ActiveRecord::Migration[6.1] def change change_table :historical_events do |t| t.string :trackable_id t.string :trackable_type end add_index :historical_events, [:trackable_type, :trackable_id] HistoricalEvent.all.each do |event| event.update_columns(trackable_id: event.activity_id, trackable_type: "Activity") end end end
class SessionsController < Devise::SessionsController def create if request.xhr? resource = warden.authenticate!( scope: resource_name, recall: "#{controller_path}#failure" ) sign_in_and_redirect(resource_name, resource) else super end end def sign_in_and_redirect(resource_or_scope, resource = nil) scope = Devise::Mapping.find_scope!(resource_or_scope) resource ||= resource_or_scope sign_in(scope, resource) unless warden.user(scope) == resource sign_out_link = view_context.link_to( 'Sign out', destroy_user_session_path, method: :delete) render json: { success: true, greeting: "Hey #{resource.first_name}! Welcome back! #{sign_out_link}", api_key: resource.authentication_token, user_id: resource.uuid } end def failure render json: { success: false, errors: I18n.t('devise.failure.invalid') } end end
SeoApp.configure do |config| # Postgress config config.db_host = 'localhost' config.db_port = '5432' config.db_name = 'sinatra' config.db_user = 'ruby' config.db_password = 'noway' config.db_url = 'postgres://ruby:noway@localhost/sinatra' config.adapter = 'sequel' end
class TemplateRepo < ActiveRecord::Base DEFAULT_PROVIDER_NAME = 'Github Public' belongs_to :template_repo_provider after_create :reload_templates after_destroy :purge_templates after_initialize :set_default_provider validates :name, presence: true, uniqueness: true def set_default_provider self.template_repo_provider ||= TemplateRepoProvider.where(name: DEFAULT_PROVIDER_NAME).first! end def files template_repo_provider.files_for(self) end def load_templates self.files.each do |file| next unless file.name.end_with?('.pmx') TemplateBuilder.create(file.content).tap { |tpl| tpl.update_attributes(source: self.name) } end self.touch end def purge_templates Template.destroy_all(source: self.name) end def reload_templates transaction do purge_templates load_templates end end def self.load_templates_from_all_repos self.all.each(&:load_templates) end end
module TrafficSpy class PayloadParser attr_reader :params def initialize(params) @params = params end def p_pams JSON.parse(params["payload"]) end def ua UserAgent.parse(p_pams["userAgent"]) end def resolution Resolution.find_or_create_by(dimension: "#{p_pams["resolutionWidth"]} x #{p_pams["resolutionHeight"]}") end def browser ua.browser end def os ua.platform end def user User.find_by(identifier: params["id"]) end def url p_pams["url"] end def parameters p_pams["parameters"] end def requested_at p_pams["requestedAt"] end def request_type p_pams["requestType"] end def responded_in p_pams["respondedIn"] end def referred_by p_pams["referredBy"] end def event_name p_pams["eventName"] end def ip p_pams["ip"] end def payload_sha Digest::SHA1.hexdigest(p_pams.to_s) end def create_payload_if_user_exists if user.nil? status, body = [403, "#{params["id"]} is not registered"] elsif TrafficSpy::Payload.find_by(payload_sha: payload_sha) status, body = [403, "This specific payload already exists in the database..."] else TrafficSpy::Payload.create(user_id: user.id, resolution_id: resolution.id, url: p_pams["url"], requested_at: p_pams["requestedAt"], responded_in: p_pams["respondedIn"], referred_by: p_pams["referredBy"], request_type: p_pams["requestType"], parameters: p_pams["parameters"], event_name: p_pams["eventName"], user_agent: browser, ip: p_pams["ip"], payload_sha: payload_sha, os: os) end end def payload_response if params["payload"].nil? status, body = [400, "No payload received in the request"] else create_payload_if_user_exists end end end end
require 'rails_helper' RSpec.describe DropdownSelectionHelper, type: :helper do describe '.chosen_period' do context 'when period value is present' do it 'returns the period value from request parameters' do controller.params[:metric] = { period: 5 } expect(helper.chosen_period).to eq(5) end end context 'when period value is not preset' do it 'returns 4 as default value' do controller.params[:metric] = {} expect(helper.chosen_period).to eq(4) end end end describe '.chosen_user' do it 'returns the user name from the id on the request parameters' do controller.params[:id] = '4' expect(helper.chosen_user).to eq('4') end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module ActiveRecord class QueryCache module ClassMethods # Enable the query cache within the block if Active Record is configured. def cache(&block) if ActiveRecord::Base.configurations.blank? yield else connection.cache(&block) end end # Disable the query cache within the block if Active Record is configured. def uncached(&block) if ActiveRecord::Base.configurations.blank? yield else connection.uncached(&block) end end end def initialize(app) @app = app end def call(env) ActiveRecord::Base.cache do @app.call(env) end end end end
require "digest" require "lita" module Lita module Handlers # Provides Travis CI webhooks for Lita. class Travis < Handler config :token, type: String, required: true config :repos, type: Hash, default: {} config :default_rooms, type: [Array, String] http.post "/travis", :receive def receive(request, response) data = parse_payload(request.params["payload"]) or return repo = get_repo(data) validate_repo(repo, request.env["HTTP_AUTHORIZATION"]) or return notify_rooms(repo, data) end private def parse_payload(json) begin MultiJson.load(json) rescue MultiJson::LoadError => e Lita.logger.error(t("parse_error", message: e.message)) return end end def get_repo(pl) "#{pl["repository"]["owner_name"]}/#{pl["repository"]["name"]}" end def notify_rooms(repo, data) rooms = rooms_for_repo(repo) or return message = t( "message", repo: repo, status_message: data["status_message"], commit: data["commit"][0...7], branch: data["branch"], committer_name: data["committer_name"], compare_url: data["compare_url"] ) rooms.each do |room| target = Source.new(room: room) robot.send_message(target, message) end end def rooms_for_repo(repo) rooms = config.repos[repo] default_rooms = config.default_rooms if rooms Array(rooms) elsif default_rooms Array(default_rooms) else Lita.logger.warn(t("no_room_configured"), repo: repo) return end end def validate_repo(repo, auth_hash) unless Digest::SHA2.hexdigest("#{repo}#{config.token}") == auth_hash Lita.logger.warn(t("auth_failed"), repo: repo) return end true end end Lita.register_handler(Travis) end end Lita.load_locales Dir[File.expand_path( File.join("..", "..", "..", "..", "locales", "*.yml"), __FILE__ )]
class Gym attr_reader :name @@all = [ ] def initialize(name) @name = name @@all << self end def self.all @@all end def memberships #1Get a list of all memberships at a specific gym Membership.all.select do |membership| membership.gym == self end end def lifters #2Get a list of all the lifters that have a membership to a specific gym memberships.map do |membership| membership.lifter end end def names_lifter #3 a list of the names of all lifters that have a membership to that gym lifters.map do |lifter| lifter.name end end def total_lift #4 the combined lift total of every lifter has a membership to that gym total = 0 lifters.map do |lifter| total += lifter.lift_total end end end
class AddTimestampsToAccountTransactions < ActiveRecord::Migration[6.0] def change add_timestamps :account_transactions end end
class AuthController < ApplicationController skip_after_action :verify_policy_scoped def index render json: current_user.as_json(only: [ :id, :name, :email, :image, ]) end def destroy sign_out current_user head :ok end end
class AddIndexToUsersEmail < ActiveRecord::Migration[5.1] def change # This ensures that we also have uniqueness in the DB level, not just in the model. add_index :users, :email, unique: true end end
class AddTemplateToSettings < ActiveRecord::Migration[5.2] def change add_column :settings, :template, :string, default: nil , after: :archiver_program end end
class MessageSerializer < ActiveModel::Serializer attributes :id, :title, :text, :sent_on, :received_on, :opened_on, :answered_on, :rejected_on, :picture has_one :recipient has_one :sender def picture object.picture.url end def recipient # return object.recipient if @current_user.is_admin? attributes["recipient"] = object.recipient.id end def sender # return object.sender if @current_user.is_admin? attributes["sender"] = object.sender.id end end
# # Copyright (c) 2013, 2021, Oracle and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Puppet::Type.type(:address_properties).provide(:solaris) do desc "Provider for managing Oracle Solaris address object properties" confine :operatingsystem => [:solaris] defaultfor :osfamily => :solaris, :kernelrelease => ['5.11'] commands :ipadm => '/usr/sbin/ipadm' mk_resource_methods def self.instances props = {} ipadm("show-addrprop", "-c", "-o", "ADDROBJ,PROPERTY,CURRENT,PERM").each_line do |line| addrobj, property, value, perm = line.strip().split(":") # Skip read-only properties next if perm == 'r-' # Skip empty values next if (value == nil || value.empty?) if not props.key? addrobj props[addrobj] = {} end props[addrobj][property] = value end addresses = [] props.each do |key, value| addresses << new(:name => key, :ensure => :present, :properties => value) end addresses end def self.prefetch(resources) # pull the instances on the system props = instances # set the provider for the resource to set the property_hash resources.keys.each do |name| if provider = props.find{ |prop| prop.name == name} resources[name].provider = provider end end end # Return an array of prop=value strings to change def change_props out_of_sync=[] # Compare the desired values against the current values resource[:properties].each_pair do |prop,should_be| is = properties[prop] # Current Value == Desired Value unless is == should_be # Stash out of sync property out_of_sync.push("%s=%s" % [prop, should_be]) end end out_of_sync end def properties=(value) tmp = if @resource[:temporary] == :true "-t" end change_props.each do |prop| args = [prop , tmp].compact ipadm("set-addrprop", "-p", *args, @resource[:name]) end end def exists? @property_hash[:ensure] == :present end def create fail "address_object #{address} must exist" end end
class Admin::EssayAwardsController < AdminController def new @essay_award = EssayAward.new(essay: essay) end def create @essay_award = EssayAward.new(params.require(:essay_award).permit(:award_id, :placement)) @essay_award.essay = essay if @essay_award.save flash[:success] = "Award \"#{@essay_award.title}\" added" redirect_to admin_issue_essay_path(params[:issue_id], params[:essay_id]) else render action: :new end end def edit @essay_award = EssayAward.find(params[:id]) end def update @essay_award = EssayAward.find(params[:id]) if @essay_award.update_attributes(params.require(:essay_award).permit(:award_id, :placement)) flash[:success] = "Award \"#{@essay_award.title}\" updated" redirect_to admin_issue_essay_path(params[:issue_id], params[:essay_id]) else render action: :edit end end def destroy @essay_award = EssayAward.find(params[:id]) @essay_award.destroy flash[:success] = "Award \"#{@essay_award.title}\" removed" redirect_to admin_issue_essay_path(params[:issue_id], params[:essay_id]) end private def essay @essay ||= EssayQuery.find(params[:essay_id]) end end
FactoryBot.define do factory :item do title { 'コート' } text { 'コートです' } category_id { 2 } status_id { 2 } shipping_id { 2 } prefecture_id { 2 } day_id { 2 } price { 114_514 } user end end
require 'test_helper' class ScholarshipTest < ActiveSupport::TestCase test 'unexpired returns unexpired scholarships' do nil_date = create :scholarship, close_time: nil active_date = create :scholarship, close_time: 3.days.from_now assert_equal Scholarship.unexpired, [nil_date, active_date] end test 'unexpired doesn\'t return expired scholarships' do expired_date = create :scholarship, close_time: 3.days.ago assert_not_includes Scholarship.unexpired, expired_date end end
# @param {String} text # @return {String} def arrange_words(text) text.split(/ /).sort_by{|word| word.length}.join(' ').capitalize end
class AddDteInvoiceUntaxedStartNumberToInvoice < ActiveRecord::Migration def change add_column :accounts, :dte_invoice_untaxed_start_number, :integer end end
class AddRememberTokenToAdministrators < ActiveRecord::Migration def change add_column :administrators, :remember_token, :string add_index :administrators, :remember_token end end
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2022, by Samuel Williams. def sample_progress_bar require_relative 'lib/console' progress = Console.logger.progress("Progress Bar", 10) 10.times do |i| sleep 1 progress.increment end end
# frozen_string_literal: true require "rails_helper" describe "Membership concern" do fixtures :all let(:participant) { participants(:participant1) } describe "before_validation" do context "updating a membership" do it "ensure_display_name_for_social_arms ensures display name exists for social groups" do participant.active_membership.valid? expect(participant.active_membership.errors.count).to eql 0 end end end end
class User < ApplicationRecord validates :User_name, uniqueness: true, :presence => true validates_format_of :Email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i validates :Password, :presence => true, :confirmation => true, :length => {:within => 6..8} validates_confirmation_of :Password validates :Mobile_number, :numericality => {only_integer: true }, :length => { is: 10 } validates :Gender, :numericality => false validates :Confirm_password,:presence => true has_and_belongs_to_many :courses, -> { distinct } validates_associated :courses #validates_uniqueness_of :course #validates :courses, presence: true, uniqueness:true has_attached_file :photo, styles: { large:"600x600", medium: "300x300>", thumb: "100x100>" } #validates_attachment_content_type :photo, content_type: /\Aimage\/.*\z/ #validates_attachment :photo, presence: true, content_type: { content_type: "image/jpeg" }, size: { in: 0..10.kilobytes } validates_attachment :photo, :content_type => { :content_type => /image/, :message => "photo must be an image" }, :size => { :in => 0..10.kilobytes, :message => "photo must be less than 10 kilobytes in size" } end
require "test_helper" class CoderTest < ActiveSupport::TestCase test "serializes globalid objects with text column" do notification = Notification.create!(recipient: user, type: "Example", params: {user: user}) assert_equal({user: user}, notification.params) end test "serializes globalid objects with json column" do notification = JsonNotification.create!(recipient: user, type: "Example", params: {user: user}) assert_equal({user: user}, notification.params) end test "serializes globalid objects with jsonb column" do notification = JsonbNotification.create!(recipient: user, type: "Example", params: {user: user}) assert_equal({user: user}, notification.params) end end
# ## Schema Information # # Table name: `activities` # # ### Columns # # Name | Type | Attributes # ----------------- | ------------------ | --------------------------- # **`id`** | `integer` | `not null, primary key` # **`created_at`** | `datetime` | `not null` # **`updated_at`** | `datetime` | `not null` # **`day`** | `date` | `not null` # **`detail`** | `string` | # # ### Indexes # # * `index_activities_on_day` (_unique_): # * **`day`** # FactoryGirl.define do factory :activity do day "2016-09-20" end end
require 'rails_helper' RSpec.describe Locacao, type: :model do describe "validations" do it { is_expected.to validate_presence_of(:pessoa_id) } it { is_expected.to validate_presence_of(:automovel_id) } it { is_expected.to validate_presence_of(:valor) } it { is_expected.to validate_presence_of(:data_inicio) } it { is_expected.to validate_presence_of(:data_termino) } end describe "associations" do it{ is_expected.to belong_to(:pessoa) } it{ is_expected.to belong_to(:automovel) } end context 'quando menor de 21 anos tenta alugar um automovel' do it do automovel = create(:automovel, tipo: 'carro') pessoa = create(:pessoa, data_nascimento: Date.today-20.year) habilitacao = create(:habilitacao, pessoa_id: pessoa.id, modalidades: 'B' ) locacao = build(:locacao, pessoa_id: pessoa.id) expect(locacao).to_not be_valid end end context 'quando tenta alugar um carro com habilitação vencida' do it do pessoa = create(:pessoa) automovel = create(:automovel) habilitacao = create(:habilitacao, pessoa_id: pessoa.id, validade: FFaker::Time.date-1.year ) locacao = build(:locacao, pessoa_id: pessoa.id, automovel_id: automovel.id) expect(locacao).to_not be_valid end end context 'quando tenta alugar um carro sem ter a categoria na habilitação' do it do automovel = create(:automovel, tipo: 'carro') pessoa = create(:pessoa) habilitacao = create(:habilitacao, pessoa_id: pessoa.id, modalidades: 'A' ) locacao = build(:locacao, pessoa_id: pessoa.id, automovel_id: automovel.id) expect(locacao).to_not be_valid end end context 'quando tenta alugar um carro com placa final 4 em uma quarta-feira' do it do automovel = create(:automovel, tipo: 'carro', placa: 'ABC-4444') pessoa = create(:pessoa) habilitacao = create(:habilitacao, pessoa_id: pessoa.id, modalidades: 'B' ) locacao = build(:locacao, pessoa_id: pessoa.id, automovel_id: automovel.id, data_inicio: DateTime.now.next_occurring(:wednesday), data_termino: DateTime.now.next_occurring(:wednesday)+1.day) expect(locacao).to_not be_valid end end end
require File.dirname(__FILE__) + '/../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "Invoking events" do before :each do @helper = EventHandlerHelper.new @method = @helper.method(:foo) @lambda = lambda { |s, count| @helper[:lambda] += count } @proc = proc { |s, count| @helper[:proc] += count } @klass = ClassWithEvents.new @no_event_klass = ClassWithEvents.new end it "works with methods via add" do @klass.full_event.add @method @klass.invoke_full_event(1) @helper[:method].should == 1 end it "works with lambdas via add" do @klass.full_event.add @lambda @klass.invoke_full_event(1) @helper[:lambda].should == 1 end it "works with procs via add" do @klass.full_event.add @proc @klass.invoke_full_event(1) @helper[:proc].should == 1 end it "works with to_proc syntax" do @klass.full_event &@lambda @klass.invoke_full_event(1) @helper[:lambda].should == 1 end it "works with block syntax" do @klass.full_event {|s,e| @helper[:block] += e} @klass.invoke_full_event(1) @helper[:block].should == 1 end it "works with multiple objects via add" do @klass.full_event.add @method @klass.full_event.add @proc @klass.full_event.add @lambda @klass.invoke_full_event(1) @helper[:proc].should == 1 @helper[:method].should == 1 @helper[:lambda].should == 1 end it "works with multiple of one callback via add" do @klass.full_event.add @method @klass.full_event.add @method @klass.invoke_full_event(1) @helper[:method].should == 2 end it "registers adds and removes" do @klass.full_event.add @method @klass.full_event.add @method @klass.invoke_full_event(1) @klass.full_event.remove @method @klass.invoke_full_event(1) @helper[:method].should == 3 end end
require 'dist_server/server/base_server' require 'dist_server/util/log' require 'dist_server/logic_server/center_server_proxy' require 'dist_server/logic_server/gate_server_proxy' class LogicServer < BaseServer def initialize(server_info) super(server_info) @center_server = nil @gate_list = [] @services = server_info.services end # center 和 gate 会连接过来, 他们都是remote server def on_create_new_client RemoteServer end def on_start super FSLogger.get_logger(self).info "logic server starting" for service in self.get_server_info.services FSLogger.get_logger(self).info "create service #{service}" end self.scheduler_update(1 / 1000, -1, :tick_center) end def register_gate gate = Logic::GateServerProxy.new get_sender gate.publicity_service_handler(self.get_server_info, @services) @gate_list << gate FSLogger.get_logger(self).info "gate register succ" end def register_center @center_server = Logic::CenterServerProxy.new get_sender @center_server.register_service_handler(self.get_server_info, @services) FSLogger.get_logger(self).info "center register succ" true end def tick_center(sid, dt) if @center_server @center_server.tick_sync end for gate in @gate_list gate.tick_sync end end end
# -*- encoding : utf-8 -*- module RedisModelExtension # == Class Autoincrement Id # get last id # generate autoincrement key module ClassAutoincrementId # get last id from redis def get_last_id Database.redis {|r| r.get generate_autoincrement_key } end #generate autoincrement key def generate_autoincrement_key "#{self.name.to_s.underscore.to_sym}:autoincrement_id" end end # == Autoincrement Id # increment id module AutoincrementId private # get auto incremented id from redis def increment_id Database.redis {|r| r.incr self.class.generate_autoincrement_key } end # get last id from redis def get_last_id self.class.get_last_id end end end
require 'migration_helpers' class SellersUsers < ActiveRecord::Migration extend MigrationHelpers def self.up create_table :sellers_users, :id => false do |t| t.column :seller_id, :integer, :null => false t.column :user_id, :integer, :null => false end foreign_key(:sellers_users, :seller_id, :sellers) end def self.down drop_table :sellers_users end end
class ChangeTotalInPlayers < ActiveRecord::Migration def change change_column :players, :total, :integer, limit: 2 end end
class Award < ApplicationRecord has_many :picks belongs_to :league validates :name, uniqueness: { scope: [:league_id], case_sensitive: false }, presence: true def full_name "#{name} - #{description}" end end
#!/usr/bin/env ruby # encoding : utf-8 # Given an epub file, will create an mkd file version require 'fileutils' if `which ebook-convert` == '' puts "Unable to find ebook-convert, please install calibre" exit end # Loop on each file ARGV.each do |file| epubFile = File.expand_path(file) ext = File.extname(epubFile) dirname = File.dirname(epubFile) basename = File.basename(epubFile) coverFile = epubFile.gsub(/\.epub$/, '.jpg') txtFile = epubFile.gsub(/\.epub$/, '.txt') mkdFile = epubFile.gsub(/\.epub$/, '.mkd') # Act only on epub next unless ext == '.epub' # Warn if no cover unless File.exists?(coverFile) puts "WARNING : No cover found in dir" end # Create a backup if mkd file already present if File.exists?(mkdFile) File.rename(mkdFile, mkdFile+'.bak') end # Convert to txt first puts "Converting to mkd" %x[ebook-convert "#{epubFile}" "#{txtFile}"] # Then converting (renaming) to mkd File.rename(txtFile, mkdFile) end
#!/usr/bin/env ruby $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'codebreaker' def generate_secret_code options =%w[1 2 3 4 5 6] (1..4).map { options.delete_at(rand(options.length))}.join end game = Codebreaker::Game.new(STDOUT) secret_code = generate_secret_code puts "\e[H\e[2J" at_exit { puts "\n***\nThe secret code was: #{secret_code}\n***" } game.start(secret_code) state = 'playing' while game.gamestate == true #somehow break out of loop if gamestate == won guess = gets.chomp print "Guess: ", game.guess(guess) end
require 'module_extensions' # == Synopsis # Various extensions to the Numeric class # Note, uses the Module.my_extension method to only add the method if # it doesn't already exist. class Numeric my_extension("elapsed_time_s") do # == Synopsis # return String formated as "HH:MM:SS" def elapsed_time_s seconds = self hours = minutes = 0 hours = seconds.div 3600 seconds = seconds - (hours * 3600) minutes = seconds.div 60 seconds = seconds - (minutes * 60) sprintf("%.2d:%2.2d:%2.2d", hours, minutes, seconds) end end end
class PulseMailer < ActionMailer::Base def red_over_one_day_notification(projects, options = {}) from("Pivotal Pulse <devnull+pulse-ci@pivotallabs.com>") recipients(RED_NOTIFICATION_EMAILS) subject("Projects RED for over one day!") multipart("red_over_one_day_notification", :projects => projects) end end
require 'hydramata/works/conversions/exceptions' module Hydramata module Works module Conversions private def ViewPathFragment(input) return input.to_view_path_fragment.to_s.downcase.gsub(/\W+/, '_') if input.respond_to?(:to_view_path_fragment) case input when String, Symbol then input.to_s.downcase.gsub(/\W+/, '_') when Hash then value = input[:to_view_path_fragment] || input['to_view_path_fragment'] ViewPathFragment(value) else fail ConversionError.new(:ViewPathFragment, input) end end end end end
# # Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Puppet::Type.newtype(:interface_properties) do @doc = "Manage Oracle Solaris interface properties Protocol must be defined either at the interface/resource name or in the properties hash. Preferred: name: net0 Properties: A complex hash of proto => { property => value },... { 'ipv4' => { 'mtu' => '1776' }, 'ipv6' => { 'mtu' => '2048' }, } Old Syntax: name: net0/ipv4 Properties: A hash of property => value when Interface defines protocol { 'mtu' => '1776' } " ensurable do # remove the ability to specify :absent. New values must be set. newvalue(:present) do # Do nothing end newvalue(:absent) do # We can only ensure synchronization fail "Interface properties cannot be removed" end end newparam(:name) do desc "The name of the interface" newvalues(/^[a-z_0-9]+[0-9]+(?:\/ipv[46]?)?$/) isnamevar validate do |value| unless (3..16).cover? value.split('/')[0].length fail "Invalid interface '#{value}' must be 3-16 characters" end unless /^[a-z_0-9]+[0-9]+(?:\/ipv[46]?)?$/ =~ value fail "Invalid interface name '#{value}' must match a-z _ 0-9" end end end newparam(:temporary) do desc "Optional parameter that specifies changes to the interface are temporary. Changes last until the next reboot." newvalues(:true, :false) end newproperty(:properties) do desc "A hash table of proto/propname => propvalue entries to apply to the interface OR a complex hash of { proto => { propname => propvalue },... } Values are assigned as '='; list properties must be fully specified. If proto is absent the protocol must be defined in the interface name. For proto 'ip' only the 'standby' property can be managed. See ipadm(8)" def insync?(is) # There will almost always be more properties on the system than # defined in the resource. Make sure the properties in the resource # are insync should.each_pair do |proto,hsh| return false unless is.key?(proto) hsh.each_pair do |key,value| # Stop after the first out of sync property return false unless property_matches?(is[proto][key],value) end end true end munge do |value| # If the supplied syntax isn't a hash of protocol options # reformat the value to that format if (value.keys & ["ip","ipv4","ipv6"]).empty? intf, proto = resource[:name].split('/') resource[:name] = intf value = { proto => value } end return value end end autorequire(:ip_interface) do children = catalog.resources.select do |resource| resource.type == :ip_interface && self[:name].split('/').include?(resource[:name]) end children.each.collect do |child| child[:name] end end end
class Loan < ApplicationRecord belongs_to :company, inverse_of: :loan has_many :payments, inverse_of: :loan, :dependent => :destroy accepts_nested_attributes_for :payments, reject_if: proc { |a| a[:status].blank? } after_create :calculate_overdrive def income_percent total_overdrive/sum/time*12 end private def calculate_overdrive self.total_overdrive = 0.0 payments.each do |p| case p.status when 'normal', 'all' self.total_overdrive += sum*base_percent/12.0 else #:delay self.total_overdrive += sum*delay_percent/12.0 end end self.save end end
module Adminpanel module Facebook extend ActiveSupport::Concern included do attr_accessor :fb_page_access_key, :fb_message end def share_link 'http://www.google.com' end # if return any other thing than nil, it'll send it as the picture_thumb # whenever it's posted. def share_picture nil end # static(class) methods module ClassMethods def fb_share? true end end end end
class FileFormatProfilesContentTypesJoin < ApplicationRecord belongs_to :file_format_profile belongs_to :content_type end
class ComprobantesController < ApplicationController before_action :set_comprobante, only: [:show, :edit, :update, :destroy] # GET /comprobantes # GET /comprobantes.json def index @comprobantes = Comprobante.all end # GET /comprobantes/1 # GET /comprobantes/1.json def show end # GET /comprobantes/new def new @comprobante = Comprobante.new end # GET /comprobantes/1/edit def edit end # POST /comprobantes # POST /comprobantes.json def create @comprobante = Comprobante.new(comprobante_params) respond_to do |format| if @comprobante.save format.html { redirect_to @comprobante, notice: 'Comprobante was successfully created.' } format.json { render :show, status: :created, location: @comprobante } else format.html { render :new } format.json { render json: @comprobante.errors, status: :unprocessable_entity } end end end # PATCH/PUT /comprobantes/1 # PATCH/PUT /comprobantes/1.json def update respond_to do |format| if @comprobante.update(comprobante_params) format.html { redirect_to @comprobante, notice: 'Comprobante was successfully updated.' } format.json { render :show, status: :ok, location: @comprobante } else format.html { render :edit } format.json { render json: @comprobante.errors, status: :unprocessable_entity } end end end # DELETE /comprobantes/1 # DELETE /comprobantes/1.json def destroy @comprobante.destroy respond_to do |format| format.html { redirect_to comprobantes_url, notice: 'Comprobante was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_comprobante @comprobante = Comprobante.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def comprobante_params params.require(:comprobante).permit(:IdComprobante, :Nombre_Duenio, :Paciente, :Ruc, :Direccion, :Fecha_Registro, :Detalle_Producto, :Precio_Unitario, :Precio_Total, :Cantidad) end end
class UsuariosController < ApplicationController def index @data =Time.now.strftime("%d/%m/%Y") @usuarios = Usuario.all end def show @usuario = Usuario.find(params[:id]) end def new @usuario = Usuario.new end def create @usuario = Usuario.new(params[:usuario]) if @usuario.save flash[:aviso] = 'Usuário Criado com Sucesso.' redirect_to (@usuario) #usuarios_path #, notice: "Usuario Criado com Sucesso." else render action: "new" end end def update #@escola = Escola.find_by_id(params[:id]) #@escola.update_attributes(params[:escola]) #flash[:success] = "Product donated!" @usuario = Usuario.find_by_id(params[:id]) respond_to do |format| #if @usuario.update_attributes(params[:usuario]) if @usuario.update_attributes(params[:usuario]) format.html { redirect_to usuarios_path, notice: 'Usuario Atualizado.' } format.json { head :no_content } else format.html { render action: "show" } format.json { render json: @usuarios.errors, status: :unprocessable_entity } end end end def edit @usuario = Usuario.find(params[:id]) end def destroy @usuario = Usuario.find(params[:id]) @usuario.destroy @data =Time.now.strftime("%d/%m/%Y") @usuarios = Usuario.all render action: "index" #flash[:info] = 'Usuario Excluido' #redirect_to (usuarios_path) end end
require "rails_helper" describe "Category management" do let(:user) { FactoryGirl.create(:user) } let!(:category) { FactoryGirl.create(:category_with_user, user: user) } let!(:category_two) { FactoryGirl.create(:category_with_user, user: user) } describe "show all categories" do before do get "/categories", nil, { "Authorization" => retrieve_token(user) } end it { expect(response.content_type).to eq "application/json" } it { expect(response).to have_http_status :ok } it { expect(response.body).to include "id", "#{category.id}", "#{category_two.id}" } end describe "show one category" do end describe "create a category" do end describe "update a category" do end end
class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] load_and_authorize_resource # GET /posts # GET /posts.json def index @posts = Post.all.order('updated_at DESC') @posts = @posts.select { |p| p.title.include?(params[:title]) } unless params[:title].nil? @posts = @posts.select { |p| User.find(p.user_id).email.include?(params[:author]) } unless params[:author].nil? @posts = @posts.select { |p| p.description.include?(params[:description]) } unless params[:description].nil? order = if params[:order] == 'descending' ' DESC' else ' ASC' end if params[:sort_option].present? if params[:sort_option] == 'user' @posts = Post.all.order('user_id' + order) unless params[:sort_option].empty? else @posts = Post.all.order(params[:sort_option].to_s + order) unless params[:sort_option].empty? end end @listing = Post.new.attributes.keys[1..5] @listing[2] = @listing[2][0..3] @hashtags = SimpleHashtag::Hashtag.select { |hashtag| !hashtag.hashtaggables.empty? } end def user_index @posts = current_user.posts @listing = Post.new.attributes.keys[1..5] @listing[2] = @listing[2][0..3] @hashtags = SimpleHashtag::Hashtag.select { |hashtag| !hashtag.hashtaggables.empty? } render :index end # GET /posts/1 # GET /posts/1.json def show @comments = @post.comments.hash_tree end # GET /posts/new def new @post = Post.new @video = @post.build_video end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = Post.new(post_params) @post.user_id = current_user.id if @post.save flash[:default] = 'Post was successfully created.' redirect_to @post else render :new end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update if @post.update(post_params) flash[:default] = 'Post was successfully updated.' redirect_to @post else render :edit end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy flash[:default] = 'Post was successfully destroyed.' redirect_to posts_url end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def post_params params.require(:post).permit(:title, :description, video_attributes: [:link]) end end
module TimecopConsole module MainHelper def time_travel_to(date) unless date.respond_to?(:year) && date.respond_to?(:month) && date.respond_to?(:day) raise ArgumentError, "Argument must be a Date object" end update_path = timecop_console.update_path(timecop: { 'current_time(1i)' => date.year, 'current_time(2i)' => date.month, 'current_time(3i)' => date.day, 'current_time(4i)' => 12, 'current_time(5i)' => 0 }) button_to(date.strftime("%B %d, %Y"), update_path, method: :post) end end end
# ApplicationController is the super class for all controller classes # Application controller wide functionality can be placed here class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! add_flash_types :success, :danger VALID_WISC_EMAIL_REGEX = /\A[\w+\-.]+@wisc\.edu+\z/i protected def coach? redirect_to 'users/sign_in' unless current_user render file: 'public/403.html', status: :forbidden unless current_user.has_role? :coach end def valid_wisc_email?(email) email =~ VALID_WISC_EMAIL_REGEX ? true : false end end
Given(/the following JSON schema:$/) do |schema| @schema = schema end When(/^I run the JSON data generator$/) do @output = JsonTestData.generate!(@schema) end Then(/^the JSON output should be:$/) do |json| expect(@output).to eq json end
# Create huge lang files from the :en: snippets cluttered along the app module Translator class Translator def initialize(from=:en, dir=nil) @source = from.to_sym self.dir = dir if dir end def dir=(dir); create_dir(dir); @dir = dir; end def create_dir(dir); FileUtils.mkdir_p(dir); end def default_dir; "#{Rails.root}/config/locale_gen"; end def generate(*targets) targets.flatten.each{|target|generate_for(target)} end def generate_for(target) self.dir = default_dir unless defined?(@dir) target = target.to_sym return true if target == @source I18n.t(:trigger_loading_by_this_lol) translations = I18n.backend.instance_variable_get(:@translations) translations[target] ||= {} save_generated(target, translations[target]) sort_translations(translations[@source], translations[target]) generate_recursive(translations[@source], translations[target]) save_generated(target, translations[target], '_huge_') end def sort_translations(*hashes) hashes.flatten.each{|hash|hash.sort_by_key(true) unless hash.nil?} end def generate_recursive(source, dest) source.each do |key, src| if src.is_a?(Hash) dest[key] ||= {} generate_recursive(src, dest[key]) else dest[key] = src unless dest[key] end end end def save_generated(target, dest, prefix='') sort_translations(dest) dest = nil if dest.empty? path = "#{@dir}/#{prefix}#{target}.yml" File.open(path, 'w') {|f| f.write({target => dest}.to_yaml) } end end end
#!/usr/bin/env ruby require 'optparse' require 'highline/import' require 'shipit-ios' options = {} OptionParser.new do |opts| opts.banner = "Usage: shipit-ios [ --workspace workspacename | --project projectname ] --scheme schemename --configuration configurationname [options]" opts.on("-w", "--workspace workspacename", "Xcode Workspace to use (required, or specify a project) ") do |w| options[:workspace] = w end opts.on("-p", "--project projectname", "Xcode project to use (required, or specify a workspace)") do |p| options[:project] = p end opts.on("-s", "--scheme schemename", "Scheme to build (required)") do |s| options[:scheme] = s end opts.on("-c", "--configuration configurationname", "Build configuration (optional, defaults to Xcode project default)") do |c| options[:configuration] = c end opts.on("-u", "--upload", "Actually upload the app to iTunes Connect") do |u| options[:upload] = u end opts.on("-a", "--archive", "Create xcarchive in current directory") do |a| options[:archive] = a end opts.on("-v", "--verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! ship = ShipitIos::Ship.new(options) ship.it
FactoryGirl.define do factory :article_list do name "article list" end end
class ChangeDefaultValueImage < ActiveRecord::Migration[5.1] def change change_column :tutorials, :image, :string, default: "default_image.png" end end
json.array!(@tour_times) do |tour_time| json.extract! tour_time, :id, :tour_id, :duration, :departure_date json.url tour_time_url(tour_time, format: :json) end
require 'vizier/argument-decorators/base' module Vizier #Indicated that the name of the argument has to appear on the command line #before it will be recognized. Useful for optional or alternating arguments class Named < ArgumentDecoration register_as "named" def state_consume(state, subject) term = advance_term(state) if name == term state.unsatisfied_arguments.shift state.unsatisfied_arguments.unshift(decorated) return [state] else return [] end end def state_complete(state, subject) prefix = completion_prefix(state) || "" if %r{^#{prefix.to_s}.*} =~ name.to_s return Orichalcum::CompletionResponse.create([name.to_s]) else return Orichalcum::NullCompletion.singleton end end end end
class TagsController < ApplicationController def show begin stem = params[:stem] pos = params[:pos] freqs = Session.all.sort{ |a,b| a.date <=> b.date }.collect do |s| sw = s.session_words.detect{ |w| w.stem == stem && w.pos == pos } if sw [s.date, sw.count] else [s.date, 0] end end @freqs_values = [] @freqs_legend = [] freqs.each_with_index do |v,i| @freqs_legend << [i,v[0]] @freqs_values << [i,v[1]] end @intervention_word = InterventionWord.find(:first, :conditions => ["stem=? and pos=?", stem, pos]) @sessions = SessionWord.find(:all, :conditions => ["stem=? and pos=?", stem, pos]).collect{ |sw| sw.session } @error = false rescue Exception => ex logger.error("error message: #{ex.message}") logger.error(ex.backtrace) @error = true end end end
class RandomPlayer def initialize(cakes) end # Decide who move first - player or opponent (return true if player) def firstmove(cakes) true # I want to move first end # Decide your next move (return 1, 2 or 3) def move(cakes, last) allow = [1,2,3].reject { |i| i == last } move = allow.sample move > cakes ? (cakes == last ? cakes-1 : cakes): move end end
# :nocov: module SessionsDoc extend ActiveSupport::Concern included do swagger_controller :sessions, 'Sessions' swagger_api :create do summary 'Sign in' notes 'Use this method in order to sign in' param :query, 'api_user[email]', :string, :required, 'E-mail' param :query, 'api_user[password]', :string, :required, 'Password' query = { api_user: { password: '12345678', email: 't@test.com' } } response :ok, 'Signed in', { query: query } response 401, 'Could not sign in', { query: query.merge({ password: '12345679' }) } end swagger_api :destroy do summary 'Sign out' notes 'Use this method in order to sign out' response :ok, 'Signed out', { query: {} } end end end # :nocov:
class Turn attr_reader :turn_player, :game def initialize(player, game) @turn_player = player @game = game end def pick_a_card_to_ask_for game.pass_question_to_player(turn_player, 'pick card') end def pick_a_player_to_ask game.pass_question_to_player(turn_player, 'pick player') end def play turn_player.take_card(game.fish_for_card) if turn_player.cards_left == 0 taken_cards = ask_for_card taken_cards = go_fish_if_necessary(taken_cards) pick_up_taken_cards(taken_cards) completed_set = turn_player.find_and_remove_set TurnResult.new(turn_player, asked_player, asked_card: asked_card, taken_cards: taken_cards, fished_for_card: fished_for_card, completed_set: completed_set) end private attr_accessor :asked_card, :asked_player, :fished_for_card def fish_for_card game.fish_for_card end def ask_for_card self.asked_card = pick_a_card_to_ask_for self.asked_player = pick_a_player_to_ask asked_player.give_cards_by_rank(asked_card.rank) end def go_fish_if_necessary(taken_cards) if taken_cards.empty? taken_cards = [fish_for_card] self.fished_for_card = true else self.fished_for_card = false end taken_cards end def pick_up_taken_cards(taken_cards) taken_cards.each { |card| turn_player.take_card(card) } end end
# == Schema Information # # Table name: assigned_bid_categories # # id :integer not null, primary key # project_id :integer # category_id :integer # created_at :datetime # updated_at :datetime # company_id :integer # winning_bid_id :integer # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :assigned_bid_category, :class => 'AssignedBidCategories' do project_id 1 category_id 1 end end
module JobsHelper def set_rowspan(object) if object.is_a? Job rowspan = 0 object.applicants.each do |applicant| rowspan += set_rowspan(applicant) end rowspan else if object.skills.any? object.skills.size else 1 end end end def first_applicant(job) job.applicants[0] end def website?(applicant) if applicant.website? link_to applicant.website, applicant.website else "---" end end def first_skill(applicant) applicant.skills[0].name end def more_skills?(applicant) applicant.skills.size > 1 end def total_applicants Applicant.all.count end def total_unique_skills Skill.all.map { |skill| skill.name }.uniq.count end end
FactoryGirl.define do factory :user_transaction do net_amount "9.99" fees "9.99" recipient nil exchange_rate "9.99" currency_iso_from nil currency_iso_to nil end end
class Order < ApplicationRecord belongs_to :client has_many :answers, through: :feedbacks end
require 'finite_field_element.rb' require 'infinity_point.rb' class CurvePoint attr_reader :x, :y, :curve def initialize(x, y, curve) @curve = curve @field = curve.field if x.is_a?(Fixnum) && y.is_a?(Fixnum) @x = x.in(@field) @y = y.in(@field) elsif x.is_a?(FiniteFieldElement) && y.is_a?(FiniteFieldElement) @x = x @y = y else raise "Invalid values for x and y" end end def +(other) if other.is_a? InfinityPoint return self elsif @x == other.x && @y != other.y return InfinityPoint.new elsif @x == other.x && @y == other.y m = (@x*@x*3 + @curve.a2*2*@x + @curve.a4 - @curve.a1)/(@y*2) else m = (@y - other.y) / (@x - other.x) end x3 = m*m - @curve.a2 - @x - other.x y3 = m*x3 + @y - m*@x intersection = CurvePoint.new(x3, y3, @curve) return -intersection end def -(other) self + (-other) end #could be made faster by using successive squaring def *(scalar) return 1.upto(scalar-1).reduce(self) {|sum, i| sum + self } end #sign change def -@ return CurvePoint.new(@x, -@curve.a1*@x - @curve.a3 - @y) end def to_s "Curve point: x=#{@x}, y=#{@y}" end def inspect self.to_s #"Curve point: x=#{@x}, y=#{@y}" end def eql?(other) return @x==other.x && @y==other.y && @curve==other.curve end def hash @x.value ^ (~@y.value) end end
require 'rails_helper' RSpec.describe Page, type: :model do describe "validations" do it "requires something in the url" do p = Page.new FactoryGirl.attributes_for(:page).merge({url: nil}) expect(p).to be_invalid end end end
require 'eventmachine' require 'rb_tuntap' require 'rbnacl/libsodium' require 'rbnacl' require 'digest/sha2' require 'cjdns/version' require 'cjdns/identity' require 'cjdns/util/base32' class Cjdns attr_reader :identity def initialize(identity) @identity = identity # @router, @switch = Router.new(identity), Switch.new(identity) # @tun = TUN.new(identity, 'tun1', 1312) # @switch.self_interface.on_receive do |packet| # @tun.receive(unwrap_packet(packet)) # end # @tun.on_transmit do |packet| # dest = packet.headers.destination # path = @router.find(dest) || @forwarder.find(dest) # @switch.handle(wrap_packet(packet, path)) # end end end
# frozen_string_literal: true require "ffi" require "pry" require_relative "yara/version" require_relative "yara/ffi" # TBD module Yara class Error < StandardError; end CALLBACK_MSG_RULE_MATCHING = 1 CALLBACK_MSG_RULE_NOT_MATCHING = 2 CALLBACK_MSG_SCAN_FINISHED = 3 RULE_IDENTIFIER = 1 def self.test(rule_string, test_string) user_data = UserData.new user_data[:number] = 42 scanning = true results = [] Yara::FFI.yr_initialize compiler_pointer = ::FFI::MemoryPointer.new(:pointer) Yara::FFI.yr_compiler_create(compiler_pointer) compiler_pointer = compiler_pointer.get_pointer(0) error_callback = proc do |error_level, file_name, line_number, rule, message, user_data| # noop end Yara::FFI.yr_compiler_set_callback(compiler_pointer, error_callback, user_data) Yara::FFI.yr_compiler_add_string(compiler_pointer, rule_string, nil) rules_pointer =::FFI::MemoryPointer.new(:pointer) Yara::FFI.yr_compiler_get_rules(compiler_pointer, rules_pointer) rules_pointer = rules_pointer.get_pointer(0) result_callback = proc do |context_ptr, message, message_data_ptr, user_data_ptr| rule = YrRule.new(message_data_ptr) case message when CALLBACK_MSG_RULE_MATCHING results << rule.values[RULE_IDENTIFIER] when CALLBACK_MSG_SCAN_FINISHED scanning = false end 0 # ERROR_SUCCESS end Yara::FFI.yr_rules_scan_mem( rules_pointer, test_string, test_string.bytesize, 0, result_callback, user_data, 1, ) while scanning do end results ensure Yara::FFI.yr_finalize end end
class AuthorsController < ApiController before_action :set_model, only: %i[ show update destroy ] before_action :doorkeeper_authorize!, only: %i[ create update destroy ] # GET /author def index @models = Author.all render json: @models, status: :ok end # GET /author/:id def show render json: @model, status: :ok end # POST /author def create @model = Author.create!(req_params) render json: @model, status: :ok end # PUT /author/:id def update render json: @model, status: :ok end # DELETE /author/:id def destroy @model.destroy render json: @model, status: :ok end private def req_params # whitelist params params.permit(:first_name, :last_name, :group) # params.permit(:authors, ) end def set_model @model = Author.where(id: params[:id]).first render plain: 'Author Not Found!', status: :not_found if @model.nil? end end
# Array Drills zombie_apocalypse_supplies = ["hatchet", "rations", "water jug", "binoculars", "shotgun", "compass", "CB radio", "batteries"] # 1. Iterate through the zombie_apocalypse_supplies array, # printing each item in the array separated by an asterisk # ---- def zombie_asterik(arr) zombie_arr = [] arr.each do |x| zombie_arr << "#{x}" end zombie_arr.join("*") end p zombie_asterik(zombie_apocalypse_supplies) # 2. In order to keep yourself organized, sort your zombie_apocalypse_supplies # in alphabetical order. Do not use any special built-in methods. # ---- def zombie_alphabetical(arr) x = arr.length loop do switch = false (x-1).times do |n| if arr[n] > arr[n+1] arr[n], arr[n+1] = arr[n+1], arr[n] switch = true endls end break if switch == false end arr end p zombie_alphabetical(zombie_apocalypse_supplies) # 3. Create a method to see if a particular item (string) is in the # zombie_apocalypse_supplies. Do not use any special built-in methods. # For instance: are boots in your list of supplies? # ---- def search_supplies(arr, str) arr.each_index do |idx| if arr[idx] == str return "Yes, #{str} is in the zombie apocalypse supplies." elsif arr[idx+1] == nil return "No, these #{str} are not part of the zombie supplies list." else next end end end p search_supplies(zombie_apocalypse_supplies, "boot") # 4. You can't carry too many things, you've only got room in your pack for 5. # Remove items in your zombie_apocalypse_supplies in any way you'd like, # leaving only 5. Do not use any special built-in methods. # ---- def only_five(arr) five_items = [] n = (0..4).to_a n.each do |x| five_items << arr[x] end five_items end p only_five(zombie_apocalypse_supplies) # 5. You found another survivor! This means you can combine your supplies. # Create a new combined supplies list out of your zombie_apocalypse_supplies # and their supplies below. You should get rid of any duplicate items. # Find the built-in method that helps you accomplish this in the Ruby # documentation for Arrays. other_survivor_supplies = [ "warm clothes", "rations", "compass", "camp stove", "solar battery", "flashlight"] # ---- def combine_supplies(arr1, arr2) combined_items = arr1.concat(arr2) combined_items_s = zombie_alphabetical(combined_items) combined_items_s.uniq end p combine_supplies(zombie_apocalypse_supplies, other_survivor_supplies) # Hash Drills extinct_animals = { "Tasmanian Tiger" => 1936, "Eastern Hare Wallaby" => 1890, "Dodo" => 1662, "Pyrenean Ibex" => 2000, "Passenger Pigeon" => 1914, "West African Black Rhinoceros" => 2011, "Laysan Crake" => 1923 } # 1. Iterate through extinct_animals hash, printing each key/value pair # with a dash in between the key and value, and an asterisk between each pair. # ---- def print_hsh(hsh1) hsh_ast = [] hsh1.each do |k,v| hsh_ast << "#{k}-#{v}" end hsh_ast.join("*") end p print_hsh(extinct_animals) # 2. Keep only animals in extinct_animals if they were extinct before # the year 2000. Do not use any special built-in methods. # ---- def extinct_2000(hsh1) hsh_2000 = {} hsh1.each do |k, v| if v < 2000 hsh_2000[k] = v end end hsh_2000 end p extinct_2000(extinct_animals) # 3. Our calculations were completely off, turns out all of those animals went # extinct 3 years before the date provided. Update the values in extinct_animals # so they accurately reflect what year the animal went extinct. # Do not use any special built-in methods. # ---- def extinct_correction(hsh1) updated_hsh = {} hsh1.each do |k, v| updated_hsh[k] = v-3 end updated_hsh end p extinct_correction(extinct_animals) # 4. You've heard that the following animals might be extinct, but you're not sure. # Check if they're included in extinct_animals, one by one: # "Andean Cat" # "Dodo" # "Saiga Antelope" # Do not use any special built-in methods. # ---- def check_extinct(hsh1, str) leftovers = [] hsh1.each_key do |k| if k == str return "Yes, the #{str} is extinct." end end return "No, the #{str} is not extinct." end puts check_extinct(extinct_animals, "Andean Cat") puts check_extinct(extinct_animals, "Dodo") puts check_extinct(extinct_animals, "Saiga Antelope") # 5. We just found out that the Passenger Pigeon is actually not extinct! # Remove them from extinct_animals and return the key value pair as a two item array. # Find the built-in method that helps you accomplish this in the Ruby documentation # for Hashes. # ---- def remove_animal(hsh1, str) remove_hsh = {} hsh1.each do |k, v| if k == str remove_hsh[k] = v end end remove_hsh.flatten end p remove_animal(extinct_animals, "Passenger Pigeon")
class AddColumnsToBondLettersDetail < ActiveRecord::Migration def change add_column :bond_letter_details, :document, :string add_column :bond_letter_details, :document_file_name, :string add_column :bond_letter_details, :document_content_type, :string add_column :bond_letter_details, :document_file_size, :integer add_column :bond_letter_details, :document_updated_at, :datetime end end
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT require 'errors/zax_error' # Session handshake token expired for the given request_id or # wasn't created in the first place. Client should start a new handshake module Errors class ExpiredError < ZAXError def http_fail super info "#{INFO_NEG} 'verify' for expired req #{dumpHex @data}" end end end
class CreateTvRageSyncs < ActiveRecord::Migration def change create_table :tv_rage_syncs do |t| t.string :data_type t.integer :summary_hash, limit: 8 t.datetime :created_at end create_first_sync_records unless reverting? end private def create_first_sync_records shows = Sofa::TVRage::Show.list events = Sofa::TVRage::Schedule.full(:us) TvRageSync.create data_type: 'show', summary_hash: shows.hash TvRageSync.create data_type: 'event', summary_hash: events.hash end end
require 'spec_helper' describe Stockfighter do describe '#heartbeat' do it 'should return a hash with the keys ok and error' do allow(subject.client).to receive(:heartbeat).and_return({'ok' => false, 'error' => 'No actual API was called' }) expect(subject.heartbeat).to eq({'ok' => false, 'error' => 'No actual API was called' }) end end end
class AddErrorCountToWeixinMediaNews < ActiveRecord::Migration[5.1] def change add_column :weixin_media_news, :error_count, :integer end end
Dado('que eu acesse o endereço {string}') do |url| visit url end Quando('pesquiso por {string}') do |texto| rastreamento = RastreamentoCorreiosPage.new rastreamento.informaCodigoRastreamentoEPesquisa(texto) end Então('é exibido o código {string} da encomenda no título') do |codTitulo| expect(page).to have_content codTitulo end Quando('pesquiso no google por {string}') do |texto| google = GooglePage.new google.insereTextoPesquisa(texto) end Então('é exibido o site do banco pan') do expect(page).to have_content 'https://www.bancopan.com.br' end
class ImdbLoader def self.load(id) new(id).load end def self.enqueue(id) ImdbLoadWorker.perform_async(id) end attr_reader :movie def initialize(id) @movie = Movie.find(id) end def load return unless movie.imdb_id data = Imdb::Movie.new(movie.imdb_id.gsub(/tt/, '')) return unless data.title process_data(data) movie.save end private def process_data(data) movie.imdb_vote_average = data.rating movie.imdb_vote_count = data.votes end end
class AddDefaultToCatalogs < ActiveRecord::Migration def change change_column_default :catalogs, :description, "" end end
class CreateRates < ActiveRecord::Migration[5.1] def change create_table :rates do |t| t.string :currency, limit: 3 t.decimal :rate, :precision => 10, :scale => 5 t.date :date t.timestamps end end end
require 'lame' class OpenJtalk::Mp3FileWriter def initialize(io, bit_rate = 128) @io = io @bit_rate = bit_rate end def write(header, data) encoder = LAME::Encoder.new encoder.configure do |config| config.bitrate = @bit_rate config.mode = :mono if header['number_of_channels'] == 1 config.number_of_channels = header['number_of_channels'] config.input_samplerate = header['sample_rate'] config.output_samplerate = header['sample_rate'] end data_array = data.unpack("v*") frame_size = encoder.framesize i = 0 while i < data_array.length do slice = data_array[i, frame_size] i = i + frame_size encoder.encode_short(slice, slice) do |mp3_data| @io.write mp3_data end end encoder.flush do |flush_frame| @io.write flush_frame end end def self.save(file, header, data) File.open(file, "wb") do |f| new(f).write(header, data) end end end
require 'open-uri' require 'pry' class Scraper def self.scrape_index_page(index_url) html = File.read("./fixtures/student-site/index.html") learn_students = Nokogiri::HTML(html) students = learn_students.css("div.student-card").collect do |student| {:name => student.css("div.card-text-container h4.student-name").text, :location=>student.css("div.card-text-container p.student-location").text, :profile_url=>student.css("a").attribute("href").value} end end def self.scrape_profile_page(profile_url) html = File.read(profile_url) student_profile = Nokogiri::HTML(html) scraped_profile = {} student_profile.css("div.main-wrapper").each do |studentinfo| studentinfo.css("div.vitals-container div.social-icon-container a").each do |socialmediainfo| if socialmediainfo.attribute("href").value[0,15] == "https://twitter" scraped_profile[:twitter] = socialmediainfo.attribute("href").value elsif socialmediainfo.attribute("href").value[0,20] == "https://www.linkedin" scraped_profile[:linkedin] = socialmediainfo.attribute("href").value elsif socialmediainfo.attribute("href").value[0,14] == "https://github" scraped_profile[:github] = socialmediainfo.attribute("href").value elsif socialmediainfo.attribute("href").value[0,5] == "http:" scraped_profile[:blog] = socialmediainfo.attribute("href").value end end scraped_profile[:profile_quote] = studentinfo.css("div.vitals-text-container div.profile-quote").text scraped_profile[:bio] = studentinfo.css("div.description-holder p").text end scraped_profile end end