Scoreboard with score evolution plots using classes

I think your use of classes mostly makes sense.

The key to object oriented programming, in my humble opinion, is relating how we think about objects in the real world to the way our code is structured. If you were playing a game, would you, as the player, add a score to the score board? Well, it might depend on the game. Sometimes, the game might determine your score and add it to the scoreboard (I'm thinking battleship). In that game, the player doesn't add their score to the scoreboard, it is behind the scenes in a way.

I like that you created a class player, most games revolve around players and encapsulating that information in a class makes sense.

When you play a game, does the scoreboard determine when a new round occurs? Not really, that is sort of inherent to the game. The scoreboard, which in the real world encapsulates information needed just for displaying information related to a game, doesn't actually make decisions about a game. It merely receives information and then displays it. Therefore, it might make sense to separate your scoreboard's display functionality from the functionality of actually playing the game.

This could happen by creating another class called game that would have as members of the class player's and a scoreboard. The game class could be responsible for starting a new round and be responsible for making sure the scoreboard is updated and the player's own score is updated.

Often in OOP, methods are like actions and take on verb-like names. I like that you called your method add_score inside player.

I hope this is constructive feedback and you find it helpful. If you have any questions, let me know.


Fitter Nearest-Neighbor function with three nested loops

Not a solution but a line of thought you may use for implementation. You can define the group of students as sets and then make tuples of these sets, so for example ({1, 3, 5}, {2, 4, 6}), let's call this tuple A and another tuple of sets B: (1, 4, 5}, {2, 3, 6}) I assume here that the order of the sets is important as you want to compare the first set of A with the first set of B, and so on...

You can then compare these tuples of sets by:

A = ({1, 3, 5}, {2, 4, 6}, {8, 10, 12})
B = ({1, 4, 5}, {2, 3, 6}, {8, 10, 12})
C = []
D = []

for i, a_list in enumerate(A):
   for j, b_list in enumerate(B):
       if i == j:
           C.append(a_list - b_list)
           D.append(b_list - a_list)

C = tuple(C)
D = tuple(D)
print(f'A: {A}\nB: {B}\nC: {C}\nD: {D}')

Answer:

A: ({1, 3, 5}, {2, 4, 6}, {8, 10, 12})
B: ({1, 4, 5}, {2, 3, 6}, {8, 10, 12})
C: ({3}, {4}, set())
D: ({4}, {3}, set())

C and D are then tuples with sets of differences for the first set, second set, etc. If these include sets with one element you know the sets in A and B are the same except for that one element.


Written numbers to numerical representation

There are a couple of issues with your code. Let me describe a few:

numbers are not EQ, use EQL or =.
Common Lisp has documentation strings. Use them.
if not progn can be replaced with a single unless

The next function does not work as expected. I have inserted a newline and you see that the parentheses are wrong.

(defun should-push (string)
 (or (equalp string "and"))
 (not (should-multiply string)))

Don't write trivial macros. If you want to have a name for a trivial function, then use a function - not a macro. If the calling overhead bothers you, then declare it inline.

(defmacro sum-list (L)
  `(reduce '+ ,L))

The next may or may not work as you think. Since Common Lisp output streams can be buffered, call FORCE-OUTPUT when you actually want to see the output.

(defun get-input ()
  (princ "Please enter a number: ")
  (read-line))

or equalp can be replaced with (member foo '("a" "b" "c") :test #'equalp). Get the data out of the logic.
instead of (symbol-function '+) use #'+
instead of COND EQUALP use ASSOC with the :test keyword. Get the data out of the code. Alternatively use a macro similar to CASE, which works for strings.
for the last form, write a function, too. Always provide functions. Don't print the result. Just return the result.
inside a LET you don't need a PROGN
EQ nil is better replaced with the NULL predicate.
format t "~c" #\newline is just format t "~%"
when not is unless


Things I would fix:

Don't do this:

import javax.swing.*;
import java.awt.*;

It could be problematic for the compiler to import a bunch of packages at once. If two packages provide the same type, both are imported, and the type is used in the class, a compile-time error occurs. This is described in JLS 6.5.5.1:

  Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.

In addition, it also saves a bit of memory.  And your IDE (if you use one), should have the ability to do this automatically.

The serializable class DrawPanel does not declare a static final serialVersionUID field of type long (thanks to @GilbertLeBlanc for the link):

private static final long serialVersionUID = 1L;

Don't ever do this:

catch (Exception exc)
{
}

Say that you do get an Exception thrown at you. You aren't handling it right now in any way.  At least print a stack trace to help you solve problems you may encounter in the future:

catch (Exception exc)
{
    exc.printStackTrace();
}

It was also mentioned in the comments to catch specific Exceptions.  Here there is no real need to do that since only an InterruptedException is being thrown.  When you do need to catch multiple Exceptions, some people might tell you to do this:

catch (IOException io)
{
    io.printStackTrace()
}
catch (InterruptedException ie)
{
    ie.printStackTrace();
}

But you could also do this:

catch (IOException | InterruptedException e)
{
    e.printStackTrace();
}

Right now there are some hard-coded values:

if(oneX >= 283)
if(oneX <= 7)
...

I would store those values in variables, and then I would make it so that it is more scalable.  For example:

int xScale = 280;
int yScale = xScale / 40;

That way, you only have to change one value in order to scale your different values.  This is just an example, and has not been implemented in my code.  I left this for you to do on your own.

Recommendations that are optional:

You have a lot of if statements with braces:

if(down)
{
    oneY++;
}

If you don't expand on them (which I don't see a need to), you can save some LOC:

if (down) oneY++;

Right now you are setting the location:

frame.setLocation(375, 55);

You don't have to do this, but I prefer the OS to set the location:

frame.setLocationByPlatform(true);

You could also set the frame to the center of the window:

frame.setLocationRelativeTo(null);

But I never liked that too much.  It makes your program seem like a pop-up, which I despise.

I always do frame.setVisible(true) after I am completely finished setting up the frame.

Right now your are doing this with your braces:

void someMethod(int someInt){
    // ...
}

Since you are a beginner, I would recommend lining up your braces (I still do this, and I've been programming for a while):

void someMethod(int someInt)
{
    // ...
}

This is a matter of taste, and it is perfectly fine to stay with what you are doing right now.

You might note that this:

public static void main(String... args)

Is a bit different than your usual:

public static void main(String[] args)

They both do the same thing, but one uses variable arity parameters.

Final code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

final public class Test
{

    JFrame frame;
    DrawPanel drawPanel;

    private int oneX = 7;
    private int oneY = 7;

    boolean up = false;
    boolean down = true;
    boolean left = false;
    boolean right = true;

    public static void main(String... args)
    {
        new Test().go();
    }

    private void go()
    {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawPanel = new DrawPanel();

        frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

        frame.setResizable(false);
        frame.setSize(300, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        moveIt();
    }

    class DrawPanel extends JPanel
    {
        private static final long serialVersionUID = 1L;

        public void paintComponent(Graphics g)
        {
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.RED);
            g.fillRect(3, 3, this.getWidth() - 6, this.getHeight() - 6);
            g.setColor(Color.WHITE);
            g.fillRect(6, 6, this.getWidth() - 12, this.getHeight() - 12);
            g.setColor(Color.BLACK);
            g.fillRect(oneX, oneY, 6, 6);
        }
    }

    private void moveIt()
    {
        while (true)
        {
            if (oneX >= 283)
            {
                right = false;
                left = true;
            }
            if (oneX <= 7)
            {
                right = true;
                left = false;
            }
            if (oneY >= 259)
            {
                up = true;
                down = false;
            }
            if (oneY <= 7)
            {
                up = false;
                down = true;
            }
            if (up) oneY--;
            if (down) oneY++;
            if (left) oneX--;
            if (right) oneX++;
            try
            {
                Thread.sleep(10);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            frame.repaint();
        }
    }
}


Excel VBA macro loops through 20-28 sheets taken from filenames in cells and pastes them to the main workbook

I'm not sure why it takes 30 seconds to process the 20 files, because with my almost empty test files, your code only takes 2.202 seconds (21 files). I'm guessing those files are quite large, contain a lot of objects, charts, data (?)

If they have a lot of rows I'd suggest changing them to the xlsb format, which will compress them quite a bit (size could go down to 40%), and they will be a lot faster to open and close

  XLSB Format

  XLSB is the Excel binary format. It is structured as a compressed
  folder that contains a large number of binary files. It is much more
  compact than the XLS format, but the amount of compression very much
  depends on the contents of the workbook. For example, ten workbooks
  show a size reduction factor ranging from two to eight with an average
  reduction factor of four...

Another consideration is that interacting with files over the network is considerably slower than the local drive

Related to the code, there are a few basic issues:

ALWAYS Use "Option Explicit"
You almost never need the Select and Activate methods

Impact performance, and all you need to do can be accomplished without them

To properly replace the select statements you need to refer to all objects explicitly:

  Example - instead of

Windows("YTD File.xlsm").Activate
Sheets(SheettoCopyLoop).Select
Sheets(SheettoCopyLoop).Range("A1").Select
ActiveSheet.Paste

  use:

Windows("YTD File.xlsm").Sheets(SheettoCopyLoop).Range("A1").Paste

Indent your code to make it easier to read, and distinguish hierarchies of logic and nesting
It's better to prevent all errors than to rely on the "On Error GoTo" statements

There are few errors that cannot be avoided
The GoTo statement breaks the flow and structure of the code

Turn off Application.Calculation (to manual) if possible
Don't force the user to dismiss dialog boxes after every iteration

They only need to be aware if their task cannot be completed

I made some changes, such as copying the entire sheets to the main Workbook, instead of copying only the data, so here is how I would change your code:

Option Explicit

Private Sub CommandButton19_Click2()
    Dim wb As Workbook, ws As Worksheet, newWB As Workbook
    Dim wsSMS As Worksheet, wsS As Worksheet, wsNew As Worksheet
    Dim fileInfo As Variant, sheetToCopy As String, r As Long
    Dim fileToCopy As String, fileName As String, t As Double

    t = Timer

    OptimizeXl True, xlWait

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Admin")
    Set wsSMS = wb.Worksheets("SM Summaries")

    fileInfo = ws.Range("D6:F34").Value2

    For r = 1 To UBound(fileInfo)               'max xl sheet name length = 31 chars
        sheetToCopy = Left(fileInfo(r, 1), 31)  'column 1 of Range("D6:F34") (Col D)
        fileToCopy = fileInfo(r, 2)             'column 2 of Range("D6:F34") (Col E)
        fileName = fileInfo(r, 3)               'column 3 of Range("D6:F34") (Col F)

        'Continue only if all necessary file details are not empty
        If Len(fileToCopy) > 0 And Len(sheetToCopy) > 0 And Len(fileName) > 0 Then
            If Len(Dir(fileToCopy)) > 0 Then    'continue only if file exists
                Application.StatusBar = "Pulling data for " & fileName & "..."

                Set newWB = Workbooks.Open(fileToCopy, False, True) 'NoLinks, ReadOnly

                If WsExists(newWB, "Summary") Then
                    'Delete existing sheet named "sheetToCopy"
                    If WsExists(wb, sheetToCopy) Then wb.Worksheets(sheetToCopy).Delete
                    Set wsS = newWB.Worksheets("Summary")
                    If r = 1 Then
                        wsSMS.Range("C2").Value = wsS.Range("C6").Value
                        wsSMS.Range("C4").Value = wsS.Range("C5").Value
                    End If
                    'Copy new sheet into this workbook, and rename it to "sheetToCopy"
                    wsS.Copy After:=wb.Worksheets(wb.Worksheets.Count)
                    Set wsNew = wb.Worksheets(wb.Worksheets.Count)
                    wsNew.Name = sheetToCopy
                Else
                    Debug.Print "Invalid sheet name for file on row " & r
                End If
                newWB.Close False
            Else
                Debug.Print "Invalid fileToCopy on row " & r & " (" & fileToCopy & ")"
            End If
            ws.Range("F1").Value2 = "Last modified: " & Date
        Else
            Debug.Print "Empty fileToCopy, sheetToCopy, or fileName on row " & r
        End If
    Next
    ws.Activate
    OptimizeXl False
    Application.StatusBar = "READY"
    Debug.Print "V2 Time: " & Format(Timer - t, "0.000") & " sec"
    MsgBox "Data pull complete!", vbInformation, "Success!"
End Sub

Private Sub OptimizeXl(ByVal stat As Boolean, Optional ByVal curs As Long = xlDefault)
    Application.Calculation = IIf(stat, xlCalculationManual, xlCalculationAutomatic)
    Application.ScreenUpdating = Not stat
    Application.DisplayAlerts = Not stat
    Application.Cursor = curs
End Sub

Private Function WsExists(ByRef wb As Workbook, ByVal wsName As String) As Boolean
    Dim ws As Worksheet
    If Not wb Is Nothing Then
        If Len(wsName) > 0 Then
            For Each ws In wb.Worksheets
                If ws.Name = wsName Then
                    WsExists = True
                    Exit Function
                End If
            Next
        End If
    End If
End Function

Test results:

V1 Time: 2.202 sec (your code)
V2 Time: 1.012 sec


C++ equivalent of Python's deque with maxlen - sliding window

You will get better performance using a ring buffer. (With an existing implementation in Boost)

This will keep an extra set of indexes into the buffer to specify the start and end of where the data is and wrap around automatically.


Database Design for representing category relationships

I have a small concern about your approach that I think you should have addressed during the interview because it could raise potential issues in your design.

Do you want/need nested product categories?

As it currently stands you're allowing nested categories and even allowing loops of categories where a category can reference itself or one of it's own subcategories.

If you don't want nested categories then one of your restrictions will have to be that category with a parent should check it's parent doesn't also have a parent. The easiest way to do this is with two extra virtual columns(not stored), the first will simply say if a table has a parent(parent_id IS NOT NULL) and the second defines the value we need to create said relationship(namely that the value should be 0).

CREATE TABLE category(
    category_id TEXT PRIMARY KEY,
    category_name TEXT,
    parent_id TEXT,
    is_subcategory INT GENERATED ALWAYS AS (parent_id IS NOT NULL) VIRTUAL,
    can_be_child_of_subcategory INT GENERATED ALWAYS AS (0) VIRTUAL,
    FOREIGN KEY (parent_id, can_be_child_of_subcategory) REFERENCES category(category_id, is_subcategory) ON UPDATE RESTRICT
);

And now without changing the definition of the virtual columns we can't add a subcategory to a subcategory.

That said there's a few less major issues that might be worth considering in a bit more detail:

You should be using a foreign key, not an index:

FOREIGN KEY(parent_id) REFERENCES category(category_id)

You appear to be using TEXT as the field type, but accessing it with integers. If you're using a text type it's worth making it clear it's a GUID, either way you should use the right type for the field.

category_id INT
category_id = :sub_category_id
-- OR
category_id CHARACTER(32)
category_id = :sub_category_guid

It's ANSISQL standards to write keywords in upper case, obviously you don't need to keep to that standard as every SQL language supports lower or mixed case, but almost every documentation will have keywords in all caps so it's worth keeping to the convention:

CREATE TABLE category(category_id CHARACTER(32) PRIMARY KEY,
category_name TEXT,parent_id CHARACTER(32));

I also suggest making things not null

CREATE TABLE category(category_id CHARACTER(32) NOT NULL PRIMARY KEY,
category_name TEXT,parent_id CHARACTER(32));

I'd also suggest adding a bit more whitespace and at least for an interview document choices

CREATE TABLE category(
    category_id CHARACTER(32) NOT NULL PRIMARY KEY,
    category_name TEXT,
    parent_id CHARACTER(32),
    FOREIGN KEY (parent_id)
        REFERENCES category(category_id) ON UPDATE RESTRICT
);

Finally I'm really not a fan of your naming on the aliases for the table. Much nicer to use a descriptive name to make it easier to understand:

-- Fetch all child subcategories for a given category
SELECT
    SubCategory.category_name AS CategoryName
FROM category ParentCategory,
     category SubCategory
WHERE
    ParentCategory.category_id = :parent_category_guid
    AND
    ParentCategory.parent_id = SubCategory.category_id
;

-- Fetch the parent category for the child
SELECT
    ParentCategory.category_name AS CategoryName
FROM category ParentCategory,
     category SubCategory
WHERE
   SubCategory.category_id = :sub_category_guid
   AND
   ParentCategory.category_id = SubCategory.parent_id
;


Not sure if I've understood yout question correctly, but I assume, that your grid is a square grid (you test both, maximal high and width, as a lower than grid's height).

Referring to your first question:
There are many options. You can make a method which takes two parameters at a time:

public void checkIfAllowed(int row, int column){
      boolean areCorrect = checkIfRowAllowed(row) && checkIfColAllowed(column);
      if(!areCorrect){
           throw new IndexOutOfBoundsException("Row or column ID is not acceptable.");
      }
}

private boolean checkIfAllowed(int row_or_column) {
    return (row_or_column < 1 || row_or_column > gridHeight);
}

Now, a client is not forced to check each row and column in separate lines. Just an example:

public boolean getCellById(int row, int column) {
      try{
          checkIfAllowed(row, column);
          return grid[row * gridHeight + column];

      } catch (IndexOutOfBoundsException e) {
           // log an error, or do something else
      }
}

But this exception handling seems strage for me. I would simply throw it in getCellById(int row, int col) and handle when this method is invoked.


I need to delete a file when an error occurs during loading it.

In other words:

Happy path:

Load a file
Move on

Unhappy path:

Load a file, exception is thrown
Delete the file
Move on

Exceptional path:

Load a file, exception is thrown
Delete the file, exception is thrown
Handle exception, move on

From these points, it appears we'd need a task that loads a file. If that task fails, we need to try to handle the unhappy path gracefully.

I haven't written async code with async/await, but I'd probably get away with this using a Task that loads the file, and then decide whether I'd .ContinueWith another Task that deletes the file, and then decide how to handle the exceptional path where that other task would have failed.

Signature

public async Task LoadFromStorageFile(string fileName)

This StackOverflow answer refers to an authoritative source for async method naming conventions:

  The Task-based Asynchronous Pattern (TAP) dictates that methods should
  always return a Task<T> (or Task) and be named with an Async suffix;
  this is separate from the use of async. Certainly, Task<bool> Connect()
  (or async Task<bool> Connect()) will compile and run just
  fine, but you won't be following the TAP naming convention.

The signature for Task LoadFromStorageFile(string) would follow the naming convention for the pattern, by appending "Async" to the method's name:

public async Task LoadFromStorageFileAsync(string fileName)

Async/Await Exception Handling

As I've found in this StackOverflow answer, an exception thrown in an async method will bubble up to the caller, so whoever called await LoadFromStorageFileAsync("somefile.txt"); can know whether to move on, or to handle the unhappy path.

  It is not allowed to perform async operations in a catch block.

Indeed. There's a question on Stack Overflow, with a nice answer from one of our top reviewers here on CR, that shows how that limitation can be circumvented. In a nutshell:

bool loadSucceeded;
try
{
    var folder = await ApplicationHelper.GetApplicationSaveFolder();
    file = await folder.GetFileAsync(fileName);
    // ...

    loadSucceeded = true;
}
catch
{
    loadSucceeded = false;
}

LoadFromStorageFileAsync can then look like this:

public async Task LoadFromStorageFileAsync(string fileName)
{
    bool loadSucceeded;
    StorageFile file;

    try
    {
        // happy path
        var folder = await ApplicationHelper.GetApplicationSaveFolder();
        file = await folder.GetFileAsync(fileName);
        // ...

        loadSucceeded = true;
    }
    catch(Exception exception)
    {
        // log exception

        loadSucceeded = false;
    }

    if (!loadSucceeded && file != null)
    {
        try
        {
            // unhappy path
            await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
            deleteSucceeded = true;
        }
        catch(Exception exception)
        {
            // exceptional path
            // log exception
        }
    }
}

This code doesn't rethrow whatever exception caused loadSucceeded to be false - rethrowing that exception in the unhappy path makes no sense, as was said before, that finally block is not needed. Instead, you could catch(Exception exception) (or anything more specific) in the happy path's catch block, and write a trace, a debug, or a warning log entry with the exception and its stack trace. At that point, it's taken care of, there's no need to re-throw it.


Printing the start and end dates of the most recent eight weeks

Don't Repeat Yourself

$currentDate = date('Y-m-d');
$weekOneStart = strtotime("-56 day", strtotime($currentDate));

You can simplify this by saying something like

$midnight = strtotime(date('Y-m-d'));
$weekOneStart = strtotime("-56 day", $midnight);

Then you don't have to keep taking strtotime of the same value.

$weekOneEnd = strtotime("-49 day", strtotime($currentDate));
$weekOneEnd = date('m/d/Y', $weekOneEnd);
$weekTwoStart = strtotime("-49 day", strtotime($currentDate));
$weekTwoStart = date("m/d/Y", $weekTwoStart);

Similarly, consider reducing this to

$weekOneEnd = strtotime("-49 day", $midnight);
$weekOneEnd = date('m/d/Y', $weekOneEnd);
$weekTwoStart = $weekOneEnd;

Now you only calculate that value once.

As a for loop

$weekMarkers = [];
$midnight = strtotime(date('Y-m-d'));

for ($current = strtotime('-8 weeks', $midnight); $current <= $midnight; $current = strtotime('+1 week', $current)) {
    $weekMarkers[] = date('m/d/Y', $current);
}

$previous = array_shift($weekMarkers);
foreach ($weekMarkers as $current) {
    echo "$previous - $current	\n";
    $previous = $current;
}

This is actually as two for loops.  You could mix them if you wanted, although many would argue that you are mixing calculation and display in that case.

$midnight = strtotime(date('Y-m-d'));

$current = date('m/d/Y', strtotime('-8 weeks', $midnight));
for ($next = strtotime('-7 weeks', $midnight); $next <= $midnight; $next = strtotime('+1 week', $next)) {
    echo "$current - ";
    $current = date('m/d/Y', $next);
    echo "$current	\n";
}

This would work, although the double use of $current is a bit odd.

I leave it up to you whether either of these is easier than your original code.


You have a problem if you want to have the escape-character immediately before a replacement, because you don't support escaping the escape-character.
I suggest dispensing with escape-characters, and simply replace an empty replacement {} with an opening brace {.
There's no reason to modify the format-string at all, and thus receiving it by copy. Doing so is supremely inefficient. Well, using named arguments at all already is, so it might not matter too much.
Do you know the ternary operator cond ? true_exp : false_exp? Using it would simplify things.
Avoid allocations, thus avoid std::string. At least the format string should be C++17 std::string_view, maybe also the map should be too.
If you template it, you don't even really have to decide for the caller:

template <class Args = std::unordered_map<std::string_view, std::string_view>>
std::string formatString(std::string_view format, const Args& args)


Finding the sum of all numeric palindromes that are less than N

This is not a proper review, but rather an extended comment.

Are there shorter, more-concise alternatives to the above approach

Yes. You should view it not as a programming problem, but as a recreational math exercise.
Consider a simplest case of N being an even power of 10, say 1000000. For a moment, allow leading zeroes. Now, each 6-digit palindromic number abccba corresponds to a 3-digit number abc, and in fact is 1000*abc + cba. Notice that if the sum of all 3-digit numbers is X, the sum of all 6-digit palindromic numbers is 1000*X + X = 1001*X. As for X, recall the formula for the sum of an arithmetic progression 0 + 1 + 2 + ... + 999.
To deal with leading zeroes you must subtract the sum of those palindromic numbers which do have leading zeroes. Yet again, they are in form abba0 = 1000*ab + 10*ba. Yet again, use the arithmetic progression formula to get the result.
No programming beyond a few arithmetic operations is required.
I don't want to spell out the complete solution. I hope this is enough to get you started with the arbitrary N.


Possible security issues in email validation

In your first validation, I think you forgot to exit, you probably meant:

if(!isset($_POST['submit']))
{
    //This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!";
    exit;
}

To validate email addresses, you can use the filter_var method, like this:

function is_valid_email($str) {
    return filter_var($str, FILTER_VALIDATE_EMAIL);
}

For example:

function check_email($email) {
    printf("checking '%s': %s\n", $email, is_valid_email($email) ? 'OK' : 'INVALID');
}
check_email('joe@example.com');
check_email('bogus');

will output:

checking 'joe@example.com': OK
checking 'bogus': INVALID

For more details and (caveats!), see the docs. Also some more examples here.

Your original IsInjected method might still be useful for other purposes, that's why I created a new method for validating emails. If you keep it I would rename it to hasInjectedChars or has_injected_chars. And these lines can be improved:

  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }

you could write simply:

return preg_match($inject, $str);


_debitBalanceAmount = debitBalance;

Assigning this to a member value doesn't seem right, and this is before any validation.

GetFundAmountToTransfer();

This function is implies it will return something, but you don't assign it anywhere.  This is a code smell.

var result = GetProceedInstruction();
if (result == "1")
    return _callerAuthorization;

A meaningless string literal, not good.  Make it an enum with a good name.  Where did _callerAuthorization get assigned?

The control flow is not complicated and yet it's hard to read.  Try breaking it up into smaller functions.


Providing advice based on user's favourite YouTuber

I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to implement it that would be great!

Here you go!

Use Dictionaries!

The entire if/elif/else if yelling, if not screaming, to be put into a dictionary. This is a lot faster than your implementation because it's a simple key lookup, instead of multiple logical checks to test the user input.

Here is your test function (now named favorite_youtuber):

def favorite_youtuber():

    youtube_response = {
        'dr. phil': 'You are an awesome lad!',
        'james charles': 'Errmm. Ok...',
        'bloamz': 'Ok then.',
        'ali a': 'I mean. Thats old but ok...',
        'jacksepticeye': 'Thats kinda cool',
        'will smith': 'Thats diferent. I rate that.',
        'jack black': 'You have good taste.',
        'jack white': 'I like him as well.',
        'dr. mike': 'So you like learning then!',
        'morgz': 'I mean just leave now.'
    }
    # Since some youtubers in the list below are not included in the dictionary, I left the list. #
    my_favorite_youtubers = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']

    youtuber = input('Enter your favourite youtuber:  ').lower()

    if youtuber in youtube_response:
        print(youtube_response[youtuber])
    else:
        print('I dont know that one. Ill check them out.')

    print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')

A dictionary works by utilizing keys and values, like so:

my_dict = {
    "key": "value of any type",
    ...
}

In this case, the key is the name of the youtuber that the user inputs, and the value is the response. This prevents you from having to have multiple print statements depending on what the user inputs. Now, all you have to do is make sure that the youtuber entered by the user is included in the dictionary's keys, utilizing this line:

if youtuber in youtube_response:

Format Your Strings!

The era of my_string = a + " " + b is over. You can now format your strings to include your variables directly in them! Take a look:

print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')

Essentially, the value of the code within {} is placed in that position in the string.

Another option is to use .format(), which is a method called on a string. Take a look:

print('My favourite youtuber is {}'.format(random.choice(my_favorite_youtubers)))

They both do the same thing. It's up to you which one you want to use.

.lower() utilization

Instead of

maybe = input("Y/N ")
maybe = maybe.lower()

do this

maybe = input("Y/N ").lower()

Since input() returns a string, .lower() applies to that string. This prevents you from having to write that extra line, and it makes your code a little nicer.

\n

Instead of

print("That is not a valid option")
print("")

do this

print("That is not a valid option.\n")

It adds a newline character at the end of the string, doing exactly what you're doing but in a nicer way.

Repetitive User Input

Now let's talk about your try_again function.

There's a lot to break down here. I find it easier to show you my improved version of your code, and walking you through what I did. Have a look:

def run_app():
    while True:
        favorite_youtuber()
        again = input("Play again? (Y/N)").lower()
        while again not in "yn":
            print("Please enter Y/N!")
            again = input("Play again? (Y/N)").lower()
        if again == "n":
            break
    print("Thank you for using this app!")

It's fairly self explanatory. The one thing I want to talk about is the nested while loop.

Instead of checking if something is within a tuple ("y", "n"), you can check if something is within a string "yn". It's easier to understand this way. The while loop keeps asking for input until the user enters a "y" or a "n". This is easier than having nested while True: loops, as those can get very messy very fast.

Since you only want to see if they don't want to keep playing, you only need to check for the existence of an "n". Then, it's a simple break statement to print out the final goodbye.

Main Guard

Last thing I'm commenting on.

You should use a main guard when running this program. Why?

Let's say you want to import this module into another program, because you don't want to rewrite all this code in a different file. When you import the module, that spare try_again is going to run. That is not what you want. Containing this extra code in a main guard will prevent this from happening. It's a simple if statement:

if __name__ == "__main__":
    run_app()

I renamed your try_again to run_app(), since that name is more fitting of what the program is doing.


As a wrapper goes I think this looks fine. The feedback I do have is that I wouldn't use let as often as you do and would use the treading macro (-> ...) instead.

For example:

(-> (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)
      .init)

does the same as

(let [provider (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)]
  (.init provider)
  provider)

and it's easier to read and shorter. You could also do it this way:

(.init (com.tulskiy.keymaster.common.Provider/getCurrentProvider true))


Dynamic Programming with Project Euler problem 67

I recommend running flake8 occasionally, and cleaning up what it complains about. And consider using python3 rather than python2.

If you really want to define a global with pyr = [], then at least name it PYR. Much better for main to call

    print(best_path(get_pyramid()))

and push the init code into a getter. Then you won't be polluting the global namespace with f. (And no need to retain the f.closed debugging statement, once you've convinced yourself that with closed it as advertised.)

EDIT: On reflection, I was viewing this in too mechanical a way. 200_success is correct, all caps is for manifest constants. The real trouble here is gratuitous globals. Scope things down appropriately without polluting the top-level namespace.

Naming the triangular pyramid pyr was a fine choice, better than the parameter name li.

Using xrange is a bit odd, nowadays. Just stick to python3, and range will be perfect.

A name like cost (or distance, or dist) would have been more natural than saver.

If you have your heart set on a triangular map of zeros, this would be more pythonic:

# Set costs for all points to 0
for y, row in enumerate(li):
    for x, val in enumerate(row):
        saver[(x, y)] = 0

But you're using it with +=, so better to instead define saver = collections.defaultdict(int), allowing increment to lazily populate the map.

This line is fairly clear:

        saver[(n-y, x)] += a + max(b, c)

The n-y could have been just y (in several expressions) if you had supplied a third optional argument of -1 for the range. And it seems likely you could move the max(a+b, a+c) expression into this loop, as well, perhaps by padding the bottom of the pyramid with a line of zeros.

Explicitly supplying a tuple as key is a good practice, one worth sticking to here:

return saver[0, 0]

This is a fine comment:

"""Find the max total from top to bottom in a triangular array."""

Writing lots of comments may not be necessary if your identifiers accurately tell the story. Consider renaming the function to best_path_cost, since it returns a scalar cost rather than a path through the pyramid.

This is a fine comment, though I would prefer "costs" over the vague "values":

# Set values for all points to 0

You might consider deleting it, and moving the code into a helper with a descriptive name like get_triangle_of_zeros(). Writing fewer comments leads to writing fewer comments that lie (or bit-rot). Functions typically should be defined with a docstring comment, as you supplied. If a function is very simple, it needs a descriptive name but perhaps no comment.


Rendering drop-down boxes for country and region

In PHP how can I follow the DRY (don't repeat yourself) principle in this piece of code? The 2 classes in question share an awful lot of code.

One approach would be to create a common superclass and extract the common elements of the function. As everything except the viewData is the same, just pass that to the newly created common function:

<?php
interface iSelect {
    public static function display();
}

abstract class AreaSelect implements iSelect {
    public static function displayData($viewData) {
            if ( class_exists( 'View' ) ) {

                // Get the full path to the template file.

                $templatePath = dirname( __FILE__ ) . '/' . static::$template;

                // Return the rendered HTML
                return View::render( $templatePath, $viewData );

            }
            else {
                return "You are trying to render a template, but we can't find the View Class";
            }
    }
}

class CountrySelect extends AreaSelect {
    public static function display() {
        $viewData = array(
            "options" => '_countries',
            "optionsText" => 'name',
            "optionsValue" => 'geonameId',
            "value" => 'selectedCountry',
            "caption" => 'Country'
        );
        parent::displayData($viewData);
    }
}

class RegionSelect extends AreaSelect {
    public static function display() {
        $viewData = array(
            "options" => '_regions',
            "optionsText" => 'name',
            "optionsValue" => 'name',
            "value" => 'selectedCity',
            "caption" => 'Region'
        );
        parent::displayData($viewData);
    }
}

The displayData is now so generic, that it might make sense to create a AbstractSelect class instead of an AreaSelect as it is likely that other selects will use the exact same method as well.

Extract

You should always be careful when using extract like this. If you ever have an entry that is called filePath, you would overwrite the $filePath argument and thus break your code.

Additionally, if $viewData is ever user-controlled, you would have an LFI vulnerability. It's unlikely, but I would always try to make generic methods such as this as secure as possible (the calling code is unlikely to expect a security issue), even for unlikely use (that's also why I would probably check filePath for directory traversal, just in case, as well as html-encode all variables in the template); at the very minimum, I would document the issue.

Misc

why are you checking if View exists (it should always exist, right?), but not if $template exists (it's more likely that one of many templates gets misplaced than that the single view class gets lost)?
your placement of curly brakets is not consistent.
your comments aren't really needed. Stuff like // Return the rendered HTML is already clear from the code. It would be better to remove comments such as these, and add PHPDoc style comments documenting the methods behaviour instead.


Changing look and feel for all current frames

Java GUIs: Swing & AWT

In standard Java there are two ways to make GUIs: Swing and AWT.

To be short, Swing is platform-independent and AWT is platform-dependent. Typically you pick either AWT or Swing and stick to it. I believe Swing is the more popular choice today as it is easier to work with.

You can tell Swing code from AWT code by the fact that Swing component classes are prefixed with a J. For example Frame is AWT and JFrame is the Swing equivalent.

The Swing components inherit from the AWT components so a JFrame is a Frame.

Windows and Frames

Now the difference between Window and Frame  (and JWindow and JFrame respectively) is that a Window is a plain window without any decorations; no borders, no title bar, no window management buttons. A Frame is a Window with all these decorations. And I put emphasis on is a in the above as Frame actually inherits Window.

So the inheritance tree looks like this:

          lang.Object
              |
           awt.Component
              |
           awt.Container
              |
           awt.Window
              |
     +--------+-------+
     |                |
swing.JWindow      awt.Frame
                      |
                 swing.JFrame

To answer your question about which of the methods is better. Note that getWindows() is defined in Window and inherited by JWindow, Frame and JFrame. Calling getWindows() will get all windows, even owner-less dialogues and system windows associated with the application, regardless of if they have decorations or not. On the other hand getFrames() is defined in Frame so calling getFrames() will get all windows with decorations (frames). If your application doesn't have any frame-less windows, the two pieces of code you posted will be equivalent.

The Code

Your code is likely fine as it is wither either approach as plain Windows are kind of rare and often transient. The approach you're using is the standard one.

If you want to be absolutely sure you get every window there is and be picky about it, this is how I would write it:

for(Window window: Window.getWindows()) {
    SwingUtilities.updateComponentTreeUI(window);
}

For your reference, see the Java Docs for JWindow  and JFrame and their super classes.


I don't see any issue with the code.

It's technically a hook, because it's using other hooks, so it must
start with use keyword. That feels weird to somebody coming outside of
the React world like me. Furthermore, it doesn't return any title...

The use prefix is just a React hook naming convention, and React hooks aren't required to return anything.

How would you name it?

If you are merely asking about what to name it, well, this is rather opinionated, but I suggest:
useDocumentTitleUpdater

Alone the functionality is to update the document title, something like updateDocumentTitle or documentTitleUpdater. The former, to me, implies you are handing the function the value you want it to update something to, while the latter is more of a delegation, telling the function to update the title. Since this is a React hook and there's a hook naming convention, useDocumentTitleUpdater explains the purpose of the hook. It could probably be shortened to useDocTitleUpdater if the previous was too verbose for your taste.

Is it appropriate to keep this functionality in a hook like I did or
is there some other convention in React for stuff that depends on
hooks?

This doesn't appear to be an inappropriate use of a React hook. The alternative would be a utility function that consumes the various arguments from redux, runs the two middle lines to compute the strings, and updates the title. This function would be called from a useEffect hook with the redux state values as dependencies instead.
Your hook has instead encapsulated this into a single line any functional component can use and they won't be responsible for getting the dependencies correct.


Maximum possibility of banknotes to keep into the given integer value

Don't use the for-case antipattern
You are using the for-case antipattern, which you should almost always avoid. Instead, find some way to simplify your code. For example, instead of hardcoding the denominations in the if-statements, put them in an array:
static const int denominations[] = {100, 50, 20, 10, 5, 2, 1};
static const int n_denominations = sizeof denominations / sizeof *denominations;

Then use it like so:
for (int i = 0; i < n_denominations; i++) {
    count = 0;

    while (number >= denominations[i]) {
        count++;
        number -= denominations[i];
    }

    printf("%d nota(s) de R$ %d,00\n", count, denominations[i]);
}


Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?

I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:

$data['pages']
$data['posts']

Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.

Basically you're treating the $data array as a sort of object you hand over to other classes.

But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?

Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:

class Data_Controller extends CI_Controller
{
    private $data;

    public function __construct()
    {
        parent::__construct();
        $this->data = $this->Static_model->get_static_data();
        $this->data['pages'] = $this->Pages_model->get_pages();
        $this->data['categories'] = $this->Categories_model->get_categories();
        $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
        $this->data['page'] = $this->Pages_model->get_page($page_id);
    }

    public function getData()
    {
        return $this->data;
    }

}

or something to the same effect and then extend this for your pages class:

class Pages extends Data_Controller {

    public function __construct()
    {
        // currently this whole method doesn't do anything, it can be removed
        parent::__construct();
    }

    public function page($page_id) {
        $data = $this->getData();
        ..........................

    }

}

And, of course, those controller classes that don't need all that data can just extend CI_Controller.

I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:

class Data_Controller extends CI_Controller
{

    public function getPages()
    {
        return $this->Pages_model->get_pages();
    }

    public function getCatagories()
    {
        return $this->Categories_model->get_categories();

    }

}

If you need to buffer the data you can do:

class Data_Controller extends CI_Controller
{

    public function getCatagories()
    {
        static $buffer = NULL;
        if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
        return $buffer;
    }

}

Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.

OK, that was a bit long. I hope you got some new ideas from my ramblings.


Objective-C class for placing UI elements based on screen size

Some thoughts on it:

Code: I'd suggest to create a Category on UIScreen. This is even more elegant than creating a separate class.
Naming: In Objective-C getter usually do not have the prefix "get".
General approach: Without knowing the background of your app and any detailed implementation, it's not common to layout UIViews relatively to the screen. As you're using UIViewControllers, any additional view should be added as a subview to the UIViewController's view. This ensures that layout and orientation changes are handled for you and are automatically being applied to all subviews by the UIViewController.


data = []
    try:
        fp = open(path, 'r')
        for f_line in fp:
            data.append(f_line.rstrip())

    finally:
            fp.close()
    return data

This can be simplified to:

data = []
with open(path) as fp:
   f_line = fp.readline()
   data.append(f_line.rstrip())
return data

The with statement in Python will automatically close the file after the code is done with it. It also handles the finally exception by closing it.

findings = [[] for x in landscape]

This initialization can be skipped if the algorithm is transformed.

for cnt, l_line in enumerate(findings):
    for found in l_line:
        if found[0] == 0 and len(findings) > (cnt + len(bug) - 1):
            check = 1
            for i in range(1, len(bug)):
                if bugInLine(findings[cnt + i], i, found[1]):
                    check = check + 1

            if check == len(bug):
                complete_bugs_cnt = complete_bugs_cnt + 1

This is close to text = [''.join(arr) for arr in zip(*text[::1])] (rotate the text by -90 degrees and search) and sum([word.count(pattern_to_find) for word in text]).

The current algorithm is too complicated. Consider an algorithm which checks if a word is present in a single line. Given the line abc  c  d e    a abc the word abc occurs twice, and .count() can be used to find how many times that pattern occurs, or, a while loop with the string split on whitespace (then check if the item is equal to that item.)

However, the text is in columns instead of rows. The text can be rotated -90 degrees which turns it into the easy-to-parse row format. From there it becomes very easy to parse.

After applying these transformations, the code becomes the following (without file reading):

def find_text_column(haystack, pattern_to_find):
  text = haystack.splitlines()
  maxlen = len(max(text, key=len))
  # make every line the same length so that zip() works, as it does not work with irregular arrays
  text = [line.ljust(maxlen, ' ') for line in text]

  # rotate string by -90 degrees
  text = [''.join(arr) for arr in zip(*text[::1])]
  return sum([word.count(pattern_to_find) for word in text])


Project Euler #85: Find the rectangular grid with closest to 2M rectangles

Well, let's ignore the code, because having started coding at that stage is wrong.

Let's look instead at a better starting-point:

Find a closed formula for the number of rectangles in a grid of given size (x, y):

N = \$\sum_{a=1}^x\sum_{b=1}^y(x-a+1)(y-b+a)\$
\$= \sum_{a=0}^{x-1}\sum_{b=0}^{y-1}(x-a)(y-b)\$
\$ = \frac 1 4 * (2x^2 - x*(x-1))(2y^2 - y*(y-1))\$
\$= \frac 1 4 * (x^2+x)(y^2+y)\$
Solve it for given y and N:

\$x^2+x-\frac{4*N}{y^2+y} = 0\$
\$x=\frac{-1 \pm \sqrt{1 + \frac{4*4*N}{y^2+y}}}2\$
\$x=-\frac 1 2 \pm \sqrt{\frac 1 4 + \frac{4*N}{y^2+y}}\$

(Only the positive solution is of interest)
Simply iterate all possible rectangles starting with short side of 1 until our short dimension becomes the long one, and calculate the number of rectangles for a slightly bigger / smaller rectangle than the fractional one we calculated.

The solution will be found in \$\Theta\left(\sqrt[4]N\right)\$.


Making a string by reading down a matrix

Most important comment: permute is just unpermute with length = 4.

There seems to be no reason to favor collections.deque over a normal list here. It is only an advantage of you do a lot of queue.popleft() calls.

For the creation of rows you can just use a list comprehension:

rows = (text[i:i+4] for i in xrange(0, len(text), 4))

I would use a generator expression here to save memory

You could simplify your un-/permute to: something like:

def permute(text, n=4, reverse=False):
    n = len(text)/n if reverse else n
    matrix = (text[i:i+n] for i in range(0, len(text), n))
    matrix_t = zip(*matrix)
    return "".join("".join(x) for x in matrix_t)

where (text[i:i+n] for i in range(0, len(text), n)) makes a generator object that is like your rows, zip(*list) transposes a list of lists and the two joins first join each row and then the rows.

This will not even create a lot of overhead because they are all generator objects (and therefore it is not one possibly big list being read into memory).

You could even inline all of it:

def permute(text, n):
    return "".join("".join(x) for x in zip(*(text[i:i+n] for i in range(0, len(text), n))))


First of all, you should not get user input from inside your Beam class. This ties it to the console and makes automated testing more difficult. A layered architecture is more suitable :

# The Beam class is only concerned by business logic.
# Notice how the logic and workflow are clear and readable,
# and how easy you it would be to write tests for it.
#
class Beam

  attr_reader :span

  def initialize( span )
    @span        = span.to_f
    @load_points = {}
  end

  def add_load_point( distance, magnitude )
    distance, magnitude = distance.to_f, magnitude.to_f
    if distance < 0 || distance > span || @load_points[distance]
      raise ArgumentError, 'invalid load point'
    end
    @load_points[distance] = magnitude
  end

  def reactions
    @load_points.inject( left: 0, right: 0 ) do |hash, (distance, magnitude)|
      hash[:left]  += distance          * magnitude / span
      hash[:right] += (span - distance) * magnitude / span
      hash
    end
  end

end

# this module is an interface between your class and the user
# via the console. Notice that this module (could be a class,
# does not matter) is only concerned about asking questions,
# adapting user input to feed the Beam class interface, and
# formatting output.
#
module BeamConsole

  # here we chose to move all questions to the user to methods,
  # and name these methods with an exclamation mark at the end
  #
  def self.invoke
    beam = Beam.new( span? )
    begin
      beam.add_load_point( distance?, magnitude? )
    rescue ArgumentError => e
      puts "Invalid parameters for load point. Please retry." ; retry
    end while more?
    format_reactions( beam.reactions )
  end

  private #===================================================================

  # adapted from @nakilon's answer, tail-recursive variant
  def self.prompt( msg )
    output = gets.strip!
    return output unless output.empty?
    prompt( msg )
  end

  def self.span?
    prompt( 'Please specify span of beam' ).to_f
  end

  def self.more?
    answer = prompt( 'Do you want to add points ? (y/n)' )
    answer = prompt( 'please answer by y or n' ) unless answer =~ /^[y|n]$/
    answer == 'y'
  end

  def self.distance?
    prompt( 'At what distance should the point be placed from left?' ).to_f
  end

  def self.magnitude?
    prompt( 'Magnitude should be?' ).to_f
  end

  def self.format_reactions( reactions )
    puts "Reaction on the left is  : %.4f" % reactions[:left]
    puts "Reaction on the right is : %.4f" % reactions[:right]
  end
end

This may seem overkill, but separating concerns is the core of OOP. With this approach, you'll end up with a Beam class devoid of any responsability concerning user interaction, and that's a good thing : you want your class to perform business logic before anything else.

This way, your code will be more readable (no logic riddled with prompts), so more maintainable, but also more reusable. Imagine that one day you want to allow users to perform calculations from a web page : you could not reuse your Beam class if it is tied to the console, but you could if you separated responsibilities.


Reading numbers from three text files in C++

I'm going to be cheeky here and make a recommendation that's currently beyond what I suspect your current C++ level is, because I feel like this is a great problem to introduce templates:

Consider splitting the file reading in its own function, so that you don't have to reimplement the file loading logic three times. In this case, this will necessarily be a function template, since you can load different type of values.

Here's what it would look like:

template<typename T>
std::vector<T> read_num_file(const char* file_name) {
  // open ifstream and error check here...

  std::vector<T> result;
  T val;
  while(InFile >> val) {
    result.push_back(val);
  }
  return result;
}

int main() {
  std::vector<unsigned short> index = read_num_file<unsigned short>("Index.txt");

  ...
}


Name-spaced JavaScript wrapped in self executing function

The IIFE/SEFE/closure/whatever

A quick discussion why we use "closures" for creating our code is that the purpose of the closure/IIFE/SEFE/whatever you want to call it, is to provide a scope where you are free to declare any variables for the internals to use, without polluting the global scope:

(function(ns){

  //I can declare tons of variables and functions here
  var a,b,c,d,e,f,g ...;

  //expose only foo to the namespace
  ns.foo = function(){
    //and foo can use them here
  }

}(this.myNS = this.myNS || {}));

//but out here, we call foo, use those variables
//but none of those variables are visible
myNS.foo();

//no a,b,c,d,e,f,g ... out here

window

Now, in the case of window, the idea that they are passed into the function is to have a local reference of whatever was pointed by them. It's because of the usage of that IIFE/SEFE/closure and how the compiler works.

//-3-found "a" here
var a = 1
(function(ns){
  //-2-no "a" here, going up
  ns.foo = function(){
    //-1-no "a" here, going up
    console.log(a);
  }
}(this.myNS = this.myNS || {}));

myNS.foo();

A quick trip into the how the compiler works is that when it tries to look for a variable/function, it searches through the local function scope first. If that variable/function is not found, it will look for it in the outer/containing scope. This goes on until the compiler finds that value or when you reach the global scope and declares it as non-existent.

In the code above, you crossed 2 scopes in order to find a. If a was declared lower into the scope, you could have minimized crossings. Now, wouldn't it be better if you provided window locally instead of having the compiler find it? YES, although:

performance gain is almost negligible
code structure might be more important than this minor optimization

undefined

For undefined, it's because undefined is mutable (it's not constant/final). Its value can be changed so that it would not be undefined anymore (but somewhat "pseudo-defined"). A quick code about that can be found here:

var a = {};
a.b === undefined; // true because property b is not set
undefined = 42;
a.b === undefined; // false, because undefined is something else

So what they did to overcome this "definable undefined" was to pass nothing into the function, and by default, passing nothing to the function and naming it something in the function gives it the value of "true undefined".

Personally, I don't pass in window and undefined into my closure for some reasons:

I don't check potentially undefined values against undefined. Since undefined values are falsy, loose comparison will tell if it is undefined or more like "unusable":

//instead of this:
if(potentiallyUndefined === undefined){...do stuff...}
if(typeof potentiallyUndefined === 'undefined'){...do stuff...}

//you can do this
if(potentiallyUndefined){...do stuff...}

Like I said, it's a minor/negligible performance gain, so I don't pass in window. Besides, how much of my code uses window anyway?


Am I missing something?

Each expansion of the tree visits every vertex, either as a member of selectedSoFar or as a candidate in matrix[row].  That makes the runtime \$O(n^2)\$ in the number of vertices.

An algorithm based on ordered data will tend toward \$O(n*log(n))\$.  With a million vertices, that's 50 thousand times faster—the difference between an hour and six years.

See also Wikipedia on Prim's; there's a section on time complexity.


Calculate total miles per gallon and average per trip

One thing you need to do is methodically test your code.  So far you have only tested your code to 'work', but the point of testing is to find what doesn't work (as intended).

It's something you can also hand in and it's a good practice to get into - you will need it if you program professionally.  As your code grows you might need to look at splitting the user interface of your code from your business logic so that you can test them separately using a test program.

For small pieces of code a test plan is 'good enough' for your needs.

Logic testing - look at your looping and branching conditions to work out which inputs should bring them to each branch.  For example your UI says that inputting -1 gallons used will exit - does it?  Could your program be given zero trips, how should it handle that?

Validation testing - Could you get invalid inputs that make your code do something you didn't expect?  For example is there an opportunity for division by zero given bad input?  If user input could generate an exception then it should be mitigated.

Computational testing - Do you get an appropriate level of accuracy when you are mixing data types?  (another answer has pointed out a bug in that department.)  Are the calculation results what you expect if you work them out manually?  Do you get the correct output (for example at each loop the spec requests the average so far.)

Since your program is quite simple it would be very easy to test well.  But each time you find a bug then don't consider it an isolated problem - when you have 1 bug it usually means you have found a class of bugs and you should check if that bug crops up elsewhere, it frequently does.

Looking at your variables in this code:

totalTrips should probably be just trips since it's just a counter.
totalMilesPerGallon is just added to but you are adding an average.  Either your naming is wrong or your logic is.

This class could use a more meaningful name than MagicNumber as
   well, choosing meaningful names is a clear indicator that you have
   fully understood the problem or need your code is trying to address.
   It's also a handy 'red-flag' that if you can't think up a name easily
   that you may need to check that you understand what you want your code to do more
   clearly before you write any (more).

Looking at code reuse, do you really need all your inputs listed twice?  Is there another way it could be coded to avoid the repetition of the inputs?

Finally, you might want to double-check your formatting, your braces {...} should match up if that's the convention you're following.  Most IDE's will do this for you.

All that should give you a good handle on what you're missing and how your code can improve for now.


What you're implementing is called Bresenham's Line Algorithm.

You can get rid of the duplication by implementing the algorithm as described on wikipedia. Mirrored here for completeness:

 function line(x0, y0, x1, y1)
     real deltax := x1 - x0
     real deltay := y1 - y0
     real error := 0
     real deltaerr := abs(deltay / deltax)    // Assume deltax != 0 (line is not vertical),
           // note that this division needs to be done in a way that preserves the fractional part
     int y := y0
     for x from x0 to x1
         plot(x,y)
         error := error + deltaerr
         while error ≥ 0.5 then
             plot(x, y)
             y := y + sign(y1 - y0)
             error := error - 1.0

If you want to, you can also look at my implementation here.


Python: keeping track of info across classes by storing a variable to self

I think what you may be looking for is the Borg design pattern. It's meant for a single class to maintain state between multiple instances. Not exactly what you're looking for but you could modify it to also maintain state across multiple classes, perhaps by specifying a global for shared state:

## {{{ http://code.activestate.com/recipes/66531/ (r2)
class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
    # and whatever else you want in your class -- that's all!
## end of http://code.activestate.com/recipes/66531/ }}}

Here are some links to various code examples of this, non chronological:

Python borg pattern problem
Singleton? We don't need no stinkin' singleton: the Borg design pattern (Python recipe)
Usage example


Well, copying my answer from SO.

Think about the number of outputs of subset/4, if every cell of Solution is unbound in the beginning. There are 44*4 = 4,294,967,296 outputs. Now you might know why your code is so slow.

You should call valid/1 inside of subset/2. Test if the puzzle is still valid after inserting one number:

subset(_,[],_).
subset(RCS,[H|T],List):-
    member(H,List),
    valid(RCS),
    subset(RCS,T,List).

% Like \+member(H,T) but unbound cells are ignored
nonmember(_, []).
nonmember(H1, [H2|T]) :-
    (var(H2); H1 \= H2),
    nonmember(H1, T).

different([]).
different([H|T]):-
    (var(H); nonmember(H,T)),
    different(T),!.

valid([]).
valid([Head|Tail]) :-
    different(Head),
    valid(Tail),!.

sudoku(Puzzle) :-
    Puzzle = [S11, S12, S13, S14,
              S21, S22, S23, S24,
              S31, S32, S33, S34,
              S41, S42, S43, S44],

    Row1 = [S11, S12, S13, S14],
    Row2 = [S21, S22, S23, S24],
    Row3 = [S31, S32, S33, S34],
    Row4 = [S41, S42, S43, S44],

    Col1 = [S11, S21, S31, S41],
    Col2 = [S12, S22, S32, S42],
    Col3 = [S13, S23, S33, S43],
    Col4 = [S14, S24, S34, S44],

    Square1 = [S11, S12, S21, S22],
    Square2 = [S13, S14, S23, S24],
    Square3 = [S31, S32, S41, S42],
    Square4 = [S33, S34, S43, S44],

    RCS = [Row1, Row2, Row3, Row4,
           Col1, Col2, Col3, Col4,
           Square1, Square2, Square3, Square4],

    subset(RCS, Puzzle, [1,2,3,4]).

Next optimization would be not to test all rows, columns and squares after every insert, but only the affected ones (3 instead of 12):

subset([], _).
subset([(P,RCS) | T], List):-
    member(P, List),
    valid(RCS),
    subset(T, List).

% Like \+member(H,T) but unbound cells are ignored
nonmember(_, []).
nonmember(H1, [H2|T]) :-
    (var(H2); H1 \= H2),
    nonmember(H1, T).

different([]).
different([H|T]):-
    (var(H); nonmember(H,T)),
    different(T),!.

valid([]).
valid([Head|Tail]) :-
    different(Head),
    valid(Tail),!.

sudoku(Puzzle) :-
    Puzzle = [S11, S12, S13, S14,
              S21, S22, S23, S24,
              S31, S32, S33, S34,
              S41, S42, S43, S44],

    Row1 = [S11, S12, S13, S14],
    Row2 = [S21, S22, S23, S24],
    Row3 = [S31, S32, S33, S34],
    Row4 = [S41, S42, S43, S44],

    Col1 = [S11, S21, S31, S41],
    Col2 = [S12, S22, S32, S42],
    Col3 = [S13, S23, S33, S43],
    Col4 = [S14, S24, S34, S44],

    Square1 = [S11, S12, S21, S22],
    Square2 = [S13, S14, S23, S24],
    Square3 = [S31, S32, S41, S42],
    Square4 = [S33, S34, S43, S44],

    RCS11 = (S11, [Row1, Col1, Square1]),
    RCS12 = (S12, [Row1, Col2, Square1]),
    RCS13 = (S13, [Row1, Col3, Square2]),
    RCS14 = (S14, [Row1, Col4, Square2]),
    RCS21 = (S21, [Row2, Col1, Square1]),
    RCS22 = (S22, [Row2, Col2, Square1]),
    RCS23 = (S23, [Row2, Col3, Square2]),
    RCS24 = (S24, [Row2, Col4, Square2]),
    RCS31 = (S31, [Row3, Col1, Square3]),
    RCS32 = (S32, [Row3, Col2, Square3]),
    RCS33 = (S33, [Row3, Col3, Square4]),
    RCS34 = (S34, [Row3, Col4, Square4]),
    RCS41 = (S41, [Row4, Col1, Square3]),
    RCS42 = (S42, [Row4, Col2, Square3]),
    RCS43 = (S43, [Row4, Col3, Square4]),
    RCS44 = (S44, [Row4, Col4, Square4]),

    RCS = [RCS11, RCS12, RCS13, RCS14,
           RCS21, RCS22, RCS23, RCS24,
           RCS31, RCS32, RCS33, RCS34,
           RCS41, RCS42, RCS43, RCS44],

    subset(RCS, [1,2,3,4]).

Now you should be able to increase the puzzle size to 9×9 and still have a reasonably fast solver.


Angular includes a tiny subset of jQuery called jqLite which is what you get with angular.element.  The html() method on it specifically only accepts a string, not an array of jqLite objects like jQuery normally does I think (unless it's a bug).

One solution would be to use jquery.  If you include jquery before angular, angular will use your jquery instead of the embedded jqlite.  Swap the script tags in this fiddle to see it toggle between working and not.

Another solution would be to use the outerHTML of your canvas element's html node like in this fiddle:

tElement.html(canvasElement[0].outerHTML);

I think using canvasElement[0] is fine.


You can use the String.prototype.replace function to "loop" through all the relevant lines of the data. It accepts a regex pattern, and a function to handle the the matched text and return the replacement text. Here, however, we don't care about actually replacing anything; we just use it to find each key/value pair

function parsePlaylist(data) {
  var tracks = [], currentTrack;

  // do a multi-line replace-all for "(key): (value)", but don't
  // bother actually replacing anything, or storing the resulting
  // string. We're just using it to walk through the data
  data.replace(/^([^:]+):\s*(.+)$/gmi, function (match, key, value) {
    // if this is the start of a new track (indicated
    // by a "file" field), or the start of the loop,
    // create a new object to hold the data
    if( !currentTrack || key === "file" ) {
      currentTrack = {};
      tracks.push(currentTrack);
    }

    // add the key/value pair
    currentTrack[key] = value;
  });

  return tracks;
}

That'll give you this:

[ { file: 'http://192.168.100.214/Music/justchill.mp3',
    Artist: 'Brian G',
    Title: 'Just Chill',
    Track: '1',
    Date: '2014',
    Genre: 'Instrumental',
    Pos: '0',
    Id: '0' },
  { file: 'http://192.168.100.214/Music/justchill.mp3',
    Pos: '1',
    Id: '1' },
  { file: 'http://streaming.radionomy.com/ABC-Lounge',
    Pos: '2',
    Id: '2' } ]


Insertion Sort Implementation Efficiency

You are looping over the array elements, and once you find an element greater than the element you are about to insert, you have to again find that element in the array of elements.

        insertion_index = len(sorted_array)
        for elem_sorted in sorted_array:
            if elem_sorted > elem:
                insertion_index = sorted_array.index(elem_sorted)
                break

You could instead use enumerate to extract both the element and its index:

        insertion_index = len(sorted_array)
        for index, elem_sorted in sorted_array:
            if elem_sorted > elem:
                insertion_index = index
                break

When you search for an element using a for loop and break when you find the element of interest, if you don't find the element, the for loop will execute an optional else: clause, so you don't need to preset the insertion_index:

        for index, elem_sorted in sorted_array:
            if elem_sorted > elem:
                insertion_index = index
                break
        else:
            insertion_index = len(sorted_array)

Biggest inefficiency

sorted_array is in sorted order.  You could use a binary search to find the insertion location, \$O(\log N)\$, instead of a linear search \$O(N)\$.


Retrieve next card(s) base on the provided parameter

Ok, in response to the conversation in comments, Here's my suggested first step:

  def index
    render json: cards, status: :ok
  end

  private

  def cards
    if next_cards
      current_user.next_cards(next_cards.to_i)
    else
      current_user.cards
    end
  end

  def next_cards
    params[:next_cards]
  end

the larger issue here though is that you are essentially using params[:next_cards] as a switch for what should essentially be two controller actions.  the latter being the index action of the cards controller, and the former being something along the lines of user/next_cards/:id . Possibly a next cards controller.  The show action of which could look something like

routes.rb:

resource :next_cards, only: :show

app/controllers/next_cards_controller.rb:

def show
  render json: current_user.next_cards(params[:id])
end

controllers don't have to have a 1 to 1 mapping with models. This way takes advantage of rails routing to validate that params[:id] will always be present. thereby eliminating the need for a nil check.

Obviously this could take more time as your views will need to be updated to reflect the new route. If it's a greenfield app, go ahead and do it right now. If it's an old, bloated codebase, start small with the refactor and do it in chunks.


Since, as you mentioned, you are pretty new to this, i will start with some novice level advice:

You should refactor your code into seperated functions, both in order to seperate functionality with different purpose, and to be able to reuse.

function connect_db($config)
{
// Create connection
    $conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);

    // Check connection
    if ($conn->connect_error){
        die('Connection failed. ' . $conn->connect_error);
    }
    return $conn;

}

function prepare_visitors_table($conn)
{

    // if table not made yet, create it
    if(!$conn->query ("DESCRIBE visitors")) {
        // sql to create table
        $sql = 'CREATE TABLE visitors(
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            email VARCHAR(50) NOT NULL,
            message VARCHAR(500),
            reg_date TIMESTAMP
        )';

        if (!$conn->query($sql)){
            die ('Sorry there was an error. Please try again later.');
        }

    }

}

function save_visitor($conn, $name, $email, $message)
{

    //insert data into table
    //clean data for SQL query
    $name = mysqli_real_escape_string($conn, $name);
    $email = mysqli_real_escape_string($conn, $email);
    $message = mysqli_real_escape_string($conn, $message);

    $sql = "INSERT INTO visitors (name, email, message)
        VALUES ('$name', '$email', '$message')";
    return $conn->query($sql) ;
}

function send_visitor_notification($name, $email, $message)
{

    // email
    // addresses and default subject
    $to = ''; // add details
    $from = ''; // add details
    $subject = 'New form entry on website';

    // prepare message variables - !not sure how to make quotes etc. display properly in email body
    $message = wordwrap($message);
    $body = <<<_END
    Name: {$name}
    Email: {$name}
    Message: $message
    _END;

    // send
    mail($to, $subject, $body, $from);

}

$config = parse_ini_file('../config.ini'); // path may vary depending on setup

$conn = connect_db($config);

prepare_visitors_table($conn);
if (save_visitor($conn, $data['name'], $data['email'], $data['message'])) {
        $usrMsg = 'Thank you we\'ll be in touch when we have some news';
    } else {
        die ("Sorry, there was an Error. Please try again later.");
    }
send_visitor_notification($data['name'], $data['email'], $data['message']);

$conn->close();


URL-safe pseudorandom string generator in C#

const string TOKENALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";

I learnt the hard way that the problem with using . in a URL token sent by e-mail is that certain mail clients (Outlook in particular) will attempt to auto-detect URLs in a plain text email, but will exclude a trailing . from the inferred URL, so when your user clicks on the auto-generated link they send an invalid token. I suggest that you change . to _.

    static string NewToken(int length = 16)

Length in what units? Generally with cryptographic stuff it's clearer to explicitly use bits as the unit of length.

        var rnd = new RNGCryptoServiceProvider();

As already noted in comments, this is IDisposable and the standard using pattern is preferred.

        var token =
            Enumerable
                .Range(0, length)
                .Select(i => TOKENALPHABET[tokenBytes[i] % TOKENALPHABET.Length])
                .ToArray();

Firstly, this could be simplified to

        var token =
            tokenBytes
                .Select(b => TOKENALPHABET[b % TOKENALPHABET.Length])
                .ToArray();

But secondly, by only using 6 bits per byte you're throwing away 25% of the entropy which the system just produced for you. On busy servers, cryptographic-grade entropy is a valuable resource and you should only request as much as you need.


To check if a string C is an interleaving of A and B Code

Just about every #include in this code is unneeded. You use cin, strlen and printf. That requires just <cstring>, <cstdio>, and <iostream>. In fact, if you're using C++, you should just use cout as an output stream instead of using printf, which would cut the imports down to <cstring> and <iostream>. The rest should be completely removed.

Why hardcode the array lengths as arguments?

int isInterleaved(char a[100],char b[100],char c[200],int i, int j, int k)

This should be:

int isInterleaved(char *a, char *b, char *c, int i, int j, int k)

Preferably, if you're using C++ and not C, you should instead use std::string (which would need an #include <string>.)

You're using a fairly strange (and inconsistent) brace style:

if(l3>l1+l2)
    {
        printf("C is not an interleaving of A and B\n");
        return 0;
    }

Or no indentation:

if(i>=0&&j>=0)
{

if(c[k]==a[i]&&c[k]!=b[j])
    return isInterleaved(a,b,c,i-1,j,k-1);
else if(c[k]==b[j]&&c[k]!=a[i])
    return isInterleaved(a,b,c,i,j-1,k-1);
else if(c[k]==a[i]&&c[k]==b[j])
    return isInterleaved(a,b,c,i-1,j,k-1)||isInterleaved(a,b,c,i,j-1,k-1);
else
    return false;
}

and

if(c[k]==b[j])
return isInterleaved(a,b,c,i,j-1,k-1);

This makes the code harder to read.

Your code could probably do with some commenting, at least explaining the different cases.

In the end, using some C++ features, I'd do it something like this:

#include <iostream>
#include <string>
#include <iterator>

template <typename Iterator>
bool is_interleaved_impl(Iterator a_begin, Iterator a_end, Iterator b_begin,
                         Iterator b_end, Iterator c_begin, Iterator c_end)
{
    // Case 1: We've exhausted a, so all we can do is draw the rest of the characters
    // from b, in order.
    if(a_begin == a_end) {
        if(std::distance(b_begin, b_end) != std::distance(c_begin, c_end)) {
            return false;
        }
        return std::string(c_begin, c_end) == std::string(b_begin, b_end);
    }
    // Case 2: We've exhausted b, so all we can do is draw the rest of the
    // characters from a, in order.
    else if(b_begin == b_end) {
        if(std::distance(a_begin, a_end) != std::distance(c_begin, c_end)) {
            return false;
        }
        return std::string(c_begin, c_end) == std::string(a_begin, a_end);
    }
    // Case 3: Characters can be chosen from either a OR b. In this case, we split into
    // 2 possibilities == 2 recurive calls.
    else if(*a_begin == *c_begin && *b_begin == *c_begin) {
        return is_interleaved_impl(a_begin + 1, a_end, b_begin, b_end, c_begin + 1, c_end) ||
               is_interleaved_impl(a_begin, a_end, b_begin + 1, b_end, c_begin + 1, c_end);
    }
    // Case 4: Only the next character from a matches.
    else if(*a_begin == *c_begin) {
        return is_interleaved_impl(++a_begin, a_end, b_begin, b_end, ++c_begin, c_end);
    }
    // Case 5: Only the next character from b matches.
    else if(*b_begin == *c_begin) {
        return is_interleaved_impl(a_begin, a_end, ++b_begin, b_end, ++c_begin, c_end);
    }
    // Nothing matches, so they aren't interleaved.
    return false;
}

bool is_interleaved(const std::string& a, const std::string& b, const std::string& c)
{
    if(a.size() + b.size() != c.size()) {
        return false;
    }
    return is_interleaved_impl(a.begin(), a.end(), b.begin(), b.end(), c.begin(), c.end());
}


Web API controller to get details of a travel plan or a leave request

I'd re-think your switch:

RequestBase LeaveInput = jsonSerializer.Deserialize<RequestBase>(content); is repeated, the only difference it is assigned to a different variable depending on the case.
response.Content = new ObjectContent(typeof(object), travelOutput, jsonFormatter); is also repeated, with the only difference being the second parameter.

In fact, the three lines of each case are virtually identical, except for repo.GetLeaveRequest() and repo.GetTravel(), which suggests to me that the switch should happen at a lower level.

Perhaps you could do something like this:

private ObjectContent GetObjectContent(string id, string content)
{
    var input = jsonSerializer.Deserialize<RequestBase>(content);

    object output;
    switch (id)
    {
        case "leave":
            output = repo.GetLeaveRequest(LeaveInput);
            break;

        case "travel":
            output = repo.GetTravel(travelInput);
            break;
    }

    return new ObjectContent(typeof(object), output, jsonFormatter);
}

Thus the contents of your try could become:

var content = Request.Content.ReadAsStringAsync().Result;
var response = Request.CreateResponse();
response.Content = GetObjectContent(content);
return response;

Note that I'm not sure this works, consider it more like an idea than workable code. (I just don't feel like starting up VS to test this.)

Just a couple of quick remarks:

Local variables like LeaveInput and LeaveOutput should be camelCase.
You explicitly use RequestBase and HttpResponseMessage and Task<LeaveForm>: why not use var like elsewhere in your code?


You are kind of overdoing it a little in my opinion, there are too many variables that don't really add much value, also I would change the parameter to be DECIMAL, to avoid calls using not numbers that would cause run time errors.

My implementation would look like this:

FUNCTION fnLuhnAlgorithm RETURNS LOGICAL
  (INPUT pcNumber AS DECIMAL):
/*------------------------------------------------------------------------------
  Purpose:  Applies Luhn Algorithm to check a Number
    Notes:  Returns True/False Validation based on check digit

    From the rightmost digit, which is the check digit, moving left, double the value
    of every second digit;
    if product of this doubling operation is greater than 9 (e.g., 7 * 2 = 14).
        Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together
    Compute the sum of the digits.
    Multiply by 9.
    The last digit, is the check digit.
------------------------------------------------------------------------------*/
    DEFINE VARIABLE cNumber     AS CHARACTER NO-UNDO INITIAL "".
    DEFINE VARIABLE iDigit      AS INTEGER   NO-UNDO INITIAL 0.
    DEFINE VARIABLE iSum        AS INTEGER   NO-UNDO INITIAL 0.
    DEFINE VARIABLE iLoopCnt    AS INTEGER   NO-UNDO INITIAL 0.

    cNumber = STRING(pcNumber).

    DO iLoopCnt = LENGTH(cNumber) - 1 TO 1 BY -1:

      iDigit = INTEGER(SUBSTR(cNumber,iLoopCnt,1)).

      IF iLoopCnt MODULO 2 = LENGTH(cNumber) MODULO 2 THEN
          iSum = iSum + iDigit.
      ELSE
          iSum = iSum + INTEGER(SUBSTR(STRING(iDigit * 2,"99"),1,1))
                      + INTEGER(SUBSTR(STRING(iDigit * 2,"99"),2,1)).

    END.

    IF ((iSum * 9) MODULO 10) = INTEGER(SUBSTR(cNumber,LENGTH(cNumber),1)) THEN
      RETURN TRUE.
    ELSE
      RETURN FALSE.

END FUNCTION. /* fnLuhnAlgorithm  */


AngularJS directive that manually transcludes content and has isolated scope

I am a bit confused, your directive basically would do what Angular already does?

When I comment out the entire testapp.directive('tag', function() { block, I see no change in the functionality of this code in fiddle.. I think you need a more extensive example for us to provide a meaningful review.

Other than that:

Your code looks fine to me
JsHint.com cannot find anything wrong besides some missing semicolons
You have 0 comments in your code


Python interactive console which automatically reload modules

Automatic tools

PEP8: I'd say your code's OK style wise, but this is what the checker said:

1:1: E266 too many leading '#' for block comment
19:40: E261 at least two spaces before inline comment
27:80: E501 line too long (86 > 79 characters)
29:80: E501 line too long (82 > 79 characters)
31:80: E501 line too long (82 > 79 characters)

Pylint: Apart for missing doc strings, the only thing it finds is that in your runcode method, you shadow a module name, code. It may be better to call you argument code_to_run or inp so that code always refers to the module. But, as the method's short, its not a big deal.

Human tool

Your check_modules_for_reload method looks like this:

def check_modules_for_reload(self):
    for module_name, module in sys.modules.items():
        if hasattr(module, '__file__'):
            module_modifier_time = os.path.getmtime(module.__file__)

            if module_name in self.stored_modifier_times:
                if module_modifier_time > self.stored_modifier_times[module_name]:
                    imp.reload(module)
                self.stored_modifier_times[module_name] = module_modifier_time
            else:
                self.stored_modifier_times[module_name] = module_modifier_time

Things to note:

Your if statement checking if you have already seen the module contains the line:

self.stored_modifier_times[module_name] = module_modifier_time

As this occurs in both branches of the if statement, you can move it out, after the branching.
Currently your code involves 4 indentation levels. You can reduce this by inverting the check_modules_for_reload logic and using continue.

The code now looks like:

def check_modules_for_reload(self):
    for module_name, module in sys.modules.items():
        if not hasattr(module, '__file__'):
            continue
        module_modifier_time = os.path.getmtime(module.__file__)

        if module_name in self.stored_modifier_times:
            if module_modifier_time > self.stored_modifier_times[module_name]:
                imp.reload(module)
        self.stored_modifier_times[module_name] = module_modifier_time

We see that the nested if could be reduced to:

if module_name in self.stored_modifier_times and module_modifier_time > self.stored_modifier_times[module_name]

That's long and horrid. But we can use dict.get combined with the fact module_modifier_time > module_modifier_time is False to produce:

if self.stored_modifier_times.get(module_name, module_modifier_time) < module_modifier_time

Which is slightly shorter. The code is now:

def check_modules_for_reload(self):
    for module_name, module in sys.modules.items():
        if not hasattr(module, '__file__'):
            continue

        module_modifier_time = os.path.getmtime(module.__file__)
        if self.stored_modifier_times.get(module_name, module_modifier_time) < module_modifier_time:
            imp.reload(module)
        self.stored_modifier_times[module_name] = module_modifier_time

Two lines shorter, two indentation levels and a bit more DRY. It might not be much, but the code was good to start with. Other things:

os.getmtime may throw OSError, but assuming no ones deleting modules or doing weird things this should not matter.
imp.reload could throw a whole horde of exceptions, crashing the shell. E.g.:

>>> m.a
Traceback (most recent call last):
File "rl.py", line 32, in <module>
    ModuleReloadingConsole().interact("Welcome to ModuleReloadingConsole")
File "/usr/lib/python3.4/code.py", line 234, in interact
    more = self.push(line)
File "/usr/lib/python3.4/code.py", line 256, in push
    more = self.runsource(source, self.filename)
File "/usr/lib/python3.4/code.py", line 74, in runsource
    self.runcode(code)
File "rl.py", line 17, in runcode
    self.check_modules_for_reload()
File "rl.py", line 28, in check_modules_for_reload
    imp.reload(module)
File "/usr/lib/python3.4/imp.py", line 315, in reload
    return importlib.reload(module)
File "/usr/lib/python3.4/importlib/__init__.py", line 149, in reload
    methods.exec(module)
File "<frozen importlib._bootstrap>", line 1153, in exec
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1467, in exec_module
File "<frozen importlib._bootstrap>", line 1572, in get_code
File "<frozen importlib._bootstrap>", line 1532, in source_to_code
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/home/matthew/m.py", line 1
    a=5svnls2
            ^
SyntaxError: invalid syntax

After which the shell exits.


Declare your variables a near as possible to their usage.

Initializing multiple variables on a single line removes readability and can lead in some languages to unexpected results.

If you divide two numbers and one of the numbers is a double the result is not a integer division result, hence you don't need the cast to double.

Because you are reinventing the wheel, it would be appropriate to do the Pow() by your code, because otherwise you could simply use Math.Pow(num, 0.5).

You should name your variables better. The int currentDecimal variable is storing the current calculated decimal points, but it reads that it holds the current Decimal number. You should rename it to currentDecimalPoint or something more meaningful.

This is a small application, but you should nevertheless extract the reading of the user input and the calculation of the result to separate methods.


Refactoring different type of param to reduce duplicate code

If I understand your question correctly I would refactor your method by implementing the template pattern in an OO or functional way whatever suits you best. Look at this excellent article for more information on the two options http://www.codeproject.com/KB/architecture/TMDPvsLambda.aspx.

This you'll be able to avoid duplicating your code while still being able to have different behaviors.


Some suggestions:

Why int for indices?

What if your input vector has 2^33 elements, and your system's sizeof(int) is 4? That's perfectly possible. Use std::vector<T>::difference_type (or perhaps std::vector<T>::size_type)  for indices into the vector and std::vector<T>::size_type for its size.

(In some cases there's some benefit to using smaller indices, but I wouldn't worry about that in your situation.)

Why just std::vector?

While std::vector is a very useful data structure, it's not the only one we might use. In fact, we might just have a raw T* and a size_t length. You're forcing your client code to copy its data into a vector to have it sorted - which is quite unnecessary.

Now, the standard C++ library approach on this matter is to template on pairs of iterators - for the beginning and the end of the range you want to sort. Another acceptable alternative, but which will only work for a consecutive range of memory, is to use a gsl::span<T> (and you can easily extract a span from a vector using v.begin() and v.end()).

In the hopefully-near future you would be able to take a range, but this has not been standardized yet.

Use meaningful names

Suppose I want to use your merge_sort() function:

template<class T>
void merge_sort(std::vector<T>& v, int p, int r);

How would I know what is p and what is r? Even v I can only guess from its' type. At least use:

template<class T>
void merge_sort(std::vector<T>& data_to_sort, int start_index, int end_index);

... and see also the next point for an even better API.

Also, you have ps, qs and rs all over your code and it's confusing. So are L and R. Remember - the reader doesn't know what you meant, only what you wrote. And s/he shouldn't have to hold a lot of "semantic context" to read your code. Surely you'll agree this:

    auto start = start_index;
    auto end = end_index;
    if (start < end) {
        auto middle = (start + end ) / 2;
        merge_sort(data_to_sort, start,  middle);
        merge_sort(v, middle + 1, end);
        merge(data_to_sort, start, middle, end);
    }

is more readable than your main merge_sort() body.

Expose the API the client code would like to use

Let's ignore the iterators option for a second and stick with a vector. If I want to use your code, why should I type

merge_sort(my_vector, 0, my_vector.size() - 1);

...when I should be able to type just

merge_sort(my_vector);

...which has all the necessary information? Now in the implementation, you're using a range (via a pair of indices). But you should still offer me:

template<class T>
void merge_sort(std::vector<T>& data_to_sort)
{
     return merge_sort(data_to_sort, 0, data_to_sort.size() - 1);
}

and consider putting the rest of your code within namespace detail.

If you switch to an iterator interface, this point might become moot.

Should you really be copying so much?

You're sorting Ts. Now, sizeof(T) could theoretically be quite large, in which case the swaps you perform during the merge are very costly. In those cases, it may be more reasonable to sort a permutation of array indices, which are "compared" by comparing their corresponding Ts. (If the comparison takes about the same time as copying the whole thing, perhaps it's not that much of an issue.)

I'm not saying you should rewrite your code now, just be aware of your implicit assumption

Your merge sort requires O(n) extra space, O(1) is possible

When merging, you allocate O(n) extra space - two vectors L and R. That's ok in many cases; but it's not the optimal thing to do, complexity-wise. It's actually possible to perform a merge sort with O(1) extra memory, still maintaining O(n log(n) time - as is established in this work by Katajainen , Pasanen and Teuhola.

Again, I wouldn't go implement that instead of your merge sort.