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
08ddcbe1b9fe31f3cb1935c90c45aea016c2c442
199
class Filedrop < Cask version :latest sha256 :no_check url 'https://commondatastorage.googleapis.com/filedropme/Filedrop.dmg' homepage 'http://www.filedropme.com/' app 'Filedrop.app' end
19.9
72
0.743719
878a81e04b7865eb34b480212eef552b8c40cd85
2,900
# frozen_string_literal: true # Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require 'spec_helper' module FatFreeCrm describe EntityObserver do before do allow(Setting).to receive(:host).and_return('http://www.example.com') allow(PaperTrail.request).to receive(:whodunnit).and_return(assigner) end %i[account contact lead opportunity].each do |entity_type| describe "on creation of #{entity_type}" do let(:assignee) { create(:user) } let(:assigner) { create(:user) } let!(:entity) { build(entity_type, user: assigner, assignee: assignee) } let(:mail) { double('mail', deliver_now: true) } after :each do entity.save end it "sends notification to the assigned user for entity" do expect(UserMailer).to receive(:assigned_entity_notification).with(entity, assigner).and_return(mail) end it "does not notify anyone if the entity is created and assigned to no-one" do entity.assignee = nil expect(UserMailer).not_to receive(:assigned_entity_notification) end it "does not notify me if I have created an entity for myself" do entity.assignee = entity.user = assigner expect(UserMailer).not_to receive(:assigned_entity_notification) end it "does not notify me if Setting.host has not been set" do allow(Setting).to receive(:host).and_return('') expect(UserMailer).not_to receive(:assigned_entity_notification) end end describe "on update of #{entity_type}" do let(:assignee) { create(:user) } let(:assigner) { create(:user) } let!(:entity) { create(entity_type, user: create(:user)) } let(:mail) { double('mail', deliver_now: true) } it "notifies the new owner if the entity is re-assigned" do expect(UserMailer).to receive(:assigned_entity_notification).with(entity, assigner).and_return(mail) entity.update(assignee: assignee) end it "does not notify the owner if the entity is not re-assigned" do expect(UserMailer).not_to receive(:assigned_entity_notification) entity.touch end it "does not notify anyone if the entity becomes unassigned" do expect(UserMailer).not_to receive(:assigned_entity_notification) entity.update(assignee: nil) end it "does not notify me if I re-assign an entity to myself" do expect(UserMailer).not_to receive(:assigned_entity_notification) entity.update(assignee: assigner) end end end end end
37.662338
110
0.643103
0303c1d7fe268679586c216ff9b7ee5cacb03dc1
3,633
require 'multi_json' # require 'nokogiri' require 'open-uri/cached' OpenURI::Cache.cache_path = 'tmp/open-uri' # transparent caching # core/stdlib extensions # classes class CBRadio def pie(array, container, pa, percs) x = 0 y = array.length - 1 names = [] while x <= y hash = array[x] name = hash['name'] val = hash['count'] names.push name container.push val.to_f # let's float these bitches x += 1 end total = container.reduce(:+).to_f x = 0 y = container.length - 1 while x <= y val = container[x] p = val / total p = (p * 100).round # pies are round pa.push p x += 1 end if pa.reduce(:+) > 100 then fix = pa.reduce(:+) - 100; pa[0] = pa[0] - fix; end # make sure the sum == 100 if pa.reduce(:+) < 100 then fix = 100 - pa.reduce(:+); pa[0] = pa[0] + fix; end x = 0 y = array.length - 1 while x <= y percs[names[x]] = pa[x] x += 1 end end def perc(x, y, earned, badge) while x <= y z = badge[x] if z['earned'] == true then earned.push z; end x += 1 end end def badge(x, y, earned) b = earned[x] bname = b['name']; bdesc = b['description']; blink = b['link']; bilink = b['image_link']; bdate = b['earned_date']; bd = Date.parse(bdate); blevel = b['level']; btrait = b['trait']; btdesc = b['trait_description']; bacc = b['account']; bissuer = bacc['name']; puts "Badge: #{bname}" puts "Description: #{bdesc}" puts "Link: #{blink}" puts "Image: #{bilink}" puts "Date Earned: #{bd}" puts "Level: #{blevel}" puts "Trait: #{btrait}" puts "Trait Description: #{btdesc}" puts "Badge Issuer: #{bissuer}\n\n" end end data = File.readlines('json/weirdpercent.json') data = data.join mjl = MultiJson.load(data) # single values first name = mjl['name']; uname = mjl['username']; title = mjl['title']; loc = mjl['location']; web = mjl['website_link']; bio = mjl['bio']; since = mjl['created']; upd = mjl['updated']; views = mjl['views']; rank = mjl['rank']; link = mjl['link']; ghash = mjl['gravatar_hash']; onebit = mjl['one_bit_badges']; eightbit = mjl['eight_bit_badges']; sixteenbit = mjl['sixteen_bit_badges']; thirtytwobit = mjl['thirty_two_bit_badges']; sixtyfourbit = mjl['sixty_four_bit_badges']; followers = mjl['follower_count']; following = mjl['following_count'] # now the arrays tops = mjl['top_skills']; topl = mjl['top_languages']; tope = mjl['top_environments']; topf = mjl['top_frameworks']; topto = mjl['top_tools']; topi = mjl['top_interests']; toptr = mjl['top_traits']; topa = mjl['top_areas']; badge = mjl['badges']; account = mjl['accounts']; sumtops = []; sumtopl = []; sumtope = []; sumtopf = []; sumtopto = []; sumtopi = []; sumtoptr = []; sumtopa = []; cbr = CBRadio.new # let's pie-chart these groups pa = []; percs = {}; cbr.pie(tops, sumtops, pa, percs); skills = percs; pa = []; percs = {}; cbr.pie(topl, sumtopl, pa, percs); languages = percs; pa = []; percs = {}; cbr.pie(tope, sumtope, pa, percs); environments = percs; pa = []; percs = {}; cbr.pie(topf, sumtopf, pa, percs); frameworks = percs; pa = []; percs = {}; cbr.pie(topto, sumtopto, pa, percs); tools = percs; pa = []; percs = {}; cbr.pie(topi, sumtopi, pa, percs); interests = percs; pa = []; percs = {}; cbr.pie(toptr, sumtoptr, pa, percs); traits = percs; pa = []; percs = {}; cbr.pie(topa, sumtopa, pa, percs); areas = percs; # now for the badges badge = mjl['badges'] x = 0 y = badge.length - 1 earned = [] cbr.perc(x, y, earned, badge) x = 0 y = earned.length - 1 while x <= y cbr.badge(x, y, earned) x += 1 end
37.84375
143
0.59978
2128c048cd9f96bcd37f8416c8399f6cda8c771f
5,696
module Formatter module Csv class AnnotationForCsv attr_reader :classification, :annotation, :cache, :workflow_information def initialize(classification, annotation, cache) @classification = classification @annotation = annotation.dup.with_indifferent_access @current = @annotation.dup @cache = cache @workflow_information = WorkflowInformation.new(cache, classification.workflow, classification.workflow_version) end def to_h task = workflow_information.task(annotation['task']) case task['type'] when 'drawing' drawing(task) when /single|multiple|shortcut/ simple(task) when 'text' text(task) when 'dropdown' dropdown(task) when 'combo' combo # combo iterates over the submitted task annotation values else @annotation end rescue ClassificationDumpCache::MissingWorkflowVersion => error Honeybadger.notify(error, context: {classification_id: classification.id}) @annotation end private def drawing(task_info) {}.tap do |new_anno| new_anno['task'] = @current['task'] new_anno['task_label'] = task_label(task_info) added_tool_lables = Array.wrap(@current["value"]).map do |drawn_item| if drawn_item.is_a?(Hash) tool_label = tool_label(task_info, drawn_item) drawn_item.merge("tool_label" => tool_label) else drawn_item end end new_anno["value"] = added_tool_lables end end def simple(task_info) {}.tap do |new_anno| new_anno['task'] = @current['task'] new_anno['task_label'] = task_label(task_info) new_anno['value'] = if %w[multiple shortcut].include?(task_info['type']) answer_labels else answer_labels.first end end end def text(task_info) {}.tap do |new_anno| new_anno['task'] = @current['task'] new_anno['value'] = @current['value'] new_anno['task_label'] = task_label(task_info) end end def combo {}.tap do |new_anno| new_anno['task'] = annotation['task'] new_anno['task_label'] = nil new_anno['value'] ||= [] Array.wrap(annotation['value']).each do |subtask| @current = subtask task_info = get_task_info(subtask) new_anno['value'].push case task_info['type'] when "drawing" drawing(task_info) when "single", "multiple" simple(task_info) when "text" text(task_info) when "combo" { error: "combo tasks cannot be nested" } when "dropdown" dropdown(task_info) else @current end end end end def dropdown(task_info) {}.tap do |new_anno| new_anno['task'] = @current['task'] new_anno['value'] = task_info['selects'].map.with_index do |selects, index| dropdown_process_selects(selects, index) end end end def dropdown_process_selects(selects, index) answer_value = nil if answer = @current['value'][index] answer_value = answer['value'] end {}.tap do |drop_anno| drop_anno['select_label'] = selects['title'] if selects['allowCreate'] drop_anno['option'] = false drop_anno['value'] = answer_value end if selected_option = dropdown_find_selected_option(selects, answer_value) drop_anno['option'] = true drop_anno['value'] = selected_option['value'] drop_anno['label'] = workflow_information.string(selected_option['label']) end end end def dropdown_find_selected_option(selects, answer_value) selects['options'].each do |key, options| options.each do |option| return option if option['value'] == answer_value end end nil end def task_label(task_info) workflow_information.string(task_info['question'] || task_info['instruction']) end def tool_label(task_info, tool) tool_index = tool["tool"] have_tool_lookup_info = !!(task_info["tools"] && tool_index) known_tool = have_tool_lookup_info && task_info["tools"][tool_index] workflow_information.string(known_tool['label']) if known_tool end def answer_labels Array.wrap(@current["value"]).map do |answer_idx| begin task_answer = workflow_at_version.tasks[@current['task']]['answers'][answer_idx] answer_string = task_answer['label'] workflow_information.string(answer_string) rescue TypeError, NoMethodError "unknown answer label" end end end def workflow_at_version workflow_information.at_version end # used in combo task to protect against invalid annotations # i.e. bad annotation data from tropical sweden project # https://github.com/zooniverse/panoptes/blob/5928d94cffb424e68aec480c619271d0783bb0dc/spec/lib/formatter/csv/annotation_for_csv_spec.rb#L196-L210 def get_task_info(task) task_key = task['task'] workflow_information.task(task_key) rescue TypeError {} end end end end
31.469613
152
0.581812
abe8e5958fd3202a30a9a5e22a83e45aa6554e11
2,240
class Pulseaudio < Formula desc "Sound system for POSIX OSes" homepage "https://wiki.freedesktop.org/www/Software/PulseAudio/" url "https://www.freedesktop.org/software/pulseaudio/releases/pulseaudio-14.2.tar.xz" sha256 "75d3f7742c1ae449049a4c88900e454b8b350ecaa8c544f3488a2562a9ff66f1" license all_of: ["GPL-2.0-or-later", "LGPL-2.1-or-later", "BSD-3-Clause"] # The regex here avoids x.99 releases, as they're pre-release versions. livecheck do url :stable regex(/href=["']?pulseaudio[._-]v?((?!\d+\.9\d+)\d+(?:\.\d+)+)\.t/i) end bottle do sha256 arm64_big_sur: "efcbf144da932e05394e9768bf27dfa1908dbb17f4b7c52f49e56c791dd51860" sha256 big_sur: "79684acaac85e9b1b7de55fc7659844d9508c6264faa0aac311e0d8eaf4056b0" sha256 catalina: "e1c181ae27f945ceee403e2e2ec80f44aebd52ac44b8e63140c1c9d2083a643b" sha256 mojave: "ae0d2ec72fc10a895c7efc330174abef08458576ed847fb4547301a2d8cc147e" end head do url "https://gitlab.freedesktop.org/pulseaudio/pulseaudio.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "gettext" => :build depends_on "intltool" => :build end depends_on "pkg-config" => :build depends_on "json-c" depends_on "libsndfile" depends_on "libsoxr" depends_on "libtool" depends_on "[email protected]" depends_on "speexdsp" uses_from_macos "perl" => :build uses_from_macos "expat" uses_from_macos "m4" def install args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --enable-coreaudio-output --disable-neon-opt --disable-nls --disable-x11 --with-mac-sysroot=#{MacOS.sdk_path} --with-mac-version-min=#{MacOS.version} ] if build.head? # autogen.sh runs bootstrap.sh then ./configure system "./autogen.sh", *args else system "./configure", *args end system "make", "install" end service do run [opt_bin/"pulseaudio", "--exit-idle-time=-1", "--verbose"] keep_alive true log_path var/"log/pulseaudio.log" error_log_path var/"log/pulseaudio.log" end test do assert_match "module-sine", shell_output("#{bin}/pulseaudio --dump-modules") end end
29.866667
92
0.692411
1a8f58d0e40d59ea47c4ed4a66fb7e6da90c4827
284
execute 'apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3F0F56A8' do not_if "apt-key list | grep '/3F0F56A8'" end remote_file '/etc/apt/sources.list.d/sorah-rbpkg.list' do owner 'root' group 'root' mode '644' notifies :run, 'execute[apt-get update]' end
25.818182
87
0.704225
e9d8f7d178c2eb5409ffe539642fde84c342b1a6
1,626
# -*- encoding: utf-8 -*- # stub: aws-sdk-s3control 1.4.0 ruby lib Gem::Specification.new do |s| s.name = "aws-sdk-s3control".freeze s.version = "1.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "changelog_uri" => "https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-s3control/CHANGELOG.md", "source_code_uri" => "https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-s3control" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Amazon Web Services".freeze] s.date = "2019-03-21" s.description = "Official AWS Ruby gem for AWS S3 Control. This gem is part of the AWS SDK for Ruby.".freeze s.email = ["[email protected]".freeze] s.homepage = "http://github.com/aws/aws-sdk-ruby".freeze s.licenses = ["Apache-2.0".freeze] s.rubygems_version = "3.0.6".freeze s.summary = "AWS SDK for Ruby - AWS S3 Control".freeze s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<aws-sigv4>.freeze, ["~> 1.0"]) s.add_runtime_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) else s.add_dependency(%q<aws-sigv4>.freeze, ["~> 1.0"]) s.add_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) end else s.add_dependency(%q<aws-sigv4>.freeze, ["~> 1.0"]) s.add_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) end end
43.945946
246
0.663592
01af5f462416a208ac74a2240fcd9a389910d0a0
300
name 'waf_testbed' maintainer 'Team Security' maintainer_email '[email protected]' license 'apache' description 'Installs/Configures waf_testbed' long_description 'Installs/Configures waf_testbed' version '0.2.0' depends 'apt', '~> 3.0.0' depends 'httpd' depends 'git' depends 'poise-python'
23.076923
50
0.783333
1d3852a2990dad63cd1238f40e767753dd72bb00
136
require 'test_helper' class InstancesControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
17
58
0.735294
282d7f9bddafad068eac67d949993cf84444d90d
102
# frozen_string_literal: true class DraftNoteSerializer < BaseSerializer entity DraftNoteEntity end
20.4
42
0.852941
79abd9c4562c974560ea8f977a2766060b79d4ef
910
# frozen_string_literal: false class Time # Deserializes JSON string by converting time since epoch to Time def self.json_create(object) if (usec = object.delete('u')) # used to be tv_usec -> tv_nsec object['n'] = usec * 1000 end if method_defined?(:tv_nsec) at(object['s'], Rational(object['n'], 1000)) else at(object['s'], object['n'] / 1000) end end # Returns a hash, that will be turned into a JSON object and represent this # object. def as_json(*) nanoseconds = [tv_usec * 1000] respond_to?(:tv_nsec) && nanoseconds << tv_nsec nanoseconds = nanoseconds.max { JSON.create_id => self.class.name, 's' => tv_sec, 'n' => nanoseconds } end # Stores class name (Time) with number of seconds since epoch and number of # microseconds for Time as JSON string def to_json(*args) as_json.to_json(*args) end end
26
77
0.643956
26f64f08931495b7be0e0d85fb6496ad5287b4fb
1,590
require 'simp/cli/config/items/data/cli_network_netmask' require 'simp/cli/config/items/data/cli_network_interface' require 'rspec/its' require_relative '../spec_helper' describe Simp::Cli::Config::Item::CliNetworkNetmask do before :each do @ci = Simp::Cli::Config::Item::CliNetworkNetmask.new end describe "#os_value" do it "returns the netmask address of a valid interface" do nic = Simp::Cli::Config::Item::CliNetworkInterface.new nic.value = 'lo' @ci.config_items = { nic.key => nic } expect( @ci.os_value ).to eq '255.0.0.0' end it "returns nil for an invalid interface" do nic = Simp::Cli::Config::Item::CliNetworkInterface.new nic.value = 'eth_oops' @ci.config_items = { nic.key => nic } expect( @ci.os_value ).to be_nil # TODO: verify only print outs 1 warning when called more than once expect( @ci.os_value ).to be_nil end end describe "#validate" do it "validates netmasks" do expect( @ci.validate '255.255.255.0' ).to eq true expect( @ci.validate '255.254.0.0' ).to eq true expect( @ci.validate '192.0.0.0' ).to eq true end it "doesn't validate bad netmasks" do expect( @ci.validate '999.999.999.999' ).to eq false expect( @ci.validate '255.999.0.0' ).to eq false expect( @ci.validate '255.0.255.0' ).to eq false expect( @ci.validate '0.255.0.0' ).to eq false expect( @ci.validate nil ).to eq false expect( @ci.validate false ).to eq false end end it_behaves_like "a child of Simp::Cli::Config::Item" end
32.44898
73
0.651572
ede2ec4045bca7ea5d211a0c4572fae7f37566c5
1,033
module MCollective module Agent # Discovery agent for The Marionette Collective # # Released under the Apache License, Version 2 class Discovery attr_reader :timeout, :meta def initialize config = Config.instance.pluginconf @timeout = 5 @timeout = config["discovery.timeout"].to_i if config.include?("discovery.timeout") @meta = {:license => "Apache License, Version 2", :author => "R.I.Pienaar <[email protected]>", :timeout => @timeout, :name => "Discovery Agent", :version => MCollective.version, :url => "http://www.marionette-collective.org", :description => "MCollective Discovery Agent"} end def handlemsg(msg, stomp) reply = "unknown request" case msg[:body] when "ping" reply = "pong" else reply = "Unknown Request: #{msg[:body]}" end reply end end end end
25.825
91
0.54211
62e00d0bbee059c05e92d0491c8bf47ef5ccc197
7,047
require 'google/api_client' require 'googleauth' require 'yaml' Faraday.default_adapter = :httpclient module ApiRequestLogger class GoogleApi DATASET_ID = Rails.env def initialize @authorized = false end def config @config = YAML.load_file(File.join(Rails.root, 'config', 'ga_config.yml')) end def client @client ||= Google::APIClient.new( application_name: config['application_name'], application_version: config['application_version'] ) end def bigquery @bigquery = client.discovered_api('bigquery','v2') end def storage @storage = client.discovered_api('storage', 'v1') end def authorize scopes = ['https://www.googleapis.com/auth/devstorage.read_write', 'https://www.googleapis.com/auth/bigquery'] client.authorization = Google::Auth.get_application_default(scopes) client.authorization.fetch_access_token! @authorized = true @authorized_at = Time.current end def upload_file(filename, bucket, remote_filename, mime_type= 'application/x-gzip') resumable_media = Google::APIClient::UploadIO.new(filename, mime_type) resumable_result = execute( :api_method => storage.objects.insert, :media => resumable_media, :parameters => { :uploadType => 'resumable', :bucket => bucket, :name => remote_filename }, :body_object => { :contentType => mime_type } ) upload = resumable_result.resumable_upload if upload.resumable? execute(upload) end upload end def insert_data(file_name, bucket, table_id, schema, format='NEWLINE_DELIMITED_JSON', write_disposition = 'WRITE_APPEND') job_data = { configuration: { load: { sourceUris: ["gs://#{bucket}/#{file_name}"], sourceFormat: format, writeDisposition: write_disposition, allowQuotedNewlines: true, schema: { fields: schema }, destinationTable: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id } } } } response = execute( api_method: bigquery.jobs.insert, parameters: { projectId: config['project_id'] }, body_object: job_data ) MultiJson.load( response.body ) end # Streams data into BigQuery def stream_data(table_id, data, schema) get_table_response = get_table(table_id) if get_table_response["error"]["code"] == 404 create_table(table_id, schema) end job_data = { kind: 'bigquery#tableDataInsertAllRequest', rows: [ sanitize_data(data) ] } response = execute( api_method: bigquery.tabledata.insert_all, parameters: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id }, body_object: job_data ) MultiJson.load( response.body ) end def delete_table(table_id) response = execute( api_method: bigquery.tables.delete, parameters: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id } ) MultiJson.load( response.body ) end def get_table(table_id) response = execute( api_method: bigquery.tables.get, parameters: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id } ) MultiJson.load( response.body ) end def create_table(table_id, schema) table_data = { tableReference: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id }, schema: { fields: schema } } response = execute( api_method: bigquery.tables.insert, parameters: { projectId: config['project_id'], datasetId: DATASET_ID }, body_object: table_data ) MultiJson.load( response.body ) end # Schema updates only allow you to append fields or relax field modes (e.g., required -> optional). # You can't change field names or types, and you can't reorder them. – Jeremy Condit def patch_table_schema(table_id, old_schema, new_schema) old_schema.merge!(new_schema) { |key, old, new| old } table_data = { schema: { fields: old_schema } } response = execute( api_method: bigquery.tables.patch, parameters: { projectId: config['project_id'], datasetId: DATASET_ID, tableId: table_id }, body_object: table_data ) MultiJson.load( response.body ) end def get_job(job_id) response = execute( :api_method => bigquery.jobs.get, :parameters => { :projectId => config['project_id'], :jobId => job_id } ) MultiJson.load( response.body ) end def get_jobs_list(status) response = execute( api_method: bigquery.jobs.list, parameters: { projectId: config['project_id'], projection: 'minimal', # Does not include the job configuration stateFilter: status } ) MultiJson.load( response.body ) end def execute(options = {}) authorize if @authorized == false || Time.current - @authorized_at > 3600 client.execute(options) end def query(sql) body = { :kind => 'bigquery#queryRequest', :query => sql, :defaultDataset => { :datasetId => Rails.env, :projectId => config['project_id'] } } response = execute( :api_method => bigquery.jobs.query, :parameters => { :projectId => config['project_id'] }, :body_object => body ) result = MultiJson.load( response.body ) beautify_result(result) end def beautify_result(result) fields = result['schema']['fields'] result['rows'].collect do |row| ob = {} fields.each_with_index do |x, y| ob[x['name'].to_sym] = case x['type'] when 'TIMESTAMP' DateTime.strptime(row['f'][y]['v'].to_f.to_s, '%s').in_time_zone('Sydney') when 'INTEGER' row['f'][y]['v'].to_i else row['f'][y]['v'] end end ob end rescue result end def get_query_results(job_id) response = execute( :api_method => bigquery.jobs.get_query_results, :parameters => { :jobId => job_id, :projectId => config['project_id'] } ) result = MultiJson.load( response.body ) beautify_result(result) end def sanitize_data(data) { json: JSON.parse(data) } end end end
24.63986
125
0.572584
915e62108ffd2f0f6d97c891174e6dae8b010ca5
1,794
MsAuthoring::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
30.40678
91
0.658863
03539713bb6405bba2f0d663fef4a66cb709216c
864
def glob_from_array(array) "{" + array.join(",") + "}" end namespace :import do desc "Import Organisations, Sites, Hosts, Hits and update DNS details" task :all, [:bucket] => [ "import:all:orgs_sites_hosts", "import:all:hits", "import:dns_details", ] namespace :all do desc "Import all Organisations, Sites and Hosts" task orgs_sites_hosts: :environment do patterns = [ "data/transition-config/data/transition-sites/*.yml", ] Rake::Task["import:orgs_sites_hosts"].invoke(glob_from_array(patterns)) end desc "Import all hits from s3" task :hits, [:bucket] => :environment do |_, args| Transition::Import::Hits.from_s3!(args[:bucket]) Transition::Import::DailyHitTotals.from_hits! Transition::Import::HitsMappingsRelations.refresh! end end end
27.870968
77
0.645833
6a4e3266509f09f493519d13cb73d0644ace4a30
85
# encoding: utf-8 # copyright: 2018, The Authors include_controls 'no_such_profile'
17
34
0.776471
21797bf988d84d2997627b3b1dc8541558a2d1d6
322
# frozen_string_literal: true module Gitlab module MarkdownCache # Increment this number every time the renderer changes its output CACHE_COMMONMARK_VERSION = 23 CACHE_COMMONMARK_VERSION_START = 10 BaseError = Class.new(StandardError) UnsupportedClassError = Class.new(BaseError) end end
24.769231
70
0.754658
e80a0a498b87cabbf9a2d9f013d7a8b75eadc084
1,123
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Auxiliary include Msf::Exploit::Remote::Tcp include Msf::Auxiliary::Scanner include Msf::Auxiliary::Report def initialize super( 'Name' => 'EMC AlphaStor Device Manager Service', 'Description' => 'This module queries the remote host for the EMC Alphastor Device Management Service.', 'Author' => 'MC', 'License' => MSF_LICENSE ) register_options([Opt::RPORT(3000),]) end def run_host(ip) connect pkt = "\x68" + Rex::Text.rand_text_alphanumeric(5) + "\x00" * 512 sock.put(pkt) select(nil,nil,nil,0.25) data = sock.get_once if ( data and data =~ /rrobotd:rrobotd/ ) print_good("Host #{ip} is running the EMC AlphaStor Device Manager.") report_service(:host => rhost, :port => rport, :name => "emc-manager", :info => data) else print_error("Host #{ip} is not running the service...") end disconnect end end
24.413043
113
0.633126
287f6e4e629523a2b101e7038624c963c8741c9b
492
class AttendancesController < ApplicationController def create @attendance = Attendance.new(attended_event_id: params[:attended_event_id], attendee_id: params[:attendee_id]) respond_to do |format| if @attendance.save format.html do redirect_to event_path(@attendance.attended_event_id), notice: 'You registered succesfully to this event.' end else format.html { render :new, status: :unprocessable_entity } end end end end
30.75
116
0.703252
18a209dcea2025abb0f83d1c9b0cf30dd1531458
57,542
require 'set' require 'active_support/json' module ActionView module Helpers # Prototype[http://www.prototypejs.org/] is a JavaScript library that provides # DOM[http://en.wikipedia.org/wiki/Document_Object_Model] manipulation, # Ajax[http://www.adaptivepath.com/publications/essays/archives/000385.php] # functionality, and more traditional object-oriented facilities for JavaScript. # This module provides a set of helpers to make it more convenient to call # functions from Prototype using Rails, including functionality to call remote # Rails methods (that is, making a background request to a Rails action) using Ajax. # This means that you can call actions in your controllers without # reloading the page, but still update certain parts of it using # injections into the DOM. A common use case is having a form that adds # a new element to a list without reloading the page or updating a shopping # cart total when a new item is added. # # == Usage # To be able to use these helpers, you must first include the Prototype # JavaScript framework in your pages. # # javascript_include_tag 'prototype' # # (See the documentation for # ActionView::Helpers::JavaScriptHelper for more information on including # this and other JavaScript files in your Rails templates.) # # Now you're ready to call a remote action either through a link... # # link_to_remote "Add to cart", # :url => { :action => "add", :id => product.id }, # :update => { :success => "cart", :failure => "error" } # # ...through a form... # # <% form_remote_tag :url => '/shipping' do -%> # <div><%= submit_tag 'Recalculate Shipping' %></div> # <% end -%> # # ...periodically... # # periodically_call_remote(:url => 'update', :frequency => '5', :update => 'ticker') # # ...or through an observer (i.e., a form or field that is observed and calls a remote # action when changed). # # <%= observe_field(:searchbox, # :url => { :action => :live_search }), # :frequency => 0.5, # :update => :hits, # :with => 'query' # %> # # As you can see, there are numerous ways to use Prototype's Ajax functions (and actually more than # are listed here); check out the documentation for each method to find out more about its usage and options. # # === Common Options # See link_to_remote for documentation of options common to all Ajax # helpers; any of the options specified by link_to_remote can be used # by the other helpers. # # == Designing your Rails actions for Ajax # When building your action handlers (that is, the Rails actions that receive your background requests), it's # important to remember a few things. First, whatever your action would normally return to the browser, it will # return to the Ajax call. As such, you typically don't want to render with a layout. This call will cause # the layout to be transmitted back to your page, and, if you have a full HTML/CSS, will likely mess a lot of things up. # You can turn the layout off on particular actions by doing the following: # # class SiteController < ActionController::Base # layout "standard", :except => [:ajax_method, :more_ajax, :another_ajax] # end # # Optionally, you could do this in the method you wish to lack a layout: # # render :layout => false # # You can tell the type of request from within your action using the <tt>request.xhr?</tt> (XmlHttpRequest, the # method that Ajax uses to make background requests) method. # def name # # Is this an XmlHttpRequest request? # if (request.xhr?) # render :text => @name.to_s # else # # No? Then render an action. # render :action => 'view_attribute', :attr => @name # end # end # # The else clause can be left off and the current action will render with full layout and template. An extension # to this solution was posted to Ryan Heneise's blog at ArtOfMission["http://www.artofmission.com/"]. # # layout proc{ |c| c.request.xhr? ? false : "application" } # # Dropping this in your ApplicationController turns the layout off for every request that is an "xhr" request. # # If you are just returning a little data or don't want to build a template for your output, you may opt to simply # render text output, like this: # # render :text => 'Return this from my method!' # # Since whatever the method returns is injected into the DOM, this will simply inject some text (or HTML, if you # tell it to). This is usually how small updates, such updating a cart total or a file count, are handled. # # == Updating multiple elements # See JavaScriptGenerator for information on updating multiple elements # on the page in an Ajax response. module PrototypeHelper unless const_defined? :CALLBACKS CALLBACKS = Set.new([ :uninitialized, :loading, :loaded, :interactive, :complete, :failure, :success ] + (100..599).to_a) AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url, :asynchronous, :method, :insertion, :position, :form, :with, :update, :script, :type ]).merge(CALLBACKS) end # Returns a link to a remote action defined by <tt>options[:url]</tt> # (using the url_for format) that's called in the background using # XMLHttpRequest. The result of that request can then be inserted into a # DOM object whose id can be specified with <tt>options[:update]</tt>. # Usually, the result would be a partial prepared by the controller with # render :partial. # # Examples: # # Generates: <a href="#" onclick="new Ajax.Updater('posts', '/blog/destroy/3', {asynchronous:true, evalScripts:true}); # # return false;">Delete this post</a> # link_to_remote "Delete this post", :update => "posts", # :url => { :action => "destroy", :id => post.id } # # # Generates: <a href="#" onclick="new Ajax.Updater('emails', '/mail/list_emails', {asynchronous:true, evalScripts:true}); # # return false;"><img alt="Refresh" src="/images/refresh.png?" /></a> # link_to_remote(image_tag("refresh"), :update => "emails", # :url => { :action => "list_emails" }) # # You can override the generated HTML options by specifying a hash in # <tt>options[:html]</tt>. # # link_to_remote "Delete this post", :update => "posts", # :url => post_url(@post), :method => :delete, # :html => { :class => "destructive" } # # You can also specify a hash for <tt>options[:update]</tt> to allow for # easy redirection of output to an other DOM element if a server-side # error occurs: # # Example: # # Generates: <a href="#" onclick="new Ajax.Updater({success:'posts',failure:'error'}, '/blog/destroy/5', # # {asynchronous:true, evalScripts:true}); return false;">Delete this post</a> # link_to_remote "Delete this post", # :url => { :action => "destroy", :id => post.id }, # :update => { :success => "posts", :failure => "error" } # # Optionally, you can use the <tt>options[:position]</tt> parameter to # influence how the target DOM element is updated. It must be one of # <tt>:before</tt>, <tt>:top</tt>, <tt>:bottom</tt>, or <tt>:after</tt>. # # The method used is by default POST. You can also specify GET or you # can simulate PUT or DELETE over POST. All specified with <tt>options[:method]</tt> # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/person/4', {asynchronous:true, evalScripts:true, method:'delete'}); # # return false;">Destroy</a> # link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete # # By default, these remote requests are processed asynchronous during # which various JavaScript callbacks can be triggered (for progress # indicators and the likes). All callbacks get access to the # <tt>request</tt> object, which holds the underlying XMLHttpRequest. # # To access the server response, use <tt>request.responseText</tt>, to # find out the HTTP status, use <tt>request.status</tt>. # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/words/undo?n=33', {asynchronous:true, evalScripts:true, # # onComplete:function(request){undoRequestCompleted(request)}}); return false;">hello</a> # word = 'hello' # link_to_remote word, # :url => { :action => "undo", :n => word_counter }, # :complete => "undoRequestCompleted(request)" # # The callbacks that may be specified are (in order): # # <tt>:loading</tt>:: Called when the remote document is being # loaded with data by the browser. # <tt>:loaded</tt>:: Called when the browser has finished loading # the remote document. # <tt>:interactive</tt>:: Called when the user can interact with the # remote document, even though it has not # finished loading. # <tt>:success</tt>:: Called when the XMLHttpRequest is completed, # and the HTTP status code is in the 2XX range. # <tt>:failure</tt>:: Called when the XMLHttpRequest is completed, # and the HTTP status code is not in the 2XX # range. # <tt>:complete</tt>:: Called when the XMLHttpRequest is complete # (fires after success/failure if they are # present). # # You can further refine <tt>:success</tt> and <tt>:failure</tt> by # adding additional callbacks for specific status codes. # # Example: # # Generates: <a href="#" onclick="new Ajax.Request('/testing/action', {asynchronous:true, evalScripts:true, # # on404:function(request){alert('Not found...? Wrong URL...?')}, # # onFailure:function(request){alert('HTTP Error ' + request.status + '!')}}); return false;">hello</a> # link_to_remote word, # :url => { :action => "action" }, # 404 => "alert('Not found...? Wrong URL...?')", # :failure => "alert('HTTP Error ' + request.status + '!')" # # A status code callback overrides the success/failure handlers if # present. # # If you for some reason or another need synchronous processing (that'll # block the browser while the request is happening), you can specify # <tt>options[:type] = :synchronous</tt>. # # You can customize further browser side call logic by passing in # JavaScript code snippets via some optional parameters. In their order # of use these are: # # <tt>:confirm</tt>:: Adds confirmation dialog. # <tt>:condition</tt>:: Perform remote request conditionally # by this expression. Use this to # describe browser-side conditions when # request should not be initiated. # <tt>:before</tt>:: Called before request is initiated. # <tt>:after</tt>:: Called immediately after request was # initiated and before <tt>:loading</tt>. # <tt>:submit</tt>:: Specifies the DOM element ID that's used # as the parent of the form elements. By # default this is the current form, but # it could just as well be the ID of a # table row or any other DOM element. # <tt>:with</tt>:: A JavaScript expression specifying # the parameters for the XMLHttpRequest. # Any expressions should return a valid # URL query string. # # Example: # # :with => "'name=' + $('name').value" # # You can generate a link that uses AJAX in the general case, while # degrading gracefully to plain link behavior in the absence of # JavaScript by setting <tt>html_options[:href]</tt> to an alternate URL. # Note the extra curly braces around the <tt>options</tt> hash separate # it as the second parameter from <tt>html_options</tt>, the third. # # Example: # link_to_remote "Delete this post", # { :update => "posts", :url => { :action => "destroy", :id => post.id } }, # :href => url_for(:action => "destroy", :id => post.id) def link_to_remote(name, options = {}, html_options = nil) link_to_function(name, remote_function(options), html_options || options.delete(:html)) end # Creates a button with an onclick event which calls a remote action # via XMLHttpRequest # The options for specifying the target with :url # and defining callbacks is the same as link_to_remote. def button_to_remote(name, options = {}, html_options = {}) button_to_function(name, remote_function(options), html_options) end # Periodically calls the specified url (<tt>options[:url]</tt>) every # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to # update a specified div (<tt>options[:update]</tt>) with the results # of the remote call. The options for specifying the target with <tt>:url</tt> # and defining callbacks is the same as link_to_remote. # Examples: # # Call get_averages and put its results in 'avg' every 10 seconds # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater('avg', '/grades/get_averages', # # {asynchronous:true, evalScripts:true})}, 10) # periodically_call_remote(:url => { :action => 'get_averages' }, :update => 'avg') # # # Call invoice every 10 seconds with the id of the customer # # If it succeeds, update the invoice DIV; if it fails, update the error DIV # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater({success:'invoice',failure:'error'}, # # '/testing/invoice/16', {asynchronous:true, evalScripts:true})}, 10) # periodically_call_remote(:url => { :action => 'invoice', :id => customer.id }, # :update => { :success => "invoice", :failure => "error" } # # # Call update every 20 seconds and update the new_block DIV # # Generates: # # new PeriodicalExecuter(function() {new Ajax.Updater('news_block', 'update', {asynchronous:true, evalScripts:true})}, 20) # periodically_call_remote(:url => 'update', :frequency => '20', :update => 'news_block') # def periodically_call_remote(options = {}) frequency = options[:frequency] || 10 # every ten seconds by default code = "new PeriodicalExecuter(function() {#{remote_function(options)}}, #{frequency})" javascript_tag(code) end # Returns a form tag that will submit using XMLHttpRequest in the # background instead of the regular reloading POST arrangement. Even # though it's using JavaScript to serialize the form elements, the form # submission will work just like a regular submission as viewed by the # receiving side (all elements available in <tt>params</tt>). The options for # specifying the target with <tt>:url</tt> and defining callbacks is the same as # +link_to_remote+. # # A "fall-through" target for browsers that doesn't do JavaScript can be # specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>. # # Example: # # Generates: # # <form action="/some/place" method="post" onsubmit="new Ajax.Request('', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> # form_remote_tag :html => { :action => # url_for(:controller => "some", :action => "place") } # # The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd) # argument in the FormTagHelper.form_tag method. # # By default the fall-through action is the same as the one specified in # the <tt>:url</tt> (and the default method is <tt>:post</tt>). # # form_remote_tag also takes a block, like form_tag: # # Generates: # # <form action="/" method="post" onsubmit="new Ajax.Request('/', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); # # return false;"> <div><input name="commit" type="submit" value="Save" /></div> # # </form> # <% form_remote_tag :url => '/posts' do -%> # <div><%= submit_tag 'Save' %></div> # <% end -%> def form_remote_tag(options = {}, &block) options[:form] = true options[:html] ||= {} options[:html][:onsubmit] = (options[:html][:onsubmit] ? options[:html][:onsubmit] + "; " : "") + "#{remote_function(options)}; return false;" form_tag(options[:html].delete(:action) || url_for(options[:url]), options[:html], &block) end # Creates a form that will submit using XMLHttpRequest in the background # instead of the regular reloading POST arrangement and a scope around a # specific resource that is used as a base for questioning about # values for the fields. # # === Resource # # Example: # <% remote_form_for(@post) do |f| %> # ... # <% end %> # # This will expand to be the same as: # # <% remote_form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # # === Nested Resource # # Example: # <% remote_form_for([@post, @comment]) do |f| %> # ... # <% end %> # # This will expand to be the same as: # # <% remote_form_for :comment, @comment, :url => post_comment_path(@post, @comment), :html => { :method => :put, :class => "edit_comment", :id => "edit_comment_45" } do |f| %> # ... # <% end %> # # If you don't need to attach a form to a resource, then check out form_remote_tag. # # See FormHelper#form_for for additional semantics. def remote_form_for(record_or_name_or_array, *args, &proc) options = args.extract_options! case record_or_name_or_array when String, Symbol object_name = record_or_name_or_array when Array object = record_or_name_or_array.last object_name = ActionController::RecordIdentifier.singular_class_name(object) apply_form_for_options!(record_or_name_or_array, options) args.unshift object else object = record_or_name_or_array object_name = ActionController::RecordIdentifier.singular_class_name(record_or_name_or_array) apply_form_for_options!(object, options) args.unshift object end concat(form_remote_tag(options)) fields_for(object_name, *(args << options), &proc) concat('</form>') end alias_method :form_remote_for, :remote_form_for # Returns a button input tag with the element name of +name+ and a value (i.e., display text) of +value+ # that will submit form using XMLHttpRequest in the background instead of a regular POST request that # reloads the page. # # # Create a button that submits to the create action # # # # Generates: <input name="create_btn" onclick="new Ajax.Request('/testing/create', # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)}); # # return false;" type="button" value="Create" /> # <%= submit_to_remote 'create_btn', 'Create', :url => { :action => 'create' } %> # # # Submit to the remote action update and update the DIV succeed or fail based # # on the success or failure of the request # # # # Generates: <input name="update_btn" onclick="new Ajax.Updater({success:'succeed',failure:'fail'}, # # '/testing/update', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)}); # # return false;" type="button" value="Update" /> # <%= submit_to_remote 'update_btn', 'Update', :url => { :action => 'update' }, # :update => { :success => "succeed", :failure => "fail" } # # <tt>options</tt> argument is the same as in form_remote_tag. def submit_to_remote(name, value, options = {}) options[:with] ||= 'Form.serialize(this.form)' html_options = options.delete(:html) || {} html_options[:name] = name button_to_remote(value, options, html_options) end # Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function # that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple # update return document using +update_element_function+ calls. def evaluate_remote_response "eval(request.responseText)" end # Returns the JavaScript needed for a remote function. # Takes the same arguments as link_to_remote. # # Example: # # Generates: <select id="options" onchange="new Ajax.Updater('options', # # '/testing/update_options', {asynchronous:true, evalScripts:true})"> # <select id="options" onchange="<%= remote_function(:update => "options", # :url => { :action => :update_options }) %>"> # <option value="0">Hello</option> # <option value="1">World</option> # </select> def remote_function(options) javascript_options = options_for_ajax(options) update = '' if options[:update] && options[:update].is_a?(Hash) update = [] update << "success:'#{options[:update][:success]}'" if options[:update][:success] update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure] update = '{' + update.join(',') + '}' elsif options[:update] update << "'#{options[:update]}'" end function = update.empty? ? "new Ajax.Request(" : "new Ajax.Updater(#{update}, " url_options = options[:url] url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash) function << "'#{escape_javascript(url_for(url_options))}'" function << ", #{javascript_options})" function = "#{options[:before]}; #{function}" if options[:before] function = "#{function}; #{options[:after]}" if options[:after] function = "if (#{options[:condition]}) { #{function}; }" if options[:condition] function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm] return function end # Observes the field with the DOM ID specified by +field_id+ and calls a # callback when its contents have changed. The default callback is an # Ajax call. By default the value of the observed field is sent as a # parameter with the Ajax call. # # Example: # # Generates: new Form.Element.Observer('suggest', 0.25, function(element, value) {new Ajax.Updater('suggest', # # '/testing/find_suggestion', {asynchronous:true, evalScripts:true, parameters:'q=' + value})}) # <%= observe_field :suggest, :url => { :action => :find_suggestion }, # :frequency => 0.25, # :update => :suggest, # :with => 'q' # %> # # Required +options+ are either of: # <tt>:url</tt>:: +url_for+-style options for the action to call # when the field has changed. # <tt>:function</tt>:: Instead of making a remote call to a URL, you # can specify javascript code to be called instead. # Note that the value of this option is used as the # *body* of the javascript function, a function definition # with parameters named element and value will be generated for you # for example: # observe_field("glass", :frequency => 1, :function => "alert('Element changed')") # will generate: # new Form.Element.Observer('glass', 1, function(element, value) {alert('Element changed')}) # The element parameter is the DOM element being observed, and the value is its value at the # time the observer is triggered. # # Additional options are: # <tt>:frequency</tt>:: The frequency (in seconds) at which changes to # this field will be detected. Not setting this # option at all or to a value equal to or less than # zero will use event based observation instead of # time based observation. # <tt>:update</tt>:: Specifies the DOM ID of the element whose # innerHTML should be updated with the # XMLHttpRequest response text. # <tt>:with</tt>:: A JavaScript expression specifying the parameters # for the XMLHttpRequest. The default is to send the # key and value of the observed field. Any custom # expressions should return a valid URL query string. # The value of the field is stored in the JavaScript # variable +value+. # # Examples # # :with => "'my_custom_key=' + value" # :with => "'person[name]=' + prompt('New name')" # :with => "Form.Element.serialize('other-field')" # # Finally # :with => 'name' # is shorthand for # :with => "'name=' + value" # This essentially just changes the key of the parameter. # # Additionally, you may specify any of the options documented in the # <em>Common options</em> section at the top of this document. # # Example: # # # Sends params: {:title => 'Title of the book'} when the book_title input # # field is changed. # observe_field 'book_title', # :url => 'http://example.com/books/edit/1', # :with => 'title' # # def observe_field(field_id, options = {}) if options[:frequency] && options[:frequency] > 0 build_observer('Form.Element.Observer', field_id, options) else build_observer('Form.Element.EventObserver', field_id, options) end end # Observes the form with the DOM ID specified by +form_id+ and calls a # callback when its contents have changed. The default callback is an # Ajax call. By default all fields of the observed field are sent as # parameters with the Ajax call. # # The +options+ for +observe_form+ are the same as the options for # +observe_field+. The JavaScript variable +value+ available to the # <tt>:with</tt> option is set to the serialized form by default. def observe_form(form_id, options = {}) if options[:frequency] build_observer('Form.Observer', form_id, options) else build_observer('Form.EventObserver', form_id, options) end end # All the methods were moved to GeneratorMethods so that # #include_helpers_from_context has nothing to overwrite. class JavaScriptGenerator #:nodoc: def initialize(context, &block) #:nodoc: @context, @lines = context, [] include_helpers_from_context @context.with_output_buffer(@lines) do @context.instance_exec(self, &block) end end private def include_helpers_from_context extend @context.helpers if @context.respond_to?(:helpers) extend GeneratorMethods end # JavaScriptGenerator generates blocks of JavaScript code that allow you # to change the content and presentation of multiple DOM elements. Use # this in your Ajax response bodies, either in a <script> tag or as plain # JavaScript sent with a Content-type of "text/javascript". # # Create new instances with PrototypeHelper#update_page or with # ActionController::Base#render, then call +insert_html+, +replace_html+, # +remove+, +show+, +hide+, +visual_effect+, or any other of the built-in # methods on the yielded generator in any order you like to modify the # content and appearance of the current page. # # Example: # # # Generates: # # new Element.insert("list", { bottom: "<li>Some item</li>" }); # # new Effect.Highlight("list"); # # ["status-indicator", "cancel-link"].each(Element.hide); # update_page do |page| # page.insert_html :bottom, 'list', "<li>#{@item.name}</li>" # page.visual_effect :highlight, 'list' # page.hide 'status-indicator', 'cancel-link' # end # # # Helper methods can be used in conjunction with JavaScriptGenerator. # When a helper method is called inside an update block on the +page+ # object, that method will also have access to a +page+ object. # # Example: # # module ApplicationHelper # def update_time # page.replace_html 'time', Time.now.to_s(:db) # page.visual_effect :highlight, 'time' # end # end # # # Controller action # def poll # render(:update) { |page| page.update_time } # end # # Calls to JavaScriptGenerator not matching a helper method below # generate a proxy to the JavaScript Class named by the method called. # # Examples: # # # Generates: # # Foo.init(); # update_page do |page| # page.foo.init # end # # # Generates: # # Event.observe('one', 'click', function () { # # $('two').show(); # # }); # update_page do |page| # page.event.observe('one', 'click') do |p| # p[:two].show # end # end # # You can also use PrototypeHelper#update_page_tag instead of # PrototypeHelper#update_page to wrap the generated JavaScript in a # <script> tag. module GeneratorMethods def to_s #:nodoc: returning javascript = @lines * $/ do if ActionView::Base.debug_rjs source = javascript.dup javascript.replace "try {\n#{source}\n} catch (e) " javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }" end end end # Returns a element reference by finding it through +id+ in the DOM. This element can then be # used for further method calls. Examples: # # page['blank_slate'] # => $('blank_slate'); # page['blank_slate'].show # => $('blank_slate').show(); # page['blank_slate'].show('first').up # => $('blank_slate').show('first').up(); # # You can also pass in a record, which will use ActionController::RecordIdentifier.dom_id to lookup # the correct id: # # page[@post] # => $('post_45') # page[Post.new] # => $('new_post') def [](id) case id when String, Symbol, NilClass JavaScriptElementProxy.new(self, id) else JavaScriptElementProxy.new(self, ActionController::RecordIdentifier.dom_id(id)) end end # Returns an object whose <tt>to_json</tt> evaluates to +code+. Use this to pass a literal JavaScript # expression as an argument to another JavaScriptGenerator method. def literal(code) ActiveSupport::JSON::Variable.new(code.to_s) end # Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be # used for further method calls. Examples: # # page.select('p') # => $$('p'); # page.select('p.welcome b').first # => $$('p.welcome b').first(); # page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide(); # # You can also use prototype enumerations with the collection. Observe: # # # Generates: $$('#items li').each(function(value) { value.hide(); }); # page.select('#items li').each do |value| # value.hide # end # # Though you can call the block param anything you want, they are always rendered in the # javascript as 'value, index.' Other enumerations, like collect() return the last statement: # # # Generates: var hidden = $$('#items li').collect(function(value, index) { return value.hide(); }); # page.select('#items li').collect('hidden') do |item| # item.hide # end # def select(pattern) JavaScriptElementCollectionProxy.new(self, pattern) end # Inserts HTML at the specified +position+ relative to the DOM element # identified by the given +id+. # # +position+ may be one of: # # <tt>:top</tt>:: HTML is inserted inside the element, before the # element's existing content. # <tt>:bottom</tt>:: HTML is inserted inside the element, after the # element's existing content. # <tt>:before</tt>:: HTML is inserted immediately preceding the element. # <tt>:after</tt>:: HTML is inserted immediately following the element. # # +options_for_render+ may be either a string of HTML to insert, or a hash # of options to be passed to ActionView::Base#render. For example: # # # Insert the rendered 'navigation' partial just before the DOM # # element with ID 'content'. # # Generates: Element.insert("content", { before: "-- Contents of 'navigation' partial --" }); # page.insert_html :before, 'content', :partial => 'navigation' # # # Add a list item to the bottom of the <ul> with ID 'list'. # # Generates: Element.insert("list", { bottom: "<li>Last item</li>" }); # page.insert_html :bottom, 'list', '<li>Last item</li>' # def insert_html(position, id, *options_for_render) content = javascript_object_for(render(*options_for_render)) record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });" end # Replaces the inner HTML of the DOM element with the given +id+. # # +options_for_render+ may be either a string of HTML to insert, or a hash # of options to be passed to ActionView::Base#render. For example: # # # Replace the HTML of the DOM element having ID 'person-45' with the # # 'person' partial for the appropriate object. # # Generates: Element.update("person-45", "-- Contents of 'person' partial --"); # page.replace_html 'person-45', :partial => 'person', :object => @person # def replace_html(id, *options_for_render) call 'Element.update', id, render(*options_for_render) end # Replaces the "outer HTML" (i.e., the entire element, not just its # contents) of the DOM element with the given +id+. # # +options_for_render+ may be either a string of HTML to insert, or a hash # of options to be passed to ActionView::Base#render. For example: # # # Replace the DOM element having ID 'person-45' with the # # 'person' partial for the appropriate object. # page.replace 'person-45', :partial => 'person', :object => @person # # This allows the same partial that is used for the +insert_html+ to # be also used for the input to +replace+ without resorting to # the use of wrapper elements. # # Examples: # # <div id="people"> # <%= render :partial => 'person', :collection => @people %> # </div> # # # Insert a new person # # # # Generates: new Insertion.Bottom({object: "Matz", partial: "person"}, ""); # page.insert_html :bottom, :partial => 'person', :object => @person # # # Replace an existing person # # # Generates: Element.replace("person_45", "-- Contents of partial --"); # page.replace 'person_45', :partial => 'person', :object => @person # def replace(id, *options_for_render) call 'Element.replace', id, render(*options_for_render) end # Removes the DOM elements with the given +ids+ from the page. # # Example: # # # Remove a few people # # Generates: ["person_23", "person_9", "person_2"].each(Element.remove); # page.remove 'person_23', 'person_9', 'person_2' # def remove(*ids) loop_on_multiple_args 'Element.remove', ids end # Shows hidden DOM elements with the given +ids+. # # Example: # # # Show a few people # # Generates: ["person_6", "person_13", "person_223"].each(Element.show); # page.show 'person_6', 'person_13', 'person_223' # def show(*ids) loop_on_multiple_args 'Element.show', ids end # Hides the visible DOM elements with the given +ids+. # # Example: # # # Hide a few people # # Generates: ["person_29", "person_9", "person_0"].each(Element.hide); # page.hide 'person_29', 'person_9', 'person_0' # def hide(*ids) loop_on_multiple_args 'Element.hide', ids end # Toggles the visibility of the DOM elements with the given +ids+. # Example: # # # Show a few people # # Generates: ["person_14", "person_12", "person_23"].each(Element.toggle); # page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements # page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements # def toggle(*ids) loop_on_multiple_args 'Element.toggle', ids end # Displays an alert dialog with the given +message+. # # Example: # # # Generates: alert('This message is from Rails!') # page.alert('This message is from Rails!') def alert(message) call 'alert', message end # Redirects the browser to the given +location+ using JavaScript, in the same form as +url_for+. # # Examples: # # # Generates: window.location.href = "/mycontroller"; # page.redirect_to(:action => 'index') # # # Generates: window.location.href = "/account/signup"; # page.redirect_to(:controller => 'account', :action => 'signup') def redirect_to(location) url = location.is_a?(String) ? location : @context.url_for(location) record "window.location.href = #{url.inspect}" end # Reloads the browser's current +location+ using JavaScript # # Examples: # # # Generates: window.location.reload(); # page.reload def reload record 'window.location.reload()' end # Calls the JavaScript +function+, optionally with the given +arguments+. # # If a block is given, the block will be passed to a new JavaScriptGenerator; # the resulting JavaScript code will then be wrapped inside <tt>function() { ... }</tt> # and passed as the called function's final argument. # # Examples: # # # Generates: Element.replace(my_element, "My content to replace with.") # page.call 'Element.replace', 'my_element', "My content to replace with." # # # Generates: alert('My message!') # page.call 'alert', 'My message!' # # # Generates: # # my_method(function() { # # $("one").show(); # # $("two").hide(); # # }); # page.call(:my_method) do |p| # p[:one].show # p[:two].hide # end def call(function, *arguments, &block) record "#{function}(#{arguments_for_call(arguments, block)})" end # Assigns the JavaScript +variable+ the given +value+. # # Examples: # # # Generates: my_string = "This is mine!"; # page.assign 'my_string', 'This is mine!' # # # Generates: record_count = 33; # page.assign 'record_count', 33 # # # Generates: tabulated_total = 47 # page.assign 'tabulated_total', @total_from_cart # def assign(variable, value) record "#{variable} = #{javascript_object_for(value)}" end # Writes raw JavaScript to the page. # # Example: # # page << "alert('JavaScript with Prototype.');" def <<(javascript) @lines << javascript end # Executes the content of the block after a delay of +seconds+. Example: # # # Generates: # # setTimeout(function() { # # ; # # new Effect.Fade("notice",{}); # # }, 20000); # page.delay(20) do # page.visual_effect :fade, 'notice' # end def delay(seconds = 1) record "setTimeout(function() {\n\n" yield record "}, #{(seconds * 1000).to_i})" end # Starts a script.aculo.us visual effect. See # ActionView::Helpers::ScriptaculousHelper for more information. def visual_effect(name, id = nil, options = {}) record @context.send(:visual_effect, name, id, options) end # Creates a script.aculo.us sortable element. Useful # to recreate sortable elements after items get added # or deleted. # See ActionView::Helpers::ScriptaculousHelper for more information. def sortable(id, options = {}) record @context.send(:sortable_element_js, id, options) end # Creates a script.aculo.us draggable element. # See ActionView::Helpers::ScriptaculousHelper for more information. def draggable(id, options = {}) record @context.send(:draggable_element_js, id, options) end # Creates a script.aculo.us drop receiving element. # See ActionView::Helpers::ScriptaculousHelper for more information. def drop_receiving(id, options = {}) record @context.send(:drop_receiving_element_js, id, options) end private def loop_on_multiple_args(method, ids) record(ids.size>1 ? "#{javascript_object_for(ids)}.each(#{method})" : "#{method}(#{ids.first.to_json})") end def page self end def record(line) returning line = "#{line.to_s.chomp.gsub(/\;\z/, '')};" do self << line end end def render(*options_for_render) old_format = @context && @context.template_format @context.template_format = :html if @context Hash === options_for_render.first ? @context.render(*options_for_render) : options_for_render.first.to_s ensure @context.template_format = old_format if @context end def javascript_object_for(object) object.respond_to?(:to_json) ? object.to_json : object.inspect end def arguments_for_call(arguments, block = nil) arguments << block_to_function(block) if block arguments.map { |argument| javascript_object_for(argument) }.join ', ' end def block_to_function(block) generator = self.class.new(@context, &block) literal("function() { #{generator.to_s} }") end def method_missing(method, *arguments) JavaScriptProxy.new(self, method.to_s.camelize) end end end # Yields a JavaScriptGenerator and returns the generated JavaScript code. # Use this to update multiple elements on a page in an Ajax response. # See JavaScriptGenerator for more information. # # Example: # # update_page do |page| # page.hide 'spinner' # end def update_page(&block) JavaScriptGenerator.new(@template, &block).to_s end # Works like update_page but wraps the generated JavaScript in a <script> # tag. Use this to include generated JavaScript in an ERb template. # See JavaScriptGenerator for more information. # # +html_options+ may be a hash of <script> attributes to be passed # to ActionView::Helpers::JavaScriptHelper#javascript_tag. def update_page_tag(html_options = {}, &block) javascript_tag update_page(&block), html_options end protected def options_for_ajax(options) js_options = build_callbacks(options) js_options['asynchronous'] = options[:type] != :synchronous js_options['method'] = method_option_to_s(options[:method]) if options[:method] js_options['insertion'] = "'#{options[:position].to_s.downcase}'" if options[:position] js_options['evalScripts'] = options[:script].nil? || options[:script] if options[:form] js_options['parameters'] = 'Form.serialize(this)' elsif options[:submit] js_options['parameters'] = "Form.serialize('#{options[:submit]}')" elsif options[:with] js_options['parameters'] = options[:with] end if protect_against_forgery? && !options[:form] if js_options['parameters'] js_options['parameters'] << " + '&" else js_options['parameters'] = "'" end js_options['parameters'] << "#{request_forgery_protection_token}=' + encodeURIComponent('#{escape_javascript form_authenticity_token}')" end options_for_javascript(js_options) end def method_option_to_s(method) (method.is_a?(String) and !method.index("'").nil?) ? method : "'#{method}'" end def build_observer(klass, name, options = {}) if options[:with] && (options[:with] !~ /[\{=(.]/) options[:with] = "'#{options[:with]}=' + encodeURIComponent(value)" else options[:with] ||= 'value' unless options[:function] end callback = options[:function] || remote_function(options) javascript = "new #{klass}('#{name}', " javascript << "#{options[:frequency]}, " if options[:frequency] javascript << "function(element, value) {" javascript << "#{callback}}" javascript << ")" javascript_tag(javascript) end def build_callbacks(options) callbacks = {} options.each do |callback, code| if CALLBACKS.include?(callback) name = 'on' + callback.to_s.capitalize callbacks[name] = "function(request){#{code}}" end end callbacks end end # Converts chained method calls on DOM proxy elements into JavaScript chains class JavaScriptProxy < ActiveSupport::BasicObject #:nodoc: def initialize(generator, root = nil) @generator = generator @generator << root if root end private def method_missing(method, *arguments, &block) if method.to_s =~ /(.*)=$/ assign($1, arguments.first) else call("#{method.to_s.camelize(:lower)}", *arguments, &block) end end def call(function, *arguments, &block) append_to_function_chain!("#{function}(#{@generator.send(:arguments_for_call, arguments, block)})") self end def assign(variable, value) append_to_function_chain!("#{variable} = #{@generator.send(:javascript_object_for, value)}") end def function_chain @function_chain ||= @generator.instance_variable_get(:@lines) end def append_to_function_chain!(call) function_chain[-1].chomp!(';') function_chain[-1] += ".#{call};" end end class JavaScriptElementProxy < JavaScriptProxy #:nodoc: def initialize(generator, id) @id = id super(generator, "$(#{id.to_json})") end # Allows access of element attributes through +attribute+. Examples: # # page['foo']['style'] # => $('foo').style; # page['foo']['style']['color'] # => $('blank_slate').style.color; # page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red'; # page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red'; def [](attribute) append_to_function_chain!(attribute) self end def []=(variable, value) assign(variable, value) end def replace_html(*options_for_render) call 'update', @generator.send(:render, *options_for_render) end def replace(*options_for_render) call 'replace', @generator.send(:render, *options_for_render) end def reload(options_for_replace = {}) replace(options_for_replace.merge({ :partial => @id.to_s })) end end class JavaScriptVariableProxy < JavaScriptProxy #:nodoc: def initialize(generator, variable) @variable = variable @empty = true # only record lines if we have to. gets rid of unnecessary linebreaks super(generator) end # The JSON Encoder calls this to check for the +to_json+ method # Since it's a blank slate object, I suppose it responds to anything. def respond_to?(method) true end def to_json(options = nil) @variable end private def append_to_function_chain!(call) @generator << @variable if @empty @empty = false super end end class JavaScriptCollectionProxy < JavaScriptProxy #:nodoc: ENUMERABLE_METHODS_WITH_RETURN = [:all, :any, :collect, :map, :detect, :find, :find_all, :select, :max, :min, :partition, :reject, :sort_by, :in_groups_of, :each_slice] unless defined? ENUMERABLE_METHODS_WITH_RETURN ENUMERABLE_METHODS = ENUMERABLE_METHODS_WITH_RETURN + [:each] unless defined? ENUMERABLE_METHODS attr_reader :generator delegate :arguments_for_call, :to => :generator def initialize(generator, pattern) super(generator, @pattern = pattern) end def each_slice(variable, number, &block) if block enumerate :eachSlice, :variable => variable, :method_args => [number], :yield_args => %w(value index), :return => true, &block else add_variable_assignment!(variable) append_enumerable_function!("eachSlice(#{number.to_json});") end end def grep(variable, pattern, &block) enumerate :grep, :variable => variable, :return => true, :method_args => [pattern], :yield_args => %w(value index), &block end def in_groups_of(variable, number, fill_with = nil) arguments = [number] arguments << fill_with unless fill_with.nil? add_variable_assignment!(variable) append_enumerable_function!("inGroupsOf(#{arguments_for_call arguments});") end def inject(variable, memo, &block) enumerate :inject, :variable => variable, :method_args => [memo], :yield_args => %w(memo value index), :return => true, &block end def pluck(variable, property) add_variable_assignment!(variable) append_enumerable_function!("pluck(#{property.to_json});") end def zip(variable, *arguments, &block) add_variable_assignment!(variable) append_enumerable_function!("zip(#{arguments_for_call arguments}") if block function_chain[-1] += ", function(array) {" yield ::ActiveSupport::JSON::Variable.new('array') add_return_statement! @generator << '});' else function_chain[-1] += ');' end end private def method_missing(method, *arguments, &block) if ENUMERABLE_METHODS.include?(method) returnable = ENUMERABLE_METHODS_WITH_RETURN.include?(method) variable = arguments.first if returnable enumerate(method, {:variable => (arguments.first if returnable), :return => returnable, :yield_args => %w(value index)}, &block) else super end end # Options # * variable - name of the variable to set the result of the enumeration to # * method_args - array of the javascript enumeration method args that occur before the function # * yield_args - array of the javascript yield args # * return - true if the enumeration should return the last statement def enumerate(enumerable, options = {}, &block) options[:method_args] ||= [] options[:yield_args] ||= [] yield_args = options[:yield_args] * ', ' method_args = arguments_for_call options[:method_args] # foo, bar, function method_args << ', ' unless method_args.blank? add_variable_assignment!(options[:variable]) if options[:variable] append_enumerable_function!("#{enumerable.to_s.camelize(:lower)}(#{method_args}function(#{yield_args}) {") # only yield as many params as were passed in the block yield(*options[:yield_args].collect { |p| JavaScriptVariableProxy.new(@generator, p) }[0..block.arity-1]) add_return_statement! if options[:return] @generator << '});' end def add_variable_assignment!(variable) function_chain.push("var #{variable} = #{function_chain.pop}") end def add_return_statement! unless function_chain.last =~ /return/ function_chain.push("return #{function_chain.pop.chomp(';')};") end end def append_enumerable_function!(call) function_chain[-1].chomp!(';') function_chain[-1] += ".#{call}" end end class JavaScriptElementCollectionProxy < JavaScriptCollectionProxy #:nodoc:\ def initialize(generator, pattern) super(generator, "$$(#{pattern.to_json})") end end end end require 'action_view/helpers/javascript_helper'
44.059724
221
0.571947
f79edb067d2de7ca28c3da85710414e7aced1ccf
497
# A function that return a file content at apply time Puppet::Functions.create_function(:'openvpn::file_content') do # @param filename Path of file to cat # @return [String] Returns the file content dispatch :file_content do param 'String', :filename return_type 'String' end def file_content(filename) if File.exist?(filename) File.read(filename) else return '' if Puppet.settings[:noop] raise "File '#{filename}' does not exists." end end end
24.85
62
0.688129
ac7b6f73937af1c3c315c7c353424f52ddcf6992
2,615
# frozen_string_literal: true require 'webmock/rspec' require './lib/atol/transaction/get_token' RSpec.describe Atol::Transaction::GetToken do describe '#new' do context 'without arguments' do it { expect { described_class.new }.not_to raise_error } end context 'with good argument' do let(:config) { Atol::Config.new } it { expect { described_class.new(config: config) }.not_to raise_error } end context 'with bad argument' do let(:error) { Atol::ConfigExpectedError } it { expect { described_class.new(config: 1) }.to raise_error(error) } end end describe '#call' do let(:config) do Atol::Config.new(overrides: { login: 'example_login', password: 'example_password', http_client: Net::HTTP }) end context 'when response is 200' do let(:token_string) { 'example_token_string' } before do stub_request(:get, /online.atol.ru/).to_return({ status: 200, headers: {}, body: { token: token_string }.to_json }) end it 'returns token string' do transaction = described_class.new(config: config) expect(transaction.call).to eql(token_string) end end context 'when response code is 400' do before do stub_request(:get, /online.atol.ru/).to_return({ status: 400, headers: {}, body: { code: 17 }.to_json }) allow(Atol.config).to receive(:http_client).and_return(Net::HTTP) end it do transaction = described_class.new(config: config) expect { transaction.call }.to raise_error Atol::AuthBadRequestError end end context 'when response code is 401' do before do stub_request(:get, /online.atol.ru/).to_return({ status: 401, headers: {}, body: {}.to_json }) allow(Atol.config).to receive(:http_client).and_return(Net::HTTP) end it do transaction = described_class.new(config: config) expect { transaction.call }.to raise_error Atol::AuthUserOrPasswordError end end context 'when response code 415' do before do stub_request(:get, /online.atol.ru/).to_return({ status: 415, headers: {}, body: {}.to_json }) allow(Atol.config).to receive(:http_client).and_return(Net::HTTP) end it do transaction = described_class.new(config: config) expect { transaction.call }.to raise_error RuntimeError end end end end
26.683673
80
0.604589
b9b34f84f30c68498b0d12686734b5e874dcc244
619
Rails.application.routes.draw do resources :leaderboards resources :recipe_garnishes resources :recipe_mixers resources :recipe_liqueurs resources :recipe_liquors resources :user_recipes resources :garnishes resources :mixers resources :liqueurs resources :liquors resources :bars resources :liquor_stores resources :stores resources :questions resources :quizzes resources :reviews resources :recipe_ingredients resources :ingedients resources :recipes resources :users # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
24.76
102
0.789984
38da346a56ff57400febcd73c6fd0ffbd50dd538
2,034
require "twitter" require_relative "./Console" class TweetSong def setup @config = Hash.new @config[:last_tweet_file_name] = '.thelasttweet' # File containing the last tweet id mentionned @config[:lb_activation_duration] = 10000 # How long time the song will be played end @@instance = TweetSong.new def self.instance return @@instance end def run args command = args[0] # Start the UI if needed if Config.start_ui_if_needed command # Get the config setup # Run the infinite loop begin puts 'Test if new tweets -- ' + Time.now.to_s + ' --'.bold if si puts '--> Send to LittleBits --' faire end # pause for 60 seconds -- One call per minute is the maximum for twitter mentions API 4.times do |i| remain = 60 - 15 * i puts "Next try in #{remain} seconds..." sleep 15 end end while 1 end end protected # IF def si # Get the last read tweet id params = { count: 1 } if (File.readable?(@config[:last_tweet_file_name])) params[:since_id] = File.read(@config[:last_tweet_file_name]) end # Call Twitter API client = Twitter::REST::Client.new do |conf| conf.consumer_key = Config.get('twt_consumer_key', true) conf.consumer_secret = Config.get('twt_consumer_secret', true) conf.access_token = Config.get('twt_access_token', true) conf.access_token_secret = Config.get('twt_access_token_secret', true) end tweets = client.mentions_timeline(params) # if new mentions if tweets.count > 0 # Save last id to file and trigger LittleBits File.open(@config[:last_tweet_file_name], 'w+') {|f| f.write(tweets[0].id) } return true else return false end end # DO def faire cmd = 'curl -i -XPOST -H "Authorization: Bearer ' + Config.get('lb_access_token', true) + '" -H "Accept: application/vnd.littlebits.v2+json" https://api-http.littlebitscloud.cc/devices/' + Config.get('lb_device_id', true) + '/output -d percent=100 -d duration_ms=10000' system cmd end end
26.763158
271
0.673058
5df6fc7a44cdf2f8fa71714ba7fe7056feb7a700
554
# encoding: utf-8 Gem::Specification.new do |gem| gem.name = "hirefire-resource" gem.version = "0.7.2" gem.platform = Gem::Platform::RUBY gem.authors = "Michael van Rooijen" gem.email = "[email protected]" gem.homepage = "https://www.hirefire.io" gem.summary = "Autoscaling for your Heroku dynos" gem.description = "Load- and schedule-based scaling for web- and worker dynos" gem.licenses = ["Apache License"] gem.files = %x[git ls-files].split("\n") gem.executables = ["hirefire", "hirefireapp"] gem.require_path = "lib" end
30.777778
80
0.689531
e2d64510f80045ad36426330716a6a0fe4257640
4,208
# -------------------------------------------------------------------------- # # Copyright 2002-2021, OpenNebula Project, OpenNebula Systems # # # # 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. # #--------------------------------------------------------------------------- # if !ONE_LOCATION LOG_LOCATION = "/var/log/one" else LOG_LOCATION = ONE_LOCATION + "/var" end LOG = LOG_LOCATION + "/onedb-fsck.log" require 'nokogiri' module OneDBPatch VERSION = "5.6.0" LOCAL_VERSION = "5.6.0" def is_hot_patch(ops) return false end def check_db_version(ops) db_version = read_db_version() if ( db_version[:version] != VERSION || db_version[:local_version] != LOCAL_VERSION ) raise <<-EOT Version mismatch: patch file is for version Shared: #{VERSION}, Local: #{LOCAL_VERSION} Current database is version Shared: #{db_version[:version]}, Local: #{db_version[:local_version]} EOT end end def patch(ops) init_log_time() puts "This patch updates images and VMs with missing NEXT_SNAPSHOT parameter." puts # BUG #2687: Disk snapshots dissapearing # https://github.com/OpenNebula/one/issues/2687 @db.transaction do @db.fetch("SELECT * FROM image_pool") do |row| doc = nokogiri_doc(row[:body], 'image_pool') next_snapshot = doc.at_xpath("//SNAPSHOTS/NEXT_SNAPSHOT") next if next_snapshot max = doc.xpath("//SNAPSHOTS/SNAPSHOT/ID").max if max next_snapshot = max.text.to_i + 1 else next_snapshot = 0 end sxml = doc.xpath("//SNAPSHOTS") if sxml ns = doc.create_element("NEXT_SNAPSHOT") ns.content = next_snapshot sxml = sxml.first.add_child(ns) puts "Image #{row[:oid]} updated with NEXT_SNAPSHOT #{next_snapshot}" @db[:image_pool].where(:oid => row[:oid]).update( :body => doc.root.to_s) end end log_time() @db.fetch("SELECT * FROM vm_pool") do |row| doc = nokogiri_doc(row[:body], 'vm_pool') # evaluate each disk snapshot individually doc.xpath("//SNAPSHOTS").each do |disk| next_snapshot = disk.at_xpath("NEXT_SNAPSHOT") next if next_snapshot max = disk.xpath("SNAPSHOT/ID").max if max next_snapshot = max.text.to_i + 1 else next_snapshot = 0 end puts "VM #{row[:oid]}, DISK #{disk.at_xpath('DISK_ID').text} updated with NEXT_SNAPSHOT #{next_snapshot}" ns = doc.create_element("NEXT_SNAPSHOT") ns.content = next_snapshot disk.add_child(ns) end @db[:vm_pool].where(:oid => row[:oid]).update( :body => doc.root.to_s) end log_time() end log_time() return true end end
32.875
125
0.478137
4a3bb70641bdb0e96f9a1acdac2b5fe4eaa46363
2,700
# Author:: Adam Jacob (<[email protected]>) # Author:: William Albenzi (<[email protected]>) # Copyright:: Copyright 2009-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # 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. # require "chef/knife" class Chef class Knife class RoleEnvRunListAdd < Knife deps do require "chef/role" require "chef/json_compat" end banner "knife role env_run_list add [ROLE] [ENVIRONMENT] [ENTRY [ENTRY]] (options)" option :after, :short => "-a ITEM", :long => "--after ITEM", :description => "Place the ENTRY in the run list after ITEM" def add_to_env_run_list(role, environment, entries, after = nil) if after nlist = [] unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end role.run_list_for(environment).each do |entry| nlist << entry if entry == after entries.each { |e| nlist << e } end end role.env_run_lists_add(environment => nlist) else nlist = [] unless role.env_run_lists.key?(environment) role.env_run_lists_add(environment => nlist) end role.run_list_for(environment).each do |entry| nlist << entry end entries.each { |e| nlist << e } role.env_run_lists_add(environment => nlist) end end def run role = Chef::Role.load(@name_args[0]) role.name(@name_args[0]) environment = @name_args[1] if @name_args.size > 2 # Check for nested lists and create a single plain one entries = @name_args[2..-1].map do |entry| entry.split(",").map { |e| e.strip } end.flatten else # Convert to array and remove the extra spaces entries = @name_args[2].split(",").map { |e| e.strip } end add_to_env_run_list(role, environment, entries, config[:after]) role.save config[:env_run_list] = true output(format_for_display(role)) end end end end
31.034483
89
0.608148
6a20c9faa27b03899edd037afbc0e6d6ce9b4fa4
782
# frozen_string_literal: true module Archangel ## # Design model # class Design < ApplicationRecord acts_as_paranoid validates :content, presence: true validates :name, presence: true validates :partial, inclusion: { in: [true, false] } validate :valid_liquid_content belongs_to :parent, -> { where(partial: false) }, class_name: "Archangel::Design", inverse_of: false, optional: true belongs_to :site protected def valid_liquid_content return if valid_liquid_content? errors.add(:content, Archangel.t(:liquid_invalid)) end def valid_liquid_content? ::Liquid::Template.parse(content) true rescue ::Liquid::SyntaxError false end end end
20.051282
56
0.644501
182400931b8d978d752feb7a514b63fe674c390b
3,350
# # Controller for FamilyMember model # @author E. M. Maximilien # Copyright (C) IBM Corp., 2011 # License under the MIT license, found here: http://goo.gl/s9uhf # class FamilyMembersController < ApplicationController include SearchableHelper before_filter :'only_superusers?', :only => [:remove, :destroy] def remove @family_member = FamilyMember.find params[:id] @family_member.destroy redirect_to :action => 'index' end # GET /family_members # GET /family_members.xml def index order = params[:order] || 'updated_at ASC' @family_members = FamilyMember.paginate :page => params[:page], :per_page => per_page, :order => order, :include => [:profile, :user] respond_to do |format| format.fbml # index.fbml.erb format.xml { render :xml => @family_members } end end # GET /family_members/1 # GET /family_members/1.xml def show @family_member = FamilyMember.find(params[:id]) respond_to do |format| format.fbml # show.fbml.erb format.xml { render :xml => @family_member } end end # GET /family_members/new # GET /family_members/new.xml def new @family_member = FamilyMember.new respond_to do |format| format.fbml # new.fbml.erb format.xml { render :xml => @family_member } end end # GET /family_members/1/edit def edit @family_member = FamilyMember.find(params[:id]) end # POST /family_members # POST /family_members.xml def create @family_member = FamilyMember.new(params[:family_member]) respond_to do |format| if @family_member.save flash[:notice] = 'FamilyMember was successfully created.' format.fbml { redirect_to(@family_member) } format.xml { render :xml => @family_member, :status => :created, :family_member => @family_member } else format.fbml { render :action => "new" } format.xml { render :xml => @family_member.errors, :status => :unprocessable_entity } end end end # PUT /family_members/1 # PUT /family_members/1.xml def update @family_member = FamilyMember.find(params[:id]) respond_to do |format| if @family_member.update_attributes(params[:family_member]) flash[:notice] = 'FamilyMember was successfully updated.' format.fbml { redirect_to(@family_member) } format.xml { head :ok } else format.fbml { render :action => "edit" } format.xml { render :xml => @family_member.errors, :status => :unprocessable_entity } end end end # DELETE /family_members/1 # DELETE /family_members/1.xml def destroy @family_member = FamilyMember.find(params[:id]) @family_member.destroy respond_to do |format| format.fbml { redirect_to(family_members_url) } format.xml { head :ok } end end protected def searchable_class FamilyMember end def perform_query klass, query state = params[:search][:state] if state.nil? or state.blank? return klass.find_by_solr(query, :limit => :all).docs else query.gsub! '*', '' return klass.find_by_solr(query, :limit => :all).docs end end end
27.459016
108
0.622687
fffa73e38fb1e6031fa27d7ca94fca7db711345b
352
class AddEvent < ActiveRecord::Migration[5.0] def change create_table :events do |t| t.belongs_to :user t.belongs_to :communty t.belongs_to :collection t.string :session_id t.string :ip_addr t.string :event_type t.string :event_class t.string :source t.datetime :event_date end end end
22
45
0.647727
1cf5276fadedd4833f1b2225d6cc4b362f4ab6b3
1,401
module HTTP module Protocol class Response class Headers < Headers define_header "Etag" do def validate(etag) unless pattern.match etag raise Error.new "invalid etag #{etag.inspect}" end end def pattern %r{^(?:W/)?"?[!#-~\x80-\xFF]*"?$}n end end define_header "Keep-Alive" do def initialize @value = {} end def coerce(str) vals = str.split "," vals.each_with_object Hash.new do |val, hsh| unless %r{^(?<property>timeout|max)=(?<number>\d+)$} =~ val raise Error.new "invalid Keep-Alive #{str.inspect}" end hsh[property.to_sym] = number.to_i end end def timeout=(val) @value[:timeout] = val.to_i end def max=(val) @value[:max] = val.to_i end def serialized_value @value.map do |name, val| "#{name}=#{val}" end * "," end end define_header "Last-Modified" do def coerce(str) Time.httpdate str rescue ArgumentError => error raise Error.new error.message end def value @value.httpdate end end end end end end
23.35
73
0.464668
33a0246f196a5d8ee2eb5042f399a996e5cdc258
90
require 'activevalidators' # Activate all the validators ActiveValidators.activate(:all)
18
31
0.822222
7a9f32fd263b06c4f7bd6b8101ea5cbe331b41c7
1,926
# frozen_string_literal: true require 'spec_helper' require 'action_view' require 'currency_select' module ActionView module Helpers describe CurrencySelect do include TagHelper class User attr_accessor :currency_code end let(:user) { User.new } let(:template) { ActionView::Base.new } let(:select_tag) do '<select name="user[currency_code]" id="user_currency_code">' end let(:selected_eur_option) do content_tag(:option, 'Euro - EUR', selected: :selected, value: 'EUR') end let(:builder) { FormBuilder.new(:user, user, template, {}) } describe 'currency_select' do let(:tag) { builder.currency_select(:currency_code) } it 'creates a select tag' do expect(tag).to include(select_tag) end it 'creates option tags for each currency' do ::CurrencySelect.currencies_array.each do |name, code| expect(tag).to include(content_tag(:option, name, value: code)) end end it 'selects the value of currency_code' do user.currency_code = 'EUR' t = builder.currency_select(:currency_code) expect(t).to include(selected_eur_option) end it 'does not mark two currencies as selected' do user.currency_code = 'USD' expect(tag.scan(/selected="selected"/).count).to eq(1) end describe 'priority currencies' do let(:tag) { builder.currency_select(:currency_code, ['EUR']) } it 'inserts the priority currencies at the top' do expect(tag).to include("#{select_tag}<option value=\"EUR") end it 'inserts a divider' do expect(tag).to include( '<option value="" disabled="disabled">' \ '-------------</option>' ) end end end end end end
27.514286
77
0.590343
e988a856ab79e79c521eee4fb21bed45e48cb724
32
module DiveEquipmentsHelper end
10.666667
27
0.90625
e9cfca9473994d6914394710b42e339bbab6207d
6,857
require 'spec_helper' describe SessionContext do describe '#create' do context 'when user signs in for the first time' do context 'and user is a member' do let(:user) { build(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([{ "login" => "triglav-developers" }]) } it { expect { context.create(auth_params_for(user)) }.to change { User.count }.by(1) } it { expect { context.create(auth_params_for(user)) }.to change { Activity.count }.by(1) } it { context.create(auth_params_for(user)) activity = Activity.order('created_at desc').first expect(activity).to be_true expect(activity.user).to be == user expect(activity.model).to be == user expect(activity.tag).to be == 'create' expect(user.member).to be_true expect(user.api_token).to be_true } end context 'and user is not a member' do let(:user) { build(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([]) } it { expect { context.create(auth_params_for(user)) }.to change { User.count }.by(0) } it { expect { context.create(auth_params_for(user)) }.to change { Activity.count }.by(0) } it { context.create(auth_params_for(user)) expect(user.member).to be_false expect(user.api_token).to be_nil } end end context 'when user signs in again' do context 'and user is a member' do let(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([{ "login" => "triglav-developers" }]) } it { expect { context.create(auth_params_for(user)) }.to change { Activity.count }.by(0) } it { context.create(auth_params_for(user)) expect(user.member).to be_true expect(user.api_token).to be_true } end context 'and user is not a member' do let!(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([]) } it { expect { context.create(auth_params_for(user)) }.to change { User.count }.by(0) } it { expect { context.create(auth_params_for(user)) }.to change { Activity.count }.by(0) } it { context.create(auth_params_for(user)) expect(user.member).to be_false expect(user.api_token).to be_nil } end end context 'when user will fail to be created' do let(:user) { build(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([{ "login" => "triglav-developers" }]) } it { auth_params = auth_params_for(user) auth_params['info']['nickname'] = nil expect(context.create(auth_params)).to be_false expect(user.valid?).to be_false } end end describe '#update_name' do let(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } before { context.update_name('updated') } it { expect(user.name).to be == 'updated'} end describe '#update_name' do let(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } before { context.stub(:shrink_avatar_url).and_return('updated') context.update_image('updated') } it { expect(user.image).to be == 'updated'} end describe "#shrink_avatar_url" do let(:user) { create(:user, member: nil) } let(:context) { SessionContext.new(user: user) } let(:original_url) { "https://secure.gravatar.com/avatar/23f4d5d797a91b6d17d627b90b5a42d9?s=420&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png "} let(:shrinked_url) { context.shrink_avatar_url(original_url) } it { expect(shrinked_url).to be == "//gravatar.com/avatar/23f4d5d797a91b6d17d627b90b5a42d9" } end describe '#update_access_token' do let(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } before { context.update_access_token('token' => 'updated') } it { expect(user.access_token).to be == 'updated'} end describe "#update_privilege" do let(:user) { create(:user, member: nil) } let(:context) { SessionContext.new(user: user) } before { context.stub(:organizations).and_return([{ "login" => "triglav-developers" }]) context.update_privilege('github') } it { expect(user.member).to be_true } end describe "#update_api_token" do context 'when user is a member' do context 'and api_token has not been set yet' do let(:user) { create(:user, member: true, api_token: nil) } let(:context) { SessionContext.new(user: user) } before { context.update_api_token } it { expect(user.api_token).to be_true } end context 'and api_token is already set' do let(:user) { create(:user, member: true, api_token: SecureRandom.urlsafe_base64) } let!(:api_token) { user.api_token } let(:context) { SessionContext.new(user: user) } before { context.update_api_token } it { expect(user.api_token).to be_true expect(user.api_token).to be == api_token } end end context 'when user is not a member' do context 'and api_token has not been set yet' do let(:user) { create(:user, member: nil, api_token: nil) } let(:context) { SessionContext.new(user: user) } before { context.update_api_token } it { expect(user.api_token).to be_nil } end context 'and api_token is already set' do let(:user) { create(:user, member: nil, api_token: SecureRandom.urlsafe_base64) } let!(:api_token) { user.api_token } let(:context) { SessionContext.new(user: user) } before { context.update_api_token } it { expect(user.api_token).to be_nil } end end end describe '#organizations' do let(:user) { create(:user) } let(:context) { SessionContext.new(user: user) } let(:orgs) { [{ "login" => "triglav-developers" }] } before { Octokit::Client.any_instance.stub(:organizations).and_return(orgs) } it { expect(context.organizations).to be == orgs } end end
28.102459
193
0.586991
08c964be81eb237e9a202d326011720fe79d36e5
5,012
# frozen_string_literal: true # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require 'capybara/rspec' RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. # require 'capybara/rails' config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. # # This allows you to limit a spec run to individual examples or groups # # you care about by tagging them with `:focus` metadata. When nothing # # is tagged with `:focus`, all examples get run. RSpec also provides # # aliases for `it`, `describe`, and `context` that include `:focus` # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. # config.filter_run_when_matching :focus # # # Allows RSpec to persist some state between runs in order to support # # the `--only-failures` and `--next-failure` CLI options. We recommend # # you configure your source control system to ignore this file. # config.example_status_persistence_file_path = "spec/examples.txt" # # # Limits the available syntax to the non-monkey patched syntax that is # # recommended. For more details, see: # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode # config.disable_monkey_patching! # # # Many RSpec users commonly either run the entire suite or an individual # # file, and it's useful to allow more verbose output when running an # # individual spec file. # if config.files_to_run.one? # # Use the documentation formatter for detailed output, # # unless a formatter has already been configured # # (e.g. via a command-line flag). # config.default_formatter = "doc" # end # # # Print the 10 slowest examples and example groups at the # # end of the spec run, to help surface which specs are running # # particularly slow. # config.profile_examples = 10 # # # Run specs in random order to surface order dependencies. If you find an # # order dependency and want to debug it, you can fix the order by providing # # the seed, which is printed after each run. # # --seed 1234 # config.order = :random # # # Seed global randomization in this process using the `--seed` CLI option. # # Setting this allows you to use `--seed` to deterministically reproduce # # test failures related to randomization by passing the same `--seed` value # # as the one that triggered the failure. # Kernel.srand config.seed end
50.626263
96
0.717877
f7c6064e43bbbca55aa1c839eb28fd66b3422056
3,561
class Tm < Formula desc "TriggerMesh CLI to work with knative objects" homepage "https://triggermesh.com" url "https://github.com/triggermesh/tm/archive/v1.15.0.tar.gz" sha256 "4978af0bf87485a6e208738498e0559f85f1734d4aee6ed69cbda59fbc7b2af3" license "Apache-2.0" head "https://github.com/triggermesh/tm.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "d80fa3093b6b1977102b08a1d77f4feba3d510ca57f7d8eaae99a1a2b8b5dcbd" sha256 cellar: :any_skip_relocation, arm64_big_sur: "5cd0ba63217a2acc6ea5a7dd22937753340972b2ee4adaf2287176c89ce57b59" sha256 cellar: :any_skip_relocation, monterey: "7913630c5b6228ec5e15bec6cc287dcd0f3e40c82d47146fb5eb7421e8cceb1e" sha256 cellar: :any_skip_relocation, big_sur: "0603f2379ab75795c83309d73f96831c0712d1a52c651819a6a580a9b2386510" sha256 cellar: :any_skip_relocation, catalina: "03c1748cc8ceaa36dec7657c61b1071de7f2b781bd27c4ca97eb80978d98c41a" sha256 cellar: :any_skip_relocation, x86_64_linux: "b3b8dfedcc955b34bf53772f39fe0c757b02e9b76a731586a0641583955e374d" end depends_on "go" => :build def install ldflags = %W[ -s -w -X github.com/triggermesh/tm/cmd.version=v#{version} ].join(" ") system "go", "build", *std_go_args(ldflags: ldflags) end test do (testpath/"kubeconfig").write <<~EOS apiVersion: v1 clusters: - cluster: certificate-authority-data: test server: http://127.0.0.1:8080 name: test contexts: - context: cluster: test user: test name: test current-context: test kind: Config preferences: {} users: - name: test user: token: test EOS ENV["KUBECONFIG"] = testpath/"kubeconfig" # version version_output = shell_output("#{bin}/tm version") assert_match "Triggermesh CLI, version v#{version}", version_output # node system "#{bin}/tm", "generate", "node", "foo-node" assert_predicate testpath/"foo-node/serverless.yaml", :exist? assert_predicate testpath/"foo-node/handler.js", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/node10/runtime.yaml" yaml = File.read("foo-node/serverless.yaml") assert_match "runtime: #{runtime}", yaml # python system "#{bin}/tm", "generate", "python", "foo-python" assert_predicate testpath/"foo-python/serverless.yaml", :exist? assert_predicate testpath/"foo-python/handler.py", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/python37/runtime.yaml" yaml = File.read("foo-python/serverless.yaml") assert_match "runtime: #{runtime}", yaml # go system "#{bin}/tm", "generate", "go", "foo-go" assert_predicate testpath/"foo-go/serverless.yaml", :exist? assert_predicate testpath/"foo-go/main.go", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/go/runtime.yaml" yaml = File.read("foo-go/serverless.yaml") assert_match "runtime: #{runtime}", yaml # ruby system "#{bin}/tm", "generate", "ruby", "foo-ruby" assert_predicate testpath/"foo-ruby/serverless.yaml", :exist? assert_predicate testpath/"foo-ruby/handler.rb", :exist? runtime = "https://raw.githubusercontent.com/triggermesh/knative-lambda-runtime/master/ruby25/runtime.yaml" yaml = File.read("foo-ruby/serverless.yaml") assert_match "runtime: #{runtime}", yaml end end
37.882979
123
0.703735
d5575450376f22dc99c77d203a6cca51cdadcf2e
803
Pod::Spec.new do |s| s.name = "Heyzap" s.version = "3.4.34" s.summary = "Heyzap's iOS SDK: Leaderboards, Achievements, and Ads for games." s.homepage = "http://developers.heyzap.com/docs" s.license = { :type => 'Commercial', :text => 'See http://www.heyzap.com/legal/terms' } s.author = { "Heyzap" => "[email protected]" } s.source = { :git => "https://github.com/MaxGabriel/HeyzapSDK.git", :tag => "3.4.34" } s.platform = :ios s.resources = 'Heyzap.bundle' s.preserve_paths = 'Heyzap.framework' s.frameworks = 'QuartzCore', 'CoreGraphics', 'Heyzap' s.weak_frameworks = 'StoreKit','AdSupport' s.source_files = 'HeyzapDummy.{m,h}' s.requires_arc = true s.xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '"$(PODS_ROOT)/Heyzap"' } end
38.238095
94
0.622665
08ca9b410bd9c195dd62d81156bdad58ea6026fe
5,693
=begin #Alfresco Content Services REST API #**Core API** Provides access to the core features of Alfresco Content Services. OpenAPI spec version: 1 Generated by: https://github.com/swagger-api/swagger-codegen.git 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. =end require 'date' module Alfresco class ProbeEntry attr_accessor :entry # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'entry' => :'entry' } end # Attribute type mapping. def self.swagger_types { :'entry' => :'ProbeEntryEntry' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'entry') self.entry = attributes[:'entry'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && entry == o.entry end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [entry].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /^(true|t|yes|y|1)$/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = Alfresco.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.465
107
0.632356
5db25962746375265539fe17e12486b357f53334
445
# frozen_string_literal: true require_relative '../params/current_helper' module Export module PathForHelper include Params::CurrentHelper def export_path_for(format) url_for export_params_for(format) end private def export_params_for(format) current_params .deep_merge(only_path: true, transform: { format: format }) end end end
18.541667
43
0.617978
2636e66ca5d71a4d48331596a90e95b8bdbe5a0b
1,341
require "application_system_test_case" class NetworkMonitorsTest < ApplicationSystemTestCase setup do @network_monitor = network_monitors(:one) end test "visiting the index" do visit network_monitors_url assert_selector "h1", text: "Network Monitors" end test "creating a Network monitor" do visit network_monitors_url click_on "New Network Monitor" fill_in "Last accessed", with: @network_monitor.last_accessed fill_in "Provision request", with: @network_monitor.provision_request fill_in "User", with: @network_monitor.user_id click_on "Create Network monitor" assert_text "Network monitor was successfully created" click_on "Back" end test "updating a Network monitor" do visit network_monitors_url click_on "Edit", match: :first fill_in "Last accessed", with: @network_monitor.last_accessed fill_in "Provision request", with: @network_monitor.provision_request fill_in "User", with: @network_monitor.user_id click_on "Update Network monitor" assert_text "Network monitor was successfully updated" click_on "Back" end test "destroying a Network monitor" do visit network_monitors_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Network monitor was successfully destroyed" end end
27.9375
73
0.747204
26cf224afeaedbbd992eb2ddf7fff15159ed80ce
3,799
require 'spec_helper' describe 'logstash::input::zenoss', :type => 'define' do let(:facts) { {:operatingsystem => 'CentOS', :osfamily => 'Linux'} } let(:pre_condition) { 'class {"logstash": }'} let(:title) { 'test' } context "Input test" do let :params do { :ack => false, :add_field => { 'field2' => 'value2' }, :arguments => ['value3'], :auto_delete => false, :charset => 'ASCII-8BIT', :debug => false, :durable => false, :exchange => 'value8', :exclusive => false, :format => 'plain', :host => 'value11', :key => 'value12', :message_format => 'value13', :passive => false, :password => 'value15', :port => 16, :prefetch_count => 17, :queue => 'value18', :ssl => false, :tags => ['value20'], :threads => 21, :type => 'value22', :user => 'value23', :verify_ssl => false, :vhost => 'value25', } end it { should contain_file('/etc/logstash/agent/config/input_zenoss_test').with(:content => "input {\n zenoss {\n ack => false\n add_field => [\"field2\", \"value2\"]\n arguments => ['value3']\n auto_delete => false\n charset => \"ASCII-8BIT\"\n debug => false\n durable => false\n exchange => \"value8\"\n exclusive => false\n format => \"plain\"\n host => \"value11\"\n key => \"value12\"\n message_format => \"value13\"\n passive => false\n password => \"value15\"\n port => 16\n prefetch_count => 17\n queue => \"value18\"\n ssl => false\n tags => ['value20']\n threads => 21\n type => \"value22\"\n user => \"value23\"\n verify_ssl => false\n vhost => \"value25\"\n }\n}\n") } end context "Instance test" do let :params do { :ack => false, :add_field => { 'field2' => 'value2' }, :arguments => ['value3'], :auto_delete => false, :charset => 'ASCII-8BIT', :debug => false, :durable => false, :exchange => 'value8', :exclusive => false, :format => 'plain', :host => 'value11', :key => 'value12', :message_format => 'value13', :passive => false, :password => 'value15', :port => 16, :prefetch_count => 17, :queue => 'value18', :ssl => false, :tags => ['value20'], :threads => 21, :type => 'value22', :user => 'value23', :verify_ssl => false, :vhost => 'value25', :instances => [ 'agent1', 'agent2' ] } end it { should contain_file('/etc/logstash/agent1/config/input_zenoss_test') } it { should contain_file('/etc/logstash/agent2/config/input_zenoss_test') } end context "Set file owner" do let(:facts) { {:operatingsystem => 'CentOS', :osfamily => 'Linux'} } let(:pre_condition) { 'class {"logstash": logstash_user => "logstash", logstash_group => "logstash" }'} let(:title) { 'test' } let :params do { :ack => false, :add_field => { 'field2' => 'value2' }, :arguments => ['value3'], :auto_delete => false, :charset => 'ASCII-8BIT', :debug => false, :durable => false, :exchange => 'value8', :exclusive => false, :format => 'plain', :host => 'value11', :key => 'value12', :message_format => 'value13', :passive => false, :password => 'value15', :port => 16, :prefetch_count => 17, :queue => 'value18', :ssl => false, :tags => ['value20'], :threads => 21, :type => 'value22', :user => 'value23', :verify_ssl => false, :vhost => 'value25', } end it { should contain_file('/etc/logstash/agent/config/input_zenoss_test').with(:owner => 'logstash', :group => 'logstash') } end end
31.92437
708
0.523296
bf87090d9c2bf3a22b7fa62d15f9d14cf1e79b43
234
module Spree class Gateway::SagePay < Gateway preference :login, :string preference :password, :string preference :account, :string def provider_class ActiveMerchant::Billing::SagePayGateway end end end
19.5
45
0.709402
d5018737217ea17e618e2e408c43bc263c267a2f
2,787
class Day14 def self.title '--- Day 14: Extended Polymerization ---' end def initialize(state) @state = state setup end def tick(args) render(args) process_input(args) end private def setup read_input('14') @state.steps = 0 count_elements end def read_input(input_id) lines = read_problem_input(input_id).split("\n") read_initial_polymer lines.first.chars read_rules lines.drop(2) end def read_initial_polymer(elements) @state.polymer = elements @state.pair_counts = {}.tap { |pairs| elements.each_cons(2) do |pair| add_into_hash pairs, pair, 1 end } @state.last_element = elements.last end def read_rules(rule_lines) @state.rules = rule_lines.map { |line| pair, inserted_element = line.split(' -> ') { pair: pair.chars, new_pairs: [[pair[0], inserted_element], [inserted_element, pair[1]]], inserted_element: inserted_element } } end def render(args) render_info(args) end def render_info(args) args.outputs.primitives << top_right_labels( 'Press Space to simulate polymer growh', "Steps: #{@state.steps}", *@state.element_counts.map { |element, count| "#{element}: #{count}" }, "Result: #{@state.result}" ) end def process_input(args) return unless args.inputs.keyboard.key_down.space simulate_polymer_growth end def simulate_polymer_growth rule_applications = determine_rule_applications update_pair_counts rule_applications count_elements @state.steps += 1 end def determine_rule_applications {}.tap { |result| @state.rules.each do |rule| number_of_pairs = @state.pair_counts[rule.pair] next unless number_of_pairs&.positive? result[rule] = number_of_pairs end } end def update_pair_counts(rule_applications) rule_applications.each do |rule, times| @state.pair_counts[rule.pair] -= times rule.new_pairs.each do |pair| add_into_hash @state.pair_counts, pair, times end end end def count_elements @state.element_counts = {}.tap { |element_counts| count_first_pair_elements element_counts add_into_hash element_counts, @state.last_element, 1 } @state.result = highest_element_count - lowest_element_count end def count_first_pair_elements(result_hash) @state.pair_counts.each do |pair, count| add_into_hash result_hash, pair[0], count end end def highest_element_count @state.element_counts.values.max end def lowest_element_count @state.element_counts.values.min end def add_into_hash(hash, key, value) hash[key] ||= 0 hash[key] += value end end SOLUTIONS[14] = Day14
22.119048
78
0.670255
014b1e25407aa7a44e78399cdccfa55f1e965319
1,720
require "language/haskell" class PandocCiteproc < Formula include Language::Haskell::Cabal desc "Library and executable for using citeproc with pandoc" homepage "https://github.com/jgm/pandoc-citeproc" url "https://hackage.haskell.org/package/pandoc-citeproc-0.10.5.1/pandoc-citeproc-0.10.5.1.tar.gz" sha256 "49038b80ad802098169852b0bc7fc7c9878a85a9091eee4c32211844fecda783" head "https://github.com/jgm/pandoc-citeproc.git" bottle do sha256 "1340684299f24b273f7ea77c0d101fccc5974d444b2219bc4f13afb94275636a" => :sierra sha256 "4b044f54b46d897260a14d4503249d2910528acb96ede60a30680691babc77c0" => :el_capitan sha256 "5959f63d0a97096a9b9340429da1380287f86eb81d0bc2e0d78737cf55dea664" => :yosemite sha256 "d9c79313c222212d6b96c5c2fdfd7d14fb2ac59af098c157dd74954e292b5f06" => :x86_64_linux # glibc 2.19 end depends_on "[email protected]" => :build depends_on "cabal-install" => :build depends_on "pandoc" def install args = [] args << "--constraint=cryptonite -support_aesni" if MacOS.version <= :lion install_cabal_package *args end test do (testpath/"test.bib").write <<-EOS.undent @Book{item1, author="John Doe", title="First Book", year="2005", address="Cambridge", publisher="Cambridge University Press" } EOS expected = <<-EOS.undent --- references: - id: item1 type: book author: - family: Doe given: John issued: - year: '2005' title: First book publisher: Cambridge University Press publisher-place: Cambridge ... EOS assert_equal expected, shell_output("#{bin}/pandoc-citeproc -y test.bib") end end
30.175439
107
0.691279
e88d7900cf6811dbfd3ae539662c1f09b3a6d015
3,016
# 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::Network::Mgmt::V2019_12_01 module Models # # List of HubVirtualNetworkConnections and a URL nextLink to get the next # set of results. # class ListHubVirtualNetworkConnectionsResult include MsRestAzure include MsRest::JSONable # @return [Array<HubVirtualNetworkConnection>] List of # HubVirtualNetworkConnections. attr_accessor :value # @return [String] URL to get the next set of operation list results if # there are any. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<HubVirtualNetworkConnection>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [ListHubVirtualNetworkConnectionsResult] with next page # content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for ListHubVirtualNetworkConnectionsResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ListHubVirtualNetworkConnectionsResult', type: { name: 'Composite', class_name: 'ListHubVirtualNetworkConnectionsResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'HubVirtualNetworkConnectionElementType', type: { name: 'Composite', class_name: 'HubVirtualNetworkConnection' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
29.281553
80
0.551061
f7b85db2bb6443ca470076d9516636ddb15e63af
929
ActiveAdmin.register SkillQuestion do permit_params :skill_id, :question, :answer, :language_id index do column :language column :skill column :question column :answer actions end form do |f| f.inputs do f.input :skill_id, as: :select, collection: Skill.all.map{ |skill| [skill.name, skill.id] } f.input :language_id, as: :select, collection: Language.all.map{ |language| [language.name, language.id] } f.input :question, as: :ckeditor f.input :answer end f.actions end # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end end
24.447368
120
0.667384
1ae95acdb50323eb3887a9f505f72d11f76d23f6
1,073
class CreateFieldContacts < ActiveRecord::Migration[6.0] def change create_table :field_contacts do |t| t.string :fc_num t.string :contact_date t.integer :contact_officer_employee_id t.string :contact_officer_name t.integer :supervisor_employee_id t.string :supervisor_name t.string :street t.string :city t.string :state t.integer :zip # for frisked and various searched fields in pre-Sep data; # will need to be brought in from field_contact_names # for post-Sep data t.boolean :frisked_searched t.integer :stop_duration t.string :circumstance t.string :basis t.integer :vehicle_year t.string :vehicle_state t.string :vehicle_make t.string :vehicle_model t.string :vehicle_color t.string :vehicle_style t.string :vehicle_type t.text :key_situations # store as JSON; only in post-Sep data t.text :narrative t.string :weather t.timestamps t.index :fc_num, unique: true end end end
25.547619
67
0.664492
e95204e3afdd483e0c80d0c63b13fb20fd03ee0b
1,450
class Genometools < Formula desc "GenomeTools: The versatile open source genome analysis software" homepage "http://genometools.org/" url "http://genometools.org/pub/genometools-1.5.10.tar.gz" sha256 "0208591333b74594bc219fb67f5a29b81bb2ab872f540c408ac1743716274e6a" head "https://github.com/genometools/genometools.git" bottle do cellar :any sha256 "41b8f4a189050f98d0f78c3972d8efb095a2eea8400c486eb6d785a3f89cadae" => :high_sierra sha256 "b081ac73906f972a1858d86070d6d79ad3985e703f347c1fe49b0511e15e0232" => :sierra sha256 "06a7a3d2450c7c6538f2005d12135e8a26e2d086fc6f1d5867e9fe03fcce9833" => :el_capitan sha256 "58630ffd033898f413d7a60fad30e2792b94bfbc50faa2f92d1035b6cc2939cb" => :x86_64_linux end depends_on "pkg-config" => :build depends_on "cairo" depends_on "pango" depends_on "python@2" if MacOS.version <= :snow_leopard def install system "make", "prefix=#{prefix}" system "make", "install", "prefix=#{prefix}" cd "gtpython" do # Use the shared library from this specific version of genometools. inreplace "gt/dlload.py", "gtlib = CDLL(\"libgenometools\" + soext)", "gtlib = CDLL(\"#{lib}/libgenometools\" + soext)" system "python", *Language::Python.setup_install_args(prefix) system "python", "-m", "unittest", "discover", "tests" end end test do system "#{bin}/gt", "-test" system "python", "-c", "import gt" end end
35.365854
94
0.72069
380a565a7b7f54cd25e11bf34dbeea8c23ba1cc6
483
class CreateDoorMatMemberships < ActiveRecord::Migration def change create_table :door_mat_memberships do |t| t.belongs_to :member, index: true, class_name: "DoorMat::Actor" t.belongs_to :member_of, index: true, class_name: "DoorMat::Actor" t.integer :sponsor, :default => 0 t.integer :owner, :default => 0 t.integer :permission, :default => 0 t.text :key, :default => '', :null => false t.timestamps :null => false end end end
32.2
72
0.654244
f8dcb3f4ba037423f1015204001605a9d1962a57
5,581
# frozen_string_literal: true require "abstract_unit" require "active_job" require "mailers/delayed_mailer" class MessageDeliveryTest < ActiveSupport::TestCase include ActiveJob::TestHelper setup do @previous_logger = ActiveJob::Base.logger @previous_delivery_method = ActionMailer::Base.delivery_method @previous_deliver_later_queue_name = ActionMailer::Base.deliver_later_queue_name ActionMailer::Base.deliver_later_queue_name = :test_queue ActionMailer::Base.delivery_method = :test ActiveJob::Base.logger = Logger.new(nil) ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true DelayedMailer.last_error = nil DelayedMailer.last_rescue_from_instance = nil @mail = DelayedMailer.test_message(1, 2, 3) end teardown do ActionMailer::Base.deliveries.clear ActiveJob::Base.logger = @previous_logger ActionMailer::Base.delivery_method = @previous_delivery_method ActionMailer::Base.deliver_later_queue_name = @previous_deliver_later_queue_name DelayedMailer.last_error = nil DelayedMailer.last_rescue_from_instance = nil end test "should have a message" do assert @mail.message end test "its message should be a Mail::Message" do assert_equal Mail::Message, @mail.message.class end test "should respond to .deliver_later" do assert_respond_to @mail, :deliver_later end test "should respond to .deliver_later!" do assert_respond_to @mail, :deliver_later! end test "should respond to .deliver_now" do assert_respond_to @mail, :deliver_now end test "should respond to .deliver_now!" do assert_respond_to @mail, :deliver_now! end def test_should_enqueue_and_run_correctly_in_activejob @mail.deliver_later! assert_equal 1, ActionMailer::Base.deliveries.size end test "should enqueue the email with :deliver_now delivery method" do assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do @mail.deliver_later end end test "should enqueue the email with :deliver_now! delivery method" do assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now!", 1, 2, 3]) do @mail.deliver_later! end end test "should enqueue a delivery with a delay" do travel_to Time.new(2004, 11, 24, 01, 04, 44) do assert_performed_with(job: ActionMailer::DeliveryJob, at: Time.current + 10.minutes, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do @mail.deliver_later wait: 10.minutes end end end test "should enqueue a delivery at a specific time" do later_time = Time.current + 1.hour assert_performed_with(job: ActionMailer::DeliveryJob, at: later_time, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do @mail.deliver_later wait_until: later_time end end test "should enqueue the job on the correct queue" do assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3], queue: "test_queue") do @mail.deliver_later end end test "should enqueue the job with the correct delivery job" do old_delivery_job = DelayedMailer.delivery_job DelayedMailer.delivery_job = DummyJob assert_performed_with(job: DummyJob, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do @mail.deliver_later end DelayedMailer.delivery_job = old_delivery_job end class DummyJob < ActionMailer::DeliveryJob; end test "can override the queue when enqueuing mail" do assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3], queue: "another_queue") do @mail.deliver_later(queue: :another_queue) end end test "deliver_later after accessing the message is disallowed" do @mail.message # Load the message, which calls the mailer method. assert_raise RuntimeError do @mail.deliver_later end end test "job delegates error handling to mailer" do # Superclass not rescued by mailer's rescue_from RuntimeError message = DelayedMailer.test_raise("StandardError") assert_raise(StandardError) { message.deliver_later } assert_nil DelayedMailer.last_error assert_nil DelayedMailer.last_rescue_from_instance # Rescued by mailer's rescue_from RuntimeError message = DelayedMailer.test_raise("DelayedMailerError") assert_nothing_raised { message.deliver_later } assert_equal "boom", DelayedMailer.last_error.message assert_kind_of DelayedMailer, DelayedMailer.last_rescue_from_instance end class DeserializationErrorFixture include GlobalID::Identification def self.find(id) raise "boom, missing find" end attr_reader :id def initialize(id = 1) @id = id end def to_global_id(options = {}) super app: "foo" end end test "job delegates deserialization errors to mailer class" do # Inject an argument that can't be deserialized. message = DelayedMailer.test_message(DeserializationErrorFixture.new) # DeserializationError is raised, rescued, and delegated to the handler # on the mailer class. assert_nothing_raised { message.deliver_later } assert_equal DelayedMailer, DelayedMailer.last_rescue_from_instance assert_equal "Error while trying to deserialize arguments: boom, missing find", DelayedMailer.last_error.message end end
33.220238
158
0.743594
03388cc857cb8fc05c5afd65f2f75dc19897912c
761
Pod::Spec.new do |s| s.name = "iOS-QuizKit" s.version = "0.1" s.summary = "Local Quiz/Test administration and management for iOS." s.homepage = "hhttps://github.com/narpas/iOS-Quizkit" s.license = { :type => 'MIT', :text => <<-LICENSE By: Justin Meiners Copyright (c) 2013 Inline Studios Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php LICENSE } s.author = { "Justin Meiners" => "[email protected]" } s.source = { :git => "https://github.com/narpas/iOS-Quizkit.git", :tag => "v0.1"} s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.6' s.source_files = 'Source/' s.frameworks = 'Foundation' s.requires_arc = false end
31.708333
89
0.620237
e273cdda73e2e27fd07eb30be2b3d80ebe2d4f02
6,703
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # The properties that define a request to migrate a cluster to Native VCN. class ContainerEngine::Models::ClusterMigrateToNativeVcnDetails # **[Required]** The network configuration for access to the Cluster control plane. # # @return [OCI::ContainerEngine::Models::ClusterEndpointConfig] attr_accessor :endpoint_config # The optional override of the non-native endpoint decommission time after migration is complete. Defaults to 30 days. # @return [String] attr_accessor :decommission_delay_duration # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'endpoint_config': :'endpointConfig', 'decommission_delay_duration': :'decommissionDelayDuration' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'endpoint_config': :'OCI::ContainerEngine::Models::ClusterEndpointConfig', 'decommission_delay_duration': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [OCI::ContainerEngine::Models::ClusterEndpointConfig] :endpoint_config The value to assign to the {#endpoint_config} property # @option attributes [String] :decommission_delay_duration The value to assign to the {#decommission_delay_duration} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.endpoint_config = attributes[:'endpointConfig'] if attributes[:'endpointConfig'] raise 'You cannot provide both :endpointConfig and :endpoint_config' if attributes.key?(:'endpointConfig') && attributes.key?(:'endpoint_config') self.endpoint_config = attributes[:'endpoint_config'] if attributes[:'endpoint_config'] self.decommission_delay_duration = attributes[:'decommissionDelayDuration'] if attributes[:'decommissionDelayDuration'] raise 'You cannot provide both :decommissionDelayDuration and :decommission_delay_duration' if attributes.key?(:'decommissionDelayDuration') && attributes.key?(:'decommission_delay_duration') self.decommission_delay_duration = attributes[:'decommission_delay_duration'] if attributes[:'decommission_delay_duration'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && endpoint_config == other.endpoint_config && decommission_delay_duration == other.decommission_delay_duration end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [endpoint_config, decommission_delay_duration].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
39.429412
245
0.699687
0308d1ca35017d547aa55cf32e2820c1908cee2b
5,450
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151025182927) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "active_admin_comments", force: :cascade do |t| t.string "namespace" t.text "body" t.string "resource_id", null: false t.string "resource_type", null: false t.integer "author_id" t.string "author_type" t.datetime "created_at" t.datetime "updated_at" end add_index "active_admin_comments", ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id", using: :btree add_index "active_admin_comments", ["namespace"], name: "index_active_admin_comments_on_namespace", using: :btree add_index "active_admin_comments", ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id", using: :btree create_table "admin_users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "admin_users", ["email"], name: "index_admin_users_on_email", unique: true, using: :btree add_index "admin_users", ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true, using: :btree create_table "assets", force: :cascade do |t| t.string "filename", limit: 45 t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "categories", force: :cascade do |t| t.string "title", limit: 45 t.integer "sort_order" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "daily_menus", force: :cascade do |t| t.integer "day_number" t.float "max_total" t.integer "dish_ids", default: [], array: true t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "daily_rations", force: :cascade do |t| t.float "price" t.integer "quantity" t.integer "person_id" t.integer "daily_menu_id" t.integer "sprint_id" t.integer "dish_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "dishes", force: :cascade do |t| t.string "title", limit: 45 t.integer "sort_order" t.text "description" t.float "price" t.text "type" t.integer "children_ids", default: [], array: true t.integer "category_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "people", force: :cascade do |t| t.string "name", null: false t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.string "authentication_token" t.integer "failed_attempts", default: 0, null: false t.datetime "locked_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "people", ["authentication_token"], name: "index_people_on_authentication_token", unique: true, using: :btree add_index "people", ["email"], name: "index_people_on_email", unique: true, using: :btree add_index "people", ["reset_password_token"], name: "index_people_on_reset_password_token", unique: true, using: :btree create_table "sprints", force: :cascade do |t| t.string "title", limit: 45 t.date "started_at" t.date "finished_at" t.string "state" t.datetime "created_at", null: false t.datetime "updated_at", null: false end end
42.248062
154
0.651376
39454a2b0b5f8aaa072c04798791a99b6d99e051
5,058
module Neo4j # A relationship between two nodes in the graph. A relationship has a start node, an end node and a type. # You can attach properties to relationships like Neo4j::Node. # # The fact that the relationship API gives meaning to start and end nodes implicitly means that all relationships have a direction. # In the example above, rel would be directed from node to otherNode. # A relationship's start node and end node and their relation to outgoing and incoming are defined so that the assertions in the following code are true: # # Furthermore, Neo4j guarantees that a relationship is never "hanging freely," # i.e. start_node, end_node and other_node are guaranteed to always return valid, non-nil nodes. class Relationship # A module that allows plugins to register wrappers around Neo4j::Node objects module Wrapper # Used by Neo4j::NodeMixin to wrap nodes def wrapper self end def neo4j_obj self end end include PropertyContainer include EntityEquality include Wrapper include EntityMarshal # @return [Hash<Symbol,Object>] all properties of the relationship def props fail 'not implemented' end # replace all properties with new properties # @param [Hash] properties a hash of properties the relationship should have def props=(properties) fail 'not implemented' end # Updates the properties, keeps old properties # @param [Hash<Symbol,Object>] properties hash of properties that should be updated on the relationship def update_props(properties) fail 'not implemented' end # Directly remove the property on the relationship (low level method, may need transaction) def remove_property(key) fail 'not implemented' end # Directly set the property on the relationship (low level method, may need transaction) # @param [Hash, String] key # @param value see Neo4j::PropertyValidator::VALID_PROPERTY_VALUE_CLASSES for valid values def set_property(key, value) fail 'not implemented' end # Directly get the property on the relationship (low level method, may need transaction) # @param [Hash, String] key # @return the value of the key def get_property(key, value) fail 'not implemented' end # Returns the start node of this relationship. # @return [Neo4j::Node,Object] the node or wrapped node def start_node _start_node.wrapper end # Same as #start_node but does not wrap the node # @return [Neo4j::Node] def _start_node fail 'not implemented' end # Returns the end node of this relationship. # @return [Neo4j::Node,Object] the node or wrapped node def end_node _end_node.wrapper end # Same as #end_node but does not wrap the node # @return [Neo4j::Node] def _end_node fail 'not implemented' end # @abstract def del fail 'not implemented' end # The unique neo4j id # @abstract def neo_id fail 'not implemented' end # @return [true, false] if the relationship exists # @abstract def exist? fail 'not implemented' end # Returns the relationship name # # @example # a = Neo4j::Node.new # a.create_rel(:friends, node_b) # a.rels.first.rel_type # => :friends # @return [Symbol] the type of the relationship def rel_type fail 'not implemented' end # A convenience operation that, given a node that is attached to this relationship, returns the other node. # For example if node is a start node, the end node will be returned, and vice versa. # This is a very convenient operation when you're manually traversing the node space by invoking one of the #rels # method on a node. For example, to get the node "at the other end" of a relationship, use the following: # # @example # end_node = node.rels.first.other_node(node) # # @raise This operation will throw a runtime exception if node is neither this relationship's start node nor its end node. # # @param [Neo4j::Node] node the node that we don't want to return # @return [Neo4j::Node] the other node wrapper # @see #_other_node def other_node(node) _other_node(node.neo4j_obj).wrapper end # Same as #other_node but can return a none wrapped node def _other_node(node) if node == _start_node _end_node elsif node == _end_node _start_node else fail "Node #{node.inspect} is neither start nor end node" end end class << self def create(rel_type, from_node, other_node, props = {}) from_node.neo4j_obj.create_rel(rel_type, other_node, props) end def load(neo_id, session = Neo4j::Session.current) rel = _load(neo_id, session) rel && rel.wrapper end def _load(neo_id, session = Neo4j::Session.current) session.load_relationship(neo_id) end end end end
31.222222
155
0.677738
ac6ba45ad45a3e40be078f796535185de24a7287
1,436
# == Schema Information # Schema version: 12 # # Table name: audit_logs # # id :integer not null, primary key # user_id :integer # record_id :integer # action :string(255) # created_at :datetime # updated_at :datetime # # # Purpose: This class represents an Audit Log entry, which provides a means to track # the actions which have been performed in the system. # class AuditLog < ActiveRecord::Base # # Most audit log entries are associated with the user who performed the action # that is being logged. # belongs_to :user # # Each audit log entry must have a description of the action performed. # validates_presence_of :action # # Some Audit Log entries are associated with a particular record # belongs_to :bodysize, :foreign_key => "record_id" # # Purpose: To help simplify logging of actions # # Input: # * message (String) - The action that occurred # * user_id (Integer) [optional] - The id of the user who performed the action # * record_id (Integer) [optional] - The bodysize record id associated with the action # # Output: # * True if the message was successfully logged # * False otherwise # def self.log(message, user_id = nil, record_id = nil) return AuditLog.create(:user_id => user_id, :record_id => record_id, :action => message) end end
24.338983
93
0.649721
d56a70789a7409d395c8c24ce846104f1e3ceeac
92
class AutoCompletesController < ApplicationController before_filter :login_required end
23
53
0.858696
280d25aa7268d9e558301326511a37b9f0ef0117
1,344
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-devicefarm/types' require_relative 'aws-sdk-devicefarm/client_api' require_relative 'aws-sdk-devicefarm/client' require_relative 'aws-sdk-devicefarm/errors' require_relative 'aws-sdk-devicefarm/resource' require_relative 'aws-sdk-devicefarm/customizations' # This module provides support for AWS Device Farm. This module is available in the # `aws-sdk-devicefarm` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # device_farm = Aws::DeviceFarm::Client.new # resp = device_farm.create_device_pool(params) # # See {Client} for more information. # # # Errors # # Errors returned from AWS Device Farm are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::DeviceFarm::Errors::ServiceError # # rescues all AWS Device Farm API errors # end # # See {Errors} for more information. # # @service module Aws::DeviceFarm GEM_VERSION = '1.31.0' end
26.352941
83
0.744792
1d6b9744da4780fa98f93f8ab299515376205484
1,417
class Nant < Formula desc ".NET build tool" homepage "http://nant.sourceforge.net/" url "https://downloads.sourceforge.net/nant/nant/nant-0.92-src.tar.gz" sha256 "72d4d585267ed7f03e1aa75087d96f4f8d49ee976c32d974c5ab1fef4d4f8305" depends_on "pkg-config" => :run depends_on "mono" patch do # fix build with newer versions of mono url "https://github.com/nant/nant/commit/69c8ee96493c5d953212397c8ca06c2392372ca4.diff" sha256 "1194a3b5c8e65d47e606f9d0f3b348fb6fe1998db929a7f711a9e172764b8075" end def install ENV.deparallelize # https://github.com/nant/nant/issues/151#issuecomment-125685734 system "make", "install", "MCS=mcs", "prefix=#{prefix}" inreplace bin/"nant", bin/"mono", "mono" end test do ENV.prepend_path "PATH", Formula["mono"].bin (testpath/"default.build").write <<-EOS.undent <project default="build" xmlns="http://nant.sf.net/release/0.86-beta1/nant.xsd"> <target name="build"> <csc target="exe" output="hello.exe"> <sources> <include name="hello.cs" /> </sources> </csc> </target> </project> EOS (testpath/"hello.cs").write <<-EOS.undent public class Hello1 { public static void Main() { System.Console.WriteLine("hello homebrew!"); } } EOS system bin/"nant" end end
27.25
91
0.633733
f7d076a274f595493ed90c28af90e4980087e3af
209
Airbrake.configure do |config| config.project_key = '975c8408c0ba86574b0344c37eec36b5' config.project_id = 109790 config.environment = Rails.env config.ignore_environments = %w(development test) end
26.125
57
0.789474
385d6d0b55651a511b08e1de23b28ca47b92bfaf
387
# frozen_string_literal: true require '../0023_merge-k-sorted-lists/merge-k-sorted-lists' require '../../helper/list_node' RSpec.describe do context '' do it 't1' do lists = [[2], [], [-1]] ans = [-1, 2] lists.map! { |list| ListNode.generate(list) } ans = ListNode.generate(ans) expect(merge_k_lists(lists).to_a).to eq ans.to_a end end end
19.35
59
0.612403
5d15870b7f651fabb166f5545568a622b8da7a61
450
# frozen_string_literal: true # require 'spec_helper' RSpec.describe PartitionCreationWorker do subject { described_class.new.perform } let(:management_worker) { double } describe '#perform' do it 'forwards to the Database::PartitionManagementWorker' do expect(Database::PartitionManagementWorker).to receive(:new).and_return(management_worker) expect(management_worker).to receive(:perform) subject end end end
23.684211
96
0.753333
bf5b9126c9407fc15ef49079dc05fd02b1bda649
1,268
# -*- encoding: utf-8 -*- # stub: turbolinks 5.2.1 ruby lib Gem::Specification.new do |s| s.name = "turbolinks".freeze s.version = "5.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "source_code_uri" => "https://github.com/turbolinks/turbolinks-rails" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["David Heinemeier Hansson".freeze] s.date = "2019-09-18" s.description = "Rails engine for Turbolinks 5 support".freeze s.email = "[email protected]".freeze s.homepage = "https://github.com/turbolinks/turbolinks".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "3.0.6".freeze s.summary = "Turbolinks makes navigating your web application faster".freeze s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<turbolinks-source>.freeze, ["~> 5.2"]) else s.add_dependency(%q<turbolinks-source>.freeze, ["~> 5.2"]) end else s.add_dependency(%q<turbolinks-source>.freeze, ["~> 5.2"]) end end
37.294118
116
0.694006
bf4ec2bc8b72dcbfe64d2aed69d01329d55f4f64
1,734
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Throw 500 error when submitting unpermitted form parameters config.action_controller.action_on_unpermitted_parameters = :raise # 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 and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = 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 # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
38.533333
85
0.779123
aba3a7dee0e69a51db2c381edeba7fd662307c14
4,969
# 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::Compute::Mgmt::V2018_04_01 module Models # # Describes a Virtual Machine Scale Set Extension. # class VirtualMachineScaleSetExtension < SubResourceReadOnly include MsRestAzure # @return [String] The name of the extension. attr_accessor :name # @return [String] If a value is provided and is different from the # previous value, the extension handler will be forced to update even if # the extension configuration has not changed. attr_accessor :force_update_tag # @return [String] The name of the extension handler publisher. attr_accessor :publisher # @return [String] Specifies the type of the extension; an example is # "CustomScriptExtension". attr_accessor :type # @return [String] Specifies the version of the script handler. attr_accessor :type_handler_version # @return [Boolean] Indicates whether the extension should use a newer # minor version if one is available at deployment time. Once deployed, # however, the extension will not upgrade minor versions unless # redeployed, even with this property set to true. attr_accessor :auto_upgrade_minor_version # @return Json formatted public settings for the extension. attr_accessor :settings # @return The extension can contain either protectedSettings or # protectedSettingsFromKeyVault or no protected settings at all. attr_accessor :protected_settings # @return [String] The provisioning state, which only appears in the # response. attr_accessor :provisioning_state # # Mapper for VirtualMachineScaleSetExtension class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VirtualMachineScaleSetExtension', type: { name: 'Composite', class_name: 'VirtualMachineScaleSetExtension', 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, serialized_name: 'name', type: { name: 'String' } }, force_update_tag: { client_side_validation: true, required: false, serialized_name: 'properties.forceUpdateTag', type: { name: 'String' } }, publisher: { client_side_validation: true, required: false, serialized_name: 'properties.publisher', type: { name: 'String' } }, type: { client_side_validation: true, required: false, serialized_name: 'properties.type', type: { name: 'String' } }, type_handler_version: { client_side_validation: true, required: false, serialized_name: 'properties.typeHandlerVersion', type: { name: 'String' } }, auto_upgrade_minor_version: { client_side_validation: true, required: false, serialized_name: 'properties.autoUpgradeMinorVersion', type: { name: 'Boolean' } }, settings: { client_side_validation: true, required: false, serialized_name: 'properties.settings', type: { name: 'Object' } }, protected_settings: { client_side_validation: true, required: false, serialized_name: 'properties.protectedSettings', type: { name: 'Object' } }, provisioning_state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.provisioningState', type: { name: 'String' } } } } } end end end end
32.477124
78
0.524854
0191bd43de96ac4efa757c4d75daa2e6f2958c31
1,454
class Pla < Formula desc "Tool for building Gantt charts in PNG, EPS, PDF or SVG format" homepage "https://www.arpalert.org/pla.html" url "https://www.arpalert.org/src/pla-1.2.tar.gz" sha256 "c2f1ce50b04032abf7f88ac07648ea40bed2443e86e9f28f104d341965f52b9c" license "GPL-2.0" bottle do cellar :any sha256 "a93517a26dab0bab4ab32aff81c7af3b7545ae1be265ce15caacc3772cd6d485" => :catalina sha256 "9d5e86767de6c9a2ac741e9edd32d053da5fde96563446a63d1b0475f4da595a" => :mojave sha256 "af3163cf8322d872694753f3d3352384fb9c8ce923c66f7be82f50bdbbe734bc" => :high_sierra sha256 "c6edebbefcf192ea4bcad704ca5b4c27157f77b4a47e3a993ac2a61e7165c13c" => :sierra sha256 "3fd0d11d1bdfa24e93bf94cb854e28382307c291b25994c82a2a8c1a64ce5072" => :el_capitan sha256 "308920e8bf8642826cd973eaa63e22f0fc3dec43a0152485d358ba575638291f" => :yosemite sha256 "df4b500589672dc1c415866b7da4c678621858f48cbac2cab5765c2b4fb1857d" => :mavericks end depends_on "pkg-config" => :build depends_on "cairo" def install system "make" bin.install "pla" end test do (testpath/"test.pla").write <<~EOS [4] REF0 Install des serveurs color #8cb6ce child 1 child 2 child 3 [1] REF0 Install 1 start 2010-04-08 01 duration 24 color #8cb6ce dep 2 dep 6 EOS system "#{bin}/pla", "-i", "#{testpath}/test.pla", "-o test" end end
32.311111
93
0.715956
61d0baff975615b519ad3582dca67277d2a6cdd7
126
class AddNoticeToItems < ActiveRecord::Migration[6.0] def change add_column :items, :checkout_notice, :string end end
21
53
0.753968
7abd24c09e371cfb9ad48322091bfc5eea7a71f8
660
# frozen_string_literal: true require ::File.expand_path("../../test_helper", __FILE__) module Stripe class ThreeDSecureTest < Test::Unit::TestCase should "be retrievable" do secure = Stripe::ThreeDSecure.retrieve("tdsrc_123") assert_requested :get, "#{Stripe.api_base}/v1/3d_secure/tdsrc_123" assert secure.is_a?(Stripe::ThreeDSecure) end should "be creatable" do _ = Stripe::ThreeDSecure.create( card: "tok_123", amount: 1500, currency: "usd", return_url: "https://example.org/3d-secure-result" ) assert_requested :post, "#{Stripe.api_base}/v1/3d_secure" end end end
27.5
72
0.660606
1c7ade7fea0bd5d9d3dcd92632405120239b7e82
164
require_relative 'transaction' module FlexCommerce module PaypalExpress module Exception class NotAuthorized < Transaction end end end end
14.909091
39
0.731707
1cd3ebae6c6afeb67636623b599d28517f727e94
22
module JrubyKafka end
7.333333
17
0.863636
9170e1d5a20d63e46866414279b6a603d2f6e8dd
2,042
# 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::Network::Mgmt::V2016_12_01 module Models # # Response for ListRoutesTable associated with the Express Route Circuits # API. # class ExpressRouteCircuitsRoutesTableListResult include MsRestAzure # @return [Array<ExpressRouteCircuitRoutesTable>] The list of routes # table. attr_accessor :value # @return [String] The URL to get the next set of results. attr_accessor :next_link # # Mapper for ExpressRouteCircuitsRoutesTableListResult class as Ruby # Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ExpressRouteCircuitsRoutesTableListResult', type: { name: 'Composite', class_name: 'ExpressRouteCircuitsRoutesTableListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ExpressRouteCircuitRoutesTableElementType', type: { name: 'Composite', class_name: 'ExpressRouteCircuitRoutesTable' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
29.171429
83
0.529383
1d8f9c6fc41c73840789716608e62488db7c203b
3,210
class ForumPostsController < ApplicationController respond_to :html, :json, :js before_action :member_only, :except => [:index, :show, :search] before_action :moderator_only, only: [:destroy, :unhide] before_action :load_post, :only => [:edit, :show, :update, :destroy, :hide, :unhide] before_action :check_min_level, :only => [:edit, :show, :update, :destroy, :hide, :unhide] skip_before_action :api_check def new if params[:topic_id] @forum_topic = ForumTopic.find(params[:topic_id]) raise User::PrivilegeError.new unless @forum_topic.visible?(CurrentUser.user) && @forum_topic.can_reply?(CurrentUser.user) end if params[:post_id] quoted_post = ForumPost.find(params[:post_id]) raise User::PrivilegeError.new unless quoted_post.topic.visible?(CurrentUser.user) && quoted_post.topic.can_reply?(CurrentUser.user) end @forum_post = ForumPost.new_reply(params) respond_with(@forum_post) end def edit check_privilege(@forum_post) respond_with(@forum_post) end def index @query = ForumPost.permitted.active.search(search_params) @forum_posts = @query.includes(:topic).paginate(params[:page], :limit => params[:limit], :search_count => params[:search]) respond_with(@forum_posts) end def search end def show if request.format == "text/html" && @forum_post.id == @forum_post.topic.original_post.id redirect_to(forum_topic_path(@forum_post.topic, :page => params[:page])) else respond_with(@forum_post) end end def create @forum_post = ForumPost.create(forum_post_params(:create)) page = @forum_post.topic.last_page if @forum_post.topic.last_page > 1 respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => page)) end def update check_privilege(@forum_post) @forum_post.update(forum_post_params(:update)) page = @forum_post.forum_topic_page if @forum_post.forum_topic_page > 1 respond_with(@forum_post, :location => forum_topic_path(@forum_post.topic, :page => page, :anchor => "forum_post_#{@forum_post.id}")) end def destroy check_privilege(@forum_post) @forum_post.destroy respond_with(@forum_post) end def hide check_privilege(@forum_post) @forum_post.hide! respond_with(@forum_post) end def unhide check_privilege(@forum_post) @forum_post.unhide! respond_with(@forum_post) end private def load_post @forum_post = ForumPost.includes(topic: [:category]).find(params[:id]) @forum_topic = @forum_post.topic end def check_min_level raise User::PrivilegeError.new unless @forum_topic.visible?(CurrentUser.user) raise User::PrivilegeError.new if @forum_topic.is_hidden? && !@forum_topic.can_hide?(CurrentUser.user) raise User::PrivilegeError.new if @forum_post.is_hidden? && !@forum_post.can_hide?(CurrentUser.user) end def check_privilege(forum_post) if !forum_post.editable_by?(CurrentUser.user) raise User::PrivilegeError end end def forum_post_params(context) permitted_params = [:body] permitted_params += [:topic_id] if context == :create params.require(:forum_post).permit(permitted_params) end end
32.1
138
0.719003
61e60611ff58be5a6c7894dbf7be6590062af736
3,891
require_relative "../fetcher" require_relative "generator_generation" require_relative "generator_fetcher" require_relative "generator_processor" require_relative "generator_tags" module GitHubChangelogGenerator # Default error for ChangelogGenerator class ChangelogGeneratorError < StandardError end class Generator attr_accessor :options, :filtered_tags, :github # A Generator responsible for all logic, related with change log generation from ready-to-parse issues # # Example: # generator = GitHubChangelogGenerator::Generator.new # content = generator.compound_changelog def initialize(options = nil) @options = options || {} @tag_times_hash = {} @fetcher = GitHubChangelogGenerator::Fetcher.new @options end def fetch_issues_and_pr issues, pull_requests = @fetcher.fetch_closed_issues_and_pr @pull_requests = @options[:pulls] ? get_filtered_pull_requests(pull_requests) : [] @issues = @options[:issues] ? get_filtered_issues(issues) : [] fetch_events_for_issues_and_pr detect_actual_closed_dates(@issues + @pull_requests) end # Encapsulate characters to make markdown look as expected. # # @param [String] string # @return [String] encapsulated input string def encapsulate_string(string) string.gsub! '\\', '\\\\' encpas_chars = %w(< > * _ \( \) [ ] #) encpas_chars.each do |char| string.gsub! char, "\\#{char}" end string end # Generates log for section with header and body # # @param [Array] pull_requests List or PR's in new section # @param [Array] issues List of issues in new section # @param [String] newer_tag Name of the newer tag. Could be nil for `Unreleased` section # @param [String] older_tag_name Older tag, used for the links. Could be nil for last tag. # @return [String] Ready and parsed section def create_log(pull_requests, issues, newer_tag, older_tag_name = nil) newer_tag_link, newer_tag_name, newer_tag_time = detect_link_tag_time(newer_tag) github_site = options[:github_site] || "https://github.com" project_url = "#{github_site}/#{@options[:user]}/#{@options[:project]}" log = generate_header(newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name, project_url) if @options[:issues] # Generate issues: log += issues_to_log(issues) end if @options[:pulls] # Generate pull requests: log += generate_sub_section(pull_requests, @options[:merge_prefix]) end log end # Generate ready-to-paste log from list of issues. # # @param [Array] issues # @return [String] generated log for issues def issues_to_log(issues) log = "" bugs_a, enhancement_a, issues_a = parse_by_sections(issues) log += generate_sub_section(enhancement_a, @options[:enhancement_prefix]) log += generate_sub_section(bugs_a, @options[:bug_prefix]) log += generate_sub_section(issues_a, @options[:issue_prefix]) log end # This method sort issues by types # (bugs, features, or just closed issues) by labels # # @param [Array] issues # @return [Array] tuple of filtered arrays: (Bugs, Enhancements Issues) def parse_by_sections(issues) issues_a = [] enhancement_a = [] bugs_a = [] issues.each do |dict| added = false dict.labels.each do |label| if @options[:bug_labels].include? label.name bugs_a.push dict added = true next end if @options[:enhancement_labels].include? label.name enhancement_a.push dict added = true next end end issues_a.push dict unless added end [bugs_a, enhancement_a, issues_a] end end end
31.379032
106
0.661784
18ec2a7ad66cfeb261e40d58785a16c95fb75b42
167
# frozen_string_literal: true module Macros class Model < Macros::Base register :build register :copy register :destroy register :persist end end
15.181818
29
0.706587
1c010d4befee512ceb2b056e55d2286429a4fee1
5,899
require 'spec_helper' describe 'apache::mod::itk', type: :class do let :pre_condition do 'class { "apache": mpm_module => false, }' end context 'on a Debian OS' do let :facts do { osfamily: 'Debian', operatingsystemrelease: '8', lsbdistcodename: 'jessie', operatingsystem: 'Debian', id: 'root', kernel: 'Linux', path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', is_pe: false, } end it { is_expected.to contain_class('apache::params') } it { is_expected.not_to contain_apache__mod('itk') } it { is_expected.to contain_file('/etc/apache2/mods-available/itk.conf').with_ensure('file') } it { is_expected.to contain_file('/etc/apache2/mods-enabled/itk.conf').with_ensure('link') } context 'with Apache version < 2.4' do let :params do { apache_version: '2.2', } end it { is_expected.not_to contain_file('/etc/apache2/mods-available/itk.load') } it { is_expected.not_to contain_file('/etc/apache2/mods-enabled/itk.load') } it { is_expected.to contain_package('apache2-mpm-itk') } end context 'with Apache version < 2.4 with enablecapabilities set' do let :params do { apache_version: '2.2', enablecapabilities: true, } end it { is_expected.not_to contain_file('/etc/apache2/mods-available/itk.conf').with_content(%r{EnableCapabilities}) } end context 'with Apache version >= 2.4' do let :pre_condition do 'class { "apache": mpm_module => prefork, }' end let :params do { apache_version: '2.4', } end it { is_expected.to contain_file('/etc/apache2/mods-available/itk.load').with('ensure' => 'file', 'content' => "LoadModule mpm_itk_module /usr/lib/apache2/modules/mod_mpm_itk.so\n") } it { is_expected.to contain_file('/etc/apache2/mods-enabled/itk.load').with_ensure('link') } end context 'with Apache version >= 2.4 with enablecapabilities not set' do let :pre_condition do 'class { "apache": mpm_module => prefork, }' end let :params do { apache_version: '2.4', } end it { is_expected.not_to contain_file('/etc/apache2/mods-available/itk.conf').with_content(%r{EnableCapabilities}) } end end context 'on a RedHat OS' do let :facts do { osfamily: 'RedHat', operatingsystemrelease: '6', operatingsystem: 'RedHat', id: 'root', kernel: 'Linux', path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', is_pe: false, } end it { is_expected.to contain_class('apache::params') } it { is_expected.not_to contain_apache__mod('itk') } it { is_expected.to contain_file('/etc/httpd/conf.d/itk.conf').with_ensure('file') } it { is_expected.to contain_package('httpd-itk') } context 'with Apache version < 2.4' do let :params do { apache_version: '2.2', } end it { is_expected.to contain_file_line('/etc/sysconfig/httpd itk enable').with('require' => 'Package[httpd]') } end context 'with Apache version < 2.4 with enablecapabilities set' do let :params do { apache_version: '2.2', enablecapabilities: 'On', } end it { is_expected.not_to contain_file('/etc/httpd/conf.d/itk.conf').with_content(%r{EnableCapabilities}) } end context 'with Apache version >= 2.4' do let :pre_condition do 'class { "apache": mpm_module => prefork, }' end let :params do { apache_version: '2.4', } end it { is_expected.to contain_file('/etc/httpd/conf.d/itk.load').with('ensure' => 'file', 'content' => "LoadModule mpm_itk_module modules/mod_mpm_itk.so\n") } end context 'with Apache version >= 2.4 with enablecapabilities set' do let :pre_condition do 'class { "apache": mpm_module => prefork, }' end let :params do { apache_version: '2.4', enablecapabilities: false, } end it { is_expected.to contain_file('/etc/httpd/conf.d/itk.conf').with_content(%r{EnableCapabilities Off}) } end end context 'on a FreeBSD OS' do let :pre_condition do 'class { "apache": mpm_module => false, }' end let :facts do { osfamily: 'FreeBSD', operatingsystemrelease: '10', operatingsystem: 'FreeBSD', id: 'root', kernel: 'FreeBSD', path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', is_pe: false, mpm_module: 'itk', } end it { is_expected.to contain_class('apache::params') } it { is_expected.not_to contain_apache__mod('itk') } it { is_expected.to contain_file('/usr/local/etc/apache24/Modules/itk.conf').with_ensure('file') } it { is_expected.to contain_package('www/mod_mpm_itk') } context 'with Apache version < 2.4 with enablecapabilities not set' do let :params do { apache_version: '2.2', } end it { is_expected.not_to contain_file('/usr/local/etc/apache24/Modules/itk.conf').with_content(%r{EnableCapabilities}) } end context 'with Apache version >= 2.4 with enablecapabilities set' do let :params do { apache_version: '2.4', enablecapabilities: true, } end it { is_expected.to contain_file('/usr/local/etc/apache24/Modules/itk.conf').with_content(%r{EnableCapabilities On}) } end end end
29.944162
164
0.583319
3975f1afe5fade117a14202f347a5aa3c9deb250
8,352
# encoding: utf-8 require ENV['TM_SUPPORT_PATH'] + '/lib/ui.rb' class RemoteController < ApplicationController ALL_REMOTES = "...all remotes..." include SubmoduleHelper::Update include SubmoduleHelper before_filter :set_script_at_top def set_script_at_top @script_at_top = true end def fetch if (branch = git.branch.current) && (remote = branch.remote) default_remote = remote.name else default_remote = git.remote.names.with_this_at_front("origin").first end for_each_selected_remote(:title => "Fetch", :prompt => "Fetch from which shared repository?", :items => git.remote.names, :default => default_remote) do |remote_name| puts "<h2>Fetching from #{remote_name}</h2>" output = run_fetch(remote_name) puts htmlize(output[:text]) unless output[:fetches].empty? puts("<h2>Log of changes fetched</h2>") output_branch_logs(git, output[:fetches]) end puts "<h2>Pruning stale branches from #{remote_name}</h2>" puts git.command('remote', 'prune', remote_name) puts "<p>Done.</p>" end end def pull if (branch = git.branch.current).nil? puts "You can't pull while not being on a branch (and you are not on a branch). Please switch to a branch, and try again." output_show_html and return end remote_names = git.remote.names.with_this_at_front(branch.remote_name) TextMate::UI.request_item(:title => "Pull", :prompt => "Pull from where?", :items => remote_names) do |remote_name| # check to see if the branch has a pull remote set up. if not, prompt them for which branch to pull from if (remote_name != branch.remote_name) || branch.merge.nil? # select a branch to merge from remote_branch_name = setup_auto_merge(remote_name, branch) return false unless remote_branch_name else remote_branch_name = branch.merge end puts "<p>Pulling from remote source ‘#{remote_name}’ on branch ‘#{branch.name}’</p>" with_submodule_updating do output = run_pull(remote_name, remote_branch_name) puts "<pre>#{output[:text]}</pre>" if ! output[:pulls].empty? puts("<h2>Log of changes pulled</h2>") output_branch_logs(git, output[:pulls]) true elsif output[:nothing_to_pull] puts "Nothing to pull" false end end end end def push if (branch = git.branch.current).nil? puts "You can't push the current branch while not being on a branch (and you are not on a branch). Please switch to a branch, and try again." output_show_html and return end current_name = branch.name for_each_selected_remote(:title => "Push", :prompt => "Select a remote source to push the branch #{current_name} to:", :items => git.remote.names) do |remote_name| puts "<p>Pushing to remote source '#{remote_name}' for branch '#{current_name}'</p>" display_push_output(git, run_push(git, remote_name, :branch => current_name)) git.submodule.all.each do |submodule| next unless (current_branch = submodule.git.branch.current) && (current_branch.tracking_branch_name) case current_branch.tracking_status when :ahead render_submodule_header(submodule) display_push_output(submodule.git, run_push(submodule.git, current_branch.remote_name, :branch => current_branch.name)) when :diverged puts "<p>Can't push submodule '#{submodule.name}' - you need to pull first</p>" end end end end def push_tag tag = params[:tag] || (raise "select tag not yet implemented") for_each_selected_remote(:title => "Push", :prompt => "Select a remote source to push the tag #{tag} to:", :items => git.remote.names) do |remote_name| puts "<p>Pushing tag #{tag} to '#{remote_name}'\n</p>" display_push_output(git, run_push(git, remote_name, :tag => tag)) end end protected def setup_auto_merge(remote_name, branch) remote_branches = git.branch.list_names(:remote, :remote => remote_name ).with_this_at_front(/(\/|^)#{branch.name}$/) remote_branch_name = TextMate::UI.request_item(:title => "Branch to merge from?", :prompt => "Merge which branch to '#{branch.name}'?", :items => remote_branches, :force_pick => true) if remote_branch_name.nil? || remote_branch_name.empty? puts "Aborted" return nil end if TextMate::UI.alert(:warning, "Setup automerge for these branches?", "Would you like me to tell git to always merge:\n #{remote_branch_name} -> #{branch.name}?", 'Yes', 'No') == "Yes" branch.remote_name = remote_name branch.merge = "refs/heads/" + remote_branch_name.split("/").last end remote_branch_name end def display_push_output(git, output) flush sleep(0.2) # this small delay prevents TextMate from garbling the HTML if ! output[:pushes].empty? puts "<pre>#{output[:text]}</pre>" output_branch_logs(git, output[:pushes]) flush elsif output[:nothing_to_push] puts "Nothing to push." puts "<pre>#{output[:text]}</pre><br/>" flush else puts "<h3>Output:</h3>" puts "<pre>#{output[:text]}</pre>" flush end end def output_branch_logs(git, branch_revisions_hash = {}) branch_revisions_hash.each do |branch_name, revisions| puts "<h2>Branch '#{branch_name}': #{short_rev(revisions.first)}..#{short_rev(revisions.last)}</h2>" render_component(:controller => "log", :action => "log", :path => ".", :git_path => git.path, :revisions => [revisions.first, revisions.last]) end end def run_pull(remote_name, remote_branch_name) flush pulls = git.pull(remote_name, remote_branch_name, :start => lambda { |state, count| progress_start(remote_name, state, count) }, :progress => lambda { |state, percentage, index, count| progress(remote_name, state, percentage, index, count)}, :end => lambda { |state, count| progress_end(remote_name, state, count) } ) pulls end def run_push(git, remote_name, options = {}) flush git.push(remote_name, options.merge( :start => lambda { |state, count| progress_start(remote_name, state, count) }, :progress => lambda { |state, percentage, index, count| progress(remote_name, state, percentage, index, count)}, :end => lambda { |state, count| progress_end(remote_name, state, count) } )) end def run_fetch(remote_name) flush git.fetch(remote_name, :start => lambda { |state, count| progress_start(remote_name, state, count) }, :progress => lambda { |state, percentage, index, count| progress(remote_name, state, percentage, index, count)}, :end => lambda { |state, count| progress_end(remote_name, state, count) } ) end def progress_start(remote_name, state, count) puts("<div>#{state} #{count} objects. <span id='#{remote_name}_#{state}_progress'>0% 0 / #{count}</span></div>") end def progress(remote_name, state, percentage, index, count) puts <<-EOF <script type='text/javascript'> $('#{remote_name}_#{state}_progress').update('#{percentage}% #{index} / #{count}') </script> EOF flush end def progress_end(remote_name, state, count) puts <<-EOF <script type='text/javascript'> $('#{remote_name}_#{state}_progress').update('Done') </script> EOF flush end def for_each_selected_remote(options, &block) options = {:title => "Select remote", :prompt => "Select a remote...", :force_pick => true}.merge(options) default = options.delete(:default) remote_names = options[:items] if default remote_names.unshift(default) remote_names.uniq! end remote_names << ALL_REMOTES if remote_names.length > 1 TextMate::UI.request_item(options) do |selections| ((selections == ALL_REMOTES) ? (remote_names-[ALL_REMOTES]) : [selections]).each do |selection| yield selection end end end end
38.311927
192
0.635057
792fe129f7edf96376ca9c907c8c56d2346acf0e
380
cask "tip" do version "2.0.0" sha256 "4d986a461d1b24bb5776fb49063b9a1891939f336b306a6bc75f58d0a4e98bcb" url "https://github.com/tanin47/tip/releases/download/v#{version}/Tip.zip" name "Tip" desc "Programmable tooltip that can be used with any app" homepage "https://github.com/tanin47/tip" app "Tip.app" zap trash: "~/Library/Application Scripts/tanin.tip" end
27.142857
76
0.747368
26bfcf3dc60961189bf25d0d4cc0a87bd18c8504
222
class AddDefaultValueToIsAdminColumn < ActiveRecord::Migration def up change_column :users, :is_admin, :boolean, default: false end def down change_column :users, :is_admin, :boolean, default: nil end end
22.2
62
0.743243
6aef3b02a1495d6eb92538ee7769b15e917cecba
2,843
class VariantsController < ApplicationController include WithComment include WithSoftDeletion actions_without_auth :index, :show, :typeahead_results, :datatable, :gene_index, :entrez_gene_index, :variant_group_index, :myvariant_info_proxy, :allele_registry_proxy, :variant_navigation skip_analytics :typeahead_results, :myvariant_info_proxy, :allele_registry_proxy def index variants = Variant.index_scope .joins(:evidence_items) .order('variants.id asc') .page(params[:page]) .per(params[:count]) .distinct render json: PaginatedCollectionPresenter.new( variants, request, VariantIndexPresenter, PaginationPresenter ) end def gene_index variant_gene_index(:gene_id, :id) end def entrez_gene_index variant_gene_index(:entrez_id, :entrez_id) end def variant_navigation variants = Variant.navigation_scope.where(gene_id: params[:gene_id]) render json: VariantNavigationPresenter.new(variants) end def variant_group_index variants = Variant.index_scope .order('variants.id asc') .page(params[:page]) .per(params[:count]) .joins(:variant_groups) .where(variant_groups: { id: params[:variant_group_id] }) .distinct render json: PaginatedCollectionPresenter.new( variants, request, VariantIndexPresenter, PaginationPresenter ) end def show variant = Variant.view_scope.find_by!(id: params[:id]) render json: VariantDetailPresenter.new(variant) end def destroy variant = Variant.view_scope.find_by!(id: params[:id]) authorize variant soft_delete(variant, VariantDetailPresenter) end def datatable render json: VariantBrowseTable.new(view_context) end def typeahead_results render json: VariantTypeaheadResultsPresenter.new(view_context) end def myvariant_info_proxy render json: MyVariantInfo.new(params[:variant_id]).response end def allele_registry_proxy render json: AlleleRegistry.new(params[:variant_id]).response end private def variant_params params.permit(:name, :description, :genome_build, :chromosome, :start, :stop, :reference_bases, :variant_bases, :representative_transcript, :chromosome2, :start2, :stop2, :reference_build, :representative_transcript2, :ensembl_version, variant_types: []) end def get_variants(param_name, field_name) Variant.index_scope .order('variants.id asc') .page(params[:page]) .per(params[:count]) .where(genes: { field_name => params[param_name] }) end def variant_gene_index(param_name, field_name) variants = get_variants(param_name, field_name) render json: PaginatedCollectionPresenter.new( variants, request, VariantIndexPresenter, PaginationPresenter ) end end
27.07619
258
0.724587
5d705b24eed50579784b23287af59eb27fbacd32
833
require "./lib/waveform/version" Gem::Specification.new do |s| s.name = "waveform" s.version = Waveform::VERSION s.summary = "Generate waveform images from audio files" s.description = "Generate waveform images from audio files. Includes a Waveform class for generating waveforms in your code as well as a simple command-line program called 'waveform' for generating on the command line." s.authors = ["Ben Alavi"] s.email = ["[email protected]"] s.homepage = "http://github.com/klangfeld/waveform" s.files = Dir[ "LICENSE", "README.md", "Rakefile", "lib/**/*.rb", "*.gemspec", "test/**/*.rb", "bin/*" ] s.executables = "waveform" s.add_dependency "ruby-audio-heroku-gem" s.add_dependency "chunky_png" end
30.851852
227
0.619448
e8beab92775bf32a989dcbe049d8a87f1a881532
987
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 RailsPracticeAPI class Application < Rails::Application # 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
41.125
99
0.725431
79de7349bf2cf3405fffc02a2c03ad9ce9136f71
2,961
module SynapsePayRest # Wrapper class for /subnets endpoints # class Subnets # Valid optional args for #get # @todo Refactor to HTTPClient VALID_QUERY_PARAMS = [:page, :per_page].freeze # @!attribute [rw] client # @return [SynapsePayRest::HTTPClient] attr_accessor :client # @param client [SynapsePayRest::HTTPClient] def initialize(client) @client = client end # Sends a GET request to /subnets endpoint. Queries a specific subnet_id # if subnet_id supplied, else queries all transactions. Returns the response. # # @param user_id [String] # @param node_id [String] id of node # @param subnet_id [String,void] (optional) id of a subnet to look up # @param page [String,Integer] (optional) response will default to 1 # @param per_page [String,Integer] (optional) response will default to 20 # # @raise [SynapsePayRest::Error] may return subclasses of error based on # HTTP response from API # # @return [Hash] API response # def get(user_id:, node_id:, subnet_id: nil, **options) path = create_subnet_path(user_id: user_id, node_id: node_id, subnet_id: subnet_id) params = VALID_QUERY_PARAMS.map do |p| options[p] ? "#{p}=#{options[p]}" : nil end.compact path += '?' + params.join('&') if params.any? client.get(path) end # Sends a POST request to /subents endpoint to create a new subnet. # Returns the response. # # @param user_id [String] user_id associated with the subnet # @param node_id [String] node the subnet belongs to # @param payload [Hash] # @see https://docs.synapsepay.com/docs/create-subnet payload structure # # @raise [SynapsePayRest::Error] may return subclasses of error based on # HTTP response from API # # @return [Hash] API response def create(user_id:, node_id:, payload:) path = create_subnet_path(user_id: user_id, node_id: node_id) client.post(path, payload) end # Sends a PATCH request to /subnets endpoint to update a subnet. # Returns the response. # # @param user_id [String] id of user associated with the subnet # @param node_id [String] id of node the subnet belongs to # @param subnet_id [String] id of subnet # @param payload [Hash] # @see https://docs.synapsepay.com/docs/subnet-1 payload structure # # @raise [SynapsePayRest::Error] may return subclasses of error based on # HTTP response from API # # @return [Hash] API response def update(user_id:, node_id:, subnet_id:, payload:) path = create_subnet_path(user_id: user_id, node_id: node_id, subnet_id: subnet_id) client.patch(path, payload) end private def create_subnet_path(user_id:, node_id:, subnet_id: nil) path = "/users/#{user_id}/nodes/#{node_id}/subnets" path += "/#{subnet_id}" if subnet_id path end end end
33.647727
89
0.660925
e2c38ab30403ddcd3ea442f3ffa351d3089a2082
1,878
# frozen_string_literal: true # Copyright 2016-2019 New Context, Inc. # # 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. require "kitchen/terraform/config_schemas/boolean" ::RSpec.shared_examples Kitchen::Terraform::ConfigSchemas::Boolean.to_s do |attribute:| context "when the config omits #{attribute.inspect}" do subject do described_class.new end before do described_class.validations.fetch(attribute).call attribute, subject[attribute], subject end specify "should associate #{attribute.inspect} with true" do expect(subject[attribute]).to be true end end context "when the config associates #{attribute.inspect} with a nonboolean" do subject do described_class.new attribute => "abc" end specify "should raise a Kitchen::UserError" do expect do described_class.validations.fetch(attribute).call attribute, subject[attribute], subject end.to raise_error ::Kitchen::UserError, /#{attribute}.*must be boolean/ end end context "when the config associates #{attribute.inspect} with a boolean" do subject do described_class.new attribute => false end specify "should not raise a Kitchen::UserError" do expect do described_class.validations.fetch(attribute).call attribute, subject[attribute], subject end.not_to raise_error end end end
32.37931
96
0.731097
f79dc780542f8d0a23695fade195236658e014d6
1,123
require('sinatra') require('sinatra/reloader') also_reload('lib/**/*.rb') require('./lib/vehicle') require('./lib/dealership') get('/') do erb(:index) end get('/dealerships') do @dealerships = Dealership.all() erb(:dealerships) end get('/dealerships/new') do erb(:dealerships_form) end post('/dealerships') do name = params.fetch('name') @dealership = Dealership.new({:name => name}).save() erb(:dealership_success) end get('/dealerships/:id') do @dealership = Dealership.find(params.fetch('id').to_i()) erb(:dealership) end get('/dealerships/:id/vehicles/new') do @dealership = Dealership.find(params.fetch('id').to_i()) erb(:dealership_vehicles_form) end post('/vehicles') do make = params.fetch('make') model = params.fetch('model') year = params.fetch('year') @vehicle = Vehicle.new({:make => make, :model => model, :year => year}) @vehicle.save() @dealership = Dealership.find(params.fetch('dealership_id').to_i()) @dealership.add_vehicle(@vehicle) erb(:vehicle_success) end get('/vehicles/:id') do @vehicle = Vehicle.find(params.fetch('id').to_i()) erb(:vehicle) end
22.019608
73
0.680321
792e493f23e006a46bb788d804ff282013c08f90
103
require 'spec_helper' describe Domain do pending "add some examples to (or delete) #{__FILE__}" end
17.166667
56
0.747573
335fc653b3e77c74009511bb44e76704f3122d6c
3,352
# -*- encoding: utf-8 -*- # stub: ransack 1.8.9 ruby lib Gem::Specification.new do |s| s.name = "ransack".freeze s.version = "1.8.9" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Ernie Miller".freeze, "Ryan Bigg".freeze, "Jon Atack".freeze, "Sean Carroll".freeze] s.date = "2018-08-09" s.description = "Ransack is the successor to the MetaSearch gem. It improves and expands upon MetaSearch's functionality, but does not have a 100%-compatible API.".freeze s.email = ["[email protected]".freeze, "[email protected]".freeze, "[email protected]".freeze, "[email protected]".freeze] s.homepage = "https://github.com/activerecord-hackery/ransack".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 1.9".freeze) s.rubyforge_project = "ransack".freeze s.rubygems_version = "2.7.6".freeze s.summary = "Object-based searching for Active Record and Mongoid (currently).".freeze s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<actionpack>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_runtime_dependency(%q<activerecord>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_runtime_dependency(%q<activesupport>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_runtime_dependency(%q<i18n>.freeze, [">= 0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3"]) s.add_development_dependency(%q<machinist>.freeze, ["~> 1.0.6"]) s.add_development_dependency(%q<faker>.freeze, ["~> 0.9.5"]) s.add_development_dependency(%q<sqlite3>.freeze, ["~> 1.3.3"]) s.add_development_dependency(%q<pg>.freeze, ["~> 0.21"]) s.add_development_dependency(%q<mysql2>.freeze, ["= 0.3.20"]) s.add_development_dependency(%q<pry>.freeze, ["= 0.10"]) else s.add_dependency(%q<actionpack>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<activerecord>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<activesupport>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<i18n>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3"]) s.add_dependency(%q<machinist>.freeze, ["~> 1.0.6"]) s.add_dependency(%q<faker>.freeze, ["~> 0.9.5"]) s.add_dependency(%q<sqlite3>.freeze, ["~> 1.3.3"]) s.add_dependency(%q<pg>.freeze, ["~> 0.21"]) s.add_dependency(%q<mysql2>.freeze, ["= 0.3.20"]) s.add_dependency(%q<pry>.freeze, ["= 0.10"]) end else s.add_dependency(%q<actionpack>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<activerecord>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<activesupport>.freeze, ["<= 5.1.1", ">= 3.0"]) s.add_dependency(%q<i18n>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3"]) s.add_dependency(%q<machinist>.freeze, ["~> 1.0.6"]) s.add_dependency(%q<faker>.freeze, ["~> 0.9.5"]) s.add_dependency(%q<sqlite3>.freeze, ["~> 1.3.3"]) s.add_dependency(%q<pg>.freeze, ["~> 0.21"]) s.add_dependency(%q<mysql2>.freeze, ["= 0.3.20"]) s.add_dependency(%q<pry>.freeze, ["= 0.10"]) end end
51.569231
172
0.633055
87e380b76c65d3f134f1e535db91463b79ab713f
1,344
# frozen_string_literal: true require 'rails_helper' RSpec.describe Stocks::Destroy do let(:operation) { described_class.new(params) } describe '#call' do let!(:bearer) { create(:bearer, name: 'Bearer') } let!(:stock) { create(:stock, name: 'Stock', bearer: bearer) } let(:params) { { id: stock.id } } def operation_call operation.call end context 'success' do it_behaves_like 'operations/success' it 'destroys a stock' do expect { operation_call }.to change(Stock, :count).from(1).to(0) end it 'destroys a stock for a related bearer' do expect { operation_call }.to change(bearer.stocks, :count).from(1).to(0) end it 'does not a destroy a related bearer ' do expect { operation_call }.not_to change(Bearer, :count) end end context 'failure' do let(:message) { 'Record cannot be destroyed' } let(:expected_error_messages) { [message] } before do allow(Stock).to receive(:find).and_return(stock) allow(stock) .to receive(:destroy!) .and_raise(ActiveRecord::RecordNotDestroyed, message) end it_behaves_like 'operations/failure' it 'does not destroy the stock' do expect { operation_call }.not_to change(Stock, :count) end end end end
25.846154
80
0.630208
f7d4bfcd859b3edb4ffe91aa18de9346033a5e1b
485
Euler.register_language('c', Class.new do def run solution dir = File.dirname(file_path(solution)) Dir.chdir(dir) `gcc #{file_path(solution)} -o #{solution.dir}/solution` `#{solution.dir}/solution` end def init solution FileUtils.cp(template_path, file_path(solution)) end private def file_path solution "#{solution.dir}/#{solution.problem.id}.c" end def template_path "#{File.dirname(__FILE__)}/../templates/c.c" end end)
21.086957
60
0.661856
1dffd16954c86225cee259c3db2d1b2ec2f8246d
1,482
require "spec_helper" describe Spree::CheckoutController, type: :controller do let(:token) { 'some_token' } let(:user) { create(:user) } let(:order) { create(:order_with_line_items) } let(:payment_method) { create(:check_payment_method) } before do allow(controller).to receive_messages try_spree_current_user: user allow(controller).to receive_messages spree_current_user: user allow(controller).to receive_messages current_order: order allow(order).to receive_messages checkout_steps: ["address", "delivery", "payment", "confirm", "complete"] order.update_attributes! user: user end def patch_payment patch :update, params: { state: "payment", order: { payments_attributes: [payment_method_id: payment_method.id] } } end context "PATCH #update" do context "Using a payment method without a redirect url" do it "proceed to the confirm step" do patch_payment expect(response).to redirect_to(spree.checkout_state_path(:confirm)) end end context "Using a payment method with a redirect url" do before do allow_any_instance_of( Spree::PaymentMethod ).to receive_messages( has_redirect_url?: true, redirect_url: "http://example.com" ) end it "redirects to the payment method site" do patch_payment expect(response).to redirect_to("http://example.com") end end end end
29.058824
110
0.673414
797e7c8b0b0e4552d8a97c24f945e9b36d26c089
103
module DesignPattern module Behavioral class Visitor def definition; end end end end
12.875
25
0.699029
ab8434c1d2f5687b998dd995f50db1465a4f0972
783
module Ebay # :nodoc: module Types # :nodoc: # == Attributes # text_node :pickup_method, 'PickupMethod', :optional => true # text_node :pickup_store_id, 'PickupStoreID', :optional => true # text_node :pickup_status, 'PickupStatus', :optional => true # text_node :merchant_pickup_code, 'MerchantPickupCode', :optional => true class PickupMethodSelected include XML::Mapping include Initializer root_element_name 'PickupMethodSelected' text_node :pickup_method, 'PickupMethod', :optional => true text_node :pickup_store_id, 'PickupStoreID', :optional => true text_node :pickup_status, 'PickupStatus', :optional => true text_node :merchant_pickup_code, 'MerchantPickupCode', :optional => true end end end
35.590909
79
0.698595
7acc3299506c491856adadfa698cb30610baa525
2,681
module Catalog class ApprovalTransition attr_reader :order_item_id attr_reader :order_item attr_reader :state def initialize(order_item_id) @order_item = OrderItem.find(order_item_id) @approvals = @order_item.approval_requests end def process Insights::API::Common::Request.with_request(@order_item.context.transform_keys(&:to_sym)) do state_transitions end self end private def state_transitions if approved? @state = "Approved" submit_order elsif denied? @state = "Denied" mark_denied elsif canceled? @state = "Canceled" mark_canceled elsif error? @state = "Failed" mark_errored else @state = "Pending" ::Catalog::OrderStateTransition.new(@order_item.order).process end end def submit_order @order_item.update_message("info", "Submitting Order #{@order_item.order_id} for provisioning ") Catalog::SubmitOrder.new(@order_item.order_id).process finalize_order rescue ::Catalog::TopologyError => e Rails.logger.error("Error Submitting Order #{@order_item.order_id}, #{e.message}") @order_item.update_message("error", "Error Submitting Order #{@order_item.order_id}, #{e.message}") end def mark_canceled finalize_order @order_item.update_message("info", "Order #{@order_item.order_id} has been canceled") Rails.logger.info("Order #{@order_item.order_id} has been canceled") end def mark_denied finalize_order @order_item.update_message("info", "Order #{@order_item.order_id} has been denied") Rails.logger.info("Order #{@order_item.order_id} has been denied") end def mark_errored finalize_order @order_item.update_message("error", "Order #{@order_item.order_id} has approval errors. #{reasons}") Rails.logger.error("Order #{@order_item.order_id} has failed. #{reasons}") end def finalize_order @order_item.update(:state => @state) Catalog::OrderStateTransition.new(@order_item.order).process end def approved? @approvals.present? && @approvals.all? { |req| req.state == "approved" } end def denied? @approvals.present? && @approvals.any? { |req| req.state == "denied" } end def canceled? @approvals.present? && @approvals.any? { |req| req.state == "canceled" } end def error? @approvals.present? && @approvals.any? { |req| req.state == "error" } end def reasons return "" if @approvals.blank? @approvals.collect(&:reason).compact.join('. ') end end end
28.221053
106
0.64752
79f2dc18111e703c5f8f02333b7d64ace8475ed6
2,136
=begin * Puppet Module : Provder: netdev * Author : Ganesh Nalawade * File : puppet/provider/netdev_groups/junos.rb * Version : 2014-11-10 * Platform : EX | QFX | MX * Description : * * The Provider class definition to implement the * netdev_lag type. There isn't really anything in * this file; refer to puppet/provider/junos.rb for details. * * Copyright (c) 2012 Juniper Networks. All Rights Reserved. * * YOU MUST ACCEPT THE TERMS OF THIS DISCLAIMER TO USE THIS SOFTWARE, * IN ADDITION TO ANY OTHER LICENSES AND TERMS REQUIRED BY JUNIPER NETWORKS. * * JUNIPER IS WILLING TO MAKE THE INCLUDED SCRIPTING SOFTWARE AVAILABLE TO YOU * ONLY UPON THE CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS * DISCLAIMER. PLEASE READ THE TERMS AND CONDITIONS OF THIS DISCLAIMER * CAREFULLY. * * THE SOFTWARE CONTAINED IN THIS FILE IS PROVIDED "AS IS." JUNIPER MAKES NO * WARRANTIES OF ANY KIND WHATSOEVER WITH RESPECT TO SOFTWARE. ALL EXPRESS OR * IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY WARRANTY * OF NON-INFRINGEMENT OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR A * PARTICULAR PURPOSE, ARE HEREBY DISCLAIMED AND EXCLUDED TO THE EXTENT * ALLOWED BY APPLICABLE LAW. * * IN NO EVENT WILL JUNIPER BE LIABLE FOR ANY DIRECT OR INDIRECT DAMAGES, * INCLUDING BUT NOT LIMITED TO LOST REVENUE, PROFIT OR DATA, OR * FOR DIRECT, SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY ARISING OUT OF THE * USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF JUNIPER HAS BEEN ADVISED OF * THE POSSIBILITY OF SUCH DAMAGES. =end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..","..")) require 'puppet/provider/junos/junos_group' Puppet::Type.type(:netdev_group).provide(:junos_group, :parent => Puppet::Provider::Junos::Group) do @doc = "Junos Configuration Group" has_feature :activable ### invoke class method to autogen the default property methods for both Puppet ### and the netdev module. That's it, yo! mk_resource_methods mk_netdev_resource_methods end
40.301887
100
0.745787
7a8eeee3b05efeed153433760024c76318c22ec2
197
require 'rails_helper' feature 'user visits homepage' do scenario 'successfully' do visit root_path expect(page).to have_css 'h1', text: 'Welcome to Your Customized Training Plans!' end end
21.888889
83
0.761421
1d189dbf44e376260d9659a06a80c8b041e865ed
2,795
require 'vertx-web/routing_context' require 'vertx/util/utils.rb' # Generated from io.vertx.ext.web.handler.BodyHandler module VertxWeb # A handler which gathers the entire request body and sets it on the . # <p> # It also handles HTTP file uploads and can be used to limit body sizes. class BodyHandler # @private # @param j_del [::VertxWeb::BodyHandler] the java delegate def initialize(j_del) @j_del = j_del end # @private # @return [::VertxWeb::BodyHandler] the underlying java delegate def j_del @j_del end # @param [::VertxWeb::RoutingContext] arg0 # @return [void] def handle(arg0=nil) if arg0.class.method_defined?(:j_del) && !block_given? return @j_del.java_method(:handle, [Java::IoVertxExtWeb::RoutingContext.java_class]).call(arg0.j_del) end raise ArgumentError, "Invalid arguments when calling handle(arg0)" end # Create a body handler with defaults # @return [::VertxWeb::BodyHandler] the body handler def self.create if !block_given? return ::Vertx::Util::Utils.safe_create(Java::IoVertxExtWebHandler::BodyHandler.java_method(:create, []).call(),::VertxWeb::BodyHandler) end raise ArgumentError, "Invalid arguments when calling create()" end # Set the maximum body size -1 means unlimited # @param [Fixnum] bodyLimit the max size # @return [self] def set_body_limit(bodyLimit=nil) if bodyLimit.class == Fixnum && !block_given? @j_del.java_method(:setBodyLimit, [Java::long.java_class]).call(bodyLimit) return self end raise ArgumentError, "Invalid arguments when calling set_body_limit(bodyLimit)" end # Set the uploads directory to use # @param [String] uploadsDirectory the uploads directory # @return [self] def set_uploads_directory(uploadsDirectory=nil) if uploadsDirectory.class == String && !block_given? @j_del.java_method(:setUploadsDirectory, [Java::java.lang.String.java_class]).call(uploadsDirectory) return self end raise ArgumentError, "Invalid arguments when calling set_uploads_directory(uploadsDirectory)" end # Set whether form attributes will be added to the request parameters # @param [true,false] mergeFormAttributes true if they should be merged # @return [self] def set_merge_form_attributes(mergeFormAttributes=nil) if (mergeFormAttributes.class == TrueClass || mergeFormAttributes.class == FalseClass) && !block_given? @j_del.java_method(:setMergeFormAttributes, [Java::boolean.java_class]).call(mergeFormAttributes) return self end raise ArgumentError, "Invalid arguments when calling set_merge_form_attributes(mergeFormAttributes)" end end end
41.716418
144
0.703757
bf6c2e4f3bc7008bc391f1e12b052267094b7824
177
Rails.configuration.stripe = { :publishable_key => ENV['PUBLISHABLE_KEY'], :secret_key => ENV['SECRET_KEY'] } Stripe.api_key = Rails.configuration.stripe[:secret_key]
25.285714
56
0.717514
abb8c25d2f779ab8757b0d5f64f24881f0130922
1,945
require File.expand_path('../boot', __FILE__) require 'rails/all' # If you have a Gemfile, require the gems listed there, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) if defined?(Bundler) module Rails4Root class Application < Rails::Application # 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. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{config.root}/extras ) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # Configure generators values. Many other options are available, be sure to check the documentation. # config.generators do |g| # g.orm :active_record # g.template_engine :erb # g.test_framework :test_unit, :fixture => true # end # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters << :password config.eager_load = false end end
42.282609
104
0.712596
11781a386a086b159d3f03e36d0e44e35d8c72b6
129
name "collectd-client" description "Collectd client" run_list( "role[base]", "recipe[collectd-graphite::collectd-client]" )
16.125
46
0.736434
f8c36fd4eb33c79844cde876eec03ec398d08733
5,203
require "testing_env" require "tab" require "formula" class TabTests < Homebrew::TestCase def setup @used = Options.create(%w[--with-foo --without-bar]) @unused = Options.create(%w[--with-baz --without-qux]) @tab = Tab.new("used_options" => @used.as_flags, "unused_options" => @unused.as_flags, "built_as_bottle" => false, "poured_from_bottle" => true, "time" => nil, "HEAD" => TEST_SHA1, "compiler" => "clang", "stdlib" => "libcxx", "source" => { "tap" => "Homebrew/homebrew", "path" => nil, "spec" => "stable" }) end def test_defaults tab = Tab.empty assert_empty tab.unused_options assert_empty tab.used_options refute_predicate tab, :built_as_bottle refute_predicate tab, :poured_from_bottle assert_nil tab.tap assert_nil tab.time assert_nil tab.HEAD assert_equal MacOS.default_compiler, tab.cxxstdlib.compiler assert_nil tab.cxxstdlib.type end def test_include? assert_includes @tab, "with-foo" assert_includes @tab, "without-bar" end def test_with? assert @tab.with?("foo") assert @tab.with?("qux") refute @tab.with?("bar") refute @tab.with?("baz") end def test_universal? tab = Tab.new(:used_options => %w[--universal]) assert_predicate tab, :universal? end def test_cxxstdlib assert_equal :clang, @tab.cxxstdlib.compiler assert_equal :libcxx, @tab.cxxstdlib.type end def test_other_attributes assert_equal TEST_SHA1, @tab.HEAD assert_equal "Homebrew/homebrew", @tab.tap.name assert_nil @tab.time refute_predicate @tab, :built_as_bottle assert_predicate @tab, :poured_from_bottle end def test_from_old_version_file path = Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt_old.json") tab = Tab.from_file(path) assert_equal @used.sort, tab.used_options.sort assert_equal @unused.sort, tab.unused_options.sort refute_predicate tab, :built_as_bottle assert_predicate tab, :poured_from_bottle assert_equal "Homebrew/homebrew", tab.tap.name assert_equal :stable, tab.spec refute_nil tab.time assert_equal TEST_SHA1, tab.HEAD assert_equal :clang, tab.cxxstdlib.compiler assert_equal :libcxx, tab.cxxstdlib.type end def test_from_file path = Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt.json") tab = Tab.from_file(path) assert_equal @used.sort, tab.used_options.sort assert_equal @unused.sort, tab.unused_options.sort refute_predicate tab, :built_as_bottle assert_predicate tab, :poured_from_bottle assert_equal "Homebrew/homebrew", tab.tap.name assert_equal :stable, tab.spec refute_nil tab.time assert_equal TEST_SHA1, tab.HEAD assert_equal :clang, tab.cxxstdlib.compiler assert_equal :libcxx, tab.cxxstdlib.type end def test_to_json tab = Tab.new(Utils::JSON.load(@tab.to_json)) assert_equal @tab.used_options.sort, tab.used_options.sort assert_equal @tab.unused_options.sort, tab.unused_options.sort assert_equal @tab.built_as_bottle, tab.built_as_bottle assert_equal @tab.poured_from_bottle, tab.poured_from_bottle assert_equal @tab.tap, tab.tap assert_equal @tab.spec, tab.spec assert_equal @tab.time, tab.time assert_equal @tab.HEAD, tab.HEAD assert_equal @tab.compiler, tab.compiler assert_equal @tab.stdlib, tab.stdlib end def test_remap_deprecated_options deprecated_options = [DeprecatedOption.new("with-foo", "with-foo-new")] remapped_options = Tab.remap_deprecated_options(deprecated_options, @tab.used_options) assert_includes remapped_options, Option.new("without-bar") assert_includes remapped_options, Option.new("with-foo-new") end end class TabLoadingTests < Homebrew::TestCase def setup @f = formula { url "foo-1.0" } @f.prefix.mkpath @path = @f.prefix.join(Tab::FILENAME) @path.write Pathname.new(TEST_DIRECTORY).join("fixtures", "receipt.json").read end def teardown @f.rack.rmtree end def test_for_keg tab = Tab.for_keg(@f.prefix) assert_equal @path, tab.tabfile end def test_for_keg_nonexistent_path @path.unlink tab = Tab.for_keg(@f.prefix) assert_nil tab.tabfile end def test_for_formula tab = Tab.for_formula(@f) assert_equal @path, tab.tabfile end def test_for_formula_nonexistent_path @path.unlink tab = Tab.for_formula(@f) assert_nil tab.tabfile end def test_for_formula_multiple_kegs f2 = formula { url "foo-2.0" } f2.prefix.mkpath assert_equal @f.rack, f2.rack assert_equal 2, @f.installed_prefixes.length tab = Tab.for_formula(@f) assert_equal @path, tab.tabfile end def test_for_formula_outdated_keg f2 = formula { url "foo-2.0" } assert_equal @f.rack, f2.rack assert_equal 1, @f.installed_prefixes.length tab = Tab.for_formula(f2) assert_equal @path, tab.tabfile end end
29.39548
90
0.673842