repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
rubinius/rubinius-bridge
lib/rubinius/bridge/compiled_code.rb
<reponame>rubinius/rubinius-bridge require "securerandom" module Rubinius class CompiledCode KernelMethodSerial = 47 attr_accessor :hints # added by the VM to indicate how it's being used. attr_accessor :metadata # [Tuple] extra data attr_accessor :name # [Symbol] name of the method attr_accessor :iseq # [Tuple] instructions to execute attr_accessor :stack_size # [Integer] size of stack at compile time attr_accessor :local_count # [Integer] number of local vars attr_accessor :required_args # [Integer] number of required args attr_accessor :post_args # [Integer] number of args after splat attr_accessor :total_args # [Integer] number of total args attr_accessor :splat # [Integer] POSITION of the splat arg attr_accessor :literals # [Tuple] tuple of the literals attr_accessor :lines # [Tuple] tuple of the lines where its found attr_accessor :file # [Symbol] the file where this comes from attr_accessor :local_names # [Array<Symbol>] names of the local vars attr_accessor :scope # [ConstantScope] scope for looking up constants attr_accessor :keywords # [Tuple] pairs of Symbol name, required flag attr_accessor :arity # [Integer] number of arguments, negative if variadic. attr_accessor :primitive attr_accessor :block_index def initialize @code_id = nil end def decode(bytecodes = @iseq) # TODO end CODE_ID_BYTES = 32 def code_id @code_id || (@code_id = SecureRandom.hex(CODE_ID_BYTES)) end def add_metadata(key, val) raise TypeError, "key must be a symbol" unless key.kind_of? Symbol case val when true, false, Symbol, Fixnum, String # ok else raise TypeError, "invalid type of value" end @metadata ||= nil # to deal with MRI seeing @metadata as not set unless @metadata @metadata = Tuple.new(2) @metadata[0] = key @metadata[1] = val return val end i = 0 fin = @metadata.size while i < fin if @metadata[i] == key @metadata[i + 1] = val return val end i += 2 end tup = Tuple.new(fin + 2) tup.copy_from @metadata, 0, fin, 0 tup[fin] = key tup[fin + 1] = val @metadata = tup return val end end end
DavidJFelix/home
Brewfile.dev.rb
<reponame>DavidJFelix/home<gh_stars>1-10 tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/cask-fonts" tap "homebrew/cask-versions" tap "homebrew/core" tap "homebrew/services" brew "asciinema" brew "asdf" brew "bazel" brew "cocoapods" brew "exa" brew "exercism" brew "gnupg" brew "jq" brew "miller" brew "ripgrep"
DavidJFelix/home
Brewfile.fonts.rb
tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/cask-fonts" tap "homebrew/core" cask "font-arvo" cask "font-fira-mono-for-powerline" cask "font-jetbrains-mono" cask "font-jetbrains-mono-nerd-font" cask "font-roboto"
DavidJFelix/home
Brewfile.core.rb
tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/core" brew "mas" cask "1password" cask "discord" cask "google-chrome" cask "kap" cask "little-snitch" cask "micro-snitch" cask "rectangle" cask "spotify" cask "visual-studio-code" cask "vlc" cask "whatsapp" cask "zoom" mas "Amphetamine", id: 937984704 mas "Gifski", id: 1351639930 mas "Keynote", id: 409183694 mas "Numbers", id: 409203825 mas "OneDrive", id: 823766827 mas "Pages", id: 409201541 mas "Slack", id: 803453959
rochefort/serie_a_bot
test/test_google_shortner.rb
<filename>test/test_google_shortner.rb require_relative "helper" require "serie_a_bot" class TestGoogleShortner < Test::Unit::TestCase sub_test_case "shorten" do sub_test_case "when correct_response" do def test_shorten_is_correct_response stub_request(:post, GoogleShortner::API_BASE_URL).to_return(status: 200, body: stub_correct_response_body) assert_equal "https://goo.gl/U98s", GoogleShortner.shorten("http://www.example.com") end end sub_test_case "when incorrect_response" do def test_shorten_is_incorrect_response_status_500 stub_request(:post, GoogleShortner::API_BASE_URL).to_return(status: 500, body: stub_correct_response_body) assert_equal "http://www.example.com", GoogleShortner.shorten("http://www.example.com") end def test_shorten_is_incorrect_response_body stub_request(:post, GoogleShortner::API_BASE_URL).to_return(status: 200, body: {}.to_json) assert_equal "http://www.example.com", GoogleShortner.shorten("http://www.example.com") end end end private def stub_correct_response_body body = { "kind": "urlshortener#url", "id": "https://goo.gl/U98s", "longUrl": "http://www.example.com" } body.to_json end end
rochefort/serie_a_bot
test/helper.rb
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), "../lib"))) ENV["RUBY_ENV"] = "test" require_relative "../config/boot" require_relative "../lib/model" require "simplecov" require "test/unit" require "test/unit/rr" require "webmock/test_unit" SimpleCov.start if ENV["COVERAGE"]
rochefort/serie_a_bot
config/boot.rb
<reponame>rochefort/serie_a_bot PROJECT_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..")) initializers_path = File.join(PROJECT_ROOT, "config/initializers") Dir.glob(File.join(initializers_path, "*.rb")).each do |f| require f end
rochefort/serie_a_bot
exe/tweet.rb
<gh_stars>0 #!/usr/bin/env ruby $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "../lib")) require "serie_a_bot" s = SerieABot.new s.tweet_rss
rochefort/serie_a_bot
config/initializers/init_environment.rb
# puts '-- called init environment' ENV["RUBY_ENV"] = "production" unless ENV["RUBY_ENV"]
rochefort/serie_a_bot
test/test_serie_a_bot.rb
<filename>test/test_serie_a_bot.rb require_relative "helper" require "serie_a_bot" class TestSerieABot < Test::Unit::TestCase setup do @bot = SerieABot.new end # privates sub_test_case "#generate_tweet" do setup do stub(GoogleShortner).shorten { "https://goo.gl/U98s" } end data( "normal" => [ "[site_title]title\ndescription\n\nhttps://goo.gl/U98s", "title", "description" ], "140 characters" => [ "[site_title]title\ndescription_is_97_9_123456789_123456789_123456789_123456789_123456789_123456789_123456789_1234567\n\nhttps://goo.gl/U98s", "title", "description_is_97_9_123456789_123456789_123456789_123456789_123456789_123456789_123456789_1234567" ], "141 characters" => [ "[site_title]title\ndescription_is_98_9_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345...\nhttps://goo.gl/U98s", "title", "description_is_98_9_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345678" ] ) def test_generate_tweet(data) expected, title, description = data rss_item = stub_rss_item(title, description) assert_equal expected, @bot.send(:generate_tweet, rss_item) end end def test_ymdhms expected_time = "2017-04-16 15:43:02" time = Time.parse(expected_time) assert_equal expected_time, @bot.send(:ymdhms, time) end sub_test_case "#about_serie_a?" do data( "incorrect singlebyte word" => [true, "inter", ["インテル", "イタリア", "inter"]], "incorrect multibytes word" => [true, "インテル悲願のスクデッド", ["インテル", "イタリア"]], "whitelist is empty" => [false, "インテル", []], "not found" => [false, "インテル", ["フロンターレ", "長友"]] ) def test_about_serie_a(data) expected, target, whitelist = data @bot.instance_variable_set(:@whitelist, whitelist) assert_equal expected, @bot.send(:about_serie_a?, target) end end private # TODO: use fixtures def stub_rss_item(title, description) rss_site = RssSite.new(title: "site_title") rss_item = RssItem.new(title: title, link: "http://www.example.com", description: description) rss_item.rss_site = rss_site rss_item end end
rochefort/serie_a_bot
lib/model.rb
<filename>lib/model.rb require "active_record" class BaseModel < ActiveRecord::Base self.abstract_class = true config = YAML.load_file(File.join(PROJECT_ROOT, "config/database.yml")) ActiveRecord::Base.configurations = config ActiveRecord::Base.establish_connection(ENV["RUBY_ENV"].to_sym) end class RssItem < BaseModel belongs_to :rss_site end class RssSite < BaseModel has_many :rss_items end
rochefort/serie_a_bot
lib/serie_a_bot.rb
#!/usr/bin/env ruby require_relative "../config/boot" require "json" require "rss" require "active_support/core_ext/string/filters" require "sanitize" require "twitter" require_relative "model" require_relative "google_shortner" class SerieABot MAX_TWEET_SIZE = 140 # url形式だと23bytesとして扱われる。 TWEET_URL_SIZE = 23 def initialize settings = YAML.load_file(File.join(PROJECT_ROOT, "config/settings.yml")) @client = Twitter::REST::Client.new do |c| c.consumer_key = settings["twitter"]["consumer_key"] c.consumer_secret = settings["twitter"]["consumer_secret"] c.access_token = settings["twitter"]["access_token"] c.access_token_secret = settings["twitter"]["access_token_secret"] end @whitelist = File.open("config/whitelist.txt").readlines.map(&:strip) @whitelist.delete("") @debug = !ENV["DEBUG"].nil? end def crawl sql = "REPLACE INTO rss_items(title, pub_date, description, link, tweeted_date, rss_site_id) " + "VALUES(?, ?, ?, ?, (SELECT tweeted_date FROM rss_items WHERE title = ? AND pub_date = ?), ?)" RssSite.all.each do |site| # SoccorKing の RSSがinvalidであるため、validationなしでparseを行う rss = RSS::Parser.parse(site.url, false) RssItem.transaction do rss.items.each do |item| title = item.title pub_date = ymdhms(item.date) description = Sanitize.clean(item.description).strip.gsub(/\A */, "") is_serie_a = about_serie_a?(title, description) if is_serie_a st = RssItem.connection.raw_connection.prepare(sql) st.execute(title, pub_date, description, item.link, title, pub_date, site.id) st.close end if @debug header = "---- #{site.title}" header << " ** seriea **" if is_serie_a puts header puts title puts # puts description end end end end end def tweet_rss RssItem.where(tweeted_date: nil).order("pub_date, title").limit(1).first.tap do |r| begin @client.update(generate_tweet(r)) r.update_attributes(tweeted_date: ymdhms(Time.now), title: r.title, pub_date: r.pub_date) rescue Twitter::Error::Forbidden => e # Tweet二重登録時には、DBの更新だけ行う r.update_attributes(tweeted_date: ymdhms(Time.now), title: r.title, pub_date: r.pub_date) rescue => e # do nothing p e if @debug end end end def tweet(msg) @client.update(msg) rescue => e p e if @debug end private def generate_tweet(rss_item) r = rss_item title = "[#{r.rss_site.title}]#{r.title}" link = "#{GoogleShortner.shorten(r.link)}" # title, desc, link の改行数 line_feed_number = 2 desc_size = MAX_TWEET_SIZE - TWEET_URL_SIZE - title.size - line_feed_number desc = "#{r.description}\n".truncate(desc_size) "#{title}\n#{desc}\n#{link}" end def ymdhms(time) time.strftime("%Y-%m-%d %H:%M:%S") end def about_serie_a?(*words) @whitelist.any? do |keyword| words.join.include?(keyword) end end end
rochefort/serie_a_bot
exe/regular_tweet.rb
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "../lib")) require "serie_a_bot" s = SerieABot.new msg = File.read(File.join(PROJECT_ROOT, "config/regular_msg.txt")) s.tweet(msg)
rochefort/serie_a_bot
lib/google_shortner.rb
require "json" require "httpclient" class GoogleShortner API_BASE_URL = "https://www.googleapis.com/urlshortener/v1/url" # Response: # { # "kind": "urlshortener#url", # "id": "http://goo.gl/CfPqZs", # "longUrl": "http://rochefort.hatenablog.com/" # } # # Error Response: # {"error"=> # {"errors"=> # [{"domain"=>"usageLimits", # "reason"=>"dailyLimitExceededUnreg", # "message"=> # "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", # "extendedHelp"=>"https://code.google.com/apis/console"}], # "code"=>403, # "message"=> # "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." # } # } def self.shorten(url) client = HTTPClient.new res = client.post(API_BASE_URL, body: { longUrl: url }.to_json, headers: { "Content-Type" => "application/json" } ) body = JSON.parse(res.body) return url unless res.code == 200 body["id"] || url end end
pjkelly/api_cache
spec/memory_store_spec.rb
require 'spec_helper' describe APICache::MemoryStore do let(:cache) { {} } let(:store) { APICache::MemoryStore.new(cache) } # Deleting created_at makes no sense given the way MemoryStore stores data @skip_created_at_deletion = true include_examples "generic store" end
pjkelly/api_cache
init.rb
# To use api_cache as a rails plugin require "api_cache"
pjkelly/api_cache
lib/api_cache/abstract_store.rb
class APICache class AbstractStore def initialize raise "Method not implemented. Called abstract class." end # Set value. Returns true if success. def set(key, value) raise "Method not implemented. Called abstract class." end # Get value. def get(key) raise "Method not implemented. Called abstract class." end # Delete the given key. The return value is not used. def delete(key) raise "Method not implemented. Called abstract class." end # Does a given key exist in the cache? def exists?(key) raise "Method not implemented. Called abstract class." end # created_at returns the time when the key was last set def created_at(key) raise "Method not implemented. Called abstract class." end # expired? returns true if the given timeout has passed since the key was # set. It has nothing to say about the existence or otherwise of said key. def expired?(key, timeout) if (created_at = created_at(key)) Time.now - created_at > timeout else # If the created_at data is missing assume expired true end end end end
pjkelly/api_cache
spec/null_store_spec.rb
require 'spec_helper' describe APICache::NullStore do before :each do @store = APICache::NullStore.new end it "should NOT set" do @store.exists?('foo').should be_false @store.set('foo', 'bar') @store.exists?('foo').should be_false end it "should always say keys are expired" do @store.expired?('foo', 1).should be_true @store.set('foo', 'bar') @store.expired?('foo', 1).should be_true end end
pjkelly/api_cache
spec/shared_store_specs.rb
<filename>spec/shared_store_specs.rb shared_examples "generic store" do before :each do cache.delete("foo") end it "should allow set and get" do store.set("foo", "bar") store.get("foo").should == "bar" end it "should report existence" do store.exists?("foo").should == false store.set("foo", "bar") store.exists?("foo").should == true end it "should allow checking expiration" do store.set("foo", "bar") store.expired?("foo", 1).should == false store.expired?("foo", 0).should == true end it "should return nil if not found" do store.get("nothing").should == nil end it "should be possible to delete" do store.set("foo", "bar") store.delete("key") store.exists?("key").should == false store.get("key").should == nil end unless @skip_created_at_deletion it "should claim that key has expired if _created_at key is missing" do store.set("key", "bar") store.expired?("foo", 10).should == false cache.delete("foo_created_at") store.expired?("foo", 10).should == true end end end
pjkelly/api_cache
lib/api_cache/dalli_store.rb
<reponame>pjkelly/api_cache class APICache class DalliStore < APICache::AbstractStore def initialize(store) @dalli = store end # Set value. Returns true if success. def set(key, value) @dalli.set(key, value) @dalli.set("#{key}_created_at", Time.now) true end # Get value. def get(key) @dalli.get(key) end # Delete value. def delete(key) @dalli.delete(key) end # Does a given key exist in the cache? def exists?(key) !get(key).nil? end def created_at(key) @dalli.get("#{key}_created_at") end end end
pjkelly/api_cache
lib/api_cache/api.rb
require 'net/http' class APICache # Wraps up querying the API. # # Ensures that the API is not called more frequently than every +period+ # seconds, and times out API requests after +timeout+ seconds. # class API # Takes the following options # # period:: Maximum frequency to call the API. If set to 0 then there is no # limit on how frequently queries can be made to the API. # timeout:: Timeout when calling api (either to the proviced url or # excecuting the passed block) # block:: If passed then the block is excecuted instead of HTTP GET # against the provided key # def initialize(key, options, &block) @key, @block = key, block @timeout = options[:timeout] @period = options[:period] end # Fetch data from the API. # # If no block is given then the key is assumed to be a URL and which will # be queried expecting a 200 response. Otherwise the return value of the # block will be used. # # This method can raise Timeout::Error, APICache::InvalidResponse, or any # exception raised in the block passed to APICache.get # def get check_queryable! APICache.logger.debug "APICache #{@key}: Calling API" set_queried_at Timeout::timeout(@timeout) do if @block # If this call raises an error then the response is not cached @block.call else get_key_via_http end end rescue Timeout::Error => e raise APICache::TimeoutError, "APICache #{@key}: Request timed out (timeout #{@timeout}s)" end private def get_key_via_http response = redirecting_get(@key) case response when Net::HTTPSuccess # 2xx response code response.body else raise APICache::InvalidResponse, "APICache #{@key}: InvalidResponse http response: #{response.code}" end rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Errno::ECONNREFUSED, SocketError => e raise APICache::InvalidResponse, "APICache #{@key}: Net::HTTP error (#{e.message} - #{e.class})" end def redirecting_get(url) r = Net::HTTP.get_response(URI.parse(url)) r.header['location'] ? redirecting_get(r.header['location']) : r end # Checks whether the API can be queried (i.e. whether :period has passed # since the last query to the API). # def check_queryable! if previously_queried? if Time.now - queried_at > @period APICache.logger.debug "APICache #{@key}: Is queryable - retry_time has passed" else APICache.logger.debug "APICache #{@key}: Not queryable - queried too recently" raise APICache::CannotFetch, "Cannot fetch #{@key}: queried too recently" end else APICache.logger.debug "APICache #{@key}: Is queryable - first query" end end def previously_queried? APICache.store.exists?("#{@key}_queried_at") end def queried_at APICache.store.get("#{@key}_queried_at") end def set_queried_at APICache.store.set("#{@key}_queried_at", Time.now) end end end
pjkelly/api_cache
spec/api_spec.rb
<gh_stars>100-1000 require 'spec_helper' describe APICache::API do before :each do stub_request(:get, "http://www.google.com/").to_return(:body => "Google") stub_request(:get, "http://froogle.google.com/").to_return(:status => 302, :headers => {:location => "http://products.google.com"}) stub_request(:get, "http://products.google.com/").to_return(:body => "Google Product Search") @options = { :period => 1, :timeout => 5 } # Reset the store otherwise get queried too recently erros APICache.store = nil end it "should not be queryable for :period seconds after a request" do api = APICache::API.new('http://www.google.com/', @options) api.get lambda { api.get }.should raise_error(APICache::CannotFetch, "Cannot fetch http://www.google.com/: queried too recently") sleep 1 lambda { api.get }.should_not raise_error end describe "without a block - key is the url" do it "should return body of a http GET against the key" do api = APICache::API.new('http://www.google.com/', @options) api.get.should =~ /Google/ end it "should handle redirecting get requests" do api = APICache::API.new('http://froogle.google.com/', @options) api.get.should =~ /Google Product Search/ end it "should rescue errors thrown by Net::HTTP and raise APICache::InvalidResponse" do stub_request(:get, "http://example.com/").to_raise(Errno::ECONNREFUSED) api = APICache::API.new('http://example.com/', @options) lambda { api.get }.should raise_error(APICache::InvalidResponse, "APICache http://example.com/: Net::HTTP error (Connection refused - Exception from WebMock - Errno::ECONNREFUSED)") end end describe "with a block" do it "should return the return value of the block" do api = APICache::API.new('http://www.google.com/', @options) do 42 end api.get.should == 42 end it "should return the raised exception if the block raises one" do api = APICache::API.new('foobar', @options) do raise RuntimeError, 'foo' end lambda { api.get }.should raise_error(StandardError, 'foo') end end end
pjkelly/api_cache
lib/api_cache/memory_store.rb
<filename>lib/api_cache/memory_store.rb class APICache class MemoryStore < APICache::AbstractStore def initialize(cache = {}) APICache.logger.debug "Using memory store" @cache = cache true end def set(key, value) APICache.logger.debug("cache: set (#{key})") @cache[key] = [Time.now, value] true end def get(key) data = exists?(key) ? @cache[key][1] : nil APICache.logger.debug("cache: #{data.nil? ? "miss" : "hit"} (#{key})") data end def delete(key) @cache.delete(key) end def exists?(key) !@cache[key].nil? end def created_at(key) @cache[key] && @cache[key][0] end end end
pjkelly/api_cache
spec/integration_spec.rb
<gh_stars>100-1000 require 'spec_helper' describe "api_cache" do before :each do stub_request(:get, "http://www.google.com/").to_return(:body => "Google") APICache.store = nil end it "should work when url supplied" do APICache.get('http://www.google.com/').should =~ /Google/ end it "should work when block supplied" do APICache.get('foobar') do 42 end.should == 42 end it "should raise error raised in block unless key available in cache" do lambda { APICache.get('foo') do raise RuntimeError, 'foo' end }.should raise_error(RuntimeError, 'foo') APICache.get('foo', :period => 0) do 'bar' end lambda { APICache.get('foo') do raise RuntimeError, 'foo' end }.should_not raise_error end it "should raise APICache::TimeoutError if the API call times out unless data available in cache" do lambda { APICache.get('foo', :timeout => 1) do sleep 1.1 end }.should raise_error APICache::TimeoutError, 'APICache foo: Request timed out (timeout 1s)' APICache.get('foo', :period => 0) do 'bar' end lambda { APICache.get('foo', :timeout => 1) do sleep 1.1 end }.should_not raise_error end it "should return a default value rather than raising an exception if :fail passed" do APICache.get('foo', :fail => "bar") do raise 'foo' end.should == 'bar' end it "should accept a proc to fail" do APICache.get('foo', :fail => lambda { "bar" }) do raise 'foo' end.should == 'bar' end it "should accept nil values for :fail" do APICache.get('foo', :fail => nil) do raise 'foo' end.should == nil end end
pjkelly/api_cache
spec/moneta_store_spec.rb
require 'spec_helper' require 'moneta' describe APICache::MonetaStore do let(:cache) { Moneta.new(:Memcached) } let(:store) { APICache::MonetaStore.new(cache) } include_examples "generic store" end
pjkelly/api_cache
spec/cache_spec.rb
require 'spec_helper' describe APICache::Cache do before :each do @options = { :cache => 1, # After this time fetch new data :valid => 2 # Maximum time to use old data } end it "should set and get" do cache = APICache::Cache.new('flubble', @options) cache.set('Hello world') cache.get.should == 'Hello world' end it "should md5 encode the provided key" do cache = APICache::Cache.new('test_md5', @options) APICache.store.should_receive(:set). with('9050bddcf415f2d0518804e551c1be98', 'md5ing?') cache.set('md5ing?') end it "should report correct invalid states" do cache = APICache::Cache.new('foo', @options) cache.state.should == :missing cache.set('foo') cache.state.should == :current sleep 1 cache.state.should == :refetch sleep 1 cache.state.should == :invalid end it "should initially have invalid state" do cache = APICache::Cache.new('foo', @options) cache.state.should == :invalid end end
pjkelly/api_cache
spec/dalli_store_spec.rb
require 'spec_helper' require 'dalli' describe APICache::DalliStore do let(:cache) { Dalli::Client.new("localhost:11211") } let(:store) { APICache::DalliStore.new(cache) } include_examples "generic store" end
pjkelly/api_cache
lib/api_cache.rb
require 'logger' # Contains the complete public API for APICache. # # See APICache.get method and the README file. # # Before using APICache you should set the store to use using # APICache.store=. For convenience, when no store is set an in memory store # will be used (and a warning will be logged). # class APICache class APICacheError < RuntimeError; end class NotAvailableError < APICacheError; end class TimeoutError < NotAvailableError; end class InvalidResponse < NotAvailableError; end class CannotFetch < NotAvailableError; end class << self attr_accessor :logger attr_accessor :store def logger # :nodoc: @logger ||= begin log = Logger.new(STDOUT) log.level = Logger::INFO log end end # Set the logger to use. If not set, <tt>Logger.new(STDOUT)</tt> will be # used. # def logger=(logger) @logger = logger end def store # :nodoc: @store ||= begin APICache.logger.warn("Using in memory store") APICache::MemoryStore.new end end # Set the cache store to use. This should either be an instance of a # moneta store or a subclass of APICache::AbstractStore. Moneta is # recommended. # def store=(store) @store = begin if store.class < APICache::AbstractStore store elsif store.class.to_s =~ /Moneta/ MonetaStore.new(store) elsif store.nil? nil else raise ArgumentError, "Please supply an instance of either a moneta store or a subclass of APICache::AbstractStore" end end end end # Optionally call with a block. The value of the block is then used to # set the cache rather than calling the url. Use it for example if you need # to make another type of request, catch custom error codes etc. To signal # that the call failed just raise any exception - the value will then # not be cached and the api will not be called again for options[:timeout] # seconds. If an old value is available in the cache then it will be # returned. # # An exception will be raised if the API cannot be fetched and the request # cannot be served by the cache. This will either be a subclass of # APICache::Error or an exception raised by the provided block. # # For example: # APICache.get("http://twitter.com/statuses/user_timeline/6869822.atom") # # APICache.get \ # "http://twitter.com/statuses/user_timeline/6869822.atom", # :cache => 60, :valid => 600 # def self.get(key, options = {}, &block) options = { :cache => 600, # 10 minutes After this time fetch new data :valid => 86400, # 1 day Maximum time to use old data # :forever is a valid option :period => 60, # 1 minute Maximum frequency to call API :timeout => 5 # 5 seconds API response timeout }.merge(options) cache = APICache::Cache.new(key, { :cache => options[:cache], :valid => options[:valid] }) api = APICache::API.new(key, { :period => options[:period], :timeout => options[:timeout] }, &block) cache_state = cache.state if cache_state == :current APICache.logger.debug "APICache #{@key}: Returning from cache" cache.get else begin value = api.get cache.set(value) value rescue => e APICache.logger.info "APICache #{key}: Exception raised (#{e.message} - #{e.class})" \ # No point outputting backgraces for internal APICache errors APICache.logger.debug "Backtrace:\n#{e.backtrace.join("\n")}" unless e.kind_of?(APICacheError) if cache_state == :refetch cache.get else APICache.logger.warn "APICache #{key}: Data not available in the cache or from API" if options.has_key?(:fail) fail = options[:fail] fail.respond_to?(:call) ? fail.call : fail else raise e end end end end end # Manually delete data from the cache. # def self.delete(key) APICache::Cache.new(key, {}).delete end end require 'api_cache/cache' require 'api_cache/api' APICache.autoload 'AbstractStore', 'api_cache/abstract_store' APICache.autoload 'DalliStore', 'api_cache/dalli_store' APICache.autoload 'MemoryStore', 'api_cache/memory_store' APICache.autoload 'MonetaStore', 'api_cache/moneta_store' APICache.autoload 'NullStore', 'api_cache/null_store'
dustmoo/seadragon-paperclip
libs/paperclip_processors/tile_art.rb
#Code for Tiler from http://blog.aisleten.com/2007/08/25/attachment_fu-s3-ruby-tile-cutter-google-maps-easy-custom-maps-in-ruby-on-rails/ #Taken from his modified tiler and then modified! :D Thanks for thie inspiration! #This is released under the MIT License which only applies to this code and not RMagic or Paperclip, which are dependancies of this code. # Coded by <NAME>, <EMAIL> # #The MIT License # #Copyright (c) 2010 Starr Map Company LLC # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. #This is a processor for the rails gem paperclip: http://github.com/thoughtbot/paperclip and is used according to their processor guidelines. with png support. #This processor also require the RMagic gem http://github.com/rmagick/rmagick module Paperclip class TileArt < Processor attr_accessor :whiny require 'RMagick' def initialize(file, options = {}, attachment = nil) super #Object is the parent object of the image attachment in this case the paperclip attachment is in a SeadragonImage object. This is so we can get it's id to set path names @object = attachment.instance @tile_size = 256 @max_width = Paperclip::Geometry.from_file(file).width @max_height = Paperclip::Geometry.from_file(file).height @whiny = options[:whiny].nil? ? true : options[:whiny] @basename = File.basename(attachment.path, File.extname(attachment.path)) @tmpname = File.basename(file.path, File.extname(file.path)) @max_level = get_max_level(@max_width, @max_height) end def make info = Tempfile.new([ @tmpname, 'xml' ].compact.join(".")) level = @max_level @width = @max_width @height = @max_height #This sets up the XML string for Seadragon to store in the location of the files. tile_xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Image TileSize=\"256\" Overlap=\"1\" Format=\"png\" ServerFormat=\"Default\" xmlns=\"http://schemas.microsoft.com/deepzoom/2009\"><Size Width=\""+@max_width.to_s+"\" Height=\""+@max_height.to_s+"\" /></Image>" info << tile_xml #I store my xml string in my Seadragon Object make sure you ad tile_xml to your model or comment this out. @object.tile_xml = tile_xml #Convert the original upload to a tmp ping to tile from. convert_from_path = File.expand_path(file.path) file_name = "tmp.png" #Begin Tile Processing while level >= 0 if @width < 256 || @height < 256 file_name = "0_0.png" end columns = (@width/@tile_size).ceil rows = (@height/@tile_size).ceil #The base path of where you want to store your tiles, I use system to prevent development/production conflicts with capistrano deployment. local_base_path = "#{RAILS_ROOT}/public/system/arts/"+@object.id.to_s+"/"+options[:geometry][:style]+"/#{@basename}_files" #Do not change tilepath, it writes the tile filenames in the way Seadragon likes. tile_path = local_base_path +"/"+level.to_s #+"/"+columns.to_s+"_"+rows.to_s+".png"attachment.path.gsub(/\.[a-z][a-z][a-z]$/, "") tile_file_path = tile_path+"/"+file_name FileUtils.mkdir_p(tile_path) unless @max_width == @width || @max_height == @height cmd = "-flatten "+convert_from_path+" -resize "+@width.to_s+"x"+@height.to_s+"\\> "+tile_file_path else cmd = "-flatten "+convert_from_path+" "+tile_file_path end begin Paperclip.run("convert", cmd) rescue PaperclipCommandLineError raise PaperclipError, "There was an error processing the tiles for #{@basename}" if whiny end #S3 processing #connect_to_S3 image_to_tile = Magick::ImageList.new(tile_file_path) (0..columns).each do |c| x = (c * 256) (0..rows).each do |r| y = (r * 256) tile = image_to_tile.crop(x, y, 258, 258) tile_file_name = c.to_s+"_"+r.to_s+".png" write_path = tile_path +"/"+tile_file_name #Uncomment for S3 storage, set the s3 path to how you want it stored on Se # s3_path = "arts/"+@object.id.to_s+"/"+options[:geometry][:style]+"/#{@basename}_files/"+level.to_s+"/"+tile_file_name tile.write(write_path) # AWS::S3::S3Object.store(s3_path, open(write_path), "smcwidget",{:access => :public_read }.update(options)) tile_info = Tile.new(:path => s3_path) @object.tiles << tile_info end end #We convert from our converted thumbs to reduce processing time convert_from_path = tile_file_path @width = (@width/2).ceil @height = (@height/2).ceil level = level - 1 end #Uncomment if using S3 to Remove Local Tiles after processing is done. # FileUtils.remove_entry_secure(local_base_path, true) info.rewind # This is the processor output, which in this case is actually the XML file, the tiles are written by RMagick. info end #Math to determine how many levels of tiles we need to make. def get_max_level(width, height) h = [width, height] max = h.max level = log_with_base(2, max).ceil return level end #Setup log with base for max level function def log_with_base(base, num) Math.log(num) / Math.log(base) end #If you want to store your tiles on S3. def connect_to_S3 unless AWS::S3::Base.connected? AWS::S3::Base.establish_connection!(:access_key_id => 'yourkey', :secret_access_key => 'youraccesskey') end end end end
utkarsh2102/aruba
lib/aruba/platforms/determine_disk_usage.rb
require 'aruba/file_size' module Aruba module Platforms # Determinate disk usage # # @private class DetermineDiskUsage def call(paths) size = paths.flatten.map do |path| minimum_disk_space_used path end.inject(0, &:+) FileSize.new(size) end private # TODO: Aruba.config.physical_block_size could be allowed to be nil # (So the unit size can be autodetected) # Report minimum disk space used # # This estimates the minimum bytes allocated by the path. # # E.g. a 1-byte text file on a typical EXT-3 filesystem takes up 4096 bytes # (could be more if it was truncated or less for sparse files). # # Both `File::Stat` and the `stat()` system call will report 8 `blocks` # (each "usually" represents 512 bytes). So 8 * 512 is exactly 4096 bytes. # # (The "magic" 512 bye implied makes the value of "blocks" so confusing). # # Currently Aruba allows you to set what's called the `physical_block_size`, # which is a bit misleading - it's the "512" value. So if you somehow have a # "filesystem unit size" of 8192 (instead of a typical 4KB), set the # `physical_block_size` to 1024 (yes, divide by 8: 8192/8 = 1024). # # Ideally, Aruba should provide e.g. `Aruba.config.fs_allocation_unit` # (with 4096 as the default), so you wouldn't have to "divide by 8". # # (typical_fs_unit / typical_dev_bsize = 4096 / 512 = 8) # # # @return [Integer] # Total bytes allocate # # TODO: this is recommended over the above "blocks" def minimum_disk_space_used(path) # TODO: replace Aruba.config.physical_block_size # with something like Aruba.config.fs_allocation_unit dev_bsize = Aruba.config.physical_block_size stat = File::Stat.new(path.to_s) blocks = stat.blocks return (blocks * dev_bsize) if blocks typical_fs_unit = 4096 typical_dev_bsize = 512 # google dev_bsize for more info block_multiplier = typical_fs_unit / typical_dev_bsize fs_unit_size = dev_bsize * block_multiplier fs_units = (stat.size + fs_unit_size - 1) / fs_unit_size fs_units = 1 if fs_units.zero? fs_units * fs_unit_size end end end end
poloniculmov/google_music_api
lib/google_music_api/playlist.rb
module GoogleMusicApi #Holds all the playlist related methods module Playlist #Gets all the playlists that user has #@return [Array] of Hashes that describe a playlist def get_all_playlists url = 'playlistfeed' make_post_request(url).fetch('data', {'items' => []})['items'] end #Gets all the tracks in the user's own playlists. Doesn't include subscribed playlists. If you want to get the tracks of a single playlist, use # {get_shared_playlists_entries} #@return [Array] of hashes describing playlist entries. Each Playlist entry will have the playlist's id and the track description def get_own_playlists_entries url = 'plentryfeed' make_post_request(url).fetch('data', {'items' => []})['items'] end #Gets all the playlist entries of a playlist that user is subscribed to #@return [Array] of describing playlist entries # @param [String] share_token - this is not the playlist's id, but the share_token # @example get_shared_playlists_entries 'AMaBXykmxW9ZMK3C7WvoLKDw8AQB00UNiHXEwWwFRZ8lGc9yfb-SFI6nmj6t-IZKE5AvKFlVSzmU2wmQ2j0e3RqCJe4ytpBAMQ==' def get_shared_playlists_entries(share_token) url = 'plentries/shared' options = {body: {entries: [{ shareToken: share_token }] }.to_json } make_post_request(url, options) end #Creates a playlist # @param [String] name # @param [String] description, default = '' # @param [boolean] public, default = false # @return [Hash] with the API response, status is in the 'response_code' key def create_playlist(name, description = '', public = false) create_playlists [{name: name, description: description, public: public}][0] end #Batch creates playlists # @param [Array] playlist_descriptions, consists of one or more hashes with the keys :name, :description and :public # @return [Array] of hashes with the result of each creation operation def create_playlists(playlist_descriptions = []) url = 'playlistbatch' creates = playlist_descriptions.map do |pd| { create: { creationTimestamp: '-1', deleted: false, lastModifiedTimestamp: '0', name: pd[:name], description: pd.fetch(:description, ''), type: 'USER_GENERATED', shareState: (pd.fetch(:public, false) ? 'PUBLIC' : 'PRIVATE') } } end options = { body: {mutations: creates}.to_json } make_post_request(url, options).fetch('mutate_response') end # Updates a single playlist # @param [string] id, the actual id, not the share token # @param [string] new_name # @param [string] new_description # @param [boolean] new_public # @return [Hash] with the API response, status is in the 'response_code' key def update_playlist(id, new_name = nil, new_description = nil, new_public = nil) update_playlists [{id: id, name: new_name, description: new_description, public: new_public}][0] end # Batch updates one or more playlists # @param [Array] playlist_descriptions, consists of one or more hashes with the keys id:, :name, :description and :public # @return [Array] of hashes with the result of each creation operation def update_playlists(playlist_descriptions) url = 'playlistbatch' updates = playlist_descriptions.map do |pd| { update: { id: pd[:id], name: pd[:name], description: pd[:description], shareState: (pd[:public] ? 'PUBLIC' : 'PRIVATE') } } end options = { body: {mutations: updates}.to_json } make_post_request(url, options).fetch('mutate_response') end #Deletes a playlist # @param [string] id # @return [Hash] with the API response, status is in the 'response_code' key def delete_playlist(id) delete_playlists([id])[0] end # Batch deletes one or more playlists # @return [Array] of hashes with the result of each creation operation # @param [Array] ids def delete_playlists(ids = []) url = 'playlistbatch' deletes = ids.map do |pd| { delete: pd } end options = { body: {mutations: deletes}.to_json } make_post_request(url, options).fetch('mutate_response') end # Adds tracks to a playlist # @param [string] playlist_id # @param [array] track_ids def add_tracks_to_playlist(playlist_id, track_ids) url = 'plentriesbatch' options = {} prev_id, cur_id, next_id = nil, SecureRandom.uuid, SecureRandom.uuid mutations = [] track_ids.each_with_index do |value, index| m_details = { clientId: cur_id, creationTimestamp: '-1', deleted: false, lastModifiedTimestamp: '0', playlistId: playlist_id, source: 1, trackId: value, } m_details[:source] = 2 if value[0] == 'T' m_details[:precedingEntryId] = prev_id if index > 0 m_details[:followingEntryId] = next_id if index < value.length - 1 mutations << {create: m_details} prev_id, cur_id, next_id = cur_id, next_id, SecureRandom.uuid end options[:body] = {mutations: mutations}.to_json make_post_request(url, options) end #Batch removes track from playlists. You can send playlist entries of multiple playlists # @param [Array] playlist_entry_ids These are playlist entries, not track ids def remove_tracks_from_playlist(playlist_entry_ids) url = 'plentriesbatch' mutations = playlist_entry_ids.map { |id| {delete: id}} options = { body: { mutations: mutations }.to_json } make_post_request url, options end def reorder_playlist_entry throw NotImplementedError.new end protected def add_track_type(track_id) if track_id[0] == 'T' {'id': track_id, 'type': 1} else {'id': track_id, 'type': 0} end end end end
poloniculmov/google_music_api
lib/google_music_api/track.rb
<filename>lib/google_music_api/track.rb require 'base64' require 'openssl' require 'google_music_api/util' module GoogleMusicApi module Track #Gets details about a track # @param [string] track_id # @return [hash] describing the track include Util def get_track_info(track_id) url = 'fetchtrack' options = { query: { nid: track_id }, headers: { 'Content-Type': 'application/json' } } make_get_request url, options end def get_track_stream(track_id, device_id = @dev_id, quality = 'hi',url='mplay') sig,salt=get_signature(track_id) options = { query: { 'opt': quality, 'net': 'mob', 'pt': 'e', 'slt': salt, 'sig': sig }, headers: { 'X-Device-ID': device_id } } if track_id.start_with?('T') || track_id.start_with?('D') # Store track or podcast episode. options[:query]['mjck'] = track_id else options[:query]['songid'] = track_id end make_play_request url, options end #Increases a tracks play count # @param [string] song_id # @param [integer] number_of_plays # @param [Time] play_time def increase_track_play_count(song_id, number_of_plays = 1, play_time = Time.now) url = 'trackstats' options = { query: { alt: 'json' } } play_timestamp = (play_time.to_f * 1000).to_i event = { context_type: 1, event_timestamp_micros: play_timestamp, event_type: 2 } options[:body] = { track_stats: [{ id: song_id, incremental_plays: number_of_plays, last_play_time_millis: play_timestamp, type: song_id[0] == 'T' ? 2 : 1, track_events: [event] * number_of_plays }] }.to_json make_post_request url, options end #Searches tracks # @param [string] query # @param [integer] max_results # @return [Hash] describing tracks def search_tracks(query, max_results=50) search(query, '1', max_results) end end end
poloniculmov/google_music_api
lib/google_music_api/library.rb
module GoogleMusicApi #Holds all the library related methods module Library #Gets all tracks in the library# # @return [Array] of hashes describing tracks def get_all_tracks url = 'trackfeed' make_post_request(url)['data']['items'] end #Gets the promoted songs # @return [Array] of hashes describing tracks def get_promoted_songs url = 'ephemeral/top' make_post_request(url)['data']['items'] end # Gets all listen now items # return [Array] of hashes, each hash can describe a different kind of item Station/Track/Album def get_listen_now_items url = 'listennow/getlistennowitems' options = {'alt': 'json'} make_get_request(url)['listennow_items'] end def add_tracks_to_library(song_ids = []) #TODO: Implement after adding Hashie support as this needs an extra call url = 'trackbatch' throw NotImplementedError.new end end end
poloniculmov/google_music_api
lib/google_music_api/podcast.rb
<reponame>poloniculmov/google_music_api require 'google_music_api/util' require 'google_music_api/track' module GoogleMusicApi #Holds all the playlist related methods module Podcast include Util include Track #Get podcast episodes from series #@id [string] id of the podcast series #@num [int] count of episodes to grab #@return [Array] of Hashes that describe episodes in a series def get_podcast_series(id,num=25) url = 'podcast/fetchseries' options = { headers: { 'Content-Type': 'application/json' }, query: { 'alt': 'json', 'nid': id, 'num': num } } make_get_request url, options end #Gets podcast episode metadata #@id [string] podcast id #@return [Array] of Hashes that describe a playlist def get_podcast_episode(id) url = 'podcast/fetchepisode' options = { headers: { 'Content-Type': 'application/json' }, query: { 'alt': 'json', 'nid': id } } make_get_request(url,options) end def get_podcast_stream(track_id, device_id = @dev_id, quality = 'hi') url = 'fplay' get_track_stream(track_id,device_id,quality,url) end end end
poloniculmov/google_music_api
lib/google_music_api/album.rb
<reponame>poloniculmov/google_music_api module GoogleMusicApi module Album #Gets an album's details # @param [string] album_id # @param [string] include_tracks # @return [Hash] describing an album and tracks def get_album_info(album_id, include_tracks = true) url = 'fetchalbum' options = { query: { nid: album_id, 'include-tracks': include_tracks }, headers: {} } make_get_request(url, options) end #Searches albums # @param [string] query # @param [integer] max_results # @return [Hash] describing albums def search_albums(query, max_results=50) search(query, '3', max_results) end end end
poloniculmov/google_music_api
lib/google_music_api/mobile_client.rb
require 'gpsoauth' require 'google_music_api/http' require 'google_music_api/genre' require 'google_music_api/playlist' require 'google_music_api/library' require 'google_music_api/station' require 'google_music_api/album' require 'google_music_api/artist' require 'google_music_api/track' require 'google_music_api/podcast' module GoogleMusicApi class MobileClient SERVICE = 'sj' APP = 'com.google.android.music' CLIENT_SIGNATURE = '38918a453d07199354f8b19af05ec6562ced5788' STREAM_ENDPOINT = 'https://mclients.googleapis.com/music/' SERVICE_ENDPOINT = 'https://mclients.googleapis.com/sj/v2.4/' include Http include Genre include Playlist include Library include Station include Album include Artist include Track include Podcast #Pass an authorization token and you won't have to login # @param [string] authorization_token def initialize(authorization_token = nil, dev_id = nil) @authorization_token = authorization_token @dev_id = dev_id end # Logs in to Google using OAuth and obtains an authorization token # # @param email [String] your email # @param [String] password you password # @param [String] android_id 16 hex digits, eg '1234567890abcdef' # @param [String] device_country the country code of the device you're impersonating, default = 'us' # @param [String] operator_country the country code of the device's mobile operator, default = 'us' # # @raise [AuthenticationError] if authentication fails # @return true if success def login(email, password, android_id, device_country='us', operator_country='us') g = Gpsoauth::Client.new(android_id, 'ac2dm', device_country, operator_country) response = g.master_login(email, password) oauth_response = g.oauth(email, response['Token'], SERVICE, APP, CLIENT_SIGNATURE) raise AuthenticationError.new('Invalid username/password') unless oauth_response.key?('Auth') @authorization_token = oauth_response['Auth'] @dev_id = android_id true end # Checks if there's an authorization token present # @return [boolean] def authenticated? !!@authorization_token end # Checks whether the user is subscribed or not # @return [boolean] def subscribed? url = 'config' options = {query: {dv: 0}} subscribed = make_get_request(url, options)['data']['entries'].find do |item| item['key'] == 'isNautilusUser' && item['value'] == 'true' end !subscribed.nil? end #Generic search # 1: Song, 2: Artist, 3: Album, 4: Playlist, 6: Station, 7: Situation, 8: Video # @param [string] query # @param [string] ct Used to restrict search to specific items, comma-separated list of item type ids. # @param [integer] max_results def search(query, ct = '1,2,3,4,6,7,8', max_results = 50) url = 'query' options = { query: { 'ct': ct, 'q': query, 'max-results': max_results } } make_get_request(url, options)['entries'] end def authorization_token @authorization_token end end end
poloniculmov/google_music_api
lib/google_music_api/errors.rb
module GoogleMusicApi class ApiError < StandardError end class AuthenticationError < ApiError end end
poloniculmov/google_music_api
lib/google_music_api/artist.rb
module GoogleMusicApi module Artist # Gets an artists details # @param [String] artist_id # @param [boolean] include_albums # @param [integer] max_top_tracks # @param [integer] max_related_artists def get_artist_info(artist_id, include_albums = true, max_top_tracks = 5, max_related_artists = 5) url = 'fetchartist' options = { query: { nid: artist_id, 'include-albums': include_albums, 'num-top-tracks': max_top_tracks, 'num-related-artists': max_related_artists } } make_get_request(url, options) end #Searches albums # @param [string] query # @param [integer] max_results # @return [Hash] describing artists def search_artists(query, max_results=50) search(query, '2', max_results) end end end
poloniculmov/google_music_api
lib/google_music_api.rb
<filename>lib/google_music_api.rb<gh_stars>1-10 require 'google_music_api/version' require 'google_music_api/mobile_client' require 'google_music_api/errors' module GoogleMusicApi # Your code goes here... end
poloniculmov/google_music_api
lib/google_music_api/station.rb
<reponame>poloniculmov/google_music_api require 'google_music_api/util' module GoogleMusicApi module Station include Util #Gets the current listen now situations and their associated stations # @return [Array] of situations and their respected stations def get_listen_now_situations url = 'listennow/situations' options = {query: {'alt': 'json', 'tier': 'aa', 'hl': 'en_US'}} body = {'requestSignals': {'timeZoneOffsetSecs': Time.now.gmt_offset}}.to_json options[:body] = body make_post_request(url, options)['situations'] end # Gets all radio stations # It seems to be tied to what the user # @return [Array] of radios stations def get_all_stations url = 'radio/station' options = {query: {'alt': 'json', 'tier': 'aa', 'hl': 'en_US'}} make_post_request(url, options) end # Gets a station's tracks # @param [string] station_id # In newer implemtations the station_id is really another ID: Track, Album, Artist, etc... # @param [integer] number_of_tracks # @param [Array] recently_played track ids # @return [Array] of tracks def get_station_tracks(station_id, number_of_tracks = 25, recently_played = []) url = 'radio/stationfeed' options = { query: {'alt': 'json', 'include-tracks': 'true', 'tier': 'aa', 'hl': 'en_US'}, headers: {'Content-Type': 'application/json'}, body: {'contentFilter': 1, 'stations': [ { 'numEntries': number_of_tracks, 'recentlyPlayed': recently_played.map { |rec| add_track_type rec}, 'seed': { "#{get_typename_from_id(station_id)}": station_id, 'kind': 'sj#radioSeed', 'seedType': get_seed_type_from_id(station_id) } } ]}.to_json } res = make_post_request(url, options) return res['data']['stations'] end #Gets I'm feeling lucky station tracks # @param [integer] number_of_tracks # @param [Array] recently_played track ids # @return [Array] of tracks def get_im_feeling_lucky_tracks(number_of_tracks = 25, recently_played = []) get_station_tracks 'IFL', number_of_tracks, recently_played end def create_station throw NotImplementedError.new end def delete_station throw NotImplementedError.new end end end
poloniculmov/google_music_api
lib/google_music_api/http.rb
<reponame>poloniculmov/google_music_api<filename>lib/google_music_api/http.rb module GoogleMusicApi module Http private def make_get_request(url, options = {}) url ="#{self.class::SERVICE_ENDPOINT}#{url}" if options[:headers] == nil options[:headers] = {} end options[:headers]['Authorization'] = 'GoogleLogin auth='+authorization_token HTTParty.get(url, options).parsed_response end def make_play_request(url, options = {}) url ="#{self.class::STREAM_ENDPOINT}#{url}" if options[:headers] == nil options[:headers] = {} end options[:headers]['Authorization'] = 'GoogleLogin auth='+authorization_token options[:follow_redirects] = false HTTParty.get(url, options).headers['location'] end def make_post_request(url, options = {}) url ="#{self.class::SERVICE_ENDPOINT}#{url}" if options[:headers] == nil options[:headers] = {} end options[:headers]['Authorization']= 'GoogleLogin auth='+authorization_token options[:headers]['Content-Type']= 'application/json' HTTParty.post(url, options).parsed_response end end end
poloniculmov/google_music_api
lib/google_music_api/util.rb
require "base64" require 'openssl' module GoogleMusicApi module Util # Gets the radio seed type for a particular id # @param [string] id # @return [string] Type name def get_seed_type_from_id(id) case id.chars[0] when 'T' '2' when 'B' '1' when 'A' '3' when 'L' '9' else '6' end end # Gets the id type based on the ID format # TODO: This list is incomplete # @param [string] id # @return [string] Type name def get_typename_from_id(id) case id.chars[0] when 'T' 'trackId' when 'A' 'artistId' when 'B' 'albumId' when 'L' 'curatedStationId' else 'stationId' end end # Gets the key used for signing urls # @return [string] key def get_key @key = Base64.decode64('<KEY>') end # This method returns components required for url signing. # @param [string] key # @param [string] salt - Optional # @return [string,string] signature, salt def get_signature(data, salt=nil) if salt == nil salt = (Time.now.to_i * 1000).to_s end hmac = OpenSSL::HMAC.new(get_key,OpenSSL::Digest.new('sha1')) hmac << data.force_encoding("utf-8") hmac << salt.force_encoding("utf-8") sig = Base64.urlsafe_encode64(hmac.digest).chop return sig,salt end end end
poloniculmov/google_music_api
lib/google_music_api/genre.rb
module GoogleMusicApi #Keeps all the genre-related methods module Genre #Returns all genres or all subgenres if parent_id is passed # @param [String] parent_id # @return [Array] of hashes that describe a genre # @example Get all the subgenres of Jazz # mobile_client.get_genres('JAZZ') def get_genres(parent_id = nil) url = 'explore/genres' options = {} options[:query] = {'parent-genre': parent_id} if parent_id make_get_request(url, options)['genres'] end end end
poloniculmov/google_music_api
spec/mobile_client_spec.rb
<gh_stars>1-10 require 'spec_helper' describe GoogleMusicApi::MobileClient do let(:api) { GoogleMusicApi::MobileClient.new } describe '#authenticated?' do it 'returns true if authentication token is set' do api.instance_variable_set '@authorization_token', 'abc' expect(api.authenticated?).to be_truthy end it 'returns false if authentication token is not set' do api.instance_variable_set '@authorization_token', nil expect(api.authenticated?).to be_falsey end end describe '#login' do it 'throws an exception if authorization fails' do allow_any_instance_of(Gpsoauth::Client).to receive(:master_login).and_return({Token: 'a'}) allow_any_instance_of(Gpsoauth::Client).to receive(:oauth).and_return({Error: 'BadAuthentication'}) expect{api.login('<EMAIL>', 'apassword', '<PASSWORD>')}.to raise_error GoogleMusicApi::AuthenticationError end it 'authenticates the api if it succeeds' do allow_any_instance_of(Gpsoauth::Client).to receive(:master_login).and_return({Token: 'a'}) allow_any_instance_of(Gpsoauth::Client).to receive(:oauth).and_return({'Auth' => 'some ok token'}) expect(api.login('<EMAIL>', 'apassword', '<PASSWORD>')).to be_truthy expect(api.authenticated?).to be_truthy end end describe '#subscribed?' do it 'returns true if subscribed' do stub_request(:get, 'https://mclients.googleapis.com/sj/v2.4/config?dv=0'). to_return(:status => 200, :body => File.read(File.expand_path('../webmocks/', __FILE__) + '/subscribed.json'), :headers => {'Content-Type': 'application/json'}) expect(api.subscribed?).to be_truthy end it 'returns false if unsubscribed' do stub_request(:get, 'https://mclients.googleapis.com/sj/v2.4/config?dv=0'). to_return(:status => 200, :body => File.read(File.expand_path('../webmocks/', __FILE__) + '/unsubscribed.json'), :headers => {'Content-Type': 'application/json'}) expect(api.subscribed?).to be_falsey end end end
poloniculmov/google_music_api
spec/google_music_api_spec.rb
require 'spec_helper' describe GoogleMusicApi do it 'has a version number' do expect(GoogleMusicApi::VERSION).not_to be nil end end
poloniculmov/google_music_api
spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'google_music_api' require 'webmock/rspec' WebMock.disable_net_connect!(allow_localhost: true)
celluloid/culture
gems/loader.rb
<gh_stars>1-10 require "yaml" module Celluloid module Sync module Gemfile class << self def [](dsl) dsl.source("https://rubygems.org") dsl.gemspec # Runs gemspec, but also @sets gem_name. Gems.gemfile(dsl) end end end module Gemspec class << self def [](gem) Gems.gemspec(gem) end end end end module Gems extend self @gem_name = nil undef gems rescue nil def gems File.expand_path("../dependencies.yml", __FILE__) end unless @dependencies ||= nil @dependencies = YAML.load_file(gems) if File.exist?(gems) end unless @dependencies.is_a?(Hash) && @dependencies.any? raise "Celluloid cannot find its dependencies." end undef core? rescue nil def core?(name=@gem_name) return false unless @dependencies[name].is_a? Hash @dependencies[name]["dependency"] == "core" end undef separate? rescue nil def separate? !@dependencies.keys.include?(@gem_name) end undef gemspec rescue nil def gemspec(gem) @gem_name = gem.name loader do |name, spec| # Rules for dependencies, to avoid so-called circular dependency: # - Only the core gem lists all the modules as runtime dependencies. # - If this gem is not in the dependencies list, then it needs the core gem at runtime; # the module gems are development dependencies only. This is a depending separate gem. # There is the core gem, module gems, true dependencies, and separately depending gems. # - If the dependency is a module, it is only a development dependency to other modules, # and even the core gem is a development dependency. It is not expected to be used alone. meth = case spec["dependency"] when "core", "module" # For the core gem, all modules are runtime dependencies. # For separate gems, only the core gem is a runtime dependency. if core? || (separate? && core?(name)) :add_runtime_dependency else :add_development_dependency end when "development" :add_development_dependency else :add_dependency end gem.send(meth, name, spec["version"] || ">= 0") end end undef gemfile rescue nil def gemfile(dsl) loader do |name, spec| params = [name, spec["version"] || ">= 0"] req = spec["gemfile"] || {} params << req.each_with_object({}) { |(k, v), o| o[k.to_sym] = v } current = dsl.dependencies.find { |d| d.name == name } dsl.dependencies.delete(current) if current dsl.gem(*params) end end private def loader @dependencies.each do |name, spec| next if name == @gem_name spec ||= {} yield name, spec end end end end
tfhartmann/puppet-stash
spec/classes/stash_facts_spec.rb
require 'spec_helper.rb' describe 'stash::facts', :type => :class do regexp_pe = /^#\!\/opt\/puppet\/bin\/ruby$/ regexp_oss = /^#\!\/usr\/bin\/env ruby$/ pe_external_fact_file = '/etc/puppetlabs/facter/facts.d/stash_facts.rb' external_fact_file = '/etc/facter/facts.d/stash_facts.rb' it { should contain_file(external_fact_file) } # Test puppet enterprise shebang generated correctly context 'with puppet enterprise' do let(:facts) { {:puppetversion => "3.4.3 (Puppet Enterprise 3.2.1)"} } it do should contain_file(pe_external_fact_file) \ .with_content(regexp_pe) end end # Test puppet oss shebang generated correctly context 'with puppet oss' do let(:facts) { {:puppetversion => "all other versions"} } it do should contain_file(external_fact_file) \ .with_content(regexp_oss) .with_content(/7990\/rest\/api\//) end end context 'with context' do let(:params) {{ :context_path => '/stash', }} it do should contain_file(external_fact_file) \ .with_content(/7990\/stash\/rest\/api\//) end end end
tfhartmann/puppet-stash
spec/classes/stash_init_spec.rb
require 'spec_helper.rb' describe 'stash', :type => :class do context 'prepare for upgrade of stash' do let(:params) {{ :version => '3.3.3' }} let(:facts) {{ :stash_version => "2.10.1" }} it { should contain_exec('service stash stop && sleep 15').with({ :command => 'service stash stop && sleep 15', }) should contain_exec('rm -f /home/stash/stash-config.properties').with({ :command => 'rm -f /home/stash/stash-config.properties', }) } end end
tfhartmann/puppet-stash
spec/classes/stash_backup_deploy_spec.rb
require 'spec_helper.rb' describe 'stash' do describe 'stash::backup' do context 'install stash backup client with deploy module' do it { should contain_group('stash') } it { should contain_user('stash').with_shell('/bin/bash') } it 'should deploy stash backup client 1.6.0 from tar.gz' do should contain_staging__file("stash-backup-distribution-1.6.0.tar.gz") end it 'should manage the stash-backup directory' do should contain_file('/opt/stash-backup').with({ 'ensure' => 'directory', 'owner' => 'stash', 'group' => 'stash' }) end it 'should manage the stash-backup archives directory' do should contain_file('/opt/stash-backup/archives').with({ 'ensure' => 'directory', 'owner' => 'stash', 'group' => 'stash' }) end it 'should manage the backup cron job' do should contain_cron('Backup Stash').with({ 'ensure' => 'present', 'command' => '/usr/bin/java -Dstash.password="password" -Dstash.user="admin" -Dstash.baseUrl="http://localhost:7990" -Dstash.home=/home/stash -Dbackup.home=/opt/stash-backup/archives -jar /opt/stash-backup/stash-backup-client-1.6.0/stash-backup-client.jar', 'user' => 'stash', 'hour' => '5', 'minute' => '0', }) end end end end
tfhartmann/puppet-stash
spec/classes/stash_upgrade_spec.rb
<filename>spec/classes/stash_upgrade_spec.rb require 'spec_helper.rb' describe 'stash' do describe 'stash::install' do context 'default params' do let(:params) {{ :javahome => '/opt/java', }} let(:facts) { { :stash_version => "3.1.0", }} it 'should stop service and remove old config file' do should contain_exec('service stash stop && sleep 15') should contain_exec('rm -f /home/stash/stash-config.properties') end end end end
tfhartmann/puppet-stash
spec/classes/stash_config_spec.rb
require 'spec_helper.rb' describe 'stash' do describe 'stash::config' do context 'default params' do let(:params) {{ :javahome => '/opt/java', :version => '3.2.4', }} it { should contain_file('/opt/stash/atlassian-stash-3.2.4/bin/setenv.sh') \ .with_content(/JAVA_HOME=\/opt\/java/) } it { should contain_file('/opt/stash/atlassian-stash-3.2.4/bin/user.sh')} it { should contain_file('/opt/stash/atlassian-stash-3.2.4/conf/server.xml')} it { should contain_file('/home/stash/shared/stash-config.properties')} end context 'proxy settings ' do let(:params) {{ :version => '3.4.0', :proxy => { 'scheme' => 'https', 'proxyName' => 'stash.example.co.za', 'proxyPort' => '443', }, }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/conf/server.xml') \ .with_content(/proxyName = \'stash\.example\.co\.za\'/) .with_content(/proxyPort = \'443\'/) .with_content(/scheme = \'https\'/) .with_content(/path=""/) end end context 'jvm_xms => 1G' do let(:params) {{ :version => '3.4.0', :jvm_xms => '1G', }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/bin/setenv.sh') .with_content(/^JVM_MINIMUM_MEMORY="1G"/) end end context 'jvm_xmx => 4G' do let(:params) {{ :version => '3.4.0', :jvm_xmx => '4G', }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/bin/setenv.sh') .with_content(/^JVM_MAXIMUM_MEMORY="4G"/) end end context 'jvm_permgen => 384m' do let(:params) {{ :version => '3.4.0', :jvm_permgen => '384m', }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/bin/setenv.sh') .with_content(/^STASH_MAX_PERM_SIZE=384m/) end end context 'java_opts => "-Dhttp.proxyHost=proxy.example.co.za -Dhttp.proxyPort=8080"' do let(:params) {{ :version => '3.4.0', :java_opts => '-Dhttp.proxyHost=proxy.example.co.za -Dhttp.proxyPort=8080', }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/bin/setenv.sh') .with_content(/JAVA_OPTS="-Dhttp\.proxyHost=proxy\.example\.co\.za -Dhttp\.proxyPort=8080/) end end context 'context_path => "stash"' do let(:params) {{ :version => '3.4.0', :context_path => '/stash', }} it do should contain_file('/opt/stash/atlassian-stash-3.4.0/conf/server.xml') .with_content(/path="\/stash"/) end end end end
tfhartmann/puppet-stash
spec/spec_helper_acceptance.rb
require 'beaker-rspec/spec_helper' require 'beaker-rspec/helpers/serverspec' unless ENV['RS_PROVISION'] == 'no' or ENV['BEAKER_provision'] == 'no' hosts.each do |host| # This will install the latest available package on el and deb based # systems fail on windows and osx, and install via gem on other *nixes foss_opts = { :default_action => 'gem_install' } install_puppet( foss_opts ) on host, "mkdir -p #{host['distmoduledir']}" on host, "sed -i '/templatedir/d' #{host['puppetpath']}/puppet.conf" end end UNSUPPORTED_PLATFORMS = ['AIX','windows','Solaris'] RSpec.configure do |c| # Project root proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do # Install module puppet_module_install( :source => proj_root, :module_name => 'stash', :ignore_list => [ 'spec/fixtures/*', '.git/*', '.vagrant/*' ], ) hosts.each do |host| on host, "/bin/touch #{default['puppetpath']}/hiera.yaml" on host, 'chmod 755 /root' if fact('osfamily') == 'Debian' on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen" on host, '/usr/sbin/locale-gen' on host, '/usr/sbin/update-locale' end on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] } on host, puppet('module','install','puppetlabs-postgresql'), { :acceptable_exit_codes => [0,1] } on host, puppet('module','install','yguenane-repoforge'), { :acceptable_exit_codes => [0,1] } on host, puppet('module','install','mkrakowitzer-deploy'), { :acceptable_exit_codes => [0,1] } on host, puppet('module','install','puppetlabs-java'), { :acceptable_exit_codes => [0,1] } on host, puppet('module','install','nanliu-staging'), { :acceptable_exit_codes => [0,1] } end end end
tfhartmann/puppet-stash
spec/spec_helper.rb
<filename>spec/spec_helper.rb<gh_stars>0 require 'puppetlabs_spec_helper/module_spec_helper' RSpec.configure do |c| c.default_facts = { :osfamily => 'Debian', :augeasversion => '1.0.0', :staging_http_get => 'curl', :path => '/usr/local/bin:/usr/bin:/bin', :stash_version => '5.5.6', :puppetversion => '3.7.4', } end
mseri/rails-purecss
lib/purecss/generators/install_generator.rb
require 'rails/generators' module Purecss module Generators class InstallGenerator < Rails::Generators::Base source_root File.join(File.dirname(__FILE__), 'templates') argument :stylesheets_type, :type => :string, :default => 'responsive', :banner => '*responsive or nonresponsive' class_option :add_viewport_meta, :type => :boolean, :default => false, :description => "Inject Viewport Meta in the Head of layout/application.html.erb (default: false)" def add_assets if stylesheets_type=='nonresponsive' purecss_type = 'purecss-nr' elsif stylesheets_type=='responsive' purecss_type = 'purecss' else raise "'#{stylesheets_type}'' is not recognized, use either 'responsive' or 'nonresponsive'" end insert_into_file "app/assets/stylesheets/application#{detect_css_format[0]}", "#{detect_css_format[1]} require #{purecss_type}\n", :after => "require_self\n" if options.add_viewport_meta if not File.exist?("app/views/layouts/application.html.erb") raise "Unable to add viewport meta tag to (see https://github.com/mseri/rails-purecss/issues/6)" end insert_into_file "app/views/layouts/application.html.erb", " <!-- Set the viewport width to device width for mobile -->\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n", :before => "</head>" end end def detect_css_format return ['.css', ' *='] if File.exist?('app/assets/stylesheets/application.css') return ['.css.sass', ' //='] if File.exist?('app/assets/stylesheets/application.css.sass') return ['.sass', ' //='] if File.exist?('app/assets/stylesheets/application.sass') return ['.css.scss', ' //='] if File.exist?('app/assets/stylesheets/application.css.scss') return ['.scss', ' //='] if File.exist?('app/assets/stylesheets/application.scss') end end end end
mseri/rails-purecss
lib/purecss/version.rb
module Purecss VERSION = "0.5.0.2" end
mseri/rails-purecss
lib/purecss.rb
<gh_stars>1-10 require "purecss/version" require "purecss/generators/install_generator" module Purecss require "purecss/engine" end
mseri/rails-purecss
lib/purecss/engine.rb
<gh_stars>1-10 module Purecss class Engine < Rails::Engine # auto wire assets end end
mseri/rails-purecss
purecss.gemspec
<filename>purecss.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'purecss/version' Gem::Specification.new do |spec| spec.name = "purecss" spec.version = Purecss::VERSION spec.authors = ["mseri"] spec.email = ["<EMAIL>"] spec.description = %q{Pure CSS (purecss.io) toolkit for Rails Asset Pipeline} spec.summary = %q{purecss gem integrates the Pure CSS (purecss.io) toolkit to the Rails Asset Pipeline.} spec.homepage = "https://github.com/mseri/rails-purecss" spec.license = "MIT" spec.files = Dir["{app,lib,vendor}/**/*"] + ["README.md", "HISTORY.md"] #spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency 'rails', '>= 3.1' spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
panyult/LTRunLoop
LTRunLoop.podspec
<reponame>panyult/LTRunLoop<filename>LTRunLoop.podspec Pod::Spec.new do |s| s.name = 'LTRunLoop' s.version = '0.1.1' s.summary = 'LTRunLoop help you to define self-define input source when you want use the run loop of a secondary thread to handle something for you.' s.homepage = 'https://github.com/panyult/LTRunLoop' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'panyult' => '<EMAIL>' } s.source = { :git => 'https://github.com/panyult/LTRunLoop.git', :tag => s.version } s.platform = :ios, '8.0' s.requires_arc = true s.source_files = 'LTRunLoop/**/*.{h,m}' s.frameworks = 'UIKit', 'Foundation', 'CoreFoundation' end
bfernandesbfs/AirBar
AirBar.podspec
<gh_stars>0 Pod::Spec.new do |spec| spec.name = "AirBar" spec.version = "2.0.5" spec.summary = "Airbnb expandable bar." spec.homepage = "https://github.com/uptechteam/AirBar" spec.license = { type: 'MIT', file: 'LICENSE' } spec.authors = { "<NAME>" => '<EMAIL>' } spec.platform = :ios, "9.1" spec.swift_version = "4.1" spec.requires_arc = true spec.source = { git: "https://github.com/uptechteam/AirBar.git", tag: "v#{spec.version}", submodules: true } spec.source_files = "AirBar/**/*.{h,swift}" end
otamm/RMathPlus
lib/r_math_plus/version.rb
<reponame>otamm/RMathPlus<filename>lib/r_math_plus/version.rb module RMathPlus VERSION = "0.0.2" end
otamm/RMathPlus
r_math_plus.gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'r_math_plus/version' Gem::Specification.new do |spec| spec.name = "r_math_plus" spec.version = RMathPlus::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{ Math operations to use in puzzles. } spec.description = %q{ Some extra math ops to the standard library which include prime number operations and the least common multiple of an array of numbers. See the Documentation link below for further details.} spec.homepage = "https://github.com/otamm/RMathPlus" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0.0" end
otamm/RMathPlus
spec/spec_helper.rb
require 'r_math_plus'
otamm/RMathPlus
spec/r_math_plus_spec.rb
require 'spec_helper' describe RMathPlus do describe ".is_prime?" do it "returns true when a number is prime" do (RMathPlus.is_prime?(3)).should == true end it "returns false when a number is not prime" do (RMathPlus.is_prime?(4)).should == false end it "returns true when a big prime number is passed as param" do (RMathPlus.is_prime?(104729)).should == true end it "executes faster when an array is passed as second parameter" do begin1 = Time.now (RMathPlus.is_prime?(50,[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47])) finish1 = Time.now begin2 = Time.now (RMathPlus.is_prime?(50)) finish2 = Time.now ((finish1 - begin1) > (finish2 - begin2)).should == true end end describe ".prime_array" do it "returns an array with all the primes lesser than or equal to its parameter" do expect(RMathPlus.prime_array(7)).to eq [2,3,5,7] end it "returns an empty array if input < 2" do expect(RMathPlus.prime_array(0)).to eq [] end end describe ".nth_prime" do it "returns an array with the first n primes" do expect(RMathPlus.nth_prime(3)).to eq [2,3,5] end it "returns first prime if n == 1" do expect(RMathPlus.nth_prime(1)).to eq [2] end it "returns the primes in correct order" do expect(RMathPlus.nth_prime(100)[-1]).to eq 541 end end describe ".prime_factors" do it "returns repeated prime factors of a given number" do expect(RMathPlus.prime_factors(8)).to eq [2,2,2] end it "returns its input if the input is a prime" do expect(RMathPlus.prime_factors(11)).to eq [11] end end describe ".lcm" do it "returns the least common multiple of an array of numbers" do expect(RMathPlus.lcm([2,4,8])).to eq 8 end it "returns the least common multiple of a big array of numbers" do odds = [] for i in (1..99) odds.push(i) if (i % 2) == 1 end expect(RMathPlus.lcm(odds)).to eq 1089380862964257455695840764614254743075 end end end
otamm/RMathPlus
lib/r_math_plus.rb
require "r_math_plus/version" module RMathPlus def self.is_prime?(n,prime_array=false) # number to be checked as first parameter, optional second parameter to be used with the 'prime_array' method. if n < 2 return false elsif n == 2 return true else if prime_array for i in (2..(n/2)+1) #it makes no sense to divide by numbers which would result in a result less than 2 (the smallest prime); the '+1' in the end is due to the default 'round down' in integer division in Ruby. prime_array.each { |prime| return false if (n % prime) == 0 } end else for i in (2..(n/2)+1) if (n % i) == 0 return false end end end end return true end def self.prime_array(n) #returns an array with all primes less than number n. if n < 2 return [] else prime_array = [] for i in (2..n) prime_array.push(i) if RMathPlus.is_prime?(i,prime_array) # the own prime_array built so far is passed as an argument in order to improve processing speed. end end return prime_array end def self.nth_prime(n) #returns an array with all primes less than number n. if n <= 1 if n == 1 return [2] end if n < 1 raise "Wops, there's no 0th prime!" end end prime_array = [2] i = 2 array_size = 1 # compares faster than running prime_array.size on each loop while true i += 1 if RMathPlus.is_prime?(i,prime_array) # the own prime_array built so far is passed as an argument in order to improve processing speed. prime_array.push(i) array_size += 1 break if array_size == n end end return prime_array end def self.prime_factors(number, biggest_number_prime_array=false) #returns the prime factors of a given number. if n is prime, returns n. second parameter to improve speed if method would be utilized in a range of numbers. factors = [] if biggest_number_prime_array primes = biggest_number_prime_array else primes = RMathPlus.prime_array(number) end while true signal = factors.size #signalizes when to break the loop. primes.each do |prime| if (number % prime) == 0 factors.push(prime) number = number / prime break end end if signal == factors.size factors.push(number) break end end factors = factors.sort return factors - [1] #...because 1 is not a prime. end def self.lcm(nums) #method that returns the least common multiple between a given array of numbers. nums = nums.uniq.sort primes = RMathPlus.prime_array(nums[-1]) #biggest number in the whole array. factorized_nums = [] #holds the prime factors for each value in nums array. nums.each { |n| factorized_nums.push(RMathPlus.prime_factors(n,primes)) } unique_lcm_factors = [] #individual prime factors of lcm lcm_factors = {} #prime factors of lcm for factors in factorized_nums for factor in factors.uniq if lcm_factors.include?(factor) lcm_factors[factor] = factors.count(factor) if factors.count(factor) > lcm_factors[factor] else lcm_factors[factor] = factors.count(factor) end end end lcm = 1 lcm_factors.each { |factor,max_quantity| lcm *= factor ** max_quantity } return lcm end end odds = [] for i in (1..99) odds.push(i) if (i % 2) == 1 end puts RMathPlus.lcm(odds)
DarthMax/lobbyliste
lib/lobbyliste/factories.rb
<gh_stars>1-10 require 'lobbyliste/factories/list_factory' require 'lobbyliste/factories/organisation_factory' require 'lobbyliste/factories/address_factory' require 'lobbyliste/factories/person_factory' module Lobbyliste module Factories end end
DarthMax/lobbyliste
test/lobbyliste/name_and_address_test.rb
<gh_stars>1-10 require 'test_helper' class Lobbyliste::NameAndAddressTest < Minitest::Test def test_full_address name_and_address = Lobbyliste::Address.new( "Test Name", "Test Address", "012345", "City", "Germany", "012345678", "012345678", "<EMAIL>", "http://example.com", :primary ) assert name_and_address.full_address.include?("012345 City") assert name_and_address.full_address.include?("Tel: 012345678") assert_equal 8, name_and_address.full_address.each_line.count end end
DarthMax/lobbyliste
lib/lobbyliste.rb
<gh_stars>1-10 require "lobbyliste/version" require "lobbyliste/factories" require "lobbyliste/list" require "lobbyliste/organisation" require "lobbyliste/address" require "lobbyliste/person" require "lobbyliste/downloader" require "lobbyliste/core_ext/string" require 'json' module Lobbyliste # Download the PDF and parse it # @param [String] link to Lobbyliste pdf, if left out pdf link is retrieved automatically from Bundestag website # @return [Lobbyliste::Liste] def self.fetch_and_parse(pdf_link=nil) downloader = Lobbyliste::Downloader.new(pdf_link) Lobbyliste::Factories::ListFactory.build(downloader.text_data,downloader.html_data) end end
DarthMax/lobbyliste
lib/lobbyliste/factories/address_factory.rb
module Lobbyliste module Factories # This class is used to build an address from raw data # Since it is to hard to separate the na,e and address data without markup, # we use the html data to accomplish that class AddressFactory # @return [Lobbyliste::Address] def self.build(name,raw_data, type=:primary) factory = new(name,raw_data,type) ::Lobbyliste::Address.new( factory.name, factory.address, factory.postcode, factory.city, factory.country, factory.tel, factory.fax, factory.website, factory.email, factory.type ) end attr_reader :name, :tel, :fax, :website, :email, :country, :postcode, :city, :type def initialize(name,raw_data,type=:primary) @name = name @raw_data = raw_data @address = [] @tel = nil @fax = nil @website = nil @email = nil @country = "Deutschland" @postcode = nil @city = nil @type=type parse end def parse @raw_data.each_with_index do |line,i| case label(line,i) when :addr then @address << line when :tel then extract_tel_fax(line) when :postcode then extract_postcode_city(line) when :email then extract_email(line) when :website then extract_website(line) when :country then @country = line else next end end end def address @address.join(", ") end private def label(line,i) # this line is part of the name return :name if name.include?(line) return :tel if line.match(/^(Tel\.|Fax): /) return :email if line.match(/^E\-Mail\: /) return :website if line.match(/^Internet\:/) # international postcodes return :postcode if line.match(/^\d{5,7}\s(.+)$/) # UK postcodes return :postcode if line.match(/^([A-Z0-9]{3}\s?[A-Z0-9]{3})$/) # if the line looks like an address return :addr if line.match(/(c\/o|^postfach\b|[Ss]tr(aße|\.)?\b|[Aa]llee\b|[Pp]latz\b|[Gg]asse\b|[Ww]eg\b|\b([0-9]+\-)?[0-9]+\s?[a-zA-Z]*$|[Vv]orstand|[Ss]ekretär|[Gg]eschäfts)/) # if the previous line ended with e.V. the next line is addr return :addr if @raw_data[i-1].match(/(e\.\s?V\.|\([A-Z]+\)$)/) return :country if %w(Niederlande Belgien Schweiz Luxemburg Dänemark Österreich Tschechien Polen USA Israel Russland).include?(line) # a single Word with a capital letter is probably a country return :country if i > 3 && line.match(/^[A-Z][a-zA-Zöüä?]+$/) return :country if line == "Vereinigtes Königreich" :addr end def extract_tel_fax(line) _tel = line.match(/Tel\.\: ((\(?\d+\)? )?(\d+\s?)+\d+)/) if _tel @tel = _tel[1].gsub(/[\(|\)]/,"").gsub(/^0{1,2}/,"+49") end _fax = line.match(/Fax\: ((\(?\d+\)? )?(\d+\s?)+\d+)/) if _fax @fax = _fax[1].gsub(/[\(|\)]/,"").gsub(/^0{1,2}/,"+49") end end def extract_postcode_city(line) _postcode_city = line.match(/(\d{5,7})\s?(.+)?/) if _postcode_city @postcode = _postcode_city[1] @city = _postcode_city[2] else _uk_postcode = line.match(/^([A-Z0-9]{3}\s?[A-Z0-9]{3})$/) @postcode = _uk_postcode[1] if _uk_postcode end end def extract_website(line) _website = line.match(/^Internet\:\s?(.+)$/) if _website @website = _website[1] end end def extract_email(line) _email = line.match(/^E\-Mail\:\s?(.+)$/) if _email @email = _email[1] end end end end end
DarthMax/lobbyliste
lib/lobbyliste/address.rb
module Lobbyliste # This class represents addresses found in the lobbylist. class Address # @return [String] organisation name (the bold part) attr_reader :name # @return [String] Everything that is not part of the name or any other field attr_reader :address # @return [String] Postcode attr_reader :postcode # @return [String] City attr_reader :city # @return [String] the country, default: "Germany" attr_reader :country # @return [String] the telephone number if given (german numbers are automatically prefixed with +49) attr_reader :tel # @return [String] the fax number if given (german numbers are automatically prefixed with +49) attr_reader :fax # @return [String] website url attr_reader :website # @return [String] contact email address attr_reader :email # @return [Symbol] address type, :primary for 1. address, :secondary for all others attr_reader :type def initialize(name, address, postcode, city, country, tel, fax, website, email, type) @name = name @address = address @postcode = postcode @city = city @country = country @tel = tel @fax = fax @website = website @email = email @type=type end # @return String pretty formated address of all existing address fields def full_address full_address = [ @name, @address, [@postcode,@city].reject(&:nil?).join(" "), @country, ] full_address << "Tel: #{@tel}" if @tel full_address << "Fax: #{@fax}" if @fax full_address << "Email: #{@email}" if @email full_address << @website if @website full_address.reject(&:nil?).join("\n") end def to_json(*a) { name: name, address: address, postcode: postcode, city: city, country: country, tel: tel, fax: fax, email: email, website: website, type: type.to_s }.to_json(*a) end end end
DarthMax/lobbyliste
lib/lobbyliste/person.rb
<reponame>DarthMax/lobbyliste module Lobbyliste # Class to encapsulate a person. class Person # @return [String] the persons name (hopefully) stripped of all titles attr_reader :name # @return [Array] list of all titles (job, academic, positions) attr_reader :titles # @return [String] the original name with titles as stated in the document attr_reader :original_name def initialize(name, titles, original_name) @name = name @titles = titles @original_name = original_name end def ==(other) original_name==other.original_name end def to_json(*a) { name: name, titles: titles }.to_json(*a) end end end
DarthMax/lobbyliste
test/test_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'lobbyliste' require 'minitest/autorun' require 'mocha/mini_test' require 'webmock/minitest' require 'vcr' VCR.configure do |config| config.cassette_library_dir = "test/vcr_cassettes" config.hook_into :webmock end
DarthMax/lobbyliste
test/lobbyliste/factories/address_factory_test.rb
require 'test_helper' class Lobbyliste::Factories::AddressFactoryTest < Minitest::Test def setup @data = [ "1219. Deutsche Stiftung für interreligiösen und interkulturellen", "Dialog e. V.", "Hinter der katholischen Kirche 3", "10117 Berlin", "Tel.: (030) 51057773 Fax: (030) 51057785", "E-Mail: <EMAIL>", "Internet: http://www.1219.eu", ] @name = "1219. Deutsche Stiftung für interreligiösen und interkulturellen Dialog e. V." @name_and_address = Lobbyliste::Factories::AddressFactory.new(@name, @data) end def test_name_extraction assert_equal "1219. Deutsche Stiftung für interreligiösen und interkulturellen Dialog e. V.", @name_and_address.name end def test_address_extraction assert_equal "Hinter der katholischen Kirche 3", @name_and_address.address end def test_postcode_extraction assert_equal "10117", @name_and_address.postcode end def test_city_extraction assert_equal "Berlin", @name_and_address.city end def test_tel_fax_extraction assert_equal "+4930 51057773", @name_and_address.tel assert_equal "+4930 51057785", @name_and_address.fax end def test_email_extraction assert_equal "<EMAIL>", @name_and_address.email end def test_website_extraction assert_equal "http://www.1219.eu", @name_and_address.website end def test_country_default assert_equal "Deutschland", @name_and_address.country end def test_country_extraction data = [ "1219. Deutsche Stiftung für interreligiösen und interkulturellen", "Dialog e. V.", "Hinter der katholischen Kirche 3", "10117 Berlin", "Germany", "Tel.: (030) 51057773 Fax: (030) 51057785", "E-Mail: <EMAIL>", "Internet: http://www.1219.eu", ] name_and_address = Lobbyliste::Factories::AddressFactory.new(@name,data) assert_equal "Germany", name_and_address.country end def test_recognize_uk_addresses data = [ "Crescent House", "5 The Cresent", "Surbiton, Surrey", "KT6 4BN", "Vereinigtes Königreich", ] name_and_address = Lobbyliste::Factories::AddressFactory.new(@name, data, :secondary) assert_equal "Crescent House, 5 The Cresent, Surbiton, Surrey" ,name_and_address.address assert_equal "KT6 4BN" ,name_and_address.postcode assert_nil name_and_address.city assert_equal "Vereinigtes Königreich" ,name_and_address.country end end
DarthMax/lobbyliste
test/lobbyliste_test.rb
<reponame>DarthMax/lobbyliste require 'test_helper' class LobbylisteTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Lobbyliste::VERSION end def test_fetch_and_parse Lobbyliste::Downloader.any_instance.expects(:text_data).returns("TEXT_DATA") Lobbyliste::Downloader.any_instance.expects(:html_data).returns("HTML_DATA") Lobbyliste::Factories::ListFactory.expects(:build).with("TEXT_DATA","HTML_DATA").returns("LISTE") assert_equal "LISTE", Lobbyliste.fetch_and_parse end end
DarthMax/lobbyliste
lib/lobbyliste/downloader.rb
<filename>lib/lobbyliste/downloader.rb<gh_stars>1-10 require 'open-uri' require 'nokogiri' module Lobbyliste # This class finds the lobbyliste pdf on the Bundestag website, downloads it and extracts the pdf content class Downloader # Creates a new Downloader # @param [String] link that will be used to fetch the lobbylist pdf, defaults to nil def initialize(pdf_link=nil) @pdf_link = pdf_link end # @return [String] raw content of pdf file def pdf_data retrieve_pdf unless @pdf_data @pdf_data end # @return [String] extracted content of pdf file def text_data extract_pdf unless @text_data @text_data end # @return [String] extracted content of pdf file in html format def html_data extract_pdf unless @html_data @html_data end # @return [String] link to Lobbyliste pdf def pdf_link fetch_pdf_link unless @pdf_link @pdf_link end # Since the link to the PDF changes with every new version we download the Lobbyliste website and extract the link # Use this method to extract link from different page if the bundestag website structure is changed again # @param [String] page that will be used to extract the PDF link. May change from time to time. # @return [String] the link to the Lobbyliste pdf def fetch_pdf_link(bundestag_page = "https://www.bundestag.de/parlament/lobbyliste") website = Nokogiri::HTML(open(bundestag_page)) link = website.css("a[title^='Aktuelle Fassung']").first raise NoPdfLinkFound.new("Could not find link to the Lobbyist PDF on the bundestag website!") unless link @pdf_link = "https://bundestag.de#{link['href']}" end private def http_version_of_url(url) url.gsub('https://', 'http://') end def retrieve_pdf begin @pdf_data = open(pdf_link) {|f| f.read} rescue RuntimeError => error non_https_link = http_version_of_url(pdf_link) @pdf_data = open(non_https_link) {|f| f.read} end end def extract_pdf pdf_file = Tempfile.new(["lobbyliste",".pdf"]) pdf_file.write(pdf_data) pdf_file.rewind @text_data = run_extraction(pdf_file) @html_data = run_extraction(pdf_file,true) ensure pdf_file.close pdf_file.unlink end def run_extraction(pdf_file,html=false) tmp_file = Tempfile.new(["lobbyliste"]) status = system("/usr/bin/java -jar #{jar_path} ExtractText #{pdf_file.path} #{html ? "-html":""} #{tmp_file.path} > /dev/null 2>&1") raise "PDF extraction failed" unless status return tmp_file.read ensure tmp_file.close tmp_file.unlink end def jar_path File.join(File.dirname(File.expand_path(__FILE__)), '../../ext/pdfbox.jar') end end class NoPdfLinkFound < StandardError ; end end
DarthMax/lobbyliste
lib/lobbyliste/core_ext/string.rb
<reponame>DarthMax/lobbyliste class Object def blank? respond_to?(:empty?) ? !!empty? : !self end class String def squish self.dup.gsub(/[[:space:]]+/, ' ').strip end def blank? empty? || /\A[[:space:]]*\z/ === self end end class Nil def blank? true end end end
DarthMax/lobbyliste
lib/lobbyliste/factories/list_factory.rb
module Lobbyliste module Factories # This class is used to build the list from raw data class ListFactory attr_reader :data # @return [Lobbyliste::List] def self.build(text_data,html_data) factory = new(text_data,html_data) ::Lobbyliste::List.new( factory.organisations, factory.tags, factory.abbreviations, factory.last_update ) end def initialize(text_data,html_data) @text_data = text_data @html_data = html_data @lines = text_data.each_line.to_a.map(&:chomp) @organisations = nil @tags = nil @abbreviations = nil @names = nil end def organisations return @organisations if @organisations @organisations = organisations_data.map do |organisation_data| id = organisation_data[0].to_i name = names[id] tags = tags_for_organisation(id) abbreviations = abbreviations_for_organisation(id) ::Lobbyliste::Factories::OrganisationFactory.build(name,organisation_data,tags,abbreviations) end end def names extract_names unless @names @names end def tags return @tags if @tags tags = Hash.new{|h,k| h[k] = []} tag_data = extract_tag_data current_tag = "A" tag_data.each do |line| if line.match(/^[A-ZÄÖÜ][a-zäöüß]+$/) && [current_tag[0],current_tag[0].next].include?(line[0]) current_tag = line elsif line.match(/^\– \d+/) id = line.match(/^\– (\d+)/)[1].to_i tags[current_tag] << id end end @tags = tags end def abbreviations return @abbreviations if @abbreviations abbreviations = Hash.new{|h,k| h[k] = []} current_abbr = "A" extract_abbreviation_data.each do |line| if line.match(/^[A-ZÄÖÜ][A-ZÄÖÜa-zäöüß]+$/) && [current_abbr[0],current_abbr[0].next].include?(line[0]) current_abbr = line elsif line.match(/^\– \d+/) id = line.match(/^\– (\d+)/)[1].to_i abbreviations[current_abbr] << id end end @abbreviations = abbreviations end def last_update date = @text_data.match(/^Stand: (\d\d\.\d\d\.\d\d\d\d)/) Date.parse(date[1]) end private def organisations_data start_lines = [] end_line = nil @lines.each_with_index do |line,i| if possible_organisation_id?(line) && begin_organisation?(@lines[i+1]) start_lines << i elsif line == "Stichwortverzeichnis" end_line = i - 1 break end end organisations_data = start_lines.each_cons(2).map do |a,b| @lines[a..b-1] end organisations_data. push(@lines[start_lines.last..end_line]). map { |data| data.reject {|line| ignored_line?(line)} } end def extract_tag_data start_line = @lines.index {|line| line == "Stichwortverzeichnis"} @lines. drop(start_line+1). take_while {|line| !(line == "Verzeichnis der anderen Namensformen")}. reject {|line| ignored_line?(line)} end def extract_abbreviation_data start_line = @lines.index {|line| line == "Verzeichnis der anderen Namensformen"} @lines. drop(start_line+1). reject {|line| ignored_line?(line)} end def tags_for_organisation(organisation_id) tags. select {|_,organisation_ids| organisation_ids.include?(organisation_id)}. map(&:first) end def abbreviations_for_organisation(organisation_id) abbreviations. select {|_,organisation_ids| organisation_ids.include?(organisation_id)}. map(&:first) end def extract_names names = {} regexp = Regexp.compile(/<p><b>(\d+)\n<\/b>N a m e u n d S i t z \, 1 \. A d r e s s e\n<\/p>\n<p><b>(.*?)\n<\/b>/m) @html_data.to_enum(:scan, regexp).each do match = Regexp.last_match names[match[1].to_i] = CGI.unescape_html(match[2].gsub("\n"," ")) end @names = names end def ignored_line?(line) regexps = [ /^– \d+ –$/, /^Aktuelle Fassung der öffentlichen Liste/, /^Die Zahlen verweisen auf die fortlaufenden Nummern im Hauptteil/, /^\n$/ ] regexps.any? {|regexp| line.match(regexp)} end def possible_organisation_id?(line) line =~ /^\d+$/ end def begin_organisation?(line) line =~/^N a m e u n d S i t z \, 1 \. A d r e s s e$/ end end end end
DarthMax/lobbyliste
test/lobbyliste/organisation_test.rb
<reponame>DarthMax/lobbyliste require 'test_helper' class Lobbyliste::OrganisationTest < Minitest::Test def test_addresses org = Lobbyliste::Organisation.new(1,"Name","Main Address","Other Address","3. Address",nil,nil,nil,nil,nil,nil) assert_equal ["Main Address","Other Address","3. Address"], org.addresses end end
DarthMax/lobbyliste
test/lobbyliste/factories/organisation_factory_test.rb
<reponame>DarthMax/lobbyliste require 'test_helper' class Lobbyliste::Factories::OrganisationFactoryTest < Minitest::Test def setup @organisation_data = [ "1", "N a m e u n d S i t z , 1 . A d r e s s e", "1219. Deutsche Stiftung für interreligiösen und interkulturellen", "Dialog e. V.", "Hinter der katholischen Kirche 3", "10117 Berlin", "Tel.: (030) 51057773 Fax: (030) 51057785", "E-Mail: <EMAIL>", "Internet: http://www.1219.eu", "W e i t e r e A d r e s s e", "c/o Missionszentrale der Franziskaner", "Albertus-Magnus-Straße 39", "53177 Bonn", "Tel.: (0228) 953540 Fax: (0228) 9535440", "V o r s t a n d u n d G e s c h ä f t s f ü h r u n g", "Vorstand:", "Pater <NAME> OFM, 1. Vorsitzender", "<NAME>, 2. Vorsitzender", "Weitere Vorstandsmitglieder:", "Dr.rer.pol. <NAME>, Geschäftsführer", "I n t e r e s s e n b e r e i c h", "Interreligiöser und interkultureller Dialog:", "- wissenschaftliche Bearbeitung von Aspekte des Dialogs und der", "Funktion von Religion in der deutschen und europäischen Gesell-", "schaft;", "Religions-", "und Meinungsfreiheit", "- Eintreten für das Grundrecht und das universale Menschenrecht Re-", "ligionsfreiheit (auch die negative Religionsfreiheit/Weltan-", "schauungsfreiheit);", "- Vermittlung von Kenntnissen über alle Aspekten von Religionen und", "Kulturen;", "- Diskussion von Toleranz und Offenheit gegenüber anderen Religio-", "nen und Kulturen in einer demokratischen Gesellschaft;", "- der Einsatz für die Rechte bedrohter Kulturen und", "- die Förderung von Dialogkultur als friedensschaffende und integrati-", "ve Maßnahme.", "M i t g l i e d e r z a h l", "7", "A n z a h l d e r a n g e s c h l o s s e n e n O r g a n i s a t i o n e n", "5", "V e r b a n d s v e r t r e t e r / - i n n e n", "(s. Abschnitt \"Vorstand und Geschäftsführung\")", "<NAME>", "A n s c h r i f t a m S i t z v o n B T u n d B R g", "Rahel-Hirsch-Straße 10 (3. OG)", "10557 Berlin", "Tel.: (030) 590083562 Fax: (030) 590083700", "E-Mail: <EMAIL>", "Internet: http://www.ziv-zweirad.de", ] @name = "1219. Deutsche Stiftung für interreligiösen und interkulturellen Dialog e. V." @org = Lobbyliste::Factories::OrganisationFactory.new(@name, @organisation_data) end def test_factory_builds_an_organisation organisation = Lobbyliste::Factories::OrganisationFactory.build(@name, @organisation_data,[],[]) assert organisation.is_a?(Lobbyliste::Organisation) assert 1, organisation.id end def test_id_extraction assert_equal 1, @org.id end def test_address_extraction name_and_address = @org.address assert name_and_address.is_a?(Lobbyliste::Address) assert_equal @name, name_and_address.name assert_equal :primary, name_and_address.type end def test_additional_address_extraction name_and_address = @org.additional_address assert name_and_address.is_a?(Lobbyliste::Address) assert name_and_address.address.include? "c/o Missionszentrale der Franziskaner" assert_equal :secondary, name_and_address.type end def test_additional_address_is_nil_if_there_is_none data = [ "1", "N a m e u n d S i t z , 1 . A d r e s s e", "1219. Deutsche Stiftung für interreligiösen und interkulturellen", "Dialog e. V.", "Hinter der katholischen Kirche 3", "10117 Berlin", "Tel.: (030) 51057773 Fax: (030) 51057785", "E-Mail: <EMAIL>", "Internet: http://www.1219.eu", "W e i t e r e A d r e s s e", "–", "V o r s t a n d u n d G e s c h ä f t s f ü h r u n g", "<NAME> OFM, 1. Vorsitzender", "<NAME>, 2. Vorsitzender", "Dr.rer.pol. <NAME>, Geschäftsführer", ] org = Lobbyliste::Factories::OrganisationFactory.new(@name, data) assert_nil org.additional_address end def test_address_at_bt_br_extraction address = @org.address_at_bt_br assert address.is_a?(Lobbyliste::Address) assert address.address.include? "Rahel-Hirsch-Straße 10" assert_equal :secondary, address.type end def test_address_at_bt_br_ignores_see_other data = [ "A n s c h r i f t a m S i t z v o n B T u n d B R g", "(s. Abschnitt \"Name und Sitz, 1. Adresse\")" ] org = Lobbyliste::Factories::OrganisationFactory.new(@name, data) assert_nil org.address_at_bt_br end def test_people_extraction assert_equal 4, @org.people.count assert @org.people.first.is_a?(Lobbyliste::Person) assert_equal ["<NAME>","<NAME>","<NAME>","<NAME>"], @org.people.map(&:name) end def test_interest_extraction interests = @org.interests assert interests.include? "- die Förderung von Dialogkultur als friedensschaffende und integrative\n" assert interests.include? "Maßnahme." refute interests.include? "Religionsund Meinungsfreiheit" end def test_member_extraction assert_equal 7, @org.members end def test_associated_organisations_extraction assert_equal 5, @org.associated_organisations end end
DarthMax/lobbyliste
lib/lobbyliste/factories/organisation_factory.rb
<reponame>DarthMax/lobbyliste module Lobbyliste module Factories # This class is used to build an organisation from raw data class OrganisationFactory # @return [Lobbyliste::Organisation] def self.build(name, raw_data,tags,abbreviations) factory = new(name, raw_data) ::Lobbyliste::Organisation.new( factory.id, factory.name, factory.address, factory.additional_address, factory.address_at_bt_br, factory.people, factory.interests, factory.members, factory.associated_organisations, tags, abbreviations ) end attr_reader :name def initialize(name,raw_data) @name = name @raw_data = raw_data end def id @raw_data.first.to_i end def address data = read_section("N a m e u n d S i t z , 1 . A d r e s s e") AddressFactory.build(name, data, :primary) end def additional_address data = read_section("W e i t e r e A d r e s s e") return nil if data[0] == "–" AddressFactory.build(name, data, :secondary) end def address_at_bt_br data = read_section("A n s c h r i f t a m S i t z v o n B T u n d B R g") return nil if data[0] == "–" || data[0].match(/\(s\. Abschnitt/) AddressFactory.build(name, data, :secondary) end def people data = read_section("V o r s t a n d u n d G e s c h ä f t s f ü h r u n g") data.concat read_section("V e r b a n d s v e r t r e t e r / - i n n e n") data.reject! {|line| ignored_person_line?(line)} data.map { |person| PersonFactory.build(person) }.uniq.reject(&:nil?) end def interests interest_lines = read_section("I n t e r e s s e n b e r e i c h").dup (0..interest_lines.count-1).each do |i| line = interest_lines[i] next_line = interest_lines[i+1] if line =~ /[-–]$/ && !(next_line.start_with?("und"," und", "oder", " oder")) line.gsub!(/[-–]$/,"") next_line_words = next_line.split(" ") line += next_line_words.slice!(0) next_line = next_line_words.join(" ") end interest_lines[i] = line interest_lines[i+1] = next_line end interest_lines.reject(&:blank?).join("\n") end def members read_section("M i t g l i e d e r z a h l")[0].to_i || nil end def associated_organisations read_section("A n z a h l d e r a n g e s c h l o s s e n e n O r g a n i s a t i o n e n")[0].to_i || nil end private def new_section?(line) line =~ /^([a-zA-Z\d\,\.\-\/äöüß]\s){3,}\w$/ end def read_section(section) start_line = @raw_data.index {|line| line == section} return [] unless start_line @raw_data.drop(start_line+1).take_while {|line| !new_section?(line)} end def ignored_person_line?(line) [ /^–$/, /\(s\. Abschnitt/, /\:$/, /^GdW$/, /^Forschung$/, /^des Verwaltungsrats$/, /^Schatzmeister$/, /^Kinder- u\. Jugendmed\.$/, /^u\. Kinderchirurgen$/, /^Finanzen & Recht I$/, /^Geschäftsführ(er(in)?|ung)$/, /^gleichzeitig Verbandsdirektor^/, /^(stellvertretender )?Vorsitzender?$/, /^weitere Vorstandsmitglieder$/, /^Managementgesellschaft des DZVhÄ/, /^Besonderer Vertreter nach § 30/, /^Sektretär$/, /^Alleingesellschafter: Ev\.Werk für/ ].any? {|regexp| line.match(regexp) } end end end end
DarthMax/lobbyliste
test/real_world_test.rb
require 'test_helper' class RealWorldTest < Minitest::Test def test_real_world_sanity_check skip unless ENV["RUN_REAL_WORLD_TEST"] == "true" VCR.turned_off do WebMock.allow_net_connect! liste = Lobbyliste.fetch_and_parse # There are 2000-3000 organisations assert (2000..3000).include?(liste.organisations.count) # every organisation has an average of 7 to 10 people assert (7..10).include?(liste.organisations.map {|org| org.people.count}.inject(&:+) / liste.organisations.count.to_f) # every organisation has an average of 1 to 3 tags assert (1..3).include?(liste.organisations.map {|org| org.tags.count}.inject(&:+) / liste.organisations.count.to_f) end ensure WebMock.disable_net_connect! end end
DarthMax/lobbyliste
lib/lobbyliste/list.rb
module Lobbyliste # This class represents an instance of the parsed lobbylist. class List # @return [Array] list of organisations attr_reader :organisations # @return [Hash] keys are the tags, values are Arrays of organisation ids attr_reader :tags # @return [Hash] keys are the abbreviations, values are Arrays of organisation ids attr_reader :abbreviations # @return [Date] the date when the document was last updated attr_reader :last_update def initialize(organisations, tags, abbreviations, last_update) @organisations = organisations @tags=tags @abbreviations = abbreviations @last_update = last_update end def to_json(*a) { organisations: organisations, tags: tags, abbreviations: abbreviations, last_update: last_update }.to_json(*a) end end end
DarthMax/lobbyliste
test/lobbyliste/downloader_test.rb
require 'test_helper' class Lobbyliste::OrganisationTest < Minitest::Test def test_pdf_link VCR.use_cassette("bundestag_website") do downloader = Lobbyliste::Downloader.new assert_equal "https://bundestag.de/blob/189476/b5c8f2195537f84bdb1fe398ff721d9d/lobbylisteaktuell-data.pdf", downloader.pdf_link end end def test_pdf_link_with_given_link link = "http://example.com/link" downloader = Lobbyliste::Downloader.new(link) assert_equal link, downloader.pdf_link end def test_pdf_download pdf_address = "http://example.com/lobbyliste.pdf" Lobbyliste::Downloader.any_instance.expects(:pdf_link).returns(pdf_address) stub_request(:get, pdf_address). to_return(status: 200, body: "Lobbyliste", headers: { 'Content-Length' => 10}) VCR.turned_off do downloader = Lobbyliste::Downloader.new assert_equal 10, downloader.pdf_data.length assert_equal "Lobbyliste", downloader.pdf_data end end end
DarthMax/lobbyliste
test/lobbyliste/factories/person_factory_test.rb
require 'test_helper' class Lobbyliste::Factories::PersonFactoryTest < Minitest::Test def test_extract_names data = [ ["Prof. Dr.med.vet <NAME>, 1. Vorsitzender", "<NAME>"], ["Dipl.-Ing <NAME>","<NAME>"], ["<NAME>, Geschäftsführerin","<NAME>"], ["<NAME>","<NAME>"], ["<NAME>M, 1. Vorsitzender","<NAME>"], ["Richter am Finanzgericht <NAME>","<NAME>"] ] data.each do |line,expected_name| factory = Lobbyliste::Factories::PersonFactory.new(line) assert_equal expected_name, factory.name, "'#{line}' should be extracted to #{expected_name}" end end def test_extract_titles data = [ ["Prof. Dr.med.vet <NAME>, 1. Vorsitzender", ["Prof. Dr.med.vet","1. Vorsitzender"]], ["Dipl.-Ing <NAME>",["Dipl.-Ing"]], ["<NAME>, Geschäftsführerin",["Apothekerin","Geschäftsführerin"]], ["<NAME>",[]] ] data.each do |line,expected_titles| factory = Lobbyliste::Factories::PersonFactory.new(line) assert_equal expected_titles, factory.titles, "'#{line}' should be extracted to #{expected_titles}" end end def test_building_a_person line = "Prof. Dr.med.vet <NAME>, 1. Vorsitzender" person = Lobbyliste::Factories::PersonFactory.build(line) assert person.is_a?(Lobbyliste::Person) assert_equal "<NAME>", person.name assert_equal ["Prof. Dr.med.vet","1. Vorsitzender"], person.titles assert_equal line, person.original_name end end
DarthMax/lobbyliste
test/lobbyliste/factories/list_factory_test.rb
require 'test_helper' class Lobbyliste::Factories::ListFactoryTest < Minitest::Test def setup @text_data = File.read(File.join(File.dirname(File.expand_path(__FILE__)), '../../test_data/lobbyliste_text.txt')) @html_data = File.read(File.join(File.dirname(File.expand_path(__FILE__)), '../../test_data/lobbyliste_html.html')) @list = Lobbyliste::Factories::ListFactory.new(@text_data,@html_data) end def test_ignored_lines lines_to_ignore = [ "– 4 –", "Aktuelle Fassung der öffentlichen Liste über die Registrierung von Verbänden und deren Vertretern (Stand: 10.06.2016)", "Die Zahlen verweisen auf die fortlaufenden Nummern im Hauptteil", "\n" ] lines_to_ignore.each do |line| assert @list.send(:ignored_line?,line), "'#{line}' should be ignored" end end def test_organisation_data_does_not_include_ignored_lines refute @list.send(:organisations_data).flatten.any? {|line| @list.send(:ignored_line?,line)} end def test_organisation_extraction organisations = @list.organisations assert_equal 4, organisations.count assert organisations.all? {|org| org.is_a?(Lobbyliste::Organisation)} assert_equal [1,2,3,4], organisations.map(&:id) end def test_organisation_tagging organisations = @list.organisations assert_equal ["Abbruch"], organisations.first.tags assert_equal ["Bau"], organisations.last.tags refute organisations[2].tags.any? end def test_organisation_abbreviations assert_equal ["ABDA"], @list.organisations.first.abbreviations assert_equal ["BBB"], @list.organisations.last.abbreviations refute @list.organisations[2].abbreviations.any? end def test_tag_extraction assert_equal 2, @list.tags.keys.count refute @list.tags.keys.include?("Dialog") assert_equal [1,2], @list.tags["Abbruch"] end def test_name_extraction assert_equal 4, @list.names.keys.count assert_equal [1, 2, 3, 4], @list.names.keys assert_equal "1219. Deutsche Stiftung für interreligiösen und interkulturellen Dialog e. V.", @list.names[1] end def test_abbreviation_extraction assert_equal ["ABDA","BBB"], @list.abbreviations.keys assert_equal [4], @list.abbreviations["BBB"] end def test_last_update assert_equal Date.parse("10.06.2016"), @list.last_update end def test_build list = Lobbyliste::Factories::ListFactory.build(@text_data,@html_data) assert list.is_a?(Lobbyliste::List) assert_equal 4, list.organisations.count assert_equal 2, list.tags.count end end
DarthMax/lobbyliste
lib/lobbyliste/organisation.rb
<reponame>DarthMax/lobbyliste module Lobbyliste # Class to encapsulate an organisation class Organisation # @return [Integer] the organisation id of the organisation. This number is not fix and may change with every new document version attr_reader :id # @return [String] the organisations name attr_reader :name # @return [Lobbyliste::Address] the primary Address of the organisation attr_reader :address # @return [Lobbyliste::Address] the address stated under "Weitere Addresse" attr_reader :additional_address # @return [Lobbyliste::Address] the address stated under "Anschrift am Sitz von BT und BRg" attr_reader :address_at_bt_br # @return [Array] List of {Lobbyliste::Person} which includes all members stated under "Vorstand und Geschäftsführung" and "Verbandsvertreter/-innen" attr_reader :people # @return [String] interests as stated under "Interessenbereich" attr_reader :interests # @return [Integer] number of members as stated under "Mitgleiderzahl" attr_reader :members # @return [Integer] number of associated organisations as stated under "Anzahl der angeschlossenen Organisationen" attr_reader :associated_organisations # @return [Array] list of tags attr_reader :tags # @return [Array] list of abbreviations attr_reader :abbreviations def initialize(id, name, address, additional_address, address_at_bt_br, people, interests, members, associated_organisations,tags,abbreviations) @id = id @name = name @address = address @additional_address = additional_address @address_at_bt_br = address_at_bt_br @people = people @interests = interests @members = members @associated_organisations = associated_organisations @tags = tags @abbreviations = abbreviations end # @return [Array] list of all known addresses def addresses [address,additional_address,address_at_bt_br].reject(&:nil?) end def to_json(*a) { id: id, name: name, addresses: addresses, people: people, interests: interests, members: members, associated_organisations: associated_organisations, tags: tags, abbreviations: abbreviations }.to_json(*a) end end end
jpamaya/casino-moped_yubi_authenticator
casino-moped_authenticator.gemspec
<gh_stars>0 # -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'casino/moped_yubi_authenticator/version' Gem::Specification.new do |s| s.name = 'casino-moped_yubi_authenticator' s.version = CASino::MopedYubiAuthenticator::VERSION s.authors = ['<NAME>'] s.email = ['<EMAIL>'] s.homepage = 'http://www.codescrum.com/' s.license = 'MIT' s.summary = 'Provides mechanism to use Moped Yubi as an authenticator for CASino.' s.description = 'This gem can be used to allow the CASino backend to authenticate Yubi keys against an MongoDB server using Moped.' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = [] # `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ['lib'] s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'rspec', '~> 2.12' s.add_development_dependency 'simplecov', '~> 0.7' s.add_development_dependency 'coveralls' s.add_runtime_dependency 'casino-moped_authenticator' end
jpamaya/casino-moped_yubi_authenticator
lib/casino-moped_yubi_authenticator.rb
<reponame>jpamaya/casino-moped_yubi_authenticator require 'casino/moped_authenticator/version' require 'casino/moped_authenticator'
jpamaya/casino-moped_yubi_authenticator
lib/casino/moped_yubi_authenticator.rb
require 'casino/moped_authenticator' class CASino::MopedYubiAuthenticator < CASino::MopedAuthenticator def validate(username, password, yubi_key) return false unless user = collection.find(@options[:username_column] => username).first password_from_database = user[@options[:password_column]] registered_yubi_key_from_database = user[@options[:yubi_key_column]] # Validate password from database if valid_password?(password, password_from_database) # Validate yubi key if valid_yubi_key?(yubi_key, registered_yubi_key_from_database) return { username: user[@options[:username_column]], extra_attributes: extra_attributes(user) } else return false end else return false end end def valid_yubi_key?(yubi_key, registered_yubi_key) registered_yubi_key == yubi_key[0..11] && valid_yubi_api_key?(yubi_key) end def valid_yubi_api_key?(yubi_key) return true if Rails.env.development? begin otp = Yubikey::OTP::Verify.new( :api_id => APP_CONFIG['yubi_api_id'], :api_key => APP_CONFIG['yubi_api_key'], :otp => yubi_key ) if otp.valid? return true else return false end rescue Yubikey::OTP::InvalidOTPError return false end end end
jpamaya/casino-moped_yubi_authenticator
spec/casino_core/moped_authenticator_spec.rb
require 'spec_helper' require 'casino/moped_authenticator' module CASino describe MopedAuthenticator do let(:pepper) { nil } let(:extra_attributes) {{ email: 'mail_address' }} let(:options) {{ database_url: 'mongodb://localhost:27017/my_db?safe=true', collection: 'users', username_column: 'username', password_column: 'password', pepper: pepper, extra_attributes: extra_attributes }} subject { described_class.new(options) } before do create_user( 'test', '$5$cegeasjoos$vPX5AwDqOTGocGjehr7k1IYp6Kt.U4FmMUa.1l6NrzD', # password: <PASSWORD> mail_address: '<EMAIL>' ) end after { @session.drop } describe '#validate' do context 'valid username' do context 'valid password' do it 'returns the username' do subject.validate('test', 'testpassword')[:username].should eq('test') end it 'returns the extra attributes' do subject.validate('test', '<PASSWORD>password')[:extra_attributes][:email].should eq('<EMAIL>') end context 'when no extra attributes given' do let(:extra_attributes) { nil } it 'returns an empty hash for extra attributes' do subject.validate('test', 'testpassword')[:extra_attributes].should eq({}) end end end context 'invalid password' do it 'returns false' do subject.validate('test', 'wrongpassword').should eq(false) end end context 'NULL password field' do it 'returns false' do update_user_pw 'test', nil subject.validate('test', 'wrongpassword').should eq(false) end end context 'empty password field' do it 'returns false' do update_user_pw 'test', '' subject.validate('test', 'wrongpassword').should eq(false) end end end context 'invalid username' do it 'returns false' do subject.validate('does-not-exist', 'testpassword').should eq(false) end end context 'support for bcrypt' do it 'is able to handle bcrypt password hashes' do create_user( 'test2', '$2a$10$dRFLSkYedQ05sqMs3b265e0nnJSoa9RhbpKXU79FDPVeuS1qBG7Jq', # password: <PASSWORD> mail_address: '<EMAIL>') subject.validate('test2', 'testpassword2').should be_instance_of(Hash) end end context 'support for bcrypt with pepper' do let(:pepper) { 'abcdefg' } it 'is able to handle bcrypt password hashes' do create_user( 'test3', '$2a$10$ndCGPWg5JFMQH/Kl6xKe.OGNaiG7CFIAVsgAOJU75Q6g5/FpY5eX6', # password: <PASSWORD>, pepper: abcdefg mail_address: '<EMAIL>') subject.validate('test3', 'test<PASSWORD>').should be_instance_of(Hash) end end context 'support for phpass' do it 'is able to handle phpass password hashes' do create_user( 'test4', '$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0', # password: <PASSWORD> mail_address: '<EMAIL>') subject.validate('test4', 'test<PASSWORD>').should be_instance_of(Hash) end end describe 'extra_attributes' do let(:extra_attributes) {{ id: '_id', email: 'mail_address', roles: 'roles', level: 'level', }} it 'returns the bson id as a string' do create_user( 'test_attributes', '$5$cegeasjoos$vPX5AwDqOTGocGjehr7k1IYp6Kt.U4FmMUa.1l6NrzD', # password: <PASSWORD> mail_address: '<EMAIL>', roles: ['admin', 'agent'], level: 26, ) data = subject.validate('test_attributes', 'testpassword') expect(data[:extra_attributes][:email]).to eq '<EMAIL>' expect(data[:extra_attributes][:roles]).to eq ['admin', 'agent'] expect(data[:extra_attributes][:level]).to eq 26 expect(data[:extra_attributes][:id]).to eq user_with_name('test_attributes')['_id'].to_s end end end def create_user(username, password, extra = {}) session[options[:collection]].insert({ username: username, password: password, }.merge(extra)) end def update_user_pw(username, new_password) session[options[:collection]].find(username: username).update(password: <PASSWORD>) end def user_with_name(username) session[options[:collection]].find(username: username).first end def session @session ||= ::Moped::Session.connect(options[:database_url]) end end end
nikolalsvk/soto
spec/ordinare/sort_spec.rb
<gh_stars>100-1000 require "spec_helper" require "fileutils" describe Ordinare::Sort do describe "#sort_gemfile" do context "no Gemfile found" do it "aborts with message" do expect { Ordinare::Sort.sort_gemfile(false, "spec/fixtures/no_gemfile") }.to raise_error(SystemExit) end end context "Gemfile found" do it "sorts basic Gemfile" do basic_gemfile = "spec/fixtures/basic_gemfile/Gemfile" Ordinare::Sort.sort_gemfile(false, basic_gemfile) same_files = FileUtils.identical?("#{basic_gemfile}.ordered", "#{basic_gemfile}.ordinare") expect(same_files).to be_truthy end it "sorts Gemfile with groups" do group_gemfile = "spec/fixtures/group_gemfile/Gemfile" Ordinare::Sort.sort_gemfile(false, group_gemfile) same_files = FileUtils.identical?("#{group_gemfile}.ordered", "#{group_gemfile}.ordinare") expect(same_files).to be_truthy end it "sorts complicated Gemfile" do complex_gemfile = "spec/fixtures/complex_gemfile/Gemfile" Ordinare::Sort.sort_gemfile(false, complex_gemfile) same_files = FileUtils.identical?("#{complex_gemfile}.ordered", "#{complex_gemfile}.ordinare") expect(same_files).to be_truthy end end end end
nikolalsvk/soto
spec/ordinare/check_spec.rb
<reponame>nikolalsvk/soto require "spec_helper" describe Ordinare::Check do describe "#gemfile_sorted?" do context "no Gemfile found" do it "aborts with message" do expect { described_class.gemfile_sorted?("spec/fixtures/no_gemfile") }.to raise_error(SystemExit) end end context "Gemfile is sorted properly" do it "returns true" do gemfile_sorted = described_class.gemfile_sorted?("spec/fixtures/ordered_gemfile/Gemfile") expect(gemfile_sorted).to be_truthy end end context "Gemfile is not sorted properly" do it "raises an exception" do expect { described_class.gemfile_sorted?("spec/fixtures/complex_gemfile/Gemfile") }.to raise_error(SystemExit) end end end end
nikolalsvk/soto
lib/ordinare/sort.rb
module Ordinare class Sort def self.sort_gemfile(overwrite = true, path = "Gemfile") new(overwrite, path).sort_gemfile end def self.sort_content(path = "Gemfile", content) new(false, path).sort_content(content) end def initialize(overwrite, path) @overwrite = overwrite @read_path = path @write_path = overwrite ? @read_path : "#{path}.ordinare" end def sort_gemfile unless File.file?(@read_path) abort "No Gemfile found in the current directory, is this a Rails project with Gemfile?" end read_content = File.readlines(@read_path) ordered_content = sort_content(read_content) write_to_a_file(ordered_content) end def sort_content(content) ranges_to_sort = find_ranges_of_gems(content) ranges_to_sort.each do |range| content[range[:start_index]..range[:end_index]] = content[range[:start_index]..range[:end_index]].sort end content end private def find_ranges_of_gems(content) gems = content.each_with_index.map do |line, index| if line.strip.start_with?("gem ") index end end ranges_to_sort = [] gems.each_with_index do |gem, index| current_range = if ranges_to_sort.last && !ranges_to_sort.last[:end_index] ranges_to_sort.last else { :start_index => nil, :end_index => nil } end start_index = current_range[:start_index] end_index = current_range[:end_index] if gem && !gems[index - 1] && gems[index + 1] current_range[:start_index] = index current_range[:end_index] = index if index == gems.length - 1 ranges_to_sort << current_range unless ranges_to_sort.any? { |range| range[:start_index] == index } elsif gem && gems[index - 1] && !gems[index + 1] ranges_to_sort.map do |range| if range[:start_index] == start_index range[:end_index] = index end range end end end ranges_to_sort end def write_to_a_file(content) File.open(@write_path, "w+") do |file| content.each { |line| file.puts(line) } end puts "Your sorted Gemfile can be found at #{@write_path} path" end end end
nikolalsvk/soto
lib/ordinare.rb
require "ordinare/version" require "ordinare/sort" require "ordinare/check" require "optparse" module Ordinare module_function def hi "Ciao, sono Ordinare" end def parse_args path = "Gemfile" overwrite = true version = nil help = nil check = nil OptionParser.new do |opts| opts.banner = "Usage: ordinare inside your Rails project" opts.separator "" opts.separator "Specific options:" opts.on("-pFILE", "--path=FILE", "Order file") do |filename| path = filename end opts.on("-n", "--no-overwrite", "Don't overwrite Gemfile") do overwrite = false end opts.on("-c", "--check", "Check if Gemfile is sorted properly") do check = true end opts.on("-v", "--version", "Check gem version") do puts Ordinare::VERSION version = true end opts.on("-h", "--help", "Get help") do puts opts help = true end end.parse! return if version || help if check Ordinare::Check.gemfile_sorted?(path) else puts path Ordinare::Sort.sort_gemfile(overwrite, path) end end end
nikolalsvk/soto
ordinare.gemspec
<reponame>nikolalsvk/soto # coding: utf-8 lib = File.expand_path("../lib/", __FILE__) $:.unshift lib unless $:.include?(lib) require "ordinare/version" Gem::Specification.new do |s| s.name = "ordinare" s.version = Ordinare::VERSION s.licenses = ["MIT"] s.summary = "Sort your gems in Gemfile with ease" s.description = "Ordinare sorts gems in your Gemfile alphabetically" s.authors = ["<NAME>"] s.email = "<EMAIL>" s.files = Dir['lib/**/*.rb'] s.homepage = "https://github.com/nikolalsvk/ordinare" s.executables = "ordinare" s.add_development_dependency "codecov" s.add_development_dependency "rspec", "~> 3.6", ">= 3.6" end
nikolalsvk/soto
spec/ordinare_spec.rb
require "spec_helper" describe Ordinare do describe "#hi" do it "says hi in italian" do expect(Ordinare.hi).to eq "Ciao, sono Ordinare" end end describe "#parse_args" do context "path to Gemfile is passed" do context "using -p" do before { ARGV = ["-p spec/fixtures/Gemfile"] } it "calls sort_gemfile" do expect(Ordinare::Sort).to receive(:sort_gemfile).with(true, " spec/fixtures/Gemfile") Ordinare.parse_args end end context "using --path" do before do ARGV = ["--path=spec/fixtures/Gemfile"] end it "calls sort_gemfile" do expect(Ordinare::Sort).to receive(:sort_gemfile).with(true, "spec/fixtures/Gemfile") Ordinare.parse_args end end end context "no overwrite option is passed" do context "using -n" do before { ARGV = ["-n"] } it "calls sort_gemfile" do expect(Ordinare::Sort).to receive(:sort_gemfile).with(false, "Gemfile") Ordinare.parse_args end end context "using --no-overwrite" do before { ARGV = ["--no-overwrite"] } it "calls sort_gemfile" do expect(Ordinare::Sort).to receive(:sort_gemfile).with(false, "Gemfile") Ordinare.parse_args end end end context "check if Gemfile is sorted properly" do context "using -c" do before { ARGV = ["-c"] } it "calls gemfile_sorted?" do expect(Ordinare::Check).to receive(:gemfile_sorted?).with("Gemfile") Ordinare.parse_args end end context "using --check" do before { ARGV = ["--check"] } it "calls gemfile_sorted?" do expect(Ordinare::Check).to receive(:gemfile_sorted?).with("Gemfile") Ordinare.parse_args end end end context "get Ordinare version" do context "using -v" do before { ARGV = ["-v"] } it "doesn't call gemfile_sorted" do expect(Ordinare::Check).not_to receive(:gemfile_sorted?) Ordinare.parse_args end it "doesn't call sort_gemfile" do expect(Ordinare::Sort).not_to receive(:sort_gemfile) Ordinare.parse_args end end context "using --version" do before { ARGV = ["--version"] } it "doesn't call gemfile_sorted" do expect(Ordinare::Check).not_to receive(:gemfile_sorted?) Ordinare.parse_args end it "doesn't call sort_gemfile" do expect(Ordinare::Sort).not_to receive(:sort_gemfile) Ordinare.parse_args end end end context "get help" do context "using -h" do before { ARGV = ["-h"] } it "doesn't call gemfile_sorted" do expect(Ordinare::Check).not_to receive(:gemfile_sorted?) Ordinare.parse_args end it "doesn't call sort_gemfile" do expect(Ordinare::Sort).not_to receive(:sort_gemfile) Ordinare.parse_args end end context "using --help" do before { ARGV = ["--help"] } it "doesn't call gemfile_sorted" do expect(Ordinare::Check).not_to receive(:gemfile_sorted?) Ordinare.parse_args end it "doesn't call sort_gemfile" do expect(Ordinare::Sort).not_to receive(:sort_gemfile) Ordinare.parse_args end end end end end
nikolalsvk/soto
lib/ordinare/check.rb
<reponame>nikolalsvk/soto<filename>lib/ordinare/check.rb module Ordinare class Check def self.gemfile_sorted?(path = "Gemfile") new(path).gemfile_sorted? end def initialize(path) @path = path end def gemfile_sorted? unless File.file?(@path) abort "No Gemfile found in the current directory, is this a Rails project with Gemfile?" end ordered_content = Ordinare::Sort.sort_content(@path, File.readlines(@path)) read_content = File.readlines(@path) if read_content == ordered_content puts "Gemfile is sorted properly" true else abort "Gemfile is not sorted" end end end end
mohitsethi/chef-storm
metadata.rb
name 'storm' maintainer "<NAME>" maintainer_email "<EMAIL>" license 'MIT License' description "Installs Twitter's Storm distributed computation system" version "1.2.35" depends "java" depends "runit" depends "zookeeper" depends "partial_search" supports "ubuntu" supports "rhel" supports "centos"
mohitsethi/chef-storm
recipes/dependencies.rb
include_recipe "java::oracle" node['storm']['packages'].each do |pkg| package pkg end bash "flush iptables" do command "service iptables stop" end if node['zookeeper']['required'] include_recipe "storm::zookeeper" end if node['zeromq']['required'] remote_file "#{Chef::Config[:file_cache_path]}/zeromq-#{node[:zeromq][:version]}.tar.gz" do source "#{node['zeromq']['download_url']}/zeromq-#{node[:zeromq][:version]}.tar.gz" mode 0744 action :create_if_missing end execute "tar" do cwd "#{Chef::Config[:file_cache_path]}" command "tar -zxvf #{Chef::Config[:file_cache_path]}/zeromq-#{node[:zeromq][:version]}.tar.gz" end bash "build_zeromq" do cwd "#{Chef::Config[:file_cache_path]}/zeromq-#{node[:zeromq][:version]}" code <<-EOH (./configure && make) EOH end bash "install_zeromq" do cwd "#{Chef::Config[:file_cache_path]}/zeromq-#{node[:zeromq][:version]}" code <<-EOH make install ldconfig EOH end end if node['jzmq']['required'] remote_file "#{Chef::Config[:file_cache_path]}/jzmq-master.zip" do source "#{node['jzmq']['download_url']}" action :create_if_missing end execute "unzip" do cwd "#{Chef::Config[:file_cache_path]}" command "unzip #{Chef::Config[:file_cache_path]}/jzmq-master.zip" end bash "build_jzmq" do cwd "#{Chef::Config[:file_cache_path]}/jzmq-master" code <<-EOH (./autogen.sh && ./configure) EOH end bash "install_jzmq" do cwd "#{Chef::Config[:file_cache_path]}/jzmq-master" code <<-EOH make install EOH end end