text stringlengths 10 2.61M |
|---|
class BancosController < ApplicationController
respond_to :html, :js
def index
@bancos = Banco.all
respond_with @bancos
end
def show
@banco = Banco.find(params[:id])
respond_with @banco
end
def new
@banco = Banco.new
respond_with @banco
end
def edit
@banco = Banco.find(params[:id])
respond_with @banco
end
def create
@banco = Banco.new(params[:banco])
flash[:notice] = "Banco foi criado com sucesso." if @banco.save
respond_with @banco
end
def update
@banco = Banco.find(params[:id])
flash[:notice] = 'Banco foi atualizado com sucesso.' if @banco.update_attributes(params[:banco])
respond_with @banco
end
def destroy
@banco = Banco.find(params[:id])
@banco.destroy
respond_with @banco
end
end
|
class Video < Content
include Getvideo
field :url, type: String
field :thumb, type: String
field :src, type: String
validates :title, :url, :presence => true
validates :url, :uniqueness => true
after_validation do |record|
record.remote_thumb_url = Getvideo.parse(url).cover
record.src = Getvideo.parse(url).flash
end
mount_uploader :thumb, VideoThumbUploader
belongs_to :community
belongs_to :video_list
# def info
# Getvideo.parse(url)
# end
end |
class CommentsController < ApplicationController
before_filter :authorize, :except => [:show, :create]
before_filter :add_breadcrumbs, :only => [:index, :edit]
# GET /comments
# GET /comments.xml
def index
@comments = Comment.find(:all).reverse
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @comments }
end
end
# GET /comments/1/edit
def edit
@comment = Comment.find(params[:id])
breadcrumbs.add t("meta.comments.edit.title"), edit_comment_path(@comment)
end
# POST /comments
# POST /comments.xml
def create
@comment = Comment.new(params[:comment])
respond_to do |format|
if verify_recaptcha(:mode => @comment, :message => "Recaptcha error") && @comment.save
Notify.comment(@comment).deliver
format.html { redirect_to post_path(@comment.post, :anchor => "comment_#{@comment.id}"), :notice => t("messages.comments.created") }
format.xml { render :xml => @comment.post, :status => :created, :location => @comment }
else
format.html { render :action => "new" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end
# PUT /comments/1
# PUT /comments/1.xml
def update
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html { redirect_to post_path(@comment.post, :anchor => "comment_#{@comment.id}"), :notice => t("messages.comments.updated") }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.xml
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_path }
format.xml { head :ok }
end
end
private
def add_breadcrumbs
breadcrumbs.add t("meta.comments.index.title"), comments_path
end
end
|
class CreateJobApplications < ActiveRecord::Migration
def change
create_table :job_applications do |t|
t.references :user
t.string :job_title
t.string :company
t.string :url
t.string :status, :default => 'PENDING'
t.datetime :application_date
t.datetime :reply_date
end
add_index :job_applications, :user_id
add_index :job_applications, :application_date
add_index :job_applications, :status
end
end
|
class DemoapiController < ApplicationController
def bearer_token
pattern = /^Bearer /
header = request.headers['Authorization']
header.gsub(pattern, '') if header && header.match(pattern)
end
# Demo example
def user
params.permit(:access_token);
access_token = params[:access_token]
if access_token.nil?
access_token = bearer_token
end
# Validate auth token
tokens = Oauthtoken.where(access_token: access_token)
if !tokens.exists?
raise "Token invalid"
end
token = tokens.take
# Todo validate expiry
# If ok, then return demo user
user = token.user_id
if user == 1
userdetails = {
:id => 1,
:username => 'demouser',
:name => 'Demo User'
}
puts userdetails
render json: userdetails.to_json
end
end
end
|
class ReviewBooksController < ApplicationController
before_action :signed_in_administrator, only:
[:index, :edit, :update, :destory, :show]
def new
@review_book = ReviewBook.new
end
def index
@review_books = ReviewBook.where(lang: I18n.locale)
end
def create
@review_book = ReviewBook.new(review_book_params)
@review_book.save
redirect_to resivefeed_path
end
def show
@review_book = ReviewBook.find(params[:id])
end
def edit
@review_book = ReviewBook.find(params[:id])
end
def update
@review_book = ReviewBook.find(params[:id])
if @review_book.update_attributes(review_book_params)
redirect_to review_books_path
else
render 'edit'
end
end
def resivefeed
end
def destroy
ReviewBook.find(params[:id]).destroy
redirect_to :back
end
private
def review_book_params
params.require(:review_book).permit(:review, :customer, :review_type, :restaurant_id, :lang)
end
end
|
require "powerapi/exception.rb"
require "powerapi/parser.rb"
require "powerapi/version.rb"
require "powerapi/data/assignment.rb"
require "powerapi/data/section.rb"
require "powerapi/data/student.rb"
require "savon"
require "json"
module PowerAPI
USER_TYPE_PARENT = 1;
USER_TYPE_STUDENT = 2;
module_function
def authenticate(url, username, password, userType=PowerAPI::USER_TYPE_STUDENT, fetch_transcript=true)
url = clean_url(url)
soap_endpoint = url + "/pearson-rest/services/PublicPortalService"
login_client = Savon.client(
endpoint: soap_endpoint,
namespace: "http://publicportal.rest.powerschool.pearson.com/xsd",
wsse_auth: ["pearson", "pearson"]
)
login = login_client.call(:login, message: { username: username, password: password, userType: 1} )
if login.body[:login_response][:return][:user_session_vo] == nil
raise PowerAPI::Exception.new(login.body[:login_response][:return][:message_v_os][:description])
end
session = login.body[:login_response][:return][:user_session_vo]
return PowerAPI::Data::Student.new(url, session, fetch_transcript)
end
def clean_url(url)
if url[-1] == "/"
url = url[0..-2]
else
url = url
end
end
def district_lookup(code)
request = HTTPI::Request.new("https://powersource.pearsonschoolsystems.com/services/rest/remote-device/v2/get-district/" + code)
request.headers = { "Accept" => "application/json" }
details = HTTPI.get(request)
if details.error?
return false
end
details = JSON.parse(details.body)
district_lookup_url(details["district"]["server"])
end
def district_lookup_url(district_server)
if district_server["sslEnabled"] == true
url = "https://"
else
url = 'http://'
end
url += district_server["serverAddress"]
if (district_server["sslEnabled"] == true and district_server["portNumber"] != 443) or
(district_server["sslEnabled"] == false and district_server["portNumber"] != 80)
url += ":" + district_server["portNumber"].to_s
end
url
end
end
|
module Bosh::Director
class ProblemResolver
attr_reader :logger
def initialize(deployment)
@deployment = deployment
@resolved_count = 0
@resolution_error_logs = StringIO.new
#temp
@event_log_stage = nil
@logger = Config.logger
end
def begin_stage(stage_name, n_steps)
@event_log_stage = Config.event_log.begin_stage(stage_name, n_steps)
logger.info(stage_name)
end
def track_and_log(task, log = true)
@event_log_stage.advance_and_track(task) do |ticker|
logger.info(task) if log
yield ticker if block_given?
end
end
def apply_resolutions(resolutions)
@resolutions = resolutions
problems = Models::DeploymentProblem.where(id: resolutions.keys)
begin_stage('Applying problem resolutions', problems.count)
if Config.parallel_problem_resolution
ThreadPool.new(max_threads: Config.max_threads).wrap do |pool|
problems.each do |problem|
pool.process do
process_problem(problem)
end
end
end
else
problems.each do |problem|
process_problem(problem)
end
end
error_message = @resolution_error_logs.string.empty? ? nil : @resolution_error_logs.string.chomp
[@resolved_count, error_message]
end
private
def process_problem(problem)
if problem.state != 'open'
reason = "state is '#{problem.state}'"
track_and_log("Ignoring problem #{problem.id} (#{reason})")
elsif problem.deployment_id != @deployment.id
reason = 'not a part of this deployment'
track_and_log("Ignoring problem #{problem.id} (#{reason})")
else
apply_resolution(problem)
end
end
def apply_resolution(problem)
handler = ProblemHandlers::Base.create_from_model(problem)
handler.job = self
resolution = @resolutions[problem.id.to_s] || handler.auto_resolution
problem_summary = "#{problem.type} #{problem.resource_id}"
resolution_summary = handler.resolution_plan(resolution)
resolution_summary ||= 'no resolution'
begin
track_and_log("#{problem.description} (#{problem_summary}): #{resolution_summary}") do
handler.apply_resolution(resolution)
end
rescue Bosh::Director::ProblemHandlerError => e
log_resolution_error(problem, e)
end
problem.state = 'resolved'
problem.save
@resolved_count += 1
rescue => e
log_resolution_error(problem, e)
end
def log_resolution_error(problem, error)
error_message = "Error resolving problem '#{problem.id}': #{error}"
logger.error(error_message)
logger.error(error.backtrace.join("\n"))
@resolution_error_logs.puts(error_message)
end
end
end
|
class AddAiControlledToArmies < ActiveRecord::Migration
def change
add_column :armies, :ai_controlled, :boolean
end
end
|
# Uncomment this if you reference any of your controllers in activate
# require_dependency 'application'
class SimpleLivechatExtension < Spree::Extension
version "1.0"
description "Describe your extension here"
url "http://yourwebsite.com/simple_livechat"
# Please use simple_livechat/config/routes.rb instead for extension routes.
def self.require_gems(config)
config.gem 'easy-gtalk-bot'
config.gem "daemon-spawn", :lib => "daemon-spawn", :version => '= 0.2.0'
config.gem "daemons"
config.gem 'eventmachine', :version => '0.12.10'
config.gem "json"
config.gem "escape_utils", :version => "~> 0.1.6"
config.gem "faye"
end
def activate
Spree::BaseController.class_eval do
before_filter :set_uid
private
def set_uid
session[:uid] ||= Digest::SHA1.hexdigest("#{rand(100)}--#{Time.now.to_i.to_s}")[4..11]
end
end
AppConfiguration.class_eval do
preference :jabber_account, :string
preference :jabber_password, :string
preference :support_jabber_account, :string
end
# make your helper avaliable in all views
Spree::BaseController.class_eval do
helper do
def livechat(options)
end
end
end
end
end
|
class Gossip < ApplicationRecord
belongs_to :user
has_many :comments
has_many :linktags
has_many :tags, through: :linktags
end
|
class Esendex
module Responses
class Account
extend Serialisable
root 'account'
attribute :id, 'id'
attribute :uri, 'uri'
element :reference, 'reference'
element :label, 'label'
element :address, 'address'
element :type, 'type'
element :messages_remaining, 'messagesremaining', Parser.for(&:to_i)
element :expires_on, 'expireson'
element :role, 'role'
element :settings, Class.new {
extend Serialisable
root 'settings'
attribute :uri, 'uri'
}
end
end
end
|
class CreateProcessManualReclassTables < ActiveRecord::Migration
def change
create_table :process_manual_reclass_tables do |t|
t.integer :representative_number
t.string :policy_type
t.integer :policy_number
t.integer :re_classed_from_manual_number
t.integer :re_classed_to_manual_number
t.string :reclass_manual_coverage_type
t.date :reclass_creation_date
t.date :payroll_reporting_period_from_date
t.date :payroll_reporting_period_to_date
t.float :re_classed_to_manual_payroll_total
t.string :payroll_origin
t.string :data_source
t.timestamps null: false
end
end
end
|
require 'rails_helper'
RSpec.describe VideoRating, :type => :model do
before(:each) do
@video = create :video
@user = create :user
end
it "is user blank" do
video = build(:video_rating, video: @video, user: nil)
video.valid?
expect(video.errors[:user]).to include("can't be blank")
end
it "is video blank" do
video = build(:video_rating, video: nil, user: @user)
video.valid?
expect(video.errors[:video]).to include("can't be blank")
end
end
|
# frozen_string_literal: true
require 'spec_helper'
require 'namarara'
describe Namarara::Parser do
let(:parser) do
Namarara::Parser.new(Namarara::Lexer.new)
end
it 'has to report var which is not defined' do
line = 'character = true'
parser.names = {}
token = parser.parse(line)
errors = token.errors.select do |el|
el.is_a? Namarara::Errors::VarNotDefined
end
_(errors.size).must_equal 1
_(errors[0].var).must_equal 'character'
end
it 'has to report vars which are not defined' do
line = 'a_girl_has_no_name AND character'
parser.names = {}
token = parser.parse(line)
errors = token.errors.select do |el|
el.is_a? Namarara::Errors::VarNotDefined
end
_(errors.size).must_equal 2
_(errors[0].var).must_equal 'a_girl_has_no_name'
_(errors[1].var).must_equal 'character'
end
it 'has to report invalid_grammar' do
line = '( a_girl_has_no_name = true ) ' \
'ANDAND ( character = "Arya Stark" ) OR false AND true'
parser.names = { 'a_girl_has_no_name' => true, 'character' => 'Arya Stark' }
token = parser.parse(line)
parser.check_grammar line, token
_(token.errors.select do |elem|
elem.is_a? Namarara::Errors::InvalidGrammar
end.size).must_equal 1
end
it 'has to be nil when grammar is completely invalid' do
line = 'false / "Arya"'
parser.names = {}
token = parser.parse(line)
parser.check_grammar line, token
assert_nil token
end
end
|
class ApplicationController < ActionController::Base
VALID_LOCALES_AS_REGEX = /(en|de)/
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
private
def set_locale
I18n.locale = extract_certrain_locals_from_params || extract_certain_locales_from_accept_language_header || I18n.default_locale
end
def extract_certrain_locals_from_params
params.fetch(:locale, '')[VALID_LOCALES_AS_REGEX]
end
def extract_certain_locales_from_accept_language_header
request.env.fetch('HTTP_ACCEPT_LANGUAGE', '')[VALID_LOCALES_AS_REGEX]
end
end
|
FactoryGirl.define do
factory :complaint do
address 'MyString'
cep 'MyString'
after(:build) do |c|
c.state = build(:state)
c.city = build(:city)
end
end
end
|
class Api::V1::OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
def index
@orders = Order.all
render json: @orders
end
def show
render json: @order
end
def new
@order = Order.new
end
def create
@user = get_current_user
@order = Order.create(user_id: @user.id)
params[:products].each do |product|
@oi = OrderItem.create(order: @order, product_id: product['id'], quantity: 1, price: product['price'])
end
if @order.valid?
render json: @order
else
render json: {error: 'Unable to create order.'}
end
end
def edit
render json: @order
end
def update
@order.update(order_params)
if @order.save
render json: @order, status: :accepted
else
render json: {errors: @order.errors.full_messages }, status: :unprocessible_entity
end
end
def destroy
if @order
@order.destroy
render json: {message: 'Order deleted'}
else
render json: {error: 'Unable to find order'}
end
end
private
def set_order
@order = Order.find(params[:id])
end
def order_params
params.require(:order).permit(:user_id)
end
end
|
class ColumnController < GpdbController
def index
dataset = Dataset.find(params[:dataset_id])
present paginate GpdbColumn.columns_for(authorized_gpdb_account(dataset), dataset)
end
end
|
require "rails_helper"
RSpec.describe "deleting anime" do
it "should delete anime and redirect to animes page" do
Animee.create(name: "Naruto")
visit "/animes"
expect(page).to have_text("Naruto")
click_button "delete"
expect(page).to_not have_text("Naruto")
end
end
|
# Optimized for Vagrant 1.7 and above.
Vagrant.require_version ">= 1.7.0"
required_plugins = %w( vagrant-disksize vagrant-winnfsd vagrant-bindfs )
_retry = false
required_plugins.each do |plugin|
unless Vagrant.has_plugin? plugin
system "vagrant plugin install #{plugin}"
_retry=true
end
end
if (_retry)
exec "vagrant " + ARGV.join(' ')
end
Vagrant.configure(2) do |config|
config.vm.boot_timeout = 600
config.vm.box = "lostsnow/dev-box"
config.vm.hostname = "dev-box"
config.vm.define "dev-box"
config.vm.provider :virtualbox do |vb|
vb.name = "dev-box"
#vb.memory = 2048
vb.customize [ "modifyvm", :id, "--cpus", 2 ]
vb.customize [ "modifyvm", :id, "--uartmode1", "file", File::NULL ]
vb.customize [ "modifyvm", :id, "--natdnshostresolver2", "on"]
end
#config.disksize.size = "40GB"
# Disable the new default behavior introduced in Vagrant 1.7, to
# ensure that all Vagrant machines will use the same SSH key pair.
# See https://github.com/mitchellh/vagrant/issues/5005
config.ssh.insert_key = false
#config.winnfsd.uid = 501
#config.winnfsd.gid = 501
config.vm.synced_folder ".", "/vagrant", disabled: true
config.vm.synced_folder "../src", "/mnt/projects",
type: "nfs",
mount_options: ['rw,vers=3,udp,nolock,actimeo=2']
#mount_options: ['rw,async,fsc,nolock,vers=3,udp,rsize=32768,wsize=32768,hard,noatime,actimeo=2']
config.bindfs.default_options = {
force_user: 'www',
force_group: 'www',
create_as_user: true,
perms: 'u=rwX:g=rD:o=rD'
}
config.bindfs.bind_folder "/mnt/projects", "/home/www/projects"
config.vm.network "private_network", ip: "172.22.22.11"
end
|
class FixComputedTokenColumnName < ActiveRecord::Migration
def up
rename_column :custom_fields, :computed_token, :easy_computed_token
[CustomField, DocumentCategoryCustomField, GroupCustomField, IssueCustomField,
IssuePriorityCustomField, ProjectCustomField, TimeEntryActivityCustomField,
TimeEntryCustomField, UserCustomField, VersionCustomField].
each {|cf_class| cf_class.reset_column_information }
end
def down
rename_column :custom_fields, :easy_computed_token, :computed_token
end
end
|
class CyclistsController < ApplicationController
before_action :set_cyclist, only: [:show, :edit, :update, :destroy]
# GET /cyclists
# GET /cyclists.json
def index
@cyclists = Cyclist.all
end
# GET /cyclists/1
# GET /cyclists/1.json
def show
end
# GET /cyclists/new
def new
@cyclist = Cyclist.new
end
# GET /cyclists/1/edit
def edit
end
# POST /cyclists
# POST /cyclists.json
def create
@cyclist = Cyclist.new(cyclist_params)
respond_to do |format|
if @cyclist.save
format.html { redirect_to @cyclist, notice: 'Cyclist was successfully created.' }
format.json { render :show, status: :created, location: @cyclist }
else
format.html { render :new }
format.json { render json: @cyclist.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cyclists/1
# PATCH/PUT /cyclists/1.json
def update
respond_to do |format|
if @cyclist.update(cyclist_params)
format.html { redirect_to @cyclist, notice: 'Cyclist was successfully updated.' }
format.json { render :show, status: :ok, location: @cyclist }
else
format.html { render :edit }
format.json { render json: @cyclist.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cyclists/1
# DELETE /cyclists/1.json
def destroy
@cyclist.destroy
respond_to do |format|
format.html { redirect_to cyclists_url, notice: 'Cyclist was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cyclist
@cyclist = Cyclist.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cyclist_params
params.require(:cyclist).permit(:photo, :first_name, :last_name, :age, :weight, :height, :cyclist_type, :description)
end
end
|
class Store < ActiveRecord::Base
has_and_belongs_to_many :customers
has_many :goods
end
|
require 'pry'
class Follower
attr_accessor :name , :age, :life_moto
@@all = []
def initialize(name , age , life_moto)
@name = name
@age = age
@life_moto = life_moto
@@all << self
end
def join_cult(cult)
#takes in an argument of a `Cult` instance and adds this follower to
#the cult`s lista of followers
BloodOath.new(self, cult)
end
def self.all
@@all
end
def self.of_a_certain_age(age_arg) # ==> integer argm.
#returns an `Array` of followers who are the given age or older
self.all.select {|member| member.age >= age_arg}
end
def blood_oaths
BloodOath.all.select do |blood_oath|
blood_oath.follower == self
end
end
def cults
blood_oaths.map do |blood_oath|
blood_oath.cult
end
end
def self.most_active
#returns the `Follower` instance who has joined the most cults
follower_activity = self.all.map do |follower|
{follower => follower.cults.length}
end
sorted = follower_activity.sort_by {|follower| follower.values[0]}.reverse
sorted[0]
end
def self.top_ten
end
end |
require 'spec_helper'
require 'xss_defense'
class ActiveRecordPerson < ActiveRecord::Base
set_table_name :people
end
describe XssDefense::ActiveRecord do
before(:all) do
load_schema
end
describe "class methods" do
it "has the xss_defense class method" do
ActiveRecordPerson.respond_to?(:xss_defense).should be_true
end
end
describe "validator set-up" do
before do
ActiveRecordPerson.send(:xss_defense)
end
it "adds a validator" do
ActiveRecordPerson.validators.count.should == 1
end
it "validates each :string field" do
validated_atts = ActiveRecordPerson.validators.map(&:attributes).flatten.uniq
validated_atts.should include(:forename)
validated_atts.should include(:surname)
end
it "validates each :text field" do
validated_atts = ActiveRecordPerson.validators.map(&:attributes).flatten.uniq
validated_atts.should include(:description)
end
end
end |
class Score < ActiveRecord::Base
belongs_to :press
belongs_to :game
def press_name
press.name if press
end
def press_name=(name)
self.press = Press.find_or_create_by_name(name) unless name.blank?
end
def game_id
game.id if game
end
def game_id=(id)
self.game = Game.find(id) unless id.blank?
end
end
|
require 'rails_helper'
RSpec.describe Contact, type: :model do
let(:contact) { create(:contact) }
describe "ActiveModel validations" do
it { expect(contact).to validate_presence_of(:user_id) }
it { expect(contact).to validate_presence_of(:uploaded_file_id) }
it { expect(contact).to validate_presence_of(:email) }
it { expect(contact).to validate_uniqueness_of(:email).scoped_to(:user_id) }
it { expect(contact).to validate_presence_of(:name) }
it { expect(contact).to validate_presence_of(:birth_date) }
it { expect(contact).to validate_presence_of(:address) }
it { expect(contact).to validate_presence_of(:credit_card) }
it { expect(contact).to validate_presence_of(:phone) }
it { expect(contact).to serialize(:credit_card) }
end
describe "ActiveRecord associations" do
it { expect(contact).to belong_to(:user) }
it { expect(contact).to belong_to(:uploaded_file) }
it { expect(contact).to have_db_column(:address).of_type(:string).with_options(null: false) }
it { expect(contact).to have_db_column(:birth_date).of_type(:date).with_options(null: false) }
it { expect(contact).to have_db_column(:credit_card).of_type(:string).with_options(null: false) }
it { expect(contact).to have_db_column(:email).of_type(:string).with_options(null: false) }
it { expect(contact).to have_db_column(:name).of_type(:string).with_options(null: false) }
it { expect(contact).to have_db_column(:phone).of_type(:string).with_options(null: false) }
it { expect(contact).to have_db_index(:user_id) }
it { expect(contact).to have_db_index(:uploaded_file_id) }
end
describe ".credit_card" do
context "when record is saved" do
it "encrypts the value" do
expect(contact.credit_card_before_type_cast).not_to eq(contact.credit_card)
end
end
end
end
|
require 'pry'
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(array)
array.keep_if{|words|word.split('').sort == words.split('').sort}
end
end
|
class AddRefrenceToSchoolFromSchoolGradeAndSchoolEssReport < ActiveRecord::Migration
def change
add_reference :school_ess_reports, :schools, index: true
add_reference :school_grades, :schools, index: true
end
end
|
class Store < ApplicationRecord
validates :name, :address, :phone, presence: true
has_many :users
has_many :store_items
has_many :retur
enum store_type:{
retail: 0,
warehouse: 1
}
end
|
module EmbeddableContent
module HtmlTags
class NodeProcessor < EmbeddableContent::NodeProcessor
include TemplateBased
def data_rows
@data_rows ||= list_data.each_slice(num_columns).to_a
end
def node_selector_class
'embedded-unstructured-data'
end
private
def list_data
@list_data ||= node.css('li').map(&:text)
end
DEFAULT_NUM_COLUMNS = 8
def num_columns
DEFAULT_NUM_COLUMNS
end
end
end
end
|
ActiveAdmin.register Subscription do
menu label: "Subscriptions"
permit_params :email
filter :email
index do
selectable_column
id_column
column :email
column :send_newsletter
column :updated_at
column :created_at
actions defaults: true do
end
end
form do |f|
f.inputs do
f.input :email
end
f.actions
end
end |
module Hippo::TransactionSets
class Base
class << self
attr_accessor :components, :identifier
def components
@components ||= []
end
def loop_name(id)
@identifier = id
end
def add_component(klass, options={})
options[:maximum] ||= 1
components << options.merge(:class => klass, :sequence => components.length)
end
alias segment add_component
alias loop add_component
end
attr_accessor :values, :parent, :sequences
def initialize(options = {})
@parent = options.delete(:parent)
end
def values
@values ||= {}
end
def increment(segment_identifier)
@sequences ||= Hash.new(0)
@sequences[segment_identifier] += 1
end
def segment_count
values.values.map(&:segment_count).inject(&:+)
end
def to_s
output = ''
values.sort.each do |sequence, component|
output += component.to_s
end
output
end
def get_component(identifier, sequence = nil)
if sequence.nil?
sequence = 0
else
sequence = sequence.to_i - 1
end
self.class.components.select do |c|
c[:class].identifier == identifier
end[sequence]
end
def populate_component(component, defaults)
defaults ||= {}
defaults.each do |key, value|
if key =~ /(\w+)\.(.+)/
next_component, next_component_value = component.send($1.to_sym), {$2 => value}
populate_component(next_component, next_component_value)
else
component.send((key + '=').to_sym, value)
end
end
component
end
def initialize_component(component_entry)
component = component_entry[:class].new :parent => self
# iterate through the hash of defaults
# and assign them to the component before
# adding to @values
populate_component(component, component_entry[:defaults])
populate_component(component, component_entry[:identified_by])
end
def method_missing(method_name, *args)
component_name, component_sequence = method_name.to_s.split('_')
component_entry = get_component(component_name, component_sequence)
if component_entry.nil?
raise Hippo::Exceptions::InvalidSegment.new "Invalid segment specified: '#{method_name.to_s}'."
end
if values[component_entry[:sequence]].nil?
component = if component_entry[:maximum] > 1
RepeatingComponent.new(component_entry, self)
else
initialize_component(component_entry)
end
values[component_entry[:sequence]] = component
end
yield values[component_entry[:sequence]] if block_given?
return values[component_entry[:sequence]]
end
class RepeatingComponent < Array
def initialize(component_entry, parent)
@component_entry = component_entry
@parent = parent
end
def build
self.push(@parent.initialize_component(@component_entry))
yield self[-1] if block_given?
self[-1]
end
def to_s
self.map(&:to_s).join
end
def segment_count
self.map(&:segment_count).inject(&:+)
end
def method_missing(method_name, *args, &block)
build if self.length == 0
self.first.send(method_name, *args, &block)
end
end
end
end
|
class CreateVelatorios < ActiveRecord::Migration[5.0]
def change
create_table :velatorios do |t|
t.string :tramites_defuncion
t.string :asesor_a_domicilio
t.string :sala_de_velatorio
t.integer :cirios
t.integer :portacirios
t.integer :cruz
t.integer :flores_en_canasto
t.string :flores_cubre_urna
t.string :integer
t.integer :libro_de_condolencias
t.string :parroco
t.integer :coro
t.integer :aviso_prensa
t.integer :tarjeta_agradecimiento
t.string :cafeteria
t.timestamps
end
end
end
|
require "#{File.expand_path(File.dirname(__FILE__))}/helper.rb"
class TestSeeds < Test::Unit::TestCase
def test_use_seed_value_for_initial_value_of_increment
t = Class.new(TestClass) do
storage_bucket :cached_count, :counter => true, :seed => Proc.new { |obj| obj.tedious_count }
def tedious_count
99_999 # ... bottle of beers on the wall
end
end.new
assert_equal t.tedious_count + 1, t.increment_cached_count
end
def test_use_seed_value_for_initial_value_of_increment_by
t = Class.new(TestClass) do
storage_bucket :cached_count, :counter => true, :seed => Proc.new { |obj| obj.tedious_count }
def tedious_count
99_999 # ... bottle of beers on the wall
end
end.new
amount = 2
assert_equal t.tedious_count + amount, t.increment_cached_count_by(amount)
end
def test_use_seed_value_for_initial_value_of_decrement
t = Class.new(TestClass) do
storage_bucket :cached_count, :counter => true, :seed => Proc.new { |obj| obj.tedious_count }
def tedious_count
99_999 # ... bottle of beers on the wall
end
end.new
assert_equal t.tedious_count - 1, t.decrement_cached_count
end
def test_use_seed_value_for_initial_value_of_decrement_by
t = Class.new(TestClass) do
storage_bucket :cached_count, :counter => true, :seed => Proc.new { |obj| obj.tedious_count }
def tedious_count
99_999 # ... bottle of beers on the wall
end
end.new
amount = 3
assert_equal t.tedious_count - amount, t.decrement_cached_count_by(amount)
end
end |
class AddBscSpecToLineItems < ActiveRecord::Migration
def change
add_column :spree_line_items, :bsc_spec, :string
end
end
|
class Event < ApplicationRecord
has_many :bookings, foreign_key: :attended_event
has_many :attendees, through: :bookings, source: :attendee
belongs_to :host, class_name: "User"
end |
require 'spec_helper'
describe ServiceController do
describe "GET 'index'" do
fixtures :all
it "returns http success" do
get 'index', {format: :html}
response.should be_success
end
it 'should handle an incorrect call with no form data' do
get 'rewards_responder', {format: 'html'}
response.should redirect_to(index_path)
end
it 'should respond with valid json from a valid account portfolio' do
portfolio = portfolios(:portfolio1)
account_id = portfolio.account_id
get 'rewards_responder', {account_id: account_id, id: portfolio.id , format: :json}
response.should be_success
assigns(:reward).should be_an_instance_of(Reward)
JSON.parse(response.body).should == ["CHAMPIONS_LEAGUE_FINAL_TICKET", "N/A"]
end
end
end
|
# encoding: utf-8
#--
# (c) Copyright 2010 Mikael Lammentausta
#
# See the file LICENSE included with the distribution for
# software license details.
#++
class Marionet
attr_reader :data, :portlet
def initialize(uri)
logger.debug 'new marionet: %s' % uri
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == "https") # enable SSL/TLS
result = http.request_get(uri.path + '?' + uri.query).body
#logger.debug("Webservice response:\n#{result}")
@data = Nokogiri::XML.parse(result)
@portlet = Marionet::Parser.transform(@data)
end
def logger
RAILS_DEFAULT_LOGGER
end
def self.logger
RAILS_DEFAULT_LOGGER
end
end |
def active_nav_item?(page)
case current_path
when 'index.html'
page == :index
when 'contact/index.html'
page == :contact
else
false
end
end
def mail_to(email, html_options: {})
link_to(
email,
"mailto:#{email}",
**html_options
)
end
def link_to_newsletter(title: 'Newsletter', html_options: {})
external_link_to(
title,
'http://eepurl.com/g3BqKX',
html_options: html_options
)
end
def external_link_to(title, url, html_options: {})
html_options = html_options.reverse_merge(
target: '_blank',
rel: 'noopener',
)
link_to(title, url, **html_options)
end
|
Rails.application.routes.draw do
get 'home/index'
resources :enrollments
resources :participants
resources :coordinators do
get :export_csv, on: :member
end
resources :registries
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'home#index'
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'pet show page', type: :feature do
it 'can complete deletion with DELETE and redirect' do
visit "/pets/#{@pet1.id}"
click_link 'Delete'
expect(current_path).to eq('/pets')
expect(page).not_to have_content(@pet1.name)
expect(page).not_to have_content(@pet1.age)
expect(page).not_to have_content(@pet1.sex)
end
end
|
class Finanzas::Transaccion < ApplicationRecord
CUENTA_GENERAL = Rails.application.credentials.cuenta_general
before_save :asignar_comision, :calcular_total
belongs_to :usuario, class_name: "Sistema::Usuario"
validates :monto, presence: true
private
def calcular_comision(monto, porcentaje, tasa_fija)
(porcentaje * monto / 100.0) + tasa_fija
end
def asignar_comision
case self.monto
when 0..1000
self.comision = calcular_comision(self.monto, 3.0, 8.0)
when 1001..5000
self.comision = calcular_comision(self.monto, 2.5, 6.0)
when 5001..10_000
self.comision = calcular_comision(self.monto, 2.0, 4.0)
when 5001..10_000
self.comision = calcular_comision(self.monto, 1.0, 3.0)
end
end
def calcular_total
self.total = self.comision + self.monto
end
end
# ## Schema Information
#
# Table name: `finanzas_transacciones`
#
# ### Columns
#
# Name | Type | Attributes
# --------------------- | ------------------ | ---------------------------
# **`id`** | `bigint(8)` | `not null, primary key`
# **`monto`** | `decimal(, )` |
# **`comision`** | `decimal(, )` |
# **`total`** | `decimal(, )` |
# **`numero_tarjeta`** | `string` |
# **`receptor`** | `string` |
# **`type`** | `string` | `not null`
# **`usuario_id`** | `bigint(8)` | `not null`
# **`created_at`** | `datetime` | `not null`
# **`updated_at`** | `datetime` | `not null`
#
|
Gem::Specification.new do |s|
s.name = 'coue'
s.version = '0.0.0'
s.date = '2019-03-21'
s.summary = "geocoder based autocompletion/suggestion tool"
s.description = "geocoder based autocompletion/suggestion tool"
s.authors = ["Antonio MalvaGomes"]
s.email = 'amalvag@g.clemson.edu'
s.files = ["lib/coue.rb"]
s.executables << 'coue'
s.add_runtime_dependency 'geocoder', '>= 1.2.0'
s.homepage =
'http://rubygems.org/gems/coue'
s.license = 'MIT'
end
|
class PrizeController < ApplicationController
before_filter :authorise_request_as_json, :only => [:send_to_friend, :redeem_prize, :share_social, :total_prize, :send_to_email]
before_filter :authenticate_user_json, :only => [:redeem_prize, :send_to_friend, :send_to_email]
before_filter :authorise_user_param, :only => [:share_social, :total_prize]
def send_to_friend
begin
ActiveRecord::Base.transaction do
@parsed_json["prize_id"] ? prize_id = @parsed_json["prize_id"].to_i : nil
@parsed_json["friend_id"] ? friend_id = @parsed_json["friend_id"].to_i : nil
@parsed_json["share_prize_id"] ? share_prize_id = @parsed_json["share_prize_id"].to_i : nil
prize = Prize.find_by_id(prize_id)
if prize.nil?
return render :status => 412, :json => {:status => :failed, :message => "Invalid params"}
end
location = nil
location = Location.find_by_id(prize.status_prize.location_id) unless prize.status_prize.nil?
friend = User.find_by_id(friend_id)
if location.nil? || friend.nil? || share_prize_id.nil?
return render :status => 412, :json => {:status => :failed, :message => "Invalid params"}
end
user_id = @user.id
if @user.first_name.nil?
username = @user.username
else
username = @user.first_name + " " +@user.last_name
end
redeem_value = prize.redeem_value
#==============Begin Phuong code
if share_prize_id == 0
UserPoint.create({
:user_id => user_id,
:point_type => PRIZES_SHARED,
:location_id => location.id,
:points => redeem_value,
:status => 1,
:is_give => 0
})
end
# add user to contact when user share share
CustomersLocations.add_contact(Array([user_id, friend_id]),location.id)
share = SharePrize.find_by_id(share_prize_id)
unless share.nil?
share.update_attributes(:is_refunded => 2)
end
share_prize = SharePrize.new
#==============End phuong code
share_prize.prize_id = prize_id
share_prize.from_user = user_id
share_prize.to_user = friend_id
share_prize.share_id = share_prize_id
share_prize.status = 1
share_prize.from_share = 'friend'
share_prize.save
noti = Notifications.new
noti.from_user = user_id
noti.to_user = friend.email
noti.message = share_prizes_msg(username, prize.name, location.name)
noti.msg_type = "single"
noti.location_id = location.id
noti.alert_type = PRIZE_ALERT_TYPE
noti.alert_logo = POINT_LOGO
noti.msg_subject= PRIZE_ALERT_TYPE
noti.points = redeem_value
noti.save!
return render :status => 200, :json => {:status => :success}
end
rescue
return render :status => 503, :json => {:status => :failed, :error => "Service Unavailable"}
end
end
# POST /prize/redeem_prize
# This is how users can exchange points for a prize
# of their choosing.
def redeem_prize
begin
ActiveRecord::Base.transaction do
# Set the variables
prize_id = @parsed_json["prize_id"] ? @parsed_json["prize_id"].to_i : 0
type = @parsed_json["type"] if @parsed_json["type"]
from_user = @parsed_json["from_user"] if @parsed_json["from_user"]
level = @parsed_json["level_number"] if @parsed_json["level_number"]
timezone = @parsed_json["time_zone"] if @parsed_json["time_zone"]
share_prize_id = @parsed_json["share_prize_id"] if @parsed_json["share_prize_id"]
# Confirm the necessary values are available
if prize_id == 0
return render :json => {:status => :failed, :message => "Invalid params"}
end
if type.blank?
return render :json => {:status => :failed, :message => "Type is not null"}
end
if from_user.blank?
return render :json => {:status => :failed, :message => "From_user is not null"}
end
if share_prize_id.blank?
return render :json => {:status => :failed, :message => "Share_prize_id is not null"}
end
if timezone.blank?
return render :json => {:status => :failed, :message => "Timezone is not null"}
end
# Retrieve the records
prize = Prize.find_by_id(prize_id)
unless prize.nil?
location = Location.find_by_id(prize.status_prize.location_id) unless prize.status_prize.nil?
end
if location.blank?
return render :status => 412, :json => {:status => :failed, :message => "Invalid params"}
end
#add user to contact group when user redeem prize
CustomersLocations.add_contact(Array([@user.id]), location.id)
# Retrieve the Prize record
if from_user.to_i == 0
prize = Prize.find_by_id(prize_id)
unless prize.blank?
sub_point_user(@user.id, location.id, prize.redeem_value)
end
end
# Create the PrizeRedeem record
redeem_prize = PrizeRedeem.new(
prize_id: prize_id,
user_id: @user.id,
from_user: from_user,
level: level,
redeem_value: prize.redeem_value,
timezone: timezone,
share_prize_id: share_prize_id,
from_redeem: type,
is_redeem: 1
)
if redeem_prize.save
# Update the SharePrize record
share_prize = SharePrize.find_by_id(share_prize_id)
share_prize.update_attribute(:is_redeem, 1) if share_prize.present?
# Return a nice little response using a bunch of ugly SQL
sql = "
SELECT DATE_FORMAT(CONVERT_TZ(pr.created_at,'+00:00', pr.timezone), '%m.%d.%Y / %I:%i%p') AS date_time_redeem
FROM prize_redeems AS pr
WHERE pr.id = #{redeem_prize.id}"
time_redeem = Prize.find_by_sql(sql)
return render json: {status: :success, date_time_redeem: time_redeem.first.date_time_redeem}
end
end
rescue => e
return render json: {status: :failed, error: e.message}
end
end
def share_social
begin
ActiveRecord::Base.transaction do
type = params[:type] if params[:type]
location_id = params[:location_id] if params[:location_id]
date_time = params[:date_time] if params[:date_time]
point = 0
share_social = SocialShare.new
share_social.location_id = location_id
share_social.user_id = @user.id
share_social.socai_type = type
share_social.date_time = date_time
location = Location.find_by_id(location_id)
return render :status => 404, :json => {:status => :failed, :error => "Resource not found"} if location.nil?
if share_social.save
user_share = SocialShare.where("location_id = ? and user_id = ? and socai_type =? and date_time = ?",location_id,@user.id,type,date_time)
item = Item.find params[:item_id]
share_social.update_attribute('item_id', item.id)
if user_share.count <= 3
socail_point = SocialPoint.find_by_location_id(location_id)
unless socail_point.nil?
if type == 'facebook'
point = socail_point.facebook_point.to_i
elsif type == 'twitter'
point = socail_point.twitter_point.to_i
elsif type == 'googleplus'
point = socail_point.google_plus_point.to_i
elsif type == 'instagram'
point = socail_point.instragram_point.to_i
end
end
if point.to_i > 0
add_point_user(@user.id, location_id, point)
end
end
#add user to contact group when user share menu item and restaurant on social
CustomersLocations.add_contact(Array([@user.id]), location_id)
return render :json => {:status => :success}
end
end
rescue
return render :status => 500, :json => {:status => :failed, :error => "Internal Service Error"}
end
end
def add_point_user(user_id,location_id,point)
UserPoint.create(
{
:user_id => user_id,
:point_type => "Points from Restaurant",
:location_id => location_id,
:points => point,
:status => 1,
:is_give => 1
})
end
def add_point_user(user_id,location_id,point)
UserPoint.create({
:user_id => user_id,
:point_type => "Points from Restaurant",
:location_id => location_id,
:points => point,
:status => 1,
:is_give => 1
})
end
def sub_point_user(user_id,location_id,point)
UserPoint.create({
:user_id => user_id,
:point_type => "Redeem Prize",
:location_id => location_id,
:points => point,
:status => 1,
:is_give => 0
})
end
def total_prize
@locations = Location.get_location_global(@user.id)
count = 0
user_id = @user.id
unless @locations.empty?
@locations.each do |l|
current_prizes = Prize.get_unlocked_prizes_by_location(l.id, l.total, user_id)
prizes = current_prizes.concat(Prize.get_received_prizes(l.id, user_id))
prizes = Prize.reject_prizes_in_order(current_prizes, l.id, user_id)
prizes = Prize.hide_redeemed_prizes_after_three_hours(prizes)
unless prizes.empty?
prizes.each do |prize|
if prize.date_time_redeem.nil?
count = count + 1
end
end
end
end
end
return render :status => 200, :json => {:status => :success , :total_prize => count}
end
def send_to_email
begin
ActiveRecord::Base.transaction do
@parsed_json["prize_id"] ? prize_id = @parsed_json["prize_id"].to_i : nil
@parsed_json["email"] ? email = @parsed_json["email"].to_s : nil
@parsed_json["share_prize_id"] ? share_prize_id = @parsed_json["share_prize_id"].to_i : nil
prize = Prize.find_by_id(prize_id)
if prize.nil?
return render :status => 412, :json => {:status => :failed, :message => "Invalid params"}
end
location = prize.status_prize.location unless prize.status_prize.nil?
if location.nil? || share_prize_id.nil?
return render :status => 412, :json => {:status => :failed, :message => "Invalid params"}
end
user_id = @user.id
if @user.first_name.nil?
username = @user.username
else
username = @user.first_name + " " + @user.last_name
end
redeem_value = prize.redeem_value
# minus point of user
if share_prize_id == 0
UserPoint.create({
:user_id => user_id,
:point_type => PRIZES_SHARED,
:location_id => location.id,
:points => prize.redeem_value,
:status => 1,
:is_give => 0
})
end
#add user to contact group when user share prize
CustomersLocations.add_contact(Array([@user.id]), location.id)
share = SharePrize.find_by_id(share_prize_id)
unless share.nil?
share.update_attributes(:is_refunded => 2)
end
share_prize = SharePrize.new
share_prize.prize_id = prize_id
share_prize.from_user = @user.id
share_prize.share_id = share_prize_id
share_prize.from_share = 'friend'
user = User.find_by_email(email)
unless user.nil?
share_prize.to_user = user.id
if user.is_register == 1 || user.is_register == 2
share_prize.status = 0
share_prize.save
@friendship = Friendship.new
@friendship.friendable_id = @user.id
@friendship.friend_id = user.id
@friendship.pending = 0
@friendship.save!
link = "http://#{request.host}:#{request.port}/share_prize/#{location.id}/#{share_prize.token}/#{@friendship.token}"
UserMailer.send_email_share_prize(email, @user.username, prize.name, location.name, link).deliver
else
share_prize.status = 1
share_prize.save
noti = Notifications.new
noti.from_user = user_id
noti.to_user = email
noti.message = share_prizes_msg(username, prize.name, location.name)
noti.msg_type = "single"
noti.location_id = location.id
noti.alert_type = PRIZE_ALERT_TYPE
noti.alert_logo = POINT_LOGO
noti.msg_subject= PRIZE_ALERT_TYPE
noti.points = redeem_value
noti.save
end
return render :status => 200 , :json => {:status => :success}
else
user_new = User.new
user_new.username = ''
user_new.email= email
user_new.password = @user.generate_password(8)
user_new.first_name = ''
user_new.last_name = ''
user_new.is_register = 1
user_new.zip = ''
user_new.role = USER_ROLE
user_new.reset_authentication_token!
user_new.save(:validate => false)
# add invited user to friend list
@friendship = Friendship.new
@friendship.friendable_id = @user.id
@friendship.friend_id = user_new.id
@friendship.pending = 0
@friendship.save!
share_prize.status = 0
share_prize.to_user = user_new.id
share_prize.save!
link = "http://#{request.host}:#{request.port}/share_prize/#{location.id}/#{share_prize.token}/#{@friendship.token}"
UserMailer.send_email_share_prize(email, @user.username, prize.name, location.name, link).deliver
return render :status => 200 , :json => {:status => :success}
end
end
rescue
return render :status => 500, :json => {:status => :failed, :error => "Internal Service Error"}
end
end
def new
@prize = SharePrize.find_by_token(params[:token])
@location = Location.find_by_id(params[:id])
@friendship = Friendship.find_by_token(params[:friendship_token])
if @prize.nil? || @location.nil?
redirect_to root_path
else
@user = User.find_by_id(@prize.to_user)
@prize_token = @prize.token
@is_receive = @prize.status
end
end
def register
ActiveRecord::Base.transaction do
token = params[:prize_token]
share_prize = SharePrize.find_by_token(token)
@friendship = Friendship.find_by_id(params[:friend_id])
@user = User.find_by_id(share_prize.to_user)
location_id = params[:location_id]
@location = Location.find(location_id)
unless @friendship.nil?
respond_to do |format|
if !@user.nil?
@user.update_attributes(params[:user])
update_geo_info(@user)
share_prize.status = 1
# share_prize.generate_token
share_prize.save
@friendship.generate_token
@friendship.update_attribute(:pending, 1)
UserMailer.custom_send_email(@user.email,SIGNUP_SUCCESS_SUBJECT,SIGNUP_SUCCESS_BODY).deliver
#add user to contact group when user share prize
CustomersLocations.add_contact(Array([@user.id]), location_id)
#redirect to succes page
format.html { render action: "success" }
else
@prize_token = token
format.html { render action: "new" }
end
end
end
end
end
def update_geo_info(user)
if user.user?
geo_obj = Geocoder.search(user.zip).first
unless geo_obj.nil?
info = {}
info[:state] = geo_obj.state unless geo_obj.state.nil?
info[:city] = geo_obj.city unless geo_obj.city.nil?
user.update_attributes(info)
end
end
end
def addPrize
prize_token = params["prize_token"] if params["prize_token"]
prize = SharePrize.find_by_token(prize_token)
unless prize.nil?
prize.status = 1
prize.save
end
return render text: "true"
end
def check_username
username = params[:username]
user = User.find_by_username(username)
if user.nil?
return render text: "true"
else
return render text: "false"
end
end
def check_email
email = params[:email]
user_id = params[:user_id]
user = User.find_by_email(email)
if user.nil?
return render text: "true"
else
if user.id.to_i == user_id.to_i
return render text: "true"
else
return render text: "false"
end
end
end
end
|
require "formula"
class Tarsnap < Formula
homepage "https://www.tarsnap.com/"
url "https://www.tarsnap.com/download/tarsnap-autoconf-1.0.35.tgz"
sha256 "6c9f6756bc43bc225b842f7e3a0ec7204e0cf606e10559d27704e1cc33098c9a"
bottle do
cellar :any
sha1 "057993febf5b5b02d022e0b1a1b1e6d9dcee1702" => :mavericks
sha1 "41b83f3a61169a73e3ce5c73f0c8f533dbf8161c" => :mountain_lion
sha1 "a84965928a810a18f8dbac38091e4ab9a9e69214" => :lion
end
depends_on "xz" => :optional
depends_on "openssl"
def install
system "./configure", "--disable-dependency-tracking",
"--enable-sse2",
"--prefix=#{prefix}",
"--sysconfdir=#{etc}"
system "make", "install"
end
end
|
class CreatePostCategories < ActiveRecord::Migration
def up
create_table "post_categories" do |t|
t.string "title"
t.integer "list_order", :default => 999
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "post_categories_posts", :id => false do |t|
t.integer "post_category_id"
t.integer "post_id"
end
end
def down
drop_table :post_categories
drop_table :post_categories_posts
end
end |
module Keyta
module ErrorFormatter
def self.call(message, backtrace, options, env, e)
{
error: e.class.to_s,
message: message,
status: e.class.method_defined?(:status) ? e.status : 599, # Check if from CustomError
traces: backtrace[0..1],
source: env['REQUEST_PATH'],
exception: e,
timestamp: Time.now.localtime
}.to_json
end
end
end |
class Item < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
has_one_attached :image
belongs_to_active_hash :shipping_cost
belongs_to_active_hash :shipping_day
belongs_to_active_hash :category
belongs_to_active_hash :condition
belongs_to_active_hash :shipping_area
belongs_to :user
has_one :purchased_item, dependent: :destroy
with_options presence: true do
validates :image
validates :name, length: { maximum: 40 }
validates :description, length: { maximum: 1000 }
validates :price, numericality: { greater_than_or_equal_to: 300, less_than_or_equal_to: 9999999 }, format: { with: /\A[0-9]+\z/ }
with_options numericality: { other_than: 0, message: "Select" } do
validates :category_id
validates :condition_id
validates :shipping_cost_id
validates :shipping_area_id
validates :shipping_day_id
end
end
end |
require 'rails_helper'
describe Api::V1::Users do
let!(:users) { create_list(:user, 2) }
let(:membership) { create(:membership, user: users[0]) }
describe 'GET /api/v1/users' do
include_context 'token accessible api' do
let(:path) { '/api/v1/users' }
end
context 'user is a guest' do
it 'returns unathorized response' do
get '/api/v1/users'
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
before do
sign_in(membership)
get '/api/v1/users'
end
after { sign_out }
it 'returns all active users for current organisation' do
expect(json_response.class).to be Array
expect(json_response.size).to eq(
UsersRepository.new.for_organisation(membership.organisation).count,
)
end
end
end
describe 'GET /api/v1/users/:user_id' do
include_context 'token accessible api' do
let(:path) { "/api/v1/users/#{user.id}" }
end
context 'user is a guest' do
it 'returns unathorized response' do
get "/api/v1/users/#{users[0].id}"
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
it 'returns specific user' do
membership = create :membership
user = create(:user)
membership.organisation.users << user
sign_in(membership)
get "/api/v1/users/#{user.id}"
expect(json_response['name']).to eq user.name
sign_out
end
it 'returns forbidden status when accessing user in different organisation' do
sign_in(create(:membership))
user_in_different_organisation = create :user
organisation_b = create :organisation
organisation_b.users << user_in_different_organisation
get "/api/v1/users/#{user_in_different_organisation.id}"
expect(response).to have_http_status(403)
sign_out
end
end
end
end
|
require_relative 'node'
class OpenAddressing
def initialize(size)
@items = Array.new(size)
@size = size
end
# Insertion of new item
def []=(key, value)
index = index(key, @size)
if @items[index] && @items[index].value != value
if key == @items[index].key
# existing key with different value, ignore insertion
return
else
# collision
new_index = next_open_index(index)
if new_index == -1
# no empty space
resize()
self[key] = value
else
# insertion at new index
@items[new_index] = Node.new(key, value)
#print()
end
end
else
# new or duplicated insertion at empty location
@items[index] = Node.new(key,value)
#print()
end
end
# Retrieval of an item by key
def [](key)
index = index(key, @size)
if @items[index] && ( @items[index].key == key )
return @items[index].value
else
next_index = index + 1
while next_index != index
if @items[next_index].key == key
return @items[next_index].value
else
if next_index < ( @size - 1 )
next_index += 1
else
next_index = 0
end
end
end
return nil
end
end
# Returns a unique, deterministically reproducible index into an array
# Hash code is the summation of the ASCII values in the key string
def index(key, size)
code = 0
key.each_byte do |c|
code = code + c
end
location = code % size
return location
end
# Given an index, find the next open index in @items
# Uses simple Linear Probing
def next_open_index(index)
if @size == 1
return -1
end
next_index = index + 1
while @items[next_index] && ( next_index != index )
if next_index < ( @size - 1 )
next_index += 1
else
next_index = 0
end
end
if next_index == index
return -1
else
return next_index
end
end
# Double the hash size & relocate existing items
def resize
@size = 2 * @size
temp = Array.new(@size)
for entry in @items do
if entry
index = index(entry.key, @size)
# collision
if temp[index]
next_index = index + 1
while temp[next_index]
if next_index < ( @size - 1 )
next_index += 1
else
next_index = 0
end
end
index = next_index
end
# insertion at new location
temp[index] = Node.new(entry.key, entry.value)
end
end
@items = temp
end
# Simple method to return the number of locations in the hash
def size
@size
end
# Number of actual items in the hash (not empty)
def count
count = 0
for location in @items do
if location
count += 1
end
end
return count
end
# Display the contents of the hash
def print
puts 'HASH SUMMARY'
puts 'size: ' + @size.to_s + ' # of items: ' + count().to_s
puts 'load factor: ' + (count()/@size.to_f).round(2).to_s
for index in 0..@size do
if @items[index]
puts 'Index: ' + index.to_s + ' ' + @items[index].key + ' -> ' + @items[index].value
end
end
end
end
def test_function
star_wars_movies = OpenAddressing.new(6)
star_wars_movies["Star Wars: The Phantom Menace"] = "Number One"
star_wars_movies["Star Wars: Attack of the Clones"] = "Number Two"
star_wars_movies["Star Wars: Revenge of the Sith"] = "Number Three"
star_wars_movies["Star Wars: A New Hope"] = "Number Four"
star_wars_movies["Star Wars: The Empire Strikes Back"] = "Number Five"
star_wars_movies["Star Wars: Return of the Jedi"] = "Number Six"
star_wars_movies["One too many"] = "Number Seven"
star_wars_movies.print()
end
test_function() |
class ProductCategoriesController < ApplicationController
load_and_authorize_resource
def index
@product_categories = ProductCategory.where(parent_id: nil)
@total_records = ProductCategory.count
end
end
|
require 'spec_helper'
describe DataLoader do
context '.load_products' do
it 'loads two products' do
expect(described_class.load_products.count).to eq(2)
end
it 'returns instances of Product model' do
expect(described_class.load_products.first).to be_a(Product)
end
it 'sets attributes correctly' do
product = described_class.load_products.first
aggregate_failures 'Product attributes' do
expect(product.id).to eq(1)
expect(product.name).to eq('Milk')
expect(product.price_in_cents).to eq(300)
expect(product.discount_ids).to eq([1])
end
end
end
context '.load_discountss' do
it 'loads two products' do
expect(described_class.load_discounts.count).to eq(2)
end
it 'returns instances of Discount model' do
expect(described_class.load_discounts.first).to be_a(Discount)
end
it 'sets attributes correctly' do
product = described_class.load_discounts.first
aggregate_failures 'Discount attributes' do
expect(product.id).to eq(1)
expect(product.name).to eq('Milk Discount')
expect(product.amount_in_cents).to eq(294)
expect(product.quantity).to eq(2)
end
end
end
end
|
# Given two singly linked lists that intersect at some point, find the intersecting node.
# The lists are non-cyclical.
# For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with
# value 8.
# In this example, assume nodes with the same value are the exact same node objects.
# Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
def intersection(headA, headB)
tailA = headA
tailB = headB
while tailA || tailB
tailA ? tailA = tailA.next : headB = headB.next
tailB ? tailB = tailB.next : headA = headA.next
end
while headA != headB
headA = headA.next
headB = headB.next
end
headA
end |
require 'pry'
def consolidate_cart(cart)
new_cart = {}
cart.each do |item|
item.each do |k, v|
if new_cart.has_key?(k)
new_cart[k][:count] += 1
else
new_cart[k] = v
new_cart[k][:count] = 1
end
end
end
new_cart
end
def apply_coupons(cart, coupons)
new_cart = cart.clone
coupons.each do |coupon|
cart.each do |item, details|
if item == coupon[:item]
if new_cart["#{item} W/COUPON"] == nil && new_cart[item][:count] >= coupon[:num]
new_cart[item][:count] = cart[item][:count] - coupon[:num]
new_cart["#{item} W/COUPON"] = {:price => coupon[:cost], :clearance => cart[item][:clearance], :count => 1}
elsif new_cart["#{item} W/COUPON"] && new_cart[item][:count] >= coupon[:num]
new_cart[item][:count] -= coupon[:num]
#binding.pry
new_cart["#{item} W/COUPON"][:count] += 1
end
end
end
if new_cart == {}
new_cart = cart
end
end
return new_cart
end
def apply_clearance(cart)
new_cart = {}
cart.each do |item, details|
if cart[item][:clearance] == true
new_cart[item] = cart[item]
new_cart[item][:price] = (cart[item][:price] * 0.8).round(2)
else
new_cart[item] = cart[item]
end
end
return new_cart
end
def checkout(cart, coupons)
new_cart = apply_clearance(apply_coupons(consolidate_cart(cart),coupons))
sum = 0
new_cart.each do |k,v|
sum += v[:count] * v[:price]
end
if sum > 100
sum*0.9.round(2)
else
sum.round(2)
end
end |
class CreateAdditions < ActiveRecord::Migration
def change
create_table :additions do |t|
t.integer :client_id
t.string :cont
t.string :contname
t.string :email
t.timestamps
end
end
end
|
require 'net/http'
require 'nokogiri'
require 'time'
module Holiday
class Holiday
def initialize(from, to)
@from = from
@to = to
end
def holiday?(time)
@from <= time and time <= @to
end
end
class Holidays
def initialize(holidays)
@holidays = holidays
end
def holiday?(time)
@holidays.any? { |h| h.holiday?(time) }
end
end
def self.query
url = "http://telechargement.index-education.com/vacances.xml"
uri = URI.parse(url)
response = Net::HTTP.get(uri)
Nokogiri::XML(response)
end
def self.parse(document)
zone = "C" # Paris
holidays = document.xpath("//zone[@libelle=\"#{zone}\"]//vacances")
h = holidays.map do |holiday|
Holiday.new(Time.strptime(holiday["debut"], "%Y/%m/%d"), Time.strptime(holiday["fin"], "%Y/%m/%d"))
end
Holidays.new(h)
end
def self.holidays
parse(query)
end
end
|
require 'pry'
class Triangle
def initialize(x, y, z)
@x = x
@y = y
@z = z
end
def validate_triangle
real_or_not = []
if @x == 0 && @y == 0 && @z == 0
return true
end
if @x + @y <= @z || @x + @z <= @y || @y + @z <= @x
return true
end
[@x, @y, @z].each do |side|
if side > 0
real_or_not << true
else
real_or_not << false
end
end
real_or_not.include?(false)
end
def kind
if validate_triangle == true
raise TriangleError
else
if @x == @y && @x == @z
return :equilateral
elsif @x == @y || @x == @z || @y == @z
return :isosceles
else
return :scalene
end
end
end
class TriangleError < StandardError
end
end
|
class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.string :line1
t.string :line2
t.string :town_city
t.string :county
t.references :country, index: true, foreign_key: true
t.string :zip
t.references :addressible, index: true, polymorphic: true
t.timestamps null: false
end
end
end
|
require 'csv'
class Pickup < ApplicationRecord
belongs_to :material
belongs_to :trash
belongs_to :session
belongs_to :cleanup_event
has_one_attached :image
scope :has_image, -> { joins(:image_attachment) }
# The to_csv_string and to_csv_file methods probably belong in some common location
# The issue is that there the csv output can vary based on use-case, but code for what goes
# inot the report is the same, regardless
def self.to_csv_string(cleanup_event_id = nil, session = nil)
CSV.generate(headers: true) do |csv|
self.as_csv(csv, cleanup_event_id, session)
end
end
def self.to_csv_file(file_name, cleanup_event_id = nil)
CSV.open(file_name, 'w') { |csv| self.as_csv csv, cleanup_event_id }
end
def self.as_csv(csv, cleanup_event_id = nil, session = nil)
csv <<
%w[
Id
Event
Session
When
Latitude
Longitude
Trash
Weight
Brand
Material
Is\ Recyclable
Organization
Group\ Size
First\ Pickup\ Time
Completed\ At
]
pickup_query =
Pickup.includes(:trash, :material, :cleanup_event, session: :haul)
if cleanup_event_id
pickup_query =
pickup_query.where(['cleanup_event_id = ?', cleanup_event_id])
end
pickup_query = pickup_query.where(['session_id = ?', session.id]) if session
pickup_query.find_each(batch_size: 5_000) do |pickup|
haul = pickup.session.haul
csv <<
[
pickup.id,
pickup.cleanup_event.name,
pickup.session_id,
pickup.created_at,
pickup.latitude,
pickup.longitude,
pickup.trash.name,
pickup.trash.weight,
pickup.brand,
pickup.material.name,
pickup.is_recyclable,
haul.organization,
haul.group_size,
haul.first_pickup_time,
haul.completed_at
]
end
end
end
|
class SemestersController < ApplicationController
before_action :find_semester, only: [:show]
def index
@semesters = Semester.all
end
def show
@good_books = @semester.books.where("rating = '2'")
@bad_books = @semester.books.where("rating = '1'")
@new_books = @semester.books.where("rating IS NULL")
end
private
def find_semester
@semester = Semester.find(params[:id])
end
end
|
require 'Redis'
require 'json'
require 'yaml'
class Redfig
attr_reader :app, :env, :redis
# How configuration values are stored in Redis:
#
# keys are formatted as:
#
# prefix:env:app:key
#
# eg: redfig:development:auth-api:db_host
# eg: redfig:prod:default:support_email
def initialize options={}
# set defaults
@env = options[:env] || 'default'
@app = options[:app] || 'default'
@verbose = options[:verbose].nil? ? true : options[:verbose]
@subscribe_to_changes = options[:subscribe_to_changes].nil? ? true : options[:subscribe_to_changes]
@cache_locally = options[:cache_locally].nil? ? true : options[:cache_locally]
redis_options = options[:redis] || {}
@prefix = redis_options[:prefix] || 'redfig'
@local_cache = {}
puts "- Initializing Redis client with settings: #{redis_options.inspect}" if @verbose
@redis = Redis.new redis_options
end
def set! identifier, val, app=nil, env=nil
raise "Key must not be type nil" if identifier.nil?
puts "- Setting #{identifier} => #{val.inspect}" if @verbose
app ||= @app
env ||= @env
unless val.instance_of? String
val = val.to_json
end
key = "#{@prefix}:#{env}:#{app}:#{identifier}"
puts "KEY: #{key}" if @verbose
@redis.set key, val
end
def get! identifier
puts "- Getting #{identifier}" if @verbose
# need to fetch four keys, in order of priority
# alternatively can just glob.. glob???
candidates = @redis.multi do
@redis.get "#{@prefix}:#{@env}:#{@app}:#{identifier}"
@redis.get "#{@prefix}:default:#{@app}:#{identifier}"
@redis.get "#{@prefix}:#{@env}:default:#{identifier}"
@redis.get "#{@prefix}:default:default:#{identifier}"
end
# iterate through keys, first non-nil wins
candidates.each do |candidate|
if candidate
@local_cache[identifier] = candidate
return candidate
end
end
raise "Key not found"
end
def [] identifier
# if we have a local cache entry, just return that
return val if val = @local_cache[identifier]
# otherwise lazily fill the cache from Redis
get! identifier
end
# import file given file handler or filename
def import_file! file
# if given a file name, try opening it
if file.instance_of? String
_file = File.open file
elsif file.instance_of? File
_file = file
else
raise "type not recognized: #{file.class.name}"
end
puts "- Iterating over keys in #{_file.inspect}" if @verbose
# iterate over keys
YAML::load(_file).each do |env, env_hash|
env_hash.each do |app, app_hash|
app_hash.each do |namespace, namespace_hash|
namespace_hash.each do |identifier, value|
k = "#{namespace}:#{identifier}"
set! k, value, app, env
end
end
end
end
end
# import every yaml file in folder
def import_folder! folder
end
end |
#Clase que define un artìculo escrito en este Blog
class Articulo
attr_accessor :id,:titulo,:contenido
def initialize id,titulo
@id = id
@titulo = titulo
@contenido = "Articulo nuevo..."
end
end
|
class UserController < ApplicationController
respond_to :json
def get_listings
@user = User.where(listing_params).first
if @user
@listings = RablRails.render @user.filtered_listings, 'index', view_path: 'app/views/homes', format: :json
respond_with(@homes)
end
end
def update
User.where(id: user_id).update update_user_params
success
end
def success
respond_with :ok
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def user_id
params.require(:id)
end
def update_user_params
params.require(:user).permit(:name)
end
end
|
class Education < ApplicationRecord
belongs_to :user, optional: :true
validates :education, :per, :year, presence: :true
end
|
class AddArtistHomeImgToArtists < ActiveRecord::Migration
def self.up
add_column :artists, :artist_home_img_url, :string
add_column :artists, :artist_home_img_hover_url, :string
end
def self.down
remove_column :artists, :artist_home_img_hover_url
remove_column :artists, :artist_home_img_url
end
end
|
ProjectMediaUserType = GraphqlCrudOperations.define_default_type do
name 'ProjectMediaUser'
description 'A mapping between users and project medias'
interfaces [NodeIdentification.interface]
field :project_media_id, types.Int
field :user_id, types.Int
field :project_media, ProjectMediaType
field :user, UserType
field :read, types.Boolean
end
|
class CreateProductions < ActiveRecord::Migration
def change
create_table :productions do |t|
t.datetime :make_at, :null => false
t.string :p_type, :null => false # facet or radial
t.string :p_pattern, :null => false # necklace, earring, and so on
t.string :p_material, :null => false # bamboo, metal or other
t.string :p_color, :null => false
t.string :p_size, :null => false
t.integer :love_count, :null => false, :default => 0
t.integer :price
t.string :img_url
t.timestamps
end
end
end
|
describe 'RMQViewStyler' do
describe 'visibility' do
before do
@view = Potion::View.new(RMQ.app.context)
@styler = RMQViewStyler.new(@view, RMQ.app.context)
end
it 'should support true' do
@styler.visibility = true
@view.getVisibility.should == Android::View::View::VISIBLE
end
it 'should support :visible' do
@styler.visibility = :visible
@view.getVisibility.should == Android::View::View::VISIBLE
end
it 'should support :invisible' do
@styler.visibility = :invisible
@view.getVisibility.should == Android::View::View::INVISIBLE
end
it 'should support false' do
@styler.visibility = false
@view.getVisibility.should == Android::View::View::INVISIBLE
end
it 'should support :gone' do
@styler.visibility = :gone
@view.getVisibility.should == Android::View::View::GONE
end
it 'should support the alias visible' do
@styler.visible = :gone
@view.getVisibility.should == Android::View::View::GONE
end
end
end
|
class MeasurementSerializer < ActiveModel::Serializer
attributes :id, :value, :time, :source, :created_at
belongs_to :channel, serializer: ChannelSerializer
belongs_to :user, serializer: UserPreviewSerializer, key: 'creator'
end
|
class RemoveOrderIdAndAddInvoiceIdToRequestsRefunds < ActiveRecord::Migration
def up
remove_index :requests_refunds, :order_id if index_exists?(:requests_refunds, :order_id)
remove_column :requests_refunds, :order_id
add_column :requests_refunds, :invoice_id, :integer
add_index :requests_refunds, :invoice_id
add_column :requests_refunds, :user_id, :integer
add_index :requests_refunds, :user_id
end
def down
add_column :requests_refunds, :order_id, :integer
add_index :requests_refunds, :order_id
remove_index :requests_refunds, :invoice_id if index_exists?(:requests_refunds, :invoice_id)
remove_column :requests_refunds, :invoice_id
remove_index :requests_refunds, :user_id if index_exists?(:requests_refunds, :user_id)
remove_column :requests_refunds, :user_id
end
end
|
# this is a dumping ground for old tasks that we don't quite want to delete,
# but we also don't want them polluting the site.rake.
#
# Please don't put desc tasks on these tasks
namespace :legacy do
# Approve duplicate answers (i.e. the exact Product_Answer already exists in Potential_Product_Answers)
task :approve_dup_answers => :environment do
# identify all the product_answers which are currently proposed but are exact duplicates
# of potential_product_answers and can thus be auto approved. Covary answers are
# excluded
ActiveRecord::Base.connection.execute <<-SQL
CREATE TABLE tmp_answers_to_approve
SELECT a.id
FROM product_answers a
JOIN product_questions q
ON a.product_question_id = q.id
AND q.column_name = 'value0'
AND q.status = 'active'
JOIN potential_product_answers pa
ON pa.category_id = q.category_id
AND pa.covary_group = q.covary_group
AND pa.value0 = a.value
LEFT OUTER JOIN product_questions q1
ON q.category_id = q1.category_id
AND q.covary_group = q1.covary_group
AND q1.column_name = 'value1'
AND q1.status = 'active'
WHERE a.status = 'proposed'
AND a.value IS NOT NULL
AND a.value != ''
AND q1.id IS NULL
SQL
# Identify all the product answers that covary in groups of 2 or 3 that can be auto
# approved
result_set = ActiveRecord::Base.connection.execute <<-SQL
SELECT a0.id, a1.id, null
FROM product_answers a0
JOIN product_answers a1
JOIN product_questions q0
JOIN product_questions q1
JOIN potential_product_answers ppa
LEFT OUTER JOIN product_questions q2 ON q2.category_id = q0.category_id AND q2.column_name = 'value2' AND q2.status = 'active' AND q2.covary_group = q0.covary_group
WHERE a0.product_id = a1.product_id
AND a0.product_question_id = q0.id
AND a1.product_question_id = q1.id
AND ppa.category_id = q0.category_id
AND ppa.covary_group = q0.covary_group
AND ppa.value0 = a0.value
AND ppa.value1 = a1.value
AND a0.status = 'proposed' AND a0.value IS NOT NULL AND a0.value != ''
AND a1.status = 'proposed' AND a1.value IS NOT NULL AND a1.value != ''
AND q0.column_name = 'value0' AND q0.status = 'active'
AND q1.column_name = 'value1' AND q1.status = 'active'
AND q2.id IS NULL
UNION
SELECT a0.id, a1.id, a2.id
FROM product_answers a0
JOIN product_answers a1
JOIN product_answers a2
JOIN product_questions q0
JOIN product_questions q1
JOIN product_questions q2
JOIN potential_product_answers ppa
LEFT OUTER JOIN product_questions q3 ON q3.category_id = q0.category_id AND q3.column_name = 'value3' AND q3.status = 'active' AND q3.covary_group = q0.covary_group
WHERE ppa.category_id = q0.category_id
AND ppa.covary_group = q0.covary_group
AND a0.product_id = a1.product_id
AND a0.product_id = a2.product_id
AND a0.product_question_id = q0.id
AND a1.product_question_id = q1.id
AND a2.product_question_id = q2.id
AND ppa.value0 = a0.value
AND ppa.value1 = a1.value
AND ppa.value2 = a2.value
AND a0.status = 'proposed' AND a0.value IS NOT NULL AND a0.value != ''
AND a1.status = 'proposed' AND a1.value IS NOT NULL AND a1.value != ''
AND a2.status = 'proposed' AND a2.value IS NOT NULL AND a2.value != ''
AND q0.column_name = 'value0' AND q0.status = 'active'
AND q1.column_name = 'value1' AND q1.status = 'active'
AND q2.column_name = 'value2' AND q2.status = 'active'
AND q3.id IS NULL
SQL
ids = []
result_set.each do |row|
row.each { |col| ids << col unless col.blank? }
end
ids.each do |id|
ActiveRecord::Base.connection.execute "INSERT INTO tmp_answers_to_approve VALUES (#{id})"
end
# index the tmp table to speed up the remaining steps
ActiveRecord::Base.connection.execute <<-SQL
CREATE INDEX tmp_answers_to_approve_id ON tmp_answers_to_approve (id)
SQL
# update the answers' status to approved
ActiveRecord::Base.connection.execute <<-SQL
UPDATE product_answers a, tmp_answers_to_approve b
SET a.status = 'approved'
WHERE a.id = b.id
SQL
# drop the tmp table
ActiveRecord::Base.connection.execute <<-SQL
DROP TABLE tmp_answers_to_approve
SQL
end
# Strip all product answer values
task :strip_product_answers => :environment do
count = 0
ProductAnswer.find_by_sql("select * from product_answers where value like ' %' or value like '% '").each_with_index do |a,i|
a.value.strip!
if a.save
puts "#{a.id}|#{a.value}:#{i}"
else
puts "*** #{a.id} save failed"
end
count = i+1
end
puts "Updated #{count} answers."
puts "*** Now you need to find any duplicate products based on answers and merge appropriately" if count > 0
end
task :disable_stats => :environment do
$stdout.sync = true
OperatingParam.create_or_update! :aggregated_page_views, "maintenance"
$stdout.puts "Disabled stats! Re-enable with `rake run_once:enable_stats`",
"after running the AggregatedPageViews migration"
end
desc "Re-enable stats"
task :enable_stats => :environment do
$stdout.sync = true
OperatingParam.create_or_update! :aggregated_page_views, nil
$stdout.puts "Stats re-enabled."
end
# KML: LEAVE THESE TASKS FOR NOW: we may repurpose them when we do the sampling project
task :import_sampling_program_users => :environment do
$stdout.puts 'Importing sampling program users'
sp_to_file = {
'Windex All-In-One 2009' => './db/staticdata/export_144049087.csv',
'Philly Cream Cheeses 2009' => ['./db/staticdata/export_144049216.csv', './db/staticdata/export_144049228.csv']
}
sp_to_file.each do |name,files|
program = SamplingProgram.find_by_name name
unless program
$stdout.puts "Couldn't find SamplingProgram named '#{name}'"
next
end
files = [files] unless files.is_a?(Array)
files.each do |file|
$stdout.puts "Importing #{file} for #{name}"
File.open(file) do |io|
io.each_line do |email|
begin
next if email =~ /Email Address/
email = email.strip
user = User.find_by_auth_email(email.downcase)
raise "Couldn't find user '#{email}'" unless user
SamplingProgramUser.create! :sampling_program => program, :user => user
rescue
$stdout.puts $!
end
end
end
end
end
end
task :update_sampling_flag => :environment do
sql = <<-SQL
UPDATE reviews r
JOIN sampling_program_users spu ON r.user_id = spu.user_id
JOIN sampling_program_products spp ON r.product_id = spp.product_id
SET r.affiliation = 'sample'
WHERE (r.affiliation IS NULL OR r.affiliation = 'none')
SQL
ActiveRecord::Base.connection.execute sql
end
end # of namespace legacy
|
class CreateAddressesTable < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.belongs_to :customer
t.boolean :is_primary
t.string :phone_number
t.string :street_address
t.string :street_address2
t.string :city
t.string :state
t.string :zip
t.string :country, default: "USA"
t.datetime :deleted_at
t.datetime :created_at
t.datetime :updated_at
t.string :notes
t.index :customer_id
t.index :phone_number
t.index :deleted_at
end
end
end
|
MANIFEST = FileList["Manifest.txt", "README.txt", "Rakefile", "lib/**/*.rb", "lib/jvyamlb.jar", "lib/jvyaml_internal.jar", "test/**/*.rb", "lib/**/*.rake", "src/**/*.java", "rakelib/*.rake"]
file "Manifest.txt" => :manifest
task :manifest do
File.open("Manifest.txt", "w") {|f| MANIFEST.each {|n| f << "#{n}\n"} }
end
Rake::Task['manifest'].invoke # Always regen manifest, so Hoe has up-to-date list of files
begin
require 'hoe'
hoe = Hoe.spec("jvyaml") do |p|
p.version = "0.0.2"
p.url = "http://github.com/olabini/jvyaml-gem"
p.author = "Ola Bini"
p.email = "ola.bini@gmail.com"
p.summary = "Alternative YAML engine for JRuby"
end
hoe.spec.files = MANIFEST
hoe.spec.dependencies.delete_if { |dep| dep.name == "hoe" }
rescue LoadError => le
puts le.to_s, *le.backtrace
puts "Problem loading Hoe; please check the error above to ensure that Hoe is installed correctly"
end
def rake(*args)
ruby "-S", "rake", *args
end
|
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
class GraphController < ApplicationController
include ProjectsHelper, DashboardHelper
include Report::Worktype
include Report::Projects
def graph_usage
date = Date::strptime(cookies[:report_date]) if cookies[:report_date]
date = Date::today unless date
# group by team and use subject as the key
series_usage = []
series_free = []
teams = []
chart = Ziya::Charts::StackedColumn.new(license = nil,"Resource Usage")
team_list = Team.find(:all)
team_list.each do |team|
capa = team.capacity(date)
if capa > 0 #only if the team has capacity this month (temporary help from other LOBs,...)
usage = team.usage(date)
free = [0,capa-usage].max #no negative free capacity
series_usage << usage
series_free << free
teams << team.name
end
end
if teams.size > 0
chart.add :series, "Used", series_usage
chart.add :series, "Free", series_free
chart.add :axis_category_text, teams
end
respond_to do |fmt|
fmt.xml { render :xml => chart.to_xml }
end
end
def graph_worktypes
date = Date::strptime(cookies[:report_date]) if cookies[:report_date]
date = Date::today unless date
team_id = params[:id]
team_id = '*' if params[:id].nil?
worktype_distribution = calculate_worktype_distribution(date, team_id)
chart = Ziya::Charts::Pie.new(license = nil,"Worktype distribution")
worktypes = []
workdays = []
worktype_distribution.keys.each do |wt|
wt_name = Worktype::find_by_id(wt).name
wt_daysbooked = worktype_distribution[wt][:daysbooked]
worktypes << wt_name
workdays << wt_daysbooked
end
if worktypes.size > 0
chart.add :axis_category_text, worktypes
chart.add :series, workdays
else
chart.add :axis_category_text, ["no data for work distribution"]
chart.add :series, [0,0]
end
respond_to do |fmt|
fmt.xml { render :xml => chart.to_xml }
end
end
def graph_quintiles
date = Date::strptime(cookies[:report_date]) if cookies[:report_date]
date = Date::today unless date
month = get_month_beg_end(date)
begda = month[:first_day]
endda = month[:last_day]
projects = Project::find(:all, :conditions => ["planbeg <= ? and ( planend >= ? or ( status <> ? and status <> ? )) and status <> ?", endda, begda, Project::StatusClosed, Project::StatusRejected, Project::StatusParked])
teams = Team::find(:all)
chart = Ziya::Charts::Column.new(license = nil,"quintiles")
values = {}
teams.each do |team|
values[team.id] = [0,0,0,0,0,0,0] if team.capacity(date) > 0
end
# group by team and use subject as the key
chart.add :axis_category_text, ["pending", "0-20%", "20-40%", "40-60%","60-80%", ">80%", "ad-hoc"]
projects.each do |project|
quintile = project_quintile(project.days_committed(begda),project.days_booked(begda))
team = project.country.team
values[team.id][quintile] += 1 if team.capacity(date) > 0
end
teams.each do |team|
chart.add(:series,team.name,values[team.id]) if team.capacity(date) > 0
end
respond_to do |fmt|
fmt.xml { render :xml => chart.to_xml }
end
end
def graph_project_age_current
chart = Ziya::Charts::Line.new(license = nil,"project_age")
projects = project_age_current
prj_week = {}
projects.each do |project|
prj_week[project[:wks_since_update]] = 0 if prj_week[project[:wks_since_update]].nil?
prj_week[project[:wks_since_update]] += 1
end
max_weeks=prj_week.keys.max
y = []
labels = []
week=0
(max_weeks+1).times do
if not prj_week[week].nil? then
y << prj_week[week]
else
y << 0
end
labels << week.to_s
week += 1
end
ymax=y.max
chart.add( :axis_category_text, labels)
chart.add( :series,'Current projects',y)
respond_to do |fmt|
fmt.xml { render :xml => chart.to_xml }
end
end
def graph_project_times(begda=nil,endda=nil)
begda = flash[:report_begda].to_date if begda.nil?
endda = flash[:report_endda].to_date if endda.nil?
chart = Ziya::Charts::Scatter.new(license = nil,"project_times")
#Find the projects
projects = Project::find(:all, :conditions => ["planend >= ? and planbeg <= ?", begda, endda])
projects.each do |project|
chart.add :series, '', [project.planeffort,project.days_booked()] if project.status == Project::StatusClosed
end
chart.add :axis_category_text, %w[x y]
chart.add :theme, 'neutral'
respond_to do |fmt|
fmt.xml { render :xml => chart.to_xml }
end
end
end
|
module Crossbeams
module DataminerPortal
module Report
extend Sinatra::Extension
get '/report/:id' do
@rpt = lookup_report(params[:id])
@qps = @rpt.query_parameter_definitions
@rpt_id = params[:id]
@load_params = params[:back] && params[:back] == 'y'
@menu = menu
@report_action = "/#{settings.url_prefix}run_rpt/#{params[:id]}"
@excel_action = "/#{settings.url_prefix}run_xls_rpt/#{params[:id]}"
erb :'report/parameters'
end
# Return a grid with the report.
post '/run_xls_rpt/:id' do
@rpt = lookup_report(params[:id])
setup_report_with_parameters(@rpt, params)
begin
xls_possible_types = {string: :string, integer: :integer, date: :string, datetime: :time, time: :time, boolean: :boolean, number: :float}
heads = []
fields = []
xls_types = []
x_styles = []
Axlsx::Package.new do | p |
p.workbook do | wb |
styles = wb.styles
tbl_header = styles.add_style :b => true, :font_name => 'arial', :alignment => {:horizontal => :center}
# red_negative = styles.add_style :num_fmt => 8
delim4 = styles.add_style(:format_code=>"#,##0.0000;[Red]-#,##0.0000")
delim2 = styles.add_style(:format_code=>"#,##0.00;[Red]-#,##0.00")
and_styles = {delimited_1000_4: delim4, delimited_1000: delim2}
@rpt.ordered_columns.each do | col|
xls_types << xls_possible_types[col.data_type] || :string # BOOLEAN == 0,1 ... need to change this to Y/N...or use format TRUE|FALSE...
heads << col.caption
fields << col.name
# x_styles << (col.format == :delimited_1000_4 ? delim4 : :delimited_1000 ? delim2 : nil) # :num_fmt => Axlsx::NUM_FMT_YYYYMMDDHHMMSS / Axlsx::NUM_FMT_PERCENT
x_styles << and_styles[col.format]
end
puts x_styles.inspect
wb.add_worksheet do | sheet |
sheet.add_row heads, :style => tbl_header
Crossbeams::DataminerPortal::DB[@rpt.runnable_sql].each do |row|
sheet.add_row(fields.map {|f| v = row[f.to_sym]; v.is_a?(BigDecimal) ? v.to_f : v }, :types => xls_types, :style => x_styles)
end
end
end
response.headers['content_type'] = "application/vnd.ms-excel"
attachment(@rpt.caption.strip.gsub(/[\/:*?"\\<>\|\r\n]/i, '-') + '.xls')
response.write(p.to_stream.read) # NOTE: could this streaming to start downloading quicker?
end
rescue Sequel::DatabaseError => e
erb(<<-EOS)
#{menu}<p style='color:red;'>There is a problem with the SQL definition of this report:</p>
<p>Report: <em>#{@rpt.caption}</em></p>The error message is:
<pre>#{e.message}</pre>
<button class="pure-button" onclick="crossbeamsUtils.toggle_visibility('sql_code', this);return false">
<i class="fa fa-info"></i> Toggle SQL
</button>
<pre id="sql_code" style="display:none;"><%= sql_to_highlight(@rpt.runnable_sql) %></pre>
EOS
end
end
post '/run_rpt/:id' do
@rpt = lookup_report(params[:id])
setup_report_with_parameters(@rpt, params)
@col_defs = []
@rpt.ordered_columns.each do | col|
hs = {headerName: col.caption, field: col.name, hide: col.hide, headerTooltip: col.caption}
hs[:width] = col.width unless col.width.nil?
hs[:enableValue] = true if [:integer, :number].include?(col.data_type)
hs[:enableRowGroup] = true unless hs[:enableValue] && !col.groupable
hs[:enablePivot] = true unless hs[:enableValue] && !col.groupable
if [:integer, :number].include?(col.data_type)
hs[:cellClass] = 'grid-number-column'
hs[:width] = 100 if col.width.nil? && col.data_type == :integer
hs[:width] = 120 if col.width.nil? && col.data_type == :number
end
if col.format == :delimited_1000
hs[:cellRenderer] = 'crossbeamsGridFormatters.numberWithCommas2'
end
if col.format == :delimited_1000_4
hs[:cellRenderer] = 'crossbeamsGridFormatters.numberWithCommas4'
end
if col.data_type == :boolean
hs[:cellRenderer] = 'crossbeamsGridFormatters.booleanFormatter'
hs[:cellClass] = 'grid-boolean-column'
hs[:width] = 100 if col.width.nil?
end
# hs[:cellClassRules] = {"grid-row-red": "x === 'Fred'"} if col.name == 'author'
@col_defs << hs
end
begin
# Use module for BigDecimal change? - register_extension...?
@row_defs = Crossbeams::DataminerPortal::DB[@rpt.runnable_sql].to_a.map {|m| m.keys.each {|k| if m[k].is_a?(BigDecimal) then m[k] = m[k].to_f; end }; m; }
@return_action = "/#{settings.url_prefix}report/#{params[:id]}"
erb :'report/display'
rescue Sequel::DatabaseError => e
erb(<<-EOS)
#{menu}<p style='color:red;'>There is a problem with the SQL definition of this report:</p>
<p>Report: <em>#{@rpt.caption}</em></p>The error message is:
<pre>#{e.message}</pre>
<button class="pure-button" onclick="crossbeamsUtils.toggle_visibility('sql_code', this);return false">
<i class="fa fa-info"></i> Toggle SQL
</button>
<pre id="sql_code" style="display:none;"><%= sql_to_highlight(@rpt.runnable_sql) %></pre>
EOS
end
end
end
end
end
|
# frozen_string_literal: true
module API
module V1
# Endpoints for users api
class Users < Base
helpers V1::Helpers::JSONAPIParamsHelpers
resource :users do
desc "Return all users"
paginate per_page: 10
params do
use :json_api_index
end
get do
render paginate User.all
end
desc "Return a user"
params do
requires :id, type: Integer, desc: "User id"
end
route_param :id do
get do
User.find(params[:id])
end
end
end
end
end
end
|
require "prawn_charts/shapes/arc"
require "prawn_charts/shapes/star"
module PrawnCharts
# Implements shape drawing for Prawn::Document.
module Shapes
include Arc
include Star
end # Shapes
end # PrawnCharts
|
require 'test_helper'
class ParrotsControllerTest < ActionController::TestCase
setup do
@parrot = parrots(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:parrots)
end
test "should get new" do
get :new
assert_response :success
end
test "should create parrot" do
assert_difference('Parrot.count') do
post :create, parrot: { age: @parrot.age, brood: @parrot.brood, color: @parrot.color, name: @parrot.name, sex: @parrot.sex }
end
assert_redirected_to parrot_path(assigns(:parrot))
end
test "should show parrot" do
get :show, id: @parrot
assert_response :success
end
test "should get edit" do
get :edit, id: @parrot
assert_response :success
end
test "should update parrot" do
patch :update, id: @parrot, parrot: { age: @parrot.age, brood: @parrot.brood, color: @parrot.color, name: @parrot.name, sex: @parrot.sex }
assert_redirected_to parrot_path(assigns(:parrot))
end
test "should destroy parrot" do
assert_difference('Parrot.count', -1) do
delete :destroy, id: @parrot
end
assert_redirected_to parrots_path
end
end
|
require 'vigenere_cipher'
describe 'VigenereCipher' do
let(:cipher) {VigenereCipher.new}
let(:message) {"Attack at dawn"}
let(:password) {"FREEDOM"}
it 'should take an input string and a passphrase' do
cipher.input_message(message)
cipher.use_password(password)
expect(cipher.message).to eq message
end
it 'passphrase should repeat for every non-" " character' do
cipher.input_message(message)
cipher.lengthen_password("FREEDOM")
expect(cipher.phrase).to eq "FREEDO MF REED"
end
it 'should reject passphrases that are not alpha-numeric' do
input = 'Bad-phrase'
expect{cipher.use_password(input)}.to raise_error 'ERROR: Non-alphanumeric pass'
end
it 'should shift each letter of the message by the appropriate amount' do
# FREEDO MF REED
# Attack at dawn
# ==============
result = 'Fkxefy my ueaq'
cipher.input_message(message)
cipher.use_password(password)
expect(cipher.encrypt).to eq result
end
end
|
require 'spec_helper'
describe 'knife cookbook site show COOKBOOK' do
it 'displays a summary of the cookbook information' do
cookbook = TestCook.create_cookbook
command = run "knife cookbook site show #{cookbook.name}"
command_output = CommandOutput.new(command.stdout)
output_fixture = KnifeOutputFixture.new('show', cookbook: cookbook)
expect(command_output.signature).to eql(output_fixture.signature)
end
it 'displays all versions of a published cookbook', focus: true do
name = "multi-version"
cookbook = TestCook.create_cookbook(name)
TestCook.publish_new_version(name, '0.2.0')
command = run "knife cookbook site show #{cookbook.name}"
command_output = CommandOutput.new(command.stdout)
output_fixture = KnifeOutputFixture.new('show_versions', cookbook: cookbook)
expect(command_output.signature).to eql(output_fixture.signature)
end
it 'exits with an error when attempting to view a nonexistent cookbook' do
cookbook_name = "dorfle-#{Time.now.to_i}"
expect do
run! "knife cookbook site show #{cookbook_name}"
end.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
end
|
require File.expand_path("../", __FILE__) + '/spec_helper'
require 'json'
describe CfnMetadataLoader do
before do
@stack_name = 'my_stack_name'
@cfn_path = '/opt/aws/bin/cfn-get-metadata'
@region = 'my_region'
@resource_name = 'my_resource_name'
@process = double 'process'
@cmd = "#{@cfn_path} "
@cmd << "-s #{@stack_name} "
@cmd << "-r #{@resource_name} "
@cmd << "--region #{@region} "
end
context "not using iam_profile" do
before do
@cfn = CfnMetadataLoader.new @stack_name,
@region,
@resource_name,
"my_access_key",
"my_secret_key",
@cfn_path
@cmd << "--access-key my_access_key "
@cmd << "--secret-key my_secret_key"
end
it "should return the metadata" do
cmd_return = { 'AWS::CloudFormation::Init' => 'test',
'AWS::CloudFormation::Authentication' => 'test',
'stack_name' => 'my_stack_name' }.to_json
@process.stub(:success?).and_return(true)
@cfn.process_status = @process
@cfn.should_receive(:`).with(@cmd).and_return cmd_return
@cfn.sanitized_metadata.should == ({ 'stack_name' => 'my_stack_name' })
end
it "should raise an error if unable to get metadata" do
@process.stub(:success?).and_return(false)
@cfn.process_status = @process
@cfn.should_receive(:`).with(@cmd)
expect { @cfn.sanitized_metadata }.to raise_error
end
end
context "using iam_profile" do
before do
@cfn = CfnMetadataLoader.new @stack_name,
@region,
@resource_name,
"",
"",
@cfn_path
@cfn.use_iam_profile = true
end
it "should return the metadata" do
cmd_return = { 'AWS::CloudFormation::Init' => 'test',
'AWS::CloudFormation::Authentication' => 'test',
'stack_name' => 'my_stack_name' }.to_json
@process.stub(:success?).and_return(true)
@cfn.process_status = @process
@cfn.should_receive(:`).with(@cmd).and_return cmd_return
@cfn.sanitized_metadata.should == ({ 'stack_name' => 'my_stack_name' })
end
it "should raise an error if unable to get metadata" do
@process.stub(:success?).and_return(false)
@cfn.process_status = @process
@cfn.should_receive(:`).with(@cmd)
expect { @cfn.sanitized_metadata }.to raise_error
end
end
end
|
class Frame
def initialize
@scores = []
end
def add_score(pins)
raise RangeError, "pins must be greater than 0" if pins < 0
@scores << pins
if self.strike?
@scores << 0
end
end
def full?
@scores.length == 2
end
def first_score
@scores[0].nil? ? 0 : @scores[0]
end
def second_score
@scores[1].nil? ? 0 : @scores[0]
end
def spare?
total_score == 10 && !strike?
end
def strike?
@scores[0] == 10
end
def total_score
@scores.length > 0 ? @scores.inject { |total, score| total + score } : 0
end
end
class TenthFrame < Frame
def add_score(pins)
raise RangeError, "pins must be greater than 0" if pins < 0
@scores << pins
end
def full?
return (self.first_score + self.second_score) < 10 if @scores.length == 2
return @scores.length == 3 ? true : false
end
def spare?
false
end
def strike?
false
end
end
class ScoreKeeper
def initialize
@frames = Array.new(9) { Frame.new }
@frames << TenthFrame.new
@current_frame_num = 0
end
def record_score(pins)
current_frame = @frames[@current_frame_num]
current_frame.add_score(pins)
if current_frame.full?
@current_frame_num += 1
end
end
def score
total_score = 0
(0...10).each do |frame_num|
frame = @frames[frame_num]
if frame.strike?
total_score += strike_bonus(frame_num)
elsif frame.spare?
total_score += spare_bonus(frame_num)
end
total_score += frame.total_score
end
total_score
end
protected
def spare_bonus(frame_num)
@frames[frame_num+1].first_score
end
def strike_bonus(frame_num)
next_frame = @frames[frame_num+1]
return next_frame.first_score + @frames[frame_num+2].first_score if next_frame.strike?
return next_to_last_frame?(frame_num) ? next_frame.first_score + next_frame.second_score : next_frame.total_score
end
def next_to_last_frame?(frame_num)
return frame_num == 8
end
end
class Game
def initialize
@scorekeeper = ScoreKeeper.new
end
def roll(pins)
@scorekeeper.record_score(pins)
end
def score
@scorekeeper.score
end
end
|
class SecretsController < ApplicationController
def show
if current_user.blank?
redirect_to new_path
end
end
end
|
class GiftsController < ApplicationController
def create
@stock = Stock.find(params[:stock_id])
@stock.gifts.create(gift_params)
redirect_to root_path
end
def destroy
@stock = Stock.find(params[:stock_id])
@gift = @stock.gifts.find(params[:id])
@gift.destroy
redirect_to root_path
end
private
def gift_params
params.require(:gift).permit(:gift_name, :value, :year_month, :comment)
end
end
|
require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
version = package['version']
Pod::Spec.new do |s|
s.name = "ReactNativeTwitterKit"
s.version = version
s.summary = "A native TwitterKit react native component."
s.description = <<-DESC
Twitterkit
DESC
s.homepage = "https://github.com/netceteragroup/react-native-twitterkit"
s.license = "MIT"
s.author = "Netcetera"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/netceteragroup/react-native-twitterkit", :branch => "master" }
s.source_files = "ios/*.{h,m}"
s.public_header_files = "ios/*.h"
s.requires_arc = true
s.dependency "React"
s.dependency "Fabric"
s.dependency "TwitterCore", "3.0.3"
s.dependency "TwitterKit", "3.2.2"
# For now, we are going with static libararies (default); the following
# stays commented out, in case we need it
# Force the static framework to be linked into this pod
# See https://github.com/CocoaPods/CocoaPods/issues/2926
# s.frameworks =
# 'Fabric',
# 'TwitterCore',
# 'TwitterKit',
# "Accounts",
# "CoreData",
# "CoreGraphics",
# "Foundation",
# "Security",
# "Social",
# "UIKit",
# "CoreText",
# "QuartzCore",
# "CoreMedia",
# "AVFoundation",
# "SafariServices"
#
# s.pod_target_xcconfig = {
# 'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "$(PODS_ROOT)/Fabric/iOS" "$(PODS_ROOT)/TwitterCore/iOS" "$(PODS_ROOT)/TwitterKit/iOS"'
# }
end
|
class AdminController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
layout "admin"
before_filter :authenticate
before_action :set_mona_article
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "admin" && password == "motivatedevshop"
end
end
# Use callbacks to share common setup or constraints between actions.
def set_mona_article
@mona_article = MonaArticle.find_or_create_by(id: 1)
end
end
|
class ShoppingCartsController < ApplicationController
def index
current_user
p @current_user.shopping_carts
@active_items = @current_user.shopping_carts.select { |item| item.order_id == nil}
end
def create
current_user
shopping_cart = ShoppingCart.new(product_id: params[:product_id])
@current_user.shopping_carts << shopping_cart
shopping_cart.save
redirect_to :back
end
def update
current_user
if params[:shopping_cart].include?(:admin)
if @admin
shopping_cart = ShoppingCart.find(params[:id])
shopping_cart.update_attributes(admin: params[:shopping_cart][:admin])
redirect_to "/shopping_carts"
end
else
@current_user.update(shopping_cart_params)
@current_user.save
session[:shopping_cart_id] = shopping_cart.id
redirect_to shopping_cart
end
end
def destroy
current_user
shopping_cart = ShoppingCart.find_by(email: params[:email])
shopping_cart.destroy if @current_user = shopping_cart
end
private
def shopping_cart_params
params.require(:shopping_cart).permit(:product_id)
end
end
|
class CharacterController
def initialize(input, output, character)
@input, @output = input, output
@character = character
end
def say(message)
@output.puts message
end
def read
@input.gets.chomp
end
def press_any_key_to_continue
say "-------------------- Press any key to continue --------------------"
read
end
def change_name
say "Welcome, young one. What is your name?"
@character.name = read
end
def change_type
type = read
if /knight|theif|mage/ === type
@character.attributes = Character::TYPES[type.to_sym]
else
say "If you are going to get anywhere, you're going to need to speak more clearly\n" \
"than that! What did you say?"
change_type
end
end
def type_descriptions
say "KNIGHT"
say " Health: 100"
say " Damage: 20"
say " Magic: N/A"
say " Armor: 50"
say " Speed: 40"
say ""
say "A noble type to be sure. Knights instill peace wherever they go just\n" \
"by their presence."
press_any_key_to_continue
say ""
say "THEIF"
say " Health: 50"
say " Damage: 20"
say " Magic: N/A"
say " Armor: N/A"
say " Speed: 100"
say ""
say "Quick and clever. Theives do whatever it takes to stay alive, and,\n" \
"whenever they can, to make a profit."
press_any_key_to_continue
say ""
say "MAGE"
say " Health: 50"
say " Damage: 10"
say " Magic: 40"
say " Armor: 20"
say " Speed: 50"
say ""
say "Masters of the magical arts, mages can dispell evil with a blessing...\n" \
"or summon it with a curse."
end
def display_status
say "You have #{@character.attributes[:health]} health and #{@character.money} rupees.\n"
end
def depart
say "In which direction do you want to depart?"
say "North (1), East (2), South (3), West (4)"
direction = read
case direction
when "1"
@character.move(:north)
when "3"
@character.move(:south)
when "2"
@character.move(:east)
when "4"
@character.move(:west)
else
"Please choose a valid option!"
depart
end
say @character.current_village.description
end
def view_chart
puts @character.chart.view(@character.current_village, @character.current_quest)
end
end
|
module Dota
module API
class Match
class AbilityUpgrade
attr_reader :ability, :level, :time
def initialize(raw)
@ability = Ability.new(raw["ability"])
@level = raw["level"]
@time = raw["time"]
end
end
end
end
end |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'mains#index'
get '/user/:id', to: 'sessions#index', as: 'user_profile'
delete '/logout', to: 'sessions#logout', as: 'logout'
resources :order_items
resources :mains, only: [:index]
resources :categories, only: [:index, :new, :create] do
resources :products, only: [:index]
end
resources :users do
resources :products, only: [:index]
end
resources :orders
resources :products do
resources :reviews, only: [:new, :create]
end
get "/auth/:provider/callback", to: "sessions#create", as: "auth_callback"
end
|
require "rspec"
describe "SimpleServer::Application" do
describe I18n do
describe "#default_locale" do
it "defaults to english locale" do
expect(I18n.default_locale).to eq(:en)
end
end
end
end
|
class DriverShift < ActiveRecord::Base
belongs_to :driver
validates_presence_of :driver_id, :shift
validates_uniqueness_of :driver_id, :scope => :shift, :message => 'already assigned to shift'
def shift_name
if self[:shift] == 'D'
'Day'
elsif self[:shift] == 'N'
'Night'
end
end
end
|
class NodesController < ApplicationController
def show
@node=Node.find(params[:id])
end
def create
@node = Node.new(node_params)
if @node.save
redirect_to @node
else
render 'new'
end
end
def new
@node=Node.new
end
private
def node_params
params.require(:node).permit(:node_name, :place_id)
end
end
|
require 'super_docopt'
require 'json'
require 'lp'
module Fredric
# Handles the command line interface
class CommandLine < SuperDocopt::Base
version VERSION
docopt File.expand_path 'docopt.txt', __dir__
subcommands %w[get pretty see url save]
attr_reader :path, :params, :file, :csv
def before_execute
@path = args['PATH']
@params = translate_params args['PARAMS']
@file = args['FILE']
@csv = args['--csv']
return if api_key
raise Fredric::MissingAuth, "Missing Authentication\nPlease set FRED_KEY=y0urAP1k3y"
end
def get
if csv
puts fredric.get_csv path, params
else
payload = fredric.get! path, params
puts payload.response.body
end
end
def save
success = if csv
fredric.save_csv file, path, params
else
fredric.save file, path, params
end
puts success ? "Saved #{file}" : 'Saving failed'
end
def pretty
payload = fredric.get path, params
puts JSON.pretty_generate payload
end
def see
lp fredric.get path, params
end
def url
puts fredric.url path, params
end
def fredric
@fredric ||= fredric!
end
private
def fredric!
Fredric::API.new api_key, options
end
# Convert a params array like [key:value, key:value] to a hash like
# {key: value, key: value}
def translate_params(pairs)
result = {}
return result if pairs.empty?
pairs.each do |pair|
key, value = pair.split ':'
result[key.to_sym] = value
end
result
end
def options
result = {}
return result unless cache_dir || cache_life
result[:use_cache] = true
result[:cache_dir] = cache_dir if cache_dir
result[:cache_life] = cache_life.to_i if cache_life
result
end
def api_key
ENV['FRED_KEY']
end
def cache_dir
ENV['FRED_CACHE_DIR']
end
def cache_life
ENV['FRED_CACHE_LIFE']
end
end
end
|
require 'spec_helper'
describe Timetable::Config do
describe '#read' do
context "given a valid YAML configuration file in the config path" do
let(:config_path) { File.join(Timetable::Config.path, "sushi.yml") }
let(:config_data) { { "sushi" => %w[maki nigiri sashimi] } }
before :all do
File.open(config_path, 'w') do |f|
YAML::dump(config_data, f)
end
# Force Config to reload the new file
Timetable::Config.reload
end
# Clean up after testing
after :all do
File.delete(config_path)
Timetable::Config.reload
end
it "returns nil for an invalid configuration key" do
Timetable::Config.read("this_key_will_never_exist").should be_nil
end
it "returns the corresponding value for a valid key" do
value = Timetable::Config.read("sushi")
value.should == YAML::load_file(config_path)["sushi"]
end
end
end
end |
#!/usr/bin/env rake
require "bundler/gem_tasks"
require 'rdoc'
require 'rake/testtask'
require 'rdoc/task'
$: << 'lib'
require 'OSM'
task :default => :test
desc "Run the tests"
Rake::TestTask::new do |t|
t.test_files = FileList['test/test_*.rb']
t.verbose = true
end
desc 'generate API documentation to doc/rdocs/index.html'
RDoc::Task.new do |rd|
rd.rdoc_dir = 'doc'
rd.main = 'README.rdoc'
rd.rdoc_files.include 'README.rdoc', 'ChangeLog', "lib/**/*\.rb"
rd.options << '--line-numbers'
rd.options << '--all'
end |
class AddConfirmStatusToEvents < ActiveRecord::Migration
def change
add_column :events, :confirm, :string, default: "Not Confirmed"
end
end
|
class Producte < ActiveRecord::Base
attr_accessible :data_caducitat, :lot, :nom, :preu, :proveidor, :unitats
validates :nom, :lot, :preu, :unitats, :presence => true;
#Exemples de formats permesos .41, .2, 3.12, 0.25, 4, 6.1 (després del punt decimal, dos dígits màxim)
validates :preu, :format => { :with => /^\d+??(?:\.\d{0,2})?$/ }, :numericality => {:greater_than => 0}
# Ordenem per nom
default_scope :order => 'nom'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.