Using datetime to obtain the time of the next lecture

Your algorithm seems good, but the while loop, and lecture_hour and lecture_minute variables make your code a lot more complicated.
If we KISS then a simple algorithm is to just remove () from Lectures and iterate through it, since it is sorted.
The first lecture that is after the current time is the lecture we want.
This is nice and simple:
import datetime

LECTURES = [(0, 10, 15), (2, 12, 15), (3, 8, 15)]

def _get_next_lecture(now):
    today = (now.weekday(), now.hour, now.minute)
    for lecture in LECTURES:
        if today < lecture:
            return lecture

def get_next_lecture(now=None):
    if now is None:
        now = datetime.datetime.now()
    day, hour, minute = _get_next_lecture(now)
    return (
        now.replace(hour=hour, minute=minute, second=0, microsecond=0)
        + datetime.timedelta(day - now.weekday())
    )

From here we can see if the weekday is 4-6 then _get_next_lecture will return nothing and so will error.
This is easy to solve, we just return the first lecture with +7 days.
def _get_next_lecture(now):
    today = (now.weekday(), now.hour, now.minute)
    for lecture in LECTURES:
        if today < lecture:
            return lecture
    day, hour, minute = LECTURES[0]
    return day + 7, hour, minute

With only 3 lectures there's not much point in optimizing further. However if you have more, here is some food for thought:

You can use bisect to find where to insert into in \$O(\log n)\$ time.

You can change LECTURES into a 7 item list with the weekday as the index and the lectures as the value (always as a list). From here you just find the date using either of the above algorithms.
This would look like your Lectures. But with a list for each day.
This has either \$O(d)\$ or \$O(\log d)\$ time where \$d\$ is the maximum amount of lectures in a day.

Test code
def replace(date, changes):
    day, hour, minute = changes
    return date.replace(hour=hour, minute=minute) + datetime.timedelta(days=day)

def test(tests, bases, fn):
    for base in bases:
        date = base.replace(second=0, microsecond=0) - datetime.timedelta(days=base.weekday())
        for test, exp in tests:
            try:
                output = fn(replace(date, test))
            except Exception as e:
                print(f'❌ {test=}, {exp=}')
                print('  ', e)
                continue
            expected = replace(date, exp)
            try:
                assert output == expected
            except AssertionError:
                print(f'❌ {test=}, {exp=}')
                print('  ', date, output, expected)
            else:
                print(f'✔ {test=}, {exp=}')

TESTS = [
    [(0, 0, 0), (0, 10, 15)],
    [(0, 10, 10), (0, 10, 15)],
    [(0, 10, 15), (2, 12, 15)],
    [(0, 10, 20), (2, 12, 15)],
    [(1, 12, 20), (2, 12, 15)],
    [(1, 13, 20), (2, 12, 15)],
    [(2, 10,  0), (2, 12, 15)],
    [(2, 10,  14), (2, 12, 15)],
    [(2, 12,  15), (3, 8, 15)],
    [(3, 8,  15), (7, 10, 15)],
]
BASES = [
    datetime.datetime.now(),
    datetime.datetime(2020, 9, 1),
    datetime.datetime(2020, 10, 1) - datetime.timedelta(days=1),
    datetime.datetime(2020, 12, 1),
    datetime.datetime(2021, 1, 1) - datetime.timedelta(days=1),
]

test(TESTS, BASES, get_next_lecture)


jQuery code to total the items in a shopping cart

this part of code  var id = $('.quant').attr('data-id');

Presuming there are multiple inputs with class "quant" (perhaps 1 for each row in the table), then this code will get a collection of elements and then as is desribed in the documentation for .attr():

  Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

So yes it will get the value of the data-id attribute of the first element with that class name.

Consider the following snippet (try running it to see the result):

//find all elements with class name "quant"
var inputsWithClassQuant = $('.quant');
console.log('inputsWithClassQuant.length: ',inputsWithClassQuant.length);
//attr only returns attribute of first element:
console.log("inputsWithClassQuant.attr('data-id') (first element only): ",inputsWithClassQuant.attr('data-id'));

<input type="text" data-id="30" data-price="20" value="3" class="quant" />
<input type="text" data-id="35" data-price="10" value="0" class="quant" />
<input type="text" data-id="36" data-price="15" value="2" class="quant" />

  Problem here:

var quantity;
$('#myTable > tbody  > tr').each(function () {
 quantity = $(this).find('.quant').val();
 ...
}

Yes, quantity = $(this).find('.quant').val(); overwrites the previous value each time so after the loop (i.e. the call to .each()), quantity will contain the value of the last element with class name quant.

  I was told that I pass first id and last quantity, but it is all present when I call function in $(document) - Please explain this to me.

This is basically a summary of points #1 and #2 above.

Perhaps a better implementation would move the code to call the AJAX request (i.e. to '/Cart/AddTocart') with the id and quantity of the row that changed, then call update() to update the total. Something like the code below.

Another suggestion is to update the request sent to the server to send the entire list of items with the respective quantities. That way, if a quantity is decreased or cleared, the cart can be accurately updated. It all depends on the back-end API - i.e. if it has endpoints to add/remove/update items with quantities, etc.

I also changed the input type of the quantity inputs to "Number" - that way only numbers can be entered, and many browsers will add up/down controls to the side of the input for the user to click on.

$(document).ready(function() {
  update();
  $(".quant").change(function() {
    //this: context of the input that was changed
    console.log('calling /Cart/AddTocart; id:',$(this).attr('data-id'),' quantity: ', $(this).val());
    $.get(
      '/Cart/AddTocart', {
        id: $(this).attr('data-id'),
        returnUrl: '',
        quantity: $(this).val()
      });
    update();
  });

  function update() {
    var sum = 0.0;
    var quantity;
    $('#myTable > tbody  > tr').each(function() {

      quantity = $(this).find('.quant').val();
      var price = parseFloat($(this).find('.price').attr('data-price').replace(',', '.'));
      var amount = (quantity * price);

      sum += amount;
      $(this).find('.amount').text('' + amount + ' грн');
    });
    $('.total').text(sum + ' грн');
  }
});

      Товар
      К-сть
      Назва Товару
      Ціна
      Загальна ціна

      <input type="number" data-id="97" data-price="30" value="1" class="quant" />

    Kart
    30
    30

      <input class="btn btn-sm btn-warning" type="submit" value="Видалити з кошику" />

      <input type="number" data-id="99" data-price="60" value="0" class="quant" />

    Kart
    10
    30

      <input class="btn btn-sm btn-warning" type="submit" value="Видалити з кошику" />

      Всього до оплати:
      @Model.Cart.ComputeTotalValue().ToString("#.## грн")


Optimizing solution for Project Euler Problem #23 (non-abundant sums)

Your first problem is that you're trying to cram too much information onto one line. As a result, you loose the overview. Here is a simple refactoring:

def is_abundant(n):
    max_divisor = int(n / 2) + 1
    sum = 0
    for x in range(1, max_divisor):
        if n % x == 0:
            sum += x
    return sum > n

abundants = list(x for x in range(1, 28123) if is_abundant(x))

sums = 0
for i in range(12, 28123):
    for abundant in abundants:
        if abundant >= i and is_abundant(i + abundant):
            sums += i
print(sums)

The == True tests are unecessary and were removed.
Naming was improved: isabundant → is_abundant.
The long statement in is_abundant was split up.

Now we can think about how this could be optimized.

One subproblem is calculating all divisors of a number. We could put the relevant code into its own function. We can furthermore exploit that if n % i == 0, then there must be another integer k so that n == i * k. This means that we only have to look at a lot less numbers: only the range(2, 1 + int(sqrt(n))) is interesting.

def divisors(n):
    """
    Returns all nontrivial divisors of an integer, but makes no guarantees on the order.
    """
    # "1" is always a divisor (at least for our purposes)
    yield 1

    largest = int(math.sqrt(n))

    # special-case square numbers to avoid yielding the same divisor twice
    if largest * largest == n:
        yield largest
    else:
        largest += 1

    # all other divisors
    for i in range(2, largest):
        if n % i == 0:
            yield i
            yield n / i

We can now rewrite our is_abundant to the simpler:

def is_abundant(n):
    if n < 12:
        return False
    return sum(divisors(n)) > n

Later, in your main loop, you are doing a rather weird calculation. What were we supposed to do?

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

We furthermore know that all integers above 28123 can be written as such a sum. Thus we have to look at the range(1, 28123 + 1)! How can we decide if a number n can be written as a sum of abundant numbers i and k? There exists any abundant number i with the constraint i < n, and another abundant number with the constraints k < n and n - i == k. Here is one clever way to write this:

def is_abundant_sum(n):
   for i in abundants_smaller_than_n:
       if (n - i) in abundants_smaller_than_n:
           return True
   return False

Because we don't want to calculate the abundants_smaller_than_n each time, we just take all possible abundants and bail out if we get larger than n:

def is_abundant_sum(n):
   for i in abundants:
       if i > n:  # assume "abundants" is ordered
         return False
       if (n - i) in abundants:
           return True
   return False

where abundants = [x for x in range(1, 28123 + 1) if is_abundant(x)].

Now, all that is left to do is to sum those numbers where this condition does not hold true:

sum_of_non_abundants = sum(x for x in range(1, 28123 + 1) if not is_abundant_sum(x))

We could perform one optimization: abundants is a list, which is an ordered data structure. If we search for an element that is not contained in the list, all elements would have to be searched. The set() data structure is faster, so:

abundants_set = set(abundants)
def is_abundant_sum(n):
   for i in abundants:
       if i > n:  # assume "abundants" is ordered
         return False
       if (n - i) in abundants_set:
           return True
   return False


Implementation of cp program that prints the number of bytes copied

Do not call printf from the signal handler. It is not signal safe. man sigaction for details.
write_buf is somewhat convoluted. while (rlen > 0) seems more straightforward.

Also, it is forced to write the entire buffer. It means that your program only pays attention to the Ctrl-C in between of writes. You may get more crispy resolution by testing wlen < rlen and inspecting errno; if write was interrupted, it would be EINTR.

void function with an in-out parameter (bytes in your case) is strange to say the least. The void function is not supposed to return anything, and in-out parameters are generally unclean. Just return bytes.
error() is a GNU extension and should not be used in programs intended to be portable. In any case, the pass errno as a second parameter. The user is very interested what exactly was wrong.
If the program was not interrupted, it doesn't print number of bytes copied. Looks like a bug (or a very dubious design decision) to me.


To reduce the amount of log files I would keep things in memory:

$Log = "C:\scripts\list.txt"
$purged = "C:\scripts\purged.txt"
$now = Get-Date
$days = "7"
$Lastwrite = $now.AddDays(-$days)
$datetime = get-date -f MM-dd-yy-hhmmtt

#Robocopy will automatically overwrite the log file unless you specifiy /log+:
robocopy "c:\downloads" "c:\downloads1" /e /Purge /R:1 /W:1 /l /TEE /FP /LOG:"$log" /MT:16

#Save purged log
rename-item $purged ($purged -replace('.txt', "_$datetime.txt"))

Get-Content $Log | foreach {

    #Split columns by tab
    $fileType =  ( $_ -split("`t") )[1]
    $filePath =  ( $_ -split("`t") )[2]

    if ( ($fileType -like "*Extra File*") -or ($fileType -like "*Extra Dir*") ){
        if ( (Get-Item $filePath).LastWriteTime -le $Lastwrite){
            "Deleting File: $filePath" | Out-File $purged -Append
            remove-item $filePath -WhatIf -Recurse
        }
    }

}


Loading images in the background for a table view

Is there any reason that imagesArray and namesArray have to be separated? If not, I probably will design a struct and join above two arrays to one since name and image can be fetched at the same time in func fetchData().

For example, let's assume we have a struct like:

struct Person {
    var username: String
    var image: PFFile
}

Then we have a global mutable array:

var items = [Person]()

Inside the for-loop in func fetchData(), we can create a new person and append it each time once we have a name and an image.

let person = Person(username: "myName", image: "myImage")
self.items.append(person)

Therefore, in the func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}, we can get a person and associated username and image directly according to indexPath.row

let person = self.items[indexPath.row]
let username = person.username
let image = person.image

The benefits like this is that,

Cell count is restricted by self.items.count; therefore, no
worries to take care of indexPath.row beyond an array.
Also username and image are always paired. It also helps to avoid
concerning the order as imagesArray and namesArray are separated. No
doubt, the condition imagesArray.count == namesArray.count can
be removed as well.
As to boolean self.imagesLoaded which is able to be removed. Owing to before remote data has been fetched, self.items.count is 0 and none cell will be rendered at that moment.


Using a service interface to get user input from dialogs

I have worked in a project where such an IUserInputService was used. After few years, the implementation was a big class containing the dialog calling logic for all modules.

Today, I would prefer a generic service which is able to connect a view with the view model without implementing the logic for each concrete dialog.

Code Review

Your code looks clean and tidy
The communication between view model and the view via events may be OK in your case, because the view model is just an internal structure not known outside the method. However, in generell I would prefer a way where the view is not references by the view model (wich is indirect the case because the delegates contain a reference to the view). Usually, I use a view model property "bool Close" and bind it to the view so that the view can react on changes and close itself.
Your approach does not allow creation of view models via DI container. If the VM has dependencies, they must be passed to the method PromptUserRegistration.
Configuring the VM with default values requires to parameterize the PromptUserRegistration as well.

All things considered, I would prefer an approach where the view model is created / configured by the calling logic and shown via an generic service because it is more flexible and less distributed code.

Note that there are also frameworks available that adress that problem. E.g. https://github.com/FantasticFiasco/mvvm-dialogs


Java blocking queue download process scenario

In your DownloadTaskEnqueuer it might be a little bit weird to mix instance methods with static fields (unless there is more code which you omitted). It might be better to either use instance fields (i.e. remove static from downloadQueue, processQueue and executor) or make the methods static.
You DownloadTaskEnqueuer.offer(...) method has void as return type but contains a return statement returning a value.
Executors.newCachedThreadPool() is not that well suited for your use case. You are creating a fixed number of work tasks which run indefinitely so an executor which creates a new thread per task would work equally well. Normally you also don't submit an indefinitely running work task which itself performs tasks to an executor, but instead directly submit the tasks to the executor.
This leads to the next question: How are you shutting down workers? It appears with your current code the DownloadTask and ProcessTask run forever. Or is there no need to shut down workers in your use case?
Using BlockingQueue.poll() and then waiting seems a little bit inefficient. Since you are already dealing with BlockingQueue you could use the blocking method BlockingQueue.take().
If I may make a suggestion, it appears CompletableFuture would be well suited for your use case:
public class DownloadProcessor {
    private final ExecutorService downloadExecutor;
    private final ExecutorService processingExecutor;

    public DownloadProcessor(int poolsSize) {
        downloadExecutor = Executors.newFixedThreadPool(poolsSize);
        processingExecutor = Executors.newFixedThreadPool(poolsSize);
    }

    public CompletableFuture<Void> downloadAndProcess(DownloadTask task) {
        return CompletableFuture.supplyAsync(() -> task.download(), downloadExecutor)
            // Assumes that DownloadTask.download() returns ProcessingTask which
            // has method `process()`
            .thenAcceptAsync(task -> task.process(), processingExecutor);
    }

    public void shutdown() {
        downloadExecutor.shutdown();
        processExecutor.shutdown();
        // Maybe also call awaitTermination
    }
}


Unit testing Spark transformation on DataFrame

Indeed, asJava looks awkward and completely unnecessary here. You can approach this problem in a few different ways.

pass RDD[Row] instead of Seq[Row] to avoid asJava:

sqlContext.createDataFrame(sc.parallelize(Seq(Row(1), Row(2), Row(3))), schema

use product types instead of Row to avoid both asJava and passing schema:

sqlContext.createDataFrame(Seq(1, 2,  3).map(Tuple1(_))).toDF("a")

or

case class Record(x: Int)

sqlContext.createDataFrame(Seq(1, 2,  3).map(Record(_)))

use implicit conversions to avoid asJava and passing schema and get concise syntax (supported for Seq[Int] only in Spark 2.0+):

import spark.implicits._

Seq(1, 2, 3).toDF("a")

In general you should prefer product types (tuples, case classes) over Row objects. You get schema for free as well as some static typing.


Using IQueryable.GroupBy to count related database entities

You don't need the grouping at the Client level. No grouping at all, actually. Don't worry, this is a common mistake when people want grouping/aggregation in child collections. Per client, the Tickets can be counted:

return clients
    .Where(cli => cli.IsActive)
    .Select(cli => new DashboardItemViewModel
    {
        Id = cli.Id,
        Name = cli.Name,
        Open = cli.Tickets.Count(t => t.Status == StatusType.Open && !t.IsArchived),
        Responded = cli.Tickets.Count(t => t.Status == StatusType.Responded && !t.IsArchived),
        Resolved = cli.Tickets.Count(t => t.Status == StatusType.Resolved && !t.IsArchived),
    });

Or in query syntax, so we can benefit from the let statement:

return from cli in clients
    where cli.IsActive
    let activeTickets = cli.Tickets.Where(t => !t.IsArchived)
    select new DashboardItemViewModel
    {
        Id = cli.Id,
        Name = cli.Name,
        Open = activeTickets.Count(t => t.Status == StatusType.Open),
        Responded = activeTickets.Count(t => t.Status == StatusType.Responded),
        Resolved = activeTickets.Count(t => t.Status == StatusType.Resolved)
    };


Bad names!!

Very poor naming, so much so that your code is almost unreadable and definitely unusable.
Use constants for variables that do not change. eg var n1= should be const n =
Always! indent your code.
Spaces between operators var n1=prompt( should be var n1 = prompt(
else on same line as closing } eg } else if (
Use === rather than == and !== rather than !=
The code is broken and throws errors because you have missing function calls. Next time you post on code review please make sure that the code works, or clearly mark code stubs.
A lot of repeated code could be put together as a function.

eg Ask question function

function askQuestion(message, yesCall, noCall, unsureCall) {
    const result = prompt(message, "").toLowerCase();
    if ( result === "y") { yesCall() }
    else if (result === "n") { noCall() }
    else if (result === "i") { unsureCall() }
    else { askQuestion(message, yesCall, noCall, unsureCall) }
}

Then you can ask the question

function mcs1() {
    askQuestion(
        "Do you have Medicare benefits (Y=Yes, N=No, I=I don't know)",
         mcs2, mcs1a, mcs1b
    );
}

User friendly

When creating interfaces you should never have ask the user to correct themselves due to improper use of the interface.

If you ask for a Y or N and you can not control the keys, don't respond with "Enter a valid choice Y,N or I!" as it is a pointless and frustrating step for the user. Just ask the question again. "Try again... Do you have Medicare benefits? Y/N"

Best is to ensure that the user can only make correct selections.

Use String.toLowerCase() or String.toUpperCase() to eliminate the need to differentiate between upper and lower case input.

Use a dialog with clickable options, or vet the key inputs with a keyboard event listener (not available on prompt)

Alert and Prompt are evil

Don't use prompts or alerts. Use the HTML5 element dialog (or use standard HTML) and create custom dialogs.

Custom dialogs  are non blocking and let you control the inputs, style, and much more. Giving a much better feel and flow to the interrogation.

See example how to use <dialog> element. (Note: full support for <dialog> element is only on Chrome for the moment. A polyfill can be found on MDN dialog reference page.)

Separate questions from code.

You have coded the questions into the source such that if you make a change to the questions you will need to make changes to the source code.

These types of apps (survey or interrogations) are generally a class of finite state machine. The state (a question or message) will always follow a previous known state, and the following state will depend on the current answer.

Seperate the state flow from the logic in such a way that you do not need to code the questions. You should be able to present any list of questions as a dataset (eg JSON) without needing to change any of the source code.

If the data structure is well defined, it also allows for non coders to create and change the interrogation.

An example.

The example may be a little advanced but have a look anyways, take what you can and feel free to ask questions in the comments.

It uses the dialog element to create the dialogs.
Async functions and promises to wait for user input.
Event listeners to get user clicks.
Defines a state machine via the object interrogation that uses named properties to connect states. The function interrogate takes a state name and use it to determine how to present and act on that state.

setTimeout(()=>interrogate("start"),0);

/* Structure of interrogation All names are case sensitive [] means optional
  name: { // state name
    [action]: string, // one of two actions "reset" or "showResult"
    [question]: string,  //  The question if included the must have Y,N and/or [I]
    [Y]: string  // name of state for yes result
    [N]: string  // name of state for no result
    [I]: string  // name of state for unsure result
    [message]: string, // Message to display. This is only optional if question is defined
    [next]: string // name of next state. If omitted then defaults to "exit"
  }
*/

const interrogation = {
    results: "",
    start: {
        action: "reset",
        question: "Do you have Medicare benefits?",
        Y: "partsAB",
        N: "deniedMedicare",
        I: "refSocialSecurityAdministration"
    },
    partsAB: {
        question: "Do you have Medicare Part A AND B",
        Y: "applyForHF",
        N: "unknown",
        I: "unknown"
    },
    applyForHF: {
        question: "Would you like to apply for HF MEdicare",
        Y: "applyForHFInfo",
        N: "haveCaretaker"
    },
    haveCaretaker: {
        question: "Do you have a caretaker relative who claims you on their taxes",
        Y: "haveCaretakerInfo",
        N: "dontHaveCaretakerInfo",
    },
    deniedMedicare: {
        question: "Have you applied and been denied Medicare Coverage",
        Y: "unknown",
        N: "unknown",
    },
    startAgain: {
        question: "Would you like to restart?",
        Y: "start",
        N: "exit",
    },
    unknown: {
        message: "Arrrghhhh. computer meltdown.. the pain, the pain... :P",
        next: "startAgain",
    },
    refSocialSecurity: {
        message: "Refer to Social Security to apply for the other part (Code E01M1)!"
    },
    refSocialSecurityAdministration: {
        message: "Refer to Social Security Administration to check status (Code E01M1)!"
    },
    haveCaretakerInfo: {
        message: "Follow standard prequalification with caretaker relative as the income."
    },
    dontHaveCaretakerInfo: {
        message: "Refer to the HRA/LDSS/SLDSS to apply for benefits (CODE E01H)",
    },
    applyForHFInfo: {
        message: "Transfer to Medicare Advertising to apply for HealthFirst Medicare"
    },
    exit: {
        action: "showResult",
        message: "Thank you for your participation.",
    },
}

async function askQuestion(message, includeNotSure) {
    return new Promise(selectionMade => {
        quesionMenuEl.addEventListener("click", event => {
            selectionMade(event.target.value);
            event.preventDefault();  // stops the dialog from permanently closing
            questionDialog.close();
        }, {once: true});
        questiomMessageEl.textContent = message;
        notSureButton.style.display = includeNotSure ? null : "none"; //null is default
        questionDialog.showModal();
    });
}
async function showMessage(message) {
    return new Promise(selectionMade => {
        messageMenuEl.addEventListener("click", event => {
            messageDialog.close();
            event.preventDefault(); // stops the dialog from permanently closing
            selectionMade("OK");
        }, {once: true});
        messageMessageEl.textContent = message;
        messageDialog.showModal();
    });
}
function interrogate(stateName = "exit") {
    const state = interrogation[stateName];
    if(state.action === "reset") { interrogation.results = "" }
    else if(state.action === "showResult") { console.log("Result: " + interrogation.results) }
    if (state.question) {
        askQuestion(state.question, state.I !== undefined)
            .then(result => {
                if (result !== undefined) {
                    interrogation.results += result;
                    interrogate(state[result]);
                } else {
                    interrogate(stateName); // clicked outside button
                }
            });
    } else if (state.message) {
        showMessage(state.message)
            .then(() => {
                if (stateName !== "exit") { interrogate(state.next) }
            });
    }
}
<dialog id="questionDialog">
  <form method="dialog">

    <menu id="quesionMenuEl">
      <button value="Y">Yes</button>
      <button value="N">No</button>
      <button value="I" id="notSureButton">Not sure</button>
    </menu>
  </form>
</dialog>
<dialog id="messageDialog">
  <form method="dialog">

    <menu id="messageMenuEl">
      <button value="ok">OK</button>
    </menu>
  </form>
</dialog>


Calculate number of pairs a,b where a^2 - b^2 = n

You were correct to try a^2 - b^2 = (a+b)(a-b) venue: take your n and break it into p and q so that p > q and p * q = n.

Usually there are several ways of doing it and almost each way defines a pair you need. a would be (p + q)/2 and b would be (p - q)/2. Thus, you only need pairs where either both p and q are even, or they are both odd.

You don't really need calculating a and b, or p and q, just number of pairs.

Thus, break your n into prime divisors and count distinct ways to divide those divisors into 2 different sets so that either both sets contain at least one 2, or neither do.

Edit:

Ok, some more math:

Case with n=1 is trivial: no solutions. For all other cases we can assume that n has nonempty set of prime divisors.

Let's start with case when all prime divisors are distinct and 2 is not present.

Each divisor can be placed either in set 1 or in set 2. Since sets will be obviously different, we're guaranteed p > q and since we're working with n's divisors, we can be sure that p * q = n.

Divisors' placement can be described bijectively by a string of bits with the length as number of divisors. Hence, we'll have 2^n placements, 2^(<number of divisors>-1) pairs of p and q ( -1 because swapping sets gives same p and q).

Now what if some prime divisor (except for 2, which is still not present) is present k>1 times?

For all other divisors, situation is exactly as above, but our special divisor will provide *(k+1), instead of *2 to number of pairs. Well, actually, *2 of other divisors is just a special case with k = 1.

So, if 2 is not present, we go through n's prime factorisation and for each divisor and its respective k number of occurences, we multiply our number of placements by k+1. If result is even - there were odd ks, meaning that in no placement our 2 sets were equal. We still counted every pair of p and q twice (once as set1, set2 and once as set2, set1) so we divide k+1 product by 2 and that's our answer. If result is not even - we have even quantity of every divisor, meaning that n is a square. That means we counted twice every pair of p and q but we've also counted pair of sqrt(n) once - which we shouldn't have! We would have to substract 1 before dividing by 2.

If 2 is present, things don't get much complicated either. If there's only one 2 we return 0 - because there's no a and b that work. If there's more than one - we say that one goes to each set every time so we simply drop 2 twos and stop concerning ourselves with them, repeating steps above.

And now for some code:

from collections import Counter
from functools import reduce
from operator import mul

def product(stuff): return reduce(mul, stuff)

def square_pairs_count(n):
    """Return number of pairs (a,b) so that a*a - b*b = n

    (Algo explanation goes here)
    """
    if n % 2 == 0 and n % 4 != 0:
        return 0 # (a+b) is odd and (a-b) is even (or vice versa)? No way!
    factorisation = Counter(prime_factorisation(n))
    if factorisation[2] > 1:
        # We use 2 '2's to guarantee that both (a+b) and (a-b) are even
        factorisation[2] -= 2
    factor_count_product = product(k + 1 for k in factorisation.values())

    if factor_count_product % 2 == 1:
        # n is a square and we counted root-root pair as (a+b) and (a-b), undo that
        factor_count_product -= 1

    return factor_count_product // 2 # we've counted every pair twice, so //2

print(square_pairs_count(155235236))

Of course, this code could be called comprehensible only in context of all math above. In the wild, most of the code would be a docstring explaining what happens.

Number of divisors grows pretty slowly with growth of n. It all boils down to how fast you produce them prime factors.

Your idea with "blocks":

You can notice that "block" number c contains a = c + 1 and all bs that would give n > 0 (but not necessarily integer).

If you shift block numbering so that (2+1)(2-1) is actually block 2 then you will have block number equal to a used in this block with block 1 being empty. (because no b and n would satisfy our needs).

You could iterate through each pair like:

for a in range(2, max_a(n)):
    for b in range(1, a):
        # test our (a-b)(a+b)

However, that means iterating a lot.

You could notice that each block can produce no more than 1 solution, so we could iterate through blocks instead. However, we'd have to check if a block really produces a solution:

for a in range(2, max_a(n)):
    b_squared = a*a - n
    # check if b_squared is actually a square

The trick will be in determining max_a(n).

Surely, if 2*a - 1 > n, then a^2 - (a-1)^2 > n and thus for any b we're interested in, a^2 - b^2 > n.That makes our max_a something like (n + 1)//2, or n//2 + 1 for sake of corner cases.

That's too much! we'll have to check around 10^13 blocks, and that's a lot. Well, checking couple hundred thousand primes is not a simple thing either, but it's way faster.

So, unless you can lower the boundary for a, the code would still take lots of time.

Modulo sieving

If you are interested in generative solutions, I'd recommend picking some number N, rewriting equation modulo N and looking for moduli N for a and b that are possible with given n. If, for example, N is around hundred buth there's only 10 possible modulo pairs that work - you would have to iterate only through 10 (a,b) pairs out of 10 000.

For example, if N = 3 and n mod 3 = 2 then a mod 3 = 0 and either b mod 3 = 1 or b mod 3 = 2. Of each 9 consecutive possible options for (a,b) only 2 remain. Of each 3 consecutive possible options for a only 1 remains.

For example, if N = 5 and n mod 5 = 1 then only a^2 mod 5 = 1, b^2 mod 5 = 0 and a^2 mod 5 = 0, b^2 mod 5 = 4. Of 25 possible options for (a,b) pair this leaves only 4. Of 5 possible options for a, it leaves only 3.

Moreover, if you have calculated allowed modulo pairs for some M and some N you can then calculate allowed modulo pairs for M*N and instead of iterating possible pairs with steps of size N (or M), go with M*N steps.

Combining 2 examples above, you'll get that you only need to check 3 out of 15 options for a.

Using these 2 tricks (modulo sieving and combining) you can iterate with ever-increasing steps without missing anything. However, problem does not ask for generating those pairs, only for counting their number, so that's a bit excessive.

If you find that option interesting, take a closer look at sieves and especially wheels part.


Cleaner way of returning true/false with error message

An alternative as MrSmith42 suggested could be to use exceptions.

public class ReplayDataParser
{
    private const string SupportedFileExtension = "w3g";
    private const string ErrorFileDoesNotExist = "Replay file does not exist: {0}";
    private const string ErrorFileExtensionNotSupported = "File extension is not a w3g replay file: {0}";
    private const string ErrorFileByteLengthTooSmall = "Replay file's byte length is too small: {0}";
    private const int ReplayMinimumByteLength = 288;

    private readonly string _replayFilePath;

    public ReplayDataParser(string replayFilePath)
    {
        _replayFilePath = replayFilePath;
    }

    public ReplayData Parse()
    {
        if (FileNotFound())
        {
            throw new FileNotFoundException(string.Format(ErrorFileDoesNotExist, _replayFilePath));
        }

        if (FileExtensionNotSupported())
        {
            throw new ArgumentException(string.Format(ErrorFileExtensionNotSupported, _replayFilePath));
        }

        if (FileNotTooSmall())
        {
            throw new FileTooSmallException(string.Format(ErrorFileByteLengthTooSmall, _replayFilePath));
        }

        return ParseFile();
    }

    private ReplayData ParseFile()
    {
        return new ReplayData();
    }

    private bool FileExtensionNotSupported()
    {
        return Path.GetExtension(_replayFilePath) != SupportedFileExtension;
    }

    private bool FileNotFound()
    {
        return !File.Exists(_replayFilePath);
    }

    private bool FileNotTooSmall()
    {
        byte[] replayFileBytes = File.ReadAllBytes(_replayFilePath);
        return replayFileBytes.Length < ReplayMinimumByteLength;
    }
}

The downside from this from what I can see is if you use this parser in alot of places then you will need to handle the exceptions accordingly.  However the upside is that if you wish to do different things based on the reason why something failed then you can catch individual exceptions as required.

Offered as an alternative for consideration in any event.


sort_by cleans this up quite a bit, and avoids the unnecessary conversions to and from strings:

def sort_alphabetically(numbers)
  alphas = %w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)
  .map.with_index {|x,i| [i, x]}.to_h

  numbers.sort_by {|x| alphas[x]}
end

Notes:

Point on naming: use a verb, or else a noun describing what the function returns: sort_alphabetically or alphabetically_sorted. I know technically alphabetically_sorted isn't a noun, but I see it as an abbreviation for alphabetically_sorted_list, which is too verbose.
If speed matters, you should compute the hash outside the function, so it's only done once.


You can test for emptiness of number by just if not number
After testing for emptiness, you could go straight to an int by adding number = int(number)
Inside the loops, when you test for i % 2 == 0:, and then put None as the loop body (that should really be pass), you could just test for if i % 2 != 0:, and replace None with the else body, and remove the else.
0 is even, so you can remove that test.
You can replace int(number) % 2 == 0 with not int(number) % 2.
Looking at the for loops, the range could be changed to range(1, number-1, 2), removing the need for an if statement.
You can also invert the last range, so the subtracting from number and 1 is not needed.
Python automatically adds newlines, so the \ns aren't really needed.

That leaves us with (after removing a few useless brackets):

while True:
    number = raw_input("Enter an odd number or hit ENTER to quit program: ")
    if not number:
        print "Quitting program..."
        break
    number = int(number)
    if not number % 2:
        print "That's an even number, try again."
    else:
        for i in range(1, number + 1, 2):
            print ("*" * i).center(number)
        for i in range(number - 2, 0, -2):
            print ("*" * i).center(number)

If you want to go functional, you can move your user input checking into a function. In this function you could also check if the user inputs a non-number, such as abc, by catching the exception or using str.isdigit:

def get_input():
    while True:
        number = raw_input("Enter an odd number or hit ENTER to quit program: ")
        if not number:
            return  # return None when the user wants to quit
        if number.isdigit() and int(number) % 2:
            return int(number)  # return the number, as its odd
        print "That's not a valid input (must be an odd integer), try again."

With this function, the rest of your program reduces to:

for number in iter(get_input, None):
    for i in range(1, number + 1, 2):
        print ("*" * i).center(number)
    for i in range(number - 2, 0, -2):
        print ("*" * i).center(number)

print "Quitting program..."

iter calls the function and gives its value until the function returns None (the sentinel value).

On a stylistic note:

You should always have spaced around operators, so range(int(number)+1) should be range(int(number) + 1) (that's PEP8).
You may want to add a big fat comment at the start of your program describing what it does.

Also, nice use of str.center, it avoided having too many loops!


Instead of modifying the structure of the list (adding, removing) you should rather use a Comparator (see the javadoc), which in your case could look like this:

Collections.sort(activeLoadList, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        boolean aContainsPattern = a.contains("C.");
        boolean bContainsPattern = b.contains("C.");
        if (aContainsPattern == bContainsPattern){
            return 0;
        } else {
            return aContainsPattern ? 1 : -1;
        }
    }
});

Note though, that you could/should extract your pattern to a constant instead of having it duplicated (like in my example) and furthermore, that you could use a lambda instead of an anonymous inner class if you use Java 8.

Edit:

In case you use Java 8 (and the ternary operator ?) you could boil that down quite a bit:

final String p = "C."; // the pattern to search for
Collections.sort(activeLoadList, (a, b) -> (a.contains(p) == b.contains(p) ? 0 : (a.contains(p) ? 1 : -1)));

But for the sake of readability you may rather use the more verbose version. Furthermore Solomonoff's Secret's solution is to prefer in case you won't have any further sorting criteria in the future. If you may have additional ones, though, a Comparator may be the easier way to go.

Edit 2:

As has been pointed out by Solomonoff's Secret this could even be simplified further with Java 8's Comparator.comparing:

Collections.sort(activeLoadList, Comparator.comparing(text -> text.contains("C.")));

Edit 3:

Thanks to Fabio F. for an even short version using Java 8:

activeLoadList.sort(Comparator.comparing(text -> text.contains("C.")));


Fibonacci sequence and quadratic equation using functions

Your functions do too many things:

get input from user
do some calculation
print result

It would be better to separate these responsibilities,
following the single responsibility principle.

When you separate these responsibilities, the Fibonacci generation logic will naturally end up in its own function, and the reusability becomes obvious.

Consider this rewrite of your Fibonnacci_sequence function:

def fib_sequence(n):
    """
    >>> fib_sequence(10)
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

    :param n: the number of items to calculate
    :return: list of the first n items in the sequence
    """
    a = 1
    b = 1
    k = 2
    seq = [a, b]
    while k < n:
        c = a + b
        seq.append(c)
        k += 1
        a = b
        b = c

    return seq

The improvements:

removed the printing
removed the user input
follows PEP8
better variable names
documented
has a doctest

The most interesting part is the doctest.
You can run doctests with the command:

python -m doctest script.py

Let's add a bunch more doctests:

>>> fib_sequence(0)
[]

>>> fib_sequence(1)
[1]

>>> fib_sequence(2)
[1, 1]

>>> fib_sequence(3)
[1, 1, 2]

And let's rerun the doctests. Which of these new tests will fail? fib_sequence(0) and fib_sequence(1) will fail. Just like your original implementation always printed the first two 1s, this one also always returns a list starting with [1, 1, ...].
The good thing is that now that we have the tests, we can go ahead and confidently refactor the implementation.

As a matter of fact, a nice way to generate sequences in Python is using generators. Here's an implementation of the Fibonacci sequence using a generator:

def fib():
    yield 1
    yield 1
    prev = 1
    current = 1
    while True:
        prev, current = current, prev + current
        yield current

Now we can rewrite fib_sequence in terms of this new fib function:

it = fib()
return [next(it) for _ in range(n)]

If we rerun the doctests, now they all pass.
We can further simplify this implementation using itertools.islice:

return list(itertools.islice(fib(), 0, n, 1))

To finish up, let's rewrite Fibonnacci_sequence in terms of fib_sequence:

def fibonacci_sequence():
    n = int(input("How many numbers of the Fibonacci sequence do you want to see: "))
    for num in fib_sequence(n):
        print(num)

It's a lot cleaner isn't it.

I invite you to write a fib_nth method similarly, following the same logical steps we took for fib_sequence:

remove the prompting and printing, make it return a value
write doctests, for all the interesting cases
rewrite fib_nth in terms of fib
rewrite fib_seqnum in terms of fib_nth


It's quite common to convert a number to a string to get the digits, and most of the times, it ought to work, but it's a hack, instead of modelling what should happen.

Here's another way to do it, which deliberately separates integers into its digits.

let rec digits i =
    let tens = i / 10I
    if tens = 0I
    then [i]
    else
        let ones = i % 10I
        (digits tens) @ [ones]

The rest is easy:

let euler16 x y = pown x y |> digits |> List.sum

Some examples from F# Interactive:

> euler16 2I 15;;
val it : System.Numerics.BigInteger = 26 {IsEven = true;
                                          IsOne = false;
                                          IsPowerOfTwo = false;
                                          IsZero = false;
                                          Sign = 1;}
> euler16 2I 1000;;
val it : System.Numerics.BigInteger = 1366 {IsEven = true;
                                            IsOne = false;
                                            IsPowerOfTwo = false;
                                            IsZero = false;
                                            Sign = 1;}


Here are just a few observations that may help you improve your code.  In all, it is quite clean and easy to read and understand.

Use const where practical

The show() and dump() function don't (and shouldn't) alter the underlying object, so they should be declared const:

void show(std::string const &label, Tower c) const;
void dump() const;

Use reserve() to prevent reallocations

The constructor can easily determine the maximum size of the vectors.  If there were much larger ones than this, one could avoid potentially costly memory reallocations by using Tower.reserve() within the constructor.

Prefer flexible output

This is admittedly a very simple program, but generally it's nice to allow for printing to any std::ostream rather than having std::cout hardcoded into the class.  Perhaps it could be a constructor argument.

Use all required #includes

The code makes use of std::initializer_list but doesn't have this line:

#include <initializer_list>

However, as @Morwenn points out in a comment, it's not needed to include it explicitly since std::vector must necessarily already include it.


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

Format your code

This code is messy and difficult to read.  It has inconsistent indentation, and very little whitespace, making it hard to read and understand.  There are abundant examples here of C++ code that is well formatted.

Eliminate global variables where practical

Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error.  Eliminating global variables where practical is always a good idea.  In your code, there's no reason that board or N couldn't be members of the TicTacToe class instead, properly encapsulating.

Simplify your code

The code is full of duplicated code and inefficiency.  Duplicated code is a sign that you either need to refactor (for example by creating a new function) or rewrite the logic in a more compact form.  For example, there is no reason that horizontal and vertical checks couldn't be done within the same loop.  Also, only the player that just made a move could possibly win, so there's no point in checking squares which aren't marked with the current player's token.

Use better names

The variable name board is OK, but the name flag is not.  The first name explains something about what the variable means within the context of the code, but the latter is only confusing.  Also check_board is vague and unhelpful.  What is it checking?  What does it return?  Comments would help, but it's important to use descriptive names first.

Sanitize user input better

The only thing the code currently checks for is a space that's already occupied, but it does not verify that the proposed move is within bounds.

Eliminate "magic values"

The values of 1 and 2 are sprinkled through the code, but they really ought to be a named constant instead, and specifically a named constant static member of the class.

Fix the bug

The "opposite diagonal check" has these lines (formatting fixed):

for (int i = N - 1; i > 1; i--) {   //Opposite diagonal check
    for (int j = 1; j < N - 1; j++) {
        if (board[i + 1][j - 1] == 1 && board[i][j] == 1

The first time through the loop i - N - 1, but the check is looking at board[i + 1][j - 1] which will be board[N][0] the first time through the loop.  That's out of the boundary of the board and thus, a bug.

Think of the user

What happens if there is a tie game?  The board is full, but neither player has won.  The code doesn't check for or recognize this state, but it should, to avoid a frustrating experience for a user.

Study other code

One way to become a better programmer is to ask for a review of your code.  You've just done that, so good job!  Another way that helps is to read other people's code.  Look at other implementations of this game on Code Review and carefully read the answers.  It's a very simple way to learn a lot of good information.


You could cut out some of those intermediate variables using the pipeline operator: |>

def age_post(post) do
  birthday = Timex.date({post.birthday_year, post.birthday_month, post.birthday_day})

  (Date.now |> Timex.diff(birthday, :years) |> Integer.to_string) <> " ans"
end


get_rover_position does not return anything, and therefore the variable is None. You need to instantiate MarsRover in that class method with the provided input and return the newly created instance. The same applies also to get_plateau_height.


I think, there is an error:

If I enter the values:

[-3,-2,1,5]

I get the result:

[-2,0,2,3,4]

but it should be:

[-1,0,2,3,4]

The error occurs when there are two adjacent numbers in the array (here -3 and -2).

Naming:

Index is not an index, but the actual value in the valid sequence (from min to max). I would call it value or curValue or something like that.

I don't like the name target either, because the target is actually the sequence of numbers from min to max. input would be better IMO.

Analysis

Basically you want to compare two sequences of numbers index by index. If they differ then save the target value, if not then increment to the next value of the input array. The index of the target sequence (here from min to max) is always incremented. Instead of the target sequence you can just increment a value starting from input[0] and ending on input.[input.length - 1].

All in all it could be done something like this:

function findMissing(input) {

  var result = [];

  for (var inputIndex = 0, targetValue = input[0]; targetValue <= input[input.length - 1]; targetValue++) {
    if (input[inputIndex] != targetValue) {
      result.push(targetValue);
    }
    else {
      inputIndex++;
    }
  }

  return result;
}


Why is append() slower than + and is there some oversight in the map() solution which slows it down?

You ask whether there is an oversight in the map solution, slowing it down.
There is, in the form of lambda.
When passing lambda objects, map is slowed down, as shown here.
Passing proper function objects does not have the same restrictions.

Other than that, I was unable to confirm the large performance discrepancy you found between append (40ms) and __iadd__/+= (28ms).
In the below tests, append is faster than += by (just) about 2 percent.
That is negligible.

Below, five versions of your function are tested.
Next to kidsWithCandies_map_builtin, which uses the ge function of the operator module to get a callable ge(a, b) that returns the same as a >= b, the arguably most Pythonic approach is also tested, list comprehension.

from collections import defaultdict, namedtuple
from operator import ge
from pprint import pprint as pp
from timeit import timeit
from typing import List

candy_distribution = namedtuple(
    "CandyDistribution", ["candies", "extra_candies", "solution"]
)

candy_distributions = [
    candy_distribution([2, 3, 5, 1, 3], 3, [True, True, True, False, True]),
    candy_distribution([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),
    candy_distribution([12, 1, 12], 10, [True, False, True]),
]

def kidsWithCandies_map_lambda(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    return list(map(lambda x: x >= threshold, candies))

def kidsWithCandies_map_builtin(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    thresholds = [threshold] * len(candies)
    return list(map(ge, candies, thresholds))

def kidsWithCandies_append(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    ans = []
    for x in candies:
        ans.append(x >= threshold)
    return ans

def kidsWithCandies_iadd(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    ans = []
    for x in candies:
        ans += [(x >= threshold)]
    return ans

def kidsWithCandies_comprehension(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    return [element >= threshold for element in candies]

functions_to_runtimes = defaultdict(int)

for func in (
    kidsWithCandies_map_lambda,
    kidsWithCandies_map_builtin,
    kidsWithCandies_append,
    kidsWithCandies_iadd,
    kidsWithCandies_comprehension,
):
    for candy_supply in candy_distributions:
        args = (candy_supply.candies, candy_supply.extra_candies)
        assert candy_supply.solution == func(*args)
        functions_to_runtimes[func.__name__] += timeit("func(*args)", globals=globals())

functions_to_runtimes = {  # sort by value, ascending
    k: v for k, v in sorted(functions_to_runtimes.items(), key=lambda item: item[1])
}

pp(functions_to_runtimes)

with an output of

{'kidsWithCandies_append': 2.2671058810083196,
 'kidsWithCandies_comprehension': 2.3766544990066905,
 'kidsWithCandies_iadd': 2.3180257579660974,
 'kidsWithCandies_map_builtin': 2.9652103499975055,
 'kidsWithCandies_map_lambda': 3.658640267996816}

So while there is not much of a difference between append, comprehension and in-place addition (+=), map is much improved by not using a lambda.

The most non-grandpa style approach is the list comprehension. map was even originally supposed to be dropped from Python 3; as such (but this is speculation), one can suspect that all the performance love and care went towards (list) comprehensions, append and +=. Others have tried here, but map, as a built-in, seems hard to introspect.

I omitted space complexity considerations because these seem similar for all approaches.


Reading contents of a thousand CSV files

First of all use early binding over late binding to slightly improve the performance of code and to take advantage of intelli-sense.

In VBE select Tools and then References. Scroll down to Microsoft Scripting Runtime and tick the checkbox to attach references to your project. That allows you to change

Dim fso, folderN
Set fso = CreateObject("Scripting.FileSystemObject")

to

Dim fso As FileSystemObject, folderN As String
Set fso = New FileSystemObject

Generally, you want to explicitly dim your variables and avoid using Variant type as it slows down the code by a lot believe or not! Bascially, don't rely on the runtime to workout the correct type for a variable as it takes its time to do so.

There is an .Activate in the loop that creates the worksheets. It's redundant there and just adds overhead -> remove it/comment it out and modify the assignment based on the ActiveSheet to

'Create new file and add/name new worksheets, set references to array ts
For i = 1 To 12
    With w2.Sheets.Add()
        .Name = tsN(13 - i)
    End With
    If i = 1 Then w2.Worksheets(2).Delete
    Set ts(13 - i) = w2.Sheets(tsN(13 - i))
Next i

The rest seems fine to me due to your current approach for reading the data. Your code seems rather clean, well indented and you have good comments in the right places.

Performance tip:

If performance is crucial to you consider another solution involving for example ADODB library and not opening the .CSV files just to get data out of them. ADODB allows you read the contents of a file into a Recordset object without actually opening the file (think of speed!). Then, you can use a very simple method of the Range class to copy the contents into the spreadsheet - Range.CopyFromRecordset.

You can see examples of how to use ADODB on my blog at http://vba4all.com - ADODB section is at the bottom of the article


Determining if the length of LinkedList is even or odd

The method signature is a bit odd, returning a Boolean object instead of a primitive boolean.  A clearer name would be isListLengthEven().  The function could be static, since it does not rely on any object state.

If the list has one node, then your code will crash on if(head.next.next == null).  In general, you should avoid cluttering your code with unnecessary special cases.

You don't need to keep track of count.  This solution, like yours, is O(n), but it is much simpler:

public static boolean isListLengthEven(ListNode head) {
    for (; head != null; head = head.next.next) {
        if (head.next == null) return false;
    }
    return true;
}

The trick is to observe the loop invariant: each iteration through the loop, it advances head by two nodes, so that the picture at the top of the loop is always equivalent to the original.  If it can't advance by two, then the list has an odd length.


Unfortunately your question about "How to..." is off-topic for this site but I feel that your code really needs to be reviewed as there are some things that can be improved.

Don't import .* Only use the imports that you need. If you need to import JButton, import JButton, don't import all other classes within the same package.
Fix your indentation and spacing for (i = 100; i >= 91; i--) { is a lot more readable than what you currently have.

Also, use an extra indentation step (one tab / four spaces) after each { and go back one indentation step after each }. Applying this, your code will look like:

for (i = 61; i <= 70; i++) {
    pane.add(new JButton(" " + i));
}

To make your IDE do the indentation for you:

If you are using Eclipse, select all your code and press either Ctrl + I or Ctrl + Alt + F.
If you are using Netbeans, select all your code and press Alt + Shift + F

Update, your for-loop can be written as only one loop (even though it's quite many variables and this code possibly needs it's own review...)

int COUNT = 100;
int last10s = 0;
for (int i = 0; i < COUNT; i++) {
    int decreasing = COUNT - i;
    int even10 = i / 10;
    if (decreasing % 10 == 0)
        last10s = decreasing;
    boolean shouldDecrease = even10 % 2 == 0;
    int increasing = last10s - 9 + i % 10;
    int chosen = shouldDecrease ? decreasing : increasing;
    pane.add(new JButton(" " + chosen));
}


My two takes in this. In you example your are creating a new event handler on each render, so if you want to do it that way you would for sure want to bind the event handlers in the constructor. But if your never re-using them and it doesent clutter up the JSX "markup" to much (e.g. just a clean setState) I am always using the inline setState like you suggested:

import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';

class App extends Component {
  constructor(props) {
    super(props);

    //Bound event handlers
    this.updateNewDeadline = this.updateNewDeadline.bind(this);
    this.updateDeadline = this.updateDeadline.bind(this);

    this.state = {
      deadline: 'December 25 2017',
      newDeadline: ''
    }
  }

  updateDeadline() {
    if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
      this.setState({deadline: this.state.deadline});
    } else {
      this.setState({deadline: this.state.newDeadline})
    }
  }

  updateNewDeadline(event) {
    this.setState({newDeadline: event.target.value})
  }

  render() {
    return (

Countdown To {this.state.deadline}

        <Clock deadline={this.state.deadline} />
        <form className="app-form">
          <FormGroup>
            <FormControl className="deadline-input"
              placeholder='Enter a new date'
              onChange={this.updateNewDeadline}
            />
            <Button bsStyle="primary" block onClick={this.updateDeadline}>Submit</Button>
          </FormGroup>
        </form>

    )
  }


Aggregating values of a path-dependent type

Taking a shower can do wonders. :)

You can take tuples instead and convert those to this.OrderLines in the constructor.

final class Order private() {
  case class OrderLine(x: Int, y: Double) { }

  def this(rawOrderLines: Seq[(Int, Double)]) = {
    this()
    _orderLines = rawOrderLines.map { case (x, y) => OrderLine(x, y) }
  }

  private var _orderLines: Seq[OrderLine] = null
  def orderLines = _orderLines
}

object Main extends App {
  val order = new Order(Seq((1, 1.0), (2, 2.0)))
  println(order.orderLines)
}

It’s simpler and more concise, although the call-site may still be rather confusing (not that it wasn’t already).


Implement a fold-like Function in Haskell

First, your function is concatMap from Prelude.

More idiomatic ways to write it:

myFold :: (a -> [b]) -> [a] -> [b]
myFold = concat . map
-- or
myFold f = foldr (\x acc -> (f x) ++ acc) []

If efficiency is a concern, it's a completely different question. Recommended steps in priority order:

Always compile at least with -O2
Lists are slow. ++ operation especially. Consider Data.Sequence or even vectors.
Avoid lazyness in your types
Provide all small functions with INLINE pragma.
And more...


Objects being returned.

This is fine as long as you define a convention and stick to it.

  Usage of Infinity

Your use case looks fine, you're using it as an upper and lower bound.

  Usage of non-pure functions

This one is a little subjective. For an algorithm like this, it makes sense to only write pure functions as that can make debugging easier. Your code is readable and clear, if a little contrived, but I wouldn't worry too much about this. JavaScript is sort of a weird language to ask this about since most functions won't follow this rule especially when you do DOM manipulation and frontend JavaScript.

  Closures

Very common in JavaScript. You should explore node.js if you're interested in learning more.

Nit: var that = {};. Aside from being a completely uninformative and useless variable name, this declaration isn't needed. You can rewrite the return statement as:

return {
    find: function() {
        return max_sub_arr(0, arr.length - 1);
    }
};

Or even better:

return max_sub_arr(0, arr.length - 1);

I don't see why you need to return a function to be invoked.


Find the pairs of integers that sum to N

In no particular order, a few suggestions to make the code more Pythonic.

return from generator

You do not need to raise StopIteration in a generator, you can simply return. So this:

if not list1:
    print("list is empty")
    raise StopIteration
if ...

Could have been a bit simpler as:

if not list1:
    print("list is empty")
elif ...

Use an Exception for exceptions

It is generally bad practice to put prints into your computation routines.  Instead consider using exceptions.

if not list1:
    raise ValueError("list is empty")

Then catch the exception like:

try:
    for j in find_pairs_sum_n(l, 10):
        print(j)
except ValueError as exc:
    print(exc)

You don't need history

Since the values you are evaluating are already unique by putting them into a set(), you don't need history.  Instead, only do the evaluation for numbers which are < 1/2 of n.

Mid value check only once

For the mid-value check I suggest you do it only once (ie, not in the loop).  Additionally if you use collections.Counter instead of the set() you don't need to do the list.count() because you already have the counts.

Consider using a generator expression

Now that we have simplified the loop somewhat, it can be pretty cleanly written as a generator expression:

yield from ((x, n-x) for x in values if x <= threshold and (n - x) in values)

Full code listing

from collections import Counter

def find_pairs_sum_n(values, n):
    values = Counter(values)
    non_ints = {x for x in values if not isinstance(x, int)}

    if non_ints:
        raise ValueError(
            "Found non-integers in values: {}".format(non_ints))

    threshold, n_odd = divmod(n, 2)
    if not n_odd:
        if values[threshold] > 1:
            yield threshold, threshold
        threshold -= 1

    yield from (
        (x, n-x) for x in values if x <= threshold and (n - x) in values)

list1 = [1, 1, 2, 1, 9, 9, 5, 5, 2, 3, 745, 8, 1, -11, 21]
list2 = [1, 1, 1, 1, 9, 9, 9, 9, 2, 8, 8, 8, 2, 2, 0, 0, 0, 4, 5, 6]
list3 = ["dog", "cat", "penguin", 9, 1]
list4 = []

for l in (list1, list2, list3, list4):
    try:
        for j in find_pairs_sum_n(l, 10):
            print(j)
    except ValueError as exc:
        print(exc)
    print('---')

Results:

(5, 5)
(1, 9)
(2, 8)
(-11, 21)
---
(1, 9)
(2, 8)
(4, 6)
---
Found non-integers in values: {'dog', 'penguin', 'cat'}
---
---


Firstly, your function names do not conform to standards. For example, typeYourword should be typeYourWord, thought I'd suggest actually using something similar to inputWord, so the verb is related to what the program does rather than the user.

You should read PEP 8, or set your GUI (If you are using one) to warn you of violations of the standard. For example, you are missing a lot of spaces around your operators. For example, b=raw_input("type your letter again \n") should be b = raw_input("type your letter again \n").

Your indent length varies between different functions making the code a bit harder to reason about.

The use of global variables is frowned upon. You are already returning the variable from typeYourword, so consider storing this in a variable and passing it into the other functions. For example:

word = typeYourword()
monmot(word)

monmot appears to have no function, as strings can already be indexed, though perhaps I am not seeing something there.

You do checks for greater than or less than when you could just be using the != operator to check for inequality (while len(yourword) != 4)

Code that is run when the module is loaded directly (the last three lines) should be contained within a check for __name__ == "__main__"

You do not need the else clause on the while loops, this is mainly for complicated loops involving break statements, and you can just outdent your code:

  while len(yourword)<4 or len(yourword)>4:
    yourword= raw_input("type your word again \n")
  print("Now your word : ",yourword," has the correct format")
  return yourword

Hopefully this can help you, and comment if you want anything I've said to be clarified


Code

  "When all you have is a hammer, everything looks like a nail."

Your tool chest seems to have dict, which you are using to implement a container which doesn't contain any duplicates.  There is a name for that tool.  It is called as set.  Study it; you will find it very useful.

Consider:

    nums_dict = {}

    for indx, val in enumerate(nums_small, target):
        if target - val in nums_dict:
            pass
        nums_dict[val] = indx

You are never using the value indx; you are just storing it and never retrieving it.  You could just as easily write:

    nums_dict = {}

    for val in nums_small:
        if target - val in nums_dict:
            pass
        nums_dict[val] = True

which avoids the enumerate(), with the odd initial value, and the indices which did nothing.  But this is still storing the values True, and never retrieving them.  You don't need to do this, if you use a set:

    nums_dict = set()

    for val in nums_small:
        if target - val in nums_dict:
            pass
        nums_dict.add(val)

You again use a dict for return_dict to ensure you don't have any duplicate solutions.  Actually, this code is a worse that the former, because you are using in return_dict.values(), so instead of an \$O(1)\$ key lookup, you're doing an \$O(n)\$ search through the entire list of values!  If that wasn't bad enough, you are sorting solutions twice: once to see if they already exist in return_dict, and a second time to add it into the dictionary if it wasn't found.  Saving the sorted solution would avoid the second sort.

You could replace return_dict with a set as well, but there is a catch, you can't add a list into a set, because the items in a set must be hashable to a constant value but lists are unhashable (because they can be mutated).  You can get around this by using tuples, which can't be mutated, so they can be hashed.

 return_dict = set()

 for index, val in ...:
    for solution in ...:
        sorted_solution = tuple(sorted(solution))
        return_dict.add(sorted_solution)

 return list(return_dict)

The above returns a list of tuples.  If you need a list of lists, that can be easily obtained as well, using list comprehension ...

 return [ list(solution) for solution in return_dict ]

... which is another useful tool for your tool chest.

Algorithm

Using _twoSum() to solve the threeSum() problem is good reuse of code.  Kudos.

However, looping over all indices and for each index, constructing a new list omitting just that one value from the list nums[:indx] + nums[indx+1:] is extremely inefficient.

Since "Leetcode" is a puzzle solving site, I won't give you the better algorithm, but I will say that splitting nums into len(nums) different lists is not the way to go.  I would split it into 2 lists, or maybe 3 lists tops.  Good luck!


The most inefficient thing in your code is usage of byte[] to hold video or image data. There is a concept of Large Object Heap in .NET which is not compacted unless explicitly otherwise made-to starting .Net 4.5.1.

Red Gate's Explanation of Large Object Heap

Latest behavior of Large Object Heap

All your objects with a size of more that 85000 bytes are allocated on large object heap. These are not collected like  mentioned in .Net garbage collection and dealt with separately. You can read better in the links above.

As a sidenote, You can cross-check if you do need engine.GetMetadata(video); to generate the thumbnail.

The answer to your question would be

Like you are returning image as a byte array, you can choose to return a image url from the disk. Some part of byte array will be reduced.
With .net 4.5.1, you can call .net LOH compaction programmatically.
You can also do this processing in completely separate appdomain in memory, and then unloading it.
Or you can generate thumbnails from a completely separate windows service or console application, you simply restart them.

Read few more things on Large Object Heap


There is quite a lot that you can do to make this idiomatic. I'll also go a bit overboard and show some ways to fully polish it (emphasis on way overboard for most projects).

You mention potentially wanting to do multi.  That's certainly possible here:

multi sub circumfix:<α ω>( ( $a where Positional, $b, $c ) ) { ... };
multi sub circumfix:<α ω>( ( $a where Int,        $b, $c ) ) { ... };

But ultimately it's unnecessary.  As the other answer points out, Raku has a junction types built in. They can be made by using the routines (or operators)  all (&), any (|), one (^) and none — the routines are available as both subs and methods.  In your case, we can take advantage of the fact that junctions can be made on a single item or a list, so that regardless whether $a is a list of Int or just a single Int, we can make it into a junction.  That right there can reduce your code to:

sub circumfix:<α ω>( ( $a, $b, $c ) ) {
   so ( $a.any >= $b & $a.any <= $c );
};

Although we're going to remove it entirely, it should be noted that & is a junction. This is slightly less efficient than using && which just checks whether both sides are true and evaluates to a Bool.  But we won't need to do that at all.  Raku allows for chained operators, and the comparison operators are defined as such.  This means that we can simplify things even further to:

sub circumfix:<α ω>( ( $a, $b, $c ) ) {
   so $b ≤ $a.any ≤ $c;
};

so has very loose operator precedence, so we don't need parentheses here.  The final two considerations are purely stylistic, but help for code maintaince.  The names $a, $b, and $c aren't descriptive.  You'd definitely want to use something better.  Also, it's fairly common, though not universal, to give extra emphasis to the fact that we're not mutating the values by using sigil-less variables.  Personally, I also like to use whitespace to indicate the tighter grouping when using deconstruction, but YMMV.  Lastly, semicolons aren't needed when they're the final expression of a block, or when a block terminates the line, so we can remove the semicolons.

sub circumfix:<α ω>( (\val,\min,\max) ) {
   so min ≤ val.any ≤ max
}

In this case, using min/max/val without sigils maybe is a bit riskier as they are also routines, but it seems to workout okay.

If we want to go above and beyond for safety's sake, we can check the values in the signature.  I'm assuming based on your original that you wanted to limit things to Int values so let's make it explicit, and specify our return value:

sub circumfix:<α ω>( (\val where .all ~~ Int, \min where Int, \max where Int) --> Bool) {
   so min ≤ val.any ≤ max
}

At this point, the signature is getting a bit unruly, and so I like to spread it across multiple lines.  Particularly if you have several deconstructed arguments, this lets identation also show structure a bit more clearly (but in this case, it's less necessary of course):

sub circumfix:<α ω> (
    (
       \val where .all ~~ Int,
       \min where         Int,
       \max where         Int
    )
    --> Bool
) {
   so min ≤ val.any ≤ max
}

And don't forget that Raku's POD syntax means we can also add in documentation that could help users or automatically create documentation:

#| Determine if a value or values are between the given values (inclusive)
sub circumfix:<α ω> (
    (
       \val where .all ~~ Int, #= The Int value or values to be tested
       \min where         Int, #= The lowest acceptable value
       \max where         Int  #= The highest acceptable value
    )
    --> Bool
) {
   so min ≤ val.any ≤ max
}

IDEs like Comma are already able to pull some of this information to make coding easier.  Using it on signatures is really only supported for generating help feedback automatically on command line usage, but it's only a matter of time before such things will be integrated into IDEs.


Functional tests for a web app repeating the same code

Move your 4 lines into a method with a [TestFixtureSetUp] Attribute. This will run everytime a test is run.

See here: http://www.nunit.org/index.php?p=fixtureSetup&r=2.2.10

For example:

class ShortTextPopupTests : BaseTest
{
    private ENAEPAdminLoginPage adminLoginPage;
    private AdminResetPage adminResetPage;
    private AppropriateType studentAssessmentPage;

    [TestFixtureSetUp]
    public void SetupFixture()
    {
        adminLoginPage = new ENAEPAdminLoginPage(Driver);
        adminLoginPage.GoToAndLoginWithOperationalBookletSupervisor();
        adminResetPage = new AdminResetPage(Driver);
        studentAssessmentPage = adminResetPage.GoToSpecificBookletLocation(BookletLocations.ShortTextPopup);
        studentAssessmentPage.ShortTextPopup.OpenPopUp();
    }

    [Test]
    [Retry(2)]
    [Description("Validate that the pop up can open and close when it is clicked.")]
    public void GivenCorrectItemIsOpened_WhenTogglingPopup_ThenPopupOpensAndCloses()
    {
        studentAssessmentPage.ShortTextPopup.ClosePopUp();
        Assert.IsFalse(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The pop up did not close after trying to close the pop up");
    }

    [Test]
    [Retry(2)]
    [Description("Validate that opening a pop up, clicking next, coming back to a page, closes that opened pop up")]
    public void NavigationToDifferentPageClosesPopup()
    {
        studentAssessmentPage.ENAEPToolBar.ClickNextButton();
        studentAssessmentPage.ENAEPToolBar.ClickBackButton();
        Assert.IsFalse(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The pop up did not close after leaving and coming back to the page.");
    }

    [Test]
    [Retry(2)]
    [Description("Opening a short text pop up and then clicking on other things on the page should not close the pop up.")]
    [Property("TCID", "35458")]
    public void ClickingItemsOnScreenShouldNotClosePopUps()
    {
        studentAssessmentPage.ClickRandomPlacesOnPage();
        Assert.IsTrue(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The popup did not stay open after clicking in random places in the assessment.");
    }
}


Laravel 5 controller to list appointments by date range and by label

The structure looks ok to me (I'm not that familiar with laravel, but this is basically how MVC in a web context generally looks). A couple of minor points:

you don't really need one-time variables such as $appointments, just return directly.
findAppointments* could be renamed to find*. It's in the Appointment class, so it's expected that it will find an appointment, unless noted otherwise. This also avoids the odd phrasing of Appointment::findAppointments and makes it Appointment::find.
be as explicit with your variable names as possible (here, it's not so important, but it's good practice, and for larger methods it does get important). eg value could be label, or even labelId, and start/end could be startDate/endDate (it may seem that this is a contradiction with the point above, but it's really not; the variables will be used inside the method, missing the direct context of the method name, while the methods will be called either directly on the class as you are doing, or on a variable, which will be named after the class, giving them direct context).
You can use self:: instead of ClassName::, even in static methods.


Print a square graph and dot based on co-ordinates

I only looked at the plot_point function, but I would suggest using an alternative approach - first create a board full of _ and then set the correct cell to a * and finally print out the whole board. This is much shorter and more "pythonic" than iterating like you are currently doing (which is rather C like).

def plot_point(x, y):
    os.system('cls') if os.name == 'nt' else os.system('clear')
    print 'Printing', x, y # Turned on for single use, off for mass use

    # Create a board of 10 x 10 underscores
    board = [['_' for col in range(10)] for row in range(10)]

    # Set the appropriate cell to a *
    board[x][y] = '*'

    # Create a string with a | seperating each element for each row
    # Print out all these rows with newlines in between
    print '\n'.join(['|' + '|'.join(row) + '|' for row in board])

    time.sleep(.05) # Just for purpose of demonstration

We use list comprehensions to make our code a lot shorter (and still very readable). The one-line print statement may be considered a little bit hard to read, in which case you can consider splitting it up a bit.

for row in board:
    print '|' + '|'.join(row) + '|'

But I think that the comprehension is fine.


Function to find factors of a number, optionally including 1 and the number itself

What about this?

[1] * one + result + [n] * itself


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

Use the correct pragma

There is no #DEFINE in standard C.  It should instead be #define.  Case is significant in C.  Similarly, INT and VOID are not keywords in standard C, but int and void are.

Fix the formatting

The code is diabolically difficult to read with its current formatting.  First, put the description above the function itself.  Second, write a meaningful comment; the current description of GenericStringSplit is so vague and confusing as to be useless.  Third, don't put multiple statements on a line.  For example, instead of this:

if (string[size] == delimiter) string[size] = replace;

write this:

if (string[size] == delimiter) {
    string[size] = replace;
}

It's wise to get into the habit of using braces even with a one-liner.  Doing so lessens the likelihood of introducing subtle bugs as you maintain the code.

Use the required #includes

The code uses strlen and size_t both of which indicate that the code needs #include <string.h>.  It was not difficult to infer, but it helps reviewers if the code is complete.

Use standard functions

Your StringDelimiterReplace is, as it's currently used, very similar to the standard strtok function.  It could also benefit from using the standard strchr function.

/*
 * replaces all instances of delimiter with replace in string.
 *
 * Note that the passed string is modified in place and so cannot
 * be const and cannot be NULL.  Also, the NUL char ('\0') cannot
 * be used as the delimiter. The use of an int that does not
 * fit within a char for either the delimiter or the replace
 * parameters is not supported.  Wide strings are also not supported.
 *
 * In short, don't actually use this function in production code.
 */
static void StringDelimiterReplace(char *string, int delimiter, int replace) {
    while (NULL != (string = strchr(string, delimiter))) {
            *string++ = replace;
    }
}

Note that this has the effect of only traversing the string once instead of twice in the original code (once for strlen and again in the loop).

Do one thing well

The GenericStringSplit does multiple things.  It modifies the passed string and it passes back a pointer.  I'd strongly suggest that the code would be easier to understand if each function only did one thing.

Allow the use of const strings

The current code modifies the passed string in place, but an enhancement would be to allow const strings to be passed in.

Rethink the interface

I'd suggest that an alternative approach would be to actually look for "vid_" or "pid_" and then extract the corresponding ID.  One approach:

unsigned hexval(const char *string, const char *target) {
    char *found = strstr(string, target);
    if (found == NULL) {
        return 0;
    }
    return 0xffff & strtoul(&found[strlen(target)], NULL, 16);
}

Usage:

unsigned vid=hexval(string, "vid_");
unsigned pid=hexval(string, "pid_");
printf("%4.4x:%4.4x\n", vid, pid);


Largest product in a grid - Project Euler 11

all_products

At the top, you initialize all_products = [].  Then you call get_horizontal(), which appends products of four_elements to all_products.  Then you get and return the maximum.

Then you call get_left() which does the same thing ... but continues appending to the all_products list.  When the maximum is computed, it is the maximum of both the horizontal and the left diagonals!

In other words, you don't need to find the maximum of the horizontal, left, right and vertical results.  That is already being accidentally done.

get_horizontal()
get_left()
get_right()
print(get_vertical())    # Still returns the maximum over all 4 directions!

You should initialize all_products = [] inside the get_left, get_right, get_horizontal and get_vertical functions, and remove it from global scope.

Float or integer?

Your results ends in .0.  All the numbers are integer numbers.  You could load the grid as an integer matrix:

grid = np.loadtxt("grid.txt", dtype='i')

And now the answer is generated without a decimal point.

Looping

You've written code like this 4 times:

    start, finish = 0, 4
    while finish <= 20:
        four_elements = ... start:finish ...
        ...
        start += 1
        finish += 1

This is a simple loop from finish=4 to finish=20 (or finish=len(dgnl)).  Start and end always differ by 4, so you could use finish - 4 instead of start.  Or loop over start and use start + 4 for finish.

Eg)

    for start in range(16 + 1):
        four_elements = ... start : start+4 ...
        ...

With 4 copies of the that code, 3 less lines per copy, you've saved 12 lines.

Flip, and flip, and flip

def get_left():
    for i in range(-16, 16):
        dgnl = np.diagonal(np.flipud(grid), i)

Each time though this loop, you flipud(grid).  That's 32 identical flips.  Maybe you'd want to save this as a temporary result:

def get_left():
    flipped_grid = np.flipud(grid)
    for i in range(-16, 16):
        dgnl = np.diagonal(flipped_grid, i)

Question: Why 32?  Perhaps you meant for i in range(-16, 16 + 1):?  You were missing a diagonal!!!   Twice!!!

Call functions more than once

Now, get_left() and get_right() are identical, save for that initial flip.  You could pass the grid into get_right(), and get_left() could pass a flipped copy to get_right():

def get_right(grid):
    for i in range(-16, 16):
        dgnl = np.diagonal(grid, i)
        for start in range(len(dgnl) - 3):
            four_elements = dgnl[start:start + 4]
            all_products.append(np.prod(four_elements))
    max_right = max(all_products)
    return max_right

def get_left(grid):
    return get_right(np.flipud(grid))

Call functions more than once (reprise)

get_horizontal() and get_vertical() are duplicates also ... save for grabbing either the ith row or column.  If you transposed the matrix, columns would become rows, and you could again use the same function.

Flip, Transpose ... Rotate!

If you flip the matrix, one left-up diagonals become left-down ones, but rows and columns are still rows and columns.  If you transpose the matrix, rows become columns, columns become rows, but the left-up diagonals are still left-up diagonals.

If you rotate the matrix 90 degrees, rows become columns and left-up diagonals become left-down diagonals.

rotated = np.rot90(grid)
print(max(get_horizontal(grid), get_horizontal(rotated), get_right(grid), get_right(rotated)))

Using NumPy

All you've really used NumPy for is loading the grid from a file, flipping it, and extracting diagonals.  It is much more powerful than that.

import numpy as np

grid = np.loadtxt("grid.txt", dtype='i')

print(max(np.max(grid[ :  , :-3] * grid[ :  , 1:-2] * grid[ :  , 2:-1] * grid[ :  , 3:]),
          np.max(grid[ :-3, :  ] * grid[1:-2,  :  ] * grid[2:-1,  :  ] * grid[3:  ,  :]),
          np.max(grid[ :-3, :-3] * grid[1:-2, 1:-2] * grid[2:-1, 2:-1] * grid[3:  , 3:]),
          np.max(grid[3:  , :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[ :-3, 3:])))

Note: this works for 20 x 20 matrices, and 200 x 200 matrices equally well.

Okay, perhaps we should explain exactly what is going on there.  Let's start with a 7x7 matrix, with random single-digit values:

>>> import numpy as np
>>> grid = np.random.randint(0, 10, (7, 7))
>>> grid
array([[8, 2, 3, 9, 9, 9, 3],
       [6, 2, 8, 0, 9, 4, 3],
       [0, 6, 9, 5, 6, 8, 8],
       [8, 5, 2, 6, 3, 0, 8],
       [5, 8, 0, 6, 7, 0, 3],
       [4, 3, 1, 0, 2, 5, 5],
       [4, 9, 5, 7, 2, 6, 0]])

grid[3:, :-3] will extract all the values starting at the 3rd row, and all the columns except the last 3 columns.

>>> grid[3:, :-3]
array([[8, 5, 2, 6],
       [5, 8, 0, 6],
       [4, 3, 1, 0],
       [4, 9, 5, 7]])

The grid[1:-2, 2:-1] extracts the 4x4 matrix one row up and one column to the right of the first:

>>> grid[2:-1, 1:-2]
array([[6, 9, 5, 6],
       [5, 2, 6, 3],
       [8, 0, 6, 7],
       [3, 1, 0, 2]])

And two rows up, two columns to the right:

>>> grid[1:-2, 2:-1]
array([[8, 0, 9, 4],
       [9, 5, 6, 8],
       [2, 6, 3, 0],
       [0, 6, 7, 0]])

And finally three rows up, three columns to the right ... in other words the top 4 rows, and the rightmost four columns:

>>> grid[:-3, 3:]
array([[9, 9, 9, 3],
       [0, 9, 4, 3],
       [5, 6, 8, 8],
       [6, 3, 0, 8]])

We can take these matrices, and multiply respective elements together:

>> grid[3:, :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[:-3, 3:]
array([[3456,    0,  810,  432],
       [   0,  720,    0,  432],
       [ 320,    0,  144,    0],
       [   0,  162,    0,    0]])

For instance, the top-left corners contain 8, 6, 8 and 9, and the product of those is 8*6*8*9 = 3456.  Looking at the original matrix, we can see these values in a diagonal starting at row 3, column 0 and going up to row 0, column 3.

The next diagonal contains 5, 5, 9, 0, 9.  5*5*9*0 = 0 and 5*9*0*9 = 0, which is the next diagonal of our product matrix.

The largest product in that matrix?

>>> np.max(grid[3:, :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[:-3, 3:])
3456

The other 3 expressions take different adjacent rectangular regions, multiply them together, and find the maximums for the other diagonal and the rows and columns.


How to modify this code, so it doesn't use forEach?

One way to achieve this is using Array.prototype.reduce():
const totalWordCount = fileTexts.reduce((big: sum, fileText: string) => {
    return sum + nlp(fileText).wordCount()
}, 0)

Notice that totalWordCount is assigned once so const can be used which helps avoid accidental re-assignment and other bugs.
If fileTexts is only used to calculate totalWordCount then the two loops could be combined into a single loop (e.g. with reduce()).
To learn more about functional techniques try these functional exercises.


Yes there is a better way to do it. It makes the computation really simple and elegant.

If you take the transpose of the matrix and then rotate the matrix row-wise along the mid row, you can get the same result as rotating the matrix by 90 degrees counter clock-wise.

For example:

[1 2 3]
[4 5 6]
[7 8 9]

Step 1: take its transpose:

[1 4 7]
[2 5 8]
[3 6 9]

Step 2: rotate the matrix across mid row:

[3 6 9]
[2 5 8]
[1 4 7]

This is exactly what you get when you rotate the matrix by 90 degrees left.

Here is the code:

public static void rotateMatrix(int[][] matrix){
    if(matrix == null)
        return;
    if(matrix.length != matrix[0].length)//INVALID INPUT
        return;
    getTranspose(matrix);
    rorateAlongMidRow(matrix);
}

private static void getTranspose(int[][] matrix) {
    for(int i = 0; i < matrix.length; i++){
        for(int j = i+1; j < matrix.length ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}

private static void rorateAlongMidRow(int[][] matrix) {
    int len = matrix.length ;
    for(int i = 0; i < len/2; i++){
        for(int j = 0;j < len; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len-1 -i][j];
            matrix[len -1 -i][j] = temp;
        }
    }
}

Edit: As suggested in the comment, for making it rotate clock-wise, just change the function getTranspose() to rotateAlongDiagonal() in rotateMatrix() function.

private static void rotateAlongDiagonal(int[][] matrix) {
    int len = matrix.length;
    for(int i = 0; i < len; i++){
        for(int j = 0; j < len - 1 - i ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len -1 - j][len-1-i];
            matrix[len -1 - j][len-1-i] = temp;
        }
    }
}


Registering endpoints and HTTP method for exemption of authentication

Basically what you are asking is what can we do about this

    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.DELETE))

    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.DELETE))

and the contents of the else block as well.

I would create a method that takes the Endpoints ep1 and ep2 as parameters

something like

Public Sub MethodAddingEndpointsToExemptedList(endpoint As String)
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.DELETE))
End Sub

and then you can just call this method inside the if block like this

If allMethods Then
    MethodAddingEndpointsToExemptedList(ep1)
    MethodAddingEndpointsToExemptedList(ep2)
Else
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method))
End If

You could go a step further and create a list of the endpoints and then use a foreach loop to add them to the list of Exempted endpoints.


Simulated arcade with a slot machine and number-guessing game

slotmachine() and higherorlower() call gameend(). In turn, gameend() may call main(). This is considered "spaghetti code", because functions should not be used as goto labels.

Rather, if your code acts as a loop, then it should be written with a loop, like this:

def main():
    while True:
        menu = int(input("What would you like to play?(Enter the corresponding number for each one)\n1. Slot Machine - 20 coins per turn\n2. Higher or Lower - 10 coins per turn\n"))
        if menu == 1:
            slot_machine(tokens)
        elif menu == 2:
            higher_or_lower(tokens)
        if game_end():
            break

The way you pass tokens is inappropriate. In main(), you are using a global variable tokens. However, in slotmachine() and higherorlower(), there is a local variable coincidentally named tokens, due to the function parameter. Make up your mind whether you want to use a global variable or pass the state around using parameters and return values.


Initial thoughts are:

Why is move calling create?  I don't know what create does, but this seems like a strange way for move to work.
You're using 5 for all four directions, this seems like it should probably be a constant.
It's unclear how you're going to implement collision detection at the moment, but it's something to consider when defining the interface for moving items.

From your comments, it seems that create draws Pacman.  If this is the case, then I'd still say that you don't want to be calling it from within your move method.  You want to try to decouple your game mechanics + movement/collision logic from your drawing/rendering logic, they are different concerns and may well move at different speeds.  One of the things you've said that you are looking for is to improve the speed that your code runs at.  If you think about running games on different hardware, one of the things to consider is that you need to start thinking about using that hardware effectively.  To give a concrete example, if your current computer processes your move method 10 times a second, that's going to move your Pacman 50 units.  Another computer may only run it 5 (moving 25 units) or may run it 50 (moving 250 units) that's a lot of variability that's usually ironed by linking the distance moved to the amount of elapsed time, which may be detached from the render time.

I haven't read the whole thing (and it seems to be aimed at the mobile market), but this seems like a fairly good introduction to game loop mechanics.


Calculate the intersections of opening hours

calculate is not reusable. It's hardcoded to always use filteredTimes. It's also putting its results to an array on the outside. Strive for pure functions as much as possible, like math equations. It keeps them reusable, testable and deterministic.
Your variable names are vague. A good sign that you're not naming things well enough is when you have to explain to another developer what it is (like what you're doing in the comments). Never be afraid to name things verbosely.
You might not need moment.js. What you're doing with moment.js is just intermediary conversion of formats - an unnecessary procedure. When operating with dates and times, it's best to have your data in a format that doesn't need intermediate conversions.

Now simply put, what you're essentially looking for "windows" where the given times overlap. Here's a modified version of your code. The modifications include:

The times are all numbers. You don't really need to have the HH:mm format in this operation. If you strip off the : from the time, they're effectively numbers from 0000 to 2359` (with the last 40 mins in each hour missing). This eliminates the need for moment.js.
Nested array.forEach(), because for loops are also clunky (you have to keep indexes, do length comparisons, etc.). Plus you're using array.forEach() already anyways.
I stored results in an object keyed by the combination of from and to. This way, the lookup doesn't require a very clunky array.find(). Converting it to an array is as simple as iterating over the keys and mapping them to the values.
computeWindows is now a pure-ish function. You can now call it anytime, anywhere with any input, and always get a deterministic-ish output (Object.keys() do not guarantee the order of keys, so while the items may be the same, the order may be different by browser).

const ranges = [{
  from: 1000,
  to: 1100
}, {
  from: 1015,
  to: 1115
}, {
  from: 1030,
  to: 1130
}, {
  from: 1045,
  to: 1145
}, {
  from: 1100,
  to: 1200
}]

const isBetween = (value, start, end) => value > start && value < end

const computeWindows = ranges => {
  const index = {}

  ranges.forEach(({ from: rFrom, to: rTo }) => {
    ranges.forEach(({ from: cFrom, to: cTo }) => {
      // The actual logic
      rFrom = isBetween(cFrom, rFrom, rTo) && cFrom > rFrom ? cFrom : rFrom
      rTo = isBetween(cTo, rFrom, rTo) && cTo < rTo ? cTo : rTo
    })

    // Construct the key and value
    const key = `${rFrom}-${rTo}`
    const value = { from: rFrom, to: rTo }

    // Use existing value of key or add new value to key.
    index[key] = index[key] || value
  })

  // Convert results into an array of ranges.
  return Object.keys(index).map(k => index[k])
}

console.log(computeWindows(ranges))