I like the use of Intersect to handle single cell ranges.

You should avoid using Cells as variable name because it could easily be confused with the built in Cells collection.  By contrast Range As Range could be used because there is no default Range value.  Personally, I use Source and Target to name my ranges.  rSource and **rTarget would generally be considered better names but I think that the context in which they are used is descriptive enough.

The use of an Error Handler here is just fluff.  All it does is just throw the same error that would be thrown without it.  You should use Error Handlers to clean up the objects and reset the "Application State" when something goes wrong.

I don't see any issues with any "Edge Cases".  Raising the Error, however, does severely limit the possible "Use Cases".  The way it is written you can not test a series of ranges for constant values because it will throw an error.  IMO, it would be more useful to have the function escape the error and return Nothing.  In this way, you can create a customized Error Handler at the point of use.  For example: If not GetConstants(rngA) is Nothing Then ... If not GetConstants(rngB) is Nothing ....


PHP performance considerations of passing variable into a function

Having (1)

public function execute(array $fooArray)
{
    foreach ($fooArray as $foo) {
        echo $foo . ":" . $this->checkBar($foo, $this->getBar()) . " ";
    }
}

public function checkBar($foo, array $fooCheck)
{
    return in_array($foo, $fooCheck);
}

is the exact same thing (performance wise) as (2)

public function execute(array $fooArray)
{
    foreach ($fooArray as $foo) {
        echo $foo . ":" . $this->checkBar($foo) . " ";
    }
}

public function checkBar($foo)
{
    return in_array($foo, $this->getBar());
}

In example (1), if you needed checkBar() to handle several different array inputs, then you would be able to differentiate them in execute(). Whereas example (2) would be better if you knew you would only be checking against a single array.

It's easier to expand code that's written like example (1).


Java Pong Game Collision between bat and ball

In the original Pong® brand video game, there were two bats which were confined to move vertically.  A collision would be detected if ball circuit was triggered at the same time as one of the bat circuits, and if the ball was not already moving in the proper direction for that bat.  The ball's vertical speed would be set to an odd number in the range -15 to +15 based upon the number of scan lines of bat that were displayed before the collision was detected (basically the difference between the ball's Y position and the bat's position).  What exact bounce behavior are you looking for in your game?


Reload pickled objects into dict - assigned to variable name from file name

Here's a couple pieces of style advice, sourced from Python's style guide (PEP0008).

Keyword arguments shouldn't have space on either side of the equals sign:

def get_saved(directory='audio/', extension='en'):

Good that you're including a docstring, but one line docstrings should be on one line.

"""Get list of files, add them to a queue and return the queue."""

Also there may be a reason, but why not use the os module's os.path.join function instead of concatenation when making paths? It checks the OS you're on to ensure it's using the right syntax. It's generally a safer way than concatenation.

return glob.glob(os.path.join(directory, '*.' + extension))


Some observations:

I don't really understand the majority of names. What does f7 mean? What does the rwh in rwh_primes mean? Why is the lisp variable called lisp? What is the difference between count and counter? Having good names is a huge part of good coding practice.
Your rwh_primes computes a list of primes, which is good, but you then ignore list of primes when you test for primality in the is_prime method (which, since it goes up to \$N\$ instead of \$\sqrt{N}\$, is particularly slow and probably the cause of most of your troubles). Instead of running is_prime, why not simply check whether number in primes (note that for this, you probably want to make primes a set rather than a list).
I'm not sure why you do len(sorted(str(x))) instead of just len(str(x)); sorting a list doesn't change its length.
You don't need to keep track of which numbers are circular primes, just how many there are. You could replace lisp with a simple count.
Why do you deal with the length 2 case differently than the case where the length is greater than 2? I understand why you might want to deal with the length 1 case separately, but your code that works for your larger cases should also work for the length 2 case.
Your method for getting a cyclic shift of the number is interesting (doubling the string then taking a substring), but python makes it really easy to just do int(num[i:] + num[:i]), which does most of the work of your while loop in one line. You can now also reduce your two indices y and z to a single index i.
Instead of checking whether you've appended all cyclic shifts during each repetition of your while loop, why not just finish your while loop and then loop through the cyclic shifts (i.e. move the if statement outside the while loop). You do this again in your inner loop (for a in working).
It looks like f7 uniqifies a list. While I don't think you actually need to do any uniqifying here, even if you do want the list of all circular primes (because you add them in increasing order), a much easier way to do this in python is simply list(set(x)); this is fast enough for most purposes.


Transforming the case of text using Excel VBA

First, I'd get rid of the modify button. You can use option button Click events to handle the change.  Something like this:

Private Sub opbLower_Click()
    ActiveCell = LCase(ActiveCell)
End Sub

Private Sub opbProper_Click()
    ActiveCell = Application.Proper(ActiveCell)
End Sub

Private Sub opbUpper_Click()
    ActiveCell = UCase(ActiveCell)
End Sub

To answer your question, you could also use the click events to return a format type for your btnmodify_click method to handle by creating a non local variable above all the code like this:

Dim format As String

Private Sub opbLower_Click()
    format = "lcase"
End Sub

Private Sub opbProper_Click()
    format = "ucase"
End Sub

Private Sub opbUpper_Click()
    format = "pcase"
End Sub

Then apply the condition in the btnmodify_click method based on the value of format.  The first example is better though, it involves less work.


Should I create two seperate Services and then combine them or have one large?

Overview of your service looks like this. I've put T-SQL commands that execute in each methods comment.

interface ICampaignService
{
    //INSERT = INSERT INTO CAMPAIGN....
    void InsertX( ... );

    //UPDATE = UPDATE CAMPAIGN....
    void UpdateX( ... );

    //DELETE = DELETE FROM CAMPAIGN
    void DeleteX( ... );

    //ALL = SELECT * FROM CAMPAIGN
    IList<Campaign> AllCampaigns();

    //FIND = SELECT * FROM CAMPAIGN WHERE ...
    //FILTER
    //GET
    Campaign FindX( ... );
    Campaign GetCampaignByID(object id);

    //SAVE = COMMIT TRANSACTION;
    void Save();
}

And you yourself say:

  I have two separate tables, Campaign and CampaignDetails. They relate via CampaignID.

The problem is your service is not just a thin layer over Entity Framework it still is a thin layer over SQL. In fact even your action names mirror database commands.

The service interface must be a must be the interface to your business logic layer.
And repositories be your gateway to the data access layer.

Let's look at the Create(Campaign campaign) action for a second:

Create(Campaign campaign)
{
// BOILER PLATE IGNORED
    _campaignService.InsertCampaign(campaign);
    var campaignDetails = new CampaignDetails()
    {
        CampaignId = campaign.CampaignId
    };

    _campaignService.InsertCampaignDetails(campaignDetails);
    _campaignService.Save();
// BOILER PLATE IGNORED
}

When your user pressed the submit button one time, did he intend 4 different things?

Create(Campaign campaign)
{
// BOILER PLATE IGNORED
    _campaignService.CreateCampaign(campaign);
// BOILER PLATE IGNORED
}

It is clear that this more closely captures user's intent.

void CreateCampaign(Campaign campaign)
{
    _campaignRepository.InsertCampaign(campaign);
    var campaignDetails = new CampaignDetails()
    {
        CampaignId = campaign.CampaignId
    };

    _campaignRepository.InsertCampaignDetails(campaignDetails);
    _campaignRepository.Save();
}

As you do the above transformation -in other words above refactoring- for each action there will be unused methods on the service interface. Remove them and your service interface will be cleaner.

  I want a service that can handle both at the same time, as they're closely related and when one gets updated- so will the other.

This means that Campaign and CampaignDetails form an aggregate. And Campaign is the aggregate root. (I'm just giving you the standard terminology, so you can more easily look up the situation on the Internet.)

In situation where you have closely related [entities] and [such that] when one gets updated- so will the other, or in database-speak a master table and one ore more detail tables, you service should not contain direct references to the detail entities, or in other words you service should only deal with the aggregate root, in this particular case Campaign. It only makes sense that ICampaignService only deals with Campaigns directly.

I had asked for the UpdateCampaignDetails example usage so that I can give a more concrete example of this but we will have to make do with the made up example below:

Suppose we are talking about sales campaigns here and one thing that is stored in CampaignDetails is a discount rate for the Campaign. After the above refactoring to your service and controller instead of UpdateCampaignDetails your service will have methods like below:

void ChangeDiscountRate(Campaign campaign, decimal newDiscountRate)

or

void ChangeDiscountRate(Guid CampaignId, decimal newDiscountRate)

whose implementation would be something like:

var campaignDetailsToUpdate = _campaignDetailsRepository.GetById(CampaignId);
campaignDetailsToUpdate.DiscountRate = newDiscountRate;
_campaignDetailsRepository.Update(campaignDetailsToUpdate);
_campaignDetailsRepository.Save();

You need not stop there. Ideally after a next round of refactorings (Including defining One-to-One and one-to-many relations where necessary) your service methods will read like below:

var campaignToUpdate = _campaignRepository.GetById(CampaignId);
campaignToUpdate.ChangeDiscountRate(newDiscountRate);
_campaignRepository.Update(campaignToUpdate );

or more generally:

var aggregateRoot = repository.GetById(id);
aggregateRoot.ModifyThisEntityAndItsDetails(...);
repository.Update(aggregateRoot);

The other thing to do would be separate the methods that update campaigns (hint those methods that return void, who are also the methods that are called from [HttpPost] controller methods from search methods (hint they are the method that return SomeCollection and take Expression<Func<Campaign, bool>> expression as parameters) that are called from elsewhere.


Just some hints to improve your C++ code if not the algorithm logic:

Use const references for passing big objects like vectors to functions. For example, replace vector<string> leds by const vector<string>& leds in any_duplicates. Otherwise, it will perform a full copy of the vector and its elements. Here, const reference is right since the vector is not modified.
You could add std::ios_base::sync_with_stdio(false); at the beginning of your code. Default thing for streams is to call C functions from cstdio. Putting that line allow streams not to use those functions and then to be faster.
For readability, you could replace (*it).stuff by it->stuff everywhere.
vector::size() returns a size_t and that's what you use in your loops. No need to cast the result to an int.
I may be wrong, but I don't see any functions from cstdlib used here. You could get rid of that header.

You could also probably improve readability and performance by using features from C++11 (usable with the option -std=c++0x with gcc). I don't know if your contest allows it or not.


Function to get daily metrics by fetching a record or evaluating a formula

Help you to figure out how to optimize this function is not easy from outside.

Optimization is hard staff and start by collecting numbers.

If you think your function is slow, you should first measure the amount of time that your function run, the size of data that processes, the memory involved and the CPU cycles used.

You could do this with a profiler included in all the modern browsers.

With this numbers you could understand if your function is really bad as you think it is or maybe not.

You said that it is slow, but how about the staff that have to do. In a part you speak about arrays of arrays.

Now if the function is just handling too much its helpful as told us we have to change our approach as the way we though to do is not fit the reality. So no need on wasting time to optimize a function rather find a way to reduce the problem in a manner that is faster to compute.

If the function is very bad, instead, according with our measurements, than it's time to profile inside and start to look where we consume all that time.

Keep the worst part and try to understand what is the problem and fix this. An then move on to the next less worse.

UPDATE

As was clarified later, the recursion is connected with complex formulas and not with stored values.

A part that is still not clear to me:

const resultMetric = state.metrics[metric_id]
...
const records = getMetricRecords(metric_id, state)

In getMetricRecords() you just look for resultMetric again. As it is an access by key is not an big issue, but for sake of code clarity, if it is the same thing you could consider to move the code of getMetricRecords(). It is not so big staff.

const records = resultMetric.records.map(id => state.records[id])

the following part could even be simplified:

let metricRecord
if (records.length > 0) {
  for (var i=0; i<records.length; i++) {
    if (moment(records[i].date).isSame(date, 'day')) {
      metricRecord = records[i]
      break
    }
  }
}
if (metricRecord) {
  result = metricRecord
}

Avoiding to check the length of the records as the for loop already do, and remove the variable metricRecord:

for (var i=0; i<records.length; i++) {
    if (moment(records[i].date).isSame(date, 'day')) {
      result = records[i]
      break
    }
}

Of course I don't think this will solve your performance issue, sorry. :(
I just like to remove not-needed code.

About records if is a huge list, and memory is not an issue, you could consider to have an object/map with date as the key so you could avoid the for loop.


Singleton with a volatile and synchronized instance

The memory model of the jvm doesn't allow double checked locking like that to work like you think it does. The jvm is allowed to assign the object before running the constructor.

In java class loading is already lazy and perfectly thread safe. So the naive

private static final ExecutorServiceSingleton instance = new ExecutorServiceSingleton();

is fine for most purposes.

If you really want the lazy ness to go further then something like:

private static class Nested{
    private static final ExecutorServiceSingleton instance = new ExecutorServiceSingleton();
}

public static ExecutorServiceSingleton getInstance() {

    return Nested.instance;
}

will do what you need.


Spurious wakeups in Java's BlockingQueue.take()

When you write, that message cannot be null, why are you asserting for it then?
That code is IMO noise. I'd rather remove it. Other than that, the comment on it is even more noisy. Your assert says exactly what your comment says. Why keep it?

Same should go for the //will block if empty. It's noise, as it adds no value to the understanding of the code. It's clear that BlockingQueue.take() will block when there's no messages, why would there be a need to write a comment on that?

Currently you catch inside your while loop. this means your execution continues, even when InterruptedException or MessageConfigurationException is thrown. You should keep that, given the case it is desired behavior. You have to decide on a case to case basis. We miss the context to decide on that, that's why its your job, isn't it ;)

If you want to stop execution when you caught an exception, just call that public method you mentioned. It's not like calls from other public members are forbidden ;)

Oh and a minor nitpick, the name for your BlockingQueue could be better, I'd probably go for messages.


You don't need both version of the copy constructor.

    LockedValue(const LockedValue& _other) :
        m_Value(_other.load())
    {}

    LockedValue(LockedValue& _other) :
        LockedValue(static_cast<const LockedValue&>(_other))
    {}

If this is a mutating copy constructor. Then just have the second one. Otherwise have the first one. Since the mutating one simple calls the const version I see no reason for the second one as a non const object will still bind to the const version.

Move operations are usually noexcept. I suppose your are potentially throwing. I would need to look up all the funtions called. You should check and if your move operations are non throwing then you need to make an appropriate comment.

    LockedValue(LockedValue&& _other) :
        m_Value(_other._takeValue())
    {}

A standard move is simply a swap. I suppose you would need a safe swap. Which would be doubly hard as you run into race conditions. But there is always std::lock to help you with that (But its an extra step).

    LockedValue& operator =(LockedValue&& _other)
    {
        if (this != &_other)
            store(_other._takeValue());
        return *this;
    }

Thay's nice. I think I learned a new thing for the day.

    template <class T_, typename = std::enable_if_t<std::is_convertible_v<T_, T>>>
    LockedValue& operator =(T_&& _value)
    {
        store(std::forward<T_>(_value));
        return *this;
    }

And a correct usage of the mutable keyword.

    mutable std::mutex m_Mutex;


Best way to relate methods with properties

I've done this several times with a typeof operator in the attribute. That's how MS does their Editor attribute. The only disadvantage is that you can't pass constructor attributes that way. In other words you have an attribute on your property like this:

[Widget(typeof(TextBoxWidget))]

If you need parameters, you could still do it with inheritors of Widget. Suppose you need a Min/Max/Inc on your numeric widget:

[NumericWidget(-42, 42, 1)]

The methods to get the attributes allow you to look for inheritors of an attribute type.

Without this parameterized attribute approach, I definitely prefer your second option. And I would put GetWidgets into its own IHasWidgets interface. That way you can fall back to some default all-text-box implementation when that interface is missing.

Another good option is to put this information into the property registration. Are you familiar with the DependencyProperty mechanism in WPF? The CSLA framework (among others) support a property registration mechanism that is a good match for what you're doing here.


My 2 cents:

I believe createDynArray should return something.
The returned value of createDynArray might have a special value of NULL in case that one of the mallocs calls failed (this scenario should be covered by the code).
In the implementation of extend - consider using realloc instead of malloc and manual copy. If you insist on malloc perhaps using memcpy might be more elegant than a manual copy.
I'd move magic numbers to #defines: Initial Capacity (hard-coded to 10) and Growth Factor (2). Alternatively, they could be parameters to the createDynArray function
How would you free this struct? Perhaps you should add a "destructor" to be called before calling free with the struct pointer as a parameter.
In terms of functionality, other than printing this "array", how would the consuming programmer could get (or set) a specific item in this "array"?


Never assume that you're only going to have one product. That will end up being a limiting factor of your design and can cause you a lot of pain later down the line and rules out any kind of code re-usability. Make your products table generic enough to handle any kind of product. Create color/size attribute tables that you can tie to the product if you need to.
What about handling the case where people want to order as a guest or will you rule that out entirely?
How will you handle returned items/payment credits, cancelled orders, or an order where the credit card is declined? Are you going to keep history for those?
You will probably need more than 1 line for address. Are you going to handle international orders? If so you'll need to allow for non-numerical zip codes and ones that don't tie to a state.
If you tie shopping carts to cookies then you can reload someone's shopping cart when they come back based on their cookie's ID.
If you're going to keep credit card numbers in the database then you need to be PCI Compliant (https://www.pcisecuritystandards.org/).


Using await to break long-running processes

Room to improve.
There is an overhead associated with interrupting the execution flow with await though it is relatively minor.
As represented in the question there is a little room for improvement.
Problems with your implementation.
Heaping closure
The way you have implemented it can be improved
await new Promise(resolve => setTimeout(resolve, 0));

You create a new function each iteration. This means there is also a new closure created for each iteration that takes heap space, an unneeded overhead, which can be avoided by pre-defining the function (see suggested improvements below).
No zero timeout
V8 (and other browsers) throttle the timeout, it is never 0ms. What it is for V8 on the version of node you are using I don't know as the throttling value has gone through changes, and may well do again.
So if you iterate 100 times and the timeout minimum is 1ms the timeout will add 100ms to the total time to complete the iteration.
The ratio of the iteration time to the timeout time needs to be controlled. If the function takes 1ms and the timeout adds 1ms you double the time to do the function. If however the function takes 100ms to do a single iteration then the timeout adds only 1% to the time to complete.
As you suggest doing the await every so many iterations will improve the ratio. But without knowing the time per iteration you can not be sure of a reasonable count.
A suggested improvement.
The await can be improved using a object to handle the promises based on time rather than iteration count.
Inside the loop you use await as follows
await idler.idle();

Which returns a promise or not depending on the idler settings. If the time since last idle context is greater than idler.interval a promise is returned and execution context is set to idle (allowing events). If the time is less than idler.interval then undefined is returned and execution continues without interrupt.
The following is a general purpose interrupt to allow for pending events to be processed. Ill call it idler for want of a better name.
// idler.interval is min time between idle execution context in ms
// idler.start() sets the timer to now (not really needed for small values
// of idler.interval. Should not be called inside a process
// idler.idle()  Request idle promise. Returns promise if time since last idle
// is greater than idler.interval. Else returns undefined.
export const idler = (() => {
    var lastIdle = 0;
    var interval = 3;  // ms
    function timeout(ready) { setTimeout(ready, 0) }
    return {
        idle() {
            var now = performance.now();
            if (now - lastIdle > interval) {
                lastIdle = now;
                return new Promise(timeout);
            }
        },
        start() { lastIdle = performance.now() },
        set interval(val) { interval = val >= 1 ? val : 1 },
        get interval() { return interval },
    };
})();

The interface provides a way to control how often (time) to idle the execution context to allow for pending events to execute. The idle time can not be directly controlled (you can create 0 latency timeout using the message event but this has some problems)
Using the above is simple and can work over concurrent iterators. See example code below on how it can be used.
This is only a suggestion as your specific circumstance are unknown to me.
Testing concurrency
The following example uses a controllable load workLoad(time) that blocks execution context for a fixed time.
It runs several concurrent iterators that call workLoad a fixed number of times. The iterators run concurrently (time share) and illustrate how idler can manage execution context switching giving you some stats regarding the overhead.
There is also a ticker that provides additional events.
The purpose is to play with the settings to match your expected environment and workloads. You can then find the optimal settings for your needs.

const iterations = 100;  // process iteration count
const load = 10;         // in ms Blocking load per iteration
const processes = 6;     // Number of iteration concurrent processes
const tickTime = 1000;   // ms between tick calls
const idlerInterval = 20;// ms Min interval between idle execution context
const ids = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/* for stats */
var tickerStart;
var totalTime = 0;
var processCount = 0;
var expectedTime = 0;
var tickCpuTime = 0;

const idler = (()=>{
    var lastIdle = 0;
    var interval = 3;  // ms
    function timeout(ready) { setTimeout(ready,0) }
    const API = {
        idle(){
            var now = performance.now();
            if(now - lastIdle > interval){
                lastIdle = now;
                return new Promise(timeout);
            }
        },
        start() { lastIdle = performance.now() },
        set interval(val) { interval = val >= 1 ? val : 1 },
        get interval() { return interval },
    }
    return API;
})();

// The work function
async function longFunction(cycles = 100, load = 10, id){
    processCount += 1;
    expectedTime += cycles * load;
    const now = performance.now();
    while(cycles--){
        workLoad(load);
        await idler.idle();
    }
    const time = performance.now() - now;
    processCount -= 1;
    results(time, id);
}

function ticker(){
   const now = performance.now();
   if(processCount > 0){
       log("Tick " + (performance.now()-tickStart).toFixed(0) + " ms ");
       setTimeout(ticker, tickTime)
   }
   tickCpuTime += performance.now() - now;
}

log(`Starting ${processes} iterators with ${iterations*load}ms workload each.`);
idler.interval = idlerInterval;
log(`Idler interval ${idlerInterval}ms.`);
idler.start();
var tickStart = performance.now();
for(let i = 0; i < processes; i++){
    longFunction(iterations, load, ids[i]);
}
ticker();

/*========================================================================
  helper functions not related to answer
  ========================================================================*/

function log(data){
   datalog.innerHTML = `<div>${data}</div>`+datalog.innerHTML;
}
function results(time,id){
    log("Id '" + id + "' took : "+(time.toFixed(3))+"ms to complete.");
    if(processCount === 0) {
        var totalTime = (performance.now() - tickStart) - tickCpuTime;
        log("===================================================");
        log("Expected time : " + (expectedTime).toFixed(0) + "ms");
        log("Actual time : " + (totalTime).toFixed(0) + "ms");
        log("Idler total overhead : " + (totalTime - expectedTime).toFixed(3) + "ms")
        const overhead = (totalTime - expectedTime)/(processes * iterations);
        log("Idler per iteration overhead : " + (overhead).toFixed(3) + "ms " + (overhead / load * 100).toFixed(2) + "% of iteration time");
        log("Ticker took : " + tickCpuTime.toFixed(3) +"ms");
        log("===================================================");
    }
}
function workLoad(time = 1){  // blocks for time in ms
    if(!isNaN(time)){
        var till = performance.now() + Number(time);
        while(performance.now() < till);
    }
}
#datalog {
   font-family : consola;
   font-size : 12px;
   color : #0F0;
}
body {
   background : black;
}

Notes:

You should cut and past into a clean environment. Running on this page adds unknown additional executing context's.

The log function is slow (uses markup insertion) and its time has been mostly ignored. The results will therefor be slightly higher than actual.


Look at JQuery Accordion

Or if you don't want to use the Accordion then here is a variant:

function imgClickHandler(divBiographyId, divTooltipId){
  var divBiographySelector = "#" + divBiographyId;
  var divTooltipSelector = "#" + divTooltipId;
  if ($(divBiographySelector).is(":visible")) {
    $(divTooltipSelector).text('Click to learn more');
  }
  else {
    $(divTooltipSelector).text('Click to hide');
  }
  $(divBiographySelector).slideToggle('slow');

  //.profileBiography - this css class you should add to lizDiv, chrisDiv, michaelDiv
  //.profileTip - this css class you should add to lizTip, chrisTip, michaelTip
  $(".profileBiography").not(divBiographySelector).hide('slow');
  $(".profileTip").not(divTooltipSelector).text('Click to learn more');
 }

$(document).ready(function() {
$('div.profile').hide(); // Hide all the profiles
var profiles = [{img: "lizIMG", biography: "lizDiv", tooltip: "lizTip"},
                {img: "chrisIMG", biography: "chrisDiv", tooltip: "chrisTip"},
                {img: "michaelIMG", biography: "michaelDiv", tooltip: "michaelTip"}];

$.each(profiles, function(){
  var biographyId = this.biography;
  var tooltipId = this.tooltip;
  $("#" + this.img).click(function(){
    imgClickHandler(biographyId, tooltipId);
  });
 });
}


Mapping one JSON message format to another in Java

It's always a bad sign if you do have different levels of presentations inside a class.

It would be much better to separate the concerns and implement based on the "single responsibility principle".

That would mean that you have the class DeliveredCommunication which holds a set of Strings/Objects for the messages. This is also known as a DTO (Data Transfer Object).

Everyone who wants to use it, can now decide how the presentation should look like.

Transforming data to a specific exchange format should be done at the level of your application where the exchange happens.

Hope it is clear enough and that it helps

P.S.: I would change DeliveredCommunicaton to Communication with a property called state which could be realized with an enum of which one value would be 'delivered'.


Implementation of Trie data structure accommodating varying number of children

Your code does several things more complex than required. In no particular order:

What purpose does Trie_node_base serve? You don’t need a base class here since you only inherit from it once.
Worse, your base class doesn’t have a virtual destructor.
To create an array of size n, you use a loop and push_back. Much easier would be to use the proper initialiser:

Trie_node_base(int n) :
    num_of_child(n) ,
    child(n)
    { }

In fact, you generally fail to use initialisers, and instead re-assign values inside the constructor.
Consider proper naming. In the above code snippet, it should really be number_of_children and children (plural!).
The num_of_child member is redundant – the same information is stored in the vector.
The tree node root doesn’t need to, and shouldn’t be, a pointer.
In general, your use of pointers and manual memory management makes the code vastly more complex and brittle (and requires the existence of the destroy method). If you need to use pointers, use smart pointers (std::unique_ptr in this case).
Better yet, omit pointers entirely. They are utterly unnecessary here. Unfortunately though, you cannot use std::vector with an incomplete class (the standard screwed up here). But you can (and should!) use boost::container::vector. Thus your tree node implementation becomes:

struct Trie_node
{
    boost::container::vector<Trie_node> children;
    bool is_word;

    Trie_node(int n)
        : children(n)
        , is_word(false)
    { }
};

… There’s more but these are the essential points that will help reduce code complexity.


Solving an unwieldy inheritance framework function

Take a look at the specification pattern (pdf).

In particular, Microsoft has already implemented this kind of framework as part of one of their (old) application blocks. You can look there for many related ideas.


You have the right instinct / deduction that this takes longer than it needs to. This is because each check for duplicates does a 'full scan' over your data. To improve this, you need a way to store / sort your data so that you can quickly ask: "Does this entry already exist?"

Enter the HashSet. A hash set is a data structure that allows for very fast lookups. It does this by mapping entries to an integer (the hash) and then using that to quickly get the right index in an array.

Using a hash set, your program will perform better and have fewer lines of code. The following example code uses the Set.add function that returns true on success (element was added) and false on failure (element was not added, because it already exists).

int n = scanner.nextInt();
Set<String> names = new HashSet<>(n); // expected capacity
while ( n-- > 0 ) {
  String name = scanner.next();
  if ( !names.add(name) ) { // returns false if already present
    // very short but a bit opaque:
    for ( int suffix = 0; !names.add(name + suffix); suffix++ );

    // alternatively, written out:
    for ( int suffix = 0; ; suffix++ ) {
      if ( names.add(name + suffix) ) {
        break;
      }
    }
  }
}

  for ( int suffix = 0; !names.add(name + suffix); suffix++ ); still scans from 0 every time till an unclaimed name is found... Is there perhaps a quicker way?

Indeed, there is—good catch! We can speed up the duplicate counting by using a Map instead, mapping a name to the number of times we've found it. (This is essentially a multi-set, but our standard libaries don't carry such a data structure, so we 'fake' it.)

Our printing code will look quite different, though:

int n = scanner.nextInt();
Map<String, Integer> names = new HashMap<>(n); // expected capacity
while ( n-- > 0 ) {
  String name = scanner.next();
  int count = names.getOrDefault(name, 0);
  names.put(name, count + 1);
  // alternatively:
  // names.merge(name, 1, Integer::sum);
}

// print results
for ( Map.Entry<String, Integer> entry : names.entrySet() ) {
  String name = entry.getKey();
  int count = entry.getValue();
  System.out.println(name); // plain name
  for ( int i = 0; i < count - 1; i++ ) {
    System.out.println(name + i); // number from 0
  }
}

If you're wondering about the performance of HashMap : it is the same as HashSet. In fact, HashSet uses a HashMap under the hood.


Higher Order Functions in VBA, the dirty way

Things I like

This idea.
You've explicitly declared ByVal and ByRef.
All methods are short, clear, and concise.

Things to watch out for

All of these functions take variants in as parameters, by necessity. Client code runs the risk of passing in a sequence that isn't enumerable. These really need a comment and maybe a VB_Description attribute describing what kind of arguments the functions expect.
You also may want to consider handling runtime error 438 "Object doesn't support Method" for the functions that use For Each loops. There's not much you can do other than return a more meaningful error message though.
If you change the loop in Map to a For Each and manually increment i, all of the functions will be compatible with collections as well as arrays.

Nitpicks

Underscores have a special meaning. They indicate event procedures. So I would change initial_value to initialValue.
While I quickly understood that el stood for element, there's no reason not to just spell it out.


Well, you have your code in a function, but it is still top down. It makes it harder to read, and much harder to improve.

If you instead break the code down into separate functions you'll have an easier time improving code. You'll also not repeat your self.

Make use of annotations!

def assign_chores(chore: list, prev_assignment: dict or None, persons: dict):
    ...

that way you don't have to litter your variable names with clues to what types they might be.

I think your trying to create a deep copy and not a shallow copy:

chore_list_copy = chore_list

to make a deep copy;

chore_list_copy = chore_list[:]

that way you'll actually get a copy.

for name in people_data.keys():

is the same as

for name in people_data:

Instead of working with the objects in people_data i suggest you work with data structures. It becomes easier to manipulate that way.

The data you care about can be represented with:

chores_dist = [[] for _ in range(len(persons))]

and if previous is summited:

prev_chores = [person["chores"] for person in prev_assigment.values()]

Work with data structures instead.

Protect your code by:

def main():
    ...

if __name__ == '__main__':
    main()

that way your code don't get executed if you import your code into another file.

Instead of choosing a random chore, you could just shuffle them all beforehand, that way the randomness task is done.

chores = chores[:]
shuffle(chores)

Another way to call your function then to send in a None

def assign_chores(chore_list, prev_assignment_data, people_data):
    ...

prev_assignment_data = None
    assigned_chores = assign_chores(chore_list, prev_assignment_data,
                                    people_data)

is to define it in your function

def assign_chore(chores: list, persons: dict, prev_assignment: dict=None):
    ...

now you can call it like

people_data = assign_chore(chores, people_data)
people_data = assign_chore(chores, people_data, some_previous_data)

When I broke down your code I did it like this:

from random import shuffle

def assign(chores: list, persons: dict):
    for key, person in enumerate(persons):
        persons[person]["chores"] = chores[key]
    return persons

def get_shuffled_chores(chores: list, persons: dict):
    chores = chores[:]
    shuffle(chores)
    chores_dist = [[] for _ in range(len(persons))]
    for key, i in enumerate(range(len(chores))):
        chores_dist[key % len(persons)] += [chores.pop()]
    return chores_dist

def assign_without_regard(chores: list, persons: dict):
    return assign(get_shuffled_chores(chores, persons), persons)

def is_repetitive(news: list, olds: list):
    for new, old in zip(news, olds):
        if any(chore in old for chore in new):
            return False
    return True

def assign_with_regard(chores: list, prev_assigment: dict, persons: dict):
    prev_chores = [person["chores"] for person in prev_assigment.values()]
    new_chores = get_shuffled_chores(chores, persons)
    return assign(new_chores, persons) \
        if not is_repetitive(new_chores, prev_chores) \
        else assign_chore(chores, prev_assigment, persons)

def assign_chore(chores: list, persons: dict, prev_assignment: dict=None):
    if prev_assignment is None:
        return assign_without_regard(chores, persons)
    return assign_with_regard(chores, prev_assignment, persons)

def main():
    chores = ["hoovering", "dusting", "wash dishes", "tidy garden",
              "clean windows", "empty dishwasher", "dust", "cook"]

    people_data = {"David": {"email": "example@gmail.com",
                             "chores": []},
                   "Mark": {"email": "example@gmail.com",
                            "chores": []},
                   "Anaya": {"email": "example@gmail.com",
                             "chores": []},
                   "Cooper": {"email": "example@gmail.com",
                              "chores": []}
                   }

    people_data = assign_chore(chores, people_data)
    print(people_data)
    print(assign_chore(chores, people_data, people_data))

if __name__ == '__main__':
    main()


Nice little system, I understand though why you think this code could be better.

I think there are a few things which would make a difference. The first is a try-finally block, and the second is a simpler loop

First, the try-finally:

    InputStream stream = assets.open(path);
    try {
    //3. Get BufferedReader object
        BufferedReader buf = new BufferedReader(new InputStreamReader(stream));
        .... do things with the buffer.
    } finally {
        stream.close();
    }

This is a bit of a pre-Java7 cheat I use. It is safe to close the inner stream, and let the outer Readers (BufferedReader,InputStreamReader) not be explicitly closed. In Java7 I would put them all in a try-with-resources, but, Android, alas!.

With the above code you don't need to worry about closing the stream at all inside the try block.

OK, so now the try-block is simple, I would put two conditions (the readLine first!) in to the read-loop:

String line = null;
int currLine = 0;

//4. Loop through using the new InputStreamReader until a match is found
while ((line = buf.readLine()) != null && currLine < lineToFetch) {
    currLine++;
}

// OK, at this point, line is either null,
// or the actual line to fetch.... Whatever it is, return it,
return line;

Putting it all together, I would have something like:

private String getRandomQuote(int lineToFetch)
        throws IOException {
    //1. get path
    AssetManager assets = getApplicationAssets();
    String path = null;
    path = getAssetPath(assets);

    //2. open assets
    InputStream stream = assets.open(path);
    try {
        //3. Get BufferedReader object
        BufferedReader buf = new BufferedReader(new InputStreamReader(stream));
        String line = null;
        int currLine = 0;

        //4. Loop through using the new InputStreamReader until a match is found
        while ((line = buf.readLine()) != null && currLine < lineToFetch) {
            currLine++;
        }

        // OK, at this point, line is either null,
        // or the actual line to fetch.... Whatever it is, return it,
        return line;

    } finally {
        stream.close();
    }
}


You are using textual strings to represent numbers. This is not ideal for the processor. It is better to store the numbers as arrays of 32 or 64-bit unsigned integers, depending on the type of CPU. The only issue of course is that you might have to convert from and to the textual representation for your input and output, but if you have to perform many operations on your numbers, this is a small cost to pay.

There are existing libraries that can handle very large numbers (usually called "bignums"). One of them is the GNU Multiple Precision Arithmetic library. You can use that one if you want, or look at its source code to see how they handle large numbers.


A little refactor solution can be

function nestedObjectToArray(obj) {
    if (typeof(obj) !== "object"){
        return [obj];
    }
    var result = [];
    if (obj.constructor === Array){
        obj.map(function(item) {
            result = result.concat(nestedObjectToArray(item));
        });
    } else {
        Object.keys(obj).map(function(key) {
            if(obj[key]) {
                var chunk = nestedObjectToArray(obj[key]);
                chunk.map(function(item) {
                    result.push(key+"-"+item);
                });
            } else {
                result.push(key);
            }
        });
    }
    return result;
}


How is my implementation of an immutable stack?

Writing an elegant immutable stack is difficult in Java, mainly due to the lack of multiple return values. But your code does look quite fine.

I am comparing your API with Scala's immutable stack. One interesting bit is that there the signature of push translates to:

public <T2 super T> ImStack<T2> push(T2 e)

which looks uncomfortable but makes a lot of sense too: Adding elements to a stack can widen the type but never narrow it down. Keeping the current type is a special case of this.

Your isEmpty method is unfortunately flawed. Assume I have created a stack of one element, like:

Object myObject = null;
ImStack<Object> stack = new ImStack<Object>(myObject, null);

Now stack.peek() is correctly null. On an empty stack, this should have created an exception, not returned a null.

One solution to solve this problem is to have isEmpty() always return false. We also create a private subclass¹ of ImStack called ImEmptyStack, where isEmpty() returns true, and peek() throws an exception. In your constructor, you create a new empty stack as tail when that argument would be null:

ImStack(T head, ImStack<? extends T> tail) {
  this.head = head;
  this.tail = tail != null ? tail : new ImEmptyStack<T>();
}

1: Actually, subclassing here leads to problems. The two classes should both be subtypes of a common interface. So basically, the Composite Pattern.

By overriding the size() in the ImEmptyStack, you can simplify that as well:

class ImStack<T> {
  public int size() {
    return 1 + tail.size();
  }
}

class ImEmptyStack<T> extends ImStack<T> {
  public int size() {
    return 0;
  }
}

Back to your isEmpty() method, code like this should never happen:

if ( head == null && tail == null)
    return true;
else return false;

because it is equivalent to return(head == null && tail == null). Every time you write code like return foo() ? true : false, you know you can simplify that.

I'd like to sketch your reverse() method in a more functional manner, using an accumulator argument:

public ... reverse() {
  return this.reverse(new ImEmptyStack<T>());
}

private ... reverse(ImStack<...> acc) {
  return tail.reverse(acc.push(head));
}

// Empty stack:

private ... reverse(... acc) {
  return acc;
}

This is as efficient as your solution, because your size call also traverses the whole stack recursively. The advantage of my solution is the simplicity. Of course, it is trivial to rewrite this to an iterative solution, because the above sketch is tail recursive:

reverse() {
  ImStack<T> accumulator = new ImEmptyStack();
  ImStack<T> current     = this;
  while(!( current instanceof ImEmptyStack<T> )) {
    accumulator = accumulator.push(current.peek());
    current     = current.pop();
  }
  return accumulator;
}

Note that .pop() can never return null in my adaption of your code (an empty stack should throw an exception).

Something minor that I noticed is your inconsistent spacing around the argument lists of your methods:

ImStack ( T head, ImStack<T> tail)  // left outer and inner space
pop()  // no space
push( T e) // left inner space

This is no problem in itself, but it would be better to settle for one style.


What if you have an order, that is

> 10lb in total weight
< $100 in subtotal
has no product with > 10lb?

Your method would not return anything in that case.

Here's my patched solution:

public function addShippingCost($subtotal) {
    $shipCost = 0;
    $weightSum = 0;
    $allItemsUnder10lb = true;

    foreach ($this->products as $product) {
        if($product->getWeight() > 10){
            $shipCost += $this::RATE_HEAVY;
            $allItemsUnder10lb = false;
        }
        $weightSum += $product->getWeight();
    }

    if ($subtotal < 100 && $weightSum < 10) {
        $shipCost = $this::RATE_FLAT;
    }

    if ($subtotal >= 100 && $allItemsUnder10lb) {
        $shipCost = $this::RATE_FREE;
    }

    return $shipCost;
}


There is a break statement at the end of the while true.
Like this, the while loop is completely pointless, you can remove it.

The output variable is never used.
Either you forgot to include the rest of the script,
or this is a pointless statement and should be removed.

The line that sets the output variable to the result of $(curl ...) is extremely long, and hard to read. It would be better to add some line breaks to reduce horizontal scrolling to read the code.
The grep-grep-head-sed chain can be shorter too with a little Awk magic.

This long condition would be simpler to write with a case:

if [ "$1" != "-l" ] && [ "$1" != "-a" ] && [ "$1" != "-h" ] && [ "$1" != "" ]; then
    output=$(curl ...)
fi

Like this:

case "$1" in
    -l|-a|-h|"") ;;
    *)
        output=$(curl ...)
        ;;
esac


Your presentation of your problem indicates that you want to emulate the permission system as used by POSIX like systems (Unix). The three sets (user, group, and world), and three permissions (read, write, execute) are from that. Your actual implementation though is very different....

What you have will work, but is wasteful of bits, and is only a partial bitwise solution.

Consider the permissions 0777 (by the way, the 0 there is supposed to indicate that the value is Octal - did you know that? - see PHP's documentation on Integers)

The 7 permission is the read permission (4), the write permission (2), and the execute permission (1). The important thing is to look at it in binary though:

read  00000100
write 00000010
exec  00000001

If we 'OR' all those permissions, we get:

rwx   00000111

Now, the way things are supposed to work, is that the right-most 3 bits represent the permissions of the world users, the next are the group users, and then the actual user:

user rwx     00000001 11000000
group rwx    00000000 00111000
world rwx    00000000 00000111

The left-most 7 bits are also used on most systems to represent other properties about the file. For example, in Linux, the details of the bits are described in the stat system function (remember, the leading 0 on the numbers means the number is in Octal...!!!):

       S_IRWXU     00700   mask for file owner permissions

       S_IRUSR     00400   owner has read permission
       S_IWUSR     00200   owner has write permission
       S_IXUSR     00100   owner has execute permission

       S_IRWXG     00070   mask for group permissions
       S_IRGRP     00040   group has read permission
       S_IWGRP     00020   group has write permission
       S_IXGRP     00010   group has execute permission

       S_IRWXO     00007   mask for permissions for others
                           (not in group)
       S_IROTH     00004   others have read permission
       S_IWOTH     00002   others have write permission
       S_IXOTH     00001   others have execute permission

The second reminder about the Octal numbers is important. Note that octal numbers go from 0 to 7. This is conveniently 3-bits in binary (and hexadecimal is conveniently 4 binary bits per hex digit).

OK, so, that's how it's normally done. Setting read-write-execute permissions for user, group, and world results in the binary:

00000001 11111111

which is 511 in decimal. Note, if I want to test whether the user has execute permission, it is a simple case of testing with:

00000000 01000000

If the permission is $perm = 0777 (octal) and the test is $userexec = 0100 (execute for user in octal), then we can do:

if (userexec & perm != 0) {
    // user has execute permission
    ....

But, what does your code do? It does:

7 * 100 + 7 * 10 + 7

which is 777 in decimal, and, unfortunately, in binary it is

00000011 00001001

Now, if I want to determine if the user has write-permissions, I have to do divisions and bit-tests to get there (which is what you do, but it's not the way it is supposed to be).

So, with all that background, what should your code look like? First, let's talk about bit shifting...

If I have the bits (in binary):

00000000 00000111

and I then shift them all 3 positions to the left, I will have:

00000000 00111000

I can left-shift bits with the left-shift operator <<. So, the first value there is 0007 (octal), and I can do:

$threebits = 0007;
$threebits = $threebits << 3;

After that shift, $threebits will have the (octal) value 0070.

Note that we need to shift permission bits 0 times for the world permissions, 3 times for group, and 6 times for user.....

$read = 4;
$write = 2;
$exec = 1;

$world = 0;
$group = 3;
$user = 6;

function check($requestedPerm, $level, $permInt){
    return ($requestedPerm << $level) & $permInt != 0;
}

Note that using the above logic we expect the $permInt to be in a different format to what you had.... so, your current code is:

$bool = check($read,$group,754);

But, that will need to change (to add the 0 to make it octal...):

$bool = check($read, $group, 0754);


Find minimal modulo-sum of pairs from two lists

Style:
This is the exact same algorithm, with the code-format, variable-names, and the use of strings cleaned up. I'm not actually sure this is the exact same function as yours, because the way you were using strings was probably wrong (because of the ' '.join(...) in the surrounding use-code).
def original_solve(N, T1, T2):
    final_list = []
    for item_1 in T1:
        temp_list = []
        already_appended = False
        for i in range(0, len(T2)):
            if (item_1 + T2[i]) % N == 0:
                T2.pop(i)
                final_list.append(0)
                already_appended = True
                break
            else:
                temp_list.append((item_1 + T2[i]) % N)
        if not already_appended:
            best_index = temp_list.index(min(temp_list))
            final_list.append(min(temp_list))
            T2.pop(best_index)

    return final_list

Benchmarking:
We should have a quick way to test out any improvements we make.
from random import randint  # insecure RNG is fine for this task.
from time import time

def make_test(N, t_len):
    return (N,
            [randint(0, N) for _ in range(t_len)],
            [randint(0, N) for _ in range(t_len)],
            None)

def time_function(f, *args):
    start = time()
    retval = f(*args)
    end = time()
    return retval, end - start

def main():
    candidates = {
        "Original": original_solve
    }
    tests = [
        (3, [1, 2, 3], [1, 2, 3], [0, 0, 0]),
        (4, [1, 2, 3], [1, 2, 3], [0, 0, 0]),
        (3, [1, 1, 3], [1, 2, 3], [0, 1, 1]),
        make_test(100, 100),
        make_test(100, 100),
        make_test(100, 100),
        make_test(10000, 10000),
        make_test(10000, 10000),
        make_test(10000, 10000),
    ]
    print('   T   ' + ''.join(f'{k:>10} (s)' for k in candidates.keys()) + '    Answer')
    for N, T1, T2, known in tests:
        results = [time_function(f, N, list(T1), list(T2))  # Copy these lists, since these algorithms modify T2.
                   for f in candidates.values()]

        assert 1 == len(set(
            tuple(answer)
            for answer in [known, *(r[0] for r in results)]
            if answer is not None
        ))
        print(f'{len(T1):^7}'
              + ''.join(f'{r[1]:>14.9f}' for r in results)
              + f'  {results[0][0][:4]}')

if __name__ == '__main__':
    main()

Improvements to the existing algorithm:
Your current code is O(n^2). I suspect we can do better than that, but first lets consider some simplifications.

Checking separately for (item_1 + T2[i]) % N == 0 and short-circuiting is unlikely to save us much time, and it clutters up the function. Let's get rid of all of that.
Finding the min of temp_list, and then searching again to get its index, is stinky. One option would be to build temp_list as a list of t2_index, computed_value tuples, but I think re-doing one of the modulo-sum computations is cheap enough to not worry about. So we can just ask for the minimum index using a key-function.

Improving the algorithm:
The modulo operator in the scoring function is what makes this problem non-trivial, but it doesn't really change the fact that numbers are easy to sort, and sorting is usually O(n log(n)). If our list (T2) were already sorted, could we do the rest of the problem in better-than O(n^2) complexity?

Sort T2, and give it a structure to keep track of what's already been used. This is bank in the bellow code. Using ints/flags to track what's already been used is (probably) better than just dropping elements from the structure, because python's list's pop-intermediate is O(n).
For each item in T1:

Calculate the ideal paring: N - item (mod N)
Use a binary search (O(log(n)) to find where that value is or should be in the bank-structure.
Search upward from there for a value that hasn't been used yet. In the worst-case this is O(n), but for randomly generated data the rate of collisions will be "low" (I haven't looked up the formula)

So yes, we can write a sub-quadratic algorithm, in fact it's O(n log(n)), which is pretty good for most purposes. Further refinement may be possibly, but I suspect there's not an algorithm better than log-linear.
Results:
from itertools import count, groupby
from random import randint  # insecure RNG is fine for this task.
from time import time

def original_solve(N, T1, T2):
    final_list = []
    for item_1 in T1:
        temp_list = []
        already_appended = False
        for i in range(0, len(T2)):
            if (item_1 + T2[i]) % N == 0:
                T2.pop(i)
                final_list.append(0)
                already_appended = True
                break
            else:
                temp_list.append((item_1 + T2[i]) % N)
        if not already_appended:
            best_index = temp_list.index(min(temp_list))
            final_list.append(min(temp_list))
            T2.pop(best_index)

    return final_list

def clean_solve(N, T1, T2):
    final_list = []
    for item_1 in T1:
        def key_function(index):
            return (item_1 + T2[index]) % N
        best_index = min(range(len(T2)), key=key_function)
        final_list.append(key_function(best_index))
        T2.pop(best_index)

    return final_list

def sub_quadratic_solve(N, T1, T2):
    # Cases of `% length` are wrapping indexes back to the start of the list.
    # Cases of `% N` are wrapping any exact N values back to 0.
    bank = tuple([t2_item, len(list(copies))]  # using list as an easily-mutable object.
            for t2_item, copies
            in groupby(sorted(t % N for t in T2)))
    length = len(bank)

    def binary_search_index(value):  # https://www.codementor.io/@info658/the-binary-search-algorithm-in-python-19jvyrt5ly
        lower_bound = 0
        upper_bound = length - 1
        while lower_bound < upper_bound:
            midpoint = (lower_bound + upper_bound) // 2
            if bank[midpoint][0] == value:
                return midpoint
            elif bank[midpoint][0] < value:
                lower_bound = midpoint + 1
            else:
                upper_bound = midpoint - 1
        return lower_bound if bank[lower_bound][0] >= value else lower_bound + 1

    def find_best(value):
        ideal_index = binary_search_index(value % N)
        useable_index = next(i % length
                             for i in count(ideal_index)
                             if bank[i % length][1])
        bank[useable_index][1] -= 1
        return bank[useable_index][0]

    return [(t1_item + find_best(N - t1_item)) % N
            for t1_item in T1]

def make_test(N, t_len):
    return (N,
            [randint(0, N) for _ in range(t_len)],
            [randint(0, N) for _ in range(t_len)],
            None)

def time_function(f, *args):
    start = time()
    retval = f(*args)
    end = time()
    return retval, end - start

def main():
    candidates = {
        "Original": original_solve,
        "Cleaned": clean_solve,
        "Sub-Quad": sub_quadratic_solve,
    }
    tests = [
        (3, [1, 2, 3], [1, 2, 3], [0, 0, 0]),
        (4, [1, 2, 3], [1, 2, 3], [0, 0, 0]),
        (3, [1, 1, 3], [1, 2, 3], [0, 1, 1]),
        make_test(100, 100),
        make_test(100, 100),
        make_test(100, 100),
        make_test(10000, 10000),
        make_test(10000, 10000),
        make_test(10000, 10000),
    ]
    print('   T   ' + ''.join(f'{k:>10} (s)' for k in candidates.keys()) + '    Answer')
    for N, T1, T2, known in tests:
        results = [time_function(f, N, list(T1), list(T2))  # Copy these lists, since these algorithms modify T2.
                   for f in candidates.values()]
        assert 1 == len(set(
            tuple(answer)
            for answer in [known, *(r[0] for r in results)]
            if answer is not None
        ))
        print(f'{len(T1):^7}'
              + ''.join(f'{r[1]:>14.9f}' for r in results)
              + f'  {results[0][0][:4]}')

if __name__ == '__main__':
    main()

Prints:
   T     Original (s)   Cleaned (s)  Sub-Quad (s)    Answer
   3      0.000027657   0.000033140   0.000041246  [0, 0, 0]
   3      0.000026226   0.000004768   0.000029802  [0, 0, 0]
   3      0.000004292   0.000024319   0.000008106  [0, 1, 1]
  100     0.000726700   0.000534534   0.000247002  [0, 2, 0, 0]
  100     0.000698566   0.000530243   0.000190973  [0, 0, 4, 0]
  100     0.000658035   0.000528812   0.000208855  [0, 5, 0, 2]
 10000    7.761836529   5.691253662   0.064605951  [0, 0, 1, 0]
 10000    7.386102200   5.667595863   0.067104578  [0, 1, 0, 2]
 10000    7.601329803   5.666092873   0.056614161  [0, 0, 0, 0]


Encapsulation is taking a beating here:

Public fieldName As String
Public fieldType As ADOX.DataTypeEnum
Public fieldProperties As String
Public fieldPropertiesValue
Public fieldIndex As Boolean
Public fieldUnique As Boolean
Public fieldKey As Boolean

You have a public constructor for assigning these fields, but the instance fields are all Public, which completely defeats the purpose of encapsulation. Fields should be Private, and ideally read-only (I'm a C# guy, not sure how/whether VB.NET implements this but in C# that would be private readonly [type] [name];).

It gets worse:

Public Shared IDOwner As classObjectField = New classObjectField("IDOwner", ADOX.DataTypeEnum.adInteger, "AutoIncrement", True, True, True, True)
Public Shared OwnerAccount As classObjectField = New classObjectField("OwnerAccount", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)
Public Shared OwnerName As classObjectField = New classObjectField("OwnerName", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True)
Public Shared OwnerMail As classObjectField = New classObjectField("OwnerMail", ADOX.DataTypeEnum.adVarWChar, fieldIndex:=True, fieldUnique:=True)

Beyond the constructor [made redundant by public fields], nothing in this class seems to justify having an instance: literally everything is Shared! These public shared object fields are statically initialized but, being fields, any calling code can swap the reference at any time, and because the fields are Shared, every single instance out there suddenly finds itself with a modified IDOwner.

Expose properties, not fields; and only expose Property Get if outside/calling code shouldn't be allowed to tamper with the encapsulated values and references.

OOP is about objects. Shared makes a member belong to a type, not an object instance: Shared is essentially the complete opposite of Object-Oriented.

Seems you mean to use the Public Shared fields as a way to return "canned" instances of this classObjectField class - that's not an awful idea, but then the constructor should be Private.

classObjectField is a bad name for a class. "class" is perfectly redundant and has nothing to do in the name of the type, and class and member names should be PascalCase, so that would be ClassObjectField, and CreateDbTable.

VB.NET isn't just Object-Oriented: it's also *strongly-typed.

Public Shared ArrayTableOwners = New Object(3) {
    IDOwner, OwnerAccount, OwnerName, OwnerMail
}

This is an array of Object references; in .NET everything is an Object - from a simple String to any class instance. Exposing Object on your public API is considered bad practice, because the caller has no idea what they're getting. This would be better (failed encapsulation aside):

Public Shared ArrayTableOwners = New classObjectField(3) {
    IDOwner, OwnerAccount, OwnerName, OwnerMail
}

Now the caller knows they're getting an array of classObjectField objects.

Public Shared Function createDBTable(Cat As ADOX.Catalog, tableName As String, objField As Object) As Boolean

I don't see a reason not to rename Cat to adoxCatalog - it's a catalog, not a cat. And objField is terribly misleading.

The signature says objField As Object, implying ONE object is expected. But then...

    For Each valueField In objField

If you expect an array, make the signature say so! This is what I meant with an object can be literally anything. And for performance reasons you should iterate arrays with a For loop, not For Each.

Actually, keep the For Each. Because you don't need an array here - you need anything that can be iterated. The .NET framework gives you the generic IEnumerable(Of T) interface for that: objField should be plural, to indicate it can "contain" many objects, and then instead of As Object it should be As IEnumerable(Of classObjectField), so that you can't give it a String and still happily compile and run the project.

The function shouldn't return a Boolean. Even your sample usage code doesn't care about the return value:

createDBTable(objCat, "OWNERLIST", ArrayTableOwners)
createDBTable(objCat, "USERLIST", ArrayTableUser)

Truth is, nobody will either, for you've already handled the exception and displayed a message box - and that's not your job!

Instead, make the function a Sub, and let exceptions bubble up the call stack, so that the calling code is responsible for handling exceptions and deciding whether they want to display a message box or log an entry to some text file or whatever. .NET works with exceptions, not return codes.

That said if I had to return a Boolean value for success, I'd default it to False and only switch it to True when I'm absolutely certain that my function did what it had to do. Here you're defaulting to True and switching it to False when an exception is thrown, which only works because you're catching all exceptions - but best practices tell us that we should only be catching the most specific exceptions we can, and let everything else bubble up - and if you did that, your function could return True when it really actually failed. confirm sounds like some flag that would be True when the user confirmed some prompt; success would be a better name for it. But that's moot anyway, as I said it's not that function's job to handle all possible exceptions and display a message box.


Monadic transformation on a list, done in three ways

I'd say that the idiomatic way to write this function in Haskell is by composing a more primitive one with a map. Indeed, given the type signature of meh, it is very tempting to "prepare" a list of all the m b actions and then combine them in order:

meh :: Monad m => [a] -> (a -> m b) -> m [b]
meh xs f = combine (f <$> xs)

Now, combine has type [m b] -> m [b]. To process that list, we can use a fold. You have used foldl in your examples but you ended up reversing the list which is a clear sign that you may have wanted a foldr instead. And we can indeed do that:

combine :: Monad m => [m b] -> m [b]
combine = foldr (\ x xs -> (:) <$> x <*> xs) (return [])

Here the functor (<$>) and applicative (<*>) combinators allow to write something that looks a bit direct style (we are basically using (:) to construct a list by giving its head and tail) but that takes care of the monadic actions.


Sorting elements according to frequency of occurence in C++

Advice 1

Do not print in the algorithms. If your friend wants to reuse your implementation on large vectors, he will be overwhelmed with the plethora of output.

Advice 2

You can simplify your sorting algorithm via an appropriate comparator:

template<class T>
void sortByFreq2(std::vector<T>& v)
{
    std::unordered_map<T, size_t> count;

    for (T i : v) {
        count[i]++;
    }

    std::sort(
        v.begin(),
        v.end(),
        [&count](T const& a, T const& b) {
        if (a == b) {
            return false;
        }
        if (count[a] > count[b]) {
            return true;
        }
        else if (count[a] < count[b]) {
            return false;
        }
        return a < b;
    });
}

Note unordered_map<T, size_t> instead of map<T, T> since you don't need to keep the keys T in order (more efficient).

Hope that helps.


Gravitational Brute Force N-body Algorithm

you did something in updateVelocityVectors that I couldn't quite figure out at first

updateVelocityVectors: function () {

    var forceVectorX = 0;
    var forceVectorY = 0;
    var forceVectorZ = 0;

    for (var i = 0, ilen = this.masses.length; i < ilen; i++) {

        for (var j = 0, jlen = this.masses.length; j < jlen; j++) {

            //We don't want to calculate self gravity!!!!!

            if (i !== j) {

                forceVectorX += (this.g * this.masses[j].m) * (this.masses[j].x - this.masses[i].x) / this.getDistance(this.masses[i], this.masses[j]);
                forceVectorY += (this.g * this.masses[j].m) * (this.masses[j].y - this.masses[i].y) / this.getDistance(this.masses[i], this.masses[j]);
                forceVectorZ += (this.g * this.masses[j].m) * (this.masses[j].z - this.masses[i].z) / this.getDistance(this.masses[i], this.masses[j]);

            }

        }

        this.masses[i].vx += forceVectorX * this.dt;
        this.masses[i].vy += forceVectorY * this.dt;
        this.masses[i].vz += forceVectorZ * this.dt;

        forceVectorX = 0;
        forceVectorY = 0;
        forceVectorZ = 0;

    }

    return this;

}

in both of the for loops you added an extra variable to hold the length of  this.masses, but never use it anywhere else in the loop. I think that you shouldn't declare the variable at all and just use this.masses.length in the declaration of both for loops like this

for (var j = 0, j < this.masses.length; j++) {

or an even better idea would be to assign the value to a variable outside of both loops so that you only call the length property of this.masses once, like this.

var massesLength = this.masses.length;
for (var i = 0; i < massesLength; i++) {
    for (var j = 0; j < massesLength; j++) {
    ...

Same thing here as well

updatePositionVectors: function () {

    for (var i = 0, len = this.masses.length; i < len; i++) {

        this.masses[i].x += this.masses[i].vx * this.dt;
        this.masses[i].y += this.masses[i].vy * this.dt;
        this.masses[i].z += this.masses[i].vz * this.dt;
    }

    return this;

},

and I would remove some of the vertical white space as well.

updatePositionVectors: function () {
    var massesLength = this.masses.length;
    for (var i = 0; i < massesLength; i++) {
        this.masses[i].x += this.masses[i].vx * this.dt;
        this.masses[i].y += this.masses[i].vy * this.dt;
        this.masses[i].z += this.masses[i].vz * this.dt;
    }
    return this;
},

@Ismael Miguel  is correct, by using the length property inside the for declaration you would access that property every loop, which would make this loop very inefficient, so create the variable outside of the for loop.


42

#define LINE_BUFFER 42

42 is not a buffer. Besides being a meaning of life, the universe, and everything, it is size. Consider renaming it to LINE_BUFFER_LENGTH.
No naked loops

Every loop represents some algorithm, and therefore deservers a name. Consider

while (fgets(line, LINE_BUFFER, file)) {
    char * mask = find_separator(line);
    *mask++ = '\0';
    convert_word_according_to_mask(line, mask);
    printf("%s\n", line);
}

Errors (like fopen returning NULL) are better handled with perror() or strerror(errno). Both functions precisely describe what went wrong.


if (course3.isFree() == true) {
    course3 = c;
    System.out.println("Course " + c + "added to period " + p +".\n");
} else {
    System.out.println("Unable to add class to a nonfree period.");
}

...

} else if (p == 8){
    if (course8.isFree() == true) {
    course8 = c;
    System.out.println("Course " + c + "added to period " + p +".\n");
} else {
    System.out.println("Unable to add class to a nonfree period.");
}

Good thing there aren't 20.. 200... 2,000... 20,000 courses!
This code needs to DRY a bit. Don't repeat yourself.™
Programming is about abstractions - this code need one here, badly: there should be a concept of a bunch of courses in your program.
Then it would be possible to only write the block once. Given courses is an array of courses Course... of course:
public void add(int period, Course course) {
|
|---if (courses[period].isFree()) {
|   |
|   |---courses[period] = course;
|   |---System.out.println("Course " + course + "added to period " + period +".\n");
|   |
|---} else {
|   |
|   |---System.out.println("Unable to add class to a nonfree period.");
|---}
|
}

Notice the position of the scope-closing braces: by lining them up with the indentation of the line that opened the scope, you make the code much easier to follow, and avoid this:

    }
    }

Also notice the names I've used. Avoid single-letter identifiers, like p and c. Code is much easier to read when it's... readable.

This is too verbose:

if (course.isFree() == true) {

Since course.isFree() obviously returns a Boolean value, the Boolean value itself can serve as the expression of the condition, which means you don't need to compare it to true:
if (course.isFree()) {


Unless you're working with an ancient version of .NET, Convert.ToString(i); is superfluous. You should be able to just do "attEdgeBox" + i;.

If you're certain that those checkboxes exist, you can do var checkBox = this.Controls.Find(checkboxName, true).FirstOrDefault() as CheckBox; and then work with checkBox instead of doing (checkboxControl[0] as CheckBox) repeatedly.

Note that CheckBox is a compound name, so checkboxName as a variable name is incorrect; it should be checkBoxName.

What type is attEdgeUpDown, and why does it return a value that isn't an int? Seems odd to me that a control that returns a value from 1 to 8 would return this in a non-numeric format.


Merging predicted values into measured values

I am assuming that the call to predict is not what is taking most of the time, so I'm not including that in my analysis.

One thing that is slowing down your code is that you are assigning vetor1 to newdata$ALTMISTA every iteration of the loop (well, every iteration that is 0). That could be pulled out of the loop since it only needs to be done once.

vetor1 <- (newdata$ALT)         # Creates a column vector from the actual heights of the data.frame
vetor1[is.na(vetor1)] <- 0      # Replaces the NA's present in the vector created above the numeric value 0
vetor2 <- c(pred)           # Creates a vector from the predicted data
for(i in 1:length(vetor1)){     # The loop is executed until all values vector1 pass the following condition
    if(vetor1[i]==0.00){      # If a value of the first vector has the value 0, ie, if it is absent
        vetor1[i]=vetor2[i]     # Then the predicted value will replace the missing value
    }
}
newdata$ALTMISTA <- vetor1  # The vector1, already possessing the actual values and the predicted values merged into the same vector goes                   on to become a new column in data.frame, this column is called a ALTMISTA
return (newdata)

Second, you replace NA with 0, and then test against 0. That means you are replacing both NA's and any 0's in the data. If you only want to replace NA's, just replace those without recoding them.

vetor1 <- (newdata$ALT)         # Creates a column vector from the actual heights of the data.frame
vetor2 <- c(pred)           # Creates a vector from the predicted data
for(i in 1:length(vetor1)){     # The loop is executed until all values vector1 pass the following condition
    if(is.na(vetor1[i])){      # If a value of the first vector is NA, ie, if it is absent
        vetor1[i]=vetor2[i]     # Then the predicted value will replace the missing value
    }
}
newdata$ALTMISTA <- vetor1  # The vector1, already possessing the actual values and the predicted values merged into the same vector goes                   on to become a new column in data.frame, this column is called a ALTMISTA
return (newdata)

Now the explicit loop can be replaced by vectorized functions, in this case ifelse

vetor1 <- (newdata$ALT)         # Creates a column vector from the actual heights of the data.frame
vetor2 <- c(pred)           # Creates a vector from the predicted data
vetor1 <- ifelse(is.na(vetor1), vetor2, vetor1) # replace elements of vetor1 that are NA with corresponding elements of vetor2
newdata$ALTMISTA <- vetor1  # The vector1, already possessing the actual values and the predicted values merged into the same vector goes                   on to become a new column in data.frame, this column is called a ALTMISTA
return (newdata)

Finally you can eliminate some single use intermediate variables. This may not appreciably speed up the function, but it does make for cleaner code.

vetor1 <- (newdata$ALT)
newdata$ALTMISTA <- ifelse(is.na(vetor1), pred, vetor1)
return (newdata)

As you did not provide example data, I was not able to benchmark these alternatives (nor, for that matter, even run them).


Is this jsperf.com test code good jsperf.com test code; is there method in my madness, or am I just mad?

Probably. This is a micro-optimization whose performance is really negligible in recent browsers. The only browsers I remember choking when it comes to strings were IE8 and older.

With that said, out of all your methods, concatenation with + is an obvious winner, all because it operates solely on strings. The other methods use an array as glue.

Test #2 is at a disadvantage as it has to wrap the strings into an array before they get concatenated by join. Test #3 is in even more disadvantage as you are creating an array twice, first on [] and second on slice.

And even with that, in terms of readability, all three look horrible in the presence of template strings which was designed to improve concatenation and interpolation in strings. It should be present on Firefox, Chrome and Edge as well as transpiler setups. Babel uses the + method when transpiling template strings, so there must be a reason for doing so.

So I have skimmed over the actual test code, and focused more on the approaches. By the way, I believe jsperf is just a front and persistent service that uses Benchmark.js under the hood. So if you're doing any actual testing, best use the library directly and locally.

var base = "so many ways to skin a cat",
  c = 0, bl, hbl,
  rand = function( s, e ) {
    return Math.floor( Math.random() * ( e - s ) ) + s;
  },
  concatenateThese = function() {
    return [].slice.call( arguments ).join( "" );
  };

A lot of vaguely named variables. What's c, bl, hbl, s, e and everything else? Tests are made to verify code. If I can't read the test, how do I know it works? How do I know what it's supposed to do?

rand appears to be a ranged random number generator. Name it as such. concatenateThese... concatenate what exactly? Sure, there's arguments, but the thing about code is that if I cannot know what the code does without having to dig up the source or pull up a debugger, then that's terrible code.

var base = "so many ways to skin a cat",

/* ton of code between */

while ( ++c < 10 ) {
    base += base;
}

Why are these two pieces of code separate? If I were reading code and the other part was 100 lines or more apart, I would wonder how base was 10 times the size. I'd have to (gasp) dig up the source... again.

By the way, another way of multiplying a string is

Array(10).join('the sentence you want multiplied');

You happen to use window. That's... bad. Nobody wants to pollute the global namespace. Suggesting you store those random strings in an array or object, not on window. While jsperf tests are isolated from each other, your prep code and tests aren't. There's a chance you might introduce something in either code that can infect the other, causing erroneous test results. Sure, you namespaced with randStr, but that doesn't guarantee that you won't mess it up in the long run. Writing tests is tedious, refactoring tests is a nightmare. Best done right always.


Small bash script to quickly edit scripts in $PATH

Use a shebang
#!/usr/bin/env bash

 I see you're already doing that.
In bash, prefer [[...]] over [...]. The double bracket conditional
command
gives you more features (including regular expression matching), and fewer
surprises (particularly about unquoted variables).
With a getopts loop, I prefer to shift at the end:
while getopts ...; do
    case $opt in
        ...
    esac
done
shift $((OPTIND - 1))

Allow the Usage function to take an error message:
Usage() {
    [[ -n $2 ]] && echo "$2" >&2
    # ... rest is the same
}

That simplifies some assertions
(( $# > 0 )) || Usage 2 "No arguments given"

Use command -v instead of which
Use an array to hold the paths. There's no other good way to hold a list of things where any of them might contain whitespace.
paths=()
for b in "$@"; do
    p=$( command -v "$b" ) && paths+=("$p")
done

You do need to command substitution (aka subshell) so you can capture the output.
The "colon" function makes me cringe.
For clarity, use if instead of long boolean chains
if (( ${#paths[@]} == 0 )); then
    echo "No valid executables found in PATH" >&2
    exit 3
fi

And prefer quoting over word splitting:
vim $flags "${paths[@]}"

Yes, the script will exit with vim's exit status. If you want to be super tidy, you could replace the script process with vim:
exec vim $flags "${paths[@]}"


Benchmarking is a tricky business. I'll focus more on the code part, you tell me if you get an improvement on the performance part too.

Containers or c-style strings?

  with containers like std::string

If you do want to work with containers, you can simplify your code a lot and avoid the use of std::string_view, which I believe triggers a good amount of conversions in your code.

For instance, your total_len function can be written as concisely as:

template<typename... String>
std::string::size_type total_len(const String&... strs) {
    return (strs.size() + ...);
}

Besides, I'm a bit skeptical about using memcpy on data() and such when you don't really need to. You won't beat std::string implementations that way, and you won't bring much flexibility either because at the end of the line, the product is still a std::string, not a newly malloced char*. But if a small error has gotten into your code, you'll be the guy who reinvented the wheel one time too many again.

Folding the right left way

Fold expressions are by the way more powerful than you seem to think. You don't have to be explicit about recursion. If you hang on to your std::strings, you can write a left folding in three lines:

template <typename... String>
void my_strcat_impl(String&&... strs) {
   (... += strs);
}
// <=> (((str1 += str2) += str...) += strN)

That means that the complete working example is rather short too:

#include <string>
using namespace std::string_literals;

template<typename... String>
std::string::size_type total_len(const String&... strs) {
    return (strs.size() + ...);
}

template <typename... String>
void my_strcat_impl(String&&... strs) {
    (... += strs);
}

template <typename... String>
std::string my_strcat(const String&... strs) {
    std::string result;
    result.reserve(total_len(strs...));
    my_strcat_impl(result, strs...);
    return result;
}

int main()  {
    auto test = my_strcat("Hello, "s,"name"s,"!\n"s);
}


Merging two files' lines of text for output

Some good things

This compiles cleanly with all my usual compiler warnings enabled - well done!

You've used stderr appropriately for the output (with the exception of the final message); that's good practice.

Don't dereference argv before you've checked its bounds

This is wrong:

    char *inName1 = argv[1], *inName2 = argv[2];

    if (argc != 3) {
        fprintf(stderr, "Usage: ./merge <file1> <file2>\n");
        return 1;
    }

We can't read from argv[1] or argv[2] until after we know that argc is big enough:

    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <file1> <file2>\n", argv[0]);
        return 1;
    }
    char *inName1 = argv[1], *inName2 = argv[2];

I've enhanced your error message to use the actual name of the program, as passed in argv[0].

Report actual error type on failure

"Can't open " at least specifies which file couldn't be opened, but we can be more specific (file not found, permission denied, ...) using the perror() function:

    FILE *const in1 = fopen(inName1, "r");
    if (!in1) {
        perror(inName1);
        return 1;
    }

I also changed this to return 1 from any error - there isn't any great benefit in distinguishing the different causes in the error code.

A slight tweak to the logic

The loops look mostly correct; there's a small duplication we can avoid here:

        while ((d = getc(in2)) != EOF)
        {
            if (d != '\n')
                putc(d, stdout);
            else
            {
                putc('\n', stdout);
                break;
            }
        }

We can bring the putc() outside the if-else like this:

        while ((d = getc(in2)) != EOF) {
            putc(d, stdout);
            if (d == '\n') {
                break;
            }
        }

A redundant test

while ((c = getc(in1)) != EOF)
{
    /* ... */
}

/* c can only be EOF here */
if (c == EOF)
{
    /* ... */
}

Consider some edge cases

You've taken good care to ensure that when one file ends, the rest of the other is output.  Have you thought about when to output a newline, if the ending file doesn't itself end with one.  It's not clear what you intend to happen in that case - comments should explain the desired output.

Alternative logic

I prefer a less deeply nested set of loops, where the first loop is the "normal" case where we're reading from both files, and we leave that loop when either file is exhausted, and finish copying from the other:

int c, d;
// Take care of output
while ((c = getc(in1)) != EOF) {
    if (c != '\n') {
        putc(c, stdout);
        continue;
    }

    while ((d = getc(in2)) != EOF) {
        putc(d, stdout);
        if (d == '\n') {
            break;
        }
    }

    if (d == EOF) {
        break;
    }
}

while ((c = getc(in1)) != EOF) {
    putc(c, stdout);
}
while ((d = getc(in2)) != EOF) {
    putc(d, stdout);
}

I've kept both c and d variables for this, although we only really need one for both files.

Error checking of output

None of the above code ever checks the return value of putc().  Filesystems do fill up, and users do disconnect streams and worse, so we really ought to ensure that the writes succeed.

Error checking of input

We currently assume that EOF returned from getc() means that we've reached the end of the file.  However, it could mean that we have an error of reading, and we should distinguish those cases using feof() or ferror().

Final message

printf("\nProcess ended successfully.\n");

This isn't part of the output (and you don't want it to be passed along in a pipeline).  Send status messages to stderr - or better still, be silent whilst successful, like the standard utilities.


Universal CSS template for global styles

I can not find unambiguous recommendations. After inspecting various sites, I have compiled the following template

The canonical example domain exists for such a purpose. Here is its style declaration:

body {
    background-color: #f0f0f2;
    margin: 0;
    padding: 0;
    font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

}
div {
    width: 600px;
    margin: 5em auto;
    padding: 50px;
    background-color: #fff;
    border-radius: 1em;
}
a:link, a:visited {
    color: #38488f;
    text-decoration: none;
}
@media (max-width: 700px) {
    body {
        background-color: #fff;
    }
    div {
        width: auto;
        margin: 0 auto;
        border-radius: 0;
        padding: 1em;
    }
}


Format string processing similar to date or printf()

Return the number of bytes written to buf
You will notice that functions like sprintf() and strftime() don't return a pointer, but rather an integer that says something about the number of bytes that (would) have been written to the output buffer. This is much more useful than just copying the pointer to buf, which doesn't give the caller any new information.
Where is the string returned by the callback function allocated?
The callback function returns a pointer to a string. But where is this allocated? Your format() function doesn't call free(), so either the string should be stored in some statically allocated array, or it is allocated on the heap. In the former case, unless you return a pointer to a string literal, your format() function can only be used from one thread at a time. If you return memory that is allocated on the heap, then you have to keep track of it so the caller can clean up all the allocated memory once format() returns.
Consider having the callback function write into buf directly
To solve the above issue, and to avoid an unncessary copy, you can pass a pointer into the buffer and the remaining size to the callback function, and have the callback function write directly to the buffer. For example:
char*
format(const char* format, char *buf, size_t len, size_t (*cb)(char c, void* ctx, char *buf, size_t len), void *ctx) {
    ...
        if (*curr == '%' && *next)
        {
            if (*next == '%') // escaped %, copy it over and skip
            {
                buf[i++] = *format++;
                continue;
            }
            i += cb(*next, ctx, buf + i, len - i - 1);
            ++format;
            continue;
        }
    ...
}

And then your callback function can look like:
size_t example_cb(char c, void *ctx, char *buf, size_t len) {
    if (c == 'f') {
        if (len > 3)
            len = 3;
        memcpy(buf, "FOO", len);
        return len;
    }

    return 0;
}

You can create a helper function to avoid repeating the above construction, and to safely write any string to the buffer:
size_t emplace_string(const char *str, char *buf, size_t max_len) {
    size_t len = strlen(str);
    if (len > max_len)
        len = max_len;
    memcpy(buf, str, len);
    return len;
}

size_t example_cb(char c, void *ctx, char *buf, size_t len) {
    switch (c) {
    case 'f':
        return emplace_string("FOO", buf, len);
    case 'B':
        return emplace_string("bar", buf, len);
    ...
    default:
        return 0;
    }
}


Faster JavaScript fuzzy string matching function?

function fuzzy_match(str,pattern){
    pattern = pattern.split("").reduce(function(a,b){ return a+".*"+b; });
    return (new RegExp(pattern)).test(str);
};

String concatenation is slow. The reason is that you need to allocate new memory anytime you concatenate two strings. A smart compiler may optimise that,  but not too much. However, what you are trying to do with that reduce already exists, and it's called join:

pattern = pattern.split("").join(".*")

The regex itself can be optimised: .* initially grabs as much as possible, then retracts only if the rest doesn't match. This takes a larger than neccessary amount of backtracking to find out. Instead, you could use a reluctant quantifier: .*?. This attempts to match as little as possible. If a match is found, it is found without backtracking. However, it still does a lot of backtracking if there is no match. We can do better: a[^b]*b (at this point, it doesn't really matter if the quantifier is greedy). A possessive quantifier (a[^b]*+b) would be even better, but javascript doesn't support these. Using a character class deprives us of a join, but see the next point.

pattern = pattern.split("").reduce(function(a,b){ return a+'[^'+b+']*'+b; });

Since you are complaining about an operation that takes about 3000 ns (as noted in the comments), it can be assumed you are doing a lot of queries. If there are very few patterns, you can cache your regexes. Underscore.js has a handy function that I'll demonstrate, but you could easily build the cache yourself.

var cache = _.memoize(function(pattern){
  return new RegExp(pattern.split("").reduce(function(a,b){
    return a+'[^'+b+']*'+b;
  })
})
function fuzzy_match(str,pattern){
  return cache(pattern).test(str)
};

If there is a lot of repetition among the tested strings, you should use these as a pattern instead, and the pattern as the tested string. This is even easier. I will also demonstrate how to scope your variables using the export pattern. Also, a bugfix must be inserted here (we can't assume all characters in the string are alphanumeric), to properly escape non-alphanumeric characters:

var fuzzy_match = (function(){
  var cache = _.memoize(function(str){
    return new RexEgp("^"+str.replace(/./g, function(x){
      return /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/.test(x) ? "\\"+x+"?" : x+"?";
    })+"$");
  })
  return function(str, pattern){
    return cache(str).test(pattern)
  })
})()

Concerning the last regex:

Given some pattern "ace", the regex you build (/a.*c.*e/) tests if the string contains the characters of the pattern in the string, in the correct order.

If you want to test if a given string "abcde" is matched some pattern: The pattern must only contain the characters of the string, in the correct order: /^a?b?c?d?e?$/. To do this, we regex-escape every regex special character (pattern source: CoolAj86), make every character optional (?), and flank the regex with string boundary anchors.


As discussed in the comments, this isn't cryptographically secure. The most obvious reason is that the optimizer may choose to do any number of things. The most likely to be concerning are a change in order of operations, or a change in join methodology. If math.RangeInt does any kind of table access (I assume this gives you a numbers table equivalent) then table access type could affect it as well.

Additionally, the bail-early for inequal length exposes information if this assumption isn't met (from comments):

  [I] wrote the code under an assumption that doesn't hold in general: that the strings being compared are hashes and thus the length is public knowledge

Ignoring comments regarding cryptographic security, I think the implementation is straightforward and makes sense. To try and address the cryptography I have a few ideas, but I am not an expert and do not endorse rolling your own security and cryptography algorithms/libraries (or using my suggestions, ever, in production).

(click here to see the image on imgur, otherwise click the image to read the original informative and entertaining comic).

Now that we have that out of the way, I think to even come close to accomplishing this, we would need to do the following:

Stop using a table valued function - we're going to need several hints to ensure that this performs consistently, which we can't add to a TVF and auditing all uses of this would be too difficult. In particular, OPTION( FORCE ORDER, RECOMPILE, MAXDOP 1, OPTIMIZE FOR @x = 0x00, @y = 0x00 ) will be necessary.
Instead of CROSS APPLY math.RangeInt, I think you'll need to join to a materialized numbers table (see below)
You're going to have to remove the length check, and pad the two values to an even 8000 (this is tedious but not hard, and I think should be doable in constant time)

I picked those hints because we want to ensure that it always joins in the order we specify, and doesn't get clever. We want to prohibit parallelism as well so it behaves consistently. Optimizing for those constant values prevents it from getting smart with parameter sniffing. We may not need to recompile; in my gut I think we want it, but I don't have a great reason for this. We may want to set a min/max grant percentage to be the same, so we get consistent behavior based on memory grant. It might also be valuable to use the USE PLAN hint, which lets you hardcode the plan to use. This might be the best way to get a consistent execution.

We're also going to have to add join and table access hints; assuming that dbo.Numbers exists with a clustered index on the first (and only) column, we might be able to do this:

FULL OUTER LOOP JOIN dbo.Numbers WITH ( INDEX(0), FORCESCAN )
  ON Numbers.Number = [@xLength].n

This should run in the same amount of time no matter the length of the string, and the query will always use the same join and table access pattern.

Overall, I think this is a lot of reasons why implementing something cryptographically secure in SQL is a bad idea; I would guess there are a lot of things I'm missing that still prevent this from being "safe".


Both ways are valid and have their own advantages. Checking upfront using an if statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.

So if you mostly have cases where 'y' is in self.axes then EAFP is better, otherwise LBYL is fine.

But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress because this except: pass is ugly:

from contextlib import suppress

with suppress(KeyError):
    ax = self.axes['y'].ax
    coord1[ax] = x0
    coord2[ax] = (y1) - height[ax]
    coord3[ax] = x0 + width[ax]
    coord4[ax] = y1