There is nothing wrong with your code when changing the data size to a larger number, except that the draw() method doesn't adjust the width of the columns by the ratio between the canvas size and the number of columns to be drawn.
You'll have to do some math like:
  let offset = Math.round(canvaswidth / len);
  let rectWidth = Math.round(offset * 0.9);

The rounding is because you want integer values (pixels).

ctx.fillStyle = "#000000"
ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
if (seen[i]) {
  ctx.fillStyle = "#00ff00"
  ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
}

This seems inefficient as you draw more and more columns twice through the sorting. A better solution would be something like:
ctx.fillStyle = seen[i] ? "#00ff00" : "#000000";
ctx.fillRect(offset * i, 500 - arr[i], rectWidth, arr[i]);

for (let i = s; i <= e; i++) {
    ctx.fillStyle = "#ffffff"
    ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
    ctx.fillStyle = "#0000ff"
    ctx.fillRect(15 * i, 500, 10, arr[i])
    seen[i] = 1
}

You shouldn't "undraw" a column by drawing a white column over it. Instead you could use clearRect with the same dimensions.

let m = parseInt((s + e) / 2)

You can integer divide by two by right shifting by one:
(s + e) >> 1

You should really be careful to end each statement with a ';' (see here)

await merge(s, e)
// await console.log(`merged ${s} to ${e} now draw...`)
await draw(s, e)

You call these with await but they are not defined as async?

Your algorithm seems to works like a merge sort - as I recall it. I think I would encapsulate the parts into a class instead of having the functions in the global scope.

Besides that, I find you graphics very illustrative.


Given an array find any three numbers which sum to zero

Your code fails this test case:

def test_winston1(self):
    res = sum_to_zero([125, 124, -100, -25])
    self.assertEqual(res, [125,-100,-25])

As for the code

def sum_to_zero(a):
    a.sort(reverse=True)

Why sort?

    len_a = len(a)
    if  len_a < 3:
        return []
    for i in xrange(0, len_a):

You can just do xrange(len_a). I recommend doing for i, a_i in enumerate(a) to avoid having the index the array later.

        j = i + 1

Thar be your bug, you can't assumed that j will be i + 1.

        for k in xrange(j + 1, len_a):
            if a[j] + a[k] == -1 * a[i]:

Why this instead of a[j] + a[k] + a[i] == 0?

                return [a[i], a[j], a[k]]
    return []

Not a good a choice of return value. I'd return None. An empty list isn't a natural continuation of the other outputs.

Here is my implementation of it:

def sum_to_zero(a):
    a.sort(reverse = True)
    for triplet in itertools.combinations(a, 3):
        if sum(triplet) == 0:
            return list(triplet)
    return []


Design patterns: choosing the right handler depending on data type

Sorry this took so long to post, it got a lot longer then I expected it to be.

Since you are already programming off of interfaces, implementing the MEF framework should be relatively simple, provide the expansion that you need, and allow you to add in new IDocumentProcessor classes without recompiling the entire program. You may/will need to modify some aspects of your code, but overall it will remain unchanged.

MEF works by importing and exporting classes based upon interfaces and metadata tied to those classes. You can think of it like the children toys where you put the round blocks in the round holes, the square blocks in the square holes, etc (Note that is overly simplified).

Using your case for example, you would want to export your:

public class DocumentAProcessor:IDocumentProcessor
{
    ....
}

To do so, you would need to add the following to your code file:

[Export(typeof(IDocumentProcessor))]
public class DocumentAProcessor:IDocumentProcessor
{
    ....
}

The Export attribute means that you want to export that class and import it into a variable marked with the Import attribute (I'll get to that in a second). The typeof(IDocumentProcessor) informs what type you are exporting so that it can be matched with an Import expecting that same type (round peg in a round hole).

Additionaly, you can add MetadataAttributes to the classes that you are exporting that give additional information about the class. To do so will take a little more work then adding the export class but taking your example, we would want to create something similar to:

public interface IDocumentProcessorMetadata
{
    string DocumentType { get; }
}

[MetadataAttribute]
public class DocumentProcessorMetadata : Attribute, IDocumentProcessorMetadata
{
    public DocumentProcessorMetadata(string documentType)
    {
        DocumentType = documentType;
    }

    public string DocumentType { get; set; }
}

This will create a simple Metadata attribute that you can attach to your class that will contain the DocumentType that the class processes. You can have this metadata attribute hold any number of items simply by adding new properties to IDocumentProcessorMetadata and DocumentProcessorMetadata. In my system for example, I use this to hold a GUID (has to be as a string), a simple name that can be used for lookups and flags for various things. To use the DocumentProcessorMetadata attribute, you would modify your class(es) to look like:

[Export(typeof(IDocumentProcessor))]
[DocumentProcessorMetadata("DocumentType1")]
public class DocumentAProcessor:IDocumentProcessor
{
    ....
}

[Export(typeof(IDocumentProcessor))]
[DocumentProcessorMetadata("DocumentType2")]
public class DocumentBProcessor:IDocumentProcessor
{
    ....
}

That is it for the Export, now for the Import. The import works in pretty much the same way as the export. You put an [ImportMany(typeof(IDocumentProcessor))] attribute above the variable that the Exports will import into, and that is pretty much it (The ImportMany attribute imports more than 1 instance of the class, while the Import attribute will only import the first instance that is encountered). However, you will need to import to an IEnumberable<Lazy<IDocumentProcessor,IDocumentProcessorMetadata>> variable instead of the Dictionary<string,IDocumentProcessor> that you were using before. You can keep the dictionary that you had, but you will need to populate it another way (I'll provide an example later). What the Lazy<T1,T2> class allows is for the classes to be imported into the variable, but not actually created until they are needed. That way, if you have 5 document processors but in the life of the program you only ever use 2, you save the overhead of creating those 3 that you never used. That said, your import would look like this:

[ImportMany(typeof(IDocumentProcessor))]
IEnumberable<Lazy<IDocumentProcessor,IDocumentProcessorMetadata>> _processors;

To get the processor that you need, you would iterate through the _processors (or you could use linq) to find the one that handles the correct Document.Type:

public void Handle(Document document)
{
    IDocumentProcessor handler;
    //note I keep the dictionary
    //if you use TryGetValue, it is only one trip to the dictionary instead of two
    Handlers.TryGetValue(document.Type, out handler);

    if(handler == null)
    {
        foreach(var processor in _processors)
        {
            if(processor.Metadata.DocumentType == document.Type)
            {
                handler = processor.Value;
                //add the processor to the dictionary so it can be easily found later
                Handlers.Add(document.Type, processor.Value);
                break;
            }
        }
        //If it gets to this point, the processor was not found and an exception should be thrown
        throw new Exception();
    }
    Task task = Task.Factory.StartNew( () => handler.Process(document) );
}

The last piece of the puzzle is the code that will actually connect everything together. I usually have this in it's own class, in the core dll of whatever application is using it. Essentially, this class handles what is called a CompositionContainer that allows all the Exports to be tied to the Imports. You add what are called AssemblyCatelogs that contain a single assembly or you can add a DirectoryCatelog that will include any files in the directory. In your case, I would use an AssemblyCatelog so include all of your Imports (this is assuming that they are in the same assembly as the code containing the CompositionContainer) and a single DirectoryCatelog that will hold all of the IDocumentProcessor classes. If everything is in the same assembly, you can get away with just the AssemblyCatelog but I would still include the DirectoryCatelog incase you wanted to add new IDocumentProcessor classes later. The class would look something like this:

public class MEFManager
{
    private CompositionContainer _container;

    public MEFManager()
    {
        //AggregateCatalog allows multiple catalogs to be added to the CompositionContainer
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
        catalog.Catalogs.Add(new DirectoryCatalog(Path.Combine("BaseDirectory","PathToAssemblies"));

        _container = new CompositionContainer(catalog);

        try
        {
            //This line of code is what ties everything together.
            this._container.ComposeParts(this);
        }
        catch (CompositionException ex)
        {
            ....
        }
    }
}

I would create this class as start up, just keeping it tucked away somewhere. If you want to get really fancy, you can add a FileSystemWatcher on the directory that you specified so if you add a new file at runtime, it calls a function that automatically loads the new assembly and ties all of the Imports and Exports together.

That is pretty much it. This allows you to create an easily extendable program, if you need to add a DocumentCProcessor you would create the class in its own assembly and add the file to the directory that you specified in the MEFManager. The next time the program starts, the MEFManager will find the files and automatically import them to where they need to be.

Surprisingly, the MSDN documentation on MEF is fairly good and can be found here.


Unit test for a function that transforms a PANDAS dataframe

The test itself seems okay.

bug

You use "ID" as columns name in the test, but "TRADEID" in the method to test.

And the result is not what was expected. The TRADEIDs don't match

Classes

There is no use for the class Operations. If you want to group functions that belong together, you can do so in a module (file) and import that. The fact disaggregate_ops_volume_date has a self parameter that is unused is a giveaway here

Vectorize

there is no reason to calculate ops['NDAYS'] row per row via apply. (df["SEQ_PERIODEND"] - df["SEQ_PERIODSTART"]).dt.days works just as well.

Then you can use DataFrame.assign, and don't have to explicitly make a copy of df

ndays = (df["SEQ_PERIODEND"] - df["SEQ_PERIODSTART"]).dt.days
ops = df.assign(NDAYS = ndays)

Day

Since a days is used a lot in that method, it can be clearer to define that up front:

DAY = pd.Timedelta("1d")

ndays can then be defined as ndays = (df["SEQ_PERIODEND"] - df["SEQ_PERIODSTART"]) // DAY. Whether this is clearer than the .dt.days is a matter of taste.

correcting the date can then be expessed more clearly as:

ops["SEQ_PERIODSTART"] += ops.groupby("TRADEID").cumcount() * DAY
ops["SEQ_PERIODEND"] = ops["SEQ_PERIODSTART"] + DAY

input

input is a builtin. By using that name as a variable name, you shadow that builtin. In this case this is not a big problem, but in general you should avoid this

indentation style

You use a very inconsistent style of indenting the code, and what goes on a separate line. Better would be to remain consistent. For this, I use black.

This changes:

expected = pd.DataFrame(
    {'SEQ_PERIODSTART':
         ['2019-02-10', '2019-02-12',                                                           '2019-02-13', '2019-02-13',                                              '2019-02-14', '2019-02-15',                                             '2019-02-16', '2019-02-17'],

      'SEQ_PERIODEND':
          ['2019-02-11',  '2019-02-13',
          '2019-02-14', '2019-02-14',                                               '2019-02-15', '2019-02-16',                                          '2019-02-17', '2019-02-18'],
       'ID': [0, 1, 2, 3, 4, 5, 6, 7],
       'NDAYS': [1, 2, 2, 5, 5, 5, 5, 5]
                       })

to:

expected = pd.DataFrame(
    {
        "SEQ_PERIODSTART": [
            "2019-02-10",
            "2019-02-12",
            "2019-02-13",
            "2019-02-13",
            "2019-02-14",
            "2019-02-15",
            "2019-02-16",
            "2019-02-17",
        ],
        "SEQ_PERIODEND": [
            "2019-02-11",
            "2019-02-13",
            "2019-02-14",
            "2019-02-14",
            "2019-02-15",
            "2019-02-16",
            "2019-02-17",
            "2019-02-18",
        ],
        "ID": [0, 1, 2, 3, 4, 5, 6, 7],
        "NDAYS": [1, 2, 2, 5, 5, 5, 5, 5],
    }
)

Which I think, is a lot more clear

pd.to_datetime

You can invoke this immediately on a list, so defining the input DataFrame can become:

input_df = pd.DataFrame(
    {
        "SEQ_PERIODSTART": pd.to_datetime(
            ["2019-02-10", "2019-02-12", "2019-02-13"]
        ),
        "SEQ_PERIODEND": pd.to_datetime(
            ["2019-02-11", "2019-02-14", "2019-02-18"]
        ),
        "ID": [0, 1, 2],
    }
)

defining test DataFrames

Instead of invoking pd.DataFrame immediately, an alternative is working via a csv-like text input, and then use pd.read_csv and StringIO to convert it to a DataFrame.

expected_str = """
SEQ_PERIODSTART  SEQ_PERIODEND  TRADEID  NDAYS
2019-02-10       2019-02-11     0        1
2019-02-12       2019-02-13     1        2
2019-02-13       2019-02-14     2        2
2019-02-13       2019-02-14     3        5
2019-02-14       2019-02-15     4        5
2019-02-15       2019-02-16     5        5
2019-02-16       2019-02-17     6        5
2019-02-17       2019-02-18     7        5"""
expected = pd.read_csv(
    StringIO(expected_str),
    sep="\s+",
    parse_dates=["SEQ_PERIODSTART", "SEQ_PERIODEND"],
)

Whether this is more clear than using pd.DataFrame() is a matter of taste. The advantage of this method is that it is easy to add or remove a line, and see whether the data is aligned correctly.


It's interesting to notice that when you parse your input, you break a comma-separated string into a list of values. The end result of your code can be achieved much more cleanly if you take a similar (but inverted) approach, i.e. generate a list of values and then have the comma-separated string generated from that list.

It's counterintuitive for the logical branching in your code to be significantly more complex than the logical branching in your description of the behavior. These should map one to one. You can just translate your pseudocode logic exactly as is.

The reason your code ended up being more complex is because you needed to add the whole "add a comma or don't" logic to it - which can be avoided by relying on String.Join, which performs that logic for you, as long as you supply it with a collection of values.

  If list contains R the Readstatus="Y"
  If list contains UR the Readstatus="N"

Dim readStatusList As New List(Of String)

If listStatus.Contains("R") Then
    readStatusList.Add("Y")
End If
If listStatus.Contains("UR") Then
    readStatusList.Add("N")
End If

Dim readStatus As String = String.Join(",", readStatusList)

The exact same applies to the "done" status:

  If list contains DO the Donestatus="Y"
  If list contains NDO the Donestatus="N"

Dim doneStatusList As New List(Of String)

If listStatus.Contains("DO") Then
    doneStatusList.Add("Y")
End If
If listStatus.Contains("NDO") Then
    doneStatusList.Add("N")
End If

Dim doneStatus As String = String.Join(",", doneStatusList)


Is this a correct recursive Scala iterator creation?

micro changes:
use == instead of equals because "==" means "equals".

Scala does not follow the Java convention of prepending set/get to mutator and accessor methods.

Try to split different parts of work (abstraction)

def innerPolygons(geometry: Geometry) : Iterator[Geometry] =
  innerGeometry(geometry).flatMap(inner)

def innerGeometry(geometry: Geometry): Iterator[Geometry]=
  (0 to geometry.GetGeometryCount()).map(geometry.GetGeometryRef(_))

def inner:Geometry => Iterator = g => if ("LINEARRING"== g.GetGeometryName())
  Iterator.single(g)
 else
  innerPolygons(g)


Permutation of a string eliminating duplicates

Best beginner's code I've seen.  Possibly ever.  Admittedly, I haven't reviewed too many beginner's programmes, but this one was definitely an easy review.
Only style change I'd suggest is to avoid the single-line if (s.charAt(currIndex) == s.charAt(i)) continue;.  It's totally valid, but easy to miss.  At least put the continue on a new line; many people prefer to put it in braces, too.
Since your main() method is obviously a way to test the rest of the code, I'd suggest pulling the loops that are currently in there into a self-documenting method like testPermutation(String arg) and call that from main().
Now that your main method is so simple (it just contains testPermutation("abc"); and testPermutation("aabb");), change it to either

loop over the arguments to main(), so you can call your program like java yourpackage.Permutation abc aabb, or
read strings from stdin until user exits.

To measure time complexity, you can maintain a counter that gets incremented inside swap(), and infer from that result.  I think you'll find that it's much less than n! * n.
Space complexity is the same as time complexity, since you create a new String every time you swap.  Or depending on how you define "space complexity", I suppose it might be n * time complexity, since each time you swap, you create a String of length n.


I think that printChild() would be better named printDescendantLeaves().  Also, printChild() always works left-to-right, which spoils your clockwise traversal.

For flexibility, consider taking a visitor instead of hard-coding System.out.println() everywhere.  Alternatively, implement your traversal as an Iterator (which is admittedly tricky to do recursively since Java doesn't support yield).

"Periphery" is misspelled.


char* join(char** strings, size_t num_strings, char* seperator)

The inputs can be const as they should not be modified by this function: const char* join(const char** strings, size_t num_strings, const char* seperator)

int cache = 0;

cache is not a very descriptive name. Prefer input_strings_length or similar

for(int i = 0; i < num_strings; i++){

Format as for (int i = 0; i < num_strings; i++) { (added spaces for readability)

char * joined

Why does the * have spaces around both side, but the rest are char* name? (space only on right side)

for(int j = 0; j < num_strings; j++){
    if(j != 0){
        int j = 0;

Prefer not using shadowed variables (same variable name in both inside and outside)

int j = 0;
while(j < strlen(seperator)){ //inserting seperators
    joined[count] = seperator[j];
    count++;
    j++;
}

This is same as:
strcpy(joined + count, seperator);
count += strlen(seperator);

which I find more readable

// big loop

This comment is not descriptive at all. What does it mean?
I would rename variable in for(int j = 0; j < num_strings; j++){ to be for (int string_index = 0; string_index < num_strings; string_index++) {

The whole program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

const char* join(const char** strings, size_t num_strings, const char* seperator) {
    int input_strings_length = 0;
    for (int i = 0; i < num_strings; i++) {
        input_strings_length += strlen(strings[i]);
    }

    size_t string_length = input_strings_length + num_strings * strlen(seperator);
    char* joined = malloc((string_length + 1) * sizeof(char));
    joined[string_length] = '\0';

    int array_offset = 0;

    for (int string_index = 0; string_index < num_strings; string_index++) {
        if (string_index != 0) {
            strcpy(joined + array_offset, seperator);
            array_offset += strlen(seperator);
        }

        strcpy(joined + array_offset, strings[string_index]);
        array_offset += strlen(strings[string_index]);
    }

    return joined;
}

int main() {
    printf("%s\n", join(array, 3, "SEP"));
    return 0;
}


A light/dark theme toggle react component

Here are some suggestions:
handleClick method
Intead of calling document.getElementById and checking for .checked twice, you can store it's value into a constant like this:
const isDarkMode = document.getElementById("switch-style").checked;

then just do window.localStorage.setItem("theme", isDarkMode ? "dark" : "light");
After these changes, the method will look like this:
handleClick() {
    document.body.classList.toggle("dark");
    const isDarkMode = document.getElementById("switch-style").checked;
    window.localStorage.setItem("theme", isDarkMode ? "dark" : "light");
}

componentDidMount method
This code can be simplified
if (window.localStorage.getItem("theme") === "dark") {
    bodyClassList.add("dark");
    themeSwitch.checked = true;
} else if (window.localStorage.getItem("theme") === "light") {
    bodyClassList.remove("dark");
    themeSwitch.checked = false;
}

You could make use of toggle method's second parameter, which is a boolean value that forces the class to be added or removed, regardless of whether or not it already existed.
So that code could be changed to
const mustUseDarkMode = window.localStorage.getItem("theme") === "dark";
bodyClassList.toggle("dark", mustUseDarkMode);
themeSwitch.checked = mustUseDarkMode;


I think that you can create one thread to handle all timers. When a new timer is created, you should add it in a (synchronized) queue of "timers to trigger". The background thread must wait for the closest timer to be triggered. Also you should wake it up each time you modify the queue of timers and recalculate "which is the closest timer now?".

When the queue is empty, the background thread can be destroyed (joined) or you can wait an "exit" event (or the creation of another timer). Those are just details. The background thread can be created by the first timer and joined when the last timer is destroyed, or it can just live in the whole program execution.

Another thing, to improve portability you could use boost::thread library and boost's condition variables instead of raw Windows events.


I think that both approaches are incorrect.

Why would you need to cast an object to its own type, while it is already typed to a type that inherits from its parent abstract type?

The method getThis() is absolutely senseless, because if you have an instance of an object, it is typed by definition.


Dynamically create ordered list in outlook from Excel

There is no reason to convert arr to a collection.  Join() can quickly build a tag list from a 1 Dimensional array.  The trick is to have Join()  insert a closing tag + open tag between each element.

"
" & Join(arr, "

") & "
"

Join Demo

Dim arr As Variant
Dim n As Long
ReDim arr(6)
For n = 1 To 7
    arr(n - 1) = WeekdayName(n)
Next

Debug.Print "
" & Join(arr, "

") & "
"
Debug.Print "
" & Join(arr, "
" & vbNewLine & "
") & "
"

You could also avoid creating the array in the first using the same tring to replace the commas with a close tag + an open tag:

Your code is building a hyperlink, filling an ordered list, and creating the message htmlBody and will probably do several other tasks before it is complete.  There is no way to test any single process without running the entire code.  The fewer tasks that a method performs the easier it is to modify and debug.

Notice how easy it was to test my Refactored Code in the immediate window.

Refactored Code

Note: I find that using an ArrayList is the easiest way to create and modify dynamic html.

Function getCheckListItems() As String
    getCheckListItems = "
" & Replace(SheetData.Range("Notes_For_Doc_Reviewer").Value, ",", "
" & vbNewLine & "
") & "
"
End Function

Function getChecklistHTML(HyperlinkTag As String, CheckListItems As String) As String
    Const Delimiter As String = vbNewLine
    Dim list As Object
    Set list = CreateObject("System.Collections.ArrayList")
    list.Add ""
    list.Add ""
    list.Add "Hello Zack"
    list.Add "
Please complete the closing document review for the following file:"
    list.Add "&nbsp&nbsp"
    list.Add HyperlinkTag
    list.Add "

"
    list.Add "Items to make note of in the file."
    list.Add "
"
    list.Add CheckListItems
    list.Add "
"
    list.Add ""
    list.Add ""

    getChecklistHTML = Join(list.ToArray, Delimiter)

End Function

Function getCurrentPathHyperlink(Wb As Workbook)
    Const DefaultLink As String = "@currDir"

    Dim currDir As String
    currDir = Replace(Wb.Path, " ", "%20")

    getCurrentPathHyperlink = Replace(DefaultLink, "@currDir", currDir)
End Function

Edit:

My original post was using an open tag instead of a closing tag in getCheckListItems().  Many thanks to Ryan Wildry!


FizzBuzz without hard-coded logic checks

The code looks well structured and seems to do its job (I have just copy-pasted it in VS2015 and worked directly), so many of the above are rather superficial:

1) Function (including constructor) parameter naming. In C#, usually all function parameters are named using CamelCase.

internal Counter(int min, int max, Catalog catalog)
{
    this.min = min;
    this.max = max;
    this.catalog = catalog;
}

2) Non-private members naming. Here, I would also favor PascalCase over CamelCase, although this targeted question and answers do not seem to clarify this.

internal class Spec
{
    internal int Divisor;
    internal string Output;
}

3) ToString usage - ToString(int Number) function has exactly the same name as Object.ToString() function (no parameters). Although it is perfectly legal (becomes an overload), I would choose a different name, just not to create any confusion (your are not getting a string representation of the object using its state only, but also providing some input).

Also, since strings are immutable, concatenation is faster and allocates less memory if StringBuilder is used.

internal string GetString(int Number)
{
    var builder = new StringBuilder();
    foreach (var x in specs)
    {
        builder.Append(Number % x.Divisor == 0 ? x.Output : "");
    }
    string outputString = builder.ToString();

    return String.IsNullOrWhiteSpace(outputString) ? Number.ToString() : outputString;
}

}

The whole code:

using System;
using System.Collections.Generic;
using System.Text;

public class Program
{
    public static void Main()
    {
        var catalog = new Catalog();
        catalog.Add(divisor: 3, Output: "Fizz");
        catalog.Add(divisor: 5, Output: "Buzz");
        catalog.Add(divisor: 10, Output: "Pozz");

        var counter = new Counter(Min: 1, Max: 100, Catalog: catalog);
        counter.Output();
        Console.ReadLine();
    }
}

internal class Counter
{
    private int min;
    private int max;
    private Catalog catalog;

    internal Counter(int min, int max, Catalog catalog)
    {
        this.min = min;
        this.max = max;
        this.catalog = catalog;
    }

    internal void Output()
    {
        for (int i = min; i <= max; i++)
        {
            Console.WriteLine(catalog.GetString(i));
        }
    }
}

internal class Catalog
{
    private List<Spec> specs;

    internal class Spec
    {
        internal int Divisor;
        internal string Output;
    }

    internal Catalog()
    {
        specs = new List<Spec>();
    }

    internal void Add(int divisor, string Output)
    {
        specs.Add(new Spec() { Divisor = divisor, Output = Output });
    }

    internal string GetString(int Number)
    {
        var builder = new StringBuilder();
        foreach (var x in specs)
        {
            builder.Append(Number % x.Divisor == 0 ? x.Output : "");
        }
        string outputString = builder.ToString();

        return String.IsNullOrWhiteSpace(outputString) ? Number.ToString() : outputString;
    }
}


Is this calculator written in Python clean/good?

This code is broken into multiple unnecessary functions. Below is all thats needed:

operations = {
    "+": lambda x, y: x + y,
    "-": lambda x, y: x - y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y
}

def calculate():

    # Get numbers #
    one, two = input("Enter two numbers separated by a space: ").split()

    while operator := input("Enter an operator: + - * /"):
        if operator in ["+", "-", "*", "/"]:
            print(operations[operator](int(one), int(two)))
            return

Getting multiple values from input

Instead of prompting for each number, simply ask for two numbers separated by a space then split the input with a given delimiter, by default a space. .split returns a list, and since you only anticipate two values, can assign the output to one, two.

Walrus Operator

If you're using python-3.8, you can utilize the walrus operator, also called assignment expressions. It allows you to assign and return a value in an expression. This reduces the need to define a variable before the loop and use it.

Checking in

I do believe using a list/tuple instead of a string when checking in this particular case because it can catch some invalid input. A catch such as if operator in "+-*/":, it will allow "+-" as a valid operator, which we don't want. So good job there.

Lambdas

I've decided to use lambdas here because it's much easier to store them in a dictionary and then simply retrieve the value from the dictionary with the operator. If you want to learn more about how lambdas work, this Google Search brings up a plethora of sources that can explain the concept much better than I can.


As for a review of the code I would suggest to avoid acronyms (also recommend, as @200_success did, to better indent the code, in case this is how your code is indented).

As for the solution, I would strongly avoid brute force ones. This is a cryptarithmetic problem and, if you work only on base 10, you have 10! possible assignments, but if you generalize (for any base) then the problem is NP-complete. I would suggest to look for solutions for cryptarithmetic problems (usually they are described on texts/sources on AI).


a few remarks:

Use int instead of unsigned short
Don't use Hungarian naming ('kusi/usi' prefix) - nobody uses that.
Add argc/argv parameters to main
Dont import everything from std with using namespace std
Add spaces around operators (=, != , ==, >>, << etc) and after 'while', 'if' etc.
You have carefully used constants for the high/low boundaries, but your print statements  don't use these constants ("Guess a number between 1 and 100:")


Here's a stab at clarifying the intent without changing any of the functionality. I didn't try to run it or anything, so don't hold me to syntax.

# handles locking and unlocking redis for a particular operation
class RedisLock
  # thrown when a lock cannot be acquired
  class NotAcquired < StandardError; end

  # since the redis key and ms are used in pretty much every method,
  # might as well go ahead and pass them in the constructor.
  # set defaults here if there are defaults that make sense.
  # make a yardoc comment and describe what these all are.
  def initialize(redis: Redis.current, nx: true, redis_key:, expiration_ms:)
    @redis = redis
    @redis_key = redis_key
    @expiration_ms = expiration_ms
    @nx = nx
  end

  # call it with_lock instead of lock
  # to make it more apparent it accepts a block
  def with_lock!
    raise(NotAcquired, "Could not acquire lock with #{args}") unless lock
    yield
    unlock(redis_key, random_lock_number)
    true # do you really need to return true here?
  end

  def with_lock
    with_lock!
  rescue NotAcquired
    false
  end

  private

  # set instance variables in the initializer, but never call them directly.
  attr_reader :redis, :redis_key, :expiration_ms, :nx

  def lock
    redis.set(redis_key, random_lock_number, nx: nx, px: expiration_ms)
  end

  # number is a little decieving here when you call `.to_s` at the end.
  # can you use SecureRandom.uuid instead?
  def random_lock_number
    @random_lock_number ||= SecureRandom.random_number(100_000_000_000_000_000).to_s
  end

  # no need for this to be exposed publicly.
  # calling eval directly is usually a bad idea.
  def unlock
    redis.eval(redis_check_and_delete, [redis_key, random_lock_number])
  end

  def redis_check_and_delete
    <<-LUA
      if redis.call('get', KEYS[1]) == KEYS[2] then
        redis.call('del', KEYS[1])
      end
    LUA
  end
end

And to call it:

RedisLock.new(redis_key: 'key', expiration_ms: 10000).with_lock! { do_something }


Bearing in mind that I don't know much Swift...

Your Rank enum could save you a lot of typing if you simply made it a plain old autoincrementing integer enumeration:

enum Rank: Int {
    case Ace = 1, Two, Three, Four, Five, Six, Seven,
    Eight, Nine, Ten, Jack, Queen, King, __EXHAUST
}

extension Rank: ForwardIndexType {
    func successor() -> Rank {
        switch self {
        case .__EXHAUST: return .__EXHAUST
        default: return Rank(rawValue: self.rawValue + 1)!
        }
    }
}

extension Rank: Printable, DebugPrintable {
    var description: String {
        get {
            switch (self) {
            case .Ace: return "Ace"
            case .Jack: return "Jack"
            case .Queen: return "Queen"
            case .King: return "King"
            default: return self.rawValue.description
            }
        }
    }
    var debugDescription: String {
        get { return self.description }
    }
}

for i in Rank.Ace ... .King {
    print(i)
}

When testing out this code, please notice that the Printable protocol doesn't work in Playgrounds at the moment.

Also, of course, shuffling the deck 3 times doesn't make the order of the cards any "more random" than shuffling the deck once. But you probably know that, since you went to the bother of implementing copying a correct shuffling algorithm.

To add jokers, the most "C-like" approach would be to add Suit.Joker and Rank.Joker and leave Card alone.
The most "functional-programming" approach would be to change Card from a struct to an enum with a special case for jokers:

enum Card {
    case Regular(Rank, Suit)
    case Joker
}

var c = Card.Regular(.Ace, .Spades)
var j = Card.Joker


Excel VBA code that displays a 14 day weather forecast

The real question here is how to get only the p tags with a data-testid with the value of wxPhrase. This can be done using querySelectorAll().

Document.querySelectorAll("p[data-testid='wxPhrase']")

See Document.querySelectorAll().
You will need to add a reference to the Microsoft HTML Object Library and declare you document variable as HTMLDocument.

Dim Document As HTMLDocument

Loading the values into an Array will offer you the best performance.  It will not make a noticeable difference if you return 10 days or all the days of the month.
Refactored Code
Sub MiamiWeather()
    Dim Data As Variant
    Data = MiamiWeatherData

    Range("A1:B1").Value = Array("Date", "Tempature")
    Range("A2").Resize(UBound(Data), 2).Value = Data

End Sub

Function MiamiWeatherData()
    Const URL = "https://weather.com/weather/tenday/l/3881cd527264bc7c99b6b541473c0085e75aa026b6bd99658c56ad9bb55bd96e"
    Dim responseText As String
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", URL, False
        .send
        responseText = .responseText
    End With

    Dim Document As HTMLDocument
    Set Document = CreateObject("HTMLFILE")
    Document.body.innerHTML = responseText

    Dim Children As IHTMLDOMChildrenCollection
    Set Children = Document.querySelectorAll("p[data-testid='wxPhrase']")
    Dim Results As Variant
    ReDim Results(1 To Children.Length, 1 To 2)
    Dim r As Long

    For r = 0 To Children.Length - 1
        Results(r + 1, 1) = Children(r).PreviousSibling.PreviousSibling.FirstChild.innerText
        Results(r + 1, 2) = Children(r).PreviousSibling.FirstChild.innerText
    Next

    MiamiWeatherData = Results
End Function


CodingBat warm up: conditionally prepending "not" to a string

It should be obvious which strategy is better. Suppose you are given a very long string. Do you really want to search the entire string for "not", then realize that the match is irrelevant because it doesn't occur at the beginning?  Or would you rather just examine the first three characters of the string?

Of course, the most straightforward solution uses .startsWith():

public String notString(String str) {
    return str.startsWith("not") ? str : "not " + str;
}

I don't know why they gave a hint to use .equals(). It's also a bit unclear how a string like "notary" should be handled. Treat these tutorial-challenge sites with some suspicion.


Copy autodiscovery results from list to an array

You certainly can! You're currently coding using the "arrow pattern" it's often nicer to return early rather than keep indenting further and further as you nest conditionals.

if (findResponse == null)
{
     return new EndpointAddress[0];
}

Now let's make the rest of the method shorter:

public static EndpointAddress[] Find()
{
    var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
    var findResponse = discoveryClient.Find(
        new FindCriteria(
            typeof(ICommunicationService)));

    if(findResponse == null)
    {
        return new EndpointAddress[0];
    }
    return findResponse.Endpoints.Select(endpoint => endpoint.Address).ToArray();
}

But, we can go further. You should prefer returning interfaces rather than concrete representations. Do you need indexed access to the EndpointAddresses? I doubt it, return IEnumerable<EndpointAddress> instead:

public static IEnumerable<EndpointAddress> Find()
{
    var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
    var findResponse = discoveryClient.Find(
        new FindCriteria(
            typeof(ICommunicationService)));

    if(findResponse == null)
    {
        return Enumerable.Empty<EndpointAddress>();
    }
    return findResponse.Endpoints.Select(endpoint => endpoint.Address);
}

You could also inject the DiscoveryClient into the classes constructor but as it is a static method and I don't know what the rest of the class looks like, I'll leave that point for now.


Couple of pointers. You are mixing data notation and fluent mapping.
replace NotMapped attribute with .Ignore fluent mapping.
Also I think its cleaner to move each entity into its own mapping config class using IEntityTypeConfiguration<T>
Dont mix DTO and entities like that. Best practice is to project your entities to DTOs.


To steal an old quote: "There are 2 hard things in computer science. Naming, cache invalidation, and off-by-one errors".

That being said, there is room for improvement here. Firstly, I'm assuming the class name, PPM, is short for Portable Pixmap Format. However, this isn't immediately obvious, and if you aren't familiar with that format (I'm not), it required a search. Hence, the first thing I'd do is change the name to something a bit more descriptive, and add a docstring explaining something about the format:

class PortablePixmap(object):
    '''A class encapsulating basic operations on images that use the
       portable pixmap format (PPM).

    '''

Python itself has a style guide known as PEP8 that you should try to follow as much as possible. Generally the convention in python is to name ClassesLikeThis, methods_like_this, and variables_like_this. Hence, another change I'd make is to rename infile and outfile to in_file and out_file respectively.

Continuing on, the first comment under __init__ is fairly obvious:

#Read in data of image
data= open(self.infile,"r")
datain=data.read()

As a minor aside, try and keep the whitespace around operators like = consistent. Again, as per PEP8, these should be:

data = open(self.infile, "r")
data_in = data.read()

I'd also consider renaming data_in to something like raw_image_data.

Back to the comments. The next line has no comment, but needs it far more than the previous 2 lines:

# Break up the image data into 4 segments because ...
splits = datain.split(None, 4)

The comment #(Return a new array of bytes) is both obvious and misleading: this is __init__; you're constructing the object - assigning to self.pixels isn't returning anything!

For grey_scale, your indentation moves to 8 spaces instead of 4. Be careful with this - especially in Python, where whitespace can modify the semantics (meaning) of your program. This function should again have a docstring:

def grey_scale(self):
    '''Converts the supplied image to greyscale.'''

The final function, def writetofile(self): should again use _ as separators
to make it easier to read. I'd also probably move the out_file parameter to this function, rather than passing it in __init__:

def write_to_file(self, output_location):
    '''Writes the image file to the location specified output location.
       The file is written in <some description of the file format>.

    '''

Watch the length of your comments (they should stick to the same line lengths as everything else in your program).

#Use format to convert back to strings to concatenate them and Those {} in the write function get's replaced by the arguments of the format function.

The comment itself is also difficult to understand:

  "convert back to string to concatenate them and Those {} ..."

That made me do a double take. Try and write comments as complete sentences.


First things first: You have a navigation but refuse to use anchor tags. Why? This is potentially harmful. How are you going to navigate if you don't have links? The only possible way would be completely relying on JavaScript. All users with disabled JavaScript have a useless list of words instead.

HTML:

Use a tags instead of the div's in your HTML (Use <a href="#"> to test this)
I'd suggest using classes instead of ID's in this scenario as well. The lower specificity of classes will ease your live later. Overwriting an ID instead could be hard

CSS:

If you use actual links for your navigation, there is no need for cursor: pointer; on list-items.
If you want the icons to be clickable as well, add the pseudo-elements to the links instead of the list-items
Don't reset the general styling for lists on the type selector ul. Doing this makes you unable to use lists as regular lists in text etc. You can reset the styles for the navigation on #accordion
Adding a class accordion-item to your list-items could help you. You don't selecting like this: #profile:before, #messages:before, #settings:before...

You have some things to consider now. There are more things to improve, but I'd like to see a new question for an updated navigation with the given advice.


First of all, nice effort for the code. But I highly go against it because there's jQuery. And if you don't like jQuery because it's heavy, then I suggest going for Sizzle.

But anyways, back to your code. First I notice this one:

var optionalSelector = "$";

Never use $. It's being abused already by frameworks. Use another namespace to avoid collisions with mainstream libraries, something unique, like MyVeryAmazingDomLibrary or MVADL for short. Hehehe.

Also, I notice this namespace declaration happens to be outside the library. Do include it inside the library's module:

;(function(window){
  ...
  window.myNamespace = myLibraryStuffHere;
  ...
}(window));

So far, your code looks ok. Everything is pretty much covered. I also see that it works only with single selectors at the moment. However, I notice you are using replace to remove the # and .:

document.getElementById(input.replace(/#/, ""));

RegExp is heavy for trivial operations such as this. You can remove the first character using substr or substring. That way, you avoid RegExp.

document.getElementById(input.substr(1));

Now, in the demo, I see this:

a[0].onclick = function() { alert("you clicked the classes"); }
a[1].onclick = function() { alert("you clicked the classes"); }

If you had a hundred elements, would you do this still? I assume you'd do a loop, right? But wouldn't it be neat if the library took care of that? Yes?

So there's a reason they call it a "jQuery object". jQuery objects are basically arrays (array-like to be exact, normally called a set or collection) that applies operations to each item in the collection.

So to get you on the right track, think of this code:

a.on('click',someFunction);

a is the jQuery object, and on is a method of jQuery that attaches a click handler to each item in set a. on would look like:

myAmazingLibraryObject.prototype.on = function(event,handler){

  //assuming "this" represents the current collection and "elements"
  //is an array of elements, a result of getting by tag or by class.
  //Let's say we are standards compliant and ES5 compliant,
  //we use forEach to loop through the set, and addEventListener to
  //add the handlers.

  this.elements.forEach(function(element){
    element.addEventListener(event,handler,false);
  });
}

Now, you can do this:

var elements = myAmazingLibrary('a'); //get all <a>

elements.on('click',function(event){
  event.preventDefault();
  console.log('clicked');
});

An advantage of using a jQuery-like object, where the results are contained in an array, is that even when your collection is empty, the code does not break. If we used on on an empty collection, nothing will go wrong. Empty set, no loop, no element access, no error.

Lastly, don't just console.log or return false on errors. Throw meaningful errors instead. Use Error objects so that try-catch can collect them and inspect them. The last thing you would want from your code is to have it running broken and not know about it.


There has already been some discussion by @Oh My Goodness and @Blindman67 in the comments about the time complexity of this code vs Fisher-Yates. I don't really have much to add to that discussion but will offer some suggestions about the code on a deeper level below.

Like I mentioned in my answer to your post Simple math game in JavaScript some variable names could more accurately hint at the semantic meaning of the value - for example, instead of x.ran = Math.random();, a name like sortVal would hint that the value is to be used for sorting.

array.forEach( x =>{
  x.sortVal = Math.random();
})

The arrow function in the shuffle() method is quite short and thus can be simplified to a single line:

array.sort( (a, b) => a.sortVal - b.sortVal)

The forEach block above it could also be simplified:

array.forEach( x => x.sortVal = Math.random())

In this case, x.sortVal would be returned in each iteration but that doesn't make a difference.

The Array sort method Array.prototype.sort() returns the array so the shuffle() function could be simplified to have the return statement on the same line as the call to that method:

  return array.sort( (a, b) => a.sortVal - b.sortVal)

Additionally, any value that doesn't get re-assigned could be declared using const, which would help avoid any unintentional re-assignment - e.g. deck within shuffle(), and deck at the end of the code.


Project Euler # 55 Lychrel numbers in Python

I like the functions you've divided up work. Good job.

def is_palindrome(number):
    """returns True for a palindrome, False otherwise."""

Its a little nickpicky, but the pep on docstrings recommends

  The docstring is a phrase ending in a period. It prescribes the
  function or method's effect as a command ("Do this", "Return that"),
  not as a description; e.g. don't write "Returns the pathname ...".

I would change the docs here to something more like

"""Return whether a number is the same if read backwards and forwards."""

last_number = reverses[-1]
new_number = int(str(reverses[-1])[::-1])

Since last_number is reverses[-1], use it. Saves a lookup.

last_number = reverses[-1]
reversed_number = int(str(last_number[::-1]))

if is_palindrome(last_number + new_number):
    reverses.append(last_number + new_number)
    return reverses
else:
    reverses.append(last_number + new_number)

Since you have the same code in each path, and nothing before it, you can hoist it up out of the if statement

reverses.append(last_number + new_number)
if is_palindrome(last_number + new_number):
    return reverses

for _ in range(count):
    ...
    if ...:
        return reverses
    ...
return reverses

+1 for using _ as the loop variable.

This is again nitpicky, but since you have an opportunity to make this code only have one return point, why not take it?

for _ in range(count):
    last_number = reverses[-1]
    new_number = int(str(reverses[-1])[::-1])

    reverses.append(last_number + new_number)
    if is_palindrome(last_number + new_number):
        break

return reverses

def count_lychrel_range(number_range, count):
    """returns Lychrel numbers within number_range, assumes count is the maximum iterations for a number."""

Except it takes the upper bound of the range, not a number range. The doc clears it up, but just looking at the method signature I would assume you pass in the list of numbers to iterate over or a range. Since the expected call is not

count_lychrel_range(range(500, 1000), 50)

I would suggest changing the names here

def count_lychrel_numbers(upper_bound, max_iterations):

Since you only care about the length of the list, why go through all the effort of building a list of intermediate numbers from the process? In fact, you only need the length so you can compare it to the maximum number of iterations to run. Doing the test means we can just return a yes/no answer, rather than an entire list of numbers.

I think something like this inplace of add_reversed would be a little nicer.

def is_lychrel(number, max_iterations):
    """Return whether a number is a lychrel number.
    A lychrel number is one which becomes a palindrome when it is repeatedly reversed and added to itself."""
    for _ in range(max_iterations):
        reversed_number = int(str(number)[::-1])
        number += reversed_number
        if is_palindrome(number):
            return True
    return False

Then count_lychrel_numbers can be a simple loop

def count_lychrel_numbers(upper_bound, max_iterations):
    """..."""
    total = 0
    for number in range(upper_bound):
        if is_lychrel(number, max_iterations):
            total += 1
    return total

Or if you want to use sum

def count_lychrel_numbers(upper_bound, max_iterations):
    """..."""
    return sum(1 for number in range(upper_bound) if is_lychrel(number, max_iterations))

As a bonus, you can see that "new_number" is reversed twice. Once in is_palindrome and once in add_reverses/is_lychrel. Can you reduce it down to just one reverse without bloating the code?


What is the best way to get the child class name for use in a parent class

Looks fine to me; though somethings to think about. Do you need to run get_class? Or might it be better to have a model variable in the child class

class Blog extends Controller
{
    private $modelClass = 'Blog';
}

The overhead of get_class might be small, but probably more than a variable; but this way also give you the ability of being able to use the same model with multiple controllers if you need to. Granted you could just inherit with the models too, but that would mean 2 includes instead of one.

If you don't go that route, consider some validation, string tidying or consistency in your model/file names.

$path = 'models/' . $name . '_model.php';

will likely equal Blog_model.php but your class is Blog_Model see the mixing of cases; consider Blog_Model.php or doing a strtolower($name). This might seem minor, but different Operating Systems handle case differently and I have been bitten by this exact issue.

I noticed you are doing a require rather than a require_once which could lead you to have cannot re-declare class errors. if require_once isn't for you consider

if(!class_exists($modelName))

This might seems abstract at the moment, but when I came to upgrade an admin system for a custom CMS I found it really handy for the admin Controllers to wrap the frontend wesbites controllers, and adding a little checking could greatly increase your flexibility further down the road.

If you haven't done already check out __autoload http://php.net/manual/en/language.oop5.autoload.php if might be more overhead, but it is just so handy I really miss it on legacy projects.


Using method trait to return something in laravel model

I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice?

This is because laravel is handling "it" for you.

getSelect2Format is not the best name since you are not handling formatting but apply a specific set of rules relevant to select2 js plugin.

I would suggest a repository class or a helper class to handle this task.

Your code is messy, very long lines too, which is hard to read! I would suggest following PSR-12.

I would suggest using response() or just return $data in controller class methods.

I would also suggest early returns in your methods to reduce nesting hence easy reviewing by reviewers.

suggest not using ->get() in a method unless you are absolutely certain on what method should do. i.e. you might want to apply a scope to this query  later on.

I suggest passing request data into the class to make it easier to test. Also, the less your class knows about other parts of the system the better.

Dont you have to use DB::raw for $column.' as text'?

class select2Filters
{
    public static function apply(
        Model $model,
        array $data,
        string $column = 'name',
        int $limit = 5
    ) {
        $filter = Arr::get($data, 'filter');

        return $model::selectRaw(['id', "{$column} as text"])
             ->where($column, 'like', "%{$data['q']}%")
             ->when(is_array($filter), function($query) use ($filter) {
                 $query->where(Arr::only($filter, $model::filterable));
             })
             ->orderBy($column, 'asc')
             ->limit($limit)
             ->get();
    }
}

I would also suggest adding an interface to each model that should have support for select2Filters. That interface should inforce filterable variable.
I would personally not use static, that way you can add configuration methods, i.e. setLimit(). OR use data struct class to contain data needed for select2Filters class.


I'm not much of a stream fan and your code itself seems rather good, so I'll skip directly to your architecture.
One note, through:
total += new Exotic().calculatePrice(map.get(breedType))

a += b is not shorthand for a = a + b, it is shorthand for a = (TYPE_A)(a + b). This is something to keep in mind, as it might silently truncate data, for example if a is an int and b is a float, no warning will be emitted by the compiler.

Let's sum it up:
interface Breed
    enum BreedType

interface Animal

class Cat implements Animal

What is odd here is that you have a Breed type, then decide not to use it and instead use a specialized enum for representing the breed. So what I'd rather expect would be to have a Cat which has the property Breed. Additionally, your handling of the price of a cat is odd. The cat gets assigned a price, which is then changed afterwards based on the breed, which means it really is more of a "base price" then the actual price of this cat.
So what I'd expect is the following setup:
public interface Breed {}

public class Cat implements Animal {
    public Breed getBreed();
    public int getPrice();
}

With getPrice here returning the actual price of this single cat. Or, an alternative would be to have an extra price calculator:
public interface Breed {}

public class Cat implements Animal {
    public Breed getBreed();
}

public class CatPriceCalculator {
    public int calculatePrice(Cat cat);
}

Depending on what you're trying to achieve, both solutions might be viable. But let's go with the first for now. To mimic your original code, let's implement Breed:
public interface Breed {
    // TODO Note that we do not support fractions here.
    public int getPriceMultiplier();
}

public class RegularBreed implements Breed {
    public int getPriceMultiplier() {
        return 1;
    }
}
public class ExitocBreed implements Breed {
    public int getPriceMultiplier() {
        return 2;
    }
}

This will allow us to calculate the price of a single cat by doing cat.getBasePrice() * cat.getBreed().getPriceMultiplier(). We could also map breeds as enum, similar to how you've done it:
public enum Breed {
    EXOTIC(2),
    REGULAR(1);

    private int priceMultiplier;

    private Breed(int priceMultiplier) {
        this.priceMultiplier = priceMultiplier;
    }

    public int getPriceMultiplier() {
        return priceMultiplier;
    }
}

But this has the downside that it is not extensible from the outside, as enums cannot be extended. So I'd suggest to stick with the interface for this one.
Looking again at my second suggestion to use an extra price calculator, this would have the upside that you can map the price of a single cat base on more properties, for example weight, color and so forth:
public class Cat extends Animal {
    public int getAge();
    public Breed getBreed();
    public Color getFurColor();
    public Quality getFurQuality();
    public int getWeight();
}

Now if we have an extra calculator class, all these properties can be weighted in there. Having an extra class for this might for example be necessary if we plan to support different markets. For example, a market of a cat-show will assess fur and color higher than other properties. On the other side, a meat market will assess age and weight higher than other properties. So decoupling the price calculation from your model classes might be preferable.


C++ template type traits for class members

If xxx is a non-accessible data member (e.g. private) your code fails to compile with gcc. However this seems to be gcc bug. (stackoverflow question) Still if your code is supposed to be compilable with gcc you should consider this.
The templates give false for non-accessible (e.g. private) members. That is usually good though, because someone using quering about a class should only see the public interfacce anyway. Still consider what the intended behavior of your templates should be.
If xxx is of reference type, then your has_member_xxx will give false, because taking an address to member of reference type is not allowed.
has_member_xxx is also false if xxx is a static data member with deleted or non-accessible operator&(), although this is a pathological case because I don't see a good reason to use operator&() in that way. You might want to take std::addressof instead to avoid such a case.
has_member_xxx will also not detect member function templates, because the address of a function template cannot be taken. However that is probably expected behavior.
The same issue also arises for overloaded member functions, though. The adress of overloaded function can also not be taken. This is probably not intended behavior.

If you could specify exactly what your templates are supposed to detect / not detect that would be helpful.


Mixing business logic and presentation layer in enum type

If you want to decouple Enum and presentation logic, consider using EnumMap . This type of collection is fast and key-safe.

IMO, there is nothing wrong to store short and full currency names in CurrencyType. But localized name (as well as country's flag and other visual aspects) better be decoupled and put into presentation layer. You can use short names as keys for resource bundles.

Furthermore, if all CurrencyType values reproduce currency short names, you can eliminate using dedicated private field for them and use Enum.name() instead.


Naive php web hook endpoint for use in a production environment

Only several years late, but since someone bumped the question let's actually answer it. This code does look somewhat reasonable, but it should be programmed more defensively to avoid situations where people can insert anything in your queue.
Handle all possible outputs
hash_hmac can return a string or the boolean false. You pass this directly to base64_encode, which will happily turn false into an empty string.
var_dump(base64_encode(false)); // string(0) ""

Currently, hash_hmac returns false if the algorithm is not supported. If for some reason sha256 is dropped as an algorithm, you can put anything in the queue with an empty signature. Adding an !empty($signature) check to the if-statement will allow the code to fail safely in case something odd is going on.
file_get_contents can return false on failure, and hash_hmac will happily treat this as an empty string for key generation. You could add a sanity check that fails early if you have nothing useful to add to the database.
Exceptions, try and catch
None of your functions seem to throw, except maybe for XeroWebHookHandler::insertPayloadIntoDatabase. This also means that adding a try-catch block does not do anything useful for you. If you have a way of telling if this function fails, you can move http_response_code below this function and potentially return a different response code if the function fails.


Reimplementation of Laravel's config system

Where is AP defined?  Should loadConfig just get passed a directory path as parameter rather than relying on some global constant and hard-coded path?

I would consider using SplDirectoryIterator and SplFileInfo functionality to load your config files, as this should allow to do this in a much more robust way in comparison to glob().  You could (and probably should), verify that the config directory and all files are readable to the application and throw an exception to bail out of the process if you can't load config properly.

Right now you are kind of "soft" loading the config.  include(), for example, will not halt execution if the file could not be included.  I would think execution should halt with exception thrown so that your application cannot even run if the dependencies aren't met.

Shouldn't get() be static, since that is the only context in which it makes sense (there is no instantiation of this config).

$configFiles as property name seems odd.  This is you actual configuration right?

I guess I am not a big fan of deriving some configuration "keys" from file name and some from the actual data structures in the file.  This seems a bit obfuscated to me.  Is it really that hard to put top level key in the file?

i.e. file like:

return [
    'toplevelkey' => [
        'secondLevel' => [
            'thirdLevel' => [
                ...
            ]
        ]
];

and in your loader:

self::config = array_merge(self::config, require $filepath);

This also could conceivably allow for configuration overrides from config in one file with config from other (this may or may not be desirable for you).  You would likely need to manage file load order in some manner for this, something you may not be able to do effectively with just using glob().

Consider adding helper method with get() to decouple key retrieval logic into it's own (testable) method with appropriate exception triggering to make your class less fragile to bad input. After all, if some portion of your application is expecting some config to be available and it is not what is expected, you should be failing loudly, because your dependency is not being met.

That might look like:

public static function get($keyString) {
    $keys = explode('.', $keyString);
    return self::findConfig($keys, self::config);
}

protected static function findConfig(array $keys, array $haystack, $keyString = '') {
    $key = array_shift($keys);
    $keyString = ltrim($keyString . '.' . $key, '.');
    if (!isset($haystack[$key]) {
        throw new OutOfRangeException("Config key '{$keyString}' is missing");
    }
    if(count($keys) === 0) {
        return $haystack[$key];
    }
    if(!is_array($haystack[$key]) {
        throw new UnexpectedValueException("Expected array value at key '{$keyString}'");
    }
    return self::findConfig($keys, $haystack[$key], $keyString);
}

This approach to use recursion to find a key in your config also unbounds you from your current hard-coded limit of only having 3 key segments.

Consider providing better validation for parameters passed to public methods.  For example, validate get() input is non-zero length string.  Particularly with something as critical to application operation as configuration, you want to take reasonable measures to make sure the class and its data are set up in an appropriate state and that other areas in application are interacting with it in a proper manner.


You can do this with str.translate, which was changed slightly in Python  3. All you need to do is pass it a translation table, and it'll do what your above code is doing. However to build the translation table is hard in Python 2 and requires the helper function string.maketrans, which was changed to str.maketrans in Python 3.

But here is how you'd use it in Python 2:

>>> import string
>>> trans = string.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'

And here is how you can use it in Python 3:

>>> trans = str.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'
>>> trans = {ord('A'): 'T', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'

You can re-implement this yourself, but the above is written in C, and so should out perform any Python code.


"Factory" which produces a "connection" object

Firstly your code lacks any comments saying what it does and why.  When I first looked at your post I assumed it was a TCP socket class and was looking for the port number.  Also the layout could be improved, regular blank lines, etc.

I would do this:

public void Mark_Connection_as_Successful()
{
    Mark_Connection_as_Successful(Last_Connection_Trying);
}

just like you have with Build.  At the moment they are trivial functions, but that might not always be the case.

Would it be appropriate to verify the format of the connection string, or is this done in the OracleConnection constructor?


Use loops!

odd_nums = []
for i in xrange(10):
    value = int(raw_input('Enter an integer: '))
    if value % 2 != 0:
        odd_nums.append(value)

if len(odd_nums) != 0:
    print max(odd_nums)
else:
    print "No odd values"

How to read this line:

for i in xrange(10):

This line means starting at 0 (the default starting point for xrange()), and ending at 10-1 (upper bound is not included), execute the following code with i set to the current iteration of the loop. This executes the code exactly 10 times (i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9).

The rest was made as similar to your code as possible, and so should be understandable.


Welcome to Code Review. While your script works as is, it is a good practice to setup and split parts of code into functions, and place the entry point inside the if __name__ wall.

You have an extra conversion to int for productsnm (which could be better named product_count).

Since each product is associated with its own quantity, say hello to a namedtuple:

from collections import namedtuple
Product = namedtuple('Product', ['name', 'quantity'])
# inside the for-loop:
    products.append(Product(name=product_name, quantity=quantity))

You wont need the string manipulation, or the loop. Just printing out the products list should give you something like

[Product(name='n0', quantity=0), Product(name='n1', quantity=1), Product(name='n2', quantity=32)]

Each element of the list now has name and quantity as its property as well.

You can have multiple functions as follows:

gather_products_list which returns a list of N products.
generate_email_body to process the products provided to the function and generating the raw email body.
send_email which accepts the aforementioned raw body, and sends it via the provider of choice.
get_integer which repeatedly asks the user to input an integer value. This function could accept an optional prompt message as well as an error message!


Though I didn't check the whole program and, according to you, performance is good enough, I do have one performance related suggestion:

avoid int64(math.Abs(float64(var1-var2))). Casting between int and float types is not free. Just read about Two's complement for ints and how floats are represented in the IEEE 754 standard. That conversion is not trivial!

As Go (as far as I know) doesn't have an abs method for int-like types, this may provide inspiration on how to calculate the abs for signed ints.


PHP function for encrypt / decrypt using openssl

I haven't looked at the security aspect of this, so you might want to wait for answers on that aspect.

Function Design

Your function does too many things (encryption and decryption), making it harder to read than necessary and hard to use.

At a minimum you would need to document it properly, as otherwise, users would need to look at the actual code to use it, which isn't ideal.

But really, it will be much simpler to have two functions:

function afz_encrypt($plaintext) {}
function afz_dencrypt($ciphertext) {}

If you don't want to duplicate the encryption parameters, saving those in the class may be a good idea.

I would also pass the key to the function instead of hardcoding it in the function itself.

Return values and error handling

The return values do not seem that well defined. The function returns:

false if an invalid action is given
false if it can't base64 encode on encryption
the base64 encoded iv if it can't encrypt (meaning the input is lost).
the encrypted input string if it can't decrypt (and this happens without any warnings by PHP).

There are probably more irregularities, but I think the point is clear: A user cannot figure out what exactly went wrong, and sometimes cannot even tell that something went wrong, which will sooner or later lead to bugs.

You should throw exceptions on invalid input stating what exactly went wrong (eg wrong action, cannot base64 decode, etc), and check the output of all the functions you use.

Invalid Output

why stripslashes? It means that decrypt(encrypt(plain)) != plain in some situations (eg foo'bar, a\b, etc).
Also, decrypt(encrypt([empty string])) != [empty string] and decrypt(aaaaaaaaaaaaaaaaaaaaaaa) = aaaaaaaaaaaaaaaaaaaaaaa because of the issues outlined above.


This query looks very nice and clean. I can't see any obvious or glaring issues here, I do have some ideas for improvement though:
Naming
a, u, q and p are not all that "expressive" aliases. There is no need to shorten these aliases to be incomprehensible for people outside the SE-System, that don't understand how Posts a is different from Posts q
Select X
How about also making the number of results variable?
SELECT TOP ##topX:int?100##

allows the user to decide how many results they want.
CTE's
Last time I checked, Data Explorer supported CTE's. Make use of them:
WITH Zombies AS (
     SELECT q.Id ZombieId, MAX(a.Score) MaxAnswerScore
     -- ...
)

SELECT ##topX:int?100## FROM Zombies


You can use much simpler algorithm in python:
Transpose matrix:

zip(*matrix)

Inverse rows in transposed matrix (equals rotation right):

list(list(x)[::-1] for x in zip(*matrix))

However, if you want to rotate left, you need first inverse rows and then transpose, which is slightly more code.


Improving excution time for list and sampling in Python

I have changed sampling part and it took only 19 sec. I have realized that numpy's random sampling is way faster than python's built-in random sampling.

import pickle
import numpy as np
from numpy.random import randint, rand, choice

def gen_edge_list(a, c, n):
    """
    Generate edge list based on 14.1.1
    """
    edge_list = np.zeros(c*n)
    p = float(c) / (float(c)+a) # % for preferential attachment edges
    edge_list[0] = 1            # edge from vertex 2 to 1
    idx = 1                     # point to the next index
    for t in range(3, n+1):
        print t
        if t <= c+1:
            """
            If network size is smaller than c+1,
            connect among all vertices.
            """
            edge_list[idx:idx+t-1] = [i for i in range(1, t)]
            idx = idx+t-1
        else:
            """
            decide preferential attachment or uniformly random attachment
            by given p
            """
            n_pref = np.sum(rand(c) < p)
            edge_list[idx:idx+n_pref] = choice(edge_list[0:idx-1], n_pref)
            idx += n_pref
            edge_list[idx:idx+c-n_pref] = randint(1, t+1, c-n_pref)
            idx = idx + c - n_pref


Refactor Ruby code from Hacker News API. Trouble parsing the JSON data

Redundant operations
After reading the data from the web service, you go over it a number of times, which seems redundant:

results = parsed.reject { |key, value| key != "results"}

Why is that important? You go over the whole JSON, and discard everything - but you gain nothing. Simply use only what you need, no need to actively remove it.

pull_items = []
pull_items = results["results"].each do |items|
  pull_items << items
end

This is simply a very convoluted way of saying pull_items = results['results']...

pull_info = []
pull_items.each do |x|
  pull_info << x["item"]
end

Ruby's idiomatic way of saying the same thing is pull_info = pull_items.map { |x| x['item'] }

@stories = pull_info.map do |s|
  News.new s["title"], s["url"], s["username"]
end

If this is what you actually wanted, you don't really need all the temporary artifacts in the middle - simply do it in one swoop:

@stories = results['results'].map do |r|
  item = r['item']
  News.new item['title'], item['url'], item['username']
end

Naming Conventions
It is conventional in ruby to name getters by the name of the member, without the get_XXX. For that convention, there is even a shortcut - attr_reader. So, instead of writing def get_url you should do:

class News
  attr_reader :url
  ...
end

@link = @stories[@counter].url

and it will just work...

Code Encapsulation
A ruby file should contain a single class. It should not contain any floating methods.
Actually, there should not be any floating methods. Create a different class, or a module, which will contain the show_story, shuffle, and next_story. This will also force you to name the module, and make it more obvious what is its role in your application.


Nice improvement is to use Enum with behaviour. This is an example from Effective Java book :

public enum Operation {
    PLUS("+") {
        double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS("-") {
        double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES("*") {
        double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE("/") {
        double apply(double x, double y) {
            return x / y;
        }
    };
    private final String symbol;

    Operation(String symbol) {
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return symbol;
    }

    abstract double apply(double x, double y);
}


Top k closest pairs in a set of million 128-dimensional points

First, cut your work load in half.  You only need to consider pairs where i < j, so:

for i in range(M-1):
    for j in range(i+1, M):
        # ...

If you actually need both (i, j) and (j, i), then you only need the 50 million closest pairs, and can duplicate & swap every pair in the list as the last step.   More savings!

Record & sort the first 100 million (50 million?) pairs.  Then, as new pairs are generated, if closer than the worst stored pair, use bisect.bisect() to find insertion spot, add the new pair, and kick out the worst pair.

Time: \$O(n^2 log k)\$,
Space: \$O(k)\$, n is number of points, k is desired number of pairs.


As you mentioned, by calling np.vectorize on your monte_carlo function and applying it to your dataset b, you are essentially running a for loop over each element individually.

np.random.noncentral_chisquare takes either a float or an array of floats for its noncentrality parameter, so you could vectorize your function call by generating your entire distribution in 1 call then applying the rest of the function to the entire matrix at once.

def monte_carlo2(x, tot_sample):
    gen_dist = np.random.noncentral_chisquare(df=1, nonc=x, size=(x.shape[0],total_sample))
    compare = gen_dist > x
    return np.divide(np.sum(compare, axis=1), tot_sample)

x2 = monte_carlo2(b, total_sample)

This passes your f_res data in as a vector, b, instead of 1 element at a time, generates a distribution with nonc= [b0, b1, b2, ..., bN]. This results in a gen_dist matrix of size (625527, 10) or (len(b), total_sample). b is a vertical vector, so the comparison will apply it across each row, then you just need to sum your comparison over each row (axis=1).

You could probably speed it up more by only generating one distribution per unique value of f_res, but depending on what percentage of your values are unique this may not be worth it, and I assume you want a new random sample each time.

With your original function I get a timeit of:

  15.2 s ± 125 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

And with the vectorized version I get:

  8.84 s ± 50.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


Dataset with optional addition to where statement

This:

+ "where s.Version = ms.CurrentVersion and scr.TargetType = 1 "
+ conditional
+ "order by svce.PeripheralNumber, ms.EnterpriseName, p.EnterpriseName";

Is poison.

conditional came from a string concatenation that involves a parameter string that the method cannot trust:

conditional = "and svce.PeripheralNumber= " + parameter.ToString() + " ";

..Uh, the ToString() call is superfluous here, parameter is already a string! ;)

Looking at the code in your other question, this is where the parameter came from:

string value = this.ValueTextBox.Text;

That is what you shouldn't be doing: concatenating user input into an SQL statement is asking for trouble, whether it's a web or a desktop application doesn't matter, SQL Injection is SQL injection. Not to mention that you just put the calling code in charge of knowing the types for all columns that might be used, whether or not the values should be enclosed in single quotes, etc.

You need to use a parameterized query instead.


Kill dead instances of Excel on a server

Your code appears to be correct - however, this can be dangerous because it will kill ALL instances of Excel that are running so you run the risk of killing one of your currently running legacy programs.  There are proper ways to clean up Excel resources - see my question here for a C# version.  Do you have any ability to update the legacy programs?  If so, I would recommend that over this.


A suggestion that may help is to make generators of loops in import_file_list and import_data.
This is more memory efficient on the intermediate steps and defers building the dataframe until the end.

def import_file_list(file_name):
    with open(file_name) as f:
        for row in f:
            yield row.strip()

def import_data_to_dfs_iter(list_of_files)
    for item in list_of_files:
        yield pd.read_csv(
            item, sep='|', usecols=['A', 'B', 'C'], compression='gzip')

def main():
    dfs_iter = import_data_to_dfs(import_file_list(sys.argv[1]))
    df = pd.concat(dfs_iter)


Dining Philosopher's problem implementation with Java Locking Framework to avoid deadlock

Your implementation is minimalistic but it does what it does and it does it good.

Your code consists basically of three elements:

Setup the place
Logging actions of the philosophers
Handling philosopher behaviour

1 and 2 are not that interesting as they may differ slightly from implementation to implementation. And in general you did not reach a code mass to address any modularization issues.

Number 3 is the part I want to address. You chose the egoistic variant of the dining philosophers. A philosopher may face starvation if other philosophers keep taking the forks in unfavorable point of times.

Another variant is cooperative. You have to introduce one more artefact to do so. Philosophers may give aquired forks directly to their neighbors if they registered for usage of a fork while the fork itself is currently unavailabe. This prevents a philosopher from releasing the fork and aquiring it again immediately so other philosophers have no chance to introduce themselves in the process.


Here are some things that may help you improve your code.

Simplify the code

This seems to be rather a lot of lines of code for a very simple game.  For example, the ask_guess and play_again both do essentially the same thing.  They show a prompt, wait for input and then check to assure the input is one of the valid choices.  Since it's done for two different things and has both associated data and functionality, that suggests an object.

Simplify winner detection

Each player has only three choices, and if we take them in the order of "rock, paper, scissors" then for any choice n, the choice n+1 wins, choice n-1 loses, and n means a tie (obviously this is all mod 3).  This allows for very simple mathematics to determine the winner.

Make all strings named constants

If you ever wanted to make, say, a German version of the game, it would be simple if all of the strings were in one location.  If they're all const, then it doesn't have much impact on the runtime speed and there really aren't that many strings.

A proposed alternative

Here's an alternative that incorporates all of these suggestions:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>
#include <cctype>

class Menu {
private:
    const std::string prompt;
    const std::vector<std::string> choices;
    const std::string error_msg;
public:
    Menu(const std::string &prompt_string, const std::vector<std::string>& items, const std::string &err_msg)
    : prompt{prompt_string},
      choices{items},
      error_msg{err_msg}
    {}
    size_t size() const { return choices.size(); }
    const std::string& operator[](int i) const { return choices[i]; }
    size_t get_choice(std::istream& in=std::cin, std::ostream& out=std::cout) const {
        bool first = true;
        auto it = choices.end();
        do {
            if (!first) {
                out << error_msg;
            }
            out << prompt;
            std::string result;
            std::getline(in, result);
            std::transform(result.begin(), result.end(), result.begin(), [](unsigned char ch){ return std::tolower(ch);});
            it = std::find(choices.begin(), choices.end(), result);
            first = false;
            in.clear();
            in.ignore(in.rdbuf()->in_avail());
        } while (it == choices.end());
        return std::distance(choices.begin(), it);
    }
};

int main() {
    const Menu rps{"Enter your choice, rock, paper, or scissors: ",
        { "rock", "paper", "scissors"}, "Not valid input.\n"};
    const Menu again{"Do you want to play again? [y/n]: ",
        {"y", "n"}, "Not valid input.\n"};
    const std::vector<std::string> results{
        "It's a tie!", "You win!", "You lose!"};
    const std::string title{"\n\n\tRock Paper Scissors Game\n\n"};
    const std::string youchose{"\n\nYou entered: "};
    const std::string computerchose{"\nComputer chose: "};
    std::mt19937 engine{ std::random_device()() };
    auto dist = std::uniform_int_distribution<>(0, rps.size()-1);
     // Game loop
    do {
        std::cout << title;
        const auto user = rps.get_choice();
        const auto computer = dist(engine);
        std::cout << youchose << rps[user]
            << computerchose << rps[computer] << '\n'
            << results[(user + rps.size() - computer) % rps.size()]
            << "\n\n";
    }
    while(!again.get_choice());
}


Processing a large number of files in a folder

You could use Directory.EnumerateFiles to allow processing of each path without loading all the paths to memory.
It is not required to check if the file exists because you just checked that (getting the path with GetFiles).
Instead of implementing your own ReadTextAsync, just use File.ReadAllText.
There is no need to use a new synchronization context (async call) for each file. If you want to process the files in the background, it is better processing all files in one single Task than using one task for each file. Remember that each context switch produces a little overhead.
If you want to use an async API that way, consider using ConfigureAwait(true) to avoid context switches:

await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(true)

I suppose the following code will do the same faster and with less memory consumption:

static async Task ProcessRead()
{
    await Task.Run(() =>
    {
        IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory");
        int count = 0;
        foreach (string fname in fileEntries)
        {
            try
            {
                count++;
                string text = File.ReadAllText(fname);
                    Console.WriteLine(text);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        Console.WriteLine(count);
    }
}


I went full performance here, so no forEach and such.
The idea is to use associative arrays and assume they cost O(1) for speed improvement. The steps of this algorithm:

For each number, store the index of the array it first appeared on.
For repeated numbers, we have intersections. As resolving the intersection right now is not performant (we might have more intersections later), we will just mark the current array and the array that number first appeared on as neighbors.
After all this preprocessing, we are ready to solve the problem. What we are left with is a graph, where a node is an array inside input. For that node, we have stored its inmediate neighbors, which represent the other arrays that also had a common number with it.
Now we do a standard DFS to iterate over all direct and indirect neighbors of a node, where we keep adding the numbers of each of those nodes to the group we are making.

The most expensive part of the algorithm is the sorting, which I´m not sure if you needed it. If you do not care about order, no need to sort them. The important part is that we only add each number to the result array once, and we process each number once, so except for the sorting, the complexity should be linear on the amount of numbers in input.

const input = [[1, 17], [3, 5], [5], [1, 3], [7], [2], [9, 8], [7, 2]];

function merge(input) {
    var numberGroup = {}
    var neighbors = new Array(input.length); // direct intersections
    var processed = new Array(input.length); // for the dfs

    for (var arrayIndex = 0; arrayIndex < input.length; arrayIndex++) {
        var array = input[arrayIndex];
        neighbors[arrayIndex] = {}; // we don´t use [] because we don´t want to keep repeated neighbors
        processed[arrayIndex] = false;

        for (var i = 0; i < array.length; i++) {
          var number = array[i];

          if (numberGroup.hasOwnProperty(number) == false) { // haven´t seen the number before
            numberGroup[number] = arrayIndex; // we mark its first apparition
          } else { // we connect the node with the one where this number appeared for the first time
            var neighbor = numberGroup[number];
            neighbors[arrayIndex][neighbor] = true;
            neighbors[neighbor][arrayIndex] = true;
          }
        }
    }

    //inline function, could be taken outside and pass input , processed and neighbors
    function makeGroup (index, group) { // dfs
      if (processed[index] == false) {
          processed[index] = true;

          for (var i = 0; i < input[index].length; i++) {
            group[input[index][i]] = true; // we only care about key, so we put value true but could be false
          }

          for (var neighbor in neighbors[index]) makeGroup(neighbor, group)
          return true; // this makes a new group
      }
      return false; // this does not make a new group
    }

    var result = [];

    for (var i = 0; i < input.length; i++) {
      var group = {};
      if(makeGroup(i, group)) {
        result.push(Object.keys(group).map(Number).sort((a, b) => a - b)); // pass the keys to an array and sort it
      }
    }

    return result;
}

console.log(merge(input));


I think the easiest way to solve this is to first calculate how many steps it takes to go from from to to, and then just build an array of that many elements. That also has the advantage that you can reserve the right amount of elements in the vector up front. You also have to make sure that step has the correct sign.
if (from <= to != step > 0)
    step = -step;

size_t distance = std::abs(to - from);
size_t stepsize = std::abs(step);
size_t nsteps = (distance + stepsize - 1) / stepsize;

std::vector<int> range;
range.reserve(nsteps);

for (size_t i = 0; i < nsteps; ++i)
    range.push_back(from + i * step);

You also might want to add some check that step is not zero.


What do you think about this usage of for loop in JavaScript?

As you can see second parameter is very atypical as for for loops

Which is why it shouldn't be a for loop, because as you write yourself(!) "[it] is a perfect case for while, or do..while loop". Saving a few lines of code and variable scope is not a good reason to obscure the code. You will (or should) be losing any perceived time/line benefit in writing the comments necessary to explain your trickery. If you want to limit variable scope, declare a new scope or function.

As @Raynos alludes to in the comments, you should avoid "magic", or rather, complicated expressions in your for loops (and other conditional statements). It might not look bad to you now (though it probably will in X months), but consider what happens when your boss/client asks you to add support for a special case. Very quickly it'll look like this:

    for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0 && currentPosition.top != -1 /* browser XYZ gives bogus answer */ && offset < fakePosition.bottom /* handle condition explained in ticket #123 */; i++ ) {
        fakePosition.top -= i * 10;
        offset = this.documentView.getOffsetFromPosition( fakePosition );
        fakePosition = this.documentView.getRenderedPosition( offset );
    }


Your version

String& operator=(String other)
{
   std::swap(m_data, other.m_data);
   return *this;
}

is

Exception safe
Correct (assuming that copy and move constructors are implemented correctly)
Fairly efficient in C++11 if the move constructor is implemented
Potentially slightly less efficient than implementing separate copy & move constructors

The interviewer's version

String& operator=(const String& other)
{
   if (this != &other)
   {
     delete[] m_data;
     m_data = new char[strlen(other.m_data) + 1] {'\0'};
     strcpy(m_data, other.m_data);
     return *this;
   }
}

is terrible, for the following reasons:

If allocation fails, m_data becomes a dangling pointer and destruction (or another assign) will lead to a double delete.
If this == &other it doesn't return a value and therefore leads to undefined behavior (again).
Will fail if other.m_data == 0 (this might be ok if null strings are disallowed, but that would make even weak exception safety complicated)
Less seriously, it might lead to the content of m_data being initialized twice (depending on the optimizer and it's knowledge of strcpy)
Cannot be extended to support C++11 by implementing only an additional move constructor.

Furthermore, the style could be improved as well:

By using an early return instead of a long indented block
By not using C-style strings (and having a length member instead, although your version is presumably implemented in the same way as only m_data is swapped)
strlen and strcpy are not prefixed with std:: which they should be in C++ (having strlen and strcpy in the global namespace is allowed but not required by the standard.

A fixed version (still using a C-style representation) might look as follows:

String& operator=(const String& other)
{
   if(this == &other)
      return *this;

   delete[] m_data;
   m_data = 0; // weak exception safety, which might be sufficient, but only if null strings are allowed, complicating the following code

   if(!other.m_data) // strlen will fail if other.m_data == 0
      return *this;

   std::size_t length = std::strlen(other.m_data);
   m_data = new char[length + 1];
   std::memcpy(m_data, other.m_data, length + 1);

   return *this;
}


Simple program to detect the number of times a vowel occurs in a string

I agree mostly with @Yuri, but I feel that regex is an overkill here. Besides, as they say: "Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems".

Check if a letter is a vowel

I'll begin with this function since it's at the core of your program:

// your code
bool vowelCount(char& temp)
{
    temp = toupper(temp);
    return (temp == 'A' || temp == 'E' || temp == 'I' || temp == 'O' || temp == 'U');
}

I didn't understand at first why you would pass the argument as a non-const reference. I realized only after that you relied on the inner toupper to store vowels in theMap as capital letters. That's a bad idea! One function should have one purpose and its purpose should be expressed clearly. In this case it assesses if the letter is a vowel, period.

So use a const reference instead or, even better, a copy of the character you take as an argument. A char is 1 byte, so taking it by reference or pointer never is an optimization and can even be a pessimization.

The other thing I find sub-optimal in your code is the way you test if temp is a vowel. Firstly because there are better, faster ways to find a value in a range,  like binary_search, which is well known as well as available in the standard library (in <algorithm>). Secondly because the vowels' list isn't the same in all languages. For instance, in french, you would need to count 'y', 'à', 'â', 'é', 'è', 'ê', 'î', 'ô', 'ù', 'û', as well. That's why it might be more flexible and readable to keep the list separated from your code.

So, I would have something like:

bool is_vowel(char c, const std::string& sorted_vowel_list) {
    return std::binary_search(sorted_vowel_list.begin(),
                              sorted_vowel_list.end(),
                              std::toupper(c));
}

A Vowels' map

I'd then count the vowels into a map almost the way you do; I'd only use a range-based loop:

for (auto letter : input_string)
    if (is_vowel(letter))
        ++vowel_map[std::toupper(letter)];

If C++17 is available to you, you can then use "structured bindings" to read the map without referring to iterators:

for (auto [vowel, count] : vowel_map)
    std::cout << "Vowel: " << vowel << " has " << count << " occurrences\n";