Overview:
In relation to the message queue:

Since you are doing a manual new and delete that seems a bit of a waste.
Also the only thing you are creating is a unique_ptr.
The unique_ptr is never in stored correctly typed so it never does any work.

So I would not store a pointer to a std::unique_ptr I would just store the original pointer. I like the idea of passing in and retrieving a unique_ptr to the access function.

Why are you passing a pointer to CommandMessage? It can't be null (you never check so must be valid. To make this more formal pass by reference to indicate to the user that it should be a normal object.
void setTestMessage(CommandMessage *testMsg, uint8_t someResource)
std::unique_ptr<DummyHelper> getUniquePtr(CommandMessage *testMsg)

// I would do this:

void setTestMessage(CommandMessage& testMsg, uint8_t someResource)
std::unique_ptr<DummyHelper> getUniquePtr(CommandMessage& testMsg)

Note: Putting the '*' on the right by the variable is very "C" like. C++ considers this part of the type information so it is usually on the left with the type.

Why is the input message different from the output message?
void setTestMessage(CommandMessage *testMsg, uint8_t someResource)
std::unique_ptr<DummyHelper> getUniquePtr(CommandMessage *testMsg)

So input is a uint8_t but the output is std::unique_ptr<DummyHelper>? I would expect the interface to be symmetric.
template<typename T>
void sendMessage(CommandMessage& messageStream, std::unique_ptr<T>&& msg);

template<typename T>
std::unique_ptr<T> recvMessage(CommandMessage& messageStream);

template<typename T>
std::unique_ptr<T> recvMessage(CommandMessage& messageStream)
{
   // To store pointers in an integer type you should be using `std::intptr_t`
   // This is an int type that is guaranteed large enough to store a pointer.
   // Don't make the assumption that `uint64_t` is large enough.
   // It might be but that is not guaranteed for the future.
   std::intptr_t raw_ptr = messageStream.getParameter();

   return reinterpret_cast<T*>(raw_ptr);
}

template<typename T>
void sendMessage(CommandMessage& messageStream, std::unique_ptr<T>&& msg)
{
    messageStream.setParameter(msg.release());
}


Counting the UpperCase, LowerCase, Numbers and Special Characters in a String

public static non-final variables are destroying your Zen, dude!

(No offense meant, it's a serious message in a funny wrapping meant to be easy to remember.)

Data hiding

Java is a language which provides so many big and small things which help us with encapsulation and data hiding. We want to encapsulate and hide data because that minimizes the risks of wrong coupling and bogus dependencies. There are 4 big design smells in the world, and almost all problems which software development projects face can be tracked down to these 4 design smells: Fragility, Rigidity, Immobility and Viscosity. More than 3.0 of these 4 design smells are primarily caused by coupling and dependency.

public static non-final variables are globally accessible mutable variables, or short global variables, and we don't want global variables.

Consider making your variables local.

Data modeling / reentrance

Think of the reusability of your function. Imagine, some big Internet company like Google, Amazon, Alibaba, Flipkart or whatsoever likes your password check algorithm and wants to reuse it.

static fields exist exactly once. (Strictly speaking they exist once per Class instance, and different ClassLoader could create separate independent such instances, but if you're not familiar with that see this as esoteric stuff for now.)
non-static fields exist once per object.
local variables exist once per function call.

This means that from a runtime reusability perspective, static fields are dangerous. What if two users would check their passwords at the same time? Their data would get messed up.

If you create non-static fields, each password check would need its own PassTest object.

If you have local variables, each password check automatically has its own copy of the relevant data.

So, I hope I've given you two good reasons for making your variables local.

Name: Test vs. Validator vs. Analyzer

You call your class PassTest. Actually, the word Test already is reserved with some meaning that's different from how you use the word Test.

A Test is an automated (ya James Bach beat me to it, as if I care :P) reproducible verification of a program's behavior for specified test cases. A test has a result, and that's either "PASS" or "FAIL".

If you want to tell the user whether the password is good or not, you might actually call it Validator instead, or if it's purely about giving some info about the password, Analyzer might be a good name.

So, I'd rename the class to PasswordAnalyzer.

Security: Sniffing / Spying the password

You might want to go for Console.readPassword() instead of BufferedReader(...System.in...).readLine(). The drawback is that Console.readPassword() bypasses stdin and directly reads from the terminal. The upside is that Console.readPassword() disables the terminal echo for the password characters and returns a char[] which is more secure.

Why not show the password on the screen?

Someone might look over your shoulder and see the password.

Why is char[] more secure than String?

Because after use of the char[], you can clear the char[] and fill it with zero - and you should! You cannot do that with a String, because Strings are immutable.
The time between end of password use and garbage collection might be infinitely long, and that's where someone might spy the password in memory.

Chinese Characters

You might want to know that Chinese characters like '噸' are neither uppercase nor lowercase. A proper Java program would allow Chinese to use it as well and produce meaningful results for them, too.

Closing Resources

You might want to dataIn.close() because that's good habit.
In other programs, forgetting to close() or even to flush() actually can lead to bugs which can be very tough to find.
I made it a habit to always finish what I start, which for streams and stuff means I always close what I open as soon as it's unused, even if it seems unnecessary.

The following code snippet shows how to dataIn.close() using try-with-resources in Java7 onwards.

try (final BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)) {
    // ...
}

The closing brace implicitly calls dataIn.close(), that's how try-with-resources is defined and works. Of course this is only required if, for some reason, you decide to stick to System.in instead of using Console.readPassword().

if-if vs. if-else if

In case things are mutually exclusive, if-else if should be preferred over if - if, for two reasons.

Performance - the else if checks are skipped if the if matched.
Expressing the intent (more important than performance unless requirements + performance analysis report says otherwise and a profile proves that this part of the code is the bottleneck)

The question now is, are isUpperCase(), isLowerCase() and isDigit() mutually exclusive? AFAIK they are, so go for else if instead of if.

Special characters

Are you sure that you have listed them completely? In the year 2015, do you want to limit this to the small bunch of ASCII non-digit non-control non-letters, when the Unicode offers so much more? Why not say: "everything else is a special character"?

Sanitize your input (NullPointerException on dataIn.readLine().length())

What if the user doesn't enter a password but closes the stream (using Ctrl+D on UNIX resp. Ctrl+Z on cmd.exe)?
In that case, dataIn.readLine() returns null, and password.X will throw new NullPointerException no matter what X is.

Therefore you might want to explicitly check that password != null.

Looping over characters of a String

The relevant part of your loop is:

for (int i = 0; i < password.length(); i++) {
    ... password.charAt(i) ...
    ... password.charAt(i) ... // again
    ... password.charAt(i) ... // and again and again...
}

The return value of password.charAt(i) would always be the same, so you can speed up the code and express the intent better at the same time by introducing a local variable and change the relevant part of the code to be like this:

for (int i = 0; i < password.length(); i++) {
    final char currentChar = password.charAt(i);
    ... currentChar ...
    ... currentChar ...
    ... currentChar ...
}

You can even go one step further because you're accessing each and every char of the entire String password, not just a few. Therefore, creating a char[] copy of the String comes with no penalty, in fact it makes the code faster - and again more maintainable:

for (final char currentChar : password.toCharArray()) {
    ... currentChar ...
    ... currentChar ...
    ... currentChar ...
}

However, in order to prevent password sniffing, you might want to clear each character as soon as it is analyzed, and thus go for:

final char[] password = Console.readPassword();
for (int i = 0; i < password.length; i++) {
    final char currentChar = password[i];
    password[i] = 0;
    ... currentChar ...
    ... currentChar ...
    ... currentChar ...
}

Platform-independent newline

In printf(), you're using \n to create a newline. You might want to use %n instead. \n is always LF (0x0A). But depending on the platform, the program should actually print \n (LF, 0x0A, UNIX), \r\n (CRLF, 0x0D 0x0A, DOS / Windows), \r (CR, 0x0D, old Mac) or even something else (weird IBM mainframes with EBCDIC and stuff).
With %n, printf will generate a newline for you with whatever the underlying platform would like to have.

Characters, char vs int, code points

When Java was invented, Unicode looked like 16 Bit.
Today, the Unicode is bigger than that.
A char in Java does not represent a Unicode character in general. It only represents a Unicode character if that character has a code point <65536. Thus analyzing single char values can be insufficient for rare alphabets.

@AJMansfield provided a solution which is functional and uses code points instead of char. Have a look at it. It also takes security into account.


Honestly I have no idea what the class is supposed to do. It is not validating anything, there is no input. It just always fails on ID 1 (whatever that means), no matter what. You probably omited too much. And whatever is omited probably deserves a review on its own.

There is no reason to have private $_errors. Change your checks so that the first passes and second fails. Then call validate() twice. The second call will not behave as expected. You better keep it as the method's local variable, or maybe you dont need a variable at all...

Question is why are you returning array of errors, if you only ever return one?
But let's say you have reason, then your errorGenerator is doing too much anyway.

public function validate()
{
  if (check1()) {
    return [$this->getErrorMessage(1)];
  }
  if (check2()) {
    return [$this->getErrorMessage(2)];
  }
  return [];
}

private function getErrorMessage(int $id)
{
  return 'an error occurred on ID ' . $id;
}

The check1, check2 methods represent something that is omited in your code samples...

And actualy you can take it a step further and remove getErrorMessage and inline the messages instead. Specific message for each check. Error message "an error occured on ID xy" is a terrible one.

Another way may be using exceptions, but to me it feels like abuse of exceptions. But I know there are a lot of devs who would disagree.

And last point to say: It's not always possible to squash two lines into one line while retaining qualities like readability. If it was possible, every program (no matter the complexity) could then be written as a well readable one liner ;)


Storing configuration data in a global variable on application startup

Regardless of whether or not this is a good use of global variables, it is a poor use of a class.

Your hub.py could look like this and function exactly the same (you could still import config_data from it):

import os
import yaml

file_path = os.path.join(os.path.expanduser("~"), "config_data.yaml")
with open(file_path) as f:
    config_data = yaml.load(f)

And now that it is obvious that this does not actually do a lot, I would make this a function and put this in your actual script (or maybe a utils script, if you have many more utilities like that):

file utils.py:

import yaml

def get_config(file_path):
    with open(file_path) as f:
        return yaml.load(f)

file bot.py:

import os
from utils import get_config

FILE_PATH = os.path.join(os.path.expanduser("~"), "config_data.yaml")
CONFIG_DATA = get_config(FILE_PATH)

class Bot:
    def __init__(self):
        self.pricing_params = CONFIG_DATA["pricing"]

if __name__ == "__main__":
    bot = Bot()


jQuery's .html() method can take a callback function - it'll be called for every element in the collection - and will use the returned value to set the element's html.

You can use bracket notation to access the key in your jsondata, so that you can dynamically get to the key you want with the string in the brackets:

$('.something').html(function () {
    return jsondata[ 'CameraTypeLabel' + $.text(this) ];
});

Note: $.text(this) is the same as $(this).text(), just a bit faster; it doesn't create a new jQuery object at every step in the loop.

If all you want to do is update the text, you can pass a function to .text() itself:

$('.something').text(function (i, oldText) {
    return jsondata[ 'CameraTypeLabel' + oldText ];
});


Using BigDecimal to validate epoch timestamp in exponential notation

There's no point in calling toBigInteger since that doesn't throw anything. You might as well just have this:

try {
    new BigDecimal(data);
} catch(NumberFormatException n) {
    return false;
}
return true;

Or you might consider using toBigIntegerExact if you don't allow fractional parts in the number (e.g. 1.2345E3 which is 1234.5 is not allowed):

try {
    new BigDecimal(data).toBigIntegerExact();
} catch(NumberFormatException | ArithmeticException e) {
    return false;
}
return true;

Also, have you thought about whether negative numbers should be allowed?

Regarding time & space performance, it will create one BigDecimal object (and possibly one BigInteger object) for every valid record. It will then release it as eligible for garbage collection. The JIT compiler will probably optimize this to make it insignificant compared to the time it takes to read and write the records.


Filtering input characters for a numeric text field using logical operators

Let's start with the assignment

let existingTextHasDecimalSeparator = textField.text?.range(of: ".")

The variable name suggests a boolean condition, but the value
is an optional range. It would be clearer to make it a boolean value:

let existingTextHasDecimalSeparator = textField.text?.range(of: ".") != nil

and similarly

let replacementTextHasDecimalSeparator = string.range(of: ".") != nil

The variable name isRangeInReplacementString is meaningless, this would
become

let existingTextHasLetters = string.rangeOfCharacter(from: .letters) != nil

and here .letters is inferred as CharacterSet.letters, so we don't
need an extra variable for that.

The variable name returnValueBool is also meaningless, that might
become

let isInvalidChange = (existingTextHasDecimalSeparator && replacementTextHasDecimalSeparator)
    || existingTextHasLetters
return !isInvalidChange

Now some simplifications: if the existing text has no decimal separator
then there is no need to check the replacement text for a separator.
And if you already detected a duplicate separator then you don't have
to check for invalid characters (letters). In other words: short-circuit:

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if textField.text?.range(of: ".") != nil && string.range(of: ".") != nil {
        return false
    }
    if string.rangeOfCharacter(from: .letters) != nil {
        return false
    }
    return true
}

But there are still two problems:

It is not possible to replace text containing the decimal separator
with new text also containing the decimal separator with copy/paste,
e.g. replace 1.2 by 3.4.
The decimal separator is locale dependent, it can be a period,
a comma (e.g. in Germany) and perhaps also other characters.

The first problem can be solved by computing the new string after
the replacement first, and then check if that is valid (only digits
and at most one decimal separator).

The second problem can be solved by using a NumberFormatter to check
if the text is a valid decimal number.

That would lead to the following implementation (which is essentially
a translation of the code in Big Nerd Ranch Bronze Challenge: Disallow Alphabetic Characters
to the current Swift 4):

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    guard let text = textField.text else { return false }
    // Compute new text after replacement:
    let newText = text.replacingCharacters(in: Range(range, in: text)!, with: string)
    // Check for empty string:
    if newText.isEmpty || newText == "-" {
        return true
    }
    // Check for valid decimal number:
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    return formatter.number(from: newText) != nil
}


You need rate-limit the amount of records you receive. You'll have to determine what the best rate is by yourself, as that is specific to your scenario.

High Priority:

Keep the list of "synced" entries in the database. Something like an IsSentToAnalytics column.
After you process a batch, update the database records you just selected with the synced set to yes, or 1, or true. The simplest way to do this would be to update each entry one by one, but there are more efficient solutions to that out there.
Your database query should only select from items that are not yet synced. This will be lighter on the database. (i.e. add the predicate and where IsSentToAnalytics <> 1)
Your dupCheck is catering for the above flag, essentially you're pulling unused data every time if it's a quiet period hence why you need the dupCheck. And also, MISSING data if it's a busy period. That can happen if you got more than 20 entries added to your database since your last run. This may be fine for hobby projects, but shoddy for production deployments.
Please, please add a surrogate primary key to your database. If anything, it keeps you from having to generate a hash every time you want to do a dupCheck.
The above entry kind of depends on how you generate the data. But since you have timestamp in there, I'm assuming every single record is unique anyways, so you might as well use the surrogate key as suggested. By the way, the surrogate key will be a sequence used as a primary key. Every entry inserted gets a unique value.
Edit. From your feedback below, you say you sometimes have duplicate values for the same timestamp. If that's the case, then you need to filter them out before inserting into the database initially. Whatever job/service that creates those entries needs to filter out the duplicates. You can try insert, and catch the DBException because it will fail the column constraint. Or, you could first do a select, and if no result is returned, insert, otherwise discard. You'll need to edit your question with more info for us to give you more detail on that.

Low Priority:

Move your sleep method into your while loop, not in your SQL pull, please. There is no need to sleep before returning data. Put the sleep where it belongs. Either that or change your function to be called PullDataAndSleep. If you think that function name is fine, then don't change the code inside it, just rename. Otherwise, put the sleep elsewhere.
Reuse your connection. You are disconnecting and reconnecting to the database every 5 seconds, it's pointless unless you expect your database connection to drop.
Change your while loop to just be "while Run", that's like saying while var == True. You're basically saying if True == True, then run. It's redundant.
Pull from the database at constant intervals(you are using 5s, play around with it).
Enforce an upper-bound amount of returned entries (you have 20)
The last two entries above will help you rate-limit how many requests you send off to Google. If you spam them too quickly, they might block/ban your IP.


An alternative would be to use a thread pool:
A fixed number of thread is created and each thread pulls and execute a task

Note that threads (from the Thread module) do not run in parallel (they are time-sharing)


There are a few things that are off in this query. Going through them in some sense of order:

I am still a fan of 'old style' joins, but, the CTE concept is a real winner in SQL Server, so, instead of creating the table variable, just use the CTE.
I can tell that your code went through some iterations, and as a result, you have some 'cruft' that can be disposed of. Delete those things that you don't select (like you select min(A.CreationDate) as AnswerTime which is never used.
The SEDE tables take some getting used to. You have done a CharIndex on the tags column. That's fine, but, your example php also pulls in php5 tags, as well as cakephp. To get around this, you should be aware that SEDE stores the tag names in <...> braces in the Tags field, so searching for <php> is what you want.

Using the CharIndex is OK, but more standard will be using like, as in: ... and Tags like '%<php>%'
I have actally given up on using the Tags field completely, and instead I do the join to the PostTags table which allows you to do the join natively without the like/charindex.
There is no need for the aggregate column on the Question's CreationDate. The max(Q.CreationDate) is redundant (there will only be one CreationDate per Question ID).
You should always use as many constants as you can when doing SQL Queries (at least as much as you can, until you find a performance reason to not overdo it....), so you should also add the A.PostTypeId = 2 even though its ParentID is the Q's ID.
I did not like the way you were 'Slotting' the data in to months. I find that subtracting the days-in-month-less-one from the given date brings the date back to the first-of-the-month, and then truncating the time, allows you to have all dates represented by exactly the first-of-the-month:

Convert(Date, DateAdd(day, 1 - DatePart(day, Q.CreationDate), Q.CreationDate)) as CreationMonth

Getting the Variable substitution to work was easier once I used the Tags table too. The stupid 'Unexpected error, blame has already been assigned' error is a PITA, but it is now gone.
Finally, the scale of the Y axis was so huge, that the count of the questions was not visibly appealing/apparent. By changing the scale from Seconds to Hours, the scales are better.

I forked your query here, and this is the SQL (I have tried to keep the capitalization and other style conventions consistent with your code):

declare @Language nvarchar(25) = ##LanguageTag:string##;
declare @tagid int;

select @tagid = Id
from Tags
where TagName = @Language

print @Language + '->' + Convert(NVarchar(max), @tagid);

with AnswerTime as (
 Select Q.Id,
       Convert(Date, DateAdd(day, 1 - DatePart(day, Q.CreationDate), Q.CreationDate)) as CreationMonth,
       Convert(float, DATEDIFF(second, Q.CreationDate, min(A.CreationDate))) AS Elapsed
 From   PostTags T,
        Posts Q,
        Posts A
 Where  T.TagId = @tagid
  and  T.PostId = Q.Id
  and  Q.PostTypeId = 1
  and  A.PostTypeId = 2
  and  Q.ClosedDate is null
  and  Q.Id = A.ParentId
 Group by Q.Id,
          Q.CreationDate,
          Convert(Date, DateAdd(day, 1 - DatePart(day, Q.CreationDate), Q.CreationDate))
)
Select CreationMonth,
       count(*)         as [Count of Tickets],
       avg(Elapsed)/3600.0 as [Average hours to first Answer]
From   AnswerTime
Group by CreationMonth

Edit/Update

I ran the query on Stack Overflow, and it fails because there are so many questions that the avg(Elapsed) fails with an arithmetic overflow. I have updated the query to only consider the past 68 years worth of data... (in case there are large date differences in seconds), and also to convert the elapsed in to a float (which does not overflow on avg())


Arrow key input to change selected row and column in a grid of HTML elements

Ok, after redoing it from scratch, here's a few points to consider:

Instead of checking if the key "exists" check if it's true/false
You can make it more flexible by making the size of the tile a variable (or even better, a variable for height and one for width)
It's better to store the tiles into an array, with their respective x and y variable. This way, you don't have to parse the DOM with jQuery each iteration of the loop, you only loop through the array and select the tile element.

Here's the new code:

HTML - Really simple, just the container for the tiles

CSS - We don't set the size of anything, we'll calculate it with JS

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body{
  background: #f1f1f1;
}

html,
body{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.board{
  display: flex;
  flex-wrap: wrap;
}

.tile{
  background-color: #000;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: .75rem;
}

.active{
  background: #aaa;
}

JS

//amount of tiles horinzontally and vertically
var tileAmountX = 15;
var tileAmountY = 15;

//actual column/row
var actualX = 0;
var actualY = 0;

//size in pixels of the tiles
var tileWidth = 40;
var tileHeight = 40;

//size in pixels of the board, calculated with tile size and tile amount
var boardWidth = tileWidth * tileAmountX;
var boardHeight = tileHeight * tileAmountY;

//array for storing the tiles
var tiles = [];

//keys object, default state are all off (false)
var keys = {left: false, top: false, right: false, down: false};

//set board size style
$('.board').css({
  width: boardWidth + 'px',
  height: boardHeight + 'px'
});

//generate tiles
for(var i = 0; i < tileAmountX; i++){
  for(var j = 0; j < tileAmountY; j++){

    //create tile and store it in temporary variable
    var el = $('
O
').appendTo('.board');

    //store that variable in the `tiles` array, with the respective `x` and `y` coordinate
    tiles.push({
      el: el,
      x: i,
      y: j
    });
  }
}

//move to right function, just changes the actualY value and check for overflow
function moveRight(){
  actualY = actualY < tileAmountY - 1 ? actualY + 1 : 0;
}

//move to left function, just changes the actualY value and check for overflow
function moveLeft(){
  actualY = actualY > 0 ? actualY - 1 : tileAmountY - 1;
}

//move to top function, just changes the actualX value and check for overflow
function moveTop(){
  actualX = actualX > 0 ? actualX - 1 : tileAmountX - 1;
}

//move to down function, just changes the actualX value and check for overflow
function moveDown(){
  actualX = actualX < tileAmountX - 1 ? actualX + 1 : 0;
}

//generic move function
function move(){
  //get the tiles that have the X or Y coordinate from actualX or actualY
  var starting = tiles.filter(function(val){
    return (val.x == actualX || val.y == actualY);
  });

  //remove the active class for all tiles
  for(var i = 0; i < tiles.length; i++){
    var tile = tiles[i];
    tile.el.removeClass('active');
  }

  //add the active class for the tiles that have the X or Y coordinate from actualX and actualY
  for(var i = 0; i < starting.length; i++){
     var tile = starting[i];
     tile.el.addClass('active');
  }
}

function loop(){

  //this is pretty self explanatory
  if(keys.right){
    moveRight();
  }else if(keys.left){
    moveLeft();
  }

  if(keys.top){
    moveTop();
  }else if(keys.down){
    moveDown();
  }

  //this function runs regardless of the user input
  move();

  //loop with 30fps
  setTimeout(loop, 1000/30);
}

//initiate loop
loop();

//event listener for keydown and keyup
$(window).on('keydown', function(e){
  if(e.keyCode==37){keys.left = true}else if(e.keyCode==39){keys.right = true};
  if(e.keyCode==38){keys.top = true}else if(e.keyCode==40){keys.down = true};
});

$(window).on('keyup', function(e){
  if(e.keyCode==37){keys.left = false}else if(e.keyCode==39){keys.right = false};
  if(e.keyCode==38){keys.top = false}else if(e.keyCode==40){keys.down = false};
});

If you want to see a live example, check this link:

https://codepen.io/tyrellrummage/full/bobxPp/

As you can see, even with a big board (15x15) the motion is very fluid and responsive.

There may be a better way to achieve this, but this is the best I can come up with!


Different neural network activation functions and gradient descent

Your code is correct. What can be improved is readability and speed.

First thing first, don't mix up the computation of the function and the computation of the derivative. I understand that passing True to the function to get the derivative can be convenient, but consider doing something less confusing.

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x)
    return x * (1 - x)

You can always pass both versions of the function to your gradient descent function, or create Sigmoid class with forward/backward versions. This is what PyBrain and Torch do for example. Let's look at the PyBrain ReLU since it's done in Python:

from pybrain.structure.modules.neuronlayer import NeuronLayer

class ReluLayer(NeuronLayer):
    """ Layer of rectified linear units (relu). """

    def _forwardImplementation(self, inbuf, outbuf):
        outbuf[:] = inbuf * (inbuf > 0)

    def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
        inerr[:] = outerr * (inbuf > 0)

I think looking at this is a good way to review your code. First, what you did is not different, congratulations! The differences are mostly about optimizations, because speed is really important in neural networks. Let's look at the differences:

They did not conflate the two functions as I explained earlier
They set up their network to avoid allocations during training: they set outbuff using inbuf inplace: once they created their neural network, they don't need to create anything, just update weights to go as fast as possible. It probably wasn't your main concern here, and that's perfectly OK if you're doing this to learn.
They don't use loops and conditions, but stick to vectorized operations. Again, it's an optimization concern: vectorized operations get executed much faster. Maybe you did not think about the inbuf > 0 trick (which will create a matrix of zeros and ones), but it will make your code faster.
They group all computation: the equivalent of inerr[:] = outerr * (inbuf > 0) in your code is layerDelta = layerError * relu(layers[i-1], True). I don't think this is a crucial difference.


Reinterpreting a string, treating < as a backspace character

Recursion is a great tool to have available when dealing with some problems, but each recursive call carries a cost. The cost depends on the language being used, and perhaps the OS architecture. As a consequence, the usefulness of recursion is limited by the circumstances in which the recursion is applied.

In Java each function call typically costs a number of kilobytes of memory as that's the size of the stack frame (and each call requires a new stack frame). Also, in Java, the stack size (memory) is pre-allocated as part of the VM settings (see -Xss commandline option) Other languages (for example, Go) have a much cheaper mechanism for stack management, and thus the cost of recursion is reduced. Java typically cannot go further than a few thousand calls deep in the stack, Go can go millions of calls deep. In your use case, the depth of the stack is proportional to the length of the input string, and strings longer than a few thousand characters will cause an out-of-memory problem.

Bottom line, is that recursion is not the solution to use for your problem. Even in other more stack-friendly languages I would still avoid recursion.

Solve it iteratively, using a StringBuilder, a Reader, and an if-statement...

public static String fix(Reader reader) {
    int ch;
    StringBuilder result = new StringBuilder();
    while ((ch = reader.read()) >= 0) {
        if (ch == '<') {
            result.setLength(result.getLength() - 1);
        } else {
            result.append((char)ch);
        }
    }
    return result.toString();
}


Here are some things I see that can improve your code.

Resource Management

To avoid resource leaks, it is usually good to close IO classes like java.util.Scanner if you won't be using them anymore. This is because the garbage collector only manages memory and not other resources.

in.close();

Modularity

Currently your program contains a main method that does all tasks. This is not a good idea if you choose to reuse some parts of it (E.G. doing celcius conversions multiple times). I think it is a good idea to put the two conversions into separate methods. That way the components of your program would be more reusable (specially if you choose to add more operations later) and would be more readable as a whole.

Error handling

At least write an error handling mechanism, even a general one. For example:

try (Scanner in = new Scanner(System.in)){
    // handle user inputs and conversions
} catch(IOException e) {
   // handle IO exception
}

Notice that I use Try with resources so the scanner resource rapped in the try block would automatically be closed after the block finishes executing. So no need to call in.close() anymore


Boolean class using shared referenced memory

I'm sorry to be so straightforward: This is madness! Your code seems to indicate a sincere lack of several language features.

Pointer to const

You define MEM to be of type uint8_t*, but it actually points to  values of const uint8_t. To account for this difference you cast the const away in both constructors. If you'd ever (accidentally) write to the memory MEM points to, undefined behavior might ensue. So it should be at least of type uint8_t const *.

Memory leak in constructor

As you have suspected, your code leaks memory. Both constructors assign new uint8_t to MEM before overwriting it directly afterwards. Now there is no way to reference the values created on the heap with new. Both allocations are not necessary since MEM always points to one of the two static variables. Therefore you should also not try to delete them once Zeroth goes out of scope.

Since we are at the constructor: why do you accept an 32bit integer as argument when all you care about is one bit and all your internal values are stored in an uint8_t? I also find it unintuitive to treat all the even numbers as false, and all the odd ones as true (this is basically a consequence of your bit mask). Often all values except 0 are treated as truthy values (exempt of this rule are exit codes, where 0 is usually seen as success).

isPresent/isNotPresent

Those functions do not even compile on a 64bit platform, since the completely unnecessary cast to int narrows the bidwidth of the pointer type from 64bit to 32bit. Apart from that, there is a whole lot of other weird things going on here.

Let's try to break this down:

(int)&(*this->MEM)

this->MEM is a pointer. You then for whatever reason decided to dereference (*this->MEM) it to get the value it's pointing to. After that, you take the address of the value (&(*this->MEM)), which should be the same as this->MEM. And if all of this weren't enough, you then try to cram the address into an int ((int)&(*this->MEM)).

Same procedure for the value you try to compare it with:

(int)&Zeroth::UnitSet

You have the value Zeroth::UnitSet, take the address of it &Zeroth::UnitSet and then try to cram this address into a 32bit integer.

You get the same effect using

bool isPresent() const { return &Zeroth::UnitSet == this->MEM; }
bool isNotPresent() const { return &Zeroth::NullSet == this->MEM; }

without all this madness.

Memory footprint

The internal state of your class is represented by a pointer to a const uint8_t. As I have already tried to tell you in the comments, the size of the pointer is 32bit or 64bit depending on which type of architecture your compiler tries to target. This 4 to 8 times larger than the 8bit you would need to store the value. If you stick with the value, there are far less possibilities to shoot yourself in the foot.

class ZerothVal {

public:
    ZerothVal() = default;  // see https://en.cppreference.com/w/cpp/language/default_constructor

    ZerothVal(uint8_t VAL) {
        val = (VAL & 0x1 ? ZerothVal::UnitSet : ZerothVal::NullSet);
    }

    bool isPresent() const { return val == ZerothVal::UnitSet; }
    bool isNotPresent() const { return val == ZerothVal::NullSet; }

    friend std::ostream& operator<<(std::ostream& os, const ZerothVal& data);

private:
    const uint8_t NullSet = 0;
    const uint8_t UnitSet = 1;

    uint8_t val = ZerothVal::NullSet;
};

std::ostream& operator<<(std::ostream& os, const ZerothVal& data) {
    return os << (data.isPresent() ? 'T' : 'F');
}

Operator support

Since you'd like to implement some kind of bool value, I'd highly recommend implementing the Safe Bool Idiom. For you that would mean that you have to implement operator bool() for your class (see this SO post for an explanation).


Shuffling algorithm for a "guess that tune" game

No. Your shuffle will not be random. You are stepping through each card and swapping it with another random card. This is a common bug found in many shuffling algorithms.

To illustrate why your shuffle is not random, let's assume you are shuffling three songs (1, 2, 3). There are six combinations of three song (123, 132, 213, 231, 321, 312). If your shuffle was random, each of these combinations should appear with equal probability. So if you run your shuffle algorithm 600,000 times, each combination should appear roughly 100,000 times each.

But it doesn't. When you run your shuffle algorithm 600,000 times (as written), you will see results similar to this:

To understand why your implementation produces biased results, read this article on Coding Horror: The Danger of Naïveté.

What you want is a Fisher-Yates shuffle where you swap the current card with any of the remaining cards (or itself).

Here it is in pseudo code for an in-place shuffle:

To shuffle an array a of n elements:
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

There are other types of Fisher-Yates shuffles listed here: Wikipedia: Fisher–Yates shuffle.


Mapping key value pairs between two JavaScript objects

It might be a little cleaner to use .reduce instead of for...of... loop:

Object.keys(widgetsObj).reduce( (obj, key) => {
    obj[key] = this.components[widgetsObj[key]];
    return obj;
}, {});


Bag data structure (a set that can store multiple copies of items)

As you're trying to implement a multiset (or bag) I would recommend you to use collections.Counter which already does the same thing:

  The Counter class is similar to bags or multisets in other languages.

So, simply inherit from Counter class and add your additional methods in the class or override the already present methods from Counter class as per your requirements. Counter class also supports &, |, - operators to perform various multiset operations.

Now, coming back to your code:

def __init__(self, items = []):
    self.bag_value = defaultdict(int)
    for item in items:
        self.bag_value[item] += 1

Never use a mutable object as default value of an argument as there value can persist between calls, the recommended way is to use None as default value and then check it inside of the __init__ method. As we are now inheriting from Counter we can directly operate on self instead of using a defaultdict to keep the count.

class Bag(Counter):

     def __init__(self, _items=None, **kwargs):

          _items = [] if _items is None else _items
          super().__init__(_items, **kwargs)

  Why both _items and kwargs?

It depends on how you want to use it ultimately, but with this signature you can use it as:

Bag('aaabbccd')
Bag(a=3, b=5, c=7)
Bag('aabbcc', a=5, c=7, r=9)

I used _items to handle the case when user actually passed a key named items:

Bag(a=5, c=7, r=9, items=9)

def __repr__(self):
    bag_list = []
    for item, count in self.bag_value.items():
         bag_list.extend(list(item*count))
    return 'Bag(' + str(bag_list) + ')'

Counter class already has a method to handle this called elements() which returns an itertools.chain object which is an iterator, we can call list on it and we are done:

def __repr__(self):
    return 'Bag({})'.format(list(self.elements()))

def __str__(self):
    return 'Bag(' + ','.join(str(item) + '[' + str(count) + ']' for item, count in self.bag_value.items()) + ')'

We can take advantage of string formatting here to make the above code a little concise and easier to read:

def __str__(self):
    format_str = '{}[{}]'.format
    return 'Bag({})'.format(', '.join(format_str(k, v) for k, v in self.items()))

def __len__(self):
     bag_len = 0
     for value in self.bag_value:
         bag_len += self.bag_value[value]
     return bag_len

In our class we can obtain the length by simply summing the .values(), sum() returns 0 when the Bag is empty so it saves a lots of line:

def __len__(self):
    return sum(self.values())

We can simply drop __contains__ as Counter can already handle that part, and for unique() we can use len(self.keys()).

def __add__(self,right):
    mergedbag = Bag()
    mergedbag.bag_value = copy.copy(self.bag_value)
    for item in right.bag_value.keys():
        mergedbag.bag_value[item] += right.bag_value[item]
    return mergedbag

Here as we're only dealing with integer values copy.copy is not actually required, and instead of manual loop use the .update() method of dictionary:

def __add__(self, right):
    merged_bag = Bag()
    merged_bag.update(self)
    merged_bag.update(right)
    return merged_bag

In .remove() the only change is that I used string formatting with __repr__ version of item. __repr__ is more useful as with str() you won't be able to differentiate between 1 and '1'.

raise ValueError('{!r} not in bag'.format(item))

def __eq__(self, right):
    if type(right) is not Bag:
        raise TypeError('Cannot compare Bag with' + type_as_str(right) + '. Can only compare Bag with Bag')
    else:
        return (Counter(self.bag_value)==Counter(right))

The recommended way to check the type of an object is to use isinstance rather than calling type. And in else block I simply called the super class's __eq__ to handle the result instead of creating Counters:

def __eq__(self, right):
    if not isinstance(right, Bag):
        raise TypeError(('Cannot compare Bag with object of type {!r}. Can only '
                         'compare Bag with Bag').format(type(right).__name__))
    else:
        return super().__eq__(right)

def __iter__(self):
    return self.__generate__(self.bag_value)

Never define your own dunder method(__generate__), these methods are considered special by Python and if any future version of Python defines a method by the same name then your code can result in some unknown errors. In our __iter__ method we can simply yield from self.elements():

def __iter__(self):
    yield from self.elements()

Note that there should be only be single line of space between method of a class and your indentation is also messed up, always use 4 spaces no tabs(Change your IDE's setting to use 4 spaces for a tab). Read PEP-008 for more information on styling-guide.

Complete code:

from collections import Counter

class Bag(Counter):

     def __init__(self, _items=None, **kwargs):

         _items = [] if _items is None else _items
         super().__init__(_items, **kwargs)

     def __repr__(self):
         return 'Bag({})'.format(list(self.elements()))

     def __str__(self):
         format_str = '{}[{}]'.format
         return 'Bag({})'.format(', '.join(format_str(k, v) for k, v in self.items()))

     def __len__(self):
         return sum(self.values())

     def unique(self):
         return len(self.keys())

     def count(self, item):
         return self[item]

     def add(self, new):
         self[new] += 1

     def __add__(self, right):
         merged_bag = Bag()
         merged_bag.update(self)
         merged_bag.update(right)
         return merged_bag

     def remove(self, item):
         if item in self:
             if self[item] == 1:
                 del self[item]
             else:
                 self[item] -= 1
         else:
             raise ValueError('{!r} not in bag'.format(item))

     def __eq__(self, right):
         if not isinstance(right, Bag):
             raise TypeError(('Cannot compare Bag with object of type {!r}. Can only '
                              'compare Bag with Bag').format(type(right).__name__))
         else:
             return super().__eq__(right)

     def __ne__(self, right):
         return not self.__eq__(right)

     def __iter__(self):
         yield from self.elements()


Data structure
There is no such thing as a "standard graph data structure." There are a few different data structures for representing a graph and you have implemented the adjacency list. The main problem with your implementation is that you have actually implemented the traversal algorithm and the data structure is just an "accessory" to it. It is not possible to extract the graph from the code and use it somewhere else so there is not much point in spending a lot of time reviewing the graph implementation as a data structure.
I would expect a graph data structrue to be encapsulated in a class named Graph (or an interface named Graph with implementations in classes like AdjacencyListGraph and AdjacencyMatrixGraph). The purpose of the encapsulation is to protect the data structure from manipulation which would break the data structure. For example, as you represent the adjacency as a Map<Node, ArrayList<Edge>> you allow a situation where a single edge could be assigned to two nodes, which would destroy your traversal algorithm.
Your Edge implementation is tightly bound to the traversal algorithm because you have placed the isExplored attribute to it. A pure graph implementation should not be concerned about how it is traversed.


Converting float from arbitrary base to arbitrary base

It is not necessary to deal separately with the integral and fractional parts.

When converting from string, remove the point, convert as integer and scale according to the position where the point was.
When converting to string, scale to integer, convert and insert point in the right place.

Here's how you can implement convert with _int_to_base as the only helper function:

def convert(number, original_base, new_base, precision=None):
    #from original_base
    integral, point, fractional = number.strip().partition('.')
    num = int(integral + fractional, original_base) * original_base ** -len(fractional)

    #to new_base
    precision = len(fractional) if precision is None else precision
    s = _int_to_base(int(round(num / new_base ** -precision)), new_base)
    if precision:
        return s[:-precision] + '.' + s[-precision:]
    else:
        return s


Let me collect a couple of thoughts here.

When the input validation is not successful, users immediately get the ">>" prompt without any notification that their input wasn't accepted. Maybe add a hint that no action was performed?

  Almost every example online uses char or int for the input, are there benefits to this?

The input that you ask for so far is one out of 1, 2, q or Q, i.e., 4 entries from the ASCII table. Using a single char for this is a reasonable choice, but might be limiting when the program grows. Maybe you want to ask users for paths, tokens, anything with more than one character? Having setup everything with std::string in the first place might be the more pragmatic approach, as it simplifies things (e.g. one function for both the one-char-only and multi-char-input).
In GetInput(), you are doing more work than necessary:

string s = "";

You want an empty string instance to be passed to std::getline, then default-construct it with std::string s; instead of initializing it with an empty string literal (remember that the type of "" is const char[1], std::string s = ""; is not a no-op), see also Item 4 in Scott Meyer's Effective C++.
You flush the standard output a lot of time, when you actually just want a newline \n to be printed out. See this thread for more details.
This is in my opinion the most severe point: the menu logic doesn't scale well. What do you have to change when you need to add a third option? You need to adjust the initial check and you need another else if branch:

input.find_first_not_of("123qQ") // ...

/* ... */

else if (input == "3") { /* ... */ }

The number of options to make this approach unreadable and hard to maintain is quite low, so think about an alternative here. To give you an idea of how this
could be improved:

struct MenuAction {
   std::string description;
   std::function<void()> action;
};

static const std::map<std::string, MenuAction> actionTable {
   {"1", { "Add entry", [](){ std::cout << "Add entry" << "\n";  }}},
   {"2", { "Edit entry", [](){ std::cout << "Edit entry" << "\n";  }}},
   {"q", { "Quit", [](){ std::cout << "Quit" << "\n";  }}}
};

Then, you can display available options (assuming C++17 is available) via

for (const auto& [key, value] : actionTable)
   std::cout << key << ". " << value.description << "\n";

and the original if-else if-else logic boils down to

while (actionTable.count(input) == 0)
   input = GetInput();

actionTable.at(input).action();

Maintaining user options is now identical to maintaining the std::map instance.
Minor detail; you naming scheme doesn't seem to be consistent. GetInput() starts with an upper case letter, while mainMenu() with a lower case letter.
This is very rare, but you could use a do-while construct here to reduce the number of calls to GetInput():

 std::string input;

 do
    input = GetInput();
 while (actionTable.count(input) == 0);

It seems at least debatable to me whether this is worth it, but as it crossed my mind, I couldn't resist suggesting it :)


First off, I'd like to say that you're asking two questions which are at odds with each other. Having readable ><> code usually requires a decent amount of whitespace, but minimising the number of ticks requires reducing the amount of whitespace and a bit of golfing. I'll assume that you're primarily aiming for the latter, while keeping the code as readable as possible under this constraint.

General comments

Less than

A minor one about your explanation - ( is second < top, so by having n, s at the top of the stack you're checking whether square > n, not square >= n. If it were the latter, your code would fail for numbers like 9! (no factorial)

Floats

Just a note of warning: both the online interpreter and the official Python interpreter use floats for division, so this program would most likely fail for large numbers. Unfortunately, I don't know of any good way to perform integer division as efficiently.

Wrapping and reading direction

Wrapping the last line doesn't affect efficiency, so it's more readable to have the , follow the @. Also, if we wanted to save every tick, we could have this part on the second-last line instead:

:?!;:2%?v2n2,30.
        >:3:02.
::*$}(?v::{:@%?!v2+
       >:1=?;n; >:@,:r~:n:02.

Note that I've also flipped the :1=?;n; for readability since it fits going left-to-right.

Print if not 1

Speaking of :1=?;n;, this reads as "halt immediately if the number is 1, else print the number then halt". This could be more clearly expressed as

:1=?!n;

to "print the number if it's not 1, then halt". Alternatively, you can use -? as an idiom for "if not equals", and do

:1-?n;

to save a tick.

Division by 2 loop

It's a bit more logical to separate the initial zero check from the rest of the first line, which divides out factors of 2. This is also a bit more efficient, since we save on the 30. jump.

:?!;v
2n2,>:2%?v

Main loop efficiency

To get from the stack state [n, n, i] to [i, n, n, s], you currently do

::*}$

Instead, you can do

:}:*

Putting all of the above notes together, we get the slightly more efficient version:

:?!;v
2n2,>:2%?v
         >:3:03.
:}:*(?v::{:@%?!v2+
      >:1-?n;  >:@,:r~:n:03.

Outputting characters

This only concerns your testing code, but outputting single characters should be done with quotes for readability, i.e. ','o rather than 4b*o to output a comma.

Would-be readability comments

In terms of general ><> readability, I wouldn't call this particularly readable, but under the constraint of efficiency it's pretty good. However, if the goal were strictly readability, here are a few comments:

Whitespace should be used to group logical components, e.g. :2%?v 2n 2, 30..
It makes more sense logically to enter the main loop starting with [n, i] rather than [n, n, i].
Because 02. starts execution of the main loop from the second : of ::*, you have an extra : to compensate before both instances of 02.. To cut down on repetition, the main loop should be indented. (You could also move the + from the end to the start so as to not lose efficiency, but that comes at a cost to readability).

Extra: using l as a counter

For extra efficiency and sheer stupidity, we can use l (which pushes the length of the stack) as a counter to save on stack manipulation. Granted, this would run into memory problems for large numbers and is terrible for readability, but I'm sure that's the least of our worries if we're factorising in ><>!

:?!;v
2n2,>:2%?v
         >:f3.
:l:*(?v:l%?!v::
;n?-1:<     >:lnl,$~f3.


Strive for self-documenting code
Python's any and all are extraordinarily useful, but few people know about them, for example:
def is_board_full(self, gameboard):
    for index in range(1, 10):
        if gameboard[index] == ' ':
            return False
    return True

Is understandable but not obvious, using all it becomes:
def is_board_full(self, gameboard):
    return all(gameboard[index] != ' ' for index in range(1, 10))

Kind of better, now let's use native iteration:
def is_board_full(self, gameboard):
    return all(square != ' ' for square in gameboard.values())

Now we can define a constant:
EMPTY = ' '

...

def is_board_full(self, gameboard):
    return all(square != EMPTY for square in gameboard.values())

That reads as "the board is full if all the squares are not empty", you may prefer "the board is full if not at least one one square is empty"), expressed as:
def is_board_full(self, gameboard):
    return not any(square == EMPTY for square in gameboard.values())

The most self-documenting of all is probably using a helper:
def is_there_at_least_one_empty(self, gameboard):
    return any(square == EMPTY for square in gameboard.values())

def is_board_full(self, gameboard):
    return not self.is_there_at_least_one_empty(gameboard)

The code now looks like a high level description of the problem, not a specific implementation.
@staticmethod
You pass self into your methods, but most do not use it. A method that does not use self is called a static method and the convention is not to pass self to those methods by applying the @staticmethod decorator:
@staticmethod
def is_there_at_least_one_empty(gameboard):
    return any(square == EMPTY for square in gameboard.values())

@staticmethod
def is_board_full(gameboard):
    return not GameBoard.is_there_at_least_one_empty(gameboard)

Given that all the methods in Gameboard are static you may consider using top-level functions, and achieve separation of concerns by putting those in a separate file. Using a class adds complexity and in this case you do not seem to need nor want one (using only static methods defies OOP completely)
Simplify
Do not start by writing a lot of loops and ifs, you start with a description of the problem:

"To print a board, I print each one of its line"
"To print a line, I print the squares joined by |"
"To divide a board into lines, I divide it in chunks of 3"

If you are wondering, dividing a list in chunks of x is present on StackOverflow: https://stackoverflow.com/questions/10364391/how-to-split-python-list-into-chunks-of-equal-size
def split_into_lines(board):
    return zip(*[iter(board.values())]*3)

def _print_line(line):
    print(' | '.join(line))

def print_gameboard(board):
    for line in split_into_lines(board):
        _print_line(line)

This is much clearer and modular then your original version.


Special summation of integer array elements

I think min and max are more descriptive names than high and low.
In C# the standard naming convention for methods is PascalCase.
You could save several iterations by doing the following things:

Create a single method for determining min and max in one go and return either a Tuple or a custom type or an array of length 2 or provide out parameters. If you don't want to use any more complex types than arrays then I'd probably go for out parameters (returning an array of a certain size doesn't seem very nice). So something along these lines:

public void DetermineMinAndMax(int[] input, out int min, out int max)
{
    min = Int32.Max;
    max = In32.Min;
    foreach (int number in input)
    {
        if (number < min) { min = number; }
        else if (number > max) { max = number; }
    }
}

Keep counters of how often you have seen the min/max already - if it's 1 add it otherwise skip. Something along these lines:

public void SumSpecial(int[] input)
{
    int min, max;

    DetermineMinAndMax(input, out min, out max);

    int countMinSeen = 0;
    int countMaxSeen = 0;

    int sum = 0;

    foreach (int number in input)
    {
        if (number == min)
        {
            if (countMinSeen == 1) { sum += number; }
            countMinSeen++;
        }
        else if (number == max)
        {
            if (countMaxSeen == 1) { sum += number; }
            countMaxSeen++;
        }
        else { sum += number; }
    }
}

This should reduce the number of required iterations to 2 instead of 4.


The expression ''.join(str(s) for s in self.characters simply returns a copy of self.characters. Consider phrasing it

    return color.RED + self.characters + color.END

Similarly ','.join(str(s) for s in self.contents seems longer than necessary.

This does not appear to be used:

    def __bool__(self):
        return True

I'm afraid you lost me here:

    gen = curr_group(iter(line))

I don't see any mentions that define line.

Yielding a value to co-routine seems to be working fine, just as you wish.


A z-shell function to quickly cd into projects

Remove unused variables

The variable argument_count is not used for anything, so you should remove it.

Simplify shell arithmetics

Instead of this:

(( argument_count=argument_count-1 ))

You could simplify using the postfix operator:

(( argument_count-- ))

Simplify condition

This condition can be written simpler:

if [[ ! (( -n $root && -n $project_name )) ]]; then

Like this:

if ! [[ -n $root && -n $project_name ]]; then

Note that you could also drop both of the -n flags there,
the expression will still mean the same:

if ! [[ $root && $project_name ]]; then

For the same reason, I suggest to drop all the -n in all conditions.

Always double-quote path variables

At some places you did a good job double-quoting path variables:

  target_dir="$target_dir/$root/$project_name"
  if [[ -n $app_name ]]; then
    target_dir="$target_dir/$app_name"
  fi

At others you didn't:

  # When the create flag is true (-c), create target directory
  if [[ $create == true ]]; then
    mkdir -p $target_dir
  fi

  # Finally, cd to the targeted directory
  cd $target_dir

Make it a habit to double-quote path variables always.


How can I make my program that calculates π faster?

You random-points sub has a few things which can be removed or simplified.

1.rand returns a Num, so there is no reason to call the method .Num on its result.
Rather than gather for take you can use the xx operator.
You only want a positive number for the count, so declare that with UInt

sub random-points(UInt $count --> Seq) {
    Point.new(x => 1.rand, y => 1.rand) xx $count
}

xx seems to be on the order of 10× faster than gather for take.
The reason is mostly that take works by throwing a CONTROL and gather captures that message.
On my computer that change alone takes it from nearly 9 minutes (8m49.881s) to around 2 and a half minutes (2m27.582s). (The other changes have no meaningful effect on the run time.)
The sweet spot for the gather take feature is where there isn't already a built-in for what you are doing, and the speed doesn't matter as much as the ease of writing it.
You could go to the work of creating your own Iterator class which could speed it up. That is why xx is so much faster, there is already an Iterator class that was created specifically for it.
(Note that I did actually test to see if writing a new Iterator class would help. It didn't help, in fact it was slower.)

There are similar issues in compute-pi.
To start off, there are improvements to be made to gather for 0..^∞.

Don't mix Int and Num endpoints for Range objects if you can help it. 0e0..∞
Don't use for for infinite loops, just use loop

gather loop {

    ...

    take $ratio * 4;
}

I would not store the filtered random-points Seq in a variable, because the only thing you need from it is the count.
my Int $points-inside = +random-points($batch).grep: *.is-inside-unit-circle;

The prefix + operator just coerces to a Numeric value. Obviously the only number that makes sense for a Seq is the same as .elems, the count of elements.
.elems could potentially return a Num, specifically Inf. Considering that would break the rest of the code anyway, I think it's fine to store it in an Int scalar.

Ok now that we are done with the more obvious cleanups we can try to make it faster.
Thankfully changing from gather for take in random-points to xx helped a lot. (No other change had any meaningful change on the amount of time taken.)
The first thing I did at this point was to run the profiler
raku --profile test.raku

There were no obvious slow parts of our code. In fact a good ⅔ of the run time was in the Raku runtime, not our code.
So let's add parallelism to see if we can reduce the time by using more CPU cores.
We could just make the sequence returned from random-points a race sequence to see if it helps.
my Int $pointsInside = +random-points($batch).race.grep(*.is-inside-unit-circle);

After that change it now takes 4 minutes, almost twice the time it took from before that change.
I did mess around with the batch and degree arguments to race, but no combination seemed to improve it meaningfully. At best I made it match the original timing.
So now we know that was a dead-end. random-points.grep was already about as fast as possible.

So let's add the asynchrony to compute-pi instead.
One obvious thing we could do is have a bunch of threads creating the sequences of random-points.grep.
Of course we don't know how many we need to create. So let's give that as an argument.
sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

Now we want to have an existing sequence that we can call race on.
my \batches = ^$batch-count;

Add race to it.
(We don't care about the order of random-points.grep values we get.)
my \batches = (^$batch-count).race(batch => 1);

The reason for the batch argument of 1 is that we know each random-points.grep takes a long time, so we don't want it to batch them together. We also don't want to wait for 64 of them to be calculated before we get any results.
Now to turn that into the sequence of values that we want by using map.
my \batches = (^$batch-count).race(batch => 1).map: {
    +random-points($batch-size).grep(*.is-inside-unit-circle)
}

Rather than have an infinite loop, we will loop over those batches
gather for batches -> Int $pointsInside {

So the last part of the file now looks like this:
sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

    my \batches = (^$batch-count).race(batch => 1).map: {
        +random-points($batch-size).grep(*.is-inside-unit-circle)
    }

    my Num $total = 0e0;
    my Num $count = 0e0;

    gather for batches -> Int $pointsInside {

        $total += $batch;
        $count += $pointsInside;
        my Num $ratio = $count / $total;

        take $ratio * 4;
    }
}

{ say "π ≈ $_" } for compute-pi(100_000, 500);

It now takes just over a minute (1m13.905s) with a cpu time of over 5 minutes (5m19.237s).
Which means we have more than 400% utilization. Which is fairly good on a 4 core CPU, with hyperthreading.

We can gain a bit more if we use native num variables instead of boxed Num variables.
You have to be careful with this as you can actually make it take more time if the value ends up needing to be boxed for an operation.
class Point {
    has num $.x;
    has num $.y;
    ...
}

...

sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

    my \batches = (^$batch-count).race(batch => 1).map: {
        random-points($batch-size).grep(*.is-inside-unit-circle).Num
    }

    my num $total = 0e0;
    my num $count = 0e0;

    gather for batches -> num $pointsInside {

        $total += $batch;
        $count += $pointsInside;
        my num $ratio = $count / $total;

        take $ratio * 4;
    }
}

That final change brings it down to about 42 seconds (0m42.771s) with 4 minutes of CPU time (4m0.929s).
Which also seems to increase the CPU utilization up over 500%.

The biggest improvement was going from gather for take to just xx. Which I'd argue was warranted just for how much it improved the clarity of the code. The other changes were of minimal benefit.
I think to get any significant improvement would require improving the compiler, runtime, or the VM.
Really what we ended up with is fairly fast considering how much of higher level language Raku is than C#, and how few people are working on it.


You should avoid mixing calculations with input/output. It would be better if your doMath() would not call the output function ap() directly, but instead would just return the result of its calculations:

ap(doMath({'numbers': [10,5,2,2], 'method':'subtract'}));

Of course the ap itself is a lousy name for a function, but it's more of a helper in here I guess.

I see no reason why you would use and options object instead of passing in just two parameters, but even when you use an options object, it would be simpler to extract its values into local variables and work with these. One can also easily drop the use of $.extend in favor of simple || operator, which is the canonical way of implementing default values for parameters:

    var method = options.method || "add";
    var numbers = options.numbers;

Another step to simplify code is to filter out the invalid numbers before doing any calculations on them. Array.filter helps us here:

var validNumbers = numbers.filter(isNumber);

The actual calculation can be easily implemented with Array.reduce. First we can define functions add and subtract

var methods = {
    add: function(a, b) { return a + b; },
    subtract: function(a, b) { return a - b; }
};

And then using Array.reduce we can apply them for the whole array:

validNumbers.reduce(methods.add);
// or
validNumbers.reduce(methods.subtract);

Pulling it all together:

function doMath(options) {
    var method = options.method || "add";
    var numbers = options.numbers;

    var validNumbers = numbers.filter(isNumber);

    var methods = {
        add: function(a, b) { return a + b; },
        subtract: function(a, b) { return a - b; }
    };

    return validNumbers.reduce(methods[method]);
}


Converting the first and last name to pig latin

Structure

Try not to use static variables. static is for when the value of a field is the same across all instances of your object. But this isn't the case with peoples names.

What if you have two people? You would create your people:

    Question3 name = new Question3("walt", "savitch");
    Question3 anotherName = new Question3("john", "smith");

But then, you cannot use them the way you want.

If instead you would rewrite your code like this:

public class Question3 {

    private String first;
    private String last;
    private String newName;

    public static void main(String[] args) {

        Question3 name = new Question3("walt", "savitch");
        Question3 anotherName = new Question3("john", "smith");
        System.out.println(name.convertFullName());
        System.out.println(anotherName.convertFullName());

    }

    public Question3(String lowerCaseFirstName, String lowerCaseLastName) {
        first = lowerCaseFirstName;
        last = lowerCaseLastName;
    }

    public String convertFullName() {
        newName = convertName(first) + " " + convertName(last);
        return newName;
    }

    [...]
}

You can see that you can create however many people you want.

Temporary variables

If you don't need variables, you shouldn't create them. For example:

    String restOfName = name.substring(1);
    return restOfName;

could just be

    return name.substring(1);

Functions

You have a function which removes the first letter from a string, but you do not have one for getting the first letter of a string, but instead write that functionality directly in your convertName function. This seems inconsistent. I would either have a function for both or neither.

I also wouldn't operate on newName directly in capitalizeFirstLetter. None of your other functions (for example nameWithoutFirstLetter) do this, so it is inconsistent and can be confusing.

Also, right now, newName is just a temporary variable, which isn't ideal. You can never be sure what state it has. I would either change the code so it always holds the complete new name (for example Altway Avitchsay), or just get rid of newName completely.


Union based encoding of .csv file into a data table with different types

I don't have time to check all now but I found some things I want to share

If you are using C++17 consider using std::variant instead of the weak union inherited from c. It will probaly also solve youre isue with std::string. See: https://en.cppreference.com/w/cpp/utility/variant

Consider using '\n' instead of std::endl. Im pretty sure you only want a newline and not also a expensive flush of the buffer: https://stackoverflow.com/questions/213907/c-stdendl-vs-n.

Consider using the more safe enum class instead of plain c enum. It is available since C++11.


Table join in DAO and delegating ResultSet reading

I was thinking that I should take away the responsability from any given DAO to know how to load a different object from a joined resultset

Well, I would have made a view which does the selection and the dao would then do the mapping, or rather the disassembly and re-assembly of the resultSet (get all Cards, extract Clients, set the Client to the corresponding Card). So at least it's only one select.

Or you could introduce a new type in a layer 'above' both dao's, which does the mapping.

To your thoughts:

  Increased complexity when writing queries

Yeaaah, that's why people tend to use existing ormappers ;) - you might want to introduce some static methods in your base dao, e.g. all() and join(String table, String condition), so the writing is more fluent and it's better to read... you might want to check the Criterion API/impl of hibernate, it's quite nice to write and read, but that's quite the work, if you really want to implement your own ormapper with a certain amount of sql features.

And: Most important: It's your job to make a class or a method readable. In test cases, I even write a static tomorrow() method, which creates a new Date and adds a day. Of course, you have to write a lot in java, but that must not be the excuse, to make your code not readable.

  Need to always load all the columns from a given table to make it possible for the loadXClass method to be called (can't select specific fields, only everything);

I really think the 'only select data you need' paradigma is quite out dated. The management of the 'choose what columns' thingy, the 'be careful because its not null in the backend but someone might not have loaded that column' and the inconvenient increase of execution plans on your backend - which has to be managed, too - is in my opinion much more expensive compared to just select all (= upgrade the switch or add another cpu to the backend server)

  What if there are more levels to it? Example: the client has an address that is linked to an Address table, so I'd have to include it in the query and join every time so the code doesn't fail, even when not using it.

... I think a view with a dao responsible for that case is the way to go ;-)

To be honest, in ormappers, I do not like the represent the complete erd in java objects approach. Maybe I just didn't get it, but sometimes it gets quite horrible. I mean, you have a Customer, the Customer has a List of Addresses, a List of Orders, a List of PhoneNumbers, a List of Items in the Shopping Card, a List of open bills and and and. And everything is present in the type of hell. And it gets worse, because all those dependencies have other dependencies, too. I found, that an app, at least above a certain size and complexity, is much more maintainable, if "those" problems are taken care of with a certain degree of isolation, even though that means, there is some redundancy, maybe a ClientAddress type and a ClientOrders type, instead of a "one size fits all" approach.

Hope that helps,...


Welcome to Stack Review, the first thing I see in your code is:
class result { ..your code }

Instead of result you should use Result as a classname because as specified in java_naming_conventions : Class names should be nouns, in mixed case with the first letter of each internal word capitalized.
The second thing I see in your code is:
HashSet<String> subs = new HashSet<String>();

Better to declare instead Set<String> subs = new HashSet<String>(); that guarantees more flexibility in case you want to use another implementation of theSet interface.
About performance, briefly you have a for loop where you instantiate a new StringBuilder object at every iteration like below:
for(int i = 0; i < numbers.length; i++){
   StringBuilder sb = new StringBuilder();
   ...other instructions
   sb.append(numbers[j] + " ");
}

There is a debated alternative to this scenario corresponding to instantiate one single StringBuilder object with a fixed capacity and resetting its length at every iteration of the loop with the StringBuilder.setLength method like below:
StringBuilder sb = new StringBuilder(Arrays.toString(numbers).length());
for(int i = 0; i < numbers.length; i++){
   ...other instructions
   sb.setLength(0);
}

For every testcase I set the capacity of the StringBuilder object to
the length of the String representation of the initial array like [1, 2, 3, 4] that is the maximal string length the StringBuilder will contain.
Update after @TorbenPutkonen comment : better to use StringBuilder.setLength(0) at the beginning of the loop to improve readibility of the code, so the reader has a clear vision of the state of the StringBuilder at the beginning and not at the end.


The solution can be made cleaner by re-arranging the order of the arguments and using pointfree style.

let StringOfLengthConstructor<'c> (length : int) (defaultConstructor : string -> 'c) (input : string) =
    match input with
    | x when x <> null && x.Length = length -> Some (defaultConstructor input)
    | _ -> None

type String3 = String3 of string
let String3 = StringOfLengthConstructor 3 String3

However, I don't think that String5 * (String4 option) is a good definition of a zip code. The code should be validating on more than just the string length.


Your function name is not very meaningful in that;

a) there is nothing to say values returned in the array will be objects (since you are just grabbing whatever data is stored for the key), and

b) you are not getting "all" data items at all: in fact you are performing a specific key search.

Perhaps something like recursiveKeySearch() or similar will makes more sense.
I also question why you would include case insensitive search behavior against keys in the first place; that is contrary to the expected behavior of key/property names in JavaScript: the potential need to do case-insensitive key/property names evaluations might suggest bad code in other areas of the application where key/property cases are not being applied consistently.

Don't put in hacks in your code which can make your code perform in unexpected manners.

If you remove that requirement, you have no need to inspect object.keys  anymore and can just directly check if the key exists, greatly simplifying your code.
Your code does not really do anything to validate that the data being passed to it is sensible to work with.

I am guessing that you are really wanting to do is require that data be either an Array specifically, or any other type of object in the Object prototype chain; you have some edge cases you are missing here like typeof(data) === 'object' returning true if data is null.

When those edge cases happen (which could be often if you are iterating over arbitrary objects) I would think you would still need to handle them within your code.
Do you truly wish for you function to be able to search against numeric keys (i.e. for case of Array object)?

This might seem like a little bit odd of an approach based on JavaScript's inability to actually have numeric keys on an object (they will be converted to strings); this really means that if an integer key is passed, you can only meaningfully search in Arrays, whereas if a string key is passed, you can only meaningfully search in Objects: I personally would expect that this function would not be meaningful for searching numeric Array keys, as typically these keys only indicate "order" not some meaningful value for use in lookup.

Thus you might consider handling Arrays differently - just iterating and recursing into them, but not actually evaluating them for matches.

If you need to deep search for numeric key matches, perhaps go with another function altogether.
The design of your recursion is a little odd.

Why the need for an inner function?
Your current code approach stops recursion for case where there is a key match; is this really desired?

I would think expected behavior would be to deep search all values in all keys regardless as to whether the key matched the criteria.

As it stands, you do not recurse into the value for any cases where you have a key match.
You have a few errors in logic around your case sensitivity handling;

In the case sensitive case, the searchTerm variable would have never been populated, thus your key comparison will always fail.

In the case-insensitive logic path, you overwrite your key value, potentially breaking your code, as you are now potentially recursing and going through subsequent iterations with a totally new key value.
This may not actually make a difference with code as written, but I would think you want key to be consistent throughout recursion.

Also, if you truly want to support integer key values, these make no sense with cases sensitivity, and you would in fact significantly alter the key you are searching for by casting it to string when performing toLowerCase() on it.
Per my earlier comment around need for case insensitive search, here is a good example for how you have introduced three potential bugs here just because of added complexity on supporting this use case, and not really implementing in best manner.
You would be better off setting Object.keys(data) to a variable, so you don't have to keep extracting the keys every time you want to act against them.

You can obviously avoid this altogether as you should probably simply just replace

This:

for (var i in Object.keys(data)){

with this:

for (var dataKey in data) {

as there is no reason you need to know the (actually meaningless and technically unpredictable) index number around an array created from the key of the data object.

Object properties in JavaScript do not have a guaranteed order, so it seems inappropriate to try to rely on index positions based on this behavior.

Just work with the property names themselves.

Putting it together

If you looked to refactor based on the considerations mentioned above, you might end up with something like:

function recursiveKeySearch(key, data) {
    // not shown - perhaps validate key as non-zero length string

    // Handle null edge case.
    if(data === null) {
        // nothing to do here
        return [];
    }

    // handle case of non-object, which will not be searched
    if(data !== Object(data)) {
        return [];
    }

    var results = [];

    // Handle array which we just traverse and recurse.
    if(data.constructor === Array) {
        for (var i = 0, len = data.length; i < len; i++) {
            results = results.concat(recursiveKeySearch(key, data[i]));
        }
        return results;
    }

    // We know we have an general object to work with now.
    // Now we need to iterate keys
    for (var dataKey in data) {
        if (key === dataKey) {
            // we found a match
            results.push(data[key]);
        }

        // now recurse into value at key
        results = results.concat(recursiveKeySearch(key, data[dataKey]));
    }

    return results;
}

Or, if you REALLY need to add a case insensitive search:

function recursiveKeySearch(key, data, caseSensitive = true) {
    // not shown - perhaps validate key as non-zero length string
    // not shown - perhaps validate caseSensitive as boolean

    // Handle null edge case.
    if(data === null) {
        // nothing to do here
        return [];
    }

    // handle case of non-object, which will not be searched
    if(data !== Object(data)) {
        return [];
    }

    var results = [];

    // determine 'key' value to be used for comparison
    var comparisonKey = key;
    if (caseSensitive === false) {
        comparisonKey = key.toLowerCase();
    }

    // Handle array which we just traverse and recurse.
    if(data.constructor === Array) {
        for (var i = 0, len = data.length; i < len; i++) {
            results = results.concat(recursiveKeySearch(key, data[i], caseSensitive));
        }
        return results;
    }

    // We know we have an general object to work with now.
    // Now we need to iterate keys
    for (var dataKey in data) {
        var isMatch = false;
        if(caseSensitive === false) {
            isMatch = (comparisonKey === dataKey.toLowerCase());
        } else {
            isMatch = (comparisonKey === dataKey);
        }

        if(isMatch) {
            results.push(data[dataKey]);
        }

        // now recurse into value at key
        results = results.concat(recursiveKeySearch(key, data[dataKey], caseSensitive));
    }

    return results;
}


Nice with some HDL on Code Review. I'll contribute with my opinions. All-in-all, I find the code all well-written.
Opinions not already covered in previous answers

A more standard way of setting count at reset would be (others => '0').

That is, as opposed to hard-coding a bit/hex literal - even if you for some reason hard-code the width as you have done, (others => '0') is more standard in this case.

You might have a good reason for asynchronous reset, but if not, synchronous reset is a better habit.

You often see these asynchronous resets, it is unfortunately a more common habit, since that's what is (or was) most often taught.
See my motivations here: http://www.fpga-dev.com/resets-make-them-synchronous-and-local/

Opinions already covered/partly covered
Somewhat in order of importance (in my subjective opinion).

Define the roll-over behaviour.

The behaviour is actually defined for an unsigned in numeric_std: any carry bits will be ignored so the unsigned will roll-over. However, neither simulators nor synthesis tools should be trusted on following this. (And even less, humans reading the code.) Also; it is good to really think about what behaviour you desire, or is the most stable: roll-over or saturate? I'll take the chance to give two comments on this choice:

For synthesis, roll-over rather than saturation will yield less logic and improved timing. The tool will be able to use a counter macro right-off.
If reaching max count is expected never to happen, add an assertion so a simulation will flag in that case. Then still code the RTL behaviour explicitly to roll-over (less logic, better timing) if there aren't stability reasons to code it to saturate.

Parameterize the width. Put it in a constant or generic.

Generate the clock separately (e.g. clk <= not(clk) after 10 ns;, and make sure to init clk to '1'.

This is more standard and more readable.
Then, when coding your stimuli, do not dead-reckon the time for stimuli assignments, instead, use wait until rising_edge(clk); etc. This makes code more stable, and gives deterministic and proper times for the stimuli changes (not only in regards to time, but also to simulation deltas, which is equally important).

Use entity instantiation

More details and motivation: http://www.fpga-dev.com/leaner-vhdl-with-entity-instantiation/

Simulation performance

There's nothing wrong in coding the RTL of the counter like this, but it could be noted that there is a simulation performance gain possible: Make count a variable, local to the process, do tests and arithmetics on this variable, and in the end of the process drive the variable to a counter signal (defined in the architecture).

Others

Thumbs up for self-checking test benches.


concatenate

There is no need to do the concatenation pairwise np.concatenate([img[:, :, :, i][0] for i in range(img.shape[-1])]) should improve the speed already

numpy.moveaxis

You can use numpy.moveaxis

new_array2 = np.concatenate(np.moveaxis(img[0],(0,1,2), (1,2,0)))

To check whether the result is the same:

assert np.array_equal(new_array, new_array2)

Other improvements

Since you don't use the first axis of the image, you can do np_img = image.data.numpy()[0] so prevent you repeating the [0] in all subsequent code


Finding possible subset combination from the user input

Avoid repetition
Whenever you are repeating yourself twice or more often, you should immediately find some way to get rid of the repetition. You probably already know how to do this. For example, in this case, just add more for-loops: one to calculate the sum, and another to print all the elements once you have found a set of consecutive elements that sums up to the desired value:
for (int i = 0; i < inpth; i++) {
    int sum = 0;

    for (int j = i; j < inpth && sum < ism; j++) {
        sum += inarr[j];

        if (sum == ism) {
            // Now I know that the sum of element i to j equals ism
            for (int k = i; k <= j; k++) {
                 printf("%d ", inarr[k]);
            }

            printf("\n");
        }
    }
}

Create functions to solve smaller problems
Try to split up your problem in smaller problems, and write functions to solve the smaller problems. This allows you to focus on the smaller problems, and the code usually becomes more readable as well. For example:
/* Print out a single subset */
static void print_subset(int subarr[], int len) {
    for (int i = 0; i < len; i++) {
        printf("%d ", subarr[i]);
    }

    printf("\n");
}

/* Check if summing from the start of the subarray will get us the desired value */
static void check_subset(int ism, int subarr[], int len) {
    int sum = 0;

    for (int i = 0; i < len && sum < ism; i++) {
        sum += subarr[i];

        if (sum == ism) {
            print_subset(subarr, i + 1);
        }
    }
}

/* Check all possible subsets of the input array */
int combiset(int ism, int inarr[], int inpth) {
    for (int i = 0; i < inpth; i++) {
        check_subset(ism, inarr + i, inpth - i);
    }
}

In the above, each function only has a single for-loop, which makes them much easier to reason about than the three nested for-loops in the first example I gave.


I can slightly improve your function, like this:

function array_whitelist($array,$whitelist)
// only allow certain keys in an array, in reaction to comment by tim
{
  $list = explode(',',$whitelist);
  return array_intersect_key($array,array_flip($list));
}

function sendMail()
{
  // check form submission
  if (is_array($_POST))
  {
    // initialize
    $to      = 'destination@mail.com';
    $copy    = 'mymail@mail.com';
    $subject = 'Email..';
    $message = '';
    // make all posted input fields into local variables
    $inputs  = array_whitelist($_POST,'email,contactName,comment');
    extract($inputs);
    // filter email address
    $email = filter_var($email,FILTER_SANITIZE_EMAIL);
    // add some fields to message
    if (isset($contactName)) $message .= "Name: $contactName".PHP_EOL;
                        else $message .= "Name: i_".$email.PHP_EOL;
    if (isset($comment)) $message .= "Message: $comment".PHP_EOL;
    // send mails
    mail($to, $subject, $message, "BCC: $copy");
  }
}

It is clear you seem to overdo the conditions, they are not used very effectively. But I think you have removed some essential parts, so this is never going to work.

Perhaps it is time you start to think about a more general email function, not just one that will fit your three forms. What if a fourth form comes along? So more than looking at what I did, think about generalizing your email routines. You could make a class. Seperate the building of the mail message from the sending of the emails. You can find enough examples here (search for: 'PHP Email Class').

Also don't forget the next thing you will want to do is send HTML email messages, and add attachments. That's when it becomes really complex. Email HTML and attachments are just plain tricky. Look for a library that can do these things for you, there are some very good ones out there (https://github.com/PHPMailer/PHPMailer, and the like).


I don't fully understand your problem statement, could you elaborate? I asked about your definition of distance because unless the distance you are interested in is some projection of the euclidian distance, it should be constant regardless which direction you are looking.

In any case, I did your problem manually and found a different result than your program above reports. So here's my implementation with inline comments:

#!/usr/local/bin/python3

from sklearn.neighbors import NearestNeighbors
import numpy as np
import matplotlib.pyplot as plt

class Turbine():

    def __init__(self, x, y):
        self.initialx = x
        self.initialy = y
        self.x = x
        self.y = y

    def rotateBy(self, theta):
        newX = self.x*np.cos(theta)-self.y*np.sin(theta)
        newY = self.x*np.sin(theta)+self.y*np.cos(theta)
        self.x = newX
        self.y = newY

    def point(self):
        return [self.x, self.y]

class Farm():
    def __init__(self, turbineList):
        self.turbineList = turbineList

    def rotateFarmBy(self, theta):
        for turbine in self.turbineList:
            turbine.rotateBy(theta)

    def turbineCoordinates(self):
        return np.array([turbine.point() for turbine in self.turbineList])

    def turbineCount(self):
        return len(self.turbineList)

for theta in [0, np.pi/4., np.pi/3., np.pi/2.]:

    # establish the coordinates,
    # but first test with a small subset and compare with hand calculations
    coordinates = [[0, 0], [0, 10], [0, 20]]
    # coordinates = [[0, 0], [10, 10], [20, 20]]
    # coordinates = [[0, 0], [0, 10], [0, 20], [10, 0], [10, 10], [10, 20], [20, 0], [20, 10], [20, 20]]

    # instantiate the turbines and the container farm
    turbines = [Turbine(coord[0], coord[1]) for coord in coordinates]
    farm = Farm(turbines)
    farm.rotateFarmBy(theta)

    # get the N nearest neighbors, where N in this case is the number of turbines in the farm
    coordinates = farm.turbineCoordinates()
    neighbors = NearestNeighbors(n_neighbors=farm.turbineCount(), algorithm='ball_tree').fit(coordinates)
    distances, indices = neighbors.kneighbors(coordinates)

    # remove any zero distances so that you dont count each turbine twice
    nonzeros = distances[distances > 0]

    print("at {0:0.1f} degrees, the average distance is {1:0.3f}".format(theta*180/np.pi, sum(nonzeros)/farm.turbineCount()))

    # print(indices)
    # print(distances)
    # plt.scatter([c[0] for c in coordinates], [c[1] for c in coordinates])
    # plt.show()


Python classes to grab HTTP response from website entities

Some suggestions:

if __name__ == '__main__': is usually followed by a call to a main method. The main method then parses arguments using for example argparse to inject all the things which should not be hardcoded in the application - definitely passwords, but in your case probably all of the parameters to WebMarketingContent. This makes the code reusable and scriptable.
WebEducationContent is not used anywhere, so it should be removed.
Take advantage of static analysis and formatting using black, flake8 and mypy with a strict configuration to improve the overall quality.
You shouldn't need to get the endpoint before getting the content. web_marketing_content.get_content(123) should itself work out the endpoint and request it.


String permutation using iteration and a filter

Are you sure this is C++?

...because this is almost 100% C. Let's go over some things:

#define is discouraged in modern C++, as is reliance on the C preprocessor in general. Just define your constants with const and (depending on the situation) constexpr.
Don't define raw arrays. Use std::array for fixed size arrays, std::vector for dynamic arrays, or any other standard container class.
Don't use char arrays if you mean strings. C++ offers std::string for general string handling and std::stringstream for string building.
Use standard algorithms. For example, your first for-loop could be replaced with a call to std::fill.

That said, there are

Other Issues

Don't use std::endl. '\n' does the same thing, but doesn't include the unnecessary flush std::endl comes with.
You don't need char_set and int_set. You can generate all lowercase letter by adding their offset in the alphabet to 'a' (i.e. 'a' + 1 == 'b') thanks to the (almost) ubiquitous ASCII encoding. The same is true for digits.
int is not the right type for index variables. Use somethings more appropriate, such as std::size_t, instead.
You should export some of your code to proper functions. Just putting everything into main makes your code hard to read and prone to bugs.
As Cris Luengo pointed out in the comments already, string is not null-terminated, and thus you're causing undefined behavior when writing it to std::cout.
filter is one character longer than it needs to be. Since you never do something with it that would require it to be null terminated (and don't even null terminate the string, just keep an unused character at the end), it suffices to make its length FILTER_LEN.


This kind of parsing by pattern matching is much better done using a regular expression.

import re

libraries = {}
for line in ldd_out.splitlines():
    match = re.match(r'\t(.*) => (.*) \(0x', line)
    if match:
        libraries[match.group(1)] = match.group(2)


Consider taking advantage of existing features that could provide an additional layer of validation.

mainly System.Net.Mail.MailAddress

Also as mentioned in a comment, no need to be creating the regular expression every time the function is called.

static Regex mailExpression = new Regex(@"(.+?(?=<))<(.*@.*?)>");
private static MailAddress getAddress(string address) {
    if (address == null) throw new ArgumentNullException("address");
    if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");

    var plainaddress = address.Trim();
    var groups = mailExpression.Match(plainaddress).Groups;

    return groups.Count == 1
        ? new MailAddress(plainaddress)
        : new MailAddress(groups[2].Value.Trim(), groups[1].Value.Trim());
}

According to reference source code, internally MailAddress will try to parse the address given to it.

This avoids having to roll your own parser as one already exists out of the box that has been tried, tested and is stable.

private static MailAddress getAddress(string address) {
    if (address == null) throw new ArgumentNullException("address");
    if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");

    address = address.Trim();
    return new MailAddress(address);
}

You have the added advantage of having a strongly typed object model to work with that will provide you with usable properties.

The following Unit Test demonstrates the desired behavior.

[TestClass]
public class EmailParserTest {
    [TestMethod]
    public void Should_Parse_EmailAddress_With_Alias() {
        //Arrange
        var expectedAlias = "test my address";
        var expectedAddress = "bla@blub.com";
        string addressWithAlias = "test my address <bla@blub.com>";

        //Act
        var mailAddressWithAlias = getAddress(addressWithAlias);

        //Assert
        mailAddressWithAlias
            .Should()
            .NotBeNull()
            .And.Match<MailAddress>(_ => _.Address == expectedAddress && _.DisplayName == expectedAlias);

    }

    [TestMethod]
    public void Should_Parse_EmailAddress_Without_Alias() {
        //Arrange
        var addressWithoutAlias = "bla@blub.com";

        //Act
        var mailAddressWithoutAlias = getAddress(addressWithoutAlias);

        //Assert
        mailAddressWithoutAlias
            .Should()
            .NotBeNull()
            .And.Match<MailAddress>(_ => _.Address == addressWithoutAlias && _.DisplayName == string.Empty);
        ;
    }

    private static MailAddress getAddress(string address) {
        if (address == null) throw new ArgumentNullException("address");
        if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");

        address = address.Trim();
        return new MailAddress(address);
    }
}