hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
38e23f87eb8daf0ff9a5597abfe5c0dcd90c2515
811
class FontXits < Formula version "1.200" sha256 "039493b95b86d15e451e818e065e6f6719977a31e43504eb6946513ba09c8a72" url "https://github.com/khaledhosny/xits/archive/v#{version}.zip" desc "XITS" homepage "https://github.com/khaledhosny/xits" def install parent = File.dirname(Dir.pwd) != (ENV['HOMEBREW_TEMP'] || '/tmp') ? '../' : '' (share/"fonts").install "#{parent}xits-#{version}/xits-bold.otf" (share/"fonts").install "#{parent}xits-#{version}/xits-bolditalic.otf" (share/"fonts").install "#{parent}xits-#{version}/xits-italic.otf" (share/"fonts").install "#{parent}xits-#{version}/xits-regular.otf" (share/"fonts").install "#{parent}xits-#{version}/xitsmath-bold.otf" (share/"fonts").install "#{parent}xits-#{version}/xitsmath-regular.otf" end test do end end
42.684211
84
0.68434
6281cd547fcce25c4b530c5f646a3917af7f4e26
640
module Odania module Config class Backend attr_accessor :service_name, :instance_name, :host, :port def initialize(service_name, instance_name, host, port) self.service_name = service_name self.instance_name = instance_name self.host = host self.port = port end def dump { 'service_name' => service_name, 'instance_name' => instance_name, 'host' => host, 'port' => port } end def load(data) self.service_name = data['service_name'] self.instance_name = data['instance_name'] self.host = data['host'] self.port = data['port'] self end end end end
20
60
0.646875
91fef171d57647b1f8b060c2e166a30c75e31a41
1,483
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Daterizer class Application < Rails::Application config.i18n.default_locale = :es # Hobo: the admin subsite loads admin.css & admin.js config.assets.precompile += %w(admin.css admin.js) # Hobo: Named routes have changed in Hobo 2.0. Set to false to emit both the 2.0 and 1.3 names. config.hobo.dont_emit_deprecated_routes = true # Hobo: remove support for ERB templates config.hobo.dryml_only_templates = true # Hobo: the front subsite loads front.css & front.js config.assets.precompile += %w(front.css front.js) # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
44.939394
101
0.718139
f8cd8df5df542e5930d47edf29935db71b7dedf8
75
Rails.application.routes.draw do mount Bancard::Engine => "/bancard" end
18.75
37
0.746667
0317e87517b025982424f475da8f0c93c7c38ccb
630
require_relative '../automated_init' context "Parse" do context "Singular ID" do id = 'some_id' parsed_id = ID.parse(id) test "Parsed IDis a list containing the ID" do assert(parsed_id == ['some_id']) end end context "Compound ID" do id = 'some_id+some_other_id' parsed_id = ID.parse(id) test "Parsed IDis a list containing the individual IDs" do assert(parsed_id == ['some_id', 'some_other_id']) end end context "Nil" do id = nil test "Is an error" do assert_raises(MessageStore::ID::Error) do ID.get_cardinal_id(id) end end end end
18.529412
62
0.631746
793e931ba2f87855292938619f0b5672c75ac088
1,355
class Ucloud < Formula desc "Official tool for managing UCloud services" homepage "https://www.ucloud.cn" url "https://github.com/ucloud/ucloud-cli/archive/0.1.35.tar.gz" sha256 "75d89abe8b6f170a0957dbc1742b060409337161d16988d14a9df8c05b81aa48" license "Apache-2.0" bottle do cellar :any_skip_relocation sha256 "c7652d227d29011105ab15ff1bbdce3d3a176afc2ae27c1003746c7a1000f4e7" => :big_sur sha256 "23eb0647583f539f176bb8110df100b14496817b7fc5da1860060bea4a1e72bf" => :arm64_big_sur sha256 "0e447115650b1cfc4a6149dd83f39c7ca849d740ec430a581be09e8e21adbff5" => :catalina sha256 "e5a5bcfec828253269cd75c1f0e7f6d606748a4b4d5ef987088581f7b5425e17" => :mojave sha256 "e7208d9e0dc5db081191c336d4e11ad44fb39d98221253a9577f6c2b7de3a374" => :high_sierra end depends_on "go" => :build def install dir = buildpath/"src/github.com/ucloud/ucloud-cli" dir.install buildpath.children cd dir do system "go", "build", "-mod=vendor", "-o", bin/"ucloud" prefix.install_metafiles end end test do system "#{bin}/ucloud", "config", "--project-id", "org-test", "--profile", "default", "--active", "true" config_json = (testpath/".ucloud/config.json").read assert_match '"project_id":"org-test"', config_json assert_match version.to_s, shell_output("#{bin}/ucloud --version") end end
38.714286
108
0.746125
28c70c4a174b8e99954df4dae859671c8d11ef84
711
module Api class ToolsController < Api::AbstractController def index maybe_paginate tools end def show render json: tool end def destroy mutate Tools::Destroy.run(tool: tool) end def create mutate Tools::Create.run(raw_json, device: current_device) end def update mutate Tools::Update.run(update_params) end private def update_params output = raw_json.merge(tool: tool) output[:name] = params[:name] if params[:name] output end def tools @tools ||= Tool.outter_join_slots(current_device.id) end def tool @tool ||= Tool.join_tool_slot_and_find_by_id(params[:id]) end end end
17.341463
64
0.64135
b991d00bb47f2962153d716fa2a66ad490abc5ee
1,610
module Typingpool class Amazon class HIT class Full #For more on why this subclass is neccesary, see the #documentation for #Typingpool::Amazon::HIT.cached_or_new_from_searchhits. In #short, RTurk::HITParser objects returned by RTurk::SearchHITs #are pointlessly and subtly different from #RTurk::GetHITResponse objects. (I need to submit a patch to #RTurk.) class FromSearchHITs < Full #Constructor. Takes an RTurk::Hit instance and the text of #the HIT's annotation. The text of the annotation must be #submitted as a separate param because RTurk::Hit instances #returned by RTurk::SearchHITs do not bother to extract the #annotation into an attribute, so we have to so that #ourselves (elsewhere) using the raw xml. def initialize(rturk_hit, annotation) import_standard_attrs_from_rturk_hit(rturk_hit) @assignments_completed = rturk_hit.completed_assignments @assignments_pending = rturk_hit.pending_assignments self.annotation = annotation @checked_question = nil end def external_question_url unless @checked_question self.external_question_url = at_amazon.xml @checked_question = true end @external_question_url end protected def at_amazon Amazon.rturk_hit_full(@id) end end #FromSearchHITs end #Full end #HIT end #Amazon end #Typingpool
35
70
0.635404
4accb6c318c76add320276da5562ccdc9b70eee6
224
# -*- encoding : ascii-8bit -*- require 'test_helper' class VMFixtureTest < Minitest::Test include Ethereum include VMTest run_fixtures "VMTests" def on_fixture_test(name, data) check_vm_test data end end
14
36
0.71875
28f6a21ceea1e1fa356608014b635d5a03235ed2
318
require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib') require 'ulticoder' require 'rspec/expectations'
24.461538
61
0.742138
91027ab945cf7d9a41e66cd2588b8d8abbbefcbd
1,400
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) @other_user = users(:archer) end test "should redirect index when not logged in" do get users_path assert_redirected_to login_url end test "should get new" do get signup_path assert_response :success end test "should redirect edit when not logged in" do log_in_as(@other_user) get edit_user_path(@user) assert flash.empty? assert_redirected_to root_url end test "should redirect update when not logged in" do log_in_as(@other_user) patch user_path(@user), params: { user: { name: @user.name, email: @user.email } } assert flash.empty? assert_redirected_to root_url end test "should redirect destroy when not logged in" do assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to login_url end test "should redirect destroy when logged in as a non-admin" do log_in_as(@other_user) assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to root_url end test "should redirect following when not logged in" do get following_user_path(@user) assert_redirected_to login_url end test "should redirect followers when not logged in" do get followers_user_path(@user) assert_redirected_to login_url end end
23.728814
64
0.739286
e272aa75e79fa19d25dbd54f17c028065c08a06d
1,083
#!/usr/bin/ruby # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # frozen_string_literal: true require 'bundler/setup' require File.expand_path('internal/config/environment', __dir__) require 'rspec/rails' require 'capybara/rspec' RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
30.083333
74
0.759926
1cc9bc13a10dfe5c10e00e594744bc2a1f52b018
2,685
require "spec_helper" describe Api::DevicesController do include Devise::Test::ControllerHelpers let(:user) { FactoryBot.create(:user) } let(:device) { user.device } describe "#sync" do EDGE_CASES = [:devices, # Singular resources :fbos_configs, :firmware_configs, :first_party_farmwares, :sensor_readings] FORMAT = "%Y-%m-%d %H:%M:%S.%5N" it "provides timestamps of updates, plus current time" do sign_in user FactoryBot.create(:farm_event, device: device) FactoryBot.create(:farmware_env, device: device) FactoryBot.create(:farmware_installation, device: device) FactoryBot.create(:generic_pointer, device: device) FactoryBot.create(:peripheral, device: device) FactoryBot.create(:pin_binding, device: device) FactoryBot.create(:plant, device: device) FactoryBot.create(:regimen, device: device) FactoryBot.create(:sensor_reading, device: device) FactoryBot.create(:sensor, device: device) FactoryBot.create(:tool_slot, device: device) FactoryBot.create(:tool, device: device) FactoryBot.create(:point_group, device: device) FakeSequence.create(device: device) get :sync, params: {}, session: { format: :json } expect(response.status).to eq(200) pair = json[:devices].first expect(pair.first).to eq(device.id) real_time = device.updated_at.strftime(FORMAT).sub(/0+$/, "") diff = (device.updated_at - DateTime.parse(pair.last)) expect(diff).to be < 1 expect(pair.last.first(8)).to eq(device.updated_at.as_json.first(8)) json.keys.without(*EDGE_CASES).map do |key| array = json[key] expect(array).to be_kind_of(Array) sample = array.sample raise "Needs #{key} entry" unless sample expect(sample).to be_kind_of(Array) expect(sample.first).to be_kind_of(Integer) expect(sample.last).to be_kind_of(String) obj = device.send(key) if obj.is_a?(ApplicationRecord) expect(obj.id).to eq(sample.first) expect(obj.updated_at.as_json).to eq(sample.last) else expected = obj.pluck(:id, :updated_at) json[key].each_with_index do |item, index| comparison = expected[index] expect(item.first).to eq(comparison.first) left = Time.parse(item.last) right = comparison.last.to_time.utc expect((right - left).seconds).to be < 1 expect((right - left).seconds).to be >= 0 end end end expect(json[:sensor_readings]).to eq([]) end end end
37.816901
74
0.631657
01dae5f71b3b898c39f530fcc036d3d2ef0fb66c
432
cask "aural" do version "3.5.6" sha256 "9214c40b8347ec6b0eaf6b50a1ee7479d5a5f6be51191c24fb8a199da416845e" url "https://github.com/maculateConception/aural-player/releases/download/v#{version}/AuralPlayer-#{version}.dmg" name "Aural Player" desc "Audio player inspired by Winamp" homepage "https://github.com/maculateConception/aural-player" app "Aural.app" zap trash: "~/Library/Preferences/anon.Aural.plist" end
30.857143
115
0.770833
b917bc48717a2eeec8ab510791f5c22dd81c9cc0
536
require 'tilt' module DocSiteBuilder class TemplateRenderer def self.template_cache @template_cache ||= {} end def self.initialize_cache(directory) Dir.glob(File.join(directory, "**/*")).each do |file| template_cache[file] = Tilt.new(file, :trim => "-") end end def render(template, args = {}) renderer_for(template).render(self, args).chomp end private def renderer_for(template) self.class.template_cache.fetch(File.expand_path(template)) end end end
20.615385
65
0.649254
e8fea0b85ff98e48b8cca330b1188c970f321ae2
383
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :setup_user protected def setup_user if session[:account_id].present? @current_user = Account.find(session[:account_id]) rescue nil end end end
23.9375
67
0.749347
26cf2ec96302f987bf24684fdab69c6823476246
5,474
#! /usr/bin/env ruby require 'spec_helper' describe Puppet::Parser::Functions do def callable_functions_from(mod) Class.new { include mod }.new end let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) } let(:environment) { Puppet::Node::Environment.create(:myenv, []) } before do Puppet::Parser::Functions.reset end it "should have a method for returning an environment-specific module" do expect(Puppet::Parser::Functions.environment_module(environment)).to be_instance_of(Module) end describe "when calling newfunction" do it "should create the function in the environment module" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } expect(function_module).to be_method_defined :function_name end it "should warn if the function already exists" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } Puppet.expects(:warning) Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } end it "should raise an error if the function type is not correct" do expect { Puppet::Parser::Functions.newfunction("name", :type => :unknown) { |args| } }.to raise_error Puppet::DevError, "Invalid statement type :unknown" end it "instruments the function to profile the execution" do messages = [] Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::WallClock.new(proc { |msg| messages << msg }, "id")) Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } callable_functions_from(function_module).function_name([]) expect(messages.first).to match(/Called name/) end end describe "when calling function to test function existence" do it "should return false if the function doesn't exist" do Puppet::Parser::Functions.autoloader.stubs(:load) expect(Puppet::Parser::Functions.function("name")).to be_falsey end it "should return its name if the function exists" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } expect(Puppet::Parser::Functions.function("name")).to eq("function_name") end it "should try to autoload the function if it doesn't exist yet" do Puppet::Parser::Functions.autoloader.expects(:load) Puppet::Parser::Functions.function("name") end it "combines functions from the root with those from the current environment" do Puppet.override(:current_environment => Puppet.lookup(:root_environment)) do Puppet::Parser::Functions.newfunction("onlyroot", :type => :rvalue) do |args| end end Puppet.override(:current_environment => Puppet::Node::Environment.create(:other, [])) do Puppet::Parser::Functions.newfunction("other_env", :type => :rvalue) do |args| end expect(Puppet::Parser::Functions.function("onlyroot")).to eq("function_onlyroot") expect(Puppet::Parser::Functions.function("other_env")).to eq("function_other_env") end expect(Puppet::Parser::Functions.function("other_env")).to be_falsey end end describe "when calling function to test arity" do let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) } it "should raise an error if the function is called with too many arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1,2,3]) }.to raise_error ArgumentError end it "should raise an error if the function is called with too few arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError end it "should not raise an error if the function is called with correct number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error end it "should raise an error if the variable arg function is called with too few arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError end it "should not raise an error if the variable arg function is called with correct number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error end it "should not raise an error if the variable arg function is called with more number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1,2,3]) }.to_not raise_error end end describe "::arity" do it "returns the given arity of a function" do Puppet::Parser::Functions.newfunction("name", :arity => 4) { |args| } expect(Puppet::Parser::Functions.arity(:name)).to eq(4) end it "returns -1 if no arity is given" do Puppet::Parser::Functions.newfunction("name") { |args| } expect(Puppet::Parser::Functions.arity(:name)).to eq(-1) end end end
41.157895
159
0.695652
6a944665a256e3b36e8d53889be4e7be5d68f06b
3,485
module ListingViewUtils extend MoneyRails::ActionViewExtension module_function # parameters: # - units, array from shape[:units] # - selected, symbol of unit type # def unit_options(units, selected_unit = nil) units .map { |u| HashUtils.compact(u) } .map { |unit| renamed = HashUtils.rename_keys({name_tr_key: :unit_tr_key, selector_tr_key: :unit_selector_tr_key}, unit) { display: translate_unit(unit[:unit_type], unit[:name_tr_key]), value: unit.to_json, kind: unit[:kind], selected: selected_unit.present? && HashUtils.sub_eq(renamed, selected_unit, :unit_type, :unit_tr_key, :unit_selector_tr_key) } } end def translate_unit(type, tr_key, locale: nil) l = (locale || I18n.locale).to_sym case type.to_s when 'hour' I18n.translate("listings.unit_types.hour", locale: l) when 'day' I18n.translate("listings.unit_types.day", locale: l) when 'night' I18n.translate("listings.unit_types.night", locale: l) when 'week' I18n.translate("listings.unit_types.week", locale: l) when 'month' I18n.translate("listings.unit_types.month", locale: l) when 'unit' I18n.translate("listings.unit_types.unit", locale: l) when 'custom' I18n.translate(tr_key, locale: l) else raise ArgumentError.new("No translation for unit type: #{type}, translation_key: #{tr_key}") end end # FIXME I feel that this is not quite right. # Instead of unit type, the first parameter should be selector type (number, day) # and that should affect how we should the information def translate_quantity(type, tr_key = nil) case type.to_s when 'hour' I18n.translate("listings.quantity.hour") when 'day' I18n.translate("listings.quantity.day") when 'night' I18n.translate("listings.quantity.night") when 'week' I18n.translate("listings.quantity.week") when 'month' I18n.translate("listings.quantity.month") when 'unit' I18n.translate("listings.quantity.unit") when 'custom' if (tr_key) I18n.translate(tr_key) else I18n.translate("listings.quantity.custom") end else raise ArgumentError.new("No translation for unit quantity: #{type}") end end def shipping_info(shipping_type, shipping_price, shipping_price_additional) if shipping_type == :shipping && shipping_price_additional.present? I18n.translate("listings.show.shipping_price_additional", price: MoneyViewUtils.to_humanized(shipping_price), shipping_price_additional: MoneyViewUtils.to_humanized(shipping_price_additional)) elsif shipping_type == :shipping I18n.translate("listings.show.shipping", price: MoneyViewUtils.to_humanized(shipping_price)) elsif shipping_type == :pickup I18n.translate("listings.show.pickup", price: MoneyViewUtils.to_humanized(shipping_price)) else raise ArgumentError.new("Delivery type not supported") end end def youtube_video_ids(text) return [] unless text.present? && text.is_a?(String) text.scan(/https?:\/\/\S+/).map { |l| youtube_video_id(l) }.compact end def youtube_video_id(link) return nil unless link.present? && link.is_a?(String) pattern = /^.*(?:(?:youtu\.be\/|youtu.*v\/|youtu.*embed\/)|youtu.*(?:\?v=|\&v=))([^#\&\?]*).*/ Maybe(pattern.match(link))[1].or_else(nil) end end
34.50495
135
0.669154
acc7c54283633dddc94c8f19ef13efe07fc77cab
875
require 'spec_helper' describe 'puppetdb::master::puppetdb_conf', :type => :class do let :node do 'puppetdb.example.com' end on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts.merge({ :puppetversion => Puppet.version, :selinux => false }) end let(:pre_condition) { 'class { "puppetdb": }' } context 'when using using default values' do it { should contain_ini_setting('puppetdbserver_urls').with( :value => 'https://localhost:8081/' )} end context 'when using using default values' do let (:params) do { :legacy_terminus => true, } end it { should contain_ini_setting('puppetdbserver').with( :value => 'localhost' )} it { should contain_ini_setting('puppetdbport').with( :value => '8081' )} end end end end
27.34375
107
0.604571
6163a966ce1162522f706b3a033b61a3b536649e
1,182
module FactoryHelpers def build(which, attrs = {}) method_name = "build_#{which}" if respond_to?(method_name) send(method_name) end end def create(which, attrs = {}) build(which, attrs).tap { |record| record.save! } end def build_star_event(attrs = {}) StarEvent.new({ event_id: "2550646448", source: { "repo_id" => "28513398", "actor_id" => "1258", "repo_name" => "MengTo/Spring", "repo_description" => "A library to simplify iOS animations in Swift.", "created_at" => Time.now.utc.iso8601, "actor_login" => "bryanveloso", "actor_avatar_url" => "https://avatars.githubusercontent.com/u/1258?", }, }.merge(attrs)) end def build_github_event(attrs = {}) GitHubEvent.new({ id: "2550646448", type: "WatchEvent", repo_id: "28513398", repo_name: "MengTo/Spring", repo_description: "A library to simplify iOS animations in Swift.", created_at: Time.now.utc.iso8601, actor_id: "1258", actor_login: "bryanveloso", actor_avatar_url: "https://avatars.githubusercontent.com/u/1258?", }.merge(attrs)) end end
28.142857
79
0.611675
bb59b7929e9616a496aa526c3102fa8199cea38a
484
class Debunker class Command::ToggleColor < Debunker::ClassCommand match 'toggle-color' group 'Misc' #'Toggle syntax highlighting.' banner <<-'BANNER' Usage: toggle-color Toggle syntax highlighting. BANNER def process _debunker_.color = color_toggle output.puts "Syntax highlighting #{_debunker_.color ? "on" : "off"}" end def color_toggle !_debunker_.color end Debunker::Commands.add_command(self) end end
19.36
74
0.663223
39d12290822aaf5503d383b37a0c8f09c252842c
2,902
module Locomotive module Extensions module Page module Tree extend ActiveSupport::Concern included do include ::Mongoid::Tree include ::Mongoid::Tree::Ordering include PatchedTreeMethods ## fields ## field :depth, type: Integer, default: 0 ## callbacks ## before_save :persist_depth before_save :ensure_index_position before_destroy :delete_descendants ## indexes ## index position: 1 index depth: 1, position: 1 index site_id: 1, depth: 1, position: 1 alias_method_chain :rearrange, :identity_map alias_method_chain :rearrange_children, :identity_map alias_method_chain :siblings_and_self, :scoping end module PatchedTreeMethods def ancestors # https://github.com/benhutton/mongoid-tree/commit/acb6eb0440dc003cd8536cb8cc6ff4b16c9c9402 super.order_by(:depth.asc) end private def assign_default_position return if self.position.present? && !self.persisted? super end end # Returns the children of this node but with the minimal set of required attributes # # @return [ Array ] The children pages ordered by their position # def children_with_minimal_attributes(attrs = []) self.children.minimal_attributes(attrs) end # Assigns the new position of each child of this node. # # @param [ Array ] ids The ordered list of page ids (string) # def sort_children!(ids) position, cached_children = 0, self.children.to_a ids.each do |id| if child = cached_children.detect { |p| p._id == Moped::BSON::ObjectId(id) } child.position = position child.save position += 1 end end end ## # Returns this document's siblings and itself, all scoped by the site # # @return [Mongoid::Criteria] Mongoid criteria to retrieve the document's siblings and itself def siblings_and_self_with_scoping base_class.where(parent_id: self.parent_id, site_id: self.site_id) end def depth self.parent_ids.count end protected def rearrange_with_identity_map ::Mongoid::IdentityMap.clear rearrange_without_identity_map end def rearrange_children_with_identity_map self.children.reset rearrange_children_without_identity_map end def persist_depth self.depth = self.parent_ids.count end def ensure_index_position self.position = 0 if self.index? end end end end end
27.377358
103
0.591661
b942dd742eab283d37bdcc5159ac240eb1828354
7,533
require 'rbconfig' # ruby 1.8.7 doesn't define RUBY_ENGINE ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby' ruby_version = RbConfig::CONFIG["ruby_version"] path = File.expand_path('..', __FILE__) $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/concurrent-ruby-1.1.8/lib/concurrent-ruby" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/i18n-1.8.7/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/minitest-5.14.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/tzinfo-2.0.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/zeitwerk-2.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/activesupport-6.1.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ast-2.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/bindata-2.4.8/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/msgpack-1.4.2" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/msgpack-1.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/bootsnap-1.7.1" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/bootsnap-1.7.1/lib" $:.unshift "#{path}/" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/byebug-11.1.3" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/byebug-11.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/docile-1.3.5/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov-html-0.12.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov_json_formatter-0.1.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov-0.21.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/codecov-0.4.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/coderay-1.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/colorize-0.8.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/highline-2.0.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/commander-4.5.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/connection_pool-2.2.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/diff-lcs-1.4.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/unf_ext-0.0.7.7" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unf_ext-0.0.7.7/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unf-0.1.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/domain_name-0.5.20190701/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/elftools-1.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/hpricot-0.8.6" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/hpricot-0.8.6/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/http-cookie-1.0.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mime-types-data-3.2020.1104/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mime-types-3.3.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/net-http-digest_auth-1.4.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/net-http-persistent-4.0.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mini_portile2-2.5.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/racc-1.5.2" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/racc-1.5.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/nokogiri-1.11.1-x86_64-darwin/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ntlm-http-0.1.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/webrick-1.7.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/webrobots-0.1.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mechanize-2.7.7/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/method_source-1.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mustache-1.1.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parallel-1.20.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parallel_tests-3.4.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parser-3.0.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rainbow-3.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-runtime-0.5.6267/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parlour-5.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/patchelf-1.3.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/plist-3.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/pry-0.13.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rack-2.2.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/universal-darwin-20/2.6.0/rdiscount-2.2.0.2" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rdiscount-2.2.0.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/regexp_parser-2.0.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rexml-3.2.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ronn-0.7.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-support-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-core-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-expectations-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-mocks-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-github-2.3.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-its-1.3.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-retry-0.6.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-static-0.5.6274-universal-darwin-20/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-0.5.6274/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-sorbet-1.8.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-wait-0.0.9/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-ast-1.4.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-progressbar-1.11.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unicode-display_width-2.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-1.9.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-performance-1.9.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rails-2.9.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rspec-2.2.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-sorbet-0.5.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-macho-2.5.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-runtime-stub-0.2.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/thor-1.0.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/spoom-1.0.7/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/tapioca-0.4.13/lib"
80.138298
109
0.669189
39cfc2a697fd0f066869a18f825c673ff86af5be
2,455
Rails.application.configure do # Verifies that versions and hashed value of the package contents in the project's package.json config.webpacker.check_yarn_integrity = false # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Cache store. config.cache_store = :memory_store, { size: 64.megabytes } # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false config.action_mailer.delivery_method = :letter_opener # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. # config.file_watcher = ActiveSupport::EventedFileUpdateChecker # for detecting n + 1 queries using Bullet Bullet.enable = true Bullet.bullet_logger = true Bullet.rails_logger = true # Oink::Middleware logs memory and activerecord usage by default. config.middleware.use Oink::Middleware # In development , let's have ActiveStorage store everything on local disk config.active_storage.service = :local end
34.577465
97
0.762933
f8c5893b0367b91b2d952daa8729fa97fd089f51
1,269
class Api::V2::RatingsController < ApiController respond_to :xml, :json # GET /api/v2/users/:user_id/ratings?given=true def index user_from_api_key = User.find_by(api_key: request.headers[:apiKey]) return render json: {ratings: [], message: "Access denied"}, status: :unauthorized if user_from_api_key.nil? user = User.find_by(id: params[:user_id]) return respond_with :ratings => [], :status => :not_found if user.nil? if params.has_key?(:given) && params[:given] == true respond_with user.ratings, status: :ok else respond_with user.ratings_received, status: :ok end end # POST /api/v2/users/:user_id/ratings?to_user_id=X&ride_id=Y&rating_type=Z def create user_from_api_key = User.find_by(api_key: request.headers[:apiKey]) return render json: {rating: [], message: "Access denied"}, status: :unauthorized if user_from_api_key.nil? user = User.find_by(id: params[:user_id]) return respond_with rating: [], :status => :not_found if user.nil? @rating = user.give_rating_to_user params[:to_user_id], params[:ride_id], params[:rating_type].to_i unless @rating.nil? render json: @rating, status: :ok else respond_with rating: [], status: :bad_request end end end
32.538462
112
0.694247
6a3b0dffae25d7ba4f150245255b19a61d17bc4e
2,588
# frozen_string_literal: true module Clusters module Aws class ProvisionService attr_reader :provider def execute(provider) @provider = provider configure_provider_credentials provision_cluster if provider.make_creating WaitForClusterCreationWorker.perform_in( Clusters::Aws::VerifyProvisionStatusService::INITIAL_INTERVAL, provider.cluster_id ) else provider.make_errored!("Failed to update provider record; #{provider.errors.full_messages}") end rescue Clusters::Aws::FetchCredentialsService::MissingRoleError provider.make_errored!('Amazon role is not configured') rescue ::Aws::Errors::MissingCredentialsError, Settingslogic::MissingSetting provider.make_errored!('Amazon credentials are not configured') rescue ::Aws::STS::Errors::ServiceError => e provider.make_errored!("Amazon authentication failed; #{e.message}") rescue ::Aws::CloudFormation::Errors::ServiceError => e provider.make_errored!("Amazon CloudFormation request failed; #{e.message}") end private def credentials @credentials ||= Clusters::Aws::FetchCredentialsService.new(provider).execute end def configure_provider_credentials provider.update!( access_key_id: credentials.access_key_id, secret_access_key: credentials.secret_access_key, session_token: credentials.session_token ) end def provision_cluster provider.api_client.create_stack( stack_name: provider.cluster.name, template_body: stack_template, parameters: parameters, capabilities: ["CAPABILITY_IAM"] ) end def parameters [ parameter('ClusterName', provider.cluster.name), parameter('ClusterRole', provider.role_arn), parameter('ClusterControlPlaneSecurityGroup', provider.security_group_id), parameter('VpcId', provider.vpc_id), parameter('Subnets', provider.subnet_ids.join(',')), parameter('NodeAutoScalingGroupDesiredCapacity', provider.num_nodes.to_s), parameter('NodeInstanceType', provider.instance_type), parameter('KeyName', provider.key_name) ] end def parameter(key, value) { parameter_key: key, parameter_value: value } end def stack_template File.read(Rails.root.join('vendor', 'aws', 'cloudformation', 'eks_cluster.yaml')) end end end end
33.179487
102
0.664219
e81acf1fd5eb80352bd50d624a5b81b1f10e1109
229
class SetupController < ApplicationController def loadView self.view = SetupView.alloc.initWithFrame(UIScreen.mainScreen.bounds) self.view.setup_controller = self self.view.swipe(:down){ dismiss_modal } end end
22.9
73
0.764192
623ac0ae98897a3104d9acaa51a6d7a557eb23be
2,625
module CantoOAuth2 class AuthorizationServer < ::Sinatra::Base OAuthError = Class.new(RuntimeError) InvalidRequest = Class.new(OAuthError) # InvalidScope = Class.new(OAuthError) # AccessDenied = Class.new(OAuthError) # ServerError = Class.new(OAuthError) # UnauthorizedClient = Class.new(OAuthError) # UnsupportedResponseType = Class.new(OAuthError) # TemporarilyUnavailable = Class.new(OAuthError) set :raise_errors, false set :show_exceptions, false error OAuthError do redirect redirect_uri :error => error_name(env['sinatra.error']) end get '/authorize' do client_id = params[:client_id] client = RegisteredClient.where(:client_id => client_id).where(~{:redirect_uri => nil}).first halt 400 unless client_id && client @redirect_uri = client.redirect_uri raise InvalidRequest unless params[:response_type] == 'code' auth = Authorization.create(:code => UUIDTools::UUID.random_create.to_s, :client_id => client_id, :redirect_uri => @redirect_uri) redirect redirect_uri :code => auth.code end post '/token' do halt 400 if params[:grant_type] != 'authorization_code' auth = Authorization.first(:code => params[:code]) halt 400 unless auth client = RegisteredClient.first(:client_id => auth[:client_id]) @auth = Rack::Auth::Basic::Request.new(request.env) if @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [auth.client_id, client.client_secret] elsif params[:client_id] && params[:client_secret] else halt 401 end content_type 'application/json' token = Token.create token_type: 'example', access_token: UUIDTools::UUID.random_create.to_s, expires_in: 3600, refresh_token: UUIDTools::UUID.random_create.to_s, authorization_id: auth.id token.to_json end def redirect_uri(opts = {}) opts[:state] = params[:state] if params[:state] uri = URI.parse(@redirect_uri) uri.query ||= '' unless opts.empty? uri.query += URI.encode_www_form(opts) if uri.query uri.to_s end ## TODO: move to error class itself def error_name(klass) underscore(klass.class.name).split(/\//).last end def underscore(string) string.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end ## end end end
32.8125
102
0.614476
5df8ce41ffc76d3202736ebee147f3c090ef96ee
125
require 'spec_helper' describe "secret_key/index.html.haml" do pending "add some examples to (or delete) #{__FILE__}" end
20.833333
56
0.752
abdac07b97c6c6693e9bedcb2db8bd7e17924530
156
# frozen_string_literal: true class Tripletexer::Configuration attr_accessor :api_url def initialize @api_url = 'https://tripletex.no/' end end
15.6
38
0.74359
6164c4c44c55c145883621675e302225d10284b7
39
module GameEcs VERSION = "0.1.0" end
9.75
19
0.666667
61b674dd40142d0c37cc979f2531b130598a2fbf
34
module Hr VERSION = "0.0.3" end
8.5
19
0.617647
e896fa22712cc820ac44bdf5fffa8a81218f9ffc
60
require 'faraday' require 'json' module FutureLearnApi end
10
21
0.8
bbe15c6b49d693369ea2cb8254d8f67593dd13e9
13,058
# frozen_string_literal: true require "stringio" require "set" require "fisk/instructions" require "fisk/basic_block" require "fisk/errors" require "fisk/version" class Fisk class Operand def works? type; self.type == type; end def unknown_label?; false; end def register?; false; end def temp_register?; false; end def extended_register?; false; end def memory?; false; end def rip?; false; end def rex_value value >> 3 end def op_value value end end class ValueOperand < Operand attr_reader :value alias :type :value def initialize value @value = value end end module Registers class Register < Operand attr_reader :name, :type, :value def initialize name, type, value @name = name @type = type @value = value end def works? type type == self.name || type == self.type end def op_value value & 0x7 end def extended_register?; @value > 7; end def rip?; false; end end class Rip attr_reader :displacement def initialize displacement @displacement = displacement end def works? type type == "m64" || type == "m" end def unknown_label?; false; end def temp_register?; false; end def memory?; true; end def rip?; true; end def rex_value 0x0 end def op_value 0x0 end end class Temp < Operand attr_reader :name, :type attr_accessor :register, :start_point, :end_point def initialize name, type @name = name @type = type @start_point = nil @end_point = nil end def temp_register?; true; end def op_value @register.op_value end def extended_register? @register.extended_register? end def rex_value @register.rex_value end def value @register.value end end EAX = Register.new "eax", "r32", 0 ECX = Register.new "ecx", "r32", 1 EDX = Register.new "edx", "r32", 2 EBX = Register.new "ebx", "r32", 3 ESP = Register.new "esp", "r32", 4 EBP = Register.new "ebp", "r32", 5 ESI = Register.new "esi", "r32", 6 EDI = Register.new "edi", "r32", 7 RAX = Register.new "rax", "r64", 0 RCX = Register.new "rcx", "r64", 1 RDX = Register.new "rdx", "r64", 2 RBX = Register.new "rbx", "r64", 3 RSP = Register.new "rsp", "r64", 4 RBP = Register.new "rbp", "r64", 5 RSI = Register.new "rsi", "r64", 6 RDI = Register.new "rdi", "r64", 7 8.times do |i| i += 8 const_set "R#{i}", Register.new("r#{i}", "r64", i) end # List of *caller* saved registers for the C calling convention CALLER_SAVED = [ RDI, RSI, RDX, RCX, R8, R9, R10, R11 ] # List of *callee* saved registers for the C calling convention CALLEE_SAVED = [ RBX, RSP, RBP, R12, R13, R14, R15 ] end class Memory < Operand attr_reader :displacement def initialize register, displacement @register = register @displacement = displacement end def value @register.value end def memory?; true; end end class M64 < Memory def type "m64" end end class M < Memory def type "m" end end def rip displacement = 0 Registers::Rip.new(displacement) end def m64 x, displacement = 0 M64.new x, displacement end def m x, displacement = 0 M.new x, displacement end # Define all immediate value methods of different sizes [8, 16, 32, 64].each do |size| class_eval <<~eostr, __FILE__, __LINE__ + 1 class Imm#{size} < ValueOperand def type "imm#{size}" end end def imm#{size} val; Imm#{size}.new(val.to_i); end eostr end class Rel8 < ValueOperand def type "rel8" end end class Rel32 < ValueOperand def type "rel32" end end class MOffs64 < ValueOperand def type "moffs64" end end class Lit < ValueOperand def type value.to_s end end class UnknownLabel < Struct.new(:name) def works? type type == "rel32" end def unknown_label?; true; end def temp_register?; false; end def value label = assembler.label_for(name) label.position - (insn.position + insn.bytesize) end end class Label < Struct.new(:name) def label?; true; end def jump?; false; end def has_temp_registers?; false; end end class Instruction def initialize insn, form, operands @insn = insn @form = form @operands = operands end def jump? false end def has_temp_registers? @operands.any?(&:temp_register?) end def temp_registers @operands.find_all(&:temp_register?) end def encodings @form.encodings end def encode buffer, labels encoding = @form.encodings.first encoding.encode buffer, @operands true end def bytesize @form.encodings.first.bytesize end def label?; false; end end class UnresolvedInstruction def initialize insn, form, operand @insn = insn @form = form @operand = operand @saved_pos = nil end def jump? true end def target @operand.name end def has_temp_registers?; false; end def encode buffer, labels # Estimate by using a rel32 offset form = find_form "rel32" encoding = form.encodings.first operand_klass = Rel32 if labels.key? @operand.name if @saved_pos # Only use rel32 if we saved the position buffer.seek @saved_pos, IO::SEEK_SET else estimated_offset = labels[@operand.name] - (buffer.pos + encoding.bytesize) if estimated_offset >= -128 && estimated_offset <= 127 # fits in a rel8 operand_klass = Rel8 form = find_form "rel8" encoding = form.encodings.first end end jump_len = -(buffer.pos + encoding.bytesize - labels[@operand.name]) encoding.encode buffer, [operand_klass.new(jump_len)] true else # We've hit a label that doesn't exist yet # Save the buffer position so we can seek back to it later @saved_pos = buffer.pos # Write 5 bytes to reserve our spot encoding.bytesize.times { buffer.putc 0 } false end end def label?; false; end private def find_form form_type @insn.forms.find { |form| form.operands.first.type == form_type } end end def initialize @instructions = [] @labels = {} # A set of temp registers recorded as we see them (not at allocation time) @temp_registers = Set.new yield self if block_given? end # Mark a temporary register as "done being used" at this point in the # instructions. Using the register after passing the register to this # method results in undefined behavior. def release_register reg if reg.end_point raise Errors::AlreadyReleasedError, "register #{reg.name} already released at #{reg.end_point}" end reg.end_point = (@instructions.length - 1) end # Releases all registers that haven't already been released def release_all_registers @temp_registers.each do |reg| next if reg.end_point release_register reg end end # Return a list of basic blocks for the instructions def basic_blocks cfg.blocks end # Return a cfg for these instructions. The CFG includes connected basic # blocks as well as any temporary registers def cfg CFG.build @instructions end # Create a label to be used with jump instructions. For example: # # fisk.jmp(fisk.label(:foo)) # fisk.int(lit(3)) # fisk.put_label(:foo) # def label name UnknownLabel.new(name) end # Insert a label named +name+ at the current position in the instructions. def put_label name @instructions << Label.new(name) self end alias :make_label :put_label # Allocate and return a new register. These registers will be replaced with # real registers when `assign_registers` is called. def register name = "temp" Registers::Temp.new name, "r64" end # Assign registers to any temporary registers. Only registers in +list+ # will be used when selecting register assignments def assign_registers list, local: false temp_registers = @temp_registers # This mutates the temp registers, setting their end_point based on # the CFG self.cfg unless local temp_registers.each do |reg| unless reg.end_point raise Errors::UnreleasedRegisterError, "Register #{reg.name} hasn't been released" end end temp_registers = temp_registers.sort_by(&:start_point) active = [] free_registers = list.reverse register_count = list.length temp_registers.each do |temp_reg| # expire old intervals active, dead = active.sort_by(&:end_point).partition do |j| j.end_point >= temp_reg.start_point end # Add unused registers back to the free register list dead.each { |tr| free_registers << tr.register } if active.length == register_count raise NotImplementedError, "Register spilled" end temp_reg.register = free_registers.pop active << temp_reg end end Registers.constants.grep(/^[A-Z0-9]*$/).each do |const| val = Registers.const_get const define_method(const.downcase) { val } end include Fisk::Instructions::DSLMethods def moffs64 val MOffs64.new val end # Create a signed immediate value of the right width def imm val if val >= -0x7F - 1 && val <= 0x7F imm8 val elsif val >= -0x7FFF - 1 && val <= 0x7FFF imm16 val elsif val >= -0x7FFFFFFF - 1 && val <= 0x7FFFFFFF imm32 val elsif val >= -0x7FFFFFFFFFFFFFFF - 1 && val <= 0x7FFFFFFFFFFFFFFF imm64 val else raise ArgumentError, "#{val} is larger than a 64 bit int" end end # Create an unsigned immediate value of the right width def uimm val if val < 0 raise ArgumentError, "#{val} is negative" elsif val <= 0xFF imm8 val elsif val <= 0xFFFF imm16 val elsif val <= 0xFFFFFFFF imm32 val elsif val <= 0xFFFFFFFFFFFFFFFF imm64 val else raise ArgumentError, "#{val} is too large for a 64 bit int" end end def rel8 val Rel8.new val end def rel32 val Rel32.new val end def lit val Lit.new val end # Instance eval's a given block and writes encoded instructions to +buf+. # For example: # # fisk = Fisk.new # fisk.asm do # mov r9, imm64(32) # end # def asm buf = StringIO.new(''.b), &block instance_eval(&block) write_to buf buf end # Encodes all instructions and returns a binary string with the encoded # instructions. def to_binary io = StringIO.new ''.b write_to io io.string end # Encode all instructions and write them to +buffer+. +buffer+ should be an # IO object. def write_to buffer labels = {} unresolved = [] @instructions.each do |insn| if insn.label? labels[insn.name] = buffer.pos else unless insn.encode buffer, labels unresolved << insn end end end return if unresolved.empty? pos = buffer.pos unresolved.each do |insn| insn.encode buffer, labels end buffer.seek pos, IO::SEEK_SET buffer end def gen_with_insn insns, params forms = insns.forms.find_all do |insn| if insn.operands.length == params.length params.zip(insn.operands).all? { |want_op, have_op| want_op.works?(have_op.type) } else false end end if forms.length == 0 valid_forms = insns.forms.map { |form| " #{insns.name} #{form.operands.map(&:type).join(", ")}" }.join "\n" msg = <<~eostr Couldn't find instruction #{insns.name} #{params.map(&:type).join(", ")} Valid forms: #{valid_forms} eostr raise NotImplementedError, msg end form = forms.first insn = nil params.each do |param| if param.unknown_label? if params.length > 1 raise ArgumentError, "labels only work with single param jump instructions" end insn = UnresolvedInstruction.new(insns, form, params.first) end if param.temp_register? if param.end_point raise Errors::UseAfterInvalidationError, "Register #{param.name} used after release" end @temp_registers << param param.start_point ||= @instructions.length end end insn ||= Instruction.new(insns, form, params) @instructions << insn self end end
22.020236
101
0.611885
ab689c5bd6418f2445dafa3669f34bda0df2976e
240
# frozen_string_literal: true require 'spec_helper' TestHosts.each_os(only: %w[opensuse]) do |os_name, host_json, spec_dir| RSpec.describe Kanrisuru::Core::Zypper do include_examples 'zypper', os_name, host_json, spec_dir end end
24
71
0.766667
f8a89a57dfa838564288fd05fda3d0a6467fe23c
170
# Cookbook Name:: oc-opsworks-recipes # Recipe:: maintenance-mode-off ::Chef::Recipe.send(:include, MhOpsworksRecipes::RecipeHelpers) toggle_maintenance_mode_to(false)
24.285714
63
0.794118
e966d3d382b281d37ed22d3c4438e6731b0dfa80
1,516
module KnifeBoxer class ConflictCheck # A Chef::Environment. This environment's version constraints will be # checked for conflicts to determine if a set of changes can be reverted. attr_reader :environment # A Hash of the form # cookbook_name<String> => { "old_version" => version<String>, "new_version" => version<String> } # This hash describes the change that the user wants to revert. attr_reader :changes_to_revert def initialize(environment, changes_to_revert) @environment = environment @changes_to_revert = changes_to_revert end # An Array of messages describing conflicts that prevent the change from # being reverted. def conflicts conflicted_changes = [] changes_to_revert.each do |cookbook_name, update_info| expected_version = update_info["new_version"] actual_version = environment.cookbook_versions[cookbook_name].sub(/^= /, '') # conflict checks; if versions have since been updated, or # old_version is "Nothing" we bail. if actual_version != expected_version conflicted_changes << "Cookbook '#{cookbook_name}' conflicts: trying to revert from version '#{expected_version}' but is '#{actual_version}'" next elsif update_info["old_version"] == "Nothing" conflicted_changes << "Cookbook '#{cookbook_name}' conflicts: there is no previous version to revert to" next end end conflicted_changes end end end
36.97561
151
0.688654
08ef5ff5794bf3fd222e502389320dd3476b3512
1,914
# Module containing the methods useful for child IFRAME to parent window communication module RespondsToParent # Executes the response body as JavaScript in the context of the parent window. # Use this method of you are posting a form to a hidden IFRAME or if you would like # to use IFRAME base RPC. def responds_to_parent(&block) yield if performed? # We're returning HTML instead of JS or XML now response.headers['Content-Type'] = 'text/html; charset=UTF-8' # Either pull out a redirect or the request body script = if location = erase_redirect_results "document.location.href = #{location.to_s.inspect}" else response.body end # Escape quotes, linebreaks and slashes, maintaining previously escaped slashes # Suggestions for improvement? script = (script || ''). gsub('\\', '\\\\\\'). gsub(/\r\n|\r|\n/, '\\n'). gsub(/['"]/, '\\\\\&'). gsub('</script>','</scr"+"ipt>') # Clear out the previous render to prevent double render erase_results # Eval in parent scope and replace document location of this frame # so back button doesn't replay action on targeted forms # loc = document.location to be set after parent is updated for IE # with(window.parent) - pull in variables from parent window # setTimeout - scope the execution in the windows parent for safari # window.eval - legal eval for Opera render :text => "<html><body><script type='text/javascript' charset='utf-8'> var loc = document.location; with(window.parent) { setTimeout(function() { window.eval('#{script}'); try { loc.replace('about:blank'); } catch(ignored){} }, 1) } </script></body></html>" end end alias respond_to_parent responds_to_parent end
40.723404
148
0.624869
1c212a33099849a1911f0b41f381d1d9bdfa766c
619
module ApplicationHelper def format_time(time) time.strftime('%l %p, %b %e %z') end def full_time_format(time) time.strftime("%d %b %Y %I:%M%p %z") end def card_image_data(card) card_url = wall_snapshot_card_path(@wall, @wall.card_snapshot(card), card) { 'data-identifier' => card.identifier, 'data-x' => card.x, 'data-y' => card.y, 'data-height' => card.height, 'data-width' => card.width, 'data-positive' => card.positive, 'title' => card.title, 'data-content' => 'Double click to see details.', 'data-url' => card_url } end end
24.76
78
0.592892
286adc3c2205c0e6a36c0043bfc04f0b373ff707
619
# Reload the browser automatically whenever files change activate :livereload ### # Compass ### compass_config do |config| config.output_style = :compressed end ### # Helpers ### helpers do def get_url absolute_prefix + url_prefix end end ### # Config ### set :css_dir, 'stylesheets' set :js_dir, 'javascripts' set :images_dir, 'images' set :url_prefix, '/' set :absolute_prefix, 'http://localhost:4567' # Build-specific configuration configure :build do puts "local build" set :url_prefix, "" set :absolute_prefix, "" activate :asset_hash activate :minify_javascript activate :minify_css end
16.289474
56
0.723748
bbc2ae0945d7f70689061f669f663d6177cd61d7
3,295
module Elastic module Transport module Transport module Connections # Wraps the collection of connections for the transport object as an Enumerable object. # # @see Base#connections # @see Selector::Base#select # @see Connection # class Collection include Enumerable DEFAULT_SELECTOR = Selector::RoundRobin attr_reader :selector # @option arguments [Array] :connections An array of {Connection} objects. # @option arguments [Constant] :selector_class The class to be used as a connection selector strategy. # @option arguments [Object] :selector The selector strategy object. # def initialize(arguments={}) selector_class = arguments[:selector_class] || DEFAULT_SELECTOR @connections = arguments[:connections] || [] @selector = arguments[:selector] || selector_class.new(arguments.merge(:connections => self)) end # Returns an Array of hosts information in this collection as Hashes. # # @return [Array] # def hosts @connections.to_a.map { |c| c.host } end # Returns an Array of alive connections. # # @return [Array] # def connections @connections.reject { |c| c.dead? } end alias :alive :connections # Returns an Array of dead connections. # # @return [Array] # def dead @connections.select { |c| c.dead? } end # Returns an Array of all connections, both dead and alive # # @return [Array] # def all @connections end # Returns a connection. # # If there are no alive connections, resurrects a connection with least failures. # Delegates to selector's `#select` method to get the connection. # # @return [Connection] # def get_connection(options={}) if connections.empty? && dead_connection = dead.sort { |a,b| a.failures <=> b.failures }.first dead_connection.alive! end selector.select(options) end def each(&block) connections.each(&block) end def slice(*args) connections.slice(*args) end alias :[] :slice def size connections.size end # Add connection(s) to the collection # # @param connections [Connection,Array] A connection or an array of connections to add # @return [self] # def add(connections) @connections += Array(connections).to_a self end # Remove connection(s) from the collection # # @param connections [Connection,Array] A connection or an array of connections to remove # @return [self] # def remove(connections) @connections -= Array(connections).to_a self end end end end end end
28.903509
116
0.529287
ff0f3ceca92e66ae979dea650b7292fd995653c7
2,698
require "formula" class Emscripten < Formula homepage "http://emscripten.org" url "https://github.com/kripken/emscripten/archive/1.21.0.tar.gz" sha1 "88967d336b50de17a4333e736b4ed3db67b7ea50" head "https://github.com/kripken/emscripten.git", :branch => "incoming" bottle do sha1 "c4632e68a9b31703e094a7e9c525d18f5340d00f" => :mavericks sha1 "a62601a61576a6aa60c4113e0b61bb374e7d3361" => :mountain_lion sha1 "c68aa901aa31c32c7d933fc4882553f1138e1b44" => :lion end head do resource "fastcomp" do url "https://github.com/kripken/emscripten-fastcomp.git", :branch => "incoming" end resource "fastcomp-clang" do url "https://github.com/kripken/emscripten-fastcomp-clang.git", :branch => "incoming" end end stable do resource "fastcomp" do url "https://github.com/kripken/emscripten-fastcomp/archive/1.21.0.tar.gz" sha1 "d468ca3ea4b3ed02b3e20ba86b781f028c2514b0" end resource "fastcomp-clang" do url "https://github.com/kripken/emscripten-fastcomp-clang/archive/1.21.0.tar.gz" sha1 "7974f7cc0646534fd226ae447b962a11d77a7c03" end end depends_on "node" depends_on "closure-compiler" => :optional depends_on "yuicompressor" def install # OSX doesn't provide a "python2" binary so use "python" instead. python2_shebangs = `grep --recursive --files-with-matches ^#!/usr/bin/.*python2$ #{buildpath}` python2_shebang_files = python2_shebangs.lines.sort.uniq python2_shebang_files.map! {|f| Pathname(f.chomp)} python2_shebang_files.reject! &:symlink? inreplace python2_shebang_files, %r{^(#!/usr/bin/.*python)2$}, "\\1" # All files from the repository are required as emscripten is a collection # of scripts which need to be installed in the same layout as in the Git # repository. libexec.install Dir['*'] (buildpath/"fastcomp").install resource("fastcomp") (buildpath/"fastcomp/tools/clang").install resource("fastcomp-clang") args = [ "--prefix=#{libexec}/llvm", "--enable-optimized", "--enable-targets=host,js", "--disable-assertions", "--disable-bindings", ] cd "fastcomp" do system "./configure", *args system "make" system "make", "install" end %w(em++ em-config emar emcc emcmake emconfigure emlink.py emmake emranlib emrun emscons).each do |emscript| bin.install_symlink libexec/emscript end end test do system "#{libexec}/llvm/bin/llvm-config", "--version" end def caveats; <<-EOS.undent Manually set LLVM_ROOT to \"#{opt_prefix}/libexec/llvm/bin\" in ~/.emscripten after running `emcc` for the first time. EOS end end
30.659091
98
0.689029
6106ed565dcbd32765db03a8d563f1b8ac2566fb
240
class Digitization::Fulltext < ApplicationRecord belongs_to :book, class_name: 'Digitization::Book', foreign_key: :digitization_book_id, primary_key: :id, inverse_of: :fulltext validates :text, presence: true end
26.666667
107
0.716667
112785434a577b28c1d3224b4f343f513d205021
19,232
require "pathname" require "securerandom" require "set" require "vagrant" require "vagrant/config/v2/util" require "vagrant/util/platform" require File.expand_path("../vm_provisioner", __FILE__) require File.expand_path("../vm_subvm", __FILE__) module VagrantPlugins module Kernel_V2 class VMConfig < Vagrant.plugin("2", :config) DEFAULT_VM_NAME = :default attr_accessor :base_mac attr_accessor :boot_timeout attr_accessor :box attr_accessor :box_url attr_accessor :box_download_ca_cert attr_accessor :box_download_checksum attr_accessor :box_download_checksum_type attr_accessor :box_download_client_cert attr_accessor :box_download_insecure attr_accessor :graceful_halt_timeout attr_accessor :guest attr_accessor :hostname attr_accessor :usable_port_range attr_reader :provisioners def initialize @boot_timeout = UNSET_VALUE @box_download_ca_cert = UNSET_VALUE @box_download_checksum = UNSET_VALUE @box_download_checksum_type = UNSET_VALUE @box_download_client_cert = UNSET_VALUE @box_download_insecure = UNSET_VALUE @box_url = UNSET_VALUE @graceful_halt_timeout = UNSET_VALUE @guest = UNSET_VALUE @hostname = UNSET_VALUE @provisioners = [] # Internal state @__compiled_provider_configs = {} @__defined_vm_keys = [] @__defined_vms = {} @__finalized = false @__networks = {} @__providers = {} @__provider_overrides = {} @__synced_folders = {} end # This was from V1, but we just kept it here as an alias for hostname # because too many people mess this up. def host_name=(value) @hostname = value end # Custom merge method since some keys here are merged differently. def merge(other) super.tap do |result| other_networks = other.instance_variable_get(:@__networks) result.instance_variable_set(:@__networks, @__networks.merge(other_networks)) result.instance_variable_set(:@provisioners, @provisioners + other.provisioners) # Merge defined VMs by first merging the defined VM keys, # preserving the order in which they were defined. other_defined_vm_keys = other.instance_variable_get(:@__defined_vm_keys) other_defined_vm_keys -= @__defined_vm_keys new_defined_vm_keys = @__defined_vm_keys + other_defined_vm_keys # Merge the actual defined VMs. other_defined_vms = other.instance_variable_get(:@__defined_vms) new_defined_vms = {} @__defined_vms.each do |key, subvm| new_defined_vms[key] = subvm.clone end other_defined_vms.each do |key, subvm| if !new_defined_vms.has_key?(key) new_defined_vms[key] = subvm.clone else new_defined_vms[key].config_procs.concat(subvm.config_procs) new_defined_vms[key].options.merge!(subvm.options) end end # Merge the providers by prepending any configuration blocks we # have for providers onto the new configuration. other_providers = other.instance_variable_get(:@__providers) new_providers = @__providers.dup other_providers.each do |key, blocks| new_providers[key] ||= [] new_providers[key] += blocks end # Merge the provider overrides by appending them... other_overrides = other.instance_variable_get(:@__provider_overrides) new_overrides = @__provider_overrides.dup other_overrides.each do |key, blocks| new_overrides[key] ||= [] new_overrides[key] += blocks end # Merge synced folders. other_folders = other.instance_variable_get(:@__synced_folders) new_folders = {} @__synced_folders.each do |key, value| new_folders[key] = value.dup end other_folders.each do |id, options| new_folders[id] ||= {} new_folders[id].merge!(options) end result.instance_variable_set(:@__defined_vm_keys, new_defined_vm_keys) result.instance_variable_set(:@__defined_vms, new_defined_vms) result.instance_variable_set(:@__providers, new_providers) result.instance_variable_set(:@__provider_overrides, new_overrides) result.instance_variable_set(:@__synced_folders, new_folders) end end # Defines a synced folder pair. This pair of folders will be synced # to/from the machine. Note that if the machine you're using doesn't # support multi-directional syncing (perhaps an rsync backed synced # folder) then the host is always synced to the guest but guest data # may not be synced back to the host. # # @param [String] hostpath Path to the host folder to share. If this # is a relative path, it is relative to the location of the # Vagrantfile. # @param [String] guestpath Path on the guest to mount the shared # folder. # @param [Hash] options Additional options. def synced_folder(hostpath, guestpath, options=nil) if Vagrant::Util::Platform.windows? # On Windows, Ruby just uses normal '/' for path seps, so # just replace normal Windows style seps with Unix ones. hostpath = hostpath.to_s.gsub("\\", "/") end options ||= {} options = options.dup options[:guestpath] = guestpath.to_s.gsub(/\/$/, '') options[:hostpath] = hostpath @__synced_folders[options[:guestpath]] = options end # Define a way to access the machine via a network. This exposes a # high-level abstraction for networking that may not directly map # 1-to-1 for every provider. For example, AWS has no equivalent to # "port forwarding." But most providers will attempt to implement this # in a way that behaves similarly. # # `type` can be one of: # # * `:forwarded_port` - A port that is accessible via localhost # that forwards into the machine. # * `:private_network` - The machine gets an IP that is not directly # publicly accessible, but ideally accessible from this machine. # * `:public_network` - The machine gets an IP on a shared network. # # @param [Symbol] type Type of network # @param [Hash] options Options for the network. def network(type, options=nil) options ||= {} options = options.dup options[:protocol] ||= "tcp" if !options[:id] default_id = nil if type == :forwarded_port # For forwarded ports, set the default ID to the # host port so that host ports overwrite each other. default_id = "#{options[:protocol]}#{options[:host]}" end options[:id] = default_id || SecureRandom.uuid end # Scope the ID by type so that different types can share IDs id = options[:id] id = "#{type}-#{id}" # Merge in the previous settings if we have them. if @__networks.has_key?(id) options = @__networks[id][1].merge(options) end # Merge in the latest settings and set the internal state @__networks[id] = [type.to_sym, options] end # Configures a provider for this VM. # # @param [Symbol] name The name of the provider. def provider(name, &block) name = name.to_sym @__providers[name] ||= [] @__provider_overrides[name] ||= [] if block_given? @__providers[name] << block if block_given? # If this block takes two arguments, then we curry it and store # the configuration override for use later. if block.arity == 2 @__provider_overrides[name] << block.curry[Vagrant::Config::V2::DummyConfig.new] end end end def provision(name, options=nil, &block) @provisioners << VagrantConfigProvisioner.new(name.to_sym, options, &block) end def defined_vms @__defined_vms end # This returns the keys of the sub-vms in the order they were # defined. def defined_vm_keys @__defined_vm_keys end def define(name, options=nil, &block) name = name.to_sym options ||= {} options = options.dup options[:config_version] ||= "2" # Add the name to the array of VM keys. This array is used to # preserve the order in which VMs are defined. @__defined_vm_keys << name if !@__defined_vm_keys.include?(name) # Add the SubVM to the hash of defined VMs if !@__defined_vms[name] @__defined_vms[name] = VagrantConfigSubVM.new end @__defined_vms[name].options.merge!(options) @__defined_vms[name].config_procs << [options[:config_version], block] if block end #------------------------------------------------------------------- # Internal methods, don't call these. #------------------------------------------------------------------- def finalize! # Defaults @boot_timeout = 300 if @boot_timeout == UNSET_VALUE @box_download_ca_cert = nil if @box_download_ca_cert == UNSET_VALUE @box_download_checksum = nil if @box_download_checksum == UNSET_VALUE @box_download_checksum_type = nil if @box_download_checksum_type == UNSET_VALUE @box_download_client_cert = nil if @box_download_client_cert == UNSET_VALUE @box_download_insecure = false if @box_download_insecure == UNSET_VALUE @box_url = nil if @box_url == UNSET_VALUE @graceful_halt_timeout = 300 if @graceful_halt_timeout == UNSET_VALUE @guest = nil if @guest == UNSET_VALUE @hostname = nil if @hostname == UNSET_VALUE @hostname = @hostname.to_s if @hostname # Make sure that the download checksum is a string and that # the type is a symbol @box_download_checksum = "" if !@box_download_checksum if @box_download_checksum_type @box_download_checksum_type = @box_download_checksum_type.to_sym end # Make sure the box URL is an array if it is set if @box_url && !@box_url.is_a?(Array) @box_url = [@box_url] end # Set the guest properly @guest = @guest.to_sym if @guest # If we haven't defined a single VM, then we need to define a # default VM which just inherits the rest of the configuration. define(DEFAULT_VM_NAME) if defined_vm_keys.empty? # Clean up some network configurations @__networks.each do |type, opts| if type == :forwarded_port opts[:guest] = opts[:guest].to_i if opts[:guest] opts[:host] = opts[:host].to_i if opts[:host] end end # Compile all the provider configurations @__providers.each do |name, blocks| # If we don't have any configuration blocks, then ignore it next if blocks.empty? # Find the configuration class for this provider config_class = Vagrant.plugin("2").manager.provider_configs[name] config_class ||= Vagrant::Config::V2::DummyConfig # Load it up config = config_class.new blocks.each do |b| b.call(config, Vagrant::Config::V2::DummyConfig.new) end config.finalize! # Store it for retrieval later @__compiled_provider_configs[name] = config end @__synced_folders.each do |id, options| if options[:nfs] options[:type] = :nfs end # Make sure the type is a symbol options[:type] = options[:type].to_sym if options[:type] # Ignore NFS on Windows if options[:type] == :nfs && Vagrant::Util::Platform.windows? options.delete(:type) end end # Flag that we finalized @__finalized = true end # This returns the compiled provider-specific configurationf or the # given provider. # # @param [Symbol] name Name of the provider. def get_provider_config(name) raise "Must finalize first." if !@__finalized result = @__compiled_provider_configs[name] # If no compiled configuration was found, then we try to just # use the default configuration from the plugin. if !result config_class = Vagrant.plugin("2").manager.provider_configs[name] if config_class result = config_class.new result.finalize! end end return result end # This returns a list of VM configurations that are overrides # for this provider. # # @param [Symbol] name Name of the provider # @return [Array<Proc>] def get_provider_overrides(name) (@__provider_overrides[name] || []).map do |p| ["2", p] end end # This returns the list of networks configured. def networks @__networks.values end # This returns the list of synced folders def synced_folders @__synced_folders end def validate(machine) errors = _detected_errors errors << I18n.t("vagrant.config.vm.box_missing") if !box errors << I18n.t("vagrant.config.vm.box_not_found", :name => box) if \ box && !box_url && !machine.box errors << I18n.t("vagrant.config.vm.hostname_invalid_characters") if \ @hostname && @hostname !~ /^[a-z0-9][-.a-z0-9]+$/i if box_download_ca_cert path = Pathname.new(box_download_ca_cert). expand_path(machine.env.root_path) if !path.file? errors << I18n.t( "vagrant.config.vm.box_download_ca_cert_not_found", path: box_download_ca_cert) end end if box_download_checksum_type if box_download_checksum == "" errors << I18n.t("vagrant.config.vm.box_download_checksum_blank") end else if box_download_checksum != "" errors << I18n.t("vagrant.config.vm.box_download_checksum_notblank") end end has_nfs = false used_guest_paths = Set.new @__synced_folders.each do |id, options| # If the shared folder is disabled then don't worry about validating it next if options[:disabled] guestpath = Pathname.new(options[:guestpath]) hostpath = Pathname.new(options[:hostpath]).expand_path(machine.env.root_path) if guestpath.relative? && guestpath.to_s !~ /^\w+:/ errors << I18n.t("vagrant.config.vm.shared_folder_guestpath_relative", :path => options[:guestpath]) else if used_guest_paths.include?(options[:guestpath]) errors << I18n.t("vagrant.config.vm.shared_folder_guestpath_duplicate", :path => options[:guestpath]) end used_guest_paths.add(options[:guestpath]) end if !hostpath.directory? && !options[:create] errors << I18n.t("vagrant.config.vm.shared_folder_hostpath_missing", :path => options[:hostpath]) end if options[:type] == :nfs has_nfs = true if options[:owner] || options[:group] # Owner/group don't work with NFS errors << I18n.t("vagrant.config.vm.shared_folder_nfs_owner_group", :path => options[:hostpath]) end end if options[:mount_options] && !options[:mount_options].is_a?(Array) errors << I18n.t("vagrant.config.vm.shared_folder_mount_options_array") end # One day remove this probably. if options[:extra] errors << "The 'extra' flag on synced folders is now 'mount_options'" end end if has_nfs errors << I18n.t("vagrant.config.vm.nfs_not_supported") if \ !machine.env.host.capability(:nfs_installed) end # Validate networks has_fp_port_error = false fp_used = Set.new valid_network_types = [:forwarded_port, :private_network, :public_network] networks.each do |type, options| if !valid_network_types.include?(type) errors << I18n.t("vagrant.config.vm.network_type_invalid", :type => type.to_s) end if type == :forwarded_port if !has_fp_port_error && (!options[:guest] || !options[:host]) errors << I18n.t("vagrant.config.vm.network_fp_requires_ports") has_fp_port_error = true end if options[:host] key = "#{options[:protocol]}#{options[:host]}" if fp_used.include?(key) errors << I18n.t("vagrant.config.vm.network_fp_host_not_unique", :host => options[:host].to_s, :protocol => options[:protocol].to_s) end fp_used.add(key) end end if type == :private_network if options[:type] != :dhcp if !options[:ip] errors << I18n.t("vagrant.config.vm.network_ip_required") end end if options[:ip] && options[:ip].end_with?(".1") errors << I18n.t("vagrant.config.vm.network_ip_ends_in_one") end end end # We're done with VM level errors so prepare the section errors = { "vm" => errors } # Validate only the _active_ provider if machine.provider_config provider_errors = machine.provider_config.validate(machine) if provider_errors errors = Vagrant::Config::V2::Util.merge_errors(errors, provider_errors) end end # Validate provisioners @provisioners.each do |vm_provisioner| if vm_provisioner.invalid? errors["vm"] << I18n.t("vagrant.config.vm.provisioner_not_found", :name => vm_provisioner.name) next end if vm_provisioner.config provisioner_errors = vm_provisioner.config.validate(machine) if provisioner_errors errors = Vagrant::Config::V2::Util.merge_errors(errors, provisioner_errors) end end end errors end end end end
35.880597
92
0.591514
7a57b2166770711dd6b58a6bc05058aacadf65c3
601
require 'ffi' module FFI module Elf class NoteHeader < FFI::Struct # Known names of notes NOTES = { :solaris => "SUNW Solaris", :gnu => "GNU" } # Value of descriptor (one word) is desired pagesize for the binary. PAGESIZE_HINT = 1 GNU_ABI_TAG = 1 # Known OSes. These values can appear in word 0 of an # NT_GNU_ABI_TAG note section entry. OSES = [ OS_LINUX = 0, OS_GNU = 1, OS_SOLARIS2 = 2, OS_FREEBSD = 3 ] GNU_HWCAP = 2 GNU_BUILD_ID = 3 end end end
17.676471
74
0.535774
1ac55e2e7b8f8da0f22a5c87d7f4fe882358e559
3,669
# frozen_string_literal: true Synvert::Rewriter.new 'rails', 'strong_parameters' do default_columns = %w[id created_at updated_at deleted_at] description <<~EOS It uses string_parameters to replace `attr_accessible`. 1. it removes active_record configurations. ```ruby config.active_record.whitelist_attributes = ... config.active_record.mass_assignment_sanitizer = ... ``` 2. it removes `attr_accessible` and `attr_protected` code in models. 3. it adds xxx_params in controllers ```ruby def xxx_params params.require(:xxx).permit(...) end ``` 4. it replaces params[:xxx] with xxx_params. ```ruby params[:xxx] => xxx_params ``` EOS if_gem 'rails', '>= 4.0' within_files 'config/**/*.rb' do # remove config.active_record.whitelist_attributes = ... with_node type: 'send', receiver: { type: 'send', receiver: { type: 'send', message: 'config' }, message: 'active_record' }, message: 'whitelist_attributes=' do remove end # remove config.active_record.mass_assignment_sanitizer = ... with_node type: 'send', receiver: { type: 'send', receiver: { type: 'send', message: 'config' }, message: 'active_record' }, message: 'mass_assignment_sanitizer=' do remove end end attributes = {} within_file 'db/schema.rb' do within_node type: 'block', caller: { type: 'send', message: 'create_table' } do object_name = node.caller.arguments.first.to_value.singularize attributes[object_name] = [] with_node type: 'send', receiver: 't', message: { not: 'index' } do attribute_name = node.arguments.first.to_value unless default_columns.include?(attribute_name) attributes[object_name] << ":#{attribute_name}" end end end end parameters = {} within_files 'app/models/**/*.rb' do within_node type: 'class' do object_name = node.name.to_source.underscore # assign and remove attr_accessible ... with_node type: 'send', message: 'attr_accessible' do parameters[object_name] = node.arguments.map(&:to_source) remove end # assign and remove attr_protected ... with_node type: 'send', message: 'attr_protected' do parameters[object_name] = attributes[object_name] - node.arguments.map(&:to_source) remove end end end within_file 'app/controllers/**/*.rb' do within_node type: 'class' do object_name = node.name.to_source.sub('Controller', '').singularize.underscore if_exist_node type: 'send', receiver: 'params', message: '[]', arguments: [object_name.to_sym] do if parameters[object_name] # append def xxx_params; ...; end permit_params = parameters[object_name].join(', ') unless_exist_node type: 'def', name: "#{object_name}_params" do append <<~EOS def #{object_name}_params params.require(:#{object_name}).permit(#{permit_params}) end EOS end # params[:xxx] => xxx_params with_node type: 'send', receiver: 'params', message: '[]' do object_name = node.arguments.first.to_value.to_s if parameters[object_name] replace_with "#{object_name}_params" end end end end end end end
29.352
103
0.583538
edff1d73687d37cd994d8469469fa39a3a99e3d1
710
cask :v1 => '1password-beta' do version '5.3.BETA-7' sha256 '9a640b58b0f929a1d4f5c34a4cb25d883b383b510a355479dd5df02e839c809d' url "https://cache.agilebits.com/dist/1P/mac4/1Password-#{version}.zip" name '1Password' homepage 'https://agilebits.com/onepassword/mac' license :commercial app '1Password 5.app' zap :delete => [ '~/Library/Application Scripts/2BUA8C4S2C.com.agilebits.onepassword-osx-helper', '~/Library/Containers/2BUA8C4S2C.com.agilebits.onepassword-osx-helper', '~/Library/Containers/com.agilebits.onepassword-osx', '~/Library/Group Containers/2BUA8C4S2C.com.agilebits', ] end
37.368421
100
0.660563
b9df2525752e0bf1b9c29d503c7e242767713ce0
999
# frozen_string_literal: true require_relative 'services/fetch_images' module JobBoard class ImageSearcher def search(request_body) JobBoard.logger.debug( 'handling request', request_body: request_body.inspect ) request_body.split(/\n|\r\n/).each do |line| images, params, limit = fetch_images_for_line(line) return [images, params, limit] unless images.empty? end [[], '', 1] end private def fetch_images_for_line(line) params = JobBoard::ImageParams.parse(line) return [[], 1] if missing_infra?(params) [fetch_images(params), params, params['limit']] end private def missing_infra?(params) params['infra'].nil? || params['infra'].empty? end private def fetch_images(params) images = JobBoard::Services::FetchImages.run(query: params) JobBoard.logger.debug( 'found', images: images.inspect, params: params.inspect ) images end end end
23.785714
65
0.647648
182945a502ec6c349b87dfb0dd4ac34e34c3fc3f
466
require 'test_helper' describe DragonflyFonts::Processors::CorrectMetrics do let(:app) { test_app.configure_with(:fonts) } let(:content) { app.fetch_file SAMPLES_DIR.join('sample.otf') } # TODO: figure out how to test # it { content.correct_metrics.font_info.must_equal '…' } # it { content.correct_metrics.font_info.must_equal '…' } describe 'tempfile has extension' do it { content.correct_metrics.tempfile.path.must_match /\.otf\z/ } end end
31.066667
69
0.729614
accb929394c65198a16b51f0844122c5ff33649d
475
cask 'audiobookbinder' do version '2.1' sha256 'ed0e722cbbbcad8ea305faa10e1f5f08c7719991118d015af132bb9d41f84170' url "https://bluezbox.com/audiobookbinder/AudiobookBinder-#{version}.dmg" appcast 'https://bluezbox.com/audiobookbinder/appcast.xml', checkpoint: '5513a6cc78863fd79e2779794a0767d241a066e1b4bd5cce19ecf5daa34c2306' name 'Audiobook Binder' homepage 'https://bluezbox.com/audiobookbinder.html' license :oss app 'AudioBookBinder.app' end
33.928571
88
0.793684
33f9a311bd35f2549c7afd9870b2eeaffcdfba38
198
class RemoveLocationColumnFromUsers < ActiveRecord::Migration def up remove_column :users, :location end def down add_column :useres, :location, :string, after: :avatar_url end end
19.8
62
0.742424
61bee4b4039e22ebe0b9afede8652db596c1fbd1
2,040
# coding: utf-8 Pod::Spec.new do |s| # MARK: - Description s.name = 'SwiftCommonsLang' s.summary = 'A collection of useful classes and Swift language extensions.' s.version = '1.4.0' s.platform = :ios s.ios.deployment_target = '9.0' s.swift_version = '4.2' s.cocoapods_version = '>= 1.7.5' s.static_framework = true s.homepage = 'https://github.com/roxiemobile/swift-commons.ios' s.authors = { 'Roxie Mobile Ltd.' => '[email protected]', 'Alexander Bragin' => '[email protected]' } s.license = 'BSD-4-Clause' # MARK: - Configuration s.source = { git: 'https://github.com/roxiemobile/swift-commons.ios.git', tag: s.version.to_s } base_dir = 'Modules/RoxieMobile.SwiftCommons/Sources/Lang/' s.source_files = base_dir + '{Sources,Dependencies}/**/*.swift' s.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => "$(inherited) SWIFTCOMMONS_FRAMEWORK_VERSION=@\\\"#{s.version}\\\"" } # MARK: - iOS Static Framework s.module_name = s.name s.name = "#{s.name}-SCF42" s.default_subspec = 'StaticCocoaFramework' s.source = { http: "https://dl.bintray.com/roxiemobile/generic/SwiftCommonsLang-#{s.version}-SCF42.zip", sha256: 'b363adf06e90f3e31017b212334ee1446ea5c9cd2806f85b78dedcb129949673' } s.source_files = nil s.subspec 'StaticCocoaFramework' do |sc| sc.preserve_paths = 'SwiftCommonsLang.framework/*' sc.source_files = 'SwiftCommonsLang.framework/Headers/*.h' sc.public_header_files = 'SwiftCommonsLang.framework/Headers/*.h' sc.vendored_frameworks = 'SwiftCommonsLang.framework' end # MARK: - Validation # Technical Q&A QA1881 v2 - Embedding Content with Swift in Objective-C # @link https://pewpewthespells.com/blog/swift_and_objc.html s.user_target_xcconfig = { 'SWIFT_STDLIB_PATH' => '${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}', 'OTHER_LDFLAGS' => '-L${SWIFT_STDLIB_PATH}' } end
31.384615
129
0.661765
3991a9116e9c78112440a247040eb7e334aff15e
569
#!/usr/bin/env ruby dir = File.dirname(File.expand_path(__FILE__)) $LOAD_PATH.unshift dir + "/../lib" require "unimidi" # Prompts the user to select a midi output # Sends some arpeggiated chords to the output notes = [36, 40, 43] # C E G octaves = 5 duration = 0.1 # Prompt the user to select an output output = UniMIDI::Output.gets # using their selection... (0..((octaves-1)*12)).step(12) do |oct| notes.each do |note| output.puts(0x90, note + oct, 100) # note on sleep(duration) # wait output.puts(0x80, note + oct, 100) # note off end end
18.966667
49
0.667838
01230baab36402dd00a5e5591ced83b05a2f6f05
1,448
class TreatiesController < ApplicationController # Controller rendering treaties index and show pages before_action :build_request ROUTE_MAP = { index: proc { ParliamentHelper.parliament_request.treaty_index }, show: proc { |params| ParliamentHelper.parliament_request.treaty_by_id.set_url_params({ treaty_id: params[:treaty_id] }) }, lookup: proc { |params| ParliamentHelper.parliament_request.treaty_lookup.set_url_params({ property: params[:source], value: params[:id] }) } }.freeze def index @treaties = FilterHelper.filter(@api_request, 'Treaty') list_components = LaidThingListComponentsFactory.sort_and_build_components(statutory_instruments: @treaties) heading = ComponentSerializer::Heading1ComponentSerializer.new(heading: I18n.t('treaties.index.title')) serializer = PageSerializer::ListPageSerializer.new(request: request, heading_component: heading, list_components: list_components, data_alternates: @alternates) render_page(serializer) end def show @treaty = FilterHelper.filter(@api_request, 'Treaty') @treaty = @treaty.first serializer = PageSerializer::TreatiesShowPageSerializer.new(request: request, treaty: @treaty, data_alternates: @alternates) render_page(serializer) end def lookup @treaty = FilterHelper.filter(@api_request, 'Treaty') @treaty = @treaty.first redirect_to :action => 'show', 'treaty_id' => @treaty.graph_id end end
38.105263
165
0.759669
1a72846f1ac18d6715746d07faea762b40580eb3
1,372
Pod::Spec.new do |s| s.name = "secp256k1-gm" s.version = "0.0.3" s.summary = "Optimized C library for EC operations on curve secp256k1" s.homepage = "https://github.com/greymass/secp256k1" s.license = { :type => "MIT", :file => "COPYING" } s.author = { "secp256k1 contributors" => "https://github.com/bitcoin-core/secp256k1/graphs/contributors" } s.source = { :git => "https://github.com/greymass/secp256k1.git", :tag => "0.0.3" } s.ios.deployment_target = "12.0" s.public_header_files = "include/*.h" s.module_name = "secp256k1" s.source_files = "src/secp256k1.c", "src/**/*.h", "include/*.h" s.compiler_flags = "-DENABLE_MODULE_ECDH", "-DENABLE_MODULE_RECOVERY", "-DUSE_NUM_NONE", "-DUSE_FIELD_INV_BUILTIN", "-DUSE_SCALAR_INV_BUILTIN", "-DUSE_FIELD_10X26", "-DUSE_SCALAR_8X32", "-DECMULT_GEN_PREC_BITS=4", "-DECMULT_WINDOW_SIZE=15" s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SRCROOT)/secp256k1-gm $(SRCROOT)/secp256k1-gm/src $(SRCROOT)/secp256k1-gm/include", "OTHER_CFLAGS" => "-pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-shorten-64-to-32 -Wno-conditional-uninitialized -Wno-unused-function -Wno-long-long -Wno-overlength-strings -O3" } end
50.814815
223
0.626093
39aaeb9303d38123286948571789ce52a614d55c
3,963
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Automation::Mgmt::V2015_10_31 module Models # # Definition of the connection. # class Connection < ProxyResource include MsRestAzure # @return [ConnectionTypeAssociationProperty] Gets or sets the # connectionType of the connection. attr_accessor :connection_type # @return [Hash{String => String}] Gets the field definition values of # the connection. attr_accessor :field_definition_values # @return [DateTime] Gets the creation time. attr_accessor :creation_time # @return [DateTime] Gets the last modified time. attr_accessor :last_modified_time # @return [String] Gets or sets the description. attr_accessor :description # # Mapper for Connection class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Connection', type: { name: 'Composite', class_name: 'Connection', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, connection_type: { client_side_validation: true, required: false, serialized_name: 'properties.connectionType', type: { name: 'Composite', class_name: 'ConnectionTypeAssociationProperty' } }, field_definition_values: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.fieldDefinitionValues', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, creation_time: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.creationTime', type: { name: 'DateTime' } }, last_modified_time: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.lastModifiedTime', type: { name: 'DateTime' } }, description: { client_side_validation: true, required: false, serialized_name: 'properties.description', type: { name: 'String' } } } } } end end end end
30.022727
76
0.467323
0148e0c79ec0f9521cb72eb49c181ea2d86b5c98
4,004
class RegistrationsController < Devise::RegistrationsController after_action :add_account, only: [:create] after_action :attach_avatar, only: [:update] before_action :set_navbar_actions, only: [:edit, :preferences, :more_actions] before_action :set_navbar_color, only: [:edit, :preferences, :more_actions] def new super if params[:referral] session[:referral] = params[:referral] end end def edit @sidenav_expansion = 'my account' @page_title = "My settings" end def preferences @sidenav_expansion = 'my account' @page_title = "My preferences" end def more_actions @sidenav_expansion = 'my account' @page_title = "More settings" end private def sign_up_params params.require(:user).permit(:name, :email, :password, :password_confirmation, :email_updates) end def account_update_params params.require(:user).permit( :name, :email, :username, :password, :password_confirmation, :email_updates, :fluid_preference, :bio, :favorite_genre, :favorite_author, :interests, :age, :location, :gender, :forums_badge_text, :keyboard_shortcuts_preference, :avatar, :favorite_book, :website, :inspirations, :other_names, :favorite_quote, :occupation, :favorite_page_type, :dark_mode_enabled, :notification_updates, :community_features_enabled, :private_profile ) end def update_resource(resource, params) resource.update_without_password(params) end def after_update_path_for(resource) request.referrer || edit_user_registration_path(resource) end def set_navbar_color @navbar_color = '#000000' end def set_navbar_actions @navbar_actions = [{ label: "About you", href: edit_user_registration_path }, { label: "Preferences", href: user_preferences_path(current_user) }, { label: "More...", href: user_more_actions_path(current_user) }] end protected def add_account # Tie any universe contributor invites with this email to this user if resource.persisted? potential_contributor_records = Contributor.where(email: resource.email.downcase, user_id: nil) if potential_contributor_records.any? potential_contributor_records.update_all(user_id: resource.id) # Create a notification letting the user know about each collaboration! potential_contributor_records.each do |contributorship| resource.notifications.create( message_html: "<div>You have been added as a contributor to the <span class='#{Universe.color}-text'>#{contributorship.universe.name}</span> universe.</div>", icon: Universe.icon, icon_color: Universe.color, happened_at: DateTime.current, passthrough_link: Rails.application.routes.url_helpers.universe_path(contributorship.universe) ) end end end # If the user was created in the last 60 seconds, report it to Slack if resource.persisted? if params[:user].key? :referral_code referral_code = ReferralCode.where(code: params[:user][:referral_code]).first Referral.create( referrer_id: referral_code.user.id, referred_id: resource.id, associated_code_id: referral_code.id ) if referral_code.present? end end end def attach_avatar return unless account_update_params.key?('avatar') current_user.avatar.purge current_user.avatar.attach(account_update_params.fetch('avatar', nil)) end def report_new_account_to_slack resource return unless Rails.env == 'production' slack_hook = ENV['SLACK_HOOK'] return unless slack_hook notifier = Slack::Notifier.new slack_hook, channel: '#analytics', username: 'tristan' notifier.ping "User signed up! :tada: Author #{resource.name} (#{resource.email.split('@').first}@...) :tada: Total authors now: #{User.count} :tada:" end end
30.8
174
0.692807
2184d7fcc8cc80e958eb7571911a22e13420f6fc
665
cask 'visual-paradigm-ce' do version '16.1,20200601' sha256 'cdf2ba06bb9321e8836bb5a037ea9475293432fc9ef619bd396548ec25653b8b' url "https://www.visual-paradigm.com/downloads/vpce/Visual_Paradigm_CE_#{version.before_comma.dots_to_underscores}_#{version.after_comma}_OSX_WithJRE.dmg" appcast 'https://www.visual-paradigm.com/downloads/vpce/checksum.html', configuration: "#{version.before_comma.dots_to_underscores}_#{version.after_comma}" name 'Visual Paradigm Community Edition' homepage 'https://www.visual-paradigm.com/' # Renamed to avoid conflict with visual-paradigm. app 'Visual Paradigm.app', target: 'Visual Paradigm CE.app' end
47.5
156
0.78797
5d15831315f0da15373bad7fb0f04e0a058005a6
182
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'runt' require 'date' require 'time' require 'rubygems' # Needed for minitest on 1.8.7 require 'minitest/autorun'
22.75
58
0.736264
e96af45dc115a7c9d81757f42cd05ff4864205d0
618
# frozen_string_literal: true require "openapi3_parser/node_factory/object" module Openapi3Parser module NodeFactory class Server < NodeFactory::Object allow_extensions field "url", input_type: String, required: true field "description", input_type: String field "variables", factory: :variables_factory private def build_object(data, context) Node::Server.new(data, context) end def variables_factory(context) NodeFactory::Map.new( context, value_factory: NodeFactory::ServerVariable ) end end end end
22.071429
53
0.668285
032c49ed1590fa46950cf8b51a9f417aeb6232c4
685
module Gitlab module QuickActions class SubstitutionDefinition < CommandDefinition # noop?=>true means these won't get extracted or removed by Gitlab::QuickActions::Extractor#extract_commands # QuickActions::InterpretService#perform_substitutions handles them separately def noop? true end def match(content) content.match %r{^/#{all_names.join('|')} ?(.*)$} end def perform_substitution(context, content) return unless content all_names.each do |a_name| content.gsub!(%r{/#{a_name} ?(.*)$}, execute_block(action_block, context, '\1')) end content end end end end
27.4
114
0.642336
622729e3274b01c07134477afad8e4adaa02e8fd
771
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "catcontacts/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "catcontacts" s.version = Catcontacts::VERSION s.authors = ["Jeff Shumate"] s.email = ["[email protected]"] s.homepage = "http://example.com" s.summary = "Summary of Catcontacts." s.description = "Description of Catcontacts." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.2.6" s.add_dependency "geocoder", "~> 1.3.4" s.add_dependency "smarter_csv", "~> 1.1.0" s.add_dependency "phonelib" end
29.653846
85
0.638132
01fc0a3cf0e8ad4fb6dab16e96c15656612d8294
1,567
# Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_view.cache_template_loading = true # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql config.gem 'thoughtbot-shoulda', :lib => 'shoulda', :source => 'http://gems.github.com' config.gem 'thoughtbot-factory_girl', :lib => 'factory_girl', :source => 'http://gems.github.com' config.action_mailer.default_url_options = { :host => 'localhost' }
47.484848
97
0.777281
1a75f93094b47b2648e2717d46b7411e9281a7c4
102
require 'shared_user' class User include Mongoid::Document include Shim include SharedUser end
12.75
27
0.784314
bbe02ee7162be35ff2491dd77502559ed06e6b28
453
module TPPlus module Nodes class RealNode < BaseNode def initialize(value) @value = value end def requires_mixed_logic?(context) false end def eval(context,options={}) val = if options[:as_string] ("%.2f" % @value).sub(/^0/,'') else @value end if @value < 0 "(#{val})" else val end end end end end
16.178571
40
0.465784
4af30ea13f1bee28616a4a980f6f4955622dae1b
39,575
require 'active_resource/connection' require 'cgi' require 'set' module ActiveResource # ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application. # # For an outline of what Active Resource is capable of, see link:files/vendor/rails/activeresource/README.html. # # == Automated mapping # # Active Resource objects represent your RESTful resources as manipulatable Ruby objects. To map resources # to Ruby objects, Active Resource only needs a class name that corresponds to the resource name (e.g., the class # Person maps to the resources people, very similarly to Active Record) and a +site+ value, which holds the # URI of the resources. # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # end # # Now the Person class is mapped to RESTful resources located at <tt>http://api.people.com:3000/people/</tt>, and # you can now use Active Resource's lifecycles methods to manipulate resources. In the case where you already have # an existing model with the same name as the desired RESTful resource you can set the +element_name+ value. # # class PersonResource < ActiveResource::Base # self.site = "http://api.people.com:3000/" # self.element_name = "person" # end # # # == Lifecycle methods # # Active Resource exposes methods for creating, finding, updating, and deleting resources # from REST web services. # # ryan = Person.new(:first => 'Ryan', :last => 'Daigle') # ryan.save # => true # ryan.id # => 2 # Person.exists?(ryan.id) # => true # ryan.exists? # => true # # ryan = Person.find(1) # # Resource holding our newly created Person object # # ryan.first = 'Rizzle' # ryan.save # => true # # ryan.destroy # => true # # As you can see, these are very similar to Active Record's lifecycle methods for database records. # You can read more about each of these methods in their respective documentation. # # === Custom REST methods # # Since simple CRUD/lifecycle methods can't accomplish every task, Active Resource also supports # defining your own custom REST methods. To invoke them, Active Resource provides the <tt>get</tt>, # <tt>post</tt>, <tt>put</tt> and <tt>delete</tt> methods where you can specify a custom REST method # name to invoke. # # # POST to the custom 'register' REST method, i.e. POST /people/new/register.xml. # Person.new(:name => 'Ryan').post(:register) # # => { :id => 1, :name => 'Ryan', :position => 'Clerk' } # # # PUT an update by invoking the 'promote' REST method, i.e. PUT /people/1/promote.xml?position=Manager. # Person.find(1).put(:promote, :position => 'Manager') # # => { :id => 1, :name => 'Ryan', :position => 'Manager' } # # # GET all the positions available, i.e. GET /people/positions.xml. # Person.get(:positions) # # => [{:name => 'Manager'}, {:name => 'Clerk'}] # # # DELETE to 'fire' a person, i.e. DELETE /people/1/fire.xml. # Person.find(1).delete(:fire) # # For more information on using custom REST methods, see the # ActiveResource::CustomMethods documentation. # # == Validations # # You can validate resources client side by overriding validation methods in the base class. # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # protected # def validate # errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/ # end # end # # See the ActiveResource::Validations documentation for more information. # # == Authentication # # Many REST APIs will require authentication, usually in the form of basic # HTTP authentication. Authentication can be specified by: # * putting the credentials in the URL for the +site+ variable. # # class Person < ActiveResource::Base # self.site = "http://ryan:[email protected]:3000/" # end # # * defining +user+ and/or +password+ variables # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # self.user = "ryan" # self.password = "password" # end # # For obvious security reasons, it is probably best if such services are available # over HTTPS. # # Note: Some values cannot be provided in the URL passed to site. e.g. email addresses # as usernames. In those situations you should use the separate user and password option. # == Errors & Validation # # Error handling and validation is handled in much the same manner as you're used to seeing in # Active Record. Both the response code in the HTTP response and the body of the response are used to # indicate that an error occurred. # # === Resource errors # # When a GET is requested for a resource that does not exist, the HTTP <tt>404</tt> (Resource Not Found) # response code will be returned from the server which will raise an ActiveResource::ResourceNotFound # exception. # # # GET http://api.people.com:3000/people/999.xml # ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound # # <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The # following HTTP response codes will also result in these exceptions: # # * 200..399 - Valid response, no exception # * 404 - ActiveResource::ResourceNotFound # * 409 - ActiveResource::ResourceConflict # * 422 - ActiveResource::ResourceInvalid (rescued by save as validation errors) # * 401..499 - ActiveResource::ClientError # * 500..599 - ActiveResource::ServerError # # These custom exceptions allow you to deal with resource errors more naturally and with more precision # rather than returning a general HTTP error. For example: # # begin # ryan = Person.find(my_id) # rescue ActiveResource::ResourceNotFound # redirect_to :action => 'not_found' # rescue ActiveResource::ResourceConflict, ActiveResource::ResourceInvalid # redirect_to :action => 'new' # end # # === Validation errors # # Active Resource supports validations on resources and will return errors if any these validations fail # (e.g., "First name can not be blank" and so on). These types of errors are denoted in the response by # a response code of <tt>422</tt> and an XML representation of the validation errors. The save operation will # then fail (with a <tt>false</tt> return value) and the validation errors can be accessed on the resource in question. # # ryan = Person.find(1) # ryan.first # => '' # ryan.save # => false # # # When # # PUT http://api.people.com:3000/people/1.xml # # is requested with invalid values, the response is: # # # # Response (422): # # <errors type="array"><error>First cannot be empty</error></errors> # # # # ryan.errors.invalid?(:first) # => true # ryan.errors.full_messages # => ['First cannot be empty'] # # Learn more about Active Resource's validation features in the ActiveResource::Validations documentation. # # === Timeouts # # Active Resource relies on HTTP to access RESTful APIs and as such is inherently susceptible to slow or # unresponsive servers. In such cases, your Active Resource method calls could timeout. You can control the # amount of time before Active Resource times out with the +timeout+ variable. # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # self.timeout = 5 # end # # This sets the +timeout+ to 5 seconds. You can adjust the +timeout+ to a value suitable for the RESTful API # you are accessing. It is recommended to set this to a reasonably low value to allow your Active Resource # clients (especially if you are using Active Resource in a Rails application) to fail-fast (see # http://en.wikipedia.org/wiki/Fail-fast) rather than cause cascading failures that could incapacitate your # server. # # When a timeout occurs, an ActiveResource::TimeoutError is raised. You should rescue from # ActiveResource::TimeoutError in your Active Resource method calls. # # Internally, Active Resource relies on Ruby's Net::HTTP library to make HTTP requests. Setting +timeout+ # sets the <tt>read_timeout</tt> of the internal Net::HTTP instance to the same value. The default # <tt>read_timeout</tt> is 60 seconds on most Ruby implementations. class Base # The logger for diagnosing and tracing Active Resource calls. cattr_accessor :logger class << self # Gets the URI of the REST resources to map for this class. The site variable is required for # Active Resource's mapping to work. def site # Not using superclass_delegating_reader because don't want subclasses to modify superclass instance # # With superclass_delegating_reader # # Parent.site = 'http://[email protected]' # Subclass.site # => 'http://[email protected]' # Subclass.site.user = 'david' # Parent.site # => 'http://[email protected]' # # Without superclass_delegating_reader (expected behaviour) # # Parent.site = 'http://[email protected]' # Subclass.site # => 'http://[email protected]' # Subclass.site.user = 'david' # => TypeError: can't modify frozen object # if defined?(@site) @site elsif superclass != Object && superclass.site superclass.site.dup.freeze end end # Sets the URI of the REST resources to map for this class to the value in the +site+ argument. # The site variable is required for Active Resource's mapping to work. def site=(site) @connection = nil if site.nil? @site = nil else @site = create_site_uri_from(site) @user = URI.decode(@site.user) if @site.user @password = URI.decode(@site.password) if @site.password end end # Gets the user for REST HTTP authentication. def user # Not using superclass_delegating_reader. See +site+ for explanation if defined?(@user) @user elsif superclass != Object && superclass.user superclass.user.dup.freeze end end # Sets the user for REST HTTP authentication. def user=(user) @connection = nil @user = user end # Gets the password for REST HTTP authentication. def password # Not using superclass_delegating_reader. See +site+ for explanation if defined?(@password) @password elsif superclass != Object && superclass.password superclass.password.dup.freeze end end # Sets the password for REST HTTP authentication. def password=(password) @connection = nil @password = password end # Sets the format that attributes are sent and received in from a mime type reference: # # Person.format = :json # Person.find(1) # => GET /people/1.json # # Person.format = ActiveResource::Formats::XmlFormat # Person.find(1) # => GET /people/1.xml # # Default format is <tt>:xml</tt>. def format=(mime_type_reference_or_format) format = mime_type_reference_or_format.is_a?(Symbol) ? ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format write_inheritable_attribute("format", format) connection.format = format if site end # Returns the current format, default is ActiveResource::Formats::XmlFormat. def format read_inheritable_attribute("format") || ActiveResource::Formats[:xml] end # Sets the number of seconds after which requests to the REST API should time out. def timeout=(timeout) @connection = nil @timeout = timeout end # Gets the number of seconds after which requests to the REST API should time out. def timeout if defined?(@timeout) @timeout elsif superclass != Object && superclass.timeout superclass.timeout end end # An instance of ActiveResource::Connection that is the base connection to the remote service. # The +refresh+ parameter toggles whether or not the connection is refreshed at every request # or not (defaults to <tt>false</tt>). def connection(refresh = false) if defined?(@connection) || superclass == Object @connection = Connection.new(site, format) if refresh || @connection.nil? @connection.user = user if user @connection.password = password if password @connection.timeout = timeout if timeout @connection else superclass.connection end end def headers @headers ||= {} end # Do not include any modules in the default element name. This makes it easier to seclude ARes objects # in a separate namespace without having to set element_name repeatedly. attr_accessor_with_default(:element_name) { to_s.split("::").last.underscore } #:nodoc: attr_accessor_with_default(:collection_name) { element_name.pluralize } #:nodoc: attr_accessor_with_default(:primary_key, 'id') #:nodoc: # Gets the prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>) # This method is regenerated at runtime based on what the prefix is set to. def prefix(options={}) default = site.path default << '/' unless default[-1..-1] == '/' # generate the actual method based on the current site path self.prefix = default prefix(options) end # An attribute reader for the source string for the resource path prefix. This # method is regenerated at runtime based on what the prefix is set to. def prefix_source prefix # generate #prefix and #prefix_source methods first prefix_source end # Sets the prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>). # Default value is <tt>site.path</tt>. def prefix=(value = '/') # Replace :placeholders with '#{embedded options[:lookups]}' prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" } # Clear prefix parameters in case they have been cached @prefix_parameters = nil # Redefine the new methods. code = <<-end_code def prefix_source() "#{value}" end def prefix(options={}) "#{prefix_call}" end end_code silence_warnings { instance_eval code, __FILE__, __LINE__ } rescue logger.error "Couldn't set prefix: #{$!}\n #{code}" raise end alias_method :set_prefix, :prefix= #:nodoc: alias_method :set_element_name, :element_name= #:nodoc: alias_method :set_collection_name, :collection_name= #:nodoc: # Gets the element path for the given ID in +id+. If the +query_options+ parameter is omitted, Rails # will split from the prefix options. # # ==== Options # +prefix_options+ - A hash to add a prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt> # would yield a URL like <tt>/accounts/19/purchases.xml</tt>). # +query_options+ - A hash to add items to the query string for the request. # # ==== Examples # Post.element_path(1) # # => /posts/1.xml # # Comment.element_path(1, :post_id => 5) # # => /posts/5/comments/1.xml # # Comment.element_path(1, :post_id => 5, :active => 1) # # => /posts/5/comments/1.xml?active=1 # # Comment.element_path(1, {:post_id => 5}, {:active => 1}) # # => /posts/5/comments/1.xml?active=1 # def element_path(id, prefix_options = {}, query_options = nil) prefix_options, query_options = split_options(prefix_options) if query_options.nil? "#{prefix(prefix_options)}#{collection_name}/#{id}.#{format.extension}#{query_string(query_options)}" end # Gets the collection path for the REST resources. If the +query_options+ parameter is omitted, Rails # will split from the +prefix_options+. # # ==== Options # * +prefix_options+ - A hash to add a prefix to the request for nested URL's (e.g., <tt>:account_id => 19</tt> # would yield a URL like <tt>/accounts/19/purchases.xml</tt>). # * +query_options+ - A hash to add items to the query string for the request. # # ==== Examples # Post.collection_path # # => /posts.xml # # Comment.collection_path(:post_id => 5) # # => /posts/5/comments.xml # # Comment.collection_path(:post_id => 5, :active => 1) # # => /posts/5/comments.xml?active=1 # # Comment.collection_path({:post_id => 5}, {:active => 1}) # # => /posts/5/comments.xml?active=1 # def collection_path(prefix_options = {}, query_options = nil) prefix_options, query_options = split_options(prefix_options) if query_options.nil? "#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}" end alias_method :set_primary_key, :primary_key= #:nodoc: # Creates a new resource instance and makes a request to the remote service # that it be saved, making it equivalent to the following simultaneous calls: # # ryan = Person.new(:first => 'ryan') # ryan.save # # Returns the newly created resource. If a failure has occurred an # exception will be raised (see <tt>save</tt>). If the resource is invalid and # has not been saved then <tt>valid?</tt> will return <tt>false</tt>, # while <tt>new?</tt> will still return <tt>true</tt>. # # ==== Examples # Person.create(:name => 'Jeremy', :email => '[email protected]', :enabled => true) # my_person = Person.find(:first) # my_person.email # => [email protected] # # dhh = Person.create(:name => 'David', :email => '[email protected]', :enabled => true) # dhh.valid? # => true # dhh.new? # => false # # # We'll assume that there's a validation that requires the name attribute # that_guy = Person.create(:name => '', :email => '[email protected]', :enabled => true) # that_guy.valid? # => false # that_guy.new? # => true def create(attributes = {}) returning(self.new(attributes)) { |res| res.save } end # Core method for finding resources. Used similarly to Active Record's +find+ method. # # ==== Arguments # The first argument is considered to be the scope of the query. That is, how many # resources are returned from the request. It can be one of the following. # # * <tt>:one</tt> - Returns a single resource. # * <tt>:first</tt> - Returns the first resource found. # * <tt>:last</tt> - Returns the last resource found. # * <tt>:all</tt> - Returns every resource that matches the request. # # ==== Options # # * <tt>:from</tt> - Sets the path or custom method that resources will be fetched from. # * <tt>:params</tt> - Sets query and prefix (nested URL) parameters. # # ==== Examples # Person.find(1) # # => GET /people/1.xml # # Person.find(:all) # # => GET /people.xml # # Person.find(:all, :params => { :title => "CEO" }) # # => GET /people.xml?title=CEO # # Person.find(:first, :from => :managers) # # => GET /people/managers.xml # # Person.find(:last, :from => :managers) # # => GET /people/managers.xml # # Person.find(:all, :from => "/companies/1/people.xml") # # => GET /companies/1/people.xml # # Person.find(:one, :from => :leader) # # => GET /people/leader.xml # # Person.find(:all, :from => :developers, :params => { :language => 'ruby' }) # # => GET /people/developers.xml?language=ruby # # Person.find(:one, :from => "/companies/1/manager.xml") # # => GET /companies/1/manager.xml # # StreetAddress.find(1, :params => { :person_id => 1 }) # # => GET /people/1/street_addresses/1.xml def find(*arguments) scope = arguments.slice!(0) options = arguments.slice!(0) || {} case scope when :all then find_every(options) when :first then find_every(options).first when :last then find_every(options).last when :one then find_one(options) else find_single(scope, options) end end # Deletes the resources with the ID in the +id+ parameter. # # ==== Options # All options specify prefix and query parameters. # # ==== Examples # Event.delete(2) # sends DELETE /events/2 # # Event.create(:name => 'Free Concert', :location => 'Community Center') # my_event = Event.find(:first) # let's assume this is event with ID 7 # Event.delete(my_event.id) # sends DELETE /events/7 # # # Let's assume a request to events/5/cancel.xml # Event.delete(params[:id]) # sends DELETE /events/5 def delete(id, options = {}) connection.delete(element_path(id, options)) end # Asserts the existence of a resource, returning <tt>true</tt> if the resource is found. # # ==== Examples # Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...') # Note.exists?(1) # => true # # Note.exists(1349) # => false def exists?(id, options = {}) if id prefix_options, query_options = split_options(options[:params]) path = element_path(id, prefix_options, query_options) response = connection.head(path, headers) response.code.to_i == 200 end # id && !find_single(id, options).nil? rescue ActiveResource::ResourceNotFound false end private # Find every resource def find_every(options) case from = options[:from] when Symbol instantiate_collection(get(from, options[:params])) when String path = "#{from}#{query_string(options[:params])}" instantiate_collection(connection.get(path, headers) || []) else prefix_options, query_options = split_options(options[:params]) path = collection_path(prefix_options, query_options) instantiate_collection( (connection.get(path, headers) || []), prefix_options ) end end # Find a single resource from a one-off URL def find_one(options) case from = options[:from] when Symbol instantiate_record(get(from, options[:params])) when String path = "#{from}#{query_string(options[:params])}" instantiate_record(connection.get(path, headers)) end end # Find a single resource from the default URL def find_single(scope, options) prefix_options, query_options = split_options(options[:params]) path = element_path(scope, prefix_options, query_options) instantiate_record(connection.get(path, headers), prefix_options) end def instantiate_collection(collection, prefix_options = {}) collection.collect! { |record| instantiate_record(record, prefix_options) } end def instantiate_record(record, prefix_options = {}) returning new(record) do |resource| resource.prefix_options = prefix_options end end # Accepts a URI and creates the site URI from that. def create_site_uri_from(site) site.is_a?(URI) ? site.dup : URI.parse(site) end # contains a set of the current prefix parameters. def prefix_parameters @prefix_parameters ||= prefix_source.scan(/:\w+/).map { |key| key[1..-1].to_sym }.to_set end # Builds the query string for the request. def query_string(options) "?#{options.to_query}" unless options.nil? || options.empty? end # split an option hash into two hashes, one containing the prefix options, # and the other containing the leftovers. def split_options(options = {}) prefix_options, query_options = {}, {} (options || {}).each do |key, value| next if key.blank? (prefix_parameters.include?(key.to_sym) ? prefix_options : query_options)[key.to_sym] = value end [ prefix_options, query_options ] end end attr_accessor :attributes #:nodoc: attr_accessor :prefix_options #:nodoc: # Constructor method for new resources; the optional +attributes+ parameter takes a hash # of attributes for the new resource. # # ==== Examples # my_course = Course.new # my_course.name = "Western Civilization" # my_course.lecturer = "Don Trotter" # my_course.save # # my_other_course = Course.new(:name => "Philosophy: Reason and Being", :lecturer => "Ralph Cling") # my_other_course.save def initialize(attributes = {}) @attributes = {} @prefix_options = {} load(attributes) end # Returns a clone of the resource that hasn't been assigned an +id+ yet and # is treated as a new resource. # # ryan = Person.find(1) # not_ryan = ryan.clone # not_ryan.new? # => true # # Any active resource member attributes will NOT be cloned, though all other # attributes are. This is to prevent the conflict between any +prefix_options+ # that refer to the original parent resource and the newly cloned parent # resource that does not exist. # # ryan = Person.find(1) # ryan.address = StreetAddress.find(1, :person_id => ryan.id) # ryan.hash = {:not => "an ARes instance"} # # not_ryan = ryan.clone # not_ryan.new? # => true # not_ryan.address # => NoMethodError # not_ryan.hash # => {:not => "an ARes instance"} def clone # Clone all attributes except the pk and any nested ARes cloned = attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.inject({}) do |attrs, (k, v)| attrs[k] = v.clone attrs end # Form the new resource - bypass initialize of resource with 'new' as that will call 'load' which # attempts to convert hashes into member objects and arrays into collections of objects. We want # the raw objects to be cloned so we bypass load by directly setting the attributes hash. resource = self.class.new({}) resource.prefix_options = self.prefix_options resource.send :instance_variable_set, '@attributes', cloned resource end # A method to determine if the resource a new object (i.e., it has not been POSTed to the remote service yet). # # ==== Examples # not_new = Computer.create(:brand => 'Apple', :make => 'MacBook', :vendor => 'MacMall') # not_new.new? # => false # # is_new = Computer.new(:brand => 'IBM', :make => 'Thinkpad', :vendor => 'IBM') # is_new.new? # => true # # is_new.save # is_new.new? # => false # def new? id.nil? end # Get the +id+ attribute of the resource. def id attributes[self.class.primary_key] end # Set the +id+ attribute of the resource. def id=(id) attributes[self.class.primary_key] = id end # Allows Active Resource objects to be used as parameters in Action Pack URL generation. def to_param id && id.to_s end # Test for equality. Resource are equal if and only if +other+ is the same object or # is an instance of the same class, is not <tt>new?</tt>, and has the same +id+. # # ==== Examples # ryan = Person.create(:name => 'Ryan') # jamie = Person.create(:name => 'Jamie') # # ryan == jamie # # => false (Different name attribute and id) # # ryan_again = Person.new(:name => 'Ryan') # ryan == ryan_again # # => false (ryan_again is new?) # # ryans_clone = Person.create(:name => 'Ryan') # ryan == ryans_clone # # => false (Different id attributes) # # ryans_twin = Person.find(ryan.id) # ryan == ryans_twin # # => true # def ==(other) other.equal?(self) || (other.instance_of?(self.class) && !other.new? && other.id == id) end # Tests for equality (delegates to ==). def eql?(other) self == other end # Delegates to id in order to allow two resources of the same type and id to work with something like: # [Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)] def hash id.hash end # Duplicate the current resource without saving it. # # ==== Examples # my_invoice = Invoice.create(:customer => 'That Company') # next_invoice = my_invoice.dup # next_invoice.new? # => true # # next_invoice.save # next_invoice == my_invoice # => false (different id attributes) # # my_invoice.customer # => That Company # next_invoice.customer # => That Company def dup returning self.class.new do |resource| resource.attributes = @attributes resource.prefix_options = @prefix_options end end # A method to save (+POST+) or update (+PUT+) a resource. It delegates to +create+ if a new object, # +update+ if it is existing. If the response to the save includes a body, it will be assumed that this body # is XML for the final object as it looked after the save (which would include attributes like +created_at+ # that weren't part of the original submit). # # ==== Examples # my_company = Company.new(:name => 'RoleModel Software', :owner => 'Ken Auer', :size => 2) # my_company.new? # => true # my_company.save # sends POST /companies/ (create) # # my_company.new? # => false # my_company.size = 10 # my_company.save # sends PUT /companies/1 (update) def save new? ? create : update end # Deletes the resource from the remote service. # # ==== Examples # my_id = 3 # my_person = Person.find(my_id) # my_person.destroy # Person.find(my_id) # 404 (Resource Not Found) # # new_person = Person.create(:name => 'James') # new_id = new_person.id # => 7 # new_person.destroy # Person.find(new_id) # 404 (Resource Not Found) def destroy connection.delete(element_path, self.class.headers) end # Evaluates to <tt>true</tt> if this resource is not <tt>new?</tt> and is # found on the remote service. Using this method, you can check for # resources that may have been deleted between the object's instantiation # and actions on it. # # ==== Examples # Person.create(:name => 'Theodore Roosevelt') # that_guy = Person.find(:first) # that_guy.exists? # => true # # that_lady = Person.new(:name => 'Paul Bean') # that_lady.exists? # => false # # guys_id = that_guy.id # Person.delete(guys_id) # that_guy.exists? # => false def exists? !new? && self.class.exists?(to_param, :params => prefix_options) end # A method to convert the the resource to an XML string. # # ==== Options # The +options+ parameter is handed off to the +to_xml+ method on each # attribute, so it has the same options as the +to_xml+ methods in # Active Support. # # * <tt>:indent</tt> - Set the indent level for the XML output (default is +2+). # * <tt>:dasherize</tt> - Boolean option to determine whether or not element names should # replace underscores with dashes (default is <tt>false</tt>). # * <tt>:skip_instruct</tt> - Toggle skipping the +instruct!+ call on the XML builder # that generates the XML declaration (default is <tt>false</tt>). # # ==== Examples # my_group = SubsidiaryGroup.find(:first) # my_group.to_xml # # => <?xml version="1.0" encoding="UTF-8"?> # # <subsidiary_group> [...] </subsidiary_group> # # my_group.to_xml(:dasherize => true) # # => <?xml version="1.0" encoding="UTF-8"?> # # <subsidiary-group> [...] </subsidiary-group> # # my_group.to_xml(:skip_instruct => true) # # => <subsidiary_group> [...] </subsidiary_group> def to_xml(options={}) attributes.to_xml({:root => self.class.element_name}.merge(options)) end # A method to reload the attributes of this object from the remote web service. # # ==== Examples # my_branch = Branch.find(:first) # my_branch.name # => "Wislon Raod" # # # Another client fixes the typo... # # my_branch.name # => "Wislon Raod" # my_branch.reload # my_branch.name # => "Wilson Road" def reload self.load(self.class.find(to_param, :params => @prefix_options).attributes) end # A method to manually load attributes from a hash. Recursively loads collections of # resources. This method is called in +initialize+ and +create+ when a hash of attributes # is provided. # # ==== Examples # my_attrs = {:name => 'J&J Textiles', :industry => 'Cloth and textiles'} # # the_supplier = Supplier.find(:first) # the_supplier.name # => 'J&M Textiles' # the_supplier.load(my_attrs) # the_supplier.name('J&J Textiles') # # # These two calls are the same as Supplier.new(my_attrs) # my_supplier = Supplier.new # my_supplier.load(my_attrs) # # # These three calls are the same as Supplier.create(my_attrs) # your_supplier = Supplier.new # your_supplier.load(my_attrs) # your_supplier.save def load(attributes) raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash) @prefix_options, attributes = split_options(attributes) attributes.each do |key, value| @attributes[key.to_s] = case value when Array resource = find_or_create_resource_for_collection(key) value.map { |attrs| resource.new(attrs) } when Hash resource = find_or_create_resource_for(key) resource.new(value) else value.dup rescue value end end self end # For checking <tt>respond_to?</tt> without searching the attributes (which is faster). alias_method :respond_to_without_attributes?, :respond_to? # A method to determine if an object responds to a message (e.g., a method call). In Active Resource, a Person object with a # +name+ attribute can answer <tt>true</tt> to <tt>my_person.respond_to?("name")</tt>, <tt>my_person.respond_to?("name=")</tt>, and # <tt>my_person.respond_to?("name?")</tt>. def respond_to?(method, include_priv = false) method_name = method.to_s if attributes.nil? return super elsif attributes.has_key?(method_name) return true elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1)) return true end # super must be called at the end of the method, because the inherited respond_to? # would return true for generated readers, even if the attribute wasn't present super end protected def connection(refresh = false) self.class.connection(refresh) end # Update the resource on the remote service. def update returning connection.put(element_path(prefix_options), to_xml, self.class.headers) do |response| load_attributes_from_response(response) end end # Create (i.e., save to the remote service) the new resource. def create returning connection.post(collection_path, to_xml, self.class.headers) do |response| self.id = id_from_response(response) load_attributes_from_response(response) end end def load_attributes_from_response(response) if response['Content-Length'] != "0" && response.body.strip.size > 0 load(self.class.format.decode(response.body)) end end # Takes a response from a typical create post and pulls the ID out def id_from_response(response) response['Location'][/\/([^\/]*?)(\.\w+)?$/, 1] end def element_path(options = nil) self.class.element_path(to_param, options || prefix_options) end def collection_path(options = nil) self.class.collection_path(options || prefix_options) end private # Tries to find a resource for a given collection name; if it fails, then the resource is created def find_or_create_resource_for_collection(name) find_or_create_resource_for(name.to_s.singularize) end # Tries to find a resource in a non empty list of nested modules # Raises a NameError if it was not found in any of the given nested modules def find_resource_in_modules(resource_name, module_names) receiver = Object namespaces = module_names[0, module_names.size-1].map do |module_name| receiver = receiver.const_get(module_name) end if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(resource_name) } return namespace.const_get(resource_name) else raise NameError end end # Tries to find a resource for a given name; if it fails, then the resource is created def find_or_create_resource_for(name) resource_name = name.to_s.camelize ancestors = self.class.name.split("::") if ancestors.size > 1 find_resource_in_modules(resource_name, ancestors) else self.class.const_get(resource_name) end rescue NameError if self.class.const_defined?(resource_name) resource = self.class.const_get(resource_name) else resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base)) end resource.prefix = self.class.prefix resource.site = self.class.site resource end def split_options(options = {}) self.class.send!(:split_options, options) end def method_missing(method_symbol, *arguments) #:nodoc: method_name = method_symbol.to_s case method_name.last when "=" attributes[method_name.first(-1)] = arguments.first when "?" attributes[method_name.first(-1)] else attributes.has_key?(method_name) ? attributes[method_name] : super end end end end
38.534567
135
0.622186
18335ad83617a028514dd856f3a4c14f7421d386
3,506
class Grafana < Formula desc "Gorgeous metric visualizations and dashboards for timeseries databases" homepage "https://grafana.com" url "https://github.com/grafana/grafana/archive/v8.1.3.tar.gz" sha256 "0ba2e11ede1501c370e5f7634125d63cf6d6f8d6c65e9e256dd998bd4f0db1cc" license "AGPL-3.0-only" head "https://github.com/grafana/grafana.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "27b975a30f40edda584abb288a1893085a3c6e17442881eda2d0a8688d3721ce" sha256 cellar: :any_skip_relocation, big_sur: "c5e988d4644a9ceeb636480c04ef49ad110a389960b813d974304c72be84da88" sha256 cellar: :any_skip_relocation, catalina: "ed7e6bec5fb75387372d25fa1ec4a841d5e90eb9eaaddd18857a614678c97224" sha256 cellar: :any_skip_relocation, mojave: "26c5128e01d6feca9786b0150879bacbf55521c14eaa93a9918d2d98944c6a5c" sha256 cellar: :any_skip_relocation, x86_64_linux: "872f39f45f6bb3e14a6bb2a585a2154c977615002b92ecda4e8ffe9898976148" end depends_on "go" => :build depends_on "node" => :build depends_on "yarn" => :build uses_from_macos "zlib" on_linux do depends_on "fontconfig" depends_on "freetype" end def install system "go", "run", "build.go", "build" system "yarn", "install", "--ignore-engines", "--network-concurrency", "1" system "node_modules/webpack/bin/webpack.js", "--config", "scripts/webpack/webpack.prod.js" if OS.mac? bin.install Dir["bin/darwin-*/grafana-cli"] bin.install Dir["bin/darwin-*/grafana-server"] else bin.install "bin/linux-amd64/grafana-cli" bin.install "bin/linux-amd64/grafana-server" end (etc/"grafana").mkpath cp("conf/sample.ini", "conf/grafana.ini.example") etc.install "conf/sample.ini" => "grafana/grafana.ini" etc.install "conf/grafana.ini.example" => "grafana/grafana.ini.example" pkgshare.install "conf", "public", "tools" end def post_install (var/"log/grafana").mkpath (var/"lib/grafana/plugins").mkpath end service do run [opt_bin/"grafana-server", "--config", etc/"grafana/grafana.ini", "--homepath", opt_pkgshare, "--packaging=brew", "cfg:default.paths.logs=#{var}/log/grafana", "cfg:default.paths.data=#{var}/lib/grafana", "cfg:default.paths.plugins=#{var}/lib/grafana/plugins"] keep_alive true error_log_path var/"log/grafana-stderr.log" log_path var/"log/grafana-stdout.log" working_dir var/"lib/grafana" end test do require "pty" require "timeout" # first test system bin/"grafana-server", "-v" # avoid stepping on anything that may be present in this directory tdir = File.join(Dir.pwd, "grafana-test") Dir.mkdir(tdir) logdir = File.join(tdir, "log") datadir = File.join(tdir, "data") plugdir = File.join(tdir, "plugins") [logdir, datadir, plugdir].each do |d| Dir.mkdir(d) end Dir.chdir(pkgshare) res = PTY.spawn(bin/"grafana-server", "cfg:default.paths.logs=#{logdir}", "cfg:default.paths.data=#{datadir}", "cfg:default.paths.plugins=#{plugdir}", "cfg:default.server.http_port=50100") r = res[0] w = res[1] pid = res[2] listening = Timeout.timeout(10) do li = false r.each do |l| if /HTTP Server Listen/.match?(l) li = true break end end li end Process.kill("TERM", pid) w.close r.close listening end end
31.303571
122
0.673987
bf1d8d8b5fc9a6cbd8ba92405847e492a3c962ce
1,080
# frozen_string_literal: true module Projects module Registry class TagsController < ::Projects::Registry::ApplicationController before_action :authorize_destroy_container_image!, only: [:destroy] def index respond_to do |format| format.json do render json: ContainerTagsSerializer .new(project: @project, current_user: @current_user) .with_pagination(request, response) .represent(tags) end end end def destroy if tag.delete respond_to do |format| format.json { head :no_content } end else respond_to do |format| format.json { head :bad_request } end end end private def tags Kaminari::PaginatableArray.new(image.tags, limit: 15) end def image @image ||= project.container_repositories .find(params[:repository_id]) end def tag @tag ||= image.tag(params[:id]) end end end end
22.5
73
0.571296
5d88a5daecd17e34ea4d870103d2a6f1ba23b812
45,823
require 'time' require 'ostruct' require 'uri' require 'rack' if ENV['SWIFT'] require 'swiftcore/swiftiplied_mongrel' puts "Using Swiftiplied Mongrel" elsif ENV['EVENT'] require 'swiftcore/evented_mongrel' puts "Using Evented Mongrel" end module Rack #:nodoc: class Request #:nodoc: # Set of request method names allowed via the _method parameter hack. By # default, all request methods defined in RFC2616 are included, with the # exception of TRACE and CONNECT. POST_TUNNEL_METHODS_ALLOWED = %w( PUT DELETE OPTIONS HEAD ) # Return the HTTP request method with support for method tunneling using # the POST _method parameter hack. If the real request method is POST and # a _method param is given and the value is one defined in # +POST_TUNNEL_METHODS_ALLOWED+, return the value of the _method param # instead. def request_method if post_tunnel_method_hack? params['_method'].upcase else @env['REQUEST_METHOD'] end end def user_agent @env['HTTP_USER_AGENT'] end private # Return truthfully if the request is a valid verb-over-post hack. def post_tunnel_method_hack? @env['REQUEST_METHOD'] == 'POST' && POST_TUNNEL_METHODS_ALLOWED.include?(self.POST.fetch('_method', '').upcase) end end module Utils extend self end end module Sinatra extend self VERSION = '0.3.2' class NotFound < RuntimeError def self.code ; 404 ; end end class ServerError < RuntimeError def self.code ; 500 ; end end Result = Struct.new(:block, :params, :status) unless defined?(Result) def options application.options end def application @app ||= Application.new end def application=(app) @app = app end def port application.options.port end def host application.options.host end def env application.options.env end # Deprecated: use application instead of build_application. alias :build_application :application def server options.server ||= defined?(Rack::Handler::Thin) ? "thin" : "mongrel" # Convert the server into the actual handler name handler = options.server.capitalize # If the convenience conversion didn't get us anything, # fall back to what the user actually set. handler = options.server unless Rack::Handler.const_defined?(handler) @server ||= eval("Rack::Handler::#{handler}") end def run begin puts "== Sinatra/#{Sinatra::VERSION} has taken the stage on port #{port} for #{env} with backup by #{server.name}" server.run(application, {:Port => port, :Host => host}) do |server| trap(:INT) do server.stop puts "\n== Sinatra has ended his set (crowd applauds)" end end rescue Errno::EADDRINUSE => e puts "== Someone is already performing on port #{port}!" end end class Event include Rack::Utils URI_CHAR = '[^/?:,&#\.]'.freeze unless defined?(URI_CHAR) PARAM = /(:(#{URI_CHAR}+)|\*)/.freeze unless defined?(PARAM) SPLAT = /(.*?)/ attr_reader :path, :block, :param_keys, :pattern, :options def initialize(path, options = {}, &b) @path = URI.encode(path) @block = b @param_keys = [] @options = options splats = 0 regex = @path.to_s.gsub(PARAM) do |match| if match == "*" @param_keys << "_splat_#{splats}" splats += 1 SPLAT.to_s else @param_keys << $2 "(#{URI_CHAR}+)" end end @pattern = /^#{regex}$/ end def invoke(request) params = {} if agent = options[:agent] return unless request.user_agent =~ agent params[:agent] = $~[1..-1] end if host = options[:host] return unless host === request.host end return unless pattern =~ request.path_info.squeeze('/') path_params = param_keys.zip($~.captures.map{|s| unescape(s) if s}).to_hash params.merge!(path_params) splats = params.select { |k, v| k =~ /^_splat_\d+$/ }.sort.map(&:last) unless splats.empty? params.delete_if { |k, v| k =~ /^_splat_\d+$/ } params["splat"] = splats end Result.new(block, params, 200) end end class Error attr_reader :type, :block, :options def initialize(type, options={}, &block) @type = type @block = block @options = options end def invoke(request) Result.new(block, options, code) end def code if type.respond_to?(:code) type.code else 500 end end end class Static include Rack::Utils def initialize(app) @app = app end def invoke(request) path = @app.options.public + unescape(request.path_info) return unless File.file?(path) block = Proc.new { send_file path, :disposition => nil } Result.new(block, {}, 200) end end # Methods for sending files and streams to the browser instead of rendering. module Streaming DEFAULT_SEND_FILE_OPTIONS = { :type => 'application/octet-stream'.freeze, :disposition => 'attachment'.freeze, :stream => true, :buffer_size => 8192 }.freeze class MissingFile < RuntimeError; end class FileStreamer attr_reader :path, :options def initialize(path, options) @path, @options = path, options end def to_result(cx, *args) self end def each size = options[:buffer_size] File.open(path, 'rb') do |file| while buf = file.read(size) yield buf end end end end protected # Sends the file by streaming it 8192 bytes at a time. This way the # whole file doesn't need to be read into memory at once. This makes # it feasible to send even large files. # # Be careful to sanitize the path parameter if it coming from a web # page. send_file(params[:path]) allows a malicious user to # download any file on your server. # # Options: # * <tt>:filename</tt> - suggests a filename for the browser to use. # Defaults to File.basename(path). # * <tt>:type</tt> - specifies an HTTP content type. # Defaults to 'application/octet-stream'. # * <tt>:disposition</tt> - specifies whether the file will be shown # inline or downloaded. Valid values are 'inline' and 'attachment' # (default). When set to nil, the Content-Disposition and # Content-Transfer-Encoding headers are omitted entirely. # * <tt>:stream</tt> - whether to send the file to the user agent as it # is read (true) or to read the entire file before sending (false). # Defaults to true. # * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used # to stream the file. Defaults to 8192. # * <tt>:status</tt> - specifies the status code to send with the # response. Defaults to '200 OK'. # * <tt>:last_modified</tt> - an optional RFC 2616 formatted date value # (See Time#httpdate) indicating the last modified time of the file. # If the request includes an If-Modified-Since header that matches this # value exactly, a 304 Not Modified response is sent instead of the file. # Defaults to the file's last modified time. # # The default Content-Type and Content-Disposition headers are # set to download arbitrary binary files in as many browsers as # possible. IE versions 4, 5, 5.5, and 6 are all known to have # a variety of quirks (especially when downloading over SSL). # # Simple download: # send_file '/path/to.zip' # # Show a JPEG in the browser: # send_file '/path/to.jpeg', # :type => 'image/jpeg', # :disposition => 'inline' # # Show a 404 page in the browser: # send_file '/path/to/404.html, # :type => 'text/html; charset=utf-8', # :status => 404 # # Read about the other Content-* HTTP headers if you'd like to # provide the user with more information (such as Content-Description). # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 # # Also be aware that the document may be cached by proxies and browsers. # The Pragma and Cache-Control headers declare how the file may be cached # by intermediaries. They default to require clients to validate with # the server before releasing cached responses. See # http://www.mnot.net/cache_docs/ for an overview of web caching and # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 # for the Cache-Control header spec. def send_file(path, options = {}) #:doc: raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path) options[:length] ||= File.size(path) options[:filename] ||= File.basename(path) options[:type] ||= Rack::File::MIME_TYPES[File.extname(options[:filename])[1..-1]] || 'text/plain' options[:last_modified] ||= File.mtime(path).httpdate options[:stream] = true unless options.key?(:stream) options[:buffer_size] ||= DEFAULT_SEND_FILE_OPTIONS[:buffer_size] send_file_headers! options if options[:stream] throw :halt, [options[:status] || 200, FileStreamer.new(path, options)] else File.open(path, 'rb') { |file| throw :halt, [options[:status] || 200, [file.read]] } end end # Send binary data to the user as a file download. May set content type, # apparent file name, and specify whether to show data inline or download # as an attachment. # # Options: # * <tt>:filename</tt> - Suggests a filename for the browser to use. # * <tt>:type</tt> - specifies an HTTP content type. # Defaults to 'application/octet-stream'. # * <tt>:disposition</tt> - specifies whether the file will be shown inline # or downloaded. Valid values are 'inline' and 'attachment' (default). # * <tt>:status</tt> - specifies the status code to send with the response. # Defaults to '200 OK'. # * <tt>:last_modified</tt> - an optional RFC 2616 formatted date value (See # Time#httpdate) indicating the last modified time of the response entity. # If the request includes an If-Modified-Since header that matches this # value exactly, a 304 Not Modified response is sent instead of the data. # # Generic data download: # send_data buffer # # Download a dynamically-generated tarball: # send_data generate_tgz('dir'), :filename => 'dir.tgz' # # Display an image Active Record in the browser: # send_data image.data, # :type => image.content_type, # :disposition => 'inline' # # See +send_file+ for more information on HTTP Content-* headers and caching. def send_data(data, options = {}) #:doc: send_file_headers! options.merge(:length => data.size) throw :halt, [options[:status] || 200, [data]] end private def send_file_headers!(options) options = DEFAULT_SEND_FILE_OPTIONS.merge(options) [:length, :type, :disposition].each do |arg| raise ArgumentError, ":#{arg} option required" unless options.key?(arg) end # Send a "304 Not Modified" if the last_modified option is provided and # matches the If-Modified-Since request header value. if last_modified = options[:last_modified] header 'Last-Modified' => last_modified throw :halt, [ 304, '' ] if last_modified == request.env['HTTP_IF_MODIFIED_SINCE'] end headers( 'Content-Length' => options[:length].to_s, 'Content-Type' => options[:type].strip # fixes a problem with extra '\r' with some browsers ) # Omit Content-Disposition and Content-Transfer-Encoding headers if # the :disposition option set to nil. if !options[:disposition].nil? disposition = options[:disposition].dup || 'attachment' disposition <<= %(; filename="#{options[:filename]}") if options[:filename] headers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' end # Fix a problem with IE 6.0 on opening downloaded files: # If Cache-Control: no-cache is set (which Rails does by default), # IE removes the file it just downloaded from its cache immediately # after it displays the "open/save" dialog, which means that if you # hit "open" the file isn't there anymore when the application that # is called for handling the download is run, so let's workaround that header('Cache-Control' => 'private') if headers['Cache-Control'] == 'no-cache' end end # Helper methods for building various aspects of the HTTP response. module ResponseHelpers # Immediately halt response execution by redirecting to the resource # specified. The +path+ argument may be an absolute URL or a path # relative to the site root. Additional arguments are passed to the # halt. # # With no integer status code, a '302 Temporary Redirect' response is # sent. To send a permanent redirect, pass an explicit status code of # 301: # # redirect '/somewhere/else', 301 # # NOTE: No attempt is made to rewrite the path based on application # context. The 'Location' response header is set verbatim to the value # provided. def redirect(path, *args) status(302) header 'Location' => path throw :halt, *args end # Access or modify response headers. With no argument, return the # underlying headers Hash. With a Hash argument, add or overwrite # existing response headers with the values provided: # # headers 'Content-Type' => "text/html;charset=utf-8", # 'Last-Modified' => Time.now.httpdate, # 'X-UA-Compatible' => 'IE=edge' # # This method also available in singular form (#header). def headers(header = nil) @response.headers.merge!(header) if header @response.headers end alias :header :headers # Set the content type of the response body (HTTP 'Content-Type' header). # # The +type+ argument may be an internet media type (e.g., 'text/html', # 'application/xml+atom', 'image/png') or a Symbol key into the # Rack::File::MIME_TYPES table. # # Media type parameters, such as "charset", may also be specified using the # optional hash argument: # # get '/foo.html' do # content_type 'text/html', :charset => 'utf-8' # "<h1>Hello World</h1>" # end # def content_type(type, params={}) type = Rack::File::MIME_TYPES[type.to_s] if type.kind_of?(Symbol) fail "Invalid or undefined media_type: #{type}" if type.nil? if params.any? params = params.collect { |kv| "%s=%s" % kv }.join(', ') type = [ type, params ].join(";") end response.header['Content-Type'] = type end # Set the last modified time of the resource (HTTP 'Last-Modified' header) # and halt if conditional GET matches. The +time+ argument is a Time, # DateTime, or other object that responds to +to_time+. # # When the current request includes an 'If-Modified-Since' header that # matches the time specified, execution is immediately halted with a # '304 Not Modified' response. # # Calling this method before perfoming heavy processing (e.g., lengthy # database queries, template rendering, complex logic) can dramatically # increase overall throughput with caching clients. def last_modified(time) time = time.to_time if time.respond_to?(:to_time) time = time.httpdate if time.respond_to?(:httpdate) response.header['Last-Modified'] = time throw :halt, 304 if time == request.env['HTTP_IF_MODIFIED_SINCE'] time end # Set the response entity tag (HTTP 'ETag' header) and halt if conditional # GET matches. The +value+ argument is an identifier that uniquely # identifies the current version of the resource. The +strength+ argument # indicates whether the etag should be used as a :strong (default) or :weak # cache validator. # # When the current request includes an 'If-None-Match' header with a # matching etag, execution is immediately halted. If the request method is # GET or HEAD, a '304 Not Modified' response is sent. For all other request # methods, a '412 Precondition Failed' response is sent. # # Calling this method before perfoming heavy processing (e.g., lengthy # database queries, template rendering, complex logic) can dramatically # increase overall throughput with caching clients. # # ==== See Also # {RFC2616: ETag}[http://w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19], # ResponseHelpers#last_modified def entity_tag(value, strength=:strong) value = case strength when :strong then '"%s"' % value when :weak then 'W/"%s"' % value else raise TypeError, "strength must be one of :strong or :weak" end response.header['ETag'] = value # Check for If-None-Match request header and halt if match is found. etags = (request.env['HTTP_IF_NONE_MATCH'] || '').split(/\s*,\s*/) if etags.include?(value) || etags.include?('*') # GET/HEAD requests: send Not Modified response throw :halt, 304 if request.get? || request.head? # Other requests: send Precondition Failed response throw :halt, 412 end end alias :etag :entity_tag end module RenderingHelpers def render(renderer, template, options={}) m = method("render_#{renderer}") result = m.call(resolve_template(renderer, template, options), options) if layout = determine_layout(renderer, template, options) result = m.call(resolve_template(renderer, layout, options), options) { result } end result end def determine_layout(renderer, template, options) return if options[:layout] == false layout_from_options = options[:layout] || :layout resolve_template(renderer, layout_from_options, options, false) end private def resolve_template(renderer, template, options, scream = true) case template when String template when Proc template.call when Symbol if proc = templates[template] resolve_template(renderer, proc, options, scream) else read_template_file(renderer, template, options, scream) end else nil end end def read_template_file(renderer, template, options, scream = true) path = File.join( options[:views_directory] || Sinatra.application.options.views, "#{template}.#{renderer}" ) unless File.exists?(path) raise Errno::ENOENT.new(path) if scream nil else File.read(path) end end def templates Sinatra.application.templates end end module Erb def erb(content, options={}) require 'erb' render(:erb, content, options) end private def render_erb(content, options = {}) locals_opt = options.delete(:locals) || {} locals_code = "" locals_hash = {} locals_opt.each do |key, value| locals_code << "#{key} = locals_hash[:#{key}]\n" locals_hash[:"#{key}"] = value end body = ::ERB.new(content).src eval("#{locals_code}#{body}", binding) end end module Haml def haml(content, options={}) require 'haml' render(:haml, content, options) end private def render_haml(content, options = {}, &b) haml_options = (options[:options] || {}). merge(Sinatra.options.haml || {}) ::Haml::Engine.new(content, haml_options). render(options[:scope] || self, options[:locals] || {}, &b) end end # Generate valid CSS using Sass (part of Haml) # # Sass templates can be in external files with <tt>.sass</tt> extension # or can use Sinatra's in_file_templates. In either case, the file can # be rendered by passing the name of the template to the +sass+ method # as a symbol. # # Unlike Haml, Sass does not support a layout file, so the +sass+ method # will ignore both the default <tt>layout.sass</tt> file and any parameters # passed in as <tt>:layout</tt> in the options hash. # # === Sass Template Files # # Sass templates can be stored in separate files with a <tt>.sass</tt> # extension under the view path. # # Example: # get '/stylesheet.css' do # header 'Content-Type' => 'text/css; charset=utf-8' # sass :stylesheet # end # # The "views/stylesheet.sass" file might contain the following: # # body # #admin # :background-color #CCC # #main # :background-color #000 # #form # :border-color #AAA # :border-width 10px # # And yields the following output: # # body #admin { # background-color: #CCC; } # body #main { # background-color: #000; } # # #form { # border-color: #AAA; # border-width: 10px; } # # # NOTE: Haml must be installed or a LoadError will be raised the first time an # attempt is made to render a Sass template. # # See http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html for comprehensive documentation on Sass. module Sass def sass(content, options = {}) require 'sass' # Sass doesn't support a layout, so we override any possible layout here options[:layout] = false render(:sass, content, options) end private def render_sass(content, options = {}) ::Sass::Engine.new(content).render end end # Generating conservative XML content using Builder templates. # # Builder templates can be inline by passing a block to the builder method, # or in external files with +.builder+ extension by passing the name of the # template to the +builder+ method as a Symbol. # # === Inline Rendering # # If the builder method is given a block, the block is called directly with # an +XmlMarkup+ instance and the result is returned as String: # get '/who.xml' do # builder do |xml| # xml.instruct! # xml.person do # xml.name "Francis Albert Sinatra", # :aka => "Frank Sinatra" # xml.email '[email protected]' # end # end # end # # Yields the following XML: # <?xml version='1.0' encoding='UTF-8'?> # <person> # <name aka='Frank Sinatra'>Francis Albert Sinatra</name> # <email>Frank Sinatra</email> # </person> # # === Builder Template Files # # Builder templates can be stored in separate files with a +.builder+ # extension under the view path. An +XmlMarkup+ object named +xml+ is # automatically made available to template. # # Example: # get '/bio.xml' do # builder :bio # end # # The "views/bio.builder" file might contain the following: # xml.instruct! :xml, :version => '1.1' # xml.person do # xml.name "Francis Albert Sinatra" # xml.aka "Frank Sinatra" # xml.aka "Ol' Blue Eyes" # xml.aka "The Chairman of the Board" # xml.born 'date' => '1915-12-12' do # xml.text! "Hoboken, New Jersey, U.S.A." # end # xml.died 'age' => 82 # end # # And yields the following output: # <?xml version='1.1' encoding='UTF-8'?> # <person> # <name>Francis Albert Sinatra</name> # <aka>Frank Sinatra</aka> # <aka>Ol&apos; Blue Eyes</aka> # <aka>The Chairman of the Board</aka> # <born date='1915-12-12'>Hoboken, New Jersey, U.S.A.</born> # <died age='82' /> # </person> # # NOTE: Builder must be installed or a LoadError will be raised the first # time an attempt is made to render a builder template. # # See http://builder.rubyforge.org/ for comprehensive documentation on # Builder. module Builder def builder(content=nil, options={}, &block) options, content = content, nil if content.is_a?(Hash) content = Proc.new { block } if content.nil? render(:builder, content, options) end private def render_builder(content, options = {}, &b) require 'builder' xml = ::Builder::XmlMarkup.new(:indent => 2) case content when String eval(content, binding, '<BUILDER>', 1) when Proc content.call(xml) end xml.target! end end class EventContext include Rack::Utils include ResponseHelpers include Streaming include RenderingHelpers include Erb include Haml include Builder include Sass attr_accessor :request, :response attr_accessor :route_params def initialize(request, response, route_params) @params = nil @data = nil @request = request @response = response @route_params = route_params @response.body = nil end def status(value=nil) response.status = value if value response.status end def body(value=nil) response.body = value if value response.body end def params @params ||= begin hash = Hash.new {|h,k| h[k.to_s] if Symbol === k} hash.merge! @request.params hash.merge! @route_params hash end end def data @data ||= params.keys.first end def stop(*args) throw :halt, args end def complete(returned) @response.body || returned end def session request.env['rack.session'] ||= {} end def reset! @params = nil @data = nil end private def method_missing(name, *args, &b) if @response.respond_to?(name) @response.send(name, *args, &b) else super end end end # The Application class represents the top-level working area of a # Sinatra app. It provides the DSL for defining various aspects of the # application and implements a Rack compatible interface for dispatching # requests. # # Many of the instance methods defined in this class (#get, #post, # #put, #delete, #layout, #before, #error, #not_found, etc.) are # available at top-level scope. When invoked from top-level, the # messages are forwarded to the "default application" (accessible # at Sinatra::application). class Application # Hash of event handlers with request method keys and # arrays of potential handlers as values. attr_reader :events # Hash of error handlers with error status codes as keys and # handlers as values. attr_reader :errors # Hash of template name mappings. attr_reader :templates # Hash of filters with event name keys (:before) and arrays of # handlers as values. attr_reader :filters # Array of objects to clear during reload. The objects in this array # must respond to :clear. attr_reader :clearables # Object including open attribute methods for modifying Application # configuration. attr_reader :options # List of methods available from top-level scope. When invoked from # top-level the method is forwarded to the default application # (Sinatra::application). FORWARD_METHODS = %w[ get put post delete head resource template layout before error not_found configures configure set set_options set_option enable disable use development? test? production? ] # Create a new Application with a default configuration taken # from the default_options Hash. # # NOTE: A default Application is automatically created the first # time any of Sinatra's DSL related methods is invoked so there # is typically no need to create an instance explicitly. See # Sinatra::application for more information. def initialize @reloading = false @clearables = [ @events = Hash.new { |hash, key| hash[key] = [] }, @errors = Hash.new, @filters = Hash.new { |hash, key| hash[key] = [] }, @templates = Hash.new, @middleware = [] ] @options = OpenStruct.new(self.class.default_options) load_default_configuration! end # Hash of default application configuration options. When a new # Application is created, the #options object takes its initial values # from here. # # Changes to the default_options Hash effect only Application objects # created after the changes are made. For this reason, modifications to # the default_options Hash typically occur at the very beginning of a # file, before any DSL related functions are invoked. def self.default_options return @default_options unless @default_options.nil? root = File.expand_path(File.dirname($0)) @default_options = { :run => true, :port => 4567, :host => '0.0.0.0', :env => (ENV['RACK_ENV'] || :development).to_sym, :root => root, :views => root + '/views', :public => root + '/public', :sessions => false, :logging => true, :app_file => $0, :raise_errors => false } load_default_options_from_command_line! @default_options end # Search ARGV for command line arguments and update the # Sinatra::default_options Hash accordingly. This method is # invoked the first time the default_options Hash is accessed. # NOTE: Ignores --name so unit/spec tests can run individually def self.load_default_options_from_command_line! #:nodoc: # fixes issue with: gem install --test sinatra return if ARGV.empty? || File.basename($0) =~ /gem/ require 'optparse' OptionParser.new do |op| op.on('-p port') { |port| default_options[:port] = port } op.on('-e env') { |env| default_options[:env] = env.to_sym } op.on('-x') { default_options[:mutex] = true } op.on('-s server') { |server| default_options[:server] = server } end.parse!(ARGV.dup.select { |o| o !~ /--name/ }) end # Determine whether the application is in the process of being # reloaded. def reloading? @reloading == true end # Yield to the block for configuration if the current environment # matches any included in the +envs+ list. Always yield to the block # when no environment is specified. # # NOTE: configuration blocks are not executed during reloads. def configures(*envs, &b) return if reloading? yield self if envs.empty? || envs.include?(options.env) end alias :configure :configures # When both +option+ and +value+ arguments are provided, set the option # specified. With a single Hash argument, set all options specified in # Hash. Options are available via the Application#options object. # # Setting individual options: # set :port, 80 # set :env, :production # set :views, '/path/to/views' # # Setting multiple options: # set :port => 80, # :env => :production, # :views => '/path/to/views' # def set(option, value=self) if value == self && option.kind_of?(Hash) option.each { |key,val| set(key, val) } else options.send("#{option}=", value) end end alias :set_option :set alias :set_options :set # Enable the options specified by setting their values to true. For # example, to enable sessions and logging: # enable :sessions, :logging def enable(*opts) opts.each { |key| set(key, true) } end # Disable the options specified by setting their values to false. For # example, to disable logging and automatic run: # disable :logging, :run def disable(*opts) opts.each { |key| set(key, false) } end # Define an event handler for the given request method and path # spec. The block is executed when a request matches the method # and spec. # # NOTE: The #get, #post, #put, and #delete helper methods should # be used to define events when possible. def event(method, path, options = {}, &b) events[method].push(Event.new(path, options, &b)).last end # Define an event handler for GET requests. def get(path, options={}, &b) event(:get, path, options, &b) end # Define an event handler for POST requests. def post(path, options={}, &b) event(:post, path, options, &b) end # Define an event handler for HEAD requests. def head(path, options={}, &b) event(:head, path, options, &b) end # Define an event handler for PUT requests. # # NOTE: PUT events are triggered when the HTTP request method is # PUT and also when the request method is POST and the body includes a # "_method" parameter set to "PUT". def put(path, options={}, &b) event(:put, path, options, &b) end # Define an event handler for DELETE requests. # # NOTE: DELETE events are triggered when the HTTP request method is # DELETE and also when the request method is POST and the body includes a # "_method" parameter set to "DELETE". def delete(path, options={}, &b) event(:delete, path, options, &b) end #define event handlers for all resources for a given url #path is a standard Sinatra path #handlers takes the form {:get => proc {},:post => [{:user_agent => 'Mozilla'},proc {}] } def resource(path, handlers) handlers.each_pair do |action,handler| options={} options,handler=handler if handler.is_a?(Array) event(action,path,options,&handler) end end # Visits and invokes each handler registered for the +request_method+ in # definition order until a Result response is produced. If no handler # responds with a Result, the NotFound error handler is invoked. # # When the request_method is "HEAD" and no valid Result is produced by # the set of handlers registered for HEAD requests, an attempt is made to # invoke the GET handlers to generate the response before resorting to the # default error handler. def lookup(request) method = request.request_method.downcase.to_sym events[method].eject(&[:invoke, request]) || (events[:get].eject(&[:invoke, request]) if method == :head) || errors[NotFound].invoke(request) end # Define a named template. The template may be referenced from # event handlers by passing the name as a Symbol to rendering # methods. The block is executed each time the template is rendered # and the resulting object is passed to the template handler. # # The following example defines a HAML template named hello and # invokes it from an event handler: # # template :hello do # "h1 Hello World!" # end # # get '/' do # haml :hello # end # def template(name, &b) templates[name] = b end # Define a layout template. def layout(name=:layout, &b) template(name, &b) end # Define a custom error handler for the exception class +type+. The block # is invoked when the specified exception type is raised from an error # handler and can manipulate the response as needed: # # error MyCustomError do # status 500 # 'So what happened was...' + request.env['sinatra.error'].message # end # # The Sinatra::ServerError handler is used by default when an exception # occurs and no matching error handler is found. def error(type=ServerError, options = {}, &b) errors[type] = Error.new(type, options, &b) end # Define a custom error handler for '404 Not Found' responses. This is a # shorthand for: # error NotFound do # .. # end def not_found(options={}, &b) error NotFound, options, &b end # Define a request filter. When <tt>type</tt> is <tt>:before</tt>, execute the # block in the context of each request before matching event handlers. def filter(type, &b) filters[type] << b end # Invoke the block in the context of each request before invoking # matching event handlers. def before(&b) filter :before, &b end # True when environment is :development. def development? ; options.env == :development ; end # True when environment is :test. def test? ; options.env == :test ; end # True when environment is :production. def production? ; options.env == :production ; end # Clear all events, templates, filters, and error handlers # and then reload the application source file. This occurs # automatically before each request is processed in development. def reload! clearables.each(&:clear) load_default_configuration! load_development_configuration! if development? @pipeline = nil @reloading = true Kernel.load options.app_file @reloading = false end # Determine whether the application is in the process of being # reloaded. def reloading? @reloading == true end # Mutex instance used for thread synchronization. def mutex @@mutex ||= Mutex.new end # Yield to the block with thread synchronization def run_safely if development? || options.mutex mutex.synchronize { yield } else yield end end # Add a piece of Rack middleware to the pipeline leading to the # application. def use(klass, *args, &block) fail "#{klass} must respond to 'new'" unless klass.respond_to?(:new) @pipeline = nil @middleware.push([ klass, args, block ]).last end private # Rack middleware derived from current state of application options. # These components are plumbed in at the very beginning of the # pipeline. def optional_middleware [ ([ Rack::CommonLogger, [], nil ] if options.logging), ([ Rack::Session::Cookie, [], nil ] if options.sessions) ].compact end # Rack middleware explicitly added to the application with #use. These # components are plumbed into the pipeline downstream from # #optional_middle. def explicit_middleware @middleware end # All Rack middleware used to construct the pipeline. def middleware optional_middleware + explicit_middleware end public # An assembled pipeline of Rack middleware that leads eventually to # the Application#invoke method. The pipeline is built upon first # access. Defining new middleware with Application#use or manipulating # application options may cause the pipeline to be rebuilt. def pipeline @pipeline ||= middleware.inject(method(:dispatch)) do |app,(klass,args,block)| klass.new(app, *args, &block) end end # Rack compatible request invocation interface. def call(env) run_safely do reload! if development? && (options.reload != false) pipeline.call(env) end end # Request invocation handler - called at the end of the Rack pipeline # for each request. # # 1. Create Rack::Request, Rack::Response helper objects. # 2. Lookup event handler based on request method and path. # 3. Create new EventContext to house event handler evaluation. # 4. Invoke each #before filter in context of EventContext object. # 5. Invoke event handler in context of EventContext object. # 6. Return response to Rack. # # See the Rack specification for detailed information on the # +env+ argument and return value. def dispatch(env) request = Rack::Request.new(env) context = EventContext.new(request, Rack::Response.new([], 200), {}) begin returned = catch(:halt) do filters[:before].each { |f| context.instance_eval(&f) } result = lookup(context.request) context.route_params = result.params context.response.status = result.status context.reset! [:complete, context.instance_eval(&result.block)] end body = returned.to_result(context) rescue => e msg = "#{e.class.name} - #{e.message}:" msg << "\n #{e.backtrace.join("\n ")}" request.env['rack.errors'] << msg request.env['sinatra.error'] = e context.status(500) raise if options.raise_errors && e.class != NotFound result = (errors[e.class] || errors[ServerError]).invoke(request) returned = catch(:halt) do [:complete, context.instance_eval(&result.block)] end body = returned.to_result(context) end body = '' unless body.respond_to?(:each) body = '' if request.env["REQUEST_METHOD"].upcase == 'HEAD' context.body = body.kind_of?(String) ? [*body] : body context.finish end private # Called immediately after the application is initialized or reloaded to # register default events, templates, and error handlers. def load_default_configuration! events[:get] << Static.new(self) configure do error do '<h1>Internal Server Error</h1>' end not_found { '<h1>Not Found</h1>'} end end # Called before reloading to perform development specific configuration. def load_development_configuration! get '/sinatra_custom_images/:image.png' do content_type :png File.read(File.dirname(__FILE__) + "/../images/#{params[:image]}.png") end not_found do (<<-HTML).gsub(/^ {8}/, '') <!DOCTYPE html> <html> <head> <style type="text/css"> body {text-align:center;color:#888;font-family:arial;font-size:22px;margin:20px;} #content {margin:0 auto;width:500px;text-align:left} </style> </head> <body> <h2>Sinatra doesn't know this diddy.</h2> <img src='/sinatra_custom_images/404.png'> <div id="content"> Try this: <pre>#{request.request_method.downcase} "#{request.path_info}" do\n .. do something ..\nend<pre> </div> </body> </html> HTML end error do @error = request.env['sinatra.error'] (<<-HTML).gsub(/^ {8}/, '') <!DOCTYPE html> <html> <head> <style type="text/css" media="screen"> body {font-family:verdana;color:#333} #content {width:700px;margin-left:20px} #content h1 {width:99%;color:#1D6B8D;font-weight:bold} #stacktrace {margin-top:-20px} #stacktrace pre {font-size:12px;border-left:2px solid #ddd;padding-left:10px} #stacktrace img {margin-top:10px} </style> </head> <body> <div id="content"> <img src="/sinatra_custom_images/500.png"> <div class="info"> Params: <pre>#{params.inspect}</pre> </div> <div id="stacktrace"> <h1>#{escape_html(@error.class.name + ' - ' + @error.message.to_s)}</h1> <pre><code>#{escape_html(@error.backtrace.join("\n"))}</code></pre> </div> </div> </body> </html> HTML end end end end # Delegate DSLish methods to the currently active Sinatra::Application # instance. Sinatra::Application::FORWARD_METHODS.each do |method| eval(<<-EOS, binding, '(__DSL__)', 1) def #{method}(*args, &b) Sinatra.application.#{method}(*args, &b) end EOS end def helpers(&b) Sinatra::EventContext.class_eval(&b) end def use_in_file_templates! require 'stringio' templates = IO.read(caller.first.split(':').first).split('__END__').last data = StringIO.new(templates) current_template = nil data.each do |line| if line =~ /^@@\s?(.*)/ current_template = $1.to_sym Sinatra.application.templates[current_template] = '' elsif current_template Sinatra.application.templates[current_template] << line end end end def mime(ext, type) Rack::File::MIME_TYPES[ext.to_s] = type end ### Misc Core Extensions module Kernel def silence_warnings old_verbose, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = old_verbose end end class Symbol def to_proc Proc.new { |*args| args.shift.__send__(self, *args) } end end class Array def to_hash self.inject({}) { |h, (k, v)| h[k] = v; h } end def to_proc Proc.new { |*args| args.shift.__send__(self[0], *(args + self[1..-1])) } end end module Enumerable def eject(&block) find { |e| result = block[e] and break result } end end ### Core Extension results for throw :halt class Proc def to_result(cx, *args) cx.instance_eval(&self) args.shift.to_result(cx, *args) end end class String def to_result(cx, *args) args.shift.to_result(cx, *args) self end end class Array def to_result(cx, *args) self.shift.to_result(cx, *self) end end class Symbol def to_result(cx, *args) cx.send(self, *args) end end class Fixnum def to_result(cx, *args) cx.status self args.shift.to_result(cx, *args) end end class NilClass def to_result(cx, *args) '' end end at_exit do raise $! if $! Sinatra.run if Sinatra.application.options.run end mime :xml, 'application/xml' mime :js, 'application/javascript' mime :png, 'image/png'
30.919703
120
0.631255
f81b4accd33ad93c4a8a4c9011076c73be530bb5
377
require 'formula' class Stress < Formula homepage 'http://weather.ou.edu/~apw/projects/stress/' url 'http://weather.ou.edu/~apw/projects/stress/stress-1.0.4.tar.gz' sha1 '7ccb6d76d27ddd54461a21411f2bc8491ba65168' def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end
26.928571
70
0.668435
bf679769074ed890e03e987e6aee6035995b0faf
950
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint flutter_yidun_captcha.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'flutter_yidun_captcha' s.version = '0.0.1' s.summary = 'A new flutter plugin project.' s.description = <<-DESC A new flutter plugin project. DESC s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.dependency 'NTESVerifyCode', '~> 3.2.8' s.platform = :ios, '8.0' # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } end
36.538462
105
0.598947
018683305e0a310e46c1db079d18155041685f88
1,662
require 'spec_helper' java_7_path = '/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java' java_7_home = '/usr/lib/jvm/java-7-openjdk-amd64' java_8_path = '/usr/lib/jvm/oracle-java8-jre-amd64/bin/java' java_8_home = '/usr/lib/jvm/oracle-java8-jre-amd64' def unlink_and_delete(filename) if File.symlink?(filename) File.unlink(filename) end return unless File.exist?(filename) File.delete(filename) end def symlink_and_test(symlink_path, java_home) File.symlink(symlink_path, './java_test') Facter::Util::Resolution.expects(:which).with('java').returns('./java_test') File.expects(:realpath).with('./java_test').returns(symlink_path) expect(Facter.value(:java_default_home)).to eql java_home end describe 'java_default_home' do before(:each) do Facter.clear Facter.fact(:kernel).stubs(:value).returns('Linux') end context 'returns java home path when java found in PATH' do context 'when java is in /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java' do it do unlink_and_delete('./java_test') symlink_and_test(java_7_path, java_7_home) unlink_and_delete('./java_test') end end context 'when java is in /usr/lib/jvm/oracle-java8-jre-amd64/bin/java' do it do unlink_and_delete('./java_test') symlink_and_test(java_8_path, java_8_home) unlink_and_delete('./java_test') end end end context 'returns nil when java not present' do it do Facter::Util::Resolution.stubs(:exec) Facter::Util::Resolution.expects(:which).with('java').at_least(1).returns(false) expect(Facter.value(:java_default_home)).to be_nil end end end
30.218182
86
0.705776
87fa858cfc9e601a280d155b779b749449659312
73
(1..10).each do |i| ... 1.upto(10) do |i| ... 10.times do |n| i=n+1; ...
18.25
26
0.452055
f8d823f019ced023c3918cdc24ea691bb5bafa0e
3,511
# name: after-logout-endpoint # about: An endpoint to redirect to after logout which performs additional functions to the user browser # version: 0.0.2 # authors: Stackable Regiments pty ltd # url: https://github.com/StackableRegiments/discourseLogout enabled_site_setting :enhancedLogout_enabled after_initialize do module ::Enderpoint PLUGIN_NAME = "enhanced_logout".freeze class Engine < ::Rails::Engine engine_name PLUGIN_NAME isolate_namespace Enderpoint end end require_dependency "application_controller" class Enderpoint::EnderController < ::ApplicationController skip_before_action :redirect_to_login_if_required, :check_xhr def clearBrowserHistory if SiteSetting.enhancedLogout_should_clear_cookies? then <<~SCRIPT_CONTENT console.log("clearing browser history"); SCRIPT_CONTENT else "" end end def clearCookies if SiteSetting.enhancedLogout_should_clear_browser_session_history? then <<~SCRIPT_CONTENT var getDocumentCookie = function(){ return document.cookie.split(";"); }; var getDomainParts = function(){ return window.location.hostname.split("."); }; var getPathParts = function(){ return window.location.pathname.split("/"); }; var cookies = getDocumentCookie(); console.log("clearingCookies",cookies); var oneDay = 24 * 60 * 60 * 1000; var expiringDate = new Date(new Date().getTime() - oneDay).toGMTString(); var domainParts = getDomainParts(); var pathParts = getPathParts(); for (var i = 0; i < cookies.length; i++){ var cookie = cookies[i]; var parts = cookie.split("="); var name = parts[0]; var value = parts[1]; if (name !== ""){ var terminalCookie = name+"="+value+"; expires="+expiringDate+"; path=/;"; console.log("clearing base cookie: ",cookie,terminalCookie); document.cookie = terminalCookie; for (var di = domainParts.length - 1; di >= 0; di--){ for (var pi = 0; pi <= pathParts.length; pi++){ var domain = domainParts.slice(di,domainParts.length).join("."); var path = "/"+pathParts.slice(0,pi).join("/"); var terminalCookie = name+"="+value+"; expires="+expiringDate+"; path="+path+"; domain="+domain+";" console.log("clearing potential cookie: ",cookie,terminalCookie); document.cookie = terminalCookie; } } } } cookies = getDocumentCookie(); console.log("clearedCookies",cookies); SCRIPT_CONTENT else "" end end def redirectAgain if SiteSetting.enhancedLogout_should_redirect? && !SiteSetting.enhancedLogout_redirect_url.blank? then <<~SCRIPT_CONTENT var redirectionLocation = "#{SiteSetting.enhancedLogout_redirect_url}"; console.log("redirecting to",redirectionLocation); window.location = redirectionLocation; SCRIPT_CONTENT else "" end end def closeTab if SiteSetting.enhancedLogout_should_close_tab? then <<~SCRIPT_CONTENT console.log("attempting to close tab"); window.open('','_self').close(); SCRIPT_CONTENT else "" end end def showContent SiteSetting.enhancedLogout_custom_logout_page_html end def index render inline: <<-HTML_CONTENT <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <script type="text/javascript"> #{clearBrowserHistory} #{clearCookies} #{redirectAgain} #{closeTab} </script> </head> <body> #{showContent} </body> </html> HTML_CONTENT end end Enderpoint::Engine.routes.draw do get "/" => "ender#index" end Discourse::Application.routes.append do mount ::Enderpoint::Engine, at: "/enhanced-logout" end end
25.627737
105
0.71632
26594f7ccfa908155f751b419aae9c4bd706cc2a
3,115
# The helper methods here are used to build the main index template file for # a SproutCore application. See the commented index.rhtml in the plugin for # example usage. # module SproutCore module Helpers module StaticHelper # This method will return the HTML to link to all the stylesheets # required by the named bundle. If you pass no options, the current # client will be used. # # bundle_name = the name of the bundle to render or nil to use the # current :language => the language to render. defaults to current # language # def stylesheets_for_client(bundle_name = nil, opts = {}) opts[:language] ||= language # Get bundle cur_bundle = bundle_name.nil? ? bundle : library.bundle_for(bundle_name) # Convert to a list of required bundles all_bundles = cur_bundle.all_required_bundles # For each bundle, get the ordered list of stylsheet urls urls = [] all_bundles.each do |b| urls += b.sorted_stylesheet_entries(opts).map { |x| x.url } urls += (b.stylesheet_libs || []) end # Convert to HTML and return urls = urls.map do |url| %( <link href="#{url}" rel="stylesheet" type="text/css" />) end urls.join("\n") end # This method will return the HTML to link to all the javascripts # required by the client. If you pass no options, the current client # will be used. # # client_name = the name of the client to render or nil to use the # current :language => the language to render. defaults to @language. # def javascripts_for_client(bundle_name = nil, opts = {}) opts[:language] ||= language # Get bundle cur_bundle = bundle_name.nil? ? bundle : library.bundle_for(bundle_name) # Convert to a list of required bundles all_bundles = cur_bundle.all_required_bundles # For each bundle, get the ordered list of stylsheet urls urls = [] all_bundles.each do |b| urls += b.sorted_javascript_entries(opts).map { |x| x.url } urls += (b.javascript_libs || []) end # Convert to HTML and return urls = urls.map do |url| %( <script type="text/javascript" src="#{url}"></script>) end # Add preferred language definition... urls << %(<script type="text/javascript">String.preferredLanguage = "#{language}";</script>) urls.join("\n") end # Returns the URL for the named resource def static_url(resource_name, opts = {}) opts[:language] ||= language entry = bundle.find_resource_entry(resource_name, opts) entry.nil? ? '' : entry.url end # Localizes the passed string, using the optional passed options. def loc(string, opts = {}) opts[:language] ||= language bundle.strings_hash(opts)[string] || string end end end end
33.138298
100
0.5939
261388ba900ea91600cf444ed5b3aec5edfa63a6
1,960
#!/usr/bin/env ruby # # Sensu Logstash Handler # # Heavily inspried (er, copied from) the GELF Handler writeen by # Joe Miller. # # Designed to take sensu events, transform them into logstah JSON events # and ship them to a redis server for logstash to index. This also # generates a tag with either 'sensu-ALERT' or 'sensu-RECOVERY' so that # searching inside of logstash can be a little easier. # # Written by Zach Dunn -- @SillySophist or http://github.com/zadunn # # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. require 'rubygems' if RUBY_VERSION < '1.9.0' require 'sensu-handler' require 'redis' require 'json' require 'socket' require 'time' class LogstashHandler < Sensu::Handler def event_name @event['client']['name'] + '/' + @event['check']['name'] end def action_to_string @event['action'].eql?('resolve') ? "RESOLVE" : "ALERT" end def handle redis = Redis.new(:host => settings['logstash']['server'], :port => settings['logstash']['port']) time = Time.now.utc.iso8601 logstash_msg = { :@source => ::Socket.gethostname, :@type => settings['logstash']['type'], :@tags => ["sensu-#{action_to_string}"], :@message => @event['check']['output'], :@fields => { :host => @event['client']['name'], :timestamp => @event['check']['issued'], :address => @event['client']['address'], :check_name => @event['check']['name'], :command => @event['check']['command'], :status => @event['check']['status'], :flapping => @event['check']['flapping'], :occurrences => @event['occurrences'], :flapping => @event['check']['flapping'], :occurrences => @event['occurrences'], :action => @event['action'] }, :@timestamp => time } redis.lpush(settings['logstash']['list'], logstash_msg.to_json) end end
32.131148
101
0.602041
ff7fe985f7a8f40b084f23065cf06916405f1dda
285
#Sources: #https://www.railstutorial.org/book, Hartl Michael, 2014 #https://www.railstutorial.org/book/modeling_users class AddResetToUsers < ActiveRecord::Migration def change add_column :users, :reset_digest, :string add_column :users, :reset_sent_at, :datetime end end
25.909091
56
0.764912
d5e2ecce90ea88a52da5d71d522c17e8cd7e09d7
1,879
# # Cookbook:: ambari-chef # Spec:: default # # The MIT License (MIT) # # Copyright:: 2018, Ryan Hansohn # # 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. require 'spec_helper' describe 'ambari-chef::ambari_server_config' do context 'When all attributes are default, on Ubuntu 18.04' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'ubuntu', '18.04' it 'converges successfully' do expect { chef_run }.to_not raise_error end end context 'When all attributes are default, on CentOS 7' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'centos', '7' it 'converges successfully' do expect { chef_run }.to_not raise_error end end end
37.58
79
0.74827
26a2afd88b5962baba576f84fed53b50d9158695
426
cask 'navicat-for-oracle' do version '12.1.12' sha256 '63241b27dccb06ca54c0df5a843e8223ca817cfc33f2788b7b3c70ccc65af47d' url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_ora_en.dmg" appcast 'https://www.navicat.com/products/navicat-for-oracle-release-note' name 'Navicat for Oracle' homepage 'https://www.navicat.com/products/navicat-for-oracle' app 'Navicat for Oracle.app' end
35.5
93
0.784038
33e08b80919154272be22533e832fe7c57006e08
1,040
# frozen_string_literal: true require "rails_helper" RSpec.describe "absence_requests/edit", type: :view do let(:absence_request) do FactoryBot.create(:absence_request, absence_type: "vacation") end before do assign(:request_change_set, AbsenceRequestChangeSet.new(absence_request, start_date: Date.parse("2019-12-23"), end_date: Date.parse("2019-12-27"))) end it "renders the edit absence_request form" do without_partial_double_verification do allow(view).to receive(:current_staff_profile).and_return(absence_request.creator) render assert_select "form[action=?][method=?]", absence_request_path(absence_request), "post" do assert_select "hours-calculator[start-date=?][end-date=?]", "12/23/2019", "12/27/2019" assert_select "input-select[name=?][value=?]", "absence_request[absence_type]", absence_request.absence_type assert_select "input-text[name=?]", "absence_request[notes][content]" assert_select 'input-button[type="submit"]' end end end end
40
151
0.726923
7a44c10c1ee14cb891a99a53f26afddf37e7b7c8
1,874
=begin #EVE Swagger Interface #An OpenAPI for EVE Online OpenAPI spec version: 0.4.5 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require 'spec_helper' require 'json' require 'date' # Unit tests for Esi::OpportunitiesGroup # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'OpportunitiesGroup' do before do # run before each test @instance = Esi::OpportunitiesGroup.new end after do # run after each test end describe 'test an instance of OpportunitiesGroup' do it 'should create an instance of OpportunitiesGroup' do expect(@instance).to be_instance_of(Esi::OpportunitiesGroup) end end describe 'test attribute "connected_groups"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "description"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "group_id"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "notification"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "required_tasks"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
26.027778
103
0.717716
11685bc8ff21926b746002c075bb1c2e39fcc045
384
# frozen_string_literal: true class NewsSerializer include JSONAPI::Serializer attributes :title, :description, :short_description, :url, :topic_url, :is_active, :created_at, :updated_at belongs_to :user attribute :news_banner do |banner| Rails.application.routes.url_helpers.rails_blob_url(banner.news_banner, only_path: true) if banner.news_banner.attached? end end
32
124
0.791667
e93763fddc6f0c7a7ef4f71c04da9e2f93c16c81
1,784
require 'support/shared/integration/integration_helper' require 'chef/mixin/shell_out' describe "LWRPs" do include IntegrationSupport include Chef::Mixin::ShellOut let(:chef_dir) { File.expand_path("../../../../bin", __FILE__) } # Invoke `chef-client` as `ruby PATH/TO/chef-client`. This ensures the # following constraints are satisfied: # * Windows: windows can only run batch scripts as bare executables. Rubygems # creates batch wrappers for installed gems, but we don't have batch wrappers # in the source tree. # * Other `chef-client` in PATH: A common case is running the tests on a # machine that has omnibus chef installed. In that case we need to ensure # we're running `chef-client` from the source tree and not the external one. # cf. CHEF-4914 let(:chef_client) { "ruby '#{chef_dir}/chef-client' --minimal-ohai" } when_the_repository "has a cookbook named l-w-r-p" do before do directory 'cookbooks/l-w-r-p' do file 'resources/foo.rb', <<EOM default_action :create EOM file 'providers/foo.rb', <<EOM action :create do end EOM file 'recipes/default.rb', <<EOM l_w_r_p_foo "me" EOM end # directory 'cookbooks/x' end it "should complete with success" do file 'config/client.rb', <<EOM local_mode true cookbook_path "#{path_to('cookbooks')}" log_level :warn EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'l-w-r-p::default'", :cwd => chef_dir) actual = result.stdout.lines.map { |l| l.chomp }.join("\n") expected = <<EOM * l_w_r_p_foo[me] action create (up to date) EOM expected = expected.lines.map { |l| l.chomp }.join("\n") expect(actual).to include(expected) result.error! end end end
30.758621
138
0.676009
d5491332771f168549fc6e82e1382cbaa231b060
76
# -*- coding: utf-8 -*- module DirCat NAME='dircat' VERSION='0.2.2' end
12.666667
23
0.592105
4a6579be73a327bcbd1c8765ac93d9f5bbf14571
660
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php73Mustache < AbstractPhp73Extension init desc "Mustache PHP Extension" homepage "https://github.com/jbboehr/php-mustache#mustache" url "https://github.com/jbboehr/php-mustache/archive/v0.7.2.tar.gz" sha256 "5eb0a25d42532db98e2e9087e49db060369651b16ac1accd61415424a47561f7" head "https://github.com/jbboehr/php-mustache.git" depends_on "libmustache" def install safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/mustache.so" write_config_file if build.with? "config-file" end end
30
75
0.751515
08cef2a89041e33db8c3ff81180bce89ace08685
849
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) # vendor = File.expand_path('../vendor', __FILE__) # puts "THE VENDOR = #{vendor}" # $LOAD_PATH.unshift(vendor) unless $LOAD_PATH.include?(vendor) require 'jcarousel/version' Gem::Specification.new do |s| s.name = "jcarousel-rails" s.version = Jcarousel::Rails::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Kevin Musselman"] s.email = ["[email protected]"] s.homepage = "http://rubygems.org/gems/jquery-rails" s.summary = "Use jcarousel with Rails" s.description = "" s.license = "MIT" s.files = `git ls-files`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.require_paths = ['lib', 'vendor'] end
33.96
83
0.631331
f84f4c2bfb03aa1a83c3a01fcae02173251a62e1
729
describe "", :type => :model do it "should do something" do author = Author.new({first_name: "Alan", last_name: "Turing", homepage: "http://wikipedia.org/Alan_Turing"}) expect(author.first_name).to eq("Alan") expect(author.last_name).to eq("Turing") expect(author.homepage).to eq("http://wikipedia.org/Alan_Turing") end it "should do sometbing" do author = Author.new({first_name: "Alan", last_name: "Turing", homepage: "http://wikipedia.org/Alan_Turing"}) expect(author.name).to eq("Alan Turing") end it "if no lastname then redirect" do author = Author.new({first_name: "Alan", last_name: "", homepage: "http://wikipedia.org/Alan_Turing"}) expect(author).to_not be_valid end end
36.45
112
0.685871
bfa6129a2184ce5ed5c774c59bcc25824604ba6e
2,711
require 'rails_helper' RSpec.describe TicketPolicy do context 'permissions' do subject { TicketPolicy.new(user, ticket) } let(:user) { FactoryGirl.create(:user) } let(:project) { FactoryGirl.create(:project) } let(:ticket) { FactoryGirl.create(:ticket, project: project) } context 'for anonymous users' do let(:user) { nil } it { should_not permit_action :show } it { should_not permit_action :create } it { should_not permit_action :update } it { should_not permit_action :destroy } it { should_not permit_action :change_state } it { should_not permit_action :tag } end context 'for viewers of the project' do before { assign_role!(user, :viewer, project) } it { should permit_action :show } it { should_not permit_action :create } it { should_not permit_action :update } it { should_not permit_action :destroy } it { should_not permit_action :change_state } it { should_not permit_action :tag } end context 'for editors of the project' do before { assign_role!(user, :editor, project) } it { should permit_action :show } it { should permit_action :create } it { should_not permit_action :update } it { should_not permit_action :destroy } it { should_not permit_action :change_state } it { should_not permit_action :tag } context 'when the editor created the ticket' do before { ticket.author = user } it { should permit_action :update } end end context 'for managers of the project' do before { assign_role!(user, :manager, project) } it { should permit_action :show } it { should permit_action :create } it { should permit_action :update } it { should permit_action :destroy } it { should permit_action :change_state } it { should permit_action :tag } end context 'for managers of other projects' do before do assign_role!(user, :manager, FactoryGirl.create(:project)) end it { should_not permit_action :show } it { should_not permit_action :create } it { should_not permit_action :update } it { should_not permit_action :destroy } it { should_not permit_action :change_state } it { should_not permit_action :tag } end context 'for administrators' do let(:user) { FactoryGirl.create :user, :admin } it { should permit_action :show } it { should permit_action :create } it { should permit_action :update } it { should permit_action :destroy } it { should permit_action :change_state } it { should permit_action :tag } end end end
31.16092
66
0.653633
798dac244ed053ec37838eefb761d600394990cb
1,324
require 'fileutils' cask '[email protected]' do version '5.5.3f1,4d2f809fd6f3' sha256 '3d9174919b3fd0adc0a749f8627a18715671720d54d2eb055bcbd33cd2f8b12b' url "http://download.unity3d.com/download_unity/#{version.after_comma}/MacEditorInstaller/Unity.pkg" name 'Unity Editor' homepage 'https://unity3d.com/unity/' pkg 'Unity.pkg' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end end postflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity-#{@cask.version.before_comma}" end if File.exist? "/Applications/Unity.temp" FileUtils.move "/Applications/Unity.temp", "/Applications/Unity" end end uninstall_preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end if File.exist? "/Applications/Unity-#{@cask.version.before_comma}" FileUtils.move "/Applications/Unity-#{@cask.version.before_comma}", "/Applications/Unity" end end uninstall_postflight do if File.exist? "/Applications/Unity.temp" FileUtils.move "/Applications/Unity.temp", "/Applications/Unity" end end uninstall quit: '', pkgutil: '' end
27.583333
102
0.69864
e9a84fcba6b193431cc1e77c168791cc46878908
275
class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.string :name t.text :description t.datetime :date t.text :notes t.decimal :price t.string :image t.timestamps null: false end end end
18.333333
44
0.625455
d5b1e46c73d6351d59a53c9bc7637fd2dc3bfd94
2,075
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker config.action_mailer.default_url_option = { host: 'localhost:300' } Paperclip.options[:command_path] = "/usr/bin/convert/" config.reload_classes_only_on_change = false end
34.016393
85
0.761446
f77c686a2cf21de30d3f5b1d70974b21bd3a3291
1,652
require_relative 'node.rb' require_relative '../processors/check_assign_type.rb' require_relative '../concerns/localvar_definition_concern.rb' require_relative '../processors/convert_set_value.rb' class DabNodeSetLocalVar < DabNode include LocalvarDefinitionConcern attr_accessor :identifier attr_reader :my_type attr_reader :original_identifier check_with CheckAssignType after_init ConvertSetValue def initialize(identifier, value, type = nil) super() @identifier = identifier insert(value || DabNodeLiteralNil.new) type ||= DabNodeType.new(nil) type = type.dab_type if type.is_a? DabNodeType @my_type = type @original_identifier = identifier end def extra_dump "<#{real_identifier}> [#{index}]" end def value self[0] end def real_identifier identifier end def formatted_source(options) original_identifier + ' = ' + value.formatted_source(options) end def all_setters all_users.select { |node| node.is_a? DabNodeSetLocalVar } end def all_getters all_users.select { |node| node.is_a? DabNodeLocalVar } end def all_unscoped_setters all_unscoped_users.select { |node| node.is_a? DabNodeSetLocalVar } end def all_unscoped_getters all_unscoped_users.select { |node| node.is_a? DabNodeLocalVar } end def all_users var_definition.all_users end def unresolved_references all_users.select { |node| node.is_a? DabNodeReferenceLocalVar } end def returns_value? false end def fixup_ssa(variable, last_setter) if variable.identifier == self.identifier self else last_setter end end end
21.179487
70
0.732446
61423b1f83a6a0f5ce74a22d9a8a03358767b1b5
1,686
data_bag_name = node["sensu"]["data_bag"]["name"] enterprise_item = node["sensu"]["data_bag"]["enterprise_item"] begin unless get_sensu_state(node, "enterprise") enterprise = Sensu::Helpers.data_bag_item(enterprise_item, true, data_bag_name) set_sensu_state(node, "enterprise", enterprise) end rescue => e Chef::Log.warn("Failed to populate Sensu state with Enterprise repository credentials from data bag: " + e.inspect) end credentials = get_sensu_state(node, "enterprise", "repository", "credentials") repository_url = case credentials.nil? when true "#{node["sensu"]["enterprise"]["repo_protocol"]}://#{node["sensu"]["enterprise"]["repo_host"]}" when false "#{node["sensu"]["enterprise"]["repo_protocol"]}://#{credentials['user']}:#{credentials['password']}@#{node["sensu"]["enterprise"]["repo_host"]}" end case node["platform_family"] when "debian" include_recipe "apt" apt_repository "sensu-enterprise" do uri File.join(repository_url, "apt") key File.join(repository_url, "apt", "pubkey.gpg") distribution "sensu-enterprise" components node["sensu"]["enterprise"]["use_unstable_repo"] ? ["unstable"] : ["main"] action :add end else { "sensu-enterprise" => "noarch", "sensu-enterprise-dashboard" => "$basearch" }.each_pair do |repo_name, arch| repo = yum_repository repo_name do description repo_name channel = node["sensu"]["enterprise"]["use_unstable_repo"] ? "yum-unstable" : "yum" url "#{repository_url}/#{channel}/#{arch}/" action :add end repo.gpgcheck(false) if repo.respond_to?(:gpgcheck) end end
38.318182
164
0.661329
bf2ea652605fe01e6e51c906bc2a2c767179e186
6,713
require "devise/hooks/lockable" module Devise module Models # Handles blocking a user access after a certain number of attempts. # Lockable accepts two different strategies to unlock a user after it's # blocked: email and time. The former will send an email to the user when # the lock happens, containing a link to unlock its account. The second # will unlock the user automatically after some configured time (ie 2.hours). # It's also possible to setup lockable to use both email and time strategies. # # == Options # # Lockable adds the following options to +devise+: # # * +maximum_attempts+: how many attempts should be accepted before blocking the user. # * +lock_strategy+: lock the user account by :failed_attempts or :none. # * +unlock_strategy+: unlock the user account by :time, :email, :both or :none. # * +unlock_in+: the time you want to lock the user after to lock happens. Only available when unlock_strategy is :time or :both. # * +unlock_keys+: the keys you want to use when locking and unlocking an account # module Lockable extend ActiveSupport::Concern delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, :to => "self.class" def self.required_fields(klass) attributes = [] attributes << :failed_attempts if klass.lock_strategy_enabled?(:failed_attempts) attributes << :locked_at if klass.unlock_strategy_enabled?(:time) attributes << :unlock_token if klass.unlock_strategy_enabled?(:email) attributes end # Lock a user setting its locked_at to actual time. def lock_access! self.locked_at = Time.now.utc if unlock_strategy_enabled?(:email) generate_unlock_token! send_unlock_instructions else save(:validate => false) end end # Unlock a user by cleaning locked_at and failed_attempts. def unlock_access! self.locked_at = nil self.failed_attempts = 0 if respond_to?(:failed_attempts=) self.unlock_token = nil if respond_to?(:unlock_token=) save(:validate => false) end # Verifies whether a user is locked or not. def access_locked? !!locked_at && !lock_expired? end # Send unlock instructions by email def send_unlock_instructions send_devise_notification(:unlock_instructions) end # Resend the unlock instructions if the user is locked. def resend_unlock_token if_access_locked { send_unlock_instructions } end # Overwrites active_for_authentication? from Devise::Models::Activatable for locking purposes # by verifying whether a user is active to sign in or not based on locked? def active_for_authentication? super && !access_locked? end # Overwrites invalid_message from Devise::Models::Authenticatable to define # the correct reason for blocking the sign in. def inactive_message access_locked? ? :locked : super end # Overwrites valid_for_authentication? from Devise::Models::Authenticatable # for verifying whether a user is allowed to sign in or not. If the user # is locked, it should never be allowed. def valid_for_authentication? return super unless persisted? && lock_strategy_enabled?(:failed_attempts) # Unlock the user if the lock is expired, no matter # if the user can login or not (wrong password, etc) unlock_access! if lock_expired? if super && !access_locked? true else self.failed_attempts ||= 0 self.failed_attempts += 1 if attempts_exceeded? lock_access! unless access_locked? else save(:validate => false) end false end end def unauthenticated_message # If set to paranoid mode, do not show the locked message because it # leaks the existence of an account. if Devise.paranoid super elsif lock_strategy_enabled?(:failed_attempts) && attempts_exceeded? :locked else super end end protected def attempts_exceeded? self.failed_attempts > self.class.maximum_attempts end # Generates unlock token def generate_unlock_token self.unlock_token = self.class.unlock_token end def generate_unlock_token! generate_unlock_token && save(:validate => false) end # Tells if the lock is expired if :time unlock strategy is active def lock_expired? if unlock_strategy_enabled?(:time) locked_at && locked_at < self.class.unlock_in.ago else false end end # Checks whether the record is locked or not, yielding to the block # if it's locked, otherwise adds an error to email. def if_access_locked if access_locked? yield else self.errors.add(:email, :not_locked) false end end module ClassMethods # Attempt to find a user by its email. If a record is found, send new # unlock instructions to it. If not user is found, returns a new user # with an email not found error. # Options must contain the user email def send_unlock_instructions(attributes={}) lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found) lockable.resend_unlock_token if lockable.persisted? lockable end # Find a user by its unlock token and try to unlock it. # If no user is found, returns a new user with an error. # If the user is not locked, creates an error for the user # Options must have the unlock_token def unlock_access_by_token(unlock_token) lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token) lockable.unlock_access! if lockable.persisted? lockable end # Is the unlock enabled for the given unlock strategy? def unlock_strategy_enabled?(strategy) [:both, strategy].include?(self.unlock_strategy) end # Is the lock enabled for the given lock strategy? def lock_strategy_enabled?(strategy) self.lock_strategy == strategy end def unlock_token Devise.friendly_token end Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys) end end end end
34.603093
135
0.647252
5de9409ad1ed2fde247260cf8ee41385be526b51
442
require 'shellwords' class MiningClass @file_path = nil def initialize(file_path) @file_path = file_path end def apache_referrer #sh = Shellwords.escape("cat /var/log/nginx/access.log | gawk -F\\\" '$4 !~ \"http://blog.kz-dev.com\" && $4 != \"-\" {system(\"echo \" $4)}' | awk -F/ '{print $3}' | sort | uniq -c | sort -n -r") sh = Shellwords.escape("cat /var/log/nginx/access.log | grep localhost") system(sh) end end
31.571429
200
0.61991
b9ce327b2ce54978f4569abee828c44e0745707a
579
class CreatePages < ActiveRecord::Migration def change create_table :pages do |t| t.string :name, null:false t.integer :kind, null:false t.integer :owner_id, null:false t.boolean :active t.string :sector t.string :no_employees t.string :links t.string :description t.string :contacts t.string :coordinates t.string :location t.string :lookingfor t.string :fbpage t.timestamps null: false t.string :slug, null: false end add_index :pages, :slug, :unique => true end end
21.444444
44
0.626943
39a82dec98bfed358366087c4cc77c009f8b31e5
202
class CreateLocations < ActiveRecord::Migration[6.0] def change create_table :locations do |t| t.string :name t.decimal :lat t.decimal :lng t.timestamps end end end
16.833333
52
0.638614
014b24313b3e214c79bba1f7149781e01f97c735
1,050
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') module Rack::Bug describe TimerPanel do before do header "rack-bug.panel_classes", [TimerPanel] end describe "heading" do it "displays the elapsed time" do response = get "/" response.should have_heading(TIME_MS_REGEXP) end end describe "content" do it "displays the user CPU time" do response = get "/" response.should have_row("#timer", "User CPU time", TIME_MS_REGEXP) end it "displays the system CPU time" do response = get "/" response.should have_row("#timer", "System CPU time", TIME_MS_REGEXP) end it "displays the total CPU time" do response = get "/" response.should have_row("#timer", "Total CPU time", TIME_MS_REGEXP) end it "displays the elapsed time" do response = get "/" response.should have_row("#timer", "Elapsed time", TIME_MS_REGEXP) end end end end
27.631579
77
0.601905
e96422ae787d629f258abdac1656b425cfae791a
630
# frozen_string_literal: true require_relative '../token' module Engine module Step module G18AL class Token < Token def place_token(entity, city, token, connected: true, extra: false, special_ability: nil) super @game.abilities(entity, :assign_hexes) do |ability| next unless ability.hexes.one? if city.hex.name == ability.hexes.first @log << "#{entity.name} receives $100 - #{ability.description}" entity.cash += 100 entity.remove_ability(ability) end end end end end end end
24.230769
97
0.58254
1115a5e7f259f60665b22276855197353d61f6dd
1,801
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. require "json" package = JSON.parse(File.read(File.join(__dir__, "..", "..", "package.json"))) version = package['version'] source = { :git => 'https://github.com/facebook/react-native.git' } if version == '1000.0.0' # This is an unpublished version, use the latest commit hash of the react-native repo, which we’re presumably in. source[:commit] = `git rev-parse HEAD`.strip else source[:tag] = "v#{version}" end folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' folly_version = '2018.10.22.00' Pod::Spec.new do |s| s.name = "RCTTypeSafety" s.version = version s.summary = "-" # TODO s.homepage = "http://facebook.github.io/react-native/" s.license = package["license"] s.author = "Facebook, Inc. and its affiliates" s.platforms = { :ios => "10.0", :tvos => "10.0" } s.compiler_flags = folly_compiler_flags s.source = source s.source_files = "**/*.{c,h,m,mm,cpp}" s.header_dir = "RCTTypeSafety" s.pod_target_xcconfig = { "USE_HEADERMAP" => "YES", "CLANG_CXX_LANGUAGE_STANDARD" => "c++14", "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/Libraries/TypeSafety\" \"$(PODS_ROOT)/Folly\"" } s.dependency "FBLazyVector", version s.dependency "Folly", folly_version s.dependency "RCTRequired", version s.dependency "React-Core", version end
40.022222
128
0.589117