text stringlengths 10 2.61M |
|---|
Pod::Spec.new do |spec|
spec.name = "SnappyOC"
spec.version = "1.1"
spec.summary = "Snappy For OC"
spec.description = <<-DESC
Snappy Wrap With Objective-C
DESC
spec.homepage = "https://github.com/silence0201/snappy-oc"
spec.license = { :t... |
require 'treetop'
# extend all node with method and default behavior
class Treetop::Runtime::SyntaxNode
def ast()
if elements
elements.map { |e| e.ast() }
else
nil
end
end
def as_sql
if elements
elements.map { |e| e.as_sql }.join
... |
def log description, &block
puts "Starting #{description}..."
block.call
puts "#{description} is done."
end
log 'outside' do
puts "Starting inside block"
puts '5'
log 'inside' do
puts "I like Thai Food!"
end
end
|
class MisRecetasController < ApplicationController
def update_recipe_action
puts ' @@@ Accion de actualizar recetas'
# Queda Pendiente recibir la receta que se va editar de la vista por parametros
@receta = Recipe.find_by id: 115
# Queda pendiente recibir los nuevos parametros capturados ... |
# Helper code for jsdoc2json
class JSDoc
def initialize(sourcecode)
@sourcecode = sourcecode
# Extract relevant blocks of code (a jsdoc comment block and the following
# function signature)
@blocks = @sourcecode.scan(%r{(/\*\*.*?\*/.*?function.*?\n)}m).flatten
end
def sp... |
module Managed
extend ActiveSupport::Concern
included do
belongs_to :manager
accepts_nested_attributes_for :manager
before_validation :find_manager
after_save :find_or_create_manager
after_save :notify_new_manager
attr_accessor :new_manager_record
end
def managed_by? manager, super_... |
require 'spec_helper'
require 'player'
describe Player do
subject { described_class.new(level, image_registry, x, y) }
it_behaves_like 'jumper'
it_behaves_like 'creature with view', PlayerView
it_behaves_like 'creature with states',
:stand, :run_right, :run_left,
:jump, :ju... |
# frozen_string_literal: true
require 'test_helper'
class RelationTest < Minitest::Test
Result = Struct.new(:where_clause, :limit_value, :group_values, :order_clause)
class TestObject
class << self
attr_accessor :call_count
def find_by_query(where_clause:, limit_value:, group_values:, order_clau... |
class Openssl < Package
desc "Cryptography and SSL/TLS Toolkit"
homepage "https://openssl.org/"
url 'https://openssl.org/source/openssl-${version}.tar.gz'
# release version: '1.0.2o', crystax_version: 1
# release version: '1.1.0h', crystax_version: 1
release version: '1.1.1g', crystax_version: 2
# relea... |
class FavoriteFoldersController < ApplicationController
before_action :set_profile
before_action :check_profile
before_action :set_favorite_folder, only: [:show, :edit, :update, :destroy]
# GET /profiles/1/favorite_folders
# GET /profiles/1/favorite_folders.json
def index
@folders = current_profile.fav... |
require 'net/http'
require 'uri'
require 'json'
require "dotenv/load"
class Conversation
attr_reader :username, :password, :version
def initialize(username:, password:, version: "2017-05-26")
@username = username
@password = password
@version = version
end
def message(workspace_id, text:, context... |
require 'rspec'
require_relative '../model/convertidor_json_objeto'
describe 'ConvertidorJsonObjeto' do
let(:convertidor) { ConvertidorJsonObjeto.new }
#Test convertir_calendario
it 'Test metodo convertir_calendario: El convertidor al recibir algo vacio deberia devolver nil' do
expect(convertidor... |
class Intent < ApplicationRecord
include PgSearch
pg_search_scope :search, against: :tag, using: {tsearch: {prefix: true, dictionary: "english"}}
validates :q_string, presence: true
validates :q_key, presence: true, uniqueness: true
belongs_to :parent_intent, class_name: 'Intent', foreign_key: "intent_id", op... |
# Идеальный вес.
# Программа запрашивает у пользователя имя и рост и выводит идеальный вес по формуле <рост> - 110, после чего выводит результат пользователю на экран с обращением по имени.
# Если идеальный вес получается отрицательным, то выводится строка "Ваш вес уже оптимальный"
puts "Как тебя зовут?"
name = ge... |
class LibView::LibraryLocationsController < ApplicationController
include AddLocaleIncludes
before_action :set_library
before_action :set_library_location, only: [:show]
before_action :set_library_schedules, only: [:show]
# GET /library/library_locations
def index
@library_locations = LibraryLocation... |
FactoryGirl.define do
factory :student do
email 'example@example.com'
password 'please'
password_confirmation 'please'
# required if the Devise Confirmable module is used
confirmed_at Time.now
title 'Mr'
forename1 'Charles'
forename2 'Philip'
forename3 'Arthur George'
surname '... |
class AddThemeRankingAndChosenDateToAnswers < ActiveRecord::Migration[5.2]
def change
add_column :answers, :theme_ranking, :string, array: true, default: []
add_column :answers, :chosen_date, :string, array: true, default: []
end
end
|
class ChangeCoralNameToSpeciesName < ActiveRecord::Migration[4.2]
def change
rename_column :species, :coral_name, :specie_name
end
end
|
class Skill < ApplicationRecord
has_many :user_skills, dependent: :destroy
end
|
GLOBAL_SAVE_MSG = '登録が正常に完了しました。'
GLOBAL_UPDATE_MSG = '更新が正常に完了しました。'
GLOBAL_UPDATE_ERROR_MSG = '更新中にエラーが発生しました。入力情報を見直してください。'
GLOBAL_CONFLICT_MSG = '他のユーザーが更新中です。時間を置いてもう一度操作を行なって下さい。'
MASTERS = {
:messages => {
"入力してください" => :fill_in_error,
"更新しました" => :save_success
},
:hero_types => {"STRENGTH"=>1, "... |
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context '新規登録がうまくいくとき' do
it "nicknameとemailとpasswordとzenkaku_familynameとzenkaku_nameとkatakana_family_kanaとkatakana_name_kanaとbirthda... |
class AddSubjectToBook < ActiveRecord::Migration
def self.up
add_column :books, :my_subjects, :string
end
def self.down
remove_column :books, :my_subjects
end
end
|
# -*- encoding : utf-8 -*-
require 'spec_helper'
describe MemberSessionsController do
describe :new do
it "should render the login template" do
get :new
response.should render_template("new")
end
it "should set redirect path when specified" do
@redirect_to = "/some/redirect/path"
... |
require 'faraday'
module Sipgate
class Connexion
include Singleton
ROOT_URL = 'https://api.sipgate.com/'
def self.conn(options={})
options.delete(:authenticated){true} ? auth_connexion : connexion
end
private
def self.connexion
@connexion ||= get_connexion(fals... |
# frozen_string_literal: true
# Apt configuration and default repos and packages
# ================================================
require 'open-uri'
include_recipe 'apt'
# Why not?
link '/usr/local/bin/can-has' do
to '/usr/bin/apt-get'
end
# Custom repos
node['sanitize']['apt_repositories'].each do |name, repo... |
require 'rails_helper'
RSpec.describe 'authentication', type: :request do
describe 'POST /login' do
let(:user) { FactoryBot.create(:user) }
let(:url) { '/login' }
let(:params) do
{
user: {
email: user.email,
password: user.password
}
}
end
context ... |
class User < ApplicationRecord
acts_as_token_authenticatable
devise :database_authenticatable, :registerable,
:rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: %i[github]
has_many :assigned_books, dependent: :destroy
has_many :read_entries, dependent: :destroy
has... |
class ProductContract < ActiveRecord::Base
belongs_to :contract
belongs_to :product
validates :contract, :product, presence: true
end
|
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :have_access! ,only: [:destroy]
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create (comment_params)
@comment.user_id= current_user.id
if (@comment... |
# Wrap UUID creation
#
# Author: Ben Nagy
# Copyright: Copyright (c) Ben Nagy, 2006-2013.
# License: The MIT License
# (See http://www.opensource.org/licenses/mit-license.php for details.)
require 'ffi'
require_relative 'winerror'
module BM3
module Win32
module UUID
extend FFI::Library
... |
# -*- encoding: utf-8 -*-
require 'cgi'
module Omniship
# After getting an API login from USPS (looks like '123YOURNAME456'),
# run the following test:
#
# usps = USPS.new(:login => '123YOURNAME456', :test => true)
# usps.valid_credentials?
#
# This will send a test request to the USPS test servers, whi... |
Rollbar.configure do |config|
# Without configuration, Rollbar is enabled in all environments.
# To disable in specific environments, set config.enabled=false.
config.access_token = ENV['ROLLBAR_SV_TOKEN']
if Rails.env.test? || Rails.env.development?
config.enabled = false
config.js_enabled = false
e... |
# encoding: utf-8
require 'spec_helper'
describe ActiverecordDIY::Json::Backed do
before(:each) do
ActiveRecord::Base.connection.execute "DROP TABLE test_models" rescue nil
class TestModel < ActiveRecord::Base
use_json_attributes do |t|
t.column :k1, :string
t.integer :k2, :k3
t... |
class BillpartsController < ApplicationController
# GET /billparts
# GET /billparts.json
def index
@billparts = Billpart.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @billparts }
end
end
# GET /billparts/1
# GET /billparts/1.json
def show
... |
control "open-development-environment-devbox-script-update" do
title "open-development-environment-devbox-script-update control"
describe file("/etc/update-manager/release-upgrades") do
it { should exist }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_readable... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe User, type: :model do
let(:subject) { build(:user) }
it 'is valid from the factory' do
expect(subject).to be_valid
end
describe 'association' do
it { is_expected.to have_many(:earning_rules) }
end
describe 'validations' do
... |
class CreateMatchResults < ActiveRecord::Migration
def change
create_table :match_results do |t|
t.integer :points
t.integer :scores
t.references :team, index: true
t.references :match, index: true
t.timestamps null: false
end
add_foreign_key :match_results, :teams
add_f... |
require 'spec_helper'
describe Admin::Studios::AdminsController do
describe "GET index" do
let(:studio_admin) { Factory :studio_admin }
let(:studio) { studio_admin.studio }
let(:other_studios_admin) { Factory :studio_admin }
before do
sign_in Factory :admin
get :index, :studio_id => studi... |
module Clockface
class EventsPresenter < SimpleDelegator
include ConfigHelper
def period
I18n.t(
"datetime.distance_in_words.x_#{event.period_units}",
count: event.period_value
)
end
def at
at = event.at
# `at` uses the day name from the ruby standard library... |
require File.join(File.dirname(__FILE__), '..', 'test_helper')
# new
# ---
class IQ::Crud::Actions::New::NewTest < Test::Unit::TestCase
def setup
ActionView::Base.any_instance.stubs(:error_messages_for).returns('<p id="errors">Errors</p>')
['', 'admin_'].each do |prefix|
send(prefix + 'crudified_instan... |
class RoundSerializer < ActiveModel::Serializer
attributes :id, :running_order, :player_id, :name
end
|
module Operations
module Notifications
class DayReport
attr_reader :organization, :except_ids
attr :worker, :appointments, :month_appointments
def initialize(options)
@organization = Organization.find(options[:organization_id])
@except_ids = options[:except_ids] || []
end
... |
class ColumnAuthorApply < ActiveRecord::Base
belongs_to :user
upload_column :logo #,:process => '1024x1024', :versions => {:thumb120 => "90x120", :thumb400 => "300x400" }
validates_presence_of :real_name,:message=>"真实姓名不能为空"
validates_presence_of :identity_type,:message=>"证件类型不能为空"
validates_presence_of :iden... |
# Комментарии к монстрам
class CommentsController < ApplicationController
# Создание нового комментария
def create
@monster = Monster.find(params[:monster_id])
comment = @monster.comments.new(comment_params)
comment.title = @current_user.username
comment.save
redirect_to monster_path(@monster)
... |
def uppercase?(string)
return true if string.empty?
string.count('a-zA-Z') == string.count('A-Z')
end
p uppercase?('t') == false
p uppercase?('T') == true
p uppercase?('Four Score') == false
p uppercase?('FOUR SCORE') == true
p uppercase?('4SCORE!') == true
p uppercase?('') == true
p '-----'
def uppercase2?(strin... |
class LCDNumbers
attr_accessor :size
NUMBERS = [
[" - "," "," - "," - "," "," - "," - "," - "," - "," - "],
["| |"," |"," |"," |","| |","| ","| "," |","| |","| |"],
[" "," "," - "," - "," - "," - "," - "," "," - "," - "],
["| |"," |","| "," |"," |"," |","| |"," |","| |"," |"]... |
# 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' }])
# Ch... |
# DataSources are stored in app/views/data_sources with attributes taken from
# the "front matter" of each page -- i'm probably being too creative here.
class DataSource
include ActiveAttr::Model
attribute :id, type: String
attribute :title, type: String
attribute :date, type: Date
attribute :description, ty... |
module OrganizationsHelper
def intake_reasons
[
'owner surrender',
'pulled from animal control',
'stray',
'returned',
'other'
]
end
def location(animal)
if animal.org_profile.organization_location.present?
animal.org_profile.organization_location.name
else... |
class PackingSlip < ActiveRecord::Base
attr_accessible :shipment_id, :shipper_id, :consignee_id, :pallets, :total_weight, :list_items_attributes, :reference_number
has_many :list_items, :dependent => :destroy
belongs_to :shipment
belongs_to :shipper, :class_name => "Contact"
belongs_to :consignee, :class_n... |
# Order
class Order < ActiveRecord::Base
belongs_to :client, counter_cache: true
default_scope -> { order('ordered_at DESC') }
end
|
require 'sinatra/base'
require 'json'
require './lib/flaggrocrag'
module Flaggrocrag
class Application < Sinatra::Base
configure do
enable :logging
set :repo, Flaggrocrag::Repository.new(File.dirname(app_file))
set :flag_dir, File.join(File.dirname(app_file), "flags")
set :flag_search, Fi... |
class JobAppliesController < SiteController
no_login_required
before_filter :find_job
def new
@job_apply = @job.job_applies.new
radiant_render :page => "/jobs"
end
def create
@job_apply = @job.job_applies.new(params[:job_apply])
if @job_apply.save
flash[:notice] == 'Votre candidatre... |
class Alumno
#notas en un array de notas
attr_accessor :nombre, :notas
def initialize(nombre, notas)
@nombre = nombre
@notas = notas
end
def promedio
@notas.sum / @notas.count
end
end
alumnos = []
5.times.each do |i|
nombre = "Alumno_#{i}"
notas = [rand(1..7)... |
module ClinkCloud
class ServerMapping
include Kartograph::DSL
kartograph do
mapping Server
property :id, scopes: [:read]
property :name, scopes: [:read, :create]
property :description, scopes: [:read, :create]
property :groupId, scopes: [:read, :create]
property :isTempla... |
require 'weapons'
describe Weapons do
subject(:weapons) { described_class.new }
describe 'defaults' do
it 'should store a hash detailing the RPS choices' do
expect(weapons.rules).to eq(rock: :scissors, paper: :rock, scissors: :paper)
end
it 'should have a nil result' do
expect(weapons.re... |
require 'spec_helper'
describe Private::AssetsController do
let(:member) { create :member }
before { session[:member_id] = member.id }
context "logged in user visit" do
describe "GET /exchange_assets" do
before { get :index }
it { should respond_with :ok }
end
end
context "non-login us... |
class FileAttachment
include Mongoid::Document
include Mongoid::Timestamps::Short
include FileAttachmentUploader::Attachment.new(:file)
field :file_data, type: String
field :file_size, type: Integer
field :file_filename, type: String
field :file_mime_type, type: String
embedded_in :attachable, polymor... |
FactoryGirl.define do
factory :prototype, class: Prototype do
title { Faker::Name.name }
catch_copy { Faker::Lorem.word }
concept { Faker::Lorem.sentence }
created_at { Faker::Time.between(2.days.ago, Time.now) }
user
trait :with_sub_images do
transient do
sub_image... |
class NumberTileGame < BrewSparkling::Recipe::Builder
github 'austinzheng/iOS-2048', branch: '7c0840a0f7bd77b01d6a36778a253f8f4b2e6529'
description 'OS drop-in library presenting a clean-room Objective-C/Cocoa implementation of the game 2048.'
version '1.0'
bundle_identifier 'f3nghuang.NumberTileGame'
def bu... |
class CreateRatings < ActiveRecord::Migration
def self.up
create_table :ratings do |t|
t.integer :property_id, :null => false
t.string :first_name, :null => false
t.string :last_name, :null => false
t.integer :rental_start_month
t.integer :rental_start_year
t.integer :rental_end... |
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def export_members
File.new("data.csv",... |
class CreateTaskDependencies < ActiveRecord::Migration
def change
create_table :task_dependencies do |t|
t.integer :blocking_task_id , :null => false
t.integer :dependent_task_id , :null => false
t.boolean :direct , :null => false
t.integer :count , :null => false
... |
# frozen_string_literal: true
class DestroyUploadOperation < BaseOperation
def initialize(owner)
@owner = owner
end
def call(mounted_as:)
remove_attach(mounted_as)
end
private
attr_reader :owner
def remove_attach(mounted_as)
method = "remove_#{mounted_as}!"
owner.public_send(method) ... |
require 'account_history'
describe AccountHistory do
let(:printer) { double :printer, print_statement: 'statement' }
let(:account_history) { described_class.new(printer) }
describe '#log_deposit' do
it 'adds deposit information to history' do
expect(account_history.log_deposit(100, 200).last.flatten)
... |
# Letter Counter (Part 2)
# Modify the word_sizes method from the previous exercise to exclude non-letters when determining word size. For instance, the length of "it's" is 3, not 4.
def word_sizes(str)
hsh = {}
# split up each word in the string to a separate array value
arr = str.split(" ")
new_arr = []
#... |
class UserResume::Xing < UserResume
attr_accessor :resume_data
def perform
to_markdown
end
protected
# Generates the markdown resume text based on the resume data
#
# @return [String]
def to_markdown
return unless resume_data
response = ''
response << markdown_header
response << m... |
#!/usr/bin/env ruby
# encoding: utf-8
# Make a bigram LM from the phone sequences in Wenda's prondict.
# On stdin, expects e.g.
# prondict_uzbek-from-wenda.txt
# prondicts/rus-prondict-july26.txt
# prondicts/Tigrinya/prondict-from-amharic-phones.txt
# where each line is: word, tab-or-space, space-delimited IPA ... |
class UserMailer < ActionMailer::Base
add_template_helper(UsersHelper)
default from: GMAIL_SMTP_USER
def welcome_email(user)
@user = user
@url = signin_path
if Rails.env.production?
mail(to: user.email, bcc: GMAIL_SMTP_USER, subject: 'Welcome to Hunt Britain')
else
mail(to: GMAIL_TEST_RECIPIENT, ... |
#!/Users/feilsafe/.rvm/rubies/ruby-2.5.3/bin/ruby
require 'json'
require 'pathname'
require_relative './models/person'
# Check if an argument was given
if ARGV.length <= 0
STDERR.puts "No csv file given. usage is `./find_nearest.rb file_path"
exit 2
end
# Check if the argument is a file path that exists
path = Pa... |
#!/usr/bin/env ruby
require 'spec_helper'
# base_vars:
# PYTHON_VERSION_MAJOR: '3'
# PYTHON_VERSION: '3.5'
# GSTREAMER: '1.0'
# USER: 'pi'
# USER_HOME: '/home/pi'
# LANGUAGE_ID: 1473
# GITHUB_BRANCH: "master"
# GITHUB_REPO_NAME: "scarlett_os"
# GITHUB_REPO_ORG: "bossjones"
#
# virtualenv_vars:
# M... |
# frozen_string_literal: true
require 'test_helper'
class PostcodeFlowsTest < ActionDispatch::IntegrationTest
test 'start page' do
get '/'
assert_select 'label', 'Please enter a postcode:'
end
test 'response' do
get index_path(postcode: "SE1 7QA")
assert_equal 200, response.status
end
end
|
# frozen_string_literal: true
require 'base64'
module MideaAirCondition
# Class to manage encryptions/decryptions/sign/etc
class Security
attr_accessor :access_token, :app_key
def initialize(app_key:, access_token: '')
@app_key = app_key
@access_token = access_token
@crc8_854_tabl... |
module EasyPostAdapter
def self.generate_shipment(args={})
EasyPost.api_key = "#{ENV['EASYPOST_KEY']}"
# Add stuff to sanitize input
to_address_hash = args.fetch(:to_address, "")
from_address_hash = args.fetch(:from_address, "")
# Sample Hash
# {street1: "4181 Main Street",
# city: ... |
class RemoveRoleFromSection < ActiveRecord::Migration
def change
remove_column :sections, :role
end
end
|
(1..99).each do |i|
puts i if i%2 != 0
end |
module TokenGenerator
class AuthToken
attr_reader :token
def initialize(user)
@token = JsonWebToken.encode(user_id: user.id)
end
end
end
|
class VeiculosUsuariosController < UsuariosController
before_action :set_veiculo, only: [:show, :edit, :update, :destroy]
skip_before_action :authenticate_user!, only: :index
def index
@veiculos = Veiculo.all
end
private
# Use callbacks to share common setup or constraints between actions.
def s... |
class A
attr_reader :x
def setx(x) @x = x end
end
a = A.new
a.setx(2)
a.x + 3
|
FactoryGirl.define do
factory :purchase_order do
supplier
warehouse
dt_expected { 2.days.from_now }
# 1 - created, 2 - sent, 3 - canceled, 4 - partially delivered
# 5 - fully delivered, 6 - closed by user
status 1
end
end
|
# Observer Design Pattern
class Employee
attr_accessor :name, :title, :salary
def initialize(name, title, salary)
@name = name
@title = title
@salary = salary
end
end
# since salary field is accessible via attr_accessor we can now update the salary for an employee
employee = Employee.new('John', 'D... |
class Product < ApplicationRecord
belongs_to :product_category
belongs_to :store_purchase
validates :name, presence: true
validates :price, presence: true
validates :store_purchase, presence: true
end
|
class UserExamsController < ApplicationController
before_action :set_user
before_action :set_user_exam, only: [:show, :update, :destroy]
# GET /users/:user_id/user_exams
def index
json_response(@user.user_exams)
end
# GET /users/:user_id/user_exams/:id
def show
json_response(@user_exam)
end
... |
require 'rails_helper'
RSpec.describe QuestionsController, type: :controller do
let(:question) { create(:question) }
let(:some_user) { create(:user) }
describe 'GET #index' do
let(:questions) { create_pair(:question) }
before { get :index }
it 'populates an array of all questions' do
expect(... |
class CreateCharacterExtraBuilds < ActiveRecord::Migration[6.0]
def change
create_table :character_extra_builds do |t|
t.belongs_to :character
t.belongs_to :user, null: true
t.integer :amount, null: false
t.string :reason, null: false
t.timestamps
end
end
end
|
class ReviewsController < ApplicationController
before_filter :authorize
def create
puts "ready to create a review, sir yes sir"
puts params
@review = Review.new(review_params)
@review.product_id = params["product_id"]
@review.user_id = current_user.id
if @review.save
redirect_to [:p... |
class UsersController < ApplicationController
def index
mac = get_remote_mac
if Host.exists?(:mac => mac)
redirect_to status_url
end
@user = User.new
end
def condition
mac = get_remote_mac
@host = Host.find_by_mac(mac)
@user = @host.user
redirect_to index_url if @host.nil... |
# -*- coding: utf-8 -*-
require "spec_helper"
describe Album do
# let(:photo) { Factory(:photo)}
describe "#photos_count" do
it "should increment if photo is created" do
@photo = build(:photo)
@photo.save
Album.find(@photo.album).photos_count.should be(1)
end
it "should decrement if p... |
module Api
module V1
class AppsController < ApplicationController
respond_to :json
def index
respond_with App.all
end
def show
respond_with App.find(params[:id])
end
def create
respond_with App.create(app_params)
end
def update
re... |
# coding: UTF-8
require 'spec_helper'
describe PushBuilder::Compiler do
describe '#compile' do
it 'crops the alert if necessary' do
alert = 50.times.map { 'foobar' }.join
payload = { aps: { alert: alert } }
json = described_class.new(payload).compile
json.bytesize.should be 256
js... |
# The premise of this algorithm is that there is a list representing a
# pile of stones where the integer values represent each stone's weight.
# A person takes the two heaviest stones and smashes them together. If
# the two stones are of equal value, then they both completely
# disintegrate. If they are not, the weigh... |
require 'spec_helper'
describe Castle do
let(:board) { Board.new }
describe "#new" do
it "works" do
expect(Castle.new(board, :white, "a1")).to be_an_instance_of Castle
end
end
describe "#possible_moves" do
it "returns the possible moves" do
expect(Castle.new(board, :white, "a1").possi... |
module WorkWithTable
private
class Table
include TypeOperations::TypeConverter
Column = Struct.new(:col_name, :type, :options)
attr_reader :columns, :user_primary_key
def initialize
@columns = Array.new
@items = Array.new
@allowed_types = [:text, :string, :float, :integer, :dou... |
class HeapSort
def initialize(arr)
@list = arr
end
def build_heap()
total_items = @list.length
total_items.step(0, total_items / 2 - 1) do |i|
heapify(total_items, i)
end
end
private
def left(i)
(2 * i) + 1
end
def right(i)
(2 * i) + 2
end
def parent(i)
(i - 1... |
control 'CIS-2.1.1' do
impact 'high'
title "Ensure all S3 buckets employ encryption-at-rest"
desc 'Encrypting data at rest reduces the likelihood that it is
unintentionally exposed and can nullify the impact of disclosure if the
encryption remains unbroken.'
tag severity: 'High'
ref 'CIS Docs', ur... |
require 'zip/zipfilesystem'
# A container to hold assets (files) belonging to members
class Folder < ActiveRecord::Base
acts_as_tree
belongs_to :user
has_many :keyed_folders, :dependent => :destroy
has_many :access_keys, :through => :keyed_folders, :readonly => false
has_many :assets, :dependent => :destroy
has_... |
class PizzasController < ApplicationController
before_action :authenticate_user!
def index
@pizzas = Pizza.all
end
def new
@pizza = Pizza.new
end
def edit
@pizza = Pizza.find(params[:id])
end
def create
@pizza = Pizza.new(pizza_params)
if @pizza.save
redirect_to pizzas_path
else
... |
class Cache
class Upgrades < Cache
SCHEDULE_FILE = '/etc/server-reports/schedule'.freeze
PACKAGES_FILE = '/var/tmp/package-upgrades/packages-by-server.yaml'.freeze
# Load the schedule of when to upgrade servers, turning into a hash with
# hash key the server name and value the scheduled week (0..4).
... |
class PlacementSerializer < ActiveModel::Serializer
has_one :order
has_one :product
attributes :quantity, :product
def product
ActiveModel::SerializableResource.new(object.product, serializer: ProductSerializer)
end
end
|
@answers_hash = response.answers.map { |answer| [answer.question_id, answer] }.to_h
json.survey do
json.(survey, :id, :title, :start_at, :end_at, :base_exp, :published)
json.description format_html(survey.description)
end
json.response do
json.(response, :id, :submitted_at)
json.creator_name response.creator.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.