text stringlengths 10 2.61M |
|---|
# desc
#
# Params:
# attr: xxx
# other: yyy
# asdf las dflkj
# Other:
# attr: aaa
#
#
# conversion =>
# {
# 'desc' => 'desc',
# 'Params' => [{level: 1, }],
# }
#
module ApiDocGeneration; module FormatNote; class << self
def analyze(filelines, line_number)
document = {}
tmp = []; last_li... |
require 'colorize'
class Cell
attr_reader :coordinate, :ship, :fired_upon, :render, :number_of_shots
def initialize(coordinate, ship = nil, fired_upon = false, render = "." )
@coordinate = coordinate
@ship = ship
@fired_upon = fired_upon
@render = render
@number_of_shots = 0
end
def empty?... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
BOX_IMAGE = "centos/7"
#BOX_IMAGE = "generic/rhel7"
NODE_COUNT = 11
Vagrant.configure("2") do |config|
# MANAGER
config.vm.define "manager" do |manager|
manager.vm.box = BOX_IMAGE
#manager.vm.box = "mmichal/CentosJenkins"
manager.vm.hostname = "ma... |
# リンクの重み
class LinkWeight
def initialize(hash = {}, &block)
@weight = {}
@default =
if block_given?
block
else
proc { rand }
end
hash.each { |(from, to), weight|
self[from, to] = weight
}
end
def [](from, to)
@weight[from] ||= {}
@weight[from][t... |
class KatoRoomsController < ApplicationController
before_action :set_kato_room, only: [:show, :edit, :update, :destroy]
def index
url = KatoAdhoc.setInfo('__skey__', __duration__, '__userid__', '__username__', '__roomid__', '__roomname__')
cookies[:KATO_ADHOC_TOKEN] = url
respond_to do |format|
... |
class V1::StickerController < ApplicationController
#TODO when adding login check for session
skip_before_action :verify_authenticity_token
def create
logger.debug "Processing request #{sticker_params}"
logger.info "Processing create sticker..."
@sticker = Sticker.new(sticker_params)
... |
class TestRenderable < Test::Unit::TestCase
Sheets::Base.renderable_formats.each do |renderable_format|
define_method "test_sheet_responds_to_#{renderable_format}" do
sheet = Sheets::Base.new( File.join('test', 'data', 'simple.csv') )
assert_nothing_raised { sheet.send("to_#{renderable_format}") }
... |
# frozen_string_literal: true
FactoryBot.define do
factory :calendar_event do
title { 'Test event' }
street_address { 'Str. Test' }
city { 'Worthington' }
state { 'Ohio' }
zipcode { '77030' }
description { 'Test calendar event' }
schedule { Montrose::Schedule.new }
end
end
|
Rails.application.routes.draw do
root 'application#index'
resources :users
resources :sessions, only: [:new, :create]
get '/about' => 'application#about'
get '/contact' => 'application#contact'
get "/login" => "sessions#new", :as => "log_in"
get '/logout' => "sessions#destroy", :as => "log_out"
g... |
class SpecializationCategoriesController < ApplicationController
before_action :set_specialization_category, only: [:show, :edit, :update, :destroy]
# GET /specialization_categories
# GET /specialization_categories.json
def index
@specialization_categories = SpecializationCategory.all
end
# GET /speci... |
require 'rails_helper'
RSpec.describe Idv::SubmitIdvJob do
subject(:service) do
Idv::SubmitIdvJob.new(
idv_session: idv_session,
vendor_params: vendor_params
)
end
let(:idv_session) do
Idv::Session.new(
current_user: user,
issuer: nil,
user_session: {
idv: {
... |
#!/usr/bin/env ruby
require 'rubygems'
require 'markaby'
######## CONFIG STUFF
now = Time.now.strftime('%Y%m%d-%H%M%S')
filename = 'polyscan-results.csv'
input_filenames = [filename]
input_folder = "output"
output_folder = "output"
output_html = "#{output_folder}/#{filename}.htm"
ip_rgx = /\b(?:(?:25[0-5]|2[0-4][0-9]... |
class EventRollup
include Mongoid::Document
def self.process_entries(start_time, end_time)
map = <<-MAP
function() {
var created_at_date = new Date(Date.parse(this.created_at));
var year = created_at_date.getFullYear().toString();
var month = (created_at_date.getMonth()+1).toStrin... |
module V1
class UsersApi < Grape::API
helpers ApiErrorHelper
format :json
resource :users do
desc 'Return user records'
params do
optional :query, type: String
end
get '/' do
declared_params = declared params, include_missing: false
present UserSearchServic... |
require_relative 'lib/magrathea/version'
Gem::Specification.new do |spec|
spec.name = "magrathea"
spec.version = Magrathea::VERSION
spec.authors = ["erik yuzwa"]
spec.email = ["wazoo@hey.com"]
spec.summary = %q{Get the conversation started to use a dark-light theme structu... |
RSpec::Matchers.define :have_a_word_maximum_of do |count|
match { |story| words_in(story).count <= count }
end
RSpec::Matchers.define :have_a_character_maximum_of do |count|
match { |story| story.length <= count }
end
RSpec::Matchers.define :have_a_word_minimum_of do |count|
match { |story| words_in(story).coun... |
class Address < ApplicationRecord
belongs_to :user
validates(
:street_address,
:city,
:state,
:postcode,
:country_code,
presence: true
)
def full_address
"#{street_address}, #{city}, #{state}, #{postcode}, #{country_code}"
end
end
|
class RepetitionScheme < ActiveRecord::Base
enum recurrence: [:no_recurrence, :daily, :every_other_day, :weekly, :monthly, :yearly]
enum status: [:regular, :preference_based, :resolved]
validate :max_min_duration
before_create :equalize_slot_duration
has_many :events, :dependent => :destroy
has_and_belongs... |
# == Schema Information
#
# Table name: antibodies
#
# id :integer not null, primary key
# name :string
# amount :decimal(, )
# panel_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_antibodies_on_panel_id (panel_id)
#... |
Shortline::Application.configure do
# Code is not reloaded between requests
config.cache_classes = true
# Use Dalli for memory caching
config.cache_store = :dalli_store
# Log to STDOUT (required for Unicorn)
config.logger = Logger.new(STDOUT)
# Full error reports are disabled and caching is turned on
... |
class AddTimeToPlaces < ActiveRecord::Migration
def self.up
add_column :places, :isTimeBase, :boolean
add_column :places, :start, :datetime
add_column :places, :end, :datetime
end
def self.down
remove_column :places, :end
remove_column :places, :start
remove_column :places, :isTimeBase
... |
class FontVidaloka < Formula
head "https://github.com/google/fonts/raw/main/ofl/vidaloka/Vidaloka-Regular.ttf", verified: "github.com/google/fonts/"
desc "Vidaloka"
homepage "https://fonts.google.com/specimen/Vidaloka"
def install
(share/"fonts").install "Vidaloka-Regular.ttf"
end
test do
end
end
|
class Dmx
attr_accessor :file, :source_page, :file_type, :has_header, :name, :path, :keys
attr_accessor :struct, :index, :numeric_key, :scheme
attr_accessor :delimiter, :unique_delimiter
def initialize(name)
@name=name
end
def struct=(a)
@keys = a
@struct = Struct.new @name.capitalize, *a
end
def field... |
class OrderItemsController < ApplicationController
def create
@order = Order.find(params[:order_id]) #eerst word de desbetreffende bestelling opgezocht
@order_item = @order.order_items.create(order_item_params) #vervolgens worden er items aan toegevoegd
if @order_item.save
redirect_to order_path(@or... |
class TagsController < ApplicationController
def show
@tag = Categorical::Tag.find_by_slug!(params[:id])
@taggables = @tag.
send(fetch_taggable_type).
published.
sorted_by_published_date.
page(params[:page]).
per(10)
end
private
def fetch_taggable_type
if params[:type... |
require "camo/version"
require "openssl"
module Camo
def camo(image_url)
hexdigest = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), ENV["CAMO_KEY"], image_url)
encoded_image_url = image_url.unpack('H*').first
"#{ENV["CAMO_HOST"]}/#{hexdigest}/#{encoded_image_url}"
end
end
if defined?(Rails)
... |
class UsersController < ApplicationController
def show
if @user = User.find_by_id(params[:id])
@destroy_message ="Are you sure you want to delete your account?\nPlease note: If you delete your account, you won't be able to reactivate it later"
else
redirect_to root_path, ale... |
Rails.application.routes.draw do
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'orders#index'
# get '/discounts', :to => redirect('/patch.js')
# sawyermerchant.pagekite.me... |
require 'cloudformation_mapper/resource'
class CloudformationMapper::Resource::AwsResourceEc2VpcGatewayAttachment < CloudformationMapper::Resource
register_type 'AWS::EC2::VPCGatewayAttachment'
type 'Template'
parameter do
type 'Template'
name :Properties
parameter do
type 'String'
n... |
# frozen_string_literal: true
module GraphQL
class Schema
# A stand-in for a type which will be resolved in a given schema, by name.
# TODO: support argument types too, make this a public API somehow
# @api Private
class LateBoundType
attr_reader :name
alias :graphql_name :name
def i... |
require 'rails_helper'
RSpec.describe Spell, type: :model do
# Relations
it { should have_many :klasses }
it { should have_many :specializations }
it { should have_many :characters }
# Validations
it { should validate_presence_of :name }
end
|
class ReportsController < ApplicationController
#AJAX requests will be returned without layout
layout proc{ |c| c.params[:format] == "js" ? false : "reports" }
def show
@report = params[:id] ? Report.find(params[:id]) : Report.find_by_shift_id(params[:shift_id])
# @tasks = Task.in_location(@report.shift.... |
class CreateBusStops < ActiveRecord::Migration
def change
create_table :bus_stops do |t|
t.integer :stop_id
t.decimal :lat, {:precision => 10, :scale => 6}
t.decimal :long, {:precision => 10, :scale => 6}
t.string :on_street
t.string :cross_street
end
add_index :bus_stops, :... |
# frozen_string_literal: true
# Mysql2
module Mysql2
# Client
class Client
# Alias of the original method
#
# @see https://www.rubydoc.info/gems/mysql2/0.5.2/Mysql2%2FClient:query
# Mysql2::Client#query
alias old_query query
# Query database
#
# @example
# .query 'SELECT na... |
class Api::ResetsPasswordsController < ApplicationController
def reset
@user = User.find_by_email(params["user"]["email"])
if @user.present?
@temp_password = SecureRandom.hex(6)
User.update(@user.id, password: @temp_password)
UserNotifierMailer.send_password_reset... |
module Api::Qdc
class Audio::PercentilesController < ApiController
before_action :init_presenter
def cumulative_percentile
render
end
def ayah_duration_percentile
render
end
protected
def init_presenter
@presenter = ::Audio::PercentilePresenter.new(params)
end
en... |
FactoryBot.define do
factory :user do
sequence(:mobile) {|n| (n + 10000000000).to_s}
password { "MyString" }
avatar { "long_url" }
sequence(:name) {|n| "foobar#{n}"}
city { "Shanghai" }
gender { "male" }
intro { "good person" }
email { "foobar@emample.com" }
end
end
|
# Initial table for Vendors
class CreateVendors < ActiveRecord::Migration[5.2]
def change
create_table :vendors do |t|
t.string :contact_name
t.string :email
t.string :phone
t.string :comment
t.integer :organization_id
t.string :address
t.string :business_name
t.flo... |
class AddAffordableProductIdToSpreeSpecialOffers < ActiveRecord::Migration
def change
add_column :spree_special_offers, :affordable_product_id, :integer
end
end
|
#!/usr/bin/env ruby
require 'syntax/convertors/html'
class LineNumberFilter
def initialize(every=1, sep=' ')
@every = every
@sep = sep
end
def filter(text)
n = 0
text.split("\n").collect { |ln|
n += 1
if (n % @every == 0)
no = "%3d#{@sep} " % n
else
no = " #... |
require 'test_helper'
class ReservationTest < ActiveSupport::TestCase
def setup
@res = Factory.build(:campsite_reservation)
end
test "duration of reservation" do
@res.arrival_at = 5.days.from_now
@res.departure_at = 7.days.from_now
assert_equal 2, @res.duration_in_days
end
test "campsites ... |
Pod::Spec.new do |s|
s.name = "HDBaseProject"
s.version = "1.1.8"
s.summary = "快速搭建项目:支持AFNetworking3.1.0请求,支持自定义下拉gif动画,开源请求类"
s.description = "新建项目中常用的基础类,项目有一定量的时候,都是代码的复制和粘贴,但是在后台的粘贴中或许有好的代码更正,这个时候我们往往没有时间去维护以前的老代码,不经意间会出现代码不同步的问题"
s.homepage = "https://github.com/erduoni... |
class Department < ApplicationRecord
has_many :users
before_save :format_data
before_destroy :create_log
validates :name, presence: true
validates :cost_center, presence: true, length: { is: 4 }
def to_s
"#{name} - Cost Center: #{cost_center}"
end
private
def format_data
self.name = sel... |
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :image, :name, :... |
require 'json'
require 'openssl'
require "net/https" # use instead of rest-client so we can set SSL options
class Hiera
module Backend
class Server_backend
def initialize
Config[:server][:backends] ||= Config[:backends]
Config[:server][:hierarchy] ||= Config[:hierarchy]
Config[:s... |
require "benchmark_client/version"
require 'benchmark_client/base'
require 'benchmark_client/configuration'
module BenchmarkClient
class << self
attr_accessor :configuration
end
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration)
end
end
|
class TodoItem < ActiveRecord::Base
def self.counts
TodoItem.where(completed: true).count
end
end
|
require 'active_support/concern'
require 'cloudformation_mapper'
require 'cloudformation_mapper/base_mapper'
require 'cloudformation_mapper/dsl_attribute_methods'
module CloudformationMapper::ParameterMapper
extend ActiveSupport::Concern
module ClassMethods
include CloudformationMapper::DslAttributeMethods
... |
class Event < ApplicationRecord
enum course: { "理系": 0, "文系": 1 }
scope :get_by_course, ->(course) {
where(course: course)
}
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
... |
class ObjectList
attr_accessor :objects
include Enumerable
def initialize
self.objects = []
end
def <<(object)
objects << object
end
def draw
objects.each do |o|
o.draw
end
end
def each(&block)
objects.each(&block)
end
end
|
require 'test_helper'
class MataKuliahsControllerTest < ActionDispatch::IntegrationTest
setup do
@mata_kuliah = mata_kuliahs(:one)
end
test "should get index" do
get mata_kuliahs_url
assert_response :success
end
test "should get new" do
get new_mata_kuliah_url
assert_response :success
... |
class CreateOutgoingLuarNegeris < ActiveRecord::Migration
def change
create_table :outgoing_luar_negeris do |t|
t.string :category
t.string :index
t.string :kpc
t.string :status
t.integer :jumlah
t.string :barang
t.timestamps
end
end
end
|
class Home::HomeController < Home::BaseController
def index
result = FindCard.call(
id: params[:id],
user: current_user
)
@card = result.card
end
end
|
#Author: Robert O Driscoll
# Test script to return all values from the 'vol' 'temp' and 'epoch' columns and returns the hash map values
# I then saved them to arrays and attempted to plot them to the 'graph' widget in dashing sent again using JS databind
# Running inside a Rufus shedular. I did not take this program a... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :www_redirect
before_action :set_browser
def health_check
render text: "true"
end
private
def set_browser
@browser = Browser.new(request.user_agent)
end
def www_redirect
... |
class AppConfig
def self.properties
@properties ||= load_properties.with_indifferent_access
end
def self.load_properties
YAML.load(File.read('config/app_config.yml'))[Rails.env]
end
def self.method_missing(sym, *args, &block)
property = properties[sym]
return property unless property.nil?
... |
require 'test_helper'
class VietnamesesControllerTest < ActionController::TestCase
setup do
@vietnamese = vietnameses(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:vietnameses)
end
test "should get new" do
get :new
assert_response :... |
class RecruitersController < ApplicationController
# Index.
get '/recruiters' do
if logged_in_agency?
@recruiters = current_user.recruiters.reverse
erb :'recruiters/index'
elsif logged_in_recruiter?
@recruiters = current_user.agency.recruiters.reverse
erb :'recruiters/index'
els... |
module Candidate
class AttendanceCadastre < ActiveRecord::Base
belongs_to :adjunct_cadastre
belongs_to :attendance_status
belongs_to :attendant, class_name: "Attendance::Attendant"
belongs_to :requeriment, class_name: "Regularization::Requeriment"
default_scope { where(status: true)}
end
end
|
module ApplicationsHelper
def personal_color(application)
application.personaled? ? 'green' : 'yellow'
end
def cover_color(application)
(application.covered? ? 'green' : 'yellow') if application.personaled?
end
def screening_color(application)
return unless application.covered?
if applicatio... |
require 'rubygems'
require 'json' #gem install json
require 'base64'
require 'cgi'
require 'openssl'
require 'net/https'
require 'net/http'
module XStreamly
class Client
def initialize(appKey,email,password)
@appKey = appKey
@email = email
@password = password
@http = Net::HTTP.new('api.x-... |
class SimplecssGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.directory(File.join('app','views','simplecss'))
m.file("navigate.html.erb", File.join("app","views","simplecss","_navigate.html.erb"))
m.file("simplecss.css", File.join("public","stylesheets","simplecss.c... |
require 'application_system_test_case'
class HomeDashboardsTest < ApplicationSystemTestCase
test 'visiting the home dashboard' do
visit root_url
assert_selector 'h1', text: 'Dashboard'
assert_selector 'a.btn-dark', text: '登录'
end
end
|
class UsersController < ApplicationController
def show
@nickname = current_user.nickname
@blogs = current_user.blogs.order("created_at DESC")
end
end
|
FactoryGirl.define do
factory :review_question do
question { Faker::Lorem.sentence }
# method { Faker::Lorem.word }
category { Faker::Lorem.word }
end
end |
$: << File.dirname(__FILE__)
$: << File.join(File.dirname(__FILE__), "..", "lib")
require "rubygems"
require "minitest-patch"
require "cabin"
require "cabin/metrics"
require "minitest/autorun" if __FILE__ == $0
describe Cabin::Metrics do
before do
@metrics = Cabin::Metrics.new
end
#test "gauge" do
#gau... |
class Dish < ApplicationRecord
belongs_to :restaurant
has_many :votes, dependent: :destroy
# has_many :comments, dependent: :destroy
has_many :users, through: :votes
# has_many :users, through: :comments
end
|
module CreateGraph
class Syntaxer
attr_reader :database
def initialize(database)
@database = database
end
def create_vertex(klass, name, type)
case database
when :Orient
"create vertex #{klass} content {name: \"#{name}\", type: \"#{type}\"}"
when :Postgres
"IN... |
require 'minitest/autorun'
require 'minitest/emoji'
require './lib/node'
require './lib/linked_list'
class LinkedListTest < Minitest::Test
def test_linked_list_exists
list = LinkedList.new
assert_instance_of LinkedList, list
end
def test_linked_list_holds_instance_of_node
list = LinkedList.new("Wes... |
class PagesController < ApplicationController
def home
@posts = Blog.all
@skills = Skill.all
# ^^ Here we are calling the Blog model, asking for all() of what it has,
# and storing the results in an instance variable. Apparently you have access
# to any model from any controller. By assigning the ... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'fileutils'
module TwitterCldr
module Resources
class CollationTriesImporter < Importer
AUXILIARY_ZIP_FILE = 'CollationAuxiliary.zip'.freeze
FRACTIONAL_UCA_FILE = 'FractionalUCA_SHORT.txt'.freeze
... |
class Budget < ApplicationRecord
has_many :users
has_many :categories
def find_category(category_name)
categories.where('lower(name) = ?', category_name.downcase).first
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
module AudioVision
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializ... |
require 'net/http'
class ApiClient
attr_reader :api_url, :api_token
def initialize(options)
@api_url = options[:api_url]
@api_token = options[:api_token]
end
def get_status_code
uri = URI(@api_url)
request = Net::HTTP::Get.new(uri)
request["Accept"] = "application/json"
response = Ne... |
require "test_helper"
require "application/user"
require "application/observers/user"
module Application
describe User do
it "notifies spectators of changes to the user" do
user = User.new "josemotanet", "Jose Mota", "Software Designer"
observer = Minitest::Mock.new
observer.expect :updated, ni... |
# typed: true
class CreateEziiSeeds < ActiveRecord::Migration[6.0]
def change
create_table :ezii_seeds do |t|
t.text :github_link
t.text :gist_link
t.text :description
t.timestamps
end
end
end
|
namespace :db do
desc "Load reference data."
task :load_reference_data => :environment do
load_fixtures(
ENV['FIXTURE_PATH'] || File.join(RAILS_ROOT, 'db', 'ref_data'),
ENV['FIXTURES'])
end
desc "Populate the database with sample data"
task :populate => :environment do
require 'machinis... |
module Horseman
module Dom
class Element
attr_accessor :id, :name
def initialize(id='', name='')
@id = id
@name = name
end
end
end
end
|
class Vendor < ActiveRecord::Base
has_many :order_templates
end
|
class Comment < ActiveRecord::Base
validates :user_id, presence: true
validates :pic_id, presence: true
validates :body, presence: true
validates_length_of :body, :minimum => 1, :maximum => 35, :allow_blank => false
belongs_to :pic,
primary_key: :id,
foreign_key: :pic_id,
class_name: "Pic"
belongs_t... |
require 'securerandom'
class ShortenedUrl < ApplicationRecord
def self.random_code
random_string = SecureRandom.urlsafe_base64
until !ShortenedUrl.exists?(short_url: random_string)
random_string = SecureRandom.urlsafe_base64
end
return random_string
end
end... |
class Card
def initialize(rank = nil, suit = nil)
if suit.nil?
@suit = ['♠', '♣', '♥', '♦'].sample
else
@suit = suit
end
if rank.nil?
@rank = [(2..10).to_a, 'J', 'Q', 'K', 'A'].flatten.sample
else
@rank = rank
end
puts "Create a new card: #{@rank} of #{@suit}"
end... |
# frozen-string-literal: true
require File.join(File.dirname(__FILE__), 'helper')
class TestVorbisFile < Test::Unit::TestCase
context 'The vorbis.oga file' do
setup do
@file = TagLib::Ogg::Vorbis::File.new('test/data/vorbis.oga')
end
should 'have a tag' do
tag = @file.tag
assert_not_n... |
require 'rails_helper'
describe Article do
describe 'associations' do
it { should have_many :comments }
end
describe 'validations' do
it { should validate_presence_of :title }
it { should validate_presence_of :text }
it { should validate_length_of(:title).is_at_least(3).is_at_most(140).on(:crea... |
class Micropost < ActiveRecord::Base
before_save :upcount
attr_accessible :content, :chemical_id, :user_id, :commenter, :reposts_count, :repost_people, :dad #commenter in chemicals will be auto-included IF YOU THINK IT SHOULD BE THERE AT ALL
belongs_to :user
belongs_to :chemical
has_many :replies,... |
class Invoice < ApplicationRecord
belongs_to :customer
belongs_to :merchant
has_many :invoice_items, dependent: :destroy
has_many :items, through: :invoice_items
has_many :transactions, dependent: :destroy
def self.ranked_revenue_unshipped(quantity = 10)
all
.select('invoices.*, sum(invoice_items... |
# rubocop:disable Layout/LineLength
NODE_PATTERN = %r{/dev/grid/node-x(?<x>\d+)-y(?<y>\d+)\s+(?<size>\d+)T\s+(?<used>\d+)T\s+(?<avail>\d+)T\s+(?<percent>\d+)%}
# rubocop:enable Layout/LineLength
class DevNode
attr_accessor :size, :used, :avail
def initialize(size, used, avail)
@size = size
@used = used
... |
# frozen_string_literal: true
module FriendshipsHelper
def delete_button(_friend)
button_to 'delete', friendship, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger btn-sm'
end
def unconfirmed_requests
current_user.inverse_friendships.where(confirmed: false)
end
def all_fri... |
# frozen_string_literal: true
module Authegy
# A `RoleAssignment` associates a `Person` to an optional "resource", and
# assigns a particular roleholds the "Profile" for a given User, but we can
# also have just Person profiles without a user, as is the case for
# "Board Members"
class RoleAssignment < Appli... |
require_dependency 'application_controller'
module Core
class ApplicationController < ApplicationController
protect_from_forgery with: :exception
layout 'application'
before_action :breadcrumb
private
def breadcrumb
@breadcrumb_title = 'Gestão de Núcleo'
@breadcrumb_description ||... |
FactoryGirl.define do
factory :link, class: Hash do
href { Faker::Internet.url }
end
end
|
class Item < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :user
belongs_to :category
belongs_to :charge
belongs_to :prefecture
belongs_to :shipping_day
belongs_to :shipping_place
has_one_attached :image
has_one :order
with_options presence: true do
valid... |
require 'spec_helper'
describe MailUp::API do
context 'initialization' do
# Make sure a hash is provided
it 'requires credentials' do
expect{ MailUp::API.new }.to raise_error(MailUp::Error, 'MailUp credentials missing')
end
# Validate the credentials hash keys
[:client_id, :client_secret, ... |
require "spec_helper"
module Realogy
describe Listing do
before :each do
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
ActiveRecord::Schema.define do
create_table :realogy_entities, force: true do |t|
t.string :type
... |
# Дан целочисленный массив. Заменить все отрицательные элементы на значение минимального.
a = [-3, 8, -5, 2, 10, -6, -7, 1, 9, -4]
def change(a)
min = a.min
a.map do |x|
x < 0 ? min : x
end
end
print change(a)
|
# frozen_string_literal: true
require 'spec_helper'
describe UserPreference do
describe '#set_notes_filter' do
let(:issuable) { build_stubbed(:issue) }
let(:user_preference) { create(:user_preference) }
shared_examples 'setting system notes' do
it 'returns updated discussion filter' do
fi... |
module SubjectsHelper
# def subject_render(subject, template, *args)
# options = args.extract_options!
# if options[:partial] && subject.nil?
# render options
# elsif subject.nil?
# return
# else
# tpl = subject.templates.find_by(name: template)
# if tpl.nil?
# render... |
module Jekyll
class Page
include Helpers
include Navigation
alias_method :_prometheus_original_initialize, :initialize
def initialize(site, base, dir, name)
_prometheus_original_initialize(site, base, dir, name)
load_navigation
end
alias_method :_prometheus_original_process, :... |
class PoormanTwitter
TWITTER_API_ENDPOINT = 'https://api.twitter.com/1.1'
def initialize
consumer_key = ENV['CONSUMER_KEY']
consumer_secret = ENV['CONSUMER_SECRET']
access_token = ENV['ACCESS_TOKEN']
access_token_secret = ENV['ACCESS_TOKEN_SECRET']
consumer = OAuth::Consumer.new(
consume... |
module Trips
class MeasureDistance
include Interactor
delegate :params, to: :context
def call
distance = Geocoder::Calculations.distance_between(start.coordinates, stop.coordinates)
context.params[:distance] = distance.round(3)
rescue StandardError
context.fail!(message: { addresse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.