repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
hlfcoding/UAFInteractiveNavigationController
UAFInteractiveNavigationController.podspec
Pod::Spec.new do |s| s.name = "UAFInteractiveNavigationController" s.version = "0.1.3" s.summary = "UAFInteractiveNavigationController makes life easier." s.description = <<-DESC UAFInteractiveNavigationController mirrors UINavigationController behavi...
p/jira-proxy
config/deploy.rb
load 'deploy' set :application, 'issues' role :web, 'etal.bsdpower.com' set :user, 'jiraproxy' set :deploy_to, "/home/#{user}/#{application}" set :cache_dir, "/var/cache/#{application}" set :scm, :subversion set :repository, "http://svn.bsdpower.com/webtools/jira-proxy/trunk" set :deploy_via, :export set :keep_rel...
nnhansg/xero-ruby
accounting/spec/models/organisation_spec.rb
=begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'spec_helper' require 'json' requi...
nnhansg/xero-ruby
accounting/lib/xero-ruby/version.rb
<gh_stars>1-10 =begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end module XeroRuby VERSION =...
nnhansg/xero-ruby
accounting/spec/models/schedule_spec.rb
=begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'spec_helper' require 'json' requi...
nnhansg/xero-ruby
accounting/spec/models/expense_claim_spec.rb
=begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'spec_helper' require 'json' requi...
nnhansg/xero-ruby
accounting/spec/models/tax_rate_spec.rb
<gh_stars>1-10 =begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'spec_helper' requi...
gregdardis/grocery-list-server
db/migrate/20180403230813_create_grocery_lists.rb
class CreateGroceryLists < ActiveRecord::Migration[5.1] def change create_table :grocery_lists do |t| # table has an ID by default t.string :title t.string :owner t.string :last_modified_by t.timestamp :created_at t.timestamps end end end
gregdardis/grocery-list-server
app/models/grocery_item.rb
class GroceryItem < ApplicationRecord belongs_to :grocery_list end
gregdardis/grocery-list-server
app/models/grocery_list.rb
<reponame>gregdardis/grocery-list-server<filename>app/models/grocery_list.rb<gh_stars>1-10 class GroceryList < ApplicationRecord has_many :grocery_items, dependent: :destroy end
gregdardis/grocery-list-server
app/controllers/grocery_items_controller.rb
class GroceryItemsController < ApplicationController # (GET) get all grocery items for a list # PATH: /grocery_lists/:grocery_list_id/grocery_items def index @grocery_items = GroceryList.find(params[:grocery_list_id]).grocery_items # status :ok = 200 render status: :ok, json: @grocery_items end ...
gregdardis/grocery-list-server
app/controllers/grocery_lists_controller.rb
class GroceryListsController < ApplicationController # (GET) get all grocery lists # PATH: /grocery_lists def index @grocery_lists = GroceryList.all # status :ok = 200 render status: :ok, json: @grocery_lists end # (POST) create new grocery list # PATH: /grocery_lists def create # initia...
gregdardis/grocery-list-server
config/routes.rb
Rails.application.routes.draw do resources :grocery_lists do resources :grocery_items end end
jerrywdlee/iuliana-challenges
app/graphql/types/update_user_type.rb
module Types class UpdateUserType < Types::BaseInputObject argument :email, String, required: false argument :password, String, required: false argument :name, String, required: false argument :img_url, String, required: false argument :roles, [String], required: false, description: "Roles i...
jerrywdlee/iuliana-challenges
app/graphql/mutations/delete_user.rb
module Mutations class DeleteUser < BaseMutation description "Delete User" # return fields field :user, Types::UserType, null: false # define arguments argument :id, ID, required: true, description: "Delete User by ID" # define resolve method def resolve(id:) Util.auth_user_graphql...
jerrywdlee/iuliana-challenges
app/graphql/types/city_type.rb
<reponame>jerrywdlee/iuliana-challenges module Types class CityType < Types::BaseObject field :id, ID, null: false field :name, String, null: false field :houses, [Types::HouseType], null: true field :datasets, [Types::DatasetType], null: true end end
jerrywdlee/iuliana-challenges
app/graphql/mutations/new_user.rb
module Mutations class NewUser < BaseMutation description "Add New User" # return fields field :user, Types::UserType, null: false # define arguments argument :user, Types::NewUserType, required: true, description: "User Info" # define resolve method def resolve(user:) Util.a...
jerrywdlee/iuliana-challenges
app/lib/data_process.rb
<filename>app/lib/data_process.rb class DataProcess class << self # calc average energy_production per house for cities def house_energy_prod_time_series DataProcess.cities_datasets_time_series(:energy_production) end # calc average energy_production per person for cities def person_energy_...
jerrywdlee/iuliana-challenges
app/controllers/contents_controller.rb
<gh_stars>0 class ContentsController < ApplicationController # GET /contents # GET /contents.json def index # If has `public/index.html`, this action will be ignored end end
jerrywdlee/iuliana-challenges
app/models/user.rb
<reponame>jerrywdlee/iuliana-challenges class User < ApplicationRecord include Devise::JWT::RevocationStrategies::JTIMatcher # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :r...
jerrywdlee/iuliana-challenges
app/services/data_series_service.rb
class DataSeriesService def date_labels Dataset.order(:year, :month).distinct .pluck(:year, :month).map do |year, month| DataProcess.date_str(year, month) end end def house_energy_prod DataProcess.house_energy_prod_time_series end def person_energy_prod DataProcess.person_energy_...
jerrywdlee/iuliana-challenges
spec/graphql/dataset_type_spec.rb
<gh_stars>0 require "rails_helper" RSpec.describe "GraphQL on DatasetType" do it "Should return all datasets" do query = <<~GRAPHQL { datasets { id } } GRAPHQL data = Util.graphql_query(query) expect(data["datasets"].size).to be > 0 end it "Should find datasets by ransack" do...
jerrywdlee/iuliana-challenges
spec/models/user_spec.rb
<reponame>jerrywdlee/iuliana-challenges<gh_stars>0 require "rails_helper" RSpec.describe User, type: :model do before do @user = User.first end it "Should create a user" do email = "<EMAIL>" pass = "<PASSWORD>" @user = User.create!({ email: email, password: <PASSWORD>, password_confi...
jerrywdlee/iuliana-challenges
spec/graphql/app_config_type_spec.rb
<reponame>jerrywdlee/iuliana-challenges require "rails_helper" RSpec.describe "GraphQL on AppConfigType" do it "Should Get total_watt_url from challenge2" do query = <<~GRAPHQL { appConfigs { challenge2 { totalWattUrl } } } GRAPHQL data = Util.graphql_query(query)["appConfigs"] ex...
jerrywdlee/iuliana-challenges
app/graphql/types/app_config_input_type.rb
module Types class GeneralInputType < Types::BaseInputObject argument :allow_graphiql, Boolean, required: false argument :show_demo_user, Boolean, required: false end class Challenge2InputType < Types::BaseInputObject argument :total_watt_url, String, required: false end class Challenge3InputTyp...
jerrywdlee/iuliana-challenges
spec/access/data_loader_spec.rb
require "rails_helper" RSpec.describe "DataLoader" do it "Should load house_data.csv from URL" do uri = "https://raw.githubusercontent.com/jerrywdlee/EnergyDataSimulationChallenge/master/challenge3/data/house_data.csv" DataLoader.load_houses(uri) house_num = House.all.size expect(house_num).to be > 0...
jerrywdlee/iuliana-challenges
spec/graphql/user_type_spec.rb
require "rails_helper" RSpec.describe "GraphQL on User" do it "Should get all users" do query = <<~GRAPHQL { users { id, email, name, roles } } GRAPHQL context = { current_user: User.admin.first } data = Util.graphql_query(query, context: context)["users"] e...
jerrywdlee/iuliana-challenges
spec/services/data_series_service_spec.rb
require "rails_helper" RSpec.describe "DataSeriesService" do before do @data_series = DataSeriesService.new end it "Should return date_labels" do date_labels = @data_series.date_labels expect(date_labels.size).to be > 0 expect(date_labels.first).to include "-" end it "Should return house_en...
jerrywdlee/iuliana-challenges
app/graphql/types/house_type.rb
<reponame>jerrywdlee/iuliana-challenges<gh_stars>0 module Types class HouseType < Types::BaseObject field :id, ID, null: false field :firstname, String, null: false field :lastname, String, null: false field :full_name, String, null: false # field :city_text, String, null: false # field :city_...
jerrywdlee/iuliana-challenges
app/graphql/types/user_type.rb
<filename>app/graphql/types/user_type.rb module Types class UserType < Types::BaseObject field :id, ID, null: false field :email, String, null: false field :name, String, null: false field :img_url, String, null: false field :roles, [String], null: false field :roles_code, Integer, null: false...
jerrywdlee/iuliana-challenges
db/schema.rb
<reponame>jerrywdlee/iuliana-challenges # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is...
jerrywdlee/iuliana-challenges
app/controllers/users/sessions_controller.rb
# frozen_string_literal: true class Users::SessionsController < Devise::SessionsController skip_before_action :verify_authenticity_token # before_action :configure_sign_in_params, only: [:create] # GET /resource/sign_in def new super end # POST /resource/sign_in def create if request.xhr? ...
jerrywdlee/iuliana-challenges
app/graphql/types/mutation_type.rb
module Types class MutationType < Types::BaseObject field :new_user, mutation: Mutations::NewUser field :update_user, mutation: Mutations::UpdateUser field :delete_user, mutation: Mutations::DeleteUser field :update_app_config, mutation: Mutations::UpdateAppConfig end end
jerrywdlee/iuliana-challenges
spec/graphql/city_type_spec.rb
require "rails_helper" RSpec.describe "GraphQL on CityType" do it "Should find city by name" do city = City.all.last query = <<~GRAPHQL { city(name: "#{city.name}") { id, name } } GRAPHQL data = Util.graphql_query(query) expect(data.dig("city", "id")).to eq city.id.to_s end ...
jerrywdlee/iuliana-challenges
app/models/city.rb
<reponame>jerrywdlee/iuliana-challenges class City < ApplicationRecord has_many :houses has_many :datasets, through: :houses validates :name, uniqueness: true end
jerrywdlee/iuliana-challenges
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # skip_before_action :verify_authenticity_token # protect_from_forgery with: :null_session end
jerrywdlee/iuliana-challenges
app/models/dataset.rb
class Dataset < ApplicationRecord belongs_to :house has_one :city, through: :house validates_presence_of :label, :year, :month, :temperature, :daylight, :energy_production scope :order_by_date, -> { order(:year, :month) } def date_str DataProcess.date_str(year, month) end end # Columns: # label, hou...
jerrywdlee/iuliana-challenges
app/controllers/api_controller.rb
class ApiController < ApplicationController skip_before_action :verify_authenticity_token before_action :authenticate_user!, except: [:default_user] def default_user if EasySettings.default_user.show render json: EasySettings.default_user elsif AppConfig.general[:show_demo_user] render json: ...
jerrywdlee/iuliana-challenges
spec/models/dataset_spec.rb
<filename>spec/models/dataset_spec.rb require "rails_helper" RSpec.describe Dataset, type: :model do before do @dataset = Dataset.first end it "Should find a Dataset" do expect(@dataset).to be_truthy end it "Should have relations on city" do expect(@dataset.city).to be_truthy end it "Shoul...
jerrywdlee/iuliana-challenges
app/graphql/types/date_time_type.rb
<gh_stars>0 module Types class DateTimeType < Types::BaseScalar description "ActiveRecord::Type::DateTime" end end
jerrywdlee/iuliana-challenges
app/graphql/mutations/update_app_config.rb
module Mutations class UpdateAppConfig < BaseMutation description "Update application configs" # return fields field :app_configs, Types::AppConfigType, null: false # arguments argument :app_configs, Types::AppConfigInputType, required: true, description: "App configs, Partial update availb...
jerrywdlee/iuliana-challenges
spec/graphql/data_series_type_spec.rb
<reponame>jerrywdlee/iuliana-challenges require "rails_helper" RSpec.describe "GraphQL on DataSeriesType" do it "Should get date_labels" do query = <<~GRAPHQL { dataSeries { dateLabels } } GRAPHQL data = Util.graphql_query(query)["dataSeries"] expect(data["dateLabels"].size).to be...
jerrywdlee/iuliana-challenges
app/graphql/types/dataset_type.rb
module Types class DatasetType < Types::BaseObject field :id, ID, null: false field :label, Integer, null: false field :house_id, Integer, null: false field :house, Types::HouseType, null: false field :city, Types::CityType, null: false field :year, Integer, null: false field :month, Integ...
jerrywdlee/iuliana-challenges
spec/models/city_spec.rb
require "rails_helper" RSpec.describe City, type: :model do before do @city = City.first end it "Should find a city" do expect(@city).to be_truthy end it "Should have relations on houses" do expect(@city.houses).to be_truthy end it "Should have relations on datasets" do expect(@city.da...
jerrywdlee/iuliana-challenges
spec/controllers/api_controller_spec.rb
require "rails_helper" RSpec.describe ApiController, type: :controller do it "Create dummy users" do email = "<EMAIL>" pass = "<PASSWORD>" @admin_user = User.create!({ email: email, password: <PASSWORD>, password_confirmation: <PASSWORD>, roles: ["admin"] }) email = "<EMAIL>" ...
jerrywdlee/iuliana-challenges
spec/access/graphiql_spec.rb
require "rails_helper" require "devise/jwt/test_helpers" headers = { "Accept" => "application/json", "Content-Type" => "application/json", } RSpec.describe "Test GraphiQL Page Shown", type: :request do it "Create dummy users" do email = "<EMAIL>" pass = "<PASSWORD>" @admin_user = User.create({ ...
jerrywdlee/iuliana-challenges
app/models/house.rb
<reponame>jerrywdlee/iuliana-challenges class House < ApplicationRecord has_many :datasets belongs_to :city, optional: true validates_presence_of :firstname, :lastname, :city_text, :num_of_people, :has_child enum has_child: { Yes: true, No: false, } def has_child_bool has_child_before_type_cas...
jerrywdlee/iuliana-challenges
config/routes.rb
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root "contents#index" devise_for :users, controllers: { sessions: "users/sessions", } resources :api, only: [] do collection do get :default_user get :user...
jerrywdlee/iuliana-challenges
config/initializers/graphiql.rb
<reponame>jerrywdlee/iuliana-challenges<filename>config/initializers/graphiql.rb # See https://github.com/rmosolgo/graphiql-rails GraphiQL::Rails.config.headers['Authorization'] = -> (context) { # this `context` is a `view_context` # allow iframe use context.headers['X-Frame-Options'] = 'ALLOWALL' # eg: localh...
jerrywdlee/iuliana-challenges
spec/graphql/mutations/update_app_config_spec.rb
require "rails_helper" RSpec.describe "GraphQL Mutation on AppConfigs" do it "Create dummy users" do email = "<EMAIL>" pass = "<PASSWORD>" @admin_user = User.create!({ email: email, password: <PASSWORD>, password_confirmation: <PASSWORD>, roles: ["admin"] }) email = "<EMAIL>" ...
jerrywdlee/iuliana-challenges
app/graphql/mutations/update_user.rb
module Mutations class UpdateUser < BaseMutation description "Update User Info" # return fields field :user, Types::UserType, null: false # define arguments argument :id, ID, required: true, description: "Find User by ID for Update" argument :user, Types::UpdateUserType, required: true,...
jerrywdlee/iuliana-challenges
app/lib/util.rb
require "json" class Util class << self def form_ransack_params(params) param_org = params.deep_dup param_res = {} if param_org.instance_of?(String) param_org = JSON.parse(param_org) end param_org.each do |key, val| key = key.to_s.underscore if (key == "s" ||...
jerrywdlee/iuliana-challenges
spec/graphql/mutations/update_user_spec.rb
<filename>spec/graphql/mutations/update_user_spec.rb require "rails_helper" RSpec.describe "Create and update user by GraphQL Mutation" do it "Create dummy users" do email = "<EMAIL>" pass = "<PASSWORD>" @admin_user = User.create({ email: email, password: <PASSWORD>, password_confirmation: <P...
jerrywdlee/iuliana-challenges
spec/graphql/house_type_spec.rb
<filename>spec/graphql/house_type_spec.rb require "rails_helper" RSpec.describe "GraphQL on HouseType" do it "Should exec house query" do query = <<~GRAPHQL { house(id: 1) { firstname, lastname } } GRAPHQL data = Util.graphql_query(query) house = House.find(1) expect(data.dig(...
jerrywdlee/iuliana-challenges
spec/models/house_spec.rb
require "rails_helper" RSpec.describe House, type: :model do before do @house = House.first end it "Should find a house" do expect(@house).to be_truthy end it "Should have relations on city" do expect(@house.city).to be_truthy end it "Should have relations on datasets" do expect(@house...
jerrywdlee/iuliana-challenges
db/migrate/20190612075751_create_datasets.rb
class CreateDatasets < ActiveRecord::Migration[5.2] def change create_table :datasets do |t| t.integer :label t.integer :house_id t.integer :year t.integer :month t.float :temperature t.float :daylight t.integer :energy_production t.timestamps end add_index...
jerrywdlee/iuliana-challenges
app/graphql/types/app_config_type.rb
<filename>app/graphql/types/app_config_type.rb module Types class GeneralType < Types::BaseObject field :allow_graphiql, Boolean, null: false field :show_demo_user, Boolean, null: false end class Challenge2Type < Types::BaseObject field :total_watt_url, String, null: false end class Challenge3Ty...
jerrywdlee/iuliana-challenges
app/graphql/types/data_series_type.rb
<filename>app/graphql/types/data_series_type.rb module Types class DataSeriesType < Types::BaseObject field :date_labels, [String], null: false field :house_energy_prod, GraphQL::Types::JSON, null: false field :person_energy_prod, GraphQL::Types::JSON, null: false field :temperature, GraphQL::Types::J...
jerrywdlee/iuliana-challenges
app/graphql/types/new_user_type.rb
module Types class NewUserType < Types::UpdateUserType argument :email, String, required: true argument :password, String, required: true end end
jerrywdlee/iuliana-challenges
lib/tasks/build_admin.rake
namespace :vue_admin do task clean: :environment do system('echo "Clean up before assets:precompile"') public_path = Rails.root.join('public') cmd = [] cmd << "rm -rf #{public_path.join('precache-manifest.*')}" cmd << "rm -rf #{public_path.join('css')}" cmd << "rm -rf #{public_path.join('js')}...
jerrywdlee/iuliana-challenges
app/graphql/types/query_type.rb
<gh_stars>0 module Types class QueryType < Types::BaseObject # Add root-level fields here. # They will be entry points for queries on your schema. # TODO: Fix vulnerability of circular reference # Eg: `house(id: 1) { datasets { house { datasets { house { id } } } } }` field :house, Types::HouseTy...
jerrywdlee/iuliana-challenges
app/lib/data_loader.rb
require "csv" require "open-uri" class DataLoader class << self ### For Challenge 3 ### def load_houses(uri) file = load_file_as_stream(uri) ActiveRecord::Base.transaction do CSV.new(file, **csv_options).each do |line| # CSV headers: # :id, :firstname, :lastname, :city...
jerrywdlee/iuliana-challenges
db/migrate/20190612070709_create_houses.rb
<filename>db/migrate/20190612070709_create_houses.rb<gh_stars>0 class CreateHouses < ActiveRecord::Migration[5.2] def change create_table :houses do |t| t.string :firstname t.string :lastname t.string :city_text t.integer :city_id t.integer :num_of_people t.boolean :has_child ...
jerrywdlee/iuliana-challenges
app/models/app_config.rb
<reponame>jerrywdlee/iuliana-challenges<gh_stars>0 # RailsSettings Model class AppConfig < RailsSettings::Base cache_prefix { "v1" } @field_keys = [] def self.field(key, **opts) @field_keys << key.to_sym super(key, **opts) end def self.field_keys @field_keys end field :general, type: :hash...
ixti/redis-lockers
lib/redis/lockers/lock.rb
# frozen_string_literal: true require "securerandom" require "concurrent/utility/monotonic_time" require "redis/prescription" class Redis module Lockers # Single lock instance. class Lock LOCK_SCRIPT = Redis::Prescription.read("#{__dir__}/scripts/lock.lua") private_constant :LOCK_SCRIPT ...
ixti/redis-lockers
spec/redis/lockers_spec.rb
# frozen_string_literal: true require "redis/lockers" RSpec.describe Redis::Lockers do describe ".acquire" do it "yields control when lock was acquired" do expect { |b| described_class.acquire(REDIS, :xxx, :ttl => 7000, &b) }. to yield_control end it "releases lock lease even if block fai...
ixti/redis-lockers
redis-lockers.gemspec
# frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "redis/lockers/version" Gem::Specification.new do |spec| spec.name = "redis-lockers" spec.version = Redis::Lockers::VERSION spec.authors = ["<NAME>"] s...
ixti/redis-lockers
lib/redis/lockers.rb
<reponame>ixti/redis-lockers # frozen_string_literal: true require "redis/lockers/version" require "redis/lockers/lock" # @see https://github.com/redis/redis-rb class Redis # Distributed locks with Redis. module Lockers # Creates new lock and yields control if it was successfully acquired. # Ensures lock ...
ixti/redis-lockers
spec/redis/lockers/lock_spec.rb
<gh_stars>1-10 # frozen_string_literal: true require "redis/lockers/lock" RSpec.describe Redis::Lockers::Lock do let(:alpha) { described_class.new(:xxx, :ttl => 123_456) } let(:omega) { described_class.new(:xxx, :ttl => 123_456) } describe "#acquire" do it "returns true if lock was acquired" do expec...
ixti/redis-lockers
lib/redis/lockers/version.rb
# frozen_string_literal: true class Redis module Lockers # Gem version. VERSION = "1.1.0" end end
petertseng/adventofcode-rb-2019
07_amplification_circuit.rb
require_relative 'lib/intcode' VERBOSE = ARGV.delete('-v') def const_input(mem, phase, input) ic = Intcode.new(mem, valid_ops: (1..8).to_a + [99]).continue(input: phase) ic.continue(input: input) until ic.halted? ic.output end # Assume each amplifier performs a linear mx+b transform. # Determine m and b by run...
petertseng/adventofcode-rb-2019
24_planet_of_discord.rb
<reponame>petertseng/adventofcode-rb-2019 SIDE_LEN = 5 NUM_ITERS = Hash.new(200) NUM_ITERS[1205552] = 10 # Only 4 values are important: 0, 1, 2, 3+ (dead for sure) # that's 2 bits BITS_PER_NEIGHBOUR_COUNT = 2 NEIGHBOUR_COUNT_MASK = (1 << BITS_PER_NEIGHBOUR_COUNT) - 1 # For deciding whether a cell is alive at the nex...
petertseng/adventofcode-rb-2019
mk17.rb
<reponame>petertseng/adventofcode-rb-2019 def scaffold(path) robot_loc = [0, 0].freeze move = ->dir { robot_loc.zip(dir).map(&:sum).freeze } dir = [-1, 0] prev_inter = false scaffold = {robot_loc => true} path.split(?,) { |x| if x == ?R dir = right(dir) next elsif x == ?L dir = ...
petertseng/adventofcode-rb-2019
weightgame.rb
def half_bits(n) raise "sorry must be even" if n % 2 != 0 # Information not known to the player: # The eight items each weigh a power of two, # and the answer is four items. (0...(1 << n)).select { |x| x.to_s(2).count(?1) == n / 2 } end def powerset(n) (0...(1 << n)).to_a end def play_game(limit, answer,...
petertseng/adventofcode-rb-2019
05_intcode_ii.rb
require_relative 'lib/intcode' DISAS = ARGV.delete('-d') def ic(mem, input) ops = (1..8).to_a + [99] Intcode.new(mem, valid_ops: ops).then { |ic| ic.continue(disas: DISAS, input: input) }.output end input = (ARGV[0]&.include?(?,) ? ARGV[0] : ARGF.read).split(?,).map(&method(:Integer)).freeze output = ic(input, ...
petertseng/adventofcode-rb-2019
01_rocket_equation.rb
def fuel(mass) mass / 3 - 2 end def fuel_of_fuel(mass) Enumerator.produce(fuel(mass), &method(:fuel)).take_while(&:positive?).sum # Another idea: https://blog.vero.site/post/advent-rocket # d3 = (mass + 3).digits(3) # (mass - d3.sum + 15) / 2 - d3[-1] - 3 * d3.size end input = ARGF.each_line.map(&method(:In...
petertseng/adventofcode-rb-2019
03_crossed_wires.rb
<filename>03_crossed_wires.rb # Two possible approaches: # 1. Store a set of all points touched by each wire, # do a set intersection. # # 2. Store all segment endpoints and intersect them. # # Turns out, the second one is faster. # 0 = unchanging coordinate # 1 = changing coordinate min # 2 = changing coordinate m...
petertseng/adventofcode-rb-2019
19_tractor_beam.rb
<filename>19_tractor_beam.rb require_relative 'lib/intcode' count_drones = ARGV.delete('-c') slowscan = ARGV.delete('--slowscan') slowpull = ARGV.delete('-s') || ARGV.delete('--slowpull') input = (ARGV[0]&.include?(?,) ? ARGV[0] : ARGF.read).split(?,).map(&method(:Integer)).freeze @drones_sent = 0 if slowpull IC ...
petertseng/adventofcode-rb-2019
12_n_body_problem.rb
def step(poses, vels) poses.each_with_index { |pi, i| # pi = 2, p = 5, we want it to increase. # so we do 5 <=> 2 which is 1. vels[i] += poses.sum { |p| p <=> pi } } vels.each_with_index { |vel, i| poses[i] += vel } end def run1k(moons) pos = moons.dup vel = moons.map { 0 } 1000.times { step(p...
petertseng/adventofcode-rb-2019
golf9_spaced.rb
m=$*.shift.split(?,).map &:to_i; b=z=0; while(c=m[z])!=99; y=-2; a,(r,q)=m[z+1,3].map{|x| d=c.to_s[y-=1]; x||=0; [ x+=d==?2?b:0, d==?1?x:m[x]||0 ] }.transpose; # Since 0 is not a valid opcode, # index from the back instead of the front, # saving one array entry (2 bytes) but cost...
petertseng/adventofcode-rb-2019
21_springdroid_adventure.rb
<reponame>petertseng/adventofcode-rb-2019<gh_stars>10-100 require_relative 'lib/intcode' VERBOSE = ARGV.delete('-v') def run(mem, script, **args) Intcode.new(mem).continue(input: script, **args) end def show_damage(ic) puts ic.output.select { |x| x <= 127 }.pack('c*') if VERBOSE puts ic.output.select { |x| x >...
petertseng/adventofcode-rb-2019
02_intcode.rb
require_relative 'lib/intcode' def run(mem, noun, verb) mem = mem.dup mem[1] = noun mem[2] = verb Intcode.new(mem, valid_ops: [1, 2, 99]).then(&:continue).memory[0] end input = (ARGV[0]&.include?(?,) ? ARGV[0] : ARGF.read).split(?,).map(&method(:Integer)).freeze puts run(input, 12, 2) # Note that for known ...
petertseng/adventofcode-rb-2019
13_breakout.rb
<gh_stars>10-100 require_relative 'lib/intcode' def affine(mem) score_func = Intcode.functions(mem)[-1] nums = mem[score_func].each_cons(4).filter_map { |op, a1, a2, d| next if op != 21101 && op != 21102 [d, op == 21101 ? a1 + a2 : a1 * a2] }.to_h a = nums[2] b = nums[3] m = nums[4] game_grid =...
petertseng/adventofcode-rb-2019
22_slam_shuffle.rb
def simplify_at(steps, i, deck_size) return unless (op2, arg2 = steps[i + 1]) op1, arg1 = steps[i] # Adjacent pairs of the same operation can be combined. # (dealwith by multiplication, cut by addition, reverse by elimination) # # Adjacent pairs of different operation can be transposed, # if applying an ...
petertseng/adventofcode-rb-2019
20_donut_maze.rb
require_relative 'lib/search' def parse_maze(flat_input, height, width) portal_pairs = Hash.new { |h, k| h[k] = {outer: nil, inner: nil} } portal_entrances = {} dirs = [-width, width, -1, 1].freeze flat_input.each_char.with_index { |cell, pos| next if pos < width next unless flat_input[pos + width] ...
petertseng/adventofcode-rb-2019
lib/search.rb
<filename>lib/search.rb require_relative 'priority_queue' module Search module_function def path_of(prevs, n) path = [n] current = n while (current = prevs[current]) path.unshift(current) end path end def astar(start, neighbours:, heuristic:, goal:) g_score = Hash.new(1.0 / 0.0)...
petertseng/adventofcode-rb-2019
06_universal_orbit_map.rb
<filename>06_universal_orbit_map.rb require_relative 'lib/search' input = ARGF.each_line.map(&:chomp) orbit = {} transfer = Hash.new { |h, k| h[k] = [] } input.each { |x| a, b = x.split(?)) orbit[b] = a transfer[a] << b transfer[b] << a } orbit.freeze transfer.freeze # Not convinced the cache makes that bi...
petertseng/adventofcode-rb-2019
18_many_worlds_interpretation.rb
require_relative 'lib/search' def bitfield(chars, range) base = range.begin.ord chars.select { |c| range.cover?(c) }.map { |c| 1 << (c.ord - base) }.reduce(0, :|) end def key_to_key(flat_input, width, sources) # AoC-specific optimisation: # For all paths between key -> key that contain doors, # the doors bl...
petertseng/adventofcode-rb-2019
16_flawed_frequency_transmission.rb
<reponame>petertseng/adventofcode-rb-2019<filename>16_flawed_frequency_transmission.rb def fft(digits) sum = 0 sum_left = digits.map { |d| sum += d } sum_left.unshift(0) digits.each_index { |i| n = i + 1 sign = 1 base = i total = 0 while base < digits.size total += ((sum_left[base + n...
petertseng/adventofcode-rb-2019
09_intcode_relative.rb
require_relative 'lib/intcode' OPT = !ARGV.delete('--no-opt') SPARSE = ARGV.delete('-sp') DISAS_DYNAMIC = ARGV.delete('-dd') disas_static = ARGV.delete('-ds') stats = ARGV.delete('-s') def run(mem, input) Intcode.new(mem, sparse: SPARSE, funopt: OPT).continue(disas: DISAS_DYNAMIC, input: input).output end mem = (A...
petertseng/adventofcode-rb-2019
08_space_image_format.rb
verbose = ARGV.delete('-v') width = 25 layer = width * 6 input = ARGF.read.chomp layers = input.each_char.each_slice(layer).to_a min_layer = layers.min_by { |x| x.count(?0) } p min_layer.tally if verbose puts min_layer.count(?1) * min_layer.count(?2) pixels = layers.transpose.map { |pixel| pixel.find { |layer| lay...
petertseng/adventofcode-rb-2019
plain_intcode.rb
<reponame>petertseng/adventofcode-rb-2019<gh_stars>10-100 require_relative 'lib/intcode' DISAS_DYNAMIC = ARGV.delete('-dd') disas_static = ARGV.delete('-ds') MEM = ARGV.delete('-m') STATS = ARGV.delete('-s') def run(mem, inputs) mem = mem.dup inputs = inputs.dup Intcode.new(mem).continue(stats: STATS, disas: DI...
petertseng/adventofcode-rb-2019
11_intcode_langtons_ant.rb
require 'set' require_relative 'lib/intcode' # Unknown grid size # we'll assume they won't exceed approx 1<<29 in each direction. # Two coordinates; (1<<60).object_id indicates it is still Fixnum, not Bignum. COORD = 30 Y = 1 << COORD ORIGIN = (Y / 2) << COORD | (Y / 2) L = -1 R = 1 U = -Y D = Y TURN = [ # 0 = lef...
petertseng/adventofcode-rb-2019
15_intcode_search.rb
require_relative 'lib/intcode' require_relative 'lib/search' # Unknown grid size (well, I know it's 41x41, but without that knowledge) # we'll assume they won't exceed approx 1<<29 in each direction. # Two coordinates; (1<<60).object_id indicates it is still Fixnum, not Bignum. COORD = 30 Y = 1 << COORD ORIGIN = (Y / ...
petertseng/adventofcode-rb-2019
10_monitoring_station.rb
<gh_stars>10-100 TO_DESTROY = 200 def asteroid_in_direction(start, dy, dx, asteroids, height, width) # Be careful here. # You cannot just add (dy * width + dx) to (y * width + x) blindly. # You might wrap around a row when you're not supposed to. # (To detect this, see whether y changed more than you expected ...
petertseng/adventofcode-rb-2019
23_category_six.rb
<reponame>petertseng/adventofcode-rb-2019<filename>23_category_six.rb require_relative 'lib/intcode' # vars prefixed with an underscore are not used by this implementation, # but may be used as temporaries by the Intcode implementation. Computer = Struct.new(:sent, :tmp1, :_tmp2, :_tmp3, :_y, :slot_divisor, :rx_slots,...
petertseng/adventofcode-rb-2019
25_cryostasis.rb
require_relative 'lib/intcode' def find_string(mem, str) expected_delta = str.chars.each_cons(2).map { |a, b| (b.ord - 1) - a.ord } deltas = mem.each_cons(2).map { |a, b| b - a } substr_starts = deltas.each_cons(str.size - 1).each_with_index.filter_map { |ds, i| i if ds == expected_delta } first_char = ...
petertseng/adventofcode-rb-2019
unspace_golf.rb
code = File.readlines('golf9_spaced.rb').map(&:strip).grep_v(/^ *#/).join File.open('golf9.rb', ?w) { |f| f.write(code) } def run(script, day, input) `echo #{input} | ruby #{script} $(tail -1 #{day}*.rb)` end def compare(in1, in2, day) ps1 = run('golf9_spaced.rb', day, in1).lines.drop_while { |x| x == "0\n" }.jo...
petertseng/adventofcode-rb-2019
17_set_and_forget.rb
<filename>17_set_and_forget.rb require_relative 'lib/intcode' def exactly_one(name, things) raise "need exactly one #{name}, not #{things}" if things.size != 1 things[0] end def modes(op) [(op / 100) % 10, (op / 1000) % 10] end def read_intcode_map(mem) _, dust_update = find_dust(mem) width = mem[dust_upd...
petertseng/adventofcode-rb-2019
14_space_stoichiometry.rb
def ore_to_make(things, leftovers = Hash.new(0), ceil: true, verbose: false) puts "make #{things} w/ leftovers #{leftovers.select { |_, v| v > 0 }}" if verbose return things[:ORE] if things.keys == [:ORE] ore_to_make({}.merge(*things.map { |thing, amount_needed| next {ORE: amount_needed} if thing == :ORE ...