repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
AcnologiatheEnd/MineEstate
|
backend/db/migrate/20201026170750_fix_column_name.rb
|
class FixColumnName < ActiveRecord::Migration[6.0]
def change
rename_column :users, :usesrname, :username
end
end
|
AcnologiatheEnd/MineEstate
|
backend/app/controllers/application_controller.rb
|
<reponame>AcnologiatheEnd/MineEstate
class ApplicationController < ActionController::API
require 'securerandom'
include SessionsHelper
@@token = "0"
@@user = 0
end
|
AcnologiatheEnd/MineEstate
|
backend/db/migrate/20201111021708_add_session_to_users.rb
|
class AddSessionToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :session, :integer
end
end
|
AcnologiatheEnd/MineEstate
|
backend/config/routes.rb
|
Rails.application.routes.draw do
resources :houses, only: [:create, :destroy]
resources :users
resources :sessions, only: [:home, :create, :new, :destroy]
get '/logout' => 'sessions#destroy'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
AcnologiatheEnd/MineEstate
|
backend/app/controllers/houses_controller.rb
|
<reponame>AcnologiatheEnd/MineEstate
class HousesController < ApplicationController
def create
house = House.new(house_params)
if current_user
current_user.houses << house
end
if house.valid?
allHouses = House.all
render json: HouseSerializer.new(allHouses).to_serialized_json
else
status = "bad"
render json: status.to_json
end
end
def destroy
house = House.find_by_id(params[:id])
if current_user.houses.include?(house)
house.destroy
status = "good"
render json: status.to_json
end
end
private
def house_params
params.require(:house).permit(:price, :description, :size, :style, :neighborhood)
end
end
|
AcnologiatheEnd/MineEstate
|
backend/app/controllers/users_controller.rb
|
<filename>backend/app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(house_params)
@user.password = <PASSWORD>[:password]
status = "bad"
if @user.valid?
@user.save
log_in @user
allHouses = House.all
render json: HouseSerializer.new(allHouses).to_serialized_json
end
end
private
def house_params
params.require(:user).permit(:username, :password, :email, :country, :state)
end
end
|
AcnologiatheEnd/MineEstate
|
backend/app/helpers/sessions_helper.rb
|
module SessionsHelper
def log_in(user)
@@token = SecureRandom.hex
user.token = @@token
user.session = 1
user.save
set_current_user(user)
end
def set_current_user(user)
@@user = user
end
def current_user
@@user
end
def logged_in?
!!(@@token == current_user.token)
end
def log_out
@@token = "0"
current_user.token = 0
current_user.session = nil
current_user.save
set_current_user(nil)
end
end
|
LaunchAcademy/gollum_client
|
spec/spec_helper.rb
|
require 'rspec'
require 'vcr'
require_relative '../lib/gollum_client'
GollumClient.path_prefix = '/codecabulary/'
GollumClient.base_url = 'http://localhost:9292'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock # or :fakeweb
c.configure_rspec_metadata!
c.default_cassette_options = { :record => :new_episodes }
end
RSpec.configure do |c|
# so we can use :vcr rather than :vcr => true;
# in RSpec 3 this will no longer be necessary.
c.treat_symbols_as_metadata_keys_with_true_values = true
end
|
LaunchAcademy/gollum_client
|
spec/gollum_client/page_spec.rb
|
require 'spec_helper'
describe GollumClient::Page, :vcr do
context "fetching content" do
let(:page) { GollumClient::Page.fetch('/test') }
it 'contains testing 1 2 3' do
expect(page.body).to include('testing')
end
it 'does not contain navigation' do
expect(page.body).to_not include('Last edited')
end
it 'returns nil if the page is not found' do
expect(GollumClient::Page.fetch('/will-never-be-present')).to be_nil
end
it 'returns a title for metadata' do
expect(page.meta[:title]).to_not be_nil
end
end
end
|
LaunchAcademy/gollum_client
|
lib/gollum_client/page.rb
|
require 'faraday'
require 'faraday_middleware'
require 'nokogiri'
module GollumClient
class Page
attr_reader :body, :title, :meta
def initialize(title, body, meta = {})
@title = title
@body = body
@meta = meta
end
class << self
def fetch(path = '')
resp = nil
begin
resp = connection.get(GollumClient.path_prefix + path)
rescue FaradayMiddleware::RedirectLimitReached
return nil
end
parsed_resp = Nokogiri.parse(resp.body)
node = parsed_resp.css('#wiki-content').first
if node
title = parsed_resp.css('#head h1').first.inner_html
html_title = parsed_resp.css('title').first.inner_html
new(title, node.to_s, title: html_title)
else
nil
end
end
def connection
Faraday.new(:url => GollumClient.base_url) do |faraday|
faraday.use FaradayMiddleware::FollowRedirects
faraday.request :url_encoded # form-encode POST params
# faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end
end
end
end
|
LaunchAcademy/gollum_client
|
lib/gollum_client.rb
|
require 'configatron'
require 'gollum_client/version'
require 'gollum_client/page'
require 'gollum_client/app'
module GollumClient
class << self
def base_url=(url)
configatron.gollum_client.base_url = url
end
def base_url
configatron.gollum_client.base_url
end
def path_prefix=(prefix)
configatron.gollum_client.path_prefix = prefix
end
def path_prefix
configatron.gollum_client.path_prefix
end
end
end
|
LaunchAcademy/gollum_client
|
lib/gollum_client/version.rb
|
<filename>lib/gollum_client/version.rb
module GollumClient
VERSION = "0.0.1"
end
|
honeycombio/faraday-honeycomb
|
lib/faraday/honeycomb/version.rb
|
<reponame>honeycombio/faraday-honeycomb<gh_stars>1-10
module Faraday
module Honeycomb
GEM_NAME = 'faraday-honeycomb'
VERSION = '0.3.3'
MIN_FARADAY_VERSION = '0.8'
end
end
|
honeycombio/faraday-honeycomb
|
lib/faraday/honeycomb.rb
|
require 'faraday'
require 'faraday/honeycomb/middleware'
Faraday::Middleware.register_middleware honeycomb: ->{ Faraday::Honeycomb::Middleware }
|
honeycombio/faraday-honeycomb
|
faraday-honeycomb.gemspec
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH << lib unless $LOAD_PATH.include?(lib)
require 'faraday/honeycomb/version'
Gem::Specification.new do |gem|
gem.name = Faraday::Honeycomb::GEM_NAME
gem.version = Faraday::Honeycomb::VERSION
gem.summary = 'Instrument your Faraday HTTP requests with Honeycomb'
gem.description = <<-DESC
TO DO *is* a description
DESC
gem.authors = ['<NAME>']
gem.email = %w(<EMAIL>)
gem.homepage = 'https://github.com/honeycombio/faraday-honeycomb'
gem.license = 'Apache-2.0'
gem.add_dependency 'libhoney', '>= 1.5.0'
gem.add_development_dependency 'faraday', ">= #{Faraday::Honeycomb::MIN_FARADAY_VERSION}"
gem.add_development_dependency 'bump'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'yard'
gem.add_development_dependency 'byebug'
gem.add_development_dependency 'pry'
gem.add_development_dependency 'honeycomb-beeline'
gem.files = Dir[*%w(
lib/**/*
README*)] & %x{git ls-files -z}.split("\0")
end
|
honeycombio/faraday-honeycomb
|
spec/middleware/middleware_spec.rb
|
<reponame>honeycombio/faraday-honeycomb<filename>spec/middleware/middleware_spec.rb
require 'faraday-honeycomb'
# Do not require honeycomb-beeline directly as that will auto-install our faraday middleware
require 'honeycomb/client'
require 'honeycomb/span'
require 'timeout'
RSpec.describe Faraday::Honeycomb::Middleware do
it "registers with Faraday::Middleware (to avoid that, require 'faraday/honeycomb/middleware')" do
expect(->{
Faraday.new('http://example.com') do |conn|
conn.use :honeycomb
end
}).to_not raise_error
end
let(:fakehoney) { Libhoney::TestClient.new }
let(:propagated_header) { "" }
let(:faraday) do
Faraday.new('http://example.com') do |conn|
conn.use :honeycomb, client: fakehoney
conn.adapter :test do |stub|
stub.get('/') { [200, {}, 'hello'] }
stub.get('/slow') { raise Timeout::Error, 'too slow' }
end
end
end
let(:emitted_event) do
events = fakehoney.events
expect(events.size).to eq(1)
events[0]
end
describe 'outgoing trace propagation' do
def headers_from_outgoing_request
headers = nil
faraday = Faraday.new('http://example.com') do |conn|
conn.use :honeycomb, client: fakehoney
conn.adapter :test do |stub|
stub.get('/') {|env| headers = env.request_headers; [200, {}, 'hello'] }
end
end
faraday.get '/'
headers
end
context 'when executed in a request that received propagated tracing data' do
let(:incoming_trace_metadata) {
'1;trace_id=d2eb2028-193e-40e9-a2c1-fe0f12a4f2af,parent_id=8618cc79-b9b9-4e08-8804-c954d7db3b64,dataset=custom.dataset,context=eyJ3b3ciOiJzdWNoIG1ldGEifQ=='
}
it 'propagates a trace header containing details from the incoming HTTP request' do
Honeycomb.trace_from_encoded_context(incoming_trace_metadata) do
trace_header = headers_from_outgoing_request.fetch('X-Honeycomb-Trace')
parsed = Honeycomb.decode_trace_context(trace_header)
expect(parsed[:trace_id]).to eq("d2eb2028-193e-40e9-a2c1-fe0f12a4f2af")
expect(parsed[:context]).to include({"wow" => "such meta"})
# TODO: seems honeycomb-beeline does not support the `dataset` keyword?
end
end
it 'propagates the ID of the faraday span as the trace parent_id' do
Honeycomb.trace_from_encoded_context(incoming_trace_metadata) do
trace_header = headers_from_outgoing_request.fetch('X-Honeycomb-Trace')
parsed = Honeycomb.decode_trace_context(trace_header)
expect(parsed[:parent_span_id]).to eq(emitted_event.data['trace.span_id'])
end
end
end
end
describe 'after the client makes a request' do
before do
response = faraday.get '/'
expect(response.status).to eq(200)
end
it 'sends an http_client event' do
expect(emitted_event.data).to include(
'type' => 'http_client',
'name' => 'GET example.com/',
)
end
it 'includes basic request and response fields' do
expect(emitted_event.data).to include(
'request.method' => 'GET',
'request.protocol' => 'http',
'request.host' => 'example.com',
'request.path' => '/',
'response.status_code' => 200,
)
end
it 'records how long the request took' do
expect(emitted_event.data).to include('duration_ms')
expect(emitted_event.data['duration_ms']).to be > 0
end
it 'includes meta fields in the event' do
expect(emitted_event.data).to include(
'meta.package' => 'faraday',
'meta.package_version' => Faraday::VERSION,
)
end
end
describe 'if the client raised an exception' do
before do
expect { faraday.get '/slow' }.to raise_error(Timeout::Error)
end
it 'records exception details' do
expect(emitted_event.data).to include(
'request.error' => 'Timeout::Error',
'request.error_detail' => 'too slow',
)
end
it 'still records how long the request took' do
expect(emitted_event.data).to include('duration_ms')
expect(emitted_event.data['duration_ms']).to be_a Numeric
end
end
end
|
honeycombio/faraday-honeycomb
|
lib/faraday/honeycomb/middleware.rb
|
require 'faraday'
require 'libhoney'
require 'securerandom'
require 'faraday/honeycomb/version'
module Faraday
module Honeycomb
USER_AGENT_SUFFIX = "#{GEM_NAME}/#{VERSION}"
class Middleware
def initialize(app, client: nil, logger: nil)
@logger = logger
@logger ||= ::Honeycomb.logger if defined?(::Honeycomb.logger)
honeycomb = if client
debug "initialized with #{client.class.name} via :client option"
client
elsif defined?(::Honeycomb.client)
debug "initialized with #{::Honeycomb.client.class.name} from honeycomb-beeline"
::Honeycomb.client
else
debug "initializing new Libhoney::Client"
Libhoney::Client.new(options.merge(user_agent_addition: USER_AGENT_SUFFIX))
end
@builder = honeycomb.builder.
add(
'type' => 'http_client',
'meta.package' => 'faraday',
'meta.package_version' => Faraday::VERSION,
)
@app = app
end
def call(env)
event = @builder.event
add_request_fields(event, env)
start = Time.now
response = with_tracing_if_available(event, env) do
@app.call(env)
end
add_response_fields(event, response)
response
rescue Exception => e
if event
event.add_field 'request.error', e.class.name
event.add_field 'request.error_detail', e.message
end
raise
ensure
if start && event
finish = Time.now
duration = finish - start
event.add_field 'duration_ms', duration * 1000
event.send
end
end
private
def debug(msg)
@logger.debug("#{self.class.name}: #{msg}") if @logger
end
def add_request_fields(event, env)
loud_method = loud_method(env)
event.add(
'name' => "#{loud_method} #{env.url.host}#{env.url.path}",
'request.method' => loud_method,
'request.protocol' => env.url.scheme,
'request.host' => env.url.host,
'request.path' => env.url.path,
)
end
def add_response_fields(event, response)
event.add_field 'response.status_code', response.status
end
def loud_method(env)
env.method.upcase.to_s
end
def with_tracing_if_available(event, env)
# return if we are not using the ruby beeline
return yield unless defined?(::Honeycomb)
# beeline version <= 0.5.0
if ::Honeycomb.respond_to? :trace_id
trace_id = ::Honeycomb.trace_id
event.add_field 'trace.trace_id', trace_id if trace_id
span_id = SecureRandom.uuid
event.add_field 'trace.span_id', span_id
::Honeycomb.with_span_id(span_id) do |parent_span_id|
event.add_field 'trace.parent_id', parent_span_id
yield
end
# beeline version > 0.5.0
elsif ::Honeycomb.respond_to? :span_for_existing_event
::Honeycomb.span_for_existing_event event, name: nil, type: 'http_client' do |span_id, trace_id|
add_trace_context_header(env, trace_id, span_id)
yield
end
# fallback if we don't detect any known beeline tracing methods
else
yield
end
end
def add_trace_context_header(env, trace_id, span_id)
# beeline version > 0.5.0
if ::Honeycomb.respond_to? :encode_trace_context
encoded_context = ::Honeycomb.encode_trace_context(trace_id, span_id, ::Honeycomb.active_trace_context)
env.request_headers['X-Honeycomb-Trace'] = encoded_context
end
end
end
end
end
|
honeycombio/faraday-honeycomb
|
spec/auto_install_spec.rb
|
require 'faraday'
require 'faraday-honeycomb'
require 'faraday-honeycomb/auto_install'
RSpec.describe Faraday::Honeycomb::AutoInstall, auto_install: true do
before(:all) do
Faraday::Honeycomb::AutoInstall.auto_install!(honeycomb_client: Libhoney::TestClient.new)
end
it "standard usage with no block works" do
f = Faraday.new("http://honeycomb.io")
expect(f.builder.handlers).to eq([
Faraday::Request::UrlEncoded,
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
it "providing a builder with string key works" do
stack = Faraday::RackBuilder.new do |builder|
builder.request :retry
builder.adapter Faraday.default_adapter
end
f = Faraday.new("builder" => stack)
expect(f.builder.handlers).to eq([
Faraday::Request::Retry,
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
it "providing a builder with symbol key works" do
stack = Faraday::RackBuilder.new do |builder|
builder.request :retry
builder.adapter Faraday.default_adapter
end
f = Faraday.new(builder: stack)
expect(f.builder.handlers).to eq([
Faraday::Request::Retry,
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
it "providing a builder that only has an adapter works" do
stack = Faraday::RackBuilder.new do |builder|
builder.adapter Faraday.default_adapter
end
f = Faraday.new(builder: stack)
expect(f.builder.handlers).to eq([
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
it "providing a builder AND url works" do
stack = Faraday::RackBuilder.new do |builder|
builder.request :retry
builder.adapter Faraday.default_adapter
end
f = Faraday.new("https://example.com", builder: stack)
expect(f.builder.handlers).to eq([
Faraday::Request::Retry,
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
it "does not attempt to add honeycomb middleware if it already exists in the passed builder" do
stack = Faraday::RackBuilder.new do |builder|
builder.adapter Faraday.default_adapter
end
f = Faraday.new(builder: stack)
# force the builder to lock the middleware stack
f.builder.app
expect(f.builder.handlers).to eq([Faraday::Honeycomb::Middleware, Faraday::Adapter::NetHttp])
f2 = Faraday.new(builder: stack)
# force the builder to lock the middleware stack
f2.builder.app
expect(f2.builder.handlers).to eq([Faraday::Honeycomb::Middleware, Faraday::Adapter::NetHttp])
end
it "providing a builder and a block works" do
stack = Faraday::RackBuilder.new do |builder|
builder.response :logger
end
f = Faraday.new(builder: stack) do |faraday|
faraday.request :url_encoded
faraday.adapter Faraday.default_adapter
end
expect(f.builder.handlers).to eq([
Faraday::Response::Logger,
Faraday::Request::UrlEncoded,
Faraday::Honeycomb::Middleware,
Faraday::Adapter::NetHttp
])
end
end
|
honeycombio/faraday-honeycomb
|
lib/faraday-honeycomb.rb
|
<reponame>honeycombio/faraday-honeycomb
require 'faraday/honeycomb/version'
begin
gem 'faraday', ">= #{Faraday::Honeycomb::MIN_FARADAY_VERSION}"
require 'faraday/honeycomb'
rescue Gem::LoadError
warn 'Faraday not detected, not enabling faraday-honeycomb'
end
|
honeycombio/faraday-honeycomb
|
lib/faraday-honeycomb/auto_install.rb
|
require 'faraday/honeycomb/version'
module Faraday
module Honeycomb
module AutoInstall
class << self
def available?(logger: nil)
constraint = ">= #{::Faraday::Honeycomb::MIN_FARADAY_VERSION}"
gem 'faraday', constraint
logger.debug "#{self.name}: detected Faraday #{constraint}, okay to autoinitialise" if logger
true
rescue Gem::LoadError => e
logger.debug "Didn't detect Faraday #{constraint} (#{e.class}: #{e.message}), not autoinitialising faraday-honeycomb" if logger
false
end
def ensure_middleware_in_builder!(builder, client, logger)
if builder.handlers.any? { |m| m.klass == ::Faraday::Honeycomb::Middleware }
logger.debug "Faraday::Honeycomb::Middleware already exists in Faraday middleware" if logger
return
end
# In faraday < 1.0 the adapter is added directly to handlers, so we
# need to find it in the stack and insert honeycomb's middleware
# before it
#
# In faraday >= 1.0 the adapter will never be in the list of
# handlers, and will _always_ be the last thing called in the
# middleware stack, so we need to handle it not being present.
# https://github.com/lostisland/faraday/pull/750
index_of_first_adapter = (builder.handlers || [])
.find_index { |h| h.klass.ancestors.include? Faraday::Adapter }
if index_of_first_adapter
logger.debug "Adding Faraday::Honeycomb::Middleware before adapter" if logger
builder.insert_before(
index_of_first_adapter,
Faraday::Honeycomb::Middleware,
client: client, logger: logger
)
else
logger.debug "Appending Faraday::Honeycomb::Middleware to stack" if logger
builder.use Faraday::Honeycomb::Middleware, client: client, logger: logger
end
end
def auto_install!(honeycomb_client:, logger: nil)
require 'faraday'
require 'faraday-honeycomb'
Faraday::Connection.extend(Module.new do
define_method :new do |*args, &orig_block|
# If there are two arguments the first argument might be an
# options hash, or a URL. The last argument in the array is
# always an instance of `ConnectionOptions`.
options = args.reduce({}) do |out, arg|
out.merge!(arg.to_hash) if arg.respond_to? :to_hash
out
end
builder = options["builder"] || options[:builder]
if !builder
# This is the configuration that would be applied if someone
# created faraday without a config block/builder. We need to specify it
# here because our monkeypatch causes a block to _always_ be
# passed to Faraday
# https://github.com/lostisland/faraday/blob/v0.15.4/lib/faraday/rack_builder.rb#L56-L60
orig_block ||= proc do |c|
c.request :url_encoded
c.adapter Faraday.default_adapter
end
end
# Always add honeycomb middleware after the middleware stack has
# been resolved by the original block/any defaults that are
# applied by Faraday
block = proc do |b|
orig_block.call(b) if orig_block
Honeycomb::AutoInstall.ensure_middleware_in_builder!(b.builder, honeycomb_client, logger)
end
super(*args, &block)
end
end)
end
end
end
end
end
|
UAlbertaALTLab/homebrew-hfst
|
Formula/hfst.rb
|
class Hfst < Formula
desc "Helsinki Finite-State Technology (library and application suite)"
homepage "https://hfst.github.io/"
url "https://github.com/hfst/hfst/releases/download/v3.15.2/hfst-3.15.2.tar.gz"
sha256 "7e28c6aa2796549b93f5e8aee7ca187716df17b9e687718d4ebf9817d214059d"
depends_on "readline" => :recommended
def install
readline = if build.with?("readline")
['--with-readline']
else
['--without-readline']
end
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
*readline,
"--prefix=#{prefix}"
system "make", "install"
end
test do
# Create a very simple transducer and enumerate its strings
expected = "test\ntests\ntested\ntesting\n"
(testpath / "test.regexp").write "test[0|s|ed|ing]"
system (bin / "hfst-regexp2fst"), (testpath / "test.regexp"), "-o", (testpath / "test.hfst")
assert_equal expected, shell_output("#{bin}/hfst-fst2strings #{testpath}/test.hfst")
end
end
|
infrablocks/terraform-aws-assumable-roles-policy
|
spec/policy_spec.rb
|
<filename>spec/policy_spec.rb
require 'spec_helper'
describe 'assumable roles policy' do
let(:policy_name) { vars.policy_name }
let(:policy_description) { vars.policy_description }
let(:policy_arn) { output_for(:harness, 'policy_arn') }
let(:target_role_arn) { output_for(:harness, 'target_role_arn') }
let(:test_role_1_arn) { output_for(:prerequisites, 'test_role_1_arn') }
let(:test_role_2_arn) { output_for(:prerequisites, 'test_role_2_arn') }
let(:test_role_3_arn) { output_for(:prerequisites, 'test_role_3_arn') }
let(:assumable_roles) {
[test_role_1_arn, test_role_2_arn, test_role_3_arn]
}
subject {
iam_policy(policy_name)
}
it { should exist }
its(:arn) { should eq(policy_arn) }
let(:target_role) {
iam_role(target_role_arn)
}
it 'should allow all assumable roles to be assumed' do
assumable_roles.each do |role|
expect(target_role)
.to(be_allowed_action('sts:AssumeRole')
.resource_arn(role))
end
end
end
|
kostya/modest
|
bench/test-libxml.rb
|
<filename>bench/test-libxml.rb
require "bundler/setup"
require "nokogiri"
page = File.read("./google.html")
s = 0
links = []
1000.times do
doc = Nokogiri::HTML(page)
links = doc.css("div.g h3.r a").map { |link| link["href"] }
s += links.size
end
p links.last
p s
|
adz/quickets
|
lib/quickets.rb
|
<filename>lib/quickets.rb
require "roda"
require "pathname"
require "quickets/version"
require "quickets/config"
require "quickets/logger"
require "quickets/ticket_printer"
require "quickets/available_printers"
# Config
$quickets_dir = Pathname.new(
if ENV['QUICKETS_DIR'].nil? || ENV['QUICKETS_DIR'] == ""
Quickets.logger.warn "No QUICKETS_DIR set, using /quickets"
"/quickets"
else
ENV['QUICKETS_DIR']
end
)
Quickets.configure($quickets_dir.join("quickets.yml"))
module Quickets
class App < Roda
plugin :json_parser # request parse
plugin :json # response to_json
plugin :error_handler
route do |r|
r.root do
"Quickets #{Quickets::VERSION}"
end
r.on 'favicon.ico' do
nil
end
r.on do
Quickets.config.check_api_key!(r['api_key'])
r.on 'printers' do
AvailablePrinters.all(r['api_key'])
end
r.post "print-tickets" do
ticket_printer = TicketPrinter.new(r.params)
if ticket_printer.can_print?
Thread.new { ticket_printer.print }
{status: 'ok'}
else
response.status = 500
{error: "Unknown printer: [#{ticket_printer.printer_name}]"}
end
end
r.on 'config' do
Quickets.configure($quickets_dir.join("quickets.yml"))
printers = Quickets.config.printers_for(r['api_key'])
installed = AvailablePrinters.installed_printers
"<h1>Reloaded config</h1>
<h3>Config for Api Key supplied</h3>
#{printers.map{ |printer_name|
printer_name + "#{' <b>NOT INSTALLED</b>' unless installed.include? printer_name}"
}.join("<br/>")}
"
end
end
end
error do |e|
Quickets.logger.error e
{ error: e.message }
end
end
end
|
adz/quickets
|
lib/quickets/logger.rb
|
require 'logger'
module Quickets
def self.logger
@logger ||= Logger.new($stdout).tap do |log|
log.progname = 'quickets'
end
end
end
|
adz/quickets
|
config.ru
|
#!/usr/bin/env ruby
# Add lib path
require 'pathname'
Pathname.new(__FILE__).dirname.join('lib').tap {|lib_dir|
$:.unshift(lib_dir) unless $:.include?(lib_dir)
}
require "bundler/setup"
require "rack/cors"
require "quickets"
use Rack::Cors do
allow do
origins '*'
resource '/*', :headers => :any, :methods => [:get, :post, :options]
end
end
run Quickets::App.freeze.app
|
adz/quickets
|
lib/quickets/config.rb
|
<reponame>adz/quickets<gh_stars>0
require 'yaml'
module Quickets
def self.configure(file_name)
@config = Config.new(YAML.load_file(file_name))
end
def self.config
@config
end
class Config
def initialize(printers_by_api_key)
@printers_by_api_key = printers_by_api_key
end
def check_api_key!(api_key)
return if valid_api_key? api_key
fail ArgumentError, 'Invalid API key'
end
def valid_api_key?(api_key)
@printers_by_api_key.key? api_key
end
def printers_for(api_key)
@printers_by_api_key.fetch(api_key)
end
end
end
|
adz/quickets
|
lib/quickets/available_printers.rb
|
<reponame>adz/quickets<filename>lib/quickets/available_printers.rb
# Interface to java lib
require "java"
require "jars/ticket_printer-1.2.0-jar-with-dependencies.jar"
java_import com.quicktravel.ticket_printer.PrintServiceLocator
module Quickets
class AvailablePrinters
def self.all(api_key)
# Return only printers configured AND installed
# ...and retain ordering as defined in config
Quickets.config.printers_for(api_key) & installed_printers
end
def self.installed_printers
PrintServiceLocator.new.all.map(&:name)
end
end
end
|
adz/quickets
|
lib/quickets/ticket_printer.rb
|
<reponame>adz/quickets
# Interface to java lib
require "java"
require "jars/ticket_printer-1.2.0-jar-with-dependencies.jar"
java_import com.quicktravel.ticket_printer.TicketPrintCommand
require 'quickets/available_printers'
module Quickets
class TicketPrinter
attr_reader :printer_name
def initialize(params)
@api_key = params.fetch('api_key')
@printer_name = params.fetch('printer_name')
@page_format = params.fetch('page_format')
@tickets = params.fetch('tickets')
end
def can_print?
AvailablePrinters.all(@api_key).include? @printer_name
end
def print
ticket_print_command = TicketPrintCommand.new
ticket_print_command.printer_name = @printer_name
ticket_print_command.ticket_page_settings_from_map = @page_format
ticket_print_command.tickets_from_data_list = @tickets
Thread.new do
ticket_print_command.execute
end
end
end
end
|
MountainCode/jruby-velocity
|
spec/file_velocity_launcher_spec.rb
|
require 'velocity'
describe Velocity::FileVelocityLauncher do
let(:launcher) { Velocity::FileVelocityLauncher.new 'spec/resources' }
subject { launcher }
it 'should merge a template from a velocity file' do
context = {
'host' => 'Cardinal Fang',
'weapons' => ['Fear', 'Surprise', 'Ruthless Efficiency']
}
subject.merge(context, 'template.vm').should eq "- Fear\n- Surprise\n- Ruthless Efficiency\n"
end
it 'should merge a template from a file in a subdirectory' do
context = {
'title' => 'Nobody Expects Us!',
:host => 'Cardinal Fang',
'weapons' => ['Fear', 'Surprise', 'Ruthless Efficiency']
}
merged = subject.merge(context, 'html/template.html')
merged.should include '<h1>Cardinal Fang</h1>'
merged.should include '<title>Nobody Expects Us!</title>'
merged.should include '<li>Fear</li>'
merged.should include '<li>Surprise</li>'
merged.should include '<li>Ruthless Efficiency</li>'
end
it 'should merge a template with a list of objects' do
class Listing
attr_accessor :listing_number, :description
end
l = Listing.new
l.listing_number = 'ABC123'
l.description = 'A description'
context = {
:listings => [l]
}
merged = subject.merge context, 'html/listings.html'
merged.should include 'description: A description'
end
end
|
MountainCode/jruby-velocity
|
lib/velocity/mysql_data_source.rb
|
<filename>lib/velocity/mysql_data_source.rb
java_import 'javax.sql.DataSource'
java_import 'java.sql.DriverManager'
java_import 'com.mysql.jdbc.Driver' # We need to load the Driver class even though we don't explicitly use it.
class MySqlDataSource
include DataSource
def initialize url, user, password
@url = url
@user = user
@password = password
end
def getConnection
return DriverManager.getConnection(@url, @user, @password)
end
end
|
MountainCode/jruby-velocity
|
lib/velocity.rb
|
<gh_stars>0
require 'java'
require 'velocity/velocity_launcher'
require 'velocity/mysql_data_source'
require 'velocity/file_velocity_launcher'
require 'velocity/mysql_velocity_launcher'
require 'velocity/hash_converter'
require 'velocity/version'
|
MountainCode/jruby-velocity
|
spec/mysql_velocity_launcher_spec.rb
|
<reponame>MountainCode/jruby-velocity<gh_stars>0
require 'yaml'
require 'velocity'
describe Velocity::MySqlVelocityLauncher do
let(:launcher) { Velocity::MySqlVelocityLauncher.new YAML.load_file('spec/resources/sql_connection.yaml') }
subject { launcher }
it 'should merge a template from a database table' do
context = {
'host' => 'Cardinal Fang',
'weapons' => ['Fear', 'Surprise', 'Ruthless Efficiency']
}
subject.merge(context, 'template.vm').should eq "- Fear\n- Surprise\n- Ruthless Efficiency\n"
end
end
|
MountainCode/jruby-velocity
|
spec/hash_converter_spec.rb
|
require 'velocity'
class Person
attr_accessor :name, :address
end
class Address
attr_accessor :city, :state, :zip
end
describe Velocity::HashConverter do
describe 'when object is converted to hash' do
converter = Velocity::HashConverter.new
person = Person.new
person.name = 'Chris'
person.address = Address.new
person.address.city = 'Londonderry'
person.address.state = 'VT'
person.address.zip = '05148'
hash = converter.to_hash person
it 'should convert an object to a hash' do
hash['name'].should eq 'Chris'
end
it 'should convert all child objects to hashes' do
hash['address'].is_a?(Hash).should be_true
end
end
describe 'when a hash contains an object' do
converter = Velocity::HashConverter.new
person = Person.new
person.name = 'Chris'
outer_hash = { 'person' => person }
converted = converter.to_hash(outer_hash)
it 'should convert objects to a hash' do
converted['person'].is_a?(Hash).should be_true
end
it 'inner hashes should have correct values' do
converted['person']['name'].should eq 'Chris'
end
end
describe 'when a hash contains an array of objects' do
converter = Velocity::HashConverter.new
person = Person.new
person.name = 'Chris'
outer_hash = { 'people' => [person] }
converted = converter.to_hash outer_hash
it 'should convert objects inside lists to hashes' do
converted['people'][0].is_a?(Hash).should be_true
end
end
describe 'when a hash uses symbols as keys' do
converter = Velocity::HashConverter.new
context = { :name => 'Bob' }
converted = converter.to_hash context
it 'should convert the keys to strings' do
converted.should have_key 'name'
end
end
end
|
MountainCode/jruby-velocity
|
lib/velocity/file_velocity_launcher.rb
|
module Velocity
class FileVelocityLauncher
include VelocityLauncher
def initialize template_dir
init({
'resource.loader' => 'file',
'file.resource.loader.path' => template_dir
})
end
end
end
|
MountainCode/jruby-velocity
|
lib/velocity/mysql_velocity_launcher.rb
|
<gh_stars>0
java_import 'org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader'
module Velocity
class MySqlVelocityLauncher
include VelocityLauncher
def initialize connection
loader = DataSourceResourceLoader.new
loader.setDataSource(MySqlDataSource.new "jdbc:mysql://#{connection['server']}/#{connection['database']}",
connection['username'], connection['password'])
init({
'resource.loader' => 'ds',
'ds.resource.loader.instance' => loader,
'ds.resource.loader.public.name' => 'DataSource',
'ds.resource.loader.description' => 'Velocity DataSource Resource Loader',
'ds.resource.loader.class' => DataSourceResourceLoader.class.name,
'ds.resource.loader.resource.datasource' => 'java:comp/env/jdbc/Velocity',
'ds.resource.loader.resource.table' => 'templates',
'ds.resource.loader.resource.keycolumn' => 'id',
'ds.resource.loader.resource.templatecolumn' => 'body',
'ds.resource.loader.resource.timestampcolumn' => 'lastModified'
})
end
end
end
|
MountainCode/jruby-velocity
|
lib/velocity/hash_converter.rb
|
module Velocity
class HashConverter
def to_hash obj
hash = {}
if(obj.is_a? Hash)
string_key_hash = {}
obj.each do |key, value|
string_key_hash[key.to_s] = to_hash value
end
string_key_hash
elsif obj.is_a? Array
obj.each_with_index { |item, i| obj[i] = to_hash item }
elsif 0 == obj.instance_variables.length
obj
else
obj.instance_variables.each do |var|
hash[var.to_s.delete '@'] = to_hash(obj.instance_variable_get var)
end
hash
end
end
end
end
|
MountainCode/jruby-velocity
|
lib/velocity/velocity_launcher.rb
|
<filename>lib/velocity/velocity_launcher.rb<gh_stars>0
module Velocity
module VelocityLauncher
java_import 'org.apache.velocity.app.Velocity'
java_import 'org.apache.velocity.app.VelocityEngine'
java_import 'org.apache.velocity.VelocityContext'
java_import 'java.io.StringWriter'
java_import 'org.apache.velocity.runtime.RuntimeSingleton'
def init properties
@ve = VelocityEngine.new
properties.each do |key, value|
@ve.setProperty key, value
end
@ve.init
end
def merge context, template
vc = VelocityContext.new(hash_converter.to_hash context)
writer = StringWriter.new
t = @ve.getTemplate template
t.merge(vc, writer)
return writer.getBuffer.toString
end
private
def hash_converter
HashConverter.new
end
end
end
|
andrewjkerr/ufid_parser
|
spec/spec_helper.rb
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'ufid_parser'
|
andrewjkerr/ufid_parser
|
spec/ufid_parser_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe UfidParser do
it 'has a version number' do
expect(UfidParser::VERSION).not_to be nil
end
describe 'with a valid UFID number' do
before { @expected = '12345678' }
describe 'and the two UFID numbers match up' do
@arr = [';200123456780220012345678020?', ';200123456780120012345678010?']
describe 'with 02200 as the separator' do
before { @input = ';200123456780220012345678020?' }
it 'correctly returns the UFID number' do
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
end
describe 'with 01200 as the separator' do
before { @input = ';200123456780120012345678010?' }
it 'correctly returns the UFID number' do
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
end
end
describe 'and one UFID number is correct while the other is malformatted' do
describe 'with 02200 as the separator' do
it 'correctly returns the first UFID number' do
@input = ';20012345678022001234568020?'
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
it 'correctly returns the last UFID number' do
@input = ';20012345680220012345678020?'
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
end
describe 'with 01200 as the separator' do
it 'correctly returns the first UFID number' do
@input = ';20012345678012001234568010?'
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
it 'correctly returns the last UFID number' do
@input = ';20012345680120012345678010?'
expect(UfidParser::UFID.new(@input).ufid_number).to eq(@expected)
end
end
end
end
describe 'without a valid UFID number' do
describe 'and both UFID numbers are not 8 characters' do
describe 'and the same length' do
it 'throws an exception' do
@input = ';2001234568022001234568020?'
expect {
UfidParser::UFID.new(@input).ufid_number
}.to raise_error(Exception)
end
end
describe 'and not the same length' do
it 'throws an exception' do
@input = ';200123458022001234568020?'
expect {
UfidParser::UFID.new(@input).ufid_number
}.to raise_error(Exception)
end
end
end
end
end
|
andrewjkerr/ufid_parser
|
lib/ufid_parser.rb
|
<gh_stars>0
require "ufid_parser/version"
module UfidParser
class UFID
attr_accessor :ufid_number
def initialize(str)
@ufid_number = parse_ufid_number(str)
end
private
def parse_ufid_number(str)
splitter = [] << str[1]
splitter << str[-3]
splitter_str = "0#{splitter.reverse.join('')}00"
# Barcode has two occurrances of UFID number separated by this string
ufid_number_arr = str.split(splitter_str)
# Cut out the junk
ufid_number_arr[0] = ufid_number_arr.first[4..-1]
ufid_number_arr[-1] = ufid_number_arr.last[0..-5]
# Check out requirement for UFID numbers
if meet_ufid_number_requirements?(ufid_number_arr)
return ufid_special_case(ufid_number_arr)
end
# Return the number!
ufid_number_arr.first
end
def ufid_special_case(ufid_number_arr)
# Return the one that has
if ufid_number_arr.first.size == ufid_number_arr.last.size
raise Exception.new("Malformatted UFID input.")
elsif ufid_number_arr.first.size == 8
ufid_number_arr.first
elsif ufid_number_arr.last.size == 8
ufid_number_arr.last
else
raise Exception.new("Malformatted UFID input.")
end
end
def meet_ufid_number_requirements?(ufid_number_arr)
ufid_number_arr.first != ufid_number_arr.last || ufid_number_correct_size?(ufid_number_arr)
end
def ufid_number_correct_size?(ufid_number_arr)
ufid_number_arr.first.size != 8 || ufid_number_arr.last.size != 8
end
end
end
|
ritabc/numbers-to-words
|
spec/number_to_words_spec.rb
|
<filename>spec/number_to_words_spec.rb
require 'rspec'
require 'number_to_words'
require 'pry'
describe ("NumberToWords#translate") do
it "will take the number 2 and return the word two" do
number = NumberToWords.new(2)
expect(number.translate()).to(eq('two'))
end
it "will take the number 11 and return eleven" do
number = NumberToWords.new(11)
expect(number.translate()).to(eq("eleven"))
end
it "will take the number 21 and return twenty one" do
number = NumberToWords.new(21)
expect(number.translate()).to(eq("twenty one"))
end
it "will take the number 97 and return ninety seven" do
number = NumberToWords.new(97)
expect(number.translate()).to(eq("ninety seven"))
end
it "will take the number 100 and return one hundred" do
number = NumberToWords.new(123)
expect(number.translate()).to(eq("one hundred twenty three"))
end
it "will take the number 100 and return one hundred" do
number = NumberToWords.new(100)
expect(number.translate()).to(eq("one hundred"))
end
it "will take the number 867 and return eight hundred sixty seven" do
number = NumberToWords.new(867)
expect(number.translate()).to(eq("eight hundred sixty seven"))
end
it "will take the number 4687 and return four thousand six hundred eighty seven" do
number = NumberToWords.new(4687)
expect(number.translate()).to(eq("four thousand six hundred eighty seven"))
end
it "will take the number 20,687 and return twenty thousand six hundred eighty seven" do
number = NumberToWords.new(20687)
expect(number.translate()).to(eq("twenty thousand six hundred eighty seven"))
end
it "will take the number 14,687 and return twenty thousand six hundred eighty seven" do
number = NumberToWords.new(99687)
expect(number.translate()).to(eq("ninety nine thousand six hundred eighty seven"))
end
end
|
ritabc/numbers-to-words
|
lib/number_to_words.rb
|
<reponame>ritabc/numbers-to-words<filename>lib/number_to_words.rb
class NumberToWords
def initialize(number)
@number = number
end
def translate()
ones_and_teens = {0 => "", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten", 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen'}
tens = {0 => nil, 1 => "ten", 2 => "twenty", 3 => "thirty", 4 => "forty", 5 => "fifty", 6 => "sixty", 7 => "seventy", 8 => "eighty", 9 => "ninety"}
base_ten = {3 => "hundred", 4 => "thousand", 5 => "thousand", 6 => "hundred thousand", 7 => "million", 8 => "million", 9 => "hundred million"}
backwards_number_array = @number.to_s().split('').reverse()
number_of_digits = backwards_number_array.length()
word_elements = []
i = 0
backwards_number_array.each do |digit|
if i == 4
if ((backwards_number_array[4] + backwards_number_array[3]).to_i()) <= 19
word_elements.pop()
word_elements.push(ones_and_teens.fetch((backwards_number_array[4] + backwards_number_array[3]).to_i()))
elsif ((backwards_number_array[4] + backwards_number_array[3]).to_i()) > 19
word_elements.pop()
word_elements.push(ones_and_teens.fetch(backwards_number_array[3].to_i()))
word_elements.push(tens.fetch(backwards_number_array[4].to_i()))
end
i = i + 1
elsif i == 3
word_elements.push(base_ten.fetch(i + 1))
word_elements.push(ones_and_teens.fetch(digit.to_i()))
i = i + 1
elsif i == 2
word_elements.push(base_ten.fetch(i + 1))
word_elements.push(ones_and_teens.fetch(digit.to_i()))
i = i + 1
elsif i == 1
if ((backwards_number_array[1] + backwards_number_array[0]).to_i()) <= 19
word_elements.pop()
word_elements.push(ones_and_teens.fetch((backwards_number_array[0] + backwards_number_array[1]).to_i()))
else
word_elements.pop()
word_elements.push(ones_and_teens.fetch(backwards_number_array[0].to_i()))
word_elements.push(tens.fetch(backwards_number_array[1].to_i()))
end
i = i + 1
else
word_elements.push(ones_and_teens.fetch(digit.to_i()))
i = i + 1
end
end
word_elements.reverse().join(" ").split(" ").join(" ").rstrip()
end
end
|
rayvaldez/fi-player-tracker
|
app/models/player.rb
|
class Player < ActiveRecord::Base
belongs_to :user
validates :name, :team, :cost, :quantity, :presence => true
end
|
rayvaldez/fi-player-tracker
|
app/models/user.rb
|
<reponame>rayvaldez/fi-player-tracker<filename>app/models/user.rb
class User < ActiveRecord::Base
has_many :player
has_secure_password
validates :username, :email, :uniqueness => true
validates :username, :email, :presence => true
end
|
rayvaldez/fi-player-tracker
|
app/controllers/application_controller.rb
|
require './config/environment'
require 'rack-flash'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "football_index"
use Rack::Flash
end
helpers do
def current_user
@user = User.find_by_id(session[:user_id])
end
def logged_in?
session[:user_id]
end
def login(email, password)
user = User.find_by(email: params["email"])
if user && user.authenticate(password)
session[:user_id] = user.id
redirect '/players'
else
flash[:message] = "Please provide a valid email/password combination."
erb :'/users/login'
end
end
end
get "/" do
if logged_in?
redirect '/players'
else
erb :index
end
end
end
|
rayvaldez/fi-player-tracker
|
app/controllers/players_controller.rb
|
<reponame>rayvaldez/fi-player-tracker<filename>app/controllers/players_controller.rb<gh_stars>0
class PlayersController < ApplicationController
get '/players' do
if logged_in?
@player_array = []
Player.all.each do |player|
if player.user_id == current_user.id
@player_array << player
end
end
erb :'/players/players'
else
redirect '/login'
end
end
get '/players/new' do
if logged_in?
@player = Player.new
erb :'/players/new'
else
redirect '/login'
end
end
post '/players' do
@player = Player.new(:name => params[:name], :team => params[:team], :cost => params[:cost], :quantity => params[:quantity])
if @player.valid?
@player.user_id = current_user.id
@player.save
redirect "/players/#{@player.id}"
else
erb :'/players/new'
end
end
get '/players/:id' do
if logged_in?
@player = Player.find(params[:id])
if @player.user_id == current_user.id
erb :'/players/show'
else
redirect '/players'
end
else
redirect '/login'
end
end
delete '/players/:id/delete' do
@player = Player.find_by_id(params[:id])
@player.destroy
redirect '/players'
end
get '/players/:id/edit' do
if logged_in?
@player = Player.find_by_id(params[:id])
if @player.user_id == current_user.id
erb :'/players/edit'
else
redirect '/players'
end
else
redirect '/login'
end
end
patch '/players/:id' do
@player = Player.find_by_id(params[:id])
@player.team = params[:team]
@player.cost = params[:cost]
@player.quantity = params[:quantity]
if @player.valid?
@player.save
redirect to "/players/#{@player.id}"
else
erb :'players/edit'
end
end
end
|
ookam/rangrok
|
rangrok.gemspec
|
$:.push File.expand_path("lib", __dir__)
# Maintain your gem's version:
require "rangrok/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |spec|
spec.name = "rangrok"
spec.version = Rangrok::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.homepage = "https://github.com/haruelico/rangrok"
spec.summary = "Add '.ngrok.io' to Rails.application.config.hosts in development environment."
spec.description = "Add '.ngrok.io' to Rails.application.config.hosts in development environment."
spec.license = "MIT"
spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
spec.add_dependency "rails", ">= 6.0.0"
spec.add_development_dependency "sqlite3"
end
|
ookam/rangrok
|
lib/rangrok/railtie.rb
|
module Rangrok
class Railtie < ::Rails::Railtie
initializer 'rangrok_add_ngrok_to_allowed_hosts' do
Rails.application.config.hosts << ".ngrok.io" if Rails.env.development?
end
initializer 'rangrok_add_localtunnel_to_allowed_hosts' do
Rails.application.config.hosts << ".localtunnel.me" if Rails.env.development?
end
initializer 'rangrok_add_serveo_to_allowed_hosts' do
Rails.application.config.hosts << ".serveo.net" if Rails.env.development?
end
initializer 'rangrok_add_tunnelto_to_allowed_hosts' do
Rails.application.config.hosts << ".tunnelto.dev" if Rails.env.development?
end
end
end
|
ookam/rangrok
|
test/rangrok_test.rb
|
require 'test_helper'
class Rangrok::Test < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, Rangrok
end
test 'allow request from "*.ngrok.io"' do
assert_includes Rails.application.config.hosts, ".ngrok.io"
end
test 'allow request from "*.localtunnel.me"' do
assert_includes Rails.application.config.hosts, ".localtunnel.me"
end
test 'allow request from "*.serveo.net"' do
assert_includes Rails.application.config.hosts, ".serveo.net"
end
test 'allow request from "*.tunnelto.dev"' do
assert_includes Rails.application.config.hosts, ".tunnelto.dev"
end
end
|
ookam/rangrok
|
lib/rangrok.rb
|
<filename>lib/rangrok.rb
require "rangrok/railtie"
module Rangrok
# Your code goes here...
end
|
ctrlok/opsworks-example-cookbooks
|
secrets_test/recipes/store.rb
|
#
# Cookbook Name:: secrets_test
# Recipe:: store
#
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
chef_gem 'aws-sdk'
ruby_block 'read_secrets' do
block do
require 'json'
require 'aws-sdk'
client = Aws::SecretsManager::Client.new(region: 'us-east-1')
resp = client.get_secret_value({secret_id: node[:env]+'-SERVICE'})
node.default['password'] = JSON.parse(resp.secret_string)
end
action :run
end
file '/tmp/passwords' do
content lazy{"passwords: #{node['password']}"}
mode '0700'
end
|
NessInMorse/Learn_Morse_WordsTEXT
|
Morse_game.rb
|
require "path/to/alle_woorden.rb"
include Words
require 'curses'
input=""
rawinput=""
rawtime=[]
c=0
time= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
count= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
line_c=0
inter_c=0
time0=0
time1=0
lettertimes=""
File.open("path/to/Letter_graph.txt","r+") do |data|
for line in data.readlines()
if line_c==0
line.tr("[]","")
if line.index(",")!=nil
line.split(",").each do |z|
count[inter_c]=z.to_i
inter_c+=1
end
end
end
if line_c==1
line.tr("[]","")
if line.index(",")!=nil
line.split(",").each do |z|
time[inter_c]=z.to_i
inter_c+=1
end
end
end
line_c+=1
inter_c=0
end
end
loadtime_a=0
loadtime_b=0
loadtime_a=Time.now
length=Words.Dictionary.length
random=rand(length)
dictionary=Words.Dictionary
morsedictionary=Words.MorseDictionary
response=""
ask=morsedictionary[random]
answer=dictionary[random]
loadtime_b=Time.now
yes_no=""
begintime=0
endtime=0
input=0
racenumber=0
morselength=0
File.open("path/to/Races.csv","r") do |data|
for line in data.readlines()
racenumber+=1
end
end
puts "Are you ready?"
pineapple=gets.chomp()
def GoSleep(time)
sleep(time)
end
while response !="n"
puts "\nrace starts in 2 seconds"
sleep(1)
puts "race starts in 1 second"
sleep(1)
Curses.init_screen
begin
Curses.addstr("The word you have to translate is: \n")
Curses.addstr("#{ask[1..ask.length]} \n")
begintime=Time.now
while rawinput.index(answer.downcase)==nil
time0=(Time.now.to_f*1000)
input = Curses.getch
unless input.ord<97 || input.ord>122
rawinput+=input
time1=(Time.now.to_f*1000)
rawtime<<(time1-time0)
end
if input.ord==8 && rawinput.length>0
rawinput[rawinput.length-1]=""
end
if response=="n"
break;
end
end
endtime=Time.now
unless rawinput.length != answer.length
while c<answer.length
time[rawinput[rawinput.length-1-c].ord-96] = (time[rawinput[rawinput.length-1-c].ord-96]*count[rawinput[rawinput.length-1-c].ord-96] + rawtime[rawtime.length-1-c])/(count[rawinput[rawinput.length-1-c].ord-96]+1)
count[rawinput[rawinput.length-1-c].ord-96] +=1
c+=1
end
end
c=0
line_c=0
File.open("path/to/Letter_graph.txt","w") do |data|
data.puts count.to_s
data.puts time.to_s
end
File.open("path/to/Races.csv","a") do |data|
data.puts "#{racenumber},#{(answer.length.to_f/5)/( (endtime.to_f-begintime.to_f)/60 ).round(3)},#{answer},#{answer.length},#{begintime},#{ask[1..ask.length].length}"
racenumber+=1
end
Curses.addstr("\nHet duurde #{(endtime.to_f)-(begintime.to_f)} seconden \n")
Curses.addstr("Dat is #{answer.length/(endtime.to_f-begintime.to_f)} tekens per seconde \n")
Curses.addstr("De dat is #{(answer.length.to_f/5)/( (endtime.to_f-begintime.to_f)/60 )} WPM \n")
Curses.addstr("De tijd om het bestand te laden was: #{loadtime_b.to_f-loadtime_a.to_f} seconden \n")
#only in cases where the final string is exactly the same as the requested answer
if answer.length == rawinput.length
while c<answer.length
lettertimes+="[#{answer[c]}|#{rawtime[c]}ms] "
c+=1
end
Curses.addstr("#{lettertimes} \n")
c=0
lettertimes=""
end
if racenumber%100==1
Curses.addstr("You have raced #{racenumber-1} times! \n")
end
Curses.addstr("wanna race again? \n")
while yes_no.index("y")==nil
input=Curses.getch
if input.ord==13 || input.ord==10
yes_no+="y"
end
unless input.ord<97 || input.ord>122 || input.ord==13 || input.ord==10 || input.ord==8
yes_no+=input.downcase
end
if yes_no.index("y")!=nil
loadtime_a=Time.now
random=rand(length)
ask=morsedictionary[random]
answer=dictionary[random]
loadtime_b=Time.now
Curses.clear
end
end
yes_no=""
rawinput=""
rawtime=[]
ensure
Curses.close_screen
end
end
puts length
|
cpuguy83/faye-client
|
lib/faye-client/channel_handlers/default_channel_handler.rb
|
module FayeClient
class DefaultChannelHandler
include Sidekiq::Worker
sidekiq_options :queue => :messaging
def perform(message)
message
end
end
end
|
cpuguy83/faye-client
|
lib/faye-client.rb
|
require 'rubygems'
require 'eventmachine'
require 'Faye' unless defined? Faye
require 'sidekiq'
require 'active_support'
require 'require_all'
require_rel 'faye-client'
|
cpuguy83/faye-client
|
lib/faye-client/faye_client.rb
|
module FayeClient
# extend FayeClient in your class/module to use
# the "start" method spins off the EM instance with the Faye client to it's own thread
# You can access the the client itself or the thread using the class accessor methods "messaging_client" and "messaging_client_thread", respectively
# You must specify a :messaging_server_url and :messaging_channels using the available class accessors
# You should also supply a default_channel_handler_class_name and a default_channel_handler_method or it will default to the built-in handler, which is useless
# Alternatively (or in addition to), you can specify a Hash for your channel which would specify which class/method to use to handler the incoming message
# Example:
#
# module MyClient
# extend FayeClient
# self.messaging_server_url = 'http://myserver/faye'
# self.messaging_channels = ['/foo', '/bar', {name: '/foofoo', handler_class_name: FooFooHandlerClass, handler_method_name: 'foofoo_handler_method' }]
# self.default_channel_handler_class_name = 'MyDefaultHandlerClass'
# self.default_channel_handler_method = 'my_default_handler_method'
# end
#
# MyClient.start
#
# Channels for '/foo' and '/bar' in the above example will use the default class/method combo specified
# Channel '/foofoo' will use the specified class/method, assuming they are defined
attr_accessor :messaging_client, :messaging_client_thread, :messaging_server_url, :messaging_channels
attr_accessor :default_channel_handler_class_name, :default_channel_handler_method
# Start client
# Will need to restart client anytime you want to add more channels
def start
raise "AlreadyRunning" if running?
self.messaging_client_thread = Thread.new do
# Must be run inside EventMachine
EventMachine.run {
# Create the actual Faye client
self.messaging_client = Faye::Client.new(messaging_server_url)
self.messaging_channels.each do |channel|
# Channel Handlers provide customization for how to handle a message
channel_handler = self.get_channel_handler(channel)
raise 'NoChannelNameProvided' if !channel_handler[:name]
self.messaging_client.subscribe(channel_handler[:name]) do |message|
channel_handler[:handler_class_name].send(channel_handler[:handler_method_name], message)
end
end
}
end
end
# Publish a :message to a :channel
def publish(options)
raise 'NoChannelProvided' unless options[:channel]
raise 'NoMessageProvided' unless options[:message]
messaging_client.publish(options[:channel], options[:message])
end
# Stop the running client
def stop
raise "NotRunning" if !running?
self.messaging_client.disconnect
self.messaging_client_thread.kill
end
# Restart the running client
def restart
stop
start
end
# Is the client running?
def running?
if self.messaging_client and self.messaging_client.state == :CONNECTED
true
else
false
end
end
# Set the handler class/method to be used for a given channel
def get_channel_handler(channel)
if channel.is_a? String
parsed_channel_name = channel.gsub(/^\//, '').gsub('/','::')
handler = get_channel_handler_for_string(parsed_channel_name)
handler[:name] = channel
elsif channel.is_a? Hash
# Can provide a Hash to get full customization of handler names/methods
handler = get_channel_handler_for_hash(channel)
handler[:name] = channel[:name]
else
raise TypeError, 'Channel Must be a String or a Hash'
end
handler
end
# If just a string is provided for a channel
def get_channel_handler_for_string(channel)
handler = {}
# Set handler class
handler[:handler_class_name] = get_channel_handler_class_name_for_string(channel)
# Set handler method
handler[:handler_method_name] = get_default_channel_handler_method_name
handler
end
# Build channel handler pointers when hash is provided for channel
def get_channel_handler_for_hash(channel)
handler = {}
if channel[:handler_class_name]
# if class name is provided, then you use it
handler[:handler_class_name] = channel[:handler_class_name]
else
# Get default class ifnone is provided
handler[:handler_class_name] = get_channel_handler_class_name_for_string(channel[:name])
end
if channel[:handler_method_name]
# Get method to use if one is provided
handler[:handler_method_name] = channel[:handler_method_name]
else
# Use default method if none is provided
handler[:handler_method_name] = get_default_channel_handler_method_name
end
return handler
end
def get_channel_handler_class_name_for_string(channel)
# Try to use the channel name to determine the class to use
class_name = "#{self.name}::#{channel.capitalize}Handler"
rescue_counter = 0
begin
class_name = ActiveSupport::Inflector.constantize class_name if class_name.is_a? String
rescue NameError
# If class_name can't be constantized, try to use a default
if self.default_channel_handler_class_name and rescue_counter == 0
# Try to use defined default from class
class_name = self.default_channel_handler_class_name
else
# Use gem default if defined default doesn't work
class_name = "FayeClient::DefaultChannelHandler"
end
rescue_counter += 1
retry if rescue_counter <= 1
raise 'CannotLoadConstant' if rescue_counter > 1
end
return class_name
end
def get_default_channel_handler_method_name
if self.default_channel_handler_method
# Use defined default if available
return self.default_channel_handler_method
else
# By default we are using Sidekiq Workers to handle incoming messages.
# 'perform_async' comes from Sidekiq
return 'perform_async'
end
end
end
|
leenasn/active_admin_auto_select
|
lib/active_admin_auto_select/version.rb
|
<gh_stars>0
module AdminAutoSelect
VERSION = "0.1.12"
end
|
leenasn/active_admin_auto_select
|
active_admin_auto_select.gemspec
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require 'active_admin_auto_select/version'
Gem::Specification.new do |spec|
spec.name = "active_admin_auto_select"
spec.version = AdminAutoSelect::VERSION
spec.authors = ["spyrbri"]
spec.email = ["<EMAIL>"]
spec.summary = %q{This gem helps you select a row of a column in a model with autocomplete in active admin}
spec.description = %q{This gem helps you build nice filters in Activeadmin. It combines Select2, PostgresSQL and Ajax to create an easy to use select field.}
spec.homepage = "https://github.com/spyrbri/active_admin_auto_select"
spec.license = "MIT"
spec.files = `git ls-files`.split("\n")
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_dependency "select2-rails"
spec.add_dependency "underscore-rails"
spec.add_dependency "pg"
end
|
leenasn/active_admin_auto_select
|
lib/active_admin_auto_select.rb
|
require "active_admin_auto_select/version"
require "active_admin_auto_select/rails"
module AutoSelectable
def auto_select(*fields)
options = fields.extract_options!
# The @resource instance variable seems unavailable in versions
# later than 1.0.0.pre1 of the ActiveAdmin.
resource = @resource || self.config.resource_class_name.constantize
create_collection_action(fields, options, resource)
end
def create_collection_action(fields, options, resource)
collection_action :autoselect, method: :get do
# Rails.logger.debug "options #{options}"
select_fields = "id, " << fields.join(", ")
if (Module.const_get(:CanCanCan) rescue false) ? authorized?(:read, resource) : true
term = params[:q].to_s
term.gsub!("%", "\\\%")
term.gsub!("_", "\\\_")
page = params[:page].try(:to_i)
offset = page ? (page - 1) * 10 + (5 * (page - 1)) : 0
effective_scope = options[params[:scope]] ||
options["default_scope"] || -> { resource }
# This param exists when we have a filtered result
if params[:ids].present?
if params[:tags].present?
tags = ActsAsTaggableOn::Tag.where("name IN (?)",
params[:ids].collect do | id |
id.gsub("[", "").gsub("]", "").gsub("\"", "").gsub(",", "")
end
)
resources = tags.collect.each do | tag |
{ id: tag.id, name: tag.name.humanize }
end
else
resources = effective_scope.call.
where("#{resource.table_name}.id IN (?)", params[:ids]).
select(select_fields)
if resources.size == 1
resources = resources.first
else
resources = resources.sort_by { |r| params[:ids].index(r.id.to_s) }
end
end
render json: resources
return
else
concat_fields = fields.join(" || ' '::text || ")
studio = current_admin_user.super_admin? ? Studio.all : current_admin_user.studio
if params[:scope] == "tags"
tags = Customer.where(studio: studio).all_tags.
where("lower(name) ILIKE '%#{term}%' AND name != 'imported'").
select(:id, :name)
.order("name")
resource_records = tags.collect.each do | tag |
{ id: tag.id, name: tag.name.humanize }
end
else
resource_records = effective_scope.call
.select(select_fields)
.where("#{concat_fields} ILIKE :term", term: "%#{term}%")
.where(studio: studio)
.order("name")
.limit(15).offset(offset)
end
render json: resource_records
end
end
end
end
end
ActiveAdmin::ResourceDSL.send :include, AutoSelectable
|
sparkrico/ruby_apk
|
spec/layout_spec.rb
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Android::Layout do
context 'with real apk sample file' do
let(:apk_path){ File.expand_path(File.dirname(__FILE__) + '/data/sample.apk') }
let(:apk){ Android::Apk.new(apk_path) }
let(:layouts) { apk.layouts }
subject { layouts }
it { should be_a Hash }
it { should have_key "res/layout/main.xml" }
it { should have(1).item }
context 'about first item' do
subject { layouts['res/layout/main.xml'] }
it { should be_a Android::Layout }
describe '#path' do
it { subject.path.should eq 'res/layout/main.xml' }
end
describe '#doc' do
it { subject.doc.should be_a REXML::Document }
end
describe '#to_xml' do
it { subject.to_xml.should be_a String }
end
end
end
context 'with real new apk sample file' do
let(:apk_path){ File.expand_path(File.dirname(__FILE__) + '/data/sample_new.apk') }
let(:apk){ Android::Apk.new(apk_path) }
let(:layouts) { apk.layouts }
subject { layouts }
it { should be_a Hash }
it { should have_key "res/layout/activity_main.xml" }
it { should have(1).item }
context 'about first item' do
subject { layouts['res/layout/activity_main.xml'] }
it { should be_a Android::Layout }
end
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_encoding.rb
|
def transcode(string)
string.encode('ISO-8859-1').force_encoding('UTF-8')
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_iteration.rb
|
def count_multibyte_char(string)
number_of_multibyte_chars = 0
string.each_char {|x| number_of_multibyte_chars+=1 if x.bytesize > 1}
number_of_multibyte_chars
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Control Structures/ruby_control_structures-infinite_loop.rb
|
loop do
coder.practice
if coder.oh_one?
break
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Arrays Hashes/ruby_array_initialization.rb
|
array = []
array_1 = [nil]
array_2 = [10, 10]
|
sarvekash/HackerRank_Solutions
|
Ruby/Arrays Hashes/ruby_hash_add_del_sel.rb
|
hackerrank.store(543121, 100)
hackerrank.keep_if {|key, value| key.is_a? Integer}
hackerrank.delete_if{|key, value| key % 2 == 0}
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_procs.rb
|
def square_of_sum (my_array, proc_square, proc_sum)
sum = proc_sum.call(my_array)
proc_square.call(sum)
end
proc_square_number = proc {|number| number**2}
proc_sum_array = proc {|array| array.inject(0){|sum,x| sum + x }}
my_array = gets.split().map(&:to_i)
puts square_of_sum(my_array, proc_square_number, proc_sum_array)
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_introduction.rb
|
<gh_stars>1-10
def single_quote
# single quote string here
'Hello World and others!'
end
def double_quote
# Double quote string here
"Hello World and others!"
end
def here_doc
# Here doc string here
document = <<-HERE
Hello World and others!
HERE
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Control Structures/ruby_control_structures-each.rb
|
def scoring(array)
array.each do |user|
user.update_score
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Enumerables/ruby_enumerables_collect.rb
|
<reponame>sarvekash/HackerRank_Solutions
def rot13(secret_messages)
secret_messages.collect { |message| message.tr("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") }
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Enumerables/ruby_enumerables_group_by.rb
|
<reponame>sarvekash/HackerRank_Solutions
def group_by_marks(marks, pass_marks)
marks.group_by {|key, value|
if value < pass_marks
"Failed"
else "Passed"
end}
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Enumerables/ruby_enumerables_reduce.rb
|
def sum_terms(n)
(1..n).reduce(0) {|sum, num| sum + num**2 + 1 }
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_blocks.rb
|
<reponame>sarvekash/HackerRank_Solutions
def factorial
yield
end
n = gets.to_i
factorial do
puts (1..n).inject(:*)
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_keyword_arguments.rb
|
<gh_stars>1-10
def convert_temp(temperature, input_scale, **output_scale)
if input_scale[:input_scale] == input_scale[:output_scale]
temperature
elsif input_scale[:input_scale] == 'celsius' and input_scale[:output_scale] == 'fahrenheit'
# T(°F) = T(°C) × 1.8 + 32
temperature * 1.8 + 32
elsif input_scale[:input_scale] == 'celsius' and input_scale[:output_scale] == 'kelvin'
# T(K) = T(°C) + 273.15
temperature + 273.15
elsif input_scale[:input_scale] == 'fahrenheit' and input_scale[:output_scale] == 'celsius'
# T(°C) = (T(°F) - 32) / 1.8
(temperature - 32) / 1.8
elsif input_scale[:input_scale] == 'fahrenheit' and input_scale[:output_scale] == 'kelvin'
# T(K) = (T(°F) + 459.67)× 5/9
(temperature + 459.67) * 5/9
elsif input_scale[:input_scale] == 'kelvin' and input_scale[:output_scale] == 'fahrenheit'
# T(°F) = T(K) × 1.8 - 459.67
temperature * 1.8 - 459.67
elsif input_scale[:input_scale] == 'kelvin' and input_scale[:output_scale] == 'celsius'
# T(°C) = T(K) - 273.15
temperature - 273.15
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Arrays Hashes/ruby_hash_initialization.rb
|
<filename>Ruby/Arrays Hashes/ruby_hash_initialization.rb
empty_hash = Hash.new
default_hash = Hash.new
default_hash.default = 1
hackerrank = Hash.new
hackerrank["simmy"] = 100
hackerrank["vivmbbs"] = 200
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_indexing.rb
|
<gh_stars>1-10
def serial_average(string)
matches = string.scan(/...-(\d+\.\d+)-*(\d+\.\d+)*/)
x = matches[0][0].to_f
unless matches[0][1].nil?
y = matches[0][1].to_f
else
y = x
end
z = ((x + y) / 2).round(2)
string[0, 4] + "#{z}"
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Control Structures/ruby_control_structures-unless.rb
|
<filename>Ruby/Control Structures/ruby_control_structures-unless.rb
def scoring(array)
# update_score of every user in the array unless the user is admin
# unless is the logical equivalent of if not
array.each do |user|
user.update_score unless user.is_admin?
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Control Structures/ruby_control_structures-until.rb
|
<filename>Ruby/Control Structures/ruby_control_structures-until.rb<gh_stars>1-10
# until is the logical equivalent of while not.
coder.practice until coder.oh_one?
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_lazy_evaluation.rb
|
n = gets.to_i
def is_prime?(n)
2.upto(Math.sqrt(n).round()).each do |x|
return false if n % x == 0
end
true
end
def is_palindrome?(n)
n.to_s == n.to_s.reverse
end
palindromic_primes_array = -> (array_size) do
2.upto(Float::INFINITY).lazy.map { |x| x if (is_palindrome?(x) && is_prime?(x)) }.select {|item| item.is_a? Integer}.first(n)
end
print palindromic_primes_array.(n)
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_variable_arguments.rb
|
def full_name(first, *rest)
fullname = ''
fullname += first
rest.each do |name|
fullname += ' ' + name
end
fullname
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Control Structures/ruby_control_structures-case_bonus.rb
|
def identify_class(obj)
case obj
when Hacker then puts "It's a Hacker!"
when Submission then puts "It's a Submission!"
when TestCase then puts "It's a TestCase!"
when Contest then puts "It's a Contest!"
else puts "It's an unknown model"
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Enumerables/ruby_enumerables_introduction.rb
|
<gh_stars>1-10
def iterate_colors(colors)
array = Array.new
colors.each do |color|
array.push(color)
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_introduction.rb
|
<reponame>sarvekash/HackerRank_Solutions
require 'prime'
def prime?(number)
return number.prime?
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Arrays Hashes/ruby_hash_each.rb
|
def iter_hash(hash)
hash.each do |key, value|
puts key
puts value
end
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_methods_ii.rb
|
def strike(string)
string.prepend("<strike>").concat("</strike>")
end
def mask_article(string, array)
array.each do |s|
if string.include?(s)
string.gsub!("#{s}", strike(s))
end
end
string
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Enumerables/ruby_enumerables_each_with_index.rb
|
def skip_animals(animals, skip)
array = Array.new
animals.each_with_index { |animal, index|
if (index >= skip)
array.push("#{index}:#{animal}")
end
}
return array
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_partial_applications.rb
|
combination = -> (number) do
-> (another_number) do
(1..number).inject(:*) / ((1..another_number).inject(:*) * (1..number-another_number).inject(:*))
end
end
n = gets.to_i
r = gets.to_i
nCr = combination.(n)
puts nCr.(r)
|
sarvekash/HackerRank_Solutions
|
Ruby/Strings/ruby_strings_methods_i.rb
|
<filename>Ruby/Strings/ruby_strings_methods_i.rb
def process_text(string_array)
result = ''
string_array.each do |s|
result += s.strip + ' '
end
result.chop
end
|
sarvekash/HackerRank_Solutions
|
Ruby/Methods/ruby_methods_arguments.rb
|
<reponame>sarvekash/HackerRank_Solutions
def take(array, len=1)
array[len, array.length]
end
|
jacobmarshall-etc/apollo
|
data/plugins/skill/magic/teleport.rb
|
# Thanks to phl0w <http://www.rune-server.org/members/phl0w> for providing
# the correct destination coordinates of the ancient teleports.
require 'java'
java_import 'org.apollo.game.model.Animation'
java_import 'org.apollo.game.model.Graphic'
java_import 'org.apollo.game.model.Position'
java_import 'org.apollo.game.model.entity.Skill'
TELEPORT_SPELLS = {}
MODERN_TELE_ANIM = Animation.new(714)
MODERN_TELE_END_ANIM = Animation.new(715)
MODERN_TELE_GRAPHIC = Graphic.new(308, 15, 100)
ANCIENT_TELE_END_GRAPHIC = Graphic.new(455)
ANCIENT_TELE_ANIM = Animation.new(1979)
ANCIENT_TELE_GRAPHIC = Graphic.new(392)
# A `Spell` that teleports a `Player` to another `Position`.
class TeleportSpell < Spell
attr_reader :ancient, :destination, :experience, :name
def initialize(ancient, level, elements, destination, experience, name)
super(level, elements, experience)
@ancient = ancient
@destination = destination
@name = name
end
end
# A `SpellAction` for a `TeleportSpell`.
class TeleportingAction < SpellAction
def initialize(mob, spell)
super(mob, spell)
end
def execute_action
@spell.ancient ? execute_ancient : execute_modern
end
def execute_modern
if @pulses == 0
mob.play_animation(MODERN_TELE_ANIM)
elsif @pulses == 1
mob.play_graphic(MODERN_TELE_GRAPHIC)
set_delay(1)
elsif @pulses == 2
mob.stop_graphic
mob.play_animation(MODERN_TELE_END_ANIM)
mob.teleport(@spell.destination)
mob.skill_set.add_experience(Skill::MAGIC, @spell.experience)
stop
end
end
def execute_ancient
if @pulses == 0
mob.play_graphic(ANCIENT_TELE_GRAPHIC)
mob.play_animation(ANCIENT_TELE_ANIM)
set_delay(2)
elsif @pulses == 2
mob.stop_graphic
mob.stop_animation
mob.teleport(@spell.destination)
mob.skill_set.add_experience(Skill::MAGIC, @spell.experience)
stop
end
end
end
def tele(ancient = false, button, level, elements, x, y, experience, name)
position = Position.new(x, y)
TELEPORT_SPELLS[button] = TeleportSpell.new(ancient, level, elements, position, experience, name)
end
def ancient_tele(*args)
tele(true, *args)
end
# Modern teleports
tele 1_164, 25, { FIRE => 1, AIR => 3, LAW => 1 }, 3213, 3424, 35, 'Varrock'
tele 1_167, 31, { EARTH => 1, AIR => 3, LAW => 1 }, 3222, 3219, 41, 'Lumbridge'
tele 1_170, 37, { WATER => 1, AIR => 3, LAW => 1 }, 2965, 3379, 47, 'Falador'
tele 1_174, 45, { AIR => 5, LAW => 1 }, 2757, 3478, 55.5, 'Camelot'
tele 1_540, 51, { WATER => 2, LAW => 2 }, 2662, 3306, 61, 'Ardougne'
tele 1_541, 58, { EARTH => 2, LAW => 2 }, 2549, 3114, 68, 'the Watchtower'
tele 7_455, 61, { FIRE => 2, LAW => 2 }, 2871, 3590, 68, 'Trollheim'
tele 18_470, 64, { FIRE => 2, WATER => 2, LAW => 2, Element.new([1963], nil, 'Banana') => 1 },
2_754, 2_785, 76, '<NAME>'
# Ancient teleports
ancient_tele 13_035, 54, { LAW => 2, FIRE => 1, AIR => 1 }, 3098, 9882, 64, 'Paddewwa'
ancient_tele 13_045, 60, { LAW => 2, SOUL => 2 }, 3320, 3338, 70, 'Senntisten'
ancient_tele 13_053, 66, { LAW => 2, BLOOD => 1 }, 3493, 3472, 76, 'Kharyll'
ancient_tele 13_061, 72, { LAW => 2, WATER => 4 }, 3003, 3470, 82, 'Lassar'
ancient_tele 13_069, 78, { LAW => 2, FIRE => 3, AIR => 2 }, 2966, 3_696, 88, 'Dareeyak'
ancient_tele 13_079, 84, { LAW => 2, SOUL => 2 }, 3163, 3664, 94, 'Carrallangar'
ancient_tele 13_087, 90, { LAW => 2, BLOOD => 2 }, 3287, 3883, 100, 'Annakarl'
ancient_tele 13_095, 96, { LAW => 2, WATER => 8 }, 2972, 3873, 106, 'Ghorrock'
|
jacobmarshall-etc/apollo
|
data/plugins/player-action/action.rb
|
<reponame>jacobmarshall-etc/apollo<gh_stars>0
require 'java'
java_import 'org.apollo.game.message.impl.SetPlayerActionMessage'
java_import 'org.apollo.game.model.entity.Player'
# A right-click action for a Player.
class PlayerAction
attr_reader :slot, :primary, :name
def initialize(slot, primary, name)
index = [:first, :second, :third, :fourth, :fifth].find_index(slot)
fail "Unsupported action slot #{slot}." if index.nil?
@slot = index
@primary = primary
@name = name
end
end
ATTACK_ACTION = PlayerAction.new(:third, true, 'Attack')
CHALLENGE_ACTION = PlayerAction.new(:third, true, 'Challenge')
TRADE_ACTION = PlayerAction.new(:fourth, true, 'Trade with')
FOLLOW_ACTION = PlayerAction.new(:fifth, true, 'Follow')
# Shows multiple context menu action for the specified player
def show_actions(player, *actions)
fail 'Must specify at least one action.' if actions.nil?
actions.each do |action|
player.add_action(action)
player.send(SetPlayerActionMessage.new(action.name, action.slot, action.primary))
end
end
# Shows a single context menu action for the specified player
def show_action(player, action)
show_actions(player, action)
end
# Hides a context menu action for the specified player
def hide_action(player, action)
player.send(SetPlayerActionMessage.new('null', action.slot, action.primary))
end
# Monkey-patch Player to provide action utility methods.
class Player
def actions
@actions ||= {}
end
def add_action(action)
actions[action.slot] = action.name
end
def action?(action)
actions[action.slot] == action.name
end
end
|
tylerxiety/tylerxiety.github.io
|
jekyll-theme-cayman-blog.gemspec
|
<reponame>tylerxiety/tylerxiety.github.io
# encoding: utf-8
# frozen_string_literal: true
Gem::Specification.new do |s|
s.name = "jekyll-theme-cayman-blog"
s.version = "0.0.9"
s.license = "CC0-1.0"
s.authors = ["Tyler"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/tylerxiety/
s.summary = "Cayman Blog Theme is a clean, responsive blogging theme for Jekyll and Gitlab/GitHub Pages. Based on Cayman theme."
s.files = `git ls-files -z`.split("\x0").select do |f|
f.match(%r{^((_includes|_layouts|_sass|assets)/|(LICENSE|README|index|about|contact|now|404)((\.(txt|md|markdown)|$)))}i)
end
s.platform = Gem::Platform::RUBY
s.add_runtime_dependency "jekyll", '~> 3.8', '>= 3.8.6'
s.add_runtime_dependency "jekyll-target-blank", '>= 0'
# s.add_runtime_dependency 'jekyll-seo-tag', '~> 2.0'
s.add_development_dependency 'html-proofer', '~> 3.0'
s.add_development_dependency 'rubocop', '~> 0.50'
s.add_development_dependency 'w3c_validators', '~> 1.3'
end
|
saadbinakhlaq/kahwa
|
lib/kahwa/utils.rb
|
<filename>lib/kahwa/utils.rb
class String
def to_snake_case
self.gsub('::', '/') # Home::PagesController => Home/PagesController
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') # HOMEController => home_controller
.gsub(/([a-z\d])([A-Z])/, '\1_\2') # FO86OBar => fo86_o_bar
.tr('-', '_')
.downcase
end
def to_camel_case
# if does not have _ and is in the format of Azzz
return self if self !~ /_/ && self =~ /[A-Z]+.*/
split('_').map{ |str| str.capitalize }.join # my_str MyStr
end
end
|
saadbinakhlaq/kahwa
|
lib/kahwa/dependencies.rb
|
<gh_stars>1-10
class Object
def self.const_missing(const)
require const.to_s.to_snake_case
Object.const_get(const)
end
end
|
saadbinakhlaq/kahwa
|
lib/kahwa.rb
|
require 'kahwa/version'
require 'kahwa/controller'
require 'kahwa/utils'
require 'kahwa/dependencies'
require 'kahwa/routing'
module Kahwa
class Application
def call(env)
if env['PATH_INFO'] == '/favicon.ico'
return [404, {}, []]
end
get_rack_app(env).call(env)
end
end
end
|
Scompler/ruby-msg
|
lib/mapi/version.rb
|
<filename>lib/mapi/version.rb
module Mapi
VERSION = '1.5.3'
end
|
Scompler/ruby-msg
|
lib/mapi/rtf.rb
|
<filename>lib/mapi/rtf.rb<gh_stars>0
require 'stringio'
require 'strscan'
class StringIO # :nodoc:
begin
instance_method :getbyte
rescue NameError
alias getbyte getc
end
end
module Mapi
#
# = Introduction
#
# The +RTF+ module contains a few helper functions for dealing with rtf
# in mapi messages: +rtfdecompr+, and <tt>rtf2html</tt>.
#
# Both were ported from their original C versions for simplicity's sake.
#
module RTF
class Tokenizer
def self.process io
while true do
case c = io.getc
when ?{; yield :open_group
when ?}; yield :close_group
when ?\\
case c = io.getc
when ?{, ?}, ?\\; yield :text, c.chr
when ?'; yield :text, [io.read(2)].pack('H*')
when ?a..?z, ?A..?Z
# read control word
str = c.chr
str << c while c = io.read(1) and c =~ /[a-zA-Z]/
neg = 1
neg = -1 and c = io.read(1) if c == '-'
num = if c =~ /[0-9]/
num = c
num << c while c = io.read(1) and c =~ /[0-9]/
num.to_i * neg
end
raise "invalid rtf stream" if neg == -1 and !num # ???? \blahblah- some text
io.seek(-1, IO::SEEK_CUR) if c != ' '
yield :control_word, str, num
when nil
raise "invalid rtf stream" # \EOF
else
# other kind of control symbol
yield :control_symbol, c.chr
end
when nil
return
when ?\r, ?\n
# ignore
else yield :text, c.chr
end
end
end
end
class Converter
# this is pretty crap, its just to ensure there is always something readable if
# there is an rtf only body, with no html encapsulation.
def self.rtf2text str, format=:text
group = 0
text = ''
text << "<html>\n<body>" if format == :html
group_type = []
group_tags = []
RTF::Tokenizer.process(StringIO.new(str)) do |a, b, c|
add_text = ''
case a
when :open_group; group += 1; group_type[group] = nil; group_tags[group] = []
when :close_group; group_tags[group].reverse.each { |t| text << "</#{t}>" }; group -= 1;
when :control_word; # ignore
group_type[group] ||= b
# maybe change this to use utf8 where possible
add_text = if b == 'par' || b == 'line' || b == 'page'; "\n"
elsif b == 'tab' || b == 'cell'; "\t"
elsif b == 'endash' || b == 'emdash'; "-"
elsif b == 'emspace' || b == 'enspace' || b == 'qmspace'; " "
elsif b == 'ldblquote'; '"'
else ''
end
if b == 'b' || b == 'i' and format == :html
close = c == 0 ? '/' : ''
text << "<#{close}#{b}>"
if c == 0
group_tags[group].delete b
else
group_tags[group] << b
end
end
# lot of other ones belong in here.\
=begin
\bullet Bullet character.
\lquote Left single quotation mark.
\rquote Right single quotation mark.
\ldblquote Left double quotation mark.
\rdblquote
=end
when :control_symbol; # ignore
group_type[group] ||= b
add_text = ' ' if b == '~' # non-breakable space
add_text = '-' if b == '_' # non-breakable hypen
when :text
add_text = b if group <= 1 or group_type[group] == 'rtlch' && !group_type[0...group].include?('*')
end
if format == :html
text << add_text.gsub(/([<>&"'])/) do
ent = { '<' => 'lt', '>' => 'gt', '&' => 'amp', '"' => 'quot', "'" => 'apos' }[$1]
"&#{ent};"
end
text << '<br>' if add_text == "\n"
else
text << add_text
end
end
text << "</body>\n</html>\n" if format == :html
text
end
end
RTF_PREBUF =
"{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}" \
"{\\f0\\fnil \\froman \\fswiss \\fmodern \\fscript " \
"\\fdecor MS Sans SerifSymbolArialTimes New RomanCourier" \
"{\\colortbl\\red0\\green0\\blue0\n\r\\par " \
"\\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx"
# Decompresses compressed rtf +data+, as found in the mapi property
# +PR_RTF_COMPRESSED+. Code converted from my C version, which in turn
# I wrote from a Java source, in JTNEF I believe.
#
# C version was modified to use circular buffer for back references,
# instead of the optimization of the Java version to index directly into
# output buffer. This was in preparation to support streaming in a
# read/write neutral fashion.
def rtfdecompr data
io = StringIO.new data
buf = RTF_PREBUF + "\x00" * (4096 - RTF_PREBUF.length)
wp = RTF_PREBUF.length
rtf = ''
# get header fields (as defined in RTFLIB.H)
compr_size, uncompr_size, magic, crc32 = io.read(16).unpack 'V*'
#warn "compressed-RTF data size mismatch" unless io.size == data.compr_size + 4
# process the data
case magic
when 0x414c454d # "MELA" magic number that identifies the stream as a uncompressed stream
rtf = io.read uncompr_size
when 0x75465a4c # "LZFu" magic number that identifies the stream as a compressed stream
flag_count = -1
flags = nil
while rtf.length < uncompr_size and !io.eof?
# each flag byte flags 8 literals/references, 1 per bit
flags = ((flag_count += 1) % 8 == 0) ? io.getbyte : flags >> 1
if 1 == (flags & 1) # each flag bit is 1 for reference, 0 for literal
rp, l = io.getbyte, io.getbyte
# offset is a 12 byte number. 2^12 is 4096, so thats fine
rp = (rp << 4) | (l >> 4) # the offset relative to block start
l = (l & 0xf) + 2 # the number of bytes to copy
l.times do
rtf << buf[wp] = buf[rp]
wp = (wp + 1) % 4096
rp = (rp + 1) % 4096
end
else
rtf << buf[wp] = io.getbyte.chr
wp = (wp + 1) % 4096
end
end
else # unknown magic number
raise "Unknown compression type (magic number 0x%08x)" % magic
end
# not sure if its due to a bug in the above code. doesn't seem to be
# in my tests, but sometimes there's a trailing null. we chomp it here,
# which actually makes the resultant rtf smaller than its advertised
# size (+uncompr_size+).
rtf.chomp! 0.chr
rtf
end
# Note, this is a conversion of the original C code. Not great - needs tests and
# some refactoring, and an attempt to correct some inaccuracies. Hacky but works.
#
# Returns +nil+ if it doesn't look like an rtf encapsulated rtf.
#
# Some cases that the original didn't deal with have been patched up, eg from
# this chunk, where there are tags outside of the htmlrtf ignore block.
#
# "{\\*\\htmltag116 <br />}\\htmlrtf \\line \\htmlrtf0 \\line {\\*\\htmltag84 <a href..."
#
# We take the approach of ignoring all rtf tags not explicitly handled. A proper
# parse tree would be nicer to work with. will need to look for ruby rtf library
#
# Some of the original comment to the c code is excerpted here:
#
# Sometimes in MAPI, the PR_BODY_HTML property contains the HTML of a message.
# But more usually, the HTML is encoded inside the RTF body (which you get in the
# PR_RTF_COMPRESSED property). These routines concern the decoding of the HTML
# from this RTF body.
#
# An encoded htmlrtf file is a valid RTF document, but which contains additional
# html markup information in its comments, and sometimes contains the equivalent
# rtf markup outside the comments. Therefore, when it is displayed by a plain
# simple RTF reader, the html comments are ignored and only the rtf markup has
# effect. Typically, this rtf markup is not as rich as the html markup would have been.
# But for an html-aware reader (such as the code below), we can ignore all the
# rtf markup, and extract the html markup out of the comments, and get a valid
# html document.
#
# There are actually two kinds of html markup in comments. Most of them are
# prefixed by "\*\htmltagNNN", for some number NNN. But sometimes there's one
# prefixed by "\*\mhtmltagNNN" followed by "\*\htmltagNNN". In this case,
# the two are equivalent, but the m-tag is for a MIME Multipart/Mixed Message
# and contains tags that refer to content-ids (e.g. img src="cid:072344a7")
# while the normal tag just refers to a name (e.g. img src="fred.jpg")
# The code below keeps the m-tag and discards the normal tag.
# If there are any m-tags like this, then the message also contains an
# attachment with a PR_CONTENT_ID property e.g. "072344a7". Actually,
# sometimes the m-tag is e.g. img src="http://outlook/welcome.html" and the
# attachment has a PR_CONTENT_LOCATION "http://outlook/welcome.html" instead
# of a PR_CONTENT_ID.
#
def rtf2html rtf
scan = StringScanner.new rtf
# require \fromhtml. is this worth keeping? apparently you see \\fromtext if it
# was converted from plain text.
return nil unless rtf["\\fromhtml"]
if scan.scan_until(/\\ansicpg/)
code_page = "cp" + scan.scan(/\d+/)
scan.pos = 0
else
code_page = 'ascii'
end
html = ''
ignore_tag = nil
# skip up to the first htmltag. return nil if we don't ever find one
return nil unless scan.scan_until /(?=\{\\\*\\htmltag)/
until scan.empty?
if scan.scan /\{/
elsif scan.scan /\}/
elsif scan.scan /\\\*\\htmltag(\d+) ?/
#p scan[1]
if ignore_tag == scan[1]
scan.scan_until /\}/
ignore_tag = nil
end
elsif scan.scan /\\\*\\mhtmltag(\d+) ?/
ignore_tag = scan[1]
elsif scan.scan /\\par ?/
html << "\r\n"
elsif scan.scan /\\tab ?/
html << "\t"
elsif scan.scan /\\'([0-9A-Za-z]{2})/
html << scan[1].hex.chr
elsif scan.scan /\\pntext/
scan.scan_until /\}/
elsif scan.scan /\\htmlrtf/
scan.scan_until /\\htmlrtf0 ?/
# a generic throw away unknown tags thing.
# the above 2 however, are handled specially
elsif scan.scan /\\[a-z-]+(\d+)? ?/
#elsif scan.scan /\\li(\d+) ?/
#elsif scan.scan /\\fi-(\d+) ?/
elsif scan.scan /[\r\n]/
elsif scan.scan /\\([{}\\])/
html << scan[1]
elsif scan.scan /(.)/
html << scan[1]
else
p :wtf
end
end
html.strip.empty? ? nil : html.encode('utf-8', code_page)
end
module_function :rtf2html, :rtfdecompr
end
end
|
drefuss/rubequ
|
config/initializers/paperclip.rb
|
Paperclip.interpolates :song_name do |attachment, style|
"#{attachment.instance.name}".downcase
end
Paperclip.interpolates :file_path do |attachment, style|
"#{attachment.instance.band}".gsub(" ", "_").downcase.gsub(/[^0-9a-z]/, '')
end
Paperclip.interpolates :custom_filename do |attachment, style|
"#{attachment.instance.name.gsub(" ", "_").downcase.gsub(/[^0-9a-z]/, '')}.mp3"
end
|
drefuss/rubequ
|
config/initializers/session_store.rb
|
<filename>config/initializers/session_store.rb<gh_stars>0
# Be sure to restart your server when you modify this file.
Rubequ::Application.config.session_store :cookie_store, key: '_rasplay_session'
|
drefuss/rubequ
|
db/migrate/20130711021551_create_songs.rb
|
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.string :name
t.string :band
t.string :album
t.string :album_cover
t.datetime :release_date
t.timestamps
end
end
end
|
drefuss/rubequ
|
lib/rubequ_mpd.rb
|
require 'ruby-mpd'
module RubequMpd
attr_accessor :mpd_server, :mpd_port
class Mpd
attr_accessor :mpd
def initialize
@mpd = MPD.new RubequMpd.mpd_server, RubequMpd.mpd_port
connect
consume
end
def consume
@mpd.consume = true
end
def connect
begin
@mpd.connect
rescue
puts "Could not connect to MPD server."
nil
end
end
def connected?
@mpd.connected?
end
def disconnect
@mpd.disconnect
end
def current_song
@mpd.current_song
end
def play
@mpd.play
end
def play_song(id)
@mpd.play(id)
end
def pause
@mpd.pause = (!paused?)
end
def paused?
@mpd.paused?
end
def stop
@mpd.stop
end
def next
@mpd.next
end
def current_song_name
current_song.nil? ? "" : current_song.file.gsub(".mp3", "").split("/")[1]
end
def current_song_artist
current_song.nil? ? "" : current_song.file.gsub(".mp3", "").split("/")[0]
end
def stats
@mpd.stats
end
def songs
@mpd.songs
end
def song_by_file(file_path)
begin
@mpd.songs.each_with_index do |s, i|
return s if s.file == file_path
end
return nil
rescue
return nil
end
end
def queue
@mpd.queue.sort_by &:pos
end
def queue_add(s)
unless song_is_in_queue?(s)
@mpd.add s
end
song_is_in_queue?(s)
end
def song_is_in_queue?(s)
return false if s.nil?
@mpd.queue.include?(s)
end
def queue_remove(s)
@mpd.remove s
end
def queue_clear
@mpd.clear
end
def update_song_list
begin
@mpd.update if @mpd.connected?
rescue
nil
end
end
def volume(val=nil)
return @mpd.volume if val.nil?
@mpd.volume = val
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.