text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
class CreateProductItems < ActiveRecord::Migration[5.2]
def change
create_table :product_items do |table|
table.belongs_to :product, index: true
table.string :name, null: false
table.integer :available_count, null: false, default: 0
table.string :description, null: false
table.boolean :is_active, null: false, default: false
table.timestamps
end
end
end
|
Pod::Spec.new do |s|
s.name = 'Phunware'
s.version = '1.2.2.7'
s.license = 'MIT'
s.summary = 'Phunware SDKs (BETA)'
s.homepage = 'https://github.com/phunware/beta-ios'
s.authors = { 'Phunware' => 'info@phunware.com' }
s.source = { :git => "https://github.com/phunware/beta-ios.git", :tag => "v1.2.2.7" }
s.requires_arc = true
s.ios.deployment_target = '9.0'
s.default_subspec = 'Beta'
s.subspec 'Beta' do |ss|
ss.subspec 'Location' do |sss|
sss.ios.vendored_frameworks = 'Framework/PWLocation.framework'
sss.dependency 'PWCore'
sss.dependency 'MistSDK'
sss.dependency 'TMCache'
sss.ios.library = 'c++'
sss.ios.frameworks = 'Security', 'QuartzCore', 'SystemConfiguration', 'MobileCoreServices', 'CoreTelephony', 'CoreBluetooth', 'CoreMotion', 'CoreLocation', 'MapKit'
sss.library = 'sqlite3', 'z', 'xml2.2'
end
ss.subspec 'MapKit' do |sss|
sss.ios.vendored_frameworks = 'Framework/PWMapKit.framework'
sss.ios.dependency 'Phunware/Beta/Location'
sss.ios.dependency 'TMCache'
sss.ios.frameworks = 'Security', 'CoreGraphics', 'QuartzCore', 'SystemConfiguration', 'MobileCoreServices', 'CoreTelephony', 'CoreLocation', 'MapKit'
end
end
end |
class RemoveMeasurementReferences < ActiveRecord::Migration[5.2]
def change
drop_table :references_measurements
end
end
|
require "setup"
class TestNull < Minitest::Test
attr_reader :provider
def setup
@provider = Cubic::Providers::Null.new
end
def test_inc
assert_nil provider.inc("metric")
end
def test_val
assert_nil provider.val("metric", 20)
end
def test_time
result = provider.time("some computation") { 50.times { raise "error" rescue nil } }
assert_equal 50, result
end
end
|
class GeoLocation
attr_reader :location, :country
def initialize(geo_location)
@location = geo_location[:results].first[:address_components].find {|hash| hash[:types].include?('locality') }[:long_name] + ', ' + geo_location[:results].first[:address_components].find {|hash| hash[:types].include?('administrative_area_level_1') }[:short_name]
@country = geo_location[:results].first[:address_components].find {|hash| hash[:types].include?('country') }[:long_name]
end
end
|
require 'minitest'
require 'minitest/autorun'
require 'delve/widgets/menu'
class MenuWidgetTest < Minitest::Test
def setup
@x = 5
@y = 5
@items = { 'n' => 'New Game', 'x' => 'Exit' }
@menu = MenuWidget.new @x, @y, @items
@display = mock('object')
end
def test_initialising_without_x_position_raises_error
assert_raises RuntimeError do
MenuWidget.new nil, @y, @items
end
end
def test_initialising_without_y_position_raises_error
assert_raises RuntimeError do
MenuWidget.new @x, nil, @items
end
end
def test_initialising_without_items_raises_error
assert_raises RuntimeError do
MenuWidget.new @x, @y, nil
end
end
def test_empty_items_fails
assert_raises RuntimeError do
MenuWidget.new @x, @y, Hash.new
end
end
def test_render_fails_if_no_display_is_given
assert_raises RuntimeError do
@menu.draw nil
end
end
def test_first_item_is_initially_selected
assert_equal 'New Game', @menu.selected_item
end
def test_move_down_selects_second_item
@menu.next
assert_equal 'Exit', @menu.selected_item
end
def test_move_down_then_up_selects_first_item
@menu.next
@menu.previous
assert_equal 'New Game', @menu.selected_item
end
def test_wrap_over_top
@menu.previous
assert_equal 'Exit', @menu.selected_item
end
def test_wrap_over_bottom
@menu.next
@menu.next
assert_equal 'New Game', @menu.selected_item
end
def test_false_returned_if_selecting_item_that_doesnt_exist
assert !@menu.select('p')
assert_equal 'New Game', @menu.selected_item
end
def test_selecting_by_key
assert @menu.select('x')
assert_equal 'Exit', @menu.selected_item
end
def test_render
@display.expects(:draw).times(12)
@menu.draw(@display)
end
def test_center_horizontally
@menu = MenuWidget.new :center, @y, {'a' => 'a'}
@display.expects(:width).returns(11)
@display.expects(:draw).with(6, @y, 'a', :red, :white)
@menu.draw @display
end
def test_center_vertically
@menu = MenuWidget.new @x, :center, {'a' => 'a'}
@display.expects(:height).returns(11)
@display.expects(:draw).with(@x, 6, 'a', :red, :white)
@menu.draw @display
end
def test_set_colors
MenuWidget.new @x, @y, @items, :red, :black, :green
end
end
|
module VagrantDockerCommand
class Docker
def initialize(machine)
@machine = machine
end
def machine_running?
@machine.state.id == :running
end
end
end
|
json.product do
json.id @product.id
json.title @product.title
json.description @product.description
json.start_date @product.start_date
json.end_date @product.end_date
json.rate_plans @product.rate_plans.active do |plan|
json.title plan.title
json.description plan.description
json.start_date plan.start_date
json.end_date plan.end_date
json.recurrence plan.recurrence
json.price plan.price
end
end
|
class MakeEventNotesNonNillable < ActiveRecord::Migration
def up
Event.where(notes: nil).each do |event|
event.notes = ""
event.save! :validate => false
end
change_column :events, :notes, :text, :null => false
end
def down
change_column :events, :notes, :text, :null => true
end
end
|
# frozen_string_literal: true
class CreateAlbums < ActiveRecord::Migration[6.0]
def change
create_table(:albums, id: false) do |t|
t.string(:id, limit: 16, primary_key: true, null: false)
t.timestamps
t.integer(:status, null: false, default: 0, index: true)
t.datetime(:release_date, null: false, index: true)
t.integer(:total_tracks, null: false, default: 0, index: true)
end
end
end
|
task :merge_results do
require 'simplecov'
require 'open-uri'
api_url = "https://circleci.com/api/v1.1/project/github/#{ENV['CIRCLE_PROJECT_USERNAME']}/#{ENV['CIRCLE_PROJECT_REPONAME']}/#{ENV['CIRCLE_BUILD_NUM']}/artifacts?circle-token=#{ENV['CIRCLE_TOKEN']}"
artifacts = open(api_url)
coverage_dir = '/tmp/coverage'
SimpleCov.coverage_dir(coverage_dir)
JSON.load(artifacts)
.map { |artifact| JSON.load(open("#{artifact['url']}?circle-token=#{ENV['CIRCLE_TOKEN']}")) }
.each_with_index do |resultset, i|
resultset.each do |_, data|
result = SimpleCov::Result.from_hash(['command', i].join => data)
SimpleCov::ResultMerger.store_result(result)
end
end
end
|
module Commontator
class Comment < ActiveRecord::Base
belongs_to :creator, polymorphic: true
belongs_to :editor, polymorphic: true, optional: true
belongs_to :thread
validates_presence_of :creator, on: :create
validates_presence_of :editor, on: :update
validates_presence_of :thread
validates_presence_of :body
validates_uniqueness_of :body,
scope: [:creator_type, :creator_id, :thread_id, :deleted_at],
message: I18n.t('commontator.comment.errors.double_posted')
include ExtendableModel
protected
cattr_accessor :acts_as_votable_initialized
public
def self.custom_simplify_email?(_comment, _message)
false
end
def simplify_email?(message)
Comment.custom_simplify_email?(self, message)
end
def is_modified?
!editor.nil?
end
def is_latest?
thread.comments.last == self
end
def is_votable?
return true if acts_as_votable_initialized
return false unless self.class.respond_to?(:acts_as_votable)
self.class.acts_as_votable
self.class.acts_as_votable_initialized = true
end
def get_vote_by(user)
return nil unless is_votable? && !user.nil? && user.is_commontator
votes_for.where(voter_type: user.class.name, voter_id: user.id).first
end
def update_cached_votes(vote_scope = nil)
self.update_column(:cached_votes_up, count_votes_up(true))
self.update_column(:cached_votes_down, count_votes_down(true))
end
def is_deleted?
!deleted_at.blank?
end
def delete_by(user)
return false if is_deleted?
self.deleted_at = Time.now
self.editor = user
self.save
end
def undelete_by(user)
return false unless is_deleted?
self.deleted_at = nil
self.editor = user
self.save
end
def created_timestamp
I18n.t 'commontator.comment.status.created_at',
created_at: I18n.l(created_at, format: :commontator)
end
def updated_timestamp
I18n.t 'commontator.comment.status.updated_at',
editor_name: Commontator.commontator_name(editor || creator),
updated_at: I18n.l(updated_at, format: :commontator)
end
##################
# Access Control #
##################
def can_be_created_by?(user)
user == creator && !user.nil? && user.is_commontator &&\
!thread.is_closed? && thread.can_be_read_by?(user)
end
def can_be_edited_by?(user)
return true if thread.can_be_edited_by?(user) &&\
thread.config.moderator_permissions.to_sym == :e
comment_edit = thread.config.comment_editing.to_sym
!thread.is_closed? && !is_deleted? && user == creator &&\
comment_edit != :n && (is_latest? || comment_edit == :a) &&\
thread.can_be_read_by?(user)
end
def can_be_deleted_by?(user)
mod_perm = thread.config.moderator_permissions.to_sym
return true if thread.can_be_edited_by?(user) &&\
(mod_perm == :e ||\
mod_perm == :d)
comment_del = thread.config.comment_deletion.to_sym
!thread.is_closed? && (!is_deleted? || editor == user) &&\
user == creator && comment_del != :n &&\
(is_latest? || comment_del == :a) &&\
thread.can_be_read_by?(user)
end
def can_be_voted_on?
!thread.is_closed? && !is_deleted? &&\
thread.config.comment_voting.to_sym != :n && is_votable?
end
def can_be_voted_on_by?(user)
!user.nil? && user.is_commontator && user != creator &&\
thread.can_be_read_by?(user) && can_be_voted_on?
end
end
end
|
module EndecaHelper
def create_review_response(product_id)
product = Product.find(product_id)
res = Endeca::Response.new
records = []
product.reviews.each do |review|
if review.stars == 5 #only top rated reviews
rec = Endeca::Response.new
rec['properties'] = {'Review Id' => review.id}
records << rec
end
end
res['records'] = records
return res
end
end
|
class Board
module Spaces
ALL = [
TOP_LEFT = 0,
TOP_MIDDLE = 1,
TOP_RIGHT = 2,
MIDDLE_LEFT = 3,
MIDDLE_MIDDLE = 4,
MIDDLE_RIGHT = 5,
BOTTOM_LEFT = 6,
BOTTOM_MIDDLE = 7,
BOTTOM_RIGHT = 8
].freeze
end
BLANK_SPACE = ' '.freeze
attr_reader :state
def initialize(moves)
@state = [BLANK_SPACE] * 9
moves.each do |move|
@state[move.position] = move.move_type
end
end
def value_at_space(space)
@state[space]
end
end
|
#coding: utf-8
class Email < ActiveRecord::Base
validates :message_id, presence: true,
uniqueness: true
validates :from, :mail_box, presence: true
belongs_to :mail_box
has_attached_file :attach,
:url => "/system/:id.:extension"
validates_attachment_content_type :attach, content_type: "application/zip"
end
|
require_relative '../guest_list'
RSpec.describe GuestList do
describe '#close_to' do
let(:guest_list) { GuestList.new([
{ 'latitude' => '52.986375', 'user_id' => 12,'name' => 'Christina McArdle','longitude' => lon },
{ 'latitude' => lat, 'user_id' => 1, 'name' => 'Alice Cahill', 'longitude' => lon },
{ 'latitude' => '51.885616', 'user_id' => 2, 'name' => 'Ian McArdle', 'longitude' => '-10.4240951' },
{ 'latitude' => '52.3191841','user_id' => 3, 'name' => 'Jack Enright', 'longitude' => '-8.5072391' }
]) }
let(:origin_lat) { 53.339428 } # Intercom Dublin's office lat
let(:origin_lon) { -6.257664 } # Intercom Dublin's office lon
subject { guest_list.process(origin_lat, origin_lon) }
context 'when there are customers close by' do
let(:lat) { '53.339428' }
let(:lon) { '-6.257664' }
it 'returns name and id of customers within 100 km of a given point' do
expect(subject.class).to eq(Array)
expect(subject).to eq([{ 'name' => 'Alice Cahill', 'user_id' => 1 }, { 'name' => 'Christina McArdle', 'user_id' => 12 }])
end
end
context 'when there are no customers close by' do
let(:lat) { '51.92893' }
let(:lon) { '-10.27699' }
it 'returns an empty array' do
expect(subject.class).to eq(Array)
expect(subject).to eq([])
end
end
end
end
|
#create a dictionary with 10 city, where the city a string and the key, and the area code would be the value
#get input from the user on the city name (hint: use gets.chomp)
#display the city names to the user which are aviailable in the dictionary
#display area code based on user's city choice
#loop - keep the program running and prompt the user for new city name to lookup
# method to look up area code, this will take in a has of the dictionary and the city name
#and will output are code
# method to display just city names
dict_city = {
'CEB' => 6000,
'BHL' => 6300
}
def display_city_name(hash)
hash.each {|key, city| puts "Type #{key}"}
end
def get_area_code(hash, key)
hash[key]
end
loop do
puts "Do you want to lookup a city? (Y/N)"
answer = gets.chomp
if answer != "Y"
break
end
puts "Which city do you want the area code for?"
display_city_name(dict_city)
puts "Enter your selection"
prompt = gets.chomp
#check if the key is inside the dictionary
if dict_city.include?(prompt)
puts "You selected #{prompt} with a zipcode #{get_area_code(dict_city, prompt)}"
else
puts "You entered a city name not in the dictionary"
end
end
|
require 'spec_helper'
describe Appilf::SavedSearch do
include Appilf::TestData
describe '.new' do
let(:saved_search) do
Appilf::DomainTrait.new(load_test_json_data(mocked_response_file_path('client/saved_search/saved_search.json')))
end
it 'should respond to id' do
saved_search.id.should == '789'
end
it 'should respond to name' do
saved_search.name.should == 'below $500'
end
end
end |
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def minimize_text(text, length)
if text.length > length
return text[0 .. (length - 4) ] + '...'
else
return text
end
end
def render_flash_messages
message = ''
flash.each do |key, value|
message << content_tag('div', value, :class => "flash #{key}", :id => "flash#{key.to_s.classify}" )
end
message
end
def new_child_fields_template(form_builder, association, options = {})
options[:object] ||= form_builder.object.class.reflect_on_association(association).klass.new
options[:partial] ||= association.to_s.singularize
options[:form_builder_local] ||= :f
content_for :jstemplates do
content_tag(:div, :id => "#{association}_fields_template", :style => "display: none") do
form_builder.fields_for(association, options[:object], :child_index => "new_#{association}") do |f|
render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
end
end
end
end
def add_child_link(name, association)
link_to(name, "#", :class => "add_child", :"data-association" => association)
end
def remove_child_link(name, f)
f.hidden_field(:_delete) + link_to(name, "#", :class => "remove_child")
end
def say_it_in_spanish(time)
time_in_spanish = time.gsub(/minute/, 'minuto').gsub(/hour/, 'hora').gsub(/day/, 'día').gsub(/less than a/, 'menos de un').gsub(/about/, '')
time_in_spanish.gsub(/months/, 'meses').gsub(/month/, 'mes').gsub(/year/, 'año')
end
def strip_html(text)
text.gsub(/<\/?[^>]*>/, "")
end
def coderay(code, lang)
CodeRay.scan(code, lang).div(:css => :class, :line_numbers => :inline).gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/\n/, "\r")
end
def inline_coderay(text)
text.gsub(/\<code( lang="(.+?)")?\>(.+?)\<\/code\>/m) do
content_tag("notextile", CodeRay.scan($3, $2).div(:css => :class, :line_numbers => :inline)).gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/\n/, "\r")
end
end
end |
class Field < ActiveRecord::Base
has_many :field_conditions
has_many :events
has_many :groups
geocoded_by :full_street_address
after_validation :geocode
def full_street_address
if intersection == ""
"#{street_number} #{street_address}, #{city}, #{state} #{zip_code}"
else
"#{intersection}"
end
end
end
|
module Arbetsformedlingen
module API
module Values
SoklistaPage = KeyStruct.new(
:list_name,
:total_ads,
:total_vacancies,
:data,
:raw_data
)
class SoklistaPage
include Enumerable
def each(&block)
data.each(&block)
end
def to_h
hash = super.to_h
hash[:data].map!(&:to_h)
hash
end
end
SoklistaResult = KeyStruct.new(
:id,
:name,
:total_ads,
:total_vacancies
)
end
end
end
|
require 'rails_helper'
RSpec.describe 'regions of interest survey' do
def check_checkbox(name)
find(:checkbox, name).trigger('click')
end
let(:account) { create_account(onboarding_state: 'regions_of_interest') }
before(:all) { @regions = Array.new(3) { create(:region) } }
after(:all) { @regions.each(&:destroy) }
let(:regions) { @regions }
before do
login_as_account(account)
visit survey_interest_regions_path
end
let(:submit_form) { click_on 'Save and continue' }
example 'initial page layout' do
expect(page).to have_no_sidebar
expect(page).to have_button 'Save and continue'
expect(page).to have_content 'Wish List'
regions.each do |region|
expect(page).to have_content region.name
expect(page).to have_field "interest_regions_survey_region_ids_#{region.id}"
end
end
example 'selecting some regions' do
check regions[0].name
check regions[2].name
expect do
submit_form
account.reload
end.to change { account.regions_of_interest.count }.by(2)
expect(account.regions_of_interest).to match_array [regions[0], regions[2]]
expect(current_path).to eq type_account_path
end
example 'selecting none' do
expect { submit_form }.not_to change { InterestRegion.count }
expect(current_path).to eq type_account_path
end
end
|
class CreateApprointments < ActiveRecord::Migration
def change
create_table :appointments do |t|
t.integer :agent_profile_id
t.integer :property_id, null: false
t.string :instructions
t.string :visitor, null: false
t.string :visitor_phone, null: false
t.string :visitor_email
t.datetime :meeting, null: false
t.timestamps
end
end
end
|
require 'spec_helper'
describe 'Comment pages' do
subject { page }
let(:issue) { FactoryGirl.create(:issue) }
let(:user) { FactoryGirl.create(:user) }
let(:message) { 'comment_message' }
let(:submit) { 'Comment on this issue' }
before { sign_in user }
specify { issue.comments.count.should == 0 }
describe 'commenting an issue' do
before do
visit issue_path(issue)
fill_in message, with: 'comment text'
click_button submit
end
it { should have_alert_success }
it { should have_content('comment text') }
it { should have_link(user.name, href: user_path(user)) }
specify { issue.reload.comments.count.should == 1 }
end
describe 'invalid comment' do
before do
visit issue_path(issue)
fill_in message, with: 'a' * 7
click_button submit
end
it { should have_alert_error }
specify { issue.reload.comments.count.should == 0 }
end
end
|
# frozen_string_literal: true
# Helpers to generate links and partials
module ApplicationHelper
def link_to_add_date_ranges(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render partial: "slides/#{association.to_s.singularize}_fields", locals: { f: builder }
end
link_to(name, '#', class: 'add_fields btn btn-success', data: { id: id, fields: fields.delete("\n") })
end
def link_to_add_date_ranges_new_collection(name, f, association, fid)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render partial: "slides/#{association.to_s.singularize}_fields", locals: { f: builder }
end
# this link is customized given the id of the uploaded file (fid) and the newly
# generated instance, also extended, taking into account the collection-slide
# relationship
link_to(name, '#', class: 'add_fields btn btn-success', data: {
id: id,
fields: fields.delete("\n").gsub('slide_date_ranges_attributes', "collection_slides_attributes_#{fid}_date_ranges_attributes").gsub('slide[date_ranges_attributes]', "collection[slides_attributes][#{fid}][date_ranges_attributes]")
})
end
end
|
require 'team-secrets/manifest_manager'
require 'team-secrets/master_key'
describe ManifestManager do
context 'managing the manifest' do
master_key = MasterKey.generate
before(:all) do
Dir.chdir File.dirname(File.dirname(__FILE__))
Dir.mkdir 'tmp' unless File.exists? 'tmp'
Dir.chdir 'tmp'
File.delete 'manifest.yaml' if File.exists? 'manifest.yaml'
File.write('users.yaml', 'Sample 1')
File.write('secrets.yaml', 'Sample 2')
end
after(:all) do
File.delete 'manifest.yaml' if File.exists? 'manifest.yaml'
File.delete 'users.yaml' if File.exists? 'users.yaml'
File.delete 'secrets.yaml' if File.exists? 'secrets.yaml'
end
it 'can update and write the data' do
manifest = ManifestManager.new(master_key)
expect(File.exists?('manifest.yaml')).to eq(false)
manifest.update
manifest.writeFile('manifest.yaml')
expect(manifest.validate).to eq(true)
expect(File.exists?('manifest.yaml')).to eq(true)
written = File.read('manifest.yaml')
data_written = YAML.load(written)
expect(data_written[:users_file]).to be
expect(data_written[:users_file].length).to eq(2)
expect(data_written[:users_file][:path]).to eq('users.yaml')
expect(data_written[:users_file][:signature]).to match(/\A[0-9a-f]{10,}\z/)
expect(data_written[:secrets_file]).to be
expect(data_written[:secrets_file].length).to eq(2)
expect(data_written[:secrets_file][:path]).to eq('secrets.yaml')
expect(data_written[:secrets_file][:signature]).to match(/\A[0-9a-f]{10,}\z/)
end
it 'can validate the data' do
expect(File.exists?('manifest.yaml')).to eq(true)
manifest = ManifestManager.new(master_key)
manifest.loadFile('manifest.yaml')
expect(manifest.validate).to eq(true)
File.write('users.yaml', 'Sample 3')
expect { manifest.validate }.to raise_error(/signature does not match/)
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authorize
redirect_to '/login' unless current_user
end
#######------------ Club ----------###########
def current_club
@current_club ||= Club.find(session[:club_id]) if session[:club_id]
end
helper_method :current_club
def authorize_club
redirect_to '/login' unless current_club
end
end
|
class Sslh < Formula
desc "Forward connections based on first data packet sent by client"
homepage "https://www.rutschle.net/tech/sslh.shtml"
url "https://www.rutschle.net/tech/sslh/sslh-v1.18.tar.gz"
sha256 "1601a5b377dcafc6b47d2fbb8d4d25cceb83053a4adcc5874d501a2d5a7745ad"
head "https://github.com/yrutschle/sslh.git"
bottle do
cellar :any
sha256 "e4c3c1eddd7b63c313a31d07f2b6a022c80a44e18e8c5b4b0dc6619f517dbe9f" => :high_sierra
sha256 "e359c254424ce33e3fce90e4de2ba642c551ba7c64997098b2aebda349574884" => :sierra
sha256 "5752d320b559239122b712dc145d3fabe760c4f32e6644062bcd542d1cf4a89c" => :el_capitan
sha256 "18a2489ddb8a4049a2885b947afa7baee2b2b9dca43c8e6639dba08059a4f810" => :yosemite
sha256 "b60865fd9ba00bd093e678c5d90b57aa85926444e847058e5a0389512b60abde" => :mavericks
end
depends_on "libconfig"
def install
ENV.deparallelize
system "make", "install", "PREFIX=#{prefix}"
end
test do
assert_match version.to_s, shell_output("#{sbin}/sslh -V")
end
end
|
class AddAvatarToRecruiter < ActiveRecord::Migration[5.1]
def change
add_attachment :recruiters, :avatar
end
end
|
require 'sendgrid-ruby'
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sendgrid.Client;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
##################################################
# Retrieve all recent access attempts #
# GET /access_settings/activity #
params = JSON.parse('{"limit": 1}')
response = sg.client.access_settings.activity.get(query_params: params)
puts response.status_code
puts response.body
puts response.headers
##################################################
# Add one or more IPs to the whitelist #
# POST /access_settings/whitelist #
data = JSON.parse('{
"ips": [
{
"ip": "192.168.1.1"
},
{
"ip": "192.*.*.*"
},
{
"ip": "192.168.1.3/32"
}
]
}')
response = sg.client.access_settings.whitelist.post(request_body: data)
puts response.status_code
puts response.body
puts response.headers
##################################################
# Retrieve a list of currently whitelisted IPs #
# GET /access_settings/whitelist #
response = sg.client.access_settings.whitelist.get()
puts response.status_code
puts response.body
puts response.headers
##################################################
# Remove one or more IPs from the whitelist #
# DELETE /access_settings/whitelist #
response = sg.client.access_settings.whitelist.delete(request_body: data)
puts response.status_code
puts response.body
puts response.headers
##################################################
# Retrieve a specific whitelisted IP #
# GET /access_settings/whitelist/{rule_id} #
rule_id = "test_url_param"
response = sg.client.access_settings.whitelist._(rule_id).get()
puts response.status_code
puts response.body
puts response.headers
##################################################
# Remove a specific IP from the whitelist #
# DELETE /access_settings/whitelist/{rule_id} #
rule_id = "test_url_param"
response = sg.client.access_settings.whitelist._(rule_id).delete()
puts response.status_code
puts response.body
puts response.headers
|
Puppet::Parser::Functions::newfunction(:direct_networks, :type => :rvalue, :doc => <<-EOS
parses network scheme and returns networks
directly attached to the host
EOS
) do |argv|
endpoints = argv[0]
networks = []
endpoints.each{ |k,v|
if v.has_key?('IP') and v['IP'].is_a?(Array)
v['IP'].each { |ip|
networks << IPAddr.new(ip).to_s + "/" + ip.split('/')[1]
}
end
}
return networks.join(' ')
end
|
require 'formula'
class SubproCompletion < Formula
homepage 'https://github.com/satoshun/subpro'
url 'https://raw.githubusercontent.com/satoshun/subpro/v1.0.3/subpro_completion'
sha256 'bdd97eb985eb8661c55bd3e1fbeabf0fe4d77294a80a1f6759c4f52661b15156'
def install
(prefix+'etc/bash_completion.d').install Dir['*']
end
end
|
require 'stringio'
require_relative '../ipfix/eventdispatch'
require_relative '../../ext/sctp/endpoint'
module SCTP
class Message < StringIO
attr_accessor :host
attr_accessor :port
attr_accessor :stream
attr_accessor :context
def initialize(string = nil, host = nil, port = nil, stream = 0, context = nil)
super(string)
@host = host
@port = port ? port.to_s : nil
@stream = stream
@context = context
end
end
class Endpoint
extend EventDispatch
event :association_up
event :association_down
event :send_failed
attr_reader :peer_host
attr_reader :peer_port
attr_accessor :message_class, :message_context
private :llinit, :llconnect, :llblock=, :llblock?
private :llbind, :lllisten, :llaccept, :llclose
private :lladdrsock, :llsockaddr
private :llsendmsg, :llrecvmsg
Maxbuf = 65536
Backlog = 4
def initialize(host = nil, port = nil, opts = {})
# Do a low-level init of the socket
llinit(opts)
# Set the class to initialize on recvmsg
@message_class = Message
# Set the context object to hand to newly created messages
@message_context = nil
# By default, no stored peer host or port
@peer_host = nil
@peer_port = nil
if ((!opts[:one_to_many] && !opts[:passive]) && host && port)
# If host and port present for one-to-one active socket, connect
llconnect(host, port)
@peer_host = host
@peer_port = port.to_i
@connected_flag = true;
elsif (opts && opts[:passive] && port)
# If passive, and we have at least a port, go ahead and bind
llbind(host, port)
lllisten(Backlog)
@passive_flag = true;
end
# Set nonblocking if requested
if (opts && opts[:nonblocking])
llblock = false
end
# Note one to many
if (opts[:one_to_many])
@one_to_many_flag = true
end
# Make sure we close on finalization
ObjectSpace.define_finalizer(self, lambda {|id| self.close})
self
end
def passive?
@passive_flag ? true : false
end
def connected?
@connected_flag ? true : false
end
def nonblocking?
llblock? ? false : true
end
def one_to_many?
@one_to_many_flag ? true : false
end
def accept
llaccept
end
def sendmsg(msg)
if (!connected? && (!msg.host || !msg.port))
raise "Cannot send message without destination on unconnected socket"
end
llsendmsg(msg)
end
def recvmsg
llrecvmsg(Maxbuf)
end
def inspect
"<SCTP:Endpoint (#{peer_host}:#{peer_port})"+
(passive? ? " passive" : "") +
(connected? ? " connected" : "") +
(one_to_many? ? " one_to_many" : "") +
">"
end
def close
llclose
end
end
class Socket < Endpoint
attr_reader :message
def initialize(host, port, opts = {})
super(host, port, opts)
@message = Message.new
end
def write(str)
@message.write(str)
end
def flush(stream = nil)
@message.stream = stream if stream
sendmsg(@message)
@message.truncate(0)
end
def nextmsg
@message = readmsg
end
def read(len)
str = @message.read(len)
if (!str)
return nil unless nextmsg
str = @message.read(len)
end
str
end
end
end
|
require "application_system_test_case"
class UserTest < ActionController::TestCase
setup do
# @user = user(:one) # Reference to the first fixture quote
Capybara.default_driver = :selenium
end
test "first visit, redirect to /location" do
cookies[:lat_lng] = ["48.56868604155446%7C-2.7600977620939764"]
visit("/")
assert :redirect
end
test "visit sign-in page / sign-up" do
# When we visit the User#sign_in page https://www.weather2.co/users/sign_in
visit("/users/sign_in")
# we expect to see a title with the text "Create a new account"
assert_selector "a", text: "Create a new account"
click_link('Create a new account')
page.fill_in 'user_pseudo', with: 'Test_pseudo'
page.fill_in 'user_email', with: 'test@example.com'
page.fill_in 'user_password', with: '123456'
page.fill_in 'user_password_confirmation', with: '123456'
# fill_in ('user_pseudo', :with => 'John')
click_button('Sign up')
# puts User.last.email
assert page.has_content?('Welcome! You have signed up successfully.')
# puts cookies
end
test "validate a geolocation" do
# driver = Selenium::WebDriver.for :chrome
# # flunk( [msg] )
# driver = Selenium::WebDriver.for :chrome
# page.driver.browser.execute_cdp(
# 'Emulation.setGeolocationOverride',
# latitude: 51.7,
# longitude: -1.3,
# accuracy: 50
# )
# page.driver.browser.execute_cdp(
# 'Browser.grantPermissions',
# origin: page.server_url,
# permissions: ['geolocation']
# )
# driver.get('/location')
cookies[:lat_lng] = ["48.56868604155446%7C-2.7600977620939764"]
visit("/")
# assert :redirect
# page.driver.browser.switch_to.alert.accept
# page.accept_confirm { click_button "Allow" }
# visit("/")
# follow_redirect
# # take_screenshot
# sleep(2)
# click_button('Ok Dude!')
# sleep(2)
# click_button('Allow')
puts cookies[:lat_lng]
# # assert_redirected_to ("/wizard")
# skip 'Fix this test later'
end
# save_and_open_page
# https://www.selenium.dev/documentation/webdriver/bidirectional/chrome_devtools/
# https://www.karlentwistle.com/capybara/2022/01/11/simulate-geolocation.html
# driver = Selenium::WebDriver.for :chrome
# begin
# # Latitude and longitude of Tokyo, Japan
# coordinates = { latitude: 35.689487,
# longitude: 139.691706,
# accuracy: 100 }
# driver.execute_cdp('Emulation.setGeolocationOverride', coordinates)
# driver.get 'http://location'
# ensure
# driver.quit
# end
end
|
require 'spec_helper'
describe ChunkyPNG::Canvas::Drawing do
describe '#compose_pixel' do
subject { ChunkyPNG::Canvas.new(1, 1, ChunkyPNG::Color.rgb(200, 150, 100)) }
it "should compose colors correctly" do
subject.compose_pixel(0,0, ChunkyPNG::Color(100, 150, 200, 128))
subject[0, 0].should == ChunkyPNG::Color(150, 150, 150)
end
it "should return the composed color" do
subject.compose_pixel(0, 0, ChunkyPNG::Color.rgba(100, 150, 200, 128)).should == ChunkyPNG::Color.rgb(150, 150, 150)
end
it "should do nothing when the coordinates are out of bounds" do
subject.compose_pixel(1, -1, :black).should be_nil
lambda { subject.compose_pixel(1, -1, :black) }.should_not change { subject[0, 0] }
end
end
describe '#line' do
it "should draw lines correctly with anti-aliasing" do
canvas = ChunkyPNG::Canvas.new(31, 31, ChunkyPNG::Color::WHITE)
canvas.line( 0, 0, 30, 30, ChunkyPNG::Color::BLACK)
canvas.line( 0, 30, 30, 0, ChunkyPNG::Color::BLACK)
canvas.line(15, 30, 15, 0, ChunkyPNG::Color.rgba(200, 0, 0, 128))
canvas.line( 0, 15, 30, 15, ChunkyPNG::Color.rgba(200, 0, 0, 128))
canvas.line(30, 30, 0, 15, ChunkyPNG::Color.rgba( 0, 200, 0, 128), false)
canvas.line( 0, 15, 30, 0, ChunkyPNG::Color.rgba( 0, 200, 0, 128))
canvas.line( 0, 30, 15, 0, ChunkyPNG::Color.rgba( 0, 0, 200, 128), false)
canvas.line(15, 0, 30, 30, ChunkyPNG::Color.rgba( 0, 0, 200, 128))
canvas.should == reference_canvas('lines')
end
it "should draw partial lines if the coordinates are partially out of bounds" do
canvas = ChunkyPNG::Canvas.new(1, 2, ChunkyPNG::Color::WHITE)
canvas.line(-5, -5, 0, 0, '#000000')
canvas.pixels.should == [ChunkyPNG::Color::BLACK, ChunkyPNG::Color::WHITE]
end
it "should return itself to allow chaining" do
canvas = ChunkyPNG::Canvas.new(16, 16, ChunkyPNG::Color::WHITE)
canvas.line(1, 1, 10, 10, :black).should equal(canvas)
end
end
describe '#rect' do
subject { ChunkyPNG::Canvas.new(16, 16, '#ffffff') }
it "should draw a rectangle with the correct colors" do
subject.rect(1, 1, 10, 10, ChunkyPNG::Color.rgba(0, 255, 0, 80), ChunkyPNG::Color.rgba(255, 0, 0, 100))
subject.rect(5, 5, 14, 14, ChunkyPNG::Color.rgba(0, 0, 255, 160), ChunkyPNG::Color.rgba(255, 255, 0, 100))
subject.should == reference_canvas('rect')
end
it "should return itself to allow chaining" do
subject.rect(1, 1, 10, 10).should equal(subject)
end
it "should draw partial rectangles if the coordinates are partially out of bounds" do
subject.rect(0, 0, 20, 20, :black, :white)
subject[0, 0].should == ChunkyPNG::Color::BLACK
end
it "should draw the rectangle fill only if the coordinates are fully out of bounds" do
subject.rect(-1, -1, 20, 20, :black, :white)
subject[0, 0].should == ChunkyPNG::Color::WHITE
end
end
describe '#circle' do
subject { ChunkyPNG::Canvas.new(32, 32, ChunkyPNG::Color.rgba(0, 0, 255, 128)) }
it "should draw circles" do
subject.circle(11, 11, 10, ChunkyPNG::Color('red @ 0.5'), ChunkyPNG::Color('white @ 0.2'))
subject.circle(21, 21, 10, ChunkyPNG::Color('green @ 0.5'))
subject.should == reference_canvas('circles')
end
it "should draw partial circles when going of the canvas bounds" do
subject.circle(0, 0, 10, ChunkyPNG::Color(:red))
subject.circle(31, 16, 10, ChunkyPNG::Color(:black), ChunkyPNG::Color(:white, 0xaa))
subject.should == reference_canvas('partial_circles')
end
it "should return itself to allow chaining" do
subject.circle(10, 10, 5, :red).should equal(subject)
end
end
describe '#polygon' do
subject { ChunkyPNG::Canvas.new(22, 22) }
it "should draw an filled triangle when using 3 control points" do
subject.polygon('(2,2) (20,5) (5,20)', ChunkyPNG::Color(:black, 0xaa), ChunkyPNG::Color(:red, 0x44))
subject.should == reference_canvas('polygon_triangle_filled')
end
it "should draw a unfilled polygon with 6 control points" do
subject.polygon('(2,2) (12, 1) (20,5) (18,18) (5,20) (1,12)', ChunkyPNG::Color(:black))
subject.should == reference_canvas('polygon_unfilled')
end
it "should draw a vertically crossed filled polygon with 4 control points" do
subject.polygon('(2,2) (21,2) (2,21) (21,21)', ChunkyPNG::Color(:black), ChunkyPNG::Color(:red))
subject.should == reference_canvas('polygon_filled_vertical')
end
it "should draw a vertically crossed filled polygon with 4 control points" do
subject.polygon('(2,2) (2,21) (21,2) (21,21)', ChunkyPNG::Color(:black), ChunkyPNG::Color(:red))
subject.should == reference_canvas('polygon_filled_horizontal')
end
it "should return itself to allow chaining" do
subject.polygon('(2,2) (20,5) (5,20)').should equal(subject)
end
end
describe '#bezier_curve' do
subject { ChunkyPNG::Canvas.new(24, 24) }
it "should draw a bezier curve starting at the first point" do
points = Array.new
points[0] = ChunkyPNG::Point.new(3,20)
points[1] = ChunkyPNG::Point.new(10,10)
points[2] = ChunkyPNG::Point.new(20,20)
subject.bezier_curve( points )
subject[points[0].x, points[0].y].should == ChunkyPNG::Color::BLACK
end
it "should draw a bezier curve ending at the last point" do
points = Array.new
points[0] = ChunkyPNG::Point.new(3,20)
points[1] = ChunkyPNG::Point.new(10,10)
points[2] = ChunkyPNG::Point.new(20,20)
subject.bezier_curve( points )
subject[points[2].x, points[2].y].should == ChunkyPNG::Color::BLACK
end
it "should draw a bezier curve with a color of green" do
points = Array.new
points[0] = ChunkyPNG::Point.new(3,20)
points[1] = ChunkyPNG::Point.new(10,10)
points[2] = ChunkyPNG::Point.new(20,20)
subject.bezier_curve( points, "green" )
subject[points[0].x, points[0].y].should == ChunkyPNG::Color(:green)
end
it "should draw a three point bezier curve" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,23)
pnts[1] = ChunkyPNG::Point.new(12,10)
pnts[2] = ChunkyPNG::Point.new(23,23)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_three_point')
end
it "should draw a three point bezier curve flipped" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,01)
pnts[1] = ChunkyPNG::Point.new(12,15)
pnts[2] = ChunkyPNG::Point.new(23,01)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_three_point_flipped')
end
it "should draw a four point bezier curve" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,23)
pnts[1] = ChunkyPNG::Point.new(01,05)
pnts[2] = ChunkyPNG::Point.new(22,05)
pnts[3] = ChunkyPNG::Point.new(22,23)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_four_point')
end
it "should draw a four point bezier curve flipped" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,01)
pnts[1] = ChunkyPNG::Point.new(01,19)
pnts[2] = ChunkyPNG::Point.new(22,19)
pnts[3] = ChunkyPNG::Point.new(22,01)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_four_point_flipped')
end
it "should draw a four point bezier curve with a shape of an s" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,23)
pnts[1] = ChunkyPNG::Point.new(01,05)
pnts[3] = ChunkyPNG::Point.new(22,05)
pnts[2] = ChunkyPNG::Point.new(22,23)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_four_point_s')
end
it "should draw a five point bezier curve" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(10,23)
pnts[1] = ChunkyPNG::Point.new(01,10)
pnts[2] = ChunkyPNG::Point.new(12,05)
pnts[3] = ChunkyPNG::Point.new(23,10)
pnts[4] = ChunkyPNG::Point.new(14,23)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_five_point')
end
it "should draw a six point bezier curve" do
pnts = Array.new
canvas = ChunkyPNG::Canvas.new(24, 24, ChunkyPNG::Color::WHITE)
pnts[0] = ChunkyPNG::Point.new(01,23)
pnts[1] = ChunkyPNG::Point.new(04,15)
pnts[2] = ChunkyPNG::Point.new(8,20)
pnts[3] = ChunkyPNG::Point.new(02,02)
pnts[4] = ChunkyPNG::Point.new(23,15)
pnts[5] = ChunkyPNG::Point.new(23,01)
canvas.bezier_curve( pnts )
canvas.should == reference_canvas('bezier_six_point')
end
end
end
|
class CreateListings < ActiveRecord::Migration
def change
create_table :listings do |t|
t.integer :organization_id, null: false
t.integer :user_id, null: false
t.string :name, null: false
t.text :description, null: false, default: "", limit: 1023
t.text :url, null: false, default: "", limit: 1023
t.timestamps null: false
end
add_index :listings, :organization_id
add_index :listings, :name
end
end
|
require 'spec_helper'
describe Immutable::Vector do
describe '#count' do
it 'returns the number of elements' do
V[:a, :b, :c].count.should == 3
end
it 'returns the number of elements that equal the argument' do
V[:a, :b, :b, :c].count(:b).should == 2
end
it 'returns the number of element for which the block evaluates to true' do
V[:a, :b, :c].count { |s| s != :b }.should == 2
end
end
end
|
module Api
module V1
class DistributionsController < Api::V1::ApiController
def show
@distribution = Distribution.find(params[:id])
render json: @distribution
end
end
end
end
|
module ApplicationHelper
def default_meta_tags
{
site: Settings.site.name,
reverse: true, # タイトルタグ内の表記順をページタイトル|サイトタイトルの順にする
title: Settings.site.page_title,
description: Settings.site.page_description,
og: default_og
}
end
def format_date_by_dot(date)
date.strftime('%Y.%m.%d')
end
def format_date_by_slash(date)
date.strftime('%Y/%m/%d')
end
private
def default_og
{
title: :title,
type: Settings.site.og.type,
url: request.original_url,
image: image_url(Settings.site.og.image_path),
site_name: Settings.site.name,
description: :description,
locale: 'ja_JP'
}
end
end
|
require_relative '../models/repository.rb'
require_relative '../services/repo_analyzer.rb'
class FetchRepo
@queue = :fetch_repository
def self.perform(repo_id)
repo = Repository.find(repo_id)
analyzer = RepoAnalyzer.new(repo)
analyzer.analyze_last_commits
rescue Exception => e
Resque.enqueue self, repo_id
puts "Performing #{self} caused an exception (#{e}). Retrying..."
raise e
end
def on_failure_retry(e, *args)
Resque.enqueue self, *args
puts "Performing #{self} caused an exception (#{e}). Retrying..."
end
end
|
class RBooksController < ApplicationController
# GET /r_books/new
def new
@r_book = RBook.new
end
# POST /r_books
def create
book = RBook.new(book_params)
book.save!
# book = RBook.new(book_params_simple)
# book.tag_list = params[:r_book][:tag_list]
# book.price_data = params[:r_book][:price_data]
render plain: book.inspect
end
private
def book_params
params
.require(:r_book)
.permit(
:title,
:content,
:published,
tag_list: [],
price_data: [:ebook, :audio, :paper])
end
def book_params_simple
params.require(:r_book).permit(:title, :content, :published)
end
end
|
class CreateAttemptTransitions < ActiveRecord::Migration[5.2]
def change
create_table :attempt_transitions do |t|
t.string :to_state, null: false
t.json :metadata, default: {}
t.integer :sort_key, null: false
t.integer :attempt_id, null: false
t.boolean :most_recent, null: false
# If you decide not to include an updated timestamp column in your transition
# table, you'll need to configure the `updated_timestamp_column` setting in your
# migration class.
t.timestamps null: false
end
# Foreign keys are optional, but highly recommended
add_foreign_key :attempt_transitions, :attempts
add_index(:attempt_transitions,
[:attempt_id, :sort_key],
unique: true,
name: "index_attempt_transitions_parent_sort")
add_index(:attempt_transitions,
[:attempt_id, :most_recent],
unique: true,
where: 'most_recent',
name: "index_attempt_transitions_parent_most_recent")
end
end
|
class MediaListSerializer < ActiveModel::Serializer
attributes :media
def media
object.media
end
end
|
#!/usr/bin/env ruby
require 'hyperdex'
def assert &block
raise RuntimeError unless yield
end
def collapse_iterator(xs)
s = Set.new []
while xs.has_next() do
x = xs.next()
x.freeze
s.add(x)
end
s
end
def to_objectset(xs)
s = Set.new []
xs.each do |x|
x.freeze
s.add(x)
end
s
end
c = HyperDex::Client::Client.new(ARGV[0], ARGV[1].to_i)
assert { c.put("kv", "k", {}) == true }
assert { c.get("kv", "k") == {:v => (Set.new [])} }
assert { c.put("kv", "k", {"v" => (Set.new [0.25, 1.0, 3.14])}) == true }
assert { c.get("kv", "k") == {:v => (Set.new [0.25, 1.0, 3.14])} }
assert { c.put("kv", "k", {"v" => (Set.new [])}) == true }
assert { c.get("kv", "k") == {:v => (Set.new [])} }
|
class Order < ApplicationRecord
# rake db:migrate VERSION=0
belongs_to :user
has_many :order_items # , dependent: :destroy
validates :user_id, presence: true
validates :status, presence: true
validates :total_price, presence: true
enum status: {
pending: 0,
paid: 1,
cancelled: 2
}
scope :by_customer, -> (user_id) {
where(user_id: user_id)
}
def self.create_from_cart(cart, user)
order = Order.new(user: user, status: 'pending', total_price: cart.total_price)
cart.items.each do |item|
order.order_items.build(item: item, quantity: item.quantity)
end
order
end
end
|
class RemovePlaceIdFromAreas < ActiveRecord::Migration
def change
remove_column :areas, :planet_id, :string
remove_column :areas, :continent_id, :string
remove_column :areas, :kingdom_id, :string
remove_column :areas, :city_id, :string
remove_column :areas, :place_id, :string
remove_column :areas, :area_type, :string
end
end
|
class Message < ApplicationRecord
validates_presence_of :sender, :message
end
|
class Game
def initialize(args = {})
@pegs = args[:pegs] || Pegs.new
@user = args[:user] || User.new
end
def setup(number_of_disks)
pegs.add_disks(number_of_disks)
end
def play(number_of_disks)
setup(number_of_disks)
until game_over
turn
end
end
def turn
user.get_move
end
def game_over
true if victory? || quit?
end
def victory?
pegs[1..2].any? do |peg|
peg.disks == number_of_disks
end
end
def quit?
user.move == "q"
end
end
|
class PagesController < ApplicationController
def home
@users = User.none
@tweets = Tweet.where(user_id: current_user.users_following)
.or(current_user.tweets)
.includes(:user)
@following = current_user.users_following
@followers = current_user.get_followers
end
end
|
# If running this program on its own, the items commented out in
# def initialize need to be un-commented. To get savings_account.rb,
# checking_account.rb, and money_market_account.rb to work, I had
# to disable the hash creation in this program. I do not understand
# why, so any theories you have would be appreciated!
require 'csv'
module Bank
class Account
attr_accessor
attr_reader :balance, :id, :creation_time
attr_writer
def initialize() #(account_hash)
# @balance = account_hash[:balance]
# @id = account_hash[:id]
# @creation_time = account_hash[:creation_time]
# create_account(account_hash[:balance])
end
def negative_initial
begin
raise ArgumentError
rescue
puts "The initial balance cannot be negative. Please enter a positive number."
@balance = gets.chomp.to_f
@balance = @balance/100
end
end
# Creates a new account should be created with an ID and an initial balance
def create_account(cents_amount)
@balance = (cents_amount / 100)
while @balance < 0.0
negative_initial
end
end
# The user inputs how much money to withdraw. If the withdraw amount is greater
# than the balance, the user is given a warning and not allowed to withdraw
# that amount. Otherwise, the balance is adjusted and returned.
def withdraw(dollar_amount)
if (@balance - dollar_amount) < 0
puts "I'm sorry, you cannot withdraw that amount, as you do not have enough money in your account."
else
@balance -= dollar_amount
end
return @balance
end
# The user inputs how much is to be deposited and the balance reflects that
# deposit
def deposit(dollar_amount)
@balance += dollar_amount
return @balance
end
# The current balance can be accessed at any time.
def balance
return @balance
end
# Returns a collection of Account instances, representing all of the
# Accounts described in the CSV.
def self.all
accounts = []
CSV.read("./support/accounts.csv").each do |line|
account_hash = {}
account_hash[:id] = line[0].to_i
account_hash[:balance] = line[1].to_f
account_hash[:creation_time] = line[2]
accounts << Bank::Account.new(account_hash)
end
return accounts
end
# Returns an instance of Account where the value of the id field
# in the CSV matches the passed parameter; will have to use self.all
def self.find(input)
account = self.all
account.each do |var|
if var.id == input
puts var.print_props
return var
end
end
end
def print_props
return "Account ID #{ @id } has a balance of $" + sprintf("%0.02f", @balance) + " and was created at #{ @creation_time }"
end
end
end
# bank_branch = Bank::Account.all
# puts bank_branch
# b = Bank::Account.find(1212)
# puts b
# bank_branch.each do |a|
# puts a.balance
# end
|
class PythonNumpyFormula < Formula
homepage "http://www.numpy.org/"
url "http://downloads.sourceforge.net/project/numpy/NumPy/1.7.1/numpy-1.7.1.tar.gz"
depends_on do
packages = [ "cblas/20110120/*acml*" ]
case build_name
when /python3.3/
packages << "python/3.3.0"
when /python2.7/
packages << "python/2.7.3"
when /python2.6/
end
packages
end
module_commands do
m = [ "unload PrgEnv-gnu PrgEnv-pgi PrgEnv-cray PrgEnv-intel" ]
case build_name
when /gnu/
m << "load PrgEnv-gnu"
when /pgi/
m << "load PrgEnv-pgi"
when /intel/
m << "load PrgEnv-intel"
when /cray/
m << "load PrgEnv-cray"
end
m << "load acml"
m << "unload python"
case build_name
when /python3.3/
m << "load python/3.3.0"
when /python2.7/
m << "load python/2.7.3"
end
m
end
def install
module_list
acml_prefix = `#{@modulecmd} display acml 2>&1|grep ACML_DIR`.split[2]
acml_prefix += "/gfortran64"
FileUtils.mkdir_p "#{prefix}/lib"
FileUtils.cp "#{cblas.prefix}/lib/libcblas.a", "#{prefix}/lib", verbose: true
FileUtils.cp "#{acml_prefix}/lib/libacml.a", "#{prefix}/lib", verbose: true
FileUtils.cp "#{acml_prefix}/lib/libacml.so", "#{prefix}/lib", verbose: true
ENV['CC'] = 'gcc'
ENV['CXX'] = 'g++'
ENV['OPT'] = '-O3 -funroll-all-loops'
patch <<-EOF.strip_heredoc
diff --git a/site.cfg b/site.cfg
new file mode 100644
index 0000000..c7a4c65
--- /dev/null
+++ b/site.cfg
@@ -0,0 +1,15 @@
+[blas]
+blas_libs = cblas, acml
+library_dirs = #{prefix}/lib
+include_dirs = #{cblas.prefix}/include
+
+[lapack]
+language = f77
+lapack_libs = acml
+library_dirs = #{acml_prefix}/lib
+include_dirs = #{acml_prefix}/include
+
+[fftw]
+libraries = fftw3
+library_dirs = /opt/fftw/3.3.0.1/x86_64/lib
+include_dirs = /opt/fftw/3.3.0.1/x86_64/include
EOF
system "cat site.cfg"
python_binary = "python"
libdirs = []
case build_name
when /python3.3/
python_binary = "python3.3"
libdirs << "#{prefix}/lib/python3.3/site-packages"
when /python2.7/
libdirs << "#{prefix}/lib/python2.7/site-packages"
when /python2.6/
libdirs << "#{prefix}/lib64/python2.6/site-packages"
end
FileUtils.mkdir_p libdirs.first
python_start_command = "PYTHONPATH=$PYTHONPATH:#{libdirs.join(":")} #{python_binary} "
system "#{python_start_command} setup.py build"
system "#{python_start_command} setup.py install --prefix=#{prefix} --compile"
end
modulefile <<-MODULEFILE.strip_heredoc
#%Module
proc ModulesHelp { } {
puts stderr "<%= @package.name %> <%= @package.version %>"
puts stderr ""
}
# One line description
module-whatis "<%= @package.name %> <%= @package.version %>"
if [ is-loaded python/3.3.0 ] {
set BUILD sles11.1_python3.3.0_gnu4.7.2_acml5.2.0
set LIBDIR python3.3
} elseif { [ is-loaded python/2.7.3 ] || [ is-loaded python/2.7.2 ] } {
set BUILD sles11.1_python2.7.3_gnu4.7.2_acml5.2.0
set LIBDIR python2.7
} else {
set BUILD sles11.1_python2.6.8_gnu4.7.2_acml5.2.0
set LIBDIR python2.6
}
set PREFIX <%= @package.version_directory %>/$BUILD
prepend-path PATH $PREFIX/bin
prepend-path LD_LIBRARY_PATH $PREFIX/lib
prepend-path LD_LIBRARY_PATH $PREFIX/lib64
prepend-path LD_LIBRARY_PATH /opt/gcc/4.7.2/snos/lib64
prepend-path MANPATH $PREFIX/share/man
prepend-path PYTHONPATH $PREFIX/lib/$LIBDIR/site-packages
prepend-path PYTHONPATH $PREFIX/lib64/$LIBDIR/site-packages
MODULEFILE
end
|
module ActiveRecord
class Base
class << self
def define_state_machine_scopes
state_machine.states.map(&:name).each do |state|
scope state, where(state: state)
scope "non_#{state}", where("#{table_name}.state != '#{state}'")
end
end
def define_defaults_events *events
events.each do |event|
define_safe_state_event_method(event)
define_state_event_method(event)
end
end
def define_safe_state_event_method(event)
define_method event do
return false unless send("can_#{event}?")
send "#{event}!"
end
end
def define_state_event_method(event)
define_method "#{event}!" do
send "_#{event}!"
end
end
def human_state_names
Hash[state_machine.states.map do |state|
[state.human_name, state.name]
end]
end
def state_names
state_machine.states.map &:name
end
end
def models_name
self.class.model_name.pluralize.underscore.to_sym
end
def errors_sentence
errors.full_messages.to_sentence
end
end
class RecordInProcess < StandardError
end
end
module Generic
def to_generic_model
klass = Class.new(ActiveRecord::Base)
klass.table_name = table_name
klass
end
end
ActiveRecord::Base.extend(Generic)
|
#201 dollars given
#want the amount given in pennies
#create a hash for numbers to words
#divide the main number by 100, and the remainder will be shown as cents
class Machine
def pennies_to_dollars(amt)
if amt.is_a?(Integer)
num_word = {1 => "one", 2 => "two"}
dollar, cent = amt.divmod(100)
"#{num_word[dollar]} dollars and #{num_word[cent]} cents"
else
"Please input an integer"
end
end
end
first_machine = Machine.new
p first_machine.pennies_to_dollars(2) |
require "sxs"
include SXS
class ProfilerControl
DEFAULT_BUFFER_SIZE = 1024*512
PROFILE_IN_RAM = :inRam
PROFILE_ON_TRACE = :onTrace
# Properties of the allocated buffer
@@bufferAddress = 0
@@bufferSize = DEFAULT_BUFFER_SIZE
# setter
def self.bufferSize=(size)
@@bufferSize = size
end
def self.bufferAddress=(size)
@@bufferAddress = size
end
# getter
def self.bufferSize()
return @@bufferSize
end
def self.bufferAddress()
return @@bufferAddress
end
end
def profilerControlReset()
ProfilerControl::bufferAddress = 0
ProfilerControl::bufferSize = 0
end
# Return true if code is not crashed, in which case
# SX remote feature (sxs_execute, sxs_RB, ...) can be used
def codeIsNotCrashed(myCon)
if (($xcpu_error_info.cpu_sp_context.read(myCon) == 0) &&
(($XCPU.cp0_Cause.read(myCon) & 0x7FFFFFFF) == 0) &&
($INT_REG_DBG_HOST.CTRL_SET.Force_BP_XCPU.read(myCon) == 0) &&
($SYS_CTRL.XCpu_Dbg_BKP.Stalled.read(myCon) == 0)
)
return true
else
return false
end
end
# Allocate the Remote Buffer use to profile in RAM.
def profilerMallocRamBuffer(size=ProfilerControl::DEFAULT_BUFFER_SIZE, connection=$CURRENTCONNECTION)
CRVERBOSE("Malloc Profiling Ram Buffer", 2)
myCon = CHEmptyConnection.new()
sxsConnection = CHEmptyConnection.new()
if (ProfilerControl::bufferAddress != 0)
# Buffer already allocated.
raise MultiProfilerExceptionBufferAlreadyAllocated, "Ram buffer already allocated at:%0x8" % [ProfilerControl::bufferAddress]
end
# Duplicate connection.
myCon = connection.copyConnection()
myCon.open(false)
sxsConnection = CHBPConnection.new(myCon, [SXS_RPC_RMC, SXS_RPC_RSP_RMC])
sxsConnection.open(false)
if (codeIsNotCrashed(myCon))
sxsExecute(sxsConnection,
$map_table.>(myCon).hal_access.>(myCon).profileControl.mallocRamBuffer.read(myCon),
SXS_RPC_RETURN_VALUE,
[SXS_RPC_VALUE_PARAM,SXS_RPC_NO_PARAM,SXS_RPC_NO_PARAM,SXS_RPC_NO_PARAM],
[size].from32to8bits)
else
raise MultiProfilerExceptionSystemCrashed, "Embedded System Crashed, cannot profile it."
end
# Hypothesis: Malloc succeeded
ProfilerControl::bufferAddress = sxsWaitExecuteResult(sxsConnection, 8.0)
ProfilerControl::bufferSize = size if (ProfilerControl::bufferAddress() != 0)
ensure
sxsConnection.close()
myCon.close()
end
# Free the Remote Buffer use to profile in RAM.
def profilerFreeRamBuffer(connection=$CURRENTCONNECTION)
CRVERBOSE("Malloc Profiling Ram Buffer", 2)
myCon = CHEmptyConnection.new()
sxsConnection = CHEmptyConnection.new()
if (ProfilerControl::bufferAddress == 0)
# Buffer already freed.
raise MultiProfilerExceptionBufferAlreadyFreed, "Ram buffer already freed"
end
# Duplicate connection.
myCon = connection.copyConnection()
myCon.open(false)
sxsConnection = CHBPConnection.new(myCon, [SXS_RPC_RMC, SXS_RPC_RSP_RMC])
sxsConnection.open(false)
if (codeIsNotCrashed(myCon))
sxsExecute(sxsConnection,
$map_table.>(myCon).hal_access.>(myCon).profileControl.freeRamBuffer.read(myCon),
SXS_RPC_RETURN_VOID,
[SXS_RPC_NO_PARAM,SXS_RPC_NO_PARAM,SXS_RPC_NO_PARAM,SXS_RPC_NO_PARAM],
[])
else
raise MultiProfilerExceptionSystemCrashed, "Embedded System Crashed, cannot free the buffer. (Not that it matters anymore ...)"
end
ensure
profilerControlReset()
sxsConnection.close()
myCon.close()
end
# Enable/Disable the Profiling on Ram
def profilerEnableProfiling(enable, mode=ProfilerControl::PROFILE_IN_RAM, connection=$CURRENTCONNECTION)
myCon = CHEmptyConnection.new()
# Duplicate connection.
myCon = connection.copyConnection()
myCon.open(false)
# Build accessor
profilerCtrlCfg = $map_table.>(myCon).hal_access.>(myCon).profileControl.config
val = profilerCtrlCfg.read(myCon)
val = profilerCtrlCfg.prepl(val)
case mode
when ProfilerControl::PROFILE_IN_RAM
val = profilerCtrlCfg.Global_Enable_Ram.wl(val, (enable)?(1):(0))
when ProfilerControl::PROFILE_ON_TRACE
val = profilerCtrlCfg.Global_Enable_Trace.wl(val, (enable)?(1):(0))
end
# Clear status if start
if (enable)
$map_table.>(myCon).hal_access.>(myCon).profileControl.status.write(myCon, 0)
end
# Write register
profilerCtrlCfg.write(myCon, val)
ensure
myCon.close()
end
# Dumper function.
def profilerDumpRamBuffer(forceHwRead=false, connection=$CURRENTCONNECTION)
CRVERBOSE("Dump Profiling Ram Buffer", 2)
myCon = CHEmptyConnection.new()
sxsConnection = CHEmptyConnection.new()
# Duplicate connection.
myCon = connection.copyConnection()
myCon.open(false)
sxsConnection = CHBPConnection.new(connection, [SXS_READ_RMC, SXS_DUMP_RMC])
sxsConnection.open(false)
# If we had wrapped, we need the whole file.
if ($map_table.>(myCon).hal_access.>(myCon).profileControl.status.wrapped.read(myCon) == 1)
size = ProfilerControl::bufferSize
else
writePointer = $map_table.>(myCon).hal_access.>(myCon).profileControl.writePointer.read(myCon)
size = writePointer - ProfilerControl::bufferAddress
end
puts "html> Start dumping data ... (May take a while)"
# FIXME sxsRB is broken, as any dump can pollute it.
# Use direct version as long as the fix is not implemented.
# return sxsRB(sxsConnection, ProfilerControl::bufferAddress, size).from8to32bits
puts "Size #{size}, addr:%08x" % [ProfilerControl::bufferAddress]
# Check is code is not crashed, and the CPU is not stalled.
if (codeIsNotCrashed(myCon) && !forceHwRead)
capturedData = (sxsRB(sxsConnection, ProfilerControl::bufferAddress, size)).from8to32bits
puts "html> Dump done."
return capturedData
else
puts "html> SX Dump failed. Fallback on hw."
capturedData = (myCon.readBlock(ProfilerControl::bufferAddress, size){|p| mpSetProgress(p*100)} ).from8to32bits
puts "html> Dump done."
return capturedData
end
ensure
sxsConnection.close()
myCon.close()
end
# Display the control structure in the register watcher
def profilerDisplayControl()
controlPanel = "$map_table.>.hal_access.>.profileControl"
# Check if already displayed
inwin=cwGetRootWatches
if (!(inwin.include?(controlPanel)))
# Add to watch
cwAddWatch(eval(controlPanel.gsub(/\.>/,".derefAt(4)")))
end
# Refresh
cwRefreshWatches
end
# Gets the Profiler Control Status
def profilerGetStatus(connection=$CURRENTCONNECTION)
hash = {}
myCon = CHEmptyConnection.new()
# Duplicate connection.
myCon = connection.copyConnection()
myCon.open(false)
# Build status.
if ($map_table.>(myCon).hal_access.>(myCon).profileControl.status.wrapped.read(myCon) == 1)
hash[:wrapped] = true;
writePointer = $map_table.>(myCon).hal_access.>(myCon).profileControl.writePointer.read(myCon)
# Index refers to a 32 bits array
hash[:wrapIndex] = (writePointer - ProfilerControl::bufferAddress)/4
else
# No wrap
hash[:wrapIndex] = 0
end
if ($map_table.>(myCon).hal_access.>(myCon).profileControl.status.overflowed.read(myCon) == 1)
hash[:overflowed] = true
end
return hash
ensure
myCon.close()
end
|
class SetTopicText < ActiveRecord::Migration
def change
change_column :channels, :Topic, :text
end
end
|
# Change the 'YOUR_AZURE_VM_IP' to the publicIpAddress from the output of
# `az vm create` command executed above
require 'json'
role :app, JSON.parse(`az vmss list-instance-connection-info -g level1 -n level1-vmss`)
# Change the YOUR_GITHUB_NAME to your github user name
set :repo_url, 'git@github.com:devigned/level1.git'
set :repo_tree, 'api-ruby'
set :application, 'level1'
set :user, 'deploy'
set :puma_threads, [4, 16]
set :puma_workers, 0
# Don't change these unless you know what you're doing
set :pty, true
set :use_sudo, false
set :stage, :production
set :deploy_via, :remote_cache
set :deploy_to, "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.access.log"
set :puma_error_log, "#{release_path}/log/puma.error.log"
set :ssh_options, { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true # Change to false when not using ActiveRecord
namespace :puma do
desc 'Create Directories for Puma Pids and Socket'
task :make_dirs do
on roles(:app) do
execute "mkdir #{shared_path}/tmp/sockets -p"
execute "mkdir #{shared_path}/tmp/pids -p"
execute "mkdir #{release_path}/log -p"
end
end
before :start, :make_dirs
end
namespace :deploy do
desc "Make sure local git is in sync with remote."
task :check_revision do
on roles(:app) do
unless `git rev-parse HEAD` == `git rev-parse origin/master`
puts "WARNING: HEAD is not the same as origin/master"
puts "Run `git push` to sync changes."
exit
end
end
end
desc 'Build and Ember Assets'
task :build_ember do
on roles(:app) do
api_host = `az network public-ip show -g level1 -n level1-vmss --query 'dnsSettings.fqdn' -o tsv`.strip
cmd = <<-CMD
cd '#{release_path}/todo-ember' && \
npm install --no-progress > log.txt 2>&1 && \
sed -i 's/{{ API_HOST }}/http:\\/\\/#{api_host}/g' config/environment.js && \
CDN_HOST=http://$(az cdn endpoint list -g level1 --profile-name level1 --query '[0] | hostName' -o tsv)/ ./node_modules/ember-cli/bin/ember build --silent --environment production && \
rm -rf ../public/* && \
cp -R dist/* ../public
CMD
execute cmd
end
end
desc 'Initial Deploy'
task :initial do
on roles(:app) do
invoke 'deploy'
execute "sudo rm -f /etc/nginx/sites-enabled/default"
execute "sudo ln -nfs #{current_path}/config/nginx.conf /etc/nginx/sites-enabled/level1"
execute "sudo service nginx restart"
end
end
before :starting, :check_revision
after :finishing, :build_ember
after :finishing, :cleanup
end
# ps aux | grep puma # Get puma pid
# kill -s SIGUSR2 pid # Restart puma
# kill -s SIGTERM pid # Stop puma |
class Dice
attr_reader :roll_value, :roll_array
attr_accessor :sides, :number
def initialize(sides)
@sides = sides
@roll_array = []
@roll_value = roll_value
end
def roll(number=1)
number.times do
@roll_value = rand(@sides.to_i) + 1
puts "\nYou rolled a #{@roll_value}!"
@roll_array << @roll_value
end
end
end
|
class Genre < ActiveRecord::Base
has_many :novels
has_many :films
end
|
class CreateAppointmentReminders < ActiveRecord::Migration
def change
create_table :appointment_reminders do |t|
t.string :d_reminder_type
t.string :reminder_time
t.boolean :skip_weekends, default:false
t.string :reminder_period
t.boolean :apply_reminder_type_to_all, default:false
t.string :ac_email_subject
t.text :ac_email_content
t.boolean :ac_app_can_show, default:false
t.boolean :hide_address_show, default:false
t.string :reminder_email_subject
t.boolean :reminder_email_enabled, default:false
t.text :reminder_email_content
t.boolean :reminder_app_can_show, default:false
t.boolean :sms_enabled, default:false
t.text :sms_text
t.boolean :sms_app_can_show, default:false
t.references :company, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
class Project < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :name, length: { minimum: 5 }
validates :description, length: { minimum: 5 }
validates :estimated_effort, presence: true
validates :status, presence: true
validates_inclusion_of :status, in: %w(created started stopped completed)
scope :published, -> {
where("published_at IS NOT NULL")
}
def self.include_user
includes(:user).
as_json(include: [:user])
end
def published=(val)
value = ActiveRecord::Type::Boolean.new.cast(val)
write_attribute(:published_at, value ? DateTime.now : nil)
end
def published
self.published?
end
def published?
self.published_at.present?
end
end
|
require 'SimpleCov'
SimpleCov.start
require_relative '../lib/merchant'
RSpec.describe Merchant do
before :each do
@m = Merchant.new({
:id => 5,
:name => 'Turing School'
})
end
it 'exists' do
expect(@m).to be_an_instance_of(Merchant)
end
it 'initializes with attributes' do
expect(@m.id).to eq(5)
expect(@m.name).to eq('Turing School')
end
it 'can update attributes' do
@m.update({:name => 'Turing School of Witchcraft and Wizardry'})
expect(@m.name).to eq('Turing School of Witchcraft and Wizardry')
end
it 'can create time' do
allow(@m).to receive(:created_at).and_return(Time.parse('2021-06-11 02:34:56 UTC'))
expect(@m.created_at).to eq(Time.parse('2021-06-11 02:34:56 UTC'))
end
end
|
class User < ActiveRecord::Base
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
has_many :yt_videos
has_many :blinks
def set_default_role
self.role ||= :user
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :omniauthable, :omniauth_providers => [:facebook]
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
def self.from_omniauth(auth)
this_user = where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email || 'test@example.com'
user.name = auth.info.name
end
this_user.fb_token = auth.credentials.token
this_user.save
return this_user
end
def fb_picture
facebook = Koala::Facebook::API.new(fb_token)
facebook.get_object("me?fields=picture.type(large) ")['picture']['data']['url']
end
def get_friends
facebook = Koala::Facebook::API.new(fb_token)
facebook.get_connections("me", "friends")
end
def get_photos
facebook = Koala::Facebook::API.new(fb_token)
facebook.get_connections("me", "photos?limit=3&offset=#{rand(0..300)}").map{|i| i['images'][1]['source']}.shuffle
end
end
|
require 'rails_helper'
require 'spec_helper'
describe Type do
describe "creation" do
it "should be valid" do
physical_type = FactoryGirl.build(:physical)
expect(physical_type).to be_valid
end
end
end
|
module Stratego
class Flag < Piece
def move_distance
0
end
def initialize(color)
super "flag", color
end
end
end
|
class Group < ActiveRecord::Base
belongs_to :administrator, class_name: 'User'
has_many :group_members, class_name: 'GroupMember'
has_many :users, through: :group_members
end
|
module Fog
module Compute
class Google
class TargetPool < Fog::Model
identity :name
attribute :backup_pool, :aliases => "backupPool"
attribute :creation_timestamp, :aliases => "creationTimestamp"
attribute :description
attribute :failover_ratio, :aliases => "failoverRatio"
attribute :health_checks, :aliases => "healthChecks"
attribute :id
attribute :instances
attribute :kind
attribute :region
attribute :self_link, :aliases => "selfLink"
attribute :session_affinity, :aliases => "sessionAffinity"
def save
requires :name, :region
data = service.insert_target_pool(
name, region, attributes.reject { |_k, v| v.nil? }
)
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? }
reload
end
def destroy(async = true)
requires :identity, :region
data = service.delete_target_pool(identity, region)
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? } unless async
operation
end
def add_instance(instance, async = true)
requires :identity
instance = instance.self_link unless instance.class == String
data = service.add_target_pool_instances(identity, region, [instance])
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? } unless async
reload
end
def remove_instance(instance, async = true)
requires :identity
instance = instance.self_link unless instance.class == String
data = service.remove_target_pool_instances(identity, region, [instance])
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? } unless async
reload
end
def add_health_check(health_check, async = true)
requires :identity, :region
health_check = health_check.self_link unless health_check.class == String
data = service.add_target_pool_health_checks(identity, region, [health_check])
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? } unless async
reload
end
def remove_health_check(health_check, async = true)
requires :identity, :region
health_check = health_check.self_link unless health_check.class == String
data = service.remove_target_pool_health_checks(identity, region, [health_check])
operation = Fog::Compute::Google::Operations
.new(:service => service)
.get(data.name, nil, data.region)
operation.wait_for { ready? } unless async
reload
end
##
# Get most recent health checks for each IP for instances.
#
# @param [String] instance_name a specific instance to look up. Default
# behavior returns health checks for all instances associated with
# this check.
# @returns [Hash<String, Array<Hash>>] a map of instance URL to health checks
#
# Example Hash:
# {
# "https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-f/instances/myinstance"=>
# [{:health_state=>"UNHEALTHY",
# :instance=>"https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-f/instances/myinstance"
# }]
# }
#
def get_health(instance_name = nil)
requires :identity, :region
if instance_name
instance = service.servers.get(instance_name)
data = service.get_target_pool_health(identity, region, instance.self_link)
.to_h[:health_status] || []
results = [[instance.self_link, data]]
else
results = instances.map do |self_link|
# TODO: Improve the returned object, current is hard to navigate
# [{instance => @instance, health_state => "HEALTHY"}, ...]
data = service.get_target_pool_health(identity, region, self_link)
.to_h[:health_status] || []
[self_link, data]
end
end
Hash[results]
end
def set_backup(backup = nil)
requires :identity, :region
backup ||= backup_pool
service.set_target_pool_backup(
identity, region, backup,
:failover_ratio => failover_ratio
)
reload
end
def ready?
service.get_target_pool(name, region)
true
rescue ::Google::Apis::ClientError => e
raise e unless e.status_code == 404
false
end
def region_name
region.nil? ? nil : region.split("/")[-1]
end
def reload
requires :name, :region
return unless data = begin
collection.get(name, region)
rescue Excon::Errors::SocketError
nil
end
new_attributes = data.attributes
merge_attributes(new_attributes)
self
end
RUNNING_STATE = "READY".freeze
end
end
end
end
|
require 'formula'
class Ledit < Formula
homepage 'http://pauillac.inria.fr/~ddr/ledit/'
url 'http://pauillac.inria.fr/~ddr/ledit/distrib/src/ledit-2.03.tgz'
sha1 '8fef728f38e8d6fc30dd5f71dd5b6b647212a43a'
depends_on 'objective-caml'
depends_on 'camlp5'
def install
# like camlp5, this build fails if the jobs are parallelized
ENV.deparallelize
args = %W[BINDIR=#{bin} LIBDIR=#{lib} MANDIR=#{man}]
system "make", *args
system "make", "install", *args
end
end
|
# This isn't reused anywhere
# It's abstracted into a module to promote readability
module Getters
def _prepare_getters
@queryable_structures = FormHash.new
@fields.each do |field|
@queryable_structures[field.name] = {
:field => field.to_html,
:label_tag => field.label_tag,
:help_text => field.help_text,
:errors => field.errors,
:instance => field
}
end
end
def get_group field
return @queryable_structures[field]
end
def get(type, field)
return get_group(field)[type]
end
def get_field field
return get_group(field)[:field]
end
def get_instance instance
return get_group(instance)[:instance]
end
def get_label_tag field
return get_group(field)[:label_tag]
end
def get_help_text field
return get_group(field)[:help_text]
end
def get_errors field
return get_group(field)[:errors]
end
end
|
class NewBookToListService
attr_reader :errors
def initialize(params, list)
@errors = []
@list = list
@user = list.user
@book_id = params[:book_id]
@user_book_params = params
end
def add_new_user_book_to_list
create_or_update_user_book!(@user_book_params)
end
private
def create_or_update_user_book!(params)
ActiveRecord::Base.transaction do
if user_has_book_saved?
@user.user_books.detect { |ub| ub.book_id == @book_id.to_i }
.update!(params.except(:book_id, :user_id))
else
@user.user_books.create!(params)
end
raise ActiveRecord::RecordInvalid if book_already_in_the_list?
add_book_to_list(@list)
end
rescue ActiveRecord::RecordInvalid => exception
@errors << exception.message
end
def user_has_book_saved?
@user.user_books.where(book_id: @book_id.to_i).exists?
end
def book_already_in_the_list?
@list.book_lists.where(book_id: @book_id.to_i).exists?
end
def add_book_to_list(list)
list.book_lists.create!(list_id: list.id, book_id: @book_id.to_i)
list.update!(updated_at: Time.zone.now)
end
end
|
class SessionsController < ApplicationController
def new
end
def create
if authenticate(params[:password])
session[:admin_mode] = true
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
session[:admin_mode] = nil
redirect_to root_url, :notice => "Logged out!"
end
def authenticate(password)
if ENV["BH_SECRET"] == BCrypt::Engine.hash_secret(password, ENV["BH_SECRET_SALT"])
true
else
nil
end
end
end
|
class ShortenUrl
def self.sign_up(user_name, email)
@current_user = User.find_by_email(email)
@current_user = User.create(:user_name => user_name, :email => email) if @current_user.nil?
@current_user
end
def self.login(email)
@current_user = User.find_by(:email => email)
end
def self.shorten(long_url)
short_url = SecureRandom.urlsafe_base64(6)
@my_long_url = LongUrl.find_by_url(long_url)
@my_long_url = LongUrl.create(:url => long_url) if @my_long_url.nil?
@my_short_url = ShortUrl.create(:long_url_id => @my_long_url.id,
:url => short_url, :user_id => @current_user.id)
short_url
end
def self.expand(short_url)
short_url_record = ShortUrl.find_by_url(short_url)
long_url_record = LongUrl.find_by_id(short_url_record.long_url_id)
display_comments(short_url_record.id)
Launchy.open(long_url_record.url)
Visit.create(:short_url_id => short_url_record.id, :user_id => @current_user.id)
end
def self.num_visits(short_url)
short_url_record = ShortUrl.find_by_url(short_url)
@visit_count = Visit.count(:id,:conditions => "short_url_id = #{short_url_record.id}",
:group => :short_url_id)
end
def self.num_distinct_visits(short_url)
short_url_record = ShortUrl.find_by_url(short_url)
@visit_count = Visit.count(:user_id, :distinct => true,
:conditions => "short_url_id = #{short_url_record.id}",
:group => :short_url_id)
end
def self.add_comment(short_url, comment)
short_url_record = ShortUrl.find_by_url(short_url)
Comment.create(:body => comment, :user_id => @current_user.id,
:short_url_id => short_url_record.id)
end
def self.display_comments(short_url_id)
comments = Comment.where(:short_url_id => short_url_id)
comments.each {|comment| puts comment.body}
end
def self.post_tag(tag, short_url)
short_url_record = ShortUrl.find_by_url(short_url)
TagTopic.create(:tag => tag, :short_url_id => short_url_record.id)
end
def self.top_url(tag)
query =
"SELECT short_urls.url FROM short_urls
JOIN
(SELECT COUNT(id) AS visit_count, short_url_id
FROM visits
GROUP BY short_url_id
ORDER BY visit_count DESC) AS count
ON short_urls.id = count.short_url_id
JOIN tag_topics ON tag_topics.short_url_id = short_urls.id
WHERE tag_topics.tag = ?
LIMIT 1"
ShortUrl.find_by_sql([query,tag])
end
def self.recent_visits(short_url)
current_time = Time.now
ten_mins_ago = current_time - 600
puts ten_mins_ago
short_url_record = ShortUrl.find_by_url(short_url)
Visit.where("short_url_id = ? AND created_at >= ?", short_url_record.id, ten_mins_ago).length
end
end
|
require 'spec_helper'
describe "commits/show" do
before(:each) do
@commit = assign(:commit, stub_model(Commit,
:committer_email => "Committer Email",
:committer_name => "Committer Name",
:html_url => "Html Url",
:repository_id => "Repository",
:sha => "Sha",
:author_name => "Author Name",
:author_email => "Author Email"
))
end
it "renders attributes in <p>" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
rendered.should match(/Committer Email/)
rendered.should match(/Committer Name/)
rendered.should match(/Html Url/)
rendered.should match(/Repository/)
rendered.should match(/Sha/)
rendered.should match(/Author Name/)
rendered.should match(/Author Email/)
end
end
|
RSpec.describe "receive messages" do
it "configures return values for the provided messages" do
dbl = double("Some Collaborator")
allow(dbl).to receive_messages(:foo => 2, :bar => 3)
expect(dbl.foo).to eq(2)
expect(dbl.bar).to eq(3)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'open-uri'
ActiveRecord::Base.transaction do
User.destroy_all
Comment.destroy_all
Post.destroy_all
Workplace.destroy_all
Education.destroy_all
Friendship.destroy_all
william = User.create(first_name: "William", last_name: "Blake", dob: "03-11-2000", password: "Az123456@", gender: "male", pronoun: "he", email: "a123@flamingo.com", bio: "If the doors of perception were cleansed, everything would appear to man as it is, infinite.")
file = open('https://flamingo-seed.s3.amazonaws.com/photo1.jpg')
william.profile_photo.attach(io: file, filename: 'photo1.jpg' )
anna = User.create(first_name: "Anna", last_name: "Malcom", dob: "12-12-1912", password: "Bz123456@", gender: "female", pronoun: "she", email: "b123@flamingo.com", bio: "Friendship with oneself is all important, because without it one cannot be friends with anyone else in the world.")
file = open("https://flamingo-seed.s3.amazonaws.com/photo2.jpg")
anna.profile_photo.attach(io: file, filename: 'photo2.jpg' )
george = User.create(first_name: "George", last_name: "Villafane", dob: "08-15-1901", password: "Cz123456@", gender: "male", pronoun: "he", email: "c123@flamingo.com", bio: "The unfortunate thing about this world is that good habits are so much easier to give up than bad ones.")
file = open("https://flamingo-seed.s3.amazonaws.com/photo3.jpg")
george.profile_photo.attach(io: file, filename: 'photo3.jpg' )
john = User.create(first_name: "John", last_name: "Doe", dob: "02-23-1967", password: "Dz123456@", gender: "male", pronoun: "he", email: "d123@flamingo.com", bio: "If you would lift me up you must be on higher ground.")
file = open("https://flamingo-seed.s3.amazonaws.com/photo4.jpg")
john.profile_photo.attach(io: file, filename: 'photo4.jpg' )
michelle = User.create(first_name: "Michelle", last_name: "Ahn", dob: "11-11-1911", password: "Ez123456@", gender: "female", pronoun: "she", email: "e123@flamingo.com", bio: "A seed grows into a beautiful flower. Thick in beauty and yet has little power.")
file = open("https://flamingo-seed.s3.amazonaws.com/photo5.jpg")
michelle.profile_photo.attach(io: file, filename: 'photo5.jpg' )
post1 = anna.wall_posts.create(body: "Life is not a spectacle or a feast; it is a predicament", author_id: anna.id)
comment1 = post1.comments.create(body: "Wine makes a man better pleased with himself; I do not say that it makes him more pleasing to others.", author_id: john.id )
comment1.child_comments.create(body: "I do not wish to kill nor to be killed, but I can foresee circumstances in which these things would be by me unavoidable.", author_id: william.id)
post2 = william.wall_posts.create(body: "A mathematician is a blind man in a dark room looking for a black cat which isn't there.", author_id: william.id)
post3 = william.wall_posts.create(body: "Enjoy every minute. There's plenty of time to be dead.", author_id: john.id)
post3.comments.create(body: "Don't waste yourself in rejection, or bark against the bad, but chant the beauty of the good.", author_id: george.id)
post4 = william.wall_posts.create(body: "Life isn't fair. It's just fairer than death, that's all.", author_id: william.id)
post4.comments.create(body: "The squirrel that you kill in jest, dies in earnest.", author_id: anna.id )
post2.comments.create(body: "This country is a one-party country. Half of it is called Republican and half is called Democrat. It doesn't make any difference. All the really good ideas belong to the Libertarians.", author_id: anna.id)
michelle.workplaces.create(company: "Facebook", description: "All human beings have three lives: public, private, and secret.")
michelle.workplaces.create(company: "Google", description: "Thinking in its lower grades is comparable to paper money. and in its higher forms it is a kind of poetry.
.")
george.educations.create(school: "Hogwarts School of Witchcraft and Wizardry", description: "Hogwarts School of Witchcraft and Wizardry is the British wizarding school, located in the Scottish Highlands. It takes students from Great Britain and Ireland. It is a state-owned school funded by the Ministry of Magic. The precise location of the school can never be uncovered because it was rendered Unplottable." )
william.educations.create(school: "Royal Academy of Arts", description: "The Royal Academy of Arts, located in the heart of London, is a place where art is made, exhibited and debated." )
john.educations.create(school: "MIT")
anna.educations.create(school: "Cornell University", description: "Cornell University is a private research university that provides an exceptional education for undergraduates and graduate and professional students. Cornell's ...
")
Friendship.create(user_id: anna.id, friend_id: william.id, status: "accepted")
Friendship.create(user_id: anna.id, friend_id: john.id , status: "accepted")
Friendship.create(user_id: john.id, friend_id: william.id, status: "accepted")
Friendship.create(user_id: george.id, friend_id: michelle.id , status: "accepted")
Friendship.create(user_id: michelle.id, friend_id: william.id , status: "accepted")
Friendship.create(user_id: george.id , friend_id: william.id , status: "accepted")
end
|
module UniversalFlashMessages::ViewHelpers
def render_flash_messages( div_id = "flash_messages", div_class = "" )
div_content = ""
UniversalFlashMessages::FlashTypes.valid.each do |key|
div_content << render_flash_message( key.to_s, flash[key] ) unless flash[key].blank?
end
return "" if div_content.blank?
content_tag( :div, div_content.html_safe, :id => div_id, :class => div_class )
end
def render_flash_message( css_class, message_array = [] )
return "" if message_array.blank?
message_array = [message_array] unless message_array.is_a?(Array)
content = ""
message_array.each { |message| content << content_tag( :p, message, :class => "#{css_class}" )}
return content
end
end
|
require 'test_helper'
require 'mazes'
class MazeTest < Minitest::Test
include Mazes
def setup
@maze = MazeCrosser::Maze.new(VALID_MAZE)
end
def test_that_dimensions_are_set_correctly_after_maze_initialization
assert_equal @maze.number_of_rows, 6
assert_equal @maze.number_of_columns, 6
end
def test_that_blocked_cell_returns_true_for_a_blocked_cell
assert @maze.blocked_cell?([3, 0])
end
def test_that_blocked_cell_returns_false_for_a_free_cell
refute @maze.blocked_cell?([1, 1])
end
def test_that_start_is_set_correctly_after_maze_initialization
assert_equal @maze.start, [0, 0]
end
def test_that_goal_is_set_correctly_after_maze_initialization
assert_equal @maze.goal, [4, 5]
end
def test_that_inside_grid_returns_true_for_a_cell_that_is_inside_the_maze
assert @maze.send(:inside_grid?, [2, 2])
end
def test_that_inside_grid_returns_false_for_a_cell_that_is_outside_the_maze
refute @maze.send(:inside_grid?, [6, 1])
end
end
|
class CreateReplacements < ActiveRecord::Migration
def up
create_table :replacements do |t|
t.string :groups, null:false
t.string :number, null:false
t.string :whom
t.string :subject, null:false
t.string :teacher, null:false
t.string :classroom, null:false
t.date :rep_date, null:false
end
end
def down
drop_table(:replacements)
end
end
|
class CardMailer < ApplicationMailer
# opts: account_id, card_ids
def annual_fee_reminder(opts = {})
opts = opts.symbolize_keys
@account = Account.find(opts.fetch(:account_id))
@cards = Card.accounts.unclosed.where(id: opts.fetch(:card_ids))
mail to: @account.email, subject: 'Annual Fee Reminder'
end
end
|
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name,presence: true,length:{minimum:2,maximum:20 }
validates :introduction,length:{maximum:50}
attachment :profile_image
has_many :books,dependent: :destroy
end
|
# == Schema Information
#
# Table name: blocked_numbers
#
# id :bigint(8) not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# platform_phone_number_id :bigint(8)
# victim_id :bigint(8)
#
# Indexes
#
# index_blocked_numbers_on_platform_phone_number_id (platform_phone_number_id)
# index_blocked_numbers_on_victim_id (victim_id)
#
# Foreign Keys
#
# fk_rails_... (victim_id => victims.id)
#
class BlockedNumber < ApplicationRecord
belongs_to :platform_phone_number, :inverse_of => :blocked_numbers
belongs_to :victim, :inverse_of => :blocked_numbers
end
|
# frozen_string_literal: true
# Cloudinary::Uploader.upload("sample.jpg", :crop => "limit", :tags => "samples", :width => 3000,
# :height => 2000)
class ImageStreamer
CHUNK_SIZE = 10 * 1024 * 1024
def initialize(image_id)
@image_id = image_id
end
def each
image_length = Image.connection.execute(<<~SQL.squish)[0]['length']
SELECT LENGTH(content_data) as length
FROM images WHERE id = #{@image_id}
SQL
(1..image_length).step(CHUNK_SIZE) do |i|
data = Image.unscoped.select(<<~SQL.squish).find(@image_id).chunk
SUBSTRING(content_data FROM #{i} FOR #{[image_length - i + 1, CHUNK_SIZE].min}) as chunk
SQL
yield(data) if data
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require 'apartment/elevators/subdomain'
module TitleLess
class Application < Rails::Application
config.middleware.use 'Apartment::Elevators::MySubdomain'
config.autoload_paths << Rails.root.join('lib')
# config.middleware.use 'ApiRequestLog'
end
end
module Apartment
module Elevators
class MySubdomain < Apartment::Elevators::Subdomain
DEFAULT_DATABASE = "public"
EXCLUDED_DOMAINS = ['www']
def call(env)
request = Rack::Request.new(env)
database = @processor.call(request)
database = DEFAULT_DATABASE if Apartment::Elevators::Subdomain.excluded_subdomains.include? database
begin
Apartment::Tenant.switch database if database
rescue Apartment::DatabaseNotFound, Apartment::SchemaNotFound
return [404, {"Content-Type" => "json"}, ["Not Found"]]
end
@app.call(env)
end
end
end
end
class ApiRequestLog
BASE_DIR = 'log/api'
def initialize app
@app = app
end
def call(env)
request = Rack::Request.new env
response_array = @app.call env
rack_response = Rack::Response.new response_array
log env, request, rack_response unless is_asset_path? request
response_array
end
private
def is_asset_path? request
request.path.match /^\/assets/
end
def log env, request, response
params = request.params
controller_and_action = Rails.application.routes.recognize_path request.url, method: request.request_method
api_file_log = ApiFileLog.new File.join(ApiRequestLog::BASE_DIR, Rails.env, Apartment::Tenant.current_tenant)
api_log = ApiLog.new controller: params[:controller],
action: params[:action],
ip_address: request.ip,
url: request.url,
path: request.path,
params: env['rack.input'].read,
request_method: request.request_method,
user_id: user_id_for_request(env),
controller: controller_and_action[:controller],
action: controller_and_action[:action],
requested_at: Time.now,
response_status: response.status,
response_body: nil
api_file_log.log api_log if api_log.valid?
end
private
def user_id_for_request env
return unless token = env['HTTP_X_USER_TOKEN']
User.find_by(authentication_token: token).try(:id)
end
end
|
class ModuloRemitente < ActiveRecord::Base
belongs_to :paciente
validates :nombre, presence: true
validates :nombre_entidad, presence: true
validates :cargo, presence: true
validates :ciudad, presence: true
validates :paciente_id, presence: true
validates :departamento, presence: true
validates :direccion, presence: true
validates :telefono, presence: true
validates :email, presence: true
validates :fecha_solicitud, presence: true
end
|
class Car < ActiveRecord::Base
attr_accessor :brand, :model, :year
validates_presence_of :brand, :model
end
|
require_relative '../db_config'
class CreatePlayerBattingStatsTable < ActiveRecord::Migration
def up
create_table :player_batting_stats do |t|
t.string :external_id
t.string :year
t.string :league
t.string :team_id
t.integer :games, :default => 0
t.integer :at_bats, :default => 0
t.integer :runs, :default => 0
t.integer :hits, :default => 0
t.integer :doubles, :default => 0
t.integer :triples, :default => 0
t.integer :home_runs, :default => 0
t.integer :runs_batted_in, :default => 0
t.integer :stolen_bases, :default => 0
t.integer :caught_stealing, :default => 0
t.decimal :batting_average, :default => 0.0, :precision => 1, :scale => 3
t.decimal :slugging_percentage, :default => 0.0, :precision => 1, :scale => 3
end
end
def down
drop_table :player_batting_stats if table_exists?(:player_batting_stats)
end
def self.table_exists?(name)
ActiveRecord::Base.connection.tables.include?(name)
end
end |
# coding: utf-8
class UserTypesController < ApplicationController
before_filter :auth_required
respond_to :html, :xml, :json
def index
end
def search
@items = UserType.order(:name)
if !params[:q].blank?
@items = @items.where("(name LIKE :q)", {:q => "%#{params[:q]}%"})
end
if params[:filter].to_i > 0
@items = @items.where("(user_types.status = :s AND year(start_date) = :y)", {:s => ArticleReferee::ACTIVE, :y => params[:filter]})
end
respond_with do |format|
format.html do
render :layout => false
end
end
end
def new
@user_type = UserType.new
render :layout => false
end
def create
@user_type = UserType.new(params[:user_type])
flash = {}
if @user_type.save
flash[:notice] = "tipo de usuario creado satisfactoriamente."
# LOG
@user_type.activity_log.create(user_id: current_user.id,
message: "Creó el tipo \"#{@user_type.name}\" (ID: #{@user_type.id}).")
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @user_type.id
json[:title] = @user_type.name
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo crear el tipo de usuario."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @user_type.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @user_type
end
end
end
end
end
def show
@user_type = UserType.find(params[:id])
render :layout => false
end
def update
@user_type = UserType.find(params[:id])
flash = {}
if @user_type.update_attributes(params[:user_type])
flash[:notice] = "Tipo de usuario actualizado satisfactoriamente"
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @user_type.id
json[:title] = @user_type.name
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo actualizar el tipo de usuario."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @user_type.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @user_type
end
end
end
end
end
end
|
class PayrollDeduction
include Mongoid::Document
include Mongoid::Timestamps
field :deduction_type, type: String
field :code, type: String
field :concept, type: String
field :amount, type: Money
belongs_to :bill
end
|
class Category < ApplicationRecord
has_many :manga_categories
has_many :mangas, through: :manga_categories
end
|
require "application_system_test_case"
class AnalysisResultsTest < ApplicationSystemTestCase
setup do
@analysis_result = analysis_results(:one)
end
test "visiting the index" do
visit analysis_results_url
assert_selector "h1", text: "Analysis Results"
end
test "creating a Analysis result" do
visit analysis_results_url
click_on "New Analysis Result"
fill_in "Analysis request", with: @analysis_result.analysis_request_id
fill_in "Content", with: @analysis_result.content
fill_in "Status", with: @analysis_result.status
click_on "Create Analysis result"
assert_text "Analysis result was successfully created"
click_on "Back"
end
test "updating a Analysis result" do
visit analysis_results_url
click_on "Edit", match: :first
fill_in "Analysis request", with: @analysis_result.analysis_request_id
fill_in "Content", with: @analysis_result.content
fill_in "Status", with: @analysis_result.status
click_on "Update Analysis result"
assert_text "Analysis result was successfully updated"
click_on "Back"
end
test "destroying a Analysis result" do
visit analysis_results_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Analysis result was successfully destroyed"
end
end
|
class Entry < ActiveRecord::Base
attr_accessor :canvas
attr_accessor :original_id
attr_accessible :chapter_id, :width, :height,:margin_top,:margin_left,:margin_bottom, :margin_right,:order_number, :canvas, :canvas_index, :option
belongs_to :chapter
has_many :entry_character
has_many :entry_balloon
after_save :save_canvas
amoeba do
include_field [:entry_character, :entry_balloon]
customize(lambda {|original_post, new_post|
new_post.original_id = original_post.id
})
end
def save_canvas
if @original_id
src = Rails.root.join("data/images/entry_canvas/#{@original_id}")
dest = Rails.root.join("data/images/entry_canvas/#{id}")
if File.exist?(src)
FileUtils.cp(src, dest)
else
FileUtils.touch(dest)
end
else
File.open(canvas_path, 'wb') do |file|
file.write(@canvas)
end
end
end
def canvas
canvas_path.binread rescue nil
end
def as_json(options = {})
options[:methods] ||= []
options[:methods] << :canvas
super
end
private
def canvas_path
Rails.root.join("data/images/entry_canvas/#{id}")
end
end
|
class User < ApplicationRecord
has_secure_password
validates :first_name,
presence: true
validates :last_name,
presence: true
validates :describtion,
presence: true,
length: { minimum: 3, maximum: 14 }
validates :email,
presence: true,
uniqueness: true,
format: {
with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/,
message: "email adress please"
}
validates :password_digest,
presence: true,
length: { minimum: 6 }
belongs_to :city
has_many :gossips
has_many :likes
has_many :comments, as: :comment_type
has_many :sent_messages, foreign_key: 'sender_id', class_name: "PrivateMessage"
has_many :received_messages, foreign_key: 'recipient_id', class_name: "PrivateMessage"
#Système de COOKIES :
#Stockage en base de `remember_digest` de l'utilisateur
def remember(remember_token)
#Hashage de `remember_token`
remember_digest = BCrypt::Password.create(remember_token)
self.update(remember_digest: remember_digest)
end
end
|
Given /^I am on the accordion page$/ do
visit AccordionPage
end
When /^I select the "([^"]*)" accordion element$/ do |label|
on(AccordionPage).accordion.select label
end
Then /^the current accordion element should be "([^"]*)"$/ do |label|
expect(on(AccordionPage).accordion.selected).to eql label
end
Then /^the accordion labels should include "([^"]*)"$/ do |label|
expect(on(AccordionPage).accordion.labels).to include label
end
Then /^the "([^"]*)" element should be selected$/ do |label|
expect(on(AccordionPage).accordion.selected?(label)).to be true
end
When /^the "([^"]*)" element should not be selected$/ do |label|
expect(on(AccordionPage).accordion.selected?(label)).to be false
end |
module Resolve
class Response
autoload :Status, 'resolve/response/status'
attr_accessor :net_response, :status
def initialize(net_response)
@net_response = net_response
@status = Status.new code
end
def code
@net_response.code.to_i
end
end
end |
module Remote
class Chapter < DigitalBiblePlatform::Base
attr_accessor :chapter_title, :chapter_id, :verses
def initialize(chapter_id, chapter_title)
self.chapter_id = chapter_id
self.chapter_title = chapter_title
self.verses = []
end
def to_h
{
chapter_title: chapter_title,
chapter_id: chapter_id,
verses: verses.collect(&:to_h)
}
end
end
end
|
require 'spec_helper'
describe Toil::Tokeniser do
before do
@subject = Toil::Tokeniser.new
end
describe :tokenise do
it 'emits an empty token list for an empty line' do
expect(@subject.tokenise('')).to eq []
end
it 'emits a single sexpr_start token for "("' do
expect(@subject.tokenise('(')).to eq [{:type => :sexpr_start}]
end
it 'emits a single sexpr_end token for ")"' do
expect(@subject.tokenise(')')).to eq [{:type => :sexpr_end}]
end
it 'emits a single whitespace token for " "' do
expect(@subject.tokenise(' ')).to eq [{:type => :whitespace,
:content => " "}]
end
it 'emits a single whitespace token for "\t"' do
expect(@subject.tokenise("\t")).to eq [{:type => :whitespace,
:content => "\t"}]
end
it 'emits a single whitespace token for multiple " "' do
expect(@subject.tokenise(' ')).to eq [{:type => :whitespace,
:content => " "}]
end
it 'emits a single symbol token for "a"' do
expect(@subject.tokenise('a')).to eq [{:type => :symbol, :content => "a"}]
end
it 'emits a single symbol token for "ab"' do
expect(@subject.tokenise('ab')).to eq [{:type => :symbol,
:content => "ab"}]
end
it 'emits two sexpr tokens for "()"' do
expect(@subject.tokenise('()')).to eq [{:type => :sexpr_start},
{:type => :sexpr_end}]
end
it 'emits five tokens for " ( ) "' do
tokens = @subject.tokenise(' ( ) ')
types = tokens.map{|tok| tok[:type]}
contents = tokens.map{|tok| tok[:content]}
expect(types).to eq [:whitespace, :sexpr_start, :whitespace,
:sexpr_end, :whitespace]
expect(contents).to eq [' ', nil, ' ', nil, ' ']
end
it 'emits five tokens for "(a b)"' do
tokens = @subject.tokenise('(a b)')
types = tokens.map{|tok| tok[:type]}
contents = tokens.map{|tok| tok[:content]}
expect(types).to eq [:sexpr_start, :symbol, :whitespace, :symbol,
:sexpr_end]
expect(contents).to eq [nil, 'a', ' ', 'b', nil]
end
it 'emits seven tokens for "(foo bar baz)"' do
tokens = @subject.tokenise('(foo bar baz)')
types = tokens.map{|tok| tok[:type]}
contents = tokens.map{|tok| tok[:content]}
expect(types).to eq [:sexpr_start, :symbol, :whitespace, :symbol,
:whitespace, :symbol, :sexpr_end]
expect(contents).to eq [nil, 'foo', ' ', 'bar', ' ', 'baz', nil]
end
it 'handles multiple lines nicely' do
INPUT = <<-FOO
(a b
(c d))
FOO
tokens = @subject.tokenise(INPUT)
types = tokens.map{|tok| tok[:type]}
contents = tokens.map{|tok| tok[:content]}
expect(types).to eq [
:sexpr_start, :symbol, :whitespace, :symbol,
:whitespace, :sexpr_start, :symbol, :whitespace, :symbol, :sexpr_end,
:sexpr_end, :whitespace]
expect(contents).to eq [
nil, 'a', ' ', 'b',
"\n ", nil, 'c', ' ', 'd', nil, nil, "\n"]
end
end
end
|
require 'rails_helper'
describe 'tagging category with link' do
context 'when logged in' do
before do
bob = Admin.create(email: 'bob@bob.com', password: '12345678', password_confirmation: '12345678')
login_as bob
end
it 'adds the category to the homepage' do
visit '/categories/new'
fill_in 'Title', with: 'Bio'
fill_in 'Description', with: 'Lorem Ipsum'
attach_file 'Image', Rails.root.join('spec/images/paintedicon.jpeg')
fill_in 'Url', with: 'http://www.paintedltd.co.uk'
fill_in 'Tags', with: 'yolo, swag'
click_button 'Submit'
expect(page).to have_link 'yolo'
expect(page).to have_link 'swag'
end
context 'existing posts' do
before do
visit '/categories/new'
fill_in 'Title', with: 'Pic1'
fill_in 'Description', with: 'Lorem Ipsum'
attach_file 'Image', Rails.root.join('spec/images/paintedicon.jpeg')
fill_in 'Url', with: 'http://www.paintedltd.co.uk'
fill_in 'Tags', with: 'yolo'
click_button 'Submit'
visit '/categories/new'
fill_in 'Title', with: 'Pic2'
fill_in 'Description', with: 'Lorem Ipsum'
attach_file 'Image', Rails.root.join('spec/images/paintedicon.jpeg')
fill_in 'Url', with: 'http://www.paintedltd.co.uk'
fill_in 'Tags', with: 'swag'
click_button 'Submit'
end
it 'should filter categories by selected tag' do
click_link 'yolo'
expect(page).to have_css 'h1', 'Categories associated with Yolo'
expect(page).to have_content 'Pic1'
expect(page).not_to have_content 'Pic2'
end
it 'uses the tag name in the url' do
click_link 'yolo'
expect(current_path).to eq '/tags/yolo'
end
end
end
end
|
class FestivalsController < ApplicationController
skip_before_action :authenticate_user!, only: [ :index, :show]
def show
@festival = Festival.find(params[:id])
session[:current_festival_id] = @festival.id
if current_user
@timetables = @festival.timetables.where(user: current_user)
@timetable = current_user.find_or_create_timetable_for!(@festival, 1)
set_timetable_parameters(@festival, 1)
set_impossible_concerts(@timetable)
else
set_timetable_parameters(@festival, 1)
end
end
def display_timetable
@festival = Festival.find(params[:festival_id])
if params[:day]
@timetable = current_user.find_or_create_timetable_for!(@festival, params[:day].to_i)
set_timetable_parameters(@festival, params[:day].to_i)
set_impossible_concerts(@timetable)
end
end
def create_event
@concert = Concert.find(params[:concert_id])
@festival = @concert.festival
@event = Event.new(concert: @concert)
timetable = current_user.find_or_create_timetable_for!(@event.concert.festival, params[:day])
@event.timetable = timetable
@day_begin = timetable.festival.concerts.where(day: timetable.day).order(:start_time).first.start_time.to_time.hour
@day_end = timetable.festival.concerts.where(day: timetable.day).order(:end_time).last.end_time.to_time.hour + 1
validation = []
timetable.events.each do |event|
if (event.concert.start_time < @event.concert.end_time && event.concert.end_time > @event.concert.start_time)
validation << false
else
validation << true
end
end
if validation.include?(false)
@events = timetable.events
else
@event.save
@events = timetable.events
@events << @event
set_impossible_concerts(@event.timetable)
end
end
def destroy_event
@event = Event.find(params[:id].to_i)
@event.destroy
respond_to do |format|
format.js
end
set_impossible_concerts(@event.timetable)
end
private
def set_timetable_parameters(festival, day)
@concerts = festival.concerts.where(day: day)
@day_begin = @concerts.order(:start_time).first.start_time.to_time.hour
@day_end = @concerts.order(:end_time).last.end_time.to_time.hour + 1
@day_duration = ((@day_end - @day_begin) > 0) ? (@day_end - @day_begin) : (24 - @day_begin + @day_end)
@hour_in_a_day = ((@day_end - @day_begin) > 0) ? (@day_end - @day_begin - 1) : (23 - @day_begin + @day_end)
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit(:timetable_id, :concert_id)
end
def set_impossible_concerts(timetable)
@impossible_concerts = []
timetable.festival.timetables.where(user: current_user).each do |timetable|
timetable.events.each do |event|
impossible_by_event = event.concert.festival.concerts.select('id').where("(start_time <= ? AND end_time >= ?) OR (? <= start_time AND start_time < ?) OR (? < end_time AND end_time <= ?)", event.concert.start_time, event.concert.end_time, event.concert.start_time, event.concert.end_time, event.concert.start_time, event.concert.end_time)
impossible_by_event.each do |concert|
@impossible_concerts << concert.id
end
end
end
return @impossible_concerts
end
end
|
class Todoitem < ApplicationRecord
belongs_to :family
validates :todotext ,presence: true
end
|
class PostsController < DivisionsController
before_action :require_administrator, only: [:index, :new, :create, :edit, :destroy]
skip_before_filter :is_student, only: [:show]
before_action :set_division, only: [:index, :show, :edit, :new, :create, :update, :destroy, :add_subject, :remove_subject]
before_filter :is_student, only: [:show]
before_action :set_post, only: [:show, :edit, :update, :destroy, :add_subject, :remove_subject]
before_action :set_post_types, only: [:new, :edit, :create]
before_action :set_posts, only: [:new, :edit, :create]
before_action :set_division_posts, only: [:index, :show, :edit, :create]
before_action :set_users, only: [:new, :edit, :create]
before_action :set_head, only: [:show, :edit]
before_action :can, only: [:edit]
def index
end
def show
@profile = @post.user.profile if @post.user
@last_image_attachment = @profile.attachments.last if @profile
if current_user_administrator?
@menu_title = @post.name
if @post.division.division_type_id == 3
@division_subjects = @post.division.subjects.includes(:educational_program) - @post.subjects
@subjects = Subject.includes(:educational_program).order(:name) - @division_subjects - @post.subjects
end
end
end
def new
@post = @division.posts.new
end
def create
@post = @division.posts.new(post_params)
if @post.save
redirect_to division_post_path(@division, @post), notice: 'Post was successfully created.'
else
render action: 'new'
end
end
def update
if @post.update(post_params)
redirect_to division_post_path(@division, @post), notice: 'Post was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@post.destroy
redirect_to division_path(@division)
end
def add_subject
@post.subjects << Subject.find(params[:subject_id])
redirect_to :back
end
def remove_subject
@post.subjects.delete(Subject.find(params[:subject_id]))
redirect_to :back
end
private
def set_post
@post = @division.posts.includes(:subjects).find(params[:id])
end
def set_division
@division = Division.find(params[:division_id])
end
def set_divisions
@divisions = Division.all
end
def set_division_posts
@division_posts = @division.posts.order(:name).all
end
def set_post_types
@post_types = PostType.all
end
def set_posts
@division.division_type.name == 'student' ? @posts = Post.order(:name).joins(:division).where(divisions: {division_type_id: [2, 6]}) : @posts = Post.order(:name).joins(:division).where.not(divisions: {division_type_id: 6})
end
def set_head
@head = @division_posts.select{|e| e if e.is_head?}
end
def can?
current_user_administrator? || (current_user == @head.first.user if @head.first)
end
def can
unless can?
flash[:error] = "You must have permissions"
redirect_to division_post_path(@division, @post)
end
end
def set_users
@division.division_type.name == 'student' ? @users = User.joins(:groups).includes(:profile).where(groups: {name: 'students'}).sort_by{|user| user.profile.full_name} : @users = User.joins(:groups).includes(:profile).where(groups: {name: 'employees'}).sort_by{|user| user.profile.full_name}
end
def post_params
params.require(:post).permit(:id, :user_id, :parent_id, :division_id, :post_type_id, :name, :phone, :feedback)
end
end
|
json.array!(@ridings) do |riding|
json.extract! riding, :id, :name, :region
json.url riding_url(riding, format: :json)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.