text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
require "rails_helper"
describe DiscourseRssPolling::FeedSettingsController do
let!(:admin) { Fabricate(:admin) }
before do
sign_in(admin)
SiteSetting.rss_polling_enabled = true
DiscourseRssPolling::RssFeed.create!(
url: "https://blog.discourse.org/feed",
author: "system",
category_id: 4,
tags: nil,
category_filter: "updates",
)
end
describe "#show" do
it "returns the serialized feed settings" do
expected_json =
ActiveModel::ArraySerializer.new(
DiscourseRssPolling::FeedSettingFinder.all,
root: :feed_settings,
).to_json
get "/admin/plugins/rss_polling/feed_settings.json"
expect(response.status).to eq(200)
expect(response.body).to eq(expected_json)
end
end
describe "#update" do
it "updates rss feeds" do
put "/admin/plugins/rss_polling/feed_settings.json",
params: {
feed_settings: [
{
feed_url: "https://www.newsite.com/feed",
author_username: "system",
feed_category_filter: "updates",
},
],
}
expect(response.status).to eq(200)
expected_json =
ActiveModel::ArraySerializer.new(
DiscourseRssPolling::FeedSettingFinder.all,
root: :feed_settings,
).to_json
expect(response.body).to eq(expected_json)
end
it "allows duplicate rss feed urls" do
put "/admin/plugins/rss_polling/feed_settings.json",
params: {
feed_settings: [
{
feed_url: "https://blog.discourse.org/feed",
author_username: "system",
discourse_category_id: 2,
feed_category_filter: "updates",
},
{
feed_url: "https://blog.discourse.org/feed",
author_username: "system",
discourse_category_id: 4,
feed_category_filter: "updates",
},
],
}
expect(response.status).to eq(200)
feeds = DiscourseRssPolling::FeedSettingFinder.all
expected_json = ActiveModel::ArraySerializer.new(feeds, root: :feed_settings).to_json
expect(response.body).to eq(expected_json)
expect(feeds.count).to eq(2)
end
end
end
|
# Serializers
class BirdSerializer
def initialize(bird)
@bird = bird
end
def as_json(*)
data = { id: @bird.id.to_s,
name: @bird.name,
family: @bird.family,
continents: @bird.continents,
added: @bird.added,
visible: @bird.visible }
data[:errors] = @bird.errors if @bird.errors.any?
data
end
end
|
class AdminUser < ActiveRecord::Base
belongs_to :user, foreign_key: :user_id, touch: true
delegate :firstname, :lastname, :name, :email, :institution, :active, :actors, :acts, :indicators, :measurements, :units, :comments, to: :user
validates :user_id, presence: true, uniqueness: true
end |
class UserFields < ActiveRecord::Migration
def change
add_column :users, :startup_name, :string
add_column :users, :startup_blurb, :text
add_column :users, :startup_url, :string
add_column :users, :startup_logo_url, :string
add_column :users, :avatar_url, :string
add_column :users, :bio, :text
add_column :users, :twitter_name, :string
add_column :users, :linkedin_url, :string
add_column :users, :facebook_id, :string
end
end
|
class AudioQuizAnswersController < ApplicationController
before_action :set_audio_quiz_answer, only: [:show, :edit, :update, :destroy]
# GET /audio_quiz_answers
# GET /audio_quiz_answers.json
def index
@audio_quiz_answers = AudioQuizAnswer.all
end
# GET /audio_quiz_answers/new
def new
@audio_quiz_answer = AudioQuizAnswer.new
end
# POST /audio_quiz_answers
# POST /audio_quiz_answers.json
def create
@audio_quiz_answer = AudioQuizAnswer.new(audio_quiz_answer_params)
respond_to do |format|
if @audio_quiz_answer.save
format.html { redirect_to '/days/6', notice: 'Thanks, I\'ll have a look at what you just submitted later on ;)' }
else
format.html { render :new }
end
end
end
# DELETE /audio_quiz_answers/1
# DELETE /audio_quiz_answers/1.json
def destroy
@audio_quiz_answer.destroy
respond_to do |format|
format.html { redirect_to audio_quiz_answers_url, notice: 'Audio quiz answer was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_audio_quiz_answer
@audio_quiz_answer = AudioQuizAnswer.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def audio_quiz_answer_params
params.require(:audio_quiz_answer).permit(:who, :called)
end
end
|
require 'setback/redis_provider'
describe Setback::RedisProvider do
subject { described_class.new(:parent_class => NilClass) }
before :each do
@old_redis_url = described_class.redis_url
end
after :each do
described_class.redis_url = @old_redis_url
end
it 'should provide a configuration methods for the redis url' do
described_class.should respond_to(:redis_url)
described_class.should respond_to(:redis_url=)
described_class.redis_url.should_not be_empty
described_class.redis_url = 'redis://zizzyballubah:8271'
described_class.redis_url.should == 'redis://zizzyballubah:8271'
end
it 'should provide a configuration methods for the redis namespace prefix' do
described_class.should respond_to(:namespace_prefix)
described_class.should respond_to(:namespace_prefix=)
described_class.namespace_prefix.should_not be_empty
described_class.namespace_prefix = 'rosebud:'
described_class.namespace_prefix.should == 'rosebud:'
end
it 'should require a parent class on initialization' do
expect { described_class.new }.to raise_error(/key not found/)
end
it 'should proxy #get to redis + YAML.load' do
subject.send(:redis).set(:snorkel, 'true')
subject.get(:snorkel).should == true
end
it 'should return false for corrupted keys' do
subject.send(:redis).should_receive(:get).and_return("\x00\x00\x00")
YAML.should_receive(:load).and_raise(StandardError)
STDERR.should_receive(:puts)
subject.get(:scuba).should be_nil
end
it 'should proxy #set to redis + YAML.dump' do
subject.set(:danish, 10000)
subject.send(:redis).get('danish').should == YAML.dump(10000)
end
it 'should proxy #keys to redis, filtering out internal keys by default' do
subject.send(:redis).tap do |redis|
redis.keys.each { |k| redis.del(k) }
redis.set(:chowder, [9876, :foo])
redis.set(:__last_load, {:stupendous => :fluffernutter})
end
subject.keys.should == [:chowder]
end
it 'should build a hash for #all' do
subject.send(:redis).tap do |redis|
redis.keys.each { |k| redis.del(k) }
redis.set(:lorax, YAML.dump(:truffulalover64))
redis.set(:onceler, YAML.dump([:you, :need, 1, 'thneed']))
redis.set(:__last_load, YAML.dump(Time.now - (60 * 20)))
end
subject.all.should == {
:lorax => :truffulalover64,
:onceler => [:you, :need, 1, 'thneed']
}
end
end
|
class Organizer::PostsController < Organizer::BaseController
before_action :load_events, only: %i(new create edit)
before_action :load_posts, only: %i(edit update destroy)
def index
@posts = Post.select_posts.order_by.page(params[:page]).per Settings.post_page
end
def new
@post = Post.new
end
def create
@post = Post.new post_params
if @post.save
flash[:success] = ".create_success"
redirect_to organizer_posts_path
else
flash[:danger] = ".create_fail"
render :new
end
end
def edit; end
def update
if @post.update post_params
flash[:success] = t ".update_cuccess"
redirect_to organizer_posts_path
else
flash[:danger] = t ".update_fail"
render :edit
end
end
def destroy
if @post.destroy
flash[:success] = t ".delete_success"
else
flash[:danger] = t ".delete_fail"
end
respond_to do |format|
format.js
format.html {redirect_to organizer_posts_path}
end
end
private
def post_params
params.require(:post).permit :title, :body, :thumbnail, :event_id
end
def load_posts
@post = Post.find_by id: params[:id]
return if @post
flash[:danger] = t ".no_post"
redirect_to organizer_posts_path
end
def load_events
@events = Event.select_events
end
end
|
Given("I am on Add LDL page") do
visit new_profile_ldl_path(profile_email: @my_profile.email)
end
Then("I should be redirected to the LDL page") do
expect(page).to have_current_path(profile_ldls_path(profile_email: @my_profile.email))
end
Given("I am on LDL page") do
visit profile_ldls_path(profile_email: @my_profile.email)
end
Then("The Add LDL page should be displayed") do
expect(page).to have_current_path(new_profile_ldl_path(profile_email: @my_profile.email))
end
When("I fill the new LDL data") do
fill_in "ldl[value]", with: "140"
fill_in "ldl[date]", with: "21/10/2018"
end
|
class Api::FoursquareController < ApiController
include FoursquareClient
include FoursquareErrors
before_filter :authenticate_user_from_token!
# Rescues
# TODO: look up foursquare api errors and make sure we're handling all
# of them correctly. FOR NOW, its just responding with 500.
# rescue_from Foursquare2::APIError, with: :handle_foursquare_api_error
# Actions
def proxy
# Strip out any version segments since the client assumes V2
foursquare_path = params[:foursquare_path].gsub(/^v[0-9]\//i, '')
# We bypass the shortcut methods the client gem offers for us and
# build a request the same way those methods do.
foursquare_response = foursquare_client.connection.get do |req|
req.url foursquare_path, foursquare_params
end
body = foursquare_client.return_error_or_body(foursquare_response, foursquare_response.body)
# Get response headers that we care about
response.headers.merge! foursquare_response.headers.slice('x-ratelimit-limit', 'x-ratelimit-remaining')
render json: body
end
private
def foursquare_params
params.except(:controller, :action, :foursquare_path, :format)
end
end
|
class Feedback < ActiveRecord::Base
validates :question, :from, :presence => true
belongs_to :post, :foreign_key => "to", :class_name => "Post"
belongs_to :user, :foreign_key => "from", :class_name => "User"
end
|
module Workarea
module Upgrade
class ReportCard
CATEGORIES = %w(
assets
controllers
helpers
listeners
mailers
models
services
view_models
views
workers
)
def initialize(diff)
@diff = diff
end
def results
CATEGORIES.inject({}) do |memo, category|
memo[category] = calculate_grade(category)
memo
end
end
def customized_percents
@customized_percents ||= CATEGORIES.inject({}) do |memo, category|
percent_customized = customized_totals[category] / changed_totals[category].to_f
percent_customized *= 100
memo[category] = percent_customized.nan? ? 0 : percent_customized.round
memo
end
end
# If a file was decorated or overridden and removed, this is the
# biggest pain point.
def worst_files
@worst_files ||= CATEGORIES.inject({}) do |memo, category|
memo[category] = customized_files_now_missing
.select { |f| f.include?(category) }
.count
memo
end
end
def changed_totals
@changed_totals ||= CATEGORIES.inject({}) do |memo, category|
memo[category] = @diff.all.select { |f| f.include?(category) }.count
memo
end
end
def customized_totals
@customized_totals ||= CATEGORIES.inject({}) do |memo, category|
memo[category] = @diff.for_current_app.select { |f| f.include?(category) }.count
memo
end
end
def calculate_grade(category)
customized_total = customized_totals[category]
return 'A' if customized_total <= 3
percent_customized = customized_percents[category]
return 'A' if percent_customized < 5
score = worst_files[category]
score += percent_customized
if score.between?(0, 9)
'A'
elsif score.between?(10, 24)
'B'
elsif score.between?(25, 34)
'C'
elsif score.between?(35, 44)
'D'
else
'F'
end
end
private
def customized_files_now_missing
@diff.customized_files & @diff.removed
end
end
end
end
|
module PlayStoreInfo
class GenericError < StandardError; end
class InvalidStoreLink < GenericError
def initialize
store_link = 'https://play.google.com/store/apps/details?id=com.your.app&hl=en'.freeze
super "URL should look like '#{store_link}'"
end
end
class AppNotFound < GenericError
def initialize
super 'Could not find app in Google Play Store'
end
end
class ConnectionError < GenericError
def initialize
super 'Could not retrieve your app information at the moment. Please try again later.'
end
end
end
|
class CartItem < ActiveRecord::Base
belongs_to :user
has_many :menu_items
def self.total_amount(user_id)
cart_items = CartItem.where(user_id: user_id)
cart_items.map { |item| item.quantity * MenuItem.find(item.menu_item_id).price }.sum
end
end
|
def __
raise "__ should be replaced with a value or expression to make the test pass."
end
describe "Nested Data Structures" do
context 'arrays' do
# Have we read about let yet?
# https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let
let(:tic_tac_toe_board){[
["A1", "A2", "A3"],
["B1", "B2", "B3"],
["C1", "C2", "C3"]
]}
it 'can read the first level of nesting' do
# Access the corresponding data from the array above by filling in the
# array accessors below. For example, you would access the middle square
# in the following manner:
middle = tic_tac_toe_board[1][1]
# Replace the __ with the correct accessors.
first_row = tic_tac_toe_board[0]
second_row = tic_tac_toe_board[1]
third_row = tic_tac_toe_board[2]
expect(first_row).to eq(["A1", "A2", "A3"])
expect(second_row).to eq(["B1", "B2", "B3"])
expect(third_row).to eq(["C1", "C2", "C3"])
end
it 'can read second level of nesting' do
bottom_middle = tic_tac_toe_board[2][1]
top_left_corner = tic_tac_toe_board[0][0]
expect(bottom_middle).to eq("C2")
expect(top_left_corner).to eq("A1")
end
it 'can write to the second level of nesting' do
# Place "X"s in the positions corresponding to a win
# on the right column.
# To place an X in the middle you would:
tic_tac_toe_board[1][1] = "X"
# Make your moves here (replace the __ with the correct accessor)
tic_tac_toe_board[0][2] = "X"
tic_tac_toe_board[1][2] = "X"
tic_tac_toe_board[2][2] = "X"
# Replace the __ with the correct accessors.
top_right = tic_tac_toe_board[0][2]
middle_right = tic_tac_toe_board[1][2]
bottom_right = tic_tac_toe_board[2][2]
expect(top_right).to eq("X")
expect(middle_right).to eq("X")
expect(bottom_right).to eq("X")
end
end
context 'hashes' do
let(:profiles){
{
:grace_hopper => {
:known_for => "COBOL",
:languages => ["COBOL", "FORTRAN"]
},
:alan_kay => {
:known_for => "Object Orientation",
:languages => ["Smalltalk", "LISP"]
},
:dennis_ritchie => {
:known_for => "Unix",
:languages => ["C"]
}
}
}
it 'can access top level data' do
# Replace the __ with the correct accessors
hopper = profiles[:grace_hopper] # What key in profile would you use to get Hopper's info?
expect(hopper).to eq({
:known_for => "COBOL",
:languages => ["COBOL", "FORTRAN"]
})
end
it 'can access second level data' do
alan_kay_is_known_for = "Object Orientation" # What combination of keys would you use?
expect(alan_kay_is_known_for).to eq("Object Orientation")
end
it 'can access data on the third level' do
dennis_ritchies_language = "C"
expect(dennis_ritchies_language).to eq("C")
end
it 'can write data to the top level' do
yukihiro_matsumoto = {
:known_for => "Ruby",
:languages => "LISP, C"
}
# Add that data to the main profiles hash so that it exists
# within profiles as a key corresponding to the programmers
# name.
# You're going to want something like profiles =
profiles[:yukihiro_matsumoto] = {
:known_for => "Ruby",
:languages => "LISP, C"
}
expect(profiles.keys).to include(:yukihiro_matsumoto)
end
it 'can write data to the second level' do
# Change what alan kay is known for to "GUI"
profiles[:alan_kay][:known_for] = "GUI"
expect(profiles[:alan_kay][:known_for]).to eq("GUI")
end
it 'can add data to the third level' do
# Add Assembly to Dennis Ritchie's Languages
profiles[:dennis_ritchie][:languages] = ["C","Assembly"]
# or << "Assembly"
expect(profiles[:dennis_ritchie][:languages]).to include("Assembly")
end
end
end
|
require 'rails_helper'
RSpec.describe Api::IssuesController, type: :request do
describe 'index' do
def dispatch(options = {})
get '/api/issues', headers: options[:headers]
end
it_behaves_like 'it required auth'
end
describe 'create' do
def dispatch(options = {})
post '/api/issues', params: { issue: { title: '1234' } }, headers: options[:headers]
end
it_behaves_like 'it required auth'
end
describe 'update' do
let!(:user) { User.create(login: 'regular', password: '123456', name: 'Mr. Regular') }
let!(:issue) { Issue.create(title: 'test', author: user) }
def dispatch(options = {})
put "/api/issues/#{issue.id}", params: { issue: { title: '1234' } }, headers: options[:headers]
end
it_behaves_like 'it required auth'
end
describe 'check_in' do
let!(:regular) { User.create(login: 'regular', password: '123456', name: 'Mr. Regular') }
let!(:issue) { Issue.create(title: 'test', author: regular) }
let!(:user) { User.create(login: 'manager', password: '123456', name: 'Mr. Manager') }
def dispatch(options = {})
post "/api/issues/#{issue.id}/check_in", headers: options[:headers]
end
it_behaves_like 'it required auth'
end
describe 'check_out' do
let!(:regular) { User.create(login: 'regular', password: '123456', name: 'Mr. Regular') }
let!(:issue) { Issue.create(title: 'test', author: regular, manager: user) }
let!(:user) { User.create(login: 'manager', password: '123456', name: 'Mr. Manager') }
def dispatch(options = {})
post "/api/issues/#{issue.id}/check_out", headers: options[:headers]
end
it_behaves_like 'it required auth'
end
describe 'update_status' do
let!(:regular) { User.create(login: 'regular', password: '123456', name: 'Mr. Regular') }
let!(:issue) { Issue.create(title: 'test', author: regular, manager: user) }
let!(:user) { User.create(login: 'manager', password: '123456', name: 'Mr. Manager') }
def dispatch(options = {})
post "/api/issues/#{issue.id}/update_status", params: {status: :in_progress}, headers: options[:headers]
end
it_behaves_like 'it required auth'
end
end
|
class UsersController < ApplicationController
before_action :authenticate_user!
def show
@user = User.find(params[:id])
end
end
|
# Question 1:
# What would you expect the code below to print out?
numbers = [1, 2, 2, 3]
numbers.uniq
puts numbers
# Answer: 1 2 2 3 -- numbers.uniq returned a new Array object with unique elements, but it did not modify the numbers object. Further, the puts method automatically calls to_s on its argument, and that’s why you see the output like above.
# Additional note: had the last line been p numbers instead, the output would have been [1, 2, 2, 3] because the p method automatically calls inspect on its argument, which gives a different formatting on the output. Furthermore, we could have also done puts numbers.inspect and the output would have been the same as using the p method.
# Question 2:
# Describe the difference between ! and ? in Ruby. And explain what would happen in the following scenarios:
# 1. what is != and where should you use it? -- does not equal
# 2. put ! before something, like !user_name -- using just one ! (!user_name) returns the opposite of its boolean equivalent (false)
# 3. put ! after something, like words.uniq! -- mutates
# 4. put ? before something - ternary operator expression???
# 5. put ? after something -- part of an expression/ternary operator: int.even? ? "is even" : "not even"
# 6. put !! before something, like !!user_name -- turns it into its boolean equivalent (true)
# Answer: They are part of Ruby's syntax and depending on how they are used in an expression effects their result. ! used at the end of a methods name is actually part of the methods name.
#Question 3:
# Replace the word "important" with "urgent" in this string:
advice = "Few things in life are as important as house training your pet dinosaur."
# Answser: advice.gsub("important", "urgent")
#Question 4:
# The Ruby Array class has several methods for removing items from the array. Two of them have very similar names. Let's see how they differ:
numbers = [1, 2, 3, 4, 5]
# What do the following method calls do (assume we reset numbers to the original array between method calls)?
numbers.delete_at(1) #=> removes 2 (which is indexed at 1) and numbers now = [1, 3, 4, 5]
numbers.delete(1) #=> removes the actual number 1 and numbers now = [2, 3, 4, 5]
#Question 5:
# Programmatically determine if 42 lies between 10 and 100. Hint: Use Ruby's range object in your solution.
(10..100).include?(42) #=> true
(10.100).cover?(42) #=> true
#Question 6:
famous_words = "seven years ago..."
# show two different ways to put the expected "Four score and " in front of it.
famous_words.insert(0, "Four score and ")
famous_words.prepend("Four score and ")
"Four score and " + famous_words
"Four score and " << famous_words
#Question 7:
# If we build an array like this:
flintstones = ["Fred", "Wilma"]
flintstones << ["Barney", "Betty"]
flintstones << ["BamBam", "Pebbles"]
# We will end up with this "nested" array:
["Fred", "Wilma", ["Barney", "Betty"], ["BamBam", "Pebbles"]]
# Make this into an un-nested array.
flintstones.flatten!
#Question 8:
flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 }
# Turn this into an array containing only two elements: Barney's name and Barney's number
flintstones.select! {|key, value| value == 2}.to_a
flintstones.assoc("Barney") |
#
# Code Solo Routing
#
ActionController::Routing::Routes.draw do |map|
# Root home controller
map.root :controller => 'home', :action => 'index'
map.resources :projects, :member => { :help => :post, :watch => :post },
:requirements => {:id => /.*/}
map.resources :pubs
map.resources :tags
map.resources :users, :member => { :follow => :post, :unfollow => :post }
# map.resources :groups, :member => { :join => :post, :unjoin => :post }
# map.resources :pubs, :member => { :fetch => :post }
map.resource :options, :only => [:show, :update]
map.resource :user_session
map.search '/search/:search', :controller => 'home', :action => 'search', :defaults => { :search => '' }
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.register '/register', :controller => 'users', :action => 'create'
map.signup '/signup', :controller => 'users', :action => 'new'
map.help '/help', :controller => 'help', :action => 'index'
map.about '/about', :controller => 'home', :action => 'about'
map.friends '/friends', :controller => 'home', :action => 'friends'
map.friends '/send', :controller => 'home', :action => 'sendmail'
# Connect usernames
map.connect ':login', :controller => 'home', :action => 'profile'
end
|
class MonthlyDistrictReport::Hypertension::FacilityData
include MonthlyDistrictReport::Utils
attr_reader :repo, :district, :month
def initialize(district, period_month)
@district = district
@month = period_month
@repo = Reports::Repository.new(district.facility_regions, periods: period_month)
end
def content_rows
district_facility_regions
.map.with_index do |facility_region, index|
facility = facility_region.source
{
"Sl.No" => index + 1,
"Facility size" => facility.localized_facility_size,
"Name of facility" => facility.name,
"Name of block" => facility_region.block_name,
"Total hypertension registrations" => repo.cumulative_registrations[facility_region.slug][month],
"Hypertension patients under care" => repo.adjusted_patients[facility_region.slug][month],
"Hypertension patients registered this month" => repo.monthly_registrations[facility_region.slug][month],
"BP control % of all patients registered before 3 months" => percentage_string(repo.controlled_rates[facility_region.slug][month])
}
end
end
def header_rows
[[
"Sl.No",
"Facility size",
"Name of facility",
"Name of block",
"Total hypertension registrations",
"Hypertension patients under care",
"Hypertension patients registered this month",
"BP control % of all patients registered before 3 months"
]]
end
private
def district_facility_regions
active_facility_ids = district.facilities.active(month_date: @month.to_date).pluck(:id)
district
.facility_regions
.where("regions.source_id" => active_facility_ids)
.joins("INNER JOIN reporting_facilities on reporting_facilities.facility_id = regions.source_id")
.select("regions.*, reporting_facilities.*")
.order(:block_name, :facility_name)
end
def row_data(facility_region, index)
facility = facility_region.source
{
"Sl.No" => index + 1,
"Facility size" => facility.localized_facility_size,
"Name of facility" => facility.name,
"Name of block" => facility_region.block_name,
"Total registrations" => repo.cumulative_registrations[facility_region.slug][month],
"Patients under care" => repo.adjusted_patients[facility_region.slug][month],
"Registrations this month" => repo.monthly_registrations[facility_region.slug][month],
"BP control % of all patients registered before 3 months" => percentage_string(repo.controlled_rates[facility_region.slug][month])
}
end
end
|
describe Chirper::UseCase::CreateChirp do
it 'Call Gateway create Chirp' do
gateway_spy = spy
use_case = described_class.new(chirp_gateway: gateway_spy)
use_case.execute(title: 'Meow', body: 'Cat')
expect(gateway_spy).to have_received(:create)
end
it 'Call Gateway create Chirp with the correct information' do
gateway_spy = spy
use_case = described_class.new(chirp_gateway: gateway_spy)
use_case.execute(title: 'Meow', body: 'Cat')
expect(gateway_spy).to have_received(:create) do |chirp|
expect(chirp.title).to eq('Meow')
expect(chirp.body).to eq('Cat')
end
end
end |
class Episode
include Mongoid::Document
include Mongoid::Timestamps::Short
field :title, type: String
field :artist, type: String
field :url, type: String
field :description, type: String
belongs_to :podcast
has_and_belongs_to_many :tags, inverse_of: nil
validates :title, presence: true
validates :url, presence: true
validates :url, :format => URI::regexp(%w(http https))
end
|
#---
# Excerpted from "Rails 4 Test Prescriptions",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information.
#---
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
test "a completed task is complete" do
task = Task.new
refute(task.complete?)
task.mark_completed
assert(task.complete?)
end
#
test "an uncompleted task does not count toward velocity" do
task = Task.new(size: 3)
refute(task.part_of_velocity?)
assert_equal(0, task.points_toward_velocity)
end
test "a task completed long ago does not count toward velocity" do
task = Task.new(size: 3)
task.mark_completed(6.months.ago)
refute(task.part_of_velocity?)
assert_equal(0, task.points_toward_velocity)
end
test "a task completed recently counts toward velocity" do
task = Task.new(size: 3)
task.mark_completed(1.day.ago)
assert(task.part_of_velocity?)
assert_equal(3, task.points_toward_velocity)
end
#
test "it finds completed tasks" do
Task.delete_all
complete = Task.create(completed_at: 1.day.ago, title: "Completed")
incomplete = Task.create(completed_at: nil, title: "Not Completed")
assert_equal([complete], Task.complete.to_a)
end
end
|
#encoding: utf-8
module Restfuls
class Canzhangs < Grape::API
#version 'v1',:using => :path
format :json
helpers CanzhangHelper
resource 'canzhang' do
desc '获取拥有残章的用户接口列表'
params do
requires :session_key,type: String,desc: "会话key"
requires :type,type: String,desc: "残章类型"
end
get '/get_list' do
get_list
end
post '/get_list' do
get_list
end
desc '上传抢夺残章结果接口'
params do
requires :session_key,type: String,desc: "会话key"
requires :type,type: String,desc: "残章类型"
requires :user_id,type: String,desc: "被抢夺的用户id"
requires :is_win,type: Integer,desc: "是否赢了"
end
get '/update_result' do
update_result
end
post '/update_result' do
update_result
end
desc "获取我拥有的残章列表"
params do
requires :session_key, type: String, desc: "会话key"
end
get '/get_my_canzhangs' do
get_my_canzhangs
end
post '/get_my_canzhangs' do
get_my_canzhangs
end
desc "更新残章接口"
params do
requires :session_key, type: String, desc: "会话key"
requires :canzhangs,type: Array,desc: "残章数组"
requires :id,type: Integer,desc: "残章记录id"
requires :number, type: Integer,desc: "残章数量"
end
get '/update_canzhangs' do
update_canzhangs
end
post '/update_canzhangs' do
update_canzhangs
end
desc "获取用户被夺残章信息"
params do
requires :session_key, type: String, desc: "会话key"
end
get '/get_grabbed_messages' do
get_grabbed_messages
end
post '/get_grabbed_messages' do
get_grabbed_messages
end
desc "创建一个用户的残章"
params do
requires :session_key, type: String, desc: "会话key"
requires :type, type: String, desc: "残章类型"
requires :number, type: Integer, desc: "残章的数量"
end
get '/create_canzhang' do
create_canzhang
end
post '/create_canzhang' do
create_canzhang
end
end
end
end
|
require 'rails_helper'
describe 'teams/index' do
let!(:teams) { create_list(:team, 4) }
it 'shows all teams' do
assign(:teams, Team.paginate(page: 1))
render
teams.each do |team|
expect(rendered).to include(team.name)
end
end
end
|
#!/usr/bin/env ruby
# coding: utf-8
require "rubygems"
require 'rb-fsevent'
LOG_CMD = %[git log --pretty="format:%C(yellow)%h%Cblue%d%Creset %s %C(white) %an, %ar%Creset" --graph --all]
def git_logger
rows, cols = `tput lines; tput cols`.scan(/\d+/).map(&:to_i)
`clear`
print `#{LOG_CMD} -#{rows} | sed -n '1, #{rows-2}p'`
puts "updated at #{Time.now.strftime("%H:%M:%S")}"
end
def on_change &block
FSEvent.new.tap {|fsevent|
fsevent.watch('.git', &block)
fsevent.run
}
end
abort("Run git_logger at the root of the git repo you'd like to watch.") if (ARGV & %w[-h --help help]).any?
abort("The current directory doesn't look like the root of a git repo.") unless File.directory?('.git')
git_logger
on_change { git_logger }
|
require File.dirname(__FILE__) + '/../test_helper'
class TestRangeMarker < Test::Unit::TestCase
def setup
@klass = Class.new(MockChart).class_eval { include GoogleChart::RangeMarker }
end
should 'not have range markers by default' do
assert_no_match(/\bchm=/, @klass.new.to_url)
end
should 'display horizontal range markers' do
assert_match(/\bchm=r,000000cc,x,0.45,0.55\b/, @klass.new(:ranges => [:h, 0.45, 0.55]).to_url)
end
should 'display vertical range markers' do
assert_match(/\bchm=R,000000cc,x,0.45,0.55\b/, @klass.new(:ranges => [:v, 0.45, 0.55]).to_url)
end
should 'display multiple range markers' do
assert_match(/\bchm=r,000000cc,x,0.1,0.2\|R,000000cc,x,0.3,0.4\b/, @klass.new(:ranges => [[:h, 0.1, 0.2], [:v, 0.3, 0.4]]).to_url)
end
should 'display range markers with custom colors' do
assert_match(/\bchm=r,abcdef,x,0.4,0.6\b/, @klass.new(:ranges => [:h, 'abcdef', 0.4, 0.6]).to_url)
end
end
|
class Stroll < ApplicationRecord
belongs_to :dogsitter
belongs_to :dog
end
|
class AddCashPossibilitiesToAccountWithdrawRequests < ActiveRecord::Migration[6.0]
def change
add_column :account_withdraw_requests, :cash_possibilities, :text, null: false
end
end
|
class UsersController < ApplicationController
def index
@users = User.all
end
def search
@users = User.user_search(params[:name])
render :index
end
def new
@user = User.new
@user.wings.build #nested attributes build for new view in user signup
end
def create
@user = User.new(user_params)
if @user.save
flash.notice = "You have successfully created an account"
session[:user_id] = @user.id
redirect_to @user
else
flash.alert = "Oh no, your account wasn't created, please correct errors"
render :new
end
end
def show
redirect_if_not_logged_in
@user = User.find_by_id(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password, wings_attributes: [:style, :flavor, :user_id, :restaurant_id])
end
end |
require "application_system_test_case"
class LeftoversTest < ApplicationSystemTestCase
setup do
@leftover = leftovers(:one)
end
test "visiting the index" do
visit leftovers_url
assert_selector "h1", text: "Leftovers"
end
test "creating a Leftover" do
visit leftovers_url
click_on "New Leftover"
fill_in "Date made", with: @leftover.date_made
fill_in "Meal recipe", with: @leftover.meal_recipe_id
fill_in "Portions", with: @leftover.portions
fill_in "Recipe", with: @leftover.recipe_id
fill_in "Stock level", with: @leftover.stock_level
fill_in "User", with: @leftover.user_id
click_on "Create Leftover"
assert_text "Leftover was successfully created"
click_on "Back"
end
test "updating a Leftover" do
visit leftovers_url
click_on "Edit", match: :first
fill_in "Date made", with: @leftover.date_made
fill_in "Meal recipe", with: @leftover.meal_recipe_id
fill_in "Portions", with: @leftover.portions
fill_in "Recipe", with: @leftover.recipe_id
fill_in "Stock level", with: @leftover.stock_level
fill_in "User", with: @leftover.user_id
click_on "Update Leftover"
assert_text "Leftover was successfully updated"
click_on "Back"
end
test "destroying a Leftover" do
visit leftovers_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Leftover was successfully destroyed"
end
end
|
class OrderedproductsController < ApplicationController
def index
find_order
@ops = Orderedproduct.where(order: @order)
end
def create
find_order
start_new_order if @order.nil?
op = Orderedproduct.find_by(product_id: params[:product_id], order_id: @order.id)
if op
op.quantity += 1
else
op = Orderedproduct.new(product_id: params[:product_id], order_id: @order.id, quantity: 1)
end
if op.save #may change this
flash[:status] = :success
flash[:result_text] = "Successfully added #{Product.find_by(id: op.product_id).name} to cart"
else
flash[:status] = :failure
flash[:result_text] = "Unable to add #{Product.find_by(id: op.product_id).name} to cart"
flash[:messages] = @product.errors.messages
end
redirect_to orderedproducts_path
end
def update
find_order
@op = Orderedproduct.find_by(id: params[:id], order_id: @order.id)
@op.update_attributes(op_params)
if @op.save
flash[:status] = :success
flash[:result_text] = "Successfully updated item quantity"
redirect_to orderedproducts_path
else
flash[:status] = :failure
flash[:result_text] = "Unable to add item to cart"
flash[:message] = @op.errors.messages
redirect_to orderedproducts_path
end
end
def destroy
find_order
ops = Orderedproduct.where(id: params[:id], order_id: @order.id)
if ops.empty?
head :not_found
else
flash[:status] = :success
flash[:result_text] = "Successfully deleted #{Product.find_by(id: ops.first.product_id).name} from cart"
ops.destroy_all
redirect_to orderedproducts_path
end
end
private
def op_params
return params.require(:orderedproduct).permit(:quantity)
end
def start_new_order
@order = Order.create(status: "pending")
session[:order_id] = @order.id
end
def find_order
@order = Order.find_by(id: session[:order_id])
end
end
|
class AddUnitOfMeasureIdToArticle < ActiveRecord::Migration
def change
add_column :articles, :unit_of_measure_id, :integer
end
end
|
require 'rails_helper'
RSpec.describe UsersController, :type => :controller do
let(:user) {create(:user)}
let(:user_2) {create(:user)}
login_user
it "should have a current_user" do
expect( subject.current_user).to be
end
describe '#index' do
it 'should assing the users variable' do
get :index
expect(assigns(:users)).to eq([user, user_2])
end
it 'renders json' do
user
user_2
get :index, format: 'json'
json = JSON.parse(response.body)
expect(json["users"].count).to eq(2)
end
it 'gets all when asked to' do
user
user_2
get :index, {all: true, format: 'json'}
json = JSON.parse(response.body)
expect(json["users"].count).to eq(3)
end
it 'gets without user when all: false' do
user
user_2
get :index, {all: false, format: 'json'}
json = JSON.parse(response.body)
expect(json["users"].count).to eq(2)
end
end
end |
#! /usr/local/bin/ruby
require 'coolio'
module Telnet
class ActionTimer < Coolio::TimerWatcher
def initialize interval, &action
super(interval)
@action = action
attach Server::Loop
end
def on_timer
detach
@action.call
end
end
class Server < Coolio::TCPSocket
Loop = Coolio::Loop.new
def on_connect
@buffer = ""
@prompt = "prompt>"
warn "Client connected."
send_prompt
end
def on_close
warn "Client disconnected."
end
def on_read data
@buffer << data
@buffer.each_line do |cmd|
cmd.chomp!
case cmd
when "foo"
warn "Client sent command #{cmd.inspect}."
write <<-OUT
>>>> foo output
OUT
send_prompt
warn "Sent output and prompt."
when "bar"
warn "Client sent command #{cmd.inspect}."
# ActionTimer.new 4 do
write <<-OUT
>>>> bar output
OUT
send_prompt
# end
when "quit"
warn "Client sent command #{cmd.inspect}."
close
else
warn "Client sent unknown command #{cmd.inspect}"
write <<-OUT
>>>> Unknown command #{cmd.inspect}.
OUT
send_prompt
end
end
@buffer = ""
end
def send_prompt
write @prompt
end
def warn str
#Kernel.warn "#{remote_addr}:#{remote_port} #{str}"
end
end
end
server = Coolio::TCPServer.new "localhost", 8000, Telnet::Server
server.attach Telnet::Server::Loop
Telnet::Server::Loop.run
|
require_relative './contact.rb' # ここでコネクトさせる。
require_relative './rolodex.rb'
class CRM
attr_reader :name
#名前の変数を他から読み込めるように編集。
def initialize(name)
@name = name #下から、crm = CRM.new("Bitmaker Labs CRM") が来る。そして、@nameに入る。
@rolodex = Rolodex.new #Rodex.newというvariableが、@rodexに含まれた。
# @rolodex = メソッドの名前となっていれば
# そのメソッドの処理が呼び出せる。
# Rolodex クラスを見てみると
# @contacts = [] という処理があるので
# これが行われる。
end
def print_main_menu
puts "[1] Add a contact"
puts "[2] Modify a contact"
puts "[3] Display all contacts"
puts "[4] Display one contact"
puts "[5] Display an attribute"
puts "[6] Delete a contact"
puts "[7] Exit"
puts "Enter a number:" # It is able to be displayed because of "put".
end
def main_menu
puts "Welcome to #{@name}" # ここでの値は、initializeからの値がやってくる。
while true #repeat because of While
print_main_menu
input = gets.chomp.to_i
return if input == 7 #Repeat until we can see 7,input==7 calls retuen, it can make this process stop.
choose_option(input) #The number which was ritten at input will be stored at (input) parameter.
end
end
def choose_option(option) #Above choose_option(input) bring values to (option).
case option #Inside of parameter (input),(option) already has a number, so the name of parameter is not matter.
when 1 then add_contact
when 2 then modify_contact # => to method modify_contact
when 3 then display_all_contacts
when 4 then display_contact #Idからどのコンタクトを表示させたいのか選ぶ? does it mean choosing contact from ID ?
when 5 then display_attribute # Does it mean just desplaying all last name or all first name or....
when 6 then delete_contact
else
puts "Invalid option. Try again!"
return
end
end
def add_contact # Because of calling 1
print "First Name: "
first_name = gets.chomp # To write a name.
print "Last Name: "
last_name = gets.chomp
print "Email: "
email = gets.chomp
print "Note: "
note = gets.chomp
contact = Contact.new(first_name, last_name, email, note)
# contact variable の定義。
#ここで、各contactの値を定義している。
#上のget.chompから各variableの値をゲットしている。
# this variable belongs to Rolodex class , so it calls any method inside of Rolodex class.
@rolodex.add_contact(contact) # is it coresponding with above contact variable ??
# @rolodex.add_contactこれに、,(contact)variableを代入。
# contactvariableは、59行目で定義されている。
# At this point we do not have to care about contact class coz already information is stored. At parameter
end
def display_all_contacts
@rolodex.contacts.each do |contact| #Dispray all information of content.
puts "#{contact.id} #{contact.first_name} #{contact.last_name} <#{contact.email}>"
end
end
def modify_contact
display_all_contacts #これで、上のメソッドを使用可能。
puts "please choose ID which you want to change."
id_to_change = gets.chomp.to_i
puts "Please choose which attribute you want to change."
puts "1 First Name, 2 Last name, 3 Email , 4 Note."
option = gets.chomp.to_i #convert string input to number.
case option
when 1 then
puts "Enter the new name."
new_name = gets.chomp
@rolodex.update_contact(id_to_change,new_name)
when 2 then
puts "Enter the new last name."
new_last_name = gets.chomp
@rolodex.update_contact_last(id_to_change,new_last_name) #id_to_change coeresponds to contact_id.
# @roledex is an instance variable, instance of Roledex class
# left side of . we have instance . class or variable.
when 3 then
puts "Enter the new email."
new_email = gets.chomp
@rolodex.update_contact_email(id_to_change,new_email)
#new_emailに新しく追加される値が代入される。
when 4 then
puts "Enter the new note."
new_note = gets.chomp
@rolodex.update_contact_note(id_to_change,new_note)
end
end
def display_contact
puts "please type your ID."
id_to_display = gets.chomp.to_i
@rolodex.display_contact(id_to_display)
end
def display_attribute
puts "Please choose which attribute you want to display."
puts "1 First Name, 2 Last name, 3 Email , 4 Note."
option_attribute = gets.chomp.to_i
case option_attribute
when 1
@rolodex.contacts.each do |contact|
puts "#{contact.first_name}"
end
when 2
@rolodex.contacts.each do |contact|
puts "#{contact.last_name}"
end
when 3
@rolodex.contacts.each do |contact|
puts "#{contact.email}"
end
when 4
@rolodex.contacts.each do |contact|
puts "#{contact.note}"
end
when 5
@rolodex.contacts.each do |contact|
puts "#{contact.id}"
end
end
end
def delete_contact
print "Enter the ID you wish to delete: "
id_delete = gets.chomp.id_to_display
@rolodex.delete_contact(id_delete)
end
end
crm = CRM.new("Bitmaker Labs CRM") # It will execute all processes.
crm.main_menu |
module WillPaginate
class PartialRenderer < (WillPaginate::VERSION::MAJOR == 2 ? WillPaginate::LinkRenderer : WillPaginate::ViewHelpers::LinkRenderer)
def prepare(collection, options, template)
@collection = collection
@options = options
@template = template
if WillPaginate::VERSION::MAJOR == 2
if !@template.respond_to?(:url_for_page)
m = method(:url_for)
@template.instance_eval do |cl|
@url_for_page = m
def url_for_page(page)
@url_for_page.call page
end
end
end
else
if !@template.respond_to?(:url_for_page)
@template.instance_eval do |cl|
def url_for_page(page)
@template.url_for(:page => page)
end
end
end
end
end
def to_html
locals = {
:first_page => 1,
:last_page => @collection.total_pages,
:previous_page => @collection.previous_page,
:next_page => @collection.next_page,
:total_pages => @collection.total_pages,
:current_page => @collection.current_page,
:per_page => @collection.per_page,
:options => @options
}
@template.render :partial => @options[:partial], :locals => locals
end
end
end
WillPaginate::ViewHelpers::pagination_options[:renderer] = 'WillPaginate::PartialRenderer'
WillPaginate::ViewHelpers::pagination_options[:partial] = '/pagination'
|
class Squares
def initialize(number)
@number = number
end
def square_of_sums
n = 1
x = 0
while n <= @number
x = x + n
n = n + 1
end
x**2
end
def sum_of_squares
n = 1
x = 0
while n <= @number
x = x + n**2
n = n + 1
end
x
end
def difference
self.square_of_sums - self.sum_of_squares
end
end |
module JbuilderSerializer
class Base
attr_reader :data, :json
def initialize(data)
@data = data
@json = Builder.new
build
end
def build
end
def to_hash
json.attributes!
end
def to_json
json.target!
end
def method_missing(method, *args)
data[method] || nil
end
end
end
|
# frozen_string_literal: true
class LessonPolicy < ApplicationPolicy
def index?
true
end
def show?
user.global_role? || user_in_lesson_org?
end
def create?
user.global_administrator? || user.is_admin_of?(lesson_organization) || user.is_teacher_of?(lesson_organization)
end
class Scope < ApplicationPolicy::Scope
def resolve
return scope.all if user.global_role?
scope.joins(group: :chapter).where(chapters: { organization_id: user.roles.select(:resource_id) }).distinct
end
end
private
def user_in_lesson_org?
user.roles.pluck(:resource_id).include? record.group.chapter.organization_id
end
def lesson_organization
record.group.chapter.organization
end
end
|
ActiveRecord::ConnectionAdapters::PostgreSQLColumn.class_eval do
def spatial?
type == :spatial || type == :geography
end
end
|
require_relative '../phase5/controller_base'
require_relative 'csrf'
module Phase6
class ControllerBase < Phase5::ControllerBase
include CSRFProtector
# use this with the router to call action_name (:index, :show, :create...)
def invoke_action(name)
self.send(name)
render(name) unless @already_built_response
end
def flash
@flash ||= Flash.new(@req)
end
def redirect_to(url)
super(url)
flash.store_session(@res)
end
def render_content(content, type)
super(content, type)
flash.store_session(@res)
end
end
class Flash
def initialize(req)
cookie = req.cookies.find { |cookie| cookie.name == '_rails_lite_flash' }
if cookie
@contents = JSON.parse(cookie.value)
@contents.each do |key, arr|
@contents[key] = [arr[0], arr[1] + 1]
end
else
@contents = {}
end
end
# grab only the value, not the counter
def [](key)
@contents[key][0] if @contents[key]
end
# set value and number of requests it has lived with
def []=(key, val)
@contents[key] = [val, 0]
end
def now(key, val)
@contents[key] = [val, 1]
end
# serialize the hash into json and save in a cookie
# add to the responses cookies
def store_session(res)
@contents.each do |key, arr|
if @contents[key][1] == 1
@contents.delete(key)
end
end
res.cookies << WEBrick::Cookie.new('_rails_lite_flash', @contents.to_json)
end
end
end
|
describe 'Link.read :comments' do
it "throws :not_found if POST is marked PRIVATE" do
WORLD!
sn.posts({}) {
aud.comments 'I am audience member.'
sn.comments 'I am owner.'
is :PRIVATE
}
catch(:not_found) {
aud.reads(:COMMENTS).of(sn.post)
}[:type].should == :READ_POST
end
it "does not list comments by authors BLOCKED by POST owner/screen_name" do
WORLD!
sn.posts({}) {
friend.comments 'I am friend.'
meanie.comments 'I am no-friend.'
}
sn.blocks meanie
STRANGER.reads(:COMMENTS).of(sn.post).map(&:id).should == [friend.comment.id]
end
it "does not list comments by authors BLOCKed by AUDIENCE member" do
WORLD!
sn.posts({}) {
friend.comments 'I am friend.'
meanie.comments 'I am meanie.'
}
aud.blocks meanie
aud.reads(:comments).of(sn.post).map(&:id).should == [friend.comment.id]
end
it "does not list comments by authors who BLOCKed the AUDIENCE member" do
WORLD!
sn.posts({}, :WORLD) {
friend.comments 'I am friend.'
meanie.comments 'I am meanie.'
}
friend.blocks aud
aud.reads(:COMMENTS).of(post).map(&:id).should == [meanie.comment.id]
end
end # === describe 'Link.read :comments'
|
class PlayerListener
java_implements InputListener
def initialize(player)
@player = player
end
def keyDown(keycode)
@player.keyDown(keycode)
return true
end
def keyUp(keycode)
@player.keyUp(keycode)
return true
end
def keyTyped(char)
return false
end
def mouseMoved(x, y)
return false
end
def scrolled(amount)
return false
end
def touchDown(x, y, pointer, button)
puts x, y
return true
end
def touchDragged(x, y, pointer)
return false
end
def touchUp(x, y, pointer, button)
return false
end
end |
module ImagesHelper
def image_uploader form, options = {}
attr_name = (options[:attr_name] or :image)
class_name = (options[:class_name] or attr_name)
value = form.object.send(attr_name)
image_preview = image_tag (value.present? ? value : ''), class: 'image-preview'
file_input = form.file_field attr_name, class: 'image-file', accept: 'image/jpg, image/jpeg, image/png'
if options[:no_remove]
remove_input = ''
remove_button = ''
else
remove_input = form.hidden_field "remove_#{attr_name}", class: 'image-remove'
remove_button = icon_close
end
errors = form.error(attr_name)
raw %{
<div class="image-uploader #{class_name}-uploader">
#{image_preview}
#{file_input}
#{remove_input}
#{remove_button}
</div>
#{errors}
}
end
def cover_uploader f
image_uploader f, attr_name: 'cover'
end
end
|
class UsersController < ApplicationController
before_action :authenticate_user!,only: :show
def show
@user = User.find(params[:id])
render = 'users/show'
end
end
|
# Sessions controller
# used to sign a user in and out
class SessionsController < ApplicationController
skip_before_action :require_login, except: %w[destroy]
layout false
def new
@user = User.new
end
def create
if (@user = login(params[:email], params[:password], params[:remember_me]))
redirect_back_or_to root_path, success: "Welcome #{@user.full_name}"
else
flash.now[:error] = _('Login failed')
render :new
end
end
def destroy
logout
redirect_to root_path, success: _('Logged out successfully')
end
end
|
require_relative '../wiremock/wiremock'
require_relative 'util/mime_type_helper'
require_relative 'util/base_rest_client'
module ScopedWireMock
CORRELATION_KEY_HEADER = 'x-sbg-messageTraceId'
PROXY_UNMAPPED_ENDPOINTS = 'automation.proxy.unmapped.endpoints'
class ScopedWireMockClient < ScopedWireMock::Util::BaseRestClient
include WireMock
attr_reader :host, :port
def initialize(base_url)
super base_url
@correlation_paths=[]
@host=URI.parse(base_url).host
@port=URI.parse(base_url).port
end
def start_new_global_scope( run_name: 'test_run',
wiremock_public_url: ,
integration_scope: 'all',
url_of_service_under_test: ,
global_journal_mode: 'NONE',
payload:{})
opts = {runName: run_name,
wireMockPublicUrl: wiremock_public_url,
integrationScope: integration_scope,
urlOfServiceUnderTest:url_of_service_under_test ,
globalJournaMode: global_journal_mode,
payload:payload}
execute(wire_mock_base_url + '/__admin/global_scopes/start', :post, opts)
end
def reset_all()
execute(wire_mock_base_url + '/__admin/reset_all_scopes', :delete, {})
end
def stop_global_scope(run_name: 'test_run',
wiremock_public_url: ,
sequence_number: ,
url_of_service_under_test: ,
payload: {})
opts = {runName: run_name,
wireMockPublicUrl: wiremock_public_url,
sequenceNumber: sequence_number,
urlOfServiceUnderTest:url_of_service_under_test ,
payload:payload}
execute(wire_mock_base_url + '/__admin/global_scopes/stop', :post, opts)
end
def start_nested_scope(parent_correlation_path, name, payload)
execute(wire_mock_base_url + '/__admin/scopes/start', :post, {
:parentCorrelationPath=>parent_correlation_path,
:name => name,
:payload=>payload
})
end
def stop_nested_scope(scope_path,payload)
execute(wire_mock_base_url + '/__admin/scopes/stop', :post, {
:correlationPath=>scope_path,
:payload=>payload
})
end
def start_user_scope(parent_correlation_path, name, payload={})
execute(wire_mock_base_url + '/__admin/user_scopes/start', :post, {
:parentCorrelationPath=>parent_correlation_path,
:name => name,
:payload=>payload
})
end
def get_correlated_scope(scope_path)
execute(wire_mock_base_url + '/__admin/scopes/get', :post, {'correlationPath' => scope_path})
end
def register(extended_mapping_builder)
execute(wire_mock_base_url + '/__admin/extended_mappings', :post, extended_mapping_builder.build)
end
#LEGACY
def sync_correlated_scope(correlation_state)
execute(wire_mock_base_url + '/__admin/scopes/sync', :post, correlation_state)
end
#Step management
def start_step(scope_path, name, payload={})
execute(wire_mock_base_url + '/__admin/scopes/steps/start', :post, {'correlationPath' => scope_path, 'currentStep' => name,'payload' => payload})
end
def stop_step(scope_path, name,payload={})
execute(wire_mock_base_url + '/__admin/scopes/steps/stop', :post, {'correlationPath' => scope_path, 'currentStep' => name,'payload' => payload})
end
def find_exchanges_against_step(scope_path, name)
execute(wire_mock_base_url + '/__admin/scopes/steps/find_exchanges', :post, {'correlationPath' => scope_path, 'currentStep' => name})
end
#Others
def get_mappings_in_scope(scope_path)
execute(wire_mock_base_url + '/__admin/scopes/mappings/find', :post, {'correlationPath' => scope_path})
end
def wire_mock_base_url
'http://' + @host +':' + @port.to_s
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + "/../lib/object_repository")
module Error
include ObjectRepository
def verifyError
open("/random")
assert isTextPresent("Looking for something on SimonandSchuster.com?")
assert isTextPresent("The page you requested was not found. You may have used an outdated link or typed the address (URL) incorrectly.")
assert isTextPresent("If you feel you have received this message in error, please take a moment to contact us.")
assert isElementPresent("link=contact us")
assert isTextPresent("Please try one of the following:")
assert isTextPresent("Check the Web address you entered to make sure that it's correct.")
assert isTextPresent("Try to access the page directly from the SimonandSchuster.com homepage, instead of using a bookmark. If the page has moved, reset your bookmark.")
assert isElementPresent("link=homepage")
# Defect raised for the below comment- arun
# assert isTextPresent("Browse for authors or books.")
assert isElementPresent("link=authors")
assert isElementPresent("link=books")
end
end |
class Heap
def initialize
@size = 0
@root = nil
@array = Array.new # let ruby manage resizing, etc
end
def insert(*values)
values.each do |value|
@array[@size] = value
self.class.upheap(@size, @array)
@size += 1
end
end
def delete_min
min = @array[0]
@size -= 1
@array[0] = @array[@size]
@array[@size] = nil
self.class.downheap(0, @array, @size)
return min
end
def min
@array[0]
end
def self.downheap(index, array, size)
while index * 2 < size
child = index * 2
# try to switch with the smaller child
child += 1 if array[child + 1] and array[child + 1] < array[child]
if array[child] < array[index]
array[child], array[index] = array[index], array[child]
index = child
else
break
end
end
end
def self.upheap(index, array)
parent = index / 2
while index > 0 and array[parent] > array[index]
array[parent], array[index] = array[index], array[parent]
index = parent
parent = index / 2
end
end
def self.heapsort(array)
size = array.size
# heap construction
mid = size / 2
mid.downto(0).each do |index|
downheap(index, array, size)
end
# sortdown
while size > 0
size -= 1
array[0], array[size] = array[size], array[0]
downheap(0, array, size)
end
return array
end
end
|
#!/usr/local/bin/ruby
require 'lib/vhod_backup/ftp_setup'
FTP, RAILS_ROOT, REPOSITORY_BASE = FtpSetup.setup(ARGV)
$stdout.sync = true
END {
FtpSetup.teardown(FTP)
}
def recovery_db
measure("Database recovery in proccess...") {
FTP.restore_from_backup("db")
begin
Dir.chdir("/tmp#{RAILS_ROOT}db") {
`gunzip *.gz`
filename = Dir.entries(".").select{|file| file.match "vhod_redmine"}[0]
`mysql -uvhod_redmine -pvhod_redmine vhod_redmine < #{filename}`
`rm redmine*.sql`
}
rescue
raise DatabaseRevertingError, "Can not revert database dump"
end
}
end
def recovery_repositories
measure("Repositories reverting in proccess...") do
list = FTP.get_repositories_list
list.each do |repname|
FTP.download_repository(repname)
rep = MySvn::Repository.create(REPOSITORY_BASE + repname)
Dir.foreach("/tmp#{REPOSITORY_BASE}") do |repdir|
unless repdir == '.' || repdir == '..'
next if File.exists?(REPOSITORY_BASE + repdir)
Dir.entries("/tmp" + REPOSITORY_BASE).sort.each do |file|
unless file == '.' || file == '..'
puts "reverting data : " + repname + ": " + file
rep.load! "/tmp" + REPOSITORY_BASE + file
end
end
end
end
`rm -rf /tmp/#{REPOSITORY_BASE}`
end
end
end
def recovery_files
measure("Files recovery in proccess...") {FTP.restore_from_backup("files")}
end
if $0 == 'tasks/recovery_all.rb'
measure("Recovery all data ...\n") do
recovery_db
recovery_repositories
recovery_files
end
end
|
source 'http://rubygems.org'
gem 'rails', '3.0.3'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
# change to prevent heroku from trying to load the sqlite3-ruby gem
gem 'sqlite3-ruby', :group => :development #:require => 'sqlite3'
# gem to handle each user’s Gravatar which is a 'globally recognized avatar'
gem 'gravatar_image_tag', '0.1.0'
# gem to enable list paging
gem 'will_paginate', '3.0.pre2'
# SSL requirement gem adds a declarative way of specifying that certain actions
# should only be allowed to run under SSL, and if they're accessed without it, they should be redirected.
#gem 'ssl_requirement', :group => :development
#
# include the gems for RSpec and the RSpec library specific to Rails
#
# include rspec in development mode for access to the RSpec-specific generators
# include gem to annotate models in development (not needed in production applications)
# include facker gem to all creation of sample users
group :development do
gem 'rspec-rails', '2.0.1'
gem 'annotate-models', '1.0.4'
gem 'faker', '0.3.1'
end
# include rspec in test mode in order to run tests
# include factory girl in order to create factories
# which are a convenient way to define objects and insert them into our test database
group :test do
gem 'rspec', '2.0.1'
gem 'webrat', '0.7.1'
gem 'factory_girl_rails', '1.0'
# needed to run 'bundle exec autotest'
gem 'autotest'
gem 'autotest-growl'
gem 'autotest-notification'
gem 'autotest-rails-pure'
end
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
|
module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def log_out
session.delete(:user_id)
@current_user = nil
end
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in? #interrogação significa que é uma função booleana, retorna true ou false
!current_user.nil?
end
end
|
class ProductMailer < ApplicationMailer
default from: "alice.advocate@gmail.com"
default to: "alice.advocate@gmail.com"
def contact_email(product, body)
@body = body
# mail to: product.user.email, subject: "User request for \"#{product.name}\""
mail subject: "User request for \"#{product.name}\""
end
end |
# Encoding: UTF-8
require_relative '../spec_helper'
describe 'steam::default' do
let(:runner) { ChefSpec::SoloRunner.new }
let(:chef_run) { runner.converge(described_recipe) }
it 'installs Steam' do
expect(chef_run).to install_steam_app('default')
end
end
|
class DepartmentsController < ApplicationController
def index
@departments = Department.all
end
def show
@department = Department.find(params[:id])
@sections = @department.sections
end
end |
require "json"
class RackspaceDriver < Provider
PROVIDER = 'Rackspace'
PROVIDER_ID = 39
LOG_PROVIDER = 'rackspace'
MAXJOBS = 1
LOGIN_AS = 'root'
IDENTURL = 'https://identity.api.rackspacecloud.com/v2.0/tokens'
DEFIMAGE = '28153eac-1bae-4039-8d9f-f8b513241efe' # Unbuntu 14.04 PVHVM
@authlocs = {}
def self.get_active loc, all, &block
srvs = list_servers loc
srvs['servers'].each do |server|
state = server['status']
id = server['id']
ip = server['accessIPv4']
name = server['name']
if state == 'ACTIVE' or all
yield id, name, ip, state
end
end
end
def self.delete_server name, id, loc, flavor
self._delete_server id, loc
nil
end
def self.create_server name, scope, flavor, loc
loc = loc.upcase
keyname = flavor['keyname']
image = flavor['imageid']
image = DEFIMAGE if image.blank?
instance = flavor['flavor'].to_s
createvol = false
if instance.start_with? "compute1-" or instance.start_with? "memory1-"
createvol = true
end
server = self._create_server name, scope, instance, loc, keyname, image, createvol
if server.nil? or ! server['server']
log "can't create #{name}: #{server}"
return nil
end
rv = {}
rv[:id] = server['server']['id']
if keyname.blank?
rv[:pass] = server['server']['adminPass']
end
nretry = 30
while nretry > 0 do
sleep 10
s = self.fetch_server rv[:id], loc
if s.nil? or ! s['server']
log "bad fetch_server: #{s}"
return nil
end
log "#{name} status: #{s['server']['status']}" if @verbose > 0
begin
if s['server']['status'] == 'ACTIVE'
rv[:ip] = s['server']['accessIPv4']
break
end
rescue Exception => e
log "server=#{s}"
end
nretry -= 1
end
if nretry <= 0
log "ERROR: timed out creating #{name}"
return nil
end
sleep 10
rv
end
def self.get_keys loc
if loc.upcase != 'LON'
rv = super({:rackspace_api_username => nil, :rackspace_api_key => nil}, loc)
rv[:username] = rv[:rackspace_api_username]
rv.delete :rackspace_api_username
rv[:apiKey] = rv[:rackspace_api_key]
rv.delete :rackspace_api_key
else
rv = super({:rackspace_lon_api_username => nil, :rackspace_lon_api_key => nil}, loc)
rv[:username] = rv[:rackspace_lon_api_username]
rv.delete :rackspace_lon_api_username
rv[:apiKey] = rv[:rackspace_lon_api_key]
rv.delete :rackspace_lon_api_key
end
rv
end
def self.curlauth method, loc, endpoint=nil
auth = self.get_auth loc
rv = "curl -X #{method} -H \"X-Auth-Token: #{auth[:token]}\" -H \"Content-Type: application/json\" "
rv += " #{auth[endpoint]}" if endpoint
end
def self.get_auth loc
if @authlocs[loc]
return @authlocs[loc]
end
cmd = "curl -X 'POST' -s #{IDENTURL} -d '{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\": #{JSON.generate(get_keys(loc))}}}' -H \"Content-Type: application/json\""
authjs = `#{cmd}`
# XXX
begin
auth = JSON.parse (authjs)
rescue Exception => e
log "can't get rs auth: #{cmd}"
log "rv: #{authjs}"
raise e
end
if auth['access'].nil?
log "can't get rs auth: #{cmd}"
log "rv: #{authjs}"
raise e
end
rv = { token: auth['access']['token']['id']}
dnsendpoint = storageendpoint = serverendpoint = nil
dnstenant = storetenant = servertenant = nil
auth['access']['serviceCatalog'].each do |service|
if service['name'] == 'cloudBlockStorage'
service['endpoints'].each do |ep|
next if ep['region'] != loc
rv[:storagetenant] = ep['tenantId']
rv[:storageendpoint] = ep['publicURL']
break
end
elsif service['name'] == 'cloudServersOpenStack'
service['endpoints'].each do |ep|
next if ep['region'] != loc
rv[:servertenant] = ep['tenantId']
rv[:serverendpoint] = ep['publicURL']
break
end
elsif service['name'] == 'cloudDNS'
service['endpoints'].each do |ep|
rv[:dnstenant] = ep['tenantId']
rv[:dnsendpoint] = ep['publicURL']
break
end
end
end
@authlocs[loc] = rv
end
def self.execcmd cmd
begin
out = `#{cmd}`
if out.blank?
log "empty output for: #{cmd}"
return nil
end
rv = JSON.parse(out)
rescue Exception => e
log "error: #{e.message}"
log "cmd= #{cmd}"
nil
end
rv
end
def self.list_domains
cmd = "#{curlauth('GET', "DFW", :dnsendpoint)}/domains/ 2>/dev/null"
execcmd cmd
end
def self.domainid domain
domains = list_domains
return nil if domains.nil?
domains['domains'].each do |d|
if d['name'] == domain
@curdomain = d
return d['id']
end
end
nil
end
def self.add_dns domain, label, ip, ttl=300
id = domainid domain
req = { records: [{
name: "#{label}.#{domain}",
type: "A",
data: ip,
ttl: ttl
}]
}
cmd = "#{curlauth('POST', "DFW", :dnsendpoint)}/domains/#{id}/records -d '#{JSON.generate(req)}' 2>/dev/null"
execcmd cmd
end
def self.fetch_dns domain, label
id = domainid domain
cmd = "#{curlauth('GET', "DFW", :dnsendpoint)}/domains/#{id}/records 2>/dev/null"
rv = execcmd cmd
return nil if rv.nil?
rv['records'].each do |r|
return r if r['name'] == "#{label}.#{domain}"
end
nil
end
def self.del_dns domain, label
r = fetch_dns domain, label
return nil if r.nil?
cmd = "#{curlauth('DELETE', "DFW", :dnsendpoint)}/domains/#{@curdomain['id']}/records/#{r['id']} 2>/dev/null"
execcmd cmd
end
def self.list_volumes loc
cmd = "#{curlauth('GET', loc, :storageendpoint)}/volumes 2>/dev/null"
execcmd cmd
end
def self.list_volume uuid, loc
cmd = "#{curlauth('GET', loc, :storageendpoint)}/volumes/#{uuid} 2>/dev/null"
execcmd cmd
end
def self.fetch_volume id, loc
cmd = "#{curlauth('GET', loc, :storageendpoint)}/volumes/#{id} 2>/dev/null"
execcmd cmd
end
def self.create_volume name, image, loc
req = {
volume: {
display_name: "perf-#{name}",
imageRef: image,
availability_zone: nil,
volume_type: "SSD",
display_description: nil,
snapshot_id: nil,
size: 50
}
}
cmd = "#{curlauth('POST', loc, :storageendpoint)}/volumes -d '#{JSON.generate(req)}' 2>/dev/null"
rv = execcmd cmd
uuid = rv['volume']['id']
log "uuid of new volume: #{uuid}"
nretry = 30
while nretry > 0
sleep 10
r = fetch_volume uuid
if r['volume'].nil?
log "ignoring volume create message: vol=#{r}" unless r['itemNotFound']
elsif r['volume']['status'] == 'available'
break
else
log "#{uuid}: #{r['volume']['status']}" if @verbose > 0
end
nretry -= 1
end
return rv
end
def self.delete_volume vol, loc
name = vol['display_name'] || vol['id']
cmd = "#{curlauth('DELETE', loc, :storageendpoint)}/volumes/#{vol['id']} 2>/dev/null"
retrycnt = 20
while retrycnt > 0
rv = execcmd cmd
if rv['badRequest']
if rv['badRequest']['message'] == "Invalid volume: Volume status must be available or error, but current status is: in-use"
sleep 10
retrycnt -= 1
else
return nil
end
else
break
end
end
if retrycnt == 0
return nil
end
rv
end
def self.list_servers loc
cmd = "#{curlauth('GET', loc, :serverendpoint)}/servers/detail 2>/dev/null"
execcmd cmd
end
def self._create_server name, scope, instance, loc, keyname=nil, image=nil, createvol=false
image = DEFIMAGE if image.nil?
req = {
server: {
name: name,
imageRef: image,
flavorRef: instance,
max_count: 1, # xxx don't know what these do, and rs dox suck
min_count: 1, # xxx
}
}
if createvol
req[:server][:imageRef] = nil
storage = scope['storage'] || 20
storage = 50 if storage < 50
req[:server][:block_device_mapping_v2] = [{ delete_on_termination: true,
boot_index: '0',
destination_type: 'volume',
uuid: image,
source_type: 'image',
volume_size: storage,
}]
end
req[:server][:key_name] = keyname unless keyname.blank?
networks = [
{ uuid: "00000000-0000-0000-0000-000000000000" },
{ uuid: "11111111-1111-1111-1111-111111111111" }
]
req[:server][:networks] = networks
cmd = "#{curlauth('POST', loc, :serverendpoint)}/servers -d '#{JSON.generate(req)}' 2>/dev/null"
execcmd cmd
end
def self.fetch_server id, loc
cmd = "#{curlauth('GET', loc, :serverendpoint)}/servers/#{id} 2>/dev/null"
execcmd cmd
end
def self._delete_server id, loc
cmd = "#{curlauth('DELETE', loc, :serverendpoint)}/servers/#{id} 2>/dev/null"
rv = `#{cmd}`
end
end
|
class User < ApplicationRecord
has_secure_password
has_many :organized_events, foreign_key: "organization_id", class_name: "Event"
has_many :commented_comments, foreign_key: "organization_id", class_name: "Comment"
has_many :being_commented_comments, foreign_key: "volunteer_id", class_name: "Comment"
has_many :joined_events, through: :being_commented_comments, :source => :event
validates :name, :email, presence: true
validates :email, uniqueness: true
validates :email, confirmation: true
scope :is_organization, -> { where(is_organization: true) }
scope :is_not_organization, -> { where(is_organization: false) }
end
|
class AddColumnToProfessional < ActiveRecord::Migration
def change
add_column :professionals, :code_tuition, :string
end
end
|
class User < ActiveRecord::Base
include Plivo
validates :name, :default_ddd, presence: true
validate :ddd_range
validates_uniqueness_of :email
validates :default_bday_msg, presence: true, if: "bday_msg == true"
validates :default_bill_msg, presence: true, if: "bill_msg == true"
validates :default_bday_msg, :default_bill_msg, length: { maximum: 160 }
validate :ascii_msg
has_many :contacts, dependent: :destroy
has_many :tags, dependent: :destroy
has_many :notifications, dependent: :destroy
before_save :initialize_settings
store_accessor :settings, :default_ddd, :default_bday_msg, :default_bill_msg, :bill_msg, :bday_msg, :days_send_bill_msg
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def initialize_settings
self.default_ddd = 75 if self.default_ddd.nil?
self.bill_msg = "false" if self.bill_msg.nil?
self.bday_msg = "false" if self.bday_msg.nil?
# self.bday_msg = "false"
end
def ascii_msg
if default_bday_msg #check if it's nil
errors.add(:default_bday_msg, "não pode ter acentos, cedilhas") unless default_bday_msg.ascii_only?
end
if default_bill_msg
errors.add(:default_bill_msg, "não pode ter acentos, cedilhas") unless default_bill_msg.ascii_only?
end
end
def ddd_range
unless default_ddd.nil?
errors.add(:default_ddd, "Deve ser entre 11 e 99") unless (11..99).to_a.include?(default_ddd.to_i)
end
end
def bill_msg
return (super == "true") if %w{true false}.include? super
super
end
def bday_msg
return (super == "true") if %w{true false}.include? super
super
end
def balance_transfer(target_user, balance)
if target_user.admin?
target_user.balance += balance.to_i
elsif self.balance >= balance.to_i
self.balance -= balance.to_i
target_user.balance += balance.to_i
end
end
def deduct_balance(msgs)
result = self.balance - msgs
self.update(balance: result)
end
def count_birthday
count = 0
self.contacts.each do |contact|
unless contact.birthday.nil?
count+=1 if contact.birthday_today?
end
end
count
end
def search_recipients(search)
if search.downcase == "todos"
return formatted_all_contacts
end
result = search_tag(search)
if result.any?
formatted_tag(result)
else
result = search_contact(search)
formatted_contact(result)
end
end
def search_contact(search)
#if returns nil query is an empty array
query = search.try(:split, " ") || []
if (query.length < 2)
self.contacts.where([ "lower(name) LIKE ? OR lower(last_name) LIKE ?", "%#{search}%".downcase, "%#{search}%".downcase])
else
name = search.split(" ").first
last_name = search.split(" ").last
self.contacts.where([ "lower(name) LIKE ? AND lower(last_name) LIKE ?", "%#{name}%".downcase, "%#{last_name}%".downcase])
end
end
def search_tag(search)
self.tags.where([ "lower(name) LIKE ?", "%#{search}%".downcase])
end
def formatted_all_contacts
all_contact = {name: "todos", phone: process_contact(self.contacts), id:0, count: self.contacts.count}
[all_contact]
end
def formatted_tag(tags)
tag_array = []
tags.each do |elem|
hash = {name: elem.name, phone: process_contact(elem.contacts), id:elem.id, count: elem.contacts.count}
tag_array.push(hash)
end
tag_array
end
def formatted_contact(contacts)
contact_array = []
contacts.each do |contact|
hash = {name: contact.full_name, phone: contact.full_number, id: contact.id}
contact_array.push(hash)
end
contact_array
end
private
def process_contact(contacts)
contacts.inject([]){|phone_string, contact| phone_string << contact.full_number }
end
end
|
class Pltt::GitlabWrapper
def initialize(url, token, project)
require 'gitlab'
@project = project
Gitlab.endpoint = url
Gitlab.private_token = token
end
def issues(scope: 'assigned-to-me', order_by: 'updated_at', state: 'opened', label: nil)
Gitlab.issues(@project, state: state, order_by: order_by, scope: scope, labels: label ? label : nil).auto_paginate
end
def issue(id, project: @project)
Gitlab.issue(project, id)
end
def create_issue(title, description, labels)
user_id = Gitlab.user.id
Gitlab.create_issue(@project, title, description: description, labels: labels.join(','), assignee_ids: [user_id])
end
def set_issue_state_label(iid, label)
note = ['state:doing', 'state:next', 'state:done', 'state:planning', 'P-Parkplatz'].map { |i|
if label == i
%{/label ~"#{i}"}
else
%{/unlabel ~"#{i}"}
end
}.join("\n")
create_issue_note(iid, note)
end
def create_issue_note(iid, content)
Gitlab.create_issue_note(@project, iid, content)
end
def labels
Gitlab.labels(@project)
end
def create_branch_and_merge_request(branch_name, issue)
Gitlab.create_branch(@project, branch_name, 'master')
Gitlab.create_merge_request(@project, "Resolve #{issue.title}",
source_branch: branch_name,
target_branch: 'master',
description: "Closes ##{issue.iid}",
remove_source_branch: true)
end
def add_time_spent_on_issue(project, issue_id, duration)
Gitlab.add_time_spent_on_issue(project, issue_id, duration)
end
end
|
json.array!(@reads) do |read|
json.extract! read, :id, :name, :book, :synopsis
json.url read_url(read, format: :json)
end
|
#!/usr/bin/env ruby
require 'oml4r'
#puts OML4R::VERSION
# Define your own Measurement Points
class SinMP < OML4R::MPBase
name :sin
param :label
param :angle, :type => :int32
param :value, :type => :double
end
class CosMP < OML4R::MPBase
name :cos
param :label
param :value, :type => :double
end
# Initialise the OML4R module for your application
# 'collect' could also be tcp:host:port
opts = {:appName => 'generator', :domain => 'foo', :collect => 'file:-'}
begin
OML4R::init(ARGV, opts)
rescue OML4R::MissingArgumentException => mex
$stderr.puts mex
exit
end
freq = 2.0 # Hz
inc = 15 # rad
# Now collect and inject some measurements
500.times do |i|
sleep 1./freq
angle = inc * i
SinMP.inject("label_#{angle}", angle, Math.sin(angle))
CosMP.inject("label_#{angle}", Math.cos(angle))
end
# Don't forget to close when you are finished
OML4R::close()
|
class CreateGuestUserSurveyTemplates < ActiveRecord::Migration
def change
create_table :guest_user_survey_templates do |t|
t.integer :survey_template_id
t.integer :guest_user_id
t.string :email_secure_token
t.boolean :accessed, :default => false
t.timestamps
end
end
end
|
class EmailLogParser
def initialize file
@log = open(file).read.split /\n/
@mails = {}
parse
end
def parse
@log.each do |line|
# Get the date, message id, and data from the line.
match = line.match /^([^ ]+ [^ ]+ [^ ]+) [^ ]+ [^ ]+ ([^ ]+): (.*)$/
# match[1] is the date/time, match[2] is the ID, match[3] is the
# rest of the information that we will continue parsing.
@mails[match[2]] ||= {}
@mails[match[2]].store :date, match[1]
# Initialize 'to' to a list, so it can store multiple addresses.
@mails[match[2]][:to] ||= []
subparse match[2], match[3]
end
end
def subparse id, data
data.split(', ').each do |attr|
# to
match = attr.match /^to=<(.+)>$/
if match != nil
@mails[id][:to].push match[1]
end
# from
match = attr.match /^from=<(.+)>$/
if match != nil
@mails[id].store :from, match[1]
end
# size
match = attr.match /^size=(\d+)$/
if match != nil
@mails[id].store :size, match[1]
end
end
end
def mails
@mails
end
def length
@mails.length
end
end
|
class ChangeDateDataTypeOnEventsTabletoString < ActiveRecord::Migration[5.2]
change_column :events, :date, :string
def change
end
end
|
require 'puppet/parameter/boolean'
require_relative '../../puppet_x/century_link/property/custom_field'
require_relative '../../puppet_x/century_link/property/read_only'
Puppet::Type.newtype(:clc_network) do
desc 'CenturyLink cloud network'
ensurable
newparam(:name) do
desc 'Name of the group'
validate do |value|
fail 'name should be a string' unless value.is_a?(String)
fail 'group must have a name' if value.strip == ''
end
end
newproperty(:description) do
desc 'User-defined description of this group'
end
newparam(:datacenter) do
desc 'Parent data center'
validate do |value|
fail 'datacenter should be a string' unless value.is_a?(String)
fail 'group must have a datacenter' if value.strip == ''
end
end
newproperty(:id, parent: PuppetX::CenturyLink::Property::ReadOnly) do
desc 'The CLC generated id for the network'
end
end
|
require 'rails_helper'
describe "Showing the list of songs" do
let!(:song1) { create :song, title: "Title 1" }
let!(:song2) { create :song, title: "Title 2" }
let!(:song3) { create :song, title: "Silly Title" }
it "shows all his songs" do
visit songs_url
expect(page).to have_text("Title 1")
expect(page).to have_text("Title 2")
end
end
|
class Pin < ApplicationRecord
validates :url_image, presence: true
belongs_to :utilisateur
has_many :commentaires, dependent: :destroy
validates_associated :commentaires
end
|
# $Id$
class ActivityStream < ActiveRecord::Base
belongs_to :member, :foreign_key => 'user_id'
has_many :items, :class_name => 'ActivityStreamItem'
end
|
require 'pry'
require 'websocket'
require 'logger'
require 'socket'
module Websocket
class Client
attr_accessor :url, :options, :logger
def initialize(url, opts = {})
@callbacks = Hash.new
@url = url
@options = opts
@logger = options[:logger] || Logger.new(STDOUT).tap{ |l| l.level = 1}
on(:ping) { |message| send(message.data, :pong) }
on(:disconnect) { stop }
yield(self) if block_given?
start
end
def on action, &block
@callbacks[action] = block
end
def start
stop if connected?
@handshake = WebSocket::Handshake::Client.new(url: url, headers: options[:headers])
@frame = WebSocket::Frame::Incoming::Server.new(version: @handshake.version)
connect
handshake
start_receiver_thread
@started = true
trigger(:start)
rescue
stop
false
end
def stop
return unless connected?
@receive_thread.kill unless @receive_thread.nil?
@socket.close unless @socket.nil?
@socket = @receive_thread = nil
@started = false
trigger(:stop)
true
end
def send(data, type = :text)
return false unless connected?
data = WebSocket::Frame::Outgoing::Client.new(
:version => @handshake.version,
:data => data,
:type => type
).to_s
@socket.write data
@socket.flush
trigger :sent, data
true
end
def connected?
@started == true
end
private
def connect
@socket = TCPSocket.new(@handshake.host, @handshake.port || 80)
if @handshake.secure
ctx = OpenSSL::SSL::SSLContext.new
if options[:ssl_verify]
ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
ctx.ca_file = options[:cert_file] # || CA_FILE
else
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
ssl_sock = OpenSSL::SSL::SSLSocket.new(@socket, ctx)
ssl_sock.sync_close = true
ssl_sock.connect
@socket = ssl_sock
end
end
def handshake
@socket.write(@handshake.to_s)
@socket.flush
loop do
data = @socket.getc
next if data.nil?
@handshake << data
if @handshake.finished?
raise @handshake.error.to_s unless @handshake.valid?
@handshaked = true
break
end
end
trigger :connect
end
def start_receiver_thread
@receive_thread = Thread.new do
loop do
begin
data = @socket.read_nonblock(1024)
rescue Errno::EAGAIN, Errno::EWOULDBLOCK
IO.select([@socket])
retry
rescue EOFError, Errno::EBADF
trigger :disconnect
end
@frame << data
while message = @frame.next
if message.type === :ping
trigger(:ping, message)
else
trigger(:receive, message.data)
end
end
end
end
end
def trigger action, *args
Thread.new do
logger.debug "#{action}: #{args}"
@callbacks[action].call(*args) unless @callbacks[action].nil?
end.join
end
end
end
if __FILE__ == $0
Thread.abort_on_exception = true
client = Websocket::Client.new "ws://localhost:9292/test", headers: {'WD_TOKEN': "FOO BAR BAZ"} do |conn|
conn.on :receive do |data|
puts data
end
conn.on :connect do |data|
puts "woot"
end
conn.on :disconnect do
puts "crap..."
conn.stop
until conn.start
sleep 1
end
end
end
binding.pry
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: ranks
#
# id :bigint not null, primary key
# name :string
# abbreviation :string
# sort_number :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Rank < ApplicationRecord
has_many :memberships
validates :name, presence: true
end
|
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# user_id :integer
# body :text
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Post < ActiveRecord::Base
attr_accessible :body, :email
belongs_to :user
has_many :comments
validates :email, presence: true
def self.search(search)
if search
begin
#Lookup on posts and comments, could have also used reg expressions in a loop
@results = Post.connection.execute("select distinct p.id from posts p left join comments c on p.id = c.post_id where p.email like '%"+search+"%' or p.body like '%"+search+"%' or c.email like '%"+search+"%' or c.body like '%"+search+"%'")
@ids = []
@results.each do |i|
@ids << i["id"]
end
find(:all, :conditions => ['id in (?)', @ids])
end
else
find(:all)
end
end
def post_text
return body if !body.nil? && body.length > 0
return 'Not much to say...'
end
def post_created
created_at.strftime "%B %d, %Y %l:%M %p"
end
def author_name
return email if user
return "<deleted user>"
end
def <=>(other)
other.comments.length <=> self.comments.length #reversed order because we want highest count first
end
end
|
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
DOLLARS_PER_GALLON = 3.92
CO2_PER_GALLON = 25
POLLUTANTS_PER_MILE = 0.0179558
belongs_to :grouping
has_many :vehicles, :order => 'position'
accepts_nested_attributes_for :vehicles, :allow_destroy => true
#validates_presence_of :login
#validates_length_of :login, :within => 3..40
#validates_uniqueness_of :login
#validates_format_of :login, :with => Authentication.login_regex, :message => :bad_login
#validates_format_of :name, :with => Authentication.name_regex, :message => :bad_name, :allow_nil => true
#validates_length_of :name, :maximum => 100
validates_presence_of :address
validates_length_of :address, :minimum => 4
validates_presence_of :state
validates_presence_of :postal_code
validates_length_of :postal_code, :minimum => 5
validates_presence_of :email
validates_length_of :email, :within => 6..100 #r@a.wk
validates_uniqueness_of :email
validates_format_of :email, :with => Authentication.email_regex, :message => :bad_email
validates_presence_of :driver_count
validates_numericality_of :driver_count, :only_integer => true
validates_acceptance_of :accept_terms, :message => "You must accept the terms and conditions"
before_create :make_activation_code
attr_accessible :email, :username, :password, :password_confirmation, :address, :driver_count, :vehicles_attributes, :state, :postal_code, :accept_terms, :on_mailing_list, :old_email
attr_accessor :accept_terms
validate :must_have_vehicle
def must_have_vehicle
errors.add_to_base("Must have at least one car") if self.vehicles.empty?
end
# Activates the user in the database.
def activate!
@activated = true
self.activated_at = Time.now.utc
self.activation_code = nil
save(false)
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
def active?
# the existence of an activation code means they have not activated yet
#activation_code.nil?
true
end
def reset_password_request
@password_reset_requested = true
self.make_password_reset_code
save(false)
end
def reset_password
self.password_reset_code = nil
save
end
#used in user_observer
def recently_password_reset_requested?
@password_reset_requested
end
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
#
# uff. this is really an authorization, not authentication routine.
# We really need a Dispatch Chain here or something.
# This will also let us return a human error message.
#
def self.authenticate(email, password)
return nil if email.blank? || password.blank?
#u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] # need to get the salt
u = find_by_email email # need to get the salt
u && u.authenticated?(password) ? u : nil
end
#def login=(value)
#write_attribute :login, (value ? value.downcase : nil)
#end
def email=(value)
write_attribute :email, (value ? value.downcase : nil)
end
def overall_weekly_mileage
vehicle_total :overall_weekly_mileage
end
def weekly_mileage(date = nil)
vehicle_data = vehicles.map{|v|v.weekly_mileage(date)}.compact
vehicle_data.sum unless vehicle_data.empty?
end
def initial_weekly_mileage
vehicle_total :initial_weekly_mileage
end
def initial_annual_mileage
vehicle_total :initial_annual_mileage
end
def baseline_percentage
if overall_weekly_mileage and initial_weekly_mileage and not initial_weekly_mileage.zero?
((overall_weekly_mileage.to_f / initial_weekly_mileage) * 100).round - 100
end
end
def miles_reduced_total
vehicle_total :miles_reduced_total
end
def co2_reduced_total
gallons_reduced = self.gallons_reduced_total
(gallons_reduced * CO2_PER_GALLON).round if gallons_reduced
end
def pollutants_reduced_total
miles_reduced = self.miles_reduced_total
(miles_reduced * POLLUTANTS_PER_MILE).round if miles_reduced
end
def gallons_reduced_total
vehicle_total :gallons_reduced_total
end
def dollars_reduced_total
gallons_reduced = self.gallons_reduced_total
(gallons_reduced * DOLLARS_PER_GALLON).round if gallons_reduced
end
def account_time
longest_time = 0
vehicles.each { |v|
longest_time = v.total_time if v.total_time and v.total_time > longest_time
}
return longest_time
end
def title_possessive
username.blank? ? "Your" : "#{username.capitalize}'s"
end
protected
def vehicle_total(msg)
vehicle_data = self.vehicles.map(&msg).compact
vehicle_data.sum unless vehicle_data.empty?
end
#def average(msg)
#array = all_enabled_users.map(&msg).reject(&:nil?)
#array.sum / array.size unless array.empty?
#end
def make_activation_code
self.activation_code = self.class.make_token
end
def make_password_reset_code
self.password_reset_code = self.class.make_token
end
# without this, save() complains about "accept_terms"
# def method_missing(symbol, *params)
# if (symbol.to_s =~ /^(.*)_before_type_cast$/)
# send $1
# else
# super
# end
# end
private
def self.cache_value(key)
unless defined? CACHE and output = CACHE.get(key)
output = yield
CACHE.set(key, output, 1.minute) if defined? CACHE
end
return output
end
end
|
class TicTacToe < ActiveRecord::Base
serialize :players, JSON
serialize :squares, JSON
def self.start_game p1,p2
g = TicTacToe.new
g.squares = [nil,nil,nil,nil,nil,nil,nil,nil,nil]
g.players = [p1,p2]
g.current_player = 0
g.save!
g
end
def self.lookup_game id
TicTacToe.find id
end
def player_turn? p
p == players[current_player]
end
def current_symbol
current_player.zero? ? :x : :o
end
def toggle_player
if current_player.zero?
update current_player: 1
else
update current_player: 0
end
end
def record_move square
place current_symbol, square
toggle_player
save!
end
def board_rows
squares.in_groups_of 3
end
# -- Ported from PORO ----
def value_at location
squares[location - 1]
end
def place sym, location
if squares[location - 1].nil?
squares[location - 1] = sym
end
end
def full?
squares.none? { |n| n.nil? }
end
def winner
lines = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,5,9],
[3,5,7],
[1,4,7],
[2,5,8],
[3,6,9]
]
lines.each do |line|
winner = check_line_for_winner line
return winner if winner
end
return nil
end
def check_line_for_winner line
# if line.all? { |square| value_at(square) == value_at(line.first) }
# unless value_at(line.first).nil?
# return value_at(line.first)
# end
# end
values = line.map { |location| value_at location }
if values.uniq.count == 1
return values.first
end
end
end
|
#!/usr/bin/env ruby
class Ship
@@clockwise_order = ["E", "S", "W", "N"]
attr_reader :location
def initialize
@location = [0, 0]
@heading_index = 0
end
def execute_all(instructions)
instructions.each { |instruction| execute(instruction) }
end
def execute(instruction)
case instruction.action
when /[LR]/
rotate(instruction.action, instruction.value)
when /[ESWN]/
move(instruction.action, instruction.value)
when "F"
move(heading, instruction.value)
end
end
private
def heading
@@clockwise_order[@heading_index]
end
def rotate(direction, value)
value = -value if direction == "L"
@heading_index = (@heading_index + (value / 90)) % 4
end
def move(direction, value)
coord_index = "EW".include?(direction) ? 0 : 1
value = -value if "SW".include?(direction)
@location[coord_index] += value
end
end
Instruction = Struct.new(:action, :value)
instructions = File.read("data_navigation_instructions.txt").split(/\n/).map do |line|
Instruction.new(line[0], line[1...line.length].to_i)
end
ship = Ship.new
ship.execute_all(instructions)
puts ship.location.reduce(0) { |sum, n| sum + n.abs }
|
SS::Application.routes.draw do
Opendata::Initializer
concern :deletion do
get :delete, on: :member
end
content "opendata" do
get "apps_approve" => "app/apps#index_approve"
get "apps_request" => "app/apps#index_request"
get "apps_closed" => "app/apps#index_closed"
resources :my_apps, concerns: :deletion, module: "mypage/app"
end
node "opendata" do
resources :apps, path: "my_app", controller: "public", cell: "nodes/mypage/app/my_app", concerns: :deletion do
resources :appfiles, controller: "public", cell: "nodes/mypage/app/my_app/appfiles", concerns: :deletion do
get "file" => "public#download"
end
end
end
end
|
# frozen_string_literal: true
class Application < ApplicationRecord
has_many :pet_applications, dependent: :destroy
has_many :pets, through: :pet_applications
validates :name,
:address,
:city,
:state,
:state,
:zip,
:phone_number,
:description, presence: true
end
|
class Public::UsersController < ApplicationController
before_action :authenticate_user!
def show
@user = User.find(current_user.id)
end
def edit
@user = User.find(current_user.id)
end
def update
user = User.find(current_user.id)
#flash[:success] = 'You have updated user successfully.'
if user.update(user_params)
if user.user_status == true
#redirect_to controller: 'devise/sessions', action: 'destroy'
#redirect_to destroy_user_session_path
redirect_to root_path
else
redirect_to public_users_path
end
else
@user = user
render action: :edit
end
end
def confirm
@user = User.find(current_user.id)
end
private
def user_params
added_attrs = [:first_name, :last_name, :first_name_kata, :last_name_kata, :email, :street_address, :postal_code, :phone_number, :user_status]
params.require(:user).permit(added_attrs)
end
end
|
# encoding: utf-8
# frozen_string_literal: true
require_relative '../cmd'
module TTY
module Commands
class Add < TTY::Cmd
attr_reader :app_name
attr_reader :cmd_name
attr_reader :options
def initialize(cmd_names, options)
@cmd_name = cmd_names[0]
@app_path = relative_path_from(root_path, root_path)
@app_name = name_from_path(root_path)
@options = options
@templater = Templater.new('add', @app_path)
end
def template_options
opts = OpenStruct.new
opts[:app_name_constantinized] = app_name_constantinized
opts[:cmd_name_constantinized] = cmd_name_constantinized
opts[:app_name_underscored] = app_name_underscored
opts[:cmd_name_underscored] = cmd_name_underscored
opts[:app_constantinized_parts] = app_name_constantinized.split('::')
opts[:cmd_constantinized_parts] = cmd_name_constantinized.split('::')
opts[:app_indent] = ' ' * app_name_constantinized.split('::').size
opts[:cmd_indent] = ' ' * cmd_name_constantinized.split('::').size
opts[:cmd_file_path] = cmd_file_path
opts
end
def color_option
options['no-color'] ? { color: false } : {}
end
def execute
validate_cmd_name(cmd_name)
@templater.add_mapping("command.rb.tt",
"lib/#{app_name}/commands/#{cmd_name_underscored}.rb")
@templater.generate(template_options, color_option)
end
private
def validate_cmd_name(cmd_name)
# TODO: check if command has correct name
end
def app_name_constantinized
constantinize(app_name)
end
def app_name_underscored
snake_case(app_name)
end
def cmd_name_constantinized
constantinize(cmd_name)
end
def cmd_name_underscored
snake_case(cmd_name)
end
def cmd_file_path
'../' * cmd_name_constantinized.split('::').size + 'cmd'
end
def spec_root
Pathname.new('spec')
end
end # Add
end # Commands
end # TTY
|
class RenameFrendRequestToFriendRequest < ActiveRecord::Migration[5.2]
def change
rename_table :frend_requests, :friend_requests
end
end
|
module Mastermind
module Mixins
module Resources
def self.inherited(subclass)
subclass.attributes = attributes.dup
super
end
def self.included(base)
base.extend ClassMethods
end
def run #(action)
provider = self.provider.new(self)
provider.action = self.action
provider.run
# TODO: rescue exceptions
end
def actions
self.class.actions
end
# Override ActiveAttr::Attributes#attribute to provide a Chef-style DSL syntax
def attribute(name, value=nil)
if value
write_attribute(name, value)
else
super(name)
end
end
module ClassMethods
def register(type)
@type = type.to_s
# Mastermind.resources[type.to_sym] = self
end
def provider(provider_class)
@provider = provider_class
attribute :provider, :type => Object, :default => provider_class
end
def actions(*actions)
@actions ||= [ 'nothing' ]
@actions << actions.map(&:to_s) unless actions.blank?
@actions.flatten!
@actions.each do |act|
validates! :name,
:presence => true,
:on => act
validates! :action,
:presence => true,
:inclusion => {
:in => @actions.map(&:to_s)
},
:on => act
end
return @actions
end
def type
@type
end
end
end
end
end
|
require('pry')
class Group
attr_reader :guests
attr_accessor :pot
def initialize(pot)
@guests = []
@pot = pot
end
def add_guest(*guest)
guest.each{ |person| @guests << person }
end
def remove_guest(leaver)
guest = @guests.find do |person|
person.name == leaver
end
@guests.delete(guest)
end
# def total
# total = 0
# @guests.each do |person|
# total + person.money
# end
# end
def total_map
total = []
total = @guests.map do |person|
person.money
end
sum = 0
total.each{|x| sum += x}
return sum
end
def group_pay(room)
@pot -= room.price
return room.price
end
end
|
describe User do
let!(:user) do
User.create(email: 'unit@test.com',
password: 'so_tired',
password_confirmation: 'so_tired')
end
it 'authenticates when given a valid user id and password' do
authenticated_user = User.authenticate('unit@test.com', 'so_tired')
expect(authenticated_user).to eq user
end
it 'does not authenticate when given an invalid password' do
authenticated_user = User.authenticate('unit@test.com', 'full_of_energy')
expect(authenticated_user).to be_nil
end
end
|
require 'spec_helper'
feature 'Catalog distribution metadata' do
before do
@user = FactoryGirl.create(:user)
given_logged_in_as(@user)
end
scenario 'fills the distribution metadata' do
catalog = create(:catalog, organization: @user.organization)
dataset = create(:opening_plan_dataset, catalog: catalog)
distribution = dataset.distributions.first
visit edit_distribution_path(distribution)
distribution_attributes = attributes_for(:distribution)
fill_catalog_distribution_metadata(distribution_attributes)
visit edit_distribution_path(distribution)
expect(page).to have_field('distribution_download_url', with: distribution_attributes[:download_url])
expect(page).to have_field('distribution_modified', with: distribution_attributes[:modified].strftime('%F'))
expect(page).to have_field('distribution_spatial', with: distribution_attributes[:spatial])
expect(page).to have_field('distribution_codelist', with: distribution_attributes[:codelist])
expect(page).to have_field('distribution_codelist_link', with: distribution_attributes[:codelist_link])
expect(page).to have_field('distribution_copyright', with: distribution_attributes[:copyright])
expect(page).to have_field('distribution_tools', with: distribution_attributes[:tools])
end
def fill_catalog_distribution_metadata(distribution_attributes)
fill_in('distribution_download_url', with: distribution_attributes[:download_url])
fill_in('distribution_modified', with: distribution_attributes[:modified].strftime('%F'))
fill_in('distribution_spatial', with: distribution_attributes[:spatial])
fill_in('distribution_tools', with: distribution_attributes[:tools])
fill_in('distribution_codelist', with: distribution_attributes[:codelist])
fill_in('distribution_codelist_link', with: distribution_attributes[:codelist_link])
fill_in('distribution_copyright', with: distribution_attributes[:copyright])
# page.find('form').click # close the date picker by clicking anywhere
click_on('Guardar')
end
end
|
module Fog
module Sql
class AzureRM
# Real class for Firewall Rule Request
class Real
def create_or_update_firewall_rule(firewall_hash)
msg = "Creating SQL Firewall Rule : #{firewall_hash[:name]}."
Fog::Logger.debug msg
resource_url = "#{resource_manager_endpoint_url}/subscriptions/#{@subscription_id}/resourceGroups/#{firewall_hash[:resource_group]}/providers/Microsoft.Sql/servers/#{firewall_hash[:server_name]}/firewallRules/#{firewall_hash[:name]}?api-version=2014-04-01-preview"
request_parameters = get_server_firewall_parameters(firewall_hash[:start_ip], firewall_hash[:end_ip])
begin
token = Fog::Credentials::AzureRM.get_token(@tenant_id, @client_id, @client_secret)
response = RestClient.put(
resource_url,
request_parameters.to_json,
accept: :json,
content_type: :json,
authorization: token
)
rescue RestClient::Exception => e
raise_azure_exception(e, msg)
end
Fog::Logger.debug "SQL Firewall Rule : #{firewall_hash[:name]} created successfully."
Fog::JSON.decode(response)
end
private
def get_server_firewall_parameters(start_ip, end_ip)
parameters = {}
properties = {}
properties['startIpAddress'] = start_ip
properties['endIpAddress'] = end_ip
parameters['properties'] = properties
parameters
end
end
# Mock class for Sql Firewall Rule Request
class Mock
def create_or_update_firewall_rule(*)
{
'properties' => {
'startIpAddress' => '{start-ip-address}',
'endIpAddress' => '{end-ip-address}'
}
}
end
end
end
end
end
|
class CreateGroups < ActiveRecord::Migration[5.0]
def change
create_table :groups do |t|
t.string 'cid'
t.string 'title'
t.string 'parent_cid'
t.string 'ancestry'
t.integer 'position'
t.string 'site_title'
t.string 'sort_type'
t.boolean 'disabled', default: false
t.integer 'importsession_id'
t.datetime 'last_new_item'
t.integer 'items_count', default: 0
t.timestamps
end
end
end
|
# Using the file 'names.txt,' a 46K text file containing
# over five-thousand first names: begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name, multiply this value by
# its alphabetical position in the list to obtain a name score.
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53,
# is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file?
names = File.open('names.txt', &:read).gsub('"', '').gsub(',', ' ').split(' ').sort
def alpha_score(names)
alpha_nums = {
'A' => '1',
'B' => '2',
'C' => '3',
'D' => '4',
'E' => '5',
'F' => '6',
'G' => '7',
'H' => '8',
'I' => '9',
'J' => '10',
'K' => '11',
'L' => '12',
'M' => '13',
'N' => '14',
'O' => '15',
'P' => '16',
'Q' => '17',
'R' => '18',
'S' => '19',
'T' => '20',
'U' => '21',
'V' => '22',
'W' => '23',
'X' => '24',
'Y' => '25',
'Z' => '26',
}
calc = names.map do |name|
name.split('').map do |letter|
letter.sub(letter, alpha_nums[letter])
end
end
calc.map {|x| x.map(&:to_i).sum }
end
def final_score(names)
final = alpha_score(names).zip(1..names.length).map { |x, y| x * y }.sum
end
puts final_score(names)
# Complete!
# Answer = 871198282
|
class AddLogoToUsers < ActiveRecord::Migration
def change
add_column :users, :logo, :string, null: false, limit: 255
end
end
|
class UsersController < ApplicationController
# GET /users
# GET /users.json
before_action :set_user, only: [ :edit, :update, :destroy]
before_filter :authorize, only: [:edit, :update, :index]
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find(current_user.id)
@registrations = Registration.where(:user_id => @user.id)
@travels = @user.travels.all
@meals = @user.meals.all
@children = Child.where(:user_id => @user.id)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
# GET /users/new
# GET /users/new.json
def new
reset_session
@user = User.new
@meal_dates = ["2013-07-08","2013-07-09","2013-07-10","2013-07-11","2013-07-12","2013-07-13","2013-07-14"]
@child = @user.children.build
@meal = @user.meals.build
@travels = @user.travels.build
@registration = @user.registrations.build
@programs = Program.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
# GET /users/1/edit
def edit
@meal_dates = ["2013-07-08","2013-07-09","2013-07-10","2013-07-11","2013-07-12","2013-07-13","2013-07-14"]
@user.meals
@user.programs
@user.travels
@programs = Program.all
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
@meal_dates = ["2013-07-08","2013-07-09","2013-07-10","2013-07-11","2013-07-12","2013-07-13","2013-07-14"]
@programs = Program.all
start = DateTime.new(2013,7,10,0,0,0)
finish = DateTime.new(2013,7,12,0,0,0)
@range = start..finish
respond_to do |format|
if @user.save
session[:user_id] = @user.id
UserMailer.confirmation_email(@user).deliver
format.html { redirect_to @user, notice: t('user_created') }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
respond_to do |format|
if @user.update_attributes(user_params)
format.html { redirect_to @User, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @User.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to Users_url }
format.json { head :no_content }
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email_address, :password, :password_confirmation, :first_name, :home_country, :payment, :phone_number, :price_category, :price_method, :reference_number, :second_name)
end
end
|
class User::PasswordAuthentication < ApplicationRecord
has_secure_password
belongs_to :user
validates :password, presence: true, length: { minimum: 8 }
end
|
require "test_helper"
class ImportersControllerTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "should get index" do
get root_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert is_logged_in?
assert_redirected_to importers_path
follow_redirect!
assert_template 'importers/index'
assert_response :success
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
# include the session helper so that its functions are accessible in controllers
# (helpers are automatically included in Rails views)
include SessionsHelper
end
|
class History < ApplicationRecord
belongs_to :user
has_many :likes
belongs_to :historyable, polymorphic: true
scope :ordered, -> {order(created_at: :desc)}
scope :by_following, -> (user){where(user_id: user.following)
.or(where(user_id: user.id))}
enum type_history: {mark: Settings.user_mark_book, follow: Settings.user_follow_other_user,
review: Settings.rating_book}
end
|
module Reservations
module UseCases
class Update < UseCase::Base
attr_reader :args, :id, :seats_taken, :user_id
def persist
@args = self.params[:args]
@id = self.params[:id]
@user_id = self.params[:user_id]
ensure_valid_parameters
reservation_params = {
cinema_id: args[:cinema_id],
movie_id: args[:movie_id],
screening_id: args[:screening_id],
user_id: user_id
}
reservation = ReservationRepository.new.update_reservation(reservation_params, id)
Positions::PositionRepository.new.delete_reservation_positions(reservation.id)
Positions::UseCases::Create.new(reservation.id, args[:seat_ids]).call
return reservation
end
private
def ensure_valid_parameters
@cinema = Cinemas::CinemaRepository.new.find_by_id(args[:cinema_id])
Movies::MovieRepository.new.find_by_id(args[:movie_id])
@screening = Screenings::ScreeningRepository.new.find_by_id(args[:screening_id])
sql_seats_taken
args[:seat_ids].map do |seat_ids|
seat = Seats::SeatRepository.new.find_by_id(seat_ids[:seat_id])
raise SeatAlreadyTaken unless seats_taken.exclude?(seat_ids[:seat_id])
end
end
def sql_seats_taken
sql_result = Reservations::ReservationRepository.new.seats_taken_sql_query(args[:screening_id])
@seats_taken = []
sql_result.map { |sql| @seats_taken << sql['seat_id'] }
end
end
end
end
|
class Item < ApplicationRecord
belongs_to :genre
has_many :order_details
has_many :cart_items
with_options presence: true do
validates :image
validates :name
validates :introduction
validates :price
validates :is_active
end
attachment :image
enum is_active: { 販売中: 1, 販売停止中: 2 }
end
|
require "formula"
class Tutum < Formula
homepage "https://www.tutum.co/"
url "https://github.com/tutumcloud/tutum-cli/archive/v0.12.6.1.tar.gz"
sha1 "75d44ba0fb7f360dfa1931ce5cf0134cc69985e0"
revision 1
bottle do
cellar :any
sha256 "eb1cd49f6dd12f483bdff9e189562b0ef9bd9873aa1f28a29f0015587ce22a13" => :yosemite
sha256 "29d3d5523a6a15916ebb95d194a6cbf01c0d6320b6af874d00e7b90332b2062d" => :mavericks
sha256 "8f268a0df07425aa566cc97b12f9e126aa9d2ceaae0caa0158271a5e7a3b5653" => :mountain_lion
end
depends_on :python if MacOS.version <= :snow_leopard
depends_on "libyaml"
resource "ago" do
url "https://pypi.python.org/packages/source/a/ago/ago-0.0.6.tar.gz"
sha1 "b48b99151370de0c1642748a3f3b206649645d8d"
end
resource "docker-py" do
url "https://pypi.python.org/packages/source/d/docker-py/docker-py-0.5.3.tar.gz"
sha1 "11708a7021e3d0d522e145c057256d7d2acaec07"
end
resource "pyyaml" do
url "https://pypi.python.org/packages/source/P/PyYAML/PyYAML-3.10.tar.gz"
sha1 "476dcfbcc6f4ebf3c06186229e8e2bd7d7b20e73"
end
resource "python-tutum" do
url "https://pypi.python.org/packages/source/p/python-tutum/python-tutum-0.12.6.tar.gz"
sha1 "21374ce80c82a7e99f1f7a5fd63d1772df541651"
end
resource "backports.ssl-match-hostname" do
url "https://pypi.python.org/packages/source/b/backports.ssl_match_hostname/backports.ssl_match_hostname-3.4.0.2.tar.gz"
sha1 "da4e41f3b110279d2382df47ac1e4f10c63cf954"
end
resource "six" do
url "https://pypi.python.org/packages/source/s/six/six-1.9.0.tar.gz"
sha1 "d168e6d01f0900875c6ecebc97da72d0fda31129"
end
resource "python-dateutil" do
url "https://pypi.python.org/packages/source/p/python-dateutil/python-dateutil-2.2.tar.gz"
sha1 "fbafcd19ea0082b3ecb17695b4cb46070181699f"
end
resource "requests" do
url "https://pypi.python.org/packages/source/r/requests/requests-2.6.0.tar.gz"
sha256 "1cdbed1f0e236f35ef54e919982c7a338e4fea3786310933d3a7887a04b74d75"
end
resource "tabulate" do
url "https://pypi.python.org/packages/source/t/tabulate/tabulate-0.7.2.tar.gz"
sha1 "da057c6d4faab9847436c3221c98f34911e623df"
end
resource "websocket-client" do
url "https://pypi.python.org/packages/source/w/websocket-client/websocket-client-0.23.0.tar.gz"
sha1 "3348c226eb44324417db777e962fec6bda8134b9"
end
resource "future" do
url "https://pypi.python.org/packages/source/f/future/future-0.14.3.tar.gz"
sha1 "44fdd9323913d21068b29ecda795a98c07dc8a40"
end
def install
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
resources.each do |r|
r.stage do
system "python", *Language::Python.setup_install_args(libexec/"vendor")
end
end
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages"
system "python", *Language::Python.setup_install_args(libexec)
bin.install Dir[libexec/"bin/*"]
bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
end
test do
system "#{bin}/tutum", "container"
end
end
|
require "hpricot"
require "open-uri"
class Fetch
EVO_EU = "http://www.newerth.com/?id=serverlist&details=83.142.226.16:11239"
USA = "http://www.newerth.com/?id=serverlist&details=69.65.40.20:11235"
GROENTJUH = "http://newerth.com/?id=serverlist&details=85.197.124.236:11235"
GIRLS = "http://newerth.com/?id=serverlist&details=88.198.26.57:11235"
PWNS = "http://www.newerth.com/?id=serverlist&details=75.126.227.114:11236"
TERRA = "http://www.newerth.com/?id=serverlist&details=200.177.229.37:11235"
# ICON_SERVER = "http://216.15.252.190/SEPicons/"
ICON_SERVER = "http://stats.newerth.com/icondir/"
attr_reader :players_rows, :map, :time
def initialize(url)
@doc = Hpricot(open(url))
@players_rows = fetch_players
@map = fetch_map
@time = fetch_time
end
def parse!
create_snapshot!
Match.create_or_update! @snapshot
end
def snapshot
@snapshot
end
private
# ==================================
# = Create Model Objects =
# ==================================
def create_snapshot!
@snapshot = Snapshot.new
@snapshot.map = Map.find_by_name(self.map) || Map.new(:name => self.map)
@snapshot.time = self.time
@snapshot.save!
@snapshot.shift_created_at # adjust Timezone
for row in self.players_rows
existing_player = Player.find_by_name_and_icon_number(row[:name], row[:icon_number])
if existing_player
player = existing_player
else
player = Player.new(:name => row[:name], :icon_number => row[:icon_number])
end
player.snapshots_count += 1
player.officer_count += 1 if row[:officer]
player.commander_count += 1 if row[:commander]
player.referee_count += 1 if row[:referee]
player.save!
performance = Performance.new(:player => player,
:snapshot => @snapshot,
:team => row[:team],
:officer => row[:officer],
:commander => row[:commander],
:referee => row[:referee])
performance.save!
end
@snapshot.players_count = @snapshot.players.count
@snapshot.save!
end
# ====================================
# = Fetch Remote Page =
# ====================================
def fetch_map
links = (@doc/".content-center-text-container")[0]/"a"
links[1].inner_html
end
def fetch_time
(@doc/("td[text()*='Time:']")).first.next_sibling.inner_html
end
def fetch_players
players = []
tds = (@doc/".ssi_table")[1]/"tr > td"
team1 = tds[0].inner_html.split("<br />")[1..-1]
team2 = tds[1].inner_html.split("<br />")[1..-1]
specs = tds[2].inner_html.split("<br />")[1..-1]
players += parse_team(1, team1)
players += parse_team(2, team2)
players += parse_team(3, specs)
players
end
def parse_team(team, br_splited)
players_rows = []
for line in br_splited
row = {}
hline = Hpricot(line)
if hline.at("font[@color=green]")
row[:commander] = true
hline.search("font[@color=green]").remove
else
row[:commander] = false
end
if hline.at("font[@color=blue]")
row[:officer] = true
hline.search("font[@color=blue]").remove
else
row[:officer] = false
end
if hline.at("font[@color=yellow]")
row[:referee] = true
hline.search("font[@color=yellow]").remove
else
row[:referee] = false
end
if hline.at("img")
row[:icon_number] = hline.at("img")["src"].split("/")[4]
hline.search("img").remove
end
row[:name] = hline.inner_text.strip
row[:team] = team
players_rows << row
end
players_rows
end
end
|
# coding: utf-8
require 'singleton'
module HupoWidget
class Base
class NoInstanceAllowed < StandardError; end
class UnknownWidget < StandardError; end
class ConfigVerificationError < StandardError; end
@widget_types = nil
class << self
attr_writer :widget_types, :all, :instances
def instances
@instances ||= {}
end
def widget_types
return @widget_types if @widget_types
@widget_types = []
create_widgets_by_config
@widget_types
end
# Creates single unique object of widget
def singleton!
include Singleton
end
def abstract!
@abstract_class = true
end
def abstract?
@abstract_class ||= false
end
# Returns hash with all widget objects in hash with classes' and modules' names as keys
def all
@all ||= widget_types.reject(&:abstract?).inject({}) {|res, type| res.deep_merge(type.instances_hash)}
end
def instances_hash
prefix = Hash.new {|h, k| h[k] = {}}
# Shortcuts::AccountInfo -> %w(shortcuts account_info)
before_last = config_paths[0...-1].inject(prefix) {|res, key| res[key] = Hash.new {|h, k| h[k] = {}}}
# Singleton class refers straight to object
# Other class refer to an array of instances
before_last[config_paths.last] = singleton? ? instance : instances
# {shortcuts: {account_info: #{instances.as_json}}}
prefix
end
def config_paths
@config_paths ||= name.underscore.sub(/_widget$/, '').split('/')
end
def config
@@config ||= HupoWidget::Configuration.new
end
def reload
config.reload
end
def unload
@widget_types.try(:each) do |type|
if type.singleton?
type.instance_variable_set(:@singleton__instance__, nil)
else
type.instances = nil
end
end
@widget_types = nil
end
def singleton?
self < Singleton
end
def new(*)
new_instance = super
# Save new instance to hash
instances[new_instance.key] = new_instance
end
# Creates all widgets defined in configuration file
def create_widgets_by_config(hash = config, prefix = '')
# Raise an exception if hash is not config or hash
if !hash.is_a?(Hash) and !hash.is_a?(HupoWidget::Configuration)
raise UnknownWidget, 'Unknown widget type %s' % prefix.underscore.gsub('/', '.')
end
hash.each do |widget_type, values|
widget_type = widget_type.camelize
widget_type = '%s::%s' % [prefix, widget_type] if prefix != ''
class_name = '%sWidget' % widget_type
if (widget_class = class_name.safe_constantize)
@widget_types << widget_class
if widget_class.singleton?
# Create a singleton object
widget_class.instance
else
values.each_key {|key| widget_class.new(key)}
end
else
# We need to go deeper
create_widgets_by_config(values, widget_type)
end
end
end
end
attr_reader :key
delegate :singleton?, :abstract?, :config_paths, to: 'self.class'
delegate :as_json, to: :@values
delegate :config, to: 'HupoWidget::Base'
def initialize(key = nil)
raise NoInstanceAllowed, 'Could not create an instance of abstract class' if abstract?
@key = singleton? ? 'singleton' : key
type_config = config_paths.inject(config) {|c, k| c[k]}
@values = singleton? ? type_config : type_config[@key]
end
def [](k)
@values[k]
end
def []=(k, v)
@values[k] = v
end
protected
def verify_config
raise ConfigVerificationError, 'Configuration for widget %s with key not found' % self.class if @values.nil?
end
def current_user
Session.find.user
end
end
end
|
require 'formula'
class RockRuntimeRuby21 < Formula
homepage 'http://www.python.org/'
url 'http://ftp.ruby-lang.org/pub/ruby/2.1/ruby-2.1.0.tar.gz'
sha1 '99114e71c7765b5bdc0414c189a338f6f21fb51d'
env :std
keg_only 'rock'
# https://github.com/rubygems/rubygems/commit/f5bbf838c8b13369a61c6756355305388df5824f
def patches; DATA; end
depends_on 'readline'
depends_on 'gdbm'
depends_on 'libyaml'
depends_on 'openssl'
depends_on 'curl-ca-bundle'
resource 'bundler' do
url 'https://rubygems.org/gems/bundler-1.5.2.gem'
sha1 '78a9fe1161407778f437fae39cb5ac51127f4635'
end
def abi_version
'2.1.0'
end
def install_bundler
ENV['GEM_HOME'] = "#{lib}/ruby/gems/#{abi_version}"
resource('bundler').stage { |r|
system 'gem', 'install',
'--config-file', 'nofile',
'--force',
'--ignore-dependencies',
'--no-rdoc',
'--no-ri',
'--local',
'--install-dir', "#{lib}/ruby/gems/#{abi_version}",
"--bindir", bin,
r.cached_download
}
system 'mv', "#{bin}/bundle", "#{bin}/rock-bundle"
(bin + 'bundle').write <<-EOS.undent
#!/usr/bin/env bash
unset RUBYOPT
exec rock-bundle "$@"
EOS
system 'chmod', '755', "#{bin}/bundle"
end
def install
lib.mkpath
system './configure',
"--prefix=#{prefix}",
'--enable-shared',
"--with-opt-dir=#{Formula.factory('openssl').opt_prefix}",
"--with-opt-dir=#{Formula.factory('readline').prefix}"
system 'make'
system 'make', 'install'
ENV['PATH'] = "#{bin}:#{ENV['PATH']}"
install_bundler
(prefix + 'rock.yml').write <<-EOS.undent
env:
PATH: "#{bin}:${PATH}"
RUBY_ABI: "#{abi_version}"
RUBYOPT: "-I#{lib}/ruby/gems/#{abi_version}/gems/bundler-#{resource('bundler').version}/lib -rbundler/setup"
SSL_CERT_FILE: "#{Formula.factory('curl-ca-bundle').prefix}/share/ca-bundle.crt"
EOS
runtime = var + 'rock/opt/rock/runtime'
runtime.mkpath
runtime += 'ruby21'
system 'rm', '-fr', runtime if runtime.exist?
File.symlink(prefix, runtime)
end
end
__END__
diff -ru ruby-2.1.0.orig/lib/rubygems/commands/install_command.rb ruby-2.1.0/lib/rubygems/commands/install_command.rb
--- ruby-2.1.0.orig/lib/rubygems/commands/install_command.rb 2014-02-01 13:34:30.000000000 -0800
+++ ruby-2.1.0/lib/rubygems/commands/install_command.rb 2014-02-01 13:35:58.000000000 -0800
@@ -228,7 +228,18 @@
def install_gem_without_dependencies name, req # :nodoc:
gem = nil
- if remote? then
+ if local? then
+ if name =~ /\.gem$/ and File.file? name then
+ source = Gem::Source::SpecificFile.new name
+ spec = source.spec
+ else
+ source = Gem::Source::Local.new
+ spec = source.find_gem name, req
+ end
+ gem = source.download spec if spec
+ end
+
+ if remote? and not gem then
dependency = Gem::Dependency.new name, req
dependency.prerelease = options[:prerelease]
@@ -236,13 +247,6 @@
gem = fetcher.download_to_cache dependency
end
- if local? and not gem then
- source = Gem::Source::Local.new
- spec = source.find_gem name, req
-
- gem = source.download spec
- end
-
inst = Gem::Installer.new gem, options
inst.install
diff -ru ruby-2.1.0.orig/test/rubygems/test_gem_commands_install_command.rb ruby-2.1.0/test/rubygems/test_gem_commands_install_command.rb
--- ruby-2.1.0.orig/test/rubygems/test_gem_commands_install_command.rb 2014-02-01 13:34:30.000000000 -0800
+++ ruby-2.1.0/test/rubygems/test_gem_commands_install_command.rb 2014-02-01 13:35:58.000000000 -0800
@@ -559,6 +559,20 @@
assert_equal %w[a-2], @cmd.installed_specs.map { |spec| spec.full_name }
end
+ def test_install_gem_ignore_dependencies_specific_file
+ spec = quick_spec 'a', 2
+
+ util_build_gem spec
+
+ FileUtils.mv spec.cache_file, @tempdir
+
+ @cmd.options[:ignore_dependencies] = true
+
+ @cmd.install_gem File.join(@tempdir, spec.file_name), nil
+
+ assert_equal %w[a-2], @cmd.installed_specs.map { |spec| spec.full_name }
+ end
+
def test_parses_requirement_from_gemname
spec_fetcher do |fetcher|
fetcher.gem 'a', 2
Only in ruby-2.1.0/test/rubygems: test_gem_commands_install_command.rb.orig
|
class DropXrons < ActiveRecord::Migration[6.1]
def change
drop_table :xrons
drop_table :xrons_references
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.