text
stringlengths
10
2.61M
class Api::Public::TargetGroupsController < ApiController def show @target_groups = TargetGroup.by_country_code(params[:country_code]) render @target_groups end end
module ZMQ class Socket attr_reader :socket def initialize sock @socket = sock end def send msg, flags=0 p, size = if msg.is_a?(NSData) [msg.bytes, msg.length] else [msg.to_data.bytes, msg.size] end zmq_send @socket, p, size, flags end def sendmsgs msgs, flags=0 flags = NonBlocking if dontwait?(flags) msgs[0..-2].each do |msg| rc = send msg, (flags | SNDMORE) return rc unless Util.resultcode_ok?(rc) end send msgs[-1], flags end def recv flags=0 pointer = Pointer.new(Zmq_msg_t_.type) zmq_msg_init(zmq_voidify(pointer)) zmq_recvmsg(@socket, zmq_voidify(pointer), flags) to_data = zmq_msg_data(zmq_voidify(pointer)) size = zmq_msg_size(zmq_voidify(pointer)) NSData.dataWithBytes(to_data, length:size).to_str end def recvmsgs flags=0 datas = [] datas << recv(flags) while getsockopt RCVMORE datas << recv(flags) end datas end def getsockopt opt case opt when RCVMORE option_value = Pointer.new(:int) option_len = Pointer.new(:uint) option_len[0] = 4 zmq_getsockopt @socket, opt, option_value, option_len option_value[0] == 0 ? false : true end end def bind addr zmq_bind @socket, addr end def connect addr zmq_connect @socket, addr end def close zmq_close @socket end def dontwait? flags (NonBlocking & flags) == NonBlocking end alias :noblock? :dontwait? def dealloc close end end # class Socket end # module ZMQ
class Person def initialize(firstName, lastName) @firstName = firstName @lastName = lastName end def to_s "Person: #@firstName #@lastName" end end person = Person.new("Lino","Espinoza") print person
require 'optparse' require 'strscan' require 'fileutils' module Deadpool module Generator class UpstartConfig attr :active alias active? active def initialize @active = false @options = [ Deadpool::ScriptOption.new('deadpool_config_dir', '/etc/deadpool'), Deadpool::ScriptOption.new('upstart_config', '/etc/init/deadpool.conf'), Deadpool::ScriptOption.new('upstart_init', '/etc/init.d/deadpool'), Deadpool::ScriptOption.new('upstart_script', '/lib/init/upstart-job') ] define_option_methods end def generate(script_args) parse_script_args(script_args) generate_upstart_conf create_upstart_link end # :reek:FeatureEnvy def add_options_to_parser(parser) parser.separator 'Upstart:' parser.on('-u', '--upstart', 'Configure deadpool upstart service.') do @active = true end @options.each do |option| parser.on("#{option.cli_flag} PATH", String, "Default: #{option.default}") end end protected def define_option_methods @options.each do |option| define_singleton_method(option.name.to_sym) do option.value end end end def parse_script_args(script_args) @options.each { |option| option.parse_script_args(script_args) } end def generate_upstart_conf config_dir_flag = "--deadpool-config-dir=#{deadpool_config_dir}" ruby_path = `which ruby`.strip deadpool_path = `which deadpool`.strip File.open upstart_config, 'w' do |file| file.write <<~UPSTART_CONF description "Deadpool Service" author "Kirt Fitzpatrick" umask 007 start on (net-device-up and local-filesystems) stop on runlevel [016] respawn exec #{ruby_path} #{deadpool_path} --foreground #{config_dir_flag} UPSTART_CONF end puts "Created #{upstart_config}" end def create_upstart_link unless File.exist? upstart_script puts "The upstart script is not at #{upstart_script}." exit 4 end if File.exist? upstart_init puts "#{upstart_init} already exists. "\ "It should be a symbolic link that points to #{upstart_script}" exit 4 end `ln -s #{upstart_script} #{upstart_init}` puts "Created link from #{upstart_init} to #{upstart_script}" end end end end
require 'benchmark' require 'nokogiri' require 'ox' require 'colorize' # This file contains a Jmeter Performance Test Result # it contains 1.5M lines and is 51MB source_file = "test_file.xml" class NokoDocSax < Nokogiri::XML::SAX::Document attr_reader :counter def initialize @counter = 0 end def start_element name, attrs = [] ++@counter if name.eql? "httpSample" end end class OxDocSax < ::Ox::Sax attr_reader :counter def initialize @counter = 0 end def start_element(name) ++@counter if name.eql? "httpSample" end end n=10 parser1 = NokoDocSax.new parser2 = OxDocSax.new puts "Testing SAX XML Parser".colorize(:magenta) puts "==========================\n" Benchmark.bm(9) do |x| x.report("nokogiri:") { n.times do ; Nokogiri::XML::SAX::Parser.new(parser1).parse(File.open(source_file)); end } x.report("ox:") { n.times do ; Ox.sax_parse(parser2, File.open(source_file)); end } end puts "Test Completed: " + "OK".colorize(:green)
class ProjectsController < ApplicationController before_filter :authenticate_user!, except: [:show] def new @project = Project.new end def show @project = Project.find(params[:id]) end def destroy @project = Project.find(params[:id]) if(@project.destroy) flash[:success] = "Your project has been deleted" redirect_to portfolio_path else flash[:error] = "Unable to delete your project" redirect_to @project end end def edit @project = Project.find(params[:id]) end def update @project = Project.find(params[:id]) if(@project.update_attributes(app_params)) flash[:success] = "Your project has been updated" redirect_to portfolio_path else flash[:error] = "Unable to update your project" redirect_to edit_project_path(@project) end end def create @project = Project.new(app_params) if(@project.save) flash[:success] = "Your project has been created" redirect_to portfolio_path else flash[:error] = "Unable to create your project" render 'new' end end private def app_params params.require(:project).permit(:title, :description, :project_id) end end
class User < ApplicationRecord def to_string "#{id}. #{name} #{email}" end end
require "#{File.dirname(__FILE__)}/../code/Demo" def render_partial(partial, locals = {}) # assuming we want to keep the rails practice of prefixing file names # of partials with "_" Haml::Engine.new(File.read("#{File.dirname(__FILE__)}/../partials/_#{partial}.html.haml")).render(Object.new, locals) end
# frozen_string_literal: true require_relative '../lib/gamelogic' require_relative '../lib/players' RSpec.describe GameLogic do subject(:game) { GameLogic.new } describe '#check_empty_space method' do context 'when all the cells are available for marking' do it 'will return true' do game.instance_variable_set('@cells', [1, 2, 3, 4, 5, 6, 7, 8, 9]) expect(game.check_empty_space). to be true end end context 'when all the cells are already marked' do it 'will return false' do game.instance_variable_set('@cells', %w[X O X X O O X]) expect(game.check_empty_space). to be false end end end describe '#game_end method' do context 'tests various conditions of game' do it 'will give true' do allow(game).to receive(:check_empty_space).and_return(true) expect(game.game_end(nil)).to be nil end end context 'there is no winner as well as space' do it 'will give true' do allow(game).to receive(:check_empty_space).and_return(false) expect(game.game_end('X')).to be true end end end describe '#check_existance method' do context 'checks whether mark is already taken or not' it 'return true' do game.instance_variable_set('@cells', [1, 2, 3, 4, 5, 6, 7, 8, 9]) expect(game.check_existance(4)). to eq(true) end it 'return false as it is already marked by player X' do game.instance_variable_set('@cells', [1, 2, 3, 'X', 'X', 6, 7, 8, 9]) expect(game.check_existance(4)). to eq(false) end end end RSpec.describe Players do let(:players) { Players.new } describe '#change_players method' do context 'this will change status of the current player' do it 'will return other player than current player' do players.instance_variable_set('@player1', 'X') players.instance_variable_set('@player2', 'O') @current_player = @player1 expect(players.change_players).not_to eql(players.player2) end end end describe '#store_mark method' do context 'when current player is player1' do it 'should add the mark in the player1_array' do @current_player = @player1 players.instance_variable_set('@player1_array', [3, 5]) players.instance_variable_set('@mark', 7) expect(players.store_mark).to eq([3, 5, 7]) end end end describe '#check_winner method' do compositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] context 'when there are empty arrays of marks both player' do it 'will return nil' do expect(players.check_winner(compositions)).to eq(nil) end end context 'when array of one element has wining composition ' do it 'will return the player symbol' do players.instance_variable_set('@player1_array', [2, 5, 7]) players.instance_variable_set('@player2', 'O') players.instance_variable_set('@player1', 'X') players.instance_variable_set('@player2_array', [1, 2, 3]) expect(players.check_winner(compositions)).to eql(players.player2) end end end describe '#check_invalid_input method' do context 'when players entered a invalid input' do it 'will return true' do players.instance_variable_set('@mark', 20) expect(players.check_invalid_input).to be true end end context 'when players select a mark between 1 and 9' do it 'will return false' do players.instance_variable_set('@mark', 4) expect(players.check_invalid_input).to be false end end end end
pg_ver = input('pg_version') pg_dba = input('pg_dba') pg_dba_password = input('pg_dba_password') pg_db = input('pg_db') pg_host = input('pg_host') pg_log_dir = input('pg_log_dir') pg_audit_log_dir = input('pg_audit_log_dir') control "V-72975" do title "PostgreSQL must generate audit records when unsuccessful attempts to modify privileges/permissions occur." desc "Failed attempts to change the permissions, privileges, and roles granted to users and roles must be tracked. Without an audit trail, unauthorized attempts to elevate or restrict privileges could go undetected. Modifying permissions is done via the GRANT and REVOKE commands. To aid in diagnosis, it is necessary to keep track of failed attempts in addition to the successful ones." impact 0.5 tag "severity": "medium" tag "gtitle": "SRG-APP-000495-DB-000329" tag "gid": "V-72975" tag "rid": "SV-87627r2_rule" tag "stig_id": "PGS9-00-006800" tag "fix_id": "F-79421r1_fix" tag "cci": ["CCI-000172"] tag "nist": ["AU-12 c", "Rev_4"] tag "false_negatives": nil tag "false_positives": nil tag "documentable": false tag "mitigations": nil tag "severity_override_guidance": false tag "potential_impacts": nil tag "third_party_tools": nil tag "mitigation_controls": nil tag "responsibility": nil tag "ia_controls": nil desc "check", "First, as the database administrator (shown here as \"postgres\"), create a role 'bob' and a test table by running the following SQL:  $ sudo su - postgres  $ psql -c \"CREATE ROLE bob; CREATE TABLE test(id INT)\"  Next, set current role to bob and attempt to modify privileges:  $ psql -c \"SET ROLE bob; GRANT ALL PRIVILEGES ON test TO bob;\"  $ psql -c \"SET ROLE bob; REVOKE ALL PRIVILEGES ON test FROM bob;\"  Now, as the database administrator (shown here as \"postgres\"), verify the unsuccessful attempt was logged:  $ sudo su - postgres  $ cat ${PGDATA?}/pg_log/<latest_log>  2016-07-14 18:12:23.208 EDT postgres postgres ERROR: permission denied for relation test  2016-07-14 18:12:23.208 EDT postgres postgres STATEMENT: GRANT ALL PRIVILEGES ON test TO bob;  2016-07-14 18:14:52.895 EDT postgres postgres ERROR: permission denied for relation test  2016-07-14 18:14:52.895 EDT postgres postgres STATEMENT: REVOKE ALL PRIVILEGES ON test FROM bob;  If audit logs are not generated when unsuccessful attempts to modify privileges/permissions occur, this is a finding." desc "fix", "Configure PostgreSQL to produce audit records when unsuccessful attempts to modify privileges occur. All denials are logged by default if logging is enabled. To ensure that logging is enabled, review supplementary content APPENDIX-C for instructions on enabling logging." if file(pg_audit_log_dir).exist? describe command("PGPASSWORD='#{pg_dba_password}' psql -U #{pg_dba} -d #{pg_db} -h #{pg_host} -A -t -c \"CREATE ROLE fooaudit; CREATE TABLE fooaudittest (id int); SET ROLE fooaudit; GRANT ALL PRIVILEGES ON fooaudittest TO fooaudit; DROP TABLE IF EXISTS fooaudittest;\"") do its('stdout') { should match // } end describe command("cat `find #{pg_audit_log_dir} -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d\" \"` | grep \"permission denied for relation\"") do its('stdout') { should match /^.*pg_authid.*$/ } end else describe "The #{pg_audit_log_dir} directory was not found. Check path for this postgres version/install to define the value for the 'pg_audit_log_dir' inspec input parameter." do skip "The #{pg_audit_log_dir} directory was not found. Check path for this postgres version/install to define the value for the 'pg_audit_log_dir' inspec input parameter." end end end
#spec/cc_test.rb require 'rspec' require './lib/cc.rb' describe Cc do describe '#caesar_cipher' do it "Accepts two parameters, string and number, the method shifts the letters of the string along the alphabet by 'number' places" do cc = Cc.new expect(cc.caesar_cipher('dog', 3)).to eql('grj') expect(cc.caesar_cipher('amazon', 7)).to eql('hthgvu') expect(cc.caesar_cipher('wizard', 10)).to eql('gsjkbn') expect(cc.caesar_cipher('research', 6)).to eql('xkykgxin') expect(cc.caesar_cipher('tomato', 12)).to eql('faymfa') expect(cc.caesar_cipher('dashboard', 20)).to eql('xumbviulx') end end end
# encoding: utf-8 class PratosController < ApplicationController # GET /pratos # GET /pratos.json def index @pratos = Prato.all respond_to do |format| format.html # index.html.erb format.json { render json: @pratos } end end # GET /pratos/1 # GET /pratos/1.json def show @prato = Prato.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @prato } end end # GET /pratos/new # GET /pratos/new.json def new @prato = Prato.new respond_to do |format| format.html # new.html.erb format.json { render json: @prato } end end # GET /pratos/1/edit def edit @prato = Prato.find(params[:id]) end # POST /pratos # POST /pratos.json def create @prato = Prato.new(params[:prato]) respond_to do |format| if @prato.save format.html { redirect_to pratos_url, notice: 'Prato cadastrado com sucesso.' } format.json { render json: @prato, status: :created, location: @prato } else format.html { render action: "new" } format.json { render json: @prato.errors, status: :unprocessable_entity } end end end # PUT /pratos/1 # PUT /pratos/1.json def update @prato = Prato.find(params[:id]) respond_to do |format| if @prato.update_attributes(params[:prato]) format.html { redirect_to pratos_url, notice: 'Prato alterado com sucesso.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @prato.errors, status: :unprocessable_entity } end end end # DELETE /pratos/1 # DELETE /pratos/1.json def destroy @prato = Prato.find(params[:id]) @prato.destroy respond_to do |format| format.html { redirect_to pratos_url } format.json { head :no_content } end end end
require 'active_support/secure_random' module Loudmouth module Generators class InstallGenerator < Rails::Generators::Base source_root File.join(File.dirname(__FILE__), 'templates') desc "Copies a loudmouth initializer and locale files to your application." class_option :orm def copy_initializer template "loudmouth_initializer.rb", "config/initializers/loudmouth.rb" end def copy_locale #copy_file "../../../config/locales/en.yml", "config/locales/loudmouth.en.yml" end def show_readme readme "README" if behavior == :invoke end end end end
INSTRUCTION_MATCHER = /row (?<row>\d+), column (?<column>\d+)/ instructions = INSTRUCTION_MATCHER.match(INPUT) row = instructions[:row].to_i column = instructions[:column].to_i def generate(num) num * 252_533 % 33_554_393 end def code_for(row, column) num = 20_151_125 r = 1 c = 1 loop do break if r == row && c == column r, c = (r == 1) ? [c + 1, 1] : [r - 1, c + 1] num = generate(num) end num end solve!("The code at #{row}, #{column}:", code_for(row, column))
require 'net/http' require 'aws-sdk-rails' require 'json' class SQSService def initialize(sqs) @sqs = sqs end def enqueue(check, start_time) Rails.logger.debug "SQSService: Start enqueuing message" resp = @sqs.get_queue_url({ queue_name: check.queue_name, }) if check.scan_id scan = Scan.find(check.scan_id) end metadata = ScansHelper.get_metadata(scan) Rails.logger.debug "SQSService: Target queue #{resp.queue_url}" check_message = { "check_id" => check.id, "target" => check.target, "image" => check.checktype.image, "timeout" => check.checktype.timeout, "options" => check.options, "required_vars" => check.required_vars, "scan_id" => check.scan_id, "metadata" => metadata, "start_time" => start_time } resp = @sqs.send_message({ queue_url: resp.queue_url, message_body: check_message.to_json, }) Rails.logger.debug "SQSService: Message #{check.id} enqueued successfully" end end
require 'pp' require 'set' def knot lengths, list, pos, skip lens = lengths.dup size = list.size while !lens.empty? len = lens.shift list = list.cycle(2).to_a sublist = list[pos, len] sublist.reverse! cdr_start = (pos + len) % size cdr_end = size - len cdr = list[cdr_start, cdr_end] list = sublist.concat cdr list = list.rotate(-pos) pos = (pos + len + skip)%size skip += 1 end [list, pos, skip] end def knothash input ascii = input.chars.map { |x| x.ord } tail = [17, 31, 73, 47, 23] lengths = ascii.concat tail list = (0..255).to_a pos, skip = 0, 0 64.times do list, pos, skip = knot(lengths, list, pos, skip) end dense = list.each_slice(16).map do |slice| slice.reduce(:^) end dense.map { |num| format "%02x", num }.join end input = "hfdlxzhv" n = 0 count = 0 rows = [] 128.times do row = "#{input}-#{n.to_s}" knot_hash = knothash row binary = knot_hash.chars.map do |x| format "%04b", x.to_i(16) end.join rows << binary count += binary.count("1") n += 1 end p "Part 1: #{count}" def neighbors i, j coords = [ [1, 0], [-1, 0], [0, 1], [0, -1] ] coords.map do |x, y| [i + x, j + y] end end # test = <<TEST # 11010100 # 01010101 # 00001010 # 10101101 # 01101000 # 11001001 # 01000100 # 11010110 # TEST # rows = test.split "\n" # pp rows: rows unseen = Set.new rows.each_with_index do |row, i| row.chars.each_with_index do |char, j| if char == "1" unseen << [i, j] end end end p unseen regions = 0 until unseen.empty? queue = [] queue.push unseen.first until queue.empty? x, y = queue.shift if unseen.include?([x, y]) unseen.delete([x, y]) queue.concat neighbors(x, y) end end regions += 1 end p "Part 2: #{regions}"
# Translates model.User Java objects to User Ruby objects class UserTranslator def translate(java_user) ruby_user = User.where(:rdbms_id => java_user.getId).first ruby_user ||= User.new ruby_user.rdbms_id = java_user.getId ruby_user.username = java_user.getUsername ruby_user.save! ruby_user end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module Parsers class UnicodeRegexParser # This is analogous to ICU's UnicodeSet class. class CharacterClass < Component GROUPING_PAIRS = { close_bracket: :open_bracket } # Character classes can include set operations (eg. union, intersection, etc). BinaryOperator = Struct.new(:operator, :left, :right) do def type :binary_operator end end UnaryOperator = Struct.new(:operator, :child) do def type :unary_operator end end class << self def opening_types @opening_types ||= GROUPING_PAIRS.values end def closing_types @closing_types ||= GROUPING_PAIRS.keys end def opening_type_for(type) GROUPING_PAIRS[type] end end def initialize(root) @root = root end def type :character_class end def to_regexp_str set_to_regex(to_set) end def to_set evaluate(root) end def codepoints codepoints_from(root) end def to_s stringify(root) end def negated? root.type == :unary_operator && root.operator == :negate end private attr_reader :root def codepoints_from(node) case node when UnaryOperator codepoints_from(node.child) when BinaryOperator codepoints_from(node.left) + codepoints_from(node.right) else node.codepoints end end def stringify(node) case node when UnaryOperator, BinaryOperator op_str = case node.operator when :negate then '^' when :union, :pipe then '' when :dash then '-' when :ampersand then '&' end left = stringify(node.left) right = stringify(node.right) "#{left}#{op_str}#{right}" else node.to_s end end def evaluate(node) case node when UnaryOperator, BinaryOperator case node.operator when :negate TwitterCldr::Shared::UnicodeRegex.valid_regexp_chars.subtract( evaluate(node.child) ) when :union, :pipe evaluate(node.left).union( evaluate(node.right) ) when :dash evaluate(node.left).difference( evaluate(node.right) ) when :ampersand evaluate(node.left).intersection( evaluate(node.right) ) end else if node node.to_set else TwitterCldr::Utils::RangeSet.new([]) end end end end end end end
require 'yaml' class VariationReader @tabix = 'tabix' def initialize(chromosome, vcf, output_dir) @chr = chromosome @file = vcf @output_dir = output_dir raise IOError "#{@output_dir} does not exist." unless File.exists?@output_dir end def set_tabix(tabix) @tabix = tabix end def read_variations(bpwindow, maxlength) # File per chromosome SNP/indel counts vout = File.open("#{@output_dir}/chr#{@chr}-counts.txt", 'w') vout.write("# Counts per #{bpwindow} base pairs\n") vout.write(['BIN','SNP', 'INDEL'].join("\t") + "\n") warnings = [] bins = (maxlength.to_i/bpwindow.to_i).ceil min = 0; max = 0 bins.times do max += bpwindow.to_i tabix_opt = "#{@chr}:#{min}-#{max}" vcf_file = "#{@output_dir}/tmp/chr#{@chr}:#{min}-#{max}.vcf" cmd = "#{@tabix} #{@file} #{tabix_opt} > #{vcf_file}" sys = system("#{cmd}") warnings << "tabix failed to run on #{@file}, please check that it is installed an available in your system path." unless sys begin snp_count, indel_count = 0, 0 File.open(vcf_file, 'r').each_line do |line| line.chomp! vcf = Vcf.new(line) vcf.samples.clear snp_count += 1 if vcf.info['VT'].eql? 'SNP' indel_count += 1 if vcf.info['VT'].eql? 'INDEL' end vout.write(["#{min}-#{max}", snp_count, indel_count].join("\t") + "\n") rescue Errno::ENOENT => e warnings << "File not found: #{vcf_file}. #{e.message}" end min = max end return {:warnings => warnings, :bins => bins, :output => "#{@output_dir}/chr#{@chr}-counts.txt"} end end
class ImageSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :id, :image_element, :user_id, :user, :client_id, :client def image_element if object.image_element.attached? { url: rails_blob_url(object.image_element) } end end end
require "../factory/*" class TableTray < Factory def initialize(caption:) super(caption: caption) end def make_html buffer = String.new buffer.add("<td>¥n") buffer.add("<table width=\"100%\" border=\"1\">") buffer.add("<td bgcolor=\"#cccccc\" align=\"centor\" colspan=\"#{tray.size}\"><b> #{caption}</b></td>") buffer.add("</tr>¥n") buffer.add("<tr>¥n") item.each do |i| buffer.add(i.make_html) end buffer.add("</tr></table>¥n") buffer.add("</ld>¥n") buffer.to_s end end
# # Cookbook Name:: replica-test # Recipe:: replica # # Copyright 2015, Dave Shawley # # 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. # include_recipe 'python' include_recipe 'supervisor' devpi_server '/opt/devpi/slave' do port 3143 replicate 'http://localhost:3142' end supervisor_service 'devpi-replica' do command '/opt/devpi/slave/bin/devpi-server --port 3143 --role replica --master-url http://localhost:3142 --serverdir /opt/devpi/slave/data' user 'devpi' action :enable autostart true end
require_relative 'open_uri_cache/version' require 'fileutils' require 'pathname' require 'open-uri' require 'cgi' require 'json' module OpenUriCache class SuccessCheckError < StandardError; end class CacheFile < File private_class_method :new def set_info(info) @info = info end def method_missing(name) n = name.to_s if @info.has_key? n @info[n] else super end end def self.open(file_path, info, *args) f = super(file_path, *args) f.set_info(info) f end end class Cache def initialize(uri, dir) @uri = uri @dir = Pathname.new(dir).join(uri.gsub(/^(https?|ftp):\/\//, '')) @content_path = "#{@dir}/content" @info_path = "#{@dir}/info.json" delete_expired_cache end def delete_expired_cache return unless exist? if Time.now > Time.parse(info_json['expiration']) delete end end def info_json JSON.parse File.open(@info_path, 'r') {|f| f.read } end def delete File.delete @content_path File.delete @info_path Dir.rmdir @dir rescue nil end def exist? File.exist? @content_path and File.exist? @info_path end def save(content, info) FileUtils.mkdir_p(@dir) File.open(@content_path, 'wb+') {|f| f.write content } File.open(@info_path, 'w+') {|f| f.puts info.to_json } end def open(*args) CacheFile.open(@content_path, info_json, *args) end end DEFAULT_CACHE_DIRECTORY = "#{ENV['HOME']}/.open_uri_cache" def self.open(uri, *rest, cache_dir: DEFAULT_CACHE_DIRECTORY, expiration: nil, after: nil, sleep_sec: 0, retry_num: 0, success_check: lambda {|f| true }) if after expiration = Time.now + after end expiration ||= Time.new(9999, 1, 1) cache = Cache.new(uri, cache_dir) if cache.exist? return cache.open(*rest) end begin sleep sleep_sec f = Kernel.open(uri, 'rb') raise SuccessCheckError unless success_check.call f rescue retry_num -= 1 retry if retry_num>=0 raise end info = { expiration: expiration, base_uri: f.base_uri, charset: f.charset, content_encoding: f.content_encoding, content_type: f.content_type, last_modified: f.last_modified, meta: f.meta, status: f.status, } cache.save(f.read, info) rescue cache.delete f.rewind return f end end
class ImportWorker include Sidekiq::Worker sidekiq_options queue: "importer_default", retry: false def perform(import_id) import = Import.find(import_id) # it would be nice if worker abort could be handled here instead of deep in the model =\ import.abort_key = ImportWorker.abort_key(jid) import.run_now end # manage abort signals, takes same signature as `perform` def self.abort(import_id) queue_name = get_sidekiq_options['queue'] # eg 'importer_default' # Remove all pending ImportWorker jobs for @import.uuid queue = Sidekiq::Queue.new(queue_name) queue.each do |q| q.delete if q.item['args'] == [import_id] end # job doesn't listen for `.quiet!` nor `.stop!' so it would get pushed back on queue (and worker would be dead) # instead, push a short-lived key into Redis for the worker to periodically check # ps = Sidekiq::ProcessSet.new workers = Sidekiq::Workers.new workers.each do |process_id, thread_id, work| if work['queue'] == queue_name && work['payload']['args'] == [import_id] # ps.detect{|p| p['pid'] == process_id}.try(:stop!) abort_key = abort_key(work['payload']['jid']) Sidekiq.redis do |c| c.setex abort_key, 2.minutes, 'abort' end end end end def self.abort_key(jid) "ImportWorker:#{jid}" end end
class UsersConfirmService def initialize(user) @user = user end def execute create_main_album end private attr_reader :user def create_main_album profile = user.profile profile.albums.create(name: 'Main album', is_main: true) unless profile.albums.any? end end
require 'spec_helper' SIZES = ['Square 75', 'Thumbnail', 'Square 150', 'Small 240', 'Small 320', 'Medium 500', 'Medium 640', 'Medium 800', 'Large 1024'] describe Flickrie::Photo do def test_sizes(photo) # TODO: simplify this # non-bang versions [ [[photo.square(75), photo.square75], ['Square 75', '75x75']], [[photo.thumbnail], ['Thumbnail', '75x100']], [[photo.square(150), photo.square150], ['Square 150', '150x150']], [[photo.small(240), photo.small240], ['Small 240', '180x240']], [[photo.small(320), photo.small320], ['Small 320', '240x320']], [[photo.medium(500), photo.medium500], ['Medium 500', '375x500']], [[photo.medium(640), photo.medium640], ['Medium 640', '480x640']], [[photo.medium(800), photo.medium800], ['Medium 800', '600x800']], [[photo.large(1024), photo.large1024], ['Large 1024', '768x1024']] ]. each do |photos, expected_values| flickr_size, size = expected_values photos.each do |photo| photo.size.should eq(flickr_size) [photo.width, photo.height].join('x').should eq(size) photo.source_url.should_not be_empty end end # bang versions [ [[proc { photo.square!(75) }, proc { photo.square75! }], ['Square 75', '75x75']], [[proc { photo.thumbnail! }], ['Thumbnail', '75x100']], [[proc { photo.square!(150) }, proc { photo.square150! }], ['Square 150', '150x150']], [[proc { photo.small!(240) }, proc { photo.small240! }], ['Small 240', '180x240']], [[proc { photo.small!(320) }, proc { photo.small320! }], ['Small 320', '240x320']], [[proc { photo.medium!(500) }, proc { photo.medium500! }], ['Medium 500', '375x500']], [[proc { photo.medium!(640) }, proc { photo.medium640! }], ['Medium 640', '480x640']], [[proc { photo.medium!(800) }, proc { photo.medium800! }], ['Medium 800', '600x800']], [[proc { photo.large!(1024) }, proc { photo.large1024! }], ['Large 1024', '768x1024']] ]. each do |blocks, expected_values| flickr_size, size = expected_values blocks.each do |block| result_photo = block.call [result_photo, photo].each do |photo| photo.size.should eq(flickr_size) [photo.width, photo.height].join('x').should eq(size) photo.source_url.should_not be_empty end end end end context "get sizes" do it "should have attributes correctly set", :vcr do [ Flickrie.get_photo_sizes(PHOTO_ID), Flickrie::Photo.public_new('id' => PHOTO_ID).get_sizes ]. each do |photo| photo.can_download?.should be_true photo.can_blog?.should be_false photo.can_print?.should be_false test_sizes(photo) photo.available_sizes.should eq(SIZES) end end end context "search" do it "should have all sizes available", :vcr do photo = Flickrie.search_photos(:user_id => USER_NSID, :extras => EXTRAS). find { |photo| photo.id == PHOTO_ID } photo.available_sizes.should eq(SIZES) end end context "get info" do it "should have all attributes correctly set", :vcr do photo = Flickrie.get_photo_info(PHOTO_ID) photo.rotation.should eq(90) end end context "blank" do it "should have all attributes equal to nil" do photo = Flickrie::Photo.public_new photo.width.should be_nil photo.height.should be_nil photo.source_url.should be_nil photo.rotation.should be_nil photo.available_sizes.should be_empty photo.size.should be_nil [ photo.square(75), photo.square(150), photo.thumbnail, photo.small(240), photo.small(320), photo.medium(500), photo.medium(640), photo.medium(800), photo.large(1024), photo.original, photo.square75, photo.square150, photo.small240, photo.small320, photo.medium500, photo.medium640, photo.medium800, photo.large1024, photo.largest ]. each do |photo| photo.source_url.should be_nil photo.width.should be_nil photo.height.should be_nil end [ proc { photo.square!(75) }, proc { photo.square!(150) }, proc { photo.thumbnail! }, proc { photo.small!(240) }, proc { photo.small!(320) }, proc { photo.medium!(500) }, proc { photo.medium!(640) }, proc { photo.medium!(800) }, proc { photo.large!(1024) }, proc { photo.original! }, proc { photo.square75! }, proc { photo.square150! }, proc { photo.small240! }, proc { photo.small320! }, proc { photo.medium500! }, proc { photo.medium640! }, proc { photo.medium800! }, proc { photo.large1024! }, proc { photo.largest! } ]. each do |prok| prok.call photo.source_url.should be_nil photo.width.should be_nil photo.height.should be_nil end end end end
class AddFollupUpDateToClientStatuses < ActiveRecord::Migration[5.1] def change add_column :client_statuses, :followup_date, :integer ClientStatus.reset_column_information active_status = ClientStatus.find_by(name: 'Active') active_status.update!(followup_date: 25) if active_status training_status = ClientStatus.find_by(name: 'Training') training_status.update!(followup_date: 25) if training_status exited_status = ClientStatus.find_by(name: 'Exited') exited_status.update!(followup_date: 85) if exited_status change_column_null :client_statuses, :followup_date, false end end
Facter.add(:pagesize) do confine :kernel => "Linux" setcode do Facter::Util::Resolution.exec('getconf PAGESIZE') end end
class Ingredient attr_accessor :cost, :name def initialize(hash) @name = hash[:name] @cost = hash[:cost] end def ==(obj) if self.__id__ != obj.__id__ && self.name == obj.name && self.cost == obj.cost true else false end end end
class FanDashboardsController < ApplicationController before_action :ensure_fan_account, only: [:show] def show @venues = Venue.where(state: current_account.location) @concerts = Concert.where(venue_id: @venues).upcoming.page params[:page] end end
class AssessmentDate < ActiveRecord::Base belongs_to :assessment_group belongs_to :batch validate :check_dates def check_dates errors.add(:start_date, :start_date_cant_be_after_end_date) if start_date > end_date end def self.save_dates(params) params[:batch_ids].each do |batch_id| dates = self.find_or_initialize_by_batch_id_and_assessment_group_id("start_date"=>params[:start_date],"end_date"=>params[:end_date],"batch_id"=>batch_id,"assessment_group_id"=>params[:assessment_group_id]) if dates.new_record? dates.save else dates.update_attributes("start_date"=>params[:start_date],"end_date"=>params[:end_date],"batch_id"=>batch_id,"assessment_group_id"=>params[:assessment_group_id]) end end end end
class CreateCategories < ActiveRecord::Migration def change create_table(:market_categories) do |t| t.text :name, null: false t.integer :position, default: 0 t.index :position t.references :category t.foreign_key :market_categories, column: :category_id t.index :category_id t.timestamps end end end
Given(/^I have signed up$/) do visit '/new_player' fill_in :playername, :with => :playername end When(/^I click on "(.*?)"$/) do |text| click_button "Register" end Then(/^I should go to the game page$/) do expect(current_path).to eq('/') end Given(/^I am on the game page$/) do visit '/game' end When(/^I see "(.*?)"$/) do |text| expect(page).to have_content text end Then(/^I should find "(.*?)" and "(.*?)" and "(.*?)"$/) do |one, two, three| expect(page).to have_content one expect(page).to have_content two expect(page).to have_content three end When(/^I click one of the choices$/) do choose("choice", :option => "Rock") click_button "Lets go!" end Then(/^I should be taken to end game page$/) do expect(current_path).to eq('/end_game') end Given(/^I have chosen one of the options$/) do visit '/game' choose("choice", :option => "Rock") click_button "Lets go!" end When(/^the computer should also generate a choice$/) do expect(page).to have_content @game_choice end Then(/^it should be able to compare them and declare a winner$/) do expect(page).to have_content end
class Comment < ActiveRecord::Base acts_as_nested_set scope: [:commentable_id, :commentable_type] validates :body, presence: true validates :user, presence: true validates :email, :full_name, presence: true, if: :guest_user? # NOTE: install the acts_as_votable plugin if you # want user to vote on the quality of comments. #acts_as_votable belongs_to :commentable, polymorphic: true # NOTE: Comments belong to a user belongs_to :user # Helper class method that allows you to build a comment # by passing a commentable object, a user_id, and comment text # example in readme def self.build_from(obj, user_id, comment_params) new( commentable: obj, user_id: user_id, body: comment_params[:body], title: comment_params[:title], subject: comment_params[:subject], parent_id: comment_params[:parent_id], email: comment_params[:email], full_name: comment_params[:full_name] ) end #helper method to check if a comment has children def has_children? self.children.any? end def guest_user? user.try(:guest?) end # Helper class method to lookup all comments assigned # to all commentable types for a given user. scope :find_comments_by_user, lambda { |user| where(:user_id => user.id).order('created_at DESC') } # Helper class method to look up all comments for # commentable class name and commentable id. scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id| where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC') } # Helper class method to look up a commentable object # given the commentable class name and id def self.find_commentable(commentable_str, commentable_id) commentable_str.constantize.find(commentable_id) end end
class Address < ApplicationRecord belongs_to :user, optional: true has_one :product validates :postal_code, :city, :address, :prefecture_id, presence: true # active_hashで都道府県データを導入する extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :prefecture end
class TransactionDetail < ActiveRecord::Base belongs_to :transaction belongs_to :product validates :product_id, presence: true validates :amount, presence: true, numericality: { only_integer: true } end
require 'spec_helper' require 'crc_examples' require 'digest/crc32' describe Digest::CRC32 do before(:all) do @crc_class = Digest::CRC32 @string = '1234567890' @expected = '261daee5' end it_should_behave_like "CRC" end
class Category < ApplicationRecord belongs_to :style has_many :articles end
class Puppy def initialize puts "Initializing new puppy instance..." end def fetch(toy) puts "I brought back the #{toy}!" toy end def speak(quantity) quantity.times {puts "Woof!"} end def roll_over puts "*rolls over*" end def dog_years(years) puts years * 7 end def chases_tail(quantity) quantity.times {puts "chases tail"} end end class Car def initialize puts "Initializing new car class..." end def starter puts "*turns key*" puts "engine rumbles" end def gas_pedal(interger) if interger == 0 puts "we're not getting anywhere soon..." elsif interger == 1 puts "now we're getting somewhere" elsif interger == 2 puts "woah baby now thats some speed!" elsif interger >= 3 puts "TOO FAST TOO FAST" end end def horn(interger) interger.times {puts "Beep!"} end end #driver code rex = Puppy.new rex.fetch("ball") rex.speak(3) rex.roll_over rex.dog_years(3) rex.chases_tail(2) # dodge = Car.new # dodge.starter # dodge.gas_pedal(1) # dodge.horn(2) #creates array to store each instance created car_array = [] #sets up iteration for desired amount of times 50.times {car_array << Car.new} #iteration that calls our methods car_array.each do |car_instance| car_instance.starter car_instance.gas_pedal(1) car_instance.horn(3) end
class Equation def self.solve_quadratic(a, b, c) if a == 0 #pokud 'a' je nula if b == 0 #a 'b' je taky nula return nil #tak vrať 'nil' else x = -c.to_f / b return [x] #jinak vrať 'x' (b*x + c = 0 -> x = -c / b) end else #pokud 'a' není nula d = b**2 - 4*a*c #vypočitej diskriminant if d > 0 #pokud je diskriminant kladný x1 = (-b + Math.sqrt(d)).to_f / (2 * a) x2 = (-b - Math.sqrt(d)).to_f / (2 * a) return [x1, x2] #vrať dva možné kořeny 'x' elsif d == 0 #pokud je diskriminant nulový x = -b.to_f / (2 * a) return [x] #vrať jen jeden kořen else return nil #jinak 'nil' end end end end
require 'spec_helper' module Belafonte describe ArgumentProcessor do describe '.new' do it 'processes the arguments' do expect_any_instance_of(described_class).to receive(:process).and_call_original described_class.new(argv: [], arguments: []) end it 'requires an argv array option' do expect{described_class.new(arguments: [])}.to raise_error(ArgumentError) expect{described_class.new(argv: [], arguments: [])}.not_to raise_error end it 'requires an arguments array option' do expect{described_class.new(argv: [])}.to raise_error(ArgumentError) expect{described_class.new(argv: [], arguments: [])}.not_to raise_error end it 'raises an error if too many args are provided' do expect {described_class.new(argv: [1], arguments: [])}. to raise_error( Belafonte::Errors::TooManyArguments, "More args provided than I can handle" ) end end describe '#processed' do let(:arg_1) {Belafonte::Argument.new(name: :arg_1, times: 1)} let(:arg_2) {Belafonte::Argument.new(name: :arg_2, times: 2)} let(:arg_3) {Belafonte::Argument.new(name: :arg_3, times: :unlimited)} let(:args) {[arg_1, arg_2, arg_3]} let(:argv) {['work', 'senora', 'work your body line']} let(:processor) { described_class.new(argv: argv, arguments: args) } let(:processed) {processor.processed} it 'is a Hash' do expect(processed).to be_a(Hash) puts "processed == '#{processed}'" end it 'contains an array for each of the processed arguments' do args.each do |arg| expect(processed[arg.name]).to be_a(Array) end end it 'provides an array with an empty string for empty unlimited args' do expect(processed[:arg_3]).to eql([""]) end end end end
#!/usr/bin/env ruby {{ruby_copyright}} require 'gli' require '{{project_name}}' include GLI::App arguments :strict subcommand_option_handling :normal program_desc 'Sample application' desc 'To-do list file name' flag [:f, :file], default_value: File.join(ENV['HOME'],'.{{project_name}}') pre do |global_options, command, options, args| $to_do_list = {{ project_name | underscore | camelize }}::ToDoList.new(global_options[:file]) end desc 'Add to-do item' arg :text command :add do |c| c.action do |global_options, options, (text)| $to_do_list.add_item(text) end end desc 'List to-do items' command :list do |c| c.action do |global_options, options| $to_do_list.items.each do |item| printf("%5d - %s\n", item.id, item.text) end end end desc 'Mark to-do item as done' arg :id command :done do |c| c.action do |global_options, options, (id_s)| id = id_s.to_i $to_do_list.items.each do |item| $to_do_list.mark_done(item) if item.id == id end end end exit run(ARGV)
module Contentful class RecipeService CONTENT_TYPE = 'recipe'.freeze RESPONSE_TYPE = { success: 200, api_error: 401, not_found: 404, }.freeze def perform(method_name, *arguments) begin { data: self.send(method_name, *arguments), status: map_status(:success) } rescue => e { data: [], status: map_status(e.message)} end end private def recipes_list recipes = [] Webservice.client.entries(content_type: CONTENT_TYPE, order: '-sys.createdAt').each_item do |recipe| recipes << map_recipe_fields_short(recipe.fields).merge({id: recipe.id}) end recipes end def recipe_details(recipe_id) recipe = Webservice.client.entry(recipe_id) raise 'not_found' if recipe.nil? map_recipe_extended(recipe.fields) end def map_recipe_fields_short(recipe_fields) { title: recipe_fields[:title], image: recipe_fields[:photo] && "https:#{recipe_fields[:photo].url}" } end def map_recipe_extended(recipe_fields) { description: recipe_fields[:description], chef_name: recipe_fields[:chef] && recipe_fields[:chef].fields[:name], tags_list: recipe_fields[:tags] && recipe_fields[:tags].collect{ |tag| tag.fields[:name] } }.merge(map_recipe_fields_short(recipe_fields)) end def map_status(response_type) key = RESPONSE_TYPE.has_key?(response_type.to_sym) ? response_type.to_sym : :api_error #fallback RESPONSE_TYPE[key] end end end
# This file contains the fastlane.tools configuration # You can find the documentation at https://docs.fastlane.tools # # For a list of all available actions, check out # # https://docs.fastlane.tools/actions # # For a list of all available plugins, check out # # https://docs.fastlane.tools/plugins/available-plugins # # Uncomment the line if you want fastlane to automatically update itself # update_fastlane platform :android do desc 'Build the Android application.' lane :build do |options| gradle(task: 'clean', project_dir: 'android/') gradle( task: 'bundle', build_type: 'Release', project_dir: 'android/', ) end desc 'Ship to Playstore Alpha.' lane :alpha do |options| build upload_to_play_store( package_name: ENV['ANDROID_APPLICATION_ID'], track: 'alpha', json_key: 'fastlane/googlePlaySecretKey.json' ) end desc 'Ship to Playstore Beta.' lane :beta do |options| upload_to_play_store( package_name: ENV['ANDROID_APPLICATION_ID'], track: 'alpha', track_promote_to: "beta", json_key: 'fastlane/googlePlaySecretKey.json' ) end desc 'Ship to Playstore Production.' lane :production do |options| upload_to_play_store( package_name: ENV['ANDROID_APPLICATION_ID'], track: 'beta', track_promote_to: "production", json_key: 'fastlane/googlePlaySecretKey.json' ) end end platform :ios do # iOS Lanes desc 'Fetch certificates and provisioning profiles' lane :certificates do # Before calling match, we make sure all our devices are registered on the Apple Developer Portal create_keychain( name: ENV["MATCH_KEYCHAIN_NAME"], password: ENV["MATCH_KEYCHAIN_PASSWORD"], default_keychain: true, unlock: true, timeout: 3600, add_to_search_list: true ) unlock_keychain( path: ENV["MATCH_KEYCHAIN_NAME"], add_to_search_list: :replace, password: ENV['MATCH_KEYCHAIN_PASSWORD'] ) match( readonly: true, type: 'appstore', storage_mode: 'git', keychain_name: ENV["MATCH_KEYCHAIN_NAME"], keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"], username: ENV['APPLE_USERNAME'], app_identifier: ENV['IOS_APPLICATION_ID'] ) end desc 'Build the iOS application.' lane :build do certificates gym( scheme: 'mobile', workspace: './ios/mobile.xcworkspace', include_bitcode: true ) end desc 'Upload symbols to Crashlytics.' lane :uploadToCrashlytics do upload_symbols_to_crashlytics( dsym_path: "./mobile.app.dSYM.zip", binary_path: "./mobile.ipa" ) end desc 'Ship to Appstore Testflight.' lane :uploadToTestflight do # build pilot( skip_waiting_for_build_processing: true ) end desc 'Ship to Appstore Production.' lane :production do deliver( submit_for_review: true, automatic_release: true, force: true, # Skip HTMl report verification, skip_binary_upload: true ) end end
class State < ActiveRecord::Base belongs_to :nation has_many :towns validates :name, presence: true end
class Createforiegnkeypaymentidincustomermobile < ActiveRecord::Migration[5.0] def change add_foreign_key :customer_mobiles, :invoices, column: :payment_id, primary_key: :id end end
describe ManageIQ::PostgresHaAdmin::ConfigHandler do describe "#before_failover" do it "raises an ArgumentError if called without a block" do expect { subject.before_failover }.to raise_error(ArgumentError) end end describe "#after_failover" do it "raises an ArgumentError if called without a block" do expect { subject.after_failover }.to raise_error(ArgumentError) end end describe "#do_before_failover" do it "runs with no callback registered" do subject.do_before_failover end it "calls the registered failover" do before_failover_obj = double("before_failover_object") subject.before_failover do before_failover_obj.before_failover_things end expect(before_failover_obj).to receive(:before_failover_things) subject.do_before_failover end end describe "#do_after_failover" do it "runs with no callback registered" do subject.do_after_failover(:host => "db.example.com") end it "calls the registered failover" do after_failover_obj = double("after_failover_object") subject.after_failover do |new_conninfo| after_failover_obj.after_failover_things(new_conninfo) end expect(after_failover_obj).to receive(:after_failover_things).with({:host => "db.example.com"}) subject.do_after_failover({:host => "db.example.com"}) end end end
class Item include Mongoid::Document include Mongoid::Paperclip include Sunspot::Mongoid2 include Mongoid::Slug #has_mongoid_attached_file :picture, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png" #active_admin purpose field :bids_id, type: String #fileds field :auction_name, type: String field :organization_name, type: String field :charity_type, type: String field :contact_name, type: String field :address, type: String field :state, type: String field :city, type: String field :zip_code, type: String field :phone_number, type: String field :unique_url, type: String field :price, type: Float field :start_time, type: Time field :end_time, type: Time field :is_expired, type: Boolean field :is_deleted, type: Boolean field :dl_community, type: Boolean field :live_event, type: Boolean field :seller_id, type: String field :delete_request, type: Boolean field :delete_reason, type: Boolean field :winner_id, type: String field :is_sold, type: Boolean field :paid, type: Boolean field :find_by_item_id slug :auction_name, :history => true belongs_to :user has_many :bids, :dependent => :destroy has_many :foo_images, :dependent => :destroy # Photoes of the dish has_many :comments, :dependent => :destroy accepts_nested_attributes_for :foo_images, :allow_destroy => true searchable do text :auction_name text :organization_name text :charity_type end #validations validates :unique_url, uniqueness: true def expired? Time.now >= self.end_time ? true : false end def is_expired expired? ? true :false end def winner_id if expired? return Bid.find_by_id(self.id).buyer_id return Bid.find_by_item_id(self.id).buyer_id Bid.all.each do|b| if b.item_id===self.id return b.buyer_id return User.find_by_id(b.buyer_id) end end else "Pending......." end end def is_sold return self.paid end end
class TiposubtipoSerializer < ActiveModel::Serializer attributes :id, :tasa_co, :tasa_runt, :valor_prima belongs_to :edad end
require 'openssl' require 'base64' require 'net/http' require 'uri' require 'json' require 'cgi' require 'digest/sha2' require 'time' class Amazonapi < ActiveRecord::Base def self.request(jan_code) aws_host = 'webservices.amazon.co.jp' if Rails.env == 'development' keys = YAML::load(File.open("#{Rails.root.to_s}/config/apikey.yml")) access_key = keys['amazon']['access_key'] secret_key = keys['amazon']['secret_key'] elsif Rails.env == 'production' access_key = Rails.application.secrets.amazon_access_key secret_key = Rails.application.secrets.amazon_secret_key end req = ["Service=AWSECommerceService", "AWSAccessKeyId=#{access_key}", "Version=2009-06-01"] req << "Operation=ItemSearch" req << "Keywords=#{jan_code}" req << "Timestamp=#{CGI.escape(Time.now.getutc.iso8601)}" req << "AssociateTag=suiyujin-22" req << "Condition=All" req << "Merchant=All" req << "SearchIndex=Grocery" req.sort! message = ['GET',aws_host,'/onca/xml',req.join('&')].join("\n") sign = make_signature(secret_key, message) req << "Signature=#{CGI.escape(sign)}" webapi( "http://#{aws_host}", '/onca/xml', req.join('&') ) end def self.webapi(site, path, params) uri = Addressable::URI.parse("#{site}#{path}?#{params}") xml = Net::HTTP.get(uri) json = Hash.from_xml(xml).to_json JSON.parse(json) end def self.make_signature(secret_key, message) hash = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA256.new, secret_key, message) Base64.encode64(hash).split.join end end
# frozen_string_literal: true class Message < ApplicationRecord belongs_to :user belongs_to :room after_create_commit do ChatMessageCreationEventBroadcastJob.perform_later(self) end end
class AddFacebookFieldsToCampaign < ActiveRecord::Migration def change add_column :campaigns, :facebook_share_title, :string add_column :campaigns, :facebook_share_lead, :string add_column :campaigns, :facebook_share_thumb, :string end end
module RunnersConnectApi module V1 class SessionsController < BaseApiController skip_before_action :authenticate_user_from_api_token#, only: :create def create user = User.find_for_authentication(email: params[:email]) if @authenticated_user = user.valid_password?(params[:password]) ? user : nil response.headers['X-RC-AUTH-TOKEN'] = @authenticated_user.auth_token else render_403 end end def show render_403 end end end end
Rails.application.routes.draw do resources :authors, shallow: true do resources :articles end root 'authors#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class Author attr_accessor :name attr_reader :posts @@post_count = 0 @@authors = [] def initialize(name) @name = name @posts = [] @@authors << self end def add_post(post) @posts << post post.author = self end def add_post_by_title(post_title) post = Post.new(post_title) @posts << post post.author = self end def self.post_count @@post_count = @@authors.map {|author| author.posts.count}.reduce(:+) end end
class User < ApplicationRecord include RatingAverage has_secure_password validates :username, uniqueness: true, length: { minimum: 3, maximum: 30 } validates :password, length: { minimum: 3 } validates_format_of :password, with: /[A-Z]/ has_many :ratings, dependent: :destroy has_many :beers, through: :ratings has_many :memberships, dependent: :destroy end
module Antlr4::Runtime class TextChunk attr_reader :text def initialize(text) raise IllegalArgumentException, 'text cannot be null' if text.nil? @text = text end def to_s "'" + @text + "'" end end end
# frozen_string_literal: true require 'rails_helper' feature 'user needs to be authenticated' do scenario 'not access user view' do person = create(:person) user = create(:user, person: person) visit user_path(user.id) expect(current_path).to eq(new_person_session_path) end scenario 'not access company view' do person = create(:person) create(:user, person: person) visit new_company_path expect(current_path).to eq(new_person_session_path) end scenario 'not access ticket history view' do person = create(:person) user = create(:user, person: person) ticket = create(:ticket, user: user) visit new_ticket_history_path(ticket) expect(current_path).to eq(new_person_session_path) end scenario 'not access ticket view' do person = create(:person) create(:user, person: person) visit new_ticket_path expect(current_path).to eq(new_person_session_path) end end
require 'appium_lib' describe 'Liputan 6' do before(:all) do appium_txt = File.join(Dir.pwd, '../appium.txt') caps = Appium.load_appium_txt file: appium_txt Appium::Driver.new(caps).start_driver Appium.promote_appium_methods RSpec::Core::ExampleGroup @top_elements = find_elements :class_name, 'android.support.v7.app.ActionBar$Tab' end after(:all) do driver_quit end describe 'Log in' do before(:all) do @navigate = find_element :name, 'Navigasi naik' @navigate.click end it 'input text on username placeholder' do @elements = find_elements :id, 'menu_item_name' login = @elements[0] expect(login.click).to eq(true) @username = find_element :id, 'login_username' @password = find_element :id, 'login_password' @button = find_element :id, 'login_button' @username.click @username.send_keys("muismuhidin") @password.click @password.send_keys("Init1234") @button.click end end end
require 'spec_helper' require_relative '../../models/user' require_relative '../../mappers/user_mapper' describe UserMapper do describe "persist" do let(:db) {Database.new} let(:mapper) {UserMapper.new(db)} let(:user) {User.new("test@test.com", "testpassword", "testpassword")} before do MongoCleaner.clean end it "should set id of site that it persisted" do mapper.persist(user) expect(user.id).to_not be(nil) end it "should be findable by id and email" do mapper.persist(user) found_user = mapper.find_by_email(user.email) expect_users_to_eq(found_user, user) found_user = mapper.find_by_id(user.id) expect_users_to_eq(found_user, user) end end def expect_users_to_eq(user1, user2) attrs = %w(id email password password_confirmation) attrs.each do |attr| expect(user1.send(attr)).to eq(user2.send(attr)) end end end
require "veda/version" module Veda class << self attr_accessor :instance_attempted_credit_enquiry include Decisioning::Logger # TODO: Implement this VALID_ENQUIRY_TYPES = [:individual_consumer_enquiry] def enquiry(creditable, enquiry_type, product = nil) raise ArgumentError, "Entity must respond to credit_enquiries" unless creditable.respond_to?(:credit_enquiries) creditable.reload creditable.credit_enquiries.reload enquiry = false # log "Credit Enquiry" do self.instance_attempted_credit_enquiry ||= false if creditable.credit_enquiries.count.zero? || creditable.latest_credit_enquiry.created_at < 30.days.ago || (creditable.latest_credit_enquiry.succeeded? == false && self.instance_attempted_credit_enquiry == false) log_info "Conducting credit enquiry..." enquiry = creditable.credit_enquiries.new(enquiry_type, product) self.instance_attempted_credit_enquiry = true log_result "Failed", :result => CrossChar unless enquiry.succeeded? log_result "Succeeded", :result => TickChar if enquiry.succeeded? elsif creditable.latest_credit_enquiry.succeeded? enquiry = creditable.latest_credit_enquiry else enquiry = false end log_info "Got credit Enquiry" enquiry end #MATRIX new veda matrix function def matrix_enquiry(matrixable) matrixable.reload matrixable.matrix_enquiries.reload matrix_enquiry = false # log "Credit Enquiry" do # if creditable.matrix_enquiries.count.zero? log_info "Conducting Matrix enquiry..." matrix_enquiry = matrixable.matrix_enquiries.new() log_result "Failed", :result => CrossChar if matrix_enquiry.matrix_response_xml.size <= 3 log_result "Succeeded", :result => TickChar if matrix_enquiry.matrix_response_xml.size > 3 # elsif creditable.latest_matrix_enquiry.succeeded? # matrix_enquiry = creditable.latest_matrix_enquiry # else # matrix_enquiry = false # end log_info "Got Matrix Enquiry" matrix_enquiry end end end
#http://ruby.bastardsbook.com/chapters/html-parsing/ require 'open-uri' require 'pry' class Scraper def self.scrape_index_page(index_url) html = open(index_url) index_page = Nokogiri::HTML(html) students = [] index_page.css(".student-card a").each do |student| #binding.pry url = student.attr('href') #same as --> student.attributes["href"].value name = student.css(".student-name").text location = student.css(".student-location").text students << { :name => name, :location => location, :profile_url => url } end students end def self.scrape_profile_page(profile_url) html = open(profile_url) profile_page = Nokogiri::HTML(html) student = {} #binding.pry links = profile_page.css(".social-icon-container a").map { |icon| icon.attr("href") } links.each do |link| if link.include?("twitter") student[:twitter] = link elsif link.include?("linkedin") student[:linkedin] = link elsif link.include?("github") student[:github] = link else student[:blog] = link end end #binding.pry student[:profile_quote] = profile_page.css(".profile-quote").text if profile_page.css(".profile-quote") student[:bio] = profile_page.css(".description-holder p").text if profile_page.css(".description-holder p") student end end
module CDI module V1 module ServiceConcerns module LearningTrackReviewsParams extend ActiveSupport::Concern WHITELIST_ATTRIBUTES = [ :learning_track_id, :student_class_id, :review_type, :comment, :score ] included do def track_review_params @track_review_params ||= filter_hash(attributes_hash, WHITELIST_ATTRIBUTES) end def attributes_hash @options.fetch(:review, {}) end end end end end end
require 'common' class TestSCP < Net::SCP::TestCase def test_start_without_block_should_return_scp_instance ssh = stub('session', :logger => nil) Net::SSH.expects(:start). with("remote.host", "username", { :password => "foo" }). returns(ssh) ssh.expects(:close).never scp = Net::SCP.start("remote.host", "username", { :password => "foo" }) assert_instance_of Net::SCP, scp assert_equal ssh, scp.session end def test_start_with_block_should_yield_scp_and_close_ssh_session ssh = stub('session', :logger => nil) Net::SSH.expects(:start). with("remote.host", "username", { :password => "foo" }). returns(ssh) ssh.expects(:loop) ssh.expects(:close) yielded = false Net::SCP.start("remote.host", "username", { :password => "foo" }) do |scp| yielded = true assert_instance_of Net::SCP, scp assert_equal ssh, scp.session end assert yielded end def test_self_upload_should_instatiate_scp_and_invoke_synchronous_upload scp = stub('scp') scp.expects(:upload!).with("/path/to/local", "/path/to/remote", { :recursive => true }) Net::SCP.expects(:start). with("remote.host", "username", { :password => "foo" }). yields(scp) Net::SCP.upload!("remote.host", "username", "/path/to/local", "/path/to/remote", { :ssh => { :password => "foo" }, :recursive => true }) end def test_self_download_should_instatiate_scp_and_invoke_synchronous_download scp = stub('scp') scp.expects(:download!).with("/path/to/remote", "/path/to/local", { :recursive => true }).returns(:result) Net::SCP.expects(:start). with("remote.host", "username", { :password => "foo" }). yields(scp) result = Net::SCP.download!("remote.host", "username", "/path/to/remote", "/path/to/local", { :ssh => { :password => "foo" }, :recursive => true }) assert_equal :result, result end end
class AddAddress2ToCampaignRecords < ActiveRecord::Migration def change add_column :campaign_records, :postcode, :string add_column :campaign_records, :address2, :string add_column :campaign_records, :telphone, :string add_column :campaign_records, :name, :string end end
class PublicController < ApplicationController layout "public" before_filter :setup_navigation, :request_separator def index # intro text, landing page end def show @page = Page.where(:permalink => params[:id], :visible => true ).first redirect_to(:action => 'index') unless @page end private def setup_navigation @stories = Story.visible.sorted end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def show render json: @parks end def current_user @current_user ||= begin auth_token = request.env['HTTP_X_AUTHENTICATION_TOKEN'] User.find_by(auth_token: auth_token) if !!auth_token end end end
HighVoltage.configure do |config| if ENV['PRIVATE_MODE'] != 'true' config.home_page = 'home' end end
namespace :db do desc "Fill db with sample data" task populate: :environment do require 'faker' (1..5).each do |i| fake_name = Faker::Lorem.sentence(1) List.create!(name: fake_name, id: i) 30.times do |j| fake_content = Faker::Lorem.sentence(7) Point.create!(content: fake_content, list_id: i, weight: 1 + rand(3), pro: [true, false].sample ) end end end end
ActiveAdmin.register User do action_item :only => :show do link_to('View on site', user_path(user)) end form do |f| f.inputs "User Details" do f.input :username f.input :email f.input :password f.input :password_confirmation f.input :admin, :label => "Administrator" f.input :banned, :label => "Banned" end f.buttons end show do |user| attributes_table do row :id row :username row :email row :current_sign_in_at row :last_sign_in_at row :current_sign_in_ip row :last_sign_in_ip row :created_at row :updated_at row :admin row :banned end active_admin_comments end index do |user| selectable_column column "Id" do |user| link_to user.id, admin_user_path(user) end column :username column :email column :current_sign_in_at column :last_sign_in_at column :current_sign_in_ip column :last_sign_in_ip column :created_at column :updated_at column :admin column :banned default_actions end filter :username filter :email filter :current_sign_in_at filter :last_sign_in_at filter :current_sign_in_ip filter :last_sign_in_ip filter :created_at filter :updated_at filter :admin filter :banned create_or_edit = Proc.new { @user = User.find_or_create_by_id(params[:id]) if params[:user][:password].blank? @user.update_without_password(params[:user], :as => :admin) else @user.update_attributes!(params[:user], :as => :admin) end if @user.save! redirect_to :action => :show, :id => @user.id else render active_admin_template((@user.new_record? ? 'new' : 'edit') + '.html.erb') end } member_action :create, :method => :post, &create_or_edit member_action :update, :method => :put, &create_or_edit end
=begin In the previous exercise, you developed a method that converts simple numeric strings to Integers. In this exercise, you're going to extend that method to work with signed numbers. Write a method that takes a String of digits, and returns the appropriate number as an integer. The String may have a leading + or - sign; if the first character is a +, your method should return a positive number; if it is a -, your method should return a negative number. If no sign is given, you should return a positive number. You may assume the string will always contain a valid number. You may not use any of the standard conversion methods available in Ruby, such as String#to_i, Integer(), etc. You may, however, use the string_to_integer method from the previous lesson. Examples string_to_signed_integer('4321') == 4321 string_to_signed_integer('-570') == -570 string_to_signed_integer('+100') == 100 =end INTEGERS = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 } def string_to_integer(str) str = str.delete('^0-9') num_array = str.chars.map { |num| INTEGERS[num] } result = num_array.inject(0) { |sum, num| ( sum * 10 ) + num } end def string_to_signed_integer(str) input = string_to_integer(str) result = str.include?("-") ? input * -1 : input puts result end string_to_signed_integer('+100')
FactoryBot.define do factory :brewery do name {"7Peaks Brasserie Sàrl"} city {"Morgins"} postal_code {"1875"} registration_number {623} end end
class AddColumnsToPeople < ActiveRecord::Migration def change add_column :people, :encrypted_email_iv, :string add_column :people, :encrypted_phone_iv, :string end end
require 'open-uri' # Reads hamlet.txt from the given URL # Saves it to a local file on your hard drive named "hamlet.txt" # Re-opens that local version of hamlet.txt and prints out every 42nd line to the screen url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt" File.open("files_io/hamlet.txt", "w"){ |text| text.puts open(url).read} file = File.open("files_io/hamlet.txt", 'r') while !file.eof? line = file.readline puts line end
module Network module Device class PPP < Stub attr_accessor :serial @ids = [{class: 'net', uevent: {interface: 'ppp.*'}}] def initialize(dev) super(dev) @operator = nil @serial = nil if @serial = Device.present.find { |dev| dputs(3) { "Checking dev: #{dev.dev._dirs.inspect}" } dev.dev._dirs.find { |d| d =~ /ttyUSB/ } } @serial.add_observer(self) @operator = @serial.operator dputs(2) { "And found #{@operator} for #{@serial}" } end end def update(operation, dev = nil) if operation =~ /operator/ if @serial @operator = @serial.operator log_msg :PPP, "Found new operator: #{@operator}" changed notify_observers(:operator) else log_msg :PPP, 'Got new operator without @serial' end end end def connection_start end def connection_stop end def connection_may_stop end def connection_status CONNECTED end def reset end def down #@serial.delete_observer(self) end end end end
class CreateReplies < ActiveRecord::Migration[5.1] def change create_table :replies do |t| t.integer :user_id, null: false t.integer :announcement_id, null: false t.string :content, null: false t.timestamps end add_index :replies, :user_id add_index :replies, :announcement_id end end
module GHI module Commands module Version MAJOR = 1 MINOR = 2 PATCH = 0 PRE = nil VERSION = [MAJOR, MINOR, PATCH, PRE].compact.join '.' def self.execute args puts "ghi version #{VERSION}" end end end end
# Copyright (c) 2009-2011 VMware, Inc. class VCAP::Services::Mysql::MysqlError< VCAP::Services::Base::Error::ServiceError MYSQL_DISK_FULL = [31001, HTTP_INTERNAL, 'Node disk is full.'] MYSQL_CONFIG_NOT_FOUND = [31002, HTTP_NOT_FOUND, 'Mysql configuration %s not found.'] MYSQL_CRED_NOT_FOUND = [31003, HTTP_NOT_FOUND, 'Mysql credential %s not found.'] MYSQL_LOCAL_DB_ERROR = [31004, HTTP_INTERNAL, 'Mysql node local db error.'] MYSQL_INVALID_PLAN = [31005, HTTP_INTERNAL, 'Invalid plan %s.'] MYSQL_BAD_SERIALIZED_DATA = [31007, HTTP_BAD_REQUEST, "File %s can't be verified"] end
# 1. Concatenate your first and last name puts "My name concatenated:" puts "Mila " + "Hose" puts "" # 2. Use the modulo and/or division operator to # take a 4-digit number and find the digit in the: # 1) thousands place # 2) hundreds place # 3) tens place # 4) ones place puts "Here is the thousands, hundreds, tens and ones place of the number 7,892:" puts 7892 / 1000 puts 7892 % 1000 / 100 puts 7892 % 1000 % 100 / 10 puts 7892 % 1000 % 100 % 10 puts "" # 3. Write a program that uses a hash to store a list of movie titles with the year they came out. movies = {"Rocky" => 1975, "Radio" => 2004, "Hoosiers" => 2013, "Remember the Titans" => 2001, "Raging Bull" => 1981} puts "List of movie dates using a hash:" puts movies["Rocky"] puts movies["Radio"] puts movies["Hoosiers"] puts movies["Remember the Titans"] puts movies["Raging Bull"] puts "" # 4. Use the dates from the previous example, stored in an array, so they print out the same thing as exercise 3. movies = [1975, 2004, 2013, 2001, 1981] puts "Same list of movie dates, using an array:" puts movies puts "" # 5. Write a program that outputs the factorial of the numbers, 5, 6, 7 and 8. puts "The factorial of 5 is #{5 * 4 * 3 * 2 * 1}." puts "The factorial of 6 is #{6 * 5 * 4 * 3 * 2 * 1}." puts "The factorial of 7 is #{7 * 6 * 5 * 4 * 3 * 2 * 1}." puts "The factorial of 8 is #{8 * 7 * 6 * 5 * 4 * 3 * 2 * 1}." puts "" # 6. Write a program that calculates the square of 3 float numbers of your choosing. puts "The square of 3.2 is #{3.2**2}." puts "The square of 5.7 is #{5.7**2}." puts "The square of 101.9 is #{101.9**2}." puts "" # 7. Interpret an error message puts "What does the following error message tell you?" puts "" puts "SyntaxError: (irb):2: syntax error, unexpected ')', expecting '}' from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>'" puts "" puts "The message shows that, on line 2, there is a syntax error where Ruby expected a closing parenthesis ')' but instead got a closing curly brace '}'"
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :email, :limit => 256, :null => false t.string :display_name, :limit => 256 t.string :persistence_token, :limit => 256 t.string :privacy_token, :limit => 256, :null => false t.timestamps end add_index :users, :email, :unique => true add_index :users, :persistence_token create_table :credentials do |t| t.string :provider, :limit => 64, :null => false t.string :identifier, :limit => 256, :null => false t.integer :user_id, :null => false end add_index :credentials, :user_id add_index :credentials, [:identifier, :provider, :user_id], :unique => true ActsAsArchive.update Credential end def self.down drop_table :archived_credentials drop_table :credentials drop_table :users end end
class Api::DamagesController < ApplicationController def index @damages = Damage.all end def show @damage = Damage.find(params[:id]) render :show end def create @damage = Damage.new(damage_params) if @damage.save! render :show else render json: @damage.errors.full_messages end end private def damage_params params.require(:damage).permit(:description, :address_id) end end
require "rack/reloader" require "sinatra" module Sinatra class Reloader < Rack::Reloader def safe_load(file, mtime, stderr = $stderr) Sinatra::Application.reset! if file == Sinatra::Application.app_file begin super # This seems to be an issue on 1.8.7. I don't recommend using 1.8.7 # at any rate, but perhaps this helps.. rescue Errno::ETIMEDOUT, Errno::EIO => e Vegas.logger.warn "ignoring #{e}, raised trying to stat #{file}" end end end end
require 'spec_helper' describe UsersController do let(:fake_user){FactoryGirl.create(:user)} let(:fake_users){[FactoryGirl.create(:user), FactoryGirl.create(:user), FactoryGirl.create(:user)]} describe "index" do before(:each) { get :index } it "renders @users to json" do @expected = { users: assigns(:users) }.to_json expect(response.body).to eq @expected end end describe "show" do before(:each) { get :show, id: fake_user.id } it "loads a user tuple into @user" do expect(assigns(:user)).to eq fake_user end it "loads a partial that shows user profile" do expect(response).to render_template(:partial => '_show') end end describe "create" do it "redirects to root path if valid user attributes" do post :create, user: FactoryGirl.attributes_for(:user) expect(response).to redirect_to(root_path) end it "add user to database if valid user attributes" do expect { post :create, user: FactoryGirl.attributes_for(:user) expect(response).to be_redirect }.to change { User.count }.by(1) end end describe "edit" do it "loads a partial for editing user's own profile" do get :edit, id: fake_user.id expect(response).to render_template(:partial => '_edit') end end describe "update" do it "updates a user table entry" do new_name = "Joe Blow" expect { put(:update, id: fake_user.id, user: { name: new_name }) }.to change { fake_user.reload.name }.to(new_name) end it "renders partial of user profile upon updating information" do new_name2 = "Joe Blow2" put(:update, id: fake_user.id, user: { name: new_name2 }) expect(response).to render_template(:partial => '_show') end end describe "results" do it "shows list of users matching search results" do post :results, pgsearch: fake_user.name expect(response).to render_template(:partial => '_results') end end end
require 'minitest/autorun' require 'minitest/pride' require_relative '../lib/flashcards' class CardTest < Minitest::Test def test_card card = Card.new("What is the capital of Alaska?", "Juneau") assert_equal "What is the capital of Alaska?", card.question card.answer assert_equal ("Juneau"), card.answer end end
require 'test_helper' class DealStepsControllerTest < ActionController::TestCase setup do @deal_step = deal_steps(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:deal_steps) end test "should get new" do get :new assert_response :success end test "should create deal_step" do assert_difference('DealStep.count') do post :create, :deal_step => @deal_step.attributes end assert_redirected_to deal_step_path(assigns(:deal_step)) end test "should show deal_step" do get :show, :id => @deal_step.to_param assert_response :success end test "should get edit" do get :edit, :id => @deal_step.to_param assert_response :success end test "should update deal_step" do put :update, :id => @deal_step.to_param, :deal_step => @deal_step.attributes assert_redirected_to deal_step_path(assigns(:deal_step)) end test "should destroy deal_step" do assert_difference('DealStep.count', -1) do delete :destroy, :id => @deal_step.to_param end assert_redirected_to deal_steps_path end end
require "rails_helper" RSpec.describe "When I visit the flight index page" do before :each do @flight1 = Flight.create!( number: "1737", date: "10/20/20", time: "10:00 AM", departure_city: "Tampa", arrival_city: "Las Vegas" ) @passenger1 = @flight1.passengers.create( name: "Jake The Dog", age: 900 ) @passenger2 = @flight1.passengers.create( name: "Fin", age: 14 ) @flight2 = Flight.create!( number: "2345", date: "01/02/21", time: "10:00 AM", departure_city: "Miami", arrival_city: "London" ) @passenger3 = @flight2.passengers.create( name: "Jake The Dog", age: 900 ) @passenger4 = @flight2.passengers.create( name: "Fin", age: 14 ) @passenger5 = @flight2.passengers.create( name: "Ice King", age: 70 ) @flight3 = Flight.create!( number: "1012", date: "05/10/20", time: "10:00 AM", departure_city: "Denver", arrival_city: "Reno" ) @passenger6 = @flight3.passengers.create( name: "Jake The Dog", age: 900 ) @passenger7 = @flight3.passengers.create( name: "Fin", age: 14 ) @passenger8 = @flight3.passengers.create( name: "Ice King", age: 70 ) @passenger9 = @flight3.passengers.create( name: "Lemondrop guy", age: 45 ) @flight4 = Flight.create!( number: "1111", date: "05/10/19", time: "2:00 AM", departure_city: "Tokyo", arrival_city: "New York" ) @passenger10 = @flight4.passengers.create( name: "Jake The Dog", age: 900 ) @passenger11 = @flight4.passengers.create( name: "Fin", age: 14 ) @passenger12 = @flight4.passengers.create( name: "Ice King", age: 70 ) @passenger13 = @flight4.passengers.create( name: "Lemondrop guy", age: 45 ) @passenger14 = @flight4.passengers.create( name: "Lemondrop guy", age: 45 ) end describe "The flights are ordered" do it "By the number of passengers on the flight, most to least" do visit flights_path expect(@flight4.number).to appear_before(@flight2.number) expect(@flight4.number).to appear_before(@flight3.number) expect(@flight3.number).to appear_before(@flight2.number) expect(@flight2.number).to appear_before(@flight1.number) expect(@flight3.number).to appear_before(@flight1.number) end end end
class CreateFeatures < ActiveRecord::Migration def change create_table :spree_features do |t| t.string :name t.integer :position t.string :link t.string :headline1 t.string :headline2 t.boolean :active t.timestamps end end end
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # 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. require_relative '../../spec_helper' describe 'hpe3par::volume_set' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: PLATFORM, version: PLATFORM_VERSION, step_into: ['volume_set']) do |node| node.override['hpe3par']['storage_system'] = { name: 'MY_3PAR', ip: '1.1.1.1.1', user: 'chef', password: 'chef' } #volumeset create node.override['hpe3par']['volume_set']['create']['name'] = 'chef_volume_set' node.override['hpe3par']['volume_set']['create']['domain'] = 'my_domain' node.override['hpe3par']['volume_set']['create']['setmembers'] = ['chef_vol_thin2'] #volumeset delete node.override['hpe3par']['volume_set']['delete']['name'] = 'chef_volume_set' #volumeset add_volume node.override['hpe3par']['volume_set']['add_volume']['name'] = 'chef_volume_set' node.override['hpe3par']['volume_set']['add_volume']['setmembers'] = ['chef_vol_thin2'] #volumeset add_volume node.override['hpe3par']['volume_set']['remove_volume']['name'] = 'chef_volume_set' node.override['hpe3par']['volume_set']['remove_volume']['setmembers'] = ['chef_vol_thin2'] end.converge(described_recipe) end it 'creates the volume set through create_volume_set' do expect(chef_run).to create_hpe3par_volume_set(chef_run.node['hpe3par']['volume_set']['create']['name']) end it 'deletes the volume set through delete_volume_set' do expect(chef_run).to delete_hpe3par_volume_set(chef_run.node['hpe3par']['volume_set']['delete']['name']) end it 'adds volume to the volume set through add_volume_set' do expect(chef_run).to add_volume_hpe3par_volume_set(chef_run.node['hpe3par']['volume_set']['add_volume']['name']) end it 'removes volume from the volume set through remove_volume_set' do expect(chef_run).to remove_volume_hpe3par_volume_set(chef_run.node['hpe3par']['volume_set']['remove_volume']['name']) end end
class Request < ActiveRecord::Base belongs_to :recruiter belongs_to :vacancy validates :status, presence: true end
class AddGameIdToDeeds < ActiveRecord::Migration[5.1] def change add_column(:deeds, :game_id, :integer, null: false) add_index(:deeds, [:property_id, :game_id], unique: true) end end
class CreateQuestions < ActiveRecord::Migration def self.up create_table :questions do |t| t.string :title t.integer :type_of_answer t.integer :score t.references :quiz, index: true, foreign_key: true t.timestamps null: false end end def self.down drop_table :questions end end
module Mutant # An AST cache class Cache include Equalizer.new, Adamantium::Mutable # Initialize object # # @return [undefined] # # @api private def initialize @cache = {} end # Root node parsed from file # # @param [#to_s] path # # @return [AST::Node] # # @api private def parse(path) @cache.fetch(path) do @cache[path] = Parser::CurrentRuby.parse(File.read(path)) end end end # Cache end # Mutant
source 'https://rubygems.org' ruby '2.3.0' gem 'rails', '4.2.5' # MVC framework vs. sinatra which is a routing framework # environment gems (front & backend, admin, db, etc.) gem 'pg', '~> 0.18.4' # Postgres db instead of sqlite # gem 'puma', '2.11.1' # Puma server - recommended for hosting on heroku gem 'unicorn' # Unicorn - backup server for heroku # gem 'sinatra' # Framework for small apps and apis vs. Rails MVC framework # javascript gems gem 'jquery-rails', '~> 4.0.5' # This gem provides jQuery and the jQuery-ujs driver for your Rails 4+ application. gem 'jquery-ui-rails', '~> 5.0' # jQuery UI's JavaScript, CSS, and image files packaged for the Rails 3.1+ asset pipeline gem 'jbuilder', '~> 2.4.0' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'uglifier', '>= 2.5' # minify javascript assets # look and feel (doc uploads, image views, etc.) gem 'font-awesome-rails', '~> 4.5.0.0' # required for font-awesome icons gem 'sass-rails', '~> 5.0.2' # use scss for stylesheets vs. css gem 'turbolinks', '2.3.0' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'bootstrap-sass', '3.2.0.0' # Bootstrap for rails scss (vs. rails less) group :development, :test do gem 'byebug' # Call 'debugger' anywhere in the code to stop execution and get a debugger console end group :test do gem 'minitest-reporters', '1.0.5' gem 'mini_backtrace', '0.1.3' gem 'guard-minitest', '2.3.1' end group :production do gem 'rails_12factor', '0.0.2' end
def clockChime &block ((Time.now.hour + 11) % 12 + 1).times do |i| puts i + 1 block.call end end clockChime do puts "DONG" end def log blockDescription, &block puts "Beginning'" + blockDescription + "'..." ret = block.call puts "...'" + blockDescription + "' finished, returning: #{ret}" end log "outer block" do log "some little block" do 5 end log "yet another block" do "asdf" end false end $indent = " " $nestingDepth = 0 def betterLog blockDescription, &block puts $indent * $nestingDepth + "Beginning'" + blockDescription + "'..." $nestingDepth += 1 ret = block.call $nestingDepth -= 1 puts $indent * $nestingDepth + "...'" + blockDescription + "' finished, returning: #{ret}" end betterLog "outer block" do betterLog "some little block" do betterLog "teeny-tiny block" do "lots of love" end 42 end betterLog "yet another block" do "I love Indian food!" end true end
# frozen_string_literal: true require 'spec_helper' describe HealthMonitor::Providers::Base do let(:request) { test_request } subject { described_class.new(request: request) } describe '#initialize' do it 'sets the request' do expect(described_class.new(request: request).request).to eq(request) end end describe '#provider_name' do it { expect(described_class.provider_name).to eq('Base') } end describe '#check!' do it 'abstract' do expect { subject.check! }.to raise_error(NotImplementedError) end end describe '#configurable?' do it { expect(described_class).not_to be_configurable } end describe '#configuration_class' do it 'abstract' do expect(described_class.send(:configuration_class)).to be_nil end end end
include_recipe 'chef-openstack::common' packages = %w[keystone python-keystone python-keystoneclient python-mysqldb memcached python-memcache] packages.each do |pkg| package pkg do action :install end end service 'keystone' do provider Chef::Provider::Service::Upstart action :nothing end execute 'keystone-manage db_sync' do user 'keystone' group 'keystone' command 'keystone-manage db_sync' action :nothing end directory '/etc/keystone' do owner 'root' group 'root' mode 00755 action :create end template '/etc/memcached.conf' do source 'memcached/memcached.conf.erb' owner 'root' group 'root' mode 00644 end template '/etc/keystone/keystone-paste.ini' do source 'keystone/keystone-paste.ini.erb' owner 'root' group 'root' mode '0644' notifies :restart, resources(:service => 'keystone') end template '/etc/keystone/keystone.conf' do source 'keystone/keystone.conf.erb' owner 'root' group 'root' mode '0644' notifies :restart, resources(:service => 'keystone'), :immediately notifies :run, resources(:execute => 'keystone-manage db_sync'), :immediately end template '/root/.openrc' do source 'keystone/openrc.erb' owner 'root' group 'root' mode '0600' end # ================================================= # BEGIN Keystone HTTP setup if node['keystone']['apache_frontend'] service 'keystone' do provider Chef::Provider::Service::Upstart action [:disable, :stop] end %w[apache2 libapache2-mod-wsgi].each do |pkg| package pkg do action :install end end service 'apache2' do supports :status => true, :restart => true, :reload => true action :nothing end directory '/usr/share/keystone/wsgi' do owner 'root' group 'root' mode 00755 recursive true action :create notifies :stop, "service[keystone]" notifies :restart, "service[apache2]" end template '/usr/share/keystone/wsgi/main' do source 'keystone/keystone.py' owner 'root' group 'root' mode 00644 notifies :stop, "service[keystone]" notifies :restart, "service[apache2]" end template '/usr/share/keystone/wsgi/admin' do source 'keystone/keystone.py' owner 'root' group 'root' mode 00644 notifies :stop, "service[keystone]" notifies :restart, "service[apache2]" end directory '/var/log/keystone' do group 'www-data' mode '0777' action :create end file '/var/log/keystone/keystone.log' do group 'www-data' mode '0666' action :create end # Ubuntu directory '/etc/apache2/conf.d/' do owner 'root' group 'root' mode 00755 recursive true action :create end template '/etc/apache2/conf.d/wsgi-keystone.conf' do source 'keystone/wsgi-keystone.conf' owner 'root' group 'root' mode 00644 notifies :stop, resources(:service => 'keystone'), :immediately notifies :restart, resources(:service => 'apache2'), :immediately end end # END Keystone HTTP setup # ================================================= include_recipe 'chef-openstack::keystone-setup'
#!/usr/bin/env ruby require 'rubygems' require 'sinatra' require 'sim_launcher' # SimLauncher starts on port 8881 by default. To specify a custom port just pass it as the first command line argument. set :port, (ARGV[0] || 8881) # otherwise sinatra won't always automagically launch its embedded # http server when this script is executed set :run, true shared_simulator = SimLauncher::Simulator.new get '/' do <<EOS <h1>SimLauncher is up and running...</h1> <a href="/showsdks">Here's a list of sdks that SimLauncher has detected</a> EOS end get '/showsdks' do '<pre>' + shared_simulator.showsdks + '</pre>' end get '/launch_ipad_app' do app_path = params[:app_path] app_name = params[:app_name] sdk = params[:sdk] restart_requested = ("true" == params[:restart]) shared_simulator.quit_simulator if restart_requested if (!app_name.nil? && !app_name.empty?) shared_simulator.launch_ipad_app_with_name( app_name, sdk ) else raise 'no app_path provided' if app_path.nil? shared_simulator.launch_ipad_app( app_path, sdk ) end end get '/launch_iphone_app' do app_path = params[:app_path] app_name = params[:app_name] sdk = params[:sdk] restart_requested = ("true" == params[:restart]) shared_simulator.quit_simulator if restart_requested if (!app_name.nil? && !app_name.empty?) shared_simulator.launch_iphone_app_with_name( app_name, sdk ) else raise 'no app_path provided' if app_path.nil? shared_simulator.launch_iphone_app( app_path, sdk ) end end
require 'test_helper' # Test para el Controlador Proyectos class ProyectosControllerTest < ActionController::TestCase setup do @proyecto = proyectos(:one) end test 'should get index' do get :index assert_response :success assert_not_nil assigns(:proyectos) end test 'should get new' do get :new assert_response :success end test 'should create proyecto' do assert_difference('Proyecto.count') do post :create, proyecto: { duracion: @proyecto.duracion, estado: @proyecto.estado, linea_tematica: @proyecto.linea_tematica, lugar_ejecucion: @proyecto.lugar_ejecucion, titulo: @proyecto.titulo } end assert_redirected_to proyecto_path(assigns(:proyecto)) end test 'should show proyecto' do get :show, id: @proyecto assert_response :success end test 'should get edit' do get :edit, id: @proyecto assert_response :success end test 'should update proyecto' do patch :update, id: @proyecto, proyecto: { duracion: @proyecto.duracion, estado: @proyecto.estado, linea_tematica: @proyecto.linea_tematica, lugar_ejecucion: @proyecto.lugar_ejecucion, titulo: @proyecto.titulo } assert_redirected_to proyecto_path(assigns(:proyecto)) end test 'should destroy proyecto' do assert_difference('Proyecto.count', -1) do delete :destroy, id: @proyecto end assert_redirected_to proyectos_path end end
class AddIsStoppedToOrg < ActiveRecord::Migration def change add_column :organizations,:is_stopped,:boolean,:default => false end end
require 'pry' class Song @@count = 0 @@genres = [] @@artists = [] def initialize(name, artist, genre) @name = name @artist = artist @genre = genre @@count += 1 @@genres << genre @@artists << artist end attr_accessor :name attr_accessor :artist attr_accessor :genre def self.count @@count end def self.genres @@genres.uniq end def self.artists @@artists.uniq end def self.genre_count genre_hash = {} @@genres.each do |genre| if genre_hash[genre] genre_hash[genre] += 1 else genre_hash[genre] = 1 end end genre_hash end def self.artist_count artist_hash = {} @@artists.each do |artist| if artist_hash[artist] artist_hash[artist] += 1 else artist_hash[artist] = 1 end end artist_hash end lucifer = Song.new("Lucifer", "Jay-Z", "rap") ninety_nine_problems = Song.new("99 Problems", "Jay-Z", "rap") hit_me = Song.new("hit me baby one more time", "Brittany Spears", "pop") p Song.genre_count end # ninety_nine_problems = Song.new("99 Problems", "Jay-Z", "rap") # # p ninety_nine_problems.name # # => "99 Problems" # # p ninety_nine_problems.artist # # => "Jay-Z" # # p ninety_nine_problems.genre # => "rap"