Let's start with a bit of theory about what a class is, why you would use one, and what makes for a good one. The key idea about classes is that a class is a blueprint for a thing, and that blueprint says how that thing works. Within the class, you define all the nitty gritty details and write code carefully to keep those details nice and orderly, and from outside the class you are free to completely forget about it and assume it just works.

The first change I would suggest with your code is separate the class that represents the game from the code that deals with the players. After all, the game is one thing that you can draw a ring around in your head, and the players are outside that ring.

Now, the game should take care of details like remembering who has played where, where someone is still allowed to play, what the board will look like if someone plays in a given square, whether this board represents a game that has been won or drawn or such like, and so on.
Meanwhile the players should take care of details like deciding where to play.
For example in the Game class you might have

def is_move_legal(self, move):
    return self.board[move] != "X" and self.board[move] != "O"

And then the players, instead of

if self.board[question] != "X" and self.board[question] != "O":

Would have something like

if current_game.is_move_legal(question):

You can imagine how it's easier to work out what the second version is doing while you're thinking about how to design the players, because you don't have to think about what the board is like. As a bonus, it's easy to tell at a glance because the function has been named in a descriptive way.

Following this approach to designing a class would be quite an extensive rewrite of your game, but it would make it much clearer

As a general rule in programming, if you find yourself writing substantially the same code twice, it is worth thinking about whether you can do it once and make up the differences with a couple of variables. In particular in this case, the p1 and p2 functions are completely identical except for what letter they print and calling the other one. So you could have just one of them, and pass the "X" or the "O" it has to print and play with as a parameter.

It's important to name your functions precisely, so you can tell what they do. For example create_board would probably be better named print_board.

Similarly it's important to name your variables so that it's clear what they represent. You call both variables that you get from user input question. I can see why, but a name like chosen_move would be clearer. (But on the topic of user input, well done for checking user input, including in play_again.)

Referring to check_win, it is generally a big of a warning sign if you find yourself using single letter variable names. Think about what a represents, and call it that.

Now for a few pesky details, which are worth the time to polish.

The second player is "O" rather than "0" which you sometimes print.

In check_win are you sure you want to exit the game after a draw, but allow a rematch otherwise?

In play you have an infinite loop of switching between the two players. That's not an inherently bad thing. So long as you have some way of breaking out of it once the game has run its course, looping is a perfectly valid way to repeatedly let the same bits of code (the player choices) run.
However, in this case it never even gets half way first the first loop, because p1 calls p2 directly, and that calls p1 and so on. This recursive approach is also a valid way to do that, but you should choose one and stick with it.


Move zipped files from multiple subfolders into one master folder via loop process

This code is very hard to follow at a casual reading, because of the inconsistent and non-standard indentation (10%) and the liberal use of GoTo's (90%).

Indentation:
The following should increase your indentation level by one level - Sub\ Function, With, If, For, Do.  In addition, labels (which we'll discuss in a moment) should not be indented.  In fact, the IDE will attempt to pin them to the left margin to make that easier.

GoTo:
Just because VBA has "Basic" in the name doesn't mean that it's the non-structured Basic I knew and loved back in the late 80s.  It has evolved into a structured language, so really the only place where you should use GoTo is in error handling.  Everything else that it can possibly be used for can be accomplished with different flow control structure or functions.  For example, this section...

With FolderPath
  .Title = "Select a master folder location to store the unzipped files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect1
    MasterFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect1:

...can be restructured in a much more readable way (and get rid of the heebie-jeebies I get when I see a jump out of a With block) like this:

With FolderPath
    .Title = "Select a master folder location to store the unzipped files."
    .AllowMultiSelect = False
    If .Show = -1 Then
        MasterFolder = .SelectedItems(1) & "\"
    End If
End With

Dead Code:
Think about the line of code MasterFolder = MasterFolder, then ask yourself what this is intended to accomplish.  There is no situation that I can come up with where setting a variable to itself will accomplish anything useful.

VbNullString:
"" should be replaced with vbNullString.  Note that the two are not the same - vbNullString is a compiler constant that is basically a string pointer to null.  "" actually allocates itself as a string with zero length, which is very different, especially if you're using Declare'd functions and API calls.  The following demonstrates:

Debug.Print StrPtr(vbNullString)
Debug.Print StrPtr("")

The first returns 0, the second returns a memory address (no huge speed gains here - the compiler is smart enough to re-use the allocation).

Testing For Empty Strings: Not a huge performance issue, but testing string equity with "" (or VbNullString for that matter) is roughly 25% slower than checking to see if the length is zero.  This is due to how Strings are stored in VBA - internally they are stored as BSTR's, so the Len function only has to grab the length from the start of the string.  This is much more efficient than a string equity check, even with the function call.  So, ...

Do While strFile <> ""

... would be better as this:

Do While Len(strFile) > 0

String v. Variant Functions: You may have noticed that most string handling functions have 2 versions - the "normal" function, and a version that ends in "$".  The ones that end in "$" return a String, the others return a Variant.  If you are assigning the return value to a String or passing it to a function that takes a String as a parameter, you should use the function that returns a String.  The reason is that there is an implicit cast performed, so this...

strFile = Dir(ZipFolder & "*.zip")

...is essentially this when compiled:

strFile = CStr(Dir(ZipFolder & "*.zip"))

Much better to just do this and omit the cast:

strFile = Dir$(ZipFolder & "*.zip")

Misc: You don't need to turn off ScreenUpdating, Events, Calculation, or Alerts.  Your code doesn't do anything that would effect any of them, so it does nothing to "Optimize Macro Speed". You also don't need to set objects to Nothing.  The variable names MasterFolder and ZipFolder are confusing - something like source and destination would be much clearer.  While you're at it, I'd ditch the Hungarian notation.  You also don't need to instantiate the FileDialog twice - you can reuse the same object (which also lets you get rid of a variable, since all of the work can go into one With block).  You also don't need to concat the "\" to the end of your source folder - it's much clearer if you put the concat where it's actually required instead of in the folder dialog code. Finally, the MsgBox at the end is confusing with your current control flow.  It gives the indication that work was performed if the user cancels out of either of the folder selections.

Performance: Unzipping over 8000 files is never going to be fast, but the main performance gain that you'll get is from removing the inner loop that copies items out of the zip files one at a time.  The .CopyHere method doesn't need individual items - it can process the entire collection at once:

oApp.Namespace(MasterFolder).CopyHere oApp.Namespace(ZipFolder & strFile).Items

Final Result: Something more like this:

Sub UnzipFileMoveToMasterFolder()
    Dim appl As Shell
    Dim archive As String
    Dim destination As String
    Dim source As String

    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select a master folder location to store the unzipped files."
        .AllowMultiSelect = False
        If .Show = -1 Then destination = .SelectedItems(1)
        If Len(destination) = 0 Then Exit Sub
        .Title = "Select folder location that contains the zipped folders with desired data files."
        If .Show = -1 Then source = .SelectedItems(1)
        If Len(source) = 0 Then Exit Sub
    End With

    Set appl = CreateObject("Shell.Application")
    archive = Dir$(source & "\*.zip")
    Do While Len(archive) > 0
        appl.Namespace(destination).CopyHere appl.Namespace(source & "\" & archive).Items
        archive = Dir$
    Loop
    MsgBox "Task Complete!"
End Sub


I'd say the code itself is not bad but there are a few things to keep in mind.

i is a bad name for a string. Also, you don't need it in the instructions function, you can just print the string.
The same goes for g. It's not a good name and you can return directly the input.
guess is not a good name because the function is not guessing, it's getting the user input, so you could call it get_user_input. Also, since the number is between 100 and 999, you could add some checks that the user input is in that range, and you could use some constants to define the range.
This works correctly on python 3, but on python 2 you would use raw_input instead of input. Just something to keep in mind.
In the hint function you're printing the output of the victory function, which actually is returning nothing. That's why it works, but the proper way would be to either use the victory function only to return the winning message, or to use the victory function separately to check that the user has won. It looks like this is the main point you want to understand, so have a close look at that.
victory is also not a really good name. If you want to check that the user has won, name it has_won, or maybe is_guess_correct.
If the user enters something invalid (like a letter or an empty line) you're going to get an error. You should use exceptions there, but maybe this is a bit of an advanced topic for now?
You don't need the continue in this case, because nothing is executed after that instruction.

Modified code:

import random

LOWER_LIMIT = 100
UPPER_LIMIT = 999

def instructions():
    """Tells user how to operate program."""
    print("""
    I have selected a random 3 digit number.  Your goal is to guess my
    number in the smallest amount of of moves.  I will tell you if your
    guess is too high or too low, but that's all the help you'll get
    from me.
    """)

def get_user_input():
    current_guess = int(input("Guess the number: "))
    while (current_guess < LOWER_LIMIT) or (current_guess > UPPER_LIMIT):
        current_guess = int(input("Please enter a number between " + str(LOWER_LIMIT) + " and " + str(UPPER_LIMIT) + ": "))

    return current_guess

def hint(x):
    if x > ans:
        print("Lower")
    elif x < ans:
        print("Higher")

def is_guess_correct(x):
    if x == ans:
        print("Congratulations!  You got it!")
        return True
    return False

instructions()

ans = random.randint(LOWER_LIMIT, UPPER_LIMIT)

while True:
    x = get_user_input()
    if is_guess_correct(x):
        replay = input("Would you like to play again? y/n: ").strip().lower()
        if replay == "y":
            ans = random.randint(100,999)
        else:
            print("Okay then.  Bye-bye.")
            break
    else:
        hint(x)


Translating status codes to messages in log files

What you have looks problematic in a few ways.

You have a poor data structure for your localization strings.  You have these in an array the must be iterated every single time you are doing a lookup against it. This is an linear complexity (O(n)) operation that when executed inside your loop (another O(n) iteration) give you O(n^2) overall performance. @TimSparrow has touched on a good alternative - to load the localization strings into an associative array the will allow O(1) lookup when being used - but perhaps didn't explain how critical this is to your performance.  By building such a data structure up front, you whole algorithm goes to O(m) (to build localization data structure) + O(n) (from your log file loop) instead of O(m * n).  To illustrate the impact to your performance, let assume you have a 10K line log file and a 100 line localization file.  With your current code, this means you could have up to 1 Million lookup operations you have to perform vs. 10,100 if using a proper data structure.
This code is a memory hog.  You store every file you are working with wholly in memory, as well as storing the same data in duplicate in the result arrays you are building, not to mention all the temporary array/string conversion you have that, again mean you are going to be holding that information in duplicate in memory.  If you can get the memory utilization more optimized here, then you may be more able to do things like for each of the individual log into their own process to parallelize the work.
You should consider working with the rows in a more structured manner vs. working with them primarily as strings.  fgetcsv(), fputcsv() or similar give you better ways to parse through and write your files.

Incorporating the above thoughts should allow you to greatly streamline both the performance of your script as well as just simplify how it works.  You might end up with something like:

$localizations = [];
$handle = fopen('ErrCODES/data_en.properties','r');
// read lines from file one at a time.
while ($line = fgetcsv($handle, 0, ' ')) {
    // this part may vary based on your format
    $localizations[$line[0]] = $line[1];
}
fclose($handle);

$logFiles = glob($uploadDIR.$filepath."/original/*.[lL][oO][gG]");
// here is where at some point you may want to fork processes to paralellize
// now it is serial foreach loop
foreach ($logFiles as $logFile) {
    $translatedFile = str_replace('/original', '/translation/', $logFile);
    $logHandle = fopen($logFile,'r');
    $translateHandle = fopen($translatedFile, 'w+');
    while($line = fgetcsv($logHandle, 0, ' ') {
        // apply localization
        if(!empty($line[4]) && isset($localization[$line[4]])) {
            $line[4] = $localization[$line[4]];
        }
        fputcsv($translateHandle, $line, ' ');
    }
    fclose($translateHandle);
    fclose($logHandle);
}

A few final thoughts on style:
 - Your style is a little bit all over the place, which makes your code a littel hard to read.
 - Particularly variable naming is odd.  PHP tends to use a mix of camelCase and snake_case in most code bases you will find (internal PHP functions mix both unfortunately).  Your approach to variable syntax is very haphazard, sometimes oddly putting portions of variable names in upper case with apparent cohesive approach, sometimes first letter is uppercase, sometimes it is lower case, etc.
 - Your indentations are inconsistent.
 - You could be well-served by better use of spacing around flow control operators.  A line of code like if(isset($LINEarray[0])){$newline .= $LINEarray[0]." ";} is extremely hard to read.
 - Consider familiarizing yourself with the PHP-FIG PHP standards, particularly PSR-1 and PSR-2 which deal with aspects of coding style.  These are pretty much the de-facto industry standards.


You have produced rather nice code, so my review is restricted to just the peripherals.

import System.IO         (readFile, appendFile)
import System.Exit       (exitSuccess)
import System.Directory  (doesFileExist, getHomeDirectory)
import Data.Time         (getZonedTime)
import Data.Char         (isDigit, isSpace)
import Network.BSD       (getHostName)
import Network.Curl      (curlGetString, URLString, CurlOption(CurlTimeout))
import Network.Curl.Code (CurlCode(CurlOK))
import Network.Info      (getNetworkInterfaces, NetworkInterface, name, ipv4)
import Control.Applicative (<$>, <*>)

localFilePath :: FilePath
localFilePath = "/myhaskell/iplog.log"

dyndns :: URLString
dyndns = "http://checkip.dyndns.org"

myEth = "eth0"

It is nicer to separate out self contained functions even if they are of type IO a (You already have some, but take out as much as you can.)

getLogPath :: IO String
getLogPath = flip (++) localFilePath <$> getHomeDirectory

The warning that there are no external ips should really be elsewhere.

getCurlIP :: URLString -> IO String
getCurlIP url = extract <$> curlGetString url [CurlTimeout 60]
  where extract (CurlOK, str) = str
        extract _ = "0.0.0.0"

getLocalIP :: [NetworkInterface] -> String
getLocalIP = show . ipv4 . head . filter (flip (==) myEth . name)

Your ip extraction can be simplified further.

firstWord :: String -> String
firstWord = takeWhile (not . isSpace)

getFileIP = firstWord

I modified your implementation a bit to make it clear what is happening. We take letters while they are not numbers, and drop the suffix that start with '<'
If your parsing goes beyond this, then go for parsec.

-- "<title>Current IP Check</title>
--  Current IP Address: 24.20.128.212\r\n"
extractIp :: String -> String
extractIp = takeWhile (/= '<') . dropWhile (not . isDigit)

Readfile shouldn't really say that a file if it does not exist will be created. It should just read the given file and return the value. The check and warning should be done elsewhere.

catFile :: FilePath -> IO String
catFile fp = doesFileExist fp >>= checkExist
  where checkExist True = readFile fp
        checkExist False = return []

checkS s [] = do
  print ("File does not exist - and will be created\n" ++ "at: ~" ++ s)
  return []
checkS s str = return str

Using auxiliary definitions can make your code read much better. Prefer sequence to do notation when values are not used in intermediate computations.
Try to move out of the imperative mindset when using do notation. (the do notation makes it easy to write 'c' in haskell :) ), using auxiliary functions can help you there. (I used case instead of if/then because that is what I prefer, there is no particular reason for that except that it makes it easy to use destructuring easier if I need to.)

main :: IO ()
main = do
    currentIP <- getCurrentIP
    iplogFilePath <- getLogPath
    oldIP <- getSavedIP iplogFilePath
    checkS iplogFilePath oldIP
    case oldIP /= currentIP of
      True -> getContent currentIP >>= appendFile iplogFilePath
      _ -> exitSuccess
  where getContent ip = unwords <$> sequence [return ip, show <$> getZonedTime, getHostName,
                                  getLocalIP <$> getNetworkInterfaces]
        getSavedIP path = getFileIP <$> catFile path
        getCurrentIP = extractIp <$> getCurlIP dyndns


Find values in list which sum to a given value within tolerance

In keeping the same algorithm, there's a bunch of extra work you're doing that's slowing you down. I am using the word slow loosely, since the one example you provided is still more or less instantaneous and the timings I performed were based on 100,000 runs.

Leave iterables alone

You wrap your combinations() call with list(). This means that you have to do actually create all the combinations up front, then iterate over them. But you never actually need all of them at once. You just need them one at a time. Changing your body to:

results = [list(comb) for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(map(float, comb)) < target+tolerance]

drops runtime from 2.64s to 2.45s. Furthermore, comb is going to be a tuple, so that's fine as is too:

results = [comb for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(map(float, comb)) < target+tolerance]

Down to 2.24s. Another 10%.

Building lists for no reason

Our numbers are already summable, no need to cast them to float first. You're making a whole bunch of extra lists that you're immediately discarding - just to be able to do a sum. But you can already do a sum:

results = [comb for comb in itertools.combinations(dataArray, i)
           if target-tolerance < sum(comb) < target+tolerance]

That alone brings us down to 1.10s. An enormous savings.

Comparisons

One comparison is faster than two comparisons, so let's just do the one:

results = [comb for comb in itertools.combinations(dataArray, i)
           if abs(sum(comb) - target) < tolerance]

Down to 1.04s.

What do you actually want

This doesn't yield all of the potential partial sums. It will yield some sums if any exist, and will return None otherwise - but it won't give you all of them. If you want all of them, you'll have to loop through all of the is. If you just want the first one, then this:

for i in xrange(1, len(dataArray)+1):
    for comb in itertools.combinations(dataArray, i):
       if abs(sum(comb) - target) < tolerance:
        return comb

just got reduced to 0.67s.

As Joe Wallis suggests, you probably want:

for i in xrange(1, len(dataArray)+1):
    for comb in itertools.combinations(dataArray, i):
       if abs(sum(comb) - target) < tolerance:
        yield comb

That way the caller can decide if one is sufficient or if all of them are needed.


Program to provide CRUD operations for a Boxers(Fighter) table in a database

Convert member field to local variable when you can

In BoxerDAO, the myBoxerDB member can be converted to a local variable.
Each utility method gets an SQLiteDatabase instance from the helper.
The class needs only an SQLiteOpenHelper as a member field.

Refer to types by interfaces

In BoxerDAO,
myScoresHelper can be declared as an instance of SQLiteOpenHelper.
It doesn't use any features of BoxScoresHelper.

Class design

BoxerDAO is only aware of Context to get an instance of BoxScoresHelper.
It would be better if it wasn't aware of Context at all.
You could pass to the constructor an SQLiteOpenHelper instead.

Naming

Prefixing member fields with "my" is not a common convention.
You could simply drop that.

Coding style

There are too many blank lines in the code.
This is unnecessary, it would be good to trim the code a little.


Validating multiple parameters by regex and length

Mutating State

I really don't like that your validation functions modify the data object that they are given. It seems like an unnecessary mutation that's mixing data with error codes. Do you have any particular reason for returning the data object? If it's passed into the function, then wouldn't the user already has a pointer to it? My reasoning is that you could instead return an failed validation response object instead of mutating the data object. Some problems with mutating the data object are immediately clear; now you can't have a property in data called code, message, resStatus, or resMessage.

Singe Exit Point

I'm not sure if this came from sanitizing the code, but the returns in the validateResponse functions are a bit redundant. One programming platitude is to strive to give functions one exit point. Currently, your validateSecondTypeRequest function has three exit points:

Validation.prototype.validateSecondTypeRequest= (data) => {
  if (!isParameterOneLengthValid(data.parameterOne)) {
    data.code = 0;
    data.message = 'Length of the parameter one is invalid';
    return data; // these returns could be merged
  } else if (!isParameterOneValid(data.parameterOne)) {
    data.resStatus = 1;
    data.resMessage = 'Parameter one is invalid';
    return data; // these returns could be merged
  }

  return data; // these returns could be merged
};

The returns in the if else block are unnecessary and could be easily eliminated to:

Validation.prototype.validateSecondTypeRequest= (data) => {
  if (!isParameterOneLengthValid(data.parameterOne)) {
    data.code = 0;
    data.message = 'Length of the parameter one is invalid';
  } else if (!isParameterOneValid(data.parameterOne)) {
    data.resStatus = 1;
    data.resMessage = 'Parameter one is invalid';
  }

  return data;
};

Eliminating Duplicate Code

Write a function for each parameter:

function validateParameterOne(value) {
  let result;

  if (value.length >= 5 && value.length <= 10) {
    result = {
      code: 0,
      message: 'Length of the parameter one is invalid'
    };
  };
  else if (!(/[^A-Za-z\-0-9\,\.]/.test(data))) {
    result = {
      resStatus: 1,
      resMessage: 'Parameter one is invalid'
    };
  }

  return result;
}

Not only do you get rid of the duplication, but now you have fewer functions; all your code for validating parameterOne is in contained in one spot. Also, now you can write your validateTypeRequest functions like so:

Validation.prototype.validateFirstTypeRequest= (data) => {
  let result;

  if (!result) {
    result = validateParameterOne(data.parameterOne);
  }

  if (!result) {
    result = validateParameterTwo(data.parameterTwo);
  }

  // If you HAVE to return and mutate data
  //if (result) {
  //  return Object.assign(data, result);
  //}

  return result;
}


I don't know how many times you wish to use this on your project so I tested and I suggest you to first extract the list from the method context and receive it as argument.

public void showAlertDialogWithList(List<String> mAnimals) {

    final CharSequence[] animals = mAnimals.toArray(new String[mAnimals.size()]);
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Animals");
    dialogBuilder.setItems(animals, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            String selectedText = animals[i].toString();
            Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
        }
    });

    AlertDialog alertDialogObject = dialogBuilder.create();
    alertDialogObject.show();
}

Then you can extract a class and put it in some util package making it available to entire project like this one:

public class AlertDialogList {
    public static void showAlertDialogWithList(String title, List<String> mAnimals, final Activity activity) {

        final CharSequence[] animals = mAnimals.toArray(new String[mAnimals.size()]);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
        dialogBuilder.setTitle(title);
        dialogBuilder.setItems(animals, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String selectedText = animals[i].toString();
                Toast.makeText(activity.getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog alertDialogObject = dialogBuilder.create();
        alertDialogObject.show();
    }
}

and use it like this

 AlertDialogList.showAlertDialogWithList("Animals Title", this.animals, this);


Install a Python package based on active_gpu or version

For this kind of problem you want to build a command line with variables, and run it only once.

You only have a few cases but the benefits of this approach become apparent as you add more cases: you don't need an exponential number of branches to keep up.

This code does not exactly follow the logic of your code but it's probably close enough.  I'm using an associative array to build the param variable, and bash regular expressions to test for multiple no-param cases.

#!/bin/bash
declare -A gpu_param=( [true]=-gpu )
[[ $version =~ nightly|dev-gpu ]] || param=package${gpu_param[$active_gpu]}==
pip install $param$version


The primary intent of your function is to get Patient instance. Secondary intent is to notify of the error. You should always attempt to translate the intent to code and function names. So, your function should return a Patient instance (happy path), or an ActionResult as an out parameter in case something goes wrong. Usually an out keyword is used when the variable is initialized inside of the function, not the ref keyword. This is done mainly to make your intent more declarative and obvious.

private Patient GetPatient(int? patientId, out ActionResult errorResult)
{
    errorResult = null;
    var patient = null;
    if (patientId == null)
    {
        errorResult = HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    else
    {
        patient = patientService.GetPatient(patientId.Value);

        if (patient == null || patient.PharmacyId != User.PharmacyId())
        {
            errorResult = HttpNotFound();
        }
    }

    return patient;
}

and the call would look like:

 ActionResult errorResult;
 var patient = GetPatient(patientId, out errorResult);
 if (errorResult!= null)
 {
     return errorResult;
 }
//do the rest of the Patient processing


Replacing a variable in a loop by records from a Table

Selecting from Date_Table in a
One option is to select Exit_Date direct from Date_Table in a. The ordering of the end results won't be the same so you may need to add an ORDER BY clause (e.g. with DATEPART()).
 with
      a as(
        select dateadd(yy,-1,Exit_date) d,0 i
        from Date_Table WHERE Date_ID <=5
          union all
        select dateadd(yy,-1,d),i+1 from a where i<14
      ),
      b as(select d,datediff(dd,0,d)%7 dd from a)
SELECT d from b --order by DATEPART(MM,d) desc

See a sample here in this SQLFidle.
Cursor
Like I mentioned in my comment, another option is to use a Transact-SQL cursor. In the squery below, we keep the temp variables @d and @EDTable. The SELECT statement from Date_Table could have ORDER BY Date_ID ASC added if you wanted to ensure those go in order (in case the records were not added sequentially).
declare @d date;
declare @EDTable table (Exit_Date  Date);
declare dateCursor CURSOR FOR
    select Exit_Date from Date_Table WHERE Date_Id <=5;

OPEN dateCursor

FETCH NEXT FROM dateCursor INTO @d

WHILE @@FETCH_STATUS = 0
BEGIN
    with
      a as(
        select dateadd(yy,-1,@d) d,0 i
          union all
        select dateadd(yy,-1,d),i+1 from a where i<14
      ),
      b as(select d,datediff(dd,0,d)%7 dd from a)
     insert into @EDTable select d from b;--*/
    FETCH NEXT FROM dateCursor
    INTO @d
END
CLOSE dateCursor;
DEALLOCATE dateCursor;

SELECT * FROM @EDTable

I am trying to get a SQL Fiddle working but having issues with the line endings. I will update when I figure that out.


I'd suggest a couple of things.

Firstly, this is a typical Euler problem example in that Euler usually provides an example test case. Build that into your code so that you confidently refactor.

Secondly, I recommend separating the algorithm from the reporting of its results; this again supports writing built in tests without generating unwanted output.

Taking this approach, you remove the need for a command line or inputs; just keep adding test cases to the code.

I've also taken the liberty of removing/renaming  a and b from the loop, but some may consider your original more readable in this respect. What is worth doing is making sure all your variable names are meaningful.

int sumOfEvenFibonaccis(int limit, int* steps)
{
    int prior = 1;
    int even_fibbonaci = 2;
    int sum = 0;//sum of even up to 2nd term
    int steps_taken = 0;
    do{
        sum += even_fibbonaci;
        prior += 2 * even_fibbonaci;
        even_fibbonaci = 2 * prior - even_fibbonaci;
        steps_taken++;
    } while (even_fibbonaci<limit);
    if (steps != NULL)
        *steps = steps_taken;
    return sum;
}

struct TestCase
{
    int limit;
    int result;
};

struct TestCase testCases[] =
{
    { 89, 2 + 8 + 34 }
};

int numTestCases = sizeof(testCases) / sizeof(testCases[0]);

void runTests()
{
    for (unsigned i = 0; i != numTestCases; ++i)
    {
        int testResult = sumOfEvenFibonaccis(testCases[i].limit, 0);
        int expectedResult = testCases[i].result;
        assert(testResult == expectedResult);
    }
}

int main(int argc, char ** argv)
{

    runTests();

    int steps = 0;
    int result = sumOfEvenFibonaccis(4000000, &steps);
    printf("Result: %d using %d steps", result, steps);

    return 0;
}


Finding duplicate files using md5sum Unix command

Well this was a very satisfying problem, thanks for sharing!

First of all, calling external resources is expensive, there for not optimized, which you ask for. Else wise, calling external resources can be preferable if the external resource is something like shell on a platform you have control over. That's the reasons I removed them and substituted them with python built-ins. It's pretty much the only reason this code is slightly faster then yours.

I found one small error in your code. What if a file you try to hash has spaces? The problem occurs when you split the return from md5_checksum, it splits to as many values as there are white spaces.

The most time consuming function of both our code is walk. It's easy to check these where cpu-time went with profilers. And python has a builtin I like, but there are many. It's the cProfiler, check my code for usage.

The biggest change was refactoring the function are_identical for

if any(cmp(x, y) for x in paths for y in paths if y != x):
                print('\nThey are identical\n')

They do the same thing, but the any() builtin, is.. as well faster, then iterating over lists.

I did remove your function comments, as they can be substituted for good function names and annotations. Do you agree?

from os import walk
from os.path import join
from hashlib import md5
from filecmp import cmp
from base64 import b64encode
from time import time
import cProfile

def md5_checksum(file_path: str) -> (bytes, str):
    """ Returns the raw MD5 bytes here used as checksum a given files content """

    with open(file_path, "rb") as f:
        file = f.read()
    m = md5()
    m.update(file)
    return m.digest(), file_path

def md5_checksum_table(dir_name: str, suffix: str) -> {bytes: [str]}:
    """
    Searches a directory for files with a given file format (a suffix) and
      computes their MD5 checksums.
    """
    table = {}
    for root, sub, files in walk(dir_name):
        for file in files:
            if file.endswith(suffix):
                checksum, filename = md5_checksum(join(root, file))
                table.setdefault(checksum, []).append(filename)
    return table

def print_duplicates(checksums: {bytes: [str]}):
    """ Prints paths of files have the same MD5 checksum and are identical. """

    for checksum, paths in checksums.items():
        if len(paths) > 1:
            print('Files have the checksum {0} are:\n {1}'.format(b64encode(checksum),
                                                                "\n".join(paths)))
            if any(cmp(x, y) for x in paths for y in paths if y != x):
                print('\nThey are identical\n')

def main():
    start = time()
    table = md5_checksum_table('/media/sf_Shared/', '.pdf')
    print_duplicates(table)
    print("Time {:.3f}s".format(time()-start))
    cProfile.run("md5_checksum_table('/home/cly/', '.pdf')")
    cProfile.run("print_duplicates({})".format(table))

if __name__ == '__main__':
    main()

That being said, they problem statement seems foggy. The MD5 function does not yield the same hash for two different sets of data, when concerned with these kinda problems. That is way it is called a hash function or a one way function. If the hashes is identical the content is identical.

The last thing I will say, is that even the very fast hash function MD5, is slower then a efficient comparing of the content. So I criticize the problem not your solution.

Thanks! Good work.


Revealing module implicity calling an internal function - is this a “smell”

In this case, you don't actually use the new keyword. It's valid to return something from a constructor, since constructors are functions as well. But when you use new to construct objects, it should return an instance of that constructor. In your case, you are returning an object, one that is not tied in any way to the constructor.

Here's the revealing module pattern and how it's used:

function createModule(name){

  //your private members, enclosed in createModule
  var privateVar = name;

  function privateFn(){
    console.log(privateVar);
  }

  //return a newly created object as the module
  return {
    //here, we have a function
    //since we live in the same scope as the privates, we can
    //also emulate getters and setters, classical OOP style
    getName : function(){
      privateFn();
    },
    setName : function(name){
      privateVar = name;
    }
  }
}

var newModule = createModule('mymodule');
newModule.getName(); //mymodule
newModule.setName('newname');
newModule.getName(); //newname

Now there are issues with this pattern, especially in usage:

Pros

It emulates private members. This would be an easy start for developers coming from Classical OOP.
Since the members are directly attached in the module, or at least only one scope above in the closure, they are fast.
No prototype chains to worry about.

Cons

Creating multiple modules mean creating multiple objects, each with it's own scope and functions. One module's getName function is not the same as another module's getName(). Although perfectly fine (And that's how classical OOP works, as far as I know), it's bad for the browser since it uses too much memory.
You can't use instanceof to determine the modules since they all are instances of the Object object, and they are all object literals ({}) to begin with.

Best use

Single global modules, like libraries.

For spawning many modules, I suggest the native way of doing it, and would be creating instances using constructors and prototypes.

function Module(name){
  this.name = name;
}

createModule.prototype.getName = function(){
  console.log(this.name);
}

var newModule = new Module('mymodule');
newModule.getName(); //mymodule
newModule.name = 'newname';
newModule.getName(); //newname

It has its own issues as well:

Pros

Smaller memory footprint. Anything attached to the constructor's prototype is shared, not duplicated, across instances. This means one instance's getName is the same function as another instance's getName. This is because of the prototype chain (think of it as inheritance chain), where instances "inherit" the same object.

Cons

No private scope
A long prototype chain is a performance penalty, especially if the method lives far up the chain.
Overkill for a single module. It was meant to spawn multiple instances.

Best Use

Spawning multiple instances of the same kind, like elements in a game (units, enemies, bullets).

What should you use:

Depends. Libraries usually use a mix as well.

Take for instance, jQuery. The library itself is a module. They are revealed into the global scope using a modified revealing module pattern called "exports/expose pattern". Creation of instances of the jQuery object uses new, hidden behind the jQuery function.

(function(window,undefined){

  jQuery = function( selector, context ) {
    //creating a new instance here
    return new jQuery.fn.init( selector, context, rootjQuery );
  }

  //...tons of library code here...

  //Expose, assign to window, basically creating the globals
  window.jQuery = window.$ = jQuery;

}(window));

When using jQuery as an object, it hosts exposed functions. This is when the module pattern is good at - singe direct fast global access.

$.ajax
$.noConflict
$.each

But when you use jQuery to wrap elements, wrap objects etc., it creates an instance of the constructor. This is where the constructor pattern is good at - creating multiple objects of the same kind.

//methods on these selectors are basically the same function, shared
// where in this case, each is shared
$('html').each(...
$('body').each(...
$('head').each(...

$('head').each === $('body').each //true


Catch specific exceptions, avoid Exception

This is a good example where it's a bad idea to catch Exception:

try {
    total = Integer.parseInt(entry);
    return Integer.toString(permutate(total));
} catch(Exception e) {
    return "Invalid input";
}

The catch here was clearly intended for parsing errors,
but what if something goes wrong in permutate due to some bug?
The bug will get masked under an "Invalid input" response.

It's good to catch the most specific exception type.
It also communicates to readers of the code what exactly can go wrong with the code.

Limit the body of the try block as much as possible

Still on the previous example,
catching NumberFormatException is a good first step, but not enough.
You should also move the permutate call outside the try-catch block,
to avoid catching NumberFormatException thrown by permutate instead of the Interger.parseInt(entry) line.

Sure, if you look at the implementation of permutation this is impossible now,
but who knows, you might add a change later.
In general, it's not practical to verify all calls going out from a try block for potential hidden bugs.
It's a lot easier to just move such calls outside of the try block
and eliminate all suspicions and potential future bugs.

Avoid repeated logic

The computePermutation method has some duplication of logic in the parsing of total.
You could rearrange the code to do it only once.

Avoid duplicated string literals

The message "Invalid input." appears multiple times.
It would be good to move it to a constant.

Check empty strings with isEmpty

Instead of limit.length() == 0,
a more idiomatic way is limit.isEmpty().


Finding the maximum number in a 2D vector

Normally, I start by walking through the code and improving it step-by-step, but this time I'll start with one piece of advice and showing my final solution. Read the Iterator docs and commit the method names and a rough idea of what they do to memory!

let max = world.iter().flat_map(|r| {
    let r = r.borrow();
    r.iter().map(|unit| unit.tiles.len()).max()
}).max();

Instead of matching, seeing if something is a Some, then unwrapping it, just bind the pattern to a variable:

match max {
    None => max_row(vec),
    Some(old_max) => {
        match max_row(vec) {
            None => Some(old_max),
            Some(new_max) => {
                if old_max < new_max {
                    Some(new_max)
                } else {
                    Some(old_max)
                }
            }
        }
    }
}

Extract that max_row call to before the match, since it's done unconditionally.
Getting a default from an Option is a common pattern: Option::unwrap_or and Option::unwrap_or_else. Converting an Option<T> to another Option<U> , but only if it's Some, is also a common pattern: Option::map and Option::and_then. You should also memorize what capabilities Option and Result have.

let mr = max_row(vec);
max.map(|old_max| {
    match mr {
        None => Some(old_max),
        Some(new_max) => {
            if old_max < new_max {
                Some(new_max)
            } else {
                Some(old_max)
            }
        }
    }
}).unwrap_or(mr)

Repeat.

max.map(|old_max| {
    mr.map(|new_max| {
        if old_max < new_max {
            Some(new_max)
        } else {
            Some(old_max)
        }
    }).unwrap_or(Some(old_max))
}).unwrap_or(mr)

map(F).unwrap_or(D) is also a common pattern: Option::map_or:

max.map_or(mr, |old_max| {
    mr.map_or(Some(old_max), |new_max| {
        if old_max < new_max {
            Some(new_max)
        } else {
            Some(old_max)
        }
    })
})

I don't know how to incrementally get out of this code. One possibility is to switch to a match statement to try and flatten some of the cases:

match (max, max_row(vec)) {
    (None, new_max) => new_max,
    (Some(old_max), None) => Some(old_max),
    (Some(old_max), Some(new_max)) => {
        if new_max > old_max {
            Some(new_max)
        } else {
            Some(old_max)
        }
    }
}

std::cmp::max exists, so I'd use that:

match (max, max_row(vec)) {
    (None, new_max) => new_max,
    (Some(old_max), None) => Some(old_max),
    (Some(old_max), Some(new_max)) => Some(cmp::max(new_max, old_max)),
}

Again, I don't know a way to incrementally get from here to iterator methods. This is why I encourage everyone to memorize what functions exist so that you can read the iterator documentation when you know there's something that solves a problem.


Reordering a list in python so that no neighboring elements are equal

As the Python version was not specified, I assume Python 3; for Python 2 you need to adjust the imports from itertools

There are a number of ways you can attack this problem. One way becomes apparent if we think of an input that has no solution, which would be if more than half + 1 (rounded up) of the elements would be equal to each other, e.g. you can find a solution for [1, 1, 1, 2, 2] but not for [1, 1, 1, 1, 2, 2].

The solution would be that you group the elements and sort them by decreasing group length, then interleave first half of the elements with the rest; so, if your list is [3, 2, 2, 1, 3, 1, 1], at first you need to somehow group them, then sort into decreasing order, so that you get for example [1, 1, 1, 3, 3, 2, 2]; then you split it into 2 almost equal parts: [1, 1, 1, 3] and [3, 2, 2], and interleave these into the result: [1, 3, 1, 2, 1, 2, 3].

There are many ways to write this algorithm, here is one, using Python standard library extensively:

from collections import Counter
from itertools import chain, repeat, starmap, zip_longest, islice

def funny_op(l):
    # use Counter to count the number of each distinct element, then
    # most_common() to sort them by decreasing frequency
    counts = Counter(l).most_common()

    # counts is a list of (element, count) pairs; with the example input
    # it could be [(1, 3), (3, 2), (2, 2)]

    # we then make an iterator that iterates over each distinct
    # element, by repeating each `element` `count` times
    sorted_els = chain.from_iterable(starmap(repeat, counts))

    # now, for example input sorted_els would be an iterator yielding
    # 1, 1, 1, 3, 3, 2, 2

    # we split it into half; we round up so that the first
    # list gets the extra element
    halfway = (len(l) + 1) // 2

    # the elements that go to even indices

    even = list(islice(sorted_els, halfway))

    # and the remaining fill up the odd indices of the result list
    odd = sorted_els

    # then we interleave elements from even and odd. In case the
    # original list had odd number of elements, there'd be an
    # extra None, which we remove by islicing only len(l) elements;
    # and return the result as a list

    return list(islice(chain.from_iterable(zip_longest(even, odd)), len(l)))

To test:

print(funny_op([2, 2, 1, 1, 1]))

prints:

[1, 2, 1, 2, 1]


Creating a database class in PHP with MySQLi

What is the purpose of this class?

  Creating a database class in PHP with mySQLI

MySQLi is a "database class."  (Whatever meaning of "database class" you choose)

Are you trying to make a class that adds on to MySQLi?
Are you trying to make a class that abstracts away certain operations (a DBAL)?
Are you trying to make a class that maps objects to a database (ORM)?

require_once("db_constants.inc.php");

The file that your class is defined in does not need to be aware of your connnection details.  Only the file that uses the class needs to know that, not the file that defines the class (unless of course, it's the same file, but it rarely should be).

or die

Constructors cannot return values, so this will never work.

The proper way to handle errors with objects is exceptions.  Please note though that exceptions should only be used when something that's actually exceptional happens.  It's far to easy to fall into the anti-pattern of using exceptions as return values.

In the case of mysqli's constructor failign to create a connection, that is definitely a cause for an exception.  (I tend to avoid the possibility of an object being in an unstable state.)

closeConnection

Why does this take a parameter when the connection is encapsulated in the class?

Also, unless you're going to have an openConnection method, avoid this.  Just let the destructor handle this.  Why would a user ever want to close the connection but keep the instance alive?

PDO vs MySQLi

I'm heavily biased in this one since I've always used PDO and never written a single line of code with MySQLi, but I've never seen the advantage of MySQLi over PDO.  I suppose there's a few MySQL functionalities that MySQLi supports and PDO doesn't, but they must be quite edge cases as I've never run into anything.

Concluding Remarks

I feel like there's barely anything here to review.  The goal of your code is not quite clear.  Can you explain a little more what your end goal is?  What is the purpose of this class?  What is an example use case?


Create all combinations of length N from a given alphabet (2)

The generate_words code looks pretty good to me.

Actually, one minor thing - you can return the vector as opposed to passing out by reference. You won't get a performance hit (see move semantics), and it'll make the function easier to use:

auto words = generate_words(letters, word_length);

Some minor observations about the code in main:

1 - As a general rule, you should allocate a vector's memory up front if you know how many elements it will contain. This prevents reallocations from occurring when new elements are inserted into the vector. std::vector provides the reserve method for doing this:

std::vector<char> alphabet;
// allocate memory for at least letter.size() chars
alphabet.reserve(letters.size());
for (const auto &it : letters)
{
    // now you don't have to worry about reallocations happening
    // here
    alphabet.push_back(it);
}

See:

What happens under the hood of vector::push_back memory wise?

std::vector push_back is bottleneck

vector::reserve example code

In this case, you can skip the loop entirely by using std::vector's iterator constructor:

std::vector<char> alphabet(letters.begin(), letters.end());

2 - If you're not using the variable 'letters' after it's been initialized, you could do your sort/unique operation in place:

std::sort(letters.begin(), letters.end());
letters.erase(std::unique(letters.begin(), letters.end()), letters.end());

and then pass letters to generate_words() (you'd have to change the first parameter to a string)


Overloading operator ->* for smart pointers

Is there anything that could be improved in my code?

I think you can accomplish the same thing in much less code with just a lambda:

template <class U>
auto operator->*(U pmf) const {
    return [=](auto&&... args){
        return (ptr->*pmf)(std::forward<decltype(args)>(args)...);
    };
}

Could have a static_assert on std::is_member_pointer for extra safety.

  How to solve the second remaining problem listed at the section “Loose Ends” of Meyer’s article?

I believe the lambda solves this problem as well.

Also you could consider const propagation. If the Smart_pointer is const, do you really want to allow calling non-const member functions? I don't know. If you decide you don't, you should provde both a const and non-const overload and forward to a helper:

template <class U>
auto operator->*(U pmf) {
    return pending_mem_fun(ptr, pmf);
}

template <class U>
auto operator->*(U pmf) const {
    return pending_mem_fun(const_cast<T const*>(ptr), pmf);
}

where pending_mem_fun doesn't actually have to be a member function.


Bounded Queue with multiple consumers and multiple producers

The implementation clearly has a race condition:

Let's assume Count == _boundedCapacity - 1
Now have 2 producers call Insert simultaneously
Both simultaneously check that the current size is less than the upper bound and move beyond the while loop
Both insert an item.
Now you've exceeded the bounded capacity by 1

While it might be ok to be able to exceed the upper bound by up to the maximum number of producers - 1 the same race occurs in Take. Except on the consumer side it has the nasty side-effect of potentially trying to remove an object from an empty collection. In this case default(T) gets returned which the caller might not expect since Insert doesn't accept null objects.

Based on the null check in Insert I would infer that you never expect this to be instantiated on a value type but only reference types. I don't see any reason for it but if this should really not be allowed then add the type restriction where T: class to the implementation to make it clear.

In the end the bounded capacity really doesn't mean all that much since it's randomly exceeded and one can dequeue randomly from an empty queue.

Overall you should use BlockingCollection<T> to wrap the ConcurrentQueue<T> which implements the bounding capacity correctly. Just make sure to use the Add and Take methods accepting a CancellationToken so blocked operations can get interrupted nicely when you want to shutdown the application.


Implementing a cross-browser event utility as an exercise

Your code looks ok. Nothing really jumps out at me except these two things:

Event handlers attached via attachEvent are executed in random order (Source: http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx). You might want to create a shim to get older versions of Internet Explorer to execute event handlers in the order they were attached, which is something I believe jQuery does (or did).
Create a function that patches the event object for cross browser compatibility, so your event handlers do not have to constantly call myEvent.getEvent(e). This will prevent repeated code in your handlers.

You could create separate functions to attach events in the three different ways, and use feature detection to determine which one to use:

var myEvent = {
    init: function() {
        if (document.addEventListener) {
            this.addListener = this.addListenerStandard;
            this.removeListener = this.removeListenerStandard;
        }
        else if (document.attachEvent) {
            this.addListener = this.addListenerMSIE;
            this.removeListener = this.removeListenerMSIE;
        }
        else {
            this.addListener = this.addListenerOldSkool;
            this.removeListener = this.removeListenerOldSkool;
        }
    },

    listen: function(elements, event, handler) {
        elements = !helpers.isCollection(elements) ? [elements] : elements;

        for (var i = 0; i < elements.length; i++) {
            this.addListener(elements[i], event, handler);
        }
    },

    stopListening: function(elements, event, handler) {
        elements = !helpers.isCollection(elements) ? [elements] : elements;

        for (var i = 0; i < elements.length; i++) {
            this.removeListener(elements[i], event, handler);
        }
    },

    addListenerStandard: function(element, event, handler) {
        element.addEventListener(event, handler, false);
    },

    addListenerMSIE: function(element, event, handler) {
        element.attachEvent("on" + event, handler);
    },

    addListenerOldSkool: function(element, event, handler) {
        element["on" + event] = handler;
    },

    removeListenerStandard: function(...) { ... },

    removeListenerMSIE: function (...) { ... },

    addListenerOldSkool: function(...) { ... },

    addListener: null,

    removeListener: null
};

myEvent.init();

That way you won't be detecting the proper DOM method on each iteration of your loop.


Trying to do Type-Driven Development in F#

From a cursory glance, this looks like a good start, but I haven't made a full exegesis of the code.

A couple of observations:

The getValuesInListOfOptions function seems redundant. AFAICT, you can rewrite the function as List.choose id list, in which case you could inline that expression and remove the function.

It seems odd to me that the function with the comment The root of the program is still a higher-order function defined in the same module as all the other functions. I'd expect the root of the program to be something akin to a main function, that only takes command-line string arguments as input, if it takes any arguments at all.


poh-tay-toh poh-tah-toh, does writing the same code a different way affect readability?

I think the first is the simplest and the most readable one from the list but I'd prefer the charAt function:

x.charAt(0) !== '_'

Furthermore, I'd reverse the condition:

if string begins with '_' {
    throw error
}
do stuff

Reference:

How to get first character of string?
Flattening Arrow Code


Yes, I can poke a few holes in this.

Firstly, your eval() isn't actually doing much of anything here. From the perspective of the parser running the script, that line looks like this:

eval(party_size < 5)

This means that party_size < 5 is evaluated to false before it is passed to the eval() function. eval() then just spits this value right back out.

Some consequences of this:

It will fail to act as expected if the expression evaluates to a string value. For example, if you put "a" + "b" into your textbox, this will fail with the error ReferenceError: ab is not defined, because the JS engine will be trying to evaluate eval("ab").
It will fail if the code is anything other than a single expression. So entering this into the textbox: var a = 2; a; fails with a syntax error, even though this is a perfectly legitimate thing to pass to eval().

So let's assume that was just a silly oversight and you meant to do this:

eval: eval("'+val+'"),\

Well, this will succeed in actually executing chunks of code, until that code contains a quotation mark:

eval("var a = "a"; a + "b"");

at which point it will be broken again.

Now let's imagine you decided to get around this by changing this line to:

eval: eval("' + val.replace(/"/g, '\\"') + '"),\

Now you can be pretty confident that the code will run (in most cases) and that all you need to worry about at this point is malicious code (haha).

In terms of malicious code, the attacker could execute something resource intensive that hogs the CPU and RAM:

var a = []; while(true) { a.push(new Date()); console.log("gotcha!"); }

Or they might choose to carry out a CSRF-like attack:

var x = new XMLHttpRequest();
x.open("post", "https://www.mybank.com/transferMoney");
x.send("amount=10000&toAccount=34567890");

So keeping the host DOM safe is really not the only thing to worry about. There are any other number of malicious things an attacker can carry out if they're able to run code on someone's machine.

Given the above, I would stick with the assertion that eval is evil, and it's not going to be easy to find a "safe" way to execute untrusted code.


Custom implementation of python queue to use dict instead of dqueue

1. Review

There is no docstring for ChannelDict. The text in the post would make a good start.
A ChannelDict is not a dictionary (it doesn't support the mapping interface, __getitem__ and __setitem__ and so on), so the name is a bit misleading.
ChannelDict is not specialized for channels: it would work for any kind of object. A name like RandomQueue would make it easier for the reader to understand the purpose of the code.
ChannelDict inherits from queue.Queue but has a different interface for initialization (it takes an iterable of channels instead of a maximum size). Perhaps this is convenient for your use case but it makes the code a little harder to understand because you can't just say "it's just like a Queue except that it gets items in random order", you have to explain the difference in initialization and that you can't set a maximum size.
The algorithm for getting a random item from the queue takes time proportional to the number of items, because get_free_channels has to loop over all the items looking for any that are free.
ChannelStatuses.UNDERFUNDED is declared but not used.

2. Revised code

One way to efficiently pick a random item (instead of looping over all the items) is to keep the available items in a list, and to swap the randomly selected item with the last item in the list before popping the selected item.

from queue import Queue
from random import randrange

class RandomQueue(Queue):
    """Variant of Queue that retrieves items in a random order."""
    def _init(self, maxsize):
        self.queue = []

    def _qsize(self):
        return len(self.queue)

    def _put(self, item):
        self.queue.append(item)

    def _get(self):
        queue = self.queue
        i = randrange(len(queue))
        queue[i], queue[-1] = queue[-1], queue[i]
        return queue.pop()


Speeding up Access query with a calculated field calling a VBA function

Why don't you just put it in the query:

Query for employees with invalid managers:

Select [Employee_Name],[Employee_Status],[Employee_Manager]
FROM employees
WHERE [Employee_Status] = 'Active' AND isNull([Employee_Manager])

Query for employees with valid managers:

Select [Employee_Name],[Employee_Status],[Employee_Manager]
FROM employees
WHERE NOT ([Employee_Status] = 'Active' AND isNull([Employee_Manager]))

Query with the column displaying if the manager is valid or invalid

Select [Employee_Name],[Employee_Status],[Employee_Manager],
Iif([Employee_Status] = 'Active' AND isNull([Employee_Manager]), 'Invalid', 'Valid') as [Manager for employee]
FROM employees


An old trick is to cast a pointer to an array of bytes to an pointer of a struct (POD) with the exact memory layout of the final message(s).

struct Message {
    int header;
    int payload;
};

// parsing bytes -> messages
char buffer[SIZE];
recv(buffer, 0, SIZE); // replace with actual code for receiving
Message *messages = reinterpret_cast<Message *>(buffer);
size_t max_message_count = SIZE * sizeof(char) / sizeof(Message);

// converting messages -> byte array
Message messages[MSG_COUNT];
// initialize messages
char *bytes = reinterpret_cast<char *>(messages);
size_t byte_count = MSG_COUNT * sizeof(Message) / sizeof(char);

However, this requires a strict memory mapping between the message struct and the serialized byte format (so Message in this case has to be a POD struct). Yes, this effectively bypasses the type system, but if used properly its the fastest way of parsing messages (and in case of embedded systems the reuse of the memory is a nice touch).


Finding weight on various different planets

it's definitely WAY above what I've learned so far

So I try...

An answer for beginners

The code is mostly alright, sure, using an enum would help and so would Java 8 features. But let's state the simple things:

public class SpaceBoxing
{

The opening brace should be written on the same line and separated by a single space.

static Scanner keyboard = new Scanner(System.in);

You're creating a Scanner, which is Closeable and ideally should be closed. Usually, failing to do so means leaking resources and can make your program crash (e.g., you can't open a file as there are already 1000 open file descriptors).

But you're lucky: Your Scanner only wraps the underlying InputStream System.in and itself uses no system resources. So let's forget it for now.

static double computeEffectiveWeight(double weight, int choice)
    {
        double realWeight = 0;

Be consistent. Is the weight "real" or "effective"?

        if(choice == 1)

Space after if (to distinguish it visually from a method call).

You'd better always use braces, even around a single statement as it's less error-prone.

            realWeight = (weight * 0.78);

Needless parentheses. And also a needless variable. It'd clearer to write

        if (choice == 1) {
            return weight * 0.78;

        } else if (choice == 2) {
            return weight * 0.39;

        ...

        } else {
            return 0;
        }

But you probably should throw an IllegalArgumentException instead of returning 0 for an illegal argument.

Actually, this is a clear case for a switch:

       switch (choice) {
           case 1: return weight * 0.78;
           case 2: return weight * 0.39;
           ...
           default: return 0; // or better throw
       }

  I'll definitely look into it more, but I got the code working, and I guess "why break it if it ain't broke"

That's a good rule in general, but after applying it consequently for one month, you'll wish you never wrote a single line. ;) Don't hesitate to change code if it can get clearer and simpler. Learn writing tests so you don't have to be afraid of change.

Simple enum usage

As the next step, I'd go for enum Planet exactly like h.j.k. did. Modify getPlanetChoice to return it like

static Planet getPlanetChoice() {
    Planet[] planets = Planet.values();
    while (true) {
        System.out.println("I have information on the following planets: ");
        System.out.println("1. Venus");
        System.out.println("2. Mars");
        System.out.println("3. Jupiter");
        System.out.println("4. Saturn");
        System.out.println("5. Uranus");
        System.out.println("6. Neptune");
        int index = keyboard.nextInt() - 1;
        if (0 <= index && index < planets.length) {
            return planets[index];
        }
        System.out.println("\nPlease try again.\n");
    }
}

and then get the needed information out of the returned Planet.


Getting the shortest sequence to reach a number

@CarySwoveland is on the right track.  The original code and several other solutions so far get the wrong answer.  For example, GetMinimumSequence(12) should not return 8, but rather 5, based on the optimal sequence 1, 2, 3, 6, 12.

One straightforward solution uses recursion:

public static int GetMinimumSequence(int n) {
    if (n <= 0) {
        throw new ArgumentOutOfRangeException();
    } else if (n == 1) {
        return 1;
    } else if ((n % 2) == 1) {
        return 1 + GetMinimumSequence(n - 1);
    } else {
        return 1 + Math.Min(GetMinimumSequence(n - 1),
                            GetMinimumSequence(n / 2));
    }
}

Add memoization to that for better performance with larger inputs.  (I'll leave that to you as an exercise.)  In technical terms, this solution uses dynamic programming, since the greedy algorithm leads you astray.


Ptr(T* t, int s = 1): sz{s<1 ? throw std::logic_error("Invalid sz parameter") : s}
{
    sz = s; //this is unnecessary
    p = new T[sz];
    std::copy(t,t+sz,p);
}

Here you are writing to sz twice, first in the initializer list then in the constructors body. In general it's best if you just write only once in the initializer list if possible:

Ptr(T* t, int s = 1):
    sz{s<1 ? throw std::logic_error("Invalid sz parameter") : s}
{
    p = new T[sz];
    std::copy(t,t+sz,p);
}

In the move constructor:

Ptr(Ptr &&t):
    p{t.p},
    sz{t.sz}
{
    t.p = nullptr;
    t.sz = 0;
}

we are changing the pointer and size in this class but not the index. I would "move" everything and take the index from the other class here as well.
We need to set t.p to nullptr so when t gets destructed the the call to delete[] p; will be a no-op, so that part is necessary. However I don't see why the sz needs to be set to 0 because it's a primitive and therefore not in the destructor. Because the range checking function always checks p for a nullptr we can't index the old object anyway so I think I would just remove that expression.

Ptr(Ptr &&t):
    p{t.p},
    sz{t.sz},
    index{t.index}
{
    t.p = nullptr;
}

(Disclaimer: I'm not especially experienced with c++ move semantics so if you think it's more readable to keep explicitly setting every element to a "null" type of value for readability please make a comment, I'd like to know what people think about that.)


Reduce a JavaScript array into named objects

As it looks like you are using ES6 syntax, you could also throw in some destructuring assignments, but I guess the main point is that one would need to create the output object only once. One could also extract the accumulation into a descriptive name:

byFirstLabel = (acc, {graph: {nodes: [node]}}) => {
  let label = node.labels[0]
  let { name: title, reference: description } = node.properties
  let entry = { title, description }

  acc[label] ? acc[label].results.push(entry) :
    acc[label] = { name: label, results: [ entry ] }

  return acc
}

response.data.reduce(byFirstLabel, {})


Translating text using Google Translate mobile site

import translate.translate
translate.translate.translate("hello")

The verbosity is strong with this one. The clarity is not.

Why do you have a translate in a translate in a translate? With constructs like this, you can bet there are better names available.

Inside your main the same problem occurs:

to_translate = 'Bonjour comment allez vous?'
print("%s >> %s" % (to_translate, translate(to_translate)))
print("%s >> %s" % (to_translate, translate(to_translate, 'es')))
print("%s >> %s" % (to_translate, translate(to_translate, 'ar')))

That's 3 counts of translate per call. It's obvious you're translating something, but the rest is vague.

Afar from that, are you familiar with the Python Enhancement Proposals? Some of them include style suggestions, most notably the PEP 8. You might want to take at least a good look at it.

The most notable violation of your code against the PEP 8 is your lines are too long. Long lines are hard to read, hard to parse by humans. The readability of your code will improve if you split them up logically.

The ugly way of breaking-up lines is with line continuations:

agent = {'User-Agent' : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}
agent2 = {'User-Agent' : "Mozilla/4.0 (\
compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; \
.NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}
print agent
print agent2

Those produce the same output.

The proper way would be turning agent into a proper data format and parsing it on request or reading it from somewhere else. You really shouldn't have hard-coded strings that long in your code anyway.


Finding the sum of all the multiples of 3 or 5 below any given number

I'm going to take by "shorten", you mean "remove this duplication", in which case the answer is yes. Extract an SumSequence function. Give things some breathing space while you're at it.

function sum_of_all_mul_3_5(){
    var value=parseInt(document.getElementById("input").value);
    var result=sumSequence(value, 3) + sumSequence(value, 5) - sumSequence(value, 15);
    document.getElementById("output").value=result ;
    }

function sumSequence(value, x){
    return (Math.floor((value - 1) / x) * (x + ((Math.floor(value - 1) / x) * x))) / 2);
    }

For the record though, using the arithmetic sum of the sequence is a very elegant solution to this problem though. I know of no more efficient way to do it, but a comment explaining what's going on here would be beneficial to any future maintainer. You might even want to go the extra mile and drop a link to wikipedia in that comment.


Automatically backup website files and database

The names are chosen well. The code is clear. Obviously it is for a specialized case so there are many constants in the code - that is OK. It is strictly procedural, which is a good thing - OOP has a tendency to just become boilerplate for small things like these (it would be useful if you intended to make a framework for a general backup tool)

I would definitely remove the unnecessary variables.

db_passwords = {'somedatabasename': 'somedbpassword'} which is only used a few lines later as db_passwords[db_name], take the password as an argument to the function instead.
date = time.strftime('%Y-%m-%d'), it would be understandable if you had to use it twice and be sure it still was the same day (in that case I would argue for a function argument), but in your case you only use it once. So remove the variable and do instead ... 'date': time.strftime('%Y-%m-%d').

Some variables could be better as functions, for example
 - zip_command, I would put that into a function which would take app_name and filename as argument and then return the command. Of course, the day you want different zip commands depending on database size or backup time you just add an extra argument.

Perhaps more subjective but I would go for the new Advanced String Formatter.

To generalize your tool, I would do one of the two: a) put your options on the command line (e.g. argparse or optparse) or b) use a configuration file (fabric can take an environment file as argument). I would absolutely only put those options that do vary between the sites (rather than making everything possible with an explosion in code for no added real utility).


Take a look as DBUtils and JDBC Template (the latter is more popular). It will give you some hints how to organize such code. Usually you want select query to be separate method and to return list of objects - PreparedStatement and ResultRow shouldn't be visible outside. While using JDBC directly it is also easy to leak DB connections, in your code sample connection.close() should be inside finally block after catch section.


Maybe it is a personal taste, but I don't like introducing a nested function because some code is repeated in a particular case. Maybe a refactoring
could avoid this.

first you notice that index is naturally offset by one... refactor it:

index = n - 1
while index > 0 and nums[index-1] >= nums[index]:
    index -= 1
if index == 0:
    swap(0, n - 1)
    return
i = n - 1
while i > index-1 and nums[i] <= nums[index-1]:
    i -= 1
nums[i], nums[index-1] = nums[index-1], nums[i]
swap(index, n - 1)

now you can remove the duplicated call to swap:

if index > 0:
    i = n - 1
    while i > index-1 and nums[i] <= nums[index-1]:
        i -= 1
    nums[i], nums[index-1] = nums[index-1], nums[i]
swap(index, n - 1)

and you can remove the nested function:

n -= 1
while index < n:
    nums[index], nums[n] = nums[n], nums[index]
    index += 1
    n -= 1

This is the resulting code. It is clear that this code is O(n) since there are no nested loops.

def nextPermutation(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    n = len(nums)
    index = n - 1
    while index > 0 and nums[index-1] >= nums[index]:
        index -= 1
    if index > 0:
        i = n - 1
        while i > index-1 and nums[i] <= nums[index-1]:
            i -= 1
        nums[i], nums[index-1] = nums[index-1], nums[i]
    n -= 1
    while index < n:
        nums[index], nums[n] = nums[n], nums[index]
        index += 1
        n -= 1


Check if images are loaded (ES6 Promises)

Well, you normally don't want to use the Promise constructor in your higher level code, you want to Promisify as low as possible. So let's create a function that checks for a single image, and resolves whenever you know the status of that image:

// When there's only one statement, you can drop the {} and the return
// x => y is equivalent to x => { return y; }
const checkImage = path =>
    new Promise(resolve => {
        const img = new Image();
        img.onload = () => resolve({path, status: 'ok'});
        img.onerror = () => resolve({path, status: 'error'});

        img.src = path;
    });

Now, with that Promise returning action, we can do some fancy things:

const loadImg = paths => Promise.all(paths.map(checkImage))

Or, if you want to get fancier

const loadImg = (...paths) => Promise.all(paths.map(checkImage));
// and call with
loadImg('path1', 'path2', 'path3');
// or
loadImg(...arrayOfPaths)

It's perfectly fine to not reject if there's no error. Yes, there was an error loading the image, but it isn't an exceptional situation, it's not something you'd throw because of. Your function is actually there to check if the image loaded fine or not.


List of Ordered pairs from unordered Pair in Java

Welcome to corereview.se and thanks for sharing your code.

general coding

avoid odd ball solutions

In your inner and outer loop, you use different methods to declare the loop counter variable.
The better way would have bee to find a solution that does not need this odd cod style.

But since you decided to do so you should have placed a comment why you had to do this.

Same is with opening braces {: In your method signature, you place them at a new line, in the rest of the code you put them on the same line as the preceding statement.

THere is a hot discussion out there where to put these opening braces.
I don't want to contribute to that argument,
but all agree that you should decide on either one place and stick to that throughout your code.

business approach

The code does basically three things:

find start point
connect elements
reorder the input array

You chose a procedural approach to the problem. This is not bad by itself, but since Java is an object oriented language you should start looking for OO approaches.

But OOP doesn't mean to "split up" code into random classes.

The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.

Doing OOP means that you follow certain principles which are (among others):

information hiding / encapsulation
single responsibility
separation of concerns
KISS (Keep it simple (and) stupid.)
DRY (Don't repeat yourself.)
"Tell! Don't ask."
Law of demeter ("Don't talk to strangers!")

A more OOish approach could look like this:

private static void sortPairs(String[][] input) {
    Map<String,String> routes = convertToMap(input);
    String start =  findFirstStart(routes);
    reorderArray(routes, start, input);
}
private static Map<String,String> convertToMap(
         String[][] input) {
    Map<String,String> routes = new HashMap();
    for(String[] route : input)
       routes.put(route[0][1]);
    return routes;
}
private static String findFirstStart(
        Map<String,String> routes) {
     return routes.keySet()
          .stream()
          .filter(city->!routes.values().contains(city))
          .findAny()
          .get();
}
private static void reorderArray(
        Map<String,String> routes,
        String start,
        String[][] input) {
     for(int i = 0 ; i < input.length) {
         String end = routes.get(start);
         input[i][0]=start;
         input[i][1]=end;
         start = end;
     }
}


Load/save plain PPMs without error checking

Seems readable enough for me. When you're working with a standardized data there is no room for ingenuity, just a mechanical work that needs to be done correctly.

Maybe it is only this snippet 'P3'..('%s*(%d+)'):rep(3), that makes you thin for a while, whether there will be three 'P3's in result.


Variable naming
Your variables should be named something more telling than breakcount , breakcount1 and breakcount2. I suggest breakcount_water (and _eyes , _physical) instead.
Simpler logic
Instead of two variables for each kind of break (6 total), you can do with just one variable for each, starting at the max, and subtract 1 for each break. Then, you're done when you reach zero.
That lets you do the same thing with half as many (3) variables to keep track of.
Don't repeat yourself
pygame.mixer.init()
pygame.mixer.music.load("water.mp3.mp3")
pygame.mixer.music.play(-1)

These three lines are identical each time you play music.
Create a function instead that takes the file name as input, and you can call play_music("water.mp3.mp3") which then executes these three lines in the function.
def play_music(filename):
    #the three lines from above

Stack abuse
You're calling the health() function from inside itself, which means you never let it exit properly and if you did this a few thousand (maybe more) times, the program would crash due to stack overflow.
Instead, you should use a while loop that checks for the condition to loop again, to start over without calling the function another time. That way, you can also initialise your variables at the start of the function (before the while-loop) and you don't need any global variables, since the function has access to them inside its own scope.


A few points.  In your code, some of these render others irrelevant, but they may be relevant in other code you write:

Try to follow PEP8
It should be possible to vectorize ComputePhaseLaplacian.
It is better to loop over rows and columns directly rather than looping over indexes.  You can use enumerate to keep track of the rows and columns.
You shouldn't flatten, you can index in two dimensions.
Instead of vstack, you should use pad in this case.
You create U and V, then immediately overwrite them.  This is redundant.
You should use ravel instead of flatten since it doesn't make a copy.


I have a class with 3 properties, [...] and as my properties list increases, [...]

Wait, stop - here, that.

Classes are the blueprint for an object - the public members are that object's interface, and that shouldn't need to change that way. The Open/Closed Principle tells us that classes should be opened for extension, and closed for modification.

I don't know what any of these members mean, but a design that needs to change all the time is a design that didn't integrate the need to change as a requirement.

A design that embraces change, is one that minimizes the amount of code that's required to add to extend a piece of existing functionality.

If, instead of saying "I need a class with a P, H and V 'dop' float values, and maybe a X, Y and Z too, eventually", you said "I need a class with an unknown bunch of 'dop' float values; for this version I'll have P, H and V values, nobody knows what future holds"... the design would have reflected that.

void parseTokens(string[] tokens)

You have a string[] array here, an IEnumerable<string> ready to play with: use it to your advantage, and ask yourself how you could possibly structure things so that parseTokens (which should really be ParseTokens - conventions FTW!) can be implemented with an iterative logic.

Consider an enum:

public enum Dop // whatever that means
{
    Pdop,
    Hdop,
    Vdop
}

To add support for a new property, you add an enum member. Then you can have a function that returns this:

return tokens
    .Select((value, index) =>
        {
            float dop;
            var success = float.TryParse(value, out dop);
            return new
            {
                Key = (Dop)index,
                Success = success,
                Value = dop
            };
        })
    .ToDictionary(item => item.Key, item => item.Success ? item.Value : (float?)null);

Notice float.TryParse is the same as Single.TryParse.

That's a Dictionary<Dop,float?>, where the float? value is null when the string couldn't be parsed into a float; you would take that and assign it to a private readonly field.

That's nice, but a Dictionary is not exactly the type of data structure you usually want to expose in your public interface - how about an indexer?

public float? this[Dop dop]
{
    get
    {
        float? value;
        return _tokens.TryGetValue(dop, out value)
            ? value
            : null;
     }
}

(assuming private readonly IDictionary<Dop,float?> _tokens; assigned in constructor)

That said, I'd like to bring your attention to the indexing here:

Single.TryParse(tokens[tokens.Length - 3], out pdop);
Single.TryParse(tokens[tokens.Length - 2], out hdop);
Single.TryParse(tokens[tokens.Length - 1], out vdop);

Whenever tokens has less than the expected number of items, things blow up. What's the index of the pdop value in the tokens array? As a maintainer you shouldn't have to be bothered with these riddles.

What does using an enum get us? Imagine the client code has an instance of a GSA class, named gsa:

var pdop = gsa[Dop.Pdop];
var hdop = gsa[Dop.Hdop];
var vdop = gsa[Dop.Vdop];

If gsa has a float value for Pdop, then pdop will contain that value. Otherwise, it will be null.

And to extend it, you now only need to do this:

public enum Dop
{
    Pdop,
    Hdop,
    Vdop,
    Xdop,
    Ydop,
    Zdop
}

...and make sure the tokens array provided has as many arguments / fail fast:

protected override void ParseTokens(string[] tokens)
{
    if (tokens.Length != Enum.GetNames(typeof(Dop)).Length)
    {
        throw new ArgumentException("Invalid number of tokens.");
    }

    //
}

Another thing that strikes me as not needed and potentially bug-prone, is exposing the setters for these hard-earned float values.

Also, the order of the accessors is unusual:

public float Pdop { set; get; }

I'm used to see the getter first.

public float Pdop { get; private set; }

With a private setter, the only way to set that value is to parse a new array of strings.

At this point I'd question the mutability of the type. How about simply this?

public class GSA : NMEAMsg
{
    private readonly IDictionary<Dop,float?> _tokens;

    public GSA(string[] tokens)
    {
        if (tokens.Length != Enum.GetNames(typeof(Dop)).Length)
        {
            throw new ArgumentException("Invalid number of tokens.");
        }

        _tokens = tokens
            .Select((value, index) =>
                {
                    float dop;
                    var success = float.TryParse(value, out dop);
                    return new
                    {
                        Key = (Dop)index,
                        Success = success,
                        Value = dop
                    };
                })
            .ToDictionary(item => item.Key, item => item.Success ? item.Value : (float?)null);
    }

    public float? this[Dop dop]
    {
        get
        {
            float? value;
            return _tokens.TryGetValue(dop, out value)
                ? value
                : null;
         }
    }
}


Arrow elements

There are two elements for the arrows, and presuming there is only one of each type (i.e. one left, one right) then it would be more appropriate to use an id attribute for distinguishing between those two.

Instead of

use the id attribute:

And instead of selecting elements by class name and taking the first one:

var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

select them using document.getElementById():

var leftArrow = document.getElementById('arrow-left');
var rightArrow = document.getElementById('arrow-right');

Obviously this would require the CSS to be updated as well.

Direction parameter

There are only two possible values for direction, so it could be changed to a boolean like forward that defaults to true (default parameters is a feature of ecmascript-6 so be aware of the browser compatibility).

function carousel(forward = true) {
  if (forward) {
    //move forward
  }
  else {
    //move backward
  }

Simplify onclick event handlers

After making the first parameter for carousel a boolean that defaults to true (for the direction), the onclick handlers can be simplified to function references. false can be tied to the leftArrow handler by employing a partially applied function with Function.bind()

leftArrow.onclick = carousel.bind(null, false);
rightArrow.onclick = carousel;

If there was a need to have multiple event handlers on each element then addEventListener() could be used:

leftArrow.addEventListener('click', carousel.bind(null, false));
rightArrow.addEventListener('click', carousel);

Simplify logic for current and next

Instead of looping through the reviews, select the elements that have class name show (should only be one):

var shownReviews = document.getElementsByClassName('show');

That will be a live HTMLCollection, meaning that it updates as the DOM is updated, so there is no need to re-query it.

Then you can utilize shownReviews[0] - this can be used to set currentReview. Then when forward is true the value for nextReview can be set utilizing nextElementSibling or if that is null using parentElement.firstElementChild (and conversely using previousElementSibling and lastElementChild when forward is false).

function carousel(forward = true) {
  currentReview = shownReviews[0];
  if (forward) {
    nextReview = currentReview.nextElementSibling || currentReview.parentElement.firstElementChild;
  }
  else {
    nextReview = currentReview.previousElementSibling || currentReview.parentNode.lastElementChild;
  }
  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

Simplify CSS

The following styles can be moved out of each of the rulesets for the arrows and moved into the ruleset for .arrow:

width: 0;
height: 0;
border: 10px solid transparent;

Then the rulesets for the arrows becomes a single style:

#arrow-left {
  border-right: 10px solid black;
}

#arrow-right {
  border-left: 10px solid black;
}

The margin styles for .arrow can be combined to a single style using two values:

margin: 0 25vw; /* top & bottom: 0, left & right: 25vw */

Rewrite

Below is simplified code using the advice above.

var shownReviews = document.getElementsByClassName('show');
var leftArrow = document.getElementById('arrow-left');
var rightArrow = document.getElementById('arrow-right');

var currentReview;
var nextReview;

function carousel(forward = true) {
  currentReview = shownReviews[0];
  if (forward) {
    nextReview = currentReview.nextElementSibling || currentReview.parentElement.firstElementChild;
  }
  else {
    nextReview = currentReview.previousElementSibling || currentReview.parentNode.lastElementChild;
  }
  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

leftArrow.onclick = carousel.bind(null, false);

rightArrow.onclick = carousel;
* {
  font-family: Arial;
}

.carousel {
  display: flex;
  align-items: center;
  justify-content: center;
}

.review {
  display: none;
  text-align: center;
}

.show {
  display: block;
}

.arrow {
  border: 10px solid transparent;
  width: 0;
  height: 0;
  margin: 0 25vw;
}

#arrow-left {
  border-right: 10px solid black;
}

#arrow-right {
  border-left: 10px solid black;
}

Title1

Title2

Title3


Set up event on class and initialize state

I'm only vaguely familiar with coffeescript, but it seems like the issue is not that you need to call the event handler on init, it's that you need to call the logic currently residing in your event handler. If you separate your logic into reusable pieces, you can call this other method to execute your init logic. Without the complete code, it's hard to see what that logic is (by the way, incomplete code examples don't bode well for the Code Review site).

Consider something like this example though (sorry, pseudocode not coffeescript):

function init() {
    hideUserInformation();
}

function checkBoxChangeHandler(checkBox) {
    if(checkBox.checked) {
        hideUserInformation();
    } else {
        showUserInformation();
    }
}

function hideUserInformation() {
    // Some logic.
}

function showUserInformation() {
    // Some logic.
}

Now the event handler is only concerned with forwarding to the real logic, and you aren't trying to call an event handler with bogus arguments just to try to run the same code.


Program to determine total stops taken by elevator

So you said that the elevator works with the first come first serve basis. That screams like using a Queue. Moreover i like using classes as much as possible because i feel that implementing a solution becomes very easy because the abstraction is more on a human level and the readability increases.
I demonstrate it on my code.

So first you know that you have Persons who want to drive from ground to a Target Floor. A Person also have a Weight. So i have implemented this in a class:

public class Person
{
    public int Weight { get; set; }

    public int ActualFloor { get; set; }

    public int TargetFloor { get; set; }

    public Person(int weight, int targetFloor, int actualFloor = 0)
    {
        this.Weight = weight;
        this.TargetFloor = targetFloor;
        this.ActualFloor = actualFloor;
    }
}

Naming:
Moreover you know that the Elevator has different attributes too. You have implemented them in Y for Maximum Weight and X for the Maximum Number of People and i think that X and Y are really bad names for MaxWeight and MaxPeople. Why not name them what they are? That makes it easier for you as the coder and easier for other coworkers trying to understand your code.

My Elevator Properties and the Constructor are implemented as this:

public class Elevator
{
    public readonly int MaxWeight;

    public readonly int MaxPersons;

    public readonly int MaxFloors;

    public Queue<Person> Persons { get; set; }

    private List<Person> Passengers { get; set; }

    public Elevator(int maxFloors, int maxWeight, int maxPersons)
    {
        this.MaxFloors = maxFloors;
        this.MaxPersons = maxPersons;
        this.MaxWeight = maxWeight;
        this.Persons = new Queue<Person>();
        this.Passengers = new List<Person>();
    }
}

MaxWeight, MaxPersons and MaxFloors should be clear. The Queue Persons contains the People you want to drive around. Passengers are the People which are in this cycle in the elevator.

Now you can calculate the number of stops very easy:

public int CalculateNumberOfStops()
{
    int stops = 0;

    while (!this.Persons.IsEmpty())
    {
        while (this.IsOneMorePersonFitting())
        {
            this.Passengers.Add(this.Persons.Dequeue());
        }

        stops += this.Passengers.GroupBy(x => x.TargetFloor).Count();
        this.Passengers.Clear();

        // Drive to Floor Zero
        stops++;
    }

    return stops;
}

private bool IsOneMorePersonFitting()
{
    return !this.Persons.IsEmpty() &&
           this.Passengers.Sum(x => x.Weight) + this.Persons.Peek().Weight < this.MaxWeight &&
           this.Passengers.Count < this.MaxPersons;
}

I am shifting the People from the Queue into the List as long the cap of the elevator is not full and the Queue is not empty.
The number of stops are calculated with the number of Groups in the List. If you have 2 Passengers and Pass 1 wants to Floor 1 and Pass 2 wants to Floor 2 then you will have two groups. But if both want to the same Floor then you will only have one group.

You can add persons and error check with a helper function like this:

public void AddPersons(IEnumerable<Person> persons)
{
    foreach (var person in persons)
    {
        // Check if person is valid:
        if (person.TargetFloor > this.MaxFloors ||
            person.Weight > this.MaxWeight)
        {
            throw new ArgumentException();
        }

        this.Persons.Enqueue(person);
    }
}

I extended the Methods of Queue with the IsEmpty function to make is a little easier to read:

public static class ExtensionHelper
{
    public static bool IsEmpty<T>(this Queue<T> queue)
    {
        return queue.Count == 0;
    }
}

Using the elevator:

static void Main(string[] args)
{
    var elevator = new Elevator(5, 200, 2);
    elevator.AddPersons(new[] { new Person(60, 2), new Person(80, 3), new Person(40, 5) });
    var stops = elevator.CalculateNumberOfStops();

    Console.WriteLine(stops);
    Console.ReadKey();
}

For better readability you could define an empty constructor and then use it as

var elevator = new Elevator() { MaxWeight = 200, MaxPersons = 2 };

but then you can't use a readonly field and the programmer must know what is needed for the instance.


Looking at the following:

terminal_width = 80
terminal_height = 25

default_length = 12

alphabet_default = string.ascii_letters + string.digits
alphabet_complex = alphabet_default + '`~!@#$%^&*()_+-={}[];:<>?,./'
alphabet_easy = re.sub(r'[l1ioO0Z2I]', '', alphabet_default)

double_letter = re.compile(r'(.)\1')

you never change them, so they are constants. Constants are written ALL CAPS in Python as a convention.

elif len(alphabet) < length:
    length = len(alphabet)

Are you sure the user really wants what you are doing here? Maybe he wants a 20 character password using only the 10 digits, with this you are silently not doing what he expects.


From where I sit, this seems to be implemented backwards. You're iterating over every pixel in the viewport and checking to see if it has a particle, then doing something with the particle. It seems like it would be way more efficient to iterate over the particles and calculate the values needed for each particle. You're doing n * m operations for the lighting, then another n * m operations for drawing the textures (so it's essentially O(2n2)). You could do the operations only for the particles and cut it down to O(2q) operations (where q is the number of particles, which looks to always be smaller than m * n).

If instead, a particle held an (x,y) position, and a lighting value, you could simply iterate over the particles and calculate the new lighting value and then draw them.

You say:

  One of the difficulties with just doing the operations for all the particles is that the world is rather large. There are many more particles than those just displayed in the viewport. It would be prohibitively slow to calculate lighting and render every particle (> 10,000,000).

The solution to this is to use an appropriate data structure. In this case a k-d tree in 2D might be a good place to start. You would check only particles whose segment of the tree intersected the viewport, and leave out all other particles.