text stringlengths 10 2.61M |
|---|
## -*- Ruby -*-
## XML::ParserNS
## namespaces-aware version of XML::Parser (experimental)
## 2002 by yoshidam
require 'xml/parser'
module XML
class InternalParserNS < Parser
XMLNS = 'http://www.w3.org/XML/1998/namespace'
attr_reader :ns
def self.new(parserNS, *args)
nssep = nil
if args.length == 2 && !args[0].is_a?(Parser)
nssep = args[1]
args = args.shift
end
obj = super(*args)
obj.__init__(parserNS, nssep)
obj
end
def __init__(parserNS, nssep)
@ns = []
@parserNS = parserNS
@nssep = nssep
end
def parse(*args)
if block_given?
super do |nodetype, name, args, parser|
case nodetype
when START_ELEM
ns, args = getNSAttrs(args)
@ns.push(ns)
if @nssep
if @parserNS.respond_to?(:startNamespaceDecl)
ns.each do |prefix, uri|
yield(START_NAMESPACE_DECL, prefix, uri, parser)
end
end
prefix, uri, localpart = resolveElementQName(name)
name = uri + @nssep + name if uri
attrs = {}
args.each do |k, v|
prefix, uri, localpart = resolveAttributeQName(k)
k = uri + @nssep + k if uri
attrs[k] = v
end
args = attrs
end
yield(nodetype, name, args, parser)
when END_ELEM
if @nssep
prefix, uri, localpart = resolveElementQName(name)
name = uri + @nssep + name if uri
end
yield(nodetype, name, args, parser)
ns = @ns.pop
if @nssep and @parserNS.respond_to?(:endNamespaceDecl)
ns.to_a.reverse.each do |prefix, uri|
yield(END_NAMESPACE_DECL, prefix, nil, parser)
end
end
else
yield(nodetype, name, args, parser)
end
end
else
super
end
end
def getNamespaces
@ns[-1]
end
def getNSURI(prefix)
return XMLNS if prefix == 'xml'
@ns.reverse_each do |n|
return n[prefix] if n.include?(prefix)
end
nil
end
def resolveElementQName(qname)
qname =~ /^((\S+):)?(\S+)$/u
prefix, localpart = $2, $3
uri = getNSURI(prefix)
[prefix, uri, localpart]
end
def resolveAttributeQName(qname)
qname =~ /^((\S+):)?(\S+)$/u
prefix, localpart = $2, $3
uri = nil
uri = getNSURI(prefix) if !prefix.nil?
[prefix, uri, localpart]
end
def getSpecifiedAttributes
ret = super
# attrs = {}
# ret.each do |k, v|
# next if k =~ /^xmlns/u
# if @nssep
# prefix, uri, localpart = resolveAttributeQName(k)
# k = uri.to_s + @nssep + k
# end
# attrs[k] = v
# end
attrs = []
ret.each do |k|
next if k =~ /^xmlns:|^xmlns$/u
if @nssep
prefix, uri, localpart = resolveAttributeQName(k)
k = uri.to_s + @nssep + k
end
attrs.push(k)
end
attrs
end
private
def getNSAttrs(args, eliminateNSDecl = false)
ns = {}
newargs = {}
args.each do |n, v|
prefix, localpart = n.split(':')
if prefix == 'xmlns'
ns[localpart] = v
next if eliminateNSDecl
end
newargs[n] = v
end
[ns, newargs]
end
def startElement(name, args)
ns, args = getNSAttrs(args)
@ns.push(ns)
if @nssep and @parserNS.respond_to?(:startNamespaceDecl)
ns.each do |prefix, uri|
@parserNS.startNamespaceDecl(prefix, uri)
end
end
if @parserNS.respond_to?(:startElement)
if @nssep
prefix, uri, localpart = resolveElementQName(name)
name = uri + @nssep + name if uri
attrs = {}
args.each do |k, v|
prefix, uri, localpart = resolveAttributeQName(k)
k = uri + @nssep + k if uri
attrs[k] = v
end
args = attrs
end
@parserNS.startElement(name, args)
end
end
def endElement(name)
if @parserNS.respond_to?(:endElement)
if @nssep
prefix, uri, localpart = resolveElementQName(name)
name = uri + @nssep + name if uri
end
@parserNS.endElement(name)
end
ns = @ns.pop
if @nssep and @parserNS.respond_to?(:endNamespaceDecl)
ns.to_a.reverse.each do |prefix, uri|
@parserNS.endNamespaceDecl(prefix)
end
end
end
end
class ParserNS
EVENT_HANDLERS = [
:character,
:processingInstruction,
:unparsedEntityDecl,
:notationDecl,
:externalEntityRef,
:comment,
:startCdata,
:endCdata,
:startNamespaceDecl,
:endNamespaceDecl,
:startDoctypeDecl,
:endDoctypeDecl,
:default,
:defaultExpand,
:unknownEncoding,
:notStandalone,
:elementDecl,
:attlistDecl,
:xmlDecl,
:entityDecl,
:externalParsedEntityDecl,
:internalParsedEntityDecl]
def initialize(*args)
@parser = InternalParserNS.new(self, *args)
end
def parse(*args, &block)
EVENT_HANDLERS.each do |m|
if self.respond_to?(m)
eval "def @parser.#{m}(*args); @parserNS.#{m}(*args); end"
end
end
@parser.parse(*args, &block)
end
def setReturnNSTriplet(do_nst); end
def method_missing(name, *args)
if @parser.respond_to?(name)
@parser.send(name, *args)
else
raise NameError.new("undefined method `#{name.id2name}' " +
"for #{self.inspect}")
end
end
end
end
|
maintainer "Christian Berkhoff"
maintainer_email "christian.berkhoff@gmail.com"
license "Apache 2.0"
description "Installs Leiningen"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "0.1"
|
FactoryGirl.define do
factory :search_result, class: 'SitescanCommon::SearchResult' do
title "MyString"
link "MyString"
# display_link "MyString"
# snippet "MyString"
end
end
|
# frozen_string_literal: true
class TeamsApplicationsController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
def index
@event = Event.find(params[:event_id])
@users = User.all
@teams = @event.teams
if @current_user.is? :admin
@teams_applications = @event.teams_applications.order(:user_id)
else
@teams_applications = TeamsApplication.where(event_id: @event.id, user_id: @current_user.id)
end
end
def new
@teams_application = TeamsApplication.new(user_id: @current_user.id)
@event = Event.find(params[:event_id])
end
def create
@event = Event.find(params[:event_id])
@teams_application = TeamsApplication.new(teams_application_params)
if @teams_application.save
flash[:success] = 'Application was successfully created'
@event.teams_applications << @teams_application
@current_user.teams_applications << @teams_application
redirect_to event_teams_path(@event)
else
flash[:danger] = 'Error creating application'
render 'new'
end
end
private
def teams_application_params
params.require(:teams_application).permit(:team_id, :priority, :user_id)
end
end
|
require 'csv'
class ImportDhcpLeasesJob < ApplicationJob
def perform()
leases = {}
leases_file.each do |row|
next unless target_ids.include?(row['subnet_id'].to_i)
leases[row.fetch('hwaddr')] = row.fetch('address')
end
changed_machines = []
ApplicationRecord.transaction do
Machine.where(mac: leases.keys).each do |machine|
machine.ip_address = leases.fetch(machine.mac)
changed_machines.push(machine) if machine.ip_address_changed?
machine.save!
end
end
UpdateMachineRoute53RecordsJob.perform_later(changed_machines)
end
private
def target_ids
Rails.application.config.x.ipam.leases_target_ids
end
def s3
@s3 ||= Aws::S3::Client.new(region: Rails.application.config.x.ipam.leases_s3_region)
end
def leases_file
@leases_file ||= Tempfile.new.yield_self do |io|
s3.get_object(
bucket: Rails.application.config.x.ipam.leases_s3_bucket,
key: Rails.application.config.x.ipam.leases_s3_key,
response_target: io,
)
io.rewind
CSV.open(io, headers: true)
end
end
end
|
require 'httparty'
class TestParty
include HTTParty
base_uri 'http://localhost:5000'
end
RSpec.describe 'API TEST - POST' do
it 'Should create a new employee' do
data = {
'name' => 'TestRamiloNeves',
'nif' => 291765022,
'address' => 'Vila Nova de Gaia'
}
begin
response = TestParty.post('/employees', body: data)
expect(response.code).to eql(201)
expect(response.parsed_response["name"]).to eql('TestRamiloNeves')
expect(response.parsed_response["nif"]).to eql(291765022)
expect(response.parsed_response["address"]).to eql('Vila Nova de Gaia')
end
end
it 'Should return httpStatus 400 when create a new employee without name' do
data = {
'nif' => 999888778,
'address' => 'Vila Nova de Gaia'
}
begin
response = TestParty.post('/employees', body: data)
expect(response.code).to eql(400)
expect(response.parsed_response).to eql('name is required.')
end
end
it 'Should return httpStatus 400 when create a new employee without nif' do
data = {
'name' => 'RamiloNeves',
'address' => 'Vila Nova de Gaia'
}
begin
response = TestParty.post('/employees', body: data)
expect(response.code).to eql(400)
expect(response.parsed_response).to eql('nif is required.')
end
end
end
RSpec.describe 'API TEST - GET' do
it 'Should return all employees' do
begin
response = TestParty.get('/employees')
expect(response.code).to eql(200)
end
end
it 'Should return a specific employee' do
begin
response = TestParty.get('/employees?name=TesterPortoMeetup')
expect(response.code).to eql(200)
expect(response[0]['name']).to eql('TesterPortoMeetup')
expect(response[0]['nif']).to eql(999888777)
expect(response[0]['address']).to eql('MTP')
end
end
it 'Should return httpStatus 404 not found' do
begin
response = TestParty.get('/employees?name=NAOEXISTE')
expect(response.code).to eql(404)
expect(response.body).to eql('Not Found')
end
end
end
RSpec.describe 'API TEST - PUT' do
it 'Should update a contact' do
newContact = {
'name' => 'TesterPortoMeetup2',
'nif' => 999888770,
'address' => 'MTPTest'
}
begin
response = TestParty.put('/employees/5cca2e2e35e9fb1c4a1ab844', body: newContact)
expect(response.code).to eql(204)
end
end
end
RSpec.describe 'API TEST - DELETE' do
it 'Should delete a contact' do
begin
response = TestParty.delete('/employees/5cca2e2e35e9fb1c4a1ab844')
expect(response.code).to eql(204)
end
end
end
|
json.forums @forums do |forum|
json.id forum.id
json.name forum.name
json.thumbnail "https://upload.wikimedia.org/wikipedia/commons/e/e5/Post-it-note-transparent.png"
#json.artist_id album.artist ? album.artist.id : nil
end |
class ChangeTypeNull < ActiveRecord::Migration[6.1]
def change
change_column :categories, :subcategory_id, :bigint, null: true
end
end
|
EmberDataExample::Application.routes.draw do
resources :contacts
root :to => 'contacts#index'
match "/*path" => "contacts#index"
end
|
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
validates_presence_of :order_id
validates_presence_of :product_id
validates_numericality_of :quantity, integer: true, greater_than: 0
def subtotal
product.price * quantity
end
end
|
class Workout < ActiveRecord::Base
def self.search(search)
where(
'exercise_name LIKE :search
OR category LIKE :search
OR workouts.force LIKE :search
OR workouts.level LIKE :search
OR main_muscle_worked LIKE :search
OR other_muscles LIKE :search
OR mechanics_type LIKE :search', search: "%#{search}%")
end
end
|
require 'rails_helper'
describe 'viewing the rankings index' do
before do
visit new_user_session_path
@user = User.create(
email: 'user@example.com',
password: 'password',
other_residents: 2
)
@total_residents = @user.other_residents + 1
fill_in 'Email', with: 'user@example.com'
fill_in 'Password', with: 'password'
click_button 'Log in'
end
it 'displays the names of each of the residents in the house' do
names = page.all('.residents li')
expect(names.length).to eql(@total_residents)
end
it 'links to the edit ranking page for each resident' do
ranking_links = page.all('.residents li a')
expect(ranking_links.length).to eql(@total_residents)
end
it 'indicates which rankings have not yet been completed' do
expect(page).to have_content('incomplete')
end
it 'displays a link to delete a ranking' do
ranking_links = page.all('.delete-ranking')
expect(ranking_links.length).to eql(@total_residents)
end
it 'takes the user to the edit ranking page when the user clicks on a resident' do
click_on('A resident\'s ranking - incomplete', match: :first)
expect(page).to have_content('What is the most you\'re willing to pay each month?')
end
it 'renders the rankings#index page with one fewer resident when removing a resident' do
num_old_residents = page.all('.residents li').length
click_on('Remove resident', match: :first)
num_residents = page.all('.residents li').length
expect(num_residents).to eql(num_old_residents - 1)
end
it 'links to the candidates#index' do
click_on('Your saved addresses')
expect(page).to have_content('Here are the addresses you\'re interested in
ranking')
end
it 'displays a link to search for a new address' do
click_on('Search for an address')
expect(page).to have_content('Search for an address')
end
end
|
require File.dirname(__FILE__) + '/../../test_helper'
class Reputable::BadgeTest < ActiveSupport::TestCase
context "a Reputable::Badge" do
test "should be created if listed in App.reputable_badges" do
badge_name = "awesome badge"
Reputable::Badge::BADGES << badge_name
badge = Reputable::Badge.find_by_name(badge_name)
badge.should be(nil)
badge = Reputable::Badge[badge_name]
badge.class.should be(Reputable::Badge)
badge.name.should be(badge_name)
end
end
end
|
class DNA
attr_reader :dna_sequence
def initialize(dna)
@dna_sequence = dna
end
def hamming_distance(other_genetic_makeup)
index = 0
hamming_distance = 0
dna_length = dna_sequence.length
other_genetic_makeup[0, dna_length].chars.each do |nucleobase|
hamming_distance += 1 unless dna_sequence[index] == nucleobase
index += 1
end
hamming_distance
end
end
|
require 'features_helper'
feature 'Show calculation results for steam vent replacement', :js, :real_measure do
include Features::CommonSupport
let!(:user) { create(:user) }
let!(:steam_vent) do
StructureType.create!(
name: 'Steam vent',
api_name: 'distribution_system',
genus_api_name: 'distribution_system')
end
let!(:measure1) do
Measure.find_by!(api_name: 'steam_vent_replacement')
end
before do
set_up_audit_report_for_measures(
[measure1],
user: user,
substructures: [
{
name: 'Vents',
structure_type: steam_vent
}
]
)
end
scenario 'Verify measure' do
add_new_structure('Vents - White House', steam_vent.api_name)
fill_out_structure_cards(
'1 - Steam vent',
proposed: {
input_annual_gas_savings: '1000',
per_unit_cost: '2000'
}
)
fill_out_measure_level_fields(retrofit_lifetime: '10')
click_link 'Edit report data'
fill_out_audit_level_fields(gas_cost_per_therm: 1)
click_link 'Edit measures'
expect_measure_summary_values(
annual_cost_savings: '$1,000.00',
annual_gas_savings: '1,000.0',
years_to_payback: '2',
cost_of_measure: '$2,000.00',
savings_investment_ratio: '5'
)
end
end
|
Rails.application.routes.draw do
root to: "songs#index"
resources :songs, only: [:index] do
get "search", on: :collection
end
end
|
# # 这个脚本基本没有了
# 只是当时用一回吧
# 先保留着
# ----
require 'csv'
# 1. 转二期双语的信息表文件到csv
# 2. 并生成二期文件的id,中文书名,英文书名csv
BOOK_INFO = 'db/xin-book-info-category.tsv'
BOOK_INFO_CSV = 'db/xin-book-info.csv'
XIN_BOOK_TITLES = 'db/xin-book-titles.csv'
s = File.readlines BOOK_INFO
arr = s.map { |l| l.chomp.split(/\t/) }
csv = arr.map { |l| l.to_csv(force_quotes: true) }
# csv header
# "书名(英文)","书名","fenlei","nianling","bid"
csv_str = csv.join
# 1. 转二期双语的信息表文件到csv
File.write(BOOK_INFO_CSV, csv_str)
xin_book_titles = arr.map { |r| [r[4], r[1], r[0]].to_csv(force_quotes: true) }
# 2. 并生成二期文件的id,中文书名,英文书名csv
p "生成二期书名文件: #{XIN_BOOK_TITLES}"
File.write(XIN_BOOK_TITLES, xin_book_titles.join)
|
require 'spec_helper'
feature 'Starting a new game' do
context 'when on new game screen' do
scenario 'user is asked to enter name' do
visit '/new_game'
expect(page).to have_field("name")
end
end
context 'when user enters name' do
scenario 'user is taken to the game page' do
visit '/new_game'
fill_in('name', with: 'Andy')
click_button('Submit')
expect(current_path).to eq '/game_page'
end
end
context 'when user does not enter name' do
scenario "user is given name 'Player1' and is taken to the game page" do
visit '/new_game'
click_button('Submit')
expect(page).to have_content("Hello, Player1! Let the games begin!")
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :conversations
def conversations
if user_signed_in?
session[:conversations] ||= []
convs = Conversation.where("recipient_id = ? OR sender_id = ?", current_user.id, current_user.id)
if !convs.empty?
convs.each do |c|
if c.someone_offline?
p "entered offline"
session[:conversations] << c.id if (!session[:conversations].include?(c.id) && c.offline_party_id == current_user.id)
c.update(someone_offline?: false, offline_party_id: nil)
end
if c.add_recipient_to_session? && !c.someone_offline?
session[:conversations] << c.id if (!session[:conversations].include?(c.id) && (c.id_to_add_to_session == current_user.id))
c.update(add_recipient_to_session?: false, id_to_add_to_session: nil)
end
if c.window_was_closed_for.length > 0 && c.window_was_closed_for.include?(current_user.id.to_s) && c.new_messages_available_for.include?(current_user.id.to_s)
session[:conversations] << c.id if (!session[:conversations].include?(c.id))
c.window_was_closed_for = c.window_was_closed_for.delete_if{|i|i==current_user.id.to_s}
c.new_messages_available_for = c.new_messages_available_for.delete_if{|i|i==current_user.id.to_s}
c.update(window_was_closed_for: c.window_was_closed_for, new_messages_available_for: c.new_messages_available_for)
end
end
end
@users = User.all.where.not(id: current_user)
@conversations = Conversation.includes(:recipient, :messages)
.find(session[:conversations])
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:name, :stripe_card_token, :email, :password, :password_confirmation)
end
end
def require_sign_in
unless user_signed_in?
redirect_to new_user_session_url, :notice => 'Please register/log in first'
end
end
def admin_user?
if user_signed_in? && current_user.admin?
return true
else
redirect_to root_url, :notice => 'You do not have enough permissions to access this page'
end
end
end
|
# only admin access of categories
# add, edit and delete.
class Category < ActiveRecord::Base
validates :name, presence: true
has_many :events
end |
require "formula"
require "language/haskell"
class Mighttpd2 < Formula
include Language::Haskell::Cabal
homepage "http://mew.org/~kazu/proj/mighttpd/en/"
url "http://hackage.haskell.org/package/mighttpd2-3.2.0/mighttpd2-3.2.0.tar.gz"
sha1 "878a9e03ad3a62221dab22cb6412ae446368e1bd"
bottle do
sha1 "3bcfd785e9a7d222a12902e962862813593364c5" => :mavericks
sha1 "cdf75e3f624eb5434e481cd1687adee204fcd8d4" => :mountain_lion
sha1 "7ed2f8494dd3acc179b63572d2a9df104ee915f8" => :lion
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "gmp"
def install
cabal_sandbox do
cabal_install "--only-dependencies"
cabal_install "--prefix=#{prefix}"
end
cabal_clean_lib
end
test do
system "#{bin}/mighty-mkindex"
assert (testpath/"index.html").file?
end
end
|
class UsersController < ApplicationController
check_authorization
load_and_authorize_resource
before_action :authenticate_user!
before_action :load_organizations, only: [:new, :create, :edit, :update]
def index
if current_user.admin?
if params[:q]
@persons = User
.where.not(role: 'admin')
.where("users.name ILIKE :search", search: "%#{params[:q]}%")
else
@persons = User.where.not(role: 'admin').all
end
elsif current_user.account_manager?
if params[:q]
ids = current_user
.organization
.users
.where("users.name ILIKE :search", search: "%#{params[:q]}%")
.pluck(:id)
else
ids = current_user.organization.users.all.pluck(:id)
ids.delete(current_user.id)
end
@persons = User.where(id: ids)
else
@persons = User.where(id: current_user.id)
end
end
def new
@person = User.new
end
def create
@person = User.create(user_params)
if @person.valid?
# skip validation
@person.skip_confirmation!
@person.save!
flash[:notice] = I18n.t('persons.created')
return redirect_to persons_path
else
flash[:errors] = @person.errors
render :new
end
end
def show
@person = User.find(params[:id])
end
def edit
if (current_user.id == params[:id])
flash[:alert] = "You cannot edit your own role"
return redirect_to root_path
end
@person = User.find(params[:id])
load_roles(@person.organization)
end
def update
@person = User.find(params[:id])
load_roles(@person.organization)
if @person.update(user_params)
flash[:notice] = I18n.t('persons.updated')
return redirect_to persons_path
else
flash[:errors] = @person.errors
render :edit
end
end
def destroy
user = User.find(params[:id])
user.configuration.delete
user.delete
flash[:alert] = I18n.t('persons.deleted')
return redirect_to persons_path
end
private
def load_organizations
@organizations = Organization.all.collect {|o| [o.name, o.id]}
@organizations.unshift(["Select Organization", nil])
end
def load_roles(organization)
if organization.users.where(role: 'account_manager').count < 1
@roles = current_user.can_create_roles
@roles.unshift(["Select Role", nil])
else
@roles = [User::ROLES[2]]
@roles.unshift(["Select Role", nil])
end
end
def user_params
params.require( :user)
.permit( :name,
:email,
:phone,
:avatar,
:role,
:organization_id,
:password,
:password_confirmation)
end
end
|
module Ultimaker
class Printer
class System
attr_reader :country
end
end
end
|
module Shipit
module StacksHelper
COMMIT_TITLE_LENGTH = 79
def redeploy_button(commit)
url = new_stack_deploy_path(@stack, sha: commit.sha)
classes = %W(btn btn--primary deploy-action #{commit.state})
unless commit.stack.deployable?
classes.push(ignore_lock? ? 'btn--warning' : 'btn--disabled')
end
caption = 'Redeploy'
caption = 'Locked' if commit.stack.locked? && !ignore_lock?
caption = 'Deploy in progress...' if commit.stack.active_task?
link_to(caption, url, class: classes)
end
def ignore_lock?
params[:force].present?
end
def deploy_button(commit)
url = new_stack_deploy_path(@stack, sha: commit.sha)
classes = %W(btn btn--primary deploy-action #{commit.state})
if deploy_button_disabled?(commit)
classes.push(params[:force].present? ? 'btn--warning' : 'btn--disabled')
end
link_to(deploy_button_caption(commit), url, class: classes)
end
def github_change_url(commit)
commit.pull_request_url || github_commit_url(commit)
end
def render_commit_message(commit)
message = commit.pull_request_title || commit.message
content_tag(:span, emojify(message.truncate(COMMIT_TITLE_LENGTH)), class: 'event-message')
end
def render_commit_message_with_link(commit)
link_to(render_commit_message(commit), github_change_url(commit), target: '_blank')
end
def render_commit_id_link(commit)
if commit.pull_request?
pull_request_link(commit) + " (#{render_raw_commit_id_link(commit)})".html_safe
else
render_raw_commit_id_link(commit)
end
end
def pull_request_link(commit)
link_to("##{commit.pull_request_number}", commit.pull_request_url, target: '_blank', class: 'number')
end
def render_raw_commit_id_link(commit)
link_to(commit.short_sha, github_commit_url(commit), target: '_blank', class: 'number')
end
private
def deploy_button_disabled?(commit)
!commit.deployable? || !commit.stack.deployable?
end
def deploy_button_caption(commit)
state = commit.status.state
state = 'locked' if commit.stack.locked? && !ignore_lock?
if commit.deployable?
state = commit.stack.active_task? ? 'deploying' : 'enabled'
end
t("deploy_button.caption.#{state}")
end
end
end
|
feature 'Attack_Player' do
scenario "Attacks player_2 and gets confirmation" do
sign_in_and_play
click_button "Attack"
expect(page).to have_content("Florence attacked Emma")
end
scenario "The attack reduces player_2's health points by 10" do
sign_in_and_play
click_button "Attack"
expect(page).to have_content("Emma's health was reduced by 10 points")
expect(page).to have_content("Emma hitpoints: 50")
end
end
|
class Task < ApplicationRecord
belongs_to :project
scope :sort_by_priority, -> { order(priority: :asc) }
end
|
namespace :rails do
desc "Tail Rails remote log"
task :log do
on roles(:app) do
execute "tail -f #{shared_path}/log/#{fetch(:rails_env)}.log"
end
end
end
|
class Api::Admin::AdminUsersController < Api::Admin::ApiController
rescue_from StandardError, with: :show_errors
def index
@admin_users = AdminUser.all.order_by_recent
render json: @admin_users.map { |admin_user| filter_returned_parameters(admin_user) }
end
private
def fetch_admin_user
@admin_user = AdminUser.find_by!(uuid: params[:uuid])
end
def filter_returned_parameters(admin_user)
admin_user.slice("name")
end
def show_errors(exception)
render json: { errors: [exception.message] }, status: :unprocessable_entity
end
end
|
include_recipe '::install_requirements'
if node['certie']['email'].nil?
raise 'Email attribute can not be nil'
end
if node['certie']['organization'].nil?
raise 'Organization attribute can not be nil'
end
if node['certie']['domains'].empty?
raise 'Domain names are not configured'
end
directory node['certie']['path'] do
action :create
end |
### WHEN ###
When /^I go to (.+)$/ do |page|
visit path_to(page)
end
### THEN ###
Then /^I should be on (.+)$/ do |_expected_page|
current_path.should == path_to(_expected_page)
end
Then /^I should be redirected to (.+)$/ do |_expected_page|
current_path.should == path_to(_expected_page)
end
|
# == Schema Information
#
# Table name: faq_audiences
#
# id :integer not null, primary key
# faq_id :integer not null
# audience_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class FaqAudience < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :faq
belongs_to :audience
end
|
module ApplicationHelper
def request_url
"#{request.protocol}#{request.host_with_port}#{request.fullpath}"
end
def add_breadcrumb_for_category(category)
add_breadcrumb_for_category category.parent_category if !category.parent_category.nil?
add_breadcrumb category.name, category_path(category)
end
end
|
class CreateSpSkillSets < ActiveRecord::Migration
def change
create_table :sp_skill_sets do |t|
t.integer :service_provider_id
t.integer :skill_id
t.boolean :primary
t.timestamps null: false
end
end
end
|
module Util
class FieldComposer
def self.compose(types)
ret = types.reduce({}) do |acc, type|
acc.merge(type.fields)
end
ret
end
end
end |
Given(/^I am logged in$/) do
@user = FactoryGirl.create(:user)
visit new_user_session_path
fill_in :user_email, with: @user.email
fill_in :user_password, with: @user.password
click_on 'Log in'
expect(current_path).to eq(gift_ideas_path)
end
When(/^I visit the "(.*?)" page$/) do |page|
path = nil
if page == 'create user'
path = new_user_path
elsif page == 'edit user'
path = edit_user_path(User.last)
elsif page == 'users index'
path = users_path
elsif page == 'wish list'
path = gift_ideas_path
elsif page == 'edit wish'
path = edit_gift_idea_path(GiftIdea.last)
end
expect(path).to_not be_nil
visit path
end
When(/^I press "(.*?)"$/) do |button|
click_on button
end
Then(/^I should be on the "(.*?)" page$/) do |page|
path = nil
if page == 'show user'
path = user_path(User.last)
elsif page == 'users index'
path = users_path
elsif page == 'wish list'
path = gift_ideas_path
elsif page == 'show wish'
path = gift_idea_path(GiftIdea.last)
end
expect(path).to_not be_nil
end
|
require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get root_url
assert_response :success
end
test "should get callback" do
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
mock_spotify_user = Minitest::Mock.new
mock_playlist = Minitest::Mock.new
mock_playlist.expect :id, 'id'
mock_spotify_user.expect :create_playlist!, mock_playlist, ['WhatsPlaying']
mock_spotify_user.expect :id, 'id'
credentials = { 'token' => 'spotify-token', 'refresh_token' => 'spotify-refresh-token' }
mock_spotify_user.expect :credentials, credentials
mock_spotify_user.expect :credentials, credentials
RSpotify::User.stub :new, mock_spotify_user do
get auth_spotify_callback_url
assert_response :success
assert_mock mock_spotify_user
end
end
end
|
class PersonAttrType < ActiveRecord::Base
attr_accessible :name, :sort
belongs_to :person
has_many :property_contacts
def self.find_owner
PersonAttrType.find(:first, :conditions => ["name = lower(?)", "Owner"])
end
end
|
Rails.application.routes.draw do
resources :enroll_studies, only: [:create, :destroy]
resources :programs
resources :users, only: [:show] do
# nested resource for people
resources :people, only: [:show, :index, :create, :destroy, :update] do
resources :enroll_studies
end
end
post "/signup", to: "users#create"
get "/me", to: "users#show"
post "/login", to: "sessions#create"
delete "/logout", to: "sessions#destroy"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
Rails.application.routes.draw do
get 'tasks/index'
get 'tasks/update'
get 'tasks/destroy'
get 'tasks/create'
get 'categories/index'
get 'categories/update'
get 'categories/destroy'
get 'categories/create'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
scope '/api/1.0' do
resources :categories, :tasks
end
end
|
module Zenform
module Param
class Trigger < Base
FIELDS = %w{title position conditions actions}
FIELDS.each { |field| attr_reader field }
attr_reader :ticket_fields, :ticket_forms
def initialize(content, ticket_fields: {}, ticket_forms: {}, **_params)
super
@ticket_fields = ticket_fields
@ticket_forms = ticket_forms
normalize
end
def validate!
validate_conditions!
validate_actions!
end
def format
to_h.merge "conditions" => formatted_conditions, "actions" => actions.map(&:format)
end
private
def normalize
@conditions = conditions.inject({}) do |h, (assoc_rule, conds)|
h.merge assoc_rule => conds.map { |c| Condition.new(c, ticket_fields: ticket_fields, ticket_forms: ticket_forms) }
end
@actions = actions.map { |a| Action.new(a, ticket_fields: ticket_fields, ticket_forms: ticket_forms) }
end
def validate_conditions!
flatten_conditions = conditions["all"] + conditions["any"]
validate_field! "conditions", flatten_conditions
flatten_conditions.each(&:validate!)
end
def validate_actions!
validate_field! "actions"
actions.each(&:validate!)
end
def formatted_conditions
compact_conditions = reject_blank_field(conditions)
compact_conditions.inject({}) { |h, (key, value)| h.merge key => value.map(&:format) }
end
end
end
end
|
class Vehicle < ApplicationRecord
has_many :orders, dependent: :destroy
validates :name, presence: true
validates :detail, presence: true
validates :price, presence: true
validates :location, presence: true
end
|
require 'spec_helper'
describe GapIntelligence::InStoreImage do
include_examples 'Record'
describe 'attributes' do
subject(:in_store_image) { described_class.new build(:in_store_image) }
it 'has category version id' do
expect(subject).to respond_to(:category_version_id)
end
it 'has merchant id' do
expect(subject).to respond_to(:merchant_id)
end
it 'has start_date' do
expect(subject).to respond_to(:start_date)
end
it 'has end_date' do
expect(subject).to respond_to(:end_date)
end
it 'has category_version_name' do
expect(subject).to respond_to(:category_version_name)
end
it 'has merchant_name' do
expect(subject).to respond_to(:merchant_name)
end
it 'has pricing_images' do
expect(subject).to respond_to(:pricing_images)
end
it 'has created_at' do
expect(subject).to respond_to(:created_at)
end
it 'has updated_at' do
expect(subject).to respond_to(:updated_at)
end
end
end
|
# encoding: utf-8
#
# Cargo culted from: https://gist.github.com/pasela/9392115
require "timeout"
# Capture the standard output and the standard error of a command.
# Almost same as Open3.capture3 method except for timeout handling and return value.
# See Open3.capture3.
#
# result = capture3_with_timeout([env,] cmd... [, opts])
#
# The arguments env, cmd and opts are passed to Process.spawn except
# opts[:stdin_data], opts[:binmode], opts[:timeout], opts[:signal]
# and opts[:kill_after]. See Process.spawn.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# If opts[:timeout] is specified, SIGTERM is sent to the command after specified seconds.
#
# If opts[:signal] is specified, it is used instead of SIGTERM on timeout.
#
# If opts[:kill_after] is specified, also send a SIGKILL after specified seconds.
# it is only sent if the command is still running after the initial signal was sent.
#
# The return value is a Hash as shown below.
#
# {
# :pid => PID of the command,
# :status => Process::Status of the command,
# :stdout => the standard output of the command,
# :stderr => the standard error of the command,
# :timeout => whether the command was timed out,
# }
module CaptureWithTimeout
def capture3_with_timeout(*cmd)
spawn_opts = Hash === cmd.last ? cmd.pop.dup : {}
opts = {
:stdin_data => spawn_opts.delete(:stdin_data) || "",
:binmode => spawn_opts.delete(:binmode) || false,
:timeout => spawn_opts.delete(:timeout),
:signal => spawn_opts.delete(:signal) || "TERM",
:kill_after => spawn_opts.delete(:kill_after),
}
in_r, in_w = IO.pipe
out_r, out_w = IO.pipe
err_r, err_w = IO.pipe
in_w.sync = true
if opts[:binmode]
in_w.binmode
out_r.binmode
err_r.binmode
end
spawn_opts[:in] = in_r
spawn_opts[:out] = out_w
spawn_opts[:err] = err_w
result = {
:pid => nil,
:status => nil,
:stdout => nil,
:stderr => nil,
:timeout => false,
}
out_reader = nil
err_reader = nil
wait_thr = nil
begin
Timeout.timeout(opts[:timeout]) do
result[:pid] = spawn(*cmd, spawn_opts)
wait_thr = Process.detach(result[:pid])
in_r.close
out_w.close
err_w.close
out_reader = Thread.new { out_r.read }
err_reader = Thread.new { err_r.read }
in_w.write opts[:stdin_data]
in_w.close
result[:status] = wait_thr.value
end
rescue Timeout::Error
result[:timeout] = true
pid = spawn_opts[:pgroup] ? -result[:pid] : result[:pid]
Process.kill(opts[:signal], pid)
if opts[:kill_after]
unless wait_thr.join(opts[:kill_after])
Process.kill("KILL", pid)
end
end
ensure
result[:status] = wait_thr.value if wait_thr
result[:stdout] = out_reader.value if out_reader
result[:stderr] = err_reader.value if err_reader
out_r.close unless out_r.closed?
err_r.close unless err_r.closed?
end
result
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "subcheat/version"
Gem::Specification.new do |s|
s.name = 'subcheat'
s.version = Subcheat::VERSION
s.authors = ['Arjan van der Gaag']
s.email = ['arjan@arjanvandergaag.nl']
s.homepage = 'http://github.com/avdgaag/subcheat'
s.summary = 'Wrapper for Subversion CLI'
s.description = 'Wrap the Subversion CLI to extract some usage patterns into commands'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest'
s.add_development_dependency 'cucumber'
s.add_development_dependency 'mocha', '>= 0.9.8'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'rdoc', '~> 3.9'
end
|
#!/usr/bin/env ruby
# encoding : utf-8
require "shellwords"
require 'fileutils'
# Given an mkd file, will create the matching epub file
if `which ebook-convert` == ''
puts "Unable to find ebook-convert, please install calibre"
exit
end
ARGV.each do |file|
mkdFile = File.expand_path(file)
ext = File.extname(file)
basename = File.basename(file)
coverFile = mkdFile.gsub(/#{ext}$/, '.jpg')
epubFile = mkdFile.gsub(/#{ext}$/, '.epub')
txtFile = mkdFile.gsub(/#{ext}$/, '.txt')
# Only operate on mkd files
next unless ext == '.mkd' || ext == '.md'
# Make a backup of the existing epub file if one is found
if File.exists?(epubFile)
File.rename(epubFile, epubFile+'.bak')
end
# ebook-convert only works on .txt file so we'll create a copy of the mkd
FileUtils.copy(mkdFile, txtFile)
# Building option list
convertOptions = [
txtFile.shellescape,
epubFile.shellescape,
"--formatting-type markdown",
"--paragraph-type off",
"--chapter '//h:h2'"
]
# Adding cover if found
if File.exists?(coverFile)
convertOptions << "--cover #{coverFile.shellescape}"
convertOptions << "--preserve-cover-aspect-ratio"
else
puts "WARNING: No cover file found, epub will have no cover"
end
# Converting file
puts "Converting to epub"
%x[ebook-convert #{convertOptions.join(' ')}]
# Removing the now useless txt file
File.delete(txtFile)
# Updating metadata
%x[ebook-metadata-update #{epubFile.shellescape}]
end
|
class Planet
attr_reader :name, :color, :mass_kg, :distance_from_sun_km, :fun_fact
def initialize(name, color, mass_kg, distance_from_sun_km, fun_fact)
raise ArgumentError.new("Mass(kg) should be a number that greater than zero: #{ mass_kg }") if !(mass_kg.to_f > 0)
@mass_kg = mass_kg.to_f
raise ArgumentError.new("Distance from sun (km) should be a number that greater than zero: #{ distance_from_sun_km }") if !(distance_from_sun_km.to_f > 0)
@distance_from_sun_km = distance_from_sun_km.to_f
@name = name
@color = color
@fun_fact = fun_fact
end
def summary
return "#{ @name } is #{ @color }, and it weights #{ @mass_kg } kg and #{ @distance_from_sun_km } km away from sun. \nThe fun fact about it: #{ @fun_fact.downcase }\n\n"
end
end
|
class ContactForm < Noodall::Component
key :form_id, String
has_one :form, :class => Noodall::Form
module ClassMethods
def form_options
lists = Noodall::Form.all(:fields => [:id, :title], :order => 'title ASC')
lists.collect{|l| [l.title, l.id.to_s]}
end
end
extend ClassMethods
end
|
Redmine::Plugin.register :redmine_bulk_ticket do
name 'Redmine Bulk Ticket plugin'
author 'Kunihiko Miyanaga'
description 'Supports bulk ticketing.'
version '0.0.1'
url 'https://github.com/miyanaga/redmine-bulk-ticket'
author_url 'http://www.ideamans.com/'
project_module :bulk_ticket do
permission :bulk_ticket, :issues => :bulk_ticket
end
end
require 'issue'
require 'issue_query'
require 'queries_helper'
class IssueQuery
self.available_columns << QueryColumn.new(:sub_issues, :inline => false)
end
module QueriesHelper
def self.included(mod)
mod.class_eval do
alias_method_chain :column_value, :my_column_value
end
end
def column_value_with_my_column_value(column, issue, value)
if column.name == :sub_issues
value
else
column_value_without_my_column_value(column, issue, value)
end
end
end
class SubIssuesWrapper
include ERB::Util
include ApplicationHelper
include ActionView::Helpers::FormTagHelper
include ActionDispatch::Routing
include Rails.application.routes.url_helpers
def initialize(issue)
@issue = issue
end
def render
return nil if @issue.children.nil? or @issue.children.length < 1
s = '<table class="list issues">'
@issue.children.each do |child|
css = "issue issue-#{child.id}"
s << content_tag('tr',
content_tag('td', h(child.project.name)) +
content_tag('td', h(child.status)) +
content_tag('td', child.assigned_to.name) +
content_tag('td', progress_bar(child.done_ratio, :width => '80px')),
:class => css)
end
s << '</table>'
html = s.html_safe
html
end
end
class Issue
def sub_issues
SubIssuesWrapper.new(self).render
end
end
class BulkTicketHooks < Redmine::Hook::Listener
include ActionView::Helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers
def self.enabled_bulk_ticket_module(project)
end
def controller_issues_edit_after_save(context = {})
current_project = context[:issue].project
return unless current_project.module_enabled? :bulk_ticket
return unless User.current.allowed_to? :bulk_ticket, current_project
params = context[:params]
values = params[:issue]
orig = context[:issue]
msg = I18n.t(:bulk_ticket_new_desc, {
:url => url_for(:controller => 'issues', :action => 'show', :id => orig.id),
:id => orig.id
})
if values[:subprojects].present?
values[:subprojects].keys.each do |pid|
project = Project.find(pid)
issue = Issue.new(parent_issue_id: orig.id, root_id: orig.root_id)
issue.attributes = orig.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
issue.description = msg
issue.project = project
issue.save!
end
end
if values[:members].present?
values[:members].keys.each do |uid|
user = User.find(uid)
issue = Issue.new(parent_issue_id: orig.id, root_id: orig.root_id)
issue.attributes = orig.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
issue.description = msg
issue.assigned_to_id = user.id
issue.save!
end
end
end
class ViewHook < Redmine::Hook::ViewListener
def view_issues_form_details_bottom(context = {})
return unless context[:project].module_enabled? :bulk_ticket
return unless User.current.allowed_to? :bulk_ticket, context[:project]
issue = context[:issue]
return if issue.id.nil?
project = context[:project]
subprojects = project.children.visible.all
members = project.members.map(&:user)
subproject_relations = {}
member_relations = {}
issue.children.each do |c|
if c.project.id != project.id
subproject_relations[c.project.id] = true
elsif c.assigned_to.present?
c.assigned_to.members.map(&:user).each do |u|
member_relations[u.id] = true
end
end
end
context[:controller].send :render_to_string,
partial: 'issues/bulk_ticket',
locals: {
context: context,
subprojects: subprojects,
subproject_relations: subproject_relations,
members: members,
member_relations: member_relations,
}
end
end
end |
describe Messages do
describe '.create' do
it 'creates a new peep' do
message = Messages.create(username: 'leoncross', name: 'leon', message: 'My very first peep!!!')
expect(message).to be_a Messages
expect(message.username).to eq 'leoncross'
expect(message.name).to eq 'leon'
expect(message.message).to eq 'My very first peep!!!'
end
end
describe '.all' do
it 'returns a list of messages in reverse cronological order' do
Messages.create(username: 'abarskey', name: 'andrey', message: 'a small message')
Messages.create(username: 'sjohn', name: 'steve', message: 'another message by steve')
message = Messages.create(username: 'leoncross', name: 'leon', message: 'My very first peep!!!')
messages = Messages.all
expect(messages.length).to eq 3
expect(messages.first).to be_a Messages
expect(messages.first.id).to eq message.id
expect(messages.first.username).to eq 'leoncross'
expect(messages.first.name).to eq 'leon'
end
end
end
|
require 'spec_helper'
describe "languages/show" do
before(:each) do
@language = assign(:language, stub_model(Language,
:title => "Title",
:reading => "Reading",
:writting => "Writting",
:perception => "Perception",
:conversation => "Conversation",
:teacher_id => 1
))
end
it "renders attributes in <p>" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
rendered.should match(/Title/)
rendered.should match(/Reading/)
rendered.should match(/Writting/)
rendered.should match(/Perception/)
rendered.should match(/Conversation/)
rendered.should match(/1/)
end
end
|
class Team < ApplicationRecord
has_many :projects, dependent: :destroy
has_many :users
accepts_nested_attributes_for :users, allow_destroy: true
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Environment variables (ENV['...']) can be set in the file config/application.yml.
# See http://railsapps.github.io/rails-environment-variables.html
# puts 'DEFAULT USERS'
# user = User.find_or_create_by_email :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup
# puts 'user: ' << user.email
require 'ffaker'
def sample_text
#(1..10).map{|i|"<p>#{Faker::HTMLIpsum.fancy_string}</p>"}.join
end
begin
15.times do
User.new.tap do |u|
u.email = Faker::Internet.email
u.password = 'password'
u.name = Faker::Name.name
u.save!
end
end
45.times do
Kid.new.tap do |k|
k.name = Faker::Name.first_name
k.save!
end
end
kid = Kid.all.each do |k|
user = User.order( 'RANDOM()' ).first
relation = Relationship.create ({kid: k, user: user})
relation.save!
end
Kid.all.each do |k|
rand(4).times do
kid = k.reminders.create
kid.name = Faker::Product.product_name
kid.save!
end
end
end
|
require 'test_helper'
module DataPlugins::Annotation
class HasAnnotationsTest < ActiveSupport::TestCase
setup do
@annotation_category = AnnotationCategory.create(title: 'Kategorie1')
end
[:orga, :event, :offer].each do |entry_factory|
should "deliver annotations for #{entry_factory}" do
entry = create(entry_factory)
assert_equal [], entry.annotations.all
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
assert_equal [annotation], entry.annotations.all
end
should "deliver annotations by updated_at for #{entry_factory}" do
entry = create(entry_factory)
assert_equal [], entry.annotations.all
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
annotation2 = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das2',
entry: entry
)
annotation3 = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das3',
entry: entry
)
ActiveRecord::Base.record_timestamps = false
now = 10.minutes.from_now
annotation2.update(updated_at: now)
ActiveRecord::Base.record_timestamps = true
assert_equal [annotation2, annotation3, annotation], entry.annotations.all
end
should "add annotation for #{entry_factory}" do
entry = create(entry_factory)
annotation = entry.save_annotation(ActionController::Parameters.new(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
))
assert_equal [annotation], entry.annotations.all
end
should "set creator on add annotation for #{entry_factory}" do
entry = create(entry_factory)
annotation = entry.save_annotation(ActionController::Parameters.new(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
))
assert_equal Current.user, annotation.creator
assert_equal Current.user, annotation.last_editor
end
should "fail adding with wrong category for #{entry_factory}" do
entry = create(entry_factory)
exception = assert_raises(ActiveRecord::RecordInvalid) {
annotation = entry.save_annotation(ActionController::Parameters.new(
annotation_category_id: 999999999,
detail: 'Mache das',
))
}
assert_match 'Kategorie existiert nicht.', exception.message
end
should "fail adding without category for #{entry_factory}" do
entry = create(entry_factory)
exception = assert_raises(ActiveRecord::RecordInvalid) {
annotation = entry.save_annotation(ActionController::Parameters.new(
detail: 'Mache das',
))
}
assert_match 'Kategorie fehlt.', exception.message
end
should "update annotation for #{entry_factory}" do
entry = create(entry_factory)
annotation_category2 = AnnotationCategory.create(title: 'Kategorie2')
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
entry.save_annotation(ActionController::Parameters.new(
id: annotation.id,
annotation_category_id: annotation_category2.id,
detail: 'Mache das jetzt so',
))
assert_equal 1, entry.annotations.count
annotation = entry.annotations.first
assert_equal annotation_category2.id, annotation.annotation_category_id
assert_equal 'Mache das jetzt so', annotation.detail
entry.save_annotation(ActionController::Parameters.new(
id: annotation.id,
detail: 'Mache das jetzt doch nicht so',
))
assert_equal 1, entry.annotations.count
annotation = entry.annotations.first
assert_equal 'Mache das jetzt doch nicht so', annotation.detail
end
should "set editor on update annotation for #{entry_factory}" do
entry = create(entry_factory)
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
assert_equal Current.user, annotation.last_editor
user2 = create(:user)
Current.stubs(:user).returns(user2)
annotation.update(detail: 'Yeah!!! Getan')
assert_equal user2, annotation.last_editor
end
should "fail update if annotation does not exist for #{entry_factory}" do
entry = create(entry_factory)
exception = assert_raises(ActiveRecord::RecordNotFound) {
entry.save_annotation(ActionController::Parameters.new(
id: 123456,
detail: 'Mache das'
))
}
end
should "fail update if annotation belongs to different entry for #{entry_factory}" do
entry = create(entry_factory)
entry2 = create(entry_factory)
entry3 = create(:event)
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
exception = assert_raises(ActiveRecord::RecordInvalid) {
entry2.save_annotation(ActionController::Parameters.new(
id: annotation.id,
detail: 'Mache das jetzt anders'
))
}
assert_match 'Eigentümer kann nicht geändert werden.', exception.message
exception = assert_raises(ActiveRecord::RecordInvalid) {
entry3.save_annotation(ActionController::Parameters.new(
id: annotation.id,
detail: 'Mache das jetzt anders'
))
}
assert_match 'Eigentümer kann nicht geändert werden.', exception.message
end
should "remove annotation for #{entry_factory}" do
entry = create(entry_factory)
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
assert_difference 'Annotation.count', -1 do
entry.delete_annotation(id: annotation.id)
end
end
should "fail remove annotation if annotation not found for #{entry_factory}" do
entry = create(entry_factory)
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
assert_no_difference 'Annotation.count' do
exception = assert_raises(ActiveRecord::RecordNotFound) {
entry.delete_annotation(id: 987989797)
}
end
end
should "remove annotation if entry gets removed for #{entry_factory}" do
entry = create(entry_factory)
annotation = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das',
entry: entry
)
annotation2 = Annotation.create(
annotation_category_id: @annotation_category.id,
detail: 'Mache das auch noch',
entry: entry
)
assert_difference 'Annotation.count', -2 do
entry.destroy
end
end
end
end
end
|
class Member < ApplicationRecord
has_many :designation_profiles, dependent: :destroy
has_many :designation_accounts, through: :designation_profiles
has_many :donations, through: :designation_accounts
has_many :donor_accounts, through: :donations
validates :name, :email, :access_token, presence: true
before_validation :create_access_token, on: :create
protected
def create_access_token
self.access_token = SecureRandom.base58(24)
end
end
|
require 'rails_helper'
RSpec.describe TutorialVideo, :type => :model do
xdescribe 'allow mass assignment of' do
it { is_expected.to allow_mass_assignment_of(:title) }
it { is_expected.to allow_mass_assignment_of(:url) }
end
end
|
class BookSubject < ActiveRecord::Base
before_validation on: [:create, :update] do
self.created_at = Date.today
end
attr_accessible :book_id, :subject_id
end
|
class AddNewFabricColumns < ActiveRecord::Migration
def change
add_column :fabrics, :meters_sold, :decimal, null: false, default: 0
add_column :fabrics, :rolls_sold, :integer, null: false, default: 0
add_column :fabrics, :total_profit, :decimal, null: false, default: 0
end
end |
require "formula"
class Nlopt < Formula
homepage "http://ab-initio.mit.edu/nlopt/"
url "http://ab-initio.mit.edu/nlopt/nlopt-2.4.1.tar.gz"
sha1 "181181a3f7dd052e0740771994eb107bd59886ad"
def install
ENV.deparallelize
system "./configure", "--with-cxx",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
end
|
class AddNumberToGotFixedIssue < ActiveRecord::Migration
def change
add_column :got_fixed_issues, :number, :integer
add_column :got_fixed_issues, :vendor_id, :string
end
end
|
# Copyright (c) 2015 - 2020 Ana-Cristina Turlea <turleaana@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
class CohortsController < AdminController
before_action :set_cohort, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token
respond_to :html, :js
include CohortsHelper
def index
@cohorts = Cohort.all
@departments_select = Department.all
end
def cohort_list
if params['department'] != ''
@cohorts = Cohort.order(:name).where(department_id: params['department'])
else
@cohorts = Cohort.order(:name)
end
respond_to do |format|
format.js
end
end
def edit
end
def update
@cohort.update(cohort_params)
@cohorts = Cohort.all
@departments_select = Department.all
end
def new
@cohort = Cohort.new
end
def create
@cohort = Cohort.new(cohort_params)
@cohort.save
@cohorts = Cohort.all
@departments_select = Department.all
respond_to do |format|
format.js
end
end
def delete
@cohort = Cohort.find(params[:cohort_id])
end
def destroy
@cohort.destroy
@departments_select = Department.all
@cohorts = Cohort.all
end
require 'csv'
def import
@errors =[]
if request.post?
CSV.parse params[:csv] do |row|
dep = Department.find_by_name(row[4].to_s.squish)
terminal = row[1].to_s.squish.downcase == 'da' ? true : false
if !dep.nil?
Cohort.create(name: row[0].to_s.squish, is_terminal: terminal, students_number: row[2], optionals_number: row[3], department_id: dep.id)
end
end
@cohorts = Cohort.all
@departments_select = Department.all
end
respond_to do |format|
format.js
end
end
def download
cohorts = []
Cohort.pluck(:name, :is_terminal, :students_number, :optionals_number, :department_id).each do |cohort|
cohort[1] = cohort[1] == true ? 'DA' : 'NU'
cohort[4] = Department.find_by_id(cohort[4]).name
cohorts << cohort
end
send_data cohorts_as_csv(cohorts), filename: "Grupe.csv", type: 'application/csv', disposition: 'attachment'
end
require 'net/http'
require 'rest_client'
require 'json'
def import_from_app
@errors =[]
str = "#{API_URL}groups?oauth_token=#{@current_user.token}"
info = JSON.parse RestClient.get str, {:accept => :json}
if not info['error'].nil?
redirect_to logout_path
return
end
print info['data'].inspect
info['data'].each do |ch|
# TODO cohort.optionals_number
old_cohort = Cohort.find_by_name ch[0]
department_name = ch[1]['domeniu'] == 'TCI' ? 'CTI' : ch[1]['domeniu']
department = Department.find_by_name department_name
if old_cohort.nil?
cohort = Cohort.new
cohort.name = ch[0]
cohort.is_terminal = ch[1]['an_terminal'] == 'DA'
cohort.department = department
cohort.students_number = ch[1]['numar_studenti']
cohort.save
else
old_cohort.is_terminal = ch[1]['an_terminal'] == 'DA'
old_cohort.department = department
old_cohort.students_number = ch[1]['numar_studenti']
old_cohort.save
end
end
@cohorts = Cohort.all
@departments_select = Department.all
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cohort
@cohort = Cohort.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cohort_params
params.require(:cohort).permit(:name, :is_terminal, :students_number, :optionals_number, :department_id)
end
end
|
# frozen_string_literal: true
module Timer
class TimerJob
def initialize(interval, base)
@interval = interval
@base = base
@mtime = Time.now
trigger
end
def mtime
@mtime
end
def result
@mtime
end
def trigger
now = Time.now
next_trigger = @base + (((now - @base) / @interval).to_i + 1) * @interval
EventMachine.add_timer(next_trigger - now) do
@mtime = Time.now
Trigger.trigger
trigger
end
end
def to_s
"Timer(#{@interval},#{@base})"
end
end
def timer(interval, base: nil)
base ||= Time.at(0)
[TimerJob.new(interval, base)]
end
end
|
require 'benchmark'
require 'prime'
# This is the largest valid bound for the prime pandigital because
# every other pandigital number bounds is divisible by 3, save for
# this and 4321.
LARGEST_PANDIGITAL = 7654321
# Returns true if an n-digit number has digits [1, n] appear
# at most once.
def pandigital?(n)
digits = n.to_s.chars.map(&:to_i)
# The correct digits for a number to be an n-pandigital.
pandigital_digits = (1..digits.length).to_a
return false if digits.include?("0") # Pandigitals do not contain 0.
return (digits.sort == pandigital_digits)
end
def largest_pandigital
largest_pandigital = 0
Prime.each(LARGEST_PANDIGITAL) do |prime|
next unless pandigital?(prime)
largest_pandigital = prime if prime > largest_pandigital
end
return largest_pandigital
end
time = Benchmark.measure do
puts "The largest pandigital prime is #{largest_pandigital}"
end
puts "Time elapsed (in seconds): #{time}"
|
class FeedsController < ApplicationController
before_action :set_feed, only: [:show, :edit, :update, :destroy]
# GET /feeds
# GET /feeds.json
def index
@feeds = Feed.all
end
# GET /feeds/1
# GET /feeds/1.json
def show
end
# GET /feeds/new
def new
@feed = Feed.new
end
# GET /feeds/1/edit
def edit
end
# POST /feeds
# POST /feeds.json
def create
source_url = feed_params["source_url"]
uri = URI.parse(source_url)
unless uri.class == URI::HTTP
flash[:danger] = "Invalid source_url. It should start with 'http://' like 'http://www.myhost.com/my_transit.zip'."
redirect_to new_feed_path
else
# Create host.
host_name = uri.host
host = FeedHost.where(:name => host_name).first_or_create
feed_name = uri.path.split("/").last
unless feed_name.is_a?(String) && feed_name.ends_with?(".zip")
flash[:danger] = "Invalid source_url. After the host, it should contain a file name ending with '.zip' like 'http://www.myhost.com/my_transit.zip'."
redirect_to new_feed_path
else
# Create feed.
@feed = Feed.where(
:source_url => source_url,
:host_id => host.id
).first_or_initialize
@feed.update_attributes(:name => feed_name)
respond_to do |format|
if @feed.save
format.html {
flash[:success] = 'Feed was successfully created.'
redirect_to @feed
}
format.json { render :show, status: :created, location: @feed }
else
format.html { render :new }
format.json { render json: @feed.errors, status: :unprocessable_entity }
end
end
end
end
end
# PATCH/PUT /feeds/1
# PATCH/PUT /feeds/1.json
def update
respond_to do |format|
if @feed.update(feed_params)
format.html {
flash[:success] = 'Feed was successfully updated.'
redirect_to @feed
}
format.json { render :show, status: :ok, location: @feed }
else
format.html { render :edit }
format.json { render json: @feed.errors, status: :unprocessable_entity }
end
end
end
# DELETE /feeds/1
# DELETE /feeds/1.json
def destroy
@feed.destroy
respond_to do |format|
format.html { redirect_to feeds_url, notice: 'Feed was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_feed
@feed = Feed.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def feed_params
params.require(:feed).permit(:source_url)
end
end
|
# MatchDueOn
#
# spot - the date which something became due
# show - the date we display as the date it became due - when the spot date
# is not acceptable.
#
MatchedDueOn = Struct.new(:spot, :show) do
def <=> other
return nil unless other.is_a?(self.class)
[spot, show] <=> [other.spot, other.show]
end
end
|
# Preview all emails at http://localhost:3000/rails/mailers/notification_mailer
class NotificationMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/post_create_email
def post_create_email
NotificationMailer.post_create_email('default@email.com')
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/post_edit_email
def post_edit_email
NotificationMailer.post_edit_email('default@email.com')
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/post_delete_email
def post_delete_email
NotificationMailer.post_delete_email('default@email.com')
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/post_approve_email
def post_approve_email
NotificationMailer.post_approve_email('default@email.com')
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/comment_new_email
def comment_new_email
NotificationMailer.comment_new_email('default@email.com')
end
end
|
class CreatePrivilegesUsers < ActiveRecord::Migration[5.0]
def up
create_table :privileges_users do |t|
t.integer :privilege_id
t.integer :user_id
t.timestamps
end
add_index(:privileges_users,[:privilege_id,:user_id])
end
def down
drop_table :privileges_users
end
end
|
class WeightsController < ApplicationController
before_filter :authenticate_user!
def show
@weight = Weight.find(params[:id])
respond_to do |format|
format.html # show.html.erb
end
end
def new
@weight = Weight.new
respond_to do |format|
format.html # new.html.erb
end
end
def edit
@weight = Weight.find(params[:id])
end
def create
@weights = Weight.all
@weight = Weight.new(params[:weight])
@weight.date = Time.now
@weight.user_id = current_user.id
respond_to do |format|
if @weight.save
format.html { redirect_to(root_path, :notice => 'Weight was successfully created.') }
else
format.html { render :action => "home/index" }
end
end
end
def update
@weight = Weight.find(params[:id])
respond_to do |format|
if @weight.update_attributes(params[:weight])
format.html { redirect_to(root_path, :notice => 'Weight was successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
def destroy
@weight = Weight.find(params[:id])
@weight.destroy
respond_to do |format|
format.html { redirect_to(root_path, :notice => 'Weight was deleted.') }
end
end
end
|
require 'miq_tempfile'
require_relative 'MiqOpenStackCommon'
#
# TODO: Create common base class for MiqOpenStackInstance and MiqOpenStackImage
# and factor out common code. Also, refactor MiqVm so it can be a proper super class.
#
class MiqOpenStackInstance
include MiqOpenStackCommon
attr_reader :vmConfigFile
SUPPORTED_METHODS = [:rootTrees, :extract, :diskInitErrors, :vmConfig, :volumeManager]
def initialize(instance_id, openstack_handle)
@instance_id = instance_id
@openstack_handle = openstack_handle
@vmConfigFile = instance_id
end
def compute_service
@compute_service ||= @openstack_handle.compute_service
end
def image_service
@image_service ||= @openstack_handle.detect_image_service
end
def volume_service
@volume_service ||= @openstack_handle.detect_volume_service
end
def instance
@instance ||= compute_service.servers.get(@instance_id)
end
def snapshot_metadata
@snapshot_metadata ||= instance.metadata.length > 0 && instance.metadata.get(:miq_snapshot)
end
def snapshot_image_id
@snapshot_image_id ||= snapshot_metadata && snapshot_metadata.value
end
def unmount
return unless @miq_vm
@miq_vm.unmount
@temp_image_file.unlink
end
def create_snapshot(options = {})
log_prefix = "MIQ(#{self.class.name}##{__method__}) instance_id=[#{@instance_id}]"
$log.debug "#{log_prefix}: Snapshotting instance: #{instance.name}..."
snapshot = compute_service.create_image(instance.id, options[:name], :description => options[:desc])
$log.debug "#{log_prefix}: #{snapshot.status}"
$log.debug "#{log_prefix}: snapshot creation complete"
return snapshot.body["image"]
rescue => err
$log.error "#{log_prefix}, error: #{err}"
$log.debug err.backtrace.join("\n") if $log.debug?
raise
end
def delete_snapshot(image_id)
delete_evm_snapshot(image_id)
end
def create_evm_snapshot(options = {})
log_prefix = "MIQ(#{self.class.name}##{__method__}) instance_id=[#{@instance_id}]"
miq_snapshot = nil
if snapshot_image_id
$log.debug "#{log_prefix}: Found pointer to existing snapshot: #{snapshot_image_id}"
miq_snapshot = begin
image_service.images.get(snapshot_image_id)
rescue => err
$log.debug "#{log_prefix}: #{err}"
$log.debug err.backtrace.join("\n")
nil
end
if miq_snapshot
raise "Already has an EVM snapshot: #{miq_snapshot.name}, with id: #{miq_snapshot.id}"
else
$log.debug "#{log_prefix}: Snapshot does not exist, deleting metadata"
snapshot_metadata.destroy
end
else
$log.debug "#{log_prefix}: No existing snapshot detected for: #{instance.name}"
end
$log.debug "#{log_prefix}: Snapshotting instance: #{instance.name}..."
# TODO: pass in snapshot name.
rv = compute_service.create_image(instance.id, "EvmSnapshot", :description => options[:desc])
rv.body['image'][:service] = image_service
miq_snapshot = image_service.images.get(rv.body['image']['id'])
until miq_snapshot.status.upcase == "ACTIVE"
$log.debug "#{log_prefix}: #{miq_snapshot.status}"
sleep 1
# TODO(lsmola) identity is missing in Glance V2 object, fix it in Fog, then miq_snapshot.reload will work
# miq_snapshot.reload
miq_snapshot = image_service.images.get(miq_snapshot.id)
end
$log.debug "#{log_prefix}: #{miq_snapshot.status}"
$log.debug "#{log_prefix}: EVM snapshot creation complete"
instance.metadata.update(:miq_snapshot => miq_snapshot.id)
return miq_snapshot
rescue => err
$log.error "#{log_prefix}, error: #{err}"
$log.debug err.backtrace.join("\n") if $log.debug?
raise
end
def delete_evm_snapshot(image_id)
log_prefix = "MIQ(#{self.class.name}##{__method__}) snapshot=[#{image_id}]"
snapshot = begin
image_service.images.get(image_id)
rescue => err
$log.debug "#{log_prefix}: #{err}"
$log.debug err.backtrace.join("\n")
nil
end
if snapshot
begin
if snapshot_image_id != image_id
$log.warn "#{log_prefix}: pointer from instance doesn't match #{snapshot_image_id}"
end
$log.info "#{log_prefix}: deleting snapshot image"
image = compute_service.images.get(image_id)
image.metadata.each do |m|
next unless m.key == "block_device_mapping"
m.value.each do |volume_snapshot|
volume_snapshot_id = volume_snapshot["snapshot_id"]
delete_volume_snapshot(volume_snapshot_id) if volume_snapshot_id
end
end
snapshot.destroy
snapshot_metadata.destroy
rescue => err
$log.debug "#{log_prefix}: #{err}"
$log.debug err.backtrace.join("\n") if $log.debug?
end
else
$log.info "#{log_prefix}: no longer exists, deleting references"
end
end
private
def miq_vm
raise "Instance: #{instance.id}, does not have snapshot reference." unless snapshot_image_id
@miq_vm ||= begin
@temp_image_file = get_image_file(snapshot_image_id)
hardware = "scsi0:0.present = \"TRUE\"\n"
hardware += "scsi0:0.filename = \"#{@temp_image_file.path}\"\n"
diskFormat = disk_format(snapshot_image_id)
$log.debug "diskFormat = #{diskFormat}"
ost = OpenStruct.new
ost.rawDisk = diskFormat == "raw"
MiqVm.new(hardware, ost)
end
end
def get_image_file(image_id)
get_image_file_common(image_id)
end
def delete_volume_snapshot(volume_snapshot_id)
log_prefix = "MIQ(#{self.class.name}##{__method__}) volume snapshot=[#{volume_snapshot_id}]"
volume_snapshot = begin
volume_service.snapshots.get(volume_snapshot_id)
rescue => err
$log.info "#{log_prefix}: (error getting snapshot id) #{err}"
$log.debug err.backtrace.join("\n")
nil
end
if volume_snapshot
begin
$log.info "#{log_prefix}: deleting volume snapshot"
volume_snapshot.destroy
rescue => err
$log.info "#{log_prefix}: #{err}"
$log.debug err.backtrace.join("\n")
end
end
end
def method_missing(sym, *args)
return super unless SUPPORTED_METHODS.include? sym
return miq_vm.send(sym) if args.empty?
miq_vm.send(sym, args)
end
def respond_to_missing?(sym, *args)
if SUPPORTED_METHODS.include?(sym)
true
else
super
end
end
end
|
module Report
module InspectionDataPageWritable
include DataPageWritable
private
def date_key
:inspection_date
end
def technician_key
:inspected_by
end
end
end |
require "webrat/selenium/application_servers/base"
module Webrat
module Selenium
module ApplicationServers
class Jetty < Webrat::Selenium::ApplicationServers::Base
def start
system start_command
end
def stop
silence_stream(STDOUT) do
system stop_command
end
end
def fail
$stderr.puts
$stderr.puts
$stderr.puts "==> Failed to boot the Jetty application server... exiting!"
$stderr.puts
$stderr.puts "Verify you can start a Jetty server on port #{Webrat.configuration.application_port} with the following command:"
$stderr.puts
$stderr.puts " #{start_command}"
exit
end
def pid_file
""
end
def start_command
"mvn jetty:run &"
end
def stop_command
"mvn jetty:stop"
end
end
end
end
end
|
class AddPairToRooms < ActiveRecord::Migration[5.2]
def change
add_column :rooms, :follower_id, :integer
add_column :rooms, :followable_id, :integer
end
end
|
# == Schema Information
#
# Table name: site_types
#
# id :bigint not null, primary key
# description :text
# name :string
# superseded_by :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_site_types_on_name (name)
# index_site_types_on_superseded_by (superseded_by)
#
class SiteType < ApplicationRecord
default_scope { order(name: :asc) }
include PgSearch::Model
pg_search_scope :search,
against: :name,
using: { tsearch: { prefix: true } } # match partial words
acts_as_copy_target # enable CSV exports
has_paper_trail
has_many :sites, inverse_of: :site_type
validates :name, presence: true
def self.label
"site type"
end
end
|
Vagrant.configure("2") do |config|
config.vm.hostname = "api-runemadsen-com"
config.vm.box = "opscode-ubuntu-12.04"
config.vm.box_url = "https://opscode-vm.s3.amazonaws.com/vagrant/opscode_ubuntu-12.04_provisionerless.box"
config.vm.network :forwarded_port, guest: 3000, host: 3001
config.vm.network :forwarded_port, guest: 8080, host: 8081
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "1024"]
end
config.omnibus.chef_version = "11.4.0"
config.berkshelf.enabled = true
config.vm.provision :chef_solo do |chef|
chef.json = {
"go" => {
"version" => "1.1.2",
"packages" => [
"github.com/codegangsta/martini",
"github.com/codegangsta/martini-contrib/...",
"github.com/bitly/go-simplejson",
"github.com/mattn/goreman",
"github.com/onsi/ginkgo",
"github.com/onsi/gomega",
"github.com/dancannon/gorethink"
]
}
}
chef.run_list = [
"apt",
"curl",
"golang::packages",
"rethinkdb"
]
end
end |
class World < ApplicationRecord
belongs_to :world_config
belongs_to :map
def self.get_joinable_world
open_worlds = World.get_open_list
# open_worlds = JSON.parse(open_worlds)
if !open_worlds.blank?
last_open_world = open_worlds.to_a.last
joinable = World.check_joinable(last_open_world[0], last_open_world[1]["population"])
if joinable
return last_open_world[0]
end
end
world_id = World.start_game_world(50, 1)
if world_id
return world_id
else
return false
end
end
def self.check_joinable(world_id, population)
world = World.find(world_id)
if world.created_at.to_i > (Time.now - 25.days).to_i && (World.get_population(world_id) < population)
return true
end
return false
end
# Logic to be written to fetch the population of a world
def self.get_population(world_id)
characters = Character.where("world_id = ?", world_id).count
return characters
end
#=========================================================
def self.world_creator_data_setter(world_size, world_config_id)
@open_worlds = World.get_open_list
@world_size = world_size
@world_config_id = world_config_id
end
# Sample OpenWorldList data = '{"1": {"name": "My World", "population": 2000, "map": 1, "wc": 1},"2": {"name": "My World2", "population": 1000, "map": 2, "wc": 2},"3": {"name": "My World3", "population": 2500, "map": 3, "wc": 5}}'
def self.get_open_list
list = $redis.get(World.open_list_key)
list = list ? JSON.parse(list) : {}
return list
end
def self.set_open_list(json_data)
status = $redis.set(World.open_list_key, json_data)
return status
end
def self.open_list_key
"OpenWorldList"
end
def self.start_game_world(world_size, world_config_id)
World.world_creator_data_setter(world_size, world_config_id)
world = World.new
map_id = World.create_map
if map_id == false
return false
end
world.map_id = map_id
world.world_config_id = @world_config_id
world.final = "false"
world.data = "{}"
new_world = world.save
if new_world
World.add_to_open_list(world)
return world.id
else
return false
end
end
def self.create_map
map_size = @world_size
map_fields = {}
for x in (-1*map_size..map_size)
fields = *(1..200)
for y in (-1*map_size..map_size)
field_type = fields.sample
map_fields["#{x},#{y}"] = field_type
fields.delete(field_type)
end
end
map = Map.new
map.data = map_fields.to_s
map.size = map_size
new_map = map.save
if new_map
return map.id
else
return false
end
end
def self.add_to_open_list(world)
worlds = @open_worlds
#{"name": "My World", "population": 2000, "map": 1, "wc": 1}
size = @world_size.to_i
population = size * size * 0.4
world_details = {"name" => world.name, "population" => population, "map" => world.map_id, "wc" => world.world_config_id}
worlds["#{world.id}"] = world_details
world_json = worlds.to_json.to_s
status = World.set_open_list(world_json)
end
end
|
class EmbedUrlFetcher < ApplicationJob
def perform(link_id)
@link = Link.find(link_id)
get_xnxx_data
get_pornhub_data
get_youtube_url
get_xvideos_data
get_xhamster_data
@link.source_url
end
def get_youtube_url
host = URI.parse(@link.url.chomp).host
if host.include? 'youtube.'
html = Net::HTTP.get_response(URI.parse(@link.url)).response.body
name, tags = MassEntry.with_info(@link.url, html)
@link.update_attributes(name: @link.name.present? ? @link.name : name, tags: "#{@link.tags} #{tags}", source_url: 'https://youtube.com/embed/' + @link.url.match(/v=(.*)/)[1])
end
end
def get_xvideos_data
host = URI.parse(@link.url.chomp).host
if host.include? 'xvideos.'
html = Net::HTTP.get_response(URI.parse(@link.url)).response.body
if html.include?('Sorry, this URL is outdated')
@link.url = 'https://www.xvideos.com' + html.match(/Url : (.*) /)[1].split(' ').first
get_xvideos_data
return
end
name, tags = MassEntry.with_info(@link.url, html)
video_url = html.match(/setVideoUrlLow\('(.*)'\)/)[1]
else
return
end
@link.update_attributes(name: name, tags: "#{@link.tags} #{tags}", source_url: video_url)
end
def get_xhamster_data
host = URI.parse(@link.url.chomp).host
if host.include? 'xhamster.'
response = Net::HTTP.get_response(URI.parse(@link.url))
html = response.response.body
if html.include?('Sorry, this URL is outdated')
@link.url = 'https://www.xhamster.com' + html.match(/Url : (.*) /)[1].split(' ').first
get_xhamster_data
return
else
case response
when Net::HTTPRedirection
@link.url = response['location']
get_xhamster_data
return
when Net::HTTPSuccess
html = response.response.body
else
return
end
end
name, tags = MassEntry.with_info(@link.url, html)
video_url = html.match(/embedUrl":"(.*)"/)[1].split('","')[0].gsub('\\', '')
else
return
end
@link.update_attributes(name: name, tags: "#{@link.tags} #{tags}", source_url: video_url)
end
def get_xnxx_data
host = URI.parse(@link.url.chomp).host
if host.include? 'xnxx.'
html = Net::HTTP.get_response(URI.parse(@link.url)).response.body
if html.include?('Sorry, this URL is outdated')
@link.url = 'https://www.xnxx.com' + html.match(/Url : (.*) /)[1].split(' ').first
get_xnxx_data
return
end
name, tags = MassEntry.with_info(@link.url, html)
video_url = html.match(/setVideoUrlLow\('(.*)'\)/)[1]
else
return
end
@link.update_attributes(name: name, tags: "#{@link.tags} #{tags}", source_url: video_url)
end
def get_pornhub_data
host = URI.parse(@link.url.chomp).host
if host.include? 'pornhub.'
html = Net::HTTP.get_response(URI.parse(@link.url.sub('.org', '.com'))).response.body
name, tags = MassEntry.with_info(@link.url, html)
else
return
end
video_url = Nokogiri::HTML(html).css('meta[name="twitter:player"]').attr('content').value
@link.update_attributes(name: name, tags: "#{@link.tags} #{tags}", source_url: video_url)
end
end |
Rails.application.routes.draw do
resources :users
resource :registrations, only: [:new, :create]
resource :sessions, only: [:new, :create, :destroy]
resource :settings, only: [:edit, :update]
resources :users, only: [:index, :show] do
resource :follows, only: [:create, :destroy]
get :favorites, on: :member
get :follows, on: :member
get :followers, on: :member
end
resources :tweets do
resource :favorites, only: [:create, :destroy]
get :timeline, on: :collection
end
root to: 'registrations#new'
# resources :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class Home::StoresController < ApplicationController
# GET /home/stores
# GET /home/stores.json
def index
@home_stores = Home::Store.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @home_stores }
end
end
# GET /home/stores/1
# GET /home/stores/1.json
def show
@home_store = Home::Store.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @home_store }
end
end
# GET /home/stores/new
# GET /home/stores/new.json
def new
@home_store = Home::Store.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @home_store }
end
end
# GET /home/stores/1/edit
def edit
@home_store = Home::Store.find(params[:id])
end
# POST /home/stores
# POST /home/stores.json
def create
@home_store = Home::Store.new(params[:home_store])
respond_to do |format|
if @home_store.save
format.html { redirect_to @home_store, notice: 'Store was successfully created.' }
format.json { render json: @home_store, status: :created, location: @home_store }
else
format.html { render action: "new" }
format.json { render json: @home_store.errors, status: :unprocessable_entity }
end
end
end
# PUT /home/stores/1
# PUT /home/stores/1.json
def update
@home_store = Home::Store.find(params[:id])
respond_to do |format|
if @home_store.update_attributes(params[:home_store])
format.html { redirect_to @home_store, notice: 'Store was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @home_store.errors, status: :unprocessable_entity }
end
end
end
# DELETE /home/stores/1
# DELETE /home/stores/1.json
def destroy
@home_store = Home::Store.find(params[:id])
@home_store.destroy
respond_to do |format|
format.html { redirect_to home_stores_url }
format.json { head :no_content }
end
end
end
|
class AddMatchedPartsToSentence < ActiveRecord::Migration
def change
add_column :sentences, :matched_parts, :string
end
end
|
module Linux
module Lxc
class Index
attr_reader :files
def initialize
@key_index = {}
@dirs = {}
@files = {}
end
def add_line(key, line)
@key_index[key] ||= Lines.new
@key_index[key].add(line)
end
def get_key(key)
@key_index[key]
end
def delete_key(key)
return if @key_index[key].nil? || !@key_index[key].empty?
@key_index.delete(key)
end
def get_directory(fname)
@dirs[fname] ||= Directory.new(fname, self)
end
def add_file(fname, dir)
@files[fname] ||= File.new(fname, dir, self)
end
end
end
end
|
# encoding: UTF-8
require_relative '../../lib/error'
require_relative 'event2task/objective/objectives'
require_relative 'event2task/visit/visits'
require_relative 'event2task/statistic/statistic'
require_relative 'event2task/statistic/chosens'
require_relative 'event2task/statistic/default'
require_relative 'event2task/statistic/custom'
#require_relative 'event2task/statistic/google_analytics' #TODO ko with ruby 223
require_relative 'event2task/traffic_source/chosens'
require_relative 'event2task/traffic_source/default'
require_relative 'event2task/traffic_source/organic'
require_relative 'event2task/traffic_source/referral'
require_relative 'event2task/traffic_source/direct'
require_relative '../planning/event'
require 'rest-client'
require 'json'
# TODO a supprimer qd toutes les tasks auront été refondus
module Tasking
class Tasklist
include Errors
ACTION_NOT_EXECUTE = 1802
attr :data, :logger, :delay
def initialize(data)
@data = data
@delay = Random.new
@logger = Logging::Log.new(self, :staging => $staging, :debugging => $debugging)
end
#--------------------------------------------------------------------------------------
# STATISTIC
#--------------------------------------------------------------------------------------
def Scraping_device_platform_resolution
execute(__method__) {
case @data[:statistic_type].to_sym
when :ga
Statistic::Googleanalytics.new.device_platform_resolution(@data[:website_label], @data[:building_date], @data[:profil_id_ga], @data[:website_id])
when :default, :custom
Statistic::Default.new(@data[:website_label], @data[:building_date], @data[:policy_type]).device_platform_resolution
end
}
end
def Scraping_device_platform_plugin
execute(__method__) {
case @data[:statistic_type].to_sym
when :ga
Statistic::Googleanalytics.new.device_platform_plugin(@data[:website_label], @data[:building_date], @data[:profil_id_ga], @data[:website_id])
when :default, :custom
Statistic::Default.new(@data[:website_label], @data[:building_date], @data[:policy_type]).device_platform_plugin
end
}
end
def Scraping_behaviour
execute(__method__) {
case @data[:statistic_type].to_sym
when :ga
Statistic::Googleanalytics.new.behaviour(@data[:website_label], @data[:building_date], @data[:profil_id_ga], @data[:website_id]) #TODO � corriger comme default ko with ruby 223
when :default
Statistic::Default.new(@data[:website_label], @data[:building_date], @data[:policy_type]).behaviour
when :custom
Statistic::Custom.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).behaviour(@data[:percent_new_visit],
@data[:visit_bounce_rate],
@data[:avg_time_on_site],
@data[:page_views_per_visit],
@data[:count_visits_per_day])
end
}
end
def Scraping_hourly_daily_distribution
execute(__method__) {
case @data[:statistic_type].to_sym
when :ga
Statistic::Googleanalytics.new.hourly_daily_distribution(@data[:website_label], @data[:building_date], @data[:profil_id_ga], @data[:website_id]) #TODO � corriger comme default ko with ruby 223
when :default
Statistic::Default.new(@data[:website_label], @data[:building_date], @data[:policy_type]).hourly_daily_distribution
when :custom
Statistic::Custom.new(@data[:website_label], @data[:building_date], @data[:policy_type]).hourly_daily_distribution(@data[:hourly_daily_distribution])
end
}
end
def Building_device_platform
execute(__method__) {
Statistic::Statistic.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_device_platform
}
end
def Building_hourly_daily_distribution
execute(__method__) {
Statistic::Statistic.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_hourly_daily_distribution
}
end
def Building_behaviour
execute(__method__) {
Statistic::Statistic.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_behaviour
}
end
def Choosing_device_platform
execute(__method__) {
Statistic::Chosens.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Choosing_device_platform(is_nil_or_empty? { @data[:count_visits] }.to_i) }
end
#--------------------------------------------------------------------------------------
# TRAFFIC SOURCE
#--------------------------------------------------------------------------------------
def Building_landing_pages_direct
execute(__method__) {
TrafficSource::TrafficSource.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_landing_pages(:direct)
}
end
def Building_landing_pages_organic
execute(__method__) {
TrafficSource::TrafficSource.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_landing_pages(:organic)
}
end
def Building_landing_pages_referral
execute(__method__) {
TrafficSource::TrafficSource.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Building_landing_pages(:referral)
}
end
def Choosing_landing_pages
execute(__method__) {
TrafficSource::Chosens.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).Choosing_landing_pages(is_nil_or_empty? { @data[:direct_medium_percent] }.to_i,
is_nil_or_empty? { @data[:organic_medium_percent] }.to_i,
is_nil_or_empty? { @data[:referral_medium_percent] }.to_i,
is_nil_or_empty? { @data[:count_visits] }.to_i) }
end
def Scraping_traffic_source_organic
execute(__method__) {
case @data[:policy_type].to_sym
when :traffic
TrafficSource::Organic.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).make_repository(@data[:url_root], # 10mn de suggesting
$staging == "development" ? (10.0 /(24 * 60)) : @data[:max_duration])
when :rank, :seaattack
TrafficSource::Default.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).make_repository(@data[:keywords])
end
}
end
def Scraping_traffic_source_referral
execute(__method__) {
TrafficSource::Referral.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).make_repository(@data[:url_root], #en dev 5 backlink max, zero = all
$staging == "development" ? 5 : 0)
}
end
def Scraping_website
execute(__method__) { |event_id|
TrafficSource::Direct.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
event_id,
@data[:policy_id]).scraping_pages(@data[:url_root],
$staging == "development" ? 10 : @data[:count_page],
@data[:max_duration],
@data[:schemes],
@data[:types])
}
end
def Evaluating_traffic_source_referral
execute(__method__) {
TrafficSource::Referral.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).evaluate(@data[:count_max]) }
end
def Evaluating_traffic_source_organic
execute(__method__) {
case @data[:policy_type].to_sym
when :traffic, :rank
# l'evaluation est identique pour Organic & Default
TrafficSource::Organic.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).evaluate(@data[:count_max], @data[:url_root])
when :seaattack
TrafficSource::Default.new(@data[:website_label],
@data[:building_date],
@data[:policy_type]).evaluate(@data[:count_max])
end
}
end
#--------------------------------------------------------------------------------------
# OBJECTIVE
#--------------------------------------------------------------------------------------
def Building_objectives
execute(__method__) {
case @data[:policy_type]
when "traffic" , "advert"
Objective::Objectives.new(@data[:website_label],
@data[:building_date],
@data[:policy_id],
@data[:website_id],
@data[:policy_type],
@data[:count_weeks],
@data[:execution_mode]).Building_objectives_traffic(is_nil_or_empty? { @data[:advertising_percent] }.to_i,
is_nil_or_empty? { @data[:advertisers] },
is_nil_or_empty? { @data[:change_count_visits_percent] }.to_i,
is_nil_or_empty? { @data[:change_bounce_visits_percent] }.to_i,
is_nil_or_empty? { @data[:count_visits_per_day] }.to_i,
is_nil_or_empty? { @data[:direct_medium_percent] }.to_i,
is_nil_or_empty? { @data[:duration_referral] },
is_nil_or_empty? { @data[:min_count_page_advertiser] },
is_nil_or_empty? { @data[:min_count_page_organic] },
is_nil_or_empty? { @data[:min_duration] },
is_nil_or_empty? { @data[:min_duration_page_advertiser] },
is_nil_or_empty? { @data[:min_duration_page_organic] },
is_nil_or_empty? { @data[:min_duration_website] },
is_nil_or_empty? { @data[:min_pages_website] },
is_nil_or_empty? { @data[:max_count_page_advertiser] },
is_nil_or_empty? { @data[:max_count_page_organic] },
is_nil_or_empty? { @data[:max_duration] },
is_nil_or_empty? { @data[:max_duration_page_advertiser] },
is_nil_or_empty? { @data[:max_duration_page_organic] },
is_nil_or_empty? { @data[:monday_start] },
is_nil_or_empty? { @data[:organic_medium_percent] }.to_i,
is_nil_or_empty? { @data[:percent_local_page_advertiser] },
is_nil_or_empty? { @data[:referral_medium_percent] }.to_i,
is_nil_or_empty? { @data[:url_root] })
when "seaattack"
Objective::Objectives.new(@data[:website_label],
@data[:building_date],
@data[:policy_id],
@data[:website_id],
@data[:policy_type],
@data[:count_weeks],
@data[:execution_mode]).Building_objectives_seaattack(is_nil_or_empty? { @data[:advertising_percent] }.to_i,
is_nil_or_empty? { @data[:advertisers] },
is_nil_or_empty? { @data[:monday_start] },
is_nil_or_empty? { @data[:min_count_page_advertiser] },
is_nil_or_empty? { @data[:max_count_page_advertiser] },
is_nil_or_empty? { @data[:min_duration_page_advertiser] },
is_nil_or_empty? { @data[:max_duration_page_advertiser] },
is_nil_or_empty? { @data[:percent_local_page_advertiser] },
is_nil_or_empty? { @data[:min_count_page_organic] },
is_nil_or_empty? { @data[:max_count_page_organic] },
is_nil_or_empty? { @data[:min_duration_page_organic] },
is_nil_or_empty? { @data[:max_duration_page_organic] },
is_nil_or_empty? { @data[:min_duration] },
is_nil_or_empty? { @data[:max_duration] },
is_nil_or_empty? { @data[:min_duration_website] },
is_nil_or_empty? { @data[:min_pages_website] },
is_nil_or_empty? { @data[:fqdn_advertisings] })
when "rank"
Objective::Objectives.new(@data[:website_label],
@data[:building_date],
@data[:policy_id],
@data[:website_id],
@data[:policy_type],
@data[:count_weeks],
@data[:execution_mode]).Building_objectives_rank(is_nil_or_empty? { @data[:count_visits_per_day] }.to_i,
is_nil_or_empty? { @data[:monday_start] },
is_nil_or_empty? { @data[:url_root] },
is_nil_or_empty? { @data[:min_count_page_advertiser] },
is_nil_or_empty? { @data[:max_count_page_advertiser] },
is_nil_or_empty? { @data[:min_duration_page_advertiser] },
is_nil_or_empty? { @data[:max_duration_page_advertiser] },
is_nil_or_empty? { @data[:percent_local_page_advertiser] },
is_nil_or_empty? { @data[:duration_referral] },
is_nil_or_empty? { @data[:min_count_page_organic] },
is_nil_or_empty? { @data[:max_count_page_organic] },
is_nil_or_empty? { @data[:min_duration_page_organic] },
is_nil_or_empty? { @data[:max_duration_page_organic] },
is_nil_or_empty? { @data[:min_duration] },
is_nil_or_empty? { @data[:max_duration] },
is_nil_or_empty? { @data[:min_duration_website] },
is_nil_or_empty? { @data[:min_pages_website] })
end
}
end
#--------------------------------------------------------------------------------------
# VISIT
#--------------------------------------------------------------------------------------
def Building_visits
execute(__method__) {
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id]).Building_visits(is_nil_or_empty? { @data[:count_visits] }.to_i,
is_nil_or_empty? { @data[:visit_bounce_rate] }.to_f,
is_nil_or_empty? { @data[:page_views_per_visit] }.to_f,
is_nil_or_empty? { @data[:avg_time_on_site] }.to_f,
is_nil_or_empty? { @data[:min_durations] }.to_i,
is_nil_or_empty? { @data[:min_pages] }.to_i) }
end
def Building_planification
execute(__method__) {
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id]).Building_planification(is_nil_or_empty? { @data[:hourly_distribution] },
is_nil_or_empty? { @data[:count_visits] }.to_i) }
end
def Extending_visits
execute(__method__) {
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id]).Extending_visits(is_nil_or_empty? { @data[:count_visits] }.to_i,
is_nil_or_empty? { @data[:advertising_percent].to_i },
is_nil_or_empty? { @data[:advertisers] }) }
end
def Reporting_visits
execute(__method__) {
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id]).Reporting_visits }
end
def Publishing_visits
execute(__method__) {
case @data[:policy_type]
when "traffic", "rank", "advert"
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id],
@data[:execution_mode]).Publishing_visits_by_hour(@data[:min_count_page_advertiser].to_i,
@data[:max_count_page_advertiser].to_i,
@data[:min_duration_page_advertiser].to_i,
@data[:max_duration_page_advertiser].to_i,
@data[:percent_local_page_advertiser].to_i,
@data[:duration_referral].to_i,
@data[:min_count_page_organic].to_i,
@data[:max_count_page_organic].to_i,
@data[:min_duration_page_orgcanic].to_i,
@data[:max_duration_page_organic].to_i,
@data[:min_duration].to_i,
@data[:max_duration].to_i)
when "seaattack"
Visit::Visits.new(@data[:website_label],
@data[:building_date],
@data[:policy_type],
@data[:website_id],
@data[:policy_id],
@data[:execution_mode]).Publishing_visits_by_hour(@data[:min_count_page_advertiser].to_i,
@data[:max_count_page_advertiser].to_i,
@data[:min_duration_page_advertiser].to_i,
@data[:max_duration_page_advertiser].to_i,
@data[:percent_local_page_advertiser].to_i,
@data[:duration_referral].to_i,
@data[:min_count_page_organic].to_i,
@data[:max_count_page_organic].to_i,
@data[:min_duration_page_orgcanic].to_i,
@data[:max_duration_page_organic].to_i,
@data[:min_duration].to_i,
@data[:max_duration].to_i,
@data[:fqdn_advertisings])
end
}
end
#--------------------------------------------------------------------------------------
# private
#--------------------------------------------------------------------------------------
private
def execute(task, &block)
info = ["policy (type/id) : #{@data[:policy_type]} / #{@data[:policy_id]}",
" website (label/id) : #{@data[:website_label]} / #{@data[:website_id]}",
" date : #{@data[:building_date]}"]
info << " objective_id : #{@data[:objective_id]}" unless @data[:objective_id].nil?
action = proc {
begin
# perform a long-running operation here, such as a database query.
send_state_to_calendar(@data[:event_id], Planning::Event::START, info)
@logger.an_event.info "task <#{task}> for <#{info.join(",")}> is start"
send_task_to_statupweb(@data[:policy_id],
@data[:policy_type],
task,
@data[:building_date],
@data[:event_id],
info)
yield (@data[:event_id])
rescue Error => e
results = e
rescue Exception => e
@logger.an_event.error "task <#{task}> for <#{info.join(",")}> is over => #{e.message}"
results = Error.new(ACTION_NOT_EXECUTE, :values => {:action => task}, :error => e)
else
@logger.an_event.info "task <#{task}> for <#{info.join(",")}> is over"
results # as usual, the last expression evaluated in the block will be the return value.
ensure
end
}
callback = proc { |results|
# on considere que la maj du calendar fait partie de lexecution complete d'une task.
# donc si une task echoue et que la maj du calendart échoué egalement, on ne publie que la maj du calendar
# vers statupweb.
# qd le pb de maj du calendar sera résolu on recuperera lerreur originelle.
begin
state = results.is_a?(Error) ? Planning::Event::FAIL : Planning::Event::OVER
# scraping website utilise spawn => tout en asycnhrone => il enverra l'Event::over à calendar
# il n'enverra jamais Event::Fail à calendar.
send_state_to_calendar(@data[:event_id],
state, info) if task != :Scraping_website
rescue Exception => e
@logger.an_event.error "update state #{state} task <#{task}> for <#{info.join(",")}> in calendar"
results = e
else
@logger.an_event.info "update state #{state} task <#{task}> for <#{info.join(",")}> in calendar"
ensure
if task != :Scraping_website
if results.is_a?(Error)
send_fail_task_to_statupweb(@data[:event_id], results.message, info)
else
send_over_task_to_statupweb(@data[:event_id], info)
end
end
end
}
if $staging == "development" #en dev tout ext exécuté hors thread pour pouvoir debugger
begin
results = action.call
rescue Exception => e
@logger.an_event.error e.message
callback.call(e)
else
callback.call(results)
end
else # en test & production tout est executé dans un thread
EM.defer(action, callback)
end
end
private
def send_state_to_calendar(event_id, state, info)
# informe le calendar du nouvelle etat de la tache (start/over/fail).
try_count = 3
begin
response = RestClient.patch "http://localhost:#{$calendar_server_port}/tasks/#{event_id}/?state=#{state}", :content_type => :json, :accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.error "cannot update state #{state} for #{info.join(",")} in calendar : #{e.message}"
rescue RestClient::RequestTimeout => e
@logger.an_event.warn "try #{try_count}, cannot update state #{state} for #{info.join(",")} in calendar : #{e.message}"
try_count -= 1
sleep @delay.rand(10..50)
retry if try_count > 0
@logger.an_event.error "cannot update state #{state} for #{info.join(",")} in calendar : #{e.message}"
else
end
end
def send_task_to_statupweb(policy_id, policy_type, label, building_date, task_id, info)
begin
task = {:policy_id => policy_id,
:policy_type => policy_type,
:label => label,
:state => Planning::Event::START,
:time => Time.now,
:building_date => building_date,
:task_id => task_id
}
response = RestClient.post "http://#{$statupweb_server_ip}:#{$statupweb_server_port}/tasks/",
JSON.generate(task),
:content_type => :json,
:accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.warn "task <#{info.join(",")}> not send to statupweb #{$statupweb_server_ip}:#{$statupweb_server_port}=> #{e.message}"
else
end
end
def send_over_task_to_statupweb(task_id, info)
begin
task = {:state => Planning::Event::OVER,
:finish_time => Time.now
}
response = RestClient.patch "http://#{$statupweb_server_ip}:#{$statupweb_server_port}/tasks/#{task_id}",
JSON.generate(task),
:content_type => :json,
:accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.warn "task <#{info.join(",")}> not update state : #{Planning::Event::OVER} to statupweb #{$statupweb_server_ip}:#{$statupweb_server_port}=> #{e.message}"
else
end
end
def send_fail_task_to_statupweb(task_id, error_label, info)
begin
task = {:state => Planning::Event::FAIL,
:finish_time => Time.now,
:error_label => error_label
}
response = RestClient.patch "http://#{$statupweb_server_ip}:#{$statupweb_server_port}/tasks/#{task_id}",
JSON.generate(task),
:content_type => :json,
:accept => :json
raise response.content unless [200, 201].include?(response.code)
rescue Exception => e
@logger.an_event.warn "task <#{info.join(",")}> not update state : #{Planning::Event::FAIL} to statupweb #{$statupweb_server_ip}:#{$statupweb_server_port}=> #{e.message}"
else
end
end
def is_nil_or_empty?
@logger.an_event.debug yield
raise StandardError, "argument is undefine" if yield.nil?
raise StandardError, "argument is empty" if !yield.nil? and yield.is_a?(String) and yield.empty?
yield
end
end
end
|
require 'httparty'
class PixelPeeper
include HTTParty
base_uri 'www.pixel-peeper.com'
default_timeout 1 # hard timeout after 1 second
def api_key
ENV['PIXELPEEPER_API_KEY']
end
def base_path
"/rest/?method=list_photos&api_key=#{ api_key }"
end
def handle_timeouts
begin
yield
rescue Net::OpenTimeout, Net::ReadTimeout
{}
end
end
def cache_key(options)
if options[:camera_id]
"pixelpeeper:camera:#{ options[:camera_id] }"
elsif options[:lens_id]
"pixelpeeper:lens:#{ options[:lens_id] }"
end
end
def handle_caching(options)
if cached = REDIS.get(cache_key(options))
JSON[cached]
else
yield.tap do |results|
REDIS.set(cache_key(options), results.to_json)
end
end
end
def build_url_from_options(options)
if options[:camera_id]
"#{ base_path }&camera=#{ options[:camera_id] }"
elsif options[:lens_id]
"#{ base_path }&lens=#{ options[:lens_id] }"
else
raise ArgumentError, "options must specify camera_id or lens_id"
end
end
def examples(options)
handle_timeouts do
handle_caching(options) do
self.class.get(build_url_from_options(options))['data']['results']
end
end
end
end
|
class User
include DataMapper::Resource
property :id, String, :key => true, :nullable => false
property :username, String, :nullable => false
property :password, String, :nullable => false
end
|
class AddRejectedFieldToModerableTexts < ActiveRecord::Migration
def change
add_column :moderable_texts, :rejected, :boolean, default: false
end
end
|
module Yara
class UserData < FFI::Struct
layout :number, :int32
end
end
|
class CommentsController < ApplicationController
def index
@comments = Comment.all
end
def new
@page_title = 'Add New Comment'
@comment = Comment.new
end
def create
@comment = Comment.new(comment_params)
@comment.user_id = current_user.id
@id = params[:stamp_id]
if @comment.save
flash[:notice] = "Comment Created!"
redirect_to current_user
else
render 'new'
end
end
def update
@comment = Comment.find(params[:id])
@comment.update(comment_params)
flash[:notice] = 'Comment Updated'
redirect_to current_user
end
def edit
@comment = Comment.find(params[:id])
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
flash[:notice] = 'comment Removed'
redirect_to current_user
end
def show
@comment = Comment.find_by_id(params[:id])
end
private
def comment_params
params.require(:comment).permit(:body, :stamp_id)
end
end
|
require_relative 'test_helper'
require './lib/display_board'
require './lib/game_board'
require './lib/shots_fired'
require './lib/user_interaction'
class DisplayBoardTest < Minitest::Test
def test_it_exists_and_initializes_with_board_and_labels_and_layout_and_coordinates
board = GameBoard.new
display = DisplayBoard.new(board)
assert_instance_of DisplayBoard, display
assert_instance_of GameBoard, display.board
assert_instance_of Array, display.board_layout
assert_equal ["A", "B", "C", "D"], display.row_label
assert_equal ["1", "2", "3", "4"], display.column_label
end
def test_it_renders_board
board = GameBoard.new
display = DisplayBoard.new(board)
display.render_board
end
def test_it_renders_shot
board = GameBoard.new
shots = ShotsFired.new(board)
display = DisplayBoard.new(board)
shots.valid_shot_is_fired('C2')
board.two_unit_ship = ['A1', 'A2']
board.three_unit_ship = ['B2', 'B3','B4']
shots.valid_shot_is_fired('A1')
shots.valid_shot_is_fired('A1')
end
end
|
class Feedback < ActiveRecord::Base
include Concerns::Cacheable
include Concerns::ReactJson
belongs_to :schedule
belongs_to :mit_class
validates :positive, inclusion: [true, false]
validates :schedule, presence: true
validates :mit_class, presence: true, uniqueness: { scope: [:schedule] }
def feature_vector
cached { self.class.build_feature_vector(schedule, mit_class, positive? ? 1 : 0) }
end
def self.num_features
@num_features ||= first.feature_vector.size - 1
end
def self.build_feature_vector(schedule, mit_class, label = nil)
schedule.feature_vector[0..-2] + mit_class.feature_vector[0..-2] + [label]
end
private
def react_json
{ number: mit_class.number, name: mit_class.name, positive: positive? }
end
end
|
class NavbarConfig
include Singleton
PROPERTIES = [
:user,
:new_class_button,
:back_link,
:needs_menu_dropdown,
:wide_search,
:profile_page
]
PROPERTIES.each do |property|
attr_accessor property
end
def clear
PROPERTIES.each do |property|
send "#{property}=", nil
end
self
end
def create_profile_button?
user && user.instructor_profile.nil?
end
def new_class_button?
new_class_button
end
def needs_menu_dropdown?
needs_menu_dropdown
end
def wide_search?
wide_search
end
def profile_page?
profile_page
end
end
|
class ApplicationController < ActionController::Base
include SessionsHelper
private
def verify_admin
return if logged_in? && is_admin?
flash[:danger] = t "permission"
redirect_to root_url
end
def verify_login
return if logged_in?
flash[:danger] = t "please_login"
redirect_to login_url
end
def make_history object, type
object.histories.create user_id: current_user.id, type_history: type
end
end
|
class Teacher < ActiveRecord::Base
#ASSOCIATIONS
# has_many :students
# has_and_belongs_to_many :students
has_many :subjects
has_many :students, through: :subjects
#VALIDATIONS
validates_presence_of :name
validates_length_of :name, maximum: 10
validates :name, uniqueness: :true
end
|
class Stuff
attr_accessor :number1, :string1, :truthy, :falsy, :floaty, :array1, :array2, :hash1, :otherstuff
def initialize
self.number1 = 1
self.string1 = "Test1"
self.truthy = true
self.falsy = false
self.floaty = 3.14
self.array1 = Array.new
self.array1 << 1
self.array1 << 2
self.array2 = Array.new
self.array2 << Array.new
self.array2[0] << 3
self.array2[0] << 4
self.hash1 = Hash.new
self.hash1["test1"] = 1
self.hash1["test2"] = 2
self.otherstuff = OtherStuff.new
end
def to_s
self.serialize.to_s
end
def inspect
self.serialize.to_s
end
def serialize
hash = {}
instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
hash
end
end
class OtherStuff
attr_accessor :number1, :string1
def initialize
self.number1 = 1
self.string1 = "Test1"
end
def to_s
self.serialize.to_s
end
def inspect
self.serialize.to_s
end
def serialize
hash = {}
instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
hash
end
end
|
class ScholarshipApplication < ApplicationRecord
validates :user_id, uniqueness: {scope: :scholarship_id}
belongs_to :user
belongs_to :scholarship
delegate :name, to: :user, prefix: true
delegate :email, to: :user, prefix: true
end
|
module Domotics::Core
class Dimmer < Element
DEFAULT_LEVEL = 0
MIN_LEVEL = 0
MAX_LEVEL = 255
MAX_STEPS = 128
STEP_DELAY = 1.0 / MAX_STEPS
STEP_SIZE = ((MAX_LEVEL + 1) / MAX_STEPS.to_f).round
def initialize(args = {})
@type = args[:type] || :dimmer
@fade_lock = Mutex.new
@fade_thread = nil
args[:driver] = "PWMPin"
load_driver args
super
end
def state
st = super
st.is_a?(Integer) ? st : 0
end
def set_state(value = DEFAULT_LEVEL, opt = {})
unless opt[:kill_fader] == :no
@fade_lock.synchronize do
@fade_thread.kill if @fade_thread and @fade_thread.alive?
end
end
if value.is_a? Integer
value = MIN_LEVEL if value < MIN_LEVEL
value = MAX_LEVEL if value > MAX_LEVEL
end
super value
end
# Decrease brightness level (value 0-100%)
def dim(value = nil)
if value
set_state value * MAX_LEVEL / 100
else
set_state state - STEP_SIZE
end
end
# Increase brightness level (value 0-100%)
def bright(value = nil)
if value
set_state value * MAX_LEVEL / 100
else
set_state state + STEP_SIZE
end
end
def off
set_state MIN_LEVEL unless state == MIN_LEVEL
end
def fade_to(value = DEFAULT_LEVEL, speed_divisor = 1)
@fade_lock.synchronize do
@fade_thread.kill if @fade_thread and @fade_thread.alive?
@fade_thread = Thread.new do
op = (value - state) >= 0 ? :+ : :-
steps = ((value - state).abs / STEP_SIZE.to_f).round
steps.times do
set_state(state.public_send(op, STEP_SIZE), kill_fader: :no)
sleep speed_divisor * STEP_DELAY
end
@fade_lock.synchronize { @fade_thread = nil }
end
end
@fade_thread
end
end
end
|
class Card
class Civil
class Technology
class Urban < Technology
def available_actions(type, phase, gc = nil)
options = super
if type == GameCard::PlayerCard && phase == Game::Civilization::Phase::ACTIONS
options[:build] = PlayerAction::Civil::Build::Building
options[:upgrade] = PlayerAction::Civil::Upgrade::Building
options[:destroy] = PlayerAction::Civil::Destroy::Building
end
return options
end
def culture_scoring(gc)
raise ArgumentError, "gc has to be a GameCard" unless gc.is_a?(GameCard)
gc.yellow_tokens * culture_value if self.respond_to?(:culture_value)
end
def science_scoring(gc)
raise ArgumentError, "gc has to be a GameCard" unless gc.is_a?(GameCard)
gc.yellow_tokens * science_value if self.respond_to?(:science_value)
end
def happiness(gc)
raise ArgumentError, "gc has to be a GameCard" unless gc.is_a?(GameCard)
gc.yellow_tokens * happy_faces if self.respond_to?(:happy_faces)
end
def strength(gc)
raise ArgumentError, "gc has to be a GameCard" unless gc.is_a?(GameCard)
gc.yellow_tokens * strength_value if self.respond_to?(:strength_value)
end
class Temple < Urban
def culture_value; return 1; end
def happy_faces
case self.age
when 0 then 1
when 1 then 2
when 2 then 3
end
end
def cost_resources
case self.age
when 0 then 3
when 1 then 5
when 2 then 7
end
end
def cost_science
case self.age
when 1 then 2
when 2 then 4
end
end
end
class Laboratory < Urban
def science_value
case self.age
when 0 then 1
when 1 then 2
when 2 then 3
when 3 then 5
end
end
def cost_resources
case self.age
when 0 then 3
when 1 then 6
when 2 then 8
when 3 then 10
end
end
def cost_science
case self.age
when 1 then 4
when 2 then 6
when 3 then 8
end
end
end
class Library < Urban
def science_value
case self.age
when 1 then 1
when 2 then 2
when 3 then 3
end
end
def culture_value
case self.age
when 1 then 1
when 2 then 2
when 3 then 3
end
end
def cost_resources
case self.age
when 1 then 4
when 2 then 8
when 3 then 11
end
end
def cost_science
case self.age
when 1 then 4
when 2 then 6
when 3 then 9
end
end
end
class Arena < Urban
def happy_faces
case self.age
when 1 then 2
when 2 then 3
when 3 then 4
end
end
def strength_value
case self.age
when 1 then 1
when 2 then 2
when 3 then 3
end
end
def cost_resources
case self.age
when 1 then 4
when 2 then 6
when 3 then 8
end
end
def cost_science
case self.age
when 1 then 3
when 2 then 5
when 3 then 7
end
end
end
class Theatre < Urban
def culture_value
case self.age
when 1 then 2
when 2 then 3
when 3 then 4
end
end
def happy_faces; return 1; end
def cost_resources
case self.age
when 1 then 5
when 2 then 9
when 3 then 12
end
end
def cost_science
case self.age
when 1 then 4
when 2 then 7
when 3 then 10
end
end
end
end
end
end
end
|
class Activity < ActiveRecord::Base
belongs_to :location
belongs_to :sport
belongs_to :group
belongs_to :captain, class_name: 'User', foreign_key: 'captain_id'
has_many :bookings, dependent: :destroy
has_many :users
has_many :comments, through: :bookings
validates :name, :number_of_players, :date, :sport, presence: true
validates_inclusion_of :open, in: [true, false]
scope :passed, -> { where("date < :today", today: DateTime.current) }
scope :planned, -> { where("date >= :today", today: DateTime.current) }
def full?
self.bookings.confirmed.count >= self.number_of_players
end
def user_booked?(user)
bookings.confirmed.where(user: user).exists?
end
end
|
class TableDrawer
CELL_LENGTH = 20
ROW_LENGTH = 63
attr_reader :headers, :rows, :total, :discount
def initialize(headers, rows, total, discount)
@headers = headers
@rows = rows
@total = total
@discount = discount
end
def call
output = "\n"
output << render_break
output << render_row(headers)
output << render_break
rows.each do |row|
output << render_row(row)
end
output << render_break
output << render_row("Total price: #{total}", ROW_LENGTH - 1)
output << render_row("Discount: #{discount}", ROW_LENGTH - 1)
output << render_break
output << "\n"
print output
end
private
def render_row(row, pad = CELL_LENGTH)
result = []
row = [row] unless row.is_a?(Array)
row.each do |cell|
result << "#{render_cell(cell, pad)}"
end
"| #{result.join('|')}|\n"
end
def render_break
"|#{'-' * ROW_LENGTH}|\n"
end
def render_cell(value, pad = CELL_LENGTH)
"#{value}#{pad(value.to_s.length, pad)}"
end
def pad(length, pad = CELL_LENGTH)
' ' * (pad - length)
end
end
|
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
def select_date(date, from:)
label_el = find('label', text: from)
id = label_el['for'].delete_suffix('_3i')
select(date.year, from: "#{id}_1i")
select(I18n.l(date, format: "%B"), from: "#{id}_2i")
select(date.day, from: "#{id}_3i")
end
# Devise test helpers
include Warden::Test::Helpers
Warden.test_mode!
end
# Register the new driver for Capybara
Capybara.register_driver :headless_chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new(args: %w[no-sandbox headless disable-gpu window-size=1400,900])
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
Capybara.save_path = Rails.root.join('tmp/capybara')
Capybara.javascript_driver = :headless_chrome
|
class PasswordsController < ApplicationController
layout 'basic'
# GET /accounts/password/new
def new
render cell(Password::Cell::New, Account.new)
end
# POST /accounts/password
def create
run Password::SendResetInstructions do
flash[:notice] = I18n.t("devise.passwords.send_instructions")
return redirect_to new_account_session_path
end
render cell(Password::Cell::New, @model)
end
# GET /accounts/password/edit?reset_password_token=abcdef
def edit
account = Account.new(reset_password_token: params[:reset_password_token])
render cell(Password::Cell::Edit, account)
end
# PUT /accounts/password
def update
account = Account.reset_password_by_token(params[:account])
if account.errors.empty?
flash[:notice] = I18n.t("devise.passwords.updated")
sign_in(:account, account)
redirect_to root_path
else
render cell(Password::Cell::Edit, account)
end
end
end
|
require 'spec_helper'
describe "edicts/show" do
before(:each) do
@edict = assign(:edict, stub_model(Edict,
:keys => "",
:kanji => "",
:kana => "",
:defs => "",
:edict_id => "MyText"
))
end
it "renders attributes in <p>" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
rendered.should match(//)
rendered.should match(//)
rendered.should match(//)
rendered.should match(//)
rendered.should match(/MyText/)
end
end
|
require "spec_helper"
describe MysticsController do
describe "routing" do
it "routes to #index" do
get("/mystics").should route_to("mystics#index")
end
it "routes to #new" do
get("/mystics/new").should route_to("mystics#new")
end
it "routes to #show" do
get("/mystics/1").should route_to("mystics#show", :id => "1")
end
it "routes to #edit" do
get("/mystics/1/edit").should route_to("mystics#edit", :id => "1")
end
it "routes to #create" do
post("/mystics").should route_to("mystics#create")
end
it "routes to #update" do
put("/mystics/1").should route_to("mystics#update", :id => "1")
end
it "routes to #destroy" do
delete("/mystics/1").should route_to("mystics#destroy", :id => "1")
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.