instruction
stringlengths
71
95.1k
The full project is up on GitHub. The codebase is super small as it stands. I'm brand new to reactive programming and Spring, and would mostly like insight on those two things. Asynchronous programming is also one of my weak points, because I'm really used to synchronous program structure - hence the need for help with...
I have created a large VBA program to automate creation of a data table that is needed to run slicers in an Excel file. While the loop works well in creating what I need, the main loop take an hour to create the list of company names that I need. I was wondering if there is a way to improve the time it takes for the lo...
I've decided to reproduce the JQuery selector - specifically for finding elements by class name, ID, and tag So for example the tests could be written like $('.box') === domSelector('.box') // Class $('#box') === domSelector('#box') // ID $('input') === domSelector('input') // Tag Here is my approach to the problem. I...
I have a function I have written in VB for use in SSRS 2012. It takes an integer and converts it to full text duration - for example 900 becomes "15 minutes", 9000 becomes "2 hours 30 minutes", and 7201 is "2 hours 1 second". The code works, and is: Public Function SecondsFullText(ByVal TotalSeconds As Integer) As Stri...
I made a script for a project I'm working on to create a tree object from a filesystem directory, without any working tree operations (can be run in a bare repository). The tree can be inserted into (a) commit(s) by using an index filter that invokes git read-tree --prefix=</...>. #!/bin/bash # createSubtreeRec <path> ...
I started working on a notification system that is pluggable into any project. I have not made any "plugin" type javascript libraries, usually just functions very specific to the project at hand. That said I wanted to reach out for pointers to avoid conflicts in both javascript (and css). I'm aware specificity is key i...
I'm rather new to programming. So far I've only done some small coding tasks once every now and then, and this the first "bigger" project for me. I love the idea of object-oriented programming and I've heard a lot of good things about Python and Pygame, so I decided to give it a shot and get coding. The result is a hou...
I don't find this algorithm in Go language here, so I just want to check that it is really most efficient algorithm in Go: func checkUnique(s *string) bool { var a [256]bool for _, ascii := range *s { if a[ascii] { return false } a[ascii] = true } return true }
An update to this post can be found here I've been writing some functions used to find paths between two types of triangles - alphas and betas. Alphas are triangles that have been in a zone we consider important, have an "interesting" value above a given threshold, and are "active". Betas are essentially anything that ...
This is my attempt on the Python 3 Sal's Shipping challenge on Codecademy (Challenge Link (instructions in the link)). I'd really appreciate anyone to take the time to review my code. I'm a very new to programming and I really wanna improve my coding, so all feedback is apreciated. def groundCost(weight): if weight >...
This is the original question: https://www.geeksforgeeks.org/run-length-encoding/ Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6”. the only change I did is t...
This is the original question https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/ Given two sorted arrays, find their union and intersection. Example: Input : arr1[] = {1, 3, 4, 5, 7} arr2[] = {2, 3, 5, 6} Output : Union : {1, 2, 3, 4, 5, 6, 7} Intersection : {3, 5} Input...
Coding challenge: Convert a given long URL into a Tiny URL. The length of this Tiny URL should be fixed and the same for all URLs. You should return the full URL if given a shortened URL. I am aware this code is technically flawed as there will be clashes owing to the limitations of the hash function in Python. ...
I was asked this question in an interview: Given a string s consisting of 0, 1 and ?. The question mark can be either 0 or 1. Find all possible combinations for the string. I came up with below code but I wanted to know whether it is the best way to solve the problem? public static void main(String[] args) { ...
New to programming with the goal being to create my own roguelike. I am mostly interested right now in creating my item generation system. I want the code to create a random item that can then be used, stored in an inventory etc. Want to know if the below is a smart way to begin with. Any suggestions to make the below ...
I just write a simple method which returns a string based on the number in accepts as a parameter. I used if/elif/esle here but I think for this simple scenario I wrote long code. I want to know is it possible to shorten this code in any way except using a lambda method. Also, I'm interested to know about the performan...
This is based upon an exercise in chapter 5 of Automate the Boring Stuff with Python. This code contains functions addToInventory which modifies a given inventory of items to add new items as well as update existing items and displayInventory which displays the items and their values. The main operation is adding the ...
I have a more massive sp, in which I use some temporary tables, below is a part of the sp where I am updating a field in a temporary table two times. Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from ( Select v.AccountId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJo...
I have a users table where some users have the same name: +----+------+ | id | name | +----+------+ | 1 | Joe | | 2 | Joey | | 3 | Joe | +----+------+ ... and a purchases table: +---------+--------+ | user_id | a...
I would like to know how I might improve my code? I just started coding and liking it a few days ago so I am quite new to this whole world... The objective is to calculate the amount of water one has drunk in a day. Depending on the user's input, the app tells him or her if the amount of water drunk is great or not. N...
This is a simple implementation of IO completion ports in user mode for Linux. In Windows IO completion ports work like this: There is a global queue for issuing IO requests. Some worker kernel threads pop from this queue and operate on each request. There is a queue associated with each port you create. When you assoc...
I made this easy game to improve my C++. The functions like NoFlicker and ShowCursor are copied from the Internet, but I made AlignString by myself and I'm proud of it. Function changeP() swaps players. Before I created this function and edited my code, I had player1pick and player2pick; now it's more clear. Function ...
Here is my code, which doesn't seem to work for numbers in between -1 and 0 (works perfectly fine otherwise) I think the code enters an infinite loop, somehow, hence I get no result after entering the number. Please have a look and let me know what changes should be made. I am a beginner at programming and would apprec...
I tried to make a function able to compute the binary sum. Binary numbers are passed as list composed of 1 and 0, like [1,1,0,1], [0,0,1], etc. It seems to work. I tried to improve the code, but I don't think this is the best way to make it work. How can I improve this? def check(value): if value%2 == 0: #check if...
I am doing an image drawing and rendering library, and would like some feedback on this code, it simply draws a line in any direction. The equation for that is: m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 y = mx + b It works but all these if statements are bothering me, and I am not sure if it's the best solution. proc l...
Here is my code for the KenKen puzzle: The user must fill in each embolded regions with numbers in the range 1-n where n is the board dimensions (e.g: 4*4, n=4) such that the total of that region equals the target number in the corner using the designated symbol. Each row and column MUST contain the numbers 1-4 only ...
I have this ProductSearchContainer.js file that it's getting too long to handle and maintain. What it's responsible for: Doing network requests to get a list of products Filter that list with filters values it gets from URL query string and update state with the new filteredList It also holds functions to simulate the...
SELECT pl_from, NS, page_title, L_NS, L_titles, num_L, SB, IU, WP FROM ( SELECT pl_from, -- pl_from_namespace does not appear to be consistently reliable; -- it might be better to select from the page table and join the pagelinks table to it. CASE -- This fails on pages missing from the page table (presumab...
I'm working on prepared statements for my website and I'm wondering if it's possible to have multiple prepared statements one after another. In this example, I have 2 select statements. I'm hoping that the question marks I have as placeholders won't be overwriting one another. After that's been answered, I was wonder...
I started to learn Python not long ago to automate certain tasks I work on. I want to optimize a script I wrote that takes a line in an Excel file and prints a pattern of text based on this line's content. Here's an example of output from my code: mgmt_cli add access-rule layer "network" position bottom name "thirdline...
I came up with the following code by following Prof. Sedgewick's lecture on Coursera. Please review this code and let me know if there is anything that I got wrong in implementing Kruskal's algorithm. I'd also like to know what is Big-O complexity of this algorithm. import java.util.ArrayDeque; import java.util.Pri...
Create a user class with id, name, age. Write a function to get users older than age 20. Group all users with same age and increment users age by 3 Is there a cleaner way to write this? Any comments are appreciated. const userList=[]; const userAboveTwenty= []; class User { constructor(name,id,age){ this.name=n...
The program is a little code about guns with user input. The program is a perfect representation of the beauty of functions. What do you think of it? import sys import time #determines reload time def reloading(reload_time): print('\nReloading', end='') for dot in range(reload_time): time.sleep(1) ...
I recently cloned a classical Spider Solitaire game from Microsoft Windows XP. I implemented almost all features of the game. Please tell me anything I can do in order to improve my coding style. Other suggestions are welcome. The link to resources here: https://github.com/Marethyu12/JSpider import java.awt.Color; impo...
How could I make my code follow the DRY principle? I feel like they are better ways to do things in my code. So any feedback will help me! js fiddle: https://jsfiddle.net/fr6ut238/ /*--------------------------- Variables ---------------------------*/ const $containerGrid = $(".containerGrid"); ...
I developed the function array_includes which checks if an array contains a value and returns it. I would like to know if there is already such a function which is more efficient or how I can make the function more efficient. <?php $params = "colorgroup-b;test;abc"; $paramsArr = explode(";", $params); var_dump(array_i...
After watching this presentation, I decided that it would be a good project for me to undergo to practice my python skills. A summary of the presentation: Jack Diederich, the presenter, talks about the overuse of classes in programming. A phrase he used a lot was "you shouldn't be writing a class if it has two methods...
This is a problem from Automate the Boring Stuff from "Pattern Matching with Regular Expression". I am a beginner in Python and the purpose of this program is to match urls which start with http:// or https://, with some urls having an optional www. after https:// How can this code be improved? #! /usr/bin/python3 #web...
I made a WPF Application, called Palindrome Checker, which checks if what you input is a palindrome. Any and all tips on how to make this code better in all capacities are wanted and appreciated. public class Check { /// <summary> /// Method for checking if the word/text is a palindrome. /// </summary> ...
I am attempting to port a linear function that I designed in a spreadsheet into HTML and Javascript. It's based on linear least squares where I have to take a Matrix and multiply it by its transformation. At any rate. I am attempting to lay out a basic input system in Javascript/HTML where I can enter in variable data...
I practiced my Java knowledge in the last couple of days. For that, I want to create a Rest API in a trimmed scale, because there a lot of aspects which must be considered in such an API (Login, Session handling ...). A lot of details aren't implemented, but the top priority was to understand the interaction/communicat...
I tried to solve some Euler's problems, this is the solution I found for problem #3 with Python. The problem asks: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? How can I improve my code? def get_largest_prime2(value): start = time.clock() #used to m...
I wrote some code to generate Latin hypercube samples for interpolation over high-dimensional parameter spaces. Latin hypercubes are essentially collections of points on a hypercube that are placed on a cubic/rectangular grid, which possess the property that no two points share any individual coordinate, and every row/...
Here is the problem: some script is injecting some HTML5 elements (actually a button with the #thebutton ID) to the current DOM. But this is a third party script and I have no control of when this will be injected to the page. I need to click automatically on this button when the button is injected to the DOM. Here is...
I'm new to C++ programming, and I'm building an Image Editor software like Lightroom/CameraRaw from scratch. Apart from procedural code (actually seems that all the functions works correctly) my goal is to improve the Design of my classes. For this I used OpenCV just for basics functions like opening/reading, convertin...
I decided to implement Conways Game of Life for my first project using Rust. I also haven't had much code review ever, and have been looking for a good critique of my code so I can improve my skills. Here is the code: extern crate glutin_window; extern crate graphics; extern crate piston; extern crate piston_window; u...
This code pre-calculates the winning combinations for an n-sized tic tac toe board. I first created my function using an imperative approach. This is just how I naturally write code most of the time. I then tried to think about the problem using a "What I want to accomplish?" approach, rather than "What do I want it ...
I'm trying to solve this question: Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. ...
As many have done on this site, I decided to create a progress indicator using a modeless Userform. However, my goal was to make said progress indicator as generic/reusable as possible. While doing some research, I stumbled upon @MathieuGuindon's post titled The Reusable Progress Indicator. I quite liked his ideas, so ...
Are there any efficient ways to solve this problem, for example using bitwise operator? public static boolean isPal(long num) { String numStr = Long.toString(num); String rNumStr = ""; boolean result = false; for (int i = numStr.length() - 1; i >= 0 ; --i) rNumStr ...
How would I go about shortening this code? I'm sure there's a smarter way to write the code. It's working fine, it's just ugly. It is a way to scrape the number of items on an e-commerce site. import requests from bs4 import BeautifulSoup import re url1 = "https://us.pandora.net/en/charms/?sz=30&start={}&format=page-...
This post is an update of the one from here. I've updated the code and a couple pieces of the post itself. I've been writing some functions used to find paths between two types of triangles - alphas and betas. Alphas are triangles that have been in a zone we consider important, have an "interesting" value above a given...
I have started the Hackerrank interview preparation kit. The first problem I have solved with Swift is as follows: Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equa...
Going through Head First C#'s Chapter 8: Enums and Collections, I learned about List<T>, as well as IComparable<T> and IComparer<T>. One exercise near the end asked to make a program to draw cards at random, then sort them. I wanted to go the extra mile and make a fully usable, realistic card deck (their solution just ...
When I saw this amazing data structure I couldn't stop myself from trying it! I first sought resources such as this and an article about it here. It basically works as a Max-Heap and a Min-Heap at the same time. I was heavily based on these amazing Java implementations here and here. This implementation is a macro that...
This code moves one element from one unordered_map to another. I would like to ask if my code below can be improved. #include <iostream> #include <string> #include <vector> #include <utility> #include <unordered_map> int main() { struct Data { int foo; bool boo; }; std::unordered_map<st...
This is a problem from "Automate the boring stuff". Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You m...
I want to execute a python script daily and thereby want to schedules task as follows. The idea is that the script will run once daily, and the script will then decide what tasks to be done today. The reason is that I can't use cron or windows scheduled task on my environment. The question is that, is there any better ...
Recently I've been toying around with C# interop and the Vulkan API. Today I discovered the SafeHandle class and decided I'd try to wrap the Windows API calls that I depend upon; please see the code below and let me know if I've made any errors during the implementation process. Code: public static class Library { ...
I am beginner in python and I am learing about syntax and other functions in python by writing Algorithm and Data Structure programs. How can this code be improved? def get_input(): #to get input from user input_str = input("Enter elements to be sorted: ") try: lst = list(map(int, input_str.split())) #m...
Below is my solution for the LeetCode Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Outpu...
I have completed my bank ATM application in C# class library project. For simplicity, the data of this version will be stored in the List instead of a database. The basic feature are Login Check balance Place cash deposit Withdraw cash Make third party transfer View transactions Entities public class UserBankAccount ...
I need to format a double value to three decimal places to a string with length of 9 with leading spaces and no decimal separator. My approach is this NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "a"; nfi.NumberGroupSeparator = ""; double a = 334.44554; Console.WriteLine($"{a.ToString(...
I have come across many spell number functions and have reviewed many VBA code available on the net. The core function that gets called repeatedly is the function that converts numbers from 001 to 999 as it is the core function for conversion under the English numeral system. I have seen that this core function is some...
Is there anything wrong with having a file path as an env variable and using that as-is in a require_once? <? $CONSTANTS_FILE = getenv('CONSTANTS_FILE_PATH'); require_once($CONSTANTS_FILE); echo DB_USER ?> And here is how it is set in apache: <VirtualHost *:80> #ServerName #DocumentRoot SetEnv CONSTANTS_F...
I've developed a fully working flash card app for kids. It has a UIImageView that cycles through 26 cards (abcs) via a gesture click and a music button that will play a sound for each image. Right now I have this 100% working, but the sound plays in an IF statement that has added an additional 400 lines of code. How I ...
As my answer to this question, I came up with this solution: static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count) { if (data == null || count < 0) yield break; Queue<T> queue = new Queue<T>(data.Take(count)); foreach (T item in data.Skip(count)) { queue.Enqueue(item); yield re...
I am working on a console renderer and I want a heap-allocated dynamic texture class. Since I am quite new to C++, I just want to check the memory management, if I destroy all pointers correctly etc. class Texture { private : char** pixels; // heap allocated int width, height; public : Texture(int width, int height,...
I just learned about Test Driven Development on a podcast yesterday. So I decided to try it out today by writing a roman numerals to integer converter (per their suggestion). I've never written Unit Tests before today. My process I wrote the test class with the runAll() function, then I started writing my tests one at ...
I'm creating my first real life Nodejs project. I've created some files and all work, but I'm not satisfied about what my files look likes. It's unreadeble. For example, I work of a file to manage JWT sessions and RSA keys. For this file, I need two function to load and save the RSA private key. This Node.js style guid...
I am solving the problems for Advent of Code 2016 to learn Rust programming. The prompt for the first problem can be summarized: I start at position 0,0 on a regular grid. I am given a set of directions to get to a location. I can only travel in "steps" on this grid, and I am only given directions in the form (e.g.): R...
I like to collect images for my desktop background, but the problem is sometimes the image names don't represent what the image is. I decided to write a script that reads a text file that contains the source of the images (folders stored in the Pictures directory under the Userprofile (windows)) to be renamed. The full...
I'm here looking for a review over my current code-base. Please: Ignore using namespace std; this is for educational purposes mostly so the usage of using namespace std; does not matter for this codebase as it's a project thrown together for educational purposes. Look at some parts of my code which I will point out b...
I am working on this problem: https://www.hackerrank.com/challenges/determining-dna-health/problem passing some test cases and time-out on others (no wrong answers). The code is here: import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; imp...
Just whipped up this quick curry function in Lua, as a building block for partial application and memoization. Any feedback is appreciated. It takes two arguments; n is the number of parameters in the function being curried, and func is the function to curry. Code generation is used to create the curried functions. Bec...
A thief finds much more loot than his bag can fit. We have to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag. For example has a bag which can fit at most 50 Kg of items. He has 3 items to choose from: the first item has a total value of $60 for 20 Kg, the s...
The idea is that when we want to create an object of some type, we will only use a robotcreator and enum from the interface. the goal is to decides what type of robot to use internally, based on a parameter supplied by the client at runtime. what's better enum or define? InterfaceRobot.h class InterfaceRobot { ...
I wanted a buffer like std::vector<uint8_t> which is very fast at resizing, and it does not require byte initialization (it resizes to 16K, then to 2-4 bytes, then goes back to 16K, and repeat, a lot. std::vector zeroes all the bytes every time it grows back to 16K, I thought I could avoid the zeroing-overhead with a c...
A while back I came across the issue of having a large delimited file where I wanted to simply parallelize my python code across each line of the file. However, doing so all at once either took up too much RAM, or took too long. So I made a simple Parallel Parser (ParPar) for sharding such delimited files and auto mapp...
I developed a small package to do matrix math. I just learned Go so I may have done it wrong. package matrix import "fmt" import "errors" import "math" type Matrix [][]float64 func Print(m Matrix) { fmt.Println(m) } func Zeros(rows, cols int) Matrix { m := make([][]float64, rows) for i := 0; i < rows; i...
I have started to learn Java for the past 20 days with no prior coding/comp science experience. My brother gave me an idea to make a subnet calc/ping tool to enhance my knowledge and mentored through this. Just wanted to know how can I upgrade this code and if I have used proper language idioms in this code. Any ideas ...
I want to know how to improve the design of Canvas drawing implementation. Canvas Drawing This solution is to implement a console-based canvas drawing application. Problem Statement Description You're given the task of writing a simple console version of a drawing program. At this time, the functionality of the progra...
This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue? Initially, I thought maybe the process is slower as it uses two memory containers...
I know there's a similar question to this: See here. And I have taken the points mentioned there into consideration. However, I wanted to learn Kotlin and thought of writing OOP based Chess myself. My attempt at writing a simplistic chess game (between White and Black basically, player does not have much to do). Basi...
I'm in the process of making a website for a friend of mine who wants to display both the tattoos he has made, as well as his paintings. The idea for the layout is to have a gallery for his tattoos, and another gallery for his paintings. I have so far achieved this, but the code is dry and duplicated - so I'm hoping to...
My task is to copy data from an Excel sheet into charts on PowerPoint slides. To minimize the interactions between the two, I have an Excel macro insert the data for each slide into that slide's Notes pane. Next I have a PowerPoint macro extract the data from each slide's Notes and insert it into the two charts on that...
I have written a solution for two sum problem in variation. first is simple with two loops and another one is one loop and hash map. But I wonder why the simple solution is faster than the efficent solution simple solution - func TwoSum(arr []int, s int) [][]int { var sum [][]int for i := 0; i < len(arr); i++ {...
Some years ago I made a Monty Hall simulations in Java, and now I decided to give it a go in Python, after learning (yet another) the language at university. I decided to make a generalized, object-oriented and modularized version of the game, in order to see what alterations would impact the results; and to get more c...
I've recently started building an API that allows a consumer to create and manipulate musical entities such as notes, intervals, scales and chords. The first step is to create a a foundation of base structures that are later used by the musical entities. One such structure is a Ring. A ring in modular arithmic A Ring ...
I need help to simplify this code about implicit date calculation. The context: I have sentences with implicit and explicit dates. For instance: "From the 5th to the 7th of September 2017, the 12th, 13th and 15th of June, from the 25th to the 31th December, the 1st and the 2nd of January 2019." A program (not shown h...
I come from this question. Project A very simple project with Gin framework with an endpoint to return a list of users based on their score. Structure liveops-tool -- user ---- model ------ user.go ---- service ------ userService.go ---- dao ------ directory.go (interface) ------ userDirectory.go (mock the db) ------ u...
I have a number of Excel tables that I want to populate into VBA dictionaries. Most of the code is repetitive but there are some unique things for each table that prevent me from making one general purpose routine and calling it for each table. The basic code: Public Sub MakeDictionary( _ ByVal Tbl As ListObject, ...
Here is my code for the LeetCode problem For a given binary tree, find the maximum width of the binary tree. The width of one level is defined as the length between the end-nodes even if there are None nodes in between My code (in PyCharm) passess all the given tests but does not seem to pass on the LeetCode website....
I am running through an app idea to help improve my knowledge of Javascript. The code attached performs the following: Performs a regex on the input field to check it is value 0-9 If not, it clears the field and shows a warning (Although this only seems to work on FF) If it passes, updates the styles of the preview bo...
I am learning to use the new API version of Paypal, and I have some doubts. Note: I've tried this on https://www.sandbox.paypal.com and it works, I have not done the tests on Live. onApprove: I need to send additional personalized data to Paypal, and once the user makes the payment, I return to a URL on my server, ...
This problem is from Automate The Boring Stuff using Python - Chapter 7. Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string....
Is there anything missing or any pitfall when using BigInt? // Assuming n is an integer and is 0 or greater function factorial(n) { var i, result = BigInt(1); for (i = BigInt(2); i <= n; i++) { result *= i; } return result; } console.log(factorial(69)); console.log(factorial(200)); console.lo...
In the existing system, we need to rebuild the user's authorization. The database includes Roles and Rights Roles were previously used but will be skipped in the new version All authorization will be based on Rights control I have prepared an attribute that performs such a task Controller: [HasRights(Rights.AddPayer, R...
I am trying to expose a simple struct via FFI. Is this the best way to do it? I am not 100% sure about the get_text function. This is taking the string out of the struct and cloning it before returning a pointer to it. I suspect this is going to leak. Whats the best idiomatic way around this? Do I need to provide a fre...
I've written a small script that automates the tasks I previously did manually for deploying onto our kubernetes clusters and I am quite happy with the results I have, but I do think that what my approach was (building a command and executing it at the end) could probably be improved. Especially the fn_magic part is so...