text stringlengths 10 2.61M |
|---|
def bubble_sort(array)
n = array.length # in computer science an array is referred to as 'n'.
loop do
is_swapped = false
(n-1).times do |i|
# if current element > next element
if array[i] > array[i +1]
# swap values
array[i], array[i + 1] = array[i + 1], array[i]
# set is_swapped to true; if its true , loop will repeat
is_swapped = true
end
end
# if a swap happened , repeat loop. otherwise,end the loop
break if not is_swapped
end
array
end
print bubble_sort([2, 5, 8, 9, 10, -1, 4, -5]) |
class ScreenshotsController < ApplicationController
before_action :set_screenshot, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@screenshots = Screenshot.all.order("created_at DESC")
end
def show
end
def new
@screenshot = current_user.screenshots.build
end
def edit
end
def create
@screenshot = current_user.screenshots.build(screenshot_params)
if @screenshot.save
redirect_to @screenshot, notice: 'Screenshot was successfully created.'
else
render action: 'new'
end
end
def update
if @screenshot.update(screenshot_params)
redirect_to @screenshot, notice: 'Screenshot was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@screenshot.destroy
redirect_to screenshots_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_screenshot
@screenshot = Screenshot.find(params[:id])
end
def correct_user
@screenshot = current_user.screenshots.find_by(id: params[:id])
redirect_to screenshots_path, notice: "Not authorized to edit this pin" if @screenshot.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def screenshot_params
params.require(:screenshot).permit(:image, :title, :game, :genre, :description)
end
end
|
require File.expand_path('../test_helper.rb', File.dirname(__FILE__))
describe RipperRubyParser::Parser do
let(:parser) { RipperRubyParser::Parser.new }
describe '#parse' do
it 'returns an s-expression' do
result = parser.parse 'foo'
result.must_be_instance_of Sexp
end
describe 'for an empty program' do
it 'returns nil' do
''.must_be_parsed_as nil
end
end
describe 'for a class declaration' do
it 'works with a namespaced class name' do
'class Foo::Bar; end'.
must_be_parsed_as s(:class,
s(:colon2, s(:const, :Foo), :Bar),
nil)
end
it 'works for singleton classes' do
'class << self; end'.must_be_parsed_as s(:sclass, s(:self))
end
end
describe 'for a module declaration' do
it 'works with a namespaced module name' do
'module Foo::Bar; end'.
must_be_parsed_as s(:module,
s(:colon2, s(:const, :Foo), :Bar))
end
end
describe 'for empty parentheses' do
it 'works with lone ()' do
'()'.must_be_parsed_as s(:nil)
end
end
describe 'for the return statement' do
it 'works with no arguments' do
'return'.
must_be_parsed_as s(:return)
end
it 'works with one argument' do
'return foo'.
must_be_parsed_as s(:return,
s(:call, nil, :foo))
end
it 'works with a splat argument' do
'return *foo'.
must_be_parsed_as s(:return,
s(:svalue,
s(:splat,
s(:call, nil, :foo))))
end
it 'works with multiple arguments' do
'return foo, bar'.
must_be_parsed_as s(:return,
s(:array,
s(:call, nil, :foo),
s(:call, nil, :bar)))
end
it 'works with a regular argument and a splat argument' do
'return foo, *bar'.
must_be_parsed_as s(:return,
s(:array,
s(:call, nil, :foo),
s(:splat,
s(:call, nil, :bar))))
end
it 'works with a function call with parentheses' do
'return foo(bar)'.
must_be_parsed_as s(:return,
s(:call, nil, :foo,
s(:call, nil, :bar)))
end
it 'works with a function call without parentheses' do
'return foo bar'.
must_be_parsed_as s(:return,
s(:call, nil, :foo,
s(:call, nil, :bar)))
end
end
describe 'for the for statement' do
it 'works with do' do
'for foo in bar do; baz; end'.
must_be_parsed_as s(:for,
s(:call, nil, :bar),
s(:lasgn, :foo),
s(:call, nil, :baz))
end
it 'works without do' do
'for foo in bar; baz; end'.
must_be_parsed_as s(:for,
s(:call, nil, :bar),
s(:lasgn, :foo),
s(:call, nil, :baz))
end
it 'works with an empty body' do
'for foo in bar; end'.
must_be_parsed_as s(:for,
s(:call, nil, :bar),
s(:lasgn, :foo))
end
end
describe 'for a begin..end block' do
it 'works with no statements' do
'begin; end'.
must_be_parsed_as s(:nil)
end
it 'works with one statement' do
'begin; foo; end'.
must_be_parsed_as s(:call, nil, :foo)
end
it 'works with multiple statements' do
'begin; foo; bar; end'.
must_be_parsed_as s(:block,
s(:call, nil, :foo),
s(:call, nil, :bar))
end
end
describe 'for the undef statement' do
it 'works with a single bareword identifier' do
'undef foo'.
must_be_parsed_as s(:undef, s(:lit, :foo))
end
it 'works with a single symbol' do
'undef :foo'.
must_be_parsed_as s(:undef, s(:lit, :foo))
end
it 'works with multiple bareword identifiers' do
'undef foo, bar'.
must_be_parsed_as s(:block,
s(:undef, s(:lit, :foo)),
s(:undef, s(:lit, :bar)))
end
it 'works with multiple bareword symbols' do
'undef :foo, :bar'.
must_be_parsed_as s(:block,
s(:undef, s(:lit, :foo)),
s(:undef, s(:lit, :bar)))
end
end
describe 'for the alias statement' do
it 'works with regular barewords' do
'alias foo bar'.
must_be_parsed_as s(:alias,
s(:lit, :foo), s(:lit, :bar))
end
it 'works with symbols' do
'alias :foo :bar'.
must_be_parsed_as s(:alias,
s(:lit, :foo), s(:lit, :bar))
end
it 'works with operator barewords' do
'alias + -'.
must_be_parsed_as s(:alias,
s(:lit, :+), s(:lit, :-))
end
it 'works with global variables' do
'alias $foo $bar'.
must_be_parsed_as s(:valias, :$foo, :$bar)
end
end
describe 'for arguments' do
it 'works for a simple case with splat' do
'foo *bar'.
must_be_parsed_as s(:call,
nil,
:foo,
s(:splat, s(:call, nil, :bar)))
end
it 'works for a multi-argument case with splat' do
'foo bar, *baz'.
must_be_parsed_as s(:call,
nil,
:foo,
s(:call, nil, :bar),
s(:splat, s(:call, nil, :baz)))
end
it 'works for a simple case passing a block' do
'foo &bar'.
must_be_parsed_as s(:call, nil, :foo,
s(:block_pass,
s(:call, nil, :bar)))
end
it 'works for a bare hash' do
'foo bar => baz'.
must_be_parsed_as s(:call, nil, :foo,
s(:hash,
s(:call, nil, :bar),
s(:call, nil, :baz)))
end
end
describe 'for collection indexing' do
it 'works in the simple case' do
'foo[bar]'.
must_be_parsed_as s(:call,
s(:call, nil, :foo),
:[],
s(:call, nil, :bar))
end
it 'works without any indexes' do
'foo[]'.must_be_parsed_as s(:call, s(:call, nil, :foo),
:[])
end
it 'drops self from self[]' do
'self[foo]'.must_be_parsed_as s(:call, nil, :[],
s(:call, nil, :foo))
end
end
describe 'for method definitions' do
it 'works with def with receiver' do
'def foo.bar; end'.
must_be_parsed_as s(:defs,
s(:call, nil, :foo),
:bar,
s(:args),
s(:nil))
end
it 'works with def with receiver and multiple statements' do
'def foo.bar; baz; qux; end'.
must_be_parsed_as s(:defs,
s(:call, nil, :foo),
:bar,
s(:args),
s(:call, nil, :baz),
s(:call, nil, :qux))
end
it 'works with a method argument with a default value' do
'def foo bar=nil; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, s(:lasgn, :bar, s(:nil))),
s(:nil))
end
it 'works with several method arguments with default values' do
'def foo bar=1, baz=2; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:lasgn, :bar, s(:lit, 1)),
s(:lasgn, :baz, s(:lit, 2))),
s(:nil))
end
it 'works with parentheses around the parameter list' do
'def foo(bar); end'.
must_be_parsed_as s(:defn, :foo, s(:args, :bar), s(:nil))
end
it 'works with a simple splat' do
'def foo *bar; end'.
must_be_parsed_as s(:defn, :foo, s(:args, :"*bar"), s(:nil))
end
it 'works with a regular argument plus splat' do
'def foo bar, *baz; end'.
must_be_parsed_as s(:defn, :foo, s(:args, :bar, :"*baz"), s(:nil))
end
it 'works with a nameless splat' do
'def foo *; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, :"*"),
s(:nil))
end
it 'works for a simple case with explicit block parameter' do
'def foo &bar; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, :"&bar"),
s(:nil))
end
it 'works with a regular argument plus explicit block parameter' do
'def foo bar, &baz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, :bar, :"&baz"),
s(:nil))
end
it 'works with a default value plus explicit block parameter' do
'def foo bar=1, &baz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:lasgn, :bar, s(:lit, 1)),
:"&baz"),
s(:nil))
end
it 'works with a default value plus mandatory argument' do
'def foo bar=1, baz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:lasgn, :bar, s(:lit, 1)),
:baz),
s(:nil))
end
it 'works with a splat plus explicit block parameter' do
'def foo *bar, &baz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, :"*bar", :"&baz"),
s(:nil))
end
it 'works with a default value plus splat' do
'def foo bar=1, *baz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:lasgn, :bar, s(:lit, 1)),
:"*baz"),
s(:nil))
end
it 'works with a default value, splat, plus final mandatory arguments' do
'def foo bar=1, *baz, qux, quuz; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:lasgn, :bar, s(:lit, 1)),
:"*baz", :qux, :quuz),
s(:nil))
end
it 'works with a named argument with a default value' do
'def foo bar: 1; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:kwarg, :bar, s(:lit, 1))),
s(:nil))
end
it 'works with a named argument with no default value' do
'def foo bar:; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args,
s(:kwarg, :bar)),
s(:nil))
end
it 'works with a double splat' do
'def foo **bar; end'.
must_be_parsed_as s(:defn,
:foo,
s(:args, :'**bar'),
s(:nil))
end
it 'works when the method name is an operator' do
'def +; end'.
must_be_parsed_as s(:defn, :+, s(:args),
s(:nil))
end
end
describe 'for yield' do
it 'works with no arguments and no parentheses' do
'yield'.
must_be_parsed_as s(:yield)
end
it 'works with parentheses but no arguments' do
'yield()'.
must_be_parsed_as s(:yield)
end
it 'works with one argument and no parentheses' do
'yield foo'.
must_be_parsed_as s(:yield, s(:call, nil, :foo))
end
it 'works with one argument and parentheses' do
'yield(foo)'.
must_be_parsed_as s(:yield, s(:call, nil, :foo))
end
it 'works with multiple arguments and no parentheses' do
'yield foo, bar'.
must_be_parsed_as s(:yield,
s(:call, nil, :foo),
s(:call, nil, :bar))
end
it 'works with multiple arguments and parentheses' do
'yield(foo, bar)'.
must_be_parsed_as s(:yield,
s(:call, nil, :foo),
s(:call, nil, :bar))
end
it 'works with splat' do
'yield foo, *bar'.
must_be_parsed_as s(:yield,
s(:call, nil, :foo),
s(:splat, s(:call, nil, :bar)))
end
it 'works with a function call with parentheses' do
'yield foo(bar)'.
must_be_parsed_as s(:yield,
s(:call, nil, :foo,
s(:call, nil, :bar)))
end
it 'works with a function call without parentheses' do
'yield foo bar'.
must_be_parsed_as s(:yield,
s(:call, nil, :foo,
s(:call, nil, :bar)))
end
end
describe 'for the __ENCODING__ keyword' do
it 'evaluates to the equivalent of Encoding::UTF_8' do
'__ENCODING__'.
must_be_parsed_as s(:colon2, s(:const, :Encoding), :UTF_8)
end
end
describe 'for the __FILE__ keyword' do
describe 'when not passing a file name' do
it "creates a string sexp with value '(string)'" do
'__FILE__'.
must_be_parsed_as s(:str, '(string)')
end
end
describe 'when passing a file name' do
it 'creates a string sexp with the file name' do
result = parser.parse '__FILE__', 'foo'
result.must_equal s(:str, 'foo')
end
end
end
describe 'for the __LINE__ keyword' do
it 'creates a literal sexp with value of the line number' do
'__LINE__'.
must_be_parsed_as s(:lit, 1)
"\n__LINE__".
must_be_parsed_as s(:lit, 2)
end
end
describe 'for the END keyword' do
it 'converts to a :postexe iterator' do
'END { foo }'.
must_be_parsed_as s(:iter, s(:postexe), 0, s(:call, nil, :foo))
end
end
describe 'for the BEGIN keyword' do
it 'converts to a :preexe iterator' do
'BEGIN { foo }'.
must_be_parsed_as s(:iter, s(:preexe), s(:args), s(:call, nil, :foo))
end
end
describe 'for constant lookups' do
it 'works when explicitely starting from the root namespace' do
'::Foo'.
must_be_parsed_as s(:colon3, :Foo)
end
it 'works with a three-level constant lookup' do
'Foo::Bar::Baz'.
must_be_parsed_as s(:colon2,
s(:colon2, s(:const, :Foo), :Bar),
:Baz)
end
it 'works looking up a constant in a non-constant' do
'foo::Bar'.must_be_parsed_as s(:colon2,
s(:call, nil, :foo),
:Bar)
end
end
describe 'for variable references' do
it 'works for self' do
'self'.
must_be_parsed_as s(:self)
end
it 'works for instance variables' do
'@foo'.
must_be_parsed_as s(:ivar, :@foo)
end
it 'works for global variables' do
'$foo'.
must_be_parsed_as s(:gvar, :$foo)
end
it 'works for regexp match references' do
'$1'.
must_be_parsed_as s(:nth_ref, 1)
end
specify { "$'".must_be_parsed_as s(:back_ref, :"'") }
specify { '$&'.must_be_parsed_as s(:back_ref, :"&") }
it 'works for class variables' do
'@@foo'.
must_be_parsed_as s(:cvar, :@@foo)
end
end
describe 'for single assignment' do
it 'works when assigning to an instance variable' do
'@foo = bar'.
must_be_parsed_as s(:iasgn,
:@foo,
s(:call, nil, :bar))
end
it 'works when assigning to a constant' do
'FOO = bar'.
must_be_parsed_as s(:cdecl,
:FOO,
s(:call, nil, :bar))
end
it 'works when assigning to a collection element' do
'foo[bar] = baz'.
must_be_parsed_as s(:attrasgn,
s(:call, nil, :foo),
:[]=,
s(:call, nil, :bar),
s(:call, nil, :baz))
end
it 'works when assigning to an attribute' do
'foo.bar = baz'.
must_be_parsed_as s(:attrasgn,
s(:call, nil, :foo),
:bar=,
s(:call, nil, :baz))
end
it 'works when assigning to a class variable' do
'@@foo = bar'.
must_be_parsed_as s(:cvdecl,
:@@foo,
s(:call, nil, :bar))
end
it 'works when assigning to a class variable inside a method' do
'def foo; @@bar = baz; end'.
must_be_parsed_as s(:defn,
:foo, s(:args),
s(:cvasgn, :@@bar, s(:call, nil, :baz)))
end
it 'works when assigning to a class variable inside a method with a receiver' do
'def self.foo; @@bar = baz; end'.
must_be_parsed_as s(:defs,
s(:self),
:foo, s(:args),
s(:cvasgn, :@@bar, s(:call, nil, :baz)))
end
it 'works when assigning to a global variable' do
'$foo = bar'.
must_be_parsed_as s(:gasgn,
:$foo,
s(:call, nil, :bar))
end
end
describe 'for operator assignment' do
it 'works with +=' do
'foo += bar'.
must_be_parsed_as s(:lasgn,
:foo,
s(:call,
s(:lvar, :foo),
:+,
s(:call, nil, :bar)))
end
it 'works with -=' do
'foo -= bar'.
must_be_parsed_as s(:lasgn,
:foo,
s(:call,
s(:lvar, :foo),
:-,
s(:call, nil, :bar)))
end
it 'works with ||=' do
'foo ||= bar'.
must_be_parsed_as s(:op_asgn_or,
s(:lvar, :foo),
s(:lasgn, :foo,
s(:call, nil, :bar)))
end
it 'works when assigning to an instance variable' do
'@foo += bar'.
must_be_parsed_as s(:iasgn,
:@foo,
s(:call,
s(:ivar, :@foo),
:+,
s(:call, nil, :bar)))
end
it 'works when assigning to a collection element' do
'foo[bar] += baz'.
must_be_parsed_as s(:op_asgn1,
s(:call, nil, :foo),
s(:arglist, s(:call, nil, :bar)),
:+,
s(:call, nil, :baz))
end
it 'works with ||= when assigning to a collection element' do
'foo[bar] ||= baz'.
must_be_parsed_as s(:op_asgn1,
s(:call, nil, :foo),
s(:arglist, s(:call, nil, :bar)),
:"||",
s(:call, nil, :baz))
end
it 'works when assigning to an attribute' do
'foo.bar += baz'.
must_be_parsed_as s(:op_asgn2,
s(:call, nil, :foo),
:bar=,
:+,
s(:call, nil, :baz))
end
it 'works with ||= when assigning to an attribute' do
'foo.bar ||= baz'.
must_be_parsed_as s(:op_asgn2,
s(:call, nil, :foo),
:bar=,
:"||",
s(:call, nil, :baz))
end
end
describe 'for multiple assignment' do
it 'works the same number of items on each side' do
'foo, bar = baz, qux'.
must_be_parsed_as s(:masgn,
s(:array, s(:lasgn, :foo), s(:lasgn, :bar)),
s(:array,
s(:call, nil, :baz),
s(:call, nil, :qux)))
end
it 'works with a single item on the right-hand side' do
'foo, bar = baz'.
must_be_parsed_as s(:masgn,
s(:array, s(:lasgn, :foo), s(:lasgn, :bar)),
s(:to_ary,
s(:call, nil, :baz)))
end
it 'works with left-hand splat' do
'foo, *bar = baz, qux'.
must_be_parsed_as s(:masgn,
s(:array, s(:lasgn, :foo), s(:splat, s(:lasgn, :bar))),
s(:array,
s(:call, nil, :baz),
s(:call, nil, :qux)))
end
it 'works with parentheses around the left-hand side' do
'(foo, bar) = baz'.
must_be_parsed_as s(:masgn,
s(:array, s(:lasgn, :foo), s(:lasgn, :bar)),
s(:to_ary, s(:call, nil, :baz)))
end
it 'works with complex destructuring' do
'foo, (bar, baz) = qux'.
must_be_parsed_as s(:masgn,
s(:array,
s(:lasgn, :foo),
s(:masgn,
s(:array, s(:lasgn, :bar), s(:lasgn, :baz)))),
s(:to_ary, s(:call, nil, :qux)))
end
it 'works with complex destructuring of the value' do
'foo, (bar, baz) = [qux, [quz, quuz]]'.
must_be_parsed_as s(:masgn,
s(:array,
s(:lasgn, :foo),
s(:masgn, s(:array, s(:lasgn, :bar), s(:lasgn, :baz)))),
s(:to_ary,
s(:array,
s(:call, nil, :qux),
s(:array, s(:call, nil, :quz), s(:call, nil, :quuz)))))
end
it 'works with instance variables' do
'@foo, @bar = baz'.
must_be_parsed_as s(:masgn,
s(:array, s(:iasgn, :@foo), s(:iasgn, :@bar)),
s(:to_ary, s(:call, nil, :baz)))
end
it 'works with class variables' do
'@@foo, @@bar = baz'.
must_be_parsed_as s(:masgn,
s(:array, s(:cvdecl, :@@foo), s(:cvdecl, :@@bar)),
s(:to_ary, s(:call, nil, :baz)))
end
it 'works with attributes' do
'foo.bar, foo.baz = qux'.
must_be_parsed_as s(:masgn,
s(:array,
s(:attrasgn, s(:call, nil, :foo), :bar=),
s(:attrasgn, s(:call, nil, :foo), :baz=)),
s(:to_ary, s(:call, nil, :qux)))
end
it 'works with collection elements' do
'foo[1], bar[2] = baz'.
must_be_parsed_as s(:masgn,
s(:array,
s(:attrasgn,
s(:call, nil, :foo), :[]=, s(:lit, 1)),
s(:attrasgn,
s(:call, nil, :bar), :[]=, s(:lit, 2))),
s(:to_ary, s(:call, nil, :baz)))
end
it 'works with constants' do
'Foo, Bar = baz'.
must_be_parsed_as s(:masgn,
s(:array, s(:cdecl, :Foo), s(:cdecl, :Bar)),
s(:to_ary, s(:call, nil, :baz)))
end
it 'works with instance variables and splat' do
'@foo, *@bar = baz'.
must_be_parsed_as s(:masgn,
s(:array,
s(:iasgn, :@foo),
s(:splat, s(:iasgn, :@bar))),
s(:to_ary,
s(:call, nil, :baz)))
end
end
describe 'for operators' do
it 'handles :!=' do
'foo != bar'.
must_be_parsed_as s(:call,
s(:call, nil, :foo),
:!=,
s(:call, nil, :bar))
end
it 'handles :=~ with two non-literals' do
'foo =~ bar'.
must_be_parsed_as s(:call,
s(:call, nil, :foo),
:=~,
s(:call, nil, :bar))
end
it 'handles :=~ with literal regexp on the left hand side' do
'/foo/ =~ bar'.
must_be_parsed_as s(:match2,
s(:lit, /foo/),
s(:call, nil, :bar))
end
it 'handles :=~ with literal regexp on the right hand side' do
'foo =~ /bar/'.
must_be_parsed_as s(:match3,
s(:lit, /bar/),
s(:call, nil, :foo))
end
it 'handles unary !' do
'!foo'.
must_be_parsed_as s(:call, s(:call, nil, :foo), :!)
end
it 'converts :not to :!' do
'not foo'.
must_be_parsed_as s(:call, s(:call, nil, :foo), :!)
end
it 'handles unary ! with a number literal' do
'!1'.
must_be_parsed_as s(:call, s(:lit, 1), :!)
end
it 'handles the range operator with positive number literals' do
'1..2'.
must_be_parsed_as s(:lit, 1..2)
end
it 'handles the range operator with negative number literals' do
'-1..-2'.
must_be_parsed_as s(:lit, -1..-2)
end
it 'handles the range operator with string literals' do
"'a'..'z'".
must_be_parsed_as s(:dot2,
s(:str, 'a'),
s(:str, 'z'))
end
it 'handles the range operator with non-literals' do
'foo..bar'.
must_be_parsed_as s(:dot2,
s(:call, nil, :foo),
s(:call, nil, :bar))
end
it 'handles the exclusive range operator with positive number literals' do
'1...2'.
must_be_parsed_as s(:lit, 1...2)
end
it 'handles the exclusive range operator with negative number literals' do
'-1...-2'.
must_be_parsed_as s(:lit, -1...-2)
end
it 'handles the exclusive range operator with string literals' do
"'a'...'z'".
must_be_parsed_as s(:dot3,
s(:str, 'a'),
s(:str, 'z'))
end
it 'handles the exclusive range operator with non-literals' do
'foo...bar'.
must_be_parsed_as s(:dot3,
s(:call, nil, :foo),
s(:call, nil, :bar))
end
it 'handles the ternary operator' do
'foo ? bar : baz'.
must_be_parsed_as s(:if,
s(:call, nil, :foo),
s(:call, nil, :bar),
s(:call, nil, :baz))
end
end
describe 'for expressions' do
it 'handles assignment inside binary operator expressions' do
'foo + (bar = baz)'.
must_be_parsed_as s(:call,
s(:call, nil, :foo),
:+,
s(:lasgn,
:bar,
s(:call, nil, :baz)))
end
it 'handles assignment inside unary operator expressions' do
'+(foo = bar)'.
must_be_parsed_as s(:call,
s(:lasgn, :foo, s(:call, nil, :bar)),
:+@)
end
end
# Note: differences in the handling of comments are not caught by Sexp's
# implementation of equality.
describe 'for comments' do
it 'handles method comments' do
result = parser.parse "# Foo\ndef foo; end"
result.must_equal s(:defn,
:foo,
s(:args), s(:nil))
result.comments.must_equal "# Foo\n"
end
it 'handles comments for methods with explicit receiver' do
result = parser.parse "# Foo\ndef foo.bar; end"
result.must_equal s(:defs,
s(:call, nil, :foo),
:bar,
s(:args),
s(:nil))
result.comments.must_equal "# Foo\n"
end
it 'matches comments to the correct entity' do
result = parser.parse "# Foo\nclass Foo\n# Bar\ndef bar\nend\nend"
result.must_equal s(:class, :Foo, nil,
s(:defn, :bar,
s(:args), s(:nil)))
result.comments.must_equal "# Foo\n"
defn = result[3]
defn.sexp_type.must_equal :defn
defn.comments.must_equal "# Bar\n"
end
it 'combines multi-line comments' do
result = parser.parse "# Foo\n# Bar\ndef foo; end"
result.must_equal s(:defn,
:foo,
s(:args), s(:nil))
result.comments.must_equal "# Foo\n# Bar\n"
end
it 'drops comments inside method bodies' do
result = parser.parse <<-END
# Foo
class Foo
# foo
def foo
bar # this is dropped
end
# bar
def bar
baz
end
end
END
result.must_equal s(:class,
:Foo,
nil,
s(:defn, :foo, s(:args), s(:call, nil, :bar)),
s(:defn, :bar, s(:args), s(:call, nil, :baz)))
result.comments.must_equal "# Foo\n"
result[3].comments.must_equal "# foo\n"
result[4].comments.must_equal "# bar\n"
end
it 'handles the use of symbols that are keywords' do
result = parser.parse "# Foo\ndef bar\n:class\nend"
result.must_equal s(:defn,
:bar,
s(:args),
s(:lit, :class))
result.comments.must_equal "# Foo\n"
end
it 'handles use of singleton class inside methods' do
result = parser.parse "# Foo\ndef bar\nclass << self\nbaz\nend\nend"
result.must_equal s(:defn,
:bar,
s(:args),
s(:sclass, s(:self),
s(:call, nil, :baz)))
result.comments.must_equal "# Foo\n"
end
end
# Note: differences in the handling of line numbers are not caught by
# Sexp's implementation of equality.
describe 'assigning line numbers' do
it 'works for a plain method call' do
result = parser.parse 'foo'
result.line.must_equal 1
end
it 'works for a method call with parentheses' do
result = parser.parse 'foo()'
result.line.must_equal 1
end
it 'works for a method call with receiver' do
result = parser.parse 'foo.bar'
result.line.must_equal 1
end
it 'works for a method call with receiver and arguments' do
result = parser.parse 'foo.bar baz'
result.line.must_equal 1
end
it 'works for a method call with arguments' do
result = parser.parse 'foo bar'
result.line.must_equal 1
end
it 'works for a block with two lines' do
result = parser.parse "foo\nbar\n"
result.sexp_type.must_equal :block
result[1].line.must_equal 1
result[2].line.must_equal 2
result.line.must_equal 1
end
it 'works for a constant reference' do
result = parser.parse 'Foo'
result.line.must_equal 1
end
it 'works for an instance variable' do
result = parser.parse '@foo'
result.line.must_equal 1
end
it 'works for a global variable' do
result = parser.parse '$foo'
result.line.must_equal 1
end
it 'works for a class variable' do
result = parser.parse '@@foo'
result.line.must_equal 1
end
it 'works for a local variable' do
result = parser.parse "foo = bar\nfoo\n"
result.sexp_type.must_equal :block
result[1].line.must_equal 1
result[2].line.must_equal 2
result.line.must_equal 1
end
it 'works for an integer literal' do
result = parser.parse '42'
result.line.must_equal 1
end
it 'works for a float literal' do
result = parser.parse '3.14'
result.line.must_equal 1
end
it 'works for a regular expression back reference' do
result = parser.parse '$1'
result.line.must_equal 1
end
it 'works for self' do
result = parser.parse 'self'
result.line.must_equal 1
end
it 'works for __FILE__' do
result = parser.parse '__FILE__'
result.line.must_equal 1
end
it 'works for nil' do
result = parser.parse 'nil'
result.line.must_equal 1
end
it 'works for a symbol literal' do
result = parser.parse ':foo'
result.line.must_equal 1
end
it 'works for a class definition' do
result = parser.parse 'class Foo; end'
result.line.must_equal 1
end
it 'works for a module definition' do
result = parser.parse 'module Foo; end'
result.line.must_equal 1
end
it 'works for a method definition' do
result = parser.parse 'def foo; end'
result.line.must_equal 1
end
it 'works for assignment of the empty hash' do
result = parser.parse 'foo = {}'
result.line.must_equal 1
end
it 'works for multiple assignment of empty hashes' do
result = parser.parse 'foo, bar = {}, {}'
result.line.must_equal 1
end
it 'assigns line numbers to nested sexps without their own line numbers' do
result = parser.parse "foo(bar) do\nnext baz\nend\n"
result.must_equal s(:iter,
s(:call, nil, :foo, s(:call, nil, :bar)),
0,
s(:next, s(:call, nil, :baz)))
arglist = result[1][3]
block = result[3]
nums = [arglist.line, block.line]
nums.must_equal [1, 2]
end
describe 'when a line number is passed' do
it 'shifts all line numbers as appropriate' do
result = parser.parse "foo\nbar\n", '(string)', 3
result.must_equal s(:block,
s(:call, nil, :foo),
s(:call, nil, :bar))
result.line.must_equal 3
result[1].line.must_equal 3
result[2].line.must_equal 4
end
end
end
end
describe '#trickle_up_line_numbers' do
it 'works through several nested levels' do
inner = s(:foo)
outer = s(:bar, s(:baz, s(:qux, inner)))
outer.line = 42
parser.send :trickle_down_line_numbers, outer
inner.line.must_equal 42
end
end
describe '#trickle_down_line_numbers' do
it 'works through several nested levels' do
inner = s(:foo)
inner.line = 42
outer = s(:bar, s(:baz, s(:qux, inner)))
parser.send :trickle_up_line_numbers, outer
outer.line.must_equal 42
end
end
end
|
module Pacer
module Pipes
class WrappingPipe < RubyPipe
attr_reader :graph, :element_type, :extensions, :wrapper
def initialize(graph, element_type = nil, extensions = [])
super()
if graph.is_a? Array
@graph, @wrapper = graph
else
@graph = graph
@element_type = element_type
@extensions = extensions || []
@wrapper = Pacer::Wrappers::WrapperSelector.build graph, element_type, @extensions
end
end
def instance(pipe, g)
g ||= graph
p = WrappingPipe.new [g, wrapper]
p.setStarts pipe
p
end
def getSideEffect
starts.getSideEffect
end
def getCurrentPath
starts.getCurrentPath
end
def wrapper=(w)
if extensions.any? and w.respond_to? :add_extensions
@wrapper = w.add_extensions extensions
else
@wrapper = w
end
end
def processNextStart
wrapper.new graph, starts.next
end
end
end
end
|
module ROXML
unless const_defined? 'XML_PARSER'
begin
require 'libxml'
XML_PARSER = 'libxml'
rescue LoadError
XML_PARSER = 'rexml'
end
end
require File.join(File.dirname(__FILE__), 'xml', XML_PARSER)
#
# Internal base class that represents an XML - Class binding.
#
class XMLRef # ::nodoc::
attr_reader :accessor, :name, :array, :default, :block, :wrapper
def initialize(accessor, args, &block)
@accessor = accessor
@array = args.array?
@name = args.name
@default = args.default
@block = block
@wrapper = args.wrapper
end
# Reads data from the XML element and populates the instance
# accordingly.
def populate(xml, instance)
data = value(xml)
instance.instance_variable_set("@#{accessor}", data) if data
instance
end
def name?
false
end
private
def xpath
wrapper ? "#{wrapper}#{xpath_separator}#{name}" : name.to_s
end
def wrap(xml)
(wrapper && xml.name != wrapper) ? xml.child_add(XML::Node.new_element(wrapper)) : xml
end
end
# Interal class representing an XML attribute binding
#
# In context:
# <element attribute="XMLAttributeRef">
# XMLTextRef
# </element>
class XMLAttributeRef < XMLRef # ::nodoc::
# Updates the attribute in the given XML block to
# the value provided.
def update_xml(xml, value)
xml.attributes[name] = value.to_utf
xml
end
def value(xml)
parent = wrap(xml)
val = xml.attributes[name] || default
block ? block.call(val) : val
end
private
def xpath_separator
'@'
end
end
# Interal class representing XML content text binding
#
# In context:
# <element attribute="XMLAttributeRef">
# XMLTextRef
# </element>
class XMLTextRef < XMLRef # ::nodoc::
attr_reader :cdata, :content
def initialize(accessor, args, &block)
super(accessor, args, &block)
@content = args.content?
@cdata = args.cdata?
end
# Updates the text in the given _xml_ block to
# the _value_ provided.
def update_xml(xml, value)
parent = wrap(xml)
if content
add(parent, value)
elsif name?
parent.name = value
elsif array
value.each do |v|
add(parent.child_add(XML::Node.new_element(name)), v)
end
else
add(parent.child_add(XML::Node.new_element(name)), value)
end
xml
end
def value(xml)
val = if content
xml.content.strip
elsif name?
xml.name
elsif array
arr = xml.search(xpath).collect do |e|
e.content.strip.to_latin if e.content
end
arr unless arr.empty?
else
child = xml.search(name).first
child.content if child
end
val = default unless val && !val.blank?
block ? block.call(val) : val
end
def name?
name == '*'
end
private
def xpath_separator
'/'
end
def add(dest, value)
if cdata
dest.child_add(XML::Node.new_cdata(value.to_utf))
else
dest.content = value.to_utf
end
end
end
class XMLHashRef < XMLTextRef # ::nodoc::
attr_reader :hash
def initialize(accessor, args, &block)
super(accessor, args, &block)
@hash = args.hash
if @hash.key.name? || @hash.value.name?
@name = '*'
end
end
# Updates the composed XML object in the given XML block to
# the value provided.
def update_xml(xml, value)
parent = wrap(xml)
value.each_pair do |k, v|
node = add_node(parent)
hash.key.update_xml(node, k)
hash.value.update_xml(node, v)
end
xml
end
def value(xml)
vals = xml.search(xpath).collect do |e|
[@hash.key.value(e), @hash.value.value(e)]
end
if block
vals.collect! do |(key, val)|
block.call(key, val)
end
end
vals.to_h
end
private
def add_node(xml)
xml.child_add(XML::Node.new_element(hash.wrapper))
end
end
class XMLObjectRef < XMLTextRef # ::nodoc::
attr_reader :klass
def initialize(accessor, args, &block)
super(accessor, args, &block)
@klass = args.type
end
# Updates the composed XML object in the given XML block to
# the value provided.
def update_xml(xml, value)
parent = wrap(xml)
unless array
parent.child_add(value.to_xml(name))
else
value.each do |v|
parent.child_add(v.to_xml(name))
end
end
xml
end
def value(xml)
val = unless array
if child = xml.search(xpath).first
instantiate(child)
end
else
arr = xml.search(xpath).collect do |e|
instantiate(e)
end
arr unless arr.empty?
end || default
block ? block.call(val) : val
end
private
def instantiate(elem)
if klass.respond_to? :parse
klass.parse(elem)
else
klass.new(elem)
end
end
end
#
# Returns an XML::Node representing this object.
#
def to_xml(name = nil)
returning XML::Node.new_element(name || tag_name) do |root|
tag_refs.each do |ref|
if v = __send__(ref.accessor)
ref.update_xml(root, v)
end
end
end
end
end |
When("I try to delete my Lists") do
visit "https://www.ferguson.com/myAccount/myList"
60.times do
@mylist_page.Click_MoreActions
@mylist_page.Click_MoreActionsDelete
@mylist_page.Click_YesBtnDeleteList
end
end
Then("I should be able to delete my list successfully") do
expect(page).to have_text('list(s) deleted')
@login_page.logout
end
|
require_relative '../UI/character_ui.rb'
require_relative './character_modules/character_combat.rb'
# Base class for all characters that show up in the game.
class Character
attr_reader :name, :alive, :party, :party_number
attr_reader :initiative, :level, :hp, :max_hp, :mana, :max_mana, :ac
include CharacterUI
include CharacterCombat
def initialize
@party = [self]
@party_number = 1
@alive = true
@name = ''
@level = 1
@hp = 10
@max_hp = 10
@mana = 100
@max_mana = 100
@ac = 13
@initiative = rand(1..20)
end
def add_ally_to_party(ally)
@party.push(ally)
ally.join_party(@party, @party.length)
end
def join_party(party, party_number)
@party_number = party_number
@party = party
end
def take_damage(damage)
@hp -= damage
@hp = 0 if @hp < 0
@alive = false if @hp <= 0
end
def heal(points)
@hp += points
@hp = @max_hp if @hp > @max_hp
@alive = true if @hp > 0
end
end
|
get '/' do
erb :index
end
post '/login' do #find user, start session
@user = User.authenticate(params[:username], params[:password])
if @user
session[:user_id] = @user.id
redirect '/profile'
else
@errors = "Username and/or password not valid. Try again."
erb :index
end
end
get '/signup' do #set user form
erb :'users/new'
end
post '/signup' do # create user
@user = User.create(username: params[:username], password: params[:password])
if @user.valid?
session[:user_id] = @user.id
redirect '/profile'
else
@errors = @user.errors
erb :'users/new'
end
end
get '/profile' do #show user profile
@user = User.find(session[:user_id])
@rounds = @user.rounds
erb :'users/profile'
end
get '/logout' do
session.clear
redirect '/'
end
|
Card = Struct.new(:rank, :suit) do
def to_s
"#{rank.capitalize} of #{suit.capitalize}"
end
def ==(other_card)
self.rank == other_card.rank
end
end
|
require "fluent/plugin/filter"
module Fluent::Plugin
class SumologicK8sEventFilter < Fluent::Plugin::Filter
Fluent::Plugin.register_filter("sumologic_k8s_event", self)
helpers :record_accessor
def configure(conf)
super
@timestamp = record_accessor_create('$.@timestamp')
@kubernetes_event = record_accessor_create('$.kubernetes.event')
@host_name = record_accessor_create('$.host.name')
@meta_cloud = record_accessor_create('$.meta.cloud')
end
def multi_workers_ready?
true
end
def filter(tag, time, record)
rewritten_record = {}
rewritten_record['timestamp'] = @timestamp.call(record)
rewritten_record['event'] = @kubernetes_event.call(record)
rewritten_record['host'] = @host_name.call(record)
rewritten_record['cloud'] = @meta_cloud.call(record)
rewritten_record
end
end
end
|
require 'json'
module SolidusMailchimpSync
# Line item for Cart or Order, mailchimp serializes the same
class LineItemSerializer
attr_reader :line_item
def initialize(line_item)
@line_item = line_item
end
def as_json
{
id: line_item.id.to_s,
product_id: line_item.product.id.to_s,
product_variant_id: line_item.variant.id.to_s,
quantity: line_item.quantity,
price: line_item.price.to_f
}
end
def to_json
JSON.dump(as_json)
end
end
end
|
class AddGuestIdToVotes < ActiveRecord::Migration
def self.up
add_column :votes, :guest_id, :string, :limit => 36, :null => false, :default => 0
add_index :votes, [:option_id, :guest_id], :unique => true
end
def self.down
remove_column :votes, :guest_id
end
end
|
class Song
attr_accessor :artist
attr_reader :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def artist_name
artist ? self.artist.name : nil
end
end |
class Charge < ActiveRecord::Base
# Setup accessible (or protected) attributes for your model
attr_accessible :customer_charge_id, :user_id
belongs_to :user
# attr_accessible :title, :body
end
|
require 'wlang'
require 'wlang/wlang_command_options'
require 'wlang/dialects/standard_dialects'
module WLang
#
# Provides the _wlang_ commandline tool. See 'wlang --help' for documentation.
#
class WLangCommand
# Creates a commandline instance.
def initialize()
end
# Run _wlang_ commandline on specific arguments
def run(args)
# parse the options
options = Options.new.parse(args)
# get output buffer
buffer = STDOUT
if options.output_file
buffer = File.new(options.output_file, "w")
end
source = File.read(options.template_file)
dialect = options.template_dialect
braces = options.template_brace
context = options.context_object
context = {options.context_name => context} unless options.context_name.nil?
template = WLang::file_template(options.template_file, options.template_dialect, braces)
if options.verbosity>1
puts "Instantiating #{options.template_file}"
puts "Using dialect #{dialect}"
puts "Block delimiters are " << Template::BLOCK_SYMBOLS[braces].inspect
puts "Context is " << context.inspect
end
buffer << template.instantiate(context || {})
# Flush and close if needed
if File===buffer
buffer.flush
buffer.close
end
end
end # class WLang
end # module WLang |
module ExchangeRateService extend self
CURRENCY_DATA = YAML.load_file(
Rails.root.join('config', 'currencies.yml')
).with_indifferent_access.freeze
CURRENCIES = CURRENCY_DATA.keys.freeze
CACHE_TIMEOUT = 15.minutes.freeze
def current_price(currency, formatted=false)
if formatted
MoneyService.format external_data[currency], currency
else
external_data[currency]
end
end
def local_current_price(user, formatted=false)
currency = user.present? ? user.currency : 'usd'
current_price(currency, formatted)
end
def updated_at
Time.zone.parse(external_data['updated_at'])
end
def fetch_external_data
data = {}
currencies = CURRENCIES.map { |currency| currency.upcase }.join(',')
external_data = JSON.parse connection.get("/data/price?fsym=DASH&tsyms=#{currencies}").body
CURRENCIES.each do |currency|
data[currency] = external_data[currency.upcase].to_f.round(2)
end
data['updated_at'] = Time.now.to_s
set_cache(data)
data
end
private
def external_data
cache = get_cache
return cache if cache_valid?(cache)
fetch_external_data
end
def cache_valid?(cache)
cache.present? and cache['updated_at'] > Time.now - CACHE_TIMEOUT
end
def get_cache
cache = $redis.get(:exchange_rate)
cache = JSON.parse(cache) if cache.present?
cache
end
def set_cache(data)
$redis.set(:exchange_rate, data.to_json)
end
def connection
Faraday.new(url: 'https://min-api.cryptocompare.com')
end
end
|
class AddOrderToFeNavigationItems < ActiveRecord::Migration[5.0]
def change
add_column :fe_navigation_items, :order, :integer, after: :parent_id, null: false, default: 0
end
end
|
class Admin::ChargesController < ApplicationController
before_action :admin_access
def index
@charges = Billing::Charge.order("created_at DESC")
end
def show
@charge = Billing::Charge.find(params[:id])
end
def new
@charge = Billing::Charge.new
end
def create
charge = Billing::Charge.new(charge_params.merge(payment_method: :deposit))
if charge.save
redirect_to admin_charge_path(charge)
else
render :new
end
end
def edit
@charge = Billing::Charge.find(params[:id])
end
def update
charge = Billing::Charge.find(params[:id])
if charge.update(charge_params)
redirect_to admin_charge_path(charge)
else
render :edit
end
end
def destroy
charge = Billing::Charge.find(params[:id])
charge.destroy
redirect_to admin_charges_path notice: "El pago se ha eliminado con รฉxito"
end
private
def charge_params
params.require(:billing_charge).permit(:first_name, :last_name, :email,
:description, :currency, :amount, :tax_percentage, :tax, :status,
:customer_name, :customer_email, :customer_type_id, :customer_id,
:customer_country, :customer_mobile, :customer_address)
end
end
|
require 'test_helper'
module SurveyBuilder
class SurveyFormsControllerTest < ActionController::TestCase
setup do
@survey_form = survey_forms(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:survey_forms)
end
test "should get new" do
get :new
assert_response :success
end
test "should create survey_form" do
assert_difference('SurveyForm.count') do
post :create, survey_form: { name: @survey_form.name, points: @survey_form.points }
end
assert_redirected_to survey_form_path(assigns(:survey_form))
end
test "should show survey_form" do
get :show, id: @survey_form
assert_response :success
end
test "should get edit" do
get :edit, id: @survey_form
assert_response :success
end
test "should update survey_form" do
patch :update, id: @survey_form, survey_form: { name: @survey_form.name, points: @survey_form.points }
assert_redirected_to survey_form_path(assigns(:survey_form))
end
test "should destroy survey_form" do
assert_difference('SurveyForm.count', -1) do
delete :destroy, id: @survey_form
end
assert_redirected_to survey_forms_path
end
end
end
|
class LikeALittlesController < ApplicationController
before_action :signed_in_student, only: [:index, :create, :destroy]
def index
@lals = LikeALittle.where(:school => current_student.school ).includes(:student, :school)
@like_a_little = current_student.like_a_littles.new
end
def create
@lal = current_student.like_a_littles.create(lal_params)
if @lal.save
flash.now[:success] = "Like A Little created!"
else
end
end
def destroy
end
def lal_params
params.require(:like_a_little).permit(:content, :school_id)
end
end
|
require 'rails_helper'
RSpec.describe Item do
describe "visiting items pages" do
before(:each) do
@merchant = create(:merchant)
@item = create(:item, merchant_id: @merchant.id)
item_2 = create(:item, id: 2, merchant_id: @merchant.id)
end
it "can visit an item show page" do
get "/api/v1/items/#{@item.id}"
expect(response).to be_successful
end
it "can visit item index page" do
get "/api/v1/items"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"].count).to eq(2)
end
it "can visit with id query params" do
get "/api/v1/items/find?id=#{@item.id}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"]['id'].to_i).to eq(@item.id)
end
it "can visit with name query params" do
get "/api/v1/items/find?name=#{@item.name}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"]['id'].to_i).to eq(@item.id)
end
it "can visit with description query params" do
get "/api/v1/items/find?description=#{@item.description}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"]['id'].to_i).to eq(@item.id)
end
it "can visit with unit_price query params" do
get "/api/v1/items/find?unit_price=#{@item.unit_price}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"]['id'].to_i).to eq(@item.id)
end
it "can visit with merchant_id query params" do
get "/api/v1/items/find?merchant_id=#{@item.merchant_id}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"]['id'].to_i).to eq(@item.id)
end
it "can visit with id find_all query params" do
get "/api/v1/items/find_all?id=#{@item.id}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"].count).to eq(1)
end
it "can visit with name find_all query params" do
get "/api/v1/items/find_all?name=#{@item.name}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"].count).to eq(2)
end
it "can visit with description find_all query params" do
get "/api/v1/items/find_all?description=#{@item.description}"
expect(response).to be_successful
items_hash = JSON.parse(response.body)
expect(items_hash["data"].count).to eq(2)
end
end
end
|
class Api::V1::ShoppingListProductsController < ApplicationController
def index
@shoppinglistproducts = ShoppingListProduct.all
render json: @shoppinglistproducts
end
def create
@shoppinglistproduct = ShoppingListProduct.create(shopppinglistproduct_params)
if @shoppinglistproduct.save
render json: @shoppinglistproduct, status: :accepted
else
render json: { errors: @shoppinglistproduct.errors.full_messages}, status: :unprocessible_entity
end
end
private
def shopppinglistproduct_params
params.permit(:shopping_list_id, :product_id)
end
end
|
#
# for CentOS 6.x
#
execute "install remi repository" do
command "rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm"
not_if "rpm -qa | grep remi"
end
service "mysqld" do
action :stop
only_if "service mysql"
end
execute "remove installed mysql" do
command "yum remove -y mysql"
only_if "rpm -qa | grep mysql"
end
%w(mysql mysql-server mysql-devel).each do |pkg|
package pkg do
action :install
options "--enablerepo remi"
end
end
service "mysqld" do
action [:enable, :start]
end
execute "set root password" do
command "mysqladmin -u root password #{node['mysql']['server_root_password']}"
only_if "mysql -u root -e 'show databases;'"
end
|
class Attempt < ActiveRecord::Base
belongs_to :webhook
belongs_to :post_error
validate :success_not_nil
validate :success_without_error
attr_accessible :success, :error
def success_without_error
(@success and not @error) or (@error and not @success)
end
def success_not_nil
!@success.nil?
end
end
|
class TracksController < ApplicationController
def new
@track = Track.new
render :new
end
def create
@track = Track.new(track_params)
if @track.save
album = Album.find(@track.album_id)
redirect_to album_url(album)
else
render :new
end
end
private
def track_params
params.require(:track).permit(:name, :album_id, :ttype, :lyrics)
end
end
|
class RecycleController < ApplicationController
before_action :ensure_admin_in
before_action :set_menu_item, only: %i[ restore_menu_items delete_menu_item ]
before_action :set_menu_cetegory, only: %i[ restore_menu_category delete_menu_category ]
def menu_items_recycle
@pagy, @menuItems = pagy(MenuItem.where("archived_on is not NULL"))
render "index"
end
def user_recycle
@pagy, @users = pagy(User.where("archived_on is not NULL"))
render "user-index"
end
def search_users
name = params[:name]
@search_category = params[:search]
if ((@search_category == "id"))
begin
id = Integer(name)
@pagy, @users = pagy(User.where("id = ? and archived_on is not NULL", name))
rescue
flash[:error] = "Enter valid input"
end
else
@pagy, @users = pagy(User.where("lower(#{@search_category}) Like '" + "#{name.downcase}%' and archived_on is not NULL").order(:name, :id), items: 10)
end
render "user-index"
end
def restore_user
user = User.find(params[:id])
user.archived_on = nil
unless user.save(validate: false)
flash[:error] = user.errors.full_messages.join(", ")
end
redirect_back(fallback_location: "/")
end
def menu_category_recycle
@pagy, @menucategories = pagy(MenuCategory.where("archived_on is not NULL"))
render "category-index"
end
def search_menucategory
name = params[:name]
unless name.nil?
@pagy, @menucategories = pagy(MenuCategory.where("archived_on is not NULL and lower(name) Like '" + "#{name.downcase}%'").order(:id), items: 12)
end
render "category-index"
end
def search
name = params[:name]
unless name.nil?
@pagy, @menuItems = pagy(MenuItem.where("archived_on is not NULL and lower(name) Like '" + "#{name.downcase}%'").order(:id), items: 12)
end
render "index"
end
def restore_menu_category
@menucategory.archived_on = nil
unless @menucategory.save
flash[:error] = @menucategory.errors.full_messages.join(", ")
else
flash[:success] = "Restored your menu Category"
end
redirect_back(fallback_location: "/")
end
def delete_menu_category
unless (@menucategory.archived_on.nil?)
menuItemcount = MenuItem.where("menu_category_id = ? and archived_on is NULL", params[:id]).count
if menuItemcount == 0
menucategory = MenuCategory.where(archived_on: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day, id: params[:id])
if (menucategory.empty?)
if @menucategory.destroy
flash[:success] = "Successfully Deleted Your menu Category"
else
flash[:error] = @menucategory.errors.full_messages.join(", ")
end
else
flash[:error] = "Today You can't delete the menu category"
end
else
flash[:error] = "Not allowed first delete all the menu Items"
end
end
redirect_back(fallback_location: "/")
end
def restore_menu_items
menu_item_id = params[:id]
menu_category = MenuCategory.where("archived_on is not NULL and id = ?", @menu_item.menu_category_id)
unless menu_category.empty?
flash[:error] = "First Restore the Menu Category"
else
@menu_item.archived_on = nil
unless @menu_item.save
flash[:error] = @menu_item.errors.full_messages.join(", ")
else
flash[:success] = "Restored your menu items"
end
end
redirect_back(fallback_location: "/")
end
def delete_menu_item
unless (@menu_item.archived_on.nil?)
menuitem = MenuItem.where(archived_on: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day, id: params[:id])
if (menuitem.empty?)
if @menu_item.destroy
flash[:success] = "Successfully Deleted Your menu Items"
else
flash[:error] = @menu_item.errors.full_messages.join(", ")
end
else
flash[:error] = "Today You can't delete the menu Item"
end
end
redirect_back(fallback_location: "/")
end
private
def set_menu_item
@menu_item = MenuItem.find(params[:id])
end
def set_menu_cetegory
@menucategory = MenuCategory.find(params[:id])
end
end
|
Rails.application.routes.draw do
resources :document_pages
resources :documents
root to: 'documents#new'
end
|
class Buda < ActiveRecord::Base
belongs_to :brecord, :foreign_key => 'bobjid'
end
# == Schema Information
#
# Table name: budas
#
# bobjid :integer(10)
# bname :string(16)
# bvalue :string(80)
# btimestamp :datetime
# bmdtid :integer(10)
# bsubclusterid :integer(5)
#
|
require 'spec_helper'
module Alchemy
describe EssencePicture do
it "should not store negative values for crop values" do
essence = EssencePicture.new(:crop_from => '-1x100', :crop_size => '-20x30')
essence.save!
essence.crop_from.should == "0x100"
essence.crop_size.should == "0x30"
end
it "should not store float values for crop values" do
essence = EssencePicture.new(:crop_from => '0.05x104.5', :crop_size => '99.5x203.4')
essence.save!
essence.crop_from.should == "0x105"
essence.crop_size.should == "100x203"
end
it "should convert newlines in caption into <br/>s" do
essence = EssencePicture.new(:caption => "hello\nkitty")
essence.save!
essence.caption.should == "hello<br/>kitty"
end
end
end
|
class Notifications < ActionMailer::Base
default from: "admin@example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.notifications.new_pin.subject
#
def new_pin(conference)
@conference = conference
@pin = Hash.new()
if conference.conferenceable_type == 'User'
user = conference.conferenceable
if ! user.first_name.blank?
@pin[:greeting] = user.first_name
else
@pin[:greeting] = user.user_name
end
else
@pin[:greeting] = conference.conferenceable.to_s
end
@pin[:conference] = conference.to_s
@pin[:pin] = conference.pin
@pin[:phone_numbers] = conference.phone_numbers.join(', ')
mail(from: Tenant.find(GsParameter.get('DEFAULT_API_TENANT_ID')).from_field_pin_change_email,to: "#{conference.conferenceable.email}", :subject => "Conference PIN changed: #{@pin[:conference]}")
end
def new_password(user, password)
@password = password
@message = Hash.new()
if ! user.first_name.blank?
@message[:greeting] = user.first_name
else
@message[:greeting] = user.user_name
end
mail(from: Tenant.find(GsParameter.get('DEFAULT_API_TENANT_ID')).from_field_pin_change_email, to: "#{user.email}", :subject => "Password recovery")
end
def new_voicemail(freeswitch_voicemail_msg, account, email, attach_file = false)
@voicemail = Hash.new()
@voicemail[:destination] = freeswitch_voicemail_msg.in_folder
@voicemail[:from] = "#{freeswitch_voicemail_msg.cid_number} #{freeswitch_voicemail_msg.cid_name}"
@voicemail[:to] = account.to_s
@voicemail[:date] = Time.at(freeswitch_voicemail_msg.created_epoch).getlocal.to_s
@voicemail[:duration] = Time.at(freeswitch_voicemail_msg.message_len).utc.strftime('%T')
if attach_file
caller_number = freeswitch_voicemail_msg.cid_number.gsub(/[^0-9]/, '')
if caller_number.blank?
caller_number = 'anonymous'
end
@voicemail[:file_name] = "#{Time.at(freeswitch_voicemail_msg.created_epoch).getlocal.strftime('%Y%m%d-%H%M%S')}-#{caller_number}.wav"
attachments[@voicemail[:file_name]] = File.read(freeswitch_voicemail_msg.file_path)
end
mail(from: Tenant.find(GsParameter.get('DEFAULT_API_TENANT_ID')).from_field_voicemail_email, to: email, :subject => "New Voicemail from #{@voicemail[:from]}, received #{Time.at(freeswitch_voicemail_msg.created_epoch).getlocal.to_s}")
end
def new_fax(fax_document)
fax_account = fax_document.fax_account
if !fax_account || fax_account.email.blank?
return false
end
caller_number = fax_document.caller_id_number.gsub(/[^0-9]/, '')
if caller_number.blank?
caller_number = 'anonymous'
end
@fax = {
:greeting => '',
:account_name => fax_account.name,
:from => "#{caller_number} #{fax_document.caller_id_name}",
:remote_station_id => fax_document.remote_station_id,
:local_station_id => fax_document.local_station_id,
:date => fax_document.created_at,
}
if fax_account.fax_accountable
if fax_account.fax_accountable_type == 'User'
user = fax_account.fax_accountable
if ! user.first_name.blank?
@fax[:greeting] = user.first_name
else
@fax[:greeting] = user.user_name
end
elsif fax_account.fax_accountable_type == 'Tenant'
@fax[:greeting] = fax_account.fax_accountable.name
end
end
attachments["#{fax_document.created_at.strftime('%Y%m%d-%H%M%S')}-#{caller_number}.pdf"] = File.read(fax_document.document.path)
mail(from: Tenant.find(GsParameter.get('DEFAULT_API_TENANT_ID')).from_field_voicemail_email, to: "#{fax_account.email}", :subject => "New Fax Document from #{@fax[:from]}, received #{fax_document.created_at}")
end
end
|
class Api::Internal::TeamsController < ApplicationController
before_action :load_team, only: [:show, :update, :destroy]
def index
@teams = Team.where(tournament_id: params[:tournament_id])
render json: @teams
end
def create
head(:unauthorized) && return unless verified_user?
@team = Team.new(team_params) do |c|
c.user_id = current_user.id
c.tournament_id = params[:tournament_id]
end
if @team.save
render json: @team
else
render json: { errors: @team.errors.full_messages }, status: 422
end
end
def show
render json: @team
end
def update
head(:unauthorized) && return unless verified_user? { |u| u.id == @team.user_id }
if @team.update(team_params)
render json: @team
else
render json: { errors: @team.errors.full_messages }, status: 422
end
end
def destroy
head(:unauthorized) && return unless verified_user? { |u| u.id == @team.user_id }
tournament_id = @team.tournament_id
@team.destroy
render json: { tournament_id: tournament_id }
end
private
def team_params
params.require(:team).permit(:logo, :name)
end
def verified_user?(&block)
if current_user.present?
block_given? ? yield(current_user) : true
else
false
end
end
def load_team
@team = Team.find(params[:id])
end
end
|
class Tweet < ApplicationRecord
belongs_to :user
has_many :coments #commentsใใผใใซใจใฎใขใฝใทใจใผใทใงใณ
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
describe Mongo::Auth::Aws::Credentials do
describe '#expired?' do
context 'when expiration is nil' do
let(:credentials) do
described_class.new('access_key_id', 'secret_access_key', nil, nil)
end
it 'returns false' do
expect(credentials.expired?).to be false
end
end
context 'when expiration is not nil' do
before do
Timecop.freeze
end
after do
Timecop.return
end
context 'when the expiration is more than five minutes away' do
let(:credentials) do
described_class.new('access_key_id', 'secret_access_key', nil, Time.now.utc + 400)
end
it 'returns false' do
expect(credentials.expired?).to be false
end
end
context 'when the expiration is less than five minutes away' do
let(:credentials) do
described_class.new('access_key_id', 'secret_access_key', nil, Time.now.utc + 200)
end
it 'returns true' do
expect(credentials.expired?).to be true
end
end
end
end
end
|
require 'capybara/rspec'
require 'capybara/dsl'
feature 'Enter names and email' do
scenario 'submitting names and email' do
sign_in_and_play
expect(page).to have_content 'Thanks for signing in Dave. Will email you at Mittens@hotmail.com'
end
end
feature 'Submit takes to correct page' do
scenario 'submitting button start!' do
sign_in_and_play
click_button('Start!')
expect(page).to have_content 'You made it this far well done! Now lets begin.....select a picture by clicking on rock, paper or scissors'
end
end
|
class Actions::NewPrivateKey
extend Extensions::Parameterizable
with :public_key
def call
api = Models::Api.find_by public_key: public_key
Models::PrivateKey.create api: api
end
end
|
class HistogramController < ApplicationController
def show
set_course
@bounds = []
render template: "histogram.html.erb",
:locals => { grades_counts: grades_counts}
end
def submitbounds
render json: {"submit": "grade bounds "}
end
def grades_counts
grades = @course.enrolls.collect(&:lettergrade)
counts = Hash.new 0
grades.each do |grade|
counts[grade] += 1
end
return counts
end
helper_method :course_id
def course_id
@course.id
end
private
# Use callbacks to share common setup or constraints between actions.
def set_course
if params[:id]
@course = Course.find(params[:id])
else
@course = Course.first
end
end
end
|
require "rails_helper"
describe "routes for tags" do
it "routes GET /repo/foo.bar/tag/latest to the tags controller" do
expect(get("/repo/foo.bar/tag/latest")).to route_to(
controller: "tags",
action: "show",
repo: "foo.bar",
tag: "latest"
)
end
it "routes GET /repo/foo/bar/tag/1.2.3 to the tags controller" do
expect(get("/repo/foo/bar/tag/1.2.3")).to route_to(
controller: "tags",
action: "show",
repo: "foo/bar",
tag: "1.2.3"
)
end
it "routes DELETE /repo/xx/yy-zz/tag/latest to the tags controller" do
expect(delete("/repo/xx/yy-zz/tag/latest")).to route_to(
controller: "tags",
action: "destroy",
repo: "xx/yy-zz",
tag: "latest"
)
end
end
describe "routes redirect for tags", type: :request do
it "routes GET /foo.bar:latest to the tags controller" do
expect(get("/foo.bar:latest")).to redirect_to('/repo/foo.bar/tag/latest')
end
it "routes GET /foo/bar:1.2.3 to the tags controller" do
expect(get("/foo/bar:1.2.3")).to redirect_to('/repo/foo/bar/tag/1.2.3')
end
end
|
require "spec_helper"
describe Game do
let(:game) { Game.new("hello") }
describe "#new" do
it "sets game_word" do
display = game.game_word
expect(display).to be_an_instance_of(Array)
string = display.join
expect(string).to eql(game.word)
end
it "sets a display word" do
display_length = game.game_word.size
expect(game.display_word.size).to eql display_length
end
end
describe "#compare_string" do
it "returns true if the argument equals" do
test_word = game.word.dup
game.compare_string(test_word)
expect(game.game_over).to be_true
end
end
describe "#compare_char" do
it "returns true if char is in the string" do
char = game.game_word[1]
expect(game.compare_char(char)).to be_true
end
it "returns false if char is not in the string" do
char = 0
expect(game.compare_char(char)).to be_false
end
end
describe "#place_char" do
it "places a char in the show holder" do
test = game.game_word
test.each do |char|
game.place_char(char)
end
expect(game.display_word).to eql game.game_word
end
end
end
|
# frozen_string_literal: true
require 'prawn/core'
require 'prawn/format'
require "prawn/measurement_extensions"
require 'gruff'
require 'pdf/format'
require 'pdf/data'
require 'pdf/styles/colored'
# REFACTOR: extract abstract Report class, and DRY functionality with InvoiceReporter
module Pdf
class Report
include Printer
attr_accessor :account, :period, :pdf, :service, :report
METRIC_HEADINGS_DAY = Format.prep_th ["Name", "Today's Total", "% Change"]
METRIC_HEADINGS_WEEK = Format.prep_th ["Name", "Week's Total", "% Change"]
SIGNUP_HEADINGS = Format.prep_th ["Name", "Registered on", "Email", "Plan"]
TOP_USERS_HEADINGS = Format.prep_th %w[Name Hits]
USERS_HEADINGS = Format.prep_th %w[Plan Users]
def initialize(account, service, options = {})
@account = account
@service = service
@period = options[:period] || :day
# TODO: accept as parameter
@style = Pdf::Styles::Colored.new
@data = Pdf::Data.new(@account, @service, period: @period)
@pdf = Prawn::Document.new(
page_size: 'A4',
page_layout: :portrait)
@pdf.tags(@style.tags)
@pdf.font(@style.font)
end
def generate
three_scale_logo
move_down 2
header
traffic_graph
traffic_and_users
move_down 3
latest_users(10)
move_down 3
metrics
move_down 3
@report = @pdf.render_file(pdf_file_path)
self
end
def deliver_notification?(user)
user.notification_preferences.include?(notification_name) && user.admin?
end
def send_notification!
account.admins.map do |admin|
if deliver_notification?(admin)
NotificationMailer.public_send(notification_name, self, admin).deliver_now
else
Rails.logger.info "[PDF::Report] Skipping delivery of #{period} report to #{admin}"
end
end
end
def notification_name
case period
when :day then :daily_report
when :week then :weekly_report
else raise "unknown notification for period #{period}"
end
end
# REFACTOR: this class should not be responsible for mailing
def mail_report
PostOffice.report(self, print_period).deliver_now
end
def pdf_file_name
['report', @account.internal_domain, @service.id].join('-') + '.pdf'
end
def pdf_file_path
Rails.root.join('tmp', pdf_file_name)
end
def print_period
return "Daily Report" if @period == :day
return "Weekly Report" if @period == :week
end
def header
@pdf.text "<period>#{print_period}</period> (<domain>#{account.external_domain} - #{EscapeUtils.escape_html(@service.name)}</domain>)"
@pdf.header @pdf.margin_box.top_left do
@pdf.text header_text, align: :right
end
end
def latest_users(count)
subtitle "Latest Signups"
print_table(@data.latest_users(count), TABLE_FULL_WIDTH, SIGNUP_HEADINGS)
end
def traffic_and_users
two_columns([0.mm, 194.mm], height: 40.mm) do |column|
case column
when :left
if (users = @data.top_users)
subtitle 'Top Users'
print_table(users, TABLE_HALF_WIDTH, TOP_USERS_HEADINGS)
end
when :right
subtitle "Users"
print_table(@data.users, TABLE_HALF_WIDTH, USERS_HEADINGS)
end
end
end
def traffic_graph
graph = @data.traffic_graph
return unless graph
subtitle "Traffic"
@pdf.image graph, position: :left, width: 520
end
def metrics
subtitle "Metrics"
if @period == :day
print_table(@data.metrics, TABLE_FULL_WIDTH, METRIC_HEADINGS_DAY)
elsif @period == :week
print_table(@data.metrics, TABLE_FULL_WIDTH, METRIC_HEADINGS_WEEK)
end
end
private
def header_text
if @period == :day
"<date>#{1.day.ago.to_date}</date>"
else
"<date>#{1.day.ago.to_date}</date> - <date>#{1.week.ago.to_date}</date>"
end
end
def three_scale_logo
logo = File.dirname(__FILE__) + "/images/logo.png"
@pdf.image logo, width: 100
end
def print_table(data, width, headings)
if data.present?
options = { headers: headings, width: width }
@pdf.table data, @style.table_style.merge(options)
else
@pdf.text "<small>No current data</small>"
end
end
end
end
|
FactoryGirl.define do
factory :audit_report do
data do
{
'name' => name,
'date' => Date.today,
'audit_structures' => []
}
end
sequence(:name) { |num| "report#{num}" }
user
initialize_with do
AuditReportCreator.new(
data: data,
user: user,
wegoaudit_id: SecureRandom.uuid
).create
end
end
end
|
Rails.application.routes.draw do
get 'cart' => 'cart#index', as: :cart
post 'cart/add/:id' => 'cart#add_item', as: :cart_add_item
post 'cart/checkout' => 'cart#checkout', as: :checkout
delete 'cart/empty' => 'cart#empty', as: :cart_empty
delete 'cart/remove/:id' => 'cart#remove_item', as: :cart_remove_item
post 'payments/notify'
get 'payments/success'
get 'payments/check'
get 'account_settings' => 'account_settings#index'
post 'account_settings/update' => 'account_settings#update'
post 'currencies/set_currency/:currency' => 'currencies#set_currency', as: :set_currency
resources :orders, only: [:index, :show]
root 'items#index'
end
|
# frozen_string_literal: true
if defined? RSpec # otherwise fails on non-live environments
task(:spec).clear
desc 'Run all specs/features in spec directory'
RSpec::Core::RakeTask.new(spec: 'db:test:prepare') do |t|
t.pattern = './spec/**/*{_spec.rb,.feature}'
end
end
|
print 'Enter your car model: '
car_model = gets.strip
output = case car_model
when 'Focus', 'Fiesta' then 'Ford'
when 'Ibiza' then 'Seat'
when 'Civic' then 'Honda'
else 'Unknown model'
end
puts "The car company for #{car_model} is: " , output
puts "Please enter you role: Example 0 for Admin, \n1 for Manager, \n2 for Supervisor, \n3 for Sales person, \n4 for Client"
name = gets.strip.to_i
message = 'Welcome. You have logged in as: '
discount = 0
item_price = 250
case name
when 0 then discount = 100
puts 'Congrats you have a discount of 100%'
when 1 then discount = 75.5
puts 'You can accumulate points that not taking discount.'
when 2 then discount = 50.9
puts 'Half a discount...That is nice!'
when 3 then discount = 92
puts 'Could have given you 100%.'
when 4 then discount = 23.60
puts 'You should be happy for the discount!'
else discount = 5
end
puts 'The discount: ', discount
puts "The price paid for the article costing #{item_price} : ", item_price - (discount / 100.0 * item_price)
|
require "miw/layout"
require "miw/size"
module MiW
module Layout
class Box
RESIZE_DEFAULT = [false, false].freeze
WEIGHT_DEFAULT = [100, 100].freeze
MIN_SIZE_DEFAULT = [0, 0].freeze
MAX_SIZE_DEFAULT = [Float::INFINITY, Float::INFINITY].freeze
def initialize(dir = 0, spacing = 0, compact = false)
@dir = dir
@spacing = spacing
@compact = compact
end
attr_accessor :spacing
def do_layout(container, rect)
Box.resize_items(container, rect, @dir, @spacing, @compact)
Box.move_items(container, rect, @dir, @spacing)
end
def self.resize_items(container, rect, dir, spacing, compact)
odir = dir ^ 1
size = [rect.width, rect.height]
extent = size[dir]
count_items = 0
count_resize_items = 0
weight_total = 0
tmp_size = [0, 0]
# pass 1:
container.each do |item, hint|
count_items += 1
tmp_size[0] = item.width
tmp_size[1] = item.height
extent -= tmp_size[dir]
resize = hint[:resize] || RESIZE_DEFAULT
weight = hint[:weight] || WEIGHT_DEFAULT
min_size = hint[:min_size] || MIN_SIZE_DEFAULT
if resize[dir] && !compact
count_resize_items += 1
weight_total += weight[dir]
end
if resize[odir]
tmp_size[odir] = size[odir]
item.resize_to *tmp_size
end
end
return if count_items == 0
count_fixed_items = count_items - count_resize_items
extent -= spacing * (count_items - 1)
# pass 2:
if count_resize_items > 0
sign = (extent <=> 0)
recalc = false
distr = extent.abs / count_resize_items
rem = extent.abs % count_resize_items
container.each do |item, hint|
resize = hint[:resize] || RESIZE_DEFAULT
next unless resize[dir]
tmp_size[0] = item.width
tmp_size[1] = item.height
min_size = hint[:min_size] || MIN_SIZE_DEFAULT
max_size = hint[:max_size] || MAX_SIZE_DEFAULT
if recalc
distr = extent.abs / count_resize_items
rem = extent.abs % count_resize_items
recalc = false
end
sz = tmp_size[dir] + distr * sign
if rem > 0
sz += sign
rem -= 1
end
szr = [[sz, min_size[dir]].max, max_size[dir]].min
recalc = (szr != sz)
extent -= szr - tmp_size[dir]
tmp_size[dir] = szr
tmp_size[odir] = size[odir] if resize[odir]
item.resize_to *tmp_size
count_resize_items -= 1
end
end
# pass 3:
if !compact && extent < 0
container.each do |item, hint|
resize = hint[:resize] || RESIZE_DEFAULT
next if resize[dir]
tmp_size[0] = item.width
tmp_size[1] = item.height
min_size = hint[:min_size] || MIN_SIZE_DEFAULT
w = (hint[:weight] || WEIGHT_DEFAULT)[dir]
distr = extent.abs * w / weight_total
sz = tmp_size[dir] - distr
szr = [sz, min_size[dir]].max
tmp_size[dir] = szr
extent += szr
item.resize_to *tmp_size
break unless extent < 0
end
end
end
def self.move_items(container, rect, dir, spacing)
odir = dir ^ 1
pos = [rect.x, rect.y]
size = [rect.width, rect.height]
left_top = pos.dup
tmp_size = [0, 0]
container.each do |item, hint|
align_odir = hint && hint[:align] && hint[:align][odir] || :center
tmp_size[0] = item.width
tmp_size[1] = item.height
case align_odir
when :top
pos[odir] = left_top[odir]
when :bottom
pos[odir] = left_top[odir] + size[odir] - tmp_size[odir]
else
pos[odir] = left_top[odir] + (size[odir] - tmp_size[odir]) / 2
end
item.offset_to pos[0], pos[1]
pos[dir] += tmp_size[dir] + spacing
end
end
end
class HBox < Box
def initialize(spacing = 0)
super 0, spacing, false
end
end
class VBox < Box
def initialize(spacing = 0)
super 1, spacing, false
end
end
class HPack < Box
def initialize(spacing = 0)
super 0, spacing, true
end
end
class VPack < Box
def initialize(spacing = 0)
super 1, spacing, true
end
end
end # module Layout
end # module MiW
|
describe "POST /signup" do
context "novo usuario" do
before(:all) do
payload = { name: "Alexandre Filho", email: "alexandrefilhor@gmail.com", password: "Teste@123" }
MongoDB.new.remove_user(payload[:email])
@result = Signup.new.create(payload)
end
it "Valida status code" do
expect(@result.code).to eql 200
end
it "Valida id do usuรกrio" do
expect(@result.parsed_response["_id"].length).to eql 24
end
end
context "usuario ja existe" do
before(:all) do
payload = { name: "Murillo Nunes", email: "murillo@gmail.com", password: "Teste@123" }
MongoDB.new.remove_user(payload[:email])
Signup.new.create(payload)
@result = Signup.new.create(payload)
end
it "Deve retornar status code 409" do
expect(@result.code).to eql 409
end
it "Deve retornar mensagem de erro" do
expect(@result.parsed_response["error"]).to eql "Email already exists :("
end
end
examples = [
{
title: "Nome Obrigatorio",
payload: { name: "", email: "francielly@gmail.com", password: "Teste@123" },
code: 412,
error: "required name",
},
{
title: "Email Obrigatorio",
payload: { name: "Alexandre Nunes", email: "", password: "Teste@123" },
code: 412,
error: "required email",
},
{
title: "Senha Obrigatoria",
payload: { name: "Alexandre Nunes", email: "francielly@gmail.com", password: "" },
code: 412,
error: "required password",
},
]
examples.each do |e|
context "#{e[:title]}" do
before(:all) do
@result = Signup.new.create(e[:payload])
end
it "Valida status code #{e[:code]}" do
expect(@result.code).to eql e[:code]
end
it "Valida id do usuรกrio" do
expect(@result.parsed_response["error"]).to eql e[:error]
end
end
end
end
|
require 'rails_helper'
RSpec.describe "transactions/new", type: :view do
before(:each) do
assign(:transaction, Transaction.new(
:from_id => 1,
:to_id => 1,
:money => 1,
:reason => "MyText"
))
end
it "renders new transaction form" do
render
assert_select "form[action=?][method=?]", transactions_path, "post" do
assert_select "input#transaction_from_id[name=?]", "transaction[from_id]"
assert_select "input#transaction_to_id[name=?]", "transaction[to_id]"
assert_select "input#transaction_money[name=?]", "transaction[money]"
assert_select "textarea#transaction_reason[name=?]", "transaction[reason]"
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
require 'support/shared/server_selector'
describe Mongo::ServerSelector::Primary do
let(:name) { :primary }
include_context 'server selector'
let(:default_address) { 'test.host' }
it_behaves_like 'a server selector mode' do
let(:secondary_ok) { false }
end
it_behaves_like 'a server selector with sensitive data in its options'
describe '#initialize' do
context 'when max_staleness is provided' do
let(:options) do
{ max_staleness: 100 }
end
it 'raises an exception' do
expect {
selector
}.to raise_exception(Mongo::Error::InvalidServerPreference)
end
end
end
describe '#tag_sets' do
context 'tags not provided' do
it 'returns an empty array' do
expect(selector.tag_sets).to be_empty
end
end
context 'tag sets provided' do
let(:tag_sets) do
[ tag_set ]
end
it 'raises an error' do
expect {
selector.tag_sets
}.to raise_error(Mongo::Error::InvalidServerPreference)
end
end
end
describe '#hedge' do
context 'hedge not provided' do
it 'returns an empty array' do
expect(selector.hedge).to be_nil
end
end
context 'hedge provided' do
let(:hedge) { { enabled: true } }
it 'raises an error' do
expect {
selector.tag_sets
}.to raise_error(Mongo::Error::InvalidServerPreference)
end
end
end
describe '#to_mongos' do
it 'returns nil' do
expect(selector.to_mongos).to be_nil
end
context 'max staleness not provided' do
it 'returns nil' do
expect(selector.to_mongos).to be_nil
end
end
context 'max staleness provided' do
let(:max_staleness) do
100
end
it 'raises an error' do
expect {
selector
}.to raise_exception(Mongo::Error::InvalidServerPreference)
end
end
end
describe '#select_in_replica_set' do
context 'no candidates' do
let(:candidates) { [] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
context 'secondary candidates' do
let(:candidates) { [secondary] }
it 'returns an empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
context 'primary candidate' do
let(:candidates) { [primary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'primary and secondary candidates' do
let(:candidates) { [secondary, primary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([primary])
end
end
context 'high latency candidates' do
let(:far_primary) { make_server(:primary, :average_round_trip_time => 0.100, address: default_address) }
let(:far_secondary) { make_server(:secondary, :average_round_trip_time => 0.120, address: default_address) }
context 'single candidate' do
context 'far primary' do
let(:candidates) { [far_primary] }
it 'returns array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_primary])
end
end
context 'far secondary' do
let(:candidates) { [far_secondary] }
it 'returns empty array' do
expect(selector.send(:select_in_replica_set, candidates)).to be_empty
end
end
end
context 'multiple candidates' do
context 'far primary, far secondary' do
let(:candidates) { [far_primary, far_secondary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_primary])
end
end
context 'far primary, local secondary' do
let(:candidates) { [far_primary, far_secondary] }
it 'returns an array with the primary' do
expect(selector.send(:select_in_replica_set, candidates)).to eq([far_primary])
end
end
end
end
end
end
|
# encoding: utf-8
#
control "V-92255" do
title "The Red Hat Enterprise Linux operating system must have a host-based intrusion detection tool installed."
desc "Adding host-based intrusion detection tools can provide the capability to automatically take actions in response to malicious behavior, which can provide additional agility in reacting to network threats. These tools also often include a reporting capability to provide network awareness of the system, which may not otherwise exist in an organization's systems management regime."
impact 0.5
tag "check": "Ask the SA or ISSO if a host-based intrusion detection application is loaded on the system. Per OPORD 16-0080, the preferred intrusion detection system is McAfee HBSS available through the U.S. Cyber Command (USCYBERCOM).
If another host-based intrusion detection application is in use, such as SELinux, this must be documented and approved by the local Authorizing Official.
Procedure:
Examine the system to determine if the Host Intrusion Prevention System (HIPS) is installed:
# rpm -qa | grep MFEhiplsm
Verify that the McAfee HIPS module is active on the system:
# ps -ef | grep -i โhipclientโ
If the MFEhiplsm package is not installed, check for another intrusion detection system:
# find / -name <daemon name>
Where <daemon name> is the name of the primary application daemon to determine if the application is loaded on the system.
Determine if the application is active on the system:
# ps -ef | grep -i <daemon name>
If the MFEhiplsm package is not installed and an alternate host-based intrusion detection application has not been documented for use, this is a finding."
tag "fix": "Install and enable the latest McAfee HIPS package, available from USCYBERCOM.
Note: If the system does not support the McAfee HIPS package, install and enable a supported intrusion detection system application and document its use with the Authorizing Official."
# Need to edit this check to look for McAfee ePO agent
describe package('name') do
it { should_be_installed }
its('version') { should eq >= x.x.x }
end
describe service('service_name') do
it { should be_enabled }
it { should be_running }
end
end
|
class Bstorage < ActiveRecord::Base
has_many :blocations, :foreign_key => 'bobjid'
has_many :bfiles, :foreign_key => 'bstorage', :primary_key => 'bname'
def open?
baccess == 'OPEN'
end
end
# == Schema Information
#
# Table name: bstorages
#
# bsubclusterid :integer(5)
# id :integer(10) primary key
# bname :string(16)
# bdesc :string(80)
# barcdate :datetime
# barclabel :string(6)
# barcset :string(32)
# breloaddate :datetime
# bsyncflag :string(3)
# baccess :string(6)
# bactive :string(3)
# bcompressflag :string(3)
# bcompressutil :string(255)
# bdictversion :integer(5)
# btimestamp :datetime
# bmdtid :integer(10)
#
|
class AddTenantIdToFaxAccount < ActiveRecord::Migration
def change
add_column :fax_accounts, :tenant_id, :integer
add_column :fax_accounts, :station_id, :string
end
end
|
module Faceter
module Nodes
# The node describes removing prefix from tuples' keys
#
# @api private
#
class RemovePrefix < ChangePrefix
private
def __operation__
:drop_prefix
end
end # class RemovePrefix
end # module Nodes
end # module Faceter
|
module Api
class BaseController < ApplicationController
before_filter :authenticate_user
private
def authenticate_user
auth_token = request.headers["Authorization"]
return render status: 401, json: { status: :failed, error: 'No access token passed' } if auth_token.blank?
@user = User.where(authentication_token: auth_token).first
# device_token = params[:device_token] if params[:device_token]
# @user.device_token = device_token;
# @user.save
return render status: 401, json: { status: :failed, error: 'User not found' } if @user.blank?
end
def current_user
@user
end
def nearby_locations
Location.all_nearby_including_unregistered(params[:latitude], params[:longitude], 5)
#params[:radius]
end
# def nearby_locations
# radius = params[:radius].present? ? params[:radius] : 20
# return @_nearby_locations if @_nearby_locations.present?
# lat_lon = if params[:zip].present?
# Location.new(address: params[:zip]).geocode
# elsif params[:latitude].present? && params[:longitude].present?
# [params[:latitude].to_d, params[:longitude].to_d]
# else
# []
# end
# @_nearby_locations = Location.near(lat_lon, radius, order: :distance)
# end
end
end
|
# encoding: utf-8
class Cjdns
VERSION = '0.0.0'
end
|
# Virus Predictor
# I worked on this challenge with Stephen Fang.
# We spent 2 hours on this challenge.
# EXPLANATION OF require_relative
# require_relative takes the file from the local / relative folder and inputs the called file into the current file. Require may be useful if the file isn't relative and you need to use an absolute path.
#
#population density is number of people per square mile as of 2012
#this data is updated every year with estimates from a 10 year census
require_relative 'state_data'
class VirusPredictor
# Initiating a new instance of a virus predictor. Inputting data for new istances for evaluation.
def initialize(state_of_origin, population_density, population)
@state = state_of_origin
@population = population
@population_density = population_density
end
# Calling methods so that all information related to the virus effects is in one place.
def virus_effects
predicted_deaths
speed_of_spread
end
private
# Method which predicts death rates depending on how dense the population is and prints out a statement.
def predicted_deaths
# predicted deaths is solely based on population density
number_of_deaths = case @population_density
when 200...
(@population * 0.4).floor
when 150...200
(@population * 0.3).floor
when 100...150
(@population * 0.2).floor
when 50...100
(@population * 0.1).floor
else
(@population * 0.05).floor
end
print "#{@state} will lose #{number_of_deaths} people in this outbreak"
end
# Method which predicts infection rates depending on how dense the population is and prints out a statement.
def speed_of_spread
speed = if @population_density >= 200
0.5
elsif @population_density >= 150
1
elsif @population_density >= 100
1.5
elsif @population_density >= 50
2
else
2.5
end
puts " and will spread across the state in #{speed} months.\n\n"
end
end
#=======================================================================
# DRIVER CODE
# initialize VirusPredictor for each state
STATE_DATA.each do |state_name, state_info|
state = VirusPredictor.new(state_name, state_info[:population_density], state_info[:population])
state.virus_effects
end
# alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population])
# alabama.virus_effects
#
# jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population])
# jersey.virus_effects
#
# california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population])
# california.virus_effects
#
# alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population])
# alaska.virus_effects
#=======================================================================
# Reflection Section
# What are the differences between the two different hash syntaxes shown in the state_data file?
# There are a few differences with the hashes, the most apparent being that one of the hash types is a variable to the other hash's keys.
# Additionally the inner hash utilized symbols since the key names used were repetative whereas the outer hash utilized strings as the key names since each one was unique.
# What does require_relative do? How is it different from require?
# require_relative points to a file that is relative in position to the file in which it is being called.
# require seems to use the current directory from which you are running the program whereas require_relative uses the directory of where the program itself resides.
# requre_relative seems like a safer way of connecting files together for long term use.
# What are some ways to iterate through a hash?
# We used the .each method to iterate thorugh each key of the main hash.
# There are other .each methods which iterate through only the keys (.each_key) or values (.each_value).
# The .each_pair submethod seems to work very similarly to the .each method.
# Some other ways to iterate through a hash, depending on what the intention is, may be .keep_if., .reject, .select
# When refactoring virus_effects, what stood out to you about the variables, if anything?
# Since the class already had the information needed for the methods called stored as attributes of the class, it was not necessary to push them to the methods again. Attributes are available to all methods within the class.
# What concept did you most solidify in this challenge?
# We had a hard time with accessing data in the sub hash. Although we had talked about how to access that data in the sub hash, since we were passing the sub hash as one variable it took us a while to click.
|
require 'addressable/uri'
module Rack
module WebSocket
class Connection
include Debugger
def initialize(app, socket, options = {})
@app = app
@socket = socket
@options = options
@debug = options[:debug] || false
socket.websocket = self
socket.comm_inactivity_timeout = 0
if socket.comm_inactivity_timeout != 0
puts "WARNING: You are using old EventMachine version. " +
"Please consider updating to EM version >= 1.0.0 " +
"or running Thin using thin-websocket."
end
debug [:initialize]
end
def trigger_on_message(msg)
@app.on_message(msg)
end
def trigger_on_open
@app.on_open
end
def trigger_on_close
@app.on_close
end
def trigger_on_error(error)
@app.on_error(error)
end
def method_missing(sym, *args, &block)
@socket.send sym, *args, &block
end
# Use this method to close the websocket connection cleanly
# This sends a close frame and waits for acknowlegement before closing
# the connection
def close_websocket
if @handler
@handler.close_websocket
else
# The handshake hasn't completed - should be safe to terminate
close_connection
end
end
def receive_data(data)
debug [:receive_data, data]
@handler.receive_data(data)
end
def unbind
debug [:unbind, :connection]
@handler.unbind if @handler
end
def dispatch(data)
debug [:inbound_headers, data.inspect] if @debug
@handler = HandlerFactory.build(self, data, @debug)
unless @handler
# The whole header has not been received yet.
return false
end
@handler.run
return true
rescue => e
debug [:error, e]
process_bad_request(e)
return false
end
def process_bad_request(reason)
trigger_on_error(reason)
send_data "HTTP/1.1 400 Bad request\r\n\r\n"
close_connection_after_writing
end
def send(data)
debug [:send, data]
if @handler
@handler.send_text_frame(data)
else
raise WebSocketError, "Cannot send data before onopen callback"
end
end
def close_with_error(message)
trigger_on_error(message)
close_connection_after_writing
end
def request
@handler ? @handler.request : {}
end
def state
@handler ? @handler.state : :handshake
end
end
end
end
|
class RemoveIndexSubscriptionToPlan < ActiveRecord::Migration
def change
remove_foreign_key :plans , :subscription
remove_index :plans , :subscription_id
remove_column :plans , :subscription_id
add_column :plans , :owner_id , :integer
end
end
|
class Task < ApplicationRecord
belongs_to :user, optional: true
belongs_to :category
belongs_to :assigned, class_name: "User", foreign_key: "assigned_id", optional: true
end
|
class DefaultChangeValidator < ActiveModel::EachValidator # :nodoc:
def validate_each(record, attribute, value)
return unless record.default_changes[attribute]
record.errors.add(attribute, 'changed by default')
end
end |
class GroupMembership < ActiveRecord::Base
attr_accessible :join_comment
validates_presence_of :group_id, :user_id
validates_length_of :join_comment, :maximum => 200
belongs_to :user
belongs_to :group
end
|
# encoding: utf-8
#
# ะัะฝะพะฒะฝะพะน ะบะปะฐัั ะธะณัั Game. ะฅัะฐะฝะธั ัะพััะพัะฝะธะต ะธะณัั ะธ ะฟัะตะดะพััะฐะฒะปัะตั ััะฝะบัะธะธ ะดะปั
# ัะฐะทะฒะธัะธั ะธะณัั (ะฒะฒะพะด ะฝะพะฒัั
ะฑัะบะฒ, ะฟะพะดััะตั ะบะพะป-ะฒะฐ ะพัะธะฑะพะบ ะธ ั. ะฟ.).
class Game
attr_reader :letters, :good_letters, :bad_letters
attr_accessor :status, :errors
MAX_ERRORS = 7
# ะฟัะธะฝะธะผะฐะตั ะฝะฐ ะฒั
ะพะด ะทะฐะณะฐะดะฝะพะต ัะปะพะฒะพ
def initialize(word)
# ะผะฐัะธะฒ ะฑัะบะฒ
@letters = get_letters(word)
# ะะตัะตะผะตะฝะฝะฐั @errors ะฑัะดะตั ั
ัะฐะฝะธัั ัะตะบััะตะต ะบะพะปะธัะตััะฒะพ ะพัะธะฑะพะบ, ะฒัะตะณะพ ะผะพะถะฝะพ
# ัะดะตะปะฐัั ะฝะต ะฑะพะปะตะต 7 ะพัะธะฑะพะบ. ะะฐัะฐะปัะฝะพะต ะทะฝะฐัะตะฝะธะต โ 0.
@errors = 0
# ะะตัะตะผะตะฝะฝัะต @good_letters ะธ @bad_lettes ะฑัะดัั ัะพะดะตัะถะฐัั ะผะฐััะธะฒั, ั
ัะฐะฝััะธะต
# ัะณะฐะดะฐะฝะฝัะต ะธ ะฝะตัะณะฐะดะฐะฝะฝัะต ะฑัะบะฒั. ะ ะฝะฐัะฐะปะต ะธะณัั ะพะฝะธ ะฟััััะต.
@good_letters = []
@bad_letters = []
# ะกะฟะตัะธะฐะปัะฝะฐั ะฟะตัะตะผะตะฝะฝะฐั-ะธะฝะดะธะบะฐัะพั ัะพััะพัะฝะธั ะธะณัั (ัะผ. ะผะตัะพะด get_status)
@status = :in_progress
@double_words = {
"ะต" => "ั",
"ั" => "ะต",
"ะธ" => "ะน",
"ะน" => "ะธ"
}
end
# ะะตัะพะด, ะบะพัะพััะน ะฒะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ ะฑัะบะฒ ะทะฐะณะฐะดะฐะฝะฝะพะณะพ ัะปะพะฒะฐ
def get_letters(word)
if word == nil || word == ""
abort "ะฒ ัะฐะนะปะต ะฝะตัั ัะปะพะฒ"
end
word.encode('UTF-8').split("")
end
# ะะตัะพะดั, ะฒะพะทะฒัะฐัะฐััะธะต ััะฐััั ะธะณัั (
# 0 โ ะธะณัะฐ ะฐะบัะธะฒะฝะฐ
# -1 โ ะธะณัะฐ ะทะฐะบะพะฝัะตะฝะฐ ะฟะพัะฐะถะตะฝะธะตะผ
# 1 โ ะธะณัะฐ ะทะฐะบะพะฝัะตะฝะฐ ะฟะพะฑะตะดะพะน
def in_progress?
status == :in_progress
end
def won?
status == :won
end
def lost?
status == :lost || errors >= MAX_ERRORS
end
# ะบะพะป-ะฒะพ ัะพัะฐะฒัะธั
ัั ะพัะธะฑะพะบ
def errors_left
MAX_ERRORS - errors
end
# ะบะพะป-ะฒะพ ะผะฐะบั ะดะพะฟัััะธะผัั
ะพัะธะฑะพะบ
def max_errors
MAX_ERRORS
end
def is_good?(user_letter)
letters.include?(user_letter) ||
(user_letter == "ะต" && letters.include?("ั")) ||
(user_letter == "ั" && letters.include?("ะต")) ||
(user_letter == "ะธ" && letters.include?("ะน")) ||
(user_letter == "ะน" && letters.include?("ะธ"))
end
# ัะณะฐะดะฐะฝะพ ะปะธ ะฒัะต ัะปะพะฒะพ ัะตะปะธะบะพะผ
def solved?
(letters - good_letters).empty?
end
# ะะพะฒัะพััะตััั ะปะธ ะฑัะบะฒะฐ, ะบะพัะพัะฐั ัะถะต ะตััั ะฒ ะพัะณะฐะดะฐะฝัั
# ะธะปะธ ะถะต ะฟะปะพั
ะธั
(ะฝะต ัััะตััะฒัััะธั
ะฒ ัะปะพะฒะต)
def repeated?(user_letter)
good_letters.include?(user_letter) || bad_letters.include?(user_letter)
end
# ะัะฝะพะฒะฝะพะน ะผะตัะพะด ะธะณัั "ัะดะตะปะฐัั ัะปะตะดัััะธะน ัะฐะณ". ะ ะบะฐัะตััะฒะต ะฟะฐัะฐะผะตััะฐ ะฟัะธะฝะธะผะฐะตั
# ะฑัะบะฒั, ะบะพัะพััั ะฒะฒะตะป ะฟะพะปัะทะพะฒะฐัะตะปั.
def check_letter(user_letter)
# ะัะตะดะฒะฐัะธัะตะปัะฝะฐั ะฟัะพะฒะตัะบะฐ: ะตัะปะธ ััะฐััั ะธะณัั ัะฐะฒะตะฝ 1 ะธะปะธ -1, ะทะฝะฐัะธั ะธะณัะฐ
# ะทะฐะบะพะฝัะตะฝะฐ ะธ ะฝะตั ัะผััะปะฐ ะดะฐะปััะต ะดะตะปะฐัั ัะฐะณ. ะัั
ะพะดะธะผ ะธะท ะผะตัะพะดะฐ ะฒะพะทะฒัะฐัะฐั
# ะฟัััะพะต ะทะฝะฐัะตะฝะธะต.
return if status == :lost || status == :won
# ะัะปะธ ะฒะฒะตะดะตะฝะฝะฐั ะฑัะบะฒะฐ ัะถะต ะตััั ะฒ ัะฟะธัะบะต "ะฟัะฐะฒะธะปัะฝัั
" ะธะปะธ "ะพัะธะฑะพัะฝัั
" ะฑัะบะฒ,
# ัะพ ะฝะธัะตะณะพ ะฝะต ะธะทะผะตะฝะธะปะพัั, ะฒัั
ะพะดะธะผ ะธะท ะผะตัะพะดะฐ.
return if repeated?(user_letter)
# ะฑัะบะฒั (ะต ั) (ะธ ะน) ะดะพะปะถะฝั ัะฐัะฟะพะทะฝะฐะฒะฐััั ะบะฐะบ ะพะดะธะฝะฐะบะพะฒัะต ะธ ะตัะปะธ ะพัะณะฐะดะฐะฝะพ ะต ัะพ ะฒัะฒะพะดะธััั ะธ ั
if is_good?(user_letter)
good_letters << user_letter
if @double_words.value?(user_letter)
good_letters << @double_words.key(user_letter)
end
# ะะพะฟะพะปะฝะธัะตะปัะฝะฐั ะฟัะพะฒะตัะบะฐ โ ัะณะฐะดะฐะฝะพ ะปะธ ะฝะฐ ััะพะน ะฑัะบะฒะต ะฒัะต ัะปะพะฒะพ ัะตะปะธะบะพะผ.
# ะัะปะธ ะดะฐ โ ะผะตะฝัะตะผ ะทะฝะฐัะตะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน @status ะฝะฐ 1 โ ะฟะพะฑะตะดะฐ.
self.status = :won if solved?
else
# ะัะปะธ ะฒ ัะปะพะฒะต ะฝะตั ะฒะฒะตะดะตะฝะฝะพะน ะฑัะบะฒั โ ะดะพะฑะฐะฒะปัะตะผ ััั ะฑัะบะฒั ะฒ ะผะฐััะธะฒ
# ยซะฟะปะพั
ะธั
ยป ะฑัะบะฒ ะธ ัะฒะตะปะธัะธะฒะฐะตะผ ััะตััะธะบ ะพัะธะฑะพะบ.
bad_letters << user_letter
self.errors += 1
# ะัะปะธ ะพัะธะฑะพะบ ะฑะพะปััะต 7 โ ััะฐััั ะธะณัั ะผะตะฝัะตะผ ะฝะฐ -1, ะฟัะพะธะณััั.
if errors >= MAX_ERRORS
self.status = :lost
end
end
end
# ะะตัะพะด, ัะฟัะฐัะธะฒะฐััะธะน ัะทะตัะฐ ะฑัะบะฒั ะธ ะฒะพะทะฒัะฐัะฐััะธะน ะตะต ะบะฐะบ ัะตะทัะปััะฐั.
def ask_next_letter
puts "\nะะฒะตะดะธัะต ัะปะตะดััััั ะฑัะบะฒั"
letter = ""
while letter == ""
letter = STDIN.gets.encode("UTF-8").chomp.downcase
end
# ะะพัะปะต ะฟะพะปััะตะฝะธั ะฒะฒะพะดะฐ, ะฟะตัะตะดะฐะตะผ ัะฟัะฐะฒะปะตะฝะธะต ะฒ ะพัะฝะพะฒะฝะพะน ะผะตัะพะด ะธะณัั
check_letter(letter)
end
end
|
class User < ApplicationRecord
has_many :events
has_many :event_followers, foreign_key: "follower_id", dependent: :destroy
has_many :joined_events, through: :event_followers, source: :event
has_many :posts
before_save { self.email = email.downcase }
validates :email, presence: true, length: { maximum: 255 },
uniqueness: { case_sensitive: false }
has_secure_password
attr_accessor :num_events_host, :num_event_joined, :num_post
end
|
class ApplicationController < ActionController::Base
protect_from_forgery :with => :exception
before_action :authorize
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authorize
redirect_to root_path unless current_user
end
def admin_authorize
redirect_to summary_index_path if current_user && current_user.admin
end
end
|
require_relative "listings_menu"
require_relative "financial_menu"
require_relative "welcome_menu"
require_relative "../data/database_handler"
module SaveMenu
#Shows main menu for saving information to file
def SaveMenu.show
system "cls"
puts "============================================================"
puts "Save information:"
puts " 1. Selection and financials"
puts " 2. Customers and addresses"
puts " 0. Return"
puts "============================================================"
puts "What do you want to do?"
get_choice
end
#Gets the user's choice (of which submenu to display).
def SaveMenu.get_choice
choice = gets.chomp
#Handles the input from the user. Easily extendable for later.
case choice
when "1" then show_save_selection
when "2" then show_save_customers
when "0" then WelcomeMenu::show
else SaveMenu.show
end
end
#Returns an available file name for the specified string, incl. txt extension
#(i.e. if name = "testfile" and testfile.txt already exists it returns
#testfile 2.txt or continues if that is unavailable as well, otherwise just
#testfile.txt).
def SaveMenu.get_file_name(name)
file_name = name
i = 1
while File.exists?(file_name+".txt")
i += 1
file_name = name+" #{i}"
end
return file_name + ".txt"
end
#Shows the file saving progress for information about financials, selection
#and prices.
def SaveMenu.show_save_selection
system "cls"
#saves file in run path
log_name = SaveMenu.get_file_name("rbws-statistics-#{Date.today.to_s}")
puts "Outputing to file: \n#{File.expand_path(log_name)}..."
#gets all needed info from database. only other part of the application than
#DatabaseHandler that handles database queries, because it works so heavily
#and specifically with the database.
db = DatabaseHandler::get_database
order_data = db.execute("SELECT * FROM orders")
product_data = db.execute("SELECT name, id FROM selection")
price_data = db.execute("SELECT * FROM prices")
#opens file for writing
output_file = File.open(log_name, "w")
output_file.write("STATISTICS FROM RUBY BEACH WATER SPORTS RENTAL SYSTEM")
#writes orders to file
output_file.write("\n\n1. FINANCIALS\n\n")
output_file.write("1.1. ORDERS\n\n")
order_data.each { |order| output_file.write(" #{ProductHandler::get_product(order[0])}\n #{OrderHandler::get_customer(order[1])}\n $#{order[4].nil? ? 0 : order[4]}\n\n") }
#writes incomes to file
output_file.write("\n\n1.2. INCOME\n\n")
paid_orders = order_data.select { |order| not order[3].nil? }
monthly_income = Hash.new
paid_orders.each do |order|
stop_time = Time.at(order[3])
month = "#{Date::MONTHNAMES[stop_time.month]} #{stop_time.year}"
unless monthly_income.has_key?(month)
monthly_income[month] = 0
end
monthly_income[month] += order[4]
end
monthly_income.each { |month,income| output_file.write(" #{month}\n $#{income}\n\n") }
#writes price list to file
output_file.write("\n\n2. PRICE LIST\n\n")
price_data.each { |price| output_file.write(" #{price[0]}\n Base price: $#{price[1]}\n Hourly price: $#{price[2]}\n Daily price: $#{price[3]}\n\n" ) }
#writes selection list to file
output_file.write("\n\n3. SELECTION\n\n")
product_data.each { |product| output_file.write(" #{product[0]} (ID: #{product[1]})\n") }
output_file.close
puts "\nDONE!"
puts "Press any key to return."
gets
WelcomeMenu::show
end
#Shows file saving progress for customer registry.
def SaveMenu.show_save_customers
system "cls"
#saves file in run path
log_name = SaveMenu.get_file_name("rbws-customers-#{Date.today.to_s}")
puts "Outputing to file: \n#{File.expand_path(log_name)}..."
#gets customer info from database
db = DatabaseHandler::get_database
customer_data = db.execute("SELECT name, address FROM customers")
#opens file for writing
output_file = File.open(log_name, "w")
#writes customer registry
output_file.write("CUSTOMER DATA FROM RUBY BEACH WATER SPORTS RENTAL SYSTEM\n\n")
customer_data.each { |customer| output_file.write(" #{customer[0]}\n #{customer[1]}\n\n") }
output_file.close
puts "\nDONE!"
puts "Press any key to return."
gets
WelcomeMenu::show
end
end
|
require_relative 'node'
class List < Node
attr_accessor :head, :tail, :name, :count
def initialize
self.head = nil
self.tail = nil
@count = 0
end
def head_value
return self.head.data
end
def tail_value
return self.tail.data
end
def count
@count
end
def pop
return nil if self.tail.nil?
@count -= 1
node = self.tail
self.tail = self.tail.next_node
return node
end
def append(node)
@count += 1
if self.head.nil?
self.head = node
self.tail = node
else
self.tail.next_node = node
self.tail = node
end
end
def insert(node)
@count += 1
if self.head.nil?
self.head = node
elsif self.head.next_node == nil
self.head.next_node = node
end
end
def include?(find)
if self.head.data == find || self.head.next_node.data == find
true
elsif self.tail.data == find
true
else
false
end
end
def prepend(node)
@count += 1
if self.head.nil?
self.head = node
else
node.next_node = self.head
self.head = node
end
end
def find_by_value(value)
if @count < 1
false
else
current_node = self.head
while current_node
return current_node if value == current_node.data
current_node = current_node.next_node
end
false
end
end
end
|
json.array!(@current_telematics_data) do |current_telematics_datum|
json.extract! current_telematics_datum, :id, :vehicle_id, :vin_number, :gps_date_time, :lat, :lon, :direction, :gps_speed, :soc, :dte, :odometer, :car_status, :hvac_status, :server_time
json.url current_telematics_datum_url(current_telematics_datum, format: :json)
end
|
require 'spec_helper'
describe Comment do
let(:user) { FactoryGirl.create(:user) }
let(:sticker) { FactoryGirl.create(:sticker) }
before do
@comment = Comment.new(comment: "A comment on a sticker by a user", user_id: user.id, sticker_id:sticker.id)
end
subject { @comment }
it { should respond_to(:comment) }
it { should respond_to(:user_id) }
it { should respond_to(:sticker_id)}
end
|
require "enex/version"
require "builder"
require "base64"
module Enex
class Note
ATTRIBUTE_NAMES = [:export_date, :title, :content, :created, :updated, :tags, :resources]
attr_accessor *ATTRIBUTE_NAMES
def initialize(attributes = {})
attributes.each do |k, v|
raise "Unknown attribute: #{k.inspect}" unless ATTRIBUTE_NAMES.include?(k)
send("#{k}=", v)
end
self.tags ||= []
self.resources ||= []
end
def to_xml
x = Builder::XmlMarkup.new
x.instruct! :xml
x.declare! :DOCTYPE, :"en-export", :SYSTEM, "http://xml.evernote.com/pub/evernote-export3.dtd"
x.tag!("en-export", "export-date": time_to_s(export_date)){|x|
x.note{|x|
x.title title
x.content{|x| x.cdata! content }
x.created created if created
x.update updated if updated
tags.each{|tag| x.tag tag }
# TODO note-attributes
resources.each{|resource| x.resouce {|x| resource.build_xml_fragment(x) } }
}
}
x.target!
end
def time_to_s(t)
t.utc.strftime("%Y%m%dT%H%M%SZ")
end
class Resource
ATTRIBUTE_NAMES = [:data, :mime, :width, :height, :duration]
attr_accessor *ATTRIBUTE_NAMES
def initialize(attributes = {})
attributes.each do |k, v|
raise "Unknown attribute: #{k.inspect}" unless ATTRIBUTE_NAMES.include?(k)
send("#{k}=", v)
end
end
def build_xml_fragment(x)
x.data Base64.encode64(data), encoding: "base64"
x.mime mime
x.width width if width
x.height height if height
x.duration duration if duration
# TODO recognition, resource-attributes, alternate-data
end
end
end
end
|
class AddMessageUrl < ActiveRecord::Migration
def change
add_column :guests, :recording_url, :string
end
end
|
require 'securerandom'
require './token'
module Sapphire
class SEXP
attr_accessor :children, :token, :uuid, :parent_id
def initialize(tkn=nil)
@uuid = SecureRandom.uuid
@token = tkn
@children = []
end
def to_s
return "<SEXP id=#{@uuid} #{@token}>"
end
def append(el)
el.parent_id = @uuid
@children.push(el)
end
end
end |
class CreateOferta < ActiveRecord::Migration[5.1]
def change
create_table :oferta do |t|
t.date :fecha
t.string :cargo
t.string :empresa
t.string :descripcion
t.timestamps
end
end
end
|
Given /^an answer "([^\"]*)"$/ do |answer|
@json_hash = { "text" => answer,
"id" => 46672912,
"user" => {"name" => "Angie",
"description" => "TV junkie...",
"location" => "NoVA",
"profile_image_url" => "http:\/\/assets0.twitter.com\/system\/user\/profile_image\/5483072\/normal\/eye.jpg?1177462492",
"url" => nil,
"id" => 5483072,
"protected" => false,
"screen_name" => "ang_410"},
"created_at" => "Wed May 02 03:04:54 +0000 2007"}
@status = Twitter::Status.new @json_hash
end
Given /^the movie title was "([^\"]*)"$/ do |title|
@movie = Question.create(:title => title)
end
When /^we compare them the answers$/ do
@result = @movie.match_title(@status.text)
end
Then /^we should announce the winner$/ do
Twitter::Client.expects(:from_config).with(File.join(RAILS_ROOT, 'config', 'twitter4r.yml'), 'test').returns(@t = mock('twitter'))
name = @movie.title[0..59]
s = "#MovieTwitvia @ang_410 won! The movie was #{name}. http://www.amazon.com/s/?url=search-alias=aps&field-keywords=#{URI.encode(@movie.title)}&tag=carmudgeonsco-20&link_code=wql&camp=212361&creative=380601&_encoding=UTF-8"
@t.expects(:status).with(:post, s).returns(stub(:id => '123'))
@movie.tweet_winner(@status.user.screen_name)
end
Then /^match should return "([^\"]*)"$/ do |truth|
@result.should == (truth == 'true') ? true : false
end
Then /^we record the winner$/ do
User.expects(:find_by_twitter_id).with("5483072").returns(@u=stub(:id => 123, :wins_count => 0))
@u.expects(:update_attribute).with(:wins_count, 1)
@movie.finalize(@status.user.id.to_s)
@movie.reload.winner_id.should == 123
end
#TBD: maybe verify the user's winning_count |
require 'test_helper'
class BrowserReadersControllerTest < ActionController::TestCase
setup do
@browser_reader = browser_readers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:browser_readers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create browser_reader" do
assert_difference('BrowserReader.count') do
post :create, browser_reader: { description: @browser_reader.description, link: @browser_reader.link, title: @browser_reader.title, version: @browser_reader.version }
end
assert_redirected_to browser_reader_path(assigns(:browser_reader))
end
test "should show browser_reader" do
get :show, id: @browser_reader
assert_response :success
end
test "should get edit" do
get :edit, id: @browser_reader
assert_response :success
end
test "should update browser_reader" do
patch :update, id: @browser_reader, browser_reader: { description: @browser_reader.description, link: @browser_reader.link, title: @browser_reader.title, version: @browser_reader.version }
assert_redirected_to browser_reader_path(assigns(:browser_reader))
end
test "should destroy browser_reader" do
assert_difference('BrowserReader.count', -1) do
delete :destroy, id: @browser_reader
end
assert_redirected_to browser_readers_path
end
end
|
module Bothan
module Helpers
module App
def config
{
title: ENV['METRICS_API_TITLE'],
description: ENV['METRICS_API_DESCRIPTION'],
license: {
name: ENV['METRICS_API_LICENSE_NAME'],
url: ENV['METRICS_API_LICENSE_URL'],
image: license_image(ENV['METRICS_API_LICENSE_URL'])
},
publisher: {
name: ENV['METRICS_API_PUBLISHER_NAME'],
url: ENV['METRICS_API_PUBLISHER_URL']
},
certificate_url: ENV['METRICS_API_CERTIFICATE_URL']
}
end
def license_image(url)
match = url.match /https?:\/\/creativecommons.org\/licenses\/([a-z\-]+)\/([0-9\.]+)/
if match
"https://licensebuttons.net/l/#{match[1]}/#{match[2]}/88x31.png"
else
nil
end
end
def error_406
content_type 'text/plain'
error 406, "Not Acceptable"
end
def error_400(error)
content_type 'text/plain'
error 400, {:status => error}.to_json
end
end
end
end
|
describe "OrderItemsRequests", :type => :request do
around do |example|
bypass_rbac do
example.call
end
end
let(:tenant) { create(:tenant) }
let!(:order_1) { create(:order, :tenant_id => tenant.id) }
let!(:order_2) { create(:order, :tenant_id => tenant.id) }
let!(:order_3) { create(:order, :tenant_id => tenant.id) }
let!(:order_item_1) { create(:order_item, :order_id => order_1.id, :portfolio_item_id => portfolio_item.id, :tenant_id => tenant.id) }
let!(:order_item_2) { create(:order_item, :order_id => order_2.id, :portfolio_item_id => portfolio_item.id, :tenant_id => tenant.id) }
let(:portfolio_item) { create(:portfolio_item, :service_offering_ref => "123", :tenant_id => tenant.id) }
let(:params) do
{ 'order_id' => order_1.id,
'portfolio_item_id' => portfolio_item.id,
'count' => 1,
'service_parameters' => {'name' => 'fred'},
'provider_control_parameters' => {'age' => 50},
'service_plan_ref' => '10' }
end
describe "CRUD" do
context "when listing order_items" do
describe "GET /orders/:order_id/order_items" do
it "lists order items under an order" do
get "/api/v1.0/orders/#{order_1.id}/order_items", :headers => default_headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data'].first['id']).to eq(order_item_1.id.to_s)
end
context "when the order does not exist" do
let(:order_id) { 0 }
it "returns a 404" do
get "/api/v1.0/orders/#{order_id}/order_items", :headers => default_headers
expect(response.content_type).to eq("application/json")
expect(JSON.parse(response.body)["message"]).to eq("Not Found")
expect(response).to have_http_status(:not_found)
end
end
end
it "list all order items by tenant" do
get "/api/v1.0/order_items", :headers => default_headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data'].collect { |item| item['id'] }).to match_array([order_item_1.id.to_s, order_item_2.id.to_s])
end
end
context "when creating order_items" do
before do
ManageIQ::API::Common::Request.with_request(default_request) do
post "/api/v1.0/orders/#{order_3.id}/order_items", :headers => default_headers, :params => params
end
end
it "create an order item under an order" do
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:ok)
end
it "stores the x-rh-insights-id from the headers" do
get "/api/v1.0/orders/#{order_3.id}/order_items", :headers => default_headers
expect(json["data"].first["insights_request_id"]).to eq default_headers["x-rh-insights-request-id"]
end
end
context "when showing order_items" do
it "show an order_item under an order" do
get "/api/v1.0/orders/#{order_1.id}/order_items/#{order_item_1.id}", :headers => default_headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:ok)
end
it "show an order_item" do
get "/api/v1.0/order_items/#{order_item_1.id}", :headers => default_headers
expect(response.content_type).to eq("application/json")
expect(response).to have_http_status(:ok)
end
end
end
end
|
class Action
attr_accessor :name, :callback
def initialize(name, &callback)
self.name = name
self.callback = callback
end
def do(player)
# Should return true if this action consumed the player's turn
# False if it did not.
unless self.callback.nil?
return self.callback.call(player)
else
return false
end
end
end
module ActionContainer
def self.included(cls)
cls.instance_eval do
def self.actions
@actions ||= []
end
def self.action(name, &callback)
action = Action.new name
action.callback = callback
self.actions << action
end
end
end
def actions
return self.class.actions
end
end
|
class PagesController < ApplicationController
def home
@date = Date.today
if current_user
@pair = current_user.pairs.find_by_day(Date.today)
end
end
end
|
class Category < ApplicationRecord
# Required fields:
validates :name, presence: true
# Other methods:
def total_hours_completed
time_records = TimeRecord.by_category(self.id)
hours_completed_sum = 0
time_records.each do |time_record|
hours_completed_sum += time_record.total_hours
end
return hours_completed_sum
end
def total_hours_planned
planned_shifts = PlannedShift.by_category(self.id)
hours_planned_sum = 0
planned_shifts.each do |planned_shift|
hours_planned_sum += planned_shift.total_hours
end
return hours_planned_sum
end
end
|
require_relative 'board.rb'
require_relative 'player.rb'
class Game
attr_reader :players, :player_one, :player_two, :board, :current_player
def initialize(player1, player2)
@player_one, @player_two = Player.new(player1), Player.new(player2)
player_one.color, player_two.color = "white", "black"
@board = Board.new
@players = [player_one, player_two]
@current_player = players.first
end
def play
until game_over?
board.current_player = current_player
take_turn
rotate_players
end
system('clear')
board.render
puts "#{players.first.color.capitalize} is in checkmate!"
puts "Game over! #{players.last.name} won!"
end
def rotate_players
@players.rotate!
@current_player = players.first
end
def take_turn
render_with_instructions
begin
move_positions = get_valid_input
board.move!(move_positions)
rescue MoveError => e
puts e.message
retry
end
end
def get_valid_input
board.current_selection = []
move_positions = []
while move_positions.count < 2 do
#@board.debugging_output
movement = @current_player.get_cursor_movement
if movement == "\r" && valid_helper(move_positions)
move_positions << board.cursor
board.current_selection = board.cursor
end
board.move_cursor(movement)
render_with_instructions
end
if move_positions.uniq.count == 1 || !board[move_positions[0]].moves.include?(move_positions[1])
move_positions = get_valid_input
end
board.current_selection = []
move_positions
end
def valid_helper(arr)
(board.occupied? && selected_right_color) || (arr.length == 1)
end
def selected_right_color
board.all_color_positions(@current_player.color).include?(board.cursor)
end
def render_with_instructions
system('clear')
board.render
puts "Please make a move #{@current_player.name}. Your color is #{@current_player.color}"
puts "#{@current_player.color.capitalize} is in check" if board.in_check?(@current_player.color)
puts "______________________________________________________"
puts "Instructions:"
puts "Please use WASD to navigate and Enter to select."
puts "Cancel a move by selecting the same piece twice, push Q to quit"
end
def game_over?
board.game_over?
end
end
# game = Game.new(Player.new("Sam"),Player.new("Zach"))
# game.play
|
# encoding: utf-8
require 'spec_helper'
describe TTY::Table::Renderer, 'with style' do
let(:header) { ['h1', 'h2', 'h3'] }
let(:rows) { [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3']] }
let(:table) { TTY::Table.new(header, rows) }
let(:color) { Pastel.new(enabled: true) }
subject(:renderer) { described_class.select(type).new(table) }
before { allow(Pastel).to receive(:new).and_return(color) }
context 'when basic renderer' do
let(:type) { :basic }
it "sets through hash" do
renderer.border(style: :red)
expect(renderer.border.style).to eql(:red)
end
it "sets through attribute" do
renderer.border.style = :red
expect(renderer.border.style).to eql :red
end
it "renders without color" do
expect(renderer.render).to eq <<-EOS.normalize
h1 h2 h3
a1 a2 a3
b1 b2 b3
EOS
end
end
context 'when ascii renderer' do
let(:type) { :ascii }
let(:red) { "\e[31m" }
let(:clear) { "\e[0m" }
it "renders border in color" do
renderer.border.style= :red
expect(renderer.render).to eq <<-EOS.normalize
#{red}+--+--+--+#{clear}
#{red}|#{clear}h1#{red}|#{clear}h2#{red}|#{clear}h3#{red}|#{clear}
#{red}+--+--+--+#{clear}
#{red}|#{clear}a1#{red}|#{clear}a2#{red}|#{clear}a3#{red}|#{clear}
#{red}|#{clear}b1#{red}|#{clear}b2#{red}|#{clear}b3#{red}|#{clear}
#{red}+--+--+--+#{clear}
EOS
end
end
context 'when unicode renderer' do
let(:type) { :unicode }
let(:red) { "\e[31m" }
let(:clear) { "\e[0m" }
it "renders each row" do
renderer.border.style= :red
expect(renderer.render).to eq <<-EOS.normalize
#{red}โโโโฌโโโฌโโโ#{clear}
#{red}โ#{clear}h1#{red}โ#{clear}h2#{red}โ#{clear}h3#{red}โ#{clear}
#{red}โโโโผโโโผโโโค#{clear}
#{red}โ#{clear}a1#{red}โ#{clear}a2#{red}โ#{clear}a3#{red}โ#{clear}
#{red}โ#{clear}b1#{red}โ#{clear}b2#{red}โ#{clear}b3#{red}โ#{clear}
#{red}โโโโดโโโดโโโ#{clear}
EOS
end
end
end
|
module Soulmate
module Helpers
def prefixes_for_phrase(phrase)
Soulmate.get_words(phrase).map do |w|
(MIN_COMPLETE-1..(w.length-1)).map{ |l| w[0..l] }
end.flatten.uniq
end
def normalize(str)
Soulmate.normalize(str)
end
end
end |
Given /^the content "([^\"]*)" for slot "([^\"]*)"$/ do |content, slot|
# def put(base_key, cobrand, preview, name, contents)
Cms.instance.put "home_#{slot}", Cobrand.root, false, slot, content
end
Given /^featured reviews? for (.*)$/ do |product_names|
@reviews = product_names.split(/,\s*/).map { |title|
Factory :review, :product => Factory(:product, :title => title.gsub(/^"|"$/) {})
}
CobrandParam.create_or_update! Cobrand.root, :featured_reviews, @reviews.map(&:id) * ","
end
Given /^featured products? (.*)$/ do |product_names|
build_products(product_names)
CobrandParam.create_or_update! Cobrand.root, :featured_products, @products.map(&:id) * ","
end
Given /^products? (.*)$/ do |product_names|
build_products(product_names)
end
Given /^featured guides? for (.*)$/ do |category_names|
build_guides(category_names)
CobrandParam.create_or_update! Cobrand.root, :featured_guides, @guides.map(&:id) * ","
end
Given /^guides? for (.*)$/ do |category_names|
build_guides(category_names)
end
Given /^featured members? (.*)$/ do |screen_names|
@guides = screen_names.split(/,\s*/).map { |name|
returning Factory(:user, :screen_name => name.gsub(/^"|"$/) {}) do |user|
Factory :review, :user => user
end
}
end
private
def build_products(names)
@products = names.split(/,\s*/).map { |title|
Factory :product, :title => title.gsub(/^"|"$/) {}
}
end
def build_guides(names)
@guides = names.split(/,\s*/).map { |name|
corrected = name.gsub(/^"|"$/) {}
Factory :guide, :title => corrected, :subject => Factory(:category, :name => corrected)
}
end
|
describe ::Treasury::Processors::HashOperations do
let(:dummy_class) do
Class.new do
include Treasury::Processors::HashOperations
end
end
let(:dummy) { dummy_class.new }
let(:raw_value) { '123:321,234:432' }
describe '#increment_raw_value' do
let(:result) { dummy.increment_raw_value(raw_value, company_id) }
context 'when company_id is in raw_value' do
let(:company_id) { '123' }
it { expect(result).to eq '123:322,234:432' }
end
context 'when company_id is not in raw_value' do
let(:company_id) { '666' }
it { expect(result).to eq '123:321,234:432,666:1' }
end
context 'when step greater than 1' do
let(:result) { dummy.increment_raw_value raw_value, company_id, step }
let(:company_id) { '123' }
let(:step) { "5" }
it { expect(result).to eq '123:326,234:432' }
end
end
describe '#decrement_raw_value' do
let(:result) { dummy.decrement_raw_value(raw_value, company_id) }
context 'when company_id is in raw_value' do
let(:company_id) { '123' }
it { expect(result).to eq '123:320,234:432' }
end
context 'when company_id is not in raw_value' do
let(:company_id) { '666' }
it { expect(result).to eq '123:321,234:432' }
end
context 'when new values goes zero' do
let(:raw_value) { '123:1,234:432' }
let(:company_id) { '123' }
it { expect(result).to eq '234:432' }
end
context 'when step greater than 1' do
let(:result) { dummy.decrement_raw_value raw_value, company_id, step }
let(:company_id) { '123' }
let(:step) { "5" }
it { expect(result).to eq '123:316,234:432' }
end
end
end
|
class CreateSusuInvites < ActiveRecord::Migration[6.1]
def change
create_table :susu_invites do |t|
t.boolean :accepted, default: false
t.references :susu, null: false, foreign_key: true
t.references :sender, null: false, foreign_key: {to_table: :users} # Custom solution to address the renaming of user to sender
t.references :recipient, null: false, foreign_key: {to_table: :users} # Custom solution to address the renaming of user to recipient
t.timestamps
end
end
end
|
class Aws::SdbInterface
def put_attributes(domain_name, item_name, attributes, replace = false, expected_attributes = {})
params = params_with_attributes(domain_name, item_name, attributes, replace, expected_attributes)
link = generate_request("PutAttributes", params)
request_info( link, QSdbSimpleParser.new )
rescue Exception
on_exception
end
def delete_attributes(domain_name, item_name, attributes = nil, expected_attributes = {})
params = params_with_attributes(domain_name, item_name, attributes, false, expected_attributes)
link = generate_request("DeleteAttributes", params)
request_info( link, QSdbSimpleParser.new )
rescue Exception
on_exception
end
private
def pack_expected_attributes(attributes) #:nodoc:
{}.tap do |result|
idx = 0
attributes.each do |attribute, value|
v = value.is_a?(Array) ? value.first : value
result["Expected.#{idx}.Name"] = attribute.to_s
result["Expected.#{idx}.Value"] = ruby_to_sdb(v)
idx += 1
end
end
end
def pack_attributes(attributes = {}, replace = false, key_prefix = "")
{}.tap do |result|
idx = 0
if attributes
attributes.each do |attribute, value|
v = value.is_a?(Array) ? value.first : value
result["#{key_prefix}Attribute.#{idx}.Replace"] = 'true' if replace
result["#{key_prefix}Attribute.#{idx}.Name"] = attribute
result["#{key_prefix}Attribute.#{idx}.Value"] = ruby_to_sdb(v)
idx += 1
end
end
end
end
def params_with_attributes(domain_name, item_name, attributes, replace, expected_attrubutes)
{}.tap do |p|
p['DomainName'] = domain_name
p['ItemName'] = item_name
p.merge!(pack_attributes(attributes, replace)).merge!(pack_expected_attributes(expected_attrubutes))
end
end
end
|
require 'oystercard'
describe Oystercard do
describe 'structure' do
it 'has a balance of zero when created' do
expect(subject.balance).to eq(0)
end
it 'starts with an empty journey history' do
expect(subject.journeys).to be_empty
end
end
describe 'top_up' do
it 'can add to the balance' do
subject.top_up(4)
expect(subject.balance).to eq(4)
end
it 'can not have a balance over CARD_LIMIT' do
expect { subject.top_up(Oystercard::CARD_LIMIT + 1) }.to raise_error("Balance over #{Oystercard::CARD_LIMIT}")
end
end
describe 'deduct' do
let(:station){ double(:station) }
it 'can have an amount deducted from the balance' do
subject.top_up(1)
subject.touch_in(station)
subject.touch_out(station)
expect(subject.balance).to eq(0)
end
end
describe 'touch_in' do
let(:entry_station) { double(:station) }
let(:exit_station) { double(:station) }
let(:entry_journey) { {entry: entry_station} }
it 'can touch in at a station' do
subject.top_up(1)
subject.touch_in(entry_station)
expect(subject.in_journey?).to eq(true)
end
it 'has to have at least the minimum fare in balance to touch in' do
expect { subject.touch_in(entry_station) }.to raise_error("You need at least #{Oystercard::MINIMUM} in balance to travel")
end
it 'stores an entry_station upon touching in' do
subject.top_up(1)
subject.touch_in(entry_station)
expect(subject.entry_station).to eq(entry_station)
end
it 'sets the exit_station nil upon touching in' do
subject.top_up(1)
subject.touch_in(entry_station)
expect(subject.exit_station).to eq(nil)
end
it 'adds the entry_station to a new hash to start a journeys history' do
subject.top_up(1)
subject.touch_in(entry_station)
expect(subject.journeys.last).to eq(entry_journey)
end
end
describe 'touch_out' do
let(:exit_station) { double(:station) }
let(:entry_station) { double(:station) }
let(:journey) { {entry: entry_station, exit: exit_station} }
it 'can touch out at a station' do
subject.top_up(1)
subject.touch_in(entry_station)
subject.touch_out(exit_station)
expect(subject.in_journey?).to eq(false)
end
it 'removes the minimum fare from balance when touching out' do
subject.top_up(1)
subject.touch_in(entry_station)
expect { subject.touch_out(exit_station) }.to change { subject.balance }.by(-Oystercard::MINIMUM)
end
it 'forgets the entry_station after touching out' do
subject.top_up(1)
subject.touch_in(entry_station)
subject.touch_out(exit_station)
expect(subject.entry_station).to eq(nil)
end
it 'sets the exit_station after touching out' do
subject.top_up(1)
subject.touch_in(entry_station)
subject.touch_out(exit_station)
expect(subject.exit_station).to eq(exit_station)
end
it 'stores the exit_station to the last hash in the journeys' do
subject.top_up(1)
subject.touch_in(entry_station)
subject.touch_out(exit_station)
expect(subject.journeys.last).to eq(journey)
end
end
describe 'in_journey?' do
let(:station){ double(:station) }
it 'has a status to indicate when user is on a journey' do
subject.top_up(1)
subject.touch_in(station)
expect(subject.in_journey?).to eq(true)
end
end
end
|
require 'oystercard'
describe Oystercard do
let(:station) {double("Kings cross")}
let(:exit_station){double("Station")}
it "the balance should be 0 by default" do
expect(subject.balance).to eq 0
end
it "raises error when balance + top up amounts to a set limit" do
allow(subject).to receive(:balance) {described_class::MAXIMUM}
expect{subject.top_up(1)}.to raise_error ('Unable to top up,maximum #{Oystercard::MAXIMUM} reached')
end
#
it "should deduct money from balance when used" do
subject.top_up(10)
subject.touch_in(station)
expect { subject.touch_out(exit_station) }.to change{subject.balance}.by(-described_class::MIN_FAIR)
end
describe "#touch_in" do
it "raises error when credit is less then ยฃ1 minimum fare" do
subject.top_up(0.9)
expect{subject.touch_in(station)}.to raise_error('Insufficient funds')
end
end
describe "#touch_out" do
it "touches out oystercard" do
subject.top_up(10)
subject.touch_in(station)
subject.touch_out(exit_station)
expect(subject.in_journey?).to eq(false)
end
it "deducts minimum fair from balance when touched out" do
subject.top_up(10)
subject.touch_in(station)
expect{subject.touch_out(exit_station)}.to change{subject.balance}.by (-described_class::MIN_FAIR)
end
# it "stores the exit_station" do
# subject.top_up(10)
# subject.touch_in(:station)
# subject.touch_out(:exit_station)
# expect(subject.exit_station).to eq(:exit_station)
# end
describe '#in_journey?' do
it 'it returns true when touched in' do
subject.top_up(10)
subject.touch_in(station)
expect(subject.in_journey?).to eq(true)
end
end
end
end
|
require 'spec_helper'
describe WithingsSDK::Utils do
let (:startdateymd) { Hash['startdateymd', '2012-01-01'] }
let (:startdate) { Hash['startdate', 1325376000 ] }
let (:enddateymd) { Hash['enddateymd', '2015-05-12'] }
let (:enddate) { Hash['enddate', 1431388800 ] }
describe '.normalize_date_params' do
context 'when given a startdate in ymd format' do
let (:opts) { subject.normalize_date_params(startdateymd) }
it 'preserves startdateymd' do
expect(opts['startdateymd']).to eq(startdateymd['startdateymd'])
end
it 'copies the value to startdate as a timestamp' do
expect(opts['startdate']).to eq(startdate['startdate'])
end
end
context 'when given an enddate in ymd format' do
let (:opts) { subject.normalize_date_params(enddateymd) }
it 'preserves enddateymd' do
expect(opts['enddateymd']).to eq(enddateymd['enddateymd'])
end
it 'copies the value to enddate as a timestamp' do
expect(opts['enddate']).to eq(enddate['enddate'])
end
end
context 'when given a startdate in unix timestamp format' do
let (:opts) { subject.normalize_date_params(startdate) }
it 'preserves startdate' do
expect(opts['startdate']).to eq(startdate['startdate'])
end
it 'copies the value to startdateymd in YYYY-MM-DD format' do
expect(opts['startdateymd']).to eq('2012-01-01')
end
end
context 'when given a Date instance' do
context 'as a startdateymd param' do
let(:startdateymd) { Hash['startdateymd', Date.new(2012, 01, 01)] }
let(:opts) { subject.normalize_date_params(startdateymd) }
it 'converts the Date instance into YYYY-MM-DD format' do
expect(opts['startdateymd']).to eq('2012-01-01')
end
it 'converts the Date instance into timestamp format' do
expect(opts['startdate']).to eq(1325376000)
end
end
context 'as a startdate param' do
let(:startdate) { Hash['startdate', Date.new(2012, 01, 01)] }
let(:opts) { subject.normalize_date_params(startdate) }
it 'converts the Date instance into YYYY-MM-DD format' do
expect(opts['startdateymd']).to eq('2012-01-01')
end
it 'converts the Date instance into timestamp format' do
expect(opts['startdate']).to eq(1325376000)
end
end
end
context 'when given a timestamp' do
context 'as a startdateymd param' do
let(:startdateymd) { Hash['startdateymd', 1325376000] }
let(:opts) { subject.normalize_date_params(startdateymd) }
it 'converts the timestamp into YYYY-MM-DD format' do
expect(opts['startdateymd']).to eq('2012-01-01')
end
it 'copies the timestamp into the startdate param' do
expect(opts['startdate']).to eq(1325376000)
end
end
context 'as a startdate param' do
let(:startdate) { Hash['startdate', 1325376000] }
let(:opts) { subject.normalize_date_params(startdate) }
it 'converts the timestamp into YYYY-MM-DD format' do
expect(opts['startdateymd']).to eq('2012-01-01')
end
end
end
end
end
|
class Ticket < ActiveRecord::Base
belongs_to :user
def self.in_month(month, product)
where("opened >= ? AND opened <= ? AND product = ?", month.beginning_of_month, month.end_of_month, product)
end
end
|
## General options
set :step, 10
set :border_snap, 10
set :gravity, :ct66
set :tiling, false
set :honor_size_hints, false
set :urgent, false
set :urgent_dialogs, false
set :click_to_focus, false
set :skip_pointer_warp, false
set :skip_urgent_warp, false
## Panels
screen 1 do
top [ :views, :separator, :title, :spacer, :mpd, :clock2 ]
bottom [ ]
end
screen 2 do
top [ :views, :seperator, :title, :spacer, :mpd, :clock2 ]
bottom [ ]
end
## Addons
# No addons for now
## Colors
background_1 = "#151515"
background_2 = "#353535"
color_above = "#ebebeb"
color_light = "#0077bb"
color_medium = "#545454"
color_dark = "#303030"
## Styles
style :all do
background "#202020"
icon "#757575"
border "#303030", 0
padding 0, 3
#font "*-*-*-*-*-*-12-*-*-*-*-*-*-*"
font "xft:terminus-8"
#font "xft:Ohsnap:pixelsize=12:antialias=false"
end
# Style for the all views
style :views do
foreground "#757575"
# Style for the active views
style :focus do
foreground "#fecf35"
icon "#FFFF00"
end
# Style for urgent window titles and views
style :urgent do
foreground "#ff9800"
icon "#FF0000"
end
# Style for occupied views (views with clients)
style :occupied do
foreground "#b8b8b8"
icon "#00BFFF"
end
end
style :subtle do
padding 0, 0, 0, 0
margin 0, 0, 0, 0
panel_top background_1
panel_bottom background_1
end
style :clients do
padding 0, 0, 0, 0
margin 4, 4, 4, 4
active color_above, 1
inactive background_2, 1
width 75
end
style :title do
padding 1, 4, 2, 4
margin 0, 0, 0, 0
foreground color_above
background background_1
font "xft:Ohsnap:pixelsize=12:antialias=false"
end
style :sublets do
padding 1, 4, 2, 4
margin 0, 0, 0, 0
foreground color_medium
background background_1
icon color_light
font "xft:Ohsnap:pixelsize=12:antialias=false"
end
style :separator do
padding 1, 2, 2, 2
margin 0, 0, 0, 0
foreground color_light
background background_1
separator "|"
font "xft:Ohsnap:pixelsize=10:antialias=false"
end
## Gravities
# Top left
gravity :tl_a1, [ 0, 0, 33, 33 ]
gravity :tl_a2, [ 0, 0, 50, 33 ]
gravity :tl_a3, [ 0, 0, 67, 33 ]
gravity :tl_b1, [ 0, 0, 33, 50 ]
gravity :tl_b2, [ 0, 0, 50, 50 ]
gravity :tl_b3, [ 0, 0, 67, 50 ]
gravity :tl_c1, [ 0, 0, 33, 67 ]
gravity :tl_c2, [ 0, 0, 50, 67 ]
gravity :tl_c3, [ 0, 0, 67, 67 ]
# Top center
gravity :tc_a1, [ 0, 0, 100, 50 ]
gravity :tc_a2, [ 0, 0, 100, 67 ]
gravity :tc_a3, [ 0, 0, 100, 33 ]
gravity :tc_b1, [ 33, 0, 34, 33 ]
gravity :tc_b2, [ 33, 0, 34, 50 ]
gravity :tc_b3, [ 33, 0, 34, 67 ]
# Top right
gravity :tr_a1, [ 67, 0, 33, 33 ]
gravity :tr_a2, [ 50, 0, 50, 33 ]
gravity :tr_a3, [ 33, 0, 67, 33 ]
gravity :tr_b1, [ 67, 0, 33, 50 ]
gravity :tr_b2, [ 50, 0, 50, 50 ]
gravity :tr_b3, [ 33, 0, 67, 50 ]
gravity :tr_c1, [ 67, 0, 33, 67 ]
gravity :tr_c2, [ 50, 0, 50, 67 ]
gravity :tr_c3, [ 33, 0, 67, 67 ]
# Left
gravity :l_a1, [ 0, 33, 33, 34 ]
gravity :l_a2, [ 0, 33, 50, 34 ]
gravity :l_a3, [ 0, 33, 67, 34 ]
gravity :l_b1, [ 0, 0, 33, 100 ]
gravity :l_b2, [ 0, 0, 50, 100 ]
gravity :l_b3, [ 0, 0, 67, 100 ]
# Center
gravity :ct, [ 0, 0, 100, 100 ]
gravity :ct33, [ 33, 33, 34, 34 ]
gravity :ct66, [ 25, 25, 50, 50 ], :vert
gravity :ct40, [ 0, 33, 100, 34 ]
# Right
gravity :r_a1, [ 67, 33, 33, 34 ]
gravity :r_a2, [ 50, 33, 50, 34 ]
gravity :r_a3, [ 33, 33, 67, 34 ]
gravity :r_b1, [ 67, 0, 33, 100 ]
gravity :r_b2, [ 50, 0, 50, 100 ]
gravity :r_b3, [ 33, 0, 67, 100 ]
# Bottom left
gravity :bl_a1, [ 0, 67, 33, 33 ]
gravity :bl_a2, [ 0, 67, 50, 33 ]
gravity :bl_a3, [ 0, 67, 67, 33 ]
gravity :bl_b1, [ 0, 50, 33, 50 ]
gravity :bl_b2, [ 0, 50, 50, 50 ]
gravity :bl_b3, [ 0, 50, 67, 50 ]
gravity :bl_c1, [ 0, 33, 33, 67 ]
gravity :bl_c2, [ 0, 33, 50, 67 ]
gravity :bl_c3, [ 0, 33, 67, 67 ]
# Bottom center
gravity :bc_a1, [ 0, 50, 100, 50 ]
gravity :bc_a2, [ 0, 33, 100, 67 ]
gravity :bc_a3, [ 0, 67, 100, 33 ]
gravity :bc_b1, [ 33, 67, 34, 33 ]
gravity :bc_b2, [ 33, 50, 34, 50 ]
gravity :bc_b3, [ 33, 33, 34, 67 ]
# Bottom right
gravity :br_a1, [ 67, 67, 33, 33 ]
gravity :br_a2, [ 50, 67, 50, 33 ]
gravity :br_a3, [ 33, 67, 67, 33 ]
gravity :br_b1, [ 67, 50, 33, 50 ]
gravity :br_b2, [ 50, 50, 50, 50 ]
gravity :br_b3, [ 33, 50, 67, 50 ]
gravity :br_c1, [ 67, 33, 33, 67 ]
gravity :br_c2, [ 50, 33, 50, 67 ]
gravity :br_c3, [ 33, 33, 67, 67 ]
# Special
gravity :sp_br, [ 70, 85, 30, 15 ]
gravity :sp_bl, [ 0, 85, 30, 15 ]
gravity :sp_tr, [ 70, 0, 30, 15 ]
gravity :sp_tl, [ 0, 0, 30, 15 ]
# Gimp
gravity :gimp_i, [ 10, 0, 80, 100 ]
gravity :gimp_t, [ 0, 0, 10, 100 ]
gravity :gimp_d, [ 90, 0, 10, 100 ]
## Grabs
# Cycle between given gravities
grab "W-KP_7", [ :tl_a1, :tl_a2, :tl_a3, :tl_b1, :tl_b2, :tl_b3, :tl_c1, :tl_c2, :tl_c3 ]
grab "W-KP_8", [ :tc_b1, :tc_b2, :tc_b3, :tc_a3, :tc_a1, :tc_a2 ]
grab "W-KP_9", [ :tr_a1, :tr_a2, :tr_a3, :tr_b1, :tr_b2, :tr_b3, :tr_c1, :tr_c2, :tr_c3 ]
grab "W-KP_4", [ :l_a1, :l_a2, :l_a3, :l_b1, :l_b2, :l_b3 ]
grab "W-KP_5", [ :ct33 , :ct66, :ct, :ct40 ]
grab "W-KP_6", [ :r_a1, :r_a2, :r_a3, :r_b1, :r_b2, :r_b3 ]
grab "W-KP_1", [ :bl_a1, :bl_a2, :bl_a3, :bl_b1, :bl_b2, :bl_b3, :bl_c1, :bl_c2, :bl_c3 ]
grab "W-KP_2", [ :bc_b1, :bc_b2, :bc_b3, :bc_a3, :bc_a1, :bc_a2 ]
grab "W-KP_3", [ :br_a1, :br_a2, :br_a3, :br_b1, :br_b2, :br_b3, :br_c1, :br_c2, :br_c3 ]
grab "W-KP_0", [ :sp_br, :sp_bl, :sp_tr, :sp_tl ]
# Naviguate through clients
grab "A-Tab" do
clients = Subtlext::Client.visible
clients.last.instance_eval do
focus
raise
end
end
# Go to next non-empty view
grab "C-F8" do
vArr = Subtlext::View[:all];
cindx = vArr.index(Subtlext::View.current);
for i in 1..vArr.size do
cV = vArr[(i + cindx) % vArr.size];
if (!cV.clients.empty? && Subtlext::View.visible.index(cV) == nil) then
cV.jump;
break;
end
end
end
# Go to previous non-empty view
grab "C-F9" do
vArr = Subtlext::View[:all].reverse;
cindx = vArr.index(Subtlext::View.current);
for i in 1..vArr.size do
cV = vArr[(i + cindx) % vArr.size];
if (!cV.clients.empty? && Subtlext::View.visible.index(cV) == nil) then
cV.jump;
break;
end
end
end
grab "W-1", :ViewSwitch1
grab "W-2", :ViewSwitch2
grab "W-3", :ViewSwitch3
grab "W-4", :ViewSwitch4
grab "W-5", :ViewSwitch5
grab "W-6", :ViewSwitch6
grab "W-7", :ViewSwitch6
# Subtle actions
grab "W-C-r", :SubtleReload
grab "W-A-r", :SubtleRestart
grab "W-C-q", :SubtleQuit
# Window actions
grab "W-B1", :WindowMove
grab "W-Up", :WindowMoveUp
grab "W-Right", :WindowMoveRight
grab "W-Down", :WindowMoveDown
grab "W-Left", :WindowMoveLeft
grab "W-B3", :WindowResize
grab "W-C-Up", :WindowResizeUp
grab "W-C-Right", :WindowResizeRight
grab "W-C-Down",:WindowResizeDown
grab "W-C-Left",:WindowResizeLeft
# grab "W-h", :WindowLeft
# grab "W-j", :WindowDown
# grab "W-k", :WindowUp
# grab "W-l", :WindowRight
# grab "W-r", :WindowRaise
# grab "W-s", :WindowLower
grab "W-q", :WindowKill
grab "W-S-f", :WindowFloat
grab "W-S-d", :WindowFull
grab "W-S-s", :WindowStick
# Shortcuts
grab "W-Return", "rxvt -name terminal"
grab "W-s", "sublime_text"
grab "W-w", "firefox"
grab "W-v", "rxvtc -name vim -e vim"
grab "W-g", "steam"
grab "W-m", "thunderbird"
grab "W-i", "gimp"
grab "W-a", "skype"
grab "W-z", "filezilla"
grab "W-l", "sleep 1 && xset dpms force off"
# Screen capture
grab "Print", "cd ~/Pictures && scrot && cd ~"
## Tags
# Simple tags
tag "web", "chromium|firefox|filezilla"
tag "msg", "skype|ekiga|thunderbird"
tag "steam", "steam"
tag "media", "easytag|sonata|audacity|gimp|feh"
# Placement
tag "web_full" do
match "chromium|firefox"
gravity :ct
end
tag "msg_full" do
match "thunderbird"
gravity :ct
end
tag "media_full" do
match "libreoffice|audacity|easytag"
gravity :ct
end
# Apps definition
tag "terms" do
match :instance => "terminal"
end
tag "vim" do
match :instance => "vim"
gravity :ct
end
tag "minecraft" do
match :name => "Minecraft*|minecraft*"
end
tag "flash" do
match "<unknown>|plugin-container|exe|operapluginwrapper|npviewer.bin"
end
# Modes
tag "stick" do
match "mplayer"
stick true
end
tag "float" do
match "mplayer|display"
float true
end
tag "fixed" do
match "display|gimp_*"
fixed true
end
tag "borderless" do
match "display|feh"
borderless true
end
tag "urgent" do
match "display"
urgent true
end
tag "resize" do
match "mplayer"
resize true
end
# Gimp
tag "gimp_image" do
match :role => "gimp-image-window"
gravity :gimp_i
end
tag "gimp_toolbox" do
match :role => "gimp-toolbox$"
gravity :gimp_t
end
tag "gimp_dock" do
match :role => "gimp-dock"
gravity :gimp_d
end
tag "gimp_scum" do
match :role => "gimp-.*|screenshot"
end
# Autostarted stuff positionning
tag "starttwitter" do
match :instance => "starttwitter"
gravity :r_b1
end
tag "startmusic" do
match :instance => "startmusic"
gravity :tl_a3
end
tag "startterminal" do
match :instance => "startterminal"
gravity :bl_c1
end
tag "startfiles" do
match :instance => "startfiles"
gravity :ct33
end
tag "startmixer" do
match :instance => "startmixer"
gravity :bc_b1
end
## Views
iconpath = "#{ENV["HOME"]}/.scripts/icons"
icons = true
view "main" do
match "terms|starttwitter|startmusic|startterminal|startfiles|startmixer"
icon Subtlext::Icon.new("#{iconpath}/terminal.xbm")
icon_only true
end
view "edit" do
match "vim|sublime_text"
icon Subtlext::Icon.new("#{iconpath}/edit1.xbm")
icon_only true
end
view "web" do
match "web|web_full|flash"
icon Subtlext::Icon.new("#{iconpath}/fox.xbm")
icon_only true
end
view "msg" do
match "msg|msg_full|mail"
icon Subtlext::Icon.new("#{iconpath}/mail.xbm")
icon_only true
end
view "fun" do
match "steam|minecraft"
icon Subtlext::Icon.new("#{iconpath}/game.xbm")
icon_only true
end
view "media" do
match "media|media_full|gimp_*"
icon Subtlext::Icon.new("#{iconpath}/paint.xbm")
icon_only true
end
view "other" do
match "default|<unknown>"
icon Subtlext::Icon.new("#{iconpath}/question.xbm")
icon_only true
end
## Sublets
sublet :mpd do
format_string "%artist% %title%"
show_icons false
show_colors true
show_pause true
artist_color color_medium
title_color color_light
pause_color color_medium
stop_color color_medium
stop_text "Stop"
pause_text "Pause"
not_running_text "Idle"
end
sublet :clock2 do
interval 30
time_format "%I:%M %m/%d"
time_color color_above
date_format ""
end
## Hooks
# Autostart
on :start do
Subtlext::Client.spawn "subtler -r"
# Subtlext::Client.spawn "compton -i 0.9 --focus-exclude 'height = 17 --vsync opengl'"
Subtlext::Client.spawn "feh --bg-center Pictures/wallpaper.jpg"
Subtlext::Client.spawn "sleep 1s && rxvt -name startmusic -e ncmpcpp"
Subtlext::Client.spawn "sleep 1s && rxvt -name startterminal"
end
# Client autofocus
on :client_create do |c|
c.views.first.jump
c.focus
c.raise
end
### End of configuration file
|
class CreateRaffles < ActiveRecord::Migration[6.1]
def change
create_table :raffles do |t|
t.references :user_id, null: false, foreign_key: true
t.references :type_id, null: false, foreign_key: true
t.string :title
t.text :description, null:true
t.datetime :probable_draw_date
t.datetime :sale_start_date
t.datetime :sale_end_date
t.datetime :draw_date, null:true
t.float :ticket_value
t.timestamps
end
end
end
|
require "rails_helper"
describe "Delete Template Mutation API", :graphql do
describe "deleteTemplate" do
let(:query) do
<<~'GRAPHQL'
mutation($input: DeleteTemplateInput!) {
deleteTemplate(input: $input) {
success
}
}
GRAPHQL
end
it "deletes the specified template" do
user = create(:user)
template = create(:template, user: user)
result = execute query, as: user, variables: {
input: {
id: template.id,
},
}
expect(result[:data][:deleteTemplate][:success]).to be(true)
expect(template.reload.deleted_at).not_to be(nil)
end
it "deletes global template if user is admin" do
admin = create(:user, :admin)
template = create(:global_template)
result = execute query, as: admin, variables: {
input: {
id: template.id,
},
}
expect(result[:data][:deleteTemplate][:success]).to be(true)
expect(template.reload.deleted_at).not_to be(nil)
end
end
end
|
module ActiveRecordSimpledbAdapter
module Defaults
def self.included(base)
base.send :alias_method_chain, :initialize, :defaults
end
def initialize_with_defaults(attrs = nil)
initialize_without_defaults(attrs) do
safe_attribute_names = []
if attrs
stringified_attrs = attrs.stringify_keys
safe_attrs = sanitize_for_mass_assignment(stringified_attrs)
safe_attribute_names = safe_attrs.keys.map { |x| x.to_s }
end
ActiveRecord::Base.connection.columns_definition(self.class.table_name).columns_with_defaults.each do |column|
has_default = !safe_attribute_names.any? { |attr_name|
attr_name =~ /^#{column.name}($|\()/
}
if has_default
value = if column.default.is_a? Proc
column.default.call
else
column.default
end
__send__("#{column.name}=", value)
changed_attributes.delete(column.name)
end
end
yield(self) if block_given?
end
end
end
end
|
class Site::CardsController < Site::DefaultController
def show
@card = Card.find(params[:id]) if params[:id]
end
end
|
class AdminsController < ApplicationController
before_action :authenticate_user!
def index
@chapters = Chapter.includes([:address])
@users = User.includes([:chapter])
authorize! :index, AdminsController
end
end
|
class WelcomeController < ApplicationController
before_action :set_raven_context
def index
Rails.logger.info("zomg division")
1 / 0
end
def view_error
end
def report_demo
@sentry_event_id = Raven.last_event_id
render(:status => 500)
end
private
def set_raven_context
Raven.user_context(id: "fake-user-id") # or anything else in session
Raven.extra_context(params: params.to_unsafe_h, url: request.url, info: "extra info")
end
end
|
require 'spec_helper'
describe GapIntelligence::CategoryVersion do
include_examples 'Record'
describe 'attributes' do
subject(:category_version) { described_class.new build(:category_version) }
it 'has name' do
expect(category_version).to respond_to(:name)
end
it 'has full_name' do
expect(category_version).to respond_to(:full_name)
end
it 'has display_name' do
expect(category_version).to respond_to(:display_name)
end
it 'has display_cents' do
expect(category_version).to respond_to(:display_cents)
end
it 'has currency' do
expect(category_version).to respond_to(:currency)
end
it 'has frequency' do
expect(category_version).to respond_to(:frequency)
end
it "has published date" do
expect(category_version.published_date).to be_an_instance_of(Date)
end
it 'has publish product location only' do
expect(category_version).to respond_to(:publish_product_location)
end
it 'has country code' do
expect(category_version).to respond_to(:country_code)
end
it 'has icon' do
expect(category_version).to respond_to(:icon)
end
it 'has report types' do
expect(category_version).to respond_to(:report_types)
end
context '#report_names' do
let!(:report_names) do
category_version.raw['report_names'].map do |report_name_attributes|
GapIntelligence::ReportName.new(report_name_attributes).raw
end
end
it 'has array of ReportName instances' do
expect(category_version.report_names.map(&:raw)).to eq(report_names)
end
end
end
end
|
class LinksChannel < ApplicationCable::Channel
def subscribed
stream_from("links_channel", coder: ActiveSupport::JSON) do |data|
transmit data
end
end
end
|
require "executables/version"
require "executables/collector"
require "executables/web"
require "executables/executor"
module Executables
class << self
attr_accessor :root_directory, :executable_directories, :async_executor
def configure
yield self
end
end
end
|
class Team
attr_accessor :name, :win, :lose, :draw
def initialize(init_name,init_win,init_lose,init_draw)
self.name = init_name
self.win = init_win
self.lose = init_lose
self.draw = init_draw
end
def calc_win_rate
self.win.to_f / (self.win.to_f + self.lose.to_f)
end
def show_team_result()
#โโ ใฎ2020ๅนดใฎๆ็ธพใฏ โณโณๅ โกโกๆ โโๅใๅ็ใฏ 0.โฝโฝโฝโฝโฝโฝใงใใ
puts "#{self.name}ใฎ2020ๅนดใฎๆ็ธพใฏ#{self.win}ๅ#{self.lose}ๆ#{self.draw}ๅใๅ็ใฏ#{self.calc_win_rate}ใงใใ"
end
end
team_Giants = Team.new("Giants",67,45,8)
team_Tigers = Team.new("Tigers",60,53,7)
team_Dragons = Team.new("Dragons",60,55,5)
team_BayStars = Team.new("BayStars",56,58,6)
team_Carp = Team.new("Carp",52,56,12)
team_Swallows = Team.new("Swallows",41,69,10)
team_Giants.show_team_result()
team_Tigers.show_team_result()
team_Dragons.show_team_result()
team_BayStars.show_team_result()
team_Carp.show_team_result()
team_Swallows.show_team_result()
|
module Fog
module Storage
class GoogleJSON
module GetObjectHttpsUrl
def get_object_https_url(bucket_name, object_name, expires, options = {})
raise ArgumentError.new("bucket_name is required") unless bucket_name
raise ArgumentError.new("object_name is required") unless object_name
https_url(options.merge(:headers => {},
:host => @host,
:method => "GET",
:path => "#{bucket_name}/#{object_name}"),
expires)
end
end
class Real
# Get an expiring object https url from Google Storage
# https://cloud.google.com/storage/docs/access-control#Signed-URLs
#
# @param bucket_name [String] Name of bucket to read from
# @param object_name [String] Name of object to read
# @param expires [Time] Expiry time for this URL
# @return [String] Expiring object https URL
include GetObjectHttpsUrl
end
class Mock # :nodoc:all
include GetObjectHttpsUrl
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.