text
stringlengths
10
2.61M
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.create!([{first_name: "Kate", last_name: "Balducci", user_name: "kbalducci", zipcode: "78758", avatar: 'http://kbjsinstaclone.s3.amazonaws.com/users/avatars/000/000/004/thumb/Hello.jpg?1426448326', phone: "5127311220", email: 'test@me.com', password: 'password', bio: "I want to make a difference by helping other people! I know that the smallest of acts can help brighten someone's day. My goal is to do 1 random act of kindness everyday. I am most interested in volunteering at The Humane Society as well as with Environmental issues." }, {first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, user_name: Faker::Internet.user_name, zipcode: Faker::Address.zip, avatar: 'http://kbjsinstaclone.s3.amazonaws.com/users/avatars/000/000/002/thumb/Nature.jpg?1426448046', phone: Faker::Number.number(10), email: 'test2@me.com', password: 'password', bio: "If you have a lemon, make lemonade. Begin to be now what you will be hereafter. Begin difficult things while they are easy. A thousand-mile journey begins with one step." }, {first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, user_name: Faker::Internet.user_name, zipcode: Faker::Address.zip, avatar: 'http://kbjsinstaclone.s3.amazonaws.com/users/avatars/000/000/003/thumb/Success.jpg?1426448202', phone: Faker::Number.number(10), email: 'test3@me.com', password: 'password', bio: 'Why not go out on a limb? That is where the fruit is Nothing is so exhausting as indecision, and nothing is so futile.' }, {first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, user_name: Faker::Internet.user_name, zipcode: Faker::Address.zip, avatar: 'http://kbjsinstaclone.s3.amazonaws.com/users/avatars/000/000/006/thumb/Jellyfish.jpg?1426448660', phone: Faker::Number.number(10), email: 'test4@me.com', password: 'password', bio: 'Imagine you only have one year to live. What important things would you be doing? How would you be allotting your time to accomplish the most you could? This exercise is one method of going after your priorities. The way to be safe is never to be secure.' }, {first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, user_name: Faker::Internet.user_name, zipcode: Faker::Address.zip, avatar: 'http://kbjsinstaclone.s3.amazonaws.com/users/avatars/000/000/005/thumb/ottercams.jpg?1426448542', phone: Faker::Number.number(10), email: 'test5@me.com', password: 'password', bio: 'Make the most of today. Translate your good intentions into actual deeds. One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man.' }]) Act.create([{ title: 'Let someone go in front of you in line.', user_id: 2 }, { title: 'Donate Blood.' }, { title: 'Have lunch with a stranger at a nursing home.', user_id: 2 }, { title: 'Become an organ donor.', user_id: 2 }, { title: 'Make a bird feeder.', user_id: 2 }, { title: 'Collect canned food for a local food bank.', user_id: 2 }, { title: 'Leave money in the parking meter.', user_id: 2 }, { title: 'Donate a teddy bear to a homeless shelter.', user_id: 2 }, { title: 'Coach a youth sporting team.', user_id: 2 }, { title: 'Use a re-usable glass water bottle vs a disposable water bottle.', user_id: 2 }, { title: 'Donate pet food to an animal shelter.', user_id: 2 }, ]) Service.create([{ title: 'Foster With The Humane Society', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/002/medium/AHS.jpg?1426457447', zipcode: '78752', description: 'Sometimes, animals aren’t yet ready for our adoption program—like animals under eight weeks old. Sometimes, animals get injured and need special care. Or, our shelter is filled to capacity. That’s when our Foster Care program volunteers swoop in to save the day.', requirement: 'First, you need to attend a Foster Care Orientation. The orientation will allow you to learn everything you need to know about caring for a foster animal. Sign up now by emailing fostercare@austinhumanesociety.org', user_id: 2 }, { title: 'Help Clean Lady Bird Lake', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/011/medium/Lake2.jpg?1426461180', zipcode: '78701', description: 'While Lady Bird Lake tops many people’s list of places to take visitors, it also tops the list of places about which Keep Austin Beautiful receives trash complaint calls. Nine watersheds (Eanes, Barton, West Bouldin, East Bouldin, Blunn, Harpers Branch, Johnson, Shoal, and Waller) flow into the lake, and after every storm an increase in trash on the lake’s surface is apparent as trash washes from the streets --> storm drains --> creeks --> lake. Over the years, Keep Austin Beautiful has regularly organized cleanups of the lake, and thousands of volunteers have pitched in to pick up trash.', requirement: 'Must be 18 or older. Go to http://www.keepaustinbeautiful.org/ladybirdlake for more info.', user_id: 2 }, { title: 'Meals on Wheels', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/004/medium/Meals.jpg?1426458340', zipcode: '78702', description: 'Our community assistance services include home delivered meals for seniors and others with disabilities. Aside from the meal delivery program, Meals on Wheels and More offers "And More" programs designed to keep people healthy and living in their own homes.', requirement: 'Must be 18 years or older, have a valid driving license and have access to transportation. For more information, visit http://www.mealsonwheelsandmore.org. Volunteer orientation for Meal Delivery Program is every Thursday 12:15p.m. at our central kitchen 3227 E. 5th St. 78702. You must attend an orientation before you start meal delivery. Other volunteer opportunities are also available at the website.', user_id: 2 }, { title: 'Big Brother/Big Sister of Austin', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/005/medium/Big.jpg?1426458966', zipcode: '78721', description: 'Being a Big Brother or Big Sister is one of the most enjoyable things you’ll ever do, and one of the most fulfilling. You have the opportunity to help shape a child’s future for the better by empowering them to achieve. And the best part is, it’s actually a lot of fun. You and your Little can share the kinds of activities you already like to do.', requirement: 'Fill out the volunteer application on http://www.bigmentoring.org. Also see the site for more details.', user_id: 2 }, { title: 'Go Fund Me', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/006/medium/fund.jpeg?1426459170', zipcode: 'Anywhere', description: 'The beauty of GoFundMe is that it allows campaign organizers to invite others to take part in their story. Just as we share parts of our lives on Facebook, we also want to share our dreams, pursuits, celebrations and challenges online with crowdfunding. People will always be eager to support others they care about. GoFundMe removes the physical barriers traditionally associated with receiving financial support from the people in our lives.', requirement: 'Go to gofundme.com and start donating today!', user_id: 2 }, { title: 'Run/Walk to Break the Silence on Ovarian Cancer', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/007/medium/Nocc.png?1426459776', zipcode: '78758', description: 'Join the Austin Chapter of the National Ovarian Cancer Coalition for its annual Run/Walk. Help raise money and help support those who are fighting Ovarian Cancer or have won their battle and help remember those who lost their fight to Ovarian Cancer.', requirement: 'For questions contact austintx@ovarian.org. Go to http://www.ovarian.org/ to learn more or to join a team.', user_id: 2 }, { title: 'Capital Area Food Bank, Austin', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/010/medium/cap3.jpg?1426460241', zipcode: '78745', description: 'Volunteers are the heart and soul of the Food Bank. They bring our mission to life. Our volunteers ensure only the safest food leaves our warehouse, keep mobile food pantry lines running smoothly and share our mission at community events throughout the year. Join the 17,000 volunteers who gave a bit of their time last year to make a difference in someone else’s life.', requirement: 'Sign up to volunteer at https://www.austinfoodbank.org/get-involved/volunteer.', user_id: 2 }, { title: 'Pets 90210', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/010/medium/pets.jpeg?1427298528', zipcode: '90210', description: 'Pets 90210 believes that shelter pets are perfect pets. Come help animals get adopted, spend time with the cats and dogs, or volunteer at our pet adoption sites to help showcase our perfect pets.', requirement: 'If you would like to volunteer, please contact bcrowe@kenquest.com or call Bill Crowe at 310-887-7070', user_id: 2 }, { title: 'Camp Arrowhead', photo: 'http://kbjsinstaclone.s3.amazonaws.com/services/photos/000/000/011/medium/camp.jpg?1427299125', zipcode: '01760', description: 'Located in Natick, MA on the wooded shores of Lake Cochituate, Camp Arrowhead offers a six-week day camp and one-week residential camp that serves children and adults with special needs. Since 1958, our campers have enjoyed a warm and caring environment where their individual needs are met, while they learn skills to help promote sociability and independence.', requirement: 'Volunteering at Camp Arrowhead is a truly rewarding experience. If you will be 14 years or older by the end of summer 2015 and would like the opportunity to volunteer, please consider obtaining an application for the summer at our website: http://camparrowheadnatick.com/volunteers/', user_id: 2 } ]) Tag.create([{ name: 'Animals' }, { name: 'Environment' }, { name: 'Elderly' }, { name: 'Youth' }, { name: 'Monetary' }, { name: 'Medical' }, { name: 'Food' }, { name: 'General'}]) Tagging.create([{ act_id: 1, tag_id: 8 }, { act_id: 2, tag_id: 6 }, { act_id: 3, tag_id: 3 }, { act_id: 4, tag_id: 3 }, { act_id: 5, tag_id: 1 }, { act_id: 6, tag_id: 7 }, { act_id: 7, tag_id: 5 }, { act_id: 8, tag_id: 4 }, { act_id: 9, tag_id: 4 }, { act_id: 10, tag_id: 2 }, { act_id: 11, tag_id: 1 }, { service_id: 1, tag_id: 1 }, { service_id: 2, tag_id: 2 }, { service_id: 3, tag_id: 3 }, { service_id: 4, tag_id: 4 }, { service_id: 5, tag_id: 5 }, { service_id: 6, tag_id: 6 }, { service_id: 7, tag_id: 7 }, { service_id: 8, tag_id: 1 }, { service_id: 9, tag_id: 4 } ])
module CJSV class RenderLineParser def initialize(line, spaces_per_indent, cjsv_instance) @line = line @spaces_per_indent = spaces_per_indent @debug = true @cjsv_instance = cjsv_instance parse end def indentation @indentation end def line @line end def preprocess_line @indentation = @line.scan(/^\s*/)[0].size/@spaces_per_indent @line = @line.gsub(LineParserFactory.render_line_regex, '').strip end def parse preprocess_line end end end
require 'rails_helper' describe StructureListGrouper do let!(:measure_selection) { create(:measure_selection) } let!(:structure_type) do create(:structure_type, name: 'Lighting', api_name: 'lighting') end let!(:structure_type_definition) do instance_double( StructureTypeDefinition, grouping_field_api_name: 'lamp_type') end before do allow(measure_selection).to receive(:structure_type_definition_for) .with(structure_type) .and_return(structure_type_definition) end describe '#grouped_structures' do it 'returns original structures if sample group ids not present' do json_structures = [ { id: SecureRandom.uuid, name: 'Hallway lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 1, sample_group_id: nil, field_values: { lamp_type: { name: 'Lamp type', value: 'LED', value_type: 'string' } } }, { id: SecureRandom.uuid, name: 'Kitchen lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 1, sample_group_id: nil, field_values: { lamp_type: { name: 'Lamp type', value: 'LED', value_type: 'string' } } } ] structures = json_structures.map do |json| Wegoaudit::Structure.new(json) end grouper = described_class.new( measure_selection, structure_type, structures) expect(grouper.grouped_structures).to eq structures end it 'returns original structures if sample group ids are different' do json_structures = [ { id: SecureRandom.uuid, name: 'Hallway lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 4, sample_group_id: 'foo', field_values: { lamp_type: { name: 'Lamp type', value: 'LED', value_type: 'string' } } }, { id: SecureRandom.uuid, name: 'Kitchen lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 2, sample_group_id: 'bar', field_values: { lamp_type: { name: 'Lamp type', value: 'LED', value_type: 'string' } } } ] structures = json_structures.map do |json| Wegoaudit::Structure.new(json) end grouper = described_class.new( measure_selection, structure_type, structures) expect(grouper.grouped_structures).to eq structures end it 'returns original structures if grouping field values are different' do json_structures = [ { id: SecureRandom.uuid, name: 'Hallway lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 4, sample_group_id: 'foo', field_values: { lamp_type: { name: 'Lamp type', value: 'type1', value_type: 'string' } } }, { id: SecureRandom.uuid, name: 'Kitchen lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 2, sample_group_id: 'foo', field_values: { lamp_type: { name: 'Lamp type', value: 'type2', value_type: 'string' } } } ] structures = json_structures.map do |json| Wegoaudit::Structure.new(json) end grouper = described_class.new( measure_selection, structure_type, structures) expect(grouper.grouped_structures).to eq structures end it 'calls StructureCombiner if grouping field values are the same' do json_structures = [ { id: SecureRandom.uuid, name: 'Hallway lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 4, sample_group_id: 'foo', field_values: { lamp_type: { name: 'Lamp type', value: 'type1', value_type: 'string' } } }, { id: SecureRandom.uuid, name: 'Kitchen lights', structure_type: { name: 'Lighting', api_name: 'lighting' }, n_structures: 2, sample_group_id: 'foo', field_values: { lamp_type: { name: 'Lamp type', value: 'type1', value_type: 'string' } } } ] structures = json_structures.map do |json| Wegoaudit::Structure.new(json) end combiner = instance_double(StructureCombiner) expect(StructureCombiner).to receive(:new).with(structures) .and_return(combiner) expect(combiner).to receive(:combined_structures) grouper = described_class.new( measure_selection, structure_type, structures) grouper.grouped_structures end end end
#!/usr/bin/env ruby TICKET_REGEXP = /[A-Z]+-\d+/ # WEB-12345 TIME_REGEXP = /\d+[.]+\d+h/ # 0.5h, 2.0h commit_message = File.open(ARGV[0], 'r') do |f| f.read end unless commit_message.match(TICKET_REGEXP) puts "[ERROR] commit-message-format: JIRA ticket number is not existed." exit(1) end unless commit_message.match(TIME_REGEXP) puts "[ERROR] commit-message-format: you do not input your work time." exit(1) end
Rails.application.routes.draw do root 'application#welcome' resources :sessions, :users end
# encoding:UTF-8 require 'uri' require 'pathname' require 'csv' require_relative 'config/environment.rb' require_relative 'lib/workers/http_tool.rb' require_relative 'lib/workers/sreality.rb' dt_start = Time.now puts "Start time: #{dt_start}" requests_per_second = 50 dt = DateTime.now - 1.minutes @http_tool = HttpTool.new def write_csv_header(csv) csv << [ 'ExternId', 'Název', 'Celková cena', '', 'Poznámka k ceně', 'Adresa', 'Datum aktualizace', 'ID zakázky', 'Budova', 'Stav objektu', 'Vlastnictví', 'Podlaží umístění', 'Plocha užitná', 'Plocha podlahová', 'Garáž', 'Voda', 'Elektřina', 'Plyn', 'Doprava', 'Výtah', 'Typ domu', 'Podlaží počet', 'Topení', 'Umístění objektu', 'Odpad', 'Telekomunikace', 'Datum nastěhování', 'Rok rekonstrukce', 'Zařízeno', 'Sklep', 'Bezbariérový přístup', 'Terasa', 'Parkovací stání', 'Plocha pozemku', 'Zástavba', 'Komunikace', 'Energetická náročnost budovy: Energetická náročnost budov', 'Půdní vestavba', nil, 'Popis', nil, 'Lat', 'Lon' ] end def transform_value(value) result = value.clone keys = ['Garáž'] keys.each do |k| if result[k] result[k] = if result[k] == 'Ano' then '1' else '0' end end end result end def puts_divider puts '-----------------------------------------------------------------' end def update_ad(ad) changed = false page = @agent.get(ad.url) sreality = Sreality.new detail = sreality.extract_detail_page_data ad.url, page #puts detail ad.title = detail['Název'] ad.price = detail['Celková cena'] || detail['Zlevněno'] ad.description = detail['Popis'] ad.externid = detail['ExternId'] # if something changed, create new AdChange object if ad.updatedAt != detail['Datum aktualizace'] changed = true else end ad.updatedAt = detail['Datum aktualizace'] ad.externsource = 'sreality.cz' ad.lastCheckAt = DateTime.now ad.lastCheckResponseStatus = '200' changed end puts_divider puts "Processing given SReality URLs" puts_divider data_urls = [] # SReality - byty #data_urls << 'http://www.sreality.cz/search?category_type_cb=1&category_main_cb=1&price_min=&price_max=&region=&distance=0&usable_area-min=&usable_area-max=&floor_number-min=&floor_number-max=&age=0&extension=0&sort=0&perPage=10&hideRegions=0&discount=-1' #data_urls << 'http://www.sreality.cz/search?category_type_cb=1&category_main_cb=1&sub%5B%5D=2&price_min=&price_max=&region=&distance=0&usable_area-min=&usable_area-max=&floor_number-min=&floor_number-max=&age=0&extension=0&sort=0&perPage=30&hideRegions=0&discount=-1' #data_urls << 'http://www.sreality.cz/search?category_type_cb=1&category_main_cb=1&sub%5B%5D=2&price_min=&price_max=&region=&distance=0&rg%5B%5D=10&dt%5B%5D=5002&usable_area-min=&usable_area-max=&floor_number-min=&floor_number-max=&age=0&extension=0&sort=0&perPage=30&hideRegions=0&discount=-1' # production urls data_urls << 'http://www.sreality.cz/search?category_type_cb=1&category_main_cb=1&price_min=&price_max=&region=&distance=0&rg%5B%5D=10&usable_area-min=20&usable_area-max=90&floor_number-min=&floor_number-max=&age=0&extension=1&sort=0&perPage=10&hideRegions=0&discount=-1' sreality = Sreality.new @http_tool data_urls.each do |url| begin puts "Getting data from listing: #{url}" spinfo = sreality.extract_search_page_info(url) puts "Number of ads stated:#{spinfo['foundCount']} / downloaded: #{spinfo['ads'].length}" ad_details = {} detail_field_stats = {} total = spinfo['ads'].length spinfo['ads'].each_index do |index| begin ad = spinfo['ads'][index] # get add details page = @http_tool.get(ad['urlNormalized']) detail = sreality.extract_detail_page_data ad['urlNormalized'], page ad_details[detail['ExternId']] = detail # update detail fields stats detail.keys.each do |k| detail_field_stats[k] = if detail_field_stats[k] then detail_field_stats[k]+1 else 1 end end puts "Extracted detail page info (#{index+1}/#{total}): EID=#{detail['ExternId']} - #{detail['Název']}" sleep 1/requests_per_second rescue puts $!, $@ end end puts "Detail keys stats" detail_field_stats.each { |k, v| puts "Key #{k} : #{v}" } puts "Writing data to CSV" CSV.open("data_all.csv", "wb") do |csv| write_csv_header csv ad_details.each do |k, v| v = transform_value v record = [ v['ExternId'], v['Název'], v['Celková cena'], v[''], v['Poznámka k ceně'], v['Adresa'], v['Datum aktualizace'], v['ID zakázky'], v['Budova'], v['Stav objektu'], v['Vlastnictví'], v['Podlaží umístění'], v['Plocha užitná'], v['Plocha podlahová'], v['Garáž'], v['Voda'], v['Elektřina'], v['Plyn'], v['Doprava'], v['Výtah'], v['Typ domu'], v['Podlaží počet'], v['Topení'], v['Umístění objektu'], v['Odpad'], v['Telekomunikace'], v['Datum nastěhování'], v['Rok rekonstrukce'], v['Zařízeno'], v['Sklep'], v['Bezbariérový přístup'], v['Terasa'], v['Parkovací stání'], v['Plocha pozemku'], v['Zástavba'], v['Komunikace'], v['Energetická náročnost budovy: Energetická náročnost budov'], v['Půdní vestavba'], nil, v['Popis'], nil, v['Gps']['lat'], v['Gps']['lon'] ] if v['Images'] v['Images'].each { |image| record << image['image'] } end csv << record end end rescue puts $!, $@ end end puts_divider dt_end = Time.now timeDiff = dt_end - dt_start puts "#{DateTime.now} Time of run: #{timeDiff}" puts_divider
#-*- mode: ruby -*- # vi: set ft=ruby : ms_jmx_port = 1099 router_jmx_port = 1100 mp_jmx_port = 1101 ingest_jmx_port = 1102 pgserver_jmx_port = 1103 pg_db_port = 5432 zk_jmx_port = 2181 cassandra_jmx_port = 7199 ms_http_port = 8080 router_self_port = 8081 mp_self_port = 8082 qpid_self_port = 8083 pgserver_self_port = 8084 cassandra_db_port = 9160 cassandra_interal_comm_port1 = 7000 cassandra_interal_comm_port2 = 9042 ui_http_port = 9000 edge_proxy_port = 9001 mysql_port = 3306 open_ldap_port = 10389 http_port = 80 expose_graphite_port = 9090 grafana_http_port = 3000 local_address = "172.28.128.55" vm_memory = 8192 Vagrant.configure(2) do |config| config.ssh.insert_key = false config.vm.box = "uclbioresource/oracle68" config.vm.define "aio_node" do |node| node.vm.hostname = '127.0.0.1' node.vm.network "private_network", ip: local_address node.vm.network "forwarded_port", guest: ms_http_port, host: ms_http_port node.vm.network "forwarded_port", guest: ms_jmx_port, host: ms_jmx_port node.vm.network "forwarded_port", guest: grafana_http_port, host: grafana_http_port node.vm.network "forwarded_port", guest: cassandra_jmx_port, host: cassandra_jmx_port node.vm.network "forwarded_port", guest: cassandra_db_port, host: cassandra_db_port node.vm.network "forwarded_port", guest: cassandra_interal_comm_port1, host: cassandra_interal_comm_port1 node.vm.network "forwarded_port", guest: cassandra_interal_comm_port2, host: cassandra_interal_comm_port2 node.vm.network "forwarded_port", guest: zk_jmx_port, host: zk_jmx_port node.vm.network "forwarded_port", guest: ui_http_port, host: ui_http_port node.vm.network "forwarded_port", guest: edge_proxy_port, host: edge_proxy_port node.vm.network "forwarded_port", guest: open_ldap_port, host: open_ldap_port node.vm.network "forwarded_port", guest: router_jmx_port, host: router_jmx_port node.vm.network "forwarded_port", guest: router_self_port, host: router_self_port node.vm.network "forwarded_port", guest: mp_jmx_port, host: mp_jmx_port node.vm.network "forwarded_port", guest: mp_self_port, host: mp_self_port node.vm.network "forwarded_port", guest: http_port, host: expose_graphite_port node.vm.network "forwarded_port", guest: mysql_port, host: mysql_port node.vm.network "forwarded_port", guest: qpid_self_port, host: qpid_self_port node.vm.network "forwarded_port", guest: pgserver_self_port, host: pgserver_self_port node.vm.network "forwarded_port", guest: pg_db_port, host: pg_db_port node.vm.network "forwarded_port", guest: pgserver_jmx_port, host: pgserver_jmx_port node.vm.network "forwarded_port", guest: ingest_jmx_port, host: ingest_jmx_port end config.vm.provider :virtualbox do |vb| vb.memory = vm_memory end end
class UsersController < ApplicationController def index end def show get_user end def edit get_user end def update get_user if @user.update_attributes(user_params) redirect_to user_path(@user) else redirect_to root_path, notice: "Couldn't save settings" end end def destroy end def new end def create end def user_params params.require(:user).permit(:email,:password,:fName,:lName) end def send_test_email TestMailer.test("hi@email.com").deliver redirect_to :back end private def get_user @user= User.find(params[:id]) end end
module APICoder module Commands class InstallPlugin < Thor::Group argument :plugin_name include Thor::Actions source_root File.expand_path('../templates', __FILE__) def create_config_file begin require "api_coder/#{plugin_name}" rescue LoadError raise "api_coder/#{plugin_name} is not found in load path" end inject_into_file 'bin/api_coder', after: "### end point for api_coder plugins\n" do "require 'api_coder/#{plugin_name}'\n" end end end end end
# frozen_string_literal: true # https://adventofcode.com/2019/day/6 require 'pry' require './boilerplate' class Planet attr_accessor :name, :parent, :children def initialize(name) @name = name @children = [] end def orbits parent.nil? ? 0 : parent.orbits + 1 end def parent?(planet) parent.nil? ? false : (parent == planet || parent.parent?(planet)) end def distance_to(planet) raise "no parent, unable to calculate distance" if parent.nil? planet == parent ? 0 : 1 + parent.distance_to(planet) end end class Universe attr_accessor :planets def initialize @planets = {} @planets["COM"] = Planet.new("COM") end def planet(name, parent: nil) @planets[name] ||= Planet.new(name) unless parent.nil? @planets[name].parent = parent parent.children << @planets[name] end @planets[name] end def orbits @planets.values.reduce(0) {|sum, p| sum + p.orbits} end def min_distance(from_name, to_name) from = @planets[from_name] to = @planets[to_name] @planets.values.reduce(nil) do |min, planet| if from.parent?(planet) && to.parent?(planet) distance = from.distance_to(planet) + to.distance_to(planet) min.nil? || min > distance ? distance : min else min end end end end def parse(orbits) universe = Universe.new() orbits.map {|o| o.split(')').map(&:strip)}.each do |o| universe.planet(o[1], parent: universe.planet(o[0])) end universe end part 1 do example = parse(["COM)B\n", "B)C\n", "E)F\n", "B)G\n", "G)H\n", "D)E\n", "D)I\n", "E)J\n", "J)K\n", "K)L\n", "C)D\n"]) assert_call_on(example.planets, 12, :length) assert_call_on(example.planet('C').parent, 'B', :name) assert_call_on(example.planet('C').children, 1, :length) assert_call_on(example.planet('C').children.first, 'D', :name) assert_call_on(example.planet('D'), 3, :orbits) assert_call_on(example.planet('L'), 7, :orbits) assert_call_on(example.planet('COM'), 0, :orbits) assert_call_on(example, 42, :orbits) log_call_on(parse(input), :orbits) # 402879 end part 2 do example = parse(['COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L', 'K)YOU', 'I)SAN']) assert_call_on(example.planet('SAN'), true, :parent?, example.planet('D')) assert_call_on(example.planet('SAN'), true, :parent?, example.planet('I')) assert_call_on(example.planet('SAN'), false, :parent?, example.planet('E')) assert_call_on(example.planet('SAN'), false, :parent?, example.planet('SAN')) assert_call_on(example.planet('SAN'), 1, :distance_to, example.planet('D')) assert_call_on(example.planet('YOU'), 3, :distance_to, example.planet('D')) assert_call_on(example, 4, :min_distance, 'SAN', 'YOU') log_call_on(parse(input), :min_distance, 'SAN', 'YOU') # 484 end
class EventsController < ApplicationController before_action :set_params, only: [:index, :more_events] def index api_token = ApiToken.find_by(platform: 'meetup') begin if api_token.present? if api_token.expire_on > Time.now events = RestClient.get "https://api.meetup.com/#{Settings.meetup.group_urlname}/events?status=upcoming,past&desc=true", headers: { "Authorization" => "Bearer #{api_token.access_token}"} else # TODO fetch new access token using refresh token access_response = RestClient.post Settings.meetup.OAuth_api_end_point, {client_id: MEETUP_API_KEY, client_secret: MEETUP_API_SECRET, grant_type: 'refresh_token', refresh_token: api_token.refresh_token} end events = JSON.parse(events) rescue [] @events = Kaminari.paginate_array(events).page(params[:page]).per(Settings.pagination.blogs.per_page) end respond_to do |format| format.js format.html end rescue Exception => e Rails.logger.error "Error: #{e.message} - #{e.backtrace.join('\n')}" flash[:danger] = "Something went wrong. Please try after sometime" redirect_to root_path end end def connect_with_meetup end def more_events get_events(@params.merge(offset: params[:offset])) if params[:offset].present? end def get_events(params) @meetup_api = MeetupApi.new events = @meetup_api.events(params) events(events) end def events(events) if events.present? && events['meta'].present? if events['meta']['next'].present? url = events['meta']['next'] uri = URI.parse(url) url_params = CGI.parse(uri.query) @next_page = url_params['offset'].first end @events = events['results'] end end private def set_params @params = { group_urlname: Settings.meetup.group_urlname, scroll: 'future_or_past', status: 'upcoming,past', format: 'json', page: Settings.meetup.per_page, desc: true, limited_events: true } end end
class User < ApplicationRecord include Recommendation include PublicActivity::Model tracked store :settings, accessors: [:birthday, :personal_activity], coder: JSON has_one_attached :avatar has_many :user_books has_many :books, through: :user_books has_many :lists, dependent: :destroy has_many :user_tags has_many :tags, through: :user_tags has_secure_password validates :name, presence: true validates :login_name, presence: true, uniqueness: { case_sensitive: false } def recent_lists lists.last(3) end def favorite_books user_books.favorite_books.map(&:book) end def favorite_authors user_books.favorite_authors.map(&:book).map(&:author) end def recent_activity PublicActivity::Activity.order('created_at desc') .where(owner_type: "User", owner_id: id) .group_by { |activity| activity.updated_at.to_date } end def update_password(password, password_confirmation) self.update(password: password, password_confirmation: password_confirmation) end def attach_avatar(avatar) avatar_file = "#{avatar}.png" path = "app/assets/images/avatars/#{avatar_file}" self.avatar.attach(io: File.open(path), filename: avatar_file, content_type: 'image/png') end end
class AddFieldsToRepository < ActiveRecord::Migration def change change_table :repositories do |t| t.column :address_1, :string t.column :address_2, :string t.column :city, :string t.column :state, :string t.column :zip, :string t.column :phone_number, :string t.column :email, :string end end end
class SessionController < ApplicationController def create if open_id?(params[:name]) open_id_authentication(params[:name]) else password_authentication(params[:name], params[:password]) end end protected def password_authentication(name, password) if @current_user = @account.users.find_by_name_and_password(params[:name], params[:password]) successful_login else failed_login "Sorry, that username/password doesn't work" end end def open_id_authentication(identity_url) authenticate_with_open_id(identity_url) do |status, identity_url| case status when :missing failed_login "Sorry, the OpenID server couldn't be found" when :canceled failed_login "OpenID verification was canceled" when :failed failed_login "Sorry, the OpenID verification failed" when :successful if @current_user = @account.users.find_by_identity_url(identity_url) successful_login else failed_login "Sorry, no user by that identity URL exists" end end end end private def successful_login session[:user_id] = @current_user.id redirect_to(root_url) end def failed_login(message) flash[:error] = message redirect_to(new_session_url) end # Set #root_url if your root url has a different named route. # # map.home '', :controller => ..., :action => ... # # Otherwise, name the route 'root' and leave this method out. def root_url home_url end end
class Columbus class Feed < Struct.new(:url, :title) attr_accessor :body def initialize(*args) super(*args) determine_feed_endpoint end def determine_feed_endpoint response = RedirectFollower.new(url).resolve self.url = response.url self.body = response.body self end end end
class Image < ApplicationRecord belongs_to :image_type, polymorphic: true end
class UsersController < ApplicationController before_filter :authenticate_user! after_action :verify_authorized def index @users = User.all.where(deleted: false) authorize User end def show @user = User.find(params[:id]) authorize @user end def new @user = User.new authorize User end def create @user = User.new(secure_params) @user.save authorize User redirect_to users_path, :notice => "User created." end def edit @user = User.find(params[:id]) authorize User end def update @user = User.find(params[:id]) authorize @user if @user.update_attributes(secure_params) redirect_to users_path, :notice => "User updated." else redirect_to users_path, :alert => "Unable to update user." end end def destroy user = User.find(params[:id]) authorize user user.destroy redirect_to users_path, :notice => "User deleted." end private def secure_params params.require(:user).permit(:firstname, :lastname, :nickname, :email, :password, :password_confirmation, :birthday, :oncalendar, :onsite, :atoffice, :deleted) end end
module SpecSupport module Cars def fetch_car_brand(index) all('.car')[-index].find("h2").text end def last_car_brand fetch_car_brand(1) end def second_to_last_car_brand fetch_car_brand(2) end def third_to_last_car_brand fetch_car_brand(3) end def fetch_car_model(index) all('.car')[-index].first("p").text end def last_car_model fetch_car_model(1) end def second_to_last_car_model fetch_car_model(2) end def third_to_last_car_model fetch_car_model(3) end def fetch_car_year(index) all('.car')[-index].find("p:last-child").text end def last_car_year fetch_car_year(1) end def second_to_last_car_year fetch_car_year(2) end def third_to_last_car_year fetch_car_year(3) end end module ClickCars def count_cars all('.car').count end def click_for_cars car_count = count_cars click_button("Load more cars") start_time = Time.now end_time = Time.now until end_time - start_time > 10 return true if count_cars >= car_count + 3 sleep(0.001) end_time = Time.now end false end end end
require "./poker-dice.rb" describe Die do describe "#roll" do it "returns a face value" do expect(Die.new.roll.length).to eq 1 end it "returns a string" do expect(Die.new.roll.class).to eq String end it "returns one of the available face values" do expect(Die.new.roll).to match (/[9TJQKA]/) end end end describe Hand do describe "#initialize" do it "has five dice in a hand instance" do expect(Hand.new.dice.count).to eq 5 end it "uses face value" do expect(Hand.new.dice[0].class).to eq String end end describe "#keep" do it "should have a count of 2" do hand = Hand.new hand.keep expect(hand.final_dice.count).to eq 2 end end # describe "#reroll" do # it "number of dice in hand is exactly five" do # expect(Hand.new.reroll.dice.count).to eq 5 # end # end end
class FavoriteSport < ApplicationRecord belongs_to :user belongs_to :sport validates :sport, presence: true validates :level, presence: true end
class ChangeBeans < ActiveRecord::Migration def up add_column :beans, :user_id, :integer rename_column :beans, :is_checkout, :redeemed end def down end end
class CreateBusinesses < ActiveRecord::Migration[5.2] def change create_table :businesses, comment: "業務" do |t| t.string :name, null:false, comment: "業務タイトル" t.string :description, null:false, comment: "詳細内容" t.string :welcome, null:false, comment: "歓迎技術者" t.references :office, foreign_key: true, comment: "募集事業所" t.references :business_type, comment: "業務種別" t.references :business_status, comment: "募集状態" t.references :parent_business, foreing_key: {to_table: :businesses}, null:true, comment: "親業務" t.integer :max_quantity, comment: "受入可能人数" t.integer :proper_quantity, comment: "希望募集人数" t.money :budget, comment: "予算" t.date :open_date, default: -> {'CURRENT_DATE'}, comment: "受付開始日" t.date :enable_date, default: -> {'CURRENT_DATE'}, comment: "受入可能日" t.date :end_date, default: '9999-12-31', comment: "受付締切日" t.date :expire_schedule, default: '9999-12-31', comment: "データ削除予定日" t.timestamps end end end
# coding: utf-8 module Typus class << self def root File.dirname(__FILE__) + "/../" end def locales { "ca" => "Català", "de" => "German", "en" => "English", "es" => "Español", "fr" => "Français", "hu" => "Magyar", "pt-BR" => "Portuguese", "ru" => "Russian" } end def applications Typus::Configuration.config.collect { |i| i.last["application"] }.compact.uniq.sort end # List of the modules of an application. def application(name) Typus::Configuration.config.collect { |i| i.first if i.last["application"] == name }.compact.uniq.sort end # Gets a list of all the models on the configuration file. def models Typus::Configuration.config.map { |i| i.first }.sort end def models_on_header models.collect { |m| m if m.constantize.typus_options_for(:on_header) }.compact end # List of resources, which are tableless models. def resources Typus::Configuration.roles.keys.map do |key| Typus::Configuration.roles[key].keys end.flatten.sort.uniq.delete_if { |x| models.include?(x) } end # Gets a list of models under app/models def discover_models all_models = [] Dir.chdir(File.join(Rails.root, "app/models")) do Dir["**/*.rb"].each do |m| class_name = m.sub(/\.rb$/,"").camelize klass = class_name.split("::").inject(Object){ |klass,part| klass.const_get(part) } all_models << "#{class_name}" if klass < ActiveRecord::Base && !klass.abstract_class? end end return all_models end def user_class Typus::Configuration.options[:user_class_name].constantize end def user_fk Typus::Configuration.options[:user_fk] end def relationship Typus::Configuration.options[:relationship] end def testing? Rails.env.test? && Dir.pwd == "#{Rails.root}/vendor/plugins/typus" end def plugin? File.directory?("#{Rails.root}/vendor/plugins/typus") end def boot! if testing? Typus::Configuration.options[:config_folder] = "vendor/plugins/typus/test/config/working" end # Ruby/Rails Extensions require "extensions/array" require "extensions/hash" require "extensions/object" require "extensions/string" require "extensions/active_record" # Load configuration and roles. Typus::Configuration.config! Typus::Configuration.roles! # Active Record Extensions. require "typus/active_record" # Typus mixins. require "typus/authentication" require "typus/format" require "typus/preferences" require "typus/reloader" require "typus/quick_edit" require "typus/user" # Vendor. require "vendor/paginator" require "vendor/inherit_views" end end end
# frozen_string_literal: true class ChangeSchoolsCodeColumnLength < ActiveRecord::Migration[4.2] def change change_column :schools, :code, :string, :limit => 32 end end
require "rails_helper" RSpec.describe RegisteredPatientsQuery do let(:user) { create(:user) } it "counts hypertensive registered patients by period" do facility = create(:facility) other_facility = create(:facility) user1 = create(:user) user2 = create(:user) Timecop.freeze("April 15th 2020") do create_list(:patient, 2, registration_facility: facility, registration_user: user1) create_list(:patient, 2, registration_facility: facility, registration_user: user1, recorded_at: "January 15 2020") create(:patient, :without_hypertension, registration_facility: facility) create_list(:patient, 1, registration_facility: other_facility, registration_user: user2) end result = described_class.new.count(facility, :month) expect(result[Period.month("December 1st 2020")]).to be_nil expect(result[Period.month("January 1st 2020")]).to eq(2) expect(result[Period.month("April 1st 2020")]).to eq(2) end it "includes dead patients" do facility = create(:facility) other_facility = create(:facility) create(:patient, registration_facility: facility, recorded_at: 3.months.ago, status: :dead, registration_user: user) create(:patient, registration_facility: other_facility, recorded_at: 2.months.ago, registration_user: user) result = described_class.new.count(facility, :month) expect(result).to eq({ 3.month.ago.to_period => 1 }) end it "can count by optional group_by arg" do facility = create(:facility) user1 = create(:user) user2 = create(:user) Timecop.freeze("April 15th 2020") do create_list(:patient, 2, registration_facility: facility, registration_user: user1) create_list(:patient, 2, registration_facility: facility, registration_user: user1, recorded_at: "January 15 2020") create_list(:patient, 3, registration_facility: facility, registration_user: user2) create(:patient, :without_hypertension, registration_facility: facility) end result = described_class.new.count(facility, :month, group_by: :registration_user_id) expected_for_jan = { user1.id => 2, user2.id => 0 } expect(result[Period.month("January 1st 2020")]).to eq(expected_for_jan) expected_for_april = { user1.id => 2, user2.id => 3 } expect(result[Period.month("April 1st 2020")]).to eq(expected_for_april) end end
class CopyrightFullService < ExperimentService PAIR_SIZE = 17 * 3 * 2 # (Full + Melody + Lyrics) * Random class << self def create(options) DB.transaction do exp = Experiment.create( username: options['username'], model: 'CopyrightFullEntry', ) PAIR_SIZE.times.to_a.shuffle.each do |i| if i < PAIR_SIZE / 2 CopyrightFullEntry.create( experiment: exp, pair_id: i, ) else song_a = (0...17).to_a.sample(1)[0] song_b = ((0...17).to_a - [song_a]).sample(1)[0] CopyrightFullEntry.create( experiment: exp, pair_id: i, song_a: song_a, song_b: song_b, ) end end return CopyrightFullService.new(exp) end end def find(options) exp = Experiment.where( username: options['username'], model: 'CopyrightFullEntry', )&.first raise NotFoundError.new('Experiment', 'No Such Experiment Existed') if exp.nil? CopyrightFullService.new(exp) end def export Experiment.where( model: 'CopyrightFullEntry', ).map do |exp| { username: exp.username, res: exp.entries.map { |row| { id: row.pair_id, similarity: row.similarity, infringe: row.infringe, answered: row.edited, } } } end end end def initialize(entity) @entity = entity end def next entity = @entity.entries.where(edited: false).order(:id).first raise NotFoundError.new('Entity', 'Experiment Finished') if entity.nil? pair_id = entity.pair_id res = { id: entity.id, progress: @entity.entries.where(edited: true).count.to_f / @entity.entries.count, wavs: [], lyrics: [], } if (0...17).include?(pair_id) res[:wavs] << { label: 'A', entity: "/static/copyright_full/full/#{pair_id}a.mp3", } res[:wavs] << { label: 'B', entity: "/static/copyright_full/full/#{pair_id}b.mp3", } elsif (17...34).include?(pair_id) res[:wavs] << { label: 'A', entity: "/static/copyright_full/melody/#{pair_id - 17}a.mp3", } res[:wavs] << { label: 'B', entity: "/static/copyright_full/melody/#{pair_id - 17}b.mp3", } elsif (34...51).include?(pair_id) res[:lyrics] << { label: 'A', entity: "#{pair_id - 34}a", } res[:lyrics] << { label: 'B', entity: "#{pair_id - 34}b", } elsif (51...68).include?(pair_id) res[:wavs] << { label: 'A', entity: "/static/copyright_full/full/#{entity.song_a}a.mp3", } res[:wavs] << { label: 'B', entity: "/static/copyright_full/full/#{entity.song_b}b.mp3", } elsif (68...85).include?(pair_id) res[:wavs] << { label: 'A', entity: "/static/copyright_full/melody/#{entity.song_a}a.mp3", } res[:wavs] << { label: 'B', entity: "/static/copyright_full/melody/#{entity.song_b}b.mp3", } elsif (85...102).include?(pair_id) res[:lyrics] << { label: 'A', entity: "#{entity.song_a}a", } res[:lyrics] << { label: 'B', entity: "#{entity.song_b}b", } end res end def update(options) entry = @entity.entries.where(id: options['id'])&.first raise NotFoundError.new('Entry Not Existed') if entry.nil? entry.similarity = options['similarity'] entry.infringe = options['infringe'] entry.edited = true entry.save nil end def destroy @entity.entries.delete @entity.delete end end
require 'ncs_navigator/configuration' module NcsNavigator::Authorization::Core class Authority attr_reader :logger attr_reader :staff_portal_uri attr_reader :staff_portal_user attr_reader :staff_portal_password def initialize(options = {}) @logger = options[:logger] || Logger.new($stderr) @staff_portal_uri = options[:staff_portal_uri] || NcsNavigator.configuration.staff_portal_uri @staff_portal_user = options[:staff_portal_user] || "psc_application" @staff_portal_password = options[:staff_portal_password] || NcsNavigator.configuration.staff_portal['psc_user_password'] @groups = {} @portal = :NCSNavigator end def amplify!(user) base = user(user) return user unless base user.merge!(base) end def user(user) staff = get_staff(user) if staff u = Aker::User.new(user.username) u.portals << @portal attributes = ["first_name", "last_name", "email"] attributes.each do |a| setter = "#{a}=" if u.respond_to?(setter) u.send(setter, staff[a]) end end u.identifiers[:staff_id] = staff["staff_id"] groups = staff['roles'].collect do |role| role['name'] end if groups u.group_memberships(@portal).concat(load_group_memberships(@portal, groups)) end u else nil end end def find_users(*criteria) return [] unless criteria.empty? result = [] if users = get_users users.each do |u| next if u["username"].blank? au = Aker::User.new(u["username"]) au.identifiers[:staff_id] = u["staff_id"] au.first_name = u["first_name"] au.last_name = u["last_name"] result << au end end result end private def get_connection(user) connection = staff_portal_client(create_authenticator(user)).connection end def staff_portal_client(authenticator) NcsNavigator::Authorization::StaffPortal::Client.new(staff_portal_uri, :authenticator => authenticator) end def create_authenticator(user) { :token => lambda { user.cas_proxy_ticket(staff_portal_uri) } } end def machine_authenticator { :basic => [staff_portal_user, staff_portal_password] } end def load_group_memberships(portal, group_data) group_data.collect do |group| Aker::GroupMembership.new(find_or_create_group(portal, group)) end end def find_or_create_group(portal, group_name) existing = (@groups[portal] ||= []).collect { |top| top.find { |g| g.name == group_name } }.compact.first return existing if existing @groups[portal] << Aker::Group.new(group_name) @groups[portal].last end def get_staff(user) connection = get_connection(user) response = make_request(connection, '/staff/' << user.username << '.json') if response.status == 200 response.body else nil end end def make_request(connection, url) connection.get(url) end def get_users users = nil begin connection = staff_portal_client(machine_authenticator).connection response = make_request(connection, '/users.json') if response.status == 200 users = response.body else logger.warn("#{Time.now}: Staff Portal Response: #{response.body}") end rescue => e logger.error("#{Time.now} : Staff Portal: #{e.class} #{e}") end users end end end
require 'rails_helper' RSpec.describe Friend, type: :model do it { should be_activitable } it { should be_accompaniable } it { should be_experienceable } it { should be_learnable } it { should have_many :activities } it { should have_many :accompaniments } it { should have_many :experiences } it { should have_many :learnings } let(:user) { FactoryGirl.create(:user, :with_one_friend) } let(:friend) { user.friends.first } let(:activity) { FactoryGirl.create :activity, activitable: user } let(:accompaniment) { FactoryGirl.create :accompaniment, accompaniable: user } let(:experience) { FactoryGirl.create :experience, experienceable: user } let(:learning) { FactoryGirl.create :learning, learnable: user } let(:new_friend) { Friend.new(email: 'friend@email.com') } it 'does not validate password' do expect(new_friend).to be_valid end end
require 'facter' Facter.add(:shortdcname) do setcode do location = Facter.value(:hostname)[1] case location when '1' then shortdcname = 'd1' when '3','gl' then shortdcname = 'd3' else 'unknown' end end end
class CreateCustomers < ActiveRecord::Migration def change create_table :customers do |t| t.string "first_name", :null => false t.string "last_name", :null => false t.string "addrStreet1" t.string "addrStreet2" t.string "addrCity" t.string "addrState" t.string "addrZip" t.string "phone" t.string "email" end add_index :customers, :phone, :unique => true add_index :customers, :email, :unique => true end end
# frozen_string_literal: true require 'rails_helper' # These tests will fail if the test database is rebuilt using db:schema:load # To fix, run the following from the command line: # rails db:structure:load RAILS_ENV=test RSpec.describe 'Visit the best efforts page and search for an effort' do let(:course) { courses(:hardrock_ccw) } let(:event) { events(:hardrock_2015) } let(:effort_1) { event.efforts.ranked_with_status.first } let(:other_efforts) { event.efforts.where.not(id: effort_1.id) } scenario 'Visitor visits the page and searches for a name' do visit best_efforts_course_path(course) expect(page).to have_content(course.name) finished_efforts = event.efforts.ranked_with_status.select(&:finished) finished_efforts.each { |effort| verify_link_present(effort, :full_name) } fill_in 'First name, last name, state, or country', with: effort_1.name click_button 'search-submit' wait_for_css verify_link_present(effort_1) other_efforts.each { |effort| verify_content_absent(effort) } end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cancancan/active_graph/version' Gem::Specification.new do |spec| spec.name = 'cancancan-activegraph' spec.version = CanCanCan::ActiveGraph::VERSION spec.authors = ['Amit Suryavanshi'] spec.email = ['amitbsuryavanshi@gmail.com'] spec.homepage = 'https://github.com/CanCanCommunity/cancancan-activegraph' spec.summary = 'neo4j database adapter for CanCanCan.' spec.description = "Implements CanCanCan's rule-based record fetching using neo4j gem." spec.platform = Gem::Platform::RUBY spec.license = 'MIT' spec.files = `git ls-files lib init.rb cancancan-activegraph.gemspec`.split($INPUT_RECORD_SEPARATOR) spec.require_paths = ['lib'] spec.add_dependency 'activegraph', '>= 9.0.0' spec.add_dependency 'cancancan' spec.add_development_dependency 'bundler', '>= 1.3' spec.add_development_dependency("neo4j-#{RUBY_PLATFORM =~ /java/ ? 'java' : 'ruby'}-driver", '>= 0.3.0') spec.add_development_dependency('neo4j-rake_tasks', '>= 0.3.0') spec.add_development_dependency 'pry', '>= 0.11.3' spec.add_development_dependency 'rake', '>= 10.1' spec.add_development_dependency 'rspec', '>= 3.2' spec.add_development_dependency 'rubocop', '>= 0.48.1' end
class UserGroup < ActiveRecord::Base attr_accessible :user_id, :group_id belongs_to :user belongs_to :group attr_accessible :edit, :manage, :read end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :configure_permitted_parameters, if: :devise_controller? layout :layout_by_resource # API authentication # http://soryy.com/blog/2014/apis-with-devise/ protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json'} before_filter :authenticate_user_from_token! # before_filter :authenticate_user! protected def layout_by_resource if devise_controller? && resource_name == :user && action_name == "new" "lock_screen" else "application" end end # https://github.com/scambra/devise_invitable def configure_permitted_parameters # Only add some parameters devise_parameter_sanitizer.for(:accept_invitation).concat [:name, :org_id] # Override accepted parameters devise_parameter_sanitizer.for(:accept_invitation) do |u| u.permit(:name, :org_id, :password, :password_confirmation, :invitation_token) end end def authenticate_user_from_token! user_email = request.headers["X-API-EMAIL"].presence user_auth_token = request.headers["X-API-TOKEN"].presence user = user_email && User.find_by_email(user_email) # Notice how we use Devise.secure_compare to compare the token # in the database with the token given in the params, mitigating # timing attacks. if user && Devise.secure_compare(user.authentication_token, user_auth_token) sign_in(user, store: false) end end end
class CreatePageDesigns < ActiveRecord::Migration def change create_table :page_designs do |t| t.references :site t.references :folder t.text :stylesheet t.string :header_image_file_name t.string :header_image_content_type t.integer :header_image_file_size t.string :header_color, :limit => 10 t.string :background_color, :limit => 10 t.string :background_image_file_name t.string :background_image_content_type t.integer :background_image_file_size t.string :background_position # left, center, right t.string :background_repeat # repeat-x, repeat-y, repeat, no-repeat t.string :background_attachment # fixed, scroll t.boolean :background_interited_from_site, :default => true t.text :footer_html t.text :header_html t.timestamps end end end
require "rails_helper" describe PatientStates::Hypertension::ControlledPatientsQuery do around do |example| with_reporting_time_zone { example.run } end let(:regions) { setup_district_with_facilities } let(:period) { Period.current } describe "#call" do it "returns all the controlled patients in a region as of the given period" do facility_1_controlled_patients = create_list(:patient, 1, :controlled, assigned_facility: regions[:facility_1]) facility_1_uncontrolled_patients = create_list(:patient, 1, :uncontrolled, assigned_facility: regions[:facility_1]) facility_2_controlled_patients = create_list(:patient, 1, :controlled, assigned_facility: regions[:facility_2]) facility_2_uncontrolled_patients = create_list(:patient, 1, :uncontrolled, assigned_facility: regions[:facility_2]) refresh_views expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:facility_1].region, period) .call .map(&:patient_id)) .to match_array(facility_1_controlled_patients.map(&:id)) expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:facility_2].region, period) .call .map(&:patient_id)) .to match_array(facility_2_controlled_patients.map(&:id)) expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:facility_1].region, period) .call .map(&:patient_id)) .not_to include(*facility_1_uncontrolled_patients.map(&:id)) expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:facility_2].region, period) .call .map(&:patient_id)) .not_to include(*facility_2_uncontrolled_patients.map(&:id)) expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:region].region, period) .call .map(&:patient_id)) .to match_array((facility_1_controlled_patients + facility_2_controlled_patients).map(&:id)) end it "returns same number of controlled patients as in the reporting facility states" do _facility_1_controlled_patients = create_list(:patient, 1, :controlled, assigned_facility: regions[:facility_1]) refresh_views expect(PatientStates::Hypertension::ControlledPatientsQuery.new(regions[:facility_1].region, period).call.count) .to eq(Reports::FacilityState .find_by(facility_id: regions[:facility_1].id, month_date: period.begin) .adjusted_controlled_under_care) end end end
require 'lib/watir-or.rb' require 'spec_helper' describe "Read xml-repository" do before(:all) do @repository = ObjectRepository::Repository.new("spec/test.xml", BrowserStub.new) end it "element with one attribute was readed" do one = ObjectRepository::RepositoryElement.new("one attribute", "text_field", [:name], ["test"], "Element with one attribute", @repository) @repository.get("one attribute").should == one end it "element with many attribute was readed" do many = ObjectRepository::RepositoryElement.new("many attributes", "select_list", [:text, :index], ["test text", 1], "Element with many attributes", @repository) @repository.get("many attributes").should == many end it "child element was readed" do child = ObjectRepository::RepositoryElement.new("with parent", "div", [:index, :parent], [3, "parent element"], "Element with parent", @repository) @repository.get("with parent").should == child end end
class CreateProjectGuests < ActiveRecord::Migration def self.up create_table :project_guests do |t| t.integer :guest_id t.integer :project_id t.boolean :status,:default=>true t.timestamps end add_index "project_guests", :guest_id add_index "project_guests", :project_id end def self.down drop_table :project_guests end end
require 'lims-api/resources/container' require 'lims-api/core_resource' require 'lims-api/struct_stream' require 'lims-laboratory-app/laboratory/tube_rack' module Lims::LaboratoryApp module Laboratory class TubeRack class TubeRackResource < Lims::Api::CoreResource include Lims::Api::Resources::Container def elements_name :tubes end def children_to_stream(s, mime_type) s.add_key :tubes tubes_to_stream(s, mime_type) end def tubes_to_stream(s, mime_type) tubes = {} object.each_with_index { |tube, location| tubes[location] = tube } hash_to_stream(s, tubes, mime_type) end end end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe RequirementsController, 'when integrating' do integrate_views before :each do @requirement = Requirement.generate! end describe 'create' do def do_request post :create, :requirement => @requirement.attributes end it_should_behave_like "a redirecting action" end describe 'destroy' do before(:each) do @requirement = Requirement.generate! @requirement_id = @requirement.id.to_s end def do_delete delete :destroy, { :id => @requirement_id } end it 'should fail if requested requirement does not exist' do @requirement.destroy lambda { do_delete }.should raise_error end it 'should delete the requested requirement' do lambda { do_delete }.should change(Requirement, :count) end it 'should redirect to the source service after deleting an requirement' do instance = @requirement.instance delete :destroy, :id => @requirement_id response.should redirect_to(instance_path(instance)) end end describe 'create' do before :each do @instance, @service = Instance.generate!, Service.generate! @instance_id, @service_id = @instance.id.to_s, @service.id.to_s end it 'should fail when no instance_id is provided' do lambda { post :create, :requirement => { :service_id => @service_id } }.should raise_error end it 'should fail when no service_id is provided' do lambda { post :create, :requirement => { :instance_id => @instance_id } }.should raise_error end it 'should fail when an invalid instance_id is provided' do lambda { post :create, :requirement => { :instance_id => (@instance.id+100).to_s, :service_id => @service_id } }.should raise_error end it 'should fail when an invalid service_id is provided' do lambda { post :create, :requirement => { :instance_id => @instance_id, :service_id => (@service.id+100).to_s } }.should raise_error end it 'should create a new requirement from the instance to the service' do lambda { post :create, :requirement => { :instance_id => @instance_id, :service_id => @service_id } }.should change(Requirement, :count) end it 'should redirect to the instance show page' do post :create, :requirement => { :instance_id => @instance_id, :service_id => @service_id } response.should redirect_to(instance_path(@instance)) end end end
class ApplicationController < ActionController::Base before_action :authentication_required skip_before_action :authentication_required, only: [:welcome] protect_from_forgery with: :exception helper_method :current_user, :logged_in?, :contact_to_relationship, :error_msg def logged_in? !!session[:user_id] end def current_user current_user ||= User.find(session[:user_id]) end def authentication_required if !logged_in? redirect_to root_path end end def welcome end end
include Support::Php require 'features/php_interpreter_spec' describe 'php environment', dev: true do describe phpcommand('php-fpm --version') do its(:exit_status) { should eq 0 } its(:stdout) { should match(/^PHP \d+\.\d+\.\d+.+fpm-fcgi/) } end describe phpcommand('php -m --version') do # Running `php -m` hangs, but adding more args doesn't (???) its(:stdout) { should include(*PHP_MODULES) } end describe file('/home/travis/.pearrc') do it { should_not exist } end end PHP_MODULES = <<EOF.split("\n") Core PDO Phar SPL Xdebug bcmath ctype curl date dom ereg exif filter ftp gd hash iconv json libxml mbstring pcre pdo_mysql pdo_sqlite posix readline sqlite3 standard sysvsem sysvshm tidy xmlrpc xmlwriter xsl zip zlib EOF
require "rails_helper" module RequestsHelper def self.prepare_requests # Usuwamy wszystkie obiekty, klasa po klasie User.all.destroy_all Movie.all.destroy_all Topic.all.destroy_all Post.all.destroy_all # Tworzymy nowego usera, zapisujemy go i uzyskujemy token user = User.new( index: "123456", name:"Zenon", password: "haslo123" ) user.save! user.regenerate_token user.reload # Tworzymy i zapisujemy w bazie nowy film movie = Movie.new( name: "Nazwa filmu", ) movie.save! # Tworzymy i zapisujemy w bazie nowy temat topic = Topic.new( movie: movie, user: user, title: 'Tytuł tematu' ) topic.save! # Tworzymy i zapisujemy w bazie nowy post post = Post.new( topic: topic, user: user, body: 'Przykładowy post' ) post.save! # Zwracamy słownik z utworzonymi obiektami return { user: user, movie: movie, topic: topic, post: post } end end
require_relative "board" require_relative "opponents" def menu puts <<-HERE ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// MAIN MENU ///////////////////////////////////////////////////////////////////////////////// HERE commands end def commands puts <<-HERE Pick a command: n = New Game h = Help q = Quit HERE print "Command: " command = gets.chomp case command when /^(q|Q|quit|exit)$/ exit when /^(n|N|New Game)$/ play when /^(h|H|help|Help)$/ help commands else puts "\n What?! \n\n" commands end end def play seeds = set_num_seeds.to_i puts <<-HERE ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// Starting a new game of Kalaha with #{seeds} seeds per house. ///////////////////////////////////////////////////////////////////////////////// HERE board = Board.new(seeds) opponent = BasicOpponent.new board.show while true result = player_turn(board) unless result == :done show_score board break end board, result = opponent_turn(opponent, board) unless result == :done show_score board break end end replay?() end def help puts <<-HERE ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// HELP ///////////////////////////////////////////////////////////////////////////////// This is the board: . 1. . 2. . 3. . 4. . 5. . 6. _.======================================================================._ // | ---- ---- ---- :: ---- ---- ---- | \\\\ || | | | | | | | :: | | | | | | | || || ---- | ---- ---- ---- :: ---- ---- ---- | ---- || || | | | :: | | | || || | | | :: | | | || || | | | :: | | | || || ---- | ---- ---- ---- :: ---- ---- ---- | ---- || || | | | | | | | :: | | | | | | | || '| | ---- ---- ---- :: ---- ---- ---- | |' *-~======================================================================-~* '13' '12' '11' .10. . 9. . 8. ///////////////////////////////////////////////////////////////////////////////// You control the houses on the right side / | : 4 5 6 | \\ of the board. They are numbered: | | : | 7 | \\ | : 10 9 8 | / Your opponent controls the houses / | 1 2 3 : | \\ on the left side of the board: | 0 | : | | \\ | 13 12 11 : | / ///////////////////////////////////////////////////////////////////////////////// Start sowing seeds from your side of the board by specifying the number of the house you wish to take seeds from, e.g. House: 4 Rules on playing the game can be found here: http://en.wikipedia.org/wiki/Kalah#Rules ///////////////////////////////////////////////////////////////////////////////// HERE end def set_num_seeds print " * Specify number of seeds per house (4-6): " num_seeds = gets.chomp if num_seeds =~ /q|quit|exit/ exit elsif num_seeds =~ /4|5|6/ num_seeds else puts " Must pick a number between 4 and 6\n\n" set_num_seeds end end def player_turn(board) puts "It's your turn. Pick a house to start sowing from:" begin result = nil while result.nil? print "House: " house = gets.chomp.to_i begin result = board.sow_seeds_from house rescue Exception => e if e.message.start_with? "[Invalid move]" puts e.message puts "try again." else raise end end end puts "You plant seeds from house #{house}:" board.show puts "Last seed landed in store. You get another turn." if result == :again end while result == :again result end def opponent_turn(op, board) begin board = board.flip house = op.pick_house_from board.seeds_in_houses result = board.sow_seeds_from house puts "Opponent plants seeds from house #{(house + 7) % 14}:" board = board.flip board.show puts "Last seed landed in store. Opponent gets another turn." if result == :again end while result == :again return board, result end def show_score(board) your_score = board.remaining_seeds opponent_score = board.flip.remaining_seeds puts <<-HERE Game over. #{(your_score > opponent_score ? "You won!" : "You lost.")} Final score: #{your_score} - #{opponent_score} HERE end def replay? print "Play again? (y/n): " if gets.chomp =~ /y|Y|yes|YES|yup|ok/ then play else exit end end menu
# frozen_string_literal: true require 'date' module IndieLand module MinistryOfCulture # Data Mapper class MusicEventsMapper def initialize(gateway_class = MinistryOfCulture::MusicApi) @gateway_class = gateway_class @gateway = @gateway_class.new end def find_events build_entity end private def build_entity @gateway.data.map do |event| EventMapper.new(event).build_entity end end # Extracts entity specific elements from data structure class EventMapper def initialize(event) @event = event end # rubocop:disable Metrics/MethodLength def build_entity IndieLand::Entity::Event.new( event_id: nil, event_uid: event_uid, event_name: event_name, event_website: event_website, event_ticket_website: event_ticket_website, description: description, sale_website: sale_website, source: source, sessions: sessions, like_num: 0 ) end # rubocop:enable Metrics/MethodLength private def event_uid @event['UID'] end def event_name @event['title'] end def event_website @event['sourceWebPromote'] end def event_ticket_website Repository::Tickets.find_ticket(event_name)[:ticket_url] end def ticket_website @event['webSales'] end def description @event['descriptionFilterHtml'] end def sale_website @event['webSales'] end def source @event['sourceWebName'] end def sessions @event['showInfo'].map do |session| SessionMapper.new(session).build_entity end end end # SessionMapper will map sessions of an event class SessionMapper def initialize(session) @session = session end def build_entity IndieLand::Entity::Session.new( session_id: nil, event_id: nil, start_time: start_time, end_time: end_time, address: address, place: place, ticket_price: ticket_price ) end def start_time DateTime.parse(@session['time']) end def end_time DateTime.parse(@session['endTime']) end def address @session['location'] end def place @session['locationName'] end def ticket_price @session['price'] end end end end end
class Source < ActiveRecord::Base has_many :facts, dependent: :destroy ORIG_SOURCE_OPTIONS = ["No", "Yes"] accepts_nested_attributes_for :facts, allow_destroy: true, reject_if: lambda { |a| a[:fact_text].blank? } end
module Ricer::Plug::Params class VariableParam < StringParam def convert_in!(input, message) super(input, message).to_sym end end end
require 'concerns/intervalable' class Spree::SubscriptionInterval < ActiveRecord::Base include Intervalable attr_accessible :name has_many :spree_subscription_interval_products, class_name: 'Spree::SubscriptionIntervalProduct', dependent: :destroy has_many :products, through: :spree_subscription_interval_products def self.translated_interval Spree::SubscriptionInterval::UNITS.map do |k, v| [I18n.t(v, scope: 'intervals.options', count: 0), k] end end end
class ContactsController < ApplicationController require 'nokogiri' require 'open-uri' before_action :set_contact, only: [:show, :edit, :update, :destroy] def index @contacts = current_user.contacts.order("created_at desc").page(params[:page]) # @contacts = Contact.all.order("created_at desc").page(params[:page]) end def show end def new @contact = Contact.new end def edit end def create @contact = Contact.new(contact_params) @contact.user_id = current_user.id if @contact.save redirect_to @contact, notice: 'Contact was successfully created.' else render :new end end def update @contact.user_id = current_user.id if @contact.update(contact_params) redirect_to @contact, notice: 'Contact was successfully updated.' else render :edit end end def destroy @contact.destroy redirect_to contacts_path, notice: 'Contact was successfully destroyed.' end def upload uploaded_io = params[:xml_file] file_path = Rails.root.join('vendor', uploaded_io.original_filename) File.open(file_path, 'wb') do |file| file.write(uploaded_io.read) end #parse xml doc = Nokogiri::XML(File.open(file_path)) doc.css("contacts contact").each do |node| name = node.children.css("name").text surname = node.children.css("lastName").text phone = node.children.css("phone").text.gsub(/\s+/, "") user_id = current_user.id Contact.create_contact(name,surname,phone,user_id) end redirect_to contacts_path, notice: 'Contacts were successfully imported.' end private def set_contact @contact = Contact.find(params[:id]) end def contact_params params.require(:contact).permit(:name, :surname, :phone, :user_id) end end
# == Schema Information # # Table name: team_bowlers # # id :integer not null, primary key # total_games :integer # total_pins :integer # bowler_id :integer # bowling_team_id :integer # class TeamBowler < ApplicationRecord end
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper') include TokyoCabinet describe QuotientCube::Tree::NodeManager do before(:each) do @tempfile = Tempfile.new('database') @database = TokyoCabinet::BDB.new @database.open(@tempfile.path, BDB::OWRITER | BDB::OCREAT) @tree = QuotientCube::Tree::Base.new(@database, :prefix => 'prefix') @root = @tree.nodes.create_root end it "should not find a root node" do @root.should == 1 end it "should not create a root node if it exists" do @tree.nodes.create_root.should == '1' @tree.nodes.root.should == '1' end it "should create a node" do @tree.nodes.create.should == 2 end it "should not find dimensions" do @tree.nodes.dimensions(@root).should == [] end it "should create and find dimensions" do @tree.nodes.add_dimension(@root, 'store').should == 'store' @tree.nodes.dimensions(@root).should == ['store'] end it "should not create a dimension on a node if it exists" do @tree.nodes.add_dimension(@root, 'store').should == 'store' @tree.nodes.add_dimension(@root, 'store').should == 'store' @tree.nodes.dimensions(@root).should == ['store'] end it "should not find children" do @tree.nodes.add_dimension(@root, 'store') @tree.nodes.children(@root, 'store').should == [] end it "should create and find children" do @tree.nodes.add_dimension(@root, 'store') @tree.nodes.add_child(@root, 'store', 'S1').should == 2 @tree.nodes.add_child(@root, 'store', 'S2').should == 3 @tree.nodes.children(@root, 'store').should == ['S1', 'S2'] @tree.nodes.child(@root, 'store', 'S1').should == '2' @tree.nodes.child(@root, 'store', 'S2').should == '3' end it "should not create a new child if one exists" do @tree.nodes.add_dimension(@root, 'store') @tree.nodes.add_child(@root, 'store', 'S1').should == 2 @tree.nodes.add_child(@root, 'store', 'S1').should == '2' @tree.nodes.children(@root, 'store').should == ['S1'] @tree.nodes.child(@root, 'store', 'S1').should == '2' end it "should not find any measures" do @tree.nodes.measures(@root).should == [] end it "should create and find measures" do @tree.nodes.add_measure(@root, 'event[count]', 2).should == 2 @tree.nodes.measures(@root).should == ['event[count]'] @tree.nodes.measure(@root, 'event[count]').to_i.should == 2 end it "should not createa a measure if it exists" do @tree.nodes.add_measure(@root, 'event[count]', 2).should == 2 @tree.nodes.add_measure(@root, 'event[count]', 3).should == 2.0 @tree.nodes.measures(@root).should == ['event[count]'] @tree.nodes.measure(@root, 'event[count]').to_i.should == 2 end it "should store float measures" do @tree.nodes.add_measure(@root, 'event[count]', 4.5).should == 4.5 end end
require_relative '../lib/cli.rb' require 'colorize' RSpec.describe Cli do xdescribe '#call_api' do let(:test) {Cli.new} it 'it expects a string ' do string = "New York" result = test.call_api(string) expect(result).to be true end end xdescribe '#convert_data' do let(:test) {Cli.new} hash = {"coord"=> {"lon"=>-73.99, "lat"=>40.73}, "weather"=> [{"id"=>800, "main"=>"Clear", "description"=> "clear sky", "icon"=>"01d"}], "base"=>"stations", "main"=> {"temp"=>281.62, "pressure"=>1023, "humidity"=>39, "temp_min"=>279.82, "temp_max"=>283.15}, "visibility"=>16093, "wind"=> {"speed"=>3.6, "deg"=>300}, "clouds"=>{"all"=>1}, "dt"=>1573835897, "sys"=> {"type"=>1, "id"=>4686, "country"=>"US", "sunrise"=> 1573818159, "sunset"=> 1573853918}, "timezone"=>-18000, "id"=>5128581, "name"=>"New York", "cod"=>200} it 'takes 1 argument' do expect{convert_data(hash)} end end xdescribe '#convert_data' do it 'it should output temperature as a string' do hash = {"coord"=> {"lon"=>-73.99, "lat"=>40.73}, "weather"=> [{"id"=>800, "main"=>"Clear", "description"=> "clear sky", "icon"=>"01d"}], "base"=>"stations", "main"=> {"temp"=>281.62, "pressure"=>1023, "humidity"=>39, "temp_min"=>279.82, "temp_max"=>283.15}, "visibility"=>16093, "wind"=> {"speed"=>3.6, "deg"=>300}, "clouds"=>{"all"=>1}, "dt"=>1573835897, "sys"=> {"type"=>1, "id"=>4686, "country"=>"US", "sunrise"=> 1573818159, "sunset"=> 1573853918}, "timezone"=>-18000, "id"=>5128581, "name"=>"New York", "cod"=>200} expect{convert_data(hash)}.to output("Temperature: 47.2 °F").to_stdout end end end
class Customer < ApplicationRecord validates :first_name, presence: true validates :email, uniqueness: { scope: :customer_id, message: "should be unique per customer" } validates :phone, uniqueness: { scope: :customer_id, message: "should be unique per customer" } class << self def import_data(csv_text) require 'csv' csv = CSV.parse(csv_text, :headers => true) if csv.headers.all? { |each| ["Customer_Id", "First_Name", "Last_Name", "Email_Address", "Phone"].include?(each) } invalid_customers_count = 0 csv.each do |row| row = row.to_hash customer = Customer.new( customer_id: row['Customer_Id'], first_name: row['First_Name'], last_name: row['Last_Name'], email: row['Email_Address'], phone: row['Phone']) if !customer.save invalid_customers_count += 1 end end ActionCable.server.broadcast "customer_room_channel", { response: '200', invalid_customers_count: invalid_customers_count, customers: Customer.all.to_json } else ActionCable.server.broadcast "customer_room_channel", {response: '500', error: 'Invalid Headers found'} end end end end
require 'rails_helper' RSpec.describe 'Challenges', type: :request do # Initialise sample data let!(:challenges) { create_list(:challenge, 10) } let(:challenge_id) { challenges.first.id } # Tests for :index describe 'index request' do before { get '/challenges' } it 'returns JSON' do expect(json).not_to be_empty expect(json.size).to eq(10) end it 'returns status code 200' do expect(response).to have_http_status(200) end context 'each entry' do it 'has a name field' do expect(json[0]['name']).not_to be_empty end it 'has the right name' do expect(json[0]['name']).to eq(challenges.find { |c| c.id == json[0]['id'] }.name) end it "doesn't have a html field" do # Avoid sending unnecessary information for the index expect(json[0]).not_to have_key('html') end end end # Tests for :show describe 'show request' do before { get "/challenges/#{challenge_id}" } context 'when the record exists' do it 'returns the challenge' do expect(json).not_to be_empty expect(json['id']).to eq(challenge_id) end it 'returns status code 200' do expect(response).to have_http_status(200) end end context 'when the record does not exist' do let(:challenge_id) { 100 } it 'returns status code 404' do expect(response).to have_http_status(404) end end end end
#!/usr/bin/env ruby # encoding: UTF-8 require 'sinatra' require 'json' require 'sqlite3' require 'yaml' require "active_record" require File.join(File.expand_path(File.dirname(__FILE__)), "lib", 'configured_connection') require File.join(File.expand_path(File.dirname(__FILE__)), "lib", 'stat_data') require File.join(File.expand_path(File.dirname(__FILE__)), "lib", 'query') get '/flagged*' do db = SQLite3::Database.new "#{ENV['HOME']}/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2" data = db.execute( "select name from Task where effectiveFlagged = 1 and dateCompleted is null;" ).flatten erb :table, :locals => {:title => "OmniFocus Flagged Tasks", :rows => data} end get '/graph*' do content_type :json max_value = StatData.find_max_value return { "graph" => { :title => "OmniFocus Tasks", :type => "line", :total => false, :yAxis => { :minValue => 0, :maxValue => (max_value + 10 - (max_value % 10)) }, :datasequences => Query.find_by_data_type("line") } }.to_json end
require "helpers/test_helper" class UnitTestMonitoringCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Monitoring.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # TimeSeries API has no 'get' method @common_method_exceptions = [Fog::Google::Monitoring::TimeseriesCollection] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class).to_a @collections = descendants.select { |d| d.name.match(/Fog::Google::Monitoring/) } end def teardown Fog.unmock! end # This tests whether Fog::Compute::Google collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new if obj.respond_to?(:get) assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end end
class AddPaymentHistoryBalanceCol < ActiveRecord::Migration def up add_column :payment_histories, :balance, :decimal , :default => 0.0 end def down remove_column :payment_histories, :balance end end
class ListProduct < ApplicationRecord belongs_to :list belongs_to :product enum status: { added: 1, removed: 2, purchased: 3 } validates :quantity, numericality: { only_integer: true } end
class SearchGeininByIndexService def initialize(index_param) @index = index_param end def execute case @index when 'a' then @indexes = "あ%","い%","う%","え%","お%" when 'ka' then @indexes = "か%","き%","く%","け%","こ%","が%","ぎ%","ぐ%","げ%","ご%" when 'sa' then @indexes = "さ%","し%","す%","せ%","そ%","ざ%","じ%","ず%","ぜ%","ぞ%" when 'ta' then @indexes = "た%","ち%","つ%","て%","と%","だ%","ぢ%","づ%","で%","ど%" when 'na' then @indexes = "な%","に%","ぬ%","ね%","の%" when 'ha' then @indexes = "は%","ひ%","ふ%","へ%","ほ%","ば%","び%","ぶ%","べ%","ぼ%","ぱ%","ぴ%","ぷ%","ぺ%","ぽ%" when 'ma' then @indexes = "ま%","み%","む%","め%","も%" when 'ya' then @indexes = "や%","ゆ%","よ%","","" when 'ra' then @indexes = "ら%","り%","る%","れ%","ろ%" when 'wa' then @indexes = "わ%","を%","ん%","","" end @geinins_list = [] @indexes.each do |index| geinins = Geinin.index_search(index) @geinins_list << geinins end return @geinins_list, @indexes end end
class Live::EventGroupsController < Live::BaseController before_action :set_event_group def live_entry authorize @event_group @presenter = EventGroupPresenter.new(@event_group, params, current_user) verify_available_live(@event_group) render :new_live_entry end private def set_event_group @event_group = EventGroup.friendly.find(params[:id]) end end
require 'spec_helper' module MWS describe XML do describe '.to_hash' do subject do str = <<-XML.gsub!(/>\s+</, '><').strip! <?xml version=\"1.0\" ?> <ItemAttributes> <Title>Anti-Oedipus</Title> <Author>Gilles Deleuze</Author> <Author>Felix Guattari</Author> <Creator Role="Translator">Robert Hurley</Creator> </ItemAttributes> XML xml = Nokogiri::XML.parse str XML.to_hash xml end it 'returns a hash' do should be_an_instance_of Hash end it 'handles single children' do subject['Title'].should eq 'Anti-Oedipus' end it 'handles arrays' do subject['Author'].should be_a Array end it 'handles attributes' do node = subject['Creator'] node['Role'].should eq 'Translator' node['__content__'].should eq 'Robert Hurley' end end end end
# require 'minitest' # require 'minitest/autorun' # require 'chawk' require 'test_helper' ts1 = [ ['A', 100], ['B', 99], ['C', 95], ['D', 50], ['E', 45], ['F', 30], ['G', 29], ['H', 28]] ts2 = [ ['A', 100], ['B', 85], ['C', 80], ['D', 71], ['E', 70], ['F', 30], ['G', 29], ['H', 28]] # Temporary harness for quantization testing class Qharness include Chawk::Quantizer attr_accessor :datum def initialize @datum = datum end end describe Chawk::Quantizer do before do @qh = Qharness.new end it 'does quantize' do @qh.must_respond_to 'quantize' @qh.quantize(ts1, 10).must_equal( [ ['A', 100], ['C', 90], ['C', 80], ['C', 70], ['C', 60], ['E', 50], ['E', 40], ['H', 30], ['H', 20]] ) @qh.quantize(ts2, 10).must_equal( [ ['A', 100], ['B', 90], ['D', 80], ['E', 70], ['E', 60], ['E', 50], ['E', 40], ['H', 30], ['H', 20]] ) @qh.quantize(ts2, 5).must_equal( [ ['A', 100], ['A', 95], ['A', 90], ['B', 85], ['C', 80], ['D', 75], ['E', 70], ['E', 65], ['E', 60], ['E', 55], ['E', 50], ['E', 45], ['E', 40], ['E', 35], ['H', 30], ['H', 25]]) end it 'picks first step' do @qh.starting_step(101, 10).must_equal(110) @qh.starting_step(111, 10).must_equal(120) @qh.starting_step(100, 10).must_equal(100) @qh.starting_step(99, 10).must_equal(100) @qh.starting_step(92, 10).must_equal(100) @qh.starting_step(91, 10).must_equal(100) @qh.starting_step(90, 10).must_equal(90) @qh.starting_step(1, 10).must_equal(10) @qh.starting_step(3, 10).must_equal(10) @qh.starting_step(7, 10).must_equal(10) @qh.starting_step(10, 10).must_equal(10) @qh.starting_step(101, 5).must_equal(105) @qh.starting_step(102, 5).must_equal(105) @qh.starting_step(105, 5).must_equal(105) @qh.starting_step(107, 5).must_equal(110) end it 'picks last step' do @qh.ending_step(101, 10).must_equal(100) @qh.ending_step(111, 10).must_equal(110) @qh.ending_step(100, 10).must_equal(100) @qh.ending_step(101, 5).must_equal(100) @qh.ending_step(106, 5).must_equal(105) @qh.ending_step(100, 5).must_equal(100) end end
#=============================================================================== # * Game_Projectile #------------------------------------------------------------------------------- # Projectiles in the game, game cannot be saved if any projectile exist #=============================================================================== class Game_Projectile < Game_Character #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :user, :target attr_reader :item attr_reader :sprite attr_reader :action #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize(action, move_formula = nil) super() @user = action.user @target = action.target ? action.target : POS.new(user.x, user.y) #puts "Projectile target address: #{target.x} #{target.y}" @moved_dis = 0 @item = action.item @max_range = item.tool_distance @move_speed = item.tool_speed @through = item.tool_through @priority_type = item.tool_priority @tool_type = item.tool_type @executed = false @action = action @move_formula = move_formula @substitute = nil @enemies = BattleManager.opponent_battler(@action.user, true) moveto([@user.x, 0].max, [@user.y, 0].max) restore activate self end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update update_movement @sprite.update super end #-------------------------------------------------------------------------- # * Movement process #-------------------------------------------------------------------------- def update_movement return if SceneManager.time_stopped? execute_action if !process_projectile_move @sprite.execute_collide if collision_ready? end #-------------------------------------------------------------------------- def collision_ready? if @moved_dis >= @max_range pos = POS.new(@x, @y) @action.target = pos return true end return true if (@x - target.x).abs < 0.2 && (@y - target.y).abs < 0.2 return true if !@target.is_a?(POS) && self.adjacent?(target.x, target.y) return false end #-------------------------------------------------------------------------- def process_projectile_move return false if @executed return wall_rammed if obstacle_touched? return process_move_formula if @move_formula pixelstep = Pixel_Core::Pixel len = [Math.hypot(@x - target.x, @y - target.y), 0.1].max dx = (target.x - @x).to_f / len dy = (target.y - @y).to_f / len delta_x = distance_per_frame * dx * pixelstep / 2 delta_y = distance_per_frame * dy * pixelstep / 2 @x = $game_map.round_x(@x + delta_x) @y = $game_map.round_y(@y + delta_y) @real_x = @x - delta_x @real_y = @y - delta_y @moved_dis += Math.hypot(delta_x, delta_y) @direction = (delta_x.abs > delta_y.abs) ? (delta_x > 0 ? 6 : 4) : (delta_y > 0 ? 2 : 8) return !(delta_x == 0 && delta_y == 0) end #-------------------------------------------------------------------------- def process_move_formula # tag: formula # link to module PONY::Formula end #-------------------------------------------------------------------------- # * Execute Action #-------------------------------------------------------------------------- def execute_action return if @executed @executed = true BattleManager.execute_action(@action) end #-------------------------------------------------------------------------- # * Restore bitmap #-------------------------------------------------------------------------- def restore dispose_sprite @sprite = Sprite_Projectile.new(SceneManager.viewport1, self) end #-------------------------------------------------------------------------- def dispose_sprite return unless @sprite @sprite.dispose unless @sprite.disposed? @sprite = nil end #-------------------------------------------------------------------------- def obstacle_touched? dir = @direction nx = @x * 4 + Pixel_Core::Tile_Range[dir][0] ny = @y * 4 + Pixel_Core::Tile_Range[dir][1] return true if !$game_map.pixel_valid?(nx,ny) || $game_map.over_edge?(@x, @y) return false if @through return true if $game_map.pixel_table[nx,ny,1] == 0 return true if check_substitute return false end #-------------------------------------------------------------------------- def check_substitute @enemies.each do |enemy| if adjacent?(enemy.x, enemy.y) @substitute = enemy return true end end return false end #-------------------------------------------------------------------------- def wall_rammed @action.target = @substitute ? @substitute : POS.new(@x, @y) @sprite.execute_collide execute_action end #-------------------------------------------------------------------------- def update_quadtree_index end #-------------------------------------------------------------------------- def character_name; return item.tool_graphic; end def animation_id; return item.animation_id; end def update_realtime_action; end def dead?; return true; end def relocate; @sprite.relocate; end #--------------------------------------------------------- end
require 'test_helper' class CmasControllerTest < ActionController::TestCase setup do @cma = cmas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:cmas) end test "should get new" do get :new assert_response :success end test "should create cma" do assert_difference('Cma.count') do post :create, cma: { name: @cma.name } end assert_redirected_to cma_path(assigns(:cma)) end test "should show cma" do get :show, id: @cma assert_response :success end test "should get edit" do get :edit, id: @cma assert_response :success end test "should update cma" do patch :update, id: @cma, cma: { name: @cma.name } assert_redirected_to cma_path(assigns(:cma)) end test "should destroy cma" do assert_difference('Cma.count', -1) do delete :destroy, id: @cma end assert_redirected_to cmas_path end end
class CreateNovels < ActiveRecord::Migration[5.0] def change create_table :novels do |t| t.text :sentence # 外部キー制約 t.references :user, foreign_key: true t.string :title t.timestamps end end end
# frozen_string_literal: true require 'rake' require './rake_extensions.rb' EXE_NAME = 'enforcer' HOME = ENV['HOME'] task :default do puts 'no default task' create_changelog end desc 'Check' task :check do sh 'cargo +nightly fmt -- --color=always --check' sh 'cargo clippy' sh 'cargo test' end desc 'run tests' task :test do sh 'cargo test' end desc 'format code with cargo nightly' task :fmt do sh 'cargo +nightly fmt' end desc 'run tests with printing to stdout' task :test_nocapture do sh 'cargo test -- --nocapture' end def build_the_release sh 'cargo build --release' current_version = get_current_version release_folder = 'target/release' os_ext = 'darwin' if OS.linux? os_ext = 'linux' elsif OS.windows? os_ext = 'windows' release_folder = 'target/x86_64-pc-windows-gnu/release' end cd release_folder.to_s do cp EXE_NAME.to_s, "#{HOME}/bin/#{EXE_NAME}" sh "tar -cvzf #{EXE_NAME}@#{current_version}-#{os_ext}.tgz #{EXE_NAME}" end end def build_the_release_windows sh 'cargo build --release --target=x86_64-pc-windows-gnu' current_version = get_current_version release_folder = 'target/x86_64-pc-windows-gnu/release' tgz_file = "#{EXE_NAME}@#{current_version}-win64.tgz" cd release_folder.to_s do sh "tar -cvzf #{tgz_file} #{EXE_NAME}.exe" end mv "#{release_folder}/#{tgz_file}", 'target/release' end def build_the_release_windows32 sh 'cargo build --release --target=i686-pc-windows-gnu' current_version = get_current_version release_folder = 'target/i686-pc-windows-gnu/release' tgz_file = "#{EXE_NAME}@#{current_version}-win32.tgz" cd release_folder.to_s do sh "tar -cvzf #{tgz_file} #{EXE_NAME}.exe" end mv "#{release_folder}/#{tgz_file}", 'target/release' end desc 'build release, no version bump' task :build_release do build_the_release if OS.linux? build_the_release_windows build_the_release_windows32 end end desc 'build release' task :build do sh 'cargo build --release' pack_release end desc 'create new version and release' task :create_release do current_tag = `git describe --tags` versioner = Versioner.for(:cargo_toml, '.') current_version = versioner.get_current_version unless current_tag.start_with?(current_version) raise "current tag #{current_tag} does not match current version: #{current_version}" end do_create_release(versioner) end def do_create_release(versioner) require 'highline' cli = HighLine.new cli.choose do |menu| default = :minor menu.prompt = "this will create and tag a new version (default: #{default}) " menu.choice(:minor) do create_and_tag_new_version(versioner, :minor) end menu.choice(:major) do create_and_tag_new_version(versioner, :major) end menu.choice(:patch) do create_and_tag_new_version(versioner, :patch) end menu.choice(:abort) { cli.say('ok...maybe later') } menu.default = default end end def create_and_tag_new_version(versioner, jump) current_version = versioner.get_current_version next_version = versioner.get_next_version(jump) assert_tag_exists(current_version) create_changelog(current_version, next_version) versioner.increment_version(jump) sh 'git add .' commit_cmd = "git commit -m \"Bump version from #{current_version} => #{next_version}\"" tag_cmd = "git tag #{next_version}" puts "to commit, you can use ====> git add .; #{commit_cmd}" puts "to tag, use ===============> \"#{tag_cmd}\"" end def pack_release require 'zip' exe_file = if OS.windows? "#{EXE_NAME}.exe" else EXE_NAME end exe_path = "target/release/#{exe_file}" zipfile_name = if OS.windows? "#{EXE_NAME}_win.zip" elsif OS.mac? "#{EXE_NAME}_mac.zip" else "#{EXE_NAME}_linux.zip" end rm_f zipfile_name Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| zipfile.add(exe_file, exe_path) end end
class Setting < ApplicationRecord validates :name, presence: true, uniqueness: true before_save :generate_slug def content saved_content.blank? ? fallback : saved_content end def generate_slug self.slug = name.to_slug.gsub("-", "_") end end
module Guard class Jasmine # The inspector verifies if the changed paths are valid # for Guard::Jasmine. Please note that request to {.clean} # paths keeps the current valid files cached until {.clear} is # called. # module Inspector class << self # Clean the changed paths and return only valid # Jasmine specs in either JavaScript or CoffeeScript. # # @param [Array<String>] paths the changed paths # @param [Hash] options the options for the Guard # @option options [String] :spec_dir the directory with the Jasmine specs # @return [Array<String>] the valid spec files # def clean(paths, options) paths.uniq! paths.compact! if paths.include?(options[:spec_dir]) paths = [options[:spec_dir]] else paths = paths.select { |p| jasmine_spec?(p) } end paths end private # Tests if the file is valid. # # @param [String] file the file # @return [Boolean] when the file valid # def jasmine_spec?(path) path =~ /_spec\.(js|coffee|js\.coffee)$/ && File.exists?(path) end end end end end
#!/usr/bin/env ruby require 'date' USAGE = <<EOS Usage: #{$PROGRAM_NAME} <license-file> <code-file> [output-file] Replaces existing license header, prepends if no license header present, no changes if license up to date. If no output file is provided, the code file will be overwritten. EOS # The license recognition: # A comment at the start of the file, which contains "COPYRIGHT" LICENSE_REGEXP = /\A\s*\/\*.*?COPYRIGHT.*?\*\//mi if(ARGV.length < 2 || ARGV.length > 3) puts(USAGE) exit(false) end license = IO.read(ARGV[0]) # update license year to current license.sub!(/20XX/, Date.today.year.to_s) file = IO.read(ARGV[1]) match = LICENSE_REGEXP.match(file) # check if any existing license if(match) # if up-to-date, exit exit(true) if(match[0].strip == license.strip) # else, delete existing license file.sub!(match[0], ""); end # prepend new license output = license + file.lstrip # write ouptput to code file, or output file if specified outfn = ARGV[ARGV.length - 1] File.open(outfn, "wb+") do |f| f.print(output) end exit(true)
class AddStoreToOrders < ActiveRecord::Migration[6.0] def change add_reference :orders, :store end end
# @param content [String] def normalize_content(content) content.sub /^\!\w+\W/, '' end
class AgendasController < ApplicationController def index @agendas = Agenda.all end def new @agenda = Agenda.new end def create Agenda.create(agenda_params) redirect_to root_path end private def agenda_params params.require(:agenda).permit(:place, :location, :date) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # categories = Category.create([{name: "Computers"}, {name: "Smart Phones"}, # {name: "Televisions"}, {name: "Game Consoles"}, {name: "Video Games"}, # {name: "Appliances"}, {name: "Other"}]) =begin rails console Product.all path to image Melissa@DESKTOP-KRVUT4Q MINGW64 /c/Sites/ecommerce (master) $ rails console Loading development environment (Rails 5.2.3) Switch to inspect mode. Product.all Product.all Product Load (48.5ms) SELECT "products".* FROM "products" LIMIT ? [["LIMIT", 11]] #<ActiveRecord::Relation [#<Product id: 1, name: "wutchamacallit", price: #<BigDecimal:6a53468,'0.1E1',9(27)>, quantity: 1, description: "It's a thingamajig", brand: "whozit", rating: 3, category_id: 1, created_at: "2019-08-03 23:30:17", updated_at: "2019-08-05 15:11:09", image: "blog-da-vinci-journals.jpg">, #<Product id: 2, name: "thingamajib", price: #<BigDecimal:6a52820,'0.1E2',9(27)>, quantity: 2, description: "woot woot", brand: "melissa", rating: 5, category_id: 1, created_at: "2019-08-05 15:09:46", updated_at: "2019-08-05 15:09:46", image: "beetlejuice2.jpg">]> =end
# frozen_string_literal: true require 'rails_helper' RSpec.describe SessionsController, type: :controller do describe 'GET #new' do describe 'when user is logged in' do let(:current_user) { create(:user) } before(:each) do session[:user_id] = current_user.id get :new end it 'returns http redirect status' do expect(response).to have_http_status(:found) end it 'redirects to users#show current_user' do expect(response).to redirect_to user_url(current_user) end it 'has flash notice "You are already Logged In" message' do expect(flash[:notice]).to be_present expect(flash[:notice]).to eq I18n.t(:already_logged_in, username: current_user.username) end end describe 'when user is not logged in' do before(:each) do get :new end it 'returns http success' do expect(response).to have_http_status(:success) end end end end
class ArtworkSharesController < ApplicationController def create viewer = User.find(params[:artwork_share][:viewer_id]) artwork = Artwork.find(params[:artwork_share][:artwork_id]) if viewer && artwork share = ArtworkShare.new(artwork_share_params) end if share.save render json: share else render json: share.errors.full_messages, status: 422 end end def destroy share = ArtworkShare.find(params[:id]) if share share.destroy render json: share else render json: share.errors.full_messages, status: 422 end end private def artwork_share_params params.require(:artwork_share).permit(:viewer_id, :artwork_id) end end
require 'formula' class Tinycdb < Formula homepage 'http://www.corpit.ru/mjt/tinycdb.html' url 'http://www.corpit.ru/mjt/tinycdb/tinycdb-0.78.tar.gz' sha1 'ade42ee1e7c56f66a63cb933206c089b9983adba' def install system "make" system "make", "install", "prefix=#{prefix}", "mandir=#{man}" end end
# This controller handles the login/logout function of the site. class SessionsController < ApplicationController # render new.rhtml def new if Member.count == 0 redirect_to "/signup" end end def create self.current_member = Member.authenticate(params[:username], params[:password]) if logged_in? if params[:remember_me] == "1" self.current_member.remember_me cookies[:auth_token] = { :value => self.current_member.remember_token , :expires => self.current_member.remember_token_expires_at } end redirect_back_or_default "/" flash[:notice] = "Signed in successfully" else flash[:notice] = "Cannot sign in" render :action => :new end end def destroy self.current_member.forget_me if logged_in? cookies.delete :auth_token reset_session flash[:notice] = "You have been signed out." redirect_back_or_default "/" end end
require 'cells_helper' RSpec.describe AdminArea::People::Cell::Balances do let(:person) { Person.new(id: 123, first_name: 'Erik') } include ActionView::Helpers::NumberHelper let(:rendered) { cell(person).() } example 'when the person has no balances' do expect(rendered).not_to have_selector 'h3', text: 'Existing Balances' expect(rendered).to have_content 'User does not have any existing points/miles balances' end context 'when the person has balances' do let(:currencies) { Array.new(2) { |i| Currency.new(name: "Curr #{i}") } } let(:balances) do [ person.balances.build(currency: currencies[0], value: 1234), person.balances.build(currency: currencies[1], value: 4321), ] end before { allow(person).to receive(:balances).and_return(balances) } it 'lists them' do expect(rendered).to have_selector 'h3', text: 'Existing Balances' balances.each do |balance| expect(rendered).to have_content balance.currency.name expect(rendered).to have_content number_with_delimiter(balance.value) end end end end
json.array!(@piece7s) do |piece7| json.extract! piece7, :id, :name, :user_id json.url piece7_url(piece7, format: :json) end
# == Schema Information # # Table name: pins # # id :bigint(8) not null, primary key # motherboard_id :bigint(8) # topic_id :string # created_at :datetime not null # updated_at :datetime not null # class Pin < ApplicationRecord belongs_to :motherboard def as_json(*) topic = Motherboard.find_topic(topic_id) if topic.present? && topic.selection?(motherboard) topic end end end
class Student attr_reader :name, :age, :scores def initialize(student_info) @name = student_info[:name] @age = student_info[:age] @scores = [] end def log_score(score) if score.class == Integer @scores << score else puts "scores must be an integer" end return @scores end def grade @scores.sum.to_f / @scores.length end end
Rails.application.routes.draw do #homes root 'homes#top' get 'homes/about' => "homes#about" #devise devise_for :publics devise_for :admins, controllers: { sessions: 'admins/sessions' } namespace :public do #住所 resources :addresses, only: [:index, :create, :edit, :update, :destroy] #カート内商品 resources :cart_items, only: [:index, :create, :update, :destroy] get "cart_items/destroy_all" => "cart_items#destroy_all", as: :destroy_all #顧客 resource :customer, only: [:show, :edit, :update] get "customers/unsubscribe" => "customers#unsubscribe", as: :unsubscribe delete "customers/withdraw" => "customers#withdraw", as: :withdraw #商品 resources :items, only: [:index, :show] #注文 resources :orders, only: [:new, :create, :index, :show] post "orders/comfirm" => "orders#comfirm", as: :comfirm get "orders/complete" => "orders#complete", as: :complete end namespace :admin do #顧客情報 resources :customers, only: [:index, :show, :edit, :destroy, :update] #ジャンル resources :genres, only: [:index, :create, :edit, :update] #商品 resources :items #注文詳細 resources :order_details, only: [:update] #注文 resources :orders, only: [:index, :show, :update] end end
class PropertyType < ApplicationRecord has_many :properties validates :name, presence: { message: 'não pode ficar em branco' } validates :name, uniqueness: { message: 'tem de ser único' } end
#!/usr/bin/env ruby require File.expand_path(File.join(File.dirname(__FILE__), "spec_common")) require 'bindata/stringz' describe BinData::Stringz, "when empty" do its(:value) { should == "" } its(:num_bytes) { should == 1 } its(:to_binary_s) { should == "\0" } end describe BinData::Stringz, "with value set" do subject { BinData::Stringz.new("abcd") } its(:value) { should == "abcd" } its(:num_bytes) { should == 5 } its(:to_binary_s) { should == "abcd\0" } end describe BinData::Stringz, "when reading" do it "should stop at the first zero byte" do io = StringIO.new("abcd\0xyz\0") subject.read(io) io.pos.should == 5 subject.should == "abcd" end it "should handle a zero length string" do io = StringIO.new("\0abcd") subject.read(io) io.pos.should == 1 subject.should == "" end it "should fail if no zero byte is found" do lambda {subject.read("abcd") }.should raise_error(EOFError) end end describe BinData::Stringz, "when setting the value" do it "should include the zero byte in num_bytes total" do subject.assign("abcd") subject.num_bytes.should == 5 end it "should accept empty strings" do subject.assign("") subject.should == "" end it "should accept strings that aren't zero terminated" do subject.assign("abcd") subject.should == "abcd" end it "should accept strings that are zero terminated" do subject.assign("abcd\0") subject.should == "abcd" end it "should accept up to the first zero byte" do subject.assign("abcd\0xyz\0") subject.should == "abcd" end end describe BinData::Stringz, "with max_length" do subject { BinData::Stringz.new(:max_length => 5) } it "should read less than max_length" do io = StringIO.new("abc\0xyz") subject.read(io) subject.should == "abc" end it "should read exactly max_length" do io = StringIO.new("abcd\0xyz") subject.read(io) subject.should == "abcd" end it "should read no more than max_length" do io = StringIO.new("abcdefg\0xyz") subject.read(io) io.pos.should == 5 subject.should == "abcd" end it "should accept values less than max_length" do subject.assign("abc") subject.should == "abc" end it "should accept values exactly max_length" do subject.assign("abcd") subject.should == "abcd" end it "should trim values greater than max_length" do subject.assign("abcde") subject.should == "abcd" end it "should write values greater than max_length" do subject.assign("abcde") subject.to_binary_s.should == "abcd\0" end it "should write values less than max_length" do subject.assign("abc") subject.to_binary_s.should == "abc\0" end it "should write values exactly max_length" do subject.assign("abcd") subject.to_binary_s.should == "abcd\0" end end
class User < ActiveRecord::Base has_secure_password belongs_to :role #before_create :set_role Roles = [:cliente, :asesor, :admin] def role?(role_name) role = Role.find_by(name: role_name) self.role_id == role.id end end
class AddRoomcodeToGameRooms < ActiveRecord::Migration[6.0] def change add_column :game_rooms, :roomcode, :string end end
class User < ApplicationRecord has_and_belongs_to_many :categories, dependent: :destroy has_many :active_relationships, class_name: Relationship.name, foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: Relationship.name, foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower before_save :downcase_email validates :name, presence: true, length: {maximum: Settings.max_name} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: {maximum: Settings.max_email}, format: {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false} has_secure_password validates :password, presence: true, length: {minimum: Settings.min_password}, allow_nil: true def downcase_email self.email = email.downcase end end
require 'rack-proxy' class ServiceProxy < Rack::Proxy def initialize(app) @app = app end def call(env) original_host = env["HTTP_HOST"] rewrite_env(env) if env["HTTP_HOST"] != original_host status, headers, response = perform_request(env) headers.delete "transfer-encoding" [status, headers, response] else @app.call(env) # just regular end end def rewrite_env(env) request = Rack::Request.new(env) if request.path =~ %r{^/api/} service = request.path.split('/')[2] env["HTTP_HOST"] = "#{service}-service.#{Rails.env}.dbg.westfield.com" env['SERVER_PORT'] = '80' end env end end
Gem::Specification.new do |s| s.name = 'rsence' s.authors = [ 'Riassence Inc.', 'Juha-Jarmo Heinonen' ] s.email = 'info@rsence.org' s.version = File.read('VERSION') s.date = Time.now s.homepage = 'http://www.rsence.org/' s.rubyforge_project = 'rsence-' s.license = 'MIT' prerelease = s.version.to_s.end_with?('.pre') s.name = 'rsence-pre' if prerelease normalized_version = s.version.to_s.to_f # release .pre -versions a separate rsence-pre gem since 2.1 if normalized_version >= 2.1 and prerelease s.version = s.version.to_s[0..-5] end s.summary = "#{'Pre-' if prerelease}Release #{normalized_version} version of RSence." # deprecated in rubygems 1.8: # s.has_rdoc = 'yard' s.description = File.read('README.rdoc').split('== Introduction')[1].split('== Installing RSence')[0].strip s.add_dependency( "rsence-deps", "971" ) require 'rake' s.files = FileList[ 'lib/**/*', 'setup/welcome/**/*', 'conf/default_conf.yaml', 'conf/default_strings.yaml', 'conf/rsence_command_strings.yaml', 'plugins/client_pkg/**/*', 'plugins/index_html/**/*', 'plugins/main/**/*', 'plugins/ticket/**/*', 'client/**/*', 'README.rdoc', 'INSTALL.rdoc', 'AUTHORS.txt', 'MIT-LICENSE.txt', 'docs/*.rdoc', 'VERSION' ].to_a s.files.reject! { |fn| fn.start_with? "." } s.files.reject! { |fn| fn.end_with? ".rbc" } s.files.push '.yardopts' if prerelease s.files.push 'bin/rsence-pre' s.executables = [ 'rsence-pre' ] # deprecated in rubygems 1.8: # s.default_executable = 'rsence-pre' else s.executables = [ 'rsence' ] # deprecated in rubygems 1.8: # s.default_executable = 'rsence' end s.required_ruby_version = '>= 1.8.7' end
class MailerWorker include Sidekiq::Worker def perform(email) UserMailer.send_report_card(email).deliver_now end end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe LogParser do subject { described_class.new(file) } let(:file) { File.read("./spec/fixtures/webserver.log") } it "takes a file" do expect { described_class.new }.to raise_error(ArgumentError) end it "stores a file" do expect(subject.file).to eql(file) end describe "#parse" do it "returns an array of results" do subject.parse expect(subject.results).to be_an(Array) end it "counts the number of entries" do subject.parse expect(subject.results).to include({url: '/home', total: 78}) end end end
class Splam::Rules::Bbcode < Splam::Rule def run add_score 10 * @body.scan("showpost.php?p=").size, "Linking to a shitty forum" # add_score 10 * @body.scan("\r\n").size, "Poorly formed POST (\\r\\n)" add_score 80 * @body.scan(/\n\[url.*?\]\n/).size, "Shitty bbcode url covers entire line" add_score 40 * @body.scan("[url=").size, "URL" # no URLS for you!! add_score 40 * @body.scan("[IMG").size, "IMG" add_score 40 * @body.scan("[URL=").size, "URL" # no URLS for you!! add_score 40 * @body.scan("[IMG").size, "IMG" add_score 45 * @body.scan("[url=http").size, "Shitty URL/html" # another 10 points for shitty bbcode html add_score 45 * @body.scan("[URL=http").size, "Shitty URL/html" # another 10 points for shitty bbcode html add_score 30 * @body.scan("[/CODE").size, "Forum codes?" add_score 10 * @body.scan(/\[[bai]/).size, "b/a/i tag" end end
class Api::MembershipsController < ApplicationController def index @memberships = Membership.all render :index end def create @membership = Membership.new(membership_params) if @membership.save render :show else end end private def membership_params params.require(:membership).permit(:user_id, :channel_id) end end
class AddCustomerIdToAppointments < ActiveRecord::Migration def change add_column :appointments, :customer_id, :integer add_index :appointments, :customer_id end end
require_relative './pack' module Schema class OrderItem < Base attribute :quantity, Integer attribute :currency, String, default: "$" attribute :pack_id, String attribute :pack, Pack attribute :amount, Decimal, default: 0.00 end end
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module Foundation module Panes # # Represents a proxy to a SproutCore main pane (SC.MainPane) # class MainPane < Lebowski::Foundation::Panes::Pane representing_sc_class 'SC.MainPane' end end end end
module Thing::Cell class Index < Trailblazer::Cell include ActionView::RecordIdentifier private def new_thing_link link_to 'New thing', new_thing_path end end end
require 'open-uri' # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Category.destroy_all Appreciation.destroy_all Comment.destroy_all Project.destroy_all User.destroy_all # ------Users Seed Data------ # vvvvvvvvvvvvvvvvvvvvvvvvvvv user1 = User.create( email: "ujpyon@gmail.com", password: "go_project_go", fname:"UnJae", lname: "Pyon", text: "Content creator extraordinaire! I am a graduate of Pratt Institute School of Architecture, but now I'm currently attending App Academy and I draw in my free time as a hobby. Take a look at my awesome projects!" ) user2 = User.create( email: "soloak@gmail.com", password: "go_extras_go", fname:"Sol", lname: "Oak", text: "My name is Sol Oak, and I'm a Pratt Institute graduate of Industrial Design." ) user3 = User.create( email: "spence@gmail.com", password: "go_extras_go", fname:"Spencer", lname: "Cambridge", text: "I make cool projects! BIZZZAM, take a look!" ) user4 = User.create( email: "ash@gmail.com", password: "go_extras_go", fname:"Ash", lname: "C. Yeung", text: "Graduate of Pratt Institute School of Architecture. Find me on LinkedIn for more info." ) user5 = User.create( email: "hmoon@gmail.com", password: "go_extras_go", fname:"Hailey", lname: "Moon", text: "I'm a chill girl, making chill things." ) user6 = User.create( email: "pko@gmail.com", password: "go_extras_go", fname:"Peter", lname: "Koo", text: "I'm a cool guy, doing cool things." ) user7 = User.create( email: "honee@gmail.com", password: "go_extras_go", fname:"Honee", lname: "Lemon", text: "I'm a designer/illustrator based in New York. I love creating works of art that inspire new ideas from something completely ordinary or presenting lesser known, field-specific subject matters that evoke curiosity." ) demo_user = User.create( email: "demo_user@gmail.com", password: "123456", fname:"Harry", lname: "Potter", text: "Thanks for logging in as a demo user! Feel free to check out my LinkedIn & Github links below!" ) test_user = User.create( email: "cube@aps", password: "123456", fname:"APERTURE SCIENCE", lname: "WEIGHTED COMPANION CUBE", text: "Property of Aperture Science - GLaDOS. DiD yOU fInD ThE cAKE?" ) # -----Project Seed Data----- # vvvvvvvvvvvvvvvvvvvvvvvvvvv ## --USER 1 PROJECTS-- proj_1 = Project.create( title: "Life Moments in Illustrations: Part 1", description: "I created a series of illustrations based on moments in my life I've shared experienced together with my wife. Hope you enjoy!", artist_id: user1.id ) proj_2 = Project.create( title: "Life is an RPG", description: "This is a set of characters I drew for my D&D group depicting each of us as our characters.", artist_id: user1.id ) proj_3 = Project.create( title: "Life Moments in Illustrations: Part 2", description: "This is part 2 of a series of illustrations I did for my wife involving moments we've shared together!", artist_id: user1.id ) proj_4 = Project.create( title: "Illustrations: People of ODA", description: "This is an illustrations project I started through sketching classmates. Thought I would share it with y'all!", artist_id: user1.id ) proj_5 = Project.create( title: "Misc. Drawings", description: "Haven't posted anything in awhile, so I decided to put up some doodles I've been working on.", artist_id: user1.id ) proj_6 = Project.create( title: "Arch 101: Spatial Study", description: "This was my design project for freshman year of design at Pratt Institute. The final project was to design a space using interconnecting pieces ", artist_id: user1.id ) proj_7 = Project.create( title: "Arch 301: Dormitory Project", description: "My design for the dormitory project: this involved a lot of milling and spatial studies, but in the end the facade came out pretty interesting!", artist_id: user1.id ) proj_8 = Project.create( title: "Drafting 101: Hand Drawings", description: "This was done freshman year of architecture for hand-drafting drawings. The construction line creation was intense :O", artist_id: user1.id ) proj_9 = Project.create( title: "Arch 302: Columbia Boathouse", description: "My proposal for redesigning the boathouse used by Columbia University for Arch 302 class. The proposal involved shaping the boathouse to have maximum access to the docks while providing amenities above.", artist_id: user1.id ) proj_10 = Project.create( title: "The Enchiridion", description: "Portable wood box design for the Enchiridion from Adventure Time. Modeled in Rhino 3D and lasercut.", artist_id: user1.id ) ## --USER 2 PROJECTS-- proj_11 = Project.create( title: "Summer Sketches", description: "Here's a few illustrations I did for some friends this summer! I really like working with different colors for these.", artist_id: user2.id ) proj_12 = Project.create( title: "First Aid Kit Design", description: "This was a project for my Industrial Design class where we were given a product to design a container for.", artist_id: user2.id ) proj_13 = Project.create( title: "Furniture Design: Table & Chair", description: "This was my design proposal for a table/chair set for cafes, which allows a customer to have a personal space under the chair to store their belongings and a hook on the back for coats.", artist_id: user2.id ) proj_14 = Project.create( title: "Tableware Design Set", description: "Designed with ergonomics in mind, the curvature of the tableware design allows for easy handling while also presenting an elegant look.", artist_id: user2.id ) proj_15 = Project.create( title: "Industrial Design Sketches", description: "I had nowhere else to place these old drawings from class, so decided to post them here for you guys to look at :)", artist_id: user2.id ) # --USER 3 PROJECTS-- proj_16 = Project.create( title: "Eaglebrook Middle School Design", description: "These were some of my renders from my proposal for redesigning the Eaglebrook School for Architecture 402 class.", artist_id: user3.id ) # --USER 4 PROJECTS-- proj_17 = Project.create( title: "Skyscraper Project", description: "Skyscraper design for my architecture senior year thesis project.", artist_id: user4.id ) proj_18 = Project.create( title: "Floating Houses", description: "Proposal for floating neighborhood that is better equipped to deal with its location in a flood zone.", artist_id: user4.id ) # --USER 7 PROJECTS-- proj_19 = Project.create( title: "My Baby Loves Christmas", description: "This was another children's book I helped put together. It's a very cute one about Christmas, hope you guys like!", artist_id: user7.id ) proj_20 = Project.create( title: "Summer Vacation: Children's Book", description: "This is a children's book I helped work on about the first day of summer vacation for children, and it was a joy to work on!", artist_id: user7.id ) proj_21 = Project.create( title: "The Arctic Fox's Journey", description: "Cover design was done by me! This was a book I helped work on about the arctic fox, and wanted to share because I love animals!", artist_id: user7.id ) # ------Categories Seed Data------ # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ## --All Categories-- cat_1 = Category.create( name: "Illustration", description: "View illustration work in its many forms, including everything from sketches to digital art and more", tag: "Il" ) cat_2 = Category.create( name: "Architecture", description: "From school projects to simple drafting exercises, browse the latest in student-submitted architectural designs", tag: "Ar" ) cat_3 = Category.create( name: "Industrial Design", description: "Browse brilliant student creations, products, and ideas for the field of industrial design", tag: "ID" ) ## --Add Projects to Categories-- cat_1.projects += [proj_1, proj_2, proj_3, proj_4, proj_5, proj_11, proj_19, proj_20, proj_21] cat_2.projects += [proj_6, proj_7, proj_8, proj_9, proj_16, proj_17, proj_18] cat_3.projects += [proj_10, proj_12, proj_13, proj_14, proj_15] # ------Image File URL Seed Data------ # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ## --User Avatars-- user1_avatar = open('https://behold-seeds.s3.amazonaws.com/user1_avatar.png') user2_avatar = open('https://behold-seeds.s3.amazonaws.com/user2_avatar.png') user7_avatar = open('https://behold-seeds.s3.amazonaws.com/user7_avatar.png') default_avatar = open('https://behold-seeds.s3.amazonaws.com/default_avatar.png') ## --User Banners-- user1_banner = open('https://behold-seeds.s3.amazonaws.com/user1_banner.jpg') user2_banner = open('https://behold-seeds.s3.amazonaws.com/user2_banner.jpg') user7_banner = open('https://behold-seeds.s3.amazonaws.com/user7_banner.jpg') ##--Project Images-- ### -USER 1 PROJECT IMAGES- file1_1 = open('https://behold-seeds.s3.amazonaws.com/1_01_01s.jpg') file1_2 = open('https://behold-seeds.s3.amazonaws.com/1_01_02s.jpg') file1_3 = open('https://behold-seeds.s3.amazonaws.com/1_01_03s.jpg') file1_4 = open('https://behold-seeds.s3.amazonaws.com/1_01_04s.jpg') file1_5 = open('https://behold-seeds.s3.amazonaws.com/1_01_05s.jpg') file2_1 = open('https://behold-seeds.s3.amazonaws.com/1_02_01s.jpg') file2_2 = open('https://behold-seeds.s3.amazonaws.com/1_02_02s.jpg') file2_3 = open('https://behold-seeds.s3.amazonaws.com/1_02_03s.jpg') file2_4 = open('https://behold-seeds.s3.amazonaws.com/1_02_04s.jpg') file2_5 = open('https://behold-seeds.s3.amazonaws.com/1_02_05s.jpg') file2_6 = open('https://behold-seeds.s3.amazonaws.com/1_02_06s.jpg') file3_1 = open('https://behold-seeds.s3.amazonaws.com/1_03_01s.jpg') file3_2 = open('https://behold-seeds.s3.amazonaws.com/1_03_02s.jpg') file3_3 = open('https://behold-seeds.s3.amazonaws.com/1_03_03s.jpg') file3_4 = open('https://behold-seeds.s3.amazonaws.com/1_03_04s.jpg') file4_1 = open('https://behold-seeds.s3.amazonaws.com/1_04_01s.jpg') file4_2 = open('https://behold-seeds.s3.amazonaws.com/1_04_02s.jpg') file4_3 = open('https://behold-seeds.s3.amazonaws.com/1_04_03s.jpg') file4_4 = open('https://behold-seeds.s3.amazonaws.com/1_04_04s.jpg') file4_5 = open('https://behold-seeds.s3.amazonaws.com/1_04_05s.jpg') file5_1 = open('https://behold-seeds.s3.amazonaws.com/1_05_01s.jpg') file5_2 = open('https://behold-seeds.s3.amazonaws.com/1_05_02s.jpg') file5_3 = open('https://behold-seeds.s3.amazonaws.com/1_05_03s.jpg') file6_1 = open('https://behold-seeds.s3.amazonaws.com/1_06_01s.jpg') file6_2 = open('https://behold-seeds.s3.amazonaws.com/1_06_02s.jpg') file6_3 = open('https://behold-seeds.s3.amazonaws.com/1_06_03s.jpg') file7_1 = open('https://behold-seeds.s3.amazonaws.com/1_07_01s.jpg') file7_2 = open('https://behold-seeds.s3.amazonaws.com/1_07_02s.jpg') file7_3 = open('https://behold-seeds.s3.amazonaws.com/1_07_03s.jpg') file8_1 = open('https://behold-seeds.s3.amazonaws.com/1_08_01s.jpg') file8_2 = open('https://behold-seeds.s3.amazonaws.com/1_08_02s.jpg') file8_3 = open('https://behold-seeds.s3.amazonaws.com/1_08_03s.jpg') file8_4 = open('https://behold-seeds.s3.amazonaws.com/1_08_04s.jpg') file9_1 = open('https://behold-seeds.s3.amazonaws.com/1_09_01s.jpg') file9_2 = open('https://behold-seeds.s3.amazonaws.com/1_09_02s.jpg') file9_3 = open('https://behold-seeds.s3.amazonaws.com/1_09_03s.jpg') file9_4 = open('https://behold-seeds.s3.amazonaws.com/1_09_04s.jpg') file10_1 = open('https://behold-seeds.s3.amazonaws.com/1_10_01s.jpg') file10_2 = open('https://behold-seeds.s3.amazonaws.com/1_10_02s.jpg') file10_3 = open('https://behold-seeds.s3.amazonaws.com/1_10_03s.jpg') ### -USER 2 PROJECT IMAGES- file11_1 = open('https://behold-seeds.s3.amazonaws.com/2_01_01s.jpg') file11_2 = open('https://behold-seeds.s3.amazonaws.com/2_01_02s.jpg') file11_3 = open('https://behold-seeds.s3.amazonaws.com/2_01_03s.jpg') file12_1 = open('https://behold-seeds.s3.amazonaws.com/2_02_01s.jpg') file12_2 = open('https://behold-seeds.s3.amazonaws.com/2_02_02s.jpg') file12_3 = open('https://behold-seeds.s3.amazonaws.com/2_02_03s.jpg') file13_1 = open('https://behold-seeds.s3.amazonaws.com/2_03_01s.jpg') file13_2 = open('https://behold-seeds.s3.amazonaws.com/2_03_02s.jpg') file13_3 = open('https://behold-seeds.s3.amazonaws.com/2_03_03s.jpg') file14_1 = open('https://behold-seeds.s3.amazonaws.com/2_04_01s.jpg') file14_2 = open('https://behold-seeds.s3.amazonaws.com/2_04_02s.jpg') file14_3 = open('https://behold-seeds.s3.amazonaws.com/2_04_03s.jpg') file15_1 = open('https://behold-seeds.s3.amazonaws.com/2_05_01s.jpg') file15_2 = open('https://behold-seeds.s3.amazonaws.com/2_05_02s.jpg') file15_3 = open('https://behold-seeds.s3.amazonaws.com/2_05_03s.jpg') file15_4 = open('https://behold-seeds.s3.amazonaws.com/2_05_04s.jpg') ### -USER 3 PROJECT IMAGES- file16_1 = open('https://behold-seeds.s3.amazonaws.com/3_01_01s.jpg') file16_2 = open('https://behold-seeds.s3.amazonaws.com/3_01_02s.jpg') file16_3 = open('https://behold-seeds.s3.amazonaws.com/3_01_03s.jpg') file16_4 = open('https://behold-seeds.s3.amazonaws.com/3_01_04s.jpg') ### -USER 4 PROJECT IMAGES- file17_1 = open('https://behold-seeds.s3.amazonaws.com/4_01_01s.jpg') file17_2 = open('https://behold-seeds.s3.amazonaws.com/4_01_02s.jpg') file17_3 = open('https://behold-seeds.s3.amazonaws.com/4_01_03s.jpg') file17_4 = open('https://behold-seeds.s3.amazonaws.com/4_01_04s.jpg') file18_1 = open('https://behold-seeds.s3.amazonaws.com/4_02_01s.jpg') file18_2 = open('https://behold-seeds.s3.amazonaws.com/4_02_02s.jpg') file18_3 = open('https://behold-seeds.s3.amazonaws.com/4_02_03s.jpg') file18_4 = open('https://behold-seeds.s3.amazonaws.com/4_02_04s.jpg') ### -USER 7 PROJECT IMAGES- file19_1 = open('https://behold-seeds.s3.amazonaws.com/7_01_01s.jpg') file19_2 = open('https://behold-seeds.s3.amazonaws.com/7_01_02s.jpg') file19_3 = open('https://behold-seeds.s3.amazonaws.com/7_01_03s.jpg') file20_1 = open('https://behold-seeds.s3.amazonaws.com/7_02_01s.jpg') file20_2 = open('https://behold-seeds.s3.amazonaws.com/7_02_02s.jpg') file20_3 = open('https://behold-seeds.s3.amazonaws.com/7_02_03s.jpg') file20_4 = open('https://behold-seeds.s3.amazonaws.com/7_02_04s.jpg') file21_1 = open('https://behold-seeds.s3.amazonaws.com/7_03_01s.jpg') file21_2 = open('https://behold-seeds.s3.amazonaws.com/7_03_02s.jpg') file21_3 = open('https://behold-seeds.s3.amazonaws.com/7_03_03s.jpg') file21_4 = open('https://behold-seeds.s3.amazonaws.com/7_03_04s.jpg') # --------Attach AWS Images-------- # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ## --Attach User Avatars-- user1.avatar.attach(io: user1_avatar, filename: 'user1_avatar.png') user2.avatar.attach(io: user2_avatar, filename: 'user2_avatar.png') user7.avatar.attach(io: user7_avatar, filename: 'user7_avatar.png') # test_user.avatar.attach(io: default_avatar, filename: 'default_avatar.png') ## --Attach User Banners-- user1.banner.attach(io: user1_banner, filename: 'user1_banner.jpg') user2.banner.attach(io: user2_banner, filename: 'user2_banner.jpg') user7.banner.attach(io: user7_banner, filename: 'user7_banner.jpg') ## --Attach Project Images-- proj_1.images.attach(io: file1_1, filename: '1_01_01s.jpg') proj_1.images.attach(io: file1_2, filename: '1_01_02s.jpg') proj_1.images.attach(io: file1_3, filename: '1_01_03s.jpg') proj_1.images.attach(io: file1_4, filename: '1_01_04s.jpg') proj_1.images.attach(io: file1_5, filename: '1_01_05s.jpg') proj_2.images.attach(io: file2_1, filename: '1_02_01s.png') proj_2.images.attach(io: file2_2, filename: '1_02_02s.png') proj_2.images.attach(io: file2_3, filename: '1_02_03s.png') proj_2.images.attach(io: file2_4, filename: '1_02_04s.png') proj_2.images.attach(io: file2_5, filename: '1_02_05s.png') proj_2.images.attach(io: file2_6, filename: '1_02_06s.png') proj_3.images.attach(io: file3_1, filename: '1_03_01s.jpg') proj_3.images.attach(io: file3_2, filename: '1_03_02s.jpg') proj_3.images.attach(io: file3_3, filename: '1_03_03s.jpg') proj_3.images.attach(io: file3_4, filename: '1_03_04s.jpg') proj_4.images.attach(io: file4_1, filename: '1_04_01s.jpg') proj_4.images.attach(io: file4_2, filename: '1_04_02s.jpg') proj_4.images.attach(io: file4_3, filename: '1_04_03s.jpg') proj_4.images.attach(io: file4_4, filename: '1_04_04s.jpg') proj_4.images.attach(io: file4_5, filename: '1_04_05s.jpg') proj_5.images.attach(io: file5_1, filename: '1_05_01s.jpg') proj_5.images.attach(io: file5_2, filename: '1_05_02s.jpg') proj_5.images.attach(io: file5_3, filename: '1_05_03s.jpg') proj_6.images.attach(io: file6_1, filename: '1_06_01s.jpg') proj_6.images.attach(io: file6_2, filename: '1_06_02s.jpg') proj_6.images.attach(io: file6_3, filename: '1_06_03s.jpg') proj_7.images.attach(io: file7_1, filename: '1_07_01s.jpg') proj_7.images.attach(io: file7_2, filename: '1_07_02s.jpg') proj_7.images.attach(io: file7_3, filename: '1_07_03s.jpg') proj_8.images.attach(io: file8_1, filename: '1_08_01s.jpg') proj_8.images.attach(io: file8_2, filename: '1_08_02s.jpg') proj_8.images.attach(io: file8_3, filename: '1_08_03s.jpg') proj_8.images.attach(io: file8_4, filename: '1_08_04s.jpg') proj_9.images.attach(io: file9_1, filename: '1_09_01s.jpg') proj_9.images.attach(io: file9_2, filename: '1_09_02s.jpg') proj_9.images.attach(io: file9_3, filename: '1_09_03s.jpg') proj_9.images.attach(io: file9_4, filename: '1_09_04s.jpg') proj_10.images.attach(io: file10_1, filename: '1_10_01s.jpg') proj_10.images.attach(io: file10_2, filename: '1_10_02s.jpg') proj_10.images.attach(io: file10_3, filename: '1_10_03s.jpg') proj_11.images.attach(io: file11_1, filename: '2_01_01s.jpg') proj_11.images.attach(io: file11_2, filename: '2_01_02s.jpg') proj_11.images.attach(io: file11_3, filename: '2_01_03s.jpg') proj_12.images.attach(io: file12_1, filename: '2_02_01s.jpg') proj_12.images.attach(io: file12_2, filename: '2_02_02s.jpg') proj_12.images.attach(io: file12_3, filename: '2_02_03s.jpg') proj_13.images.attach(io: file13_1, filename: '2_03_01s.jpg') proj_13.images.attach(io: file13_2, filename: '2_03_02s.jpg') proj_13.images.attach(io: file13_3, filename: '2_03_03s.jpg') proj_14.images.attach(io: file14_1, filename: '2_04_01s.jpg') proj_14.images.attach(io: file14_2, filename: '2_04_02s.jpg') proj_14.images.attach(io: file14_3, filename: '2_04_03s.jpg') proj_15.images.attach(io: file15_1, filename: '2_05_01s.jpg') proj_15.images.attach(io: file15_2, filename: '2_05_02s.jpg') proj_15.images.attach(io: file15_3, filename: '2_05_03s.jpg') proj_15.images.attach(io: file15_4, filename: '2_05_04s.jpg') proj_16.images.attach(io: file16_1, filename: '3_01_01s.jpg') proj_16.images.attach(io: file16_2, filename: '3_01_02s.jpg') proj_16.images.attach(io: file16_3, filename: '3_01_03s.jpg') proj_16.images.attach(io: file16_4, filename: '3_01_04s.jpg') proj_17.images.attach(io: file17_1, filename: '4_01_01s.jpg') proj_17.images.attach(io: file17_2, filename: '4_01_02s.jpg') proj_17.images.attach(io: file17_3, filename: '4_01_03s.jpg') proj_17.images.attach(io: file17_4, filename: '4_01_04s.jpg') proj_18.images.attach(io: file18_1, filename: '4_02_01s.jpg') proj_18.images.attach(io: file18_2, filename: '4_02_02s.jpg') proj_18.images.attach(io: file18_3, filename: '4_02_03s.jpg') proj_18.images.attach(io: file18_4, filename: '4_02_04s.jpg') proj_19.images.attach(io: file19_1, filename: '7_01_01s.jpg') proj_19.images.attach(io: file19_2, filename: '7_01_02s.jpg') proj_19.images.attach(io: file19_3, filename: '7_01_03s.jpg') proj_20.images.attach(io: file20_1, filename: '7_02_01s.jpg') proj_20.images.attach(io: file20_2, filename: '7_02_02s.jpg') proj_20.images.attach(io: file20_3, filename: '7_02_03s.jpg') proj_20.images.attach(io: file20_4, filename: '7_02_04s.jpg') proj_21.images.attach(io: file21_1, filename: '7_03_01s.jpg') proj_21.images.attach(io: file21_2, filename: '7_03_02s.jpg') proj_21.images.attach(io: file21_3, filename: '7_03_03s.jpg') proj_21.images.attach(io: file21_4, filename: '7_03_04s.jpg') # --------Comments Seed Data-------- # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ## --PROJ 1 COMMENTS-- comment_001 = Comment.create( body: "love it so my style", author_id: user5.id, project_id: proj_1.id ) comment_002 = Comment.create( body: "DIG IT!!!!!!!", author_id: user3.id, project_id: proj_1.id ) comment_003 = Comment.create( body: "wow these are amazing. great line art and colors", author_id: user2.id, project_id: proj_1.id ) comment_004 = Comment.create( body: "very beautiful. Good job, keep it up", author_id: user4.id, project_id: proj_1.id ) comment_005 = Comment.create( body: "AWESOME WORK...", author_id: user6.id, project_id: proj_1.id ) ## --PROJ 2 COMMENTS-- comment_006 = Comment.create( body: "Cute !", author_id: user5.id, project_id: proj_2.id ) comment_007 = Comment.create( body: "These are amazing, you should do more! :)", author_id: user2.id, project_id: proj_2.id ) comment_008 = Comment.create( body: "Great characters", author_id: user3.id, project_id: proj_2.id ) comment_009 = Comment.create( body: "This is so brilliant and very creative. The work looks perfect!", author_id: user4.id, project_id: proj_2.id ) ## --PROJ 3 COMMENTS-- comment_010 = Comment.create( body: "Beautiful illustrations", author_id: user6.id, project_id: proj_3.id ) comment_011 = Comment.create( body: "Good Job!!!", author_id: user2.id, project_id: proj_3.id ) comment_012 = Comment.create( body: "Great drawings. Nicely done.", author_id: user5.id, project_id: proj_3.id ) comment_013 = Comment.create( body: "Please make one for me too!!", author_id: user6.id, project_id: proj_3.id ) ## --PROJ 4 COMMENTS-- comment_014 = Comment.create( body: "So beautiful", author_id: user4.id, project_id: proj_4.id ) comment_015 = Comment.create( body: "WOW!!! I really like your work!!!", author_id: user6.id, project_id: proj_4.id ) comment_016 = Comment.create( body: "They are so cute! Beautiful :)", author_id: user5.id, project_id: proj_4.id ) ## --PROJ 5 COMMENTS-- comment_017 = Comment.create( body: "AHHHH the pokemon are so cute~!", author_id: user2.id, project_id: proj_5.id ) comment_018 = Comment.create( body: "Awesome!!!!", author_id: user3.id, project_id: proj_5.id ) comment_019 = Comment.create( body: "Awesome work & Great artist", author_id: user4.id, project_id: proj_5.id ) comment_020 = Comment.create( body: "very nice!!! :D", author_id: user6.id, project_id: proj_5.id ) ## --PROJ 6 COMMENTS-- comment_021 = Comment.create( body: "Spatial design looks great!", author_id: user5.id, project_id: proj_6.id ) comment_022 = Comment.create( body: "I love your hand drawings", author_id: user3.id, project_id: proj_6.id ) comment_023 = Comment.create( body: "cool work, what year was this for?", author_id: user6.id, project_id: proj_6.id ) comment_024 = Comment.create( body: "Thanks! this was for my first semester of freshman year :D", author_id: user1.id, project_id: proj_6.id ) comment_025 = Comment.create( body: "dude sweet", author_id: user6.id, project_id: proj_6.id ) ## --PROJ 7 COMMENTS-- comment_026 = Comment.create( body: "My dormitory project came out alright i guess", author_id: user1.id, project_id: proj_7.id ) comment_027 = Comment.create( body: "cool project!", author_id: user2.id, project_id: proj_7.id ) comment_028 = Comment.create( body: "nice, I like the facade design", author_id: user3.id, project_id: proj_7.id ) ## --PROJ 8 COMMENTS-- comment_029 = Comment.create( body: "handdrawn drafting looks intense!", author_id: user2.id, project_id: proj_8.id ) comment_030 = Comment.create( body: "Yeah it's a shame they don't really teach hand drafting anymore :/", author_id: user1.id, project_id: proj_8.id ) comment_031 = Comment.create( body: "nice job on these!", author_id: user5.id, project_id: proj_8.id ) ## --PROJ 9 COMMENTS-- comment_032 = Comment.create( body: "the boathouse project was wack lol", author_id: user3.id, project_id: proj_9.id ) comment_033 = Comment.create( body: "Interesting design; I like the views that the design allows.", author_id: user2.id, project_id: proj_9.id ) ## --PROJ 10 COMMENTS-- comment_034 = Comment.create( body: "i love it!!!", author_id: user5.id, project_id: proj_10.id ) comment_035 = Comment.create( body: "Lasercutting is always cool", author_id: user4.id, project_id: proj_10.id ) comment_036 = Comment.create( body: "love it!!!", author_id: user2.id, project_id: proj_10.id ) ## --PROJ 11 COMMENTS-- comment_037 = Comment.create( body: "i love your work as always haha", author_id: user1.id, project_id: proj_11.id ) comment_038 = Comment.create( body: "Great job!)", author_id: user6.id, project_id: proj_11.id ) comment_039 = Comment.create( body: "Lovely! can you draw me too??", author_id: user5.id, project_id: proj_11.id ) comment_040 = Comment.create( body: "haha thanks, i take commissions :)", author_id: user2.id, project_id: proj_11.id ) ## --PROJ 12 COMMENTS-- comment_041 = Comment.create( body: "Ohhh I remember this class! Nice idea for product design!", author_id: user1.id, project_id: proj_12.id ) comment_042 = Comment.create( body: "Awesome work!", author_id: user3.id, project_id: proj_12.id ) comment_043 = Comment.create( body: "I love it!!", author_id: user5.id, project_id: proj_12.id ) ## --PROJ 13 COMMENTS-- comment_044 = Comment.create( body: "Ugh i remember the long nights in the woodshop making this :/", author_id: user2.id, project_id: proj_13.id ) comment_045 = Comment.create( body: "I think it came out amazing!", author_id: user1.id, project_id: proj_13.id ) ## --PROJ 14 COMMENTS-- comment_046 = Comment.create( body: "lovely design", author_id: user6.id, project_id: proj_14.id ) comment_047 = Comment.create( body: "Cool, keep up the good work!", author_id: user1.id, project_id: proj_14.id ) comment_048 = Comment.create( body: "AMAZING", author_id: user3.id, project_id: proj_14.id ) comment_049 = Comment.create( body: "Nice Work", author_id: user5.id, project_id: proj_14.id ) ## --PROJ 15 COMMENTS-- comment_050 = Comment.create( body: "I wish I could sketch as well as you :D", author_id: user1.id, project_id: proj_15.id ) comment_051 = Comment.create( body: "Your sketches are impressive", author_id: user6.id, project_id: proj_15.id ) comment_052 = Comment.create( body: "nicee", author_id: user3.id, project_id: proj_15.id ) ## --PROJ 16 COMMENTS-- comment_053 = Comment.create( body: "School design looks awesome!", author_id: user1.id, project_id: proj_16.id ) comment_054 = Comment.create( body: "Looks great!!", author_id: user5.id, project_id: proj_16.id ) comment_055 = Comment.create( body: "Awesome work as usual man", author_id: user3.id, project_id: proj_16.id ) ## --PROJ 17 COMMENTS-- comment_056 = Comment.create( body: "WOAH, skyscraper design!", author_id: user2.id, project_id: proj_17.id ) comment_057 = Comment.create( body: "that looks like an intense project to have done! :O", author_id: user1.id, project_id: proj_17.id ) comment_058 = Comment.create( body: "Yeah, thesis projects always suck lol", author_id: user4.id, project_id: proj_17.id ) ## --PROJ 18 COMMENTS-- comment_059 = Comment.create( body: "Nice work on this!", author_id: user1.id, project_id: proj_18.id ) comment_060 = Comment.create( body: "The idea is very unique, floating houses!", author_id: user2.id, project_id: proj_18.id ) comment_061 = Comment.create( body: "niceee", author_id: user6.id, project_id: proj_18.id ) ## --PROJ 19 COMMENTS-- comment_062 = Comment.create( body: "Beautiful stuff, the design look well put together.", author_id: user4.id, project_id: proj_19.id ) comment_063 = Comment.create( body: "this is your work from after graduation right?? it looks great!", author_id: user5.id, project_id: proj_19.id ) comment_064 = Comment.create( body: "Absolutely fantastic", author_id: user6.id, project_id: proj_19.id ) comment_065 = Comment.create( body: "I'd buy this book :)", author_id: user2.id, project_id: proj_19.id ) ## --PROJ 20 COMMENTS-- comment_066 = Comment.create( body: "WOW! Amazing work! This book has a really cute style", author_id: user1.id, project_id: proj_20.id ) comment_067 = Comment.create( body: "Nice job!", author_id: user3.id, project_id: proj_20.id ) comment_068 = Comment.create( body: "I miss the summertime, great work on this!", author_id: user2.id, project_id: proj_20.id ) ## --PROJ 21 COMMENTS-- comment_069 = Comment.create( body: "Amazing design work as always!", author_id: user2.id, project_id: proj_21.id ) comment_070 = Comment.create( body: "ahhhh my favorite animal!! very cute!", author_id: user6.id, project_id: proj_21.id ) comment_071 = Comment.create( body: "Great work !", author_id: user3.id, project_id: proj_21.id ) comment_072 = Comment.create( body: "I like it", author_id: user4.id, project_id: proj_21.id ) # --New User (user7) Comments for Projects-- comment_073 = Comment.create( body: "I didn't know Pratt's architecture projects were so cool!", author_id: user7.id, project_id: proj_17.id ) comment_074 = Comment.create( body: "Cool project! Educational design is super important nowadays :)", author_id: user7.id, project_id: proj_16.id ) comment_075 = Comment.create( body: "Pokemon and Super Mario combo, nice~", author_id: user7.id, project_id: proj_5.id ) comment_076 = Comment.create( body: "This makes me appreciate digital art lol, so intense!", author_id: user7.id, project_id: proj_8.id ) comment_077 = Comment.create( body: "I love your illustration style!", author_id: user7.id, project_id: proj_1.id ) comment_067 = Comment.create( body: "Lovely drawings~ :D", author_id: user7.id, project_id: proj_11.id ) comment_068 = Comment.create( body: "Woah, really nice work on the furniture design!", author_id: user7.id, project_id: proj_13.id ) # --------Appreciations Seed Data-------- # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv # Appreciation.create()
require 'spec_helper' describe "Stage" do describe "Home page" do it "should have the content 'Welcome home'" do visit '/home' expect(page).to have_content('Welcome') end it "should have the content 'Home' " do visit '/home' expect(page).to have_title("Home") end end #CAUTIONS:: do comment out the failing test after validating it. #it "should not have the content ?? the custome one" do # visit '/stage/home' # expect(page).not_to have_title("| Home") # end*/ describe "Help page" do it "should have the content 'Help'" do visit '/help' expect(page).to have_content('Help') end it "should have the content 'Help' " do visit '/help' expect(page).to have_title("Help ") end end describe "Contact us" do it "should have the location 'Located here' " do visit '/contact' expect(page).to have_content('Located here') end it "should have the title 'contact us' " do visit '/contact' expect(page).to have_title("Contact us") end end describe "for signed-in users" do let(:user) { FactoryGirl.create(:user) } before do FactoryGirl.create(:micropost, user: user, content: "LOrem ipsum") FactoryGirl.create(:micropost, user: user, content: "Dollar it is what i need but bitcoin definitely") sign_in user visit root_path end ##continue from 10.37 it "should render the user's feed " do user.feed.each do |item| expect(page).to have_selector("li##{item.id}", text: item.content) end end describe "follower/following counts" do let(:other_user) { FactoryGirl.create(:user)} before do other_user.follow!(user) visit root_path end it {should have_link("0 following", href: following_user_path(user))} it { should have_link("1 following", href: followers_user_path(user))} end end end
require File.expand_path("../helper", __FILE__) class TestConnect < Test::Unit::TestCase context "Sauce Connect" do should "be running when ready" do connect = Sauce::Connect.new(:host => "saucelabs.com", :port => 80) assert_equal "uninitialized", connect.status connect.wait_until_ready assert_equal "running", connect.status connect.status.should == "running" connect.disconnect end should "set error flag if things don't go well" do connect = Sauce::Connect.new(:host => "saucelabs.com", :port => 80, :username => 'fail') start = Time.now while Time.now-start < 20 && !connect.error sleep 1 end assert connect.error connect.disconnect end end end