I think it overall is good, but there's some minor changes that could still quicken this script, namely using fetchAll and foreach instead of fetch and while

using fetchAll will get the values quicker then fetch on every single row. also foreach will prevent you from having to check if you have results, it just won't run if there are not.

also, you prepare the statement multiple times in the huge loop, instead of preparing it outside of the loop and execute() it multiple times

function update_menu(&$pdo, $filepath){
    $qry = "SELECT * FROM pages WHERE top = 1";
    $exec = $pdo->query($qry)->fetchAll(PDO::FETCH_ASSOC);
    $qryChild = $pdo->prepare("SELECT * FROM pages WHERE parent = ?");
    $string = '
' . "\n";
    foreach($exec as $row)){
        $string.= "
".$row['title'].'' . "\n";
        $qryChild->execute($row['id']);
        $childs = $qryChild->fetchAll(PDO::FETCH_ASSOC);
        $i=0;
        foreach($childs as $child){
            if($i==0){
                $string.='
' . "\n";
            }
            $string.="
".$child['title'].'' . "\n";
            $i++;
        }
    if($i != 0) $string.='
' . "\n";
    $string.='
' . "\n";
    }
$string.='
' . "\n";
file_put_contents($filepath, $string);

also, adding some "\n" will give some better readability to you html code


Synchronizing billing fields with the corresponding shipping fields

Since I don't know your markup, I don't know for sure if this will work, but it might

$("input[id*=Shipping]").change(function (event) {
  var billingId = this.id.replace('Shipping', 'Billing');
  $("#" + billingId).val($(this).val());
});

Basically, get every input with "Shipping" in its id, and when such an input changes, use its id to determine the corresponding billing-input.

Edit: While this solution is a neat little demonstration of the attribute-value-contains selector, it is - as the other answers have pointed out - better to use a class or data-attribute


Returning largest product of longest subsequence between min and max

The second example is terrible, don't use it.

You assign sl to either (l_min, r_max) or (l_max, r_min), and so you just need to change your ifs to become one if and an else.

First off len(range(l_min, r_max+1)) is the same as r_max+1 - l_min, and there's no need for the +1 if both sides have it. So your first if could become: r_max - l_min > r_min - l_max.

To merge the first and third, you should check it's the first, or explicitly check it's not the second and is the third. And so you can get:

def prod_between_min_and_max(arr):
    l_min = arr.index(min(arr))
    l_max = arr.index(max(arr))
    r_max = len(arr)-1 - arr[::-1].index(max(arr))
    r_min = len(arr)-1 - arr[::-1].index(min(arr))
    if (r_max - l_min > r_min - l_max
      or (r_max - l_min == r_min - l_max
          and prod(arr[l_min:r_max+1]) >= prod(arr[l_max:r_min+1]))):
        sl = (l_min, r_max)
    else:
        sl = (l_max, r_min)
    return prod(arr[slice(sl[0], sl[1]+1)])

This reminds me of FizzBuzz, as there doesn't seem to be a 'nice' solution.


How to reduce runtime of gene data processing program?

The first thing for solving a problem like this is to find out what the actual bottleneck is. In your case the two most likely parameters are disk IO or CPU power.

Disk IO

Make sure the data sits on local drives and not on a network share or USB stick or similar.
Make sure your disks are reasonably fast (SSDs might help).
Put your input file and your output file on two different hard drives.
mmap might gain you some speed in reading and/or writing the data. At least in this case it seemed to make a difference.

CPU

There are several calculations you perform for each line in the input file but those numbers seem to be static (unless the script you posted is incomplete)

Var_A = float(1) / float(21-3) #SAMPLESIZE - 3 looks like a constant to me which can be calculated once.
Similar Var_B
From these two a bunch of other variables are calculated which would also be static: WT_A, WT_B, SumofWT, Var, SE, WT_POWER_A, WT_POWER_B, SumofWT_POWER, c
Might not make a huge impact but still seems redundant

As each line seems to be independently calculated this code would be a prime example for parallelization. I have not much experience with python and parallel programming but the ProcessPoolExecutor seems like a good start. Bascially utilize as many processes as you have cores and split your input into chunks to be distributed to the processes. You'd have to collect the results (and presumably make sure you write them out in the correct order) so this will make your code a bit more complicated but has the potential to speed up your calculations close to a factor of N (assuming N is the number of CPU cores) provided disk IO is not killing you.

You could also split the input, distribute it to other computers in the office and get the processing done there and collect the results.


This is not really a speed issue; there are a couple of problems with your code that prevent it from working properly.

The most serious problem is that, if the position is not good you set isok2 = false. The while loop then picks another position. But nothing resets isok2 to true. So in fact, if the function does not find a good position on the first attempt, it will continue to loop indefinitely, which is why the page does not load.

A second problem is that when the position is not good you set all of the cells to empty.

for (var a = 0;  a < size; a++) { // Reset cell
    gridHit[i][j+a].stat = "empty";
}

but this overwrites other ships that might have been in that space. A better approach would be to find an appropriate space first, and only once the whole space has been checked, start filling that space with 'ship' cells. Then you don't have to worry about resetting cells you have started filling before realising the space was blocked.

Some other comments:

(1) Instead of using the condition if((side ? j : i)+size-1 < 11) to check if the position is within the grid, it would be better to make sure that the random numbers chosen are within the grid in the first place:

i = iio.getRandomInt(1, side ? 11 : 11 - size);
j = iio.getRandomInt(1, side ? 11 - size : 11);

(2) Instead of setting k = 10 to break out of the loop, simply use break.

(3) Debug what is happening in your code by strategically placing console.log commands.

(4) It's often cleaner to use functions and return statements rather than flags. For instance, you could have a function like this within your main function:

function blocked() {
    for (var k = 0; k < size; k++) {
        if (side ? grid[i][j + k] : grid[i + k][j]) {
            return true;
        }
    }
}

Here is a jsfiddle demonstrating these points (in the function makeEnemyShip). It uses the same basic algorithm that you do and there is no speed problem.


Listing employees and their project tasks

Try putting GROUP BY in a sub-select.

SELECT  personTaskProject.TaskCount,
        ppl.Name,
        ppl.Birthdate,
        ppl.Title,
        ppl.Role,
        ppl.Status,
        ppl.Warehouse,
        ppl.StartDate,
        ppl.SalaryBand,
        ppl.Salary,
        personTaskProject.Title
    FROM
        People ppl,
        (SELECT COUNT(t.id) TaskCount, tp.PersonId, p.Title
            FROM TaskPersons tp
                JOIN Tasks t
                    ON t.Id = tp.TaskId
                JOIN Projects p
                    ON p.Id = t.ProjectId
            GROUP BY tp.PersonId, p.Title) AS personTaskProject
    WHERE ppl.Id = personTaskProject.PersonId;

SQL Fiddle


Spreading the load more evenly from a background thread

If you use a random delay and fixed period, all machines will make roughly the same number of calls during their lifetime. With this approach you can be sure that every machine makes a call within the period.

If you use a fixed delay and random period, then some machines may end up making more calls than average, and others less than average.

If you want more balanced calls, the first approach makes more sense.

To measure the actual load, add some logging on the server. To give you an example, given this simplified sample from an apache log:

66.249.67.190 - - [30/Aug/2014:04:28:23 -0700] "GET
66.249.67.203 - - [30/Aug/2014:04:28:34 -0700] "GET
66.249.65.126 - - [30/Aug/2014:05:32:54 -0700] "GET
66.249.65.126 - - [30/Aug/2014:05:32:54 -0700] "GET
66.249.65.118 - - [30/Aug/2014:08:11:20 -0700] "GET
66.249.65.118 - - [30/Aug/2014:08:11:20 -0700] "GET
66.249.65.126 - - [30/Aug/2014:08:11:21 -0700] "GET
180.76.5.168 - - [30/Aug/2014:14:30:57 -0700] "GET

I would extract the timestamp part using cut or awk commands, for example:

# extract the timestamp part, until minutes, without seconds
cat access.log | cut -d' ' -f4 | cut -d: -f-2
[30/Aug/2014:04
[30/Aug/2014:04
[30/Aug/2014:05
[30/Aug/2014:05
[30/Aug/2014:08
[30/Aug/2014:08
[30/Aug/2014:08
[30/Aug/2014:14

And pipe this to uniq -c to get a count per-minute:

cat access.log | cut -d' ' -f4 | cut -d: -f-2 | uniq -c
  2 [30/Aug/2014:04
  2 [30/Aug/2014:05
  3 [30/Aug/2014:08
  1 [30/Aug/2014:14

Hopefully you should see a balanced count, and a repeating pattern every 5 minutes.

This is just an example (and not the best way, quick and dirty way) of measuring the load, use whatever method that suits you best.


Your algorithm can be summarized as follows:

  Fetch the list of cookies and sort in ascending order.
  Initialize a counter to zero
  If the smallest cookie is less than K,  then:

  (a) Increment the counter and combine this cookie with the next smallest cookie (or return -1 if there are fewer than 2 cookies left)
  (b) Remove the two smallest cookies from the list and add the new cookie to the list
  (c) Sort the list in ascending order again

  Otherwise, exit with the value of the counter
  Go back to step 3

Your code is taking a long time to run because you are sorting the entire list at step 3(c). This is unnecessary; since the list is already sorted (apart from the new value being added), you can just do a binary search in \$\mathcal{O}(\log(n))\$ time to find the correct position in which to insert the combined cookie. This is going to be much faster than sorting, which typically takes \$\mathcal{O}(n\log(n))\$ time.

An even better approach would be to use a min-heap data structure, which will keep track of the smallest element in a set in the most efficient way possible.

Addendum:

I converted your code to use a PriorityQueue data structure (Java's equivalent to a min-heap). I also created some test data using the following code:

perl -e '$n=100000;$h=$n/2;print "$n $h\n";for $i(0..$n){$r = int(rand()*$n); print "$r ";};print "\n";' > testdata.txt

Your original code took 1 minute to process 100,000 items. With a priority queue, this went down to 0.7 seconds. Here's my code:

import java.util.*;

public class Solution2 {

  private static int getMinStepsToGetK(long k,PriorityQueue<Integer> newQueue){
    int count=0;
    while(newQueue.peek()<k) {
      if(newQueue.size()>=2) {
        count++;
        int tempFirst = newQueue.poll();
        int tempSecond = newQueue.poll();
        newQueue.offer(tempFirst+(tempSecond*2));
      }
      else {
        return -1;
      }
    }
    return count;
  }

  public static void main(String[] args) {
    Scanner scanObj = new Scanner(System.in);
    int numOfCookies = scanObj.nextInt();
    long minSweetness = scanObj.nextLong();
    PriorityQueue<Integer> newQueue = new PriorityQueue<Integer>();
    for(int i=0;i<numOfCookies;i++) {
      newQueue.offer(scanObj.nextInt());
    }
    System.out.println(getMinStepsToGetK(minSweetness,newQueue));
  }

}

Note: There's no need to create a new Solution object in order to access the getMinStepsToGetK() member function. Since it isn't needed externally, I declared it as a private static function.


As mentioned in comment, it is harder to be more specific without being able to run the code, but what can I say:

Separate event code function and then the function, that will "do the work" itself, with all necessary parameters.
Extract for into separate function.

That will overall make it easier to read and cleaner + easier to test. Something like:

function getAttributes(event) {
  event.preventDefault();
  var thisValue = event.target.getAttribute('data-filter');
  setGridItems(gridItem, thisValue);
}

function setGridItems(gridItems, dataFilter) {
  for (let a = 0; a < gridItems.length; a++) {
    setGridItem(gridItems[a], dataFilter);
  }
}

function setGridItem(singleGridItem, dataFilter) {
    const gridFilterAttr = singleGridItem.getAttribute('data-filterType');
    if (dataFilter == gridFilterAttr) {
      singleGridItem.classList.add('active')
      singleGridItem.classList.remove('not-active')
    } else if (dataFilter == 'all') {
      singleGridItem.className = 'active';
      featuredItem.className = 'featured active'
    } else {
      singleGridItem.classList.remove('active')
      singleGridItem.classList.add('not-active')
    }

}

Would be cool to use foreach there, but it is a bit problematic with NodeList and support is not that broad yet, but maybe you could do that. Now when you have it a bit separated, you can continue with refactoring. I don't like that some variables are pre-cached and "global", that's why I passed gridItem variable anyway to make it local in function, but featuredItem is still global.
Last function could use more of refactoring, but I'd need more info about problem for that :-)


I took some time to look at your code and rewrite it a little bit.

My first advice is, try to make your code a little bit more verbose. It will be only written once and read over and over. It's very important that the code communicates what it's supposed to do, either through variable naming or comments.
The Art Of Readable Code is a great book on this topic, thoroughly covered by "Implementation Patterns" as well.

So...you can try this out:

function newAlgorithm(data){
    // Intial row needs data for headers
    var newData = [['price', 'bid', 'ask']],
    // Optimizes for loops
    entriesCount = data.bids.length,
    // Will be calculcated later on
    bidAmountSum = 0,
    askAmountSum = 0,
    // Will contain all entries that should be pushed into the final array
    bidEntries = [],
    askEntries = [];

    // Calculate bid and ask sums
    for(var i = 0; i < entriesCount; i++){
        bidAmountSum += data.bids[i][1];
        askAmountSum += data.asks[i][1];
    }

    // Create bid and ask entries for each one in one pass, since their count is the same
    for(var i = 0; i < entriesCount; i++){
        // Pid price is iterated in reverse
        // Bid amount sum is cumulative sum of previous bids for each point in iteration
        bidEntries.push([data.bids[data.bids.length-1 - i][0], bidAmountSum, null]);
        bidAmountSum -= data.bids[i][1];

        // Price is iterated in forward order
        // Ask amount sum is cumulative sum of previous asks for each point in iteration
        askEntries.push([data.asks[i][0], null, askAmountSum]);
        askAmountSum -= data.asks[i][1];
    }

    return newData.concat(bidEntries).concat(askEntries.reverse());
}

I tested how it performs when tested with NodeJS runtime. I increased the dataset from 100 entries through 2,000,000.

I also made in-browser test here: http://jsperf.com/chart-data-repacking

I hope this helps.


Backbone.Collection - Ensure that at most one model has property set to true

That seems wrong on a few levels.

Slows down every update call
This is pretty much 'magic happens here'
I feel this should be enforced in the UI, is it not too late for this in Backbone?

I would modify the setter to accomplish what you need : https://stackoverflow.com/a/9415926/7602


Checking if an event is not null before firing it in C#

But is creating the handler variable required, best practice, or superfluous, when compared to:

Yes, it is needed. Otherwise, CustomEvent could be set to null after you've checked for null, but before you've invoked it. This can happen if it gets set in another thread, or if one of the event handlers unregisters itself or another one.

I usually have this declared somewhere in my codebase:

public static class EventExtensions
{
    public static void Raise<T>(this EventHandler<T> handler, T args) {
        if (handler != null) handler(args);
    }
}

Now, with any event handler, you can just do:

handler.Raise(args);

You can call an extension method with a null this, so it will do the right thing even if handler is null. Furthermore, by copying handler into the local variable used by Raise, you automatically get the copy you need to make sure the handler won't disappear under you. Works like a charm.


Shuffling many collections by folding over a numeric range

If you want to transform a value v by applying a function f n times, it may be clearer to use a combination of iterate and nth:

(nth (iterate f v) n)

If you want to write a 'good' general-purpose implementation of shuffle that accepts a random generator, I suggest you simply adapt the implementation in clojure.core. You'll see the implementation you proposed is actually pretty close!

Regarding performance, keep in mind that if you want to shuffle a coll n times, nothing will beat the performance of repeatedly shuffling a mutable collection in place.


Making a function which can be called with an object literal

First, just a note: You check against undefined, but undefined is unfortunately not a keyword, meaning it's mutable. Better to use typeof something === 'undefined'

If I understand you right, you want to be able to "leave out" anyone of the object values. In that case, here's my take on the code (I'm returning an array, just for clarity)

function trackProduct(obj) {
  var keys = ['category', 'action', 'label', 'value'],  // properties to look for
      values = [],
      i, l, value;

  for(i = 0, l = keys.length ; i < l ; i++) {
    value = obj[keys[i]];
    if(typeof value !== 'undefined') {
      values.push(value); // if the value's there, put it in the array
    }
  }

  return values;
}

This would work like so:

trackProduct({
  category: "foo",
  label:    "bar",
  value:    "23",
  ignored:  "something"
}); // => ["foo", "bar", "23"]


Evaluate an expression binary tree - Daily Coding Challenge

dict > ifs
operator contains all the functions you need.
Taking total as an argument is unneeded.
I would personally split the 'Tree' which is actually a Node into two types, operators and values. But that may go against the challenge.
Use is to compare to None.

import operator

operators = {
    '*': operator.mul,
    '+': operator.add,
    '-': operator.sub,
    '/': operator.truediv,
}

class Tree:
    def __init__(self, value, left=None, right=None):
        """Initialise values"""
        self.value = value
        self.left = left
        self.right = right

    def determine(self):
        if self.left is None and self.right is None:
            return int(self.value)

        return operators[self.value](
            self.left.determine(),
            self.right.determine()
        )


Your code makes remarkably good usage of modern C++ idioms. Bravo!

The only improvement that jumps out to me is the signature of vertex_of. By reading its definition, you can deduce that it returns a std::vector<line>, but ideally this should be documented in the declaration itself. I'd advice changing the signature to either

std::vector<line> vertex_of(const container_t<cell> &cells)

or

auto vertex_of(const container_t<cell> &cells) -> std::vector<line>

depending on the stlye you prefer.


So... handle() gets an incoming connection. Great! What's not so great is that it then spawns self.send in a thread that will never die.

More minorly, I'm not sure why you'd do

    self.username = self.request.recv(8192)
    self.username = self.username.decode()

instead of just

    self.username = self.request.recv(8192).decode()


How to correctly use lock when adding/renewing cached data in asp.net cache?

First, I think your code doesn't make much sense. The only reason why Cache can be useful is if you want the cached data to expire after some time or if the memory is low. But you're preventing the memory to be freed by using the field _cachedResults, which will hold the data even after they are removed from the cache. This field is of no use for you, _cachedResults should be a local variable instead.

Second, your code is not reliably thread-safe, because of the way you're assigning to _cachedResults. What could happen is if GetSomeData() creates the result using new, an uninitialized object could be first assigned to _cachedResults and only then would be the constructor called. Such reordering could happen, because it's safe from the point of view of a single thread.

Normally, you would solve this by using a volatile write. But in your case, simply using a local variable instead of a field will be enough.

For more details, see The Famous Double-Check Locking Technique in Chapter 29 of Jeffrey Richter's CLR via C#, or the Wikipedia article Double-checked locking.


Python Constant Class, Different Enum Implementation

The code looks decent, but there are a couple problems with the overall design:

"constants" can be changed (rebound) or removed from the class
the constants don't have a nice repr() (very useful for debugging)

To solve these problems, and more, check out the aenum library1 -- besides advanced Enum and NamedTuple implementations, it also has a Constant2 class.

Your code above would look like:

from aenum import Constant

class TypeNames(Constant):
    TYPE_A = 'Whatever you want it to be'
    TYPE_B = 'Another example'

and in use:

>>> print(repr(TypeNames.TYPE_A))
<TypeNames.TYPE_A: 'Whatever you want it to be'>

>>> print(TypeNames.TYPE_A)
Whatever you want it to be

>>> try:
...     del TypeNames.TYPE_B
... except AttributeError as exc:
...    print(exc)
....
cannot delete constant <TypeNames.TYPE_B>

>>> try:
...     TypeNames.TYPE_B = 'oops!'
... except AttributeError as exc:
...     print(exc)
...
cannot rebind constant <TypeNames.TYPE_B>

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

2 Looking at your all() implementation I can see that should be added to Constant.


Since it's a code-review site, I'll focus on issues you have with your code...
Having Main in your class
I would generally avoid this. I understand that this is probably a single-class demonstration project, but typically C# projects have a Program class that has Main inside of it, and I would stick with that. If you want to be able to unit-test FizzBuzzer, the Main function would not be unit-testable. As a result, your code-coverage of this class will be lower.
Inconsistent method names
You have a method properly cased as StartLoop and then you have an improper cased getOutputForI. Stick with the Microsoft recommendation of Capitalization Rules for Methods which should be Pascal Cased.
Method names and parameters that don't self-document
The name you give a method should identify to the caller what it does. StartLoop both starts and ends a loop, and runs the entire sequence. Ideally this would be named Run instead of StartLoop, but even then, what is it returning? Maybe CountFizzBuzz would be even better. Similarly, getOutputForI certainly gets the output for the method parameter I, but that really doesn't say what it does. Maybe consider renaming it to FizzBuzz(int input) instead.
Similarly the method parameters are not self documenting. What is n exactly in StartLoop? It would be more apparent if the method were something like Run(int max). Which would also require a modification of your for loop because you would stop just shy of max. i is also not apparent of what it is (see a suggested version in the paragraph above).
Mixing UI with code
This makes your code unit-test unfriendly. You can't unit test the output to the console, so in order to unit test this you would need to pass a stream to the output:
public int CountFizzBuzz(int max, TextWriter output)
{
    int fizzBuzzes = 0;
    for (int i = 0; i <=max; i++)
    {
        string fizzBuzz = FizzBuzz(i);
        if (fizzBuzz == "FizzBuzz")
        {
            fizzBuzzes++;
        }
        output.WriteLine(fizzBuzz);
    }
    return fizzBuzzes;
}

Now this is unit-testable because you can create a TextWriter and pass in a value that can be Asserted later.
Inconsistent Brackets
You have two methods of writing brackets in your code, the "Microsoft" way, and the "Java" way. Again, I would stick with Microsoft practices here and use the one that has both brackets on their own lines.
Using an instance object for something that has no state
FizzBuzzer has no state, so why isn't everything static? There isn't a good reason to require a new each time you have to run the "Fizz Buzzer", take up space on the stack, etc. This class should be made static.

So with all my recommendations, here is what it would possibly turn out like:
public static class FizzBuzzer
{
    public static int CountFizzBuzzes(int max)
    {
        return CountFizzBuzzes(max, Console.Out);
    }

    public static int CountFizzBuzzes(int max, TextWriter output)
    {
        int fizzBuzzes = 0;
        for (int i = 0; i <= max; i++)
        {
            string result = FizzBuzz(i);

            if (result == "FizzBuzz")
                fizzBuzzes++;

            output.WriteLine(result);
        }
        return fizzBuzzes;
    }

    public static string FizzBuzz(int input)
    {
        string s = "";

        if (input % 3 == 0)
            s += "Fizz";

        if (input % 5 == 0)
            s += "Buzz";

        if (s.Length == 0)
            s = "" + input;

        return s;
    }
}

I still don't find this completely "ideal" as CountFizzBuzzes really does two things, counts them and outputs them to the stream. This really should be two separate methods for separation of concerns.
Just as a final note, your Main has an issue... Right now when you start the program it just stares at you with a blank window until you mash the right key(s).
public static void Main()
{
    FizzBuzzer fizzBuzzer = new FizzBuzzer();
    int n = Convert.ToInt32(Console.ReadLine());
    fizzBuzzer.StartLoop(n);
}

What is to stop the user here from entering "My Name Is" instead of "42"? The Convert.ToInt32 will throw an exception and the program will terminate. The user isn't even prompted for a number or any thing. At least prompt the user:
There are a multitude of questions on here about how to validate console input, so I'll leave that to you to research, but you should prompt the user "Please Enter a Number:" and if that isn't a number, tell them and ask again (and provide them a way to quit).


Implementing a Treeview component using React

You might notice that createChildren is almost the same as MyTree -- the only difference is that createChildren takes its argument directly instead of as a props object. So with a small change we can remove createChildren entirely:

const MyTreeNestedItems = (props) => {
    const { data } = props;

    let children = null;
    if (data.children.length) {
      children = <MyTree list={data.children} />;
    }

    return (

                 {" "}
                { data.descp }

{children}

    );
}

This can be a bit more compact as so:

const MyTreeNestedItems = ({ data }) => {
    return (

                 {" "}
                { data.descp }

                {data.children.length ? <MyTree list={data.children} /> : null}

    );
};

Currently this code renders invalid HTML -- it renders with a
 as the top level element but
 should only be contained in a
,
, or <menu>.

Looking at the code so far, <MyTree> is rendered in two places -- it may be tempting to just add another
 around <MyTree list={tree} /> in the render() call. But then we would have two occurrences of a structure like this:
<MyTree/>
. It'd be easier to just move the
 into the <MyTree/>.

With that, the code now looks like this:

const MyTree = ({ list }) => {
    return (

            {list.map((child,i)=> <MyTreeNestedItems key={i} data={child} />)}

    );
};

const MyTreeNestedItems = ({ data }) => {
    return (

                 {" "}
                { data.descp }

            {data.children.length ? <MyTree list={data.children} /> : null}

    );
};

render(<MyTree list={tree} />, document.querySelector('.js-mytree'));

From here it's a matter of taste. Both of the components are just directly returning a value, so we can use short arrow function syntax now: (...) => (value) instead of (...) => { return (value); }

Also, the components are now simple enough that I would just combine the two.

All in, that leaves us with this final version of the code:

const MyTree = ({ list }) => (

        {list.map(({icon, descp, children}, i) => (

                     {descp}

                {children.length ? <MyTree list={children} /> : null}

        ))}

);

render(<MyTree list={tree} />, document.querySelector('.js-mytree'));


Importing JPG, JPEG, and PNG images from a folder to an Excel worksheet

I will summarize what I said before (and add a few new ones):

Use Option Explicit at the top of your module. It helps you to prevent mistakes and forces you to declare the variables
instead of Instr use Right as in If Right(strCompFilePath,4)=".jpg"
rename counter and counter1 so it is clear what they are (row and column indices)
Declare insert as a Sub and not a Function.
instead of passing the row and column index to the insert function/sub and then using the ActiveSheet pass the cell as a Range to the insert function/sub. (Instead of Activesheet you can use cell.Worksheet to get the right sheet)
possibly rename insert so you don't confuse it with Pictures.insert
add the option savewithfile := true to the Pictures.Insert method so the pictures will stay in the file even if you send it somewhere.
as it is now, you don't really need NoOfFiles and mainWorkBook
instead of the FileSystemObject I would use Dir. See this for more on that.


You don't have enough comments, and the comments that you have don't explain anything. Comments are supposed to explain why the code is the way it is (in other words: what the goal is), not restate the obvious. Everyone who knows graph theory knows that edges link vertexes, and everyone who knows C knows that something typed as Vertex * is a pointer to a vertex. Those comments have no point and should be removed.
Where's the implementation of Graph::BFS()?
Where's the code that calls ::Add_data?
What is ::Add_data even supposed to do? It appears to only support one-line files; was that your intention? Is it the same function as Vertex::Add_data?
What's the point of the linked list, when it never gets initialized?
Whenever you're manually repeating something, either by typing similar stuff over and over again, or by copy-pasting, you're doing something wrong. Computers are good at automating repetitive tasks. When you write code, you should think of writing loops. So code like

if(!(data>>parent>>child1>>child2>>child3>>child4>>child5>>child>>6>>child7>>child8))

should never appear (besides the obvious syntax error of the spurious >> between child and 6).


You should not use global variables unless you really need to. Instead, pass relevant parameters as arguments to the functions and return the results. This makes them actually reusable. Currently you have two functions to count the initial and final number of words, when you could just have a word_count function:

def wordcount(file_name):
    """count the number of words in the file"""
    with open(file_name) as f:
        return sum(len(line.split()) for line in f)

def dupfilter(file_initial, file_final):
    with open(file_initial) as in_file, open(file_final, "w") as out_file:
        out_file.writelines(set(in_file.readlines()))

if __name__ == '__main__':
    while True:
        file_initial = input("What is the name of the text?")
        file_final = input("How do you want to name the filtered file?")
        if file_initial and file_final and file_initial != file_final:
            break

    num_words_initial = wordcount(file_initial)
    dupfilter(file_initial, file_final)
    num_words_final = wordcount(file_final)

    print("Number of duplicates filtered:", num_words_initial - num_words_final)
    input("\nPress <ENTER> to quit the program.")

I also used sum with a generator expression to simplify the wordcount function, used with to ensure that files are properly closed.
In addition, I replaced the while not ready loop with a while True loop and an explicit break. This is much more common in Python, especially for user input.

Note that if file_initial and file_final != "" is only incidentally the same as if file_initial != "" and file_final != "" because non-empty strings are truthy. This is why it is also equivalent to if file_initial and file_final. But for example x and y == 3 is not the same as x == 3 and y == 3.

You also don't need to call str on things to be printed, print does that for you if necessary.

Note that using set does not guarantee the same order as the original file, for that you would want to use the itertools recipe unique_everseen:

from itertools import filterfalse

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

def dupfilter(file_initial, file_final):
    with open(file_initial) as in_file, open(file_final, "w") as out_file:
        out_file.writelines(unique_everseen(in_file))


... how can I make it shorter and more efficient according to both readability and professional rules?

Calling

usTick = 0;

is superfluous in the else branches sub-conditions. That can be rewritten like:

/*not pressed*/
else
{
    if( usTick > 1000){
        ButtonState.PressedState = LongPressed;
        HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
    }
    else if( usTick >350){
        ButtonState.PressedState = ShortPressed;
        HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
    }
    // Calling those statements Once is enough here
    usTick = 0;
}

Checking the minimum limit and reducing the whole sub-conditions with a ternary condition operator (as mentioned in @David Isla's answer), the whole code could be boiled down to a few lines:

/*not pressed*/
else
{
    if( usTick > 350) {
         ButtonState.PressedState = usTick > 1000 ? LongPressed : ShortPressed;
         HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
    }
    usTick = 0;
}

  What should I add or change to get double Tap pressing information with this code?

You might consider to put any data updating operations into critical sections (or other non-interruptible code paths):

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    /*button pressed and count*/
    if(!HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13))
    {
        START_CRITCAL_SECTION();
        usTick++;
        END_CRITCAL_SECTION();
    }
    /*not pressed*/
    else {
        START_CRITCAL_SECTION();
        if( usTick > 350) {
             ButtonState.PressedState = usTick > 1000 ? LongPressed : ShortPressed;
             HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
        }
        usTick = 0;
        END_CRITCAL_SECTION();
    }
}

where START_CRITCAL_SECTION() disables all interrupts, and END_CRITCAL_SECTION() reenables their former state.

This may help, that any co-routines or threads will always read consistent values for ustick or the GPIO_PIN_5 state.


Building a nested tree structure from an ordered list

First, nestComments appears very long. Functions that usually do too much are also functions that become harder to test. Also, code that is is visually long is usually hard to understand. Consider splitting it off into smaller, manageable functions.

Now one thing that makes code slow is when you nest loops. In this case, you have 3 levels, 2 for loops and findIndex which is essentially a loop. Nesting loops can cause operations to explode exponentially. What you'd want to do is keep it to a minimum, since some operations really require nested loops.

Next would be trimComments. The problem of having a switch (or any code that does comparison against a hard set of items) is that you have to play catch-up with the things you need to compare. You will constantly dive into code to add things you never wrote in the first place.

Also, your trimComments is just sending in a value and expecting a result that's pretty 1:1, reminiscent of a key-value pair. This can easily be done with regular objects instead of a switch statement. You can find the input from the keys, and get its corresponding value.

Looking for how trimComments is used, I see that you use it to determine if a comment is included. Ok, cool, you use it to skip a push. But the problem is that you've already done processing, then just suddenly skip it from being included. That's a waste of operations. Also, you can preprocess your paths so that you only include the intended maximum number of comment paths, and operate on that instead.

Here's my take on it:

Normalize your input by working on full paths.
Trim down the paths based on maximums.
Operate on the remaining paths.

And the code would be broken down into:

const commentsPerLevel = {
  '1': 5
  '2': 5
  '3': 3
  '4': 2
  '5': 1
  '6': 1
}

function getMaxForLevel(level){
  // returns value from commentsPerLevel or a default value
  return commentsPerLevel[level] || 0;
}

function getCommentPaths(comments){
  // returns full paths from input
  return comments.map(comment => `0-${comment.path}-${comment.comment_id}`);
}

function trimPaths(paths){
  // returns paths trimmed based on maximums from commentsPerLevel
}

function buildCommentTree(paths){
  // build comment tree based on paths
}

function nestComments(comments){
  const paths        = getCommentPaths(comments);
  const trimmedPaths = trimPaths(paths);
  const commentTree  = buildCommentTree(trimmedPaths);
  return commentTree;
}

I left out implementation for some, but the idea is to break down your operations into functions so they won't be that hard to maintain.


Naming

What is the difference between xChunk and chunkX? yChunk and chunkY? Choose names that will help, not hinder you.

Don't skimp on letters. size is better than siz, point is better than kps. Almost anything is better than step2. On the other hand, chunks is better than allChunks, chunk is better than currentChunk.

Class names are usually singular -- see for instance Point, Color, Rectangle. Follow the pattern and rename Chunks to Chunk.

The names Chunk and CeldsChunk don't convey anything to me -- that might be because I have no domain knowledge of what you're doing, or it might be because their names can be improved.

Commented-out code

It's confusing. Is it a failed attempt? Commented out for performance testing? No-one knows. If you might need it later, save it on a new branch. Otherwise, delete it.

Conventions

Follow C# conventions. Install StyleCop and listen to its recommendations.

Performance

Profiling is your best bet. You can try things like moving repeated calculations out of loops, as I suggested in the comment, but it's possible you're just asking too much of the computer. You're drawing up to sizeX * sizeY * ? images, and the solution might be to make do with fewer images.


Solving the max-subarray problem from CLRS in C++

I'd really like to use the modern additions to C++ effectively, so please
  let me know where things can be improved.

C++ is suprisingly strong in expressing algorithms in terms of minimal type
requirements quite "easily" with templates. To effectively use the standard
library and its modern additions one should know that

C++ algorithms are written in terms of iterators (or ranges)

So I would like to C++-ify your implementation of max_subarray and show the
usage of some new and cool features of C++17.

Your current version only works for std::vector and with little adaption to
any array-like container. But what if you want to search a std::list or some
container like std::unordered_map (with some projection onto keys or values)?

With that abstraction I wouldn't call the algorithm max_subarray but
max_subrange. The fundamental algorithm is max_crossing_subrange and that
is why I will show you how to C++ify this function

  One of my concerns was using std::numeric_limits::infinity in the code.
  Would this be used in production code? How would one handle something like
  infinity otherwise?

You are right to question that, because it is not okay or generic in any way.
What if you don't sum numbers but you are folding some lists instead in your
accumulation of neighboured elements?
What you do there is a simple search for a maximum and you could simply
evaluate the first expression instead. Look as an example at std::max_element, to see it is done there.

Just to answer your last concern

  Another concern was using tuples to return multiple values from a function.
  I find that I then have to use std::get quite a lot to access the individual
  elements of the tuple. Is this acceptable?

Yes, that is okay and should be optimized away completely.

Now lets start step-by-step with a generic mas_crossing_subrange algorithm.

Warning: This does not lead to the optimal algorithm (which is O(N)) but just shows how to express algorithms in a C++-way for your example.

Your max_crossing_subarray uses two loops which are essentially same but reversed in their direction. In fact you can express it as one function using std::reverse_iterator. Lets refactor a sub function which performs the loop. An Iterator version would look like this:

/// \brief Fixing the first position we search an end position which
///        maximises the sum from first to end.
template <
    typename I,
    typename T = value_type_t<I>
>
constexpr std::pair<I, T>
max_sum_not_empty(I first, I last, const T& init = T{})
noexcept
{
    assert(first != last);
    auto max = std::make_pair(first, *first);
    auto current_sum = max.second;
    for (auto iter{std::next(first)}; iter != last; ++iter) {
        current_sum = current_sum + *iter;
        if (max < current_sum) {
            max = std::make_pair(iter, current_sum);
        }
    }
    return max;
}

But this isn't totally generic either. What if we want to generalise the accumulation to not just sums but any given fold operator f: X x X -> X (we can not use f: Y x X -> Y in max_crossing) where summation and less-comparison are default behaviour. It would look like this:

template <
    typename I,
    typename T = value_type_t<I>,
    typename F = std::plus<>,
    typename P = std::less<>
>
constexpr std::pair<I, T> max_accumulation_not_empty(
        I first, I last, const T& init = T{}, F op = F{}, P pred = P{})
noexcept (
    std::is_nothrow_callable_v<F(const T&, reference_t<I>)> &&
    std::is_nothrow_callable_v<P(const T&, const T&)>
)
{
    assert(first != last);
    auto max = std::make_pair(first, std::invoke(op, init, *first));
    auto current_sum = max.second;
    for (auto iter{std::next(first)}; iter != last; ++iter) {
        current_sum = std::invoke(op, current_sum, *iter);
        if (std::invoke(pred, max.second, current_sum)) {
            max = std::make_pair(iter, current_sum);
        }
    }
    return max;
}

The reversed algorithm can be written as

template <
    typename I,
    typename T = value_type_t<I>,
    typename F = std::plus<>,
    typename P = std::less<>
>
constexpr std::pair<I, T> reverse_max_accumulation_not_empty(
        I first, I last, const T& init = T{}, F op = F{}, P pred = P{})
noexcept (
    std::is_nothrow_callable_v<F(const T&, reference_t<I>)> &&
    std::is_nothrow_callable_v<P(const T&, const T&)>
)
{
    auto rfirst = std::make_reverse_iterator(last);
    auto rlast = std::make_reverse_iterator(first);
    auto [rbest, sum] = max_accumulation_not_empty(rfirst, rlast, init,
                std::ref(op), std::ref(pred));
    auto best = std::next(rbest).base();
    return std::make_pair(best, sum);
}

Your max_crossing algorithm can be then given as

template <
    typename I,
    typename T = value_type_t<I>,
    typename F = std::plus<>,
    typename P = std::less<>
>
constexpr std::tuple<I, difference_type_t<I>, T>
max_crossing_subrange(I first, I mid, I last, const T& init = T{},
        F op = F{}, P pred = P{})
noexcept (
    std::is_nothrow_callable_v<F(const T&, reference_t<I>)> &&
    std::is_nothrow_callable_v<P(const T&, const T&)>
)
{
    assert(first != mid && mid != last);
    auto [best_left, left_sum] = reverse_max_accumulation_not_empty(
            first, mid, init, std::ref(op), std::ref(pred));
    auto [best_right, right_sum] = max_accumulation_not_empty(
            mid, last, init, std::ref(op), std::ref(pred));
    auto length = std::distance(best_left, best_right);
    // here comes a strong assumption: op(left_sum, right_sum) needs
    // an operator op: X x X -> X
    return {best_left, length, op(left_sum, right_sum)};
}

If this would lead to an optimal algorithm it would look like this in production code. As an exercise: Try to finish this and proof that the assertions always evaluates to true.


Use None rather then Node.no_value.

None is the typical value to use for the absence of value. However, its possible that you actually want to store None in your trie, so that doesn't work.

Checking the type of the object is not really a good plan because somebody could decide to store plain objects in your trie. I would add another value, a boolean "self.value is Node.no_value", to the tuple in setstate. By checking that I could be sure that it works correctly.


Better way to check if Javascript Date object exists

I can think of the following improvements:

Hide t. If you're running other JS modules, you can't really be sure that no-one else writes to the same variable.
If you want to be sure that your code doesn't mix up an uninitialized timer with a "cleared" timer, you might want to pre-initialize the variable to null instead.
Use === when comparing null, undefined, etc. In JavaScript, null == undefined, but only null === null.

You might want to do something like this:

var timer = (function () {
    var t = null,

    start = function () {
        if (t === null) {
            t = new Date();
        }
    },

    stop = function () {
        var time = new Date() - t;
        t = null;
        return time;
    };

    return {
        start: start,
        stop: stop
    };
})();

timer.start();

var timePassed = timer.stop();


This wrapper effectively removes some of the available functionality from std::stoi() because its signature is

int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);

Because your wrapper does not allow a pos or base argument you cannot use it to give you the number of characters processed (with pos) nor to convert using a different base. std::stoi() provides default values for these arguments so you'd only have to provide them if you need the non-default behavior.

Also, you don't take the std::string argument by const reference like std::stoi() -- the string argument is probably not too expensive to copy in this context but why not accept the argument the same way std::stoi() does?

For completeness, I would also implement the overload of std::stoi() which accepts a std::wstring (and possibly std::stol() and std::stoll()).

I would also avoid the leading underscore, as identifiers with a leading underscore are reserved.

With these suggestions the wrapper would be implemented as

int stoi(const std::string& str, int* p_value, std::size_t* pos = 0, int base = 10) {
    // wrapping std::stoi because it may throw an exception

    try {
        *p_value = std::stoi(str, pos, base);
        return 0;
    }

    catch (const std::invalid_argument& ia) {
        //std::cerr << "Invalid argument: " << ia.what() << std::endl;
        return -1;
    }

    catch (const std::out_of_range& oor) {
        //std::cerr << "Out of Range error: " << oor.what() << std::endl;
        return -2;
    }

    catch (const std::exception& e)
    {
        //std::cerr << "Undefined error: " << e.what() << std::endl;
        return -3;
    }
}


Casting base to derived class according to a type flag

Is casting a base class object to a derived class object given a type flag a good programming design?

Usually no.
It usually indicates a badly defined interface in your base class.

A better way to do it will depend on what you want you want to do with it. If you can define an abstract interface with virtual functions that would be the normal way of solving this problem.

But you seem to be using DisplayEventData as simply a bag of properties so maybe there is no generic interface. In which case I would go with a union (but that choice could change quickly based on other information).

struct DisplayEventData   // struct because it is a property bag not a real class.
{
     DisplayEventType   type;
     union
     {
            WindowEventData   win;
            KeyboardEventData key;
            MouseEventData    mouse;
            JoystickEventData joy;
     } data;
};

PS:

This is the wrong cast:

KeyboardEventData* kev = static_cast<KeyboardEventData>(ev.GetEventData());

You should be using dynamic_cast


Counting Characters from an HTML File with Python

I don’t have enough reputation to comment, so I must say this in an answer.
It looks clunky to use
    while x == 4:

and then do
    x = 3

whenever you want to break out of the loop.
It looks better to do
    while True:

and when you want to break out of the loop do
    break

Cheers!


Given that you are already using the ToObject, consider simplifying the code for readability and the advantage of not having to convert anything.

var contentJson = await SendRequest(request);
dynamic response = JsonConvert.DeserializeObject(contentJson);
List<Organization> organizations = response.organizations.ToObject<List<Organization>>();

The actual response appears to be of no concern so using a dynamic simplifies things. Converting back to strongly typed objects by calling ToObject<T> was a good choice and should work out fine.


Check string is permutation of palindrome

I would separate the algorithm from the main so that you can reuse your algorithm later.

The idea of using a hash-table based unordered_map is going into the right direction. However...

if(m.find(arr[i]) == m.end())
{
     m[arr[i]] = 1;
}

you don't need that initialization; you can think that each integer key is zero by default.

What comes to this:

for (int i = 0; i<len; i++) {
    if((m[arr[i]] % 2) == 1)count++;
}

In the loop, you can check whether the counter gets the value of 2, and exit as soon as you detect this, which adds to the efficiency of the routine.

All in all, I had this in mind:

bool is_palindrome_permutation(char* p)
{
    std::unordered_map<char, size_t> m;

    while (*p)
    {
        if (std::isalpha(*p))
        {
            m[*p]++;
        }

        p++;
    }

    size_t count = 0;

    for (auto& p : m)
    {
        if (p.second % 2 == 1)
        {
            if (++count == 2)
            {
                return false;
            }
        }
    }

    return true;
}

Hope that helps.

Edit 1

As additional fun, you can consider having a template, which allows you to abstract away the actual sequence implementation:

template<typename ForwardIter>
bool is_palindrome_permutation(ForwardIter begin, ForwardIter end)
{
    using value_type = typename std::iterator_traits<ForwardIter>::value_type;
    std::unordered_map<value_type, size_t> m;

    while (begin != end && *begin) // *begin: a dirty hack for correctness
    {                              // on zero-terminated C strings.
        m[*begin]++;
        ++begin;
    }

    size_t count = 0;

    for (auto& pair : m)
    {
        if (pair.second % 2 == 1)
        {
            if (++count == 2)
            {
                return false;
            }
        }
    }

    return true;
}

template<typename Sequence>
bool is_palindrome_permutation(const Sequence& seq)
{
    return is_palindrome_permutation(std::begin(seq), std::end(seq));
}

int main() {
    char str[] = "tacoota";
    cout << "Palindrome permutation: "
         << std::boolalpha
         << is_palindrome_permutation(str,
                                      str + sizeof(str) / sizeof(str[0]))
         << endl;

    std::string str2{"tacoota"};
    cout << "Palindrome permutation: "
         << is_palindrome_permutation(str2)
         << endl;

    std::vector<char> vec;
    std::copy(str2.begin(), str2.end(), std::back_inserter(vec));
    cout << "Palindrome permutation: "
         << is_palindrome_permutation(vec)
         << endl;
    return 0;
}


Given time intervals determine if a person could attend all meetings

These two functions look quite sufficient to solve the task. I will say that the functional solution will likely be slower, not only because it is functional but also because of the call to .flat() and iterating over twice as many elements.

Correct me if this is incorrect, but the call to .flat() could be removed if the call to .every() was changed to a condition similar to the condition in the imperative solution:

.every((x,i, src) => i === 0 || !(src[i][0] < src[i - 1][1]));


I would have to agree with @EliasVanOotegem. Consider using password_hash() and password_verify(). All you've done is recreate something, which we know shouldn't be done.

Documentation for the former and latter.


Your MyCacheProvider will hold an instance of JilSerializer and since your MyCacheProvider is a singleton - there's going to be an instance of JilSerializer around forever as well.

As it's apparently fine for your ICacheProvider to use the same serializer throughout the lifetime of the app, and the implementation looks completely fine for sharing an instance, I don't see any reason why you can't just make ISerializer a singleton too.

I think that this isn't quite a captive dependency as the default lifetime of ISerializer is transient but it's certainly a related topic that you can read about on Mark Seemann's blog.


For your methods that only return a single expression, I would use the single expression syntax operator fun get(key: K) = Observable.create<T> (same for getSharedObservable). If you want to still have keep the explicit return type, you can do that, too.

For methods that take a lambda as the last parameter, the style guide recommend to put the lambda outside of the parans. I also would format it to have the first curly brace on the same line, resulting in

operator fun get(key: K) = Observable.create<T> { subscriber ->

    val bindingSubscriber = from(subscriber)
    lock.withLock {
        getSharedObservable(key).subscribe(bindingSubscriber)
    }

    subscriber.add(Subscriptions.create {
        lock.withLock {
            bindingSubscriber.unsubscribe()
        }
    })
}

same for getSharedObservable


Your current implementation you will lose all but the first word:

std::string str("this is a sentence");
std::string t  = trim(str);

std::cout << t << "\n"

// Output
this

If that is your intention then there is an easier way of doing that:

std::string trim(std::string const& str)
{
    std::string word;
    std::stringstream stream(str)
    stream >> word;

    return word;
}

If you want to trim space of the ends on the string, then I would use the string search functions [coliru demo]:

std::string trim(std::string const& str)
{
    if(str.empty())
        return str;

    std::size_t firstScan = str.find_first_not_of(' ');
    std::size_t first     = firstScan == std::string::npos ? str.length() : firstScan;
    std::size_t last      = str.find_last_not_of(' ');
    return str.substr(first, last-first+1);
}

Here is the string documentation. Boost also has some extra libraries on the subject.


Some general remarks:

Variables should be declared explicitly with var, otherwise you
create a global variable.
The indent amount is different between the first level and the
deeper levels.
The spacing is not consistent: while ( vs if(. Generally I would
insert a space at least after keywords, and around parentheses/braces etc.

Your implementation is correct but not efficient, as the number of loop iterations
and remainder operations is equal to the input number.

The count of divisors can be efficiently computed from the
prime number factorization: If
$$
 n = p_1^{e_1} \, p_2^{e_2} \cdots p_k^{e_k}
$$
is the factorization of \$ n \$ into prime numbers \$ p_i \$
with exponents \$ e_i \$, then
$$
 \sigma_0(n) = (e_1+1)(e_2+1) \cdots (e_k+1)
$$
is the number of divisors of \$ n \$, see for example
Wikipedia: Divisor function. Example:
$$
 720 = 2^4 \cdot 3^2 \cdot 5^1 \Longrightarrow
  \sigma_0(720) = (4+1)(2+1)(1+1) = 30 \, .
$$

An implementation in JavaScript would be

function getDivisorsCnt(n){

    var numDivisors = 1;
    var factor = 2; // Candidate for prime factor of `n`

    // If `n` is not a prime number then it must have one factor
    // which is <= `sqrt(n)`, so we try these first:
    while (factor * factor <= n) {
        if (n % factor === 0) {
            // `factor` is a prime factor of `n`, determine the exponent:
            var exponent = 0;
            do {
                n /= factor;
                exponent++;
            } while (n % factor === 0)
            // `factor^exponent` is one term in the prime factorization of n,
            // this contributes as factor `exponent + 1`:
            numDivisors *= exponent + 1;
        }
        // Next possible prime factor:
        factor = factor == 2 ? 3 : factor + 2
    }

    // Now `n` is either 1 or a prime number. In the latter case,
    // it contributes a factor 2:
    if (n > 1) {
        numDivisors *= 2;
    }

    return numDivisors;
}

As an example, getDivisorsCnt(720) requires 720 remainder operations
in your algorithm, but only 8 remainder operations and 6 divisions in this algorithm.


You could create a curried function that takes an array of colors, an element, and an event. Then you build your other functions by partial application:

var divOne = document.getElementById("one"),
  divTwo = document.getElementById("two"),
  RGB = ["red","green","blue"],
  YPB = ["yellow","purple","black"];

var colorMe = function(colors) {
  return function(elem) {
    return function(event) {
      elem.style.backgroundColor = colors[Math.random() * colors.length |0];
      event.stopPropagation();
    };
  };
}

var colorMeRGB = colorMe(RGB);
var colorMeYPB = colorMe(YPB);

divOne.addEventListener("click", colorMeRGB(divOne), false);
divTwo.addEventListener("click", colorMeYPB(divTwo), false);

In you have something like LoDash at hand, you can use curry:

var colorMe = _.curry(function(colors, elem, event) {
  ...
})

You could also use this inside the event, which refers to the element, but  find it can be confusing, and you may lose flexibility.

If you think of data flow and transformations, rather than steps, you can come up with a slightly more DRY solution:

var colorMe = _.curry(function(colors, elem, event) {
  elem.style.backgroundColor = colors[Math.random() * colors.length | 0];
  event.stopPropagation();
});

var data = [
  {id: 'one', colors: ['red','green','blue']},
  {id: 'two', colors: ['yellow','purple','black']}
];

data.forEach(function(x) {
  var elem = document.getElementById(x.id);
  elem.addEventListener('click', colorMe(x.colors, elem), false);
});

But if you're reusing the elements it is recommended to cache them in variables.

Note I used |0 to floor the number. This is quite common, and it cleans up that line a bit.

DEMO: http://jsfiddle.net/uqkutqht/1/


Setting a page number from the URL, with fallbacks

You could re-write it something like this:

<cfif StructKeyExists(stElement,'idInfoPage') AND isNumeric(stElement.idInfopage)>
    <cfset idInfopage = stElement.idInfopage />

<cfelseif StructKeyExists(Url,'idInfoPage') AND isNumeric(Url.idInfopage)>
    <cfset idInfopage = Url.idInfopage />

<cfelse>
    <cfset idInfopage = 0 />

</cfif>

Notes on the changes:

StructKeyExists is generally recommended over isDefined.
isNumeric wont return true for empty string.

If you have a lot of code like this, it might make sense to create a function, something like:

<cfset idInfopage = getNumberOrZero('idInfopage',stElement,Url) />

Then implemented as:

<cffunction name="getNumberOrZero" returntype="numeric" output=false
    hint="Loops through structs (args 2..n) looking for number; else return 0">
    <cfargument name="Key" type="String" required />
    <cfset var i = 0 />

    <cfloop index="i" from=2 to=#ArrayLen(Arguments)#>
        <cfif StructKeyExists(Arguments[i],Arguments.Key)
            AND isNumeric(Arguments[i][Arguments.Key])
            >
            <cfreturn Arguments[i][Arguments.Key] />
        </cfif>
    </cfloop>

    <cfreturn 0 />
</cffunction>


There are a couple of improvements you can make in your componentDidMount.

First, you create an empty array of shops, then push to it in every iteration over the querySnapshot. When constructing an array by transforming another array (or array-like collection), the appropriate method to use is Array.prototype.map. You can get an array of documents from the snapshot by accessing its .docs property.

Second, rather than calling doc.data many times repetitively, you can make an array of properties and extract each of them from the document being iterated over, putting them into a new object with Object.fromEntries:

async componentDidMount() {
  const querySnapshot = await db.mShopsCollection().get();
  const properties = ['address1', 'address2', 'address3', 'name', 'prefecture', 'zip_code'];
  const shops = querySnapshot.docs.map((doc) => {
    const data = doc.data();
    return {
      id: doc.id,
      ...Object.fromEntries(properties.map(prop => data[prop]))
    };
  });
  this.setState({ shops });
}

Lodash's pick is another method that can be used to extract certain properties from an object into a new object.


Not an answer to your questions, but a correction for your first, looping attempt for Q3:

Things get much easier if you initially have at least one prime number in your list. You could ensure this by a separate case in isPrime, but why not cheat a little bit, and add it directly?

primes = 2 : filter isPrime [3..]

Then you can use your solution for Q1 without much changes (I took the freedom to kill some parens etc):

isPrime :: Integer -> Bool
isPrime v = let maxDiv = floor $ sqrt $ fromIntegral v
            in all ((/= 0).(v `rem`)) $ takeWhile (<= maxDiv) primes

However, this is not the best way to generate a list of primes. Read the excellent paper http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf for details.

[Edit]

I forgot to mention http://www.haskell.org/haskellwiki/Prime_numbers with many interesting techniques.


For built-in types, there is no point in passing it as a const& - prefer a plain int (or a const int) instead.

Other comments:

Your add- functions are said to return int even though you don't have a return statement. I don't think that would or should even compile. Change them to void.
Take the time to write out day, month and year. The extra seconds in typing is nothing compared to the readability gain.
Are you sure you want a default date?
Consider overloading operator<< to allow printing your class.
Consider changing your display() function into a to_string function instead, and have it return a std::string.
Make your class easy to use correctly, and hard to use incorrectly. What if month is 12 and someone calls addMonth()? What is someone passes in June as month, but 31 as day? Is day day the day of the month, or day of the year? Adhere to the principle of least astonishment. Your class should behave the way users of the class expect it to.
Don't pollute the global namespace with using namespace std.
Split the code into a header and an implementation file. Even though you won't need it now, it's good practice. That makes point 7 even more crucial.

You need to make some judgments to design a Date class properly. I won't give you any further suggestions, because it is a good exercise to think about it. Revise your code, and think about the pros and cons of various approaches. Apart from that and the points above, your code looks OK.


Faster solution for row-wise matrix subtraction

It's not pretty, but this gives a factor-3 speed improvement:

d = (A**2).sum(axis=-1)[:, np.newaxis] + (B**2).sum(axis=-1)
d -= 2 * np.squeeze(A.dot(B[..., np.newaxis]), axis=-1)
d **= 0.5

This is based off of the fact

$$
(a - b)^2 = a^2 + b^2 - 2ab
$$

and so, ignoring the fudging with indices,

$$
\sum(a - b)^2 = \sum a^2 + \sum b^2 - 2\sum ab
$$

The squared terms are just

(A**2).sum(axis=-1)[:, np.newaxis] + (B**2).sum(axis=-1)

and \$\sum ab = \vec A \cdot \vec B\$. This can be broadcast with a bit of fudging the axes:

np.squeeze(A.dot(B[..., np.newaxis]), axis=-1)


Am I using my data source array correctly?

Yes. Everything seems correct here.

Like you mention yourself: make sure you use self.dataSourceArray to assign new values, and the synthesized setter will take care of memory management.


Use Requests for HTTP and let it deal with the encoding
Do not bake the query into the URL string
Use BeautifulSoup for HTML parsing
Use typehints

Nice and simple:
from requests import get
from bs4 import BeautifulSoup

def get_cuit(dni: int) -> str:
    with get(
        'https://www.cuitonline.com/search.php',
        params={'q': dni},
    ) as resp:
        resp.raise_for_status()
        doc = BeautifulSoup(resp.text, 'html.parser')

    span = doc.find('span', class_='cuit')
    return span.text

print(get_cuit(71_179_047))


Sieve of Eratosthenes - Standard and Optimized implementation

Style

You code does not follow PEP 8, the usual Python coding convention. You'll find tools such as pep8 (or its online version), pylint, pyflakes or pychecker to check for this and other points that might make your code cleaner, more idiomatic or more correct.

I can't be bothered to break the too long lines nor to fix typos in the comments but I did perform the other changes so make pep8 happy.

The result is :

"""
This module contains two implementations of the algorithm Sieve of
Eratosthenes.
"""

import math
import numpy

def SieveBasic(n):
    """
    This function runs the basic sieve of eratosthenis algorithm (non-optimized)
    and returns a list of prime numbers. The algorithm is implemented as described @:
    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example
    """
    l = list(range(2, n+1))
    isPrime = [True] * (n-1)

    for m, n in enumerate(l):
        currentCheck = n
        # take each number and compare with later numbers
        for i, x in enumerate(l[m+1:]):
            if x % currentCheck == 0:
                isPrime[i+m+1] = False

    primes = [0, 1]
    for i, prime in enumerate(isPrime):
        if prime:
            primes.append(2+i)

    return primes

def generateJs(i, n):
    """
    This function generates a list of Js required for optimized sieve of eratosthenis algorithm.
    """
    j = i**2
    if j < n:
        yield j

    while j+i <= n:
        j += i
        yield j

def SieveOptimized(n):
    """
        This function runs the optimized sieve of eratosthenis algorithm
        and returns a list of prime numbers. The algorithm is implemented as described @:
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation

    """
    l = list(range(2, n+1))
    isPrime = [True] * (n+1)
    maxChk = math.sqrt(n)

    for q, r in enumerate(l):
        if r > maxChk:
            break

        for z in generateJs(r, n):
            isPrime[z] = False

    return numpy.where(isPrime)[0]

def main():
    """Main function"""
    for n in range(1, 200):
        s1 = SieveBasic(n)
        s2 = SieveOptimized(n).tolist()
        if s1 != s2:
            print n, s1, s2

if __name__ == "__main__":
    main()

Also, the name of generateJs is not so great as it doesn't tell us much.

Correctness

When you write two functions to perform the same thing, it can be a good idea to check that you get the same result on a big set of inputs. Here's what I wrote :

def main():
    """Main function"""
    for n in range(1, 200):
        s1 = SieveBasic(n)
        s2 = SieveOptimized(n).tolist()
        if s1 != s2:
            print n, s1, s2

This shows that the result is different when n is 4, 9, 25, 49, 121, 169. The optimised algorithm consider these values as prime even though they shouldn't (as they are perfect squares - of prime numbers which might have its importance when looking for the fix). Once this is fixed, you can use assert to ensure the results of the two functions are the same.

In your case, the fix is simple : changing if j < n for if j <= n in generateJs :

def generateJs(i, n):
    """
    This function generates a list of Js required for optimized sieve of eratosthenis algorithm.
    """
    j = i**2
    if j <= n:
        yield j

    while j+i <= n:
        j += i
        yield

0 and 1 shouldn't be considered as primes. Again, fixing this is simple : initialising primes as being primes = [] in the basic function and setting isPrime[0] = isPrime[1] = False in the optimised function.

Improving the code for the optimised version

In generateJs, you can factorise code by writing :

def generateJs(i, n):
    """
    This function generates a list of Js required for optimized sieve of eratosthenis algorithm.
    """
    j = i**2
    while j <= n:
        yield j
        j += i

Interestingly, this now looks a lot like range (or xrange depending on the version of Python you are using). We can get rid of it and write :

Also, you don't need to use enumerate:

def SieveOptimized(n):
    """
        This function runs the optimized sieve of eratosthenis algorithm
        and returns a list of prime numbers. The algorithm is implemented as described @:
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation

    """
    l = list(range(2, n+1))
    isPrime = [True] * (n+1)
    isPrime[0] = isPrime[1] = False
    maxChk = math.sqrt(n)

    for r in l:
        if r > maxChk:
            break

        for z in xrange(r*r, n+1, r):
            isPrime[z] = False

    return numpy.where(isPrime)[0]

Now, if you think about it, the list l is not that useful. The point is just to perform a re-indexing : what we are really doing is that we loop starting as 2 and we stop at n (included). We can write this directly : for r in xrange(2, n+1):. The same kind of comment also applies to the "basic" version of the code.

def SieveOptimized(n):
    """
        This function runs the optimized sieve of eratosthenis algorithm
        and returns a list of prime numbers. The algorithm is implemented as described @:
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation

    """
    isPrime = [True] * (n+1)
    isPrime[0] = isPrime[1] = False
    maxChk = math.sqrt(n)

    for r in xrange(2, n+1):
        if r > maxChk:
            break

        for z in xrange(r*r, n+1, r):
            isPrime[z] = False

    return numpy.where(isPrime)[0]

Because sqrt(n) + 1 <= n + 1 for any n >= 1, we can use maxChk in the call to range :

def SieveOptimized(n):
    """
        This function runs the optimized sieve of eratosthenis algorithm
        and returns a list of prime numbers. The algorithm is implemented as described @:
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation

    """
    isPrime = [True] * (n+1)
    isPrime[0] = isPrime[1] = False

    for r in xrange(2, int(math.sqrt(n))+1):
        for z in xrange(r*r, n+1, r):
            isPrime[z] = False

    return numpy.where(isPrime)[0]

Improving the code for the basic version

Here again, the list l is not that useful. The point is just to perform a re-indexing : what we are really doing is that we loop starting as 2 and we stop at n (included).

You can put a few asserts in your code to double check that we don't really need the values from l as we can compute them.

for m, n in enumerate(l):
    assert m == n-2
    assert n == m+2
    currentCheck = m+2
    # take each number and compare with later numbers
    for i, x in enumerate(l[m+1:]):
        assert x - m - i == 3
        assert x == 3 + m + i
        if x % currentCheck == 0:
            isPrime[i+m+1] = False

Messing a bit with indices, you get :

def SieveBasic(n):
    """
    This function runs the basic sieve of eratosthenis algorithm (non-optimized)
    and returns a list of prime numbers. The algorithm is implemented as described @:
    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Example
    """
    isPrime = [True] * (n-1)

    for x in range(2, n+1):
        # take each number and compare with later numbers
        for j in range(x+1, n+1):
            if j % x == 0:
                isPrime[j - 2] = False

    primes = []
    for i, prime in enumerate(isPrime):
        if prime:
            primes.append(2+i)

    return primes

And the end of the function can be re-written with a list comprehension :

return [2+i for i, prime in enumerate(isPrime) if prime]

This code is still not optimal but because it corresponds to the "basic" version, I guess there is no need to try to make it too much better.

Additional note

In my code, I've been using range and xrange as I am used to switch between Python 2 and Python 3. Depending on the version you are using, I suggest you have a look online to see more details about this. Just keep in mind that you should try to avoid creating a list when an iterator is enough for you.


Optimizing run time of Python solution to Project Euler Problem 34

You can shave some (minimal) time by bailing out early of your factorial sum calculation, and using the divmod operator:

while number and factorial_sum <= number:
    number, digit = divmod(number, 10)
    factorial_sum += factorials[digit]

But that is still going to be fairly slow, and take several seconds to compute. If you want a quick solution, you need to stop rechecking numbers that you already know cannot fulfill the condition. This is best done checking the digits from most significant to least significant. A possible implementation using recursion would be:

factorials = [1, 1]
for j in range(2, 10):
    factorials.append(j * factorials[-1])

def factorion_sum(number, factorial_sum):
    number *= 10
    total = 0
    for digit in range(10):
        new_number = number + digit
        new_factorial_sum = factorial_sum + factorials[digit]
        if new_number == new_factorial_sum:
            total += new_number
        # If the smallest number in the next iteration exceeds
        # the next largest factorial sum, we are done here
        if new_number*10 <= new_factorial_sum + factorials[-1]:
            total += factorion_sum(new_number, new_factorial_sum)
    return total

print sum(factorion_sum(j, factorials[j]) for j in range(1, 10)

This produces the right result in a fraction of a second.


Is it a good idea to keep Request querystring as a property?

Can you guarantee that eventId will never change? If so it might not be a bad idea, but this comes down to a few things

eventId never changes;
how and where you're using it. It might be somewhat difficult for a new programmer in the project to locate and realize what it actually does (it returns the eventId for the current Http Request), solely based on the property name; and
Are you sure that both HttpContext.Current and Current.Request are initialized before retrieving eventId. There is a change these will throw a null reference exception. It might be a very good idea to do a simple if != null check before invoking the Request property.

If your code can accommodate for these points I don't see any inherently wrong with doing this.


Return the largest palindrome from the string

Your basic algorithm seems pretty efficient, but building a list then sorting it just to find the longest one isn't very efficient.  It would be much more efficient to just keep track of the longest palindrome:

    private static string GetLongestPalindrome(string input)
    {
        int rightIndex = 0, leftIndex = 0;
        var x = "";
        string currentPalindrome = string.Empty;
        string longestPalindrome = string.Empty;
        for(int currentIndex = 1; currentIndex < input.Length - 1; currentIndex++)
        {
            leftIndex = currentIndex - 1;
            rightIndex = currentIndex + 1;
            while(leftIndex >= 0 && rightIndex < input.Length)
            {
                if(input[leftIndex] != input[rightIndex])
                {
                    break;
                }
                currentPalindrome = input.Substring(leftIndex, rightIndex - leftIndex + 1);
                if(currentPalindrome.Length > x.Length)
                    x = currentPalindrome;
                leftIndex--;
                rightIndex++;
            }
        }
        return x;
    }

In my tests this is 3 times faster.

I hate to break this to you, but there is a bug in your code, which will probably mean rewriting your algorithm.  You algorithm assumes that the palindrome will be an odd number of characters.  However, a palindrome can be an even number of characters and your code won't find it if it is.

Here's some code that will find the longest palindrome regardless:

static string LargestPalindrome(string input)
{
    string output = "";
    int minimum = 2;
    for(int i = 0; i < input.Length - minimum; i++)
    {
        for(int j = i + minimum; j < input.Length - minimum; j++)
        {
            string forstr = input.Substring(i, j - i);
            string revstr = new string(forstr.Reverse().ToArray());
            if(forstr == revstr && forstr.Length > minimum)
            {
                output = forstr;
                minimum = forstr.Length;
            }
        }
    }
    return output;
}

EDIT

The above code has a bug.  Here it is reworked:

static string LargestPalindrome(string input)
{
    int longest = 0;
    int limit = input.Length;
    for (int i = 0; i < limit; i++)
    {
        for (int j = limit-1; j > i; j--)
        {
            string forStr = input.Substring(i, j - i);
            string revStr = new string(forStr.Reverse().ToArray());
            if (forStr == revStr && forStr.Length > longest)
            {
                return forStr;
            }
        }
    }
    return "";
}


Fetching items from database with "Outstanding" status

As far as I can see this is a very old Rails code. Please follow these steps:

Refactor the code a little bit:

scope user_hierarchies_filter: lambda { |user|
  select('distinct item_masters.id').
  where("item_masters.company_id = ?", user.company_id)
}

and

    @items = current_company.item_masters.
    user_hierarchies_filter(current_user).accessible_by(current_ability).
    includes(includable_tables).
    order(sort_column + " " + sort_direction).
    paginate(page: new_params[:page],
             per_page: new_params[:per_page_records].blank? ? 10 : new_params[:per_page_records])

from the generated query:

SELECT DISTINCT item_masters.id
FROM `item_masters`
WHERE (item_masters.status IN ('Outstanding'))
AND (((item_masters.company_id = 1)
AND (`item_masters`.company_id = 1)))
ORDER BY item_number asc LIMIT 331230, 10

I propose a couple of things:

Remove the duplicated condition on the company_id.
Explain the query and try to see why is so slow. I guess you are missing an index on the status, company_id and item_number columns: do things get better if you run the following migration?

add_index :item_masters, :company_id
add_index :item_masters, :status
add_index :item_masters, :item_number


Setting a default value if a variable is empty

Before dealing with your question, I'd like to point out that you probably want to use empty() instead of comparing with an empty string and that if you really want to compare to an empty string, use the === operator.

Anyway, default initialization is a real problem in many languages. C# even has a ?? operator to solve this kind of issue! So, let's try to make it better to make your code better step by step.

Ternary operator no more

The one-liner is too long, and using the ternary operator on multiple lines is a bad idea: that's what if-statement are for:

if (empty($newsItems[0]['image_url'])) {
    $newsItems[0]['image_url'] = '/img/cat_placeholder.jpg';
}

This is more readable for two reasons : it's easier to understand the syntax, but more importantly, it's easier to see that you simply want a default value when there's nothing. We don't need the 'else' part which is confusing with the ternary operator.

Note: as mentioned by Simon Scarfe and corrected by mseancole, PHP also has some special ternary syntax to do this:

$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?: 'img/cat_placeholder.jpg';

Factorize it!

If you're doing this only once or twice, then all is good, but otherwise you'd want to factorize it into a function, since you don't repeat yourself, right? The simple way is:

function default_value($var, $default) {
    return empty($var) ? $default : $var;
}

$newsItems[0]['image_url'] = default_value($newsItems[0]['image_url'], '/img/cat_placeholder.jpg');

(The ternary operator does make sense here since variable names are short and both branches of the condition are useful.)

However, we're looking up $newsItems[0]['image_url'] when calling default_value, and this is possibly not defined, and will raise an error/warning. If that's a concern (it should), stick to the first version, or look at this other answer that gives a more robust solution at the expense of storing PHP code as a a string and thus cannot be checked syntactically.

Still too long

If we don't care about the warning/error, can we do better? Yes we can! We're writing the variable name twice, but passing by reference can help us here:

function default_value(&$var, $default) {
    if (empty($var)) {
        $var = $default;
    }
}

default_value($newsItems[0]['image_url'], '/img/cat_placeholder.jpg');

It's much shorter, and feels more declarative: you can look at a bunch of default_value calls and see what the default values are instantly. But we still have the same warning/error issue.


How to search for a word in a sorted text file efficiently?

Your biggest problem is the code does not take into account not finding the word. If it fails your code will loop forever. You need a not found exit case.

This is always a bad sign

while(!fin.eof())

That line is nearly always wrong (in every programming language I know). Especially in your case that should never be true (since you know where the end is).

Remember that the last successful read reads up-to but not past the EOF. The eof-flag is only set when you read past EOF.

So on the last good read you will read up-to the end of file processes the data. There is no more data left in the file but the eof-flag will not be set because you have not read past the EOF yet so you will re-enter the loop. The next attempt to read data will fail (setting the eof-flag), but the read has failed and thus left the variables you just read into in a questionable state.

Luckily you don't get into that state because you move after each search. But it is a sign of the wrong type of test. This should be:

while(searching) //   Set to false when you finish searching.
                 //   Which may be when you find the word
                 //   or there are no more word to search.

You are assuming that words start on the exact boundary of middle!

    middle=(first+last)/2;
    fin.seekg(middle);
    fin>>search;

Not sure I believe that will hold. Middle is a good estimate. But you need to find the start of the word. So seek forward for the next word.

    middle=(first+last)/2;
    fin.seekg(middle);
    fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    if (!fin.eof()) // That may have read past EOF
    {
    }

Correct typing in C++ is everything:

fin.seekg(0,ios::end);
int last = fin.tellg(); // This does not return an int.
                        // With todays big files this can be rather a large
                        // number.

// That line should be.
std::streamsize last = fin.tellg();

If you don't care about the actual type (you just want the correct one). Then let the compiler work it out for you.

// C++11 let the compiler deduct the correct type of last.
auto last = fin.tellg()

Why take two lines to open the file:

ifstream fin;
fin.open("/usr/dict/words");

// Much simpler to read and write:
ifstream fin("/usr/dict/words");

Sure you can test for good(). But its better to let the stream decide if it is a usable state.

if(!fin.good()){cout<<"No dictionary file!\n"; exit(1);}

// Prefer to let the stream decide:
if (fin)  // Stream used in a boolean context will convert itself into
          // something useful that is convertible to true if you can
          // use the stream or false if the stream is not usable.
{
     cout<<"No dictionary file!\n";
     exit(1);
}

If the size of the dictionary is not huge (couple of Meg). I personally would just load it into memory and let the standard data structures handle it. Alternatively You could map the file to memory and do a more standard search.

bool isWordInDict(std::string const& word);
{
    struct MyDict: std::set<std::string>
    {
        typedef std::set<std::string>::const_iterator const_iterator;

        MyDict()
        {
            std::ifstream fin("/usr/dict/words");

            std::copy(std::istream_iterator<std::string>(fin), std::istream_iterator<std::string>(),
                      std::inserter(*this, end()));
        }
    };
    static const MyDict  dict;

    MyDict::const_iterator find = dict.find(word);
    return find != dict.end();
}


Extracting an adjaceny matrix containing haversine distance from points on map

More than half of your code is being used to convert from one data format to another (from two lat and long list to tuples and then from a list of lists to an array).

The easiest to understand version would be to use numpy.loadtxt:

def read_two_column_file(file_name):
    return np.loadtxt(file_name, delimiter=", ")

This is then a 2D numpy.array. However, this is actually a lot slower than it could be, so you could also use pandas.read_csv instead:

import pandas as pd

def read_two_column_file(file_name):
    return pd.read_csv(file_name, header=None).values

Which one is faster depends on the size of your file.

Now we need to modify the display_points function to work with this new data format:

def display_points(points):
    plt.figure()
    plt.ylabel('longitude')
    plt.xlabel('latitude')
    plt.title('longitude vs latitude')
    plt.scatter(points[:, 0], points[:, 1])
    plt.show()

Now for the actual calculation. First, you can use itertools.combinations_with_replacement to get all pairs of points. Then you can insert them directly into the correct row of an array:

from itertools import combinations_with_replacement

def main():

    points = read_two_column_file(file_name)

    adj_matrix = np.empty(len(points)**2)
    for i, (point1, point2) in enumerate(combinations_with_replacement(points, 2)):
        adj_matrix[i] = haversine(point1, point2)
    adj_matrix.reshape((len(points), len(points))

    print(adj_matrix)
    display_points(points)

This can probably be further improved by using numpy.meshgrid to get the combinations of points and using a vectorized version of the haversine function.


Simple yet threadsafe file cache in java

Since you mentioned that the file could be written by another process (assuming in another jvm), there is no way you can introduce the Object monitor based thread safety. So you can depend upon the last modified time of the file object. You can also remove the synchronization from your getLines() if you dont return the instance variable. But you do return that so synchronization should be there in getLines().

Basically you want to read the file without the data corruption. That could happen if another process is writing to the file when your process reads from it. If that is the case, you want to re-read the file. Here is how I would implement it.

 private void readFile() throws IOException {
     int retryCount = 5;

     while (retryCount > 0) {

       long beforeRead = file.lastModified();
        //read file to cache
       fileLines = FileUtils.readLines(file);

       if (beforeRead == file.lastModified())
           break;

       retryCount--;
     }
  //cache the last modified time
    lastModified = file.lastModified() ;

  //set the cached flag to true
    fileCached = true ;
}

The while loop will retry the read operation if there is a mismatch. Also the retry has to be finite number to avoid looping forever in case of any file system failures.


User needs to type in the password to send an email

def send_mail() :

Per PEP8, you wouldn't typically include a space before those colons. You should run your code through a linter.

password = input("Password :")

This is a big no-no. Never expose a user's password content on the screen if you can avoid it. Instead, use the built-in getpass which attempts to mask your input.

mail.close()

You should avoid doing this explicitly, and instead use mail in a with statement.

'3 attempts before locking you out for 10 seconds.'

This line has no effect. Perhaps you meant to write print here. Also, don't hard-code the 3 in the string; use num_of_tries.


Use OR
You should make it a habit to look at your queries' execution plan when in doubt. I recreated the table in SQL Fiddle (albeit, without containing data) and it shows that the query with OR is less complex.
Please note: SQL Fiddle does not support your FOREIGN KEY constraints, so I had to remove them.
First query with OR:

Second query with UNION:

As you can see, the complexity of the 2nd query is higher, which might make it slower (or faster!), albeit the direction (faster or slower) and how much difference it will have depends on a lot of other things too.
In MySQL (and many other DBMS), it's actually (and counter-intuitively) the UNION ALL is usually more efficient than the OR version. Of course, that's because the UNION ALL does not have to remove duplicate rows. In many cases, including this one, we have use UNION (so UNION DISTINCT).

The edit below has been suggested by @ypercube, from dba.SE, and voluntarily added by OP:
Also note that your second query has a unnecessary level and an extra DISTINCT that is redundant which will almost certainly drag efficiency down. Here are two simplifications:
 -- query 2b:  SELECT DISTINCT - UNION DISTINCT - SELECT DISTINCT
SELECT
    DISTINCT sender AS `user`
FROM
    messages
WHERE
    receiver = 15
UNION
    SELECT
        DISTINCT receiver
    FROM
        messages
    WHERE
        sender = 15 ;

-- query 2c: SELECT ALL - UNION DISTINCT - SELECT ALL
SELECT
    sender AS `user`
FROM
    messages
WHERE
    receiver = 15
UNION
    SELECT
        receiver
    FROM
        messages
    WHERE
        sender = 15 ;


Pythonic split list into n random chunks of roughly equal size

import random

def chunk(xs, n):
    ys = list(xs)

Copies of lists are usually taken using xs[:]

    random.shuffle(ys)
    ylen = len(ys)

I don't think storing the length in a variable actually helps your code much

    size = int(ylen / n)

Use size = ylen // n // is the integer division operator

    chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)]

Why the 0+?

    leftover = ylen - size*n

Actually, you can find size and leftover using size, leftover = divmod(ylen, n)

    edge = size*n
    for i in xrange(leftover):
            chunks[i%n].append(ys[edge+i])

You can't have len(leftovers) >= n. So you can do:

   for chunk, value in zip(chunks, leftover):
       chunk.append(value)

    return chunks

Some more improvement could be had if you used numpy. If this is part of a number crunching code you should look into it.


Python Making Bruteforce Password Crack Faster

As has been noted in the comments, you should try to figure out what part of the code is slow. Is it the connection to the server or does your program just have to try many passwords and that takes so long?

The former can be measured by decorating connection with a decorator that records the time it took to run the function:

import time
from functools import wraps

def timeit(func):
    func.mean_time = [0]
    func.k = [0]
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        ret = func(*args, **kwargs)
        t = time.perf_counter() - start

        # update average
        func.k[0] += 1
        func.mean_time[0] += (t - func.mean_time[0]) / func.k[0]

        print(f"{func.__name__} took {t} s (Average: {func.mean_time[0]} s)")
        return ret
    return wrapper

Which you can use like this in general:

@timeit
def f():
    time.sleep(0.1)

for _ in range(10):
    f()
# f took 0.1002191620063968 s (Average: 0.1002191620063968 s)
# f took 0.10021526199852815 s (Average: 0.10021721200246247 s)
# f took 0.10016683799767634 s (Average: 0.10020042066753376 s)
# f took 0.10014399800274987 s (Average: 0.10018631500133779 s)
# f took 0.10016678299871273 s (Average: 0.10018240860081278 s)
# f took 0.10017002299719024 s (Average: 0.10018034433354235 s)
# f took 0.10020436099875951 s (Average: 0.10018377528571623 s)
# f took 0.1001491690039984 s (Average: 0.1001794495005015 s)
# f took 0.10017034399788827 s (Average: 0.10017843777798892 s)
# f took 0.10020105999865336 s (Average: 0.10018070000005536 s)

And here specifically:

@timeit
def connect(ip, user, passw, port):
    ...

Note that this will slow down the overall execution time a bit (since stuff needs to be done in addition), but you do learn if the connect is the bottleneck (and you can always remove the timing again later).

To find out if it is just the number of permutations, I would add some debug prints. I would also factor out the generating of the passwords from trying them further:

def brute_force_n(chars, password_length):
    start = time.perf_counter()
    for i, guess in enumerate(itertools.product(chars, repeat=password_length)):
        yield ''.join(guess)
    print(f"Tried all {i + 1} permutations of length {password_length}.")
    print(f"It took {time.perf_counter() - start} s.")

def brute_force(max_length=8):
    chars = string.digits + string.ascii_letters
    for password_length in range(1, max_length + 1):
        yield from brute_force_n(chars, password_length)

def crack(ip, user, port):
    for guess in brute_force():
        p = connection(ip, user, guess, port)
        if '230'.encode() in p:
            print('Username : ' + user + '\nPassword : ' + guess)
            sys.exit(1)

When testing this you will quickly discover that there are many permutations to try and even when doing nothing with them, this takes quite some time:

for _ in brute_force(5):
    pass  # do nothing with it

# Tried all 62 permutations of length 1.
# It took 3.321799886180088e-05 s.
# Tried all 3844 permutations of length 2.
# It took 0.0009744890048750676 s.
# Tried all 238328 permutations of length 3.
# It took 0.06495958699815674 s.
# Tried all 14776336 permutations of length 4.
# It took 4.06446365499869 s.
# Tried all 916132832 permutations of length 5.
# It took 310.80436263100273 s.

I stopped at length 5, you want to go to length 8. As you can see in this plot, the time rises very quickly (note the logarithmic y-axis):

Extrapolating this to password_length = 8, it would take about 536 days just to generate all combinations of that length.

The real solution to this problem is that you need to use some more information/a more clever tactic. A common method is to try words in a dictionary (and then words in a dictionary with numbers at the end, with known common replacements, etc).

Passwords are still used today because it is very hard to guess a (random) password of sufficient length.


Initializing connection to a MySQL database in PHP

Why the intermediate step of writing values to array? Why not:

define('DB_HOST', $db_ini['db_data_source_name']['host']);
define('DB_USER', $db_ini['db_general']['user']);
// etc.

Be careful with relative path with regards to including in other pieces of code.  If being included by code in another directory (particularly at a different level in directory structure), this may break.  Also, you won't be able to include this file more than once within any given script execution since you are defining constants.

Since you can only include this once per execution, do you really need to define constants at all?

$connection = mysqli_connect(
    $db_ini['db_data_source_name']['host'],
    $db_ini['db_general']['user'],
    $db_ini['db_general']['password'],
    $db_ini['db_data_source_name']['dbname']
);

I am just generally worried about your thinking of including this within other files "as needed".  That tends to make me think that you don't have a good strategy around managing your application dependencies (such as database connection).  Just sprinkling includes/requires throughout your code can really make your code fragile and hard to maintain.  If you really want to take you application coding to another level, I would suggest familiarizing yourself with dependency injection, both in a philosophical sense as well as from a practical standpoint looking at typical PHP libraries that do this (Pimple, PHP-DI, or pretty much any popular framework has some level of dependency injection strategy).

Hopefully your ini file is separate from your codebase (i.e. not under revision control) to where you are storing your DB passwords in your code.  If that is the case, consider taking the next step and have the ini file parsed in a different process such that this particular code is not responsible for reading configuration data from files that should perhaps should just be available in environmental variables.