I see a number of things that may help you improve your code.

Don't use leading underscores in names

Anything with a leading underscore is a reserved name in C++ (and in C).  See this question for details.

Don't use void main()

The only function signatures allowed by the C++ standard both require an int return type. See this question for details.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  This sample doesn't explicitly have that, but it's implied by the way the usage code is written.

Fix the bug

Right now, the way the arrays are constructed and the way that they're used are reversed.  Try implementing a state machine in which the number of states does not equal the number of events and you'll quickly see what I mean.

Rethink the interface

Right now, there is very little benefit in using the FSM class.  All of the actual code to implement the finite state machine is done with freestanding functions rather than member functions and requires a pair of enum classes that each must have _ as the last named item.  Further, the event that caused the transition isn't passed to the function -- it's implicit.  All of this makes for a fragile design.  Take the classic example of a vending machine that dispenses items for fifteen cents and that accepts only nickels (5 cents) and dimes (10 cents).  We'd have something like this:

enum class State : char { Empty, Five, Ten, _ };
enum class Event : char { Nickel, Dime,   _ };

// Then the state machine
auto fsm = FSM< State, Event >(State::Empty, {{
    // Nickel       Dime
    { zeroToFive,  zeroToTen },    // Empty
    { fiveToTen,   fiveToFifteen},  // Five
    { tenToFifteen, tenToTwenty}   // Ten
}});

Now we still have to write six standalone functions to implement this!  That's not very convenient.  Worse, the argument each function gets isn't even used, so each function looks something like this:

State fiveToFifteen(State ) {
  std::cout << "got a dime, now have 15 cents\nHere's your item!\n";
  return State::Empty;
}


Good use of Lazy on the connection multiplexer but consider making it a readonly field so you can't accidentally replace it later.

Doing this in the Lazy's factory function is a bit odd in my opinion ThreadPool.SetMinThreads(50, 50);. I'm not sure what options you have for initialization in a Azure Function but you could do worse than use a static constructor on your type.

As for the rest of the function, did you know that there is a ConfigurationOptions type in StackExchange.Redis?

new Lazy<ConnectionMultiplexer>(() =>
    {
        string redisCacheName = System.Environment.GetEnvironmentVariable("rediscache_name", EnvironmentVariableTarget.Process).ToString();
        string redisCachePassword = System.Environment.GetEnvironmentVariable("rediscache_password", EnvironmentVariableTarget.Process).ToString();
        return ConnectionMultiplexer.Connect(new ConfigurationOptions
            {
                AbortOnConnectFail = false,
                Ssl = true,
                // not 100% sure this is exactly right but should be rightish
                EndPoints = { { redisCacheName, 0 } }
                Password = redisCachePassword
            }
        });
};

It's a bit more code but it means you don't have to build the string yourself.

Expression bodied members save some boilerplate:

public static ConnectionMultiplexer Connection => lazyConnection.Value;

C# should never snake_case anything. All methods, regardless of accessibility, should be PascalCase: depersonalise_value should be DepersonaliseValue. See the capitalization conventions on msdn.

I notice that you're not using var at all. Just wanted to double check that you knew it existed. e.g

var depersvalue = $"{account_id}:{field}:{input}";

Naming again: depersvalue should be depersonalisedValue although not clear to me whether it's already depersonalised here or whether it's about to be...

Your final else is redundant, it can be removed.

Remove the parentheses around the returned value - they just add noise.

The connection management looks fine to me - ConnectionMultiplexer is incredibly clever and it's designed to be a long-lived singleton which I think makes it fine to be in a static readonly field.

IDatabase is intentionally very lightweight and you can make as many as you like.

Edit

In response to your edit, I would suggest renaming this from "depersonalised" data to something like a PersonalDataAlias (naming is hard).


Looping through a tree to get branch or leaf

all in all this code does what it needs to do, but czan be improved in some small points

Exception

Instead of the try-except clause, just let the exception bubble up to the caller if he passes a wrong index. returning a string in this case is almost never the correct way to treat it. Now the caller has to check each response he gets and compare it to  "INPUT OUT OF RANGE". Even returning None would be better than this errorstring

list

index = list(index) is useless. tuples can be sliced too, and you can get the length of them

code

The algorithm becomes very simple. It raises a TypeError or IndexError if the caller passes in something illegal, but that's his responsibility

def tree_ref_recursion(tree, index):
    if index:
        return tree_ref_recursion(tree[index[0]], index[1:])
    else:
        return tree

The if index: just checks whether index is a non-empty tuple. There is no need to check for the type of tree. If this is no more tuple, and there is still an index, the caller passed in an illegal tree or index.

recursion

This was a recursive method. Because of the recursion, you need to check the index. You can also use a loop:

def tree_ref(tree, index):
    for idx in index:
        tree = tree[idx]
    return tree


Try a speculative, concurrent, lock free, atomic update until abort condition matches

I'm not sure I like the method's signature:

public static bool TrySpeculativeUpdate(ref int, out int, Func<int, int>, Func<int, bool>)

It's probably just me, but I like pushing ref and out parameters to the end of the parameters list, so I'd write it like this:

public static bool TrySpeculativeUpdate(Func<int, int>, Func<int, bool>, ref int, out int)

I'd use var to ease reading, and FWIW it might be clearer to pass snapshot instead of field to shouldAbort:

public static bool TrySpeculativeUpdate(Func<int, int> update, Func<int, bool> shouldAbort, ref int field, out int result)
{
    var spinWait = new SpinWait();
    while (true)
    {
        var snapshot = field;

        if (shouldAbort(snapshot))
        {
            result = 0;
            return false;
        }
        else
        {
            var calc = update(snapshot);
            if (Interlocked.CompareExchange(ref field, calc, snapshot) == snapshot)
            {
                result = calc;
                return true;
            }
        }

        spinWait.SpinOnce();
    }
}

That's all I could see. The naming looks about right, but I don't write enough multithreaded code to know for a fact whether this code is optimal or not - it does look good though, I don't see how nesting could be reduced, other than by extacting a tiny little specialized function responsible for this part:

if (Interlocked.CompareExchange(ref field, calc, snapshot) == snapshot)
{
    result = calc;
    return true;
}

But that clearly would be overkill IMO.


Proper usage of "using" statement in base64 encode method

SRP

Your method is responsible of to many things, like

reading from a file
writing to a file
converting to base64

So I would suggest to add some more methods

public static bool ConvertToBase64(string inputFile, string outputFile)
{
    try
    {
        byte[] input = System.IO.File.ReadAllBytes(inputFile);
        byte[] base64 = ConvertToBase64(input);
        System.IO.File.WriteAllBytes(outputFile,base64);
        return true;
    }
    catch(Exception)
    {
        return false;
    }
}

private byte[] ConvertToBase64(byte[] input)
{

}

As already stated in the comment, the inner try..catch statements are useless. Your outer try..catch would handle the exceptions in the same way.

About the using statements

If you don't need them, don't use them. As you are reading/writing to/from a file, you can just use the above methods, which internally using a using statement. Always use the right tool to do the job.

If you need to use using statements, you can also stack them like

using (disposable1)
using (disposible2)
{

}

Comments

Don't use comments to describe what you are doing, but why you are doing something. Especially if it is crystal clear what you are doing like

//Buffers for read/write operations
Byte[] outputBuffer = new byte[base64Transform.OutputBlockSize];
Byte[] inputBuffer = new byte[inputFileStream.Length];

this comment is just useless.

Magic numbers

As you need a comment to describe

if (inputOffset % 19 == 0)

you should better use a const for that 19 (but don't ask me how to name it)

If you still want the inner try..catch you can simply use catch(Exception) as there is no need for ex.

Otherwise your code looks good. The naming of your fields is also meaningful.


Find contiguous integers with a given sum

Unused code
 for i, num in enumerate(nums):, the i variable is used in your commented code, but commented code shouldn't exist, so i shouldn't exist either.
To come back on the commented code, I hope you didn't submit your solution with these comments as this is a (in my opinion) very bad practice. What does commented code mean after all? These comments could all be replaced by any debugging tool.
Running time
I believe your solution is actually running on \$O(n*\log(n))\$  time as the nested loop doesn't restart at index 1 every time it runs (which is a good thing). Seems like this is wrong.
Code structure
Usually, in an interview question code structure is pretty important. Right now you have one method that does everything. You should at least have a method that returns your result and one that prints it. Something like :
def main():
    nums = ...
    k = ...
    print(contigSum(nums, k))

def contigSum(nums, k):
    ...

and contigSum should return the result, not print it.


Returning maximum number of consecutive 1s in list of binary numbers

I will mainly focus on style and design, instead of speed and memory usage, as I think that is where you have the most room for improvement. :)

Formatting: Always run cargo fmt (aka rustfmt) before posting your code online! It enforces standard formatting to improve readability.

Function arguments: This is a function that does not need ownership over its argument; you can count the ones in a purely read-only way. So it should take &[i32] instead of Vec<i32>. The idea is that this will be much faster and more memory-efficient if the user has a Vec<i32> but needs to retain ownership over it.

Naming: The name, print_values, is nondescriptive. A good name for this function would be count_consecutive_ones or max_consecutive_ones.
Other than this, the names for your variables look good to me.

Program logic: The implementation is a bit convoluted. A few specifics:

&& index != nums.len() is not necessary, here you know index is used to index nums so it is less than the length.

The logic in the block if index == nums.len() - 1 does not belong inside the loop, but outside. In particular, this fails if the vector is empty, but it is also just clearer to include "final" code at the end.

With this fixed, you shouldn't need index at all.

Local variables (result and count): don't initialize variables at the top of the function, but rather initialize as late as possible, when you need a particular variable.

Here's a better implementation of the main part of the body:
    let mut result = 0;
    let mut count = 0;
    for num in nums.iter() {
        if *num == 1 {
            count += 1;
            if count > result {
                result = count;
            }
        } else {
            count = 0;
        }
    }
    result

Length cap: Regarding the cap you put on the function (panic!ing if nums.len() >= 10000), I like the idea, but I think that you want to be more thoughtful about the way this is designed. Presently, if a user has a vector longer than 10000 to count, they will (1) not be able to use your function, and (2) even worse, probably run into an unexpected crash at runtime that they did not realize would occur.
The rule in Rust is to always make the possibility of errors -- especially panic! runtime errors -- explicit. I would consider the following design:

First, make the magic number 10000 configurable: const LIST_TOO_LARGE: usize = 10000.

Second, provide a version that does not fail -- e.g. max_consecutive_ones(nums: &[i32]) -> i32. If you like, you can print a warning: if nums.len() >= LIST_TOO_LARGE { eprintln!("Warning: list too large! Function may be a bit slow.") }

Third, if you like, provide a version which fails by wrapping around your non-failing version. Basically if nums.len() >= LIST_TOO_LARGE { /* fail */ } else { max_consecutive_ones(nums) }
I would return Result<i32, String> (expose the error explicitly) in this version instead of using panic!().

Another design you could consider: you could define
max_consecutive_ones_throttled(nums, throttle: Option<usize>), where if throttle is specified then you only check the first throttle values. That seems to go along with the idea of providing a cap for efficiency, but now you have the advantage that (1) users of your code can choose a throttle specific to their use case; (2) you don't just fail if the list is too long, but you still at least check the first throttle values.

Answering your question about semicolons after panic: whether you have a semicolon or not doesn't make any difference. It is up to you what style you prefer.


Convert between date/time and time-stamp without using standard library routines

Good that OP is using 4 simplifications: year 2000-2099, no DST, no leap second, no timezone.  So OP knows of code limitations concerning these.  Various elements of this function break without those givens.
Make static unsigned short days a const.
Use a long for your epoch as in:

void epoch_to_date_time(date_time_t* date_time,unsigned long epoch)

as unsigned is only guaranteed to range form 0 to at least 65535 which is insufficient here.
For various functions, consider adding const.  There are pros and cons to this, but may be beneficial in your case:

// unsigned int date_time_to_epoch(date_time_t* date_time)
unsigned int date_time_to_epoch(const date_time_t* date_time)

There exist equation based (non-loop) solutions to the year-day that do not need a table like your  unsigned short days[4][12].  Code then looks more complicated, but is faster.  Please advise if interested.
Most of the magic numbers like 60, 24 are so well-known that constant or macro substitution seems superfluous.  But (365*4+1) may benefit with something like "DaysPer4Years".


There is no magic method in .NET that will know the datatype and magically returns the right parsed value for you. So, creating your own method of parsing and doing manipulation is not a bad thing. This can be improved though.

Use a method:

I prefere to place code that does a certain manipulation or calculation on variables in a separate method/function. This gives me the ability to reuse the code if necessary and maintaining the code is also easier then looking in chunks of code to change just a small bit (like adding a datatype in your case).

switch vs. if/else:

When facing a simple check for a value or condition of a variable, an if/else-statement will certainly do. But when you have a list of options for a variable, it's better to use a swicth-statement. Your code not only looks cleaner, it is cleaner and again, easier to maintain.

This results in following code:

public object ParseValue(string type, string value)
{
    switch(type)
    {
        case "int64" : return Int64.Parse(value);
        case "datetime" : return DateTime.Parse(value);
        case "double" : return Double.Parse(value);
        default: throw new ArgumentException("DataType is not supported");
    }
}

And the usage:

foreach (var row in parametersTable.Rows)
{
    object value;

    if (parametersTable.ContainsColumn("DataType") && !String.IsNullOrEmpty(row["DataType"]))
    {
        var dataType = row["DataType"].ToLower();
        value = ParseValue(dataType, row["Value"]);
    }
    else
    {
        value = row["Value"];
    }

    pfe.AddParameter(row["Name"], value);
}

Another way of using a method is making it return a bool to see if the parsing succeeded and using the out parameter. This results in following method and usage:

public bool TryParseValue(string type, string value, out object parsedValue)
{
    switch(type)
    {
        case "int64" : parsedValue = Int64.Parse(value); return true;
        case "datetime" : parsedValue = DateTime.Parse(value); return true;
        case "double" : parsedValue = Double.Parse(value); return true;
        default: parsedValue = null; return false;
    }
}

foreach (var row in parametersTable.Rows)
{
    object value;

    if (parametersTable.ContainsColumn("DataType") && !String.IsNullOrEmpty(row["DataType"]))
    {
        var dataType = row["DataType"].ToLower();
        if(!TryParseValue(dataType, row["Value"], out value))
        {
            throw new ArgumentException("DataType is not supported");
        }
        //'value' will be correct if the parsing succeeeded
    }
    else
    {
        value = row["Value"];
    }

    pfe.AddParameter(row["Name"], value);
}


An Edit action in ASP.NET MVC, with handling for missing id parameter

I think "BadRequest" is OK for that case. Alternative options are "PageNotFound" or "redirect to index".

Some other points about your code:

0 is usually a valid ID so I would use -1 as default, even if that is not true in your case.
You could check for null or empty first to simplify the code

.

public ActionResult Edit(int id = -1)
{
    if (id < 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    string result = _foodAppService.GetById(id);
    if (string.IsNullOrEmpty(result))
    {
        return RedirectToAction("Index");
    }

    var food = JsonConvert.DeserializeObject<FoodVm>(result);
    return View(food);
}


You could remove all the duplicate lines in the @media queries and provide only the changes in these tags. This is beacause in CSS, the CSS classes that are interpreted by the browser down-most on your page, are the ones prevailing in your final design. All previous defined CSS rules apply unless overwritten. In your case this means that only the font-size changes and should be redefined:

.navButtonText p {
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
    font-weight: 900;
    color: gray;
    font-size: 20px;
    line-height: 20px;
    vertical-align: middle;
    margin-top: 6px;
}
@media only screen and (max-width: 650px) {
    .navButtonText p {
        font-size: 18px;
    }
}
@media only screen and (max-width: 550px) {
    .navButtonText p {
        font-size: 16px;
    }
}
@media only screen and (max-width: 450px) {
    .navButtonText p {
        font-size: 14px;
    }
}
@media only screen and (max-width: 350px) {
    .navButtonText p {
        font-size: 12px;
    }
}

FYI: there is away to prevent this from happening, using the !important tag.


Finding the array indices of three specific headers

Both one-for-loop and getIndexOfColumnTypesolutions represent a naive approach: its main drawback is that for each index you need a dedicated variable like indexOfID or indexOfName.

Since you confirm that the header array can be quite large, this also means that you'll need as many variables for indices as there are items in the array.

Of course, there might be more flexible solutions and I see that the first step is already in the original code, supposing that Constant is an enumeration like this:

public enum Constant {
  ID,
  NAME,
  CATEGORY;
}

The index of each column can be mapped with a dedicated EnumMap:

Map<Constant, Integer> indices = new EnumMap<>(Constant.class);

Now this map can be filled with the indices, using a single loop and they will be accessible by the references to the respective Constants:

private void calculateColumnIndices() {
  for (int i = 0; i < header.length; i++) {
    try {
      Constant column = Constant.valueOf(header[i]);
      indices.put(column, i);
    } catch (IllegalArgumentException ex) {
      // handle the exception depending on what you expect to do if the header contains an invalid column name
      // TODO
    }
  }
}

To access the index:

int index = indices.get(Constant.CATEGORY);

P.S. I'd also suggest to rename Constant to something more meaningful, e.g. ColumnName.


could I get some tips on optimization, etc.

Alignment loss

free_ptr = (char*) free_ptr + size; simply increases the next available allocation to so many bytes later.  This differs from malloc() whose allocations meets all possible system alignment needs.

Either document that bump_alloc() does not provide aligned allocations or change code to do so.

Error messages

I'd expect the error message to go out stderr - yet your call.

// printf("unable to map memory\n");
fprintf(stderr, "Unable to map memory\n");

Missing include

intptr_t is define in <stdint.h>.  Best to include that rather than rely of a hidden inclusion.

Good type math

The below avoids int overflow.

#define KB(size) ((size_t) size * 1024)

Better code would () each macro parameter.

#define KB(size) ((size_t) (size) * 1024)

Yet I'd recommend rather than type-casting, which may narrow the math, allow gentle widening.  The below multiplication will occur with the wider of size_t and the type of size.

#define KB(size) ((size_t) 1024 * (size))

Unneeded cast, simplify

Casting not needed going from void * to an object pointer.  Size to the de-referenced type.  Easier to code right, review and maintain.

// int* x = (int*) bump_alloc(sizeof(int));
int* x = bump_alloc(sizeof *x);


Car Showroom Database: Taking user inputs and manipulating arrays

first, using Parse for user input it would be a bad practice, as you're parsing the input without any validation. thus, you'll need to use TryParse instead, which will validate the input to the specific type, if it's valid input that would be acceptable by the targeted type, then it would return true and output the parsed value.

Example direct parsing :

// this would pass the value without validation
int amountofcars = int.Parse(Console.ReadLine());

Example of validated parsing :

// this validates the input value, then process :
bool isValid = int.TryParse(Console.ReadLine(), out int amountofcars);
// isValid == true, then it's an interger.

if(isValid) // if it's a valid integer
{
    // process the amountofcars
}

you'll find a lot of System types that already has TryParse like int.TryParse, double.TryParse and so on. You should always use it when parsing user inputs. You can still use Parse but use it whenever you see that you're diffidently sure a hundred percent that the value will always be compatible with the targeted type.

Since you have cars, carprice and models arrays, I assume you need one class model, that would hold car information. something like :

public class Car
{
    public double Price { get; set; }

    public string Model { get; set; }
}

now you can initiate a car array :

Car[] cars = new Car[amountofcars];

then inside your loop you can simply do this :

for(int i = 0; i < amountofcars; i++)
{
    Console.WriteLine("List the model of car #{0}", i + 1);
    string carmodels = Console.ReadLine();
    cars[i].Model = carmodels;
    Console.WriteLine("Input car price");
    double price = double.Parse(Console.ReadLine()); // use TryParse instead;
    cars[i].Price = price;
}

doing this, would let you have and process one array which  hold the car information in each element.

I suggest you use List instead of array. It would make things easier for you to process like adding and removing and also you don't need to specify its length. Also, it has more functionality than a system array.

Here is a modified version with some comments that would help you throughout the code, if you feel you need a clarification just let me know.

public class Car
{
    public double Price { get; set; }

    public string Model { get; set; }
}

public static class Program
{
    public static void Main(string[] args)
    {
        List<Car> cars = new List<Car>();

        int amountofcars = 0;

        do
        {
            // this should forced the user to input a valid integer
            // it won't break this loop until it gets a valid integer.
            Console.WriteLine("How many cars are in the workshop?");
        }
        while (int.TryParse(Console.ReadLine(), out amountofcars) == false);

        // now we can process
        for (int i = 0; i < amountofcars; i++)
        {

            Console.WriteLine("List the model of car #{0}", i + 1);
            // since it's string, there is no need for type validation, unless you need to include business validation.
            string carmodels = Console.ReadLine();

            // repeat the same validation :
            double price = 0;
            do
            {
                // this should forced the user to input a valid integer
                // it won't break this loop until it gets a valid integer.
                Console.WriteLine("Input car price");
            }
            while (double.TryParse(Console.ReadLine(), out price) == false);

            cars.Add(new Car { Model = carmodels, Price = price });
        }

        Console.WriteLine("Data stored");
        Console.WriteLine();
        Console.WriteLine("What do you want to do next?");
        Console.WriteLine("Type \"Search\" to start a new search or any key to leave program");
        string responce = Console.ReadLine();

        while (true)
        {
            //using StringComparison.InvariantCultureIgnoreCase
            // this would make it case-insensitive
            if (responce.Equals("Search", StringComparison.InvariantCultureIgnoreCase))
            {
                Car found = null;

                Console.WriteLine("What car did you want to search for?");

                string modelsearch = Console.ReadLine();

                foreach (var car in cars)
                {
                    if (car.Model.Equals(modelsearch, StringComparison.InvariantCultureIgnoreCase))
                    {
                        found = car;
                    }
                }

                if (found != null)
                {
                    Console.WriteLine($"{found.Model} {found.Price}");
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine($"Model {modelsearch} not found.");
                    Console.WriteLine();
                }

                Console.WriteLine("What do you want to do next?");
                Console.WriteLine("Search again? \"Y\" or any key to exit");

                // this line would break if it's not a char.
                //searchagain = char.Parse(Console.ReadLine());

                var whatnext = Console.ReadLine();

                if (whatnext.Equals("Y", StringComparison.InvariantCultureIgnoreCase) == false)
                {
                    // if user input anything else will break this loop.
                    break;
                }
            }
            else
            {
                // in case if pressed any key, it'll break this loop.
                break;
            }

        }

    }
}


The use of Boolean for status as a kind of 'ternary type' (true, false, null) feels a little misleading, even if it's documented in the Javadoc.

I would replace it with either three static final int constants or an enum.


Using a loop isn't inherently wrong, the problem you're anticipating though is right -- you won't have a way of comparing and referencing the buttons since they all become anonymous with your current approach.

Instead, use an array of JButton and simply use the iterator of the loop to instantiate at that location which you can later utilize as an index to reference a specific JButton.

JButton[0] board = new JButton[9];
    for (int i = 0; i < board.length; i++) {
        board[i] = new JButton("");
    }

On the topic of anonymity, as of Java 8 rather than using anonymous inner classes for Action Events you can use Lambda Expressions.

So, you can replace this chunk of code:

 btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

With:

btn.addActionListener(e -> {

Of course, you close the bracket. This also has the benefit of no longer requiring you to import ActionEvent and ActionListener directly.


Algorithm of PairAnagrams()

You are calling

var sortedWord1 = item.ToArray();
Array.Sort(sortedWord1);

inside the inner loop, but item won't change there.

One time you are using Array.Sort(sortedWord1); and two lines below Array.Sort<char>(sortedWord2); Be consistent in your style.

This

for (i = 0; i < sortedWord2.Length; i++)
{
    if (sortedWord2[i] != sortedWord1[i])
    {
        break;
    }
}
if (i == sortedWord1.Length)
{
    dictionary.Add(item, item2);
}

can be replaced by

if (sortedWord1.SequenceEqual(sortedWord2))
{
    dictionary.Add(item, item2);
}

By using .Where() on the wordList at the for each you can omit the check for length and equal.

By using the .OrderBy() on the chars of the words, there won't be a need to call .ToArray() and Array.Sort().

This reduces the code to

Dictionary<string, string> PairAnagrams(List<string> words)
{
    Dictionary<string, string> pairedAnagrams = new Dictionary<string, string>();
    foreach (var word in words)
    {
        if (pairedAnagrams.ContainsValue(word))
        {
            continue;
        }

        var sortedWord1 = word.OrderBy(c => c);
        int wordLength = word.Length;
        foreach (var word2 in words.Where(w => w.Length == wordLength && !word.Equals(w)))
        {
            if (sortedWord1.SequenceEqual(word2.OrderBy(c => c)))
            {
                pairedAnagrams.Add(word, word2);
            }
        }
    }
    return pairedAnagrams;
}

Constructor

The constructor of an object should be used only for constructing the object. You are misusing it to start the action.

Naming

variable names should be correctly spelled. anagarms vs anagrams
parameters should't be pre/post fixed by their types. List<string> wordsList-> List<string> words

General

no need for using System.Security.Cryptography


Extract specified field value from filename using positional indexing

This task is nearly equivalent to another recent question.  My advice is that string analysis is usually best done using regular expressions.

import os
import re

def get_field_str(file_path, field):
    """
    Get the string value of field stored in file_path

    >>> get_field_str('/path/to/file/Z998-5.asdf', 'session')
    '5'
    """
    pattern = re.compile('(?P<place>.)(?P<year>.{3})-(?P<session>.)\.')
    return pattern.search(os.path.basename(file_path)).group(field)

The regex can validate the filename as it works.  Feel free to adjust it to match your expectations.


To answer another question I provided some helpful information about optimization in vba here, VBA syntax that compiles sub data into master sheet.
This maybe help you to skip the blank rows (You did not clarify your question but based on the data you provided I think that would be your problem) and find the actual last row used. It is in reference to this post. Here's the code:
Dim srcData As Range, rng As Range
Dim rowNum As Long, lastRow As Long
Dim wsh As Worksheet

Sub GSFC_V4()
 Set wsh = Worksheets(2)

 wsh.Activate
 Set srcData = Range("K:M")
 Set rng = Range("K4")

 With wsh
  If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
     lastrow = srcData.Find(What:="*", _
                  After:=rng, _
                  Lookat:=xlPart, _
                  LookIn:=xlFormulas, _
                  SearchOrder:=xlByRows, _
                  SearchDirection:=xlPrevious, _
                  MatchCase:=False).Row
 Else
     lastrow = 1
 End If

     With .Cells(4, "H").Resize(lastRow - 4 + 1, 1)
         .FormulaR1C1 = "=rc[3]&rc[4]&rc[5]"
         .Value = .Value2
     End With
 End With

End Sub

This is what I am using to optimize my macros. I call OptimizeVBA True at the beginning of each macro and at the end call OptimizeVBA False to set everything back to default. It increases the performance remarkably.
Sub OptimizeVBA(isOn As Boolean)

  Application.Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic)
  Application.EnableEvents = Not (isOn)
  Application.ScreenUpdating = Not (isOn)
  Application.StatusBar = Not (isOn)

End Sub

You need to be careful of how you refer to ranges to avoid getting errors.


Java 8 streams - restructure entity classes for UI Grid

Type inference for generic instance creation
You can rely on type inference for generic instance creation when declaring unifiedHoldings:
List<Map<DataSource, List<Holding>>> unifiedHoldings = new ArrayList<>();

Mutable operations on collections
List<Holding> aSourceHoldings = holdingService.getHoldings(date);
List<Holding> unMatchedHoldings = /* ... */ ;
aSourceHoldings.removeAll(unMatchedHoldings);
List<Holding> toBeMatchedHoldings = holdingRepository.getHoldings(date);
toBeMatchedHoldings.addAll(aSourceHoldings);

Calling mutable operations such as removeAll(Collection) and addAll(Collection) may throw UnsupportedOperationException if the underlying List does not return a mutable implementation. As such, in these scenarios, you should be creating your own List given the resulting elements, and then do the necessary removal/addition calls on the new instance.
Account and Product usage
Interestingly, it looks like Account and Product themselves aren't used in the processing, after kind of using them as 'keys' for grouping. The nested Maps looks too peculiar, which brings us to the next point...
Grouping your Holding objects

I currently break up the list of holdings into several lists where each list contains only holdings with the same product id and account. Also, I key each list by data source.
(emphasis mine)

This looks like a good use case for a supplementary 'key' class that will allow us to grouping Holding objects with the same account, product and data source. For example:
private static final class HoldingKey {
    private final Account account;
    private final Product product;

    HoldingKey(Account account, Product product) {
        this.account = Objects.requireNonNull(account);
        this.product = Objects.requireNonNull(product);
    }

    Account getAccount() {
        return account;
    }

    Product getProduct() {
        return product;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof HoldingKey
                && getAccount().equals(((HoldingKey) o).getAccount())
                && getProduct().equals(((HoldingKey) o).getProduct());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getAccount(), getProduct());
    }

    static HoldingKey toKey(Holding holding) {
        return new HoldingKey(holding.getAccount(),
                                holding.getDataSourceProduct().getProduct());
    }
}

Using the method reference HoldingKey::toKey to group Holding objects by, with a dash of Stream.concat(Stream, Stream) to combine two streams together, we can combine the processing on both the repository and service results with relative ease:
    Stream<Holding> fromRepository = holdingRepository.getHoldings(date).stream();
    Stream<Holding> fromService = holdingService.getHoldings(date).stream()
            .filter(h -> h.getDataSourceProduct().getProduct().getId() != null);
    Map<HoldingKey, List<Holding>> map = Stream.concat(fromRepository, fromService)
            .collect(Collectors.groupingBy(HoldingKey::toKey));

This simplifies the nested Maps we have by flattening that multi-key structure into a single HoldingKey object. Achieving what you require is a simple continuation on map's entrySet(), with a mapping function to turn List<Holding> into your required Map<DataSource, Holding>:
private static final Function<List<Holding>, Map<DataSource, Holding>> MAPPER =
        x -> x.stream().collect(Collectors.toMap(
                y -> y.getDataSourceProduct().getDataSource(), Function.identity()));

private static List<Map<DataSource, List<Holding>>> getUnifiedHoldings(Date date) {
    Stream<Holding> fromRepository = holdingRepository.getHoldings(date).stream();
    Stream<Holding> fromService = holdingService.getHoldings(date).stream()
            .filter(h -> h.getDataSourceProduct().getProduct().getId() != null);
    return Stream.concat(fromRepository, fromService)
            .collect(Collectors.groupingBy(HoldingKey::toKey))
            .entrySet()
            .stream()
            .map(MAPPER.compose(Map.Entry::getValue))
            .collect(Collectors.toList());
}

Here, we compose() our MAPPER function with the 'extractor' function Map.Entry::getValue to derive our resulting list elements.


Interface for unit of work pattern and repository pattern

I think your interfaces are mostly well-defined, with a couple exceptions:

I don't think Load, Attach and Detach should be members of IUnitOfWork, but rather IRepository.  It seems that the repository that manages objects of type T would be the best place to place methods that acts on that type.

The UnitOfWork property on IRepository does not belong there. Things that modify one repository shouldn't be allowed to go and get other repositories to modify on their own.  If they need them, pass them in explicitly.  Otherwise, you're hiding from potential callers the fact that your implementation actually depends on more than just the one repository, and hiding your dependencies like you're ashamed of them is one of my least favorite code smells.


I'll make no comment on the use of C-style <stdio.h>, since that's likely an artefact of the surrounding code, rather than something you'd have written yourself.

A missing header and a typo/oversight

The header required for std::make_pair is <utility>.  Your implementation may have defined it as a side-effect of including <map>, but it's not portable to rely on that.

size_t pos ought to be std::size_t pos.

Test program

I managed to re-create some input from your sample output:

int main()
{
    static auto const messages = {
        "<3>CTRL-EVENT-SCAN-STARTED ",
        "<3>CTRL-EVENT-BSS-ADDED 0 00:00:00:00:00:00",
        "<3>CTRL-EVENT-BSS-ADDED 1 00:00:00:00:00:01",
        "<3>CTRL-EVENT-BSS-ADDED 2 00:00:00:00:00:02",
        "<3>CTRL-EVENT-SCAN-RESULTS ",
        "<3>WPS-AP-AVAILABLE ",
        "<3>Trying to associate with 00:00:00:00:00:00 (SSID='my_ssid' freq=5745 MHz)",
        "<3>Associated with 00:00:00:00:00:00",
        "<3>CTRL-EVENT-SUBNET-STATUS-UPDATE status=0",
        "<3>WPA: Key negotiation completed with 00:00:00:00:00:00 [PTK=CCMP GTK=TKIP]",
        "<3>CTRL-EVENT-CONNECTED - Connection to 00:00:00:00:00:00 completed [id=1 id_str=]",
    };

    wpa_monitor monitor;

    for (auto m: messages)
        monitor.handle_wpa_message(m);
}

Naming

I avoid names that include their type, as it can be confusing if you later change that type.  So I'd call the map mac_to_ssid instead.  That also has the benefit of being shorter, so easy to type and to read.

Extensibility

You'll find that a single large method gets harder to navigate as it gets bigger.  As hinted in another answer, it makes sense to delegate to a bunch of simple methods that each handle a single case.  You could iterate through a vector, but I'd stick to something simple like this:

class wpa_monitor
{
public:
    bool handle_wpa_message(const std::string& message);

private:
    std::map<std::string, std::string> mac_ssid_association_map = {};

    bool handle_associate(const std::string& message);
    bool handle_connected(const std::string& message);
    bool handle_scanresult(const std::string& message);
};

bool wpa_monitor::handle_wpa_message(const std::string& message)
{
    DEBUG_PRINT("WPA event: '%s'\n", message.c_str());

    return handle_associate(message)
        || handle_connected(message)
        || handle_scanresult(message);
}

Now we can look at each matcher in turn.

Refactor some common code

We repeatedly search for a string and take an interest in its end, like this:

auto pos = message.find("Trying to associate with ");
if (pos == std::string::npos)
    return false;

std::string mac_substring = message.substr(pos + sizeof "Trying to associate with " - 1);

Obviously there's scope for error if we don't keep the two copies of the string in agreement.  Instead, we can write a small function to do this:

static std::size_t find_end(const std::string& s, const std::string& substr)
{
    auto pos = s.find(substr);
    if (pos != std::string::npos)
        pos += substr.size();
    return pos;
}

That makes the caller simpler and more robust:

auto pos = find_end(message, "Trying to associate with ");
if (pos == std::string::npos)
    return false;

auto const mac_substring = message.substr(pos);

Actually, that's not really the MAC substring, as it continues to the end of the string.  We really want another helper, accepting a termination character:

static std::string find_in_delimiters(const std::string& s,
                                      const std::string& open, const char close)
{
    auto start = s.find(open);
    if (start == std::string::npos)
        return {};
    start += open.size();

    auto end = s.find(close, start);
    if (end == std::string::npos)
        return {};

    return s.substr(start, end-start);
}

And we simplify the callers even more:

    auto mac_addr = find_in_delimiters(message, "Trying to associate with ", ' ');
    if (mac_addr.empty()) {
        return false;
    }

More on make_pair()

I get a failure to compile, as GCC seems to want rvalue references for make_pair<string,string>().  I could resolve that with a std::move() like this:

    mac_ssid_association_map.insert( std::make_pair< std::string, std::string >( std::move(mac_addr), std::move(ssid) ) );

However, we can let template type deduction do its thing:

    mac_ssid_association_map.insert(std::make_pair(std::move(mac_addr), std::move(ssid)));

Or even just:

    mac_ssid_association_map.insert({std::move(mac_addr), std::move(ssid)});

Use auto instead of exact iterator types

Here's a place where changing the map type could be a maintenance headache:

    std::map< std::string, std::string >::iterator it = mac_ssid_association_map.find( mac_addr );

We can use auto, which also makes it more readable:

    auto it = mac_ssid_association_map.find(mac_addr);

My version

#include <cstdio>
#include <string>
#include <map>
#include <utility>

#define DEBUG_PRINT std::printf

class wpa_monitor
{
public:
    bool handle_wpa_message(const std::string& message);

private:
    std::map<std::string, std::string> mac_to_ssid = {};

    bool handle_associate(const std::string& message);
    bool handle_connected(const std::string& message);
    bool handle_scanresult(const std::string& message);
};

// Helper method - returns substring of s contained between
// open and close, or empty if not matched
static std::string find_in_delimiters(const std::string& s,
                                      const std::string& open, const char close)
{
    auto start = s.find(open);
    if (start == s.npos)
        return {};
    start += open.size();

    auto end = s.find(close, start);
    if (end == s.npos)
        return {};

    return s.substr(start, end-start);
}

// Handlers for specific message types

bool wpa_monitor::handle_associate(const std::string& message)
{
    auto mac_addr = find_in_delimiters(message, "Trying to associate with ", ' ');
    if (mac_addr.empty())
        return false;

    auto ssid = find_in_delimiters(message, "SSID='", '\'');
    if (ssid.empty())
        return false;

    DEBUG_PRINT("Associating mac_address '%s' with ssid '%s'\n", mac_addr.c_str(), ssid.c_str());
    mac_to_ssid.insert({std::move(mac_addr), std::move(ssid)});
    return true;
}

bool wpa_monitor::handle_connected(const std::string& message)
{
    auto mac_addr = find_in_delimiters(message, "CTRL-EVENT-CONNECTED - Connection to ", ' ');
    if (mac_addr.empty())
        return false;

    auto it = mac_to_ssid.find(mac_addr);
    if (it != mac_to_ssid.end()) {
        DEBUG_PRINT("We are now connected to ssid '%s'\n", it->second.c_str());
    }

    return true;
}

bool wpa_monitor::handle_scanresult(const std::string& message)
{
    auto pos = message.find("CTRL-EVENT-SCAN-RESULTS");
    if (pos == message.npos)
        return false;

    //scan results ready
    DEBUG_PRINT("Scan results are ready\n");
    return true;
}

// Test program

int main()
{
    static auto const messages = {
        "<3>CTRL-EVENT-SCAN-STARTED ",
        "<3>CTRL-EVENT-BSS-ADDED 0 00:00:00:00:00:00",
        "<3>CTRL-EVENT-BSS-ADDED 1 00:00:00:00:00:01",
        "<3>CTRL-EVENT-BSS-ADDED 2 00:00:00:00:00:02",
        "<3>CTRL-EVENT-SCAN-RESULTS ",
        "<3>WPS-AP-AVAILABLE ",
        "<3>Trying to associate with 00:00:00:00:00:00 (SSID='my_ssid' freq=5745 MHz)",
        "<3>Associated with 00:00:00:00:00:00",
        "<3>CTRL-EVENT-SUBNET-STATUS-UPDATE status=0",
        "<3>WPA: Key negotiation completed with 00:00:00:00:00:00 [PTK=CCMP GTK=TKIP]",
        "<3>CTRL-EVENT-CONNECTED - Connection to 00:00:00:00:00:00 completed [id=1 id_str=]",
    };

    wpa_monitor monitor;

    for (auto m: messages)
        monitor.handle_wpa_message(m);
}


Performance is too low, online compiler wants a faster way to find all possible combinations of k numbers out of 1...n

Preface:

  if you can, don't use advanced syntax

I understand why you say this, but do not shy away from strange looking syntax.  When you encounter something you cannot read, take the time to lookup what the syntax does (even experienced developers do this).  The weird looking syntax may be doing useful stuff.  And after you understand what's going on, the syntax usually doesn't look weird anymore.

Another algorithm:

First off, for a beginner, this is a great start.  It's very simple code which is good.

If you want faster code, the first thing to do is make sure your general approach is reasonable or better yet optimal.  Your algorithm generates all possible sets of length K with elements from {1,2,...N} and then checks if the sets are sorted.  Note that I have used N for the size of the input set and K for the size of the combinations -- this is a convention I have seen in many places but is different from your code.

There are $$K^N$$ possible sets of length K from a set of N objects.  For the same set of N objects, there are $$\frac{N!}{K!(N-K)!}$$ combinations.  Since the combinations are a subset of the possible sets, they are a smaller set and in many cases they are a much smaller set.  Interestingly there are some non integer solutions for K^N < (N choose K) e.g. K = 0.5 and N = 1.5. maybe someone else can shed some light on that.  But they key takeaway is that only generating combinations will be a lot faster.

How can you only generate combinations?  There's more than one way to do this, but I will describe one way.

Consider the n=5, k=3 example.  The set of numbers to maybe print is 1,2,3,4,5, and the set of numbers to definitely print is {} (empty set).  I'll simplify this as ({}, {1,2,3,4,5}).  Some of the combinations have 1 and some don't. So we now have to consider both the possibilities ({1},{2,3,4,5}) and ({}, {2,3,4,5}).  We repeat this recursively, and when we have a set of things of size el_maxim (or, by convention, k), we print.  In psuedo-code:

void recurse(int indexK, int indexN) {
    if (indexK == K) {
        print(result);
        return;
    }

    // "if there more slots to fill than numbers to fill them"
    // could also say `if (indexN == N)` ... correct but slower
    if (N - indexN < K - indexK) {
        return;
    }

    result[indexK] = indexN;

    recurse(indexK + 1, indexN + 1);
    recurse(indexK, indexN + 1);
}

I encourage you to try getting this function to compile and then benchmarking to make sure you see the speedup you would expect.  You'll have to try a few different values of N and K.  For some inputs <10, the improved algorithm should run 1000s of times faster!

Review of your code:

Since my main advice is to use a better algorithm, I haven't given any specific comments on your code.  I'll do that here:

Your program should be based around a function that can generate combinations.  The function should take N and K as input, and it should return all the combinations.  Something like this:

/// This function generates all combinations of integers {1,2,...,N}
/// @param N    the size of the set
/// @param K    the size of the combinations
ResultType generateCombinations(int N, int K) { ... }

Then your main function should call generateCombinations.  This has several advantages over your method:

The compiler will make sure you set all the inputs.  In your version, if you forget to set a global variable, then you'll get the wrong answer.
You have a convenient place to put a big comment about what the function does.  The comment I've placed above is in Doxygen's format so you can generate documentation from your comments.  It also looks pretty good in my opinion.
You can easily call the function in several places.
You don't have to worry about name collisions.
The compiler can optimize arguments better than global variables.  In general, compilers are really good with functional code and not so good with code that uses lots of memory.
I could go on but I think you get the point.

Separate printing the combinations from generating the combinations.  You've sort of done that with the display function, but not really since anyone who calls bkt is forced to print the result.  There are two main ways to do this.  The first way is to return a big data structure, and then print it:

std::vector<std::vector<int>> generateCombinations(int N, int K) { ... }

for (auto& vec : genCombinations(5, 3)) { print(vec); }

This way is pretty easy/simple.  The downside is it uses a lot of memory.

The second way is to accept an argument that says what to do with each result:

void genCombinations(int N, int K, std::function<void(vector<int>&)> func) { ... }

genCombinations(5, 3, [](auto& vec) { print(vec); });

This is probably harder to read for many people, but it saves a large amount of memory in this case!

Your names are a little weird.  el_maxim instead of maximum_element or N as dictated by convention.  n instead of num_elements or K per the convention.  Also bkt and okay seem like they were chosen because they are short rather than because they are good descriptions of what they do.

okay();
if (okay() == 1)

Is this intended?

P.S.

I encourage you to rewrite and post another code review using a faster algorithm!  You may get more comments on your code rather than on your approach.


Dealing with DB Through EF within Winforms

this.metroGrid1.Columns["Id"].Visible = false;
    this.metroGrid1.Columns["ExamId"].Visible = false;
    this.metroGrid1.Columns["Comments"].Visible = false;
    this.metroGrid1.Columns["CreationDate"].Visible = false;
    this.metroGrid1.Columns["LastModified"].Visible = false;
    this.metroGrid1.Columns["PatientState"].Visible = false;

These lines have a lot of repetition. It would be better to create an array of the column names, and then loop over the array and set each one.

    var patients = db.Patients;

What's the purpose of having a temporary variable here? You're not even declaring its type.


BinaryChar is a class with one method. You continually change the state of the object so you can call the method with the right "argument". That's not what classes are for, but module functions or class methods. I rewrote the code twice: once using a class in the right way and once using a module function (or class method).

with a class

class BinaryChar
  def initialize(string)
    @binary = string.scan(/.{1,8}/).map do |character|
      character.to_i(2).chr
    end
  end

  def to_s
    @binary.join
  end
end

loop do
  print "Enter string: "
  bc = BinaryChar.new(gets)

  puts bc # to_s is called automatically by puts.
end

with a module function

module Binary
  def self.to_binary(string)
    binary = string.scan(/.{1,8}/).map do |character|
      character.to_i(2).chr
    end

    binary.join
  end
end

loop do
  print "Enter string: "

  puts Binary.to_binary
end

A couple of minor nitpicks:

In ruby the convention is to use snake_case for anything but ClassNames and CONSTANTS.
When you get input from stdin (gets) a newline is appended to it ("\n"). In most cases you want to strip the newline of using String#chomp.
Accessor methods can look just like variable assignments: bc.binary_string = speak.
Conversion methods are usually named to_<something>. To convert to a String, for example, most classes implement a to_s method.


You can refine your algorithm by getting rid of all these counters and while loops and replace them with a for loop such as this:

for (int i = 0; i < parquet.size(); i++)
    parquet[i] = ... // do whatever

Similarly, you can re-write the summing algorithm as:

for (int i = 0; i < parquet.size(); i++){
    for (int j = 0; j < parquet[i].size(); j++) {
      if (parquet[i][j] == '*') && (parquet[i][j + 1] == '*') {
          j++;
          sum += a;
      else
          sum += b;
      }
    }
}

That said, I notice you're naming your counters as "iter" (which I assume is a short for iterator). Are you trying to access your vector in a typical STL manner (i.e.: using iterators?). If that was your intent, you can try something like:

vector<string>::iterator myIterator;
for (myIterator = parquet.begin(); myIterator != parquet.end(); myIterator++)
// Do whatever

That is, of course, assuming your procedure works as intended. If not, please state otherwise.


I would add rvalue reference support with moving of temporaries.

<op> seems to be too low precidence to be practical - you end up having to (bracket) everything (as demonstrated above).  % at least binds tightly.

I do like a <op>= b.  Better than my a +op= b.

Forwarding operator() from the operator to the function lets you forget the function behind the operator entirely:  in(3, vec) -- very Haskell.

N ary infix operators that defer application of f allow s <append> s2 <append> s3 to run as efficiently as possible.  But doing that cleanly might be hard.

Not sure what inline is intended to do above.

For an interesting test case, implement (std::future<T> %then% [](T)->U)->std::future<U> (where that lambda is a placeholder for a functor)

Block some copy and move ctors to prevent persistance, and friend the approriate operators.

As noted, I allowed arbitrary binary operators (chosen when you make_infix) to bracket the named operator: the precidence of the resulting named operator exactly matches the bracketing operators.  So +append+ has precidence of + and *in* has precidence of *.  Of the 3 first use cases (lin alg, container append, then) for two of them the named operators where variants of existing operators, and matching their precidence seemed useful.


Sum of all the primes less than or equal to N

Sieve of Eratosthenes

The first possibility would be to implement the Sieve of Eratosthenes.  It's one of the more efficient ways to find all primes between 1 and N.  But there are other things we can do with your existing algorithm.

Initialize with 2

    long sum = 0;
    long primes[] = new long[((int)max/2)+1];
    int index = 0;

But you know the first prime number (at least I hope you do).  So try this

    if (max < 2) {
        return 0;
    }
    long sum = 2;

    long primes[] = new long[((int)max/2)+1];
    primes[0] = 2;
    int index = 1;

This helps a little now, but it helps a lot later since we know that 2 is the only even prime.  Since all even numbers are divisible by 2 and all primes are only divisible by themselves and 1, 2 is the only possible even prime.

Check fewer numbers

    for(long counter = 2; counter <= max; counter++){

This checks every number from 2 to max, but we can trivially reduce this to every odd number from 3 to max if we initialize the array with 2.

    for (long counter = 3; counter <= max; counter += 2) {

I also added some additional spaces, as I find they make it easier to read the code.

No evens or divisible by three

And we can actually do even better.  Every third odd number is divisible by three.  So

    if (max < 2) {
        return 0;
    } else if (max == 2) {
        return 2;
    }
    long sum = 5;

    long primes[] = new long[((int)max/2)+1];
    primes[0] = 2;
    primes[1] = 3;
    int index = 2;

    int increment = 4;
    for (long counter = 5; counter <= max; counter += increment) {
         increment = 6 - increment;

Now the increment varies between 2 and 4.  So we have 5, 7, 11 (skipping 9), 13, 17...  So we skip every number that is divisible by three.  And you can never add an even number to an odd number and get an even number, so we skip all the evens as well.

Don't use a generic isPrime

Your code uses a generic isPrime method that will work regardless of the caller.  You don't need to do that.

    if(num == 2 || num == 3){
        return true;
    }

You can skip this, as you never pass 2 or 3 to this method.

    //System.out.println(Arrays.toString(primes));

This is debugging code and shouldn't be sent to review.

    long primesCount = primes.length;
    for(int i = 0; i < primesCount; i++){
        if(primes[i] !=0 && num % primes[i] == 0){
            return false;
        }
    }

You can simplify this to just

    for (long prime : primes) {
        if (prime == 0) {
            return true;
        }

        if (num % prime == 0) {
            return false;
        }
    }

Now it will check that num is not divisible by any number in the primes array.  Once it reaches the first 0, that means that it is done processing and can return true immediately.

Note that if primes were a List rather than an array, you wouldn't need to check for 0, as the List would only have prime values in it.  Perhaps the performance improvement from not checking for 0 values would outweigh the increased overhead of the List.

    long range = (long) Math.sqrt((double)num);
    if(primesCount > 0 && primes[primes.length-1] < range)
    {
        for(long counter = 2; counter <= range; counter++){
            if(num % counter == 0){
                return false;
            }
        }
    }

You don't need this block of code.  You already checked that it's not divisible by any of the primes less than it.  You don't need to check it again with both primes and non-primes.

It's possible that you could save some time with the following optimizations:

    long range = (long) Math.sqrt((double)num);
    for (long i = 2; primes[i] <= range; i++) {
        if (num % primes[i] == 0) {
            return false;
        }
    }

    return true;

This relies on there always being at least one prime between range and num in the primes array.  You might have to preload 5 into the primes array to make this work, as this skips past 3 which is greater than range.  Alternatively you could check that primes[i] is not 0, but that would never happen if you start checking with 7.

Since we don't pass numbers divisible by 2 or 3 to this method, we don't need to attempt to divide by them.  So we start with the third prime, primes[2] which is 5.

Note that this makes isPrime dangerously fragile.  You may want to make it private rather than public to make it clear that it should only be called under limited circumstances.  Unless performance is a big issue, the previous version is more robust.  And the previous version may be faster anyway.


What do you think of my regex for URL validation?

Your regex has many false positives (matches without a valid URL being there), and many false negativs (URLs you don't recognize). You should read the appropriate RFCs which contain relevant parts of the grammar.

Here are some failure scenarios:

⊖ You don't match schemes other than HTTP or HTTPS. Consider FTP, SFTP, data URLs, and other widespread schemes like file:, mailto:, irc: or skype:. Consider also that the scheme is sometimes omitted, so that the same protocol as the current document is assumed. Test cases:

ftp://example.com/
data:text/html,<p>Hello World!
mailto:foo@example.com
//example.com/

Every scheme has a slightly different syntax, so you'll have to decide which ones you support. Note that matching a HTTP(S) URL is different from matching all URLs.
⊕ You match some domain names that are syntactically correct, but semantically only consist of a top level domain. You may or may not wish to rule these out:

http://co.uk/

See the Mozilla Public Suffix List for the only reliable way to do this.
⊖ Some host names don't have a TLD:

http://localhost/

⊕ You match loads of stuff that isn't ok, e.g.:

999.999.999.999/this-is-no-ip4-address
-.-

⊖ You don't have support for ports:

http://example.com:80/

⊖ You don't have support for IPv6 IPs.

http://::1/
http://[::1]:80/

⊖ You can't match any authority in the host part:

ftp://user:password@example.com/

⊖ You don't support URL-encoding:

http://example.com/some%20path

⊖ You don't support Unicode chars:

http://example.com/smørrebrød/greek-Λεττερς

Consider also that the host name may contain Unicode characters, but will have an equivalent punycode representation.
⊖ Coming to think of it, you actually forbid quite a lot of (special) characters, although they would be perfectly valid (the host part is more restricted).

http://example.com/stuff_(in parens)/

⊖ In a URL, the path is followed by a single query string, introduced by a ?. Note that the semicolon ; is the more modern, but equivalent alternative to the & separator. The + means a literal space here. The query string may only be followed by a fragment, which is separated by #. Other instances have to be encoded.

For an overview of URL syntax, start with this Wikipedia article. Also look at URI Schemes. These articles also link to relevant specs.


Architecture for manager that gets shared among different components

About the architecture and thinking exclusively on the given example application (logging), I believe manager does not need to track all manager::instance instances. Maybe in other applications this might be needed, but not in this one. Thus, I would just turn get_instance into a convenience method (make_instance) to create new manager::instances:

class manager {
public:
    class instance;

    std::unique_ptr<instance> make_instance(const std::string& name);
    void print(const std::string& sender, const std::string& message);
};

std::unique_ptr<manager::instance> manager::make_instance(const std::string& name) {
    return std::unique_ptr<instance>(new instance(name, *this));
}

If you plan using the manager like a singleton (having only one instance and everyone can access it), maybe the manager and manager::instance classes could be merge into a single one, where manager members would become static and manager::instance would become an actual instance of manager.

Please note that both simplifications above may not apply to other applications.

Now, the general code review comments (some of which were already applied on the snippet above):

The code is very well organized, very easy to read and understand. The coding style is consistent. I have only 3 suggestions for improvement:

Always pass std::string to a function as const std::string& instead of just std::string to avoid an unnecessary copy.

Avoid using namespace std;. If, for instance, you really want to use some std symbols unqualified, import them explicitly (like using std::string;). Also avoid using declarations on headers where they may affect user code (in global or namespace scope), otherwise it may break other's code when they include your header.

Also, use braces after if, while, do and for. Those kind of bugs (adding another indented line thinking it inside a block) are hard to spot.


Despite what you may have been taught, you should not get into the habit of using using namespace std, especially when you start writing larger programs.
Since you're in main(), you should just return 1 instead of calling exit(1).  The latter is only necessary in other places from which you will need to terminate early.
You don't need to display an output if the file was successfully opened.  You'll know it failed if the program terminates after asking for a filename.
Do not use std::eof() for detecting the end of the file.  It will look for the eof bit after reading the end of the stream (and will not even consider errors in reading (i.e. bad bit)).  Read this for more information.

Instead, read from the file and check for the bad bit using std::getline():

while (std::getline(std::cin, line))
{
    // ...
}

You ask the user for input, but you only validate it once.  If the user enters an invalid value a second time, the program will continue, causing problems.  All of that should be in a loop that will terminate once the user provides valid input.

do
{
    std::cout << "Pick a number between 1 through 100. ";
    std::cin >> value;

} while (value < 1 || value > 100);

You don't need return 0 at the end of main().  Reaching the end already implies a successful termination, so the compiler will do this return for you.


Program to compute final grade for weighted assignments

Split assignment into three functions. homework, exam and labwork. Take:

def homework(grade, weight=1):
    global hw_tally, hw_weight_count, hw_final
    hw_weight_count += weight
    hw_temporary = (grade * weight)
    hw_tally += hw_temporary
    hw_final = hw_tally/hw_weight_count

Change homework into a class.

class Scores:
    def __init__(self):
        self.tally = 0
        self.weight_count = 0

    @property
    def final(self):
        return self.tally / self.weight_count

    def grade(grade, weight=1):
        self.weight_count += weight
        self.tally += grade * weight

Now you can use the above class to total all the separate things. And then perform your total on Scores.final.
Group the exam types into another class, say StudentScores.
Expand Scores to also take the percentage. And make final return the percentage.
Move your final calculation into StudentScores.

This can make:

class Scores:
    def __init__(self, percentage=1):
        self.tally = 0
        self.weight_count = 0
        self.percentage = percentage

    @property
    def final(self):
        return self.tally / self.weight_count * self.percentage

    def grade(self, grade, weight=1):
        self.weight_count += weight
        self.tally += grade * weight

class StudentScores:
    def __init__(self, scores):
        total = sum(scores.values())
        self._scores = {
            key: Scores(score / total)
            for key, score in scores.items()
        }

    def __getattr__(self, name):
        return self._scores[name]

    @property
    def grade(self):
        return sum(scores.final for scores in self._scores.values())

student = StudentScores({
    'homework': 0.4,
    'labwork': 0.1,
    'exam': 0.5
})

student.homework.grade(81)
student.exam.grade(90, 4)
student.homework.grade(100, 2)
student.labwork.grade(84, 3)
student.labwork.grade(90, 2)
student.exam.grade(78)
student.exam.grade(85)
student.labwork.grade(88)
student.exam.grade(75)

print("Final grade = ", student.grade)

This uses a lot of classes, and isn't really the best way if you're taking data from a file. And so if you store your results as a JSON file, and read it into Python however you want. Then you can default the weights into the JSON data. And then perform the rest of the code in a couple of comprehensions, wrapped in a sum:

results = {
    'homework': [
        0.4,
        [
            [81],
            [100, 2]
        ]
    ],
    'labwork': [
        0.1,
        [
            [84, 3],
            [90, 2],
            [88]
        ]
    ],
    'exam': [
        0.5,
        [
            [90, 4],
            [78],
            [85],
            [75]
        ]
    ]
}

def default_weights(results):
    return [
        [percentage, [(score + [1])[:2] for score in scores]]
        for percentage, scores in results.values()
    ]

def grade(results):
    return sum(
        percentage * sum(s*w for s, w in scores) / sum(w for _, w in scores)
        for percentage, scores in results
    )

print("Final grade = ", grade(default_weights(results)))


The main thing I see wrong is that you are not accounting for sizeof(foo).

The other problem is that auto_ptr<> will not de-allocate the memory correctly. It  calls delete X, but this is not legal as you did not allocate the memory with new. You need a custom destroy function (as you can provide to std::unique_ptr) that does the following:

Note: Original Question was:

std::auto_ptr<Base> p(malloc(size)) Packet());

Leading to my original answer:

// Assuming Packet*   packet = // stufff

packet->~Packet();   // Need to call destructor
free(packet);        // then free the memory allocated with malloc

Why not do this?

size_t const size = ...;
std::auto_ptr<Base> p = new Packet(size);

Then change packet too:

struct Packet : Base
{
  int foo;
  std::vector<char> data;
  Packet(size_t size): foo(0), data(size) {}
};

Edit:

Based on the comments and the updated question:

I posted the question here (to get more eyes on it): https://stackoverflow.com/q/9714359/14065

Which brought up two points:

You still can use std::auto_ptr<>

The memory allocated with new char[size] must be freed by delete []
This is not supported by std::auto_ptr<> though you may be able to use std::unique_ptr

Secondly the implementation is allowed to put a marker after the end of the object

A few other points need to be considered so please read the linked questiom.


Parse JSON array into different Object using Reduce

This can be handled with a single Array.prototype.forEach loop. Consider the following:

function parseItems(json){
  var output = '';
  json.freight.items.forEach(function (item) {
    output += `
      <LineItem>
        <PieceCount>${item.units * item.qty}</PieceCount>
        <NetWeight UOM="Lb">${item.weight * item.qty}</NetWeight>
        <GrossWeight UOM="Lb">${item.weight * item.qty}</GrossWeight>
        <FreightClassification>50</FreightClassification>
      </LineItem>`;
  });

  return output;
}

No need to iterate over everything repeatedly for this.

Edit: Made a fiddle for you


The most important approach to reduce duplicated code is to put the repetitive code into a parameterized method. In case you use an integrated Development Environment (IDE) like eclipse, IntelliJ or alike they have an automated Refactoring to assist you with that. (lookup your IDEs online help how to invoke it).
Here is how I do this step by step
The initial step is to identify the duplicated  parts. In your case the two while/do loops are the first candidates. They are similar that means that there are variables and literals that differ. We need to make them looking the same so that we can replace all of them with the call to the new method to be created.

To be able to do that we need to provide a unique variable scope for both parts. This is done by enclosing each of the loop in braces {}
 {
     do {
         System.out.print("Price?: ");
         priceInitial = scan.nextDouble();
         if (priceInitial < 0) {
             System.out.println("Enter A Value  Above 0");
         } else {
             System.out.println(priceInitial);
             break;
         }
     } while (true);
 }
 {
     do {
         System.out.print("HST?: ");
         HST = scan.nextDouble();
         if (HST < 0) {
             System.out.println("Enter A Value  Above 0");
         } else {
             System.out.println(HST);
             break;
         }
     } while (true);
 }

Inside this braces we declare and use new variables, that have the same names in both places (it is important that the new variables are declared in each block individually and not reused in the lower block!):
 {
     String message = "Price?: ";
     double userInput = 0;
     do {
         System.out.print(message);
         userInput = scan.nextDouble();
         if (userInput < 0) {
             System.out.println("Enter A Value  Above 0");
         } else {
             System.out.println(userInput);
             break;
         }
     } while (true);
     priceInitial = userInput;
 }
 {
     String message = "HST?: ";
     double userInput = 0;
     do {
         System.out.print(message);
         userInput = scan.nextDouble();
         if (userInput < 0) {
             System.out.println("Enter A Value  Above 0");
         } else {
             System.out.println(userInput);
             break;
         }
     } while (true);
     HST = userInput;
 }

Now we select all the lines in the first part that look exactly the same as in the second part. Then you can apply the extract method refactoring of the IDE. The result should look like this:
 {
     String message = "Price?: ";
     // replaces by the IDE
     double userInput = extracted(scan, message);
     priceInitial = userInput;
 }

  // new method created by the IDE behind main()
 private static double extracted(Scanner scan, String message) {
     double userInput = 0;
     do {
         System.out.print(message);
         userInput = scan.nextDouble();
         if (userInput < 0) {
             System.out.println("Enter A Value  Above 0");
         } else {
             System.out.println(userInput);
             break;
         }
     } while (true);
     return userInput;
 }

Of cause you should give it a better name then what the IDE suggested.

In case your IDE did not replace the other occurrence of the selected code itself  you copy the method call from the first block the other one and delete the obsolete code:
  {
      String message = "Price?: ";
      double userInput = extracted(scan, message);
      priceInitial = userInput;
  }
  {
      String message = "HST?: ";
      double userInput = extracted(scan, message);
      HST = userInput;
  }

Then inline the new variables in both blocks
 {
     priceInitial = extracted(scan, "Price?: ");
 }
 {
     HST = extracted(scan, "HST?: ");
 }

And finally remove the blocks too.
 priceInitial = extracted(scan, "Price?: ");
 HST = extracted(scan, "HST?: ");

Why do I suggest this rather complicated approach?

Each single step is a very small change to your code.
You don't need to think about the signature of the new method beside giving it a good name.
After each step you can compile and run the code to check if it still does what it should. (having Unittest will be handy...)


I'm glad to see someone did a WPF calculator, and I hope that I can add to what was already stated. Before I get started: "yes this is a MVVM rant". Now that I got that out of the way, I can understand though why a person would do a code behind approach. One is that it is what a ton of people are used too (I was one of them coming from Java, then going to winforms and eventually landing on WPF) Two is that at first glance it looks to be more compact and easier to understand. So why should a person do it? Well for one is that you'll be less tempted to put FrameworkElement properties in your code. string str = txtDisp.Text;, txtDisp.Text = str;, txtDisp.Text = b.ToString(); ...etc

Why is that helpful? well if you were to write tests for your code to make sure your logic is sound you don't want to setup a window in your favorite test framework. (trust me..I tried) However if you setup your ViewModel using normal primitive properties and bind your Window to those properties you'll find it much easier to test. I can imagine my ViewModel looking sorta like this

public class CalculatorViewModel : INotifyPropertyChanged
{
    public string Display {get; private set;}

    public ICommand NumericButtonPressedCommand {get; private set;}

    //... other things to set this all up

    //called from the UI and state contains a string of 0-9
    private void NumericButtonPressed(object state)
    {
        //convert state to int, update display
    }
}

TIP you can find much more information about MVVM and how to properly bind and setup commands all over the internet.

The viewmodel above can easily be tested with something like this:

public class CalculatorViewModelTest
{
    [Test]
    public void WhenNumericButtonIsPressedDigitIsShownOnDisplay()
    {
        var viewModel = new CalculatorViewModel();

        NumericButtonPressedCommand.Execute("4");

        Assert.That(viewModel.Display, Is.EqualTo("4"));

        NumericButtonPressedCommand.Execute("4");
        NumericButtonPressedCommand.Execute("2");
        NumericButtonPressedCommand.Execute("4");

        Assert.That(viewModel.Display, Is.EqualTo("4,242"));
    }
}

This is another reason why it's good to separate your logic from your UI. It facilitates easier testing.

So enough of a rant about that. If you decide to give it a go you'll read that over and over and over again. Your code uses the Tag object property of your buttons which IMO is much less clear than just setting up 4 (or more) operator ClickListeners. If you were to revisit this code in a few days or weeks and say your plus button was subtracting. You'd first look at Compute and see that it looks for a CalcOperator being set to lastOper. You look to see where it is set which is by HandleOperator, that is called from OnClickOperator and uses a Tag. Now you are searching for where Tag is set and you finally see that you accidentally set the Plus button's Tag to Subtract. copy paste error. Had you had individual Operator ClickListeners you would probably have gone to the OnClickAddition and see that you accidently set lastOper to Subtract. (In reality you didn't do that, but you can see how tracking the bug is easier when some things are spelled out. Not always, but sometimes)


Shorten JavaScript Code due to duplicate variables without polluting global namespace

If those variables are constant (ie, they don't change between invocations of of the functions), you can put the functions and variables into a closure:

(function() {
    //FIRST FUNCTION
    var imageSum = snapshots.total_entries; //Inner Box
    var dl = $j('#snapshots')[0]; //Outer Box
    ...
    window.snapshotScroll = function (amount, refresh) {
        ...
    } // end snapshotScroll();

    //SECOND FUNCTION
    window.snapshotCheck = function (){ // Check if snapshot is in view
        ...
    } // end snapshotCheck();
})();


code review for count then sort problems (go lang)

In Go, I would write:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "sort"
)

type Key string
type Count int

type Elem struct {
    Key
    Count
}

type Elems []*Elem

func (s Elems) Len() int {
    return len(s)
}

func (s Elems) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

type ByReverseCount struct{ Elems }

func (s ByReverseCount) Less(i, j int) bool {
    return s.Elems[j].Count < s.Elems[i].Count
}

func main() {
    m := make(map[Key]Count)
    fi, err := os.Open("keys.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer fi.Close()
    r := bufio.NewReader(fi)
    for {
        line, err := r.ReadString('\n')
        if err != nil {
            if err == io.EOF && len(line) == 0 {
                break
            }
            fmt.Println(err)
            return
        }
        key := line[:len(line)-1]
        m[Key(key)] += 1
    }
    fi.Close()

    e := make(Elems, 0, len(m))
    for k, c := range m {
        e = append(e, &Elem{k, c})
    }
    sort.Sort(ByReverseCount{e})

    fo, err := os.Create("counts.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer fo.Close()
    for _, e := range e {
        line := fmt.Sprintf("%s: %d\n", e.Key, e.Count)
        fo.WriteString(line)
    }
}

Input (keys.txt):

apple
banana
orange
apple
banana
apple

Output (counts.txt):

apple: 3
banana: 2
orange: 1


Which is correct : Open one Connection for inserting List of objects or open connection for every single insertion?

In general, the best is to do all your inserts in one connection.

Open/Close a connection implies a penalty. Although it is mitigated by some connection pooling mechanism on the database side (btw what is it ?), it is additional work that is not useful nor required.

The reason is that there is the possibility to use a Transaction to ensure that "all or nothing" is inserted, regarding whether things goes good or bad in your insertion loop, and in most cases a transaction is tied to a connection.

Here is something that includes a transaction. That'the way I am doing it in SQLServer. I assumed that the Informix transaction are correctly implemented using the ADO.NET scheme, and I do not know is this implementation is working.

public int Insert(List<Day> days)
{
    int affectedRow = -1;
    using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["sh"].ToString()))
    {
        con.Open();
        using(var transaction = con.BeginTransaction())
        {
            var cmdTxt = " INSERT INTO shedule(day,short,name,depcode,studycode,batchnum) VALUES (?,?,?,?,?,?) ";
            using (var myIfxCmd = new IfxCommand(cmdTxt, con,transaction ))
            {
                myIfxCmd.CommandType = CommandType.Text;
                myIfxCmd.Parameters.Add("day", IfxType.Char);
                myIfxCmd.Parameters.Add("short", IfxType.NVarChar);
                myIfxCmd.Parameters.Add("name", IfxType.NVarChar);
                myIfxCmd.Parameters.Add("depcode", IfxType.Integer);
                myIfxCmd.Parameters.Add("studycode", IfxType.Integer);
                myIfxCmd.Parameters.Add("batchnum", IfxType.Integer);

                foreach (Day a in days)
                {
                    myIfxCmd.Parameters[0].Value = ((object)a.DayId) ?? DBNull.Value;
                    myIfxCmd.Parameters[1].Value = ((object)a.ShortName) ?? DBNull.Value;
                    myIfxCmd.Parameters[2].Value = ((object)a.Name) ?? DBNull.Value;
                    myIfxCmd.Parameters[3].Value = a.DepCode;
                    myIfxCmd.Parameters[4].Value = a.StudyCode;
                    myIfxCmd.Parameters[5].Value = a.BatchNum;

                    affectedRow = myIfxCmd.ExecuteNonQuery();
                }
            }

            // commit the changes in the database.
            // if an exception occurs somewhere, then the using blocks
            // makes that the transaction is disposed and rolled back,
            // and nothing will be updated in the database
            transaction.Commit();
        }
    }

    return affectedRow;
}


config files for different development environments (Production, Dev, Testing)

Incase you are using Docker for deployment. The required environment variable can be configured as Kuberenetes configuration and it reads based on the deployment configuration environment.


I would argue the exact opposite.

Explicitly closing a stream is probably not what you want to do. This is because when you close() the stream there is the potential for exceptions to be thrown. Thus when you explicitly close a file stream it is an indication you both want to close the stream and explicitly handle any errors that can result (exceptions or bad-bits) from the closing of the stream (or potentially you are saying if this fails I want to fail fast (exception being allowed to kill the application)).

If you don't care about the errors (ie you are not going to handle them anyway). You should just let the destructor do the closing. This is because the destructor will catch and discard any exceptions thus allowing code to flow normally. When dealing with the closing of a file this is what you normally want to do (if the closing fails does it matter?).


I see some things that may help you improve your code.

List all required #includes

The code needs the following #includes to actually compile.  Since they therefore form part of the interface, they should be included in the file and in a code review:

#include <mutex>
#include <queue>

Be clear about ownership

If the intention is to have a thread-safe queue, then passing pointers in and out is definitely not the way to go.  The problem is with object ownership.  Even if your thread-safe queue works perfectly, all of its inherent goodness is all too easily bypassed because you're using pointers.  For example:

SafeQueue<std::string> sq;

{
    std::string msg1{"this message exists"};
    sq.push(&msg1);
}   // msg1 is now destroyed, but queue still has pointer
std::cout << *sq.next() << " no longer\n";  // kaboom!

The problem is that the queue doesn't actually own the object (or at least have a std::shared_ptr) so there's not much point in perfecting the queue until that's addressed.

Choose better names

I have never thought of push and next as inverse operations, and I'll bet you never have either.  The push member function name is OK, since it actually does that, but next is just a strange name.  I'd say use pop or pop_front might be better names.

Minimize locking duration

In the push code, we have this:

void push(T* elem) {
    m.lock();
    if(elem != nullptr) {
        q.push(elem);
    }
    m.unlock();
}

But why acquire a lock if you don't need it?  It just slows things down.  You could instead write that like this:

void push(T* elem) {
    if (elem == nullptr) {
        return;
    }
    m.lock();
    q.push(elem);
    m.unlock();
}

Or better, see the next suggestion:

Use RAII to reduce errors

If you happened to forget to remove the lock on the code above, Bad Things would likely happen.  Fortunately, in C++, there's a handy idiom that is very often used in C++ and it's called Resource Allocation is Initialization.  In this context, we use a std::lock_guard like this:

void push(T elem) {
    std::lock_guard<std::mutex> lock(m);
    q.push(elem);
}

The lock_guard automatically gets locked on creation and unlocked on deletion, so when it goes out of scope, the lock is released even if you forget.

Return an indicator of success

Since we've already established that passing pointers in or out is a problem, I'd suggest changing the interface for the next() function.  Have it take a reference (so the caller must supply one) and then return a bool to indicate success.  That might look like this:

bool next(T& elem) {
    std::lock_guard<std::mutex> lock(m);
    if (q.empty()) {
        return false;
    }
    elem = q.front();
    q.pop();
    return true;
}


Avoiding nested callbacks when using MongooseJS

Yes you're right, there are better solutions. For example you could use promises instead of callbacks since mongoose operations can return promises according to the documentation.

Your example with promises:

var Pet = require("models/pet.js");
var User = require("models/user.js");

exports.register = function (req, res, next) {

    var user = new User({
        username: req.body.username,
        password: req.body.password
    });

    user.save()
        .then(function () {
            return Pet.findOne({
                "name": "Egg",
                "ownerId": "<<system>>"
            });
        })
        .then(function (pet) {
            return Pet.clonePetForUser(user._id, pet._id);
        })
        .then(function () {
            res.json({message: 'User created'});
        })
        .catch(function (err) {
            console.error(err);
            next(err);
        });

});

You can write your own method to return a promise. Instead of:

petSchema.statics.clonePetForUser = function (userId, petId, callback) {
     this.find({ }, callback);
};

You can write:

petSchema.statics.clonePetForUser = function (userId, petId) {
    return this.find({ });
};


Without even doing anything clever regarding the algorithm, this:

    new_count = count + sum(stones[start:start + k])
    merged_count = sum(stones[start:start + k])

can be cleaned up as

    merged_count = sum(stones[start:start + k])
    new_count = merged_count + count


Honestly, your loop doesn't seem that complex. I would probably ignore this warning in your case, at least until it grew in complexity or the surrounding function grew in size.

In any case, here are some things you could change:

a. Add a variable to replace the five instances of data.Reservations[i].Instances[0].

b. Off the top of my head, I'm pretty sure an EC2 instance is only going to have one "Name" tag. You can extract this loop into a separate function if you feel comfortable with this assumption.

c. If your lint rules / personal style allows for multiple returns, you can reduce the depth by returning from the error.

var instancesList = '';
ec2.describeInstances(params,function(err, data) {
  if (err) return console.log(err, err.stack);

  for (var i in data.Reservations){
    var ins = data.Reservations[i].Instances[0]
    var name = findInstanceName(ins)
    if(name === null) continue;

    instancesList+= 'Name: ' + name +
                    '  id: ' +ins.InstanceId +
                    '  Status: ' + ins.State.Name +'\n';
  }
  console.log(instancesList);
}

function findInstanceName(ins){
  for(var j in ins.Tags){
    if(ins.Tags[j].Key === 'Name'){
      return ins.Tags[j].Value;
    }
  }
  //I'm not sure skipping the instance is the best choice.
  //You might instead return "<Unknown>" so you can know you
  //have an unnamed instance running.
  return null;
}

Brief aside: If this script is only to list the instances for you, you might find it useful to check out the aws-cli and the jq tool:

aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | [(.Tags | from_entries | .Name), .InstanceId, .State.Name] | @tsv' | column -t -s $'\t'

Output:

hello-world      i-a1a1a1a1  running
jenkins          i-b2b2b2b2  running
production       i-c3c3c3c3  running
qa               i-d4d4d4d4  stopped
testing          i-e5e5e5e5  terminated


Did you try to use google for this? You have multiple way to do this :P

For example: @Transactional annotation on method.

Or using XML file to wrap methods with transaction.

Just look for this on google: https://spring.io/guides/gs/managing-transactions/


Using BufferedReader to read lines of a file into a list

Since Java 7, you can make use of try-with-resources, which would change the implementation to:

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    while ((lineRead = br.readLine()) != null) {
        data.add(lineRead);
    }
} catch (IOException e) {
    ...
}

Some other tips:

Your documentation is not telling the truth and incomplete, you have to add some return documentation. Also, for parameters, the first string represents the name, and what follows is the explanation. So it should be more like e.g. @param file the file to read all lines from.
Return the interface instead of the implementation, i.e. return List instead of ArrayList, which means you can always change the implementation.
Never just print the stack trace, wrap and throw an (unchecked) exception or log. For more information as to why, see why printStackTrace is considered bad practice. In case you want to propagate the exception nonetheless, you can wrap it in another exception, e.g.:

try {
    ...
} catch (IOException e) {
    throw new UncheckedIOException(e);
}

This example may be used when the method this code is executed in does not declare to throw a checked Exception. But it all depends on the case at hand.

BufferedReader has a lines method returning all String lines as a stream. With this, you could also implement it as follows:

return br.lines().collect(toList());

I statically imported Collectors#toList. Notice how this results in a List and not an ArrayList.


Observing PEP maximum line size, particularly when formatting localized timestamps

First of all, notice the duplicated parts in these long expressions:

pytz.utc.localize(
    datetime.datetime.utcfromtimestamp(time.time())).astimezone(
    pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S')

pytz.utc.localize(
    datetime.datetime.utcfromtimestamp(float(job.get('starttime')))).astimezone(
    pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S')

Having duplicated code segments is both inconvenient and error-prone.
If you want to / need to change anything later,
you have to remember to do that in all places,
and it's easy to make a mistake.

So it will be good to extract this to a helper function:

def get_formatted_time(val):
    return pytz.utc.localize(
        datetime.datetime.utcfromtimestamp(val)).astimezone(
        pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S')

You can break lines within parentheses.
Now this looks fairly tidy, and it's PEP8 compliant.

Using this helper you can rewrite the original code becomes simpler:

SMS.publish('/jobs', {
    'batchdate': job.get('batchdate'),
    'job': job.get('name'),
    'Script execution date (EST)': get_formatted_time(time.time()),
    'Start time(EST)': get_formatted_time(float(job.get('starttime'))),
    'Current runtime': change_format_num(cur_runtime),
    'Average runtime': change_format_num(avg_time)
})


Grouping an array of strings into anagrams

Technical

   groupAnagrams( args );

That should be:

    groupAnagrams( args, hm );

Bug in copy/paste somehow?

1-liner statements, even simple ones like this:

      if( list[ x ] == null ) continue;

should be braced like:

       if( list[ x ] == null ) {
           continue;
       }

This prevents maintenance problems later, and makes revision history easier to follow.

Algorithm

Your algorithm is taking each member of the array, and comparing to each subsequent member, removing anagram matches.

The primeHash() method is interesting, but ultimately it is a red herring of sorts... and it only works for lower-case input words. You have obviously invested some thought in to it, but there's a simpler solution to that problem:

private static final String anagramKey(String word) {
    word = word.toLowerCase();
    char[] chars = word.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

Take all letters, sort them, return a String. All anagrams of the same letters will have the same keys.

With that key system, the basic code can be come simpler with:

HashMap<String,List<String>> matchMap = new HashMap<>();
for (String word : args) {
    String key = anagramKey(word);
    if (!matchMap.containsKey(key)) {
        matchMap.put(key, new ArrayList<String>());
    }
    matchMap.get(key).add(word);
}

System.out.println(matchMap);

That reduces your problem to an \$O(n)\$ one.


Is there any way to improve the code when the structure entries are heavy.

1st idea is to use a different sort method.  This code runs in O(n*n) time with the for(i=0; i<n-1; i++) for(j=i+1; j<n; j++) loops.

Various sorts operate in O(n*lo2(n)) time and are not too difficult to code.

2nd idea: Make an array of pointers to the list and sort that.  Then only pointers need to be moved during the heavy part of the algorithm.  When done, the final list can then be arranged per the pointer list.

3rd.  Use a hash table for even faster sorting.  Of course, this is more code and complexity.

General coding observations

fflush(stdin); is non-portable.  Code should be able to be written without it.  Better to use fgets() and then scan the string.
printf("Enter city\n"); scanf("%s",c[i].city); is problematic for 1) it does not limit input to 99 characters as needed per the buffer size.  Many cities have a space in their name "New York" and "%s" does not save spaces.  Use fgets() and lop off the tailing '\n' as needed.  name[] too.
Best to validate input:  check return value from *scanf() functions.
The check it too late. Do it before declaring College[]

// struct College c[n];
if(n<=0)
  ...
struct College c[n];

A point on improved sorting methods.

By sorting on name[] only, code could have multiple entries with the same name like "John Adams".  With OP's slow O(n*n) method, a benefit to it is that it is a stable sort.  OP's sorting would not change the sequence concerning ties.

Now consider the standard function qsort()  with a simple compare function that only reference name[], then the order of entries on ties is not guaranteed.

  "If two elements compare as equal, their order in the resulting sorted array is unspecified."  C11 §7.22.5.2

Many fast methods do not guarantee stability.

A classic solution is to include a unique index number with each College[].  Then when there is a tie on the name[], the index could be the tie breaker, ensuring a stable sort.  With the reference table idea far above, possible the "index" could be the College[] address (a pointer) in a clever usage, thus incurring no additional memory cost.


I don't see any issue with code other than below two things.

First, I'll suggest is to use classList.toggle instead of contains and then add/remove class. See browser compability and if target browser does not support toggle method, use polyfill from MDN.

function toggle() {
    if (this.nextElementSibling.classList.contains('active')) {
        this.nextElementSibling.removeAttribute('style');
    } else {
        var elementHeight = this.nextElementSibling.scrollHeight;
        this.nextElementSibling.style.maxHeight = elementHeight + 'px';
    }

    // Toggle `active` class
    this.nextElementSibling.classList.toggle('active');
    this.classList.toggle('active');
}

Second, caching the length of array when iterating using for will slightly improve the performance.

for (var i = 0, len = header.length; i < len; i++) {
              ^^^^^^^^^^^^^^^^^^^^^                  : Caching length

If running the code in latest environment where for...of is supported, you can use it to iterate over elements.

var headers = accordion.getElementsByClassName('accordion-header');
for (header of headers) {
    header.addEventListener('click', toggle);
}


Minimum swaps algorithm terminated due to timeout

Your algorithm can be summarized by the pseudocode:

for each position in the array
    if a position is occupied by the wrong number
        find the number that fits into the position
        perform a swap

A better algorithm would be:

for each position in the array
    if a number is in the wrong location
        find the position the number should go
        perform a swap

This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.

The full program could look like this (in python, as I don't speak js):

def minimumSwaps(arr):
    def swap(i, j):
        arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
        while arr[i]-1 != i:
            swap(i, arr[i]-1)
            swaps += 1
    return swaps