I don't see how this could benefit from C++11/14 techniques much - modern C++ gives you more tools mainly in terms of template metaprogramming, container algorithms, functional programming etc. You are dealing solely with primitive types and operate on streams, and newer standards haven't brought a revolution to these areas. The code is clean, variables have proper names etc, and that's why I'll stick to some general remarks.

Optimize I/O streams usage

Since you may possibly print a lot of information to std::cout, it might be a good idea to decouple it from the C streams. Synchronizing with C streams is associated with a significant performance hit, but necessary if you try to write to the stream concurrently or mix C and C++ streams - you are not doing any of these things though, so it's safe to do this at the start of your program:

std::ios_base::sync_with_stdio(false);

See this link for further information on this topic. Also, there are some benchamrks backing up this approach on SO, e.g. here.

Usually you don't have to care about the performance of I/O streams that much, but several times this trick helped me get to the top of the shortest execution times in coding exercises like this. Also it does make a difference if you are printing thousand of lines.

Don't use using-directive file-wide

It's considered a bad practice to put e.g. using namespace std; on top of the file as it may introduce subtle bugs when you use functions of the same name coming from different namespaces - it also requires manual checking to see from which namespace a particular function comes. It's not a problem in a simple program like that of course, but it's good to nurture good habits.

Put your code into proper function

Again, maybe you know it and it's just because this program is just a small competitive programming task, but usually you want to put your code inside a function of proper name, avoiding putting too much bare code inside main().

Make variables that are not to be mutated const

breadth and height are set once and never changed. Making them const would prevent you from accidentally mutating them while you expect them to hold their value. It also shows their role in the code better.


What is a "good" hash function?

The requirement of a hash function is that it always produces the same value for a given key (in the same instance of the program) and a good hash function should produce each output with equal probability.

Your function achieves this (multiplying by a prime such as 31 is a well-known way of combining hash values to reduce collisions caused by different permutations of the same values).

However, it's up to you to decide whether the hash inputs in your application have a random distribution, or whether they have some pattern that may perturb the output distribution from the hash function.

Can you use your mental reasoning to force a collision?  {1, 0} and {0, 31} might do it, for example.  Can you think of any reason why your code might produce collisions more often than by independent chance?

Style points

The code is neat and clear.  It might be an idea to allow an alternative to std::hash<T> to be supplied by the caller, just as std::unordered_map itself allows a user-supplied hasher.  This may be useful with char* strings, for example.

You could simplify the loop, as std::array supports range-based for:

    for (const auto& element: key) {
        result = result * 31 + hasher(element);
    }

More tests

It's good that you've provided a test suite.  Consider whether you could add more tests - at least one test with an element type other than int and at least least one with different array lengths (you should probably include a test for std::array<char, 1> as a boundary case, for example).

Alternatives

Boost provides a hash() function that accepts built-in (i.e. C-style) arrays, so you might be able to reinterpret_cast the std::array.  I've never tried this, but I don't see why it wouldn't work...


Your map is of booleans so you can replace if _, ok := seen[job.url]; ok || bar with if seen[job.url] || bar. The zero value (which is what gets returned for non-existing map lookups) of bool is false.
It would be better to have Crawl do something like

defer func() {
    job.done <- true
}()

immediately once only rather than sprinkle job.done <- true at all the right places and hoping you (and any future editors) don't ever miss any.
Your for loop in Crawl should either just require the channel is sufficiently buffered (as it currently is) and not bother with goroutines, or the whole for loop should be put into a single goroutine (and then you don't need any channel buffering).
for i := 0; i < len(urls); i++ should be just for i := range urls (or since you don't need i just for _ = range urls).
You seem to be using Jobs.done like sync.WaitGroup.

You could just have a single wait group that keeps track of outstanding jobs. Your main would make sure to call wg.Add(1) before sending it's first job and before it then does wg.Wait(). Mostly everywhere you do job.done <- true would then be just wg.Done(). You'd just need to make sure that your crawler did wg.Add(len(urls)) before it did wg.Done() to make sure the wait group count could never accidentally fall to zero too early.
Although having dedup check the depth is probably still a good idea, it's easy and trivially to do it in the crawl function and save some effort.

You code modified with the above points:

type Job struct {
    url   string
    depth int
}

func dedup(fetcher Fetcher, ch chan Job, wg *sync.WaitGroup) {
    seen := make(map[string]bool)
    for job := range ch {
        if seen[job.url] || job.depth <= 0 {
            wg.Done()
            continue
        }
        seen[job.url] = true
        go Crawl(job, fetcher, ch, wg)
    }
}

func Crawl(job Job, fetcher Fetcher, q chan Job, wg *sync.WaitGroup) {
    defer wg.Done()
    body, urls, err := fetcher.Fetch(job.url)
    if err != nil {
        log.Println("Crawl failure:", err) // TODO: something better with errors
        return
    }
    log.Printf("Crawl: found %s\t%q\n", job.url, body)

    if job.depth <= 1 {
        return
    }

    wg.Add(len(urls))
    for _, u := range urls {
        q <- Job{u, job.depth - 1}
    }
}

func main() {
    wg := new(sync.WaitGroup)
    wg.Add(1)

    q := make(chan Job)
    go dedup(fetcher, q, wg)
    q <- Job{"http://golang.org/", 4}
    wg.Wait()

    // We close q here so that the dedup goroutine
    // will finish. This isn't strictly needed here
    // since we're main and everything gets stopped
    // when we return; but that wouldn't be the case
    // if we were some other function in a long lived
    // program.
    close(q)
}

And runnable on the playground (by including the Go tour stuff):
http://play.golang.org/p/cuY3PZdQmI

(For comparison: your original code is also runnable on the playground.)


Performance: getting first value from comma delimited string

UPDATE:
A more complete benchmark script:

$start = $first = $str = null;//create vars, don't benchmark this
//time preg_match
$start = microtime(true);
$first = $str = implode(',', range(213,9999));
if (preg_match('/^[^,]+/', $str, $match))
{
    $first = $match[0];
}
echo $first, PHP_EOL, microtime(true) - $start, ' time taken
', PHP_EOL;
//time str* functions
$start = microtime(true);
$first = $str = implode(',', range(213,9999));
$first = substr($str, 0, strpos($str, ','));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken
', PHP_EOL;
//now explode + current
$first = null;
$start = microtime(true);
$str = implode(',', range(213, 9999));
$first = current(explode(',', $str));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken';

The result varried a little, but after 100 runs, the averages amounted to:

#1 substr+strpos: ~.0022ms as 1//base for speed
#2 preg_match: ~.0041 as ~2//about twice as slow as #1
#3 explode: ~.00789 as ~4//about 4 times <=> #1, twice as slow <=> regex

You're absolutely right, exploding a string, constructing an array to get just the first value is a waste of resources, and it is not the fastest way to get what you want.
Some might run to regex for help, and chances are that, in your case that will be faster. But nothing I can think of will beat the speed of PHP's string functions (which are very close to the C string functions). I'd do this:

$first = substr($var, 0, strpos($var, ','));

If the comma isn't present (say $var = '123'), then your current approach will assign 123 to $first. To preserve this behaviour, I'd go for:

$first = strpos($var, ',') === false ? $var : substr($var, 0, strpos($var, ','));

This is to say: if strpos returns false, then there is no comma at all, so assign the entire string to $first, else get everything in front of the first comma.

For completeness sake (and after some initial bench-marking), using preg_match did indeed prove to be faster than using explode with large strings ($var = implode(',', range(1, 9999));), when using this code:

$first = $var = implode(',', range(1,9999));
if (preg_match('/^[^,]*/',$var, $match))
{
    $first = $match[0];
}

But honestly, I wouldn't use regex in this case.

In the interest of fairness, and to to clarify how I found the regex to be faster:

$start = microtime(true);
$first = $str = implode(',', range(213,9999));
if (preg_match('/^[^,]+/', $str, $match))
{
    $first = $match[0];
}
echo $first, PHP_EOL, $str, PHP_EOL, microtime(true) - $start, ' time taken';
$first = null;
$start = microtime(true);
$str = implode(',', range(213, 9999));
$first = current(explode(',', $str));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken';


Ranking and storing scores to a database

Formatting

your indentation is off, making your code hard to read.
it is customary to put the opening curly bracket on the same line as the statement it belongs to (except for functions and classes).
if (cond) return true; else return false; can be written as return cond.
Your spacing is not consistent (use an IDE to fix this - and most other formatting issues - easily).

If we fix these issues, the first function for example would look like this:

function gradeScoreFormula($score1, $score2)
{
    return $score1 > $score2;
}

Naming

gradeScoreFormula is quite specific for such a generic function, yet it doesn't really tell me anything about what the function actually does. isLargerThan might be better. [Although the function seems all wrong anyways. All the sort functions expect the function to return an integer; in that case, you could simply call the function compare]

Security

You should use prepared statements, as you may otherwise be vulnerable to second order SQL injection.

Even if the score and/or uid values in the users table are not currently user input, they may be in the future.

Additionally, prepared statements may increase performance in this case, as the query would only need to be prepared once.

Misc

WHERE uid = $k AND score = $v seems odd to me. Why are you checking for the score as well? If there is a reason, I would add a comment about it. If there is no reason, I would remove that check; the primary id should be enough, as far as I can tell.
why have position and a? It doesn't seem necessary to have two variables here. For that matter, it doesn't seem necessary to have either one, you could simply use i + 1 directly in the query.
Your foreach($reversedArr[$i] as $k => $v) is confusing and unnecessary. You only have it to access the key and value of a one-entry array. If you need the key, you can use the key function.

Complexity

Your code is indeed overly complex, mainly because you perform unnecessary and complex transformations between data structures and because you are not using the correct functions.

The core of your program could be as simple as this:

function gradeScore(array $values, $dbc)
{
    arsort($values);

    $position = 0;
    $query = "UPDATE users set subposition = ? WHERE uid = ?";
    $statement = $dbc->prepare($query);
    foreach($values as $id => $score) {
        $position++;
        $statement->bind_param("ss", $position, $id);
        $result = $statement->execute();
    }
}


Is there a simpler way to write a row from one table to another?

Transferring Data Using SqlBulkCopy

private static void PerformBulkCopy()
{
    string connectionString =
            @"Server=localhost;Database=Northwind;Trusted_Connection=true";
    // get the source data
    using (SqlConnection sourceConnection =
            new SqlConnection(connectionString))
    {
        SqlCommand myCommand =
            new SqlCommand("SELECT * FROM Products_Archive", sourceConnection);
        sourceConnection.Open();
        SqlDataReader reader = myCommand.ExecuteReader();

        // open the destination data
        using (SqlConnection destinationConnection =
                    new SqlConnection(connectionString))
        {
            // open the connection
            destinationConnection.Open();

            using (SqlBulkCopy bulkCopy =
            new SqlBulkCopy(destinationConnection.ConnectionString))
            {
                bulkCopy.BatchSize = 500;
                bulkCopy.NotifyAfter = 1000;
                bulkCopy.SqlRowsCopied +=
                    new SqlRowsCopiedEventHandler(bulkCopy_SqlRowsCopied);
                bulkCopy.DestinationTableName = "Products_Latest";
                bulkCopy.WriteToServer(reader);
            }
        }
        reader.Close();
    }
}

Solution #2: stored procedure


Concerning whatWentWrong, the main problem is that the function isn't total. This means that for Unknown it will fail badly and unconditionally.

If you declare the functions from map and filter as named functions in a where (or let block), you will be able to check for Unknown as well in pattern matching. Also, you can combine several constructors in a pattern.

There are two options how to fix map: Either return some String for Unknown, or remove such entries. I'll show an example for the latter option using mapMaybe:

whatWentWrong :: [LogMessage] -> [String]
whatWentWrong = mapMaybe getMsg
                . filter filterExp
                . inOrder . build
  where
    filterExp (LogMessage (Error sev) _ _) = sev >= 50
    filterExp _                            = False
    getMsg (LogMessage _ _ s) = Just s
    getMsg _                  = Nothing

Also note that you can declare this function as a composition of functions, in so-called point-free style.


With this random data and a few tweeks I got the time reduced about 30 times. The inner loop can be taken outside which is the biggest difference.

clear all

n=800;
data = randn(2,n,30);
times=linspace(-1900,8600,n);

tic;

samplingrate = 200;
scalefac = 1000/samplingrate;

brainchannel = 12;  % channel # for brain data
heartchannel = 62;  % channel # for heart data

brainchannel = 1;
heartchannel = 2; %adjusted for test data

brainbin = 10;      % bin length for brain data (symmetric, in msec)
heartbin = 250;     % bin length for heart data (= 500 msec window)

heart = 5500;       % max point (from zero, in msec) for heart data
brain = 2500;       % max point (from zero, in msec) for brain data
first = -500;       % first point (from zero, in msec)

xvec=find(times>first,1):find(times>brain,1);
yvec=find(times>first,1):find(times>heart,1);

CECT=zeros(length(xvec),length(yvec));  %initialize

braindata=squeeze(data(brainchannel,(xvec(1)-heartbin/scalefac):(xvec(end)+brainbin/scalefac),:));
bn=length((xvec(1)-brainbin/scalefac):(xvec(1)+brainbin/scalefac));

heartdata=squeeze(data(heartchannel,(yvec(1)-heartbin/scalefac):(yvec(end)+heartbin/scalefac),:));
hn=length((yvec(1)-heartbin/scalefac):(yvec(1)+heartbin/scalefac));
hps=zeros(length(yvec),size(data,3));

p=1;
for y = yvec
    hps(p,:) = mean(heartdata(p:p-1+hn,:),1);
    p = p+1;    % counter for looping over heart data
end

yy = 1;             % counter for looping over brain data
for x = xvec
    eeg = mean(braindata(yy:yy-1+bn,:),1);
    CECT(yy,:) = corr(squeeze(eeg).',hps.');
    %%CECT(yy,:) = eeg * hps.'; %for testing
    yy = yy+1;
end

toc


Find all files that match a filename pattern in a folder tree

As you tagged this Python 3.x, I'd suggest using pathlib.Path.rglob() and collections.defaultdict.  Also, check out f-strings.

import collections
import pathlib

mp4s = collections.defaultdict(list)

root = pathlib.Path(r'/mnt/mp4library/mp4library')

file_count = 0

for filepath in root.rglob('*.mp4'):
    #filepath is relative to root. Uncomment the next line for absolute paths
    #filepath = filepath.resolve()

    mp4s[filepath.parent].append(filepath.name)

    file_count += 1

for record_number, (folder, filenames) in enumerate(sorted(mp4s.items())):

    print(f"-----record {record_number}---{folder} ... files={len(filenames)}")

    for c,filename in enumerate(filenames):
        print(f"mp4 File {c}---filename")

print('Count of files: {filecount}')


Show furnitures in a different way considering django principle

Do take care to run flake8 over the source, and follow its advice.

Array slicing [:max_furnitures] is idiomatic and nice. But if you have a thousand or a million items, you will prefer to use SQL limit, so you don't retrieve a ton of items from the DB only to discard them. You will get a different execution plan from the backend DB if you expose limit 10 to its query optimizer.

I see four different max_furnitures parameters. Now maybe this is perfectly nice and we prefer to leave it as is. But also consider introducing it as an attribute used by constructor.

Looks good.

Ship it.


I usually focus on the design and this review won't be different. You seem to have created some custom universal allocator, that will place all the (different) objects in continuous space (a page) or create new page if needed. The whole space can be released all at once, but no individual objects. So...

void reset() {
    //delete objects
    for(T* obj : data) {
        obj->~T(); // <<< will not call the appropriate destructor if not virtual

This can be very problematic, unless T has virtual destructor, you should place some static_assert:

template<class T>
class  PagedVector {
    static_assert(std::has_virtual_destructor<T>::value,
        "Objects without virtual destructor cannot be used");

Similar problem is in create allowing any class, should allow derived only:

template<class U>
U* create() {
    static_assert(std::is_same<U,T>::value || std::is_base_of<T,U>::value,
        "Objects not derived from T are not allowed");

Minor note about = delete:

//non-copiable:
PagedVector(PagedVector&);
PagedVector& operator=(PagedVector&);

The above should be written with const and = delete to avoid using it inside the class:

//non-copiable:
PagedVector(const PagedVector&) = delete;
PagedVector& operator=(const PagedVector&) = delete;


Python script to create Android/iOS strings from a .csv

The Python style for naming is snake_case for functions and variables, and PascalCase for classes. If you have constant variables (values don't change), they should be in UPPER_SNAKE_CASE.

You also shouldn't be importing multiple modules on one line, like you've done here:

import sys, os, getopt, csv, xml.etree.ElementTree as ET

These imports should be separated onto separate lines, as per PEP8, Python's official style guide.

These comments at the very top of your file:

# Script takes a csv and creates strings for Android (.xml) and iOS (.Strings).
# csv in the format [key, language1, langauge2 ......]
# usage - Python converter.py [FILEPATH]

Should be converted into a docstring, like this:

"""
Script takes a csv and creates strings for Android (.xml) and iOS (.Strings).
csv in the format [key, language1, langauge2 ......]
usage - Python converter.py [FILEPATH]
"""

This is not how you should be opening files.

f = open('Strings.csv')

Rather, you should use a with ... as ... context manager. By using a context manager, you can ensure that the file is properly closed. Here's how you'd do that:

with open("Strings.csv") as f:
    ...

Finally, the below line does nothing.

++rowIndex

It should be changed to row_index += 1, if I understand your intent correctly.


Expandable text boxes for legends of fieldsets

Don't use ids at all. (You almost never should be using them. Ids get to be really problematic once you have composite views and/or multiple people on a project)

Place a few appropriate classes in your html. And use the jquery composite and relative references to do it all at once.

$('.expander').click(function() {
  $(this).closest('fieldset').find('.expandable').toggle('show');
  var l = $(this).find('label');
  l.text(l.text() === '+' ? '-' : '+');
});

where your clicker span gets a class of expander and your rolesList gets the class of expandable. You could just use rolesList directly, but I find  expandable to be somewhat more descriptive.


is it good practice to use relative path in xpath more than once

is it bad practice to use relative path(//) twice in a single xpath?

It would depend on the HTML source of the code - how many elements are there in the path between the nodes, how unique are the elements and their attributes, in general.

In this case though, it is perfectly okay - it is even better than having:

//div[@id='a1']/div/div/span[@id='s1']

because here we check more nodes on the way to span and we start to depend on the markup even more than before - this means our locator is more fragile, less resistant to a design/layout change.

In general, you should avoid using XPath locators if possible - they are the slowest and the least readable. Selenium offers much more options for locating elements:

by CSS selector:

driver.findElement(By.cssSelector("#a1 #s1"));

by ID:

WebElement parent = driver.findElement(By.id("a1"));
WebElement child = parent.findElement(By.id("s1"));

Note that we are not checking tag names here at all - it is a good idea to not use "container"-type tags like div and span inside locators.

IDs are the fastest available locators - locating an element by id internally comes down to executing getElementById() which is optimized by the modern browsers. IDs are also unique by definition (even though nothing prevents you to create two or more elements with the same ID).


Illumination as a way of instantiating new objects

I suppose we are talking about DI.

Based on your example, I can not see the advantages of the Illuminator class. If MegaBigClass depends on AbcComposite and XyzComposite, the right way would be to pass that objects to the constructor. In your case, you have to pass the dependencies of AbcComposite and XyzComposite to MegaBigClass to be able to create the composite objects within that class. However, MegaBigClass should not be responsible for creating that objects.

If MegaBigClass must be able to create the composit objects during runtime, Illuminator serves as something like a "generic factory" (Btw: In that case, I would call it factory so that other developers know what it is). For that case, the Illuminator provides a way to create objects without using new where the concrete creation logic can be changed for testing.

The logic of the Illuminator is (correct me if I am wrong): Search the first constructor from an unordered list that's signature matches to any sub set of the passed arguments.

Well, lets assume we will use the Illuminator that way:

I am not able to define which constructor should be used. If the class to create has a parameterless constructor that is returned first in .GetConstructors(), the class will be created always by the parameterless constructor.

MSDN - GetConstructors()

  The M:System.Type.GetConstructors method does not return constructors in a particular order, such as declaration order. Your code must not depend on the order in which constructors are returned, because that order varies.

because that order varies.! Therfore, it is possible that running the code twice, the class creates objects on different ways.
Even if the order of the returned constructors will not change (or will be ordered first), what is if the class to be created becomes a new constructor somedays... That means that all the places where the Illuminator is used, objects may be created using another constructor! That may result in funny bugs ;)

Conclusion

I would really suggest NOT to use that class! There are excellent frameworks that adress the problems you are tring to solve (e.g. NInject factory extensions for creating factories, Moq for mocking objecs to enable testability ...).


HttpClient Wrapper supports ignoring invalid/self-signed certs

bool ignoreCertificateErrors = ConfigurationManager.AppSettings["IgnoreCertificateErrors"].ToBool();
string environmentName = ConfigurationManager.AppSettings["EnvironmentName"];

These two lines I think shouldn't be there because with them, the wrapper is tigthly coupled to the app.config.

I see three possibilities how you can decouple the wrapper:

make both values constructor parameters if they shouldn't change
make them properties if they can
use the UnityCommon service locator that you use in the SendAsync method and let it resolve some ConfigProvider from which you can get both settings.

environmentName.ToUpper() != "PRODUCTION"

Usually in situations like this it's safer to use a  case insensitive comparison

environmentName.Equals("PRODUCTION", StringComparison.OrdinalIgnoreCase)


While this is recursive, it entirely misses the point.  As the while loop will only ever execute once (because the function it calls only returns when i < j it could just as well have been an if, and thus all you've got is tail-recursion.

What you have is equivalent to the following, but impossible to call twice and maybe less efficient:

void reverse(char s[])
{
    int i = 0, j = strlen(s)-1;
    int c;
    while (i < j) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
}

That's obviously not recursive.  The way you'd do it recursively is always swap the outer two characters of the string and then pass pointers to the beginning and end of a substring along.

Apart from that, you're initialising j but not i, which makes little sense: both will be 0 initially anyway, so at least be consistent.  You're also not using MAXLINE, so you might as well get rid of it (if C allows it).  You're also not checking for a NULL being passed in.


Three observations:

There are two many assert statements in a single test function. Ideally each function should only test one thing. That way when the test fails you know exactly what is wrong.
Instead of initializing test data in the test function, you can write fixtures. Each fixture can be used in multiple test functions.
You don't need to assert 'KeyError' in str(excinfo.type) since you already has with pytest.raises(KeyError).


dplyr -- tidyverse, pipes, correlation, same variable across time "a" "b"

Here are two possible rewrites. For the first one, notice how Hmisc::rcorr already computes correlations ($r) and p-values ($P) matrices so you can base all your work from it, provided you extract the rights rows (a_vars) and columns (b_vars) and only keep the diagonal values:

correlations <- rcorr(as.matrix(all_items), type = "spearman")
a_vars <- ends_with("a", vars = names(all_items))
b_vars <- ends_with("b", vars = names(all_items))
all_correlation <- data.frame(
  item    = seq_along(a_vars),
  Result  = diag(correlations$r[a_vars, b_vars]),
  P_Valor = diag(correlations$P[a_vars, b_vars])
)

What I don't like too much about this approach is that it only uses 3 of the 36 correlations that were computed by rcorr. In this second approach, I start by splitting the data into two tables (one for a and one for b) so as to compute only 3 correlations via Map. I also switched from rcorr to the base cor.test which has (IMO) a more intuitive behavior: when given two vectors as input, it computes one correlation, not four.

a <- all_items %>% select(ends_with("a"))
b <- all_items %>% select(ends_with("b"))
cor_test <- Map(cor.test, a, b)
all_correlation <- data.frame(
  item    = seq_along(a),
  Result  = sapply(cor_test, `[[`, "estimate"),
  P_Valor = sapply(cor_test, `[[`, "p.value")
)


3Sum 2 Different implementations complexity

Your version

You have a bug in your three-loop implementation. This sort of bug creeps in when you use copy/paste to code without being diligent about checking what's useful. In your 'k' loop you have:

for (int k = i + 2; k < array.Count ; k++)

But that should loop from j + 1 and not i + 1. You should have:

for (int k = j + 1; k < array.Count ; k++)

This will significantly improve your performance for large lists.

The performance of this option will scale in terms of \$O(n^3)\$ which means each time you double the input data size, you will take 8 times longer to compute a result.

Wiki Version

The second method uses the wiki algorithm, which is also the base of the algorithm I would recommend....

The Sort will take \$O(n \log{n})\$ time. For largeish lists the log(n) can be effectively ignored....

What's interesting here, is that you loop to the array size still in the i loop. You can actually limit the outer loop to valeus less than or equal to 0.

At least one of the values has to be 0 or less in order for there to be a zero-sum.

Similarly, once you have a second number, chosen from values after i, you should then be able to do a binary-search for the third number.


Transcribe .docx files via python-docx to modify font and font size. Need to reconstruct paragraphs in target files

This modification resolves this issue.
Thanks to Scanny at Stack Overflow

for src_paragraph in src_doc.paragraphs:
            tgt_paragraph = tgt_doc.add_paragraph()
            for src_run in src_paragraph.runs:
                print('Run: ', src_run.text)
                tgt_run = tgt_paragraph.add_run(src_run.text)
                if src_run.bold:
                    tgt_run.bold = True
                if src_run.italic:
                    tgt_run.italic = True
                if src_run.underline:
                    tgt_run.underline = True


Updates href values for a limited collection of links on a page

There's no need to wrap this all in an IIFE. You aren't introducing any variables in the top scope, so no need to prevent them from leaking. Though it will become more useful when you follow my advice of introducing some helper functions. But even then there's no need to safe-guard the window global (as you aren't worried about the location and document globals).
Why are you running the loop backwards? Better use a looping construct that's meant for dealing with lists, like the for-of loop.
The environment variable contains a result of a regex match and is used like so:

// If production, remove any environment segments ...
if (environment === null) {

If you would translate the regex match into an actual environment name, the code would become much more self-explanatory:

if (environment === "production") {

For changing the link href value, I'd suggest extracting helper functions like stripEnvironment() and replaceEnvironment(), which could be used as:

link.setAttribute('href', stripEnvironment(href));
link.setAttribute('href', replaceEnvironment(href, environment));

If you want to have the domains and environments lists to be easily extensible, regex is probably not the best choice. Better to define them as arrays of strings which you can later transform into regexes using the RegExp constructor.
Your regexes look a bit too loose. The /sys\./ pattern would also match linksys.. You should at least anchor them at word boundary using \b.


Welcome to Code Review, the complexity of your code can be reduced using a Map object having as keys sorted lexicographically strings and as values arrays of their anagrams. For example you will have the following couples key - value starting from your input:
key = "aet"  value = ["eat","tea","ate"]
key = "ant"  value = ["tan","nat"]
key = "abt"  value = ["bat"]

So you can define a function anagrams like this:
function anagrams(input) {
    const map = new Map();

    for (let i = 0; i < input.length; ++i) {
        const key = [...input[i]].sort().join('');
        const value = map.has(key) ? map.get(key) : [];
        value.push(input[i]);
        map.set(key, value);
    }

    return [...map.values()];
}

/*below it will print the expected result*/
console.log(anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));

I just used the Spread operator to expand the string input[i] to array of characters and after I sort it to obtain the corrisponding key in the map. After I add it to the array of strings associated to the key and finally I return the map values as an array.
Note: I'm a javascript beginner so every hint or criticism about my answer is highly appreciated.


Display a dropdown based on another dropdown change

First to address the controller method your calling in the ajax function.

Your currently returning a serialized collection of SelectListItem which means your unnecessarily passing all the values of the other properties of SelectListItem (Selected, Group and Disabled) back to the view when you don't need or use them. You should only pass back the values you need, by either using a view model, or by creating anonymous objects. Note also that you do not need .ToList() in your query. Your code can simply be

public JsonResult ListOfCoverLetterByCompanyId(int companyId)
{
    var coverletters = _context.CoverLetters.Where(x => x.CompanyId == companyId).Select(x => new
    {
        Value = x.CoverLetterId,
        Text = x.CoverLetterName
    });
    return Json(coverletters, JsonRequestBehavior.AllowGet);
}

Your method is also a [HttpGet] meaning that users can navigate to it via the address bar, which is probably not what you want. You should mark the method [HttpPost] (in which case you do not need the JsonRequestBehavior.AllowGet argument). Alternatively you can check if the request is an ajax request. A simple way to do that is to create a FilterAttribute. A typical example is shown in MVC Set accessibility level on a method called from ajax.

The main issue with your code however, is that your not binding the 2nd dropdownlist to your model. Not only does your name attribute of the <select> not match the property you want to bind it to (CoverLetterId), but if the user submits the form and you need to return the view because ModelState is invalid, then the data the user entered in the 2nd dropdownlist is lost (in fact the 2nd dropdownlist will be empty). You also will not be able to use you code for editing an existing Referral for the same reason. To address this, first modify your model to

public class ReferralViewModel
{
    public int? Id { get; set; }
    [Display(Name = "Company")]
    [Required(ErrorMessage = "Please select a Company")]
    public int? CompanyId { get; set; }
    [Display(Name = "Cover Letter")]
    [Required(ErrorMessage = "Please select a Cover Letter")]
    public int? CoverLetterId { get; set; }

    public IEnumerable<SelectListItem> Companies { get; set; }
    public IEnumerable<SelectListItem> CoverLetters { get; set; }
}

A few things to note.

Name your PK property just Id. This means that if your using
the same view model for editing an existing Referral, that you do
not need to include a hidden input in the view for the property
(assuming your using the default route, and that your method is
public ActionResult Edit(int id)). The framework will automatically
add a route value in the forms action attribute and it will
automatically be bound in the POST method.
Assuming that both ResumeId and CoverLetterId are required in
the database, you should make your properties nullable and add a
[Required] attribute to protect against under-posting attacks.
Refer What does it mean for a property to be [Required] and
nullable?
for more detail.

Your model is also referring to ResumeId, but the view code is creating the first dropdownlist for CompanyId so I assume that was just a typo.

Now your view code for the dropdownlists will then be (<div> elements omitted for clarity)

@Html.LabelFor(m => model.CompanyId, new { @class = "control-label col-md-2" })
@Html.DropDownListFor(m => m.CompanyId, Model.Companies, "Please select", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.CompanyId, "", new { @class = "text-danger" })

@Html.LabelFor(m => model.CoverLetterId, new { @class = "control-label col-md-2" })
@Html.DropDownListFor(m => m.CoverLetterId, Model.CoverLetters, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.CompanyId, "", new { @class = "text-danger" })

Note that I have removed the additional class name, and the onchange attribute which I will discuss later. Note also the 3rd parameter in the 1st DropDownListFor() method, which adds a <option value="">Please select</option> which will be selected if a value for CompanyId has not been set, and forces the user to make a selection and trigger the ajax call. It also means that when the user submits the form, a client side validation error will be shown if they have not selected a Company.

Then you need to modify your controller code so that if the value of CompanyId is null, then you set the value of CoverLetters to be an empty SelectList (i.e when the page is first rendered in your Create() method, but if its not null, then populate it based on the value of CompanyId (i.e. in a POST method if you need to return the view, or in an Edit() method. You controller code would typically look like

public ActionResult Create()
{
    ReferralViewModel model = new ReferralViewModel();
    ConfigureViewModel(model);
    return View(model);
}
[HttpPost]
public ActionResult Create(ReferralViewModel model)
{
    if (!ModelState.IsValid)
    {
        ConfigureViewModel(model);
        return View(model);
    }
    .... // Initialize a new instance of the data model, set its properties based on the view model, save and redirect
}
private void ConfigureViewModel(ReferralViewModel model)
{
    // Populate companies always
    model.Companies = _context.Companies.Select(x => new SelectListItem
    {
        Text = x.CompanyName,
        Value = x.CompanyId.ToString()
    });
    // Populate cover letters only if a company has been selected
    // i.e. if your editing an existing Referral, or if you return the view in the POST method
    if (model.CompanyId.HasValue)
    {
        model.CoverLetters = _context.CoverLetters.Where(x => x.CompanyId == model.CompanyId).Select(x => new SelectListItem
        {
            Value = x.CoverLetterId.ToString(),
            Text = x.CoverLetterName
        });
    }
    else
    {
        model.CoverLetters  = new SelectList(Enumerable.Empty<SelectListItem>());
    }
}

Finally, your scripts.

It is better practice to use Unobtrusive Javascript rather than polluting your htlm markup with behavior, so rather that using an onchange attribute, use $('#CompanyId').change(function() { ...

You should also cache elements that you repeatedly refer to by assigning them to a javascript variable so that your functions are not searching through the DOM again. You script would look like

var coverLetterSelect = $('#CoverLetterId'); // cache it
$('#CompanyId').change(function() {
    var companyId = $(this).val(); // use $(this)
    coverLetterSelect.empty(); // clear existing options
    if (!companyId) {
        return; // there is no point making an ajax call so just exit
    }
    $.ajax({
        type: 'POST', // or 'GET' depending on how you have modified the method above
        url: "@Url.Action("ListOfCoverLetterByCompanyId", "Referral")', // use @Url.Action() to generate urls
        data: {companyId : companyId },
        success: function (response) {
            coverLetterSelect.append($('<option></option>').val('').text('Please select')); // add a default null option
            $.each(response, function (i, item) {
                coverLetterSelect.append($('<option></option>').val(item.Value).text(item.Text));
            });
        },
        ....
    });
})

Note that you need to remove the contentType option.


Dynamic Multi-threading lock with while loop

Just one question : when do you release the key ?
Suppose twice the same key is called almost simultaneously, so that one of the two threads involved will go through the

  Thread.Sleep(50) ;

line ..
The first thread enters the lock, the key is added to the dictionary, fine.
At almost the same time the other thread enters the lock, find the key already there and go sleeping.
When the first thread exit, if you don't release the key, the other thread will wait a long long time ..
May be something like

_lockByKeys.Remove(key)

is enough to solve this one.

After this, reading again this code, I found a dictionary, a lock and a monitor. I'm quite sure that a ConcurrentDictionary could make the same job, with a cleaner code if not faster.

Lastly, 100 threads with some of them blocked could become a production nightmare if too much keys have the same value.

Hope this help !


I'll start with something unrelated to recursion: A first cleanup step might be to reduce the repetition in segment:

segment els @ (head:tail) =
  let constr = case head of
                 Emph ch        -> Just (Emph, ch)
                 Strong ch      -> Just (Strong, ch)
                 Strikeout ch   -> Just (Strikeout, ch)
                 Superscript ch -> Just (Superscript, ch)
                 Subscript ch   -> Just (Subscript, ch)
                 SmallCaps ch   -> Just (SmallCaps, ch)
                 Quoted qt ch   -> Just (Quoted qt, ch)
                 Cite cs ch     -> Just (Cite cs, ch)
                 Span attr ch   -> Just (Span attr, ch)
                 _              -> Nothing
      sentence = Span ("", ["sentence"], [])
  in case constr of
    Just (inlnConstr, ch) -> map inlnConstr (segment ch) ++ segment tail
    _               ->
      maybe [sentence els] (\i -> (sentence $ take i els) : segment (drop i els))
        $ (1 +) <$> List.findIndex split els

Note that we not only cut away the repeating (segment ch) and ++ segment tail, but also the toList, which is just an id here (as the result of segment already is a List.

Next would be the splitting, which could be done using break instead of findIndex, drop, and take:

      case break split els of
        (_, [])    -> [sentence els]
        (xs, y:ys) -> sentence (xs ++ [y]) : segment ys

The last part of your post might better be asked on stackoverflow, as there is no working code for this yet.


Have you looked at C++20 osyncstream?  It seems to have a better interface.

Multithreading

std::lock_guard<std::mutex>(PrintLn<Stream>::m);

This line is useless, because temporary objects are destroyed at the end of the full-expression.  (Does this even have a temporary in C++17?)  You need a named variable instead.  Also make use of class template argument deduction:

std::lock_guard lock{m};

Also,

Streams

Your approach is unnecessarily restricted because only three hardcoded streams std::cout, std::cerr, and std::clog are supported.  And I think {} is OK and these don't really help a lot:

#define CoutLn CoutLn{}
#define CerrLn CerrLn{}
#define ClogLn ClogLn{}

Make the function object have regular semantics instead.  You may use a hash map internally to store the mutexes, as syncbuf does.

Also SFINAE on operator<<.

Here's the same thing implemented with osyncstream:

template <
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class PrintLn : public std::basic_osyncstream<CharT, Traits, Allocator> {
    using Base = std::basic_osyncstream<CharT, Traits, Allocator>;
public:
    using Base::Base;

    PrintLn(PrintLn&&) = default;
    PrintLn& operator=(PrintLn&&) = default;
    ~PrintLn()
    {
        if (this->get_wrapped()) {
            *static_cast<Base*>(this) << '\n';
        }
    }
};

inline auto cout_ln()
{
    return PrintLn{std::cout};
}
inline auto cerr_ln()
{
    return PrintLn{std::cerr};
}
inline auto clog_ln()
{
    return PrintLn{std::clog};
}

But anyway, why would you wanna do this when you can simply print a \n?


Python - Faster random business date generation

one of the really easy ways to probably make this faster is by foregoing the idea of "I generate n records and then do things with them".

Instead think something like "I generate a record and do things with it. n times".

Python has the really handy concept of iterators. Consider the following:

def rng_dates():
   while true:
       yield pd.to_datetime(rnd.choice(pd.bdate_range(start_date, end_date)))

to make this a little less infinity-ish, you could pass a number of records to it:

def rng_dates(n):
    # hat tip to Peilonrayz
    for _ in range(n):
        yield pd.to_datetime(rnd.choice(pd.bdate_range(start_date, end_date)))

this should allow some optimizations wrt. memory management, cache-misses and list-appending, which should translate into a pretty hefty speedup in larger sample-sizes


Project Euler #5 - Lowest Multiple of 1 through 20

A number of answers have pointed out some algorithmic changes, and some logic steps you can take, to calculate the result, but there's a simpler way to do it, which is not necessarily the fastest way, but it is still blazingly fast, and still very simple.

The algorithm you have by testing every number is obviously overkill, but, what about going through the basics of the process, and implementing it in code. What is the question actually asking? It's asking for the lowest common multiple of all the numbers 1 through 20.

Mathematically, 1 is a multiple of 1. so, we start there...

Then, find the multiple of 1 that is also a multiple of 2... to do that, we add the 1 to itself repeatedly, until we get a multiple of 2. This is easy, it is just once....

Now we have 2, which is a multiple of both 1, and 2. We want to find the multiple of both 1 and 2 (which is 2), that is also a multiple of 3, so, we check whether 2 is a multiple (it's not), so we add 2 to itself, which is 4. Is 4 a multiple? No, so we add 2 again, to get 6. Is 6 a multiple of 3? Yes. So, 6 is the lowest multiple of 1, 2, and 3. Now, we just repeat this process to 20.

Let's introduce some names here, lcm is the lowest common multiple, and sum is some value that is a multiple of lcm. If sum is a multiple of lcm, then it is also a multiple of everything that lcm is a multiple of.

The rest is actually easier to understand with code....., and it can be generalized very easily with a method like:

public static int GetLCM(int from, int to) {
    // lcm is the Lowest Common Multiple, which starts as just 'from'
    var lcm = from;
    for (int i = from; i <= to; i++) {
        var sum = lcm;
        while (sum % i != 0) {
            sum += lcm;
        }
        // sum is now the first multiple of lcm that is also a multiple of i
        lcm = sum;
    }
    return lcm;
}

Now, I have taken that concept and implemented it on Ideone, and you can see that it arrives at the right solution, using a simple algorithm, in almost no time.


Break an array into n equal or almost-equal sized sublists

Using roundrobin on a rotored array works

sub fair-lists ( @array, Int $num-lists ) {

  # "invert" the following "matrix"
  roundrobin

    # make it at least $num-lists long
    |@array[{ 0 ..^ ( $_ max $num-lists ) }]\

    # split it into chunks that are as big as the number of $num-lists
    .rotor: $num-lists, :partial

}

say fair-lists( 1..1, 3 ).perl;
# ((1,), (Any,), (Any,)).Seq

say fair-lists( 1..4, 3 ).perl;
# ((1, 4), (2,), (3,)).Seq

test it


I reworked the code a bit. Check out the comments for explanation.

$(document).ready(function() {
  //Don't copy and paste the same string.
  //It is also helpful when the CSS or text changes. There is just one part
  //of the code to look at.
  var followBtn = $('.btn-follow'),
      followCls = 'following',
      dangerCls = 'btn-danger',
      primaryCls = 'btn-primary',
      unfollowText = 'UnFollow',
      followText = 'Follow'

  //No need to keep making a jQuery "query" to get a the button every time.
  //I am not sure about the internals of jQuery, but I assume it is reading the
  //DOM on every $('.btn-follow') call.

  //Don't pass argument to method if it is not being used.
  followBtn.on('mouseover', function(){
    //same thing inside the handler no need for $(this).
    if (followBtn.hasClass(followCls)){
      followBtn.removeClass(primaryCls).addClass(dangerCls).text(unfollowText);
    }
  });

  followBtn.on('mouseleave',function(){
    if (followBtn.hasClass(followCls)){
      //Keep the same order as before, just be consistent.
      followBtn.removeClass(dangerCls).addClass(primaryCls).text(followText);
    }
  });
  //The rest
});

If you post the CSS I can help you with that. I suspect that a few of the removeClass calls can be removed in favor of more specific selectors.


Overall, this code was very simple and easy to follow. I just have a few nit-picks to point out.

The function syntax

def func_name(param_name: type) -> return_type:

is new in Python 3. However, it is not a very common thing to be used in Python, and I don't think it looks very pythonic.

Your code will work just as well without making functions like this, so I recommend that you stick to using the usual syntax:

def func_name(param_name):

This clunky statement:

if msg[0][0] in ['.', '-', '/']:
    return True
else:
    return False

can be reduced to a more pythonic and clean version:

return msg[0][0] in ['.', '-', '/']

Comments like this:

# type: list

are really unnecessary and just add noise to your code. Just from reading your code, someone reviewing it should be able to determine what type each variable is.

You need to do some more error catching.

For example, say you are translating a string from morse code to english. What if you encounter a character that is not a valid morse character? Your program will raise an error here:

for char in msg:
    c = eng[char] # <======
    out += "{} ".format(c)

Therefore, this is what you should do:

Encase that line in a try/except.
In the except, throw a custom InvalidMorseLetter exception.
Exit

Here is what I mean:

try:
    c = eng[char] # type: str
except KeyError:
    raise(InvalidMorseLetter)

where InvalidMorseLetter is:

class InvalidMorseLetter(Exception):
    pass

Read here and here.

In the code, I wrote to catch a KeyError because that is the error that would be raised if an invalid dictionary key is used.

You should use a custom exception because it specifically describes what went wrong with your specific code, rather than just a general KeyError.

You should do something very similar to this for when you are translating english to morse.

Thanks to Zenohm for this.

In your translation functions, you should not be constantly modifying a single string each iteration:

c = morse[char] # type: str
out += c # <======================

The reason: python strings are immutable. Therefore, by constantly changing the string, you are actually creating a new string each and every time. This is very inefficient.

As Zenohm posted in the comments, you should be doing something along the lines of this:

return ''.join("{} ".format(eng[char]) for char in msg))

  While the modifying of a single string does not a bad habit make and
  isn't really a problem here, I think it would be good if he started
  avoiding the modifying of an immutable object right off the bat.
  return ''.join("{} ".format(eng[char]) for char in msg) Could be used
  in place of his original string modification and would help to
  encourage better practice in future.


Firstly, python includes a json module. Use that rather then writing your own.

However, just to give some comments on your style:

def to_json_with_key(nodes, key, fields, insertIndex=False):

python recommend words_with_underscores for parameter names

    i=0

Rather then manually keeping a count use enumerate

    s="{"
    for node in nodes:
        s += '"%s":{' % getattr(node,key)

You don't check the value to make sure it is json-safe. Building strings by concatenation is not usually a good idea. Either build a list and join it or use StringIO

        attrs=[]
        for field in fields:
            attr = getattr(node,field)
            if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long):

You can pass several types in a tuple to isinstance to check several types at once.

                attrs.insert(0, '"%s":"%s"' % (field, attr.replace('"','\"') ))

This won't be sufficient. For example, you could have a \ at the end of a string. You also need to handle newlines, tabs, and other escaped characters.

            else:
                attrs.insert(0, '"%s":%s' % (field, attr ))

Why insert rather then append?

        if (insertIndex):

No need for parens

            s+='index:%d,' % i
            i=i+1

        s+=','.join(attrs) + "},"
    s = s.rstrip(",") + "}"

It would be cleaner to join a list of items rather then stripping off stray commas.

    return s


Reading a line from a text file and splitting its contents

I don't think that using : is a bad practice but you have to escape it somehow if it occurs inside your data. Anyway, I'd consider using XML or JSON here.

Some notes about the code:

You should close the stream (in a finally block). See Guideline 1-2: Release resources in all cases in Secure Coding Guidelines for the Java Programming Language
The .ser file extension is often used for serialized Java objects. I'd use something else to avoid the possible confusion.
It's a good practice to set the character set when you read a text file. The used FileReader always uses the default charset which could vary from system to system. Consider using InputStreamReader and FileInputStream as the documentation of FileReader says. Here is an example:

FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
    fileInputStream = new FileInputStream("people.dat");
    inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
    bufferedReader = new BufferedReader(inputStreamReader);

    // use BufferedReader here
} finally {
    IOUtils.closeQuietly(bufferedReader);
    IOUtils.closeQuietly(inputStreamReader);
    IOUtils.closeQuietly(fileInputStream);
}

It uses IOUtils from Apache Commons IO and closes the FileInputStream even if the constructor of InputStreamReader or BufferedReader throws an exception.


Delete Entry from SQL-Table and confirm the deletion to a CommandSender in a spigot plugin

Regarding your questions:

Is an early return better for the first method? Or is it just a question of personal taste?

The alternative you suggest would be:
private void deleteMessage(CommandSender sender, int messageId) {
    int deleted = DatabaseMethods.deleteMessage(messageId);
    if (deleted == 0) {
        sender.sendMessage(MessageManager.couldNotBeFound(messageId));
        return;
    }
    sender.sendMessage(MessageManager.deletedMessage(messageId));
}

I generally don't recommend it. A developer might delete the empty return thinking it's unnecessary causing a bug. The if-else is more readable in my opinion.

Can the SQL-handling be improved? Should maybe the method return a boolean instead of an int?

If the delete operation can return only 0 or 1, then it should be a boolean. However, there are more than two outcomes: the database is down, the database call times out, etc. "Message not found" is just one of the reasons for deleteMessage to return 0. So instead of MessageManager.couldNotBeFound(messageId)), would be more appropriate to say "message cannot be deleted".
To tell the user "message not found", you can let the second method throw the exception and catch it in the first method.
One more thing, from the method signature is not clear why deleteMessage(CommandSender sender, int messageId) needs a CommandSender, a better name can be deleteMessageAndNotify.


Checking whether two lists contain the same elements

The only way to reduce the number of operations is to sort one of the arrays. But 4 elements is hardly worth it.

Perhaps when adding the numbers to the array then add them in a sorted order, otherwise quicksort is good for arrays under 10 elements in size.

Performing a binary search on a sorted array would give you O(log n) time for each search - with O(n log n) time to compare two full arrays of the same size. Quicksort is O(n log n), with binary search that's roughly O(2[n log n]).

Adding items in a sorted order, then searching, would be a similar complexity: O(n log n) for adding 'n' items, and O(n log n) for searching through n items. I prefer this solution because it's one simple algorithm, and it's cleaner.


Printing an Alternating Pattern to the Console

I like that you have separated the CreateGrid method out in to a reusable method. This is good.

Your logic inside the method is even quite good, despite your concerns about the duplication. There is a trick, though.... use a boolean:

    for (var row = 0; row < gridSize; row++)
    {
        bool toggle = row % 2 == 0;
        for (var col = 0; col < gridSize; col++)
        {
            grid[row, col] = toggle ? dark : light;
            toggle = !toggle;
        }
    }

Your print-grid method would likely benefit from some Linq, but what you have is OK.... rather, it is very readable. Linq (or using a StringBuilder) will improve performance by reducing the calls to Write.


Capitalizing the first letter of every word in a string (with arbitrary spacing)

remove the unused imports

Your code logic is OK but the execution is not good. Try not to overcomplicate it. Take a piece of paper and write the procedure of how a human like YOU would do it, just with a pencil and paper.
read the names individually... make first character capital if it isn't a digit

Now that you have  basic design, become more specific, or in Python terms

read the names individually for word in string.split()
make the first character capital: string.title()
if it isn't a digit : if not string[0].isdigit()

The primary problem which I faced is handling arbitrary spaces

string.split() will return the same thing, let it be 1 space or 1000 spaces. It does not matter
Now you have exactly what you need, it is just a matter of putting it together.
for every word in words, capitalize if the first character isn't a digit else do nothing

    return " ".join(word.title() if not word[0].isdigit() else word for word in words.split())

Furthermore, using capitalize() will avoid the extra check
    return " ".join(word.capitalize() for word in words.split(' '))

EDIT:
You have to use .split(' ') and NOT .split() since .split() removes all the whitespaces.

As you mentioned, title() and capitalize() fail for scenarios where you pass something like
ALLISON heck

Output
Allison Heck

In that case, you need to have extra checks. The best thing to do here is to create another function that specifically capitalizes the first letter
Here is what I thought of
def cap_first(word):
    return word[:1].upper() + word[1:]

the solve function remains the same
def solve(words):
    return ' '.join(cap_first(word) for word in words.split(' ')

Benchmarks
the latter code is surely more readable and compact, but what is its performance compared to the previous solution?
I will measure the execution time in the following manner using the time module
for iterations in (10 ** 5,11 ** 5, 10 ** 6, 11 ** 6):
    print(f"\n{iterations} iteartions\n")

    start = time.time()
    for _ in range(iterations): solvenew(names)
    print(f"Time taken for new function: {time.time() - start:.3f} s")

    start = time.time()
    for _ in range(iterations): solveoriginal(names)
    print(f"Time taken for original function: {time.time() - start:.3f} s")

Here are the results
#                      Time taken
#
#     iterations  |  original    |   new
#   --------------------------------------
#       10 ** 6   |   2.553 s    |  2.106 s
#   --------------------------------------
#       11 ** 6   |   6.203 s    |  5.542 s
#   --------------------------------------
#       10 ** 7   |   32.412 s   |  24.774 s

Feel free to try it yourself


Somewhat esoteric if statement in a paginated feed

You're checking that "page does not contain any posts and page number is not one".

Reversing the condition is often the easiest way to clarify it. The inverse condition would be "page contains at least one post, or page number is one".

I would make it look like this:

if (pagePosts.Any() || pageNumber == 1)
{
    return View(pagePosts);
}
else
{
    return RedirectToAction("Index", new { pageNumber = pagePosts.TotalPageCount });
}

Notice page renamed to pagePosts, also for clarity: it's not a page, it's the posts on the page that was requested. pagePosts is less ambiguous I find.


General notes:

the code would benefit from splitting it into more methods,
go uses camelCaseConvention, not onlylowerletters.

Now, some particulars.

stack = append(stack, room{0, 0})

You can use start variable here.

func (r room) neighbors() []room {

In this function, it'd be more idiomatic to use switch { ... } instead of sequence of ifs. Same for the if-elses in the main().

Also it may be more efficient to have a single global re-used [4]room array and have neighbors/nonvisitedneighbors returns slices on it instead of make-ing a new one each call.


Finding the shortest excerpt that contains all search terms

Pythonicity

Your solution feels very procedural and not really Pythonic.  I believe that this function accomplishes the same task using roughly the same approach:

from itertools import product

def answer(document, search_terms):
    words = document.split(" ")

    search_term_positions = [
        [i for i, word in enumerate(words) if word == term]
        for term in search_terms
    ]

    combos = [sorted(combo) for combo in product(*search_term_positions)]
    if not combos:
        return None    # Could not find all search terms
    best_combo = min(combos, key=lambda combo: combo[-1] - combo[0])

    return " ".join(words[best_combo[0] : best_combo[-1] + 1])

Observations:

d is a variable name that suggests that it's a dict, but is not much more helpful than that.  Instead of d.values(), I've defined search_term_positions, which is a much more descriptive variable name.  You don't really even need a dictionary, since you only care about the values, not the keys.
You can simplify the second for loop by taking full advantage of the built-in min() function.
You wrote sum(differenceList) three times!  sum(differenceList) is just sortedList[-1] - sortedList[0], because

$$(n_1 - n_0) + (n_2 - n_1) + (n_3 - n_2) + \ldots + (n_N - n_{N - 1})$$

is a telescoping series where all of the terms cancel except \$-n_0\$ and \$n_N\$.
sortedElement[len(sortedElement)-1] can be written as sortedElement[-1].
Swallowing all exceptions with except: pass is a no-no.

Bugs

This function only recognizes words that are delimited by spaces.  Any other punctuation could cause words to fail to be recognized.

Your algorithm works based on word count rather than by character positions.  Therefore, you end up finding the excerpt with the fewest intervening words, which is not necessarily what I would consider to be the "shortest snippet".  Example:

>>> answer('many google supercalifragilistic program to google a program', ['google', 'program'])
'google supercalifragilistic program'

I've also written a different solution to solve the same problem.  There, as here, I've made no attempt to choose a speedy algorithm, but rather aimed for clarity.


Partitioning and sorting even and odd numbers within an array

Your code is quite complicated. The C standard library provides all the ingredients you need to sort an array. You just need to define a comparison function. All the rest is done by the qsort function from stdlib.h.

The comparison function should look like:

static int even_first(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;

    int res = (left % 2 != 0) - (right % 2 != 0);
    if (res == 0)
        res = (left > right) - (left < right);
    return res;
}

The expressions of the form cond1 - cond2 may look strange at first, but they are commonly used in C code in comparison functions like this one.

The benefit over a naïve left - right is that no integer overflow can happen. Integer overflow is a common source of undefined behavior.

To make the code more readable, it's also possible to extract the basic integer comparison into a separate function:

static int compare(int a, int b) {
    return a < b ? -1 : a > b ? +1 : 0;
    // alternatively: return (a > b) - (a < b);
    // alternatively: return a < b ? -1 : a > b;
}

Then, the comparison function becomes:

static int even_first(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;

    int res = compare(left % 2 != 0, right % 2 != 0);
    if (res == 0)
        res = compare(left, right);
    return res;
}

This form is much less of a brain twister than the above variant.


Interesting problem.

I think your answer is quite a bit longer than it needs to be.  Consider rethinking what the solution entails, essentially.  Also, your code will be quite a bit more readable if you avoid nesting statement -- especially thing like loops nested inside conditionals, such as you have here:

  } else {
        // Distribute (maxLen - size) in $(spacesCount) evenly
        for(let i = 0; i < this.words.length - 1; i++) {
            this.spaces[i] = quotient + ((mod-- > 0)? 1 : 0);
        }
    }

You have the right idea to break the problem down into the subproblems of line breaks and justification, but trying to do so with objects, rather than simple functions, seems to have added complexity for you.

Consider this rewrite, which expresses the line breaking problem using recursion, and also takes advantage of es6 features.  It's about a third the size of the original, even with lots of intermediate variables which exist only for the sake of readability

function fullJustify(words, maxLen) {
  return asLines(words, maxLen).map(x => justify(x, maxLen))
}

function asLines(words, maxLen, curLine=[], charCount = 0, lines = []) {

  if (!words.length)
    return lines.concat([curLine])

  const nextWord        = words[0]
  const remainingWords  = words.slice(1)
  const additionalChars = nextWord.length + (curLine.length ? 1 : 0)
  const nextCharCount   = charCount + additionalChars
  const breakLine       = nextCharCount > maxLen

  if (breakLine)
    return asLines(words, maxLen, [], 0, lines.concat([curLine]))

  return asLines( remainingWords, maxLen, curLine.concat(nextWord),
    nextCharCount, lines )
}

function justify(words, len) {
  if (words.length == 1)
    return words[0] + ' '.repeat(len - words[0].length)

  const numPaddedWords  = words.length - 1
  const totalChars      = words.reduce((m, w) => m + w.length, 0)
  const extraChars      = len - totalChars
  const spaceBetween    = Math.floor(extraChars / numPaddedWords)
  const spacer          = ' '.repeat(spaceBetween)
  const extraSpaces     = extraChars - spaceBetween * numPaddedWords
  const leftPaddedWords = words.slice(1).map(
    (w, i) => spacer + (i < extraSpaces ? ' ' : '') + w
  )
  return [words[0], ...leftPaddedWords].join('')
}

additional improvement

my asLines function above is still too complex for my taste, so i did one more improvement, using a few utility functions from ramda.js:

function asLines(words, len, lines=[]) {

  if (!words.length) return lines

  let charCount    = -1  // bc the first word is not left-padded
  const fitsOnLine = w => (charCount += w.length + 1) < len
  const nextLine   = takeWhile(fitsOnLine, words)
  const remaining  = drop(nextLine.length, words)
  return asLines(remaining, len, lines.concat([nextLine]))
}


Can you use temp tables?  I think that's generally the best idea... using a lot of subqueries can get nasty real quick.  Here's my version:

(I'm not able to test it so use it at your own risk.  Also if you use temp tables, you'll still probably want to define your datatypes in the CREATE TABLE sections)

DROP TABLE IF EXISTS temp_date_unjoin;

CREATE TABLE temp_date_unjoin
SELECT
    user_id,
    MAX(created_at) AS date_unjoin
FROM wants_email_logs
WHERE value = 0
GROUP BY user_id;

DROP TABLE IF EXISTS temp_date_last_order;

CREATE TABLE temp_date_last_order
SELECT
    user_id,
    MAX(created_at) AS date_last_order
FROM orders o
WHERE state IN ('paid', 'processing', 'shipped', 'completed')
GROUP BY user_id;

DROP TABLE IF EXISTS temp_cheque_date;

CREATE TABLE temp_cheque_date
SELECT
    user_id,
    MAX(created_at) AS cheque_date
FROM cheques
GROUP BY user_id;

SELECT
    u.first_name,
    u.last_name,
    u.email,
    u.birthdate,
    u.id,
    u.sex,
    c.name,
    u.facebook_id,
    u.created_at,
    u.last_active,
    u.referrer_id,
    du.date_unjoin,
    lo.date_last_order,
    cd.cheque_date
FROM
    users u
    LEFT JOIN temp_date_unjoin du
        ON du.user_id = u.id
    LEFT JOIN temp_date_last_order lo
        ON lo.user_id = u.id
    LEFT JOIN temp_cheque_date cd
        ON cd.user_id = u.id
    LEFT JOIN countries c
        ON u.country_id = c.id
;


Foreword

I know that this was posted nearly 1.5 years ago and the code appears to have changed dramatically and perhaps you've already learned about what I will mention below, but I feel like this question needs an answer...

Feedback

I like the good use of the Notification interface, as well as the radix passed to parseInt().

Suggestions

The code to check if the site is in the list of active sites, i.e.

if ((tabUrl == sites[site].site_url + '/review')
            && (ACTIVESITES.indexOf(sites[site].name.toLowerCase()) > -1)) {

can be simplified using Array.prototype.includes(), which has been supported since FF 43 (released 12/15/2015) and Chrome 47 (released 12/01/2015):

if ((tabUrl == sites[site].site_url + '/review')
            && (ACTIVESITES.includes(sites[site].name.toLowerCase()))) {

The reload registration could be simplified from:

setTimeout(function(){
    window.location.reload();
}, DELAY);

To the following, which makes a partially applied function using Function.bind():

setTimeout(window.location.reload.bind(), DELAY);

that way there is no excess lambda/anonymous function, and two fewer lines (I get the impression you might like one-liners)!
The selection of dashboard elements could be simplified, using a more selective CSS selector:

var reviewItems = document.getElementsByClassName('dashboard-num');
for (var i = 0; i < reviewItems.length; i++){
    if (reviewItems[i].parentNode.className != 'dashboard-count dashboard-faded'){

Instead, one could utilize the :not() selector and document.querySelectorAll() (or jQuery selector function, though that would return a jQuery collection instead of a NodeList):

var reviewItems = document.querySelectorAll('.dashboard-num:not(.dashboard-count):not(.dashboard-faded)');

One could utilize promises for the asynchronous callbacks...


Instead of using indices from 0 to 9, change the way you store your board to be a 3x3 list.
board = list([[0] * 3] * 3)
"""
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
"""

This will allow you to come back to it and add a GUI.
It also becomes easier for anyone reading the code to understand what's happening visually.
Next is your printout of the board. Join will be your friend here.
for row in board:
  printout = "\t|\t".join(str(element) for element in row)
  print(printout) # this can be reduced to a single line if you want.

ranges
range() accepts 3 variables. START, STOP and INCREMENT AMOUNT
for i in range(0, 9, 3):

You can also reverse with negative values
for i in range(9, 0, -1):

or
for row in board[::-1]:

if statements
In math class you know how you were able to write a < x > b? You can do that in python without requiring and.
if 0 <= number > 10:

Then there is checking the board state if someone has won.
Your current approach requires a lot of coding and can't be expanded on quickly
There are a few different approaches you can do with this. All will "work."
First the rows
for row in board:
  if len(set(row)) == 1:
    return True

for row in board:
  if all(element == row[0] for element in rows):
    return True

Diagonals next (I would use a tempory dummy variable for len(board) to increase readability. -> _ = len(board)
if len(set(board[i][i] for i in range(len(board)) == 1:
  return True
if len(set(board[i][len(board)-i-1] for i in range(len(board)) == 1:
  return True

The columns can be a trickier but transposing would probably be the most pythonic way to approach it.
board_T = [list(column) for column in zip(board)]

This will allow you to call the rows again and check to see if someone won.
It should be noted that the return values for the winner state could return the PLAYER of rather than True or False. Python sees 0, None, Empty iterables, and False as False in an if statement.
I also noticed you didn't follow a lot of the advice given to you in the original post. You are still lacking an if __name__ == "__main__": statement
def playTicTacToe():
   display_board(test_board)
   ...

...
if __name__ == "__main__":
  playTicTacToe()


I am not an expert at scala, but this works for me

def pairUp2( list1: List[A], list2: List[B]): List[(A, B)] = {
    (for{
     a <- list1
     b <- list2
     if a.serial == b.serial
   } yield (a,b))
 }

 val pairs = pairUp2(l1, l2)
 pairs: List[(A, B)] = List((A(0),B(0)), (A(1),B(1)), (A(2),B(2)), (A(3),B(3)), (A(4),B(4)))

The for comprehension, takes each element of list1 and an element of list2 and yields a tuple only if the serial values match.


Promise Chaining for a Firebase v3 Auth Subsystem - Password Based Users

registerPasswordUser is a weird name. It's sort of like "register a user with a password" which all of registered users should have anyways. registerUser might be just fine.

One thing you can do instead of "nullifying" is to accept a user object that has the 4 fields. Then to "nullify", use Object.assign.

const userDefaults = {email: ..., displayName: ..., password: ..., photoURL: ... };

function registerUser(user){
  const finalUserConfig = Object.assign({}, defaults, user);
  ...
}

There is no way for the caller to actually know if the procedure succeeded or failed. This function is a one-off, and the only way to know is a visual console.log. Consider returning the promise, that way the caller knows it succeeded or failed.

function registerUser(user){
  ...
  return firebase.auth()
    .createUserWithEmailAndPassword(email, password)
    .then(...)
    .then(...)
    .catch(error => {
      console.log(error.message);

      // promise.catch recovers the chain.
      // We want to preserve the error for the caller.
      return Promise.reject(error);
    })
}

The two thens you have appear to have one-off calls, sendEmailVerification and updateProfile. They first then doesn't return a promise, which means next one doesn't appear to be waiting for it. They both will fire when createUserWithEmailAndPassword resolves and they may both be merged in one then.

However, since they don't return promises, the chain will not know about their presence. Should they fail, your catch will not capture.

Promise.resolve('test')
.then(function(v){
  Promise.reject('error')
})
.then(function(v){
  console.log('this gets called');
})
.catch(function(error){
  console.log('this never gets called');
});

Consider using Promise.all to handle both calls that return promises. This way, you know if they fail.

Here's how I would do it:

function registerPasswordUser(config){
  const defaults = {email: null,displayName: null,password: null,photoURL: null };
  const userConfig = Object.assign({}, defaults, userConfig);

  firebase.auth()
    .createUserWithEmailAndPassword(userConfig.email, userConfig.password)
    .then(() => {
      const user = firebase.auth().currentUser;

      // Do both in parallel while being able to capture errors in promise
      return Promise.all([
        user.sendEmailVerification(),
        user.updateProfile({ displayName, photoURL });
      ]);
    })
    .catch(error => {
      console.log(error.message);
    });
}


Recursive function, high performance critical

For recursion, you can try adding an @memoize decorator to it, to speed it up.

import functools

def memoize(f):
    cache= {}
    @functools.wraps(f)
    def memf(*x):
        if x not in cache:
            cache[x] = f(*x)
        return cache[x]
    return memf

Not sure if in your case it will speed up a lot, but if you try with fibonacci, you will see that it vastly speeds up the recursions, since it caches previous results.

This is something that speeds up recursion things in general. For your specific case, we need a bit more info, on what your functions are, and what you want to achieve to get a more specific answer.


Query to get number of related records in 2 child tables

Did you try this query?  Did it work?  Unless ID and Title are the only columns in the Brands table this query would result in an error.

I would use subqueries for this:

SELECT
   Brands.*,
   (SELECT COUNT(*) FROM Pens WHERE CatID = Brands.ID) AS PensCount,
   (SELECT COUNT(*) FROM Pencils WHERE CatID = Brands.ID) AS PencilsCount
FROM
   Brands


Another key feature to dictionaries is the dict.get(key, default) function which allows you to get a default value if the key doesn't exist. This allows you to make the code less cluttered with if statements and also try/except.

The solution is often a balance between if and try statements and default values. If you are checking correctness of values, keep the try/catch statements as small as possible.

    response = api_result.get('response', None)
    if response:
        city_name = response.get('name', '')
        try:
            user_details['city'] = int( reponse.get('cid', 0) )
        except ValueError, e:
            pass # report that the 'cid' value was bogus


Improve nested loop for bio-statistics calculation

Using small l for the index is bad because it looks like the digit 1.  It's better to use large L.

Instead of j*NN, it's better to use a cached index that increments by for:

int NN2 = NN*NN
for(int iNN=k; iNN < (NN2+k); iNN+=NN) {
  thirdlayer = thirdlayer + V[k]*V[iNN]*fourthlayer;
}

This could be a bit faster.

Another hook - more use pointer as array sintax:
for 3layer better get a row vector in wich 4layer for process:

int* VVj = &(V[j*NN]);
int* VNN = &(V[NN]);
for (int k=0; k<NN; k++) {
                int* JNNk = &(J[k*NN]);
                fourthlayer = 0;
                for (int l=0; l<NN; l++) {
                    fourthlayer =  fourthlayer + VVj[l]*VNN[l]*JNNk[l];
                }
                thirdlayer = thirdlayer + V[k]*V[i*NN+k]*fourthlayer;
            }

good compiler do it for you byself, but in such decomposition may better see data dependents, and it is a bit simpler and short

also you can deploy from 4layer V[j*NN+l]*V[NN+l] into stanalone vector that can be prepared in outer j cycle.

Instead of division (xxx)/Padt (better=faster), use multiplication *(1/Padt), or move out from the last cycle:

double thp = thirdlayer/Padt;
for(int i=0; i<NN; i++) {
    if(i != j && pi_cod[j] != 0)
      Transitions[i*NN +j] =  sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thp;
  }

Instead of a conditional calculation, it's better to use a conditional assignment since it can better optimized for x86:

double thp = thirdlayer/Padt;
for(int i=0; i<NN; i++) {
    int pcodj = (pi_cod[j] != 0)?pi_cod[j]: 1;
    double transition = sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thp;
    if(i != j && pi_cod[j] != 0)
      Transitions[i*NN +j] = transition;
  }

If it's rare misses for assignment, so penalty for calculation could be negligible.


Checking for many alertable conditions before saving customer information

You can absolutely extract validation part out of this method because almost every validation is depending on self.service object.

1 Write a method in self.service class that will validate situation and return NSString message if not valid situation.

2 As only one validation is happening on self i.e. checkRequireCellOTM method, pass result of this method while validating self.service.

3 According to result of new method show an alert or proceed.

Here is how I'm trying to clean it-

New method in class of self.service:

- (NSString*)validateServiceReadiness:(NSString*)requiredCellOTM {
  // Cannot save if customer is pending
  if ([self isWaitingForApproval]) {
    return NSLocalizedString(@"message.waiting-approval", nil);
  }

  // Check required field
  NSString *incompleteRequiredField = [self checkRequiredFields];
  if (incompleteRequiredField) {
    NSString *message = [NSString localizedStringWithFormat:NSLocalizedString(@"message.required field %@", nil), NSLocalizedString(incompleteRequiredField, nil)];
    return message;
  }

  if(![self isDistributorOrWholesalerInTW]) {
    incompleteRequiredField = requiredCellOTM;
    if(incompleteRequiredField) {
        NSString *message = [NSString localizedStringWithFormat:NSLocalizedString(@"message.required otm %@", nil), NSLocalizedString(incompleteRequiredField, nil)];
        return message;
    }
  }

  Country_Identifier countryID = (Country_Identifier)[self.customer.country_id integerValue];
  if (countryID == Country_Taiwan || countryID == Country_Thailand) {
    if (![self isHasContact]) {
        return ALERT_CONFRIM_HAVE_CONTACT;
    }
  }
}

Then use this method for validation as:

- (IBAction)saveCustomer:(id)sender {
  @try {
    [self.view endEditing:YES];

    NSString *serviceReadinessMessage = [self.service validateServiceReadiness:[self checkRequireCellOTM]];
    if (serviceReadynessMessage != nil) {
        APAlert(WARNING_TITLE, serviceReadinessMessage);
        return;
    }
    [[SomeManager alertViewManager] showAlertWithTitle:SAVING_TITLE
                                               message:SAVE_CUSTOMER_CONFIRM
                                                target:self
                                            actionView:nil
                                     cancelButtonTitle:YES_BUTTON_TITLE
                                     otherButtonTitles:NO_BUTTON_TITLE
                                                andTag:AlertViewTag_Save];
  }
  @catch(NSException *exception) {
    [self sendException:exception];
  }
}

I'm not sure which method is throwing an exception here, but if it's belongs to our new method validateServiceReadiness then modify syntax accordingly.


In addition to what Reinderien posted:
Look at std::forward_list
Your linked list is a single-linked list, the closes equivalent in the standard library is std::forward_list. You will notice from the documentation of std::forward_list that it doesn't implement a push_back(), and its erase() function only takes iterators, not indices. All this is to keep this data structure light and focused only on the properties that a single-linked list has: inserting and removing at the head is fast, and you can iterate over it in one direction. There is no operator[] overload.
Slower operations, like finding the node at a given index, are left to other functions such as std::advance(). And this makes it clear that if you want to do something like access random elements, you are better off using a different data structure, such as a std::vector.
Spelling
There are some spelling errors in your code:

LincedList -> LinkedList
currectNode -> currentNode (and some variants)

Maybe English is not your native language, that's fine. There are some tools that can help you find and fix common spelling errors in source code, like codespell. Consider running them on your code from time to time.
Don't do bounds checking
Well, you asked how to improve performance.
In C++ it is normal for standard containers to not do any bounds checking. The burden of bounds checking is placed on the caller. This avoids some overhead every time your functions are called.
Not throwing exceptions also allows code using your class to be compiled without exceptions enabled, which can have various benefits.


Indentation and formatting
    currentNum = Integer.parseInt(line)
    ;
Is there a chance of an MAX_INT overflow for reverse(). Seems unlikely for the given contraints though.
Since n is an integer, so negatives are allowed. In that case .reverse() will cause problem. Please check the constraints.
getPalindrome() should return a palindrome instead of an output you wish to have. Instead either have the function name changed. (Though not a big concern but ensure that when I see a function name, it shoul dbe intuitive so that I do not have to check the code for the actual output.)
Test cases:

Include 0, 9998 (max non palindromic n).
Negatives (if constraints dont mention so).
Invalid input. (Not handled by your program and may not be required but would help for a production code and not a programming challenge).

Optimisation:

reverse() though takes negligible time (in nanoseconds) but can be improved to handle all above cases along with speed in calculation. Ideone link

private static int reverseInt(int n) {
    int rev = 0;
    while(n>0){
        rev = (rev*10)+n%10;
        n=n/10;
   }
   return rev;
}


Iterating string characters and passing them to a BIOS API

The two samples don't quite do the same thing. The first sample starts by setting the location of the stack and data segments to some 'magic' location in memory:

mov ax, 07C0h
add ax, 288
mov ss, ax
mov sp, 4096
mov ax, 07C0h
mov ds, ax

The second sample doesn't (so it will use the SS and DS locations which are left in those registers by the O/S which loaded the program). I don't understand what 07C0h is and why there is that difference between the two programs.

Also the styles of assembly are different, for example one uses 0Eh and the other uses 0x0E. Are they both supported by NASM?

The first sample ends with jmp $ which I don't understand: does it mean "jump to here" i.e. "infinite loop"? The .done: ret label seems to be unreachable.

The second sample ends with exit_function: ret which I guess returns to the O/S.

  The most significant place in both code for me is the loop for printing a char from the whole string, so I want you to tell me which variant is more correct (or maybe both variants are bad and you can provide me a much better sample).

Your using BIOS int 10h which Wikipedia says is:

Teletype output AH=0Eh  AL = Character, BH = Page Number, BL = Color (only in graphic mode)

The first sample doesn't initialize the BX register (so it may may contain a semi-random value), the second does. BX may or may not have an effect (in fact this whole "BIOS Teletype output" API may or may not work) depending on current the video mode.

If you're interested in speed then the following algorithm can be much faster than using the BIOS interrupt:

Set the right video mode
Set registers (for example, es:di) to point to the main memory location which is shared with the video card (perhaps 0xB0000 if I recall correctly)
Write the character into video memory

Or instead of writing characters the the BIOS one at a time, there's a BIOS API which lets you write an entire string. I copied the following from 8086 BIOS and DOS interrupts (IBM PC):

INT 10h / AH = 13h - write string.

input:
AL = write mode:
    bit 0: update cursor after writing;
    bit 1: string contains attributes.
BH = page number.
BL = attribute if string contains only characters (bit 1 of AL is zero).
CX = number of characters in string (attributes are not counted).
DL,DH = column, row at which to start writing.
ES:BP points to string to be printed.
example:
mov al, 1
mov bh, 0
mov bl, 0011_1011b
mov cx, msg1end - offset msg1 ; calculate message size.
mov dl, 10
mov dh, 7
push cs
pop es
mov bp, offset msg1
mov ah, 13h
int 10h
jmp msg1end
msg1 db " hello, world! "
msg1end:

As for your print loops:

print_string:
    mov ah, 0Eh

.repeat:
    lodsb
    cmp al, 0
    je .done
    int 10h
    jmp .repeat

The first one (above) looks tight: i.e. it's good and short, with the mov ah, 0Eh performed once outside the loop. lodsb doesn't affect flags, so the separate cmp is necessary. There may be a faster way to compare al with 0, perhaps something like or al,al.

I don't have a BIOS reference manual, but one thing it's lacking is a check of the 'return code' to see whether the output might have failed. This suggests that if the call fails it might leave a return code in ah. You want your ah preserved, so you might want to check that at least the first one didn't fail, and then have a loop which assumes that subsequent won't fail.

If your string weren't null-terminated, if instead you knew the length of it ...

HelloString:
dw 0bh
db 'Hello World'

... then you could load the length into cx and use the loop instruction, something like:

mov si, HelloString
lodsw
mov cx,ax
mov ah,0eh
.repeat:
lodsb
int 10h
loop .repeat
; .done:
ret

Beware that the above may not be the fastest way to loop, anymore. I once read that the more complicated opcodes (like loop) perform more slowly on modern CPUs than using several primitive instructions (e.g. dec cx and jnz). The reason for that is that a developer (or compiler) will choose and place those more primitive opcodes in such as way as to use both pipelines and not cause a stall. Writing assembly which keeps both pipelines busy is an advanced art (which, they try to build-in to compilers). If I look at the output from a compiler, I hardly recognize it any more! Because, it often uses several instructions instead of one or two. Nevertheless I think that the loop above is compact and idiomatic (if you're writing code for another programmer to read, not writing code in order use every last CPU cycle).

The second one doesn't seem to be optimized for size or speed:

PrintCharacter:
    mov ah, 0x0E
    mov bh, 0x00
    mov bl, 0x07
    int 0x10
    ret

PrintString:
    next_character:
        mov al, [si]
        inc si
        or al, al
        jz exit_function
        call PrintCharacter
        jmp next_character
    exit_function:
        ret

Why not use lodsb instead of mov al, [si] and inc si?
Why set bl and bh instead of setting bx?
Why not set bx and ah before the loop begins (I think that a call to int 10h should preserve the contents of the bx register?
Why make PrintCharacter a subroutine to be called, instead of including those instructions inline?

  Also, about code style. I don't know which style is more correct in ASM, for e.g. in the 1st variant I'm using the name of the functions like: print_string, but as for the 2nd variant, I'm using the style, which is closer to C# name style PrintCharacter, so which variant of naming is more suitable in ASM language?

The NASM manual seems to use naming conventions more like print_string. Chapter 9 talks about writing assembly called from high-level languages. Names of HLL functions are subject to name mangling so if you want to write the C printf function in assembly you might need to call it _printf.


ARC 067 - read ints and find the best choices

Learn to love rustfmt.

No space between a method name and the parens, space after the parens.

-fn main (){
+fn main() {

Multiple statements belong on different lines.

-    let a = input_one[1]; let b = input_one[2];
+    let a = input_one[1];
+    let b = input_one[2];

Spaces go between comma-separated items.

-    println!("{}", solve(&a,&b,&xs));
+    println!("{}", solve(&a, &b, &xs));

Spaces go after the : in declarations.

-fn distances(xs:&[u64]) -> Vec<u64>{
+fn distances(xs: &[u64]) -> Vec<u64> {

Using Result::ok is not appropriate error handling. If there had been a failure while reading from standard input, your program would continue with an empty string. That's unlikely to be what you want.
unwrapping a Result is better than losing an error, expecting is better than that as you get a little bit of a clue as to where there was a problem, and returning a Result is even better.
If you are going to document a function, use doc comments, not programmer comments.
Zipping the slice with itself is fine, but using slice::windows is a bit shorter, and may be easier to understand when reading the code.
folding over the distances is fine, but a combination of map and sum is probably easier to understand and is as efficient.
There's no real benefit to taking values like u64 by reference. They are small and implement Copy. I'd expect that passing by value would be the same speed if not faster.
a, b, 'xs' are bad variable names. Make them something useful.

use std::io;
use std::cmp::min;

fn main() {
    let input_one = read_ints();
    let walk_cost = input_one[1];
    let teleport_cost = input_one[2];
    let locations = read_ints();
    println!("{}", solve(walk_cost, teleport_cost, &locations));
}

/// Find the distances between adjacent towns
fn distances(locations: &[u64]) -> Vec<u64> {
    locations.windows(2).map(|w| w[1] - w[0]).collect()
}

fn solve(walk_cost: u64, teleport_cost: u64, locations: &[u64]) -> u64 {
    let dists = distances(locations);
    dists.iter().map(|dist| min(walk_cost * dist, teleport_cost)).sum()
}

fn read_ints() -> Vec<u64> {
    get_line()
        .trim()
        .split_whitespace()
        .map(|n| n.parse().expect("Unable to parse"))
        .collect()
}

fn get_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("Unable to read");
    buf
}

Overall, your code was easy to read and understand.

However, it feels like there's more allocation than there needs to be. Specifically, taking an iterator and making a Vec to make it into an iterator to make a Vec to just iterate through it again seems unfortunate.

One silly alternative would be something like this:

extern crate itertools;

use std::io::{self, BufRead};
use std::cmp::min;

use itertools::Itertools;

fn main() {
    let input = io::stdin();
    let input = input.lock();
    let mut lines = input.lines();

    let line = lines.next().expect("no line").expect("Unable to read line");
    let mut config_line = line.split_whitespace().map(|n| n.parse::<u64>().expect("not an integer")).skip(1);
    let walk_cost = config_line.next().expect("no walk cost provided");
    let teleport_cost = config_line.next().expect("no teleport cost provided");

    let line = lines.next().expect("no line").expect("Unable to read line");
    let locations = line.split_whitespace().map(|n| n.parse::<u64>().expect("not an integer"));
    let distances = locations.tuple_windows().map(|(a, b)| b - a);
    let costs = distances.map(|dist| min(walk_cost * dist, teleport_cost));
    let total_cost: u64 = costs.sum();

    println!("{}", total_cost);
}

This is not what I'd consider idiomatic Rust code, however. I always find iterators that return Results to be a bit awkward to deal with while still passing up errors to the calling function.


The code looks good to me, it is well documented and I do not have much to say.

Suggestion for _partition_by

In:

    if returned == last_value:
        chunk.append(x)
    else:
        if chunk:
            yield chunk
        chunk = [x]

I'd tried to write chunk = [x] as chunk = [] ; chunk.append(x). This allows some rewriting as you can extract the common line out of the if / else.

    if returned == last_value:
        pass
    else:
        if chunk:
            yield chunk
        chunk = []
    chunk.append(x)

Then revert condition

    if returned != last_value:
        if chunk:
            yield chunk
        chunk = []
    chunk.append(x)

Then group condition as there is nothing to do when chunk is already empty.

    if chunk and returned != last_value:
        yield chunk
        chunk = []
    chunk.append(x)

There is nothing wrong with the way things were done, this is a pure personal preference.

Details about docstring

The docstrings are slightly inconsistent as we have two different forms for the verb: with and without the final 's'. If that can be of any help, there are Docstring conventions for Python in PEP 257.

It suggests:

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


Performance of List representation of MonadPlus versus Tree representation

A bit late, but perhaps it'll still help someone.

From the benchmark it's not clear if the time difference is caused by producing a tree or consuming it. I'm not very familiar with operational to make a guess.

It seems that what you're looking for is a free MonadPlus. The closest to this is probably FreeT f [] using FreeT, see also this question. I tried to benchmark it with your code with

exploreFreeTree :: FreeT Identity [] (Sum Int) -> Sum Int
exploreFreeTree = mconcat . iterT runIdentity

that flattens a tree into a list and then concatenates it, and it was almost as fast as plain [].

But there is another potential problem. For free monads the bind operation >>= needs to traverse the whole sequence of operations in the left argument, which can cause performance issues. It's similar to appending two lists. I don't know if operational has a similar problem or not. For free monads the solution is to use the Codensity monad, in particular it's enough to just wrap your computation with improve. For this it might be better to use Free [] instead of FreeT [] Identity (although I haven't checked the details), as Codensity works only on Free, not FreeT.

It might be relevant to read
Is there a Codensity MonadPlus that asymptotically optimizes a sequence of MonadPlus operations?, although it's somewhat complicated stuff.

An good alternative could be to use logict. You could express your computations using MonadLogic and then run your computation in LogicT to do whatever processing you need to do. The advantage of this is that LogicT is internally build with continuations, which alleviates the problem with >>= performance of Free, and is built exactly to deal with branching computations. If you'd be interested, I could try to work out an example.